Enhance VirtFusion WHMCS module with security fixes, new features, and improved UX

Security improvements:
- Enable SSL/TLS certificate verification by default (was disabled, MITM risk)
- Remove error_reporting(0) that silenced all errors
- Add input sanitization on all user parameters (int casting, regex filtering)
- Return proper HTTP status codes (401, 403, 400, 500) instead of always 200
- Add XSS protection with htmlspecialchars and encodeURIComponent
- Add null checks on API response data before property access

New features:
- Power management: boot, shutdown, restart, and force power off controls
- Server rebuild: reinstall with any available OS template from client area
- Server rename: change server display name via PATCH API
- OS template fetching: client-side endpoint for rebuild OS selection
- TestConnection: validate API credentials from WHMCS server settings
- ServiceSingleSignOn: native WHMCS SSO integration for VirtFusion panel
- Server status badge: visual indicator of server state in overview
- Traffic usage display: show bandwidth used vs allocated
- Checkout validation: ShoppingCartValidateCheckout hook ensures OS selection

Ordering process improvements:
- Add default "Select Operating System" placeholder option
- Add "No SSH Key (Optional)" default for SSH dropdown
- Hide SSH key field/container when no keys available
- Wrap hook in try/catch to prevent checkout page breakage
- Sanitize template names with htmlspecialchars
- Use JSON_HEX_* flags for safe script injection

Theme compatibility:
- Properly formatted Smarty templates with readable indentation
- Dual panel/card CSS classes for Bootstrap 3/4/5 compatibility
- Responsive power button layout with mobile breakpoint
- Framework-agnostic HTML that works with Six, Twenty-One, Lagom, and custom themes
- Suspended service state messaging

Code quality:
- Readable, unminified JavaScript with JSDoc header
- Structured CSS with logical section organization
- Improved error messages throughout all provisioning functions
- Added PATCH method support to Curl wrapper
- Added curl error capture on connection failures
- Added connection and request timeouts (10s/30s)
- Fixed memory conversion to check key name instead of display name

Documentation:
- Complete README rewrite with installation, configuration, and troubleshooting guides
- API endpoint reference table
- Configurable options mapping documentation
- Theme override instructions
- Security considerations section

https://claude.ai/code/session_01TCsJ4WZCGuEX3zqh1tQ2zx
This commit is contained in:
Claude
2026-02-07 12:18:11 +00:00
parent 7b87fdcc3f
commit c93072b1c6
12 changed files with 1468 additions and 293 deletions

View File

@@ -8,12 +8,14 @@ class Curl
private $data;
private $customOptions = [];
private $defaultOptions = [
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'CURL',
CURLOPT_USERAGENT => 'VirtFusion-WHMCS/2.0',
CURLOPT_HEADER => false,
CURLOPT_NOBODY => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
];
@@ -24,7 +26,7 @@ class Curl
public function useCookies()
{
$cookiesFile = tempnam('/tmp', 'virtfusion_cookies');
$cookiesFile = tempnam(sys_get_temp_dir(), 'virtfusion_cookies');
$this->defaultOptions[CURLOPT_COOKIEFILE] = $cookiesFile;
$this->defaultOptions[CURLOPT_COOKIEJAR] = $cookiesFile;
}
@@ -57,6 +59,15 @@ class Curl
return $this->send('PUT', $url);
}
/**
* @param null $url
* @return bool|string|void
*/
public function patch($url = null)
{
return $this->send('PATCH', $url);
}
/**
* @param $method
* @param $url
@@ -84,6 +95,12 @@ class Curl
$response = curl_exec($this->ch);
$this->data['info'] = curl_getinfo($this->ch);
if ($response === false) {
$this->data['info']['curl_error'] = curl_error($this->ch);
$this->data['info']['curl_errno'] = curl_errno($this->ch);
}
if (isset($this->customOptions[CURLOPT_HEADER]) && $this->customOptions[CURLOPT_HEADER]) {
$this->data['info']['request_header'] = trim($this->data['info']['request_header']);
$this->processHeaders($response);
@@ -197,4 +214,4 @@ class Curl
return $this->data['data'];
}
}
}

View File

@@ -2,46 +2,45 @@
namespace WHMCS\Module\Server\VirtFusionDirect;
class Module
{
public function __construct()
{
error_reporting(0);
Database::schema();
}
/**
* @param bool $exitOnError
* @return mixed
* @return string
*/
public function validateAction($exitOnError = true)
{
if (!isset($_GET['action'])) {
$this->output(['errors' => 'no action specified'], true, $exitOnError, 200);
$this->output(['success' => false, 'errors' => 'no action specified'], true, $exitOnError, 400);
}
return $_GET['action'];
return preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['action']);
}
/**
* @param bool $exitOnError
* @return mixed
* @return int
*/
public function validateServiceID($exitOnError = true)
{
if (!isset($_GET['serviceID'])) {
$this->output(['errors' => 'no serviceID specified'], true, $exitOnError, 200);
if (!isset($_GET['serviceID']) || !is_numeric($_GET['serviceID'])) {
$this->output(['success' => false, 'errors' => 'no valid serviceID specified'], true, $exitOnError, 400);
}
return $_GET['serviceID'];
return (int) $_GET['serviceID'];
}
/**
* @param $serviceID
* @param int $serviceID
* @param bool $exitOnError
* @return bool
* @return int|false
*/
public function validateUserOwnsService($serviceID, $exitOnError = true)
{
$serviceID = (int) $serviceID;
$currentUser = new \WHMCS\Authentication\CurrentUser;
$client = $currentUser->client();
@@ -57,11 +56,12 @@ class Module
}
/**
* @param $serviceID
* @param int $serviceID
* @return false|string
*/
public function fetchLoginTokens($serviceID)
{
$serviceID = (int) $serviceID;
$service = Database::getSystemService($serviceID);
if ($service) {
@@ -69,13 +69,15 @@ class Module
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->post($cp['url'] . '/users/' . $whmcsService->userid . '/serverAuthenticationTokens/' . $service->server_id);
$data = $request->post($cp['url'] . '/users/' . (int) $whmcsService->userid . '/serverAuthenticationTokens/' . (int) $service->server_id);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
if ($request->getRequestInfo('http_code') == '200') {
$data = json_decode($data);
return $cp['base_url'] . $data->data->authentication->endpoint_complete;
if (isset($data->data->authentication->endpoint_complete)) {
return $cp['base_url'] . $data->data->authentication->endpoint_complete;
}
}
}
return false;
@@ -117,13 +119,14 @@ class Module
public function fetchServerData($serviceID)
{
$serviceID = (int) $serviceID;
$service = Database::getSystemService($serviceID);
if ($service) {
$whmcsService = Database::getWhmcsService($serviceID);
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/servers/' . $service->server_id);
$data = $request->get($cp['url'] . '/servers/' . (int) $service->server_id);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -134,8 +137,170 @@ class Module
return false;
}
/**
* Execute a power action on a server.
*
* @param int $serviceID
* @param string $action One of: boot, shutdown, restart, poweroff
* @return object|false
*/
public function serverPowerAction($serviceID, $action)
{
$serviceID = (int) $serviceID;
$allowedActions = ['boot', 'shutdown', 'restart', 'poweroff'];
if (!in_array($action, $allowedActions, true)) {
return false;
}
$service = Database::getSystemService($serviceID);
if ($service) {
$whmcsService = Database::getWhmcsService($serviceID);
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/power/' . $action);
Log::insert(__FUNCTION__ . ':' . $action, $request->getRequestInfo(), $data);
$httpCode = $request->getRequestInfo('http_code');
if ($httpCode == 200 || $httpCode == 204) {
return json_decode($data) ?: (object) ['success' => true];
}
}
return false;
}
/**
* Rebuild/reinstall a server with a new OS.
*
* @param int $serviceID
* @param int $osId Operating system template ID
* @param string|null $hostname Optional new hostname
* @return object|false
*/
public function rebuildServer($serviceID, $osId, $hostname = null)
{
$serviceID = (int) $serviceID;
$osId = (int) $osId;
if ($osId <= 0) {
return false;
}
$service = Database::getSystemService($serviceID);
if ($service) {
$whmcsService = Database::getWhmcsService($serviceID);
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$buildData = [
'operatingSystemId' => $osId,
'email' => true,
];
if ($hostname !== null && $hostname !== '') {
$buildData['hostname'] = $hostname;
}
$request->addOption(CURLOPT_POSTFIELDS, json_encode($buildData));
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/build');
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
$httpCode = $request->getRequestInfo('http_code');
if ($httpCode == 200 || $httpCode == 201) {
return json_decode($data) ?: (object) ['success' => true];
}
}
return false;
}
/**
* Rename a server.
*
* @param int $serviceID
* @param string $newName
* @return bool
*/
public function renameServer($serviceID, $newName)
{
$serviceID = (int) $serviceID;
$newName = trim($newName);
if (empty($newName) || strlen($newName) > 255) {
return false;
}
$service = Database::getSystemService($serviceID);
if ($service) {
$whmcsService = Database::getWhmcsService($serviceID);
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$request->addOption(CURLOPT_POSTFIELDS, json_encode(['name' => $newName]));
$data = $request->patch($cp['url'] . '/servers/' . (int) $service->server_id . '/name');
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
$httpCode = $request->getRequestInfo('http_code');
return ($httpCode == 200 || $httpCode == 204);
}
return false;
}
/**
* Fetch available OS templates for a server's package.
*
* @param int $serviceID
* @return array|false
*/
public function fetchOsTemplates($serviceID)
{
$serviceID = (int) $serviceID;
$service = Database::getSystemService($serviceID);
if ($service) {
$whmcsService = Database::getWhmcsService($serviceID);
$cp = $this->getCP($whmcsService->server);
$product = \WHMCS\Database\Capsule::table('tblproducts')->where('id', $whmcsService->packageid)->first();
if (!$product || !$product->configoption2) {
return false;
}
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/media/templates/fromServerPackageSpec/' . (int) $product->configoption2);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
if ($request->getRequestInfo('http_code') == '200') {
$templates = json_decode($data, true);
$result = [];
if (isset($templates['data'])) {
foreach ($templates['data'] as $osCategory) {
foreach ($osCategory['templates'] as $template) {
$result[] = [
'id' => $template['id'],
'name' => $template['name'] . ' ' . $template['version'] . ' ' . $template['variant'],
];
}
}
usort($result, function ($a, $b) {
return strcmp($a['name'], $b['name']);
});
}
return $result;
}
}
return false;
}
public function resetUserPassword($serviceID, $clientID)
{
$serviceID = (int) $serviceID;
$clientID = (int) $clientID;
$service = Database::getSystemService($serviceID);
if ($service) {
@@ -201,7 +366,7 @@ class Module
return true;
}
$this->output(['errors' => 'unauthenticated'], true, true, 200);
$this->output(['success' => false, 'errors' => 'unauthenticated'], true, true, 401);
}
/**
@@ -213,7 +378,7 @@ class Module
return true;
}
$this->output(['errors' => 'unauthenticated'], true, true, 200);
$this->output(['success' => false, 'errors' => 'unauthenticated'], true, true, 401);
}
/**

View File

@@ -23,59 +23,49 @@ class ModuleFunctions extends Module
try {
/**
*
* If the service exists in the custom table, Cancel the create account action.
*
* If the service exists in the custom table, cancel the create account action.
*/
if (Database::checkSystemService($params['serviceid'])) {
return 'Service already exists. You must run a termination first.';
}
/**
*
* If no VirtFusionDirect control server exists, cancel the create account action.
*
*/
$server = $params['serverid'] ?: false;
$cp = $this->getCP($server, !$server);
if (!$cp) {
return 'No Control server found.';
return 'No Control server found. Please ensure a VirtFusion server is configured in WHMCS.';
}
Log::insert(__FUNCTION__, $params, []);
/**
*
* Does a user account in VirtFusion match this account (byExtRelationId) in WHMCS.
*
*/
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/users/' . $params['userid'] . '/byExtRelation');
$data = $request->get($cp['url'] . '/users/' . (int) $params['userid'] . '/byExtRelation');
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
switch ($request->getRequestInfo('http_code')) {
case 200:
/**
*
* A user with relation ID exists in VirtFusion. We can provision under that account.
*
*/
break;
case 404:
/**
*
* A user doesn't exist in VirtFusion. We should attempt to create one.
*
*/
$user = Database::getUser($params['userid']);
if (!$user) {
return 'WHMCS user not found for ID ' . (int) $params['userid'];
}
$request = $this->initCurl($cp['token']);
$request->addOption(CURLOPT_POSTFIELDS, json_encode(
@@ -91,19 +81,17 @@ class ModuleFunctions extends Module
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
if ($request->getRequestInfo('http_code') !== 201) {
return 'Unable to create user.';
return 'Unable to create user in VirtFusion. API returned HTTP ' . $request->getRequestInfo('http_code');
}
break;
default:
return 'Error processing user account.';
return 'Error processing user account. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
$data = json_decode($data);
/**
*
* A user is available. We can now attempt to create a server.
*
*/
$configOptionDefaultNaming = [
@@ -123,26 +111,27 @@ class ModuleFunctions extends Module
$configOptionCustomNaming = [];
if (file_exists(ROOTDIR . '/modules/servers/VirtFusionDirect/config/ConfigOptionMapping.php')) {
$configOptionCustomNaming = require_once ROOTDIR . '/modules/servers/VirtFusionDirect/config/ConfigOptionMapping.php';
$configOptionCustomNaming = require ROOTDIR . '/modules/servers/VirtFusionDirect/config/ConfigOptionMapping.php';
}
$options = [
"packageId" => $params['configoption2'],
"packageId" => (int) $params['configoption2'],
"userId" => $data->data->id,
"hypervisorId" => $params['configoption1'],
"ipv4" => $params['configoption3'],
"hypervisorId" => (int) $params['configoption1'],
"ipv4" => (int) $params['configoption3'],
];
if (array_key_exists('configoptions', $params)) {
foreach ($configOptionDefaultNaming as $key => $option) {
$currentOption = array_key_exists($key, $configOptionCustomNaming) ? $configOptionCustomNaming[$key] : $option;
if (array_key_exists($currentOption, $params['configoptions'])) {
// If the option key is "Memory" and the value is less than 1024, we need to convert it to MB
$value = $params['configoptions'][$currentOption];
// If the option key is "Memory" and the value is less than 1024, convert to MB
// VirtFusion expects memory in MB.
if ($currentOption === 'Memory' && $params['configoptions'][$currentOption] < 1024) {
$options[$key] = $params['configoptions'][$currentOption] * 1024;
if ($key === 'memory' && is_numeric($value) && $value < 1024) {
$options[$key] = (int) ($value * 1024);
} else {
$options[$key] = $params['configoptions'][$currentOption];
$options[$key] = is_numeric($value) ? (int) $value : $value;
}
}
}
@@ -166,17 +155,15 @@ class ModuleFunctions extends Module
$cs = new ConfigureService();
$cs->initServerBuild($data->data->id, $params);
/**
*
* Server was created successfully.
*
*/
return 'success';
} else {
if ($data->errors[0]) {
if (isset($data->errors) && is_array($data->errors) && isset($data->errors[0])) {
return $data->errors[0];
}
return 'Unknown error.';
if (isset($data->msg)) {
return $data->msg;
}
return 'Server creation failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
} catch (\Exception $e) {
Log::insert(__FUNCTION__, $params, $e->getMessage());
@@ -184,16 +171,10 @@ class ModuleFunctions extends Module
}
}
// This function was implemented by Zander Scott / awildboop of Blinkoh, LLC
// Please read this function thoroughly before use to ensure security & integrity
/**
* Allows changing of the package of a server
*
* @author https://github.com/BlinkohHost/virtfusion-whmcs-module
*
* @param $params
*
* @return string
*/
public function changePackage($params)
@@ -204,7 +185,7 @@ class ModuleFunctions extends Module
$whmcsService = Database::getWhmcsService($params['serviceid']);
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->put($cp['url'] . '/servers/' . $service->server_id . '/package/' . $params['configoption2']);
$data = $request->put($cp['url'] . '/servers/' . (int) $service->server_id . '/package/' . (int) $params['configoption2']);
$data = json_decode($data);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -214,17 +195,17 @@ class ModuleFunctions extends Module
case 204:
return 'success';
case 404:
return '404 was returned from the web service without the msg property. The service may be currently unavailable.';
return 'The server or package was not found in VirtFusion (HTTP 404).';
case 423:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
return $data->msg;
}
break;
return 'The server is currently locked. Please try again later.';
default:
return 'Update package request failed. The web service reported HTTP code ' . $request->getRequestInfo('http_code');
return 'Update package request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
}
return 'Service not found.';
return 'Service not found in module database.';
}
/**
@@ -247,7 +228,7 @@ class ModuleFunctions extends Module
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->delete($cp['url'] . '/servers/' . $service->server_id);
$data = $request->delete($cp['url'] . '/servers/' . (int) $service->server_id);
$data = json_decode($data);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -260,22 +241,22 @@ class ModuleFunctions extends Module
return 'success';
case 404:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
if ($data->msg == 'server not found') {
Database::deleteSystemService($params['serviceid']);
return 'success';
} else {
return '404 was returned from the web service with the msg property but doesn\'t contain appropriate data to process a termination.';
return 'VirtFusion returned 404: ' . $data->msg;
}
} else {
return '404 was returned from the web service without the msg property. The service may be currently unavailable.';
return 'VirtFusion returned 404 without details. The API may be unavailable.';
}
default:
return 'Termination request failed. The web service reported HTTP code ' . $request->getRequestInfo('http_code');
return 'Termination request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
}
return 'Service not found. Termination routine has already been run?';
return 'Service not found in module database. Has termination already been run?';
}
/**
@@ -297,7 +278,7 @@ class ModuleFunctions extends Module
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->post($cp['url'] . '/servers/' . $service->server_id . '/suspend');
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/suspend');
$data = json_decode($data);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -308,27 +289,27 @@ class ModuleFunctions extends Module
return 'success';
case 404:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
if ($data->msg == 'server not found') {
Database::deleteSystemService($params['serviceid']);
return 'success';
} else {
return '404 was returned from the web service with the msg property but doesn\'t contain appropriate data to process a suspension.';
return 'VirtFusion returned 404: ' . $data->msg;
}
} else {
return '404 was returned from the web service without the msg property. The service may be currently unavailable.';
return 'VirtFusion returned 404 without details. The API may be unavailable.';
}
case 423:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
return $data->msg;
}
return 'The server is currently locked. Please try again later.';
default:
return 'Suspend request failed. The web service reported HTTP code ' . $request->getRequestInfo('http_code');
return 'Suspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
}
return 'Service not found.';
return 'Service not found in module database.';
}
function updateServerObject($params)
@@ -341,7 +322,7 @@ class ModuleFunctions extends Module
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/servers/' . $service->server_id);
$data = $request->get($cp['url'] . '/servers/' . (int) $service->server_id);
$data = json_decode($data);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -355,10 +336,10 @@ class ModuleFunctions extends Module
return 'success';
default:
return 'Request failed. The web service reported HTTP code ' . $request->getRequestInfo('http_code');
return 'Request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
}
return 'Service not found.';
return 'Service not found in module database.';
}
@@ -371,7 +352,7 @@ class ModuleFunctions extends Module
$cp = $this->getCP($whmcsService->server);
$request = $this->initCurl($cp['token']);
$data = $request->post($cp['url'] . '/servers/' . $service->server_id . '/unsuspend');
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/unsuspend');
$data = json_decode($data);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
@@ -382,27 +363,27 @@ class ModuleFunctions extends Module
return 'success';
case 404:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
if ($data->msg == 'server not found') {
Database::deleteSystemService($params['serviceid']);
return 'success';
} else {
return '404 was returned from the web service with the msg property but doesn\'t contain appropriate data to process an unsuspension.';
return 'VirtFusion returned 404: ' . $data->msg;
}
} else {
return '404 was returned from the web service without the msg property. The service may be currently unavailable.';
return 'VirtFusion returned 404 without details. The API may be unavailable.';
}
case 423:
if (property_exists($data, 'msg')) {
if (isset($data->msg)) {
return $data->msg;
}
break;
return 'The server is currently locked. Please try again later.';
default:
return 'Unsuspend request failed. The web service reported HTTP code ' . $request->getRequestInfo('http_code');
return 'Unsuspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
}
}
return 'Service not found';
return 'Service not found in module database.';
}
public function adminServicesTabFields($params)
@@ -432,12 +413,13 @@ class ModuleFunctions extends Module
public function adminServicesTabFieldsSave($params)
{
if ($_POST['modulefields'][0] == '') {
if (!isset($_POST['modulefields'][0]) || $_POST['modulefields'][0] === '') {
Database::deleteSystemService($params['serviceid']);
} else {
Database::updateSystemServiceServerId($params['serviceid'], $_POST['modulefields'][0]);
$serverId = (int) $_POST['modulefields'][0];
if ($serverId > 0) {
Database::updateSystemServiceServerId($params['serviceid'], $serverId);
}
}
}

View File

@@ -8,33 +8,54 @@ class ServerResource
{
$server = json_decode(json_encode($data->data), true);
$traffic = '';
$traffic = '-';
if ($server['settings']['resources']['traffic']) {
if (isset($server['settings']['resources']['traffic'])) {
if ($server['settings']['resources']['traffic'] > 0) {
$traffic = $server['settings']['resources']['traffic'] . ' GB';
} else {
$traffic = 'Unlimited';
}
}
$trafficUsed = '-';
if (isset($server['usage']['traffic']['used'])) {
$trafficUsed = round($server['usage']['traffic']['used'] / 1073741824, 2) . ' GB';
}
$data = [
'name' => $server['name'] ?: '-',
'hostname' => $server['hostname'] ?: '-',
'memory' => $server['settings']['resources']['memory'] . ' MB',
'memory' => isset($server['settings']['resources']['memory']) ? $server['settings']['resources']['memory'] . ' MB' : '-',
'traffic' => $traffic,
'storage' => $server['settings']['resources']['storage'] . ' GB',
'cpu' => $server['settings']['resources']['cpuCores'] . ' Core(s)',
'trafficUsed' => $trafficUsed,
'storage' => isset($server['settings']['resources']['storage']) ? $server['settings']['resources']['storage'] . ' GB' : '-',
'cpu' => isset($server['settings']['resources']['cpuCores']) ? $server['settings']['resources']['cpuCores'] . ' Core(s)' : '-',
'status' => isset($server['state']) ? $server['state'] : 'unknown',
'powerStatus' => isset($server['hypervisor']['settings']['state']) ? $server['hypervisor']['settings']['state'] : 'unknown',
'username' => isset($server['owner']['email']) ? $server['owner']['email'] : '',
'password' => '',
'primaryNetwork' => [
'ipv4' => ['-'],
'ipv4Unformatted' => [],
'ipv6' => ['-'],
'ipv6Unformatted' => [],
]
'mac' => '-',
],
'networkSpeed' => [
'inbound' => isset($server['settings']['resources']['networkSpeedInbound']) ? $server['settings']['resources']['networkSpeedInbound'] . ' Mbps' : '-',
'outbound' => isset($server['settings']['resources']['networkSpeedOutbound']) ? $server['settings']['resources']['networkSpeedOutbound'] . ' Mbps' : '-',
],
];
if (array_key_exists('network', $server)) {
if (array_key_exists('interfaces', $server['network'])) {
if (count($server['network']['interfaces'])) {
if (isset($server['network']['interfaces'][0]['mac'])) {
$data['primaryNetwork']['mac'] = $server['network']['interfaces'][0]['mac'];
}
if (count($server['network']['interfaces'][0]['ipv4'])) {
$data['primaryNetwork']['ipv4'] = [];
foreach ($server['network']['interfaces'][0]['ipv4'] as $ip) {
@@ -59,4 +80,4 @@ class ServerResource
return $data;
}
}
}