From 1bea222a263d59e4cddbc3c4076fbc0b241dfef7 Mon Sep 17 00:00:00 2001 From: Robert Thomas <31854736+wolveix@users.noreply.github.com> Date: Tue, 16 Jan 2024 12:40:22 +0000 Subject: [PATCH] Refactor `Server` Library + Improve Docs (#2063) * Refactor `Server` library component + improve docs * Refactor `Server` library component + improve docs * More meaningful documentation * Allow null strings * Generate new PHPStan baseline * Address comments + Rector and PHP-CS-Fixer * Handle converting package bandwidth and disk quota into bytes * Remove previous PHPStan baseline change * Fix `password_length` bug caused by previous PR It seems that the database code automatically converts camel case (`passwordLength`) into snake case (`password_length`) * Rectify migration * Resolve merge issue --- phpstan-baseline.neon | 16 +- src/install/sql/structure.sql | 2 +- src/library/FOSSBilling/UpdatePatcher.php | 2 +- src/library/Server/Account.php | 261 +++++-- src/library/Server/Client.php | 305 ++++++-- src/library/Server/Exception.php | 3 +- src/library/Server/Manager.php | 151 ++-- src/library/Server/Manager/CWP.php | 293 +++++--- src/library/Server/Manager/Custom.php | 195 +++-- src/library/Server/Manager/Directadmin.php | 748 ++++++++++++-------- src/library/Server/Manager/Hestia.php | 615 ++++++++-------- src/library/Server/Manager/Plesk.php | 662 +++++++++++------ src/library/Server/Manager/Whm.php | 785 +++++++++++++-------- src/library/Server/Package.php | 263 +++++-- 14 files changed, 2759 insertions(+), 1542 deletions(-) diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 857ea9fb9..90ac377fb 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -127,17 +127,17 @@ parameters: - message: "#^Call to an undefined method Server_Package\\:\\:getMaxEmailAutoresponders\\(\\)\\.$#" - count: 2 + count: 3 path: src/library/Server/Manager/Directadmin.php - message: "#^Call to an undefined method Server_Package\\:\\:getMaxEmailForwarders\\(\\)\\.$#" - count: 2 + count: 3 path: src/library/Server/Manager/Directadmin.php - message: "#^Call to an undefined method Server_Package\\:\\:getMaxEmailLists\\(\\)\\.$#" - count: 2 + count: 3 path: src/library/Server/Manager/Directadmin.php - @@ -174,13 +174,3 @@ parameters: message: "#^Call to an undefined method Server_Package\\:\\:getMaxEmailLists\\(\\)\\.$#" count: 3 path: src/library/Server/Manager/Plesk.php - - - - message: "#^Method Server_Manager_Plesk\\:\\:_createClient\\(\\) should return int but returns true\\.$#" - count: 1 - path: src/library/Server/Manager/Plesk.php - - - - message: "#^Method Server_Manager_Plesk\\:\\:changeAccountDomain\\(\\) should return bool but return statement is missing\\.$#" - count: 1 - path: src/library/Server/Manager/Plesk.php diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index 4bdc130b3..a9bbce20f 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -1079,7 +1079,7 @@ CREATE TABLE `service_hosting_server` ( `username` text, `password` text, `accesshash` text, - `passwordLength` tinyint DEFAULT NULL, + `password_length` tinyint DEFAULT NULL, `port` varchar(20) DEFAULT NULL, `config` text, `secure` tinyint(1) DEFAULT NULL, diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index 89692158f..148930138 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -354,7 +354,7 @@ class UpdatePatcher implements InjectionAwareInterface }, 40 => function () { // Added `passwordLength` field to server managers - $q = 'ALTER TABLE service_hosting_server ADD COLUMN `passwordLength` TINYINT DEFAULT NULL;'; + $q = 'ALTER TABLE service_hosting_server ADD COLUMN `password_length` TINYINT DEFAULT NULL;'; $this->executeSql($q); }, ]; diff --git a/src/library/Server/Account.php b/src/library/Server/Account.php index 03b1c87b6..5499ec35f 100644 --- a/src/library/Server/Account.php +++ b/src/library/Server/Account.php @@ -1,191 +1,338 @@ username = $param; - - return $this; - } - - public function getUsername() + /** + * Get the username associated with the Server_Account instance. + * + * @return string returns the username as a string + */ + public function getUsername(): string { return $this->username; } - public function setPassword($param) + /** + * Set the username associated with the Server_Account instance. + * + * @param string|null $username the username to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setUsername(?string $username): static { - $this->password = $param; + $this->username = $username; return $this; } - public function getPassword() + /** + * Get the password associated with the Server_Account instance. + * + * @return string|null returns the password as a string if it exists, otherwise returns null + */ + public function getPassword(): ?string { return $this->password; } - public function setDomain($param) + /** + * Set the password associated with the Server_Account instance. + * + * @param string|null $password the password to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setPassword(?string $password): static { - $this->domain = $param; + $this->password = $password; return $this; } - public function getDomain() + /** + * Get the domain associated with the Server_Account instance. + * + * @return string|null returns the domain as a string if it exists, otherwise returns null + */ + public function getDomain(): ?string { return $this->domain; } - public function setIp($param) + /** + * Set the domain associated with the Server_Account instance. + * + * @param string|null $domain the domain to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setDomain(?string $domain): static { - $this->ip = $param; + $this->domain = $domain; return $this; } - public function getIp() + /** + * Get the IP address associated with the Server_Account instance. + * + * @return string|null returns the IP address as a string if it exists, otherwise returns null + */ + public function getIp(): ?string { return $this->ip; } /** - * @return $this + * Set the IP address associated with the Server_Account instance. + * + * @param string|null $ip the IP address to be set + * + * @return $this returns the current instance to allow for method chaining */ - public function setClient(Server_Client $param) + public function setIp(?string $ip): static { - $this->client = $param; + $this->ip = $ip; return $this; } /** - * @return Server_Client + * Get the client associated with the Server_Account instance. + * + * @return Server_Client|null returns the client if it exists, otherwise returns null */ - public function getClient() + public function getClient(): ?Server_Client { return $this->client; } /** - * @return $this + * Set the client associated with the Server_Account instance. + * + * @param Server_Client|null $client the client to be set + * + * @return $this returns the current instance to allow for method chaining */ - public function setPackage(Server_Package $param) + public function setClient(?Server_Client $client): static { - $this->package = $param; + $this->client = $client; return $this; } + /** + * Get the package associated with the Server_Account instance. + * + * @return Server_Package returns the package + */ public function getPackage(): Server_Package { return $this->package; } - public function setNote($param) + /** + * Set the package associated with the Server_Account instance. + * + * @param Server_Package|null $package the package to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setPackage(?Server_Package $package): static { - $this->note = $param; + $this->package = $package; return $this; } - public function getNote() + /** + * Get the note associated with the Server_Account instance. + * + * @return string|null returns the note as a string if it exists, otherwise returns null + */ + public function getNote(): ?string { return $this->note; } - public function setReseller($param) + /** + * Set the note associated with the Server_Account instance. + * + * @param string|null $note the note to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setNote(?string $note): static { - $this->reseller = (bool) $param; + $this->note = $note; return $this; } - public function getReseller() + /** + * Get the reseller status associated with the Server_Account instance. + * + * @return bool|null returns the reseller status as a boolean if it exists, otherwise returns null + */ + public function getReseller(): ?bool { return $this->reseller; } - public function setSuspended($param) + /** + * Set the reseller status associated with the Server_Account instance. + * + * @param bool $reseller the reseller status to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setReseller(bool $reseller): static { - $this->suspended = (bool) $param; + $this->reseller = $reseller; return $this; } - public function getSuspended() + /** + * Get the suspension status associated with the Server_Account instance. + * + * @return bool|null returns the suspension status as a boolean if it exists, otherwise returns null + */ + public function getSuspended(): ?bool { return $this->suspended; } - public function setNs1($param) + /** + * Set the suspension status associated with the Server_Account instance. + * + * @param bool $suspended the suspension status to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setSuspended(bool $suspended): static { - $this->ns_1 = $param; + $this->suspended = $suspended; return $this; } - public function getNs1() + /** + * Get the first nameserver associated with the Server_Account instance. + * + * @return string|null returns the first nameserver as a string if it exists, otherwise returns null + */ + public function getNs1(): ?string { return $this->ns_1; } - public function setNs2($param) + /** + * Set the first nameserver associated with the Server_Account instance. + * + * @param string|null $ns1 the first nameserver to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setNs1(?string $ns1): static { - $this->ns_2 = $param; + $this->ns_1 = $ns1; return $this; } - public function getNs2() + /** + * Get the second nameserver associated with the Server_Account instance. + * + * @return string|null returns the second nameserver as a string if it exists, otherwise returns null + */ + public function getNs2(): ?string { return $this->ns_2; } - public function setNs3($param) + /** + * Set the second nameserver associated with the Server_Account instance. + * + * @param string|null $ns2 the second nameserver to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setNs2(?string $ns2): static { - $this->ns_3 = $param; + $this->ns_2 = $ns2; return $this; } - public function getNs3() + /** + * Get the third nameserver associated with the Server_Account instance. + * + * @return string|null returns the third nameserver as a string if it exists, otherwise returns null + */ + public function getNs3(): ?string { return $this->ns_3; } - public function setNs4($param) + /** + * Set the third nameserver associated with the Server_Account instance. + * + * @param string|null $ns3 the third nameserver to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setNs3(?string $ns3): static { - $this->ns_4 = $param; + $this->ns_3 = $ns3; return $this; } - public function getNs4() + /** + * Get the fourth nameserver associated with the Server_Account instance. + * + * @return string|null returns the fourth nameserver as a string if it exists, otherwise returns null + */ + public function getNs4(): ?string { return $this->ns_4; } + + /** + * Set the fourth nameserver associated with the Server_Account instance. + * + * @param string|null $ns4 the fourth nameserver to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setNs4(?string $ns4): static + { + $this->ns_4 = $ns4; + + return $this; + } } diff --git a/src/library/Server/Client.php b/src/library/Server/Client.php index 9ed4ef3ce..eed8dcf7d 100644 --- a/src/library/Server/Client.php +++ b/src/library/Server/Client.php @@ -1,28 +1,29 @@ id; + } + + /** + * Set the ID of the Server_Client instance. + * + * @param int $id the ID to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setId(int $id): static { $this->id = $id; return $this; } - public function getId() - { - return $this->id; - } - - public function setFullName($param) - { - $this->full_name = $param; - - return $this; - } - - public function getFullName() + /** + * Get the full name of the Server_Client instance. + * + * @return string|null returns the full name as a string if it exists, otherwise returns null + */ + public function getFullName(): ?string { return $this->full_name; } - public function setCompany($company) + /** + * Set the full name of the Server_Client instance. + * + * @param string $fullName the full name to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setFullName(string $fullName): static + { + $this->full_name = $fullName; + + return $this; + } + + /** + * Get the company of the Server_Client instance. + * + * @return string|null returns the company as a string if it exists, otherwise returns null + */ + public function getCompany(): ?string + { + return $this->company; + } + + /** + * Set the company of the Server_Client instance. + * + * @param string $company the company to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setCompany(string $company): static { $this->company = $company; return $this; } - public function getCompany() - { - return $this->company; - } - - public function setEmail($param) - { - $this->email = $param; - - return $this; - } - - public function getEmail() + /** + * Get the email of the Server_Client instance. + * + * @return string|null returns the email of the Server_Client instance + */ + public function getEmail(): ?string { return $this->email; } - public function setAddress1($param) + /** + * Set the email of the Server_Client instance. + * + * @param string $email the email to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setEmail(string $email): static { - $this->address_1 = $param; + $this->email = $email; return $this; } - public function getAddress1() + /** + * Get the first address of the Server_Client instance. + * + * @return string|null returns the first address of the Server_Client instance + */ + public function getAddress1(): ?string { return $this->address_1; } - public function setAddress2($param) + /** + * Set the first address of the Server_Client instance. + * + * @param string $address1 the first address to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setAddress1(string $address1): static { - $this->address_2 = $param; + $this->address_1 = $address1; return $this; } - public function getAddress2() + /** + * Get the second address of the Server_Client instance. + * + * @return string|null returns the second address of the Server_Client instance + */ + public function getAddress2(): ?string { return $this->address_2; } - public function setStreet($param) + /** + * Set the second address of the Server_Client instance. + * + * @param string $address2 the second address to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setAddress2(string $address2): static { - $this->street = $param; + $this->address_2 = $address2; return $this; } - public function getStreet() + /** + * Get the street of the Server_Client instance. + * + * @return string|null returns the street of the Server_Client instance + */ + public function getStreet(): ?string { return $this->street; } - public function setCity($param) + /** + * Set the street of the Server_Client instance. + * + * @param string $street the street to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setStreet(string $street): static { - $this->city = $param; + $this->street = $street; return $this; } - public function getCity() + /** + * Get the city of the Server_Client instance. + * + * @return string|null returns the city of the Server_Client instance + */ + public function getCity(): ?string { return $this->city; } - public function setState($param) + /** + * Set the city of the Server_Client instance. + * + * @param string $city the city to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setCity(string $city): static { - $this->state = $param; + $this->city = $city; return $this; } - public function getState() + /** + * Get the state of the Server_Client instance. + * + * @return string|null returns the state as a string if it exists, otherwise returns null + */ + public function getState(): ?string { return $this->state; } - public function setCountry($param) + /** + * Set the state of the Server_Client instance. + * + * @param string $state the state to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setState(string $state): static { - $this->country = $param; + $this->state = $state; return $this; } - public function getCountry() + /** + * Get the country of the Server_Client instance. + * + * @return string|null returns the country as a string if it exists, otherwise returns null + */ + public function getCountry(): ?string { return $this->country; } - public function setZip($param) + /** + * Set the country of the Server_Client instance. + * + * @param string $country the country to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setCountry(string $country): static { - $this->zip = $param; + $this->country = $country; return $this; } - public function getZip() + /** + * Get the zip code of the Server_Client instance. + * + * @return string|null returns the zip code of the Server_Client instance + */ + public function getZip(): ?string { return $this->zip; } - public function setTelephone($param) + /** + * Set the zip code of the Server_Client instance. + * + * @param string $zip the zip code to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setZip(string $zip): static { - $this->telephone = $param; + $this->zip = $zip; return $this; } - public function getTelephone() + /** + * Get the telephone number of the Server_Client instance. + * + * @return string|null returns the telephone number of the Server_Client instance + */ + public function getTelephone(): ?string { return $this->telephone; } - public function setFax($param) + /** + * Set the telephone number of the Server_Client instance. + * + * @param string $telephone the telephone number to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setTelephone(string $telephone): static { - $this->fax = $param; + $this->telephone = $telephone; return $this; } - public function getFax() + /** + * Get the fax number of the Server_Client instance. + * + * @return string|null returns the fax number of the Server_Client instance + */ + public function getFax(): ?string { return $this->fax; } - public function setWww($param) + /** + * Set the fax number of the Server_Client instance. + * + * @param string $fax the fax number to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setFax(string $fax): static { - $this->www = $param; + $this->fax = $fax; return $this; } - public function getWww() + /** + * Get the website URL of the Server_Client instance. + * + * @return string|null returns the website URL as a string if it exists, otherwise returns null + */ + public function getWww(): ?string { return $this->www; } + + /** + * Set the website URL of the Server_Client instance. + * + * @param string $www the website URL to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setWww(string $www): static + { + $this->www = $www; + + return $this; + } } diff --git a/src/library/Server/Exception.php b/src/library/Server/Exception.php index 8d50303a8..ff0238c1b 100644 --- a/src/library/Server/Exception.php +++ b/src/library/Server/Exception.php @@ -1,11 +1,12 @@ null, 'host' => null, 'secure' => false, @@ -22,6 +23,7 @@ abstract class Server_Manager 'port' => null, 'passwordLength' => null, ]; + private ?Box_Log $_log = null; /** * Constructor for the class. @@ -38,7 +40,7 @@ abstract class Server_Manager * - 'port': Custom port number for the connection. * - 'passwordLength': Password length for accounts. */ - public function __construct($options) + public function __construct(array $options) { if (isset($options['ip'])) { $this->_config['ip'] = $options['ip']; @@ -91,25 +93,37 @@ abstract class Server_Manager } /** - * Generates a username for an account based on the provided domain name. - * Server managers may define this function to provide their own method for username generation depending on the specifics of the server they are integrated with. + * Initializes the object after construction. + * This function can be used to perform any necessary setup tasks that are required after the object has been constructed. * - * @param mixed $domain_name the domain name used to generate the username - * - * @return string the generated username + * @return void */ - public function generateUsername(mixed $domain_name) + protected function init() { - $username = preg_replace('/[^A-Za-z0-9]/', '', $domain_name); - $username = substr($username, 0, 7); - $randnum = random_int(0, 9); - $prefix = $this->_config['config']['userprefix'] ?? ''; - - return $prefix . $username . $randnum; } /** - * This method is used to get the password length from the configuration. + * Generates a username for an account based on the provided domain name. + * Server managers may define this function to provide their own method for username generation depending on the specifics of the server they are integrated with. + * + * @param string $domain the domain used to generate the username + * + * @return string the generated username + * + * @throws RandomException + */ + public function generateUsername(string $domain): string + { + $username = preg_replace('/[^A-Za-z0-9]/', '', $domain); + $username = substr($username, 0, 7); + $randomNumber = random_int(0, 9); + $prefix = $this->_config['config']['userprefix'] ?? ''; + + return $prefix . $username . $randomNumber; + } + + /** + * Get the password length from the configuration. * If the password length is not set in the configuration, it defaults to 10. * * @return int the password length @@ -119,26 +133,12 @@ abstract class Server_Manager return $this->_config['passwordLength'] ?? 10; } - /** - * Sets the logger object. - * - * @param Box_Log $value the logger object - * - * @return $this - */ - public function setLog(Box_Log $value) - { - $this->_log = $value; - - return $this; - } - /** * Returns the logger object. * - * @return Box_Log the logger object + * @return Box_Log|null the logger object */ - public function getLog() + public function getLog(): ?Box_Log { if (!$this->_log instanceof Box_Log) { $log = new Box_Log(); @@ -150,6 +150,20 @@ abstract class Server_Manager return $this->_log; } + /** + * Sets the logger object. + * + * @param Box_Log $value the logger object + * + * @return $this + */ + public function setLog(Box_Log $value): static + { + $this->_log = $value; + + return $this; + } + /** * Creates and returns an interface for the Symfony HTTP client. */ @@ -158,43 +172,26 @@ abstract class Server_Manager return Symfony\Component\HttpClient\HttpClient::create(); } - /** - * Initializes the object after construction. - * - * This function can be used to perform any necessary setup tasks that are required after the object has been constructed. - * - * @return void - */ - protected function init() - { - } - /** * Returns the login URL for the server. (ex: panel.example.com). * * @param Server_Account|null $account either the related `Server_Account` which can be used to generate an SSO link or `null` - * - * @return string */ - abstract public function getLoginUrl(?Server_Account $account); + abstract public function getLoginUrl(?Server_Account $account): string; /** * Returns the login URL for the server for reseller accounts. * * @param Server_Account|null $account either the related `Server_Account` which can be used to generate an SSO link or `null` - * - * @return string */ - abstract public function getResellerLoginUrl(?Server_Account $account); + abstract public function getResellerLoginUrl(?Server_Account $account): string; /** * Used to test the connection to the server and verify the server configuration is correct. * - * @return bool - * * @throws Server_Exception */ - abstract public function testConnection(); + abstract public function testConnection(): bool; /** * Creates a new account on the server. @@ -205,109 +202,107 @@ abstract class Server_Manager * * @throws Server_Exception if there was an error while creating the account */ - abstract public function createAccount(Server_Account $account); + abstract public function createAccount(Server_Account $account): bool; /** * Synchronizes the account status from the server. * - * @param Server_Account $a account object containing the details of the account to synchronize + * @param Server_Account $account account object containing the details of the account to synchronize * * @return Server_Account a new account object with the updated status * * @throws Server_Exception if there was an error while synchronizing the account */ - abstract public function synchronizeAccount(Server_Account $a); + abstract public function synchronizeAccount(Server_Account $account): Server_Account; /** * Suspends an account on the server. * - * @param Server_Account $a account object containing the details of the account to suspend + * @param Server_Account $account account object containing the details of the account to suspend * * @return bool True if the account was suspended successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while suspending the account */ - abstract public function suspendAccount(Server_Account $a); + abstract public function suspendAccount(Server_Account $account): bool; /** * Unsuspends an account on the server. * - * @param Server_Account $a account object containing the details of the account to unsuspend + * @param Server_Account $account account object containing the details of the account to unsuspend * * @return bool True if the account was unsuspended successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while unsuspending the account */ - abstract public function unsuspendAccount(Server_Account $a); + abstract public function unsuspendAccount(Server_Account $account): bool; /** * Cancels an account on the server. * - * @param Server_Account $a account object containing the details of the account to cancel + * @param Server_Account $account account object containing the details of the account to cancel * * @return bool True if the account was canceled successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while canceling the account */ - abstract public function cancelAccount(Server_Account $a); + abstract public function cancelAccount(Server_Account $account): bool; /** * Changes the password for an account on the server. * - * @param Server_Account $a account object containing the details of the account to update - * @param string $new_password the new password for the account + * @param Server_Account $account account object containing the details of the account to update + * @param string $newPassword the new password for the account * * @return bool True if the password was changed successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while changing the password */ - abstract public function changeAccountPassword(Server_Account $a, $new_password); + abstract public function changeAccountPassword(Server_Account $account, string $newPassword): bool; /** * Changes the username for an account on the server. * - * @param Server_Account $a account object containing the details of the account to update - * @param string $new_username the new username for the account + * @param Server_Account $account account object containing the details of the account to update + * @param string $newUsername the new username for the account * * @return bool True if the username was changed successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while changing the username */ - abstract public function changeAccountUsername(Server_Account $a, $new_username); + abstract public function changeAccountUsername(Server_Account $account, string $newUsername): bool; /** * Changes the domain for an account on the server. * - * @param Server_Account $a account object containing the details of the account to update - * @param string $new_domain the new domain for the account + * @param Server_Account $account account object containing the details of the account to update * * @return bool True if the domain was changed successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while changing the domain */ - abstract public function changeAccountDomain(Server_Account $a, $new_domain); + abstract public function changeAccountDomain(Server_Account $account, string $newDomain): bool; /** * Changes the IP address for an account on the server. * - * @param Server_Account $a account object containing the details of the account to update - * @param string $new_ip the new IP address for the account + * @param Server_Account $account account object containing the details of the account to update * * @return bool True if the IP address was changed successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while changing the IP address */ - abstract public function changeAccountIp(Server_Account $a, $new_ip); + abstract public function changeAccountIp(Server_Account $account, string $newIp): bool; /** * Changes the package for an account on the server. * - * @param Server_Account $a account object containing the details of the account to update - * @param Server_Package $p new package for the account + * @param Server_Account $account account object containing the details of the account to update + * @param Server_Package $package new package for the account * * @return bool True if the package was changed successfully, if not the sever manager should throw an exception * * @throws Server_Exception if there was an error while changing the package */ - abstract public function changeAccountPackage(Server_Account $a, Server_Package $p); + abstract public function changeAccountPackage(Server_Account $account, Server_Package $package): bool; } diff --git a/src/library/Server/Manager/CWP.php b/src/library/Server/Manager/CWP.php index 3b2d082df..195c64fce 100644 --- a/src/library/Server/Manager/CWP.php +++ b/src/library/Server/Manager/CWP.php @@ -5,7 +5,7 @@ * SPDX-License-Identifier: Apache-2.0. * * @copyright FOSSBilling (https://www.fossbilling.org) - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ /** @@ -15,28 +15,12 @@ */ class Server_Manager_CWP extends Server_Manager { - public function init() - { - if (empty($this->_config['ip'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'IP address'], 2001); - } - - if (empty($this->_config['host'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'Hostname'], 2001); - } - - if (empty($this->_config['accesshash'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'API Key / Access Hash'], 2001); - } else { - $this->_config['accesshash'] = trim($this->_config['accesshash']); - } - - if (empty($this->_config['port'])) { - $this->_config['port'] = '2304'; - } - } - - public static function getForm() + /** + * Returns the form configuration for the CWP server manager. + * + * @return array returns an array with the label and form configuration for the CWP server manager + */ + public static function getForm(): array { return [ 'label' => 'CWP', @@ -57,16 +41,54 @@ class Server_Manager_CWP extends Server_Manager } /** - * We can actually generate a direct log-in link from CWP, but I'm not sure if that's a secure thing to do here. + * Initializes the server manager. + * Checks if the required parameters (IP, host, access hash, port) are set. + * + * @throws Server_Exception if any of the required parameters are not set */ - public function getLoginUrl(Server_Account $account = null) + public function init(): void + { + if (empty($this->_config['ip'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'IP address'], 2001); + } + + if (empty($this->_config['host'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'Hostname'], 2001); + } + + if (empty($this->_config['accesshash'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'CWP', ':missing' => 'API Key / Access Hash'], 2001); + } else { + $this->_config['accesshash'] = trim($this->_config['accesshash']); + } + + if (empty($this->_config['port'])) { + $this->_config['port'] = '2304'; + } + } + + /** + * Returns the login URL for the CWP server manager. + * + * @param Server_Account|null $account the account for which the login URL is generated + * + * @return string returns the login URL as a string + */ + public function getLoginUrl(?Server_Account $account): string { $host = $this->_config['host']; return 'https://' . $host . ':2083'; } - public function getResellerLoginUrl(Server_Account $account = null) + /** + * Returns the reseller login URL for the CWP server manager. + * + * @param Server_Account|null $account the account for which the reseller login URL is generated + * + * @return string returns the reseller login URL as a string + */ + public function getResellerLoginUrl(?Server_Account $account): string { $host = $this->_config['host']; @@ -74,33 +96,44 @@ class Server_Manager_CWP extends Server_Manager } /** - * CWP doesn't have a connection test function, so we ask what kind of server it is (EX: KVM / OpenVZ) - * No error means the connection worked and we can continue. + * Tests the connection to the CWP server. + * Makes a request to the server and checks if the response is successful. + * + * @return bool returns true if the connection test is successful + * + * @throws Server_Exception if the connection test fails */ - public function testConnection() + public function testConnection(): bool { $data = [ 'action' => 'list', ]; - if ($this->makeAPIRequest('account', $data)) { + if ($this->request('account', $data)) { return true; } else { throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'CWP']); } } - public function synchronizeAccount(Server_Account $a) + /** + * Synchronizes the account with the server. + * + * @param Server_Account $account the account to be synchronized + * + * @return Server_Account returns the synchronized account + */ + public function synchronizeAccount(Server_Account $account): Server_Account { - $this->getLog()->info('Synchronizing account with server ' . $a->getUsername()); + $this->getLog()->info('Synchronizing account with server ' . $account->getUsername()); $data = [ 'action' => 'list', - 'user' => $a->getUsername(), + 'user' => $account->getUsername(), ]; - $new = clone $a; - $acc = $this->makeAPIRequest('accountdetail', $data); + $new = clone $account; + $acc = $this->request('accountdetail', $data); if ($acc['account_info']['state'] == 'suspended') { $new->setSuspended(true); @@ -115,9 +148,15 @@ class Server_Manager_CWP extends Server_Manager } /** - * Package name must match on both CWP and FOSSBilling! + * Creates a new account on the CWP server. + * + * @param Server_Account $account the account to be created + * + * @return bool returns true if the account is successfully created + * + * @throws Server_Exception if the account creation fails */ - public function createAccount(Server_Account $account) + public function createAccount(Server_Account $account): bool { $this->getLog()->info('Creating account ' . $account->getUsername()); @@ -141,163 +180,245 @@ class Server_Manager_CWP extends Server_Manager $data['reseller'] = 1; } - if ($this->makeAPIRequest('account', $data)) { - return true; - } else { + if (!$this->request('account', $data)) { $placeholders = [':action:' => __trans('create account'), ':type:' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } - public function suspendAccount(Server_Account $a) + /** + * Suspends an account on the CWP server. + * + * @param Server_Account $account the account to be suspended + * + * @return bool returns true if the account is successfully suspended + * + * @throws Server_Exception if the account suspension fails + */ + public function suspendAccount(Server_Account $account): bool { - $this->getLog()->info('Suspending account ' . $a->getUsername()); + $this->getLog()->info('Suspending account ' . $account->getUsername()); $data = [ 'action' => 'susp', - 'user' => $a->getUsername(), + 'user' => $account->getUsername(), ]; - if ($this->makeAPIRequest('account', $data)) { - return true; - } else { + if (!$this->request('account', $data)) { $placeholders = ['action' => __trans('suspend account'), 'type' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } - public function unsuspendAccount(Server_Account $a) + /** + * Unsuspends an account on the CWP server. + * + * @param Server_Account $account the account to be unsuspended + * + * @return bool returns true if the account is successfully unsuspended + * + * @throws Server_Exception if the account unsuspension fails + */ + public function unsuspendAccount(Server_Account $account): bool { - $this->getLog()->info('Un-suspending account ' . $a->getUsername()); + $this->getLog()->info('Un-suspending account ' . $account->getUsername()); $data = [ 'action' => 'unsp', - 'user' => $a->getUsername(), + 'user' => $account->getUsername(), ]; - if ($this->makeAPIRequest('account', $data)) { - return true; - } else { + if (!$this->request('account', $data)) { $placeholders = [':action:' => __trans('unsuspend account'), ':type:' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } - public function cancelAccount(Server_Account $a) + /** + * Cancels an account on the CWP server. + * + * @param Server_Account $account the account to be cancelled + * + * @return bool returns true if the account is successfully cancelled + * + * @throws Server_Exception if the account cancellation fails + */ + public function cancelAccount(Server_Account $account): bool { - $this->getLog()->info('Canceling account ' . $a->getUsername()); + $this->getLog()->info('Canceling account ' . $account->getUsername()); - $client = $a->getClient(); + $client = $account->getClient(); $data = [ 'action' => 'del', - 'user' => $a->getUsername(), + 'user' => $account->getUsername(), 'email' => $client->getEmail(), ]; - if ($this->makeAPIRequest('account', $data)) { - return true; - } else { + if (!$this->request('account', $data)) { $placeholders = [':action:' => __trans('cancel account'), ':type:' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } - public function changeAccountPackage(Server_Account $a, Server_Package $p) + /** + * Changes the package of an account on the CWP server. + * + * @param Server_Account $account the account for which the package is to be changed + * @param Server_Package $package the new package + * + * @return bool returns true if the package is successfully changed + * + * @throws Server_Exception if the package change fails + */ + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool { - $this->getLog()->info('Changing package on account ' . $a->getUsername()); - - $package = $a->getPackage()->getName(); + $this->getLog()->info('Changing package on account ' . $account->getUsername()); $data = [ 'action' => 'upd', - 'user' => $a->getUsername(), - 'package' => $package, + 'user' => $account->getUsername(), + 'package' => $account->getPackage()->getName(), ]; - if ($this->makeAPIRequest('changepack', $data)) { - return true; - } else { + if (!$this->request('changepack', $data)) { $placeholders = [':action:' => __trans('change account package'), ':type:' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } - public function changeAccountPassword(Server_Account $a, $new) + /** + * Changes the password of an account on the CWP server. + * + * @param Server_Account $account the account for which the password is to be changed + * @param string $newPassword the new password + * + * @return bool returns true if the password is successfully changed + * + * @throws Server_Exception if the password change fails + */ + public function changeAccountPassword(Server_Account $account, string $newPassword): bool { - $this->getLog()->info('Changing password on account ' . $a->getUsername()); + $this->getLog()->info('Changing password on account ' . $account->getUsername()); $data = [ 'action' => 'udp', - 'user' => $a->getUsername(), - 'pass' => $new, + 'user' => $account->getUsername(), + 'pass' => $newPassword, ]; - if ($this->makeAPIRequest('changepass', $data)) { - return true; - } else { + if (!$this->request('changepass', $data)) { $placeholders = [':action:' => __trans('change account password'), ':type:' => 'CWP']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + + return true; } /** - * Function graveyard for things CWP doesn't support. + * Throws an exception because CWP does not support username changes. + * + * @param Server_Account $account the account for which the username is to be changed + * @param string $newUsername the new username + * + * @throws Server_Exception always throws an exception because CWP does not support username changes */ - public function changeAccountUsername(Server_Account $a, $new): never + public function changeAccountUsername(Server_Account $account, string $newUsername): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'CWP', ':action:' => __trans('username changes')]); } - public function changeAccountDomain(Server_Account $a, $new): never + /** + * Throws an exception because CWP does not support changing the account domain. + * + * @param Server_Account $account the account for which the domain is to be changed + * @param string $newDomain the new domain + * + * @throws Server_Exception always throws an exception because CWP does not support changing the account domain + */ + public function changeAccountDomain(Server_Account $account, string $newDomain): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'CWP', ':action:' => __trans('changing the account domain')]); } - public function changeAccountIp(Server_Account $a, $new): never + /** + * Throws an exception because CWP does not support changing the account IP. + * + * @param Server_Account $account the account for which the IP is to be changed + * @param string $newIp the new IP + * + * @throws Server_Exception always throws an exception because CWP does not support changing the account IP + */ + public function changeAccountIp(Server_Account $account, string $newIp): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'CWP', ':action:' => __trans('changing the account IP')]); } /** - * Makes the HTTP request to the server. + * Makes an API request to the CWP server. + * + * @param string $func the function to be called on the server + * @param array $data the data to be sent with the request + * + * @return mixed returns the response from the server */ - private function makeAPIRequest($func, $data) + private function request(string $func, array $data): mixed { + // Add the access hash to the data array $data['key'] = $this->_config['accesshash']; + + // Get the host and port from the config $host = $this->_config['host']; $port = $this->_config['port']; + + // Construct the URL for the request $url = 'https://' . $host . ':' . $port . '/v1/' . $func; + // Get the HTTP client with options set to ignore SSL verification $client = $this->getHttpClient()->withOptions([ 'verify_peer' => false, 'verify_host' => false, ]); + // Make the request and convert the response to an array $request = $client->request('POST', $url, [ 'body' => $data, ]); - $response = $request->toArray(); + // Get the status, result, and message from the response, with default values if they are not set $status = $response['status'] ?? 'Error'; $result = $response['result'] ?? null; $msg = $response['msg'] ?? 'CWP did not return a message in it\'s response.'; - if ($status == 'OK' && $func != 'accountdetail') { - return true; - } elseif ($status !== 'OK') { + // If the status is not 'OK', log an error message and return false + if ($status !== 'OK') { error_log('CWP Server manager error. Status: ' . $status . '. Message: ' . $msg); return false; - } else { + } + + // If the function called is 'accountdetail', return the result from the response + if ($func == 'accountdetail') { return $result; } + + return true; } } diff --git a/src/library/Server/Manager/Custom.php b/src/library/Server/Manager/Custom.php index 734a12ea9..5f7ac3e58 100644 --- a/src/library/Server/Manager/Custom.php +++ b/src/library/Server/Manager/Custom.php @@ -1,28 +1,21 @@ 'Custom Server Manager', @@ -30,177 +23,239 @@ class Server_Manager_Custom extends Server_Manager } /** - * Returns link to account management page. - * - * @return string + * Initializes the server manager. + * Add required parameters checks here. */ - public function getLoginUrl(Server_Account $account = null) + public function init() + { + } + + /** + * Returns the URL for account management. + * + * @param Server_Account|null $account the account for which the URL is generated + * + * @return string returns the URL as a string + */ + public function getLoginUrl(Server_Account $account = null): string { return 'http://www.google.com?q=cpanel'; } /** - * Returns link to reseller account management. + * Returns the URL for reseller account management. * - * @return string + * @param Server_Account|null $account the account for which the URL is generated + * + * @return string returns the URL as a string */ - public function getResellerLoginUrl(Server_Account $account = null) + public function getResellerLoginUrl(Server_Account $account = null): string { return 'http://www.google.com?q=whm'; } /** - * This method is called to check if configuration is correct - * and class can connect to server. + * Tests the connection to the server. * - * @return bool + * @return bool returns true if the connection is successful */ - public function testConnection() + public function testConnection(): bool { return true; } /** - * Methods retrieves information from server, assigns new values to - * cloned Server_Account object and returns it. + * Synchronizes the account with the server. * - * @return Server_Account + * @param Server_Account $account the account to be synchronized + * + * @return Server_Account returns the synchronized account */ - public function synchronizeAccount(Server_Account $a) + public function synchronizeAccount(Server_Account $account): Server_Account { - $this->getLog()->info('Synchronizing account with server ' . $a->getUsername()); - $new = clone $a; + $this->getLog()->info('Synchronizing account with server ' . $account->getUsername()); // @example - retrieve username from server and set it to cloned object // $new->setUsername('newusername'); - return $new; + return clone $account; } /** - * Create new account on server. + * Creates a new account on the server. + * + * @param Server_Account $account the account to be created + * + * @return bool returns true if the account is successfully created */ - public function createAccount(Server_Account $account) + public function createAccount(Server_Account $account): bool { if ($account->getReseller()) { $this->getLog()->info('Creating reseller hosting account'); } else { $this->getLog()->info('Creating shared hosting account'); } + + return true; } /** - * Suspend account on server. + * Suspends an account on the server. + * + * @param Server_Account $account the account to be suspended + * + * @return bool returns true if the account is successfully suspended */ - public function suspendAccount(Server_Account $a) + public function suspendAccount(Server_Account $account): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Suspending reseller hosting account'); } else { $this->getLog()->info('Suspending shared hosting account'); } + + return true; } /** - * Unsuspend account on server. + * Unsuspends an account on the server. + * + * @param Server_Account $account the account to be unsuspended + * + * @return bool returns true if the account is successfully unsuspended */ - public function unsuspendAccount(Server_Account $a) + public function unsuspendAccount(Server_Account $account): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Unsuspending reseller hosting account'); } else { $this->getLog()->info('Unsuspending shared hosting account'); } + + return true; } /** - * Cancel account on server. + * Cancels an account on the server. + * + * @param Server_Account $account the account to be cancelled + * + * @return bool returns true if the account is successfully cancelled */ - public function cancelAccount(Server_Account $a) + public function cancelAccount(Server_Account $account): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Canceling reseller hosting account'); } else { $this->getLog()->info('Canceling shared hosting account'); } + + return true; } /** - * Change account package on server. + * Changes the package of an account on the server. + * + * @param Server_Account $account the account for which the package is to be changed + * @param Server_Package $package the new package + * + * @return bool returns true if the package is successfully changed */ - public function changeAccountPackage(Server_Account $a, Server_Package $p) + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Updating reseller hosting account'); } else { $this->getLog()->info('Updating shared hosting account'); } - $p->getName(); - $p->getQuota(); - $p->getBandwidth(); - $p->getMaxSubdomains(); - $p->getMaxParkedDomains(); - $p->getMaxDomains(); - $p->getMaxFtp(); - $p->getMaxSql(); - $p->getMaxPop(); + $package->getName(); + $package->getQuota(); + $package->getBandwidth(); + $package->getMaxSubdomains(); + $package->getMaxParkedDomains(); + $package->getMaxDomains(); + $package->getMaxFtp(); + $package->getMaxSql(); + $package->getMaxPop(); - $p->getCustomValue('param_name'); + $package->getCustomValue('param_name'); + + return true; } /** - * Change account username on server. + * Changes the username of an account on the server. * - * @param type $new - new account username + * @param Server_Account $account the account for which the username is to be changed + * @param string $newUsername the new username + * + * @return bool returns true if the username is successfully changed */ - public function changeAccountUsername(Server_Account $a, $new) + public function changeAccountUsername(Server_Account $account, string $newUsername): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Changing reseller hosting account username'); } else { $this->getLog()->info('Changing shared hosting account username'); } + + return true; } /** - * Change account domain on server. + * Changes the domain of an account on the server. * - * @param type $new - new domain name + * @param Server_Account $account the account for which the domain is to be changed + * @param string $newDomain the new domain + * + * @return bool returns true if the domain is successfully changed */ - public function changeAccountDomain(Server_Account $a, $new) + public function changeAccountDomain(Server_Account $account, string $newDomain): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Changing reseller hosting account domain'); } else { $this->getLog()->info('Changing shared hosting account domain'); } + + return true; } /** - * Change account password on server. + * Changes the password of an account on the server. * - * @param type $new - new password + * @param Server_Account $account the account for which the password is to be changed + * @param string $newPassword the new password + * + * @return bool returns true if the password is successfully changed */ - public function changeAccountPassword(Server_Account $a, $new) + public function changeAccountPassword(Server_Account $account, string $newPassword): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Changing reseller hosting account password'); } else { $this->getLog()->info('Changing shared hosting account password'); } + + return true; } /** - * Change account IP on server. + * Changes the IP of an account on the server. * - * @param type $new - account IP + * @param Server_Account $account the account for which the IP is to be changed + * @param string $newIp the new IP + * + * @return bool returns true if the IP is successfully changed */ - public function changeAccountIp(Server_Account $a, $new) + public function changeAccountIp(Server_Account $account, string $newIp): bool { - if ($a->getReseller()) { + if ($account->getReseller()) { $this->getLog()->info('Changing reseller hosting account ip'); } else { $this->getLog()->info('Changing shared hosting account ip'); } + + return true; } } diff --git a/src/library/Server/Manager/Directadmin.php b/src/library/Server/Manager/Directadmin.php index 93f557681..ec42d306c 100644 --- a/src/library/Server/Manager/Directadmin.php +++ b/src/library/Server/Manager/Directadmin.php @@ -5,10 +5,12 @@ * SPDX-License-Identifier: Apache-2.0. * * @copyright FOSSBilling (https://www.fossbilling.org) - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ use Random\RandomException; +use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface; +use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; /** * Class Server_Manager_Directadmin @@ -17,31 +19,6 @@ use Random\RandomException; */ class Server_Manager_Directadmin extends Server_Manager { - /** - * Initialize the server manager. - * Checks if the host, username, and password are set in the configuration. - * Throws an exception if any of these are not set. - * - * @throws Server_Exception - */ - public function init(): void - { - // Check if host is set in the configuration - if (empty($this->_config['host'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'hostname'], 2001); - } - - // Check if username is set in the configuration - if (empty($this->_config['username'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'username'], 2001); - } - - // Check if password is set in the configuration - if (empty($this->_config['password'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'password'], 2001); - } - } - /** * Returns the form configuration for the DirectAdmin server manager. * The form includes fields for username and password. @@ -75,6 +52,54 @@ class Server_Manager_Directadmin extends Server_Manager ]; } + /** + * Initialize the server manager. + * Checks if the host, username, and password are set in the configuration. + * Throws an exception if any of these are not set. + * + * @throws Server_Exception + */ + public function init(): void + { + // Check if host is set in the configuration + if (empty($this->_config['host'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'hostname'], 2001); + } + + // Check if username is set in the configuration + if (empty($this->_config['username'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'username'], 2001); + } + + // Check if password is set in the configuration + if (empty($this->_config['password'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'DirectAdmin', ':missing' => 'password'], 2001); + } + } + + /** + * Cancels an account on the DirectAdmin server. + * This method sends a request to the server to delete the account. + * + * @param Server_Account $account the account to be cancelled + * + * @return bool returns true if the account is successfully cancelled + * + * @throws Server_Exception if there is an error while sending the request to the server + */ + public function cancelAccount(Server_Account $account): bool + { + $fields = [ + 'confirmed' => 'Confirm', + 'delete' => 'yes', + 'select0' => $account->getUsername(), + ]; + + $this->request('API_SELECT_USERS', $fields); + + return true; + } + /** * Returns the port number for the DirectAdmin server. * If the port is set in the configuration, verify that it's a valid port number (0 - 65535). @@ -82,7 +107,7 @@ class Server_Manager_Directadmin extends Server_Manager * * @return int|string the port number */ - public function _getPort(): int|string + public function getPort(): int|string { $port = $this->_config['port']; @@ -94,89 +119,93 @@ class Server_Manager_Directadmin extends Server_Manager } /** - * Returns the login URL for the DirectAdmin server. - * The URL includes the host and port from the configuration. - * If the 'secure' configuration option is set, the URL uses the 'https' protocol. - * Otherwise, it uses the 'http' protocol. + * Changes the domain of an account on the DirectAdmin server. + * This method is not supported and will always throw an exception. * - * @param Server_Account|null $account The server account. This parameter is not used in this method. + * @param Server_Account $account the account for which the domain is to be changed + * @param string $newDomain the new domain * - * @return string the login URL + * @throws Server_Exception always throws an exception indicating that the method is not supported */ - public function getLoginUrl(Server_Account $account = null): string + public function changeAccountDomain(Server_Account $account, string $newDomain): never { - $protocol = $this->_config['secure'] ? 'https://' : 'http://'; - - return $protocol . $this->_config['host'] . ':' . $this->_getPort(); + throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('changing the account domain')]); } /** - * Returns the login URL for a reseller account on the DirectAdmin server. - * This method simply calls the getLoginUrl method, as the URL is the same for reseller accounts. + * Changes the IP of an account on the DirectAdmin server. + * This method is not supported and will always throw an exception. * - * @param Server_Account|null $account The server account. This parameter is not used in this method. + * @param Server_Account $account the account for which the IP is to be changed + * @param string $newIp the new IP * - * @return string the login URL + * @throws Server_Exception always throws an exception indicating that the method is not supported */ - public function getResellerLoginUrl(Server_Account $account = null): string + public function changeAccountIp(Server_Account $account, string $newIp): never { - return $this->getLoginUrl(); + throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('changing the account IP')]); } /** - * Generates a username for a new account on the DirectAdmin server. - * The username is based on the domain name, but is sanitized to be alphanumeric and start with a letter. - * The username is also limited to 10 characters to avoid collisions. + * Changes the package of an account on the DirectAdmin server. + * This method sends a request to the server to change the package of the account. * - * @param string $domain_name the domain name + * @param Server_Account $account the account for which the package is to be changed + * @param Server_Package $package the new package * - * @return string the generated username + * @return bool returns true if the package is successfully changed * - * @throws RandomException + * @throws Server_Exception if there is an error while sending the request to the server */ - public function generateUsername($domain_name): string + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool { - // Username must be alphanumeric. - $username = preg_replace('/[^A-Za-z0-9]/', '', $domain_name); + $fields = [ + 'action' => 'package', + 'user' => $account->getUsername(), + 'package' => $account->getPackage()->getName(), + ]; - // Username must start with a-z. - $username = is_numeric(substr($username, 0, 1)) ? substr_replace($username, chr(random_int(97, 122)), 0, 1) : $username; - - // Username must be at most 10 characters long, and sufficiently random to avoid collisions. - $username = substr($username, 0, 7); - - $random_number = random_int(0, 99); - - return $username . $random_number; - } - - /** - * Tests the connection to the DirectAdmin server. - * This method sends a request to the server and checks if the response is an array. - * - * @return bool true if the connection is successful, false otherwise - * - * @throws Server_Exception - */ - public function testConnection(): bool - { - // Makes login test connection. As we don't currently force JSON, DirectAdmin will return HTML on a failed attempt, which causes the request to throw an error. - $this->_request('API_LOGIN_TEST'); + $this->request('API_MODIFY_USER', $fields); return true; } /** - * Synchronizes the server account with the DirectAdmin server. - * This method currently does nothing and simply returns the account as is. + * Changes the password of an account on the DirectAdmin server. + * This method sends a request to the server to change the password of the account. * - * @param Server_Account $a the server account + * @param Server_Account $account the account for which the password is to be changed + * @param string $newPassword the new password * - * @return Server_Account the same server account + * @return bool returns true if the password is successfully changed + * + * @throws Server_Exception if there is an error while sending the request to the server */ - public function synchronizeAccount(Server_Account $a): Server_Account + public function changeAccountPassword(Server_Account $account, string $newPassword): bool { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('synchronizing the account')]); + $fields = [ + 'username' => $account->getUsername(), + 'passwd' => $newPassword, + 'passwd2' => $newPassword, + ]; + + $this->request('API_USER_PASSWD', $fields); + + return true; + } + + /** + * Changes the username of an account on the DirectAdmin server. + * This method is not supported and will always throw an exception. + * + * @param Server_Account $account the account for which the username is to be changed + * @param string $newUsername the new username + * + * @throws Server_Exception always throws an exception indicating that the method is not supported + */ + public function changeAccountUsername(Server_Account $account, string $newUsername): never + { + throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('username changes')]); } /** @@ -201,78 +230,93 @@ class Server_Manager_Directadmin extends Server_Manager $package = $account->getPackage(); $client = $account->getClient(); - $fields = []; - $fields['action'] = 'create'; - $fields['add'] = 'Submit'; - $fields['username'] = $account->getUsername(); - $fields['email'] = $client->getEmail(); - $fields['passwd'] = $account->getPassword(); - $fields['passwd2'] = $account->getPassword(); - $fields['domain'] = $account->getDomain(); - $fields['ip'] = $ip; - $fields['notify'] = 'no'; + $fields = [ + 'action' => 'create', + 'add' => 'Submit', + 'username' => $account->getUsername(), + 'email' => $client->getEmail(), + 'passwd' => $account->getPassword(), + 'passwd2' => $account->getPassword(), + 'domain' => $account->getDomain(), + 'ip' => $ip, + 'notify' => 'no', + ]; + // If the `package` custom value is set, use that package from the DirectAdmin server instead of implicitly creating a new one if (!empty($package->getCustomValue('package'))) { $this->getLog()->info('Using DirectAdmin package name: ' . $package->getCustomValue('package') . ', ignoring package settings'); $fields['package'] = $package->getCustomValue('package'); } else { - $fields['bandwidth'] = $package->getBandwidth(); // Amount of bandwidth User will be allowed to use. Number, in Megabytes + // Specify the package quotas + $fields = array_merge($fields, [ + 'aftp' => $package->getCustomValue('aftp') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will be able to have anonymous ftp accounts. + 'bandwidth' => $package->getBandwidth(), // Bandwidth quota in MB + 'catchall' => $package->getCustomValue('catchall') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to enable and customize a catch-all email (*@domain.com). + 'cgi' => $package->getCustomValue('cgi') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run cgi scripts in their cgi-bin. + 'cron' => $package->getCustomValue('cron') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to creat cronjobs. + 'dnscontrol' => $package->getCustomValue('dnscontrol') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will be able to modify his/her dns records. + 'domainptr' => $package->getMaxParkedDomains(), // Domain pointer quota + 'ftp' => $package->getMaxFtp(), // FTP account quota + 'login_keys' => $package->getCustomValue('login_keys') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have access to the Login Key system for extra account passwords. + 'mysql' => $package->getMaxSql(), // Database quota + 'nemailf' => $package->getMaxEmailForwarders(), // Email forwarder quota + 'nemailml' => $package->getMaxEmailLists(), // Mailing list quota + 'nemailr' => $package->getMaxEmailAutoresponders(), // Autoresponder quota + 'nemails' => $package->getMaxPop(), // Email account quota + 'nsubdomains' => $package->getMaxSubdomains(), // Subdomain quota + 'php' => $package->getCustomValue('php') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run php scripts. + 'quota' => $package->getQuota(), // Disk space quota in MB + 'spam' => $package->getCustomValue('spam') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run scan email with SpamAssassin. + 'ssh' => $package->getCustomValue('ssh') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have an ssh account. + 'ssl' => $package->getCustomValue('ssl') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to access their websites through secure https://. + 'suspend_at_limit' => $package->getCustomValue('suspend_at_limit') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will be suspended if their User bandwidth limit is exceeded. + 'sysinfo' => $package->getCustomValue('sysinfo') ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have access to a page that shows the system information. + 'vdomains' => $package->getMaxDomains(), // Domain quota + ]); + if ($package->getBandwidth() == 'unlimited') { $fields['ubandwidth'] = 'ON'; // ON or OFF. If ON, bandwidth is ignored and no limit is set } - $fields['quota'] = $package->getQuota(); // Amount of disk space User will be allowed to use. Number, in Megabytes + if ($package->getQuota() == 'unlimited') { $fields['uquota'] = 'ON'; // ON or OFF. If ON, quota is ignored and no limit is set } - $fields['vdomains'] = $package->getMaxDomains(); // Number of domains the User will be allowed to create + if ($package->getMaxDomains() == 'unlimited') { $fields['uvdomains'] = 'ON'; // ON or OFF. If ON, vdomains is ignored and no limit is set } - $fields['nsubdomains'] = $package->getMaxSubdomains(); // Number of subdomains the User will be allowed to create + if ($package->getMaxSubdomains() == 'unlimited') { $fields['unsubdomains'] = 'ON'; // ON or OFF. If ON, nsubdomains is ignored and no limit is set } - $fields['domainptr'] = $package->getMaxParkedDomains(); // Number of domain pointers the User will be allowed to create + if ($package->getMaxParkedDomains() == 'unlimited') { $fields['udomainptr'] = 'ON'; // ON or OFF Unlimited option for domainptr } - $fields['nemails'] = $package->getMaxPop(); // Number of pop accounts the User will be allowed to create + if ($package->getMaxPop() == 'unlimited') { $fields['unemails'] = 'ON'; // ON or OFF Unlimited option for nemails } - $fields['mysql'] = $package->getMaxSql(); // Number of MySQL databases the User will be allowed to create + if ($package->getMaxSql() == 'unlimited') { $fields['umysql'] = 'ON'; // ON or OFF Unlimited option for mysql } - $fields['ftp'] = $package->getMaxFtp(); // Number of ftp accounts the User will be allowed to create + if ($package->getMaxFtp() == 'unlimited') { $fields['uftp'] = 'ON'; // ON or OFF Unlimited option for ftp } - $fields['nemailf'] = $package->getCustomValue('nemailf'); // Number of forwarders the User will be allowed to create + if ($fields['nemailf'] == 'unlimited') { $fields['unemailf'] = 'ON'; // ON or OFF Unlimited option for nemailf } - $fields['nemailml'] = $package->getCustomValue('nemailml'); // Number of mailing lists the User will be allowed to create + if ($fields['nemailml'] == 'unlimited') { $fields['unemailml'] = 'ON'; // ON or OFF Unlimited option for nemailml } - $fields['nemailr'] = $package->getCustomValue('nemailr'); // Number of autoresponders the User will be allowed to create + if ($fields['nemailr'] == 'unlimited') { $fields['unemailr'] = 'ON'; // ON or OFF Unlimited option for nemailr } - - $fields['aftp'] = $package->getCustomValue('aftp') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will be able to have anonymous ftp accounts. - $fields['cgi'] = $package->getCustomValue('cgi') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run cgi scripts in their cgi-bin. - $fields['php'] = $package->getCustomValue('php') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run php scripts. - $fields['spam'] = $package->getCustomValue('spam') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run scan email with SpamAssassin. - $fields['cron'] = $package->getCustomValue('cron') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to creat cronjobs. - $fields['catchall'] = $package->getCustomValue('catchall') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to enable and customize a catch-all email (*@domain.com). - $fields['ssl'] = $package->getCustomValue('ssl') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to access their websites through secure https://. - $fields['ssh'] = $package->getCustomValue('ssh') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have an ssh account. - $fields['sysinfo'] = $package->getCustomValue('sysinfo') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have access to a page that shows the system information. - $fields['login_keys'] = $package->getCustomValue('login_keys') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have access to the Login Key system for extra account passwords. - $fields['dnscontrol'] = $package->getCustomValue('dnscontrol') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will be able to modify his/her dns records. - $fields['suspend_at_limit'] = $package->getCustomValue('suspend_at_limit') ? 'ON' : 'OFF'; // ON or OFF If ON, the User will be suspended if their User bandwidth limit is exceeded. } $command = 'API_ACCOUNT_USER'; @@ -285,7 +329,7 @@ class Server_Manager_Directadmin extends Server_Manager } try { - $results = $this->_request($command, $fields); + $results = $this->request($command, $fields); } catch (Exception $e) { if (strtolower($e->getMessage()) == strtolower(sprintf('Server Manager DirectAdmin Error: "%s" ', 'That domain already exists'))) { return true; @@ -305,224 +349,269 @@ class Server_Manager_Directadmin extends Server_Manager return true; } - public function suspendAccount(Server_Account $a) + /** + * Returns the login URL for a reseller account on the DirectAdmin server. + * This method simply calls the getLoginUrl method, as the URL is the same for reseller accounts. + * + * @param Server_Account|null $account The server account. This parameter is not used in this method. + * + * @return string the login URL + */ + public function getResellerLoginUrl(Server_Account $account = null): string { - $info = $this->getAccountInfo($a); + return $this->getLoginUrl(); + } + + /** + * Returns the login URL for the DirectAdmin server. + * The URL includes the host and port from the configuration. + * If the 'secure' configuration option is set, the URL uses the 'https' protocol. + * Otherwise, it uses the 'http' protocol. + * + * @param Server_Account|null $account The server account. This parameter is not used in this method. + * + * @return string the login URL + */ + public function getLoginUrl(Server_Account $account = null): string + { + $protocol = $this->_config['secure'] ? 'https://' : 'http://'; + + return $protocol . $this->_config['host'] . ':' . $this->getPort(); + } + + /** + * Generates a username for a new account on the DirectAdmin server. + * The username is based on the domain name, but is sanitized to be alphanumeric and start with a letter. + * The username is also limited to 10 characters to avoid collisions. + * + * @param string $domain the domain name + * + * @return string the generated username + * + * @throws RandomException + */ + public function generateUsername(string $domain): string + { + // Username must be alphanumeric. + $username = preg_replace('/[^A-Za-z0-9]/', '', $domain); + + // Username must start with a-z. + $username = is_numeric(substr($username, 0, 1)) ? substr_replace($username, chr(random_int(97, 122)), 0, 1) : $username; + + // Username must be at most 10 characters long, and sufficiently random to avoid collisions. + $username = substr($username, 0, 7); + + $random_number = random_int(0, 99); + + return $username . $random_number; + } + + /** + * Tests the connection to the DirectAdmin server. + * This method sends a request to the server and checks if the response is an array. + * + * @return bool true if the connection is successful, false otherwise + * + * @throws Server_Exception + */ + public function testConnection(): bool + { + // Makes login test connection. As we don't currently force JSON, DirectAdmin will return HTML on a failed attempt, which causes the request to throw an error. + $this->request('API_LOGIN_TEST'); + + return true; + } + + /** + * Synchronizes the server account with the DirectAdmin server. + * This method currently does nothing and simply returns the account as is. + * + * @param Server_Account $account the server account + * + * @return Server_Account the same server account + * + * @throws Server_Exception + */ + public function synchronizeAccount(Server_Account $account): Server_Account + { + throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('synchronizing the account')]); + } + + /** + * Suspends an account on the DirectAdmin server. + * This method sends a request to the server to suspend the account. + * + * @param Server_Account $account the account to be suspended + * + * @return bool returns true if the account is already suspended or is successfully suspended + * + * @throws Server_Exception if there is an error while sending the request to the server + */ + public function suspendAccount(Server_Account $account): bool + { + $info = $this->getAccountInfo($account); if ($info['suspended'] == 'yes') { return true; } - $fields = []; - $fields['location'] = 'USER_SHOW'; - $fields['suspend'] = 'Suspend'; - $fields['select0'] = $a->getUsername(); - $result = $this->_request('API_SELECT_USERS', $fields); + $fields = [ + 'location' => 'USER_SHOW', + 'suspend' => 'Suspend', + 'select0' => $account->getUsername(), + ]; + + $this->request('API_SELECT_USERS', $fields); return true; } - public function unsuspendAccount(Server_Account $a) + /** + * Unsuspends an account on the DirectAdmin server. + * This method sends a request to the server to unsuspend the account. + * + * @param Server_Account $account the account to be unsuspended + * + * @return bool returns true if the account is successfully unsuspended + * + * @throws Server_Exception if the account is not suspended or there is an error while sending the request to the server + */ + public function unsuspendAccount(Server_Account $account): bool { - $info = $this->getAccountInfo($a); + $info = $this->getAccountInfo($account); if ($info['suspended'] == 'no') { throw new Server_Exception('Server Manager DirectAdmin Error: "Account is not suspended"'); } - $fields = []; - $fields['location'] = 'USER_SHOW'; - $fields['suspend'] = 'Unsuspend'; - $fields['select0'] = $a->getUsername(); - $this->_request('API_SELECT_USERS', $fields); + $fields = [ + 'location' => 'USER_SHOW', + 'suspend' => 'Unsuspend', + 'select0' => $account->getUsername(), + ]; + + $this->request('API_SELECT_USERS', $fields); return true; } - public function cancelAccount(Server_Account $a) - { - $fields = []; - $fields['confirmed'] = 'Confirm'; - $fields['delete'] = 'yes'; - $fields['select0'] = $a->getUsername(); - $this->_request('API_SELECT_USERS', $fields); - - return true; - } - - public function modifyAccount(Server_Account $a) - { - $package = $a->getPackage(); - - $fields = []; - $fields['action'] = 'customize'; - $fields['user'] = $a->getUsername(); - - $fields['bandwidth'] = $package->getBandwidth(); // Amount of bandwidth User will be allowed to use. Number, in Megabytes - if ($package->getBandwidth() == 'unlimited') { - $fields['ubandwidth'] = 'ON'; // ON or OFF. If ON, bandwidth is ignored and no limit is set - } - $fields['quota'] = $package->getQuota(); // Amount of disk space User will be allowed to use. Number, in Megabytes - if ($package->getQuota() == 'unlimited') { - $fields['uquota'] = 'ON'; // ON or OFF. If ON, quota is ignored and no limit is set - } - $fields['vdomains'] = $package->getMaxDomains(); // Number of domains the User will be allowed to create - if ($package->getMaxDomains() == 'unlimited') { - $fields['uvdomains'] = 'ON'; // ON or OFF. If ON, vdomains is ignored and no limit is set - } - $fields['nsubdomains'] = $package->getMaxSubdomains(); // Number of subdomains the User will be allowed to create - if ($package->getMaxSubdomains() == 'unlimited') { - $fields['unsubdomains'] = 'ON'; // ON or OFF. If ON, nsubdomains is ignored and no limit is set - } - $fields['nemails'] = $package->getMaxPop(); // Number of pop accounts the User will be allowed to create - if ($package->getMaxPop() == 'unlimited') { - $fields['unemails'] = 'ON'; // ON or OFF Unlimited option for nemails - } - $fields['nemailf'] = $package->getMaxEmailForwarders(); // Number of forwarders the User will be allowed to create - if ($package->getMaxEmailForwarders() == 'unlimited') { - $fields['unemailf'] = 'ON'; // ON or OFF Unlimited option for nemailf - } - $fields['nemailml'] = $package->getMaxEmailLists(); // Number of mailing lists the User will be allowed to create - if ($package->getMaxEmailLists() == 'unlimited') { - $fields['unemailml'] = 'ON'; // ON or OFF Unlimited option for nemailml - } - $fields['nemailr'] = $package->getMaxEmailAutoresponders(); // Number of autoresponders the User will be allowed to create - if ($package->getMaxEmailAutoresponders() == 'unlimited') { - $fields['unemailr'] = 'ON'; // ON or OFF Unlimited option for nemailr - } - $fields['mysql'] = $package->getMaxSql(); // Number of MySQL databases the User will be allowed to create - if ($package->getMaxSql() == 'unlimited') { - $fields['umysql'] = 'ON'; // ON or OFF Unlimited option for mysql - } - $fields['domainptr'] = $package->getMaxParkedDomains(); // Number of domain pointers the User will be allowed to create - if ($package->getMaxParkedDomains() == 'unlimited') { - $fields['udomainptr'] = 'ON'; // ON or OFF Unlimited option for domainptr - } - $fields['ftp'] = $package->getMaxFtp(); // Number of ftp accounts the User will be allowed to create - if ($package->getMaxFtp() == 'unlimited') { - $fields['uftp'] = 'ON'; // ON or OFF Unlimited option for ftp - } - $fields['aftp'] = $package->getHasAnonymousFtp() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will be able to have anonymous ftp accounts. - $fields['cgi'] = $package->getHasCgi() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run cgi scripts in their cgi-bin. - $fields['php'] = $package->getHasPhp() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run php scripts. - $fields['spam'] = $package->getHasSpamFilter() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to run scan email with SpamAssassin. - $fields['cron'] = $package->getHasCron() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to creat cronjobs. - $fields['catchall'] = $package->getHasCatchAll() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to enable and customize a catch-all email (*@domain.com). - $fields['ssl'] = $package->getHasSll() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have the ability to access their websites through secure https://. - $fields['ssh'] = $package->getHasShell() ? 'ON' : 'OFF'; // ON or OFF If ON, the User will have an ssh account. - $fields['sysinfo'] = 'ON'; // ON or OFF If ON, the User will have access to a page that shows the system information. - $fields['dnscontrol'] = 'ON'; // ON or OFF If ON, the User will be able to modify his/her dns records. - - $fields['ns1'] = $a->getNs1(); - $fields['ns2'] = $a->getNs2(); - - $this->_request('API_MODIFY_USER', $fields); - - return true; - } - - public function changeAccountDomain(Server_Account $a, $new_domain): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('changing the account domain')]); - } - - public function changeAccountIp(Server_Account $account, $new_ip): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('changing the account IP')]); - } - - public function changeAccountPackage(Server_Account $a, Server_Package $p): bool - { - $fields = []; - $fields['action'] = 'package'; - $fields['user'] = $a->getUsername(); - $fields['package'] = $a->getPackage()->getName(); - - $this->_request('API_MODIFY_USER', $fields); - - return true; - } - - public function changeAccountPassword(Server_Account $a, $new_password) - { - $fields = []; - $fields['username'] = $a->getUsername(); - $fields['passwd'] = $new_password; - $fields['passwd2'] = $new_password; - $this->_request('API_USER_PASSWD', $fields); - - return true; - } - - public function changeAccountUsername(Server_Account $a, $new_username): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'DirectAdmin', ':action:' => __trans('username changes')]); - } - /** - * @throws Server_Exception - */ - private function getAccountInfo(Server_Account $account): array - { - $fields = []; - $fields['action'] = 'create'; - - $fields['add'] = 'Submit'; - $fields['user'] = $account->getUsername(); - - return $this->_request('API_SHOW_USER_CONFIG', $fields); - } - - /** - * @throws Server_Exception - */ - private function getUserInfo(Server_Account $account) - { - $fields = []; - $fields['user'] = $account->getUsername(); - $result = $this->_request('API_SHOW_USER_CONFIG', $fields); - - return; - } - - /** - * This method is used to verify the authentication credentials for the DirectAdmin server. - * It sends a request to the server with the 'API_VERIFY_PASSWORD' command and the username and password from the configuration. - * The response from the server is stored in the $response variable, but is not used in this method. - * The method always returns true, regardless of the server's response. + * Modifies an existing account on the DirectAdmin server. + * This method sends a request to the server with the updated account details. + * If certain account parameters are set to 'unlimited', the corresponding fields are set to 'ON'. * - * @return bool always returns true + * @param Server_Account $account the server account to be modified + * + * @return bool returns true if the account is modified successfully * * @throws Server_Exception if there is an error while sending the request to the server */ - private function checkAuth() + public function modifyAccount(Server_Account $account): bool { - $response = $this->_request('API_VERIFY_PASSWORD', [ - 'user' => $this->_config['username'], - 'passwd' => $this->_config['password'], - ]); + // Get the package associated with the account + $package = $account->getPackage(); + + // Prepare the fields for the request + $fields = [ + 'aftp' => $package->getHasAnonymousFtp() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will be able to have anonymous ftp accounts. + 'action' => 'customize', + 'bandwidth' => $package->getBandwidth(), // Bandwidth quota in MB + 'catchall' => $package->getHasCatchAll() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to enable and customize a catch-all email (*@domain.com). + 'cgi' => $package->getHasCgi() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run cgi scripts in their cgi-bin. + 'cron' => $package->getHasCron() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to creat cronjobs. + 'dnscontrol' => 'ON', // ON or OFF. If ON, the User will be able to modify his/her dns records. + 'domainptr' => $package->getMaxParkedDomains(), // Domain pointer quota + 'ftp' => $package->getMaxFtp(), // FTP account quota + 'mysql' => $package->getMaxSql(), // MySQL database quota + 'nemailf' => $package->getMaxEmailForwarders(), // Email forwarder quota + 'nemailml' => $package->getMaxEmailLists(), // Mailing list quota + 'nemailr' => $package->getMaxEmailAutoresponders(), // Autoresponder quota + 'nemails' => $package->getMaxPop(), // Email account quota + 'nsubdomains' => $package->getMaxSubdomains(), // Subdomain quota + 'ns1' => $account->getNs1(), + 'ns2' => $account->getNs2(), + 'php' => $package->getHasPhp() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run php scripts. + 'quota' => $package->getQuota(), // Disk space quota in MB + 'spam' => $package->getHasSpamFilter() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to run scan email with SpamAssassin. + 'ssh' => $package->getHasShell() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have an ssh account. + 'ssl' => $package->getHasSll() ? 'ON' : 'OFF', // ON or OFF. If ON, the User will have the ability to access their websites through secure https://. + 'sysinfo' => 'ON', // ON or OFF. If ON, the User will have access to a page that shows the system information. + 'user' => $account->getUsername(), + 'vdomains' => $package->getMaxDomains(), // Domain quota + ]; + + // Check if certain parameters are set to 'unlimited' and set the corresponding fields to 'ON' + if ($package->getBandwidth() == 'unlimited') { + $fields['ubandwidth'] = 'ON'; // ON or OFF. If ON, bandwidth is ignored and no limit is set + } + + if ($package->getQuota() == 'unlimited') { + $fields['uquota'] = 'ON'; // ON or OFF. If ON, quota is ignored and no limit is set + } + + if ($package->getMaxDomains() == 'unlimited') { + $fields['uvdomains'] = 'ON'; // ON or OFF. If ON, vdomains is ignored and no limit is set + } + + if ($package->getMaxSubdomains() == 'unlimited') { + $fields['unsubdomains'] = 'ON'; // ON or OFF. If ON, nsubdomains is ignored and no limit is set + } + + if ($package->getMaxPop() == 'unlimited') { + $fields['unemails'] = 'ON'; // ON or OFF Unlimited option for nemails + } + + if ($package->getMaxEmailForwarders() == 'unlimited') { + $fields['unemailf'] = 'ON'; // ON or OFF Unlimited option for nemailf + } + + if ($package->getMaxEmailLists() == 'unlimited') { + $fields['unemailml'] = 'ON'; // ON or OFF Unlimited option for nemailml + } + + if ($package->getMaxEmailAutoresponders() == 'unlimited') { + $fields['unemailr'] = 'ON'; // ON or OFF Unlimited option for nemailr + } + + if ($package->getMaxSql() == 'unlimited') { + $fields['umysql'] = 'ON'; // ON or OFF Unlimited option for mysql + } + + if ($package->getMaxParkedDomains() == 'unlimited') { + $fields['udomainptr'] = 'ON'; // ON or OFF Unlimited option for domainptr + } + + if ($package->getMaxFtp() == 'unlimited') { + $fields['uftp'] = 'ON'; // ON or OFF Unlimited option for ftp + } + + // Send the request to the server + $this->request('API_MODIFY_USER', $fields); return true; } /** - * @throws Server_Exception + * Sends a request to the DirectAdmin server. + * + * @param string $command the command to be executed on the server + * @param array $fields the fields to be included in the request + * @param bool $post Whether the request should be a POST request. If false, a GET request is sent. + * + * @return array the response from the server, parsed into an array + * + * @throws Server_Exception if there is an error while sending the request or if the server returns an error */ - private function getIps() - { - $results = $this->_request('API_SHOW_RESELLER_IPS'); - - return $results['list'] ?? []; - } - - /** - * @throws Server_Exception - */ - private function _request(string $command, array $fields = [], bool $post = true): array + private function request(string $command, array $fields = [], bool $post = true): array { + // Get the host from the configuration $host = $this->_config['host']; + + // Determine the protocol based on the 'secure' configuration option $protocol = $this->_config['secure'] ? 'https://' : 'http://'; + // Build the field string for the request $field_string = http_build_query($fields); + // Get the HTTP client with the basic authentication and timeout options set $httpClient = $this->getHttpClient()->withOptions([ 'auth_basic' => [$this->_config['username'], $this->_config['password']], 'timeout' => 60, @@ -530,7 +619,10 @@ class Server_Manager_Directadmin extends Server_Manager 'verify_peer' => false, ]); - $url = $protocol . $host . ':' . $this->_getPort() . '/CMD_' . $command . '?' . $field_string; + // Construct the URL for the request + $url = $protocol . $host . ':' . $this->getPort() . '/CMD_' . $command . '?' . $field_string; + + // Log the URL for debugging purposes $this->getLog()->debug($url); try { @@ -540,29 +632,34 @@ class Server_Manager_Directadmin extends Server_Manager 'body' => $fields, ]); } else { + // Otherwise, send a GET request $request = $httpClient->request('GET', $url); } + // Get the content of the response $data = $request->getContent(); - } catch (Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface| - Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface $error) { - $exception = new Server_Exception('HttpClientException: :error', [':error' => $error->getMessage()]); - $this->getLog()->err($exception); + } catch (TransportExceptionInterface|HttpExceptionInterface $error) { + // If there is an error while sending the request, throw an exception + $exception = new Server_Exception('HttpClientException: :error', [':error' => $error->getMessage()]); + $this->getLog()->err($exception); - throw $exception; - } + throw $exception; + } // Check if the response data contains HTML, as some endpoints return HTML if the request fails (such as auth requests) if (strlen(strstr($data, '')) > 0 || strlen(strstr($data, 'DirectAdmin Login')) > 0) { throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'DirectAdmin']); } + // Check if the response data contains an error message indicating that the request cannot be executed if (strlen(strstr($data, "The request you've made cannot be executed because it does not exist in your authority level")) > 0) { throw new Server_Exception('Server Manager DirectAdmin Error: "The request you have made cannot be executed because it does not exist in your authority level"'); } - $response = $this->_parseResponse($data); + // Parse the response data into an array + $response = $this->parseResponse($data); + // If the response contains an error, log the error and throw an exception if (isset($response['error']) && $response['error'] == 1) { $placeholders = [':action:' => $command, ':type:' => 'DirectAdmin']; $this->getLog()->err('Failed to ' . $command . ' on the DirectAdmin server: ' . $response['text'] . ': ' . $response['details']); @@ -570,11 +667,12 @@ class Server_Manager_Directadmin extends Server_Manager throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); } + // Return the parsed response data, or an empty array if the response is empty return empty($response) ? [] : $response; } /** - * This method is used to parse the response data from the DirectAdmin server. + * Parses the response data from the DirectAdmin server. * It first logs the raw response data for debugging purposes. * Then it replaces certain HTML entities in the data with their corresponding characters. * After that, it parses the data into an array using PHP's parse_str function. @@ -584,7 +682,7 @@ class Server_Manager_Directadmin extends Server_Manager * * @return array the parsed response data */ - private function _parseResponse(string $data): array + private function parseResponse(string $data): array { // Log the raw response data for debugging purposes $this->getLog()->debug('Raw Response: ' . $data); @@ -603,4 +701,38 @@ class Server_Manager_Directadmin extends Server_Manager // Return the parsed response data return $response; } + + /** + * Retrieves the list of IPs from the DirectAdmin server. + * + * @return array the list of IPs + * + * @throws Server_Exception if there is an error while sending the request to the server + */ + private function getIps(): array + { + $results = $this->request('API_SHOW_RESELLER_IPS'); + + return $results['list'] ?? []; + } + + /** + * Retrieves the information of an account from the DirectAdmin server. + * + * @param Server_Account $account the account for which the information is to be retrieved + * + * @return array the account information + * + * @throws Server_Exception if there is an error while sending the request to the server + */ + private function getAccountInfo(Server_Account $account): array + { + $fields = [ + 'action' => 'create', + 'add' => 'Submit', + 'user' => $account->getUsername(), + ]; + + return $this->request('API_SHOW_USER_CONFIG', $fields); + } } diff --git a/src/library/Server/Manager/Hestia.php b/src/library/Server/Manager/Hestia.php index 8afbb00c2..cc209a4b1 100644 --- a/src/library/Server/Manager/Hestia.php +++ b/src/library/Server/Manager/Hestia.php @@ -1,27 +1,15 @@ _config['port']) ? $this->_config['port'] : '8083'; - } - /** * Return server manager parameters. */ @@ -53,28 +41,314 @@ class Server_Manager_Hestia extends Server_Manager } /** - * Returns link to account management page. - * - * @return string + * Method is called just after object construct is complete. + * Add required parameters checks here. */ - public function getLoginUrl(Server_Account $account = null) + public function init() { - return 'https://' . $this->_config['host'] . ':' . $this->_getPort() . '/'; } /** * Returns link to reseller account management. - * - * @return string */ - public function getResellerLoginUrl(Server_Account $account = null) + public function getResellerLoginUrl(Server_Account $account = null): string { return $this->getLoginUrl(); } - private function _makeRequest($params) + /** + * Returns link to account management page. + */ + public function getLoginUrl(Server_Account $account = null): string { - $host = 'https://' . $this->_config['host'] . ':' . $this->_getPort() . '/api/'; + return 'https://' . $this->_config['host'] . ':' . $this->getPort() . '/'; + } + + public function getPort(): int|string + { + $port = $this->_config['port']; + + if (filter_var($port, FILTER_VALIDATE_INT) !== false && $port >= 0 && $port <= 65535) { + return $this->_config['port']; + } else { + return 8083; + } + } + + public function generateUsername(string $domain): string + { + $processedDomain = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $domain)); + $username = substr($processedDomain, 0, 7) . random_int(0, 9); + + // HestiaCP doesn't allow usernames to start with a number, so automatically append the letter 'a' to the start of a username that does. + // See: https://github.com/hestiacp/hestiacp/pull/4195 + if (is_numeric(substr($username, 0, 1))) { + $username = substr_replace($username, 'a', 0, 1); + } + + return $username; + } + + /** + * This method is called to check if configuration is correct + * and class can connect to server. + * + * @throws Server_Exception + */ + public function testConnection(): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-list-users', + 'arg1' => $this->_config['username'], + 'arg2' => $this->_config['password'], + ]; + + // Make request and check sys info + $result = $this->request($postVars); + if (intval($result) != 0) { + throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'HestiaCP']); + } + + return true; + } + + /** + * Methods retrieves information from server, assign's new values to + * cloned Server_Account object and returns it. + */ + public function synchronizeAccount(Server_Account $account): Server_Account + { + $this->getLog()->info('Synchronizing account with server ' . $account->getUsername()); + + // @example - retrieve username from server and set it to cloned object + // $new->setUsername('newusername'); + return clone $account; + } + + /** + * Create new account on server. + * + * @return true + * + * @throws Server_Exception + */ + public function createAccount(Server_Account $account): bool + { + $client = $account->getClient(); + + // Prepare POST query + $postVars = [ + 'cmd' => 'v-add-user', + 'arg1' => $account->getUsername(), + 'arg2' => $account->getPassword(), + 'arg3' => $client->getEmail(), + 'arg4' => $account->getPackage()->getName(), + 'arg5' => trim($client->getFullName()), + ]; + + // Make request and create user + $result1 = $this->request($postVars); + if (intval($result1) == 0) { + // Create Domain Prepare POST query + $postVars = [ + 'cmd' => 'v-add-domain', + 'arg1' => $account->getUsername(), + 'arg2' => $account->getDomain(), + ]; + $result2 = $this->request($postVars); + } else { + $placeholders = [':action:' => __trans('create user'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + if (intval($result2) !== 0) { + $postVars = [ + 'cmd' => 'v-delete-user', + 'arg1' => $account->getUsername(), + ]; + + $result3 = $this->request($postVars); + if (intval($result3) !== 0) { + $placeholders = [':action1:' => __trans('delete domain'), ':action2:' => __trans('create domain'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action1: on the :type: server after failed to :action2:, check the error logs for further details', $placeholders); + } + $placeholders = [':action:' => __trans('create domain'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Suspend account on server. + * + * @throws Server_Exception + */ + public function suspendAccount(Server_Account $account): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-suspend-user', + 'arg1' => $account->getUsername(), + 'arg2' => 'no', + ]; + + // Make request and suspend user + $result = $this->request($postVars); + + // Check for known errors + if (intval($result) !== 0 && intval($result) !== 6) { + $placeholders = [':action:' => __trans('suspend account'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Unsuspend account on server. + * + * @throws Server_Exception + */ + public function unsuspendAccount(Server_Account $account): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-unsuspend-user', + 'arg1' => $account->getUsername(), + 'arg2' => 'no', + ]; + + $result = $this->request($postVars); + if (intval($result) !== 0) { + $placeholders = [':action:' => __trans('unsuspend account'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Cancel account on server. + * + * @throws Server_Exception + */ + public function cancelAccount(Server_Account $account): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-delete-user', + 'arg1' => $account->getUsername(), + 'arg2' => 'no', + ]; + + // Make request and delete user + $result = $this->request($postVars); + if (intval($result) !== 0 && intval($result) !== 3) { + $placeholders = [':action:' => __trans('cancel account'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Change account package on server. + * + * @throws Server_Exception + */ + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-change-user-package', + 'arg1' => $account->getUsername(), + 'arg2' => $package->getName(), + 'arg3' => 'no', + ]; + + // Make request and change package + $result = $this->request($postVars); + if (intval($result) !== 0) { + $placeholders = [':action:' => __trans('change account package'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Change account username on server. + * + * @throws Server_Exception + */ + public function changeAccountUsername(Server_Account $account, $newUsername): never + { + throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('username changes')]); + } + + /** + * Change account domain on server. + * + * @throws Server_Exception + */ + public function changeAccountDomain(Server_Account $account, $newDomain): never + { + throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('changing the account domain')]); + } + + /** + * Change account password on server. + * + * @throws Server_Exception + */ + public function changeAccountPassword(Server_Account $account, string $newPassword): bool + { + // Prepare POST query + $postVars = [ + 'cmd' => 'v-change-user-password', + 'arg1' => $account->getUsername(), + 'arg2' => $newPassword, + ]; + + // Make request and change password + $result = $this->request($postVars); + if (intval($result) !== 0) { + $placeholders = [':action:' => __trans('change account password'), ':type:' => 'HestiaCP']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + return true; + } + + /** + * Change account IP on server. + * + * @throws Server_Exception + */ + public function changeAccountIp(Server_Account $account, string $newIp): never + { + throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('changing the account IP')]); + } + + /** + * @throws Server_Exception + */ + private function request($params): mixed + { + $host = 'https://' . $this->_config['host'] . ':' . $this->getPort() . '/api/'; + + // Set return code to yes + $params['returncode'] = 'yes'; // Server credentials if ($this->_config['accesshash'] != '' && $this->_config['username'] != '') { @@ -92,9 +366,11 @@ class Server_Manager_Hestia extends Server_Manager 'verify_host' => false, 'timeout' => 30, ]); + $response = $client->request('POST', $host, [ 'body' => $params, ]); + $result = $response->getContent(); if (str_contains($result, 'Error')) { @@ -105,295 +381,4 @@ class Server_Manager_Hestia extends Server_Manager return $result; } - - private function _getPackageName(Server_Package $package) - { - $name = $package->getName(); - - return $name; - } - - public function generateUsername($domainName) - { - $processedDomain = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $domainName)); - $username = substr($processedDomain, 0, 7) . random_int(0, 9); - - // HestiaCP doesn't allow usernames to start with a number, so automatically append the letter 'a' to the start of a username that does. - // See: https://github.com/hestiacp/hestiacp/pull/4195 - if (is_numeric(substr($username, 0, 1))) { - $username = substr_replace($username, 'a', 0, 1); - } - - return $username; - } - - /** - * This method is called to check if configuration is correct - * and class can connect to server. - * - * @return bool - */ - public function testConnection() - { - // Server credentials - $vst_command = 'v-list-users'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $this->_config['username'], - 'arg2' => $this->_config['password'], - ]; - - // Make request and check sys info - $result = $this->_makeRequest($postvars); - if (intval($result) == 0) { - return true; - } else { - throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'HestiaCP']); - } - - return true; - } - - /** - * Methods retrieves information from server, assign's new values to - * cloned Server_Account object and returns it. - * - * @return Server_Account - */ - public function synchronizeAccount(Server_Account $a) - { - $this->getLog()->info('Synchronizing account with server ' . $a->getUsername()); - $new = clone $a; - - // @example - retrieve username from server and set it to cloned object - // $new->setUsername('newusername'); - return $new; - } - - /** - * Create new account on server. - */ - public function createAccount(Server_Account $account) - { - $p = $account->getPackage(); - $packname = $this->_getPackageName($p); - $client = $account->getClient(); - // Server credentials - $vst_command = 'v-add-user'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $account->getUsername(), - 'arg2' => $account->getPassword(), - 'arg3' => $client->getEmail(), - 'arg4' => $packname, - 'arg5' => trim($client->getFullName()), - ]; - // Make request and create user - $result1 = $this->_makeRequest($postvars); - if (intval($result1) == 0) { - // Create Domain Prepare POST query - $postvars2 = [ - 'returncode' => 'yes', - 'cmd' => 'v-add-domain', - 'arg1' => $account->getUsername(), - 'arg2' => $account->getDomain(), - ]; - $result2 = $this->_makeRequest($postvars2); - } else { - $placeholders = [':action:' => __trans('create user'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - if (intval($result2) !== 0) { - $postvars3 = [ - 'returncode' => 'yes', - 'cmd' => 'v-delete-user', - 'arg1' => $account->getUsername(), - ]; - $result3 = $this->_makeRequest($postvars3); - if (intval($result3) !== 0) { - $placeholders = [':action1:' => __trans('delete domain'), ':action2:' => __trans('create domain'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action1: on the :type: server after failed to :action2:, check the error logs for further details', $placeholders); - } - $placeholders = [':action:' => __trans('create domain'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Suspend account on server. - */ - public function suspendAccount(Server_Account $a) - { - $user = $a->getUsername(); - // Prepare POST query - $postvars = [ - 'returncode' => 'yes', - 'cmd' => 'v-suspend-user', - 'arg1' => $a->getUsername(), - 'arg2' => 'no', - ]; - // Make request and suspend user - $result = $this->_makeRequest($postvars); - // Check if error 6 the account is suspended on server - if (intval($result) == 6) { - return true; - } - if (intval($result) !== 0) { - $placeholders = [':action:' => __trans('suspend account'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Unsuspend account on server. - */ - public function unsuspendAccount(Server_Account $a) - { - // Server credentials - $vst_command = 'v-unsuspend-user'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $a->getUsername(), - 'arg2' => 'no', - ]; - - $result = $this->_makeRequest($postvars); - if (intval($result) !== 0) { - $placeholders = [':action:' => __trans('unsuspend account'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Cancel account on server. - */ - public function cancelAccount(Server_Account $a) - { - // Server credentials - $vst_username = $this->_config['username']; - $vst_password = $this->_config['password']; - $vst_command = 'v-delete-user'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $a->getUsername(), - 'arg2' => 'no', - ]; - // Make request and delete user - $result = $this->_makeRequest($postvars); - if (intval($result) == '3') { - return true; - } elseif (intval($result) !== 0) { - $placeholders = [':action:' => __trans('cancel account'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Change account package on server. - */ - public function changeAccountPackage(Server_Account $a, Server_Package $p) - { - $package = $a->getPackage()->getName(); - - // Server credentials - $vst_username = $this->_config['username']; - $vst_password = $this->_config['password']; - $vst_command = 'v-change-user-package'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $a->getUsername(), - 'arg2' => $this->_getPackageName($p), - 'arg3' => 'no', - ]; - // Make request and change package - $result = $this->_makeRequest($postvars); - if (intval($result) !== 0) { - $placeholders = [':action:' => __trans('change account package'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Change account username on server. - */ - public function changeAccountUsername(Server_Account $a, $new): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('username changes')]); - } - - /** - * Change account domain on server. - */ - public function changeAccountDomain(Server_Account $a, $new): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('changing the account domain')]); - } - - /** - * Change account password on server. - */ - public function changeAccountPassword(Server_Account $a, $new) - { - // Server credentials - $vst_username = $this->_config['username']; - $vst_password = $this->_config['password']; - $vst_command = 'v-change-user-password'; - $vst_returncode = 'yes'; - // Prepare POST query - $postvars = [ - 'returncode' => $vst_returncode, - 'cmd' => $vst_command, - 'arg1' => $a->getUsername(), - 'arg2' => $new, - ]; - // Make request and change password - $result = $this->_makeRequest($postvars); - if (intval($result) !== 0) { - $placeholders = [':action:' => __trans('change account password'), ':type:' => 'HestiaCP']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return true; - } - - /** - * Change account IP on server. - */ - public function changeAccountIp(Server_Account $a, $new): never - { - throw new Server_Exception(':type: does not support :action:', [':type:' => 'HestiaCP', ':action:' => __trans('changing the account IP')]); - } } diff --git a/src/library/Server/Manager/Plesk.php b/src/library/Server/Manager/Plesk.php index 0d56726d3..f7ad85a23 100644 --- a/src/library/Server/Manager/Plesk.php +++ b/src/library/Server/Manager/Plesk.php @@ -1,31 +1,63 @@ _config['port'] = empty($this->_config['port']) ? 8443 : $this->_config['port']; - - $this->_client = new PleskX\Api\Client($this->_config['host'], $this->_config['port']); - $this->_client->setCredentials($this->_config['username'], $this->_config['password']); - } - - public static function getForm() + /** + * Returns an array with a single key-value pair, where the key is 'label' and the value is 'Plesk'. + * + * @return string[] an array with a single key-value pair + */ + public static function getForm(): array { return [ 'label' => 'Plesk', ]; } + /** + * Initializes the Plesk client with the host, port, username, and password from the configuration. + * If the port is not set in the configuration, it defaults to 8443. + */ + public function init(): void + { + $this->_config['port'] = empty($this->_config['port']) ? 8443 : $this->_config['port']; + $this->_client = new Client($this->_config['host'], $this->_config['port']); + $this->_client->setCredentials($this->_config['username'], $this->_config['password']); + } + + /** + * Returns the login URL for a reseller account. + * This method is a wrapper for the getLoginUrl method. + * + * @param Server_Account|null $account the account for which the login URL should be retrieved + * + * @return string the login URL for the reseller account + */ + public function getResellerLoginUrl(Server_Account $account = null): string + { + return $this->getLoginUrl(); + } + + /** + * Returns the login URL for a given account. + * If an account is provided, a session is created for the account and the session ID is appended to the URL. + * + * @param Server_Account|null $account the account for which the login URL should be retrieved + * + * @return string the login URL for the account + */ public function getLoginUrl(Server_Account $account = null): string { $protocol = $this->_config['secure'] ? 'https' : 'http'; @@ -38,12 +70,15 @@ class Server_Manager_Plesk extends Server_Manager return $url; } - public function getResellerLoginUrl(Server_Account $account = null) - { - return $this->getLoginUrl(); - } - - public function testConnection() + /** + * Tests the connection to the Plesk server by retrieving the server's statistics. + * If the server's uptime is less than 0, an exception is thrown. + * + * @return true if the connection to the Plesk server is successful + * + * @throws Server_Exception if the connection to the Plesk server fails + */ + public function testConnection(): bool { $stats = $this->_client->server()->getStatistics(); @@ -54,17 +89,35 @@ class Server_Manager_Plesk extends Server_Manager return true; } - public function synchronizeAccount(Server_Account $a): never + /** + * Throws an exception indicating that account synchronization is not supported. + * + * @param Server_Account $account the account to be synchronized + * + * @throws Server_Exception always throws an exception + */ + public function synchronizeAccount(Server_Account $account): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'Plesk', ':action:' => __trans('account synchronization')]); } - public function createAccount(Server_Account $account) + /** + * Creates an account on the Plesk server. + * If the account is a reseller account, an exclusive IP address is assigned to the account if available. + * A client is created for the account and a subscription is set for the client. + * + * @param Server_Account $account the account to be created + * + * @return true if the account is successfully created + * + * @throws Server_Exception if the client creation fails + */ + public function createAccount(Server_Account $account): bool { $this->getLog()->info('Creating account ' . $account->getUsername()); if ($account->getReseller()) { - $ips = $this->_getIps(); + $ips = $this->getIps(); foreach ($ips['exclusive'] as $key => $ip) { if (!$ip['empty']) { unset($ips['exclusive'][$key]); @@ -72,8 +125,8 @@ class Server_Manager_Plesk extends Server_Manager } /* - if (count($ips['exclusive']) == 0) { - // Disabled. Resellers can also use shared IP addresses. + if (count($ips['exclusive']) == 0) { + // Disabled. Resellers can also use shared IP addresses. // throw new Server_Exception('Out of free IP addresses'); } */ @@ -84,155 +137,258 @@ class Server_Manager_Plesk extends Server_Manager } } - $id = $this->_createClient($account); + $id = $this->createClient($account); $client = $account->getClient(); + if (!$id) { $placeholders = [':action:' => __trans('create account'), ':type"' => 'Plesk']; throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } else { - $client->setId((string) $id); } + + $client->setId((string) $id); + $this->setSubscription($account); // We need to improve the way we handle the IP address before we should enable this. /* - if ($a->getReseller()) { - $this->_setIp($a); - $this->_changeIpType($a); - $this->_addNs($a, $domainId); - } + if ($a->getReseller()) { + $this->_setIp($a); + $this->_changeIpType($a); + $this->_addNs($a, $domainId); + } */ return true; } - public function setSubscription(Server_Account $a) + /** + * Sets a subscription for a given account. + * + * @param Server_Account $account the account for which the subscription should be set + */ + public function setSubscription(Server_Account $account): void { - $this->getLog()->info('Setting subscription for account ' . $a->getUsername()); + $this->getLog()->info('Setting subscription for account ' . $account->getUsername()); - $this->_client->webspace()->request($this->_createSubscriptionProps($a, 'add')); + $this->_client->webspace()->request($this->createSubscriptionProps($account, 'add')); } // ?? - public function createServicePlan(Server_Account $a) + + /** + * Suspends a given account. + * The customer's status is set to 16, which is suspended. + * + * @param Server_Account $account the account to be suspended + * @param bool $suspend Whether the account should be suspended. Defaults to true. + * + * @return bool the result of the API request to suspend the account + */ + public function suspendAccount(Server_Account $account, bool $suspend = true): bool { - } - - public function updateSubscription(Server_Account $a) - { - $this->getLog()->info('Updating subscription for account ' . $a->getUsername()); - - $this->_client->webspace()->request($this->_createSubscriptionProps($a, 'set')); - } - - public function deleteSubscription(Server_Account $a) - { - $result = $this->_client->webspace()->delete('name', $a->getDomain()); - - return $result; - } - - public function suspendAccount(Server_Account $a, $suspend = true) - { - if ($a->getReseller()) { - $result = $this->_client->reseller()->setProperties('login', $a->getUsername(), ['status' => 16]); + if ($account->getReseller()) { + $result = $this->_client->reseller()->setProperties('login', $account->getUsername(), ['status' => 16]); } else { - $result = $this->_client->customer()->setProperties('login', $a->getUsername(), ['status' => 16]); + $result = $this->_client->customer()->setProperties('login', $account->getUsername(), ['status' => 16]); } return $result; } - public function unsuspendAccount(Server_Account $a) + /** + * Unsuspends a given account. + * Set the customer's status to 0, which is active. + * + * @param Server_Account $account the account to be unsuspended + * + * @return bool the result of the API request to unsuspend the account + */ + public function unsuspendAccount(Server_Account $account): bool { - if ($a->getReseller()) { - $result = $this->_client->reseller()->setProperties('login', $a->getUsername(), ['status' => 0]); + if ($account->getReseller()) { + $result = $this->_client->reseller()->setProperties('login', $account->getUsername(), ['status' => 0]); } else { - $result = $this->_client->customer()->setProperties('login', $a->getUsername(), ['status' => 0]); + $result = $this->_client->customer()->setProperties('login', $account->getUsername(), ['status' => 0]); } return $result; } - public function cancelAccount(Server_Account $a) + /** + * Cancels a given account. + * Delete the customer or reseller associated with the account. + * + * @param Server_Account $account the account to be cancelled + * + * @return bool the result of the API request to cancel the account + */ + public function cancelAccount(Server_Account $account): bool { - if ($a->getReseller()) { - $result = $this->_client->reseller()->delete('login', $a->getUsername()); + if ($account->getReseller()) { + $result = $this->_client->reseller()->delete('login', $account->getUsername()); } else { - $result = $this->_client->customer()->delete('login', $a->getUsername()); + $result = $this->_client->customer()->delete('login', $account->getUsername()); } return $result; } - public function changeAccountPackage(Server_Account $a, Server_Package $p) + /** + * Changes the package of a given account. + * The client's properties are modified and the subscription is updated. + * If the account is a reseller account, a nameserver (NS) record is added for the account. + * + * @param Server_Account $account the account for which the package should be changed + * @param Server_Package $package the new package + * + * @return true if the package is successfully changed + * + * @throws Server_Exception if the client modification fails + */ + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool { $domainId = null; - $id = $this->_modifyClient($a); - $client = $a->getClient(); + $id = $this->modifyClient($account); + $client = $account->getClient(); if (!$id) { throw new Server_Exception('Can\'t modify client'); } else { $client->setId($id); } - $a->setPackage($p); - $this->updateSubscription($a); + $account->setPackage($package); + $this->updateSubscription($account); - if ($a->getReseller()) { - $this->_addNs($a, $domainId); + if ($account->getReseller()) { + $this->addNs($account, $domainId); } return true; } - public function changeAccountPassword(Server_Account $a, $new) + /** + * Updates the subscription for a given account. + * Sends a request to the Plesk API to update the subscription for the account. + * + * @param Server_Account $account the account for which the subscription should be updated + */ + public function updateSubscription(Server_Account $account): void { - $this->getLog()->info('Changing password for account ' . $a->getUsername()); + $this->getLog()->info('Updating subscription for account ' . $account->getUsername()); - if ($a->getReseller()) { - $result = $this->_client->reseller()->setProperties('login', $a->getUsername(), ['passwd' => $new]); + $this->_client->webspace()->request($this->createSubscriptionProps($account, 'set')); + } + + /** + * Changes the password of a given account. + * + * @param Server_Account $account the account for which the password should be changed + * @param string $newPassword the new password + * + * @return bool the result of the API request to change the password + */ + public function changeAccountPassword(Server_Account $account, string $newPassword): bool + { + $this->getLog()->info('Changing password for account ' . $account->getUsername()); + + if ($account->getReseller()) { + $result = $this->_client->reseller()->setProperties('login', $account->getUsername(), ['passwd' => $newPassword]); } else { - $result = $this->_client->customer()->setProperties('login', $a->getUsername(), ['passwd' => $new]); + $result = $this->_client->customer()->setProperties('login', $account->getUsername(), ['passwd' => $newPassword]); } return $result; } - public function changeAccountUsername(Server_Account $a, $new): never + /** + * This is not implemented for Plesk. + * + * @param Server_Account $account the account for which the username should be changed + * @param string $newUsername the new username + * + * @throws Server_Exception always throws an exception + */ + public function changeAccountUsername(Server_Account $account, string $newUsername): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'Plesk', ':action:' => __trans('username changes')]); } - public function changeAccountDomain(Server_Account $a, $new) + /** + * Changes the domain of a given account. + * The domain of the account is updated and a request is sent to the Plesk API to update the domain of the account. + * + * @param Server_Account $account the account for which the domain should be changed + * @param string $newDomain the new domain + * + * @return bool the result of the API request to change the domain + */ + public function changeAccountDomain(Server_Account $account, string $newDomain): bool { - $this->getLog()->info('Updating domain for account ' . $a->getUsername()); + $this->getLog()->info('Updating domain for account ' . $account->getUsername()); - $a->setDomain($new); + $account->setDomain($newDomain); $params = [ 'set' => [ 'filter' => [ - 'owner-login' => $a->getUsername(), + 'owner-login' => $account->getUsername(), ], 'values' => [ 'gen_setup' => [ - 'name' => $new, + 'name' => $newDomain, ], ], ], ]; $this->_client->webspace()->request($params); + + return true; } - public function changeAccountIp(Server_Account $a, $new): never + /** + * This is not implemented for Plesk. + * + * @param Server_Account $account the account for which the IP should be changed + * @param string $newIp the new IP address + * + * @throws Server_Exception always throws an exception + */ + public function changeAccountIp(Server_Account $account, string $newIp): never { throw new Server_Exception(':type: does not support :action:', [':type:' => 'Plesk', ':action:' => __trans('changing the account IP')]); } - private function _getIps() + /** + * This is not implemented for Plesk. + * + * @param Server_Account $account the account for which the service plan should be created + */ + public function createServicePlan(Server_Account $account) + { + } + + /** + * Deletes a subscription for a given account. + * Sends a request to the Plesk API to delete the webspace associated with the account's domain. + * + * @param Server_Account $account the account for which the subscription should be deleted + * + * @return mixed the result of the API request to delete the webspace + */ + public function deleteSubscription(Server_Account $account): mixed + { + return $this->_client->webspace()->delete('name', $account->getDomain()); + } + + /** + * Retrieves the IP addresses from the Plesk server. + * Sends a request to the Plesk API to get the IP addresses and categorizes them into 'shared' and 'exclusive'. + * + * @return array an array containing 'shared' and 'exclusive' IP addresses + */ + private function getIps(): array { $response = $this->_client->ip()->get(); @@ -241,127 +397,115 @@ class Server_Manager_Plesk extends Server_Manager foreach ($response as $ip) { $ips[(string) $ip->type][] = [ 'ip' => (string) $ip->ipAddress, - 'empty' => empty($ip->default) ? true : false, + 'empty' => empty($ip->default), ]; } return $ips; } - private function _setIp(Server_Account $a, $new) + /** + * Sets the IP address for a given account. + * Sends a request to the Plesk API to add the IP address to the reseller's IP pool. + * + * @param Server_Account $account the account for which the IP should be set + * @param string $newIp the new IP address + */ + private function setIp(Server_Account $account, string $newIp): void { $params = [ 'reseller' => [ 'ippool-add-ip' => [ - 'reseller-id' => $a->getUsername(), + 'reseller-id' => $account->getUsername(), 'ip' => [ - 'ip-address' => $new, + 'ip-address' => $newIp, ], ], ], ]; - $response = $this->_client->request($params); + $this->_client->request($params); } - private function _addNs(Server_Account $a, $domainId) + /** + * Creates a client on the Plesk server. + * Sends a request to the Plesk API to create a customer or reseller based on the account type. + * The client's properties include the company name, full name, username, password, telephone number, fax number, email address, address, city, and state. + * + * @param Server_Account $account the account for which the client should be created + * + * @return bool returns true after the client has been created + */ + private function createClient(Server_Account $account): bool { - // Will be done in the future + $client = $account->getClient(); - return true; - } - - private function _getNs(Server_Account $a, $domainId) - { - $response = $this->_client->dns()->get('domain_id', $domainId); - - $ns = []; - - foreach ($response->dns->get_rec->result as $dns) { - if ($dns->data->type == 'NS') { - $ns[] = (string) $dns->id; - } - } - - return $ns; - } - - private function _removeDns($ns) - { - foreach ($ns as $key => $id) { - $params['dns']['del_rec']['filter']['id' . $key] = $id; - } - if (empty($params)) { - return true; - } - - $response = $this->_client->request($params); - - return true; - } - - private function _modifyClient(Server_Account $a) - { - $client = $a->getClient(); - - if ($a->getReseller()) { - $result = $this->_client->reseller()->setProperties('login', $a->getUsername(), $this->_createClientProps($a)); - } else { - $result = $this->_client->customer()->setProperties('login', $a->getUsername(), $this->_createClientProps($a)); - } - - return $result; - } - - private function _changeIpType(Server_Account $a) - { - $client = $a->getClient(); - $params = [ - 'reseller' => [ - 'ippool-set-ip' => [ - 'reseller-id' => $client->getId(), - 'filter' => [ - 'ip-address' => $a->getIp(), - ], - 'values' => [ - 'ip-type' => 'shared', - ], - ], - ], + $props = [ + 'cname' => $client->getCompany(), + 'pname' => $client->getFullname(), + 'login' => $account->getUsername(), + 'passwd' => $account->getPassword(), + 'phone' => $client->getTelephone(), + 'fax' => $client->getFax(), + 'email' => $client->getEmail(), + 'address' => $client->getAddress1(), + 'city' => $client->getCity(), + 'state' => $client->getState(), + 'description' => 'Created using FOSSBilling.', ]; - $response = $this->_client->reseller()->request($params); - - if (isset($response->reseller->{'ippool-set-ip'}->result->status) - && $response->reseller->{'ippool-set-ip'}->result->status == 'ok') { - return true; + if ($account->getReseller()) { + $this->_client->reseller()->create($props); } else { - return false; + $this->_client->customer()->create($props); } + + return true; } - private function _createSubscriptionProps(Server_Account $a, $action) + /** + * Creates an array of properties for a subscription. + * The properties include the domain name, owner login, hosting type, IP address, FTP login, FTP password, PHP, SSL, CGI, limits, and permissions. + * + * @param Server_Account $account the account for which the properties should be created + * @param string $action the action to be performed on the subscription + * + * @return array the array of subscription properties + */ + private function createSubscriptionProps(Server_Account $account, string $action): array { - $p = $a->getPackage(); + $package = $account->getPackage(); + + // check if bandwidth quota is set as an integer. If so, convert it to bytes + $bandwidth = 0; + if (is_numeric($package->getBandwidth())) { + $bandwidth = intval($package->getBandwidth()) * 1024 * 1024; + } + + // check if disk quota is set as an integer. If so, convert it to bytes + $quota = 0; + if (is_numeric($package->getQuota())) { + $quota = intval($package->getQuota()) * 1024 * 1024; + } return [ $action => [ 'gen_setup' => [ - 'name' => $a->getDomain(), - 'owner-login' => $a->getUsername(), + 'name' => $account->getDomain(), + 'owner-login' => $account->getUsername(), 'htype' => 'vrt_hst', - 'ip_address' => $a->getIp(), + 'ip_address' => $account->getIp(), ], 'hosting' => [ 'vrt_hst' => [ 'property' => [ [ 'name' => 'ftp_login', - 'value' => $a->getUsername(), + 'value' => $account->getUsername(), ], [ 'name' => 'ftp_password', - 'value' => $a->getPassword(), + 'value' => $account->getPassword(), ], [ 'name' => 'php', @@ -376,46 +520,46 @@ class Server_Manager_Plesk extends Server_Manager 'value' => 'true', ], ], - 'ip_address' => $a->getIp(), + 'ip_address' => $account->getIp(), ], ], 'limits' => [ 'limit' => [ [ 'name' => 'max_db', - 'value' => $p->getMaxSql() ?: 0, + 'value' => $package->getMaxSql() ?: 0, ], [ 'name' => 'max_maillists', - 'value' => $p->getMaxEmailLists() ?: 0, + 'value' => $package->getMaxEmailLists() ?: 0, ], [ 'name' => 'max_maillists', - 'value' => $p->getMaxEmailLists() ?: 0, + 'value' => $package->getMaxEmailLists() ?: 0, ], [ 'name' => 'max_box', - 'value' => $p->getMaxPop() ?: 0, + 'value' => $package->getMaxPop() ?: 0, ], [ 'name' => 'max_traffic', - 'value' => $p->getBandwidth() ? $p->getBandwidth() * 1024 * 1024 : 0, + 'value' => $bandwidth, ], [ 'name' => 'disk_space', - 'value' => $p->getQuota() ? $p->getQuota() * 1024 * 1024 : 0, + 'value' => $quota, ], [ 'name' => 'max_subdom', - 'value' => $p->getMaxSubdomains() ?: 0, + 'value' => $package->getMaxSubdomains() ?: 0, ], [ 'name' => 'max_subftp_users', - 'value' => $p->getMaxFtp() ?: 0, + 'value' => $package->getMaxFtp() ?: 0, ], [ 'name' => 'max_site', - 'value' => $p->getMaxDomains() ?: 0, + 'value' => $package->getMaxDomains() ?: 0, ], ], ], @@ -423,7 +567,7 @@ class Server_Manager_Plesk extends Server_Manager 'permission' => [ [ 'name' => 'manage_subdomains', - 'value' => $p->getMaxSubdomains() ? 'true' : 'false', + 'value' => $package->getMaxSubdomains() ? 'true' : 'false', ], [ 'name' => 'manage_dns', @@ -431,19 +575,19 @@ class Server_Manager_Plesk extends Server_Manager ], [ 'name' => 'manage_crontab', - 'value' => $p->getHasCron() ? 'true' : 'false', + 'value' => $package->getHasCron() ? 'true' : 'false', ], [ 'name' => 'manage_anonftp', - 'value' => $p->getHasAnonymousFtp() ? 'true' : 'false', + 'value' => $package->getHasAnonymousFtp() ? 'true' : 'false', ], [ 'name' => 'manage_sh_access', - 'value' => $p->getHasShell() ? 'true' : 'false', + 'value' => $package->getHasShell() ? 'true' : 'false', ], [ 'name' => 'manage_maillists', - 'value' => $p->getMaxEmailLists() ? 'true' : 'false', + 'value' => $package->getMaxEmailLists() ? 'true' : 'false', ], [ 'name' => 'create_domains', @@ -455,11 +599,11 @@ class Server_Manager_Plesk extends Server_Manager ], [ 'name' => 'manage_quota', - 'value' => $a->getReseller() ? 'true' : 'false', + 'value' => $account->getReseller() ? 'true' : 'false', ], [ 'name' => 'manage_not_chroot_shell', - 'value' => $p->getHasShell() ? 'true' : 'false', + 'value' => $package->getHasShell() ? 'true' : 'false', ], [ 'name' => 'manage_domain_aliases', @@ -467,11 +611,11 @@ class Server_Manager_Plesk extends Server_Manager ], [ 'name' => 'manage_subftp', - 'value' => $p->getMaxFtp() ? 'true' : 'false', + 'value' => $package->getMaxFtp() ? 'true' : 'false', ], [ 'name' => 'manage_spamfilter', - 'value' => $p->getHasSpamFilter() ? 'true' : 'false', + 'value' => $package->getHasSpamFilter() ? 'true' : 'false', ], ], ], @@ -480,56 +624,154 @@ class Server_Manager_Plesk extends Server_Manager } /** - * Creates a new client account. + * Modifies the properties of a client account on the Plesk server. * - * @return int client's Plesk id + * @param Server_Account $account the account for which the properties should be modified * - * @throws Server_Exception + * @return mixed the result of the API request to modify the client's properties */ - private function _createClient(Server_Account $a) + private function modifyClient(Server_Account $account): mixed { - $client = $a->getClient(); + if ($account->getReseller()) { + $result = $this->_client->reseller()->setProperties('login', $account->getUsername(), $this->createClientProps($account)); + } else { + $result = $this->_client->customer()->setProperties('login', $account->getUsername(), $this->createClientProps($account)); + } - $props = [ + return $result; + } + + /** + * Creates an array of properties for a client account. + * The properties include the client's company name, full name, username, password, telephone number, fax number, email address, address, city, and state. + * + * @param Server_Account $account the account for which the properties should be created + * + * @return array the array of client properties + */ + private function createClientProps(Server_Account $account): array + { + $client = $account->getClient(); + + return [ 'cname' => $client->getCompany(), 'pname' => $client->getFullname(), - 'login' => $a->getUsername(), - 'passwd' => $a->getPassword(), + 'login' => $account->getUsername(), + 'passwd' => $account->getPassword(), 'phone' => $client->getTelephone(), 'fax' => $client->getFax(), 'email' => $client->getEmail(), 'address' => $client->getAddress1(), 'city' => $client->getCity(), 'state' => $client->getState(), - 'description' => 'Created using FOSSBilling.', ]; + } - if ($a->getReseller()) { - $result = $this->_client->reseller()->create($props); - } else { - $result = $this->_client->customer()->create($props); - } - + /** + * Adds a nameserver (NS) record for a given account and domain ID. + * This method is not yet implemented and currently always returns true. + * + * @param Server_Account $account the account for which the NS record should be added + * @param string $domainId the ID of the domain for which the NS record should be added + * + * @return bool always returns true + */ + private function addNs(Server_Account $account, string $domainId): bool + { + // Will be done in the future return true; } - private function _createClientProps(Server_Account $a) + /** + * Retrieves the nameserver (NS) records for a given account and domain ID. + * Sends a request to the Plesk API to get the DNS records for the domain. + * Then, iterates over the DNS records and adds the IDs of the NS records to an array. + * + * @param Server_Account $account the account for which the NS records should be retrieved + * @param string $domainId the ID of the domain for which the NS records should be retrieved + * + * @return array the array of NS record IDs + */ + private function getNs(Server_Account $account, string $domainId) { - $client = $a->getClient(); + $response = $this->_client->dns()->get('domain_id', $domainId); - $props = [ - 'cname' => $client->getCompany(), - 'pname' => $client->getFullname(), - 'login' => $a->getUsername(), - 'passwd' => $a->getPassword(), - 'phone' => $client->getTelephone(), - 'fax' => $client->getFax(), - 'email' => $client->getEmail(), - 'address' => $client->getAddress1(), - 'city' => $client->getCity(), - 'state' => $client->getState(), + $ns = []; + + foreach ($response->dns->get_rec->result as $dns) { + if ($dns->data->type == 'NS') { + $ns[] = (string) $dns->id; + } + } + + return $ns; + } + + /** + * Removes DNS records from the Plesk server. + * Sends a request to the Plesk API to remove DNS records. + * The DNS records to be removed are identified by their IDs. + * + * @param array $ns an array of DNS record IDs to be removed + * + * @return bool returns true after the DNS records have been removed + * + * @throws Exception + */ + private function removeDns(array $ns): bool + { + // Iterate over each DNS record ID + foreach ($ns as $key => $id) { + // Prepare the parameters for the API request + $params['dns']['del_rec']['filter']['id' . $key] = $id; + } + + // If there are no DNS records to remove, return true + if (empty($params)) { + return true; + } + + // Send the request to the Plesk API to remove the DNS records + $response = $this->_client->request($params); + + // Return true after the DNS records have been removed + return true; + } + + /** + * Changes the IP type of a given account to 'shared'. + * Sends a request to the Plesk API to change the IP type of the given account to 'shared'. + * The account is identified by its reseller ID and IP address. + * + * @param Server_Account $account the account for which the IP type should be changed + * + * @return bool returns true if the IP type was successfully changed to 'shared', false otherwise + */ + private function changeIpType(Server_Account $account): bool + { + // Get the client associated with the account + $client = $account->getClient(); + + // Prepare the parameters for the API request + $params = [ + 'reseller' => [ + 'ippool-set-ip' => [ + 'reseller-id' => $client->getId(), + 'filter' => [ + 'ip-address' => $account->getIp(), + ], + 'values' => [ + 'ip-type' => 'shared', + ], + ], + ], ]; - return $props; + // Send the request to the Plesk API + $response = $this->_client->reseller()->request($params); + + // Check if the IP type was successfully changed to 'shared' + return isset($response->reseller->{'ippool-set-ip'}->result->status) + && $response->reseller->{'ippool-set-ip'}->result->status == 'ok'; } } diff --git a/src/library/Server/Manager/Whm.php b/src/library/Server/Manager/Whm.php index 9be7da8fd..01cbc279c 100644 --- a/src/library/Server/Manager/Whm.php +++ b/src/library/Server/Manager/Whm.php @@ -6,9 +6,10 @@ * SPDX-License-Identifier: Apache-2.0. * * @copyright FOSSBilling (https://www.fossbilling.org) - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ +use Random\RandomException; use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface; /** @@ -18,39 +19,12 @@ use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface; */ class Server_Manager_Whm extends Server_Manager { - public function init() - { - if (empty($this->_config['host'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'hostname'], 2001); - } - - if (empty($this->_config['username'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'username'], 2001); - } - - if (empty($this->_config['password']) && empty($this->_config['accesshash'])) { - throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'authentication credentials'], 2001); - } - - // If port not set, use WHM default. - $this->_config['port'] = empty($this->_config['port']) ? '2087' : $this->_config['port']; - } - - public function getLoginUrl(Server_Account $account = null) - { - $host = $this->_config['host']; - - return 'http://' . $host . '/cpanel'; - } - - public function getResellerLoginUrl(Server_Account $account = null) - { - $host = $this->_config['host']; - - return 'http://' . $host . '/whm'; - } - - public static function getForm() + /** + * Returns the form configuration for the WHM (cPanel) server manager. + * + * @return array the form configuration as an associative array + */ + public static function getForm(): array { return [ 'label' => 'WHM (cPanel)', @@ -77,17 +51,86 @@ class Server_Manager_Whm extends Server_Manager ]; } - public function testConnection() + /** + * Initializes the WHM server manager. + * Checks if the necessary configuration options are set and throws an exception if any are missing. + * + * @throws Server_Exception if any necessary configuration options are missing + */ + public function init(): void { - $json = $this->_request('version'); + if (empty($this->_config['host'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'hostname'], 2001); + } + + if (empty($this->_config['username'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'username'], 2001); + } + + if (empty($this->_config['password']) && empty($this->_config['accesshash'])) { + throw new Server_Exception('The ":server_manager" server manager is not fully configured. Please configure the :missing', [':server_manager' => 'cPanel WHM', ':missing' => 'authentication credentials'], 2001); + } + + // If port not set, use WHM default. + $this->_config['port'] = empty($this->_config['port']) ? '2087' : $this->_config['port']; + } + + /** + * Returns the login URL for a cPanel account. + * + * @param Server_Account|null $account The account for which to get the login URL. This parameter is currently not used. + * + * @return string the login URL + */ + public function getLoginUrl(Server_Account $account = null): string + { + $host = $this->_config['host']; + + return 'http://' . $host . '/cpanel'; + } + + /** + * Returns the login URL for a WHM reseller account. + * + * @param Server_Account|null $account The account for which to get the login URL. This parameter is currently not used. + * + * @return string the login URL + */ + public function getResellerLoginUrl(Server_Account $account = null): string + { + $host = $this->_config['host']; + + return 'http://' . $host . '/whm'; + } + + /** + * Tests the connection to the WHM server. + * Sends a request to the WHM server to get its version. + * + * @return true if the connection was successful + * + * @throws Server_Exception if an error occurs during the request + */ + public function testConnection(): bool + { + $this->request('version'); return true; } - // https://docs.cpanel.net/knowledge-base/accounts/reserved-invalid-and-misconfigured-username/ - public function generateUsername($domainName) + /** + * Generates a username for a new account on the WHM server. + * The username is generated based on the domain name, with some modifications to comply with WHM's username restrictions. + * + * @param string $domain the domain name for which to generate a username + * + * @return string the generated username + * + * @throws RandomException if an error occurs during the generation of a random number + */ + public function generateUsername(string $domain): string { - $processedDomain = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $domainName)); + $processedDomain = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $domain)); $username = substr($processedDomain, 0, 7) . random_int(0, 9); // WHM doesn't allow usernames to start with "test", so replace it with a random string if it does (test3456 would then become something like a62f93456). @@ -103,24 +146,35 @@ class Server_Manager_Whm extends Server_Manager return $username; } - public function synchronizeAccount(Server_Account $a) + /** + * Synchronizes an account with the WHM server. + * Sends a request to the WHM server to get the account's details and updates the Server_Account object accordingly. + * + * @param Server_Account $account the account to be synchronized + * + * @return Server_Account the updated account + * + * @throws Server_Exception if an error occurs during the request, or if the account does not exist on the WHM server + */ + public function synchronizeAccount(Server_Account $account): Server_Account { - $this->getLog()->info(sprintf('Synchronizing account %s %s with server', $a->getDomain(), $a->getUsername())); + $this->getLog()->info(sprintf('Synchronizing account %s %s with server', $account->getDomain(), $account->getUsername())); $action = 'accountsummary'; - $var_hash = [ - 'user' => $a->getUsername(), + $varHash = [ + 'user' => $account->getUsername(), ]; - $result = $this->_request($action, $var_hash); + + $result = $this->request($action, $varHash); if (!isset($result->acct[0])) { error_log('Could not synchronize account with cPanel server. Account does not exist.'); - return $a; + return $account; } $acc = $result->acct[0]; - $new = clone $a; + $new = clone $account; $new->setSuspended($acc->suspended); $new->setDomain($acc->domain); $new->setUsername($acc->user); @@ -129,122 +183,205 @@ class Server_Manager_Whm extends Server_Manager return $new; } - public function createAccount(Server_Account $account) + /** + * Creates a new account on the WHM server. + * Sends a request to the WHM server to create a new account with the details provided in the Server_Account object. + * If the account is a reseller account, it also sets up the reseller and assigns the appropriate ACL list. + * + * @param Server_Account $account The account to be created. This object should contain all the necessary details for the new account. + * + * @return bool returns true if the account was successfully created, false otherwise + * + * @throws Server_Exception if an error occurs during the request, or if the response from the WHM server indicates an error + */ + public function createAccount(Server_Account $account): bool { + // Log the account creation $this->getLog()->info('Creating account ' . $account->getUsername()); + // Get the client and package associated with the account $client = $account->getClient(); $package = $account->getPackage(); - $this->_checkPackageExists($package, true); + // Check if the package exists on the WHM server, create it if not + $this->checkPackageExists($package, true); + // Prepare the parameters for the API request $action = 'createacct'; - $var_hash = [ + $varHash = [ 'username' => $account->getUsername(), 'domain' => $account->getDomain(), 'password' => $account->getPassword(), 'contactemail' => $client->getEmail(), - 'plan' => $this->_getPackageName($package), + 'plan' => $this->getPackageName($package), 'useregns' => 0, ]; + // If the account is a reseller account, add the 'reseller' parameter if ($account->getReseller()) { - $var_hash['reseller'] = 1; + $varHash['reseller'] = 1; } - $json = $this->_request($action, $var_hash); + // Send the request to the WHM API + $json = $this->request($action, $varHash); $result = ($json->result[0]->status == 1); - // if this account is reseller account set ACL list + // If the account is a reseller account and was successfully created, set up the reseller and assign the ACL list if ($result && $account->getReseller()) { $params = [ 'user' => $account->getUsername(), 'makeowner' => 0, ]; - $this->_request('setupreseller', $params); + $this->request('setupreseller', $params); $params = [ 'reseller' => $account->getUsername(), 'acllist' => $package->getAcllist(), ]; - $this->_request('setacls', $params); + $this->request('setacls', $params); } + // Return the result of the account creation return $result; } - public function suspendAccount(Server_Account $a) + /** + * Suspends an account on the WHM server. + * + * @param Server_Account $account the account to be suspended + * + * @return bool returns true if the account was successfully suspended + * + * @throws Server_Exception if an error occurs during the request + */ + public function suspendAccount(Server_Account $account): bool { - $this->getLog()->info('Suspending account ' . $a->getUsername()); + // Log the suspension + $this->getLog()->info('Suspending account ' . $account->getUsername()); + // Define the action and parameters for the API request $action = 'suspendacct'; - $var_hash = [ - 'user' => $a->getUsername(), - 'reason' => $a->getNote(), + $varHash = [ + 'user' => $account->getUsername(), + 'reason' => $account->getNote(), ]; - $this->_request($action, $var_hash); + // Send the request to the WHM API + $this->request($action, $varHash); return true; } - public function unsuspendAccount(Server_Account $a) + /** + * Unsuspends an account on the WHM server. + * + * @param Server_Account $account the account to be unsuspended + * + * @return bool returns true if the account was successfully unsuspended + * + * @throws Server_Exception if an error occurs during the request + */ + public function unsuspendAccount(Server_Account $account): bool { - $this->getLog()->info('Activating account ' . $a->getUsername()); + // Log the unsuspension + $this->getLog()->info('Activating account ' . $account->getUsername()); + // Define the action and parameters for the API request $action = 'unsuspendacct'; - $var_hash = [ - 'user' => $a->getUsername(), + $varHash = [ + 'user' => $account->getUsername(), ]; - $this->_request($action, $var_hash); + // Send the request to the WHM API + $this->request($action, $varHash); return true; } - public function cancelAccount(Server_Account $a) + /** + * Cancels an account on the WHM server. + * + * @param Server_Account $account the account to be cancelled + * + * @return bool returns true if the account was successfully cancelled + * + * @throws Server_Exception if an error occurs during the request + */ + public function cancelAccount(Server_Account $account): bool { - $this->getLog()->info('Canceling account ' . $a->getUsername()); + // Log the cancellation + $this->getLog()->info('Canceling account ' . $account->getUsername()); + // Define the action and parameters for the API request $action = 'removeacct'; - $var_hash = [ - 'user' => $a->getUsername(), + $varHash = [ + 'user' => $account->getUsername(), 'keepdns' => 0, ]; - $this->_request($action, $var_hash); + // Send the request to the WHM API + $this->request($action, $varHash); return true; } - public function changeAccountPackage(Server_Account $a, Server_Package $p) + /** + * Changes the package of an account on the WHM server. + * + * @param Server_Account $account the account for which to change the package + * @param Server_Package $package the new package + * + * @return bool returns true if the package was successfully changed + * + * @throws Server_Exception if an error occurs during the request + */ + public function changeAccountPackage(Server_Account $account, Server_Package $package): bool { - $this->getLog()->info('Changing account ' . $a->getUsername() . ' package'); - $this->_checkPackageExists($p, true); + // Log the package change + $this->getLog()->info('Changing account ' . $account->getUsername() . ' package'); - $var_hash = [ - 'user' => $a->getUsername(), - 'pkg' => $this->_getPackageName($p), + // Check if the package exists on the WHM server, create it if not + $this->checkPackageExists($package, true); + + // Define the action and parameters for the API request + $varHash = [ + 'user' => $account->getUsername(), + 'pkg' => $this->getPackageName($package), ]; - $this->_request('changepackage', $var_hash); + // Send the request to the WHM API + $this->request('changepackage', $varHash); return true; } - public function changeAccountPassword(Server_Account $a, $new) + /** + * Changes the password of an account on the WHM server. + * + * @param Server_Account $account the account for which to change the password + * @param string $newPassword the new password + * + * @return bool returns true if the password was successfully changed + * + * @throws Server_Exception if an error occurs during the request + */ + public function changeAccountPassword(Server_Account $account, string $newPassword): bool { - $this->getLog()->info('Changing account ' . $a->getUsername() . ' password'); + // Log the password change + $this->getLog()->info('Changing account ' . $account->getUsername() . ' password'); + // Define the action and parameters for the API request $action = 'passwd'; - - $var_hash = [ - 'user' => $a->getUsername(), - 'pass' => $new, + $varHash = [ + 'user' => $account->getUsername(), + 'pass' => $newPassword, 'db_pass_update' => true, ]; - $result = $this->_request($action, $var_hash); + // Send the request to the WHM API + $result = $this->request($action, $varHash); + + // If the password change failed, throw an exception if (isset($result->passwd[0]) && $result->passwd[0]->status == 0) { throw new Server_Exception($result->passwd[0]->statusmsg); } @@ -252,64 +389,245 @@ class Server_Manager_Whm extends Server_Manager return true; } - public function changeAccountUsername(Server_Account $a, $new) + /** + * Changes the username of an account on the WHM server. + * + * @param Server_Account $account the account for which to change the username + * @param string $newUsername the new username + * + * @return bool returns true if the username was successfully changed + * + * @throws Server_Exception if an error occurs during the request + */ + public function changeAccountUsername(Server_Account $account, string $newUsername): bool { - $this->getLog()->info('Changing account ' . $a->getUsername() . ' username'); + // Log the username change + $this->getLog()->info('Changing account ' . $account->getUsername() . ' username'); + // Define the action and parameters for the API request $action = 'modifyacct'; - $var_hash = [ - 'user' => $a->getUsername(), - 'newuser' => $new, + $varHash = [ + 'user' => $account->getUsername(), + 'newuser' => $newUsername, ]; - $this->_request($action, $var_hash); - - return true; - } - - public function changeAccountDomain(Server_Account $a, $new) - { - $this->getLog()->info('Changing account ' . $a->getUsername() . ' domain'); - - $action = 'modifyacct'; - $var_hash = [ - 'user' => $a->getUsername(), - 'domain' => $new, - ]; - - $this->_request($action, $var_hash); - - return true; - } - - public function changeAccountIp(Server_Account $a, $new) - { - $this->getLog()->info('Changing account ' . $a->getUsername() . ' ip'); - - $action = 'setsiteip'; - $var_hash = [ - 'domain' => $a->getDomain(), - 'ip' => $new, - ]; - - $this->_request($action, $var_hash); + // Send the request to the WHM API + $this->request($action, $varHash); return true; } /** - * Check if Package exists. + * Changes the domain of an account on the WHM server. * - * @return bool + * @param Server_Account $account the account for which to change the domain + * @param string $newDomain the new domain + * + * @return bool returns true if the domain was successfully changed + * + * @throws Server_Exception if an error occurs during the request */ - private function _checkPackageExists(Server_Package $package, $create = false) + public function changeAccountDomain(Server_Account $account, string $newDomain): bool { - $var_hash = []; - $name = $this->_getPackageName($package); + // Log the domain change + $this->getLog()->info('Changing account ' . $account->getUsername() . ' domain'); - $json = $this->_request('listpkgs'); + // Define the action and parameters for the API request + $action = 'modifyacct'; + $varHash = [ + 'user' => $account->getUsername(), + 'domain' => $newDomain, + ]; + + // Send the request to the WHM API + $this->request($action, $varHash); + + return true; + } + + /** + * Changes the IP of an account on the WHM server. + * + * @param Server_Account $account the account for which to change the IP + * @param string $newIp the new IP + * + * @return bool returns true if the IP was successfully changed + * + * @throws Server_Exception if an error occurs during the request + */ + public function changeAccountIp(Server_Account $account, string $newIp): bool + { + // Log the IP change + $this->getLog()->info('Changing account ' . $account->getUsername() . ' ip'); + + // Define the action and parameters for the API request + $action = 'setsiteip'; + $varHash = [ + 'domain' => $account->getDomain(), + 'ip' => $newIp, + ]; + + // Send the request to the WHM API + $this->request($action, $varHash); + + return true; + } + + /** + * Retrieves the packages from the WHM server. + * + * @return array an array of packages, each represented as an associative array of package details + * + * @throws Server_Exception if an error occurs during the request + */ + public function getPackages(): array + { + // Send a request to the WHM server to list the packages + $pkgs = $this->request('listpkgs'); + $return = []; + + // Iterate over the packages and add their details to the return array + foreach ($pkgs->package as $pkg) { + $return[] = [ + 'title' => $pkg->name, + 'name' => $pkg->name, + 'feature_list' => $pkg->FEATURELIST, + 'theme' => $pkg->CPMOD, + 'quota' => $pkg->QUOTA, + 'bandwidth' => $pkg->BWLIMIT, + 'max_ftp' => $pkg->MAXFTP, + 'max_sql' => $pkg->MAXSQL, + 'max_emails' => $pkg->MAXLST, + 'max_sub' => $pkg->MAXSUB, + 'max_pop' => $pkg->MAXPOP, + 'max_park' => $pkg->MAXPARK, + 'max_addon' => $pkg->MAXADDON, + 'has_shell' => $pkg->HASSHELL == 'n' ? 0 : 1, + 'has_ip' => $pkg->IP == 'n' ? 0 : 1, + 'has_cgi' => $pkg->CGI == 'n' ? 0 : 1, + 'has_frontpage' => $pkg->FRONTPAGE == 'n' ? 0 : 1, + 'free_registration' => 0, + 'free_transfer' => 0, + 'free_renewal' => 0, + ]; + } + + return $return; + } + + /** + * Sends a request to the WHM server and returns the response. + * This method sends a request to the WHM server using the provided action and parameters. + * It handles the creation of the HTTP client, the construction of the request URL and headers, + * and the sending of the request. It also handles any errors that may occur during the request, + * logging them and throwing a Server_Exception if necessary. + * + * @param string $action the action to be performed on the WHM server + * @param array $params the parameters to be sent with the request + * + * @return mixed the response from the WHM server, decoded from JSON into a PHP variable + * + * @throws Server_Exception if an error occurs during the request, or if the response from the WHM server indicates an error + */ + private function request(string $action, array $params = []): mixed + { + // Create the HTTP client with the necessary options + $client = $this->getHttpClient()->withOptions([ + 'verify_peer' => false, + 'verify_host' => false, + 'timeout' => 90, // Account creation can timeout if set too low - see #1086. + ]); + + // Construct the request URL + $url = ($this->_config['secure'] ? 'https' : 'http') . '://' . $this->_config['host'] . ':' . $this->_config['port'] . '/json-api/' . $action; + + // Construct the authorization header + $username = $this->_config['username']; + $accessHash = $this->_config['accessHash']; + $password = $this->_config['password']; + $authHeader = (!empty($accessHash)) ? 'WHM ' . $username . ':' . $accessHash + : 'Basic ' . $username . ':' . $password; + + // Log the request + $this->getLog()->debug(sprintf('Requesting WHM server action "%s" with params "%s" ', $action, print_r($params, true))); + + // Send the request and handle any errors + try { + $response = $client->request('POST', $url, [ + 'headers' => ['Authorization' => $authHeader], + 'body' => $params, + ]); + } catch (HttpExceptionInterface $error) { + $e = new Server_Exception('HttpClientException: :error', [':error' => $error->getMessage()]); + $this->getLog()->err($e); + + throw $e; + } + + // Decode the response from JSON into a PHP variable + $body = $response->getContent(); + $json = json_decode($body); + + // Check the response for errors and throw a Server_Exception if any are found + if (!is_object($json)) { + $msg = sprintf('Function call "%s" response is invalid, body: %s', $action, $body); + $this->getLog()->crit($msg); + + $placeholders = [':action:' => $action, ':type:' => 'cPanel']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + if (isset($json->cpanelresult->error)) { + $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->cpanelresult->error)); + $placeholders = ['action' => $action, 'type' => 'cPanel']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + if (isset($json->data->result) && $json->data->result == '0') { + $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->data->reason)); + $placeholders = [':action:' => $action, ':type:' => 'cPanel']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + if (isset($json->result) && is_array($json->result) && $json->result[0]->status == 0) { + $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->result[0]->statusmsg)); + $placeholders = [':action:' => $action, ':type:' => 'cPanel']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + if (isset($json->status) && $json->status != '1') { + $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->statusmsg)); + $placeholders = [':action:' => $action, ':type:' => 'cPanel']; + + throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); + } + + // Return the response + return $json; + } + + /** + * Checks if a package exists on the WHM server. + * + * @param Server_Package $package the package to check + * @param bool $create whether to create the package if it does not exist + * + * @throws Server_Exception if an error occurs during the request + */ + private function checkPackageExists(Server_Package $package, bool $create = false): void + { + // Get the name of the package + $name = $this->getPackageName($package); + + // Send a request to the WHM server to list the packages + $json = $this->request('listpkgs'); $packages = $json->package; + // Check if the package exists $exists = false; foreach ($packages as $p) { if ($p->name == $name) { @@ -319,167 +637,76 @@ class Server_Manager_Whm extends Server_Manager } } - if (!$create) { - return $exists; + // If the package does not exist and the $create parameter is true, create the package + if (!$exists && $create) { + $varHash = [ + 'name' => $name, + 'quota' => $package->getQuota(), + 'bwlimit' => $package->getBandwidth(), + 'maxsub' => $package->getMaxSubdomains(), + 'maxpark' => $package->getMaxParkedDomains(), + 'maxaddon' => $package->getMaxDomains(), + 'maxftp' => $package->getMaxFtp(), + 'maxsql' => $package->getMaxSql(), + 'maxpop' => $package->getMaxPop(), + 'cgi' => $package->getCustomValue('cgi'), + 'cpmod' => $package->getCustomValue('cpmod'), + 'maxlst' => $package->getCustomValue('maxlst'), + 'hasshell' => $package->getCustomValue('hasshell'), + ]; + + // Send a request to the WHM server to add the package + $this->request('addpkg', $varHash); } - - if (!$exists) { - $var_hash['name'] = $name; - $var_hash['quota'] = $package->getQuota(); - $var_hash['bwlimit'] = $package->getBandwidth(); - $var_hash['maxsub'] = $package->getMaxSubdomains(); - $var_hash['maxpark'] = $package->getMaxParkedDomains(); - $var_hash['maxaddon'] = $package->getMaxDomains(); - $var_hash['maxftp'] = $package->getMaxFtp(); - $var_hash['maxsql'] = $package->getMaxSql(); - $var_hash['maxpop'] = $package->getMaxPop(); - - $var_hash['cgi'] = $package->getCustomValue('cgi'); - $var_hash['cpmod'] = $package->getCustomValue('cpmod'); - $var_hash['maxlst'] = $package->getCustomValue('maxlst'); - $var_hash['hasshell'] = $package->getCustomValue('hasshell'); - - $this->_request('addpkg', $var_hash); - } - - return $exists; - } - - private function _getPackageName(Server_Package $package) - { - $name = $package->getName(); - $name = $this->_config['username'] . '_' . $name; - - return $name; - } - - private function modifyAccountPackage(Server_Account $a, Server_Package $p) - { - $this->getLog()->info('Midifying account ' . $a->getUsername()); - - $package = $p; - $action = 'modifyacct'; - - $var_hash = [ - 'user' => $a->getUsername(), - 'domain' => $a->getDomain(), - 'HASCGI' => $package->getHasCgi(), - 'CPTHEME' => $package->getTheme(), - 'LANG' => $package->getLanguage(), - 'MAXPOP' => $package->getMaxPop(), - 'MAXFTP' => $package->getMaxFtp(), - 'MAXLST' => $package->getMaxEmailLists(), - 'MAXSUB' => $package->getMaxSubdomains(), - 'MAXPARK' => $package->getMaxParkedDomains(), - 'MAXADDON' => $package->getMaxAddons(), - 'MAXSQL' => $package->getMaxSql(), - 'shell' => $package->getHasShell(), - ]; - - $this->_request($action, $var_hash); - - return true; - } - - public function getPkgs() - { - $pkgs = $this->_request('listpkgs'); - - $return = []; - $i = 0; - foreach ($pkgs->package as $pkg) { - $return[$i]['title'] = $pkg->name; - $return[$i]['name'] = $pkg->name; - $return[$i]['feature_list'] = $pkg->FEATURELIST; - $return[$i]['theme'] = $pkg->CPMOD; - $return[$i]['quota'] = $pkg->QUOTA; - $return[$i]['bandwidth'] = $pkg->BWLIMIT; - $return[$i]['max_ftp'] = $pkg->MAXFTP; - $return[$i]['max_sql'] = $pkg->MAXSQL; - $return[$i]['max_emails'] = $pkg->MAXLST; - $return[$i]['max_sub'] = $pkg->MAXSUB; - $return[$i]['max_pop'] = $pkg->MAXPOP; - $return[$i]['max_park'] = $pkg->MAXPARK; - $return[$i]['max_addon'] = $pkg->MAXADDON; - - $return[$i]['has_shell'] = ($pkg->HASSHELL == 'n' ? 0 : 1); - $return[$i]['has_ip'] = ($pkg->IP == 'n' ? 0 : 1); - $return[$i]['has_cgi'] = ($pkg->CGI == 'n' ? 0 : 1); - $return[$i]['has_frontpage'] = ($pkg->FRONTPAGE == 'n' ? 0 : 1); - - $return[$i]['free_registration'] = 0; - $return[$i]['free_transfer'] = 0; - $return[$i++]['free_renewal'] = 0; - } - - return $return; } /** - * @param string $action + * Generates a package name based on the WHM server's username and the package's name. + * + * @param Server_Package $package the package for which to generate a name + * + * @return string the generated package name */ - private function _request($action, $params = []) + private function getPackageName(Server_Package $package): string { - $client = $this->getHttpClient()->withOptions([ - 'verify_peer' => false, - 'verify_host' => false, - 'timeout' => 90, // Account creation can timeout if set too low - see #1086. - ]); + return $this->_config['username'] . '_' . $package->getName(); + } - $url = ($this->_config['secure'] ? 'https' : 'http') . '://' . $this->_config['host'] . ':' . $this->_config['port'] . '/json-api/' . $action; - $username = $this->_config['username']; - $accesshash = $this->_config['accesshash']; - $password = $this->_config['password']; - $authstr = (!empty($accesshash)) ? 'WHM ' . $username . ':' . $accesshash - : 'Basic ' . $username . ':' . $password; + /** + * Modifies the package of an account on the WHM server. + * + * @param Server_Account $a the account for which to modify the package + * @param Server_Package $p the new package + * + * @return true if the package was successfully modified + * + * @throws Server_Exception if an error occurs during the request + */ + private function modifyAccountPackage(Server_Account $a, Server_Package $p): bool + { + // Log the modification + $this->getLog()->info('Modifying account ' . $a->getUsername()); - $this->getLog()->debug(sprintf('Requesting WHM server action "%s" with params "%s" ', $action, print_r($params, true))); + // Prepare the parameters for the API request + $varHash = [ + 'user' => $a->getUsername(), + 'domain' => $a->getDomain(), + 'HASCGI' => $p->getHasCgi(), + 'CPTHEME' => $p->getTheme(), + 'LANG' => $p->getLanguage(), + 'MAXPOP' => $p->getMaxPop(), + 'MAXFTP' => $p->getMaxFtp(), + 'MAXLST' => $p->getMaxEmailLists(), + 'MAXSUB' => $p->getMaxSubdomains(), + 'MAXPARK' => $p->getMaxParkedDomains(), + 'MAXADDON' => $p->getMaxAddons(), + 'MAXSQL' => $p->getMaxSql(), + 'shell' => $p->getHasShell(), + ]; - try { - $response = $client->request('POST', $url, [ - 'headers' => ['Authorization' => $authstr], - 'body' => $params, - ]); - } catch (HttpExceptionInterface $error) { - $e = throw new Server_Exception('HttpClientException: :error', [':error' => $error->getMessage()]); - $this->getLog()->err($e); - } - $body = $response->getContent(); - $json = json_decode($body); + // Send a request to the WHM server to modify the account's package + $this->request('modifyacct', $varHash); - if (!is_object($json)) { - $msg = sprintf('Function call "%s" response is invalid, body: %s', $action, $body); - $this->getLog()->crit($msg); - - $placeholders = [':action:' => $action, ':type:' => 'cPanel']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - if (isset($json->cpanelresult) && isset($json->cpanelresult->error)) { - $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->cpanelresult->error)); - $placeholders = ['action' => $action, 'type' => 'cPanel']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - if (isset($json->data) && isset($json->data->result) && $json->data->result == '0') { - $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->data->reason)); - $placeholders = [':action:' => $action, ':type:' => 'cPanel']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - if (isset($json->result) && is_array($json->result) && $json->result[0]->status == 0) { - $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->result[0]->statusmsg)); - $placeholders = [':action:' => $action, ':type:' => 'cPanel']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - if (isset($json->status) && $json->status != '1') { - $this->getLog()->crit(sprintf('WHM server response error calling action %s: "%s"', $action, $json->statusmsg)); - $placeholders = [':action:' => $action, ':type:' => 'cPanel']; - - throw new Server_Exception('Failed to :action: on the :type: server, check the error logs for further details', $placeholders); - } - - return $json; + return true; } } diff --git a/src/library/Server/Package.php b/src/library/Server/Package.php index a227419d4..2c27d6e23 100644 --- a/src/library/Server/Package.php +++ b/src/library/Server/Package.php @@ -1,28 +1,35 @@ custom = $param; return $this; } - public function setCustomValue($param, $value) + /** + * Set a custom value for the Server_Package instance. + * + * @param string $param the name of the custom value to be set + * @param string|null $value the value to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setCustomValue(string $param, ?string $value): static { $this->custom[$param] = $value; @@ -50,123 +72,254 @@ class Server_Package } /** - * @param string $param + * Get a custom value from the Server_Package instance. + * + * @param string $param the name of the custom value to be retrieved + * + * @return string|null returns the custom value if it exists, otherwise returns null */ - public function getCustomValue($param) + public function getCustomValue(string $param): ?string { return $this->custom[$param] ?? null; } - public function setName($param) - { - $this->name = $param; - - return $this; - } - - public function getName() + /** + * Get the name of the Server_Package instance. + * + * @return string|null returns the name as a string if it exists, otherwise returns null + */ + public function getName(): ?string { return $this->name; } - public function setQuota($param) + /** + * Set the name of the Server_Package instance. + * + * @param string|null $name the name to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setName(?string $name): static { - $this->quota = $param; + $this->name = $name; return $this; } - public function getQuota() + /** + * Get the quota of the Server_Package instance. + * + * @return string returns the quota + */ + public function getQuota(): string { return $this->quota; } - public function setBandwidth($param) + /** + * Set the quota of the Server_Package instance. + * + * @param string|null $quota the quota to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setQuota(?string $quota): static { - $this->bandwidth = $param; + $this->quota = $quota; return $this; } - public function getBandwidth() + /** + * Get the bandwidth of the Server_Package instance. + * + * @return string returns the bandwidth + */ + public function getBandwidth(): string { return $this->bandwidth; } - public function setMaxDomains($param) + /** + * Set the bandwidth of the Server_Package instance. + * + * @param string|null $bandwidth the bandwidth to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setBandwidth(?string $bandwidth): static { - $this->maxdomains = $param; + $this->bandwidth = $bandwidth; return $this; } - public function getMaxDomains() + /** + * Get the maximum number of domains for the Server_Package instance. + * + * @return string returns the maximum number of domains + */ + public function getMaxDomains(): string { - return $this->maxdomains; + return $this->maxDomains; } - public function setMaxSubdomains($param) + /** + * Set the maximum number of domains for the Server_Package instance. + * + * @param string|null $maxDomains the maximum number of domains to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxDomains(?string $maxDomains): static { - $this->maxsubdomains = $param; + $this->maxDomains = $maxDomains; return $this; } - public function getMaxSubdomains() + /** + * Get the maximum number of subdomains for the Server_Package instance. + * + * @return string returns the maximum number of subdomains + */ + public function getMaxSubdomains(): string { - return $this->maxsubdomains; + return $this->maxSubdomains; } - public function setMaxParkedDomains($param) + /** + * Set the maximum number of subdomains for the Server_Package instance. + * + * @param string|null $maxSubdomains the maximum number of subdomains to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxSubdomains(?string $maxSubdomains): static { - $this->maxparkeddomains = $param; + $this->maxSubdomains = $maxSubdomains; return $this; } - public function getMaxParkedDomains() + /** + * Get the maximum number of parked domains for the Server_Package instance. + * + * @return string returns the maximum number of parked domains + */ + public function getMaxParkedDomains(): string { - return $this->maxparkeddomains; + return $this->maxParkedDomains; } - public function setMaxFtp($param) + /** + * Set the maximum number of parked domains for the Server_Package instance. + * + * @param string|null $maxParkedDomains the maximum number of parked domains to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxParkedDomains(?string $maxParkedDomains): static { - $this->maxftp = $param; + $this->maxParkedDomains = $maxParkedDomains; return $this; } - public function getMaxFtp() + /** + * Get the maximum number of FTP accounts for the Server_Package instance. + * + * @return string returns the maximum number of FTP accounts + */ + public function getMaxFtp(): string { - return $this->maxftp; + return $this->maxFtp; } - public function setMaxSql($param) + /** + * Set the maximum number of FTP accounts for the Server_Package instance. + * + * @param string|null $maxFtp the maximum number of FTP accounts to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxFtp(?string $maxFtp): static { - $this->maxsql = $param; + $this->maxFtp = $maxFtp; return $this; } - public function getMaxSql() + /** + * Get the maximum number of SQL databases for the Server_Package instance. + * + * @return string returns the maximum number of SQL databases + */ + public function getMaxSql(): string { - return $this->maxsql; + return $this->maxSql; } - public function setMaxPop($param) + /** + * Set the maximum number of SQL databases for the Server_Package instance. + * + * @param string|null $maxSql the maximum number of SQL databases to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxSql(?string $maxSql): static { - $this->maxpop = $param; + $this->maxSql = $maxSql; return $this; } - public function getMaxPop() + /** + * Get the maximum number of POP email accounts for the Server_Package instance. + * + * @return string|null returns the maximum number of POP email accounts + */ + public function getMaxPop(): ?string { - return $this->maxpop; + return $this->MaxPop; } - public function getMaxQuota() + /** + * Set the maximum number of POP email accounts for the Server_Package instance. + * + * @param string|null $maxPop the maximum number of POP email accounts to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxPop(?string $maxPop): static + { + $this->MaxPop = $maxPop; + + return $this; + } + + /** + * Get the maximum quota for the Server_Package instance. + * + * @return string|null returns the maximum quota + */ + public function getMaxQuota(): ?string { return $this->quota; } + + /** + * Set the maximum quota for the Server_Package instance. + * + * @param string|null $maxQuota the maximum quota to be set + * + * @return $this returns the current instance to allow for method chaining + */ + public function setMaxQuota(?string $maxQuota): static + { + $this->quota = $maxQuota; + + return $this; + } }