From 1f52134bd7b73859b933146e283c089aa9ac47ef Mon Sep 17 00:00:00 2001 From: Sheldon Lee Date: Sun, 19 Nov 2023 15:28:39 +0800 Subject: [PATCH] Implement basic config file --- .gitignore | 1 + config.default.json | 6 ++++++ php/get.php | 44 ++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 config.default.json diff --git a/.gitignore b/.gitignore index 4c1f3b5..1eecd6e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ php/psalm.xml php/vendor php.log +config.json diff --git a/config.default.json b/config.default.json new file mode 100644 index 0000000..64d8bab --- /dev/null +++ b/config.default.json @@ -0,0 +1,6 @@ +{ + "ROOT_URL": "http://localhost/", + "ROOT_DIR": "/var/www/html/", + "IMG_DIR": "img/", + "THUMBNAIL_DIR": "thumbnails/" +} diff --git a/php/get.php b/php/get.php index e322614..3bdd069 100644 --- a/php/get.php +++ b/php/get.php @@ -3,10 +3,11 @@ include_once __DIR__ . "/logging.php"; include_once __DIR__ . "/cors.php"; cors(); -define("ROOT_URL", "http://localhost/"); -define("ROOT_DIR", "/var/www/localhost/"); -define("IMG_DIR", "img/"); -define("THUMBNAIL_DIR", "thumbnails/"); +$config_data = get_config(); +define("ROOT_URL", $config_data["ROOT_URL"]); +define("ROOT_DIR", $config_data["ROOT_DIR"]); +define("IMG_DIR", $config_data["IMG_DIR"]); +define("THUMBNAIL_DIR", $config_data["THUMBNAIL_DIR"]); define("THUMBNAIL_SCRIPT", __DIR__ . "/../scripts/resize-img"); define("IMAGE_EXTENSIONS", [ @@ -116,5 +117,40 @@ function is_image_file_type(string $filename): bool { return false; } +function get_config(): array { + $config_data = file_exists(__DIR__ . "/../config.json") ? + json_decode(file_get_contents(__DIR__ . "/../config.json"), true) : null; + + if (!is_valid_config_data($config_data)) { + log_error("Config invalid, falling back to default. Please check config.json"); + + $config_data = json_decode(file_get_contents(__DIR__ . "/../config.default.json"), true); + if (!is_valid_config_data($config_data)) + log_error("Default config invalid. Please check or create config.json"); + } + return $config_data; +} + + +function is_valid_config_data(?array $data): bool { + if (!$data) return false; + $keys = ["ROOT_URL", "ROOT_DIR", "IMG_DIR", "THUMBNAIL_DIR"]; + foreach ($keys as $key) { + if (!isset($data[$key])) return false; + switch ($key) { + case "ROOT_URL": + case "THUMBNAIL_DIR": + break; + case "ROOT_DIR": + if (!is_dir($data[$key])) return false; + break; + case "IMG_DIR": + if (!is_dir($data["ROOT_DIR"].$data[$key])) return false; + break; + } + } + return true; +} + main(); ?>