v.1.1 changes 16-04-2026:

- Minor changes to interface.
- Fixed different missing includes.
- Access now denied to api calls that are related to disabled modules.
- Fixed sorting of CPU and memory in server overview.
This commit is contained in:
2026-04-16 15:01:40 +02:00
parent 36b0ebd10c
commit eec1d13cf5
40 changed files with 26451 additions and 26428 deletions

View File

@@ -44,8 +44,11 @@ class API
public function __construct()
{
# Setup Database connection
require_once $_SERVER['DOCUMENT_ROOT'] . '/bin/php/db_connect.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/bin/php/Functions/globalFunctions.php';
# Setup Database connection
$this->conn = $GLOBALS['conn'];
if (!empty($_SESSION['user']['user_uuid'])) {
@@ -77,6 +80,9 @@ class API
}
}
# Get the enabled modules for the user
$GLOBALS['modules_enabled'] = getEnabledModules();
// Disable builder input for non-GET requests to prevent potential SQL injection vulnerabilities.
// Also disable the builder for users with the 'frontend' user type as an extra security measure.
// The builder should only be active for API users making GET requests.
@@ -98,7 +104,6 @@ class API
$this->user_type = 'frontend';
# Load the locale for the user, this is used for the return message in the frontend and other globalFunctions.
include_once $_SERVER['DOCUMENT_ROOT'] . '/bin/php/Functions/globalFunctions.php';
$locale = getPreferredLocale();
global $translations;
$translations = require $_SERVER['DOCUMENT_ROOT'] . "/bin/locales/{$locale}.php";

View File

@@ -1,20 +1,20 @@
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_companies extends API
{
public function updateCompanyState()
{
$query = "UPDATE companies SET company_state = ? WHERE company_uuid = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('ss', $this->data['company_state'], $this->data['company_uuid']);
if ($this->executeStatement($stmt)) {
$this->apiOutput(200, ['success' => 'company state successfully updated']);
}
}
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_companies extends API
{
public function updateCompanyState()
{
$query = "UPDATE companies SET company_state = ? WHERE company_uuid = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('ss', $this->data['company_state'], $this->data['company_uuid']);
if ($this->executeStatement($stmt)) {
$this->apiOutput(200, ['success' => 'company state successfully updated']);
}
}
}

View File

@@ -1,478 +1,478 @@
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_inserve extends API
{
private $inserve_url;
private $inserve_token;
public $inserve_source_uuid;
private $ch;
public $httpCode = false;
public $response = false;
private $cloudDistrubutor = 'digistate-servers';
public function setupConnection()
{
$query = "SELECT * FROM system_sources WHERE source_name = 'inserve'";
$result = $this->conn->query($query)->fetch_assoc();
$this->inserve_url = $result['source_url'];
$this->inserve_token = $result['source_auth_token'];
$this->inserve_source_uuid = $result['source_uuid'];
}
public function execCurl()
{
$this->response = curl_exec($this->ch);
$this->httpCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
curl_close($this->ch);
}
public function returnResponse()
{
$this->apiOutput($this->httpCode, json_decode($this->response, true));
}
public function authMe()
{
$this->ch = curl_init($this->inserve_url . 'auth/me');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function getLinkedCompanies()
{
$this->ch = curl_init($this->inserve_url . 'cloud-distributors/digistate-servers/companies');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function companies($page)
{
// Build array the way the API expects
$params = [
'b' => [
['orderBy' => ['name', 'ASC']],
['orderBy' => ['id', 'DESC']],
['with' => ['operator', 'country']],
['paginate' => 300],
],
'page' => $page
];
$query = http_build_query($params);
$this->ch = curl_init($this->inserve_url . 'companies?' . $query);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
return json_decode($this->response, true);
}
public function syncCompaniesFromSentri()
{
# First retrieve all the active companies to sync to the Inserver cloud distributor
$companies = [];
$sql = "SELECT company_source_id FROM companies WHERE company_state = 'active'";
$stmt = $this->conn->query($sql);
while ($row = $stmt->fetch_assoc()) {
$id = (int)$row['company_source_id'];
$companies[] = [
'cloud_distribution_id' => (string)$id,
'company_id' => $id
];
}
$url = $this->inserve_url . 'cloud-distributors/digistate-servers/companies';
$this->ch = curl_init($url);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($companies),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
public function getCloudSubscriptions()
{
$this->ch = curl_init($this->inserve_url . 'cloud-distribution-subscriptions/');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function updateSubscription($subscriptionId = false, $payload = false)
{
$url = $this->inserve_url . 'cloud-distribution-subscriptions/' . $subscriptionId;
$this->ch = curl_init($url);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
private function getAllTypes($type)
{
$allowedColumns = [
'server_licenses',
'server_backup'
];
if (!in_array($type, $allowedColumns, true)) {
throw new Exception('Invalid column name');
}
$query = "SELECT `$type` FROM servers";
$stmt = $this->prepareStatement($query);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$servers = [];
while ($row = $result->fetch_assoc()) {
array_push($servers, $row);
}
$allTypes = [];
foreach ($servers as $server) {
if (!empty($server[$type])) {
$types = json_decode($server[$type], true);
if (is_array($types)) {
foreach ($types as $item) {
foreach ($item as $key => $value) {
$allTypes[$key . '.' . $value] = 0;
}
}
}
}
}
return $allTypes;
}
private function calculateTotalDiskUsage($diskJson)
{
$disks = json_decode($diskJson, true);
$server_disks_count = 0;
if (is_array($disks)) {
foreach ($disks as $disk) {
$server_disks_count += $disk['disk_space'];
}
}
if (is_array($disks) && count($disks) > 0) {
$sizes = array_column($disks, 'disk_space');
$server_disks_count = array_sum($sizes);
}
return $server_disks_count;
}
private function buildCountObject(string $serverUuid, string $key): array
{
return [
'countSentri' => 0,
'countInserve' => 0,
'sentriCompanyId' => 0,
'SentriStatus' => 0,
'subscriptionInserveExists' => false,
'subscriptionInserveId' => false,
'subscriptionInserveCompanyId' => false,
'subscriptionInserveName' => false,
'subscriptionInserveStatus' => 0,
'md5' => md5($serverUuid . ':' . $key),
];
}
private function transformTypes(array $types, string $serverUuid): array
{
$result = [];
foreach ($types as $key => $value) {
$result[$key] = $this->buildCountObject($serverUuid, $key);
}
return $result;
}
private function buildCountArray($serverUuid)
{
$allBackupTypes = $this->getAllTypes('server_backup');
$allLicenseTypes = $this->getAllTypes('server_licenses');
$backupCounts = $this->transformTypes($allBackupTypes, $serverUuid);
$licenseCounts = $this->transformTypes($allLicenseTypes, $serverUuid);
return array_merge(
[
"server_CPU_count" => $this->buildCountObject($serverUuid, 'server_cpu_count'),
"server_Memory_count" => $this->buildCountObject($serverUuid, 'server_memory_count'),
"server_Disk_space_count" => $this->buildCountObject($serverUuid, 'server_disks_count'),
],
$licenseCounts,
$backupCounts
);
}
public function syncServerLicencesToInserve()
{
# Get all the linked companies
$this->getLinkedCompanies();
$allCompanies = json_decode($this->response, true);
$allCompaniesIds = array_column($allCompanies['matched'], 'id', 'company_id');
# first get the current subscriptions
$this->getCloudSubscriptions();
$allInserveSubscriptions = json_decode($this->response, true);
# Filter out all the none Sentri posted subscriptions based on the name for performance
$allInserveSubscriptions = array_filter($allInserveSubscriptions, function ($subscription) {
return isset($subscription['cloud_subscription_id']) && $subscription['cloud_subscription_id'] === 'sentri-servers';
});
# Build lookup of existing Inserve subscriptions by cloud_distribution_id
# this will be used later to lookup
$inserveLookup = [];
foreach ($allInserveSubscriptions as $subscription) {
if (!empty($subscription['cloud_distribution_id'])) {
$inserveLookup[$subscription['cloud_distribution_id']] = [
'id' => (int)$subscription['id'],
'quantity' => (int)$subscription['quantity'],
'status' => (int)$subscription['status'],
'cloud_distribution_company_id' => (int)$subscription['cloud_distribution_company_id'],
];
}
}
# get all the servers from Sentri
$sql = "SELECT * FROM servers INNER JOIN companies ON servers.company_uuid = companies.company_uuid WHERE company_state = 'active' AND server_state != 'new' AND server_state != 'disabled' ";
$stmt = $this->conn->query($sql);
while ($row = $stmt->fetch_assoc()) {
# Create a count of all the Subscriptions possible with every count on 0
$subscriptionCounts = $this->buildCountArray($row['server_uuid']);
$totalDiskSpace = $this->calculateTotalDiskUsage($row['server_disks']);
# Inserve status codes are:
# 0 = active, 1 = cancelled, 2 = pending, 3 = trial, 4 = on hold, 5 = removed
$statusMap = [
'active' => 0,
'trial' => 3,
'deleted' => 5,
];
// if no states matched there is something terrifying wrong, call the ambulance!
if (!isset($statusMap[$row['server_state']])) {
exit;
}
$sentriStatus = $statusMap[$row['server_state']];
# Set all the server resource counts from Sentri into the $subscriptionCounts
$subscriptionCounts['server_CPU_count']['countSentri'] = $row['server_cpu'];
$subscriptionCounts['server_Memory_count']['countSentri'] = (int)ceil($row['server_memory'] / 1024);
$subscriptionCounts['server_Disk_space_count']['countSentri'] = $totalDiskSpace;
$licenses = json_decode($row['server_licenses'], true);
foreach ($licenses as $license) {
foreach ($license as $key => $LicenseType) {
$subscriptionCounts[$key . '.' . $LicenseType]['countSentri']++;
}
}
$backups = json_decode($row['server_backup'], true);
foreach ($backups as $backup) {
foreach ($backup as $key => $BackupType) {
$subscriptionCounts[$key . '.' . $BackupType]['countSentri'] = $totalDiskSpace;
}
}
# Mark subscriptions that already exist in Inserve
foreach ($subscriptionCounts as $key => &$item) {
if (!is_array($item) || !isset($item['md5'])) {
continue;
}
$md5 = (string)$item['md5'];
if (isset($inserveLookup[$md5])) { # Subscription already exists in Inserve
$item['SentriStatus'] = $sentriStatus;
$item['sentriCompanyId'] = (int)$allCompaniesIds[$row['company_source_id']] ?? 0;
$item['subscriptionInserveExists'] = true;
$item['subscriptionInserveId'] = $inserveLookup[$item['md5']]['id'];
$item['countInserve'] = $inserveLookup[$item['md5']]['quantity'];
$item['subscriptionInserveCompanyId'] = $inserveLookup[$item['md5']]['cloud_distribution_company_id'];
$item['subscriptionInserveStatus'] = $inserveLookup[$item['md5']]['status'];
} else { # Subscription does not exists in Inserve
$item['sentriCompanyId'] = (int)$allCompaniesIds[$row['company_source_id']] ?? 0;
$item['subscriptionInserveExists'] = false;
$item['subscriptionInserveId'] = false;
$item['countInserve'] = 0;
$item['subscriptionInserveCompanyId'] = false;
}
}
unset($item);
// Make the subscriptions names look nice and dandy.
foreach ($subscriptionCounts as $key => &$item) {
// Set server name
$serverName = $row['server_hostname'] ?? $row['server_vm_host_name'] ?? 'Unknown';
// remove server_ prefix and _count suffix
$namePart = $key;
if (str_starts_with($key, 'server_') && str_ends_with($key, '_count')) {
$namePart = substr($key, 7, -6);
$namePart = ucfirst($namePart);
} // Handle keys with "."
elseif (strpos($key, '.') !== false) {
[$first, $second] = explode('.', $key, 2);
if ($first === $second || strtolower($second) === 'yes') {
$namePart = ucfirst($first);
} else {
$namePart = ucfirst($first) . ' - ' . $second;
}
} //Handle keys without . but with a space (expmale directadmin.Standard Discounted)
elseif (strpos($key, ' ') !== false) {
// explode on first .
$parts = explode('.', $key, 2);
if (count($parts) === 2) {
$namePart = ucfirst($parts[0]) . ' - ' . $parts[1];
} else {
// Cap first word before first space
$spacePos = strpos($key, ' ');
$first = ucfirst(substr($key, 0, $spacePos));
$rest = substr($key, $spacePos + 1);
$namePart = $first . ' - ' . $rest;
}
}
$item['subscriptionInserveName'] = $serverName . ' - ' . $namePart;
}
unset($item);
foreach ($subscriptionCounts as $key => $item) {
// if subscriptionInserveExists but the countInserve is null skip creation
if ($item['subscriptionInserveExists'] === false && (int)$item['countSentri'] === 0) {
continue;
}
// if subscriptionInserveExists is false create a new subscription
if ($item['subscriptionInserveExists'] === false) {
$payload = [
"cloud_distribution_id" => $item['md5'], #md5 hash based on the server_uuid from sentri and the subscription name (eg. server_cpu_count)
"cloud_subscription_id" => "sentri-servers", # Mark all the sentri-servers subscriptions so we can filter the subscriptions better
"name" => $item['subscriptionInserveName'],
"quantity" => $item['countSentri'],
"cloud_distribution_company_id" => $item['sentriCompanyId'], # this is generated by inserve (306 = digistate)
"status" => $item['SentriStatus'],
"period_type" => 0, # 0 = monthly, 1 = anual, 2 = one time cost
"start_date" => date('Y-m-d')
];
$this->createSubscription($payload);
continue;
}
// update the subscription if the countInserve and countSentri dont match
// Or when sentriCompanyId and subscriptionInserveCompanyId dont match
if ((
(int)$item['countInserve'] !== (int)$item['countSentri'] ||
(int)$item['sentriCompanyId'] !== (int)$item['subscriptionInserveCompanyId'] ||
(int)$item['SentriStatus'] !== (int)$item['subscriptionInserveStatus']
)
&& $item['subscriptionInserveExists'] !== false
) {
$payload = [
"quantity" => (int)$item['countSentri'],
"cloud_distribution_company_id" => (int)$item['sentriCompanyId'],
"name" => $item['subscriptionInserveName'],
"status" => $item['SentriStatus'],
"quantity" => $item['countSentri']
];
$this->updateSubscription($item['subscriptionInserveId'], $payload);
continue;
}
}
}
}
public function createSubscription($payload)
{
$url = $this->inserve_url . 'cloud-distribution-subscriptions';
$this->ch = curl_init($url);
# I need to make this pay load:
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_inserve extends API
{
private $inserve_url;
private $inserve_token;
public $inserve_source_uuid;
private $ch;
public $httpCode = false;
public $response = false;
private $cloudDistrubutor = 'digistate-servers';
public function setupConnection()
{
$query = "SELECT * FROM system_sources WHERE source_name = 'inserve'";
$result = $this->conn->query($query)->fetch_assoc();
$this->inserve_url = $result['source_url'];
$this->inserve_token = $result['source_auth_token'];
$this->inserve_source_uuid = $result['source_uuid'];
}
public function execCurl()
{
$this->response = curl_exec($this->ch);
$this->httpCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
curl_close($this->ch);
}
public function returnResponse()
{
$this->apiOutput($this->httpCode, json_decode($this->response, true));
}
public function authMe()
{
$this->ch = curl_init($this->inserve_url . 'auth/me');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function getLinkedCompanies()
{
$this->ch = curl_init($this->inserve_url . 'cloud-distributors/digistate-servers/companies');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function companies($page)
{
// Build array the way the API expects
$params = [
'b' => [
['orderBy' => ['name', 'ASC']],
['orderBy' => ['id', 'DESC']],
['with' => ['operator', 'country']],
['paginate' => 300],
],
'page' => $page
];
$query = http_build_query($params);
$this->ch = curl_init($this->inserve_url . 'companies?' . $query);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
return json_decode($this->response, true);
}
public function syncCompaniesFromSentri()
{
# First retrieve all the active companies to sync to the Inserver cloud distributor
$companies = [];
$sql = "SELECT company_source_id FROM companies WHERE company_state = 'active'";
$stmt = $this->conn->query($sql);
while ($row = $stmt->fetch_assoc()) {
$id = (int)$row['company_source_id'];
$companies[] = [
'cloud_distribution_id' => (string)$id,
'company_id' => $id
];
}
$url = $this->inserve_url . 'cloud-distributors/digistate-servers/companies';
$this->ch = curl_init($url);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($companies),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
public function getCloudSubscriptions()
{
$this->ch = curl_init($this->inserve_url . 'cloud-distribution-subscriptions/');
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json"
]
]);
$this->execCurl();
}
public function updateSubscription($subscriptionId = false, $payload = false)
{
$url = $this->inserve_url . 'cloud-distribution-subscriptions/' . $subscriptionId;
$this->ch = curl_init($url);
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
private function getAllTypes($type)
{
$allowedColumns = [
'server_licenses',
'server_backup'
];
if (!in_array($type, $allowedColumns, true)) {
throw new Exception('Invalid column name');
}
$query = "SELECT `$type` FROM servers";
$stmt = $this->prepareStatement($query);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$servers = [];
while ($row = $result->fetch_assoc()) {
array_push($servers, $row);
}
$allTypes = [];
foreach ($servers as $server) {
if (!empty($server[$type])) {
$types = json_decode($server[$type], true);
if (is_array($types)) {
foreach ($types as $item) {
foreach ($item as $key => $value) {
$allTypes[$key . '.' . $value] = 0;
}
}
}
}
}
return $allTypes;
}
private function calculateTotalDiskUsage($diskJson)
{
$disks = json_decode($diskJson, true);
$server_disks_count = 0;
if (is_array($disks)) {
foreach ($disks as $disk) {
$server_disks_count += $disk['disk_space'];
}
}
if (is_array($disks) && count($disks) > 0) {
$sizes = array_column($disks, 'disk_space');
$server_disks_count = array_sum($sizes);
}
return $server_disks_count;
}
private function buildCountObject(string $serverUuid, string $key): array
{
return [
'countSentri' => 0,
'countInserve' => 0,
'sentriCompanyId' => 0,
'SentriStatus' => 0,
'subscriptionInserveExists' => false,
'subscriptionInserveId' => false,
'subscriptionInserveCompanyId' => false,
'subscriptionInserveName' => false,
'subscriptionInserveStatus' => 0,
'md5' => md5($serverUuid . ':' . $key),
];
}
private function transformTypes(array $types, string $serverUuid): array
{
$result = [];
foreach ($types as $key => $value) {
$result[$key] = $this->buildCountObject($serverUuid, $key);
}
return $result;
}
private function buildCountArray($serverUuid)
{
$allBackupTypes = $this->getAllTypes('server_backup');
$allLicenseTypes = $this->getAllTypes('server_licenses');
$backupCounts = $this->transformTypes($allBackupTypes, $serverUuid);
$licenseCounts = $this->transformTypes($allLicenseTypes, $serverUuid);
return array_merge(
[
"server_CPU_count" => $this->buildCountObject($serverUuid, 'server_cpu_count'),
"server_Memory_count" => $this->buildCountObject($serverUuid, 'server_memory_count'),
"server_Disk_space_count" => $this->buildCountObject($serverUuid, 'server_disks_count'),
],
$licenseCounts,
$backupCounts
);
}
public function syncServerLicencesToInserve()
{
# Get all the linked companies
$this->getLinkedCompanies();
$allCompanies = json_decode($this->response, true);
$allCompaniesIds = array_column($allCompanies['matched'], 'id', 'company_id');
# first get the current subscriptions
$this->getCloudSubscriptions();
$allInserveSubscriptions = json_decode($this->response, true);
# Filter out all the none Sentri posted subscriptions based on the name for performance
$allInserveSubscriptions = array_filter($allInserveSubscriptions, function ($subscription) {
return isset($subscription['cloud_subscription_id']) && $subscription['cloud_subscription_id'] === 'sentri-servers';
});
# Build lookup of existing Inserve subscriptions by cloud_distribution_id
# this will be used later to lookup
$inserveLookup = [];
foreach ($allInserveSubscriptions as $subscription) {
if (!empty($subscription['cloud_distribution_id'])) {
$inserveLookup[$subscription['cloud_distribution_id']] = [
'id' => (int)$subscription['id'],
'quantity' => (int)$subscription['quantity'],
'status' => (int)$subscription['status'],
'cloud_distribution_company_id' => (int)$subscription['cloud_distribution_company_id'],
];
}
}
# get all the servers from Sentri
$sql = "SELECT * FROM servers INNER JOIN companies ON servers.company_uuid = companies.company_uuid WHERE company_state = 'active' AND server_state != 'new' AND server_state != 'disabled' ";
$stmt = $this->conn->query($sql);
while ($row = $stmt->fetch_assoc()) {
# Create a count of all the Subscriptions possible with every count on 0
$subscriptionCounts = $this->buildCountArray($row['server_uuid']);
$totalDiskSpace = $this->calculateTotalDiskUsage($row['server_disks']);
# Inserve status codes are:
# 0 = active, 1 = cancelled, 2 = pending, 3 = trial, 4 = on hold, 5 = removed
$statusMap = [
'active' => 0,
'trial' => 3,
'deleted' => 5,
];
// if no states matched there is something terrifying wrong, call the ambulance!
if (!isset($statusMap[$row['server_state']])) {
exit;
}
$sentriStatus = $statusMap[$row['server_state']];
# Set all the server resource counts from Sentri into the $subscriptionCounts
$subscriptionCounts['server_CPU_count']['countSentri'] = $row['server_cpu'];
$subscriptionCounts['server_Memory_count']['countSentri'] = (int)ceil($row['server_memory'] / 1024);
$subscriptionCounts['server_Disk_space_count']['countSentri'] = $totalDiskSpace;
$licenses = json_decode($row['server_licenses'], true);
foreach ($licenses as $license) {
foreach ($license as $key => $LicenseType) {
$subscriptionCounts[$key . '.' . $LicenseType]['countSentri']++;
}
}
$backups = json_decode($row['server_backup'], true);
foreach ($backups as $backup) {
foreach ($backup as $key => $BackupType) {
$subscriptionCounts[$key . '.' . $BackupType]['countSentri'] = $totalDiskSpace;
}
}
# Mark subscriptions that already exist in Inserve
foreach ($subscriptionCounts as $key => &$item) {
if (!is_array($item) || !isset($item['md5'])) {
continue;
}
$md5 = (string)$item['md5'];
if (isset($inserveLookup[$md5])) { # Subscription already exists in Inserve
$item['SentriStatus'] = $sentriStatus;
$item['sentriCompanyId'] = (int)$allCompaniesIds[$row['company_source_id']] ?? 0;
$item['subscriptionInserveExists'] = true;
$item['subscriptionInserveId'] = $inserveLookup[$item['md5']]['id'];
$item['countInserve'] = $inserveLookup[$item['md5']]['quantity'];
$item['subscriptionInserveCompanyId'] = $inserveLookup[$item['md5']]['cloud_distribution_company_id'];
$item['subscriptionInserveStatus'] = $inserveLookup[$item['md5']]['status'];
} else { # Subscription does not exists in Inserve
$item['sentriCompanyId'] = (int)$allCompaniesIds[$row['company_source_id']] ?? 0;
$item['subscriptionInserveExists'] = false;
$item['subscriptionInserveId'] = false;
$item['countInserve'] = 0;
$item['subscriptionInserveCompanyId'] = false;
}
}
unset($item);
// Make the subscriptions names look nice and dandy.
foreach ($subscriptionCounts as $key => &$item) {
// Set server name
$serverName = $row['server_hostname'] ?? $row['server_vm_host_name'] ?? 'Unknown';
// remove server_ prefix and _count suffix
$namePart = $key;
if (str_starts_with($key, 'server_') && str_ends_with($key, '_count')) {
$namePart = substr($key, 7, -6);
$namePart = ucfirst($namePart);
} // Handle keys with "."
elseif (strpos($key, '.') !== false) {
[$first, $second] = explode('.', $key, 2);
if ($first === $second || strtolower($second) === 'yes') {
$namePart = ucfirst($first);
} else {
$namePart = ucfirst($first) . ' - ' . $second;
}
} //Handle keys without . but with a space (expmale directadmin.Standard Discounted)
elseif (strpos($key, ' ') !== false) {
// explode on first .
$parts = explode('.', $key, 2);
if (count($parts) === 2) {
$namePart = ucfirst($parts[0]) . ' - ' . $parts[1];
} else {
// Cap first word before first space
$spacePos = strpos($key, ' ');
$first = ucfirst(substr($key, 0, $spacePos));
$rest = substr($key, $spacePos + 1);
$namePart = $first . ' - ' . $rest;
}
}
$item['subscriptionInserveName'] = $serverName . ' - ' . $namePart;
}
unset($item);
foreach ($subscriptionCounts as $key => $item) {
// if subscriptionInserveExists but the countInserve is null skip creation
if ($item['subscriptionInserveExists'] === false && (int)$item['countSentri'] === 0) {
continue;
}
// if subscriptionInserveExists is false create a new subscription
if ($item['subscriptionInserveExists'] === false) {
$payload = [
"cloud_distribution_id" => $item['md5'], #md5 hash based on the server_uuid from sentri and the subscription name (eg. server_cpu_count)
"cloud_subscription_id" => "sentri-servers", # Mark all the sentri-servers subscriptions so we can filter the subscriptions better
"name" => $item['subscriptionInserveName'],
"quantity" => $item['countSentri'],
"cloud_distribution_company_id" => $item['sentriCompanyId'], # this is generated by inserve (306 = digistate)
"status" => $item['SentriStatus'],
"period_type" => 0, # 0 = monthly, 1 = anual, 2 = one time cost
"start_date" => date('Y-m-d')
];
$this->createSubscription($payload);
continue;
}
// update the subscription if the countInserve and countSentri dont match
// Or when sentriCompanyId and subscriptionInserveCompanyId dont match
if ((
(int)$item['countInserve'] !== (int)$item['countSentri'] ||
(int)$item['sentriCompanyId'] !== (int)$item['subscriptionInserveCompanyId'] ||
(int)$item['SentriStatus'] !== (int)$item['subscriptionInserveStatus']
)
&& $item['subscriptionInserveExists'] !== false
) {
$payload = [
"quantity" => (int)$item['countSentri'],
"cloud_distribution_company_id" => (int)$item['sentriCompanyId'],
"name" => $item['subscriptionInserveName'],
"status" => $item['SentriStatus'],
"quantity" => $item['countSentri']
];
$this->updateSubscription($item['subscriptionInserveId'], $payload);
continue;
}
}
}
}
public function createSubscription($payload)
{
$url = $this->inserve_url . 'cloud-distribution-subscriptions';
$this->ch = curl_init($url);
# I need to make this pay load:
curl_setopt_array($this->ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
"X-Api-Key: $this->inserve_token",
"Accept: application/json",
"Content-Type: application/json"
],
]);
$this->execCurl();
}
}

View File

@@ -1,32 +1,32 @@
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_office_stompjes extends API
{
public function addStomp()
{
$query = "INSERT INTO office_stompjes (stomp_uuid, user_uuid, stomp_timestamp) VALUES (UUID(), ?, ?)";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('si', $this->data['user_uuid'], time());
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Stomp added.']);
}
public function deleteStomp()
{
$query = "DELETE FROM office_stompjes WHERE stomp_uuid = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('s', $this->data['stomp_uuid']);
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Stomp removed.']);
}
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_office_stompjes extends API
{
public function addStomp()
{
$query = "INSERT INTO office_stompjes (stomp_uuid, user_uuid, stomp_timestamp) VALUES (UUID(), ?, ?)";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('si', $this->data['user_uuid'], time());
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Stomp added.']);
}
public function deleteStomp()
{
$query = "DELETE FROM office_stompjes WHERE stomp_uuid = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('s', $this->data['stomp_uuid']);
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Stomp removed.']);
}
}

View File

@@ -1,277 +1,277 @@
<?php
namespace api\classes;
use api\classes\API;
use JsonException;
require_once 'API.php';
class API_servers extends API
{
public function getServers($returnBoolean = false)
{
list($query, $types, $params) = $this->buildDynamicQuery('servers');
$items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'Server');
return $items;
}
public function validateDiskData($disks)
{
foreach ($disks as $index => $disk) {
// Ensure $disk is an array
if (!is_array($disk)) {
$this->apiOutput(400, ['error' => "Disk entry is not an array"]);
}
$requiredFields = ['disk_name', 'disk_space', 'disk_used', 'disk_location'];
foreach ($requiredFields as $field) {
if (!array_key_exists($field, $disk)) {
$this->apiOutput(400, ['error' => "Missing required field '$field' in disk information"]);
}
switch ($field) {
case 'disk_used':
case 'disk_space':
$disks[$index][$field] = $this->validateSingleData($disk[$field], ['type' => 'float']);
break;
case 'disk_location':
case 'disk_name':
$disks[$index][$field] = $this->validateSingleData($disk[$field], ['type' => 'string']);
break;
}
}
}
try {
return json_encode($disks, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$this->apiOutput(400, ['error' => "Failed to encode disk data to JSON: " . $e->getMessage()]);
}
}
public function updateServer()
{
# if the server_state that is posted is 'deleted' check if the current server state is 'new' if so, delete it perm.
if ($this->data['server_state'] == 'deleted') {
$stmt = $GLOBALS['pdo']->prepare("SELECT server_state FROM servers WHERE server_vm_id = ? AND server_state = 'new'");
$stmt->execute([$this->data['server_vm_id']]);
if ($stmt->fetch()) {
$deleteStmt = $GLOBALS['pdo']->prepare("DELETE FROM servers WHERE server_vm_id = ? AND server_state = 'new'");
$deleteStmt->execute([$this->data['server_vm_id']]);
return;
}
}
if (isset($this->data['company_uuid'])) {
if (strlen($this->data['company_uuid']) == 0) {
$this->data['company_uuid'] = NULL;
}
}
$fields = [
'company_uuid',
'server_vm_id',
'server_vm_host_id',
'server_vm_host_name',
'server_power_state',
'server_state',
'server_hostname',
'server_os',
'server_cpu',
'server_memory',
'server_memory_demand',
'server_disks',
'server_ipv4',
'server_ipv6',
'server_vm_generation',
'server_vm_snapshot',
'server_licenses',
'server_backup',
'server_description'
];
$insertFields = ['server_uuid'];
$insertValues = ['UUID()'];
$bindParams = [];
foreach ($fields as $field) {
if (array_key_exists($field, $this->data)) {
$insertFields[] = $field;
$insertValues[] = ":$field";
$bindParams[":$field"] = $this->data[$field];
}
}
# Always include server_create_timestamp and server_modified_timestamp
$insertFields[] = 'server_create_timestamp';
$insertValues[] = ':server_create_timestamp';
$bindParams[':server_create_timestamp'] = time();
$insertFields[] = 'server_modified_timestamp';
$insertValues[] = ':server_modified_timestamp';
$bindParams[':server_modified_timestamp'] = time();
$query = "INSERT INTO servers (" . implode(',', $insertFields) . ")
VALUES (" . implode(',', $insertValues) . ")
ON DUPLICATE KEY UPDATE ";
# Build the ON DUPLICATE KEY UPDATE, only foor fields that exist
$updateParts = [];
foreach ($insertFields as $field) {
if (!in_array($field, ['server_create_timestamp', 'server_uuid'])) {
$updateParts[] = "$field = VALUES($field)";
}
}
$query .= implode(", ", $updateParts);
$stmt = $GLOBALS['pdo']->prepare($query);
if (!$stmt->execute($bindParams)) {
$this->apiOutput(400, ['error' => "Failed to insert server into database"]);
}
}
private function validateLicenseData($server_vm_id, $server_licenses)
{
$server_vm_id = $this->validateSingleData($server_vm_id, ['type' => 'string']);
$server_licenses_posted = $this->validateSingleData($server_licenses, ['type' => 'array']);
$query = "SELECT server_licenses FROM servers WHERE server_vm_id = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param("s", $server_vm_id);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$server_licenses_db = $result->fetch_assoc();
$server_licenses_db = $server_licenses_db['server_licenses'] ?? null;
$server_licenses_db_new = [];
if (!empty($server_licenses_db)) {
$decoded = json_decode($server_licenses_db, true);
if (is_array($decoded)) {
foreach ($decoded as $item) {
foreach ($item as $key => $value) {
$server_licenses_db_new[$key] = $value;
}
}
}
}
foreach ($server_licenses_posted as $item) {
foreach ($item as $rawKey => $value) {
$prefix = substr($rawKey, 0, 1);
$license = substr($rawKey, 1);
if ($prefix === '+') {
$server_licenses_db_new[$license] = $value;
}
if ($prefix === '-') {
unset($server_licenses_db_new[$license]);
}
}
}
$server_licenses_db_new_final = [];
foreach ($server_licenses_db_new as $key => $value) {
$server_licenses_db_new_final[] = [$key => $value];
}
return empty($server_licenses_db_new_final) ? '[]' : json_encode($server_licenses_db_new_final);
}
private function validateBackupData($server_vm_id, $server_backup)
{
$server_vm_id = $this->validateSingleData($server_vm_id, ['type' => 'string']);
$server_backup_posted = $this->validateSingleData($server_backup, ['type' => 'array']);
$query = "SELECT server_backup FROM servers WHERE server_vm_id = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param("s", $server_vm_id);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$server_backup_db = $result->fetch_assoc();
$server_backup_db = $server_backup_db['server_backup'] ?? null;
$server_backup_db_new = [];
if (!empty($server_backup_db)) {
$decoded = json_decode($server_backup_db, true);
if (is_array($decoded)) {
foreach ($decoded as $item) {
foreach ($item as $key => $value) {
$server_backup_db_new[$key] = $value;
}
}
}
}
foreach ($server_backup_posted as $item) {
foreach ($item as $rawKey => $value) {
$prefix = substr($rawKey, 0, 1);
$backup = substr($rawKey, 1);
if ($prefix === '+') {
$server_backup_db_new[$backup] = $value;
}
if ($prefix === '-') {
unset($server_backup_db_new[$backup]);
}
}
}
$server_backup_db_new_final = [];
foreach ($server_backup_db_new as $key => $value) {
$server_backup_db_new_final[] = [$key => $value];
}
return empty($server_backup_db_new_final) ? '[]' : json_encode($server_backup_db_new_final);
}
public function processServerData($server, $requiredFields, $optionalFields)
{
// since the disk data is sent as an array we need to check it seperatly from the other data validations
if (!empty($server['server_disks']) && is_array($server['server_disks'])) {
$server['server_disks'] = $this->validateDiskData($server['server_disks']);
} else {
unset($server['server_disks']);
}
if (!empty($server['server_licenses']) && is_array($server['server_licenses'])) {
$server['server_licenses'] = $this->validateLicenseData($server['server_vm_id'], $server['server_licenses']);
} else {
unset($server['server_licenses']);
}
if (!empty($server['server_backup']) && is_array($server['server_backup'])) {
$server['server_backup'] = $this->validateBackupData($server['server_vm_id'], $server['server_backup']);
} else {
unset($server['server_backup']);
}
foreach (['server_ipv4', 'server_ipv6'] as $key) {
if (!empty($server[$key]) && is_array($server[$key])) {
$server[$key] = json_encode($server[$key]);
} else {
unset($server[$key]);
}
}
$this->postedData = $server;
$this->validateData($requiredFields, $optionalFields);
$this->updateServer();
}
<?php
namespace api\classes;
use api\classes\API;
use JsonException;
require_once 'API.php';
class API_servers extends API
{
public function getServers($returnBoolean = false)
{
list($query, $types, $params) = $this->buildDynamicQuery('servers');
$items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'Server');
return $items;
}
public function validateDiskData($disks)
{
foreach ($disks as $index => $disk) {
// Ensure $disk is an array
if (!is_array($disk)) {
$this->apiOutput(400, ['error' => "Disk entry is not an array"]);
}
$requiredFields = ['disk_name', 'disk_space', 'disk_used', 'disk_location'];
foreach ($requiredFields as $field) {
if (!array_key_exists($field, $disk)) {
$this->apiOutput(400, ['error' => "Missing required field '$field' in disk information"]);
}
switch ($field) {
case 'disk_used':
case 'disk_space':
$disks[$index][$field] = $this->validateSingleData($disk[$field], ['type' => 'float']);
break;
case 'disk_location':
case 'disk_name':
$disks[$index][$field] = $this->validateSingleData($disk[$field], ['type' => 'string']);
break;
}
}
}
try {
return json_encode($disks, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$this->apiOutput(400, ['error' => "Failed to encode disk data to JSON: " . $e->getMessage()]);
}
}
public function updateServer()
{
# if the server_state that is posted is 'deleted' check if the current server state is 'new' if so, delete it perm.
if ($this->data['server_state'] == 'deleted') {
$stmt = $GLOBALS['pdo']->prepare("SELECT server_state FROM servers WHERE server_vm_id = ? AND server_state = 'new'");
$stmt->execute([$this->data['server_vm_id']]);
if ($stmt->fetch()) {
$deleteStmt = $GLOBALS['pdo']->prepare("DELETE FROM servers WHERE server_vm_id = ? AND server_state = 'new'");
$deleteStmt->execute([$this->data['server_vm_id']]);
return;
}
}
if (isset($this->data['company_uuid'])) {
if (strlen($this->data['company_uuid']) == 0) {
$this->data['company_uuid'] = NULL;
}
}
$fields = [
'company_uuid',
'server_vm_id',
'server_vm_host_id',
'server_vm_host_name',
'server_power_state',
'server_state',
'server_hostname',
'server_os',
'server_cpu',
'server_memory',
'server_memory_demand',
'server_disks',
'server_ipv4',
'server_ipv6',
'server_vm_generation',
'server_vm_snapshot',
'server_licenses',
'server_backup',
'server_description'
];
$insertFields = ['server_uuid'];
$insertValues = ['UUID()'];
$bindParams = [];
foreach ($fields as $field) {
if (array_key_exists($field, $this->data)) {
$insertFields[] = $field;
$insertValues[] = ":$field";
$bindParams[":$field"] = $this->data[$field];
}
}
# Always include server_create_timestamp and server_modified_timestamp
$insertFields[] = 'server_create_timestamp';
$insertValues[] = ':server_create_timestamp';
$bindParams[':server_create_timestamp'] = time();
$insertFields[] = 'server_modified_timestamp';
$insertValues[] = ':server_modified_timestamp';
$bindParams[':server_modified_timestamp'] = time();
$query = "INSERT INTO servers (" . implode(',', $insertFields) . ")
VALUES (" . implode(',', $insertValues) . ")
ON DUPLICATE KEY UPDATE ";
# Build the ON DUPLICATE KEY UPDATE, only foor fields that exist
$updateParts = [];
foreach ($insertFields as $field) {
if (!in_array($field, ['server_create_timestamp', 'server_uuid'])) {
$updateParts[] = "$field = VALUES($field)";
}
}
$query .= implode(", ", $updateParts);
$stmt = $GLOBALS['pdo']->prepare($query);
if (!$stmt->execute($bindParams)) {
$this->apiOutput(400, ['error' => "Failed to insert server into database"]);
}
}
private function validateLicenseData($server_vm_id, $server_licenses)
{
$server_vm_id = $this->validateSingleData($server_vm_id, ['type' => 'string']);
$server_licenses_posted = $this->validateSingleData($server_licenses, ['type' => 'array']);
$query = "SELECT server_licenses FROM servers WHERE server_vm_id = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param("s", $server_vm_id);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$server_licenses_db = $result->fetch_assoc();
$server_licenses_db = $server_licenses_db['server_licenses'] ?? null;
$server_licenses_db_new = [];
if (!empty($server_licenses_db)) {
$decoded = json_decode($server_licenses_db, true);
if (is_array($decoded)) {
foreach ($decoded as $item) {
foreach ($item as $key => $value) {
$server_licenses_db_new[$key] = $value;
}
}
}
}
foreach ($server_licenses_posted as $item) {
foreach ($item as $rawKey => $value) {
$prefix = substr($rawKey, 0, 1);
$license = substr($rawKey, 1);
if ($prefix === '+') {
$server_licenses_db_new[$license] = $value;
}
if ($prefix === '-') {
unset($server_licenses_db_new[$license]);
}
}
}
$server_licenses_db_new_final = [];
foreach ($server_licenses_db_new as $key => $value) {
$server_licenses_db_new_final[] = [$key => $value];
}
return empty($server_licenses_db_new_final) ? '[]' : json_encode($server_licenses_db_new_final);
}
private function validateBackupData($server_vm_id, $server_backup)
{
$server_vm_id = $this->validateSingleData($server_vm_id, ['type' => 'string']);
$server_backup_posted = $this->validateSingleData($server_backup, ['type' => 'array']);
$query = "SELECT server_backup FROM servers WHERE server_vm_id = ?";
$stmt = $this->prepareStatement($query);
$stmt->bind_param("s", $server_vm_id);
$this->executeStatement($stmt);
$result = $stmt->get_result();
$server_backup_db = $result->fetch_assoc();
$server_backup_db = $server_backup_db['server_backup'] ?? null;
$server_backup_db_new = [];
if (!empty($server_backup_db)) {
$decoded = json_decode($server_backup_db, true);
if (is_array($decoded)) {
foreach ($decoded as $item) {
foreach ($item as $key => $value) {
$server_backup_db_new[$key] = $value;
}
}
}
}
foreach ($server_backup_posted as $item) {
foreach ($item as $rawKey => $value) {
$prefix = substr($rawKey, 0, 1);
$backup = substr($rawKey, 1);
if ($prefix === '+') {
$server_backup_db_new[$backup] = $value;
}
if ($prefix === '-') {
unset($server_backup_db_new[$backup]);
}
}
}
$server_backup_db_new_final = [];
foreach ($server_backup_db_new as $key => $value) {
$server_backup_db_new_final[] = [$key => $value];
}
return empty($server_backup_db_new_final) ? '[]' : json_encode($server_backup_db_new_final);
}
public function processServerData($server, $requiredFields, $optionalFields)
{
// since the disk data is sent as an array we need to check it seperatly from the other data validations
if (!empty($server['server_disks']) && is_array($server['server_disks'])) {
$server['server_disks'] = $this->validateDiskData($server['server_disks']);
} else {
unset($server['server_disks']);
}
if (!empty($server['server_licenses']) && is_array($server['server_licenses'])) {
$server['server_licenses'] = $this->validateLicenseData($server['server_vm_id'], $server['server_licenses']);
} else {
unset($server['server_licenses']);
}
if (!empty($server['server_backup']) && is_array($server['server_backup'])) {
$server['server_backup'] = $this->validateBackupData($server['server_vm_id'], $server['server_backup']);
} else {
unset($server['server_backup']);
}
foreach (['server_ipv4', 'server_ipv6'] as $key) {
if (!empty($server[$key]) && is_array($server[$key])) {
$server[$key] = json_encode($server[$key]);
} else {
unset($server[$key]);
}
}
$this->postedData = $server;
$this->validateData($requiredFields, $optionalFields);
$this->updateServer();
}
}

View File

@@ -1,34 +1,34 @@
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_system_modules extends API
{
public function getModules($returnBoolean = false)
{
list($query, $types, $params) = $this->buildDynamicQuery('system_modules');
$items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'Permission');
return $items;
}
public function enableModule()
{
$module_uuid_enabled = ($this->data['module_enabled']) ? 0 : 1;
# Module 'system cannot be disabled'
$query = "UPDATE system_modules SET module_enabled = ? WHERE module_uuid = ? AND module_slugify != 'system'";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('is', $module_uuid_enabled, $this->data['module_uuid']);
if ($this->executeStatement($stmt)) {
$this->apiOutput(200, ['success' => 'Module ' . ($module_uuid_enabled ? 'enabled' : 'disabled') . ' successfully.']);
}
}
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_system_modules extends API
{
public function getModules($returnBoolean = false)
{
list($query, $types, $params) = $this->buildDynamicQuery('system_modules');
$items = $this->generalGetFunction($query, $types, $params, $returnBoolean, 'Permission');
return $items;
}
public function enableModule()
{
$module_uuid_enabled = ($this->data['module_enabled']) ? 0 : 1;
# Module 'system cannot be disabled'
$query = "UPDATE system_modules SET module_enabled = ? WHERE module_uuid = ? AND module_slugify != 'system'";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('is', $module_uuid_enabled, $this->data['module_uuid']);
if ($this->executeStatement($stmt)) {
$this->apiOutput(200, ['success' => 'Module ' . ($module_uuid_enabled ? 'enabled' : 'disabled') . ' successfully.']);
}
}
}

View File

@@ -1,26 +1,26 @@
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_system_sources extends API
{
public function inserveUpdate()
{
$query = "INSERT INTO system_sources (source_uuid, source_name, source_url, source_auth_username, source_auth_password, source_auth_token, source_create_timestamp, source_modified_timestamp)
VALUES (UUID(), ?, ?, '', '', ?, ?, NULL)
ON DUPLICATE KEY UPDATE
source_url = VALUES(source_url),
source_auth_token = VALUES(source_auth_token),
source_modified_timestamp = VALUES(source_create_timestamp)";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('sssi', $this->data['source_name'], $this->data['source_url'], $this->data['source_auth_token'], time());
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Information modified'], 'Information updated successfully.');
}
<?php
namespace api\classes;
use api\classes\API;
require_once 'API.php';
class API_system_sources extends API
{
public function inserveUpdate()
{
$query = "INSERT INTO system_sources (source_uuid, source_name, source_url, source_auth_username, source_auth_password, source_auth_token, source_create_timestamp, source_modified_timestamp)
VALUES (UUID(), ?, ?, '', '', ?, ?, NULL)
ON DUPLICATE KEY UPDATE
source_url = VALUES(source_url),
source_auth_token = VALUES(source_auth_token),
source_modified_timestamp = VALUES(source_create_timestamp)";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('sssi', $this->data['source_name'], $this->data['source_url'], $this->data['source_auth_token'], time());
$this->executeStatement($stmt);
$stmt->close();
$this->apiOutput(200, ['success' => 'Information modified'], 'Information updated successfully.');
}
}