Refactor API structure: update internal handling, enhance input retrieval, and improve template loading

This commit is contained in:
marc-go committed 2026-10-10 15:05:24 +02:00
1 parent a33de15f0c
commit 9cb50d7d28
13 files changed
+181 -95

No files matched your search

+64 -13
View File
@@ -6,13 +6,17 @@ if ($debug) {
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);
}
debug_print_backtrace();
// API Main Library
class gbAPI {
public $username;
public $input;
private $db;
private $config;
private $internal;
private $response;
private function b64url_encode($data) {
return rtrim(strtr(base64_encode($data), "+/", "-_"), "=");
@@ -23,10 +27,13 @@ class gbAPI {
}
function __construct($authRequired, $internal) {
define("APP_PATH", __DIR__ . "/../");
if (!defined("APP_PATH")) {
define("APP_PATH", __DIR__ . "/../");
}
$this->internal = $internal;
if ($authRequired) {
if ($authRequired && !$internal) {
if (!$this->checkAuth()) {
$status = 401;
$data = [
@@ -39,6 +46,27 @@ class gbAPI {
}
}
function getInput() {
if (isset($this->input)) {
return $this->input;
}elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
$input = json_decode(file_get_contents("php://input"), true);
} catch (JsonException $error) {
$this->answer(400, [
"error" => "invalid_body",
"error_text" => "Can not read request body: " . $error
]);
}
return $input;
}else{
$this->answer(400, [
"error" => "false_request_method",
"error_text" => "Only POST allowed"
], true);
}
}
function getConfig() {
if (isset($this->config)) {
return $config;
@@ -136,27 +164,49 @@ class gbAPI {
}
function answer($status, $data = [], $error = false) {
http_response_code($status);
header("Content-Type: application/json; charset=UTF-8");
if ($error) {
$json = [];
$return = [];
$json["status"] = $status;
$return["status"] = $status;
foreach ($data as $key => $value) {
$json[$key] = $value;
$return[$key] = $value;
}
}else{
$json = [
$return = [
"status" => $status,
"data" => $data
];
}
// Check if request is internal or external
if ($this->internal) {
$this->response = $return;
}else{
http_response_code($status);
header("Content-Type: application/json; charset=UTF-8");
$return = json_encode($json);
die($return);
$return = json_encode($return);
die($return);
}
}
function getAnswer() {
if (!isset($this->response)) {
$error = [
"status" => 500,
"error" => "empty_return",
"error_text" => "API Returned nothing."
];
return $error;
}
return $this->response;
}
function getResponse() {
return $this->response;
}
function dbCommand($command, $expectResult, $stmtArgsRequired = false, $stmtArgs = []) {
@@ -192,6 +242,7 @@ class gbAPI {
$command = "SELECT name, value FROM settings WHERE name = :name";
$value = $this->dbCommand($command, true, true, [":name" => $key]);
return $value;
return $value[0]["value"];
}
}