[WIP] Loading of config .toml's

Deprecate load_config_lua, use MyAAC\Server\Lua\Loader::load instead
This commit is contained in:
slawkens
2026-04-19 16:05:22 +02:00
parent 6e603ad558
commit 1eba4cc509
17 changed files with 268 additions and 123 deletions

View File

@@ -104,6 +104,8 @@ const OTSERV_FIRST = OTSERV;
const OTSERV_LAST = OTSERV_06; const OTSERV_LAST = OTSERV_06;
const TFS_02 = 3; const TFS_02 = 3;
const TFS_03 = 4; const TFS_03 = 4;
const BLACKTEK_2 = 5;
const BLACKTEK = 6;
const TFS_FIRST = TFS_02; const TFS_FIRST = TFS_02;
const TFS_LAST = TFS_03; const TFS_LAST = TFS_03;

View File

@@ -1,4 +1,7 @@
<?php <?php
use MyAAC\Server\Lua\Loader;
defined('MYAAC') or die('Direct access not allowed!'); defined('MYAAC') or die('Direct access not allowed!');
if(!isset($_SESSION['var_server_path'])) { if(!isset($_SESSION['var_server_path'])) {
@@ -11,23 +14,35 @@ $config['server_path'] = $_SESSION['var_server_path'];
if($config['server_path'][strlen($config['server_path']) - 1] != '/') if($config['server_path'][strlen($config['server_path']) - 1] != '/')
$config['server_path'] .= '/'; $config['server_path'] .= '/';
if((!isset($error) || !$error) && !file_exists($config['server_path'] . 'config.lua')) { $configLuaExists = file_exists($config['server_path'] . 'config.lua');
$configTomlExists = file_exists($config['server_path'] . 'config/server.toml');
if((!isset($error) || !$error)
&& !$configLuaExists
&& !$configTomlExists) {
error($locale['step_database_error_config']); error($locale['step_database_error_config']);
$error = true; $error = true;
} }
if(!isset($error) || !$error) { if (!isset($error) || !$error) {
$config['lua'] = load_config_lua($config['server_path'] . 'config.lua'); if($configLuaExists) {
if(isset($config['lua']['sqlType'])) // tfs 0.3 $config['lua'] = Loader::load($config['server_path'] . 'config.lua');
$config['database_type'] = $config['lua']['sqlType']; if (isset($config['lua']['sqlType'])) // tfs 0.3
else if(isset($config['lua']['mysqlHost'])) // tfs 0.2/1.0 $config['database_type'] = $config['lua']['sqlType'];
$config['database_type'] = 'mysql'; elseif (isset($config['lua']['mysqlHost'])) // tfs 0.2/1.0
else if(isset($config['lua']['database_type'])) // otserv $config['database_type'] = 'mysql';
$config['database_type'] = $config['lua']['database_type']; elseif (isset($config['lua']['database_type'])) // otserv
else if(isset($config['lua']['sql_type'])) // otserv $config['database_type'] = $config['lua']['database_type'];
$config['database_type'] = $config['lua']['sql_type']; elseif (isset($config['lua']['sql_type'])) // otserv
else { $config['database_type'] = $config['lua']['sql_type'];
$config['database_type'] = ''; else {
$config['database_type'] = '';
}
}
elseif ($configTomlExists) {
$tomlConfig = new MyAAC\Server\TOML\Config();
$tomlConfig->load();
$config['server'] = $tomlConfig->get();
$config['database_type'] = (isset($config['server']['database']['mysql']) ? 'mysql' : '');
} }
$config['database_type'] = strtolower($config['database_type']); $config['database_type'] = strtolower($config['database_type']);

View File

@@ -1,5 +1,6 @@
<?php <?php
use MyAAC\Server\Config;
use Twig\Environment as Twig_Environment; use Twig\Environment as Twig_Environment;
use Twig\Loader\FilesystemLoader as Twig_FilesystemLoader; use Twig\Loader\FilesystemLoader as Twig_FilesystemLoader;
@@ -83,7 +84,7 @@ if($step == 'database') {
$config['server_path'] .= '/'; $config['server_path'] .= '/';
} }
if(!file_exists($config['server_path'] . 'config.lua')) { if(!Config::exists()) {
$errors[] = $locale['step_database_error_config']; $errors[] = $locale['step_database_error_config'];
break; break;
} }

View File

@@ -9,6 +9,8 @@
*/ */
defined('MYAAC') or die('Direct access not allowed!'); defined('MYAAC') or die('Direct access not allowed!');
use MyAAC\Server\Lua\Loader;
class Validator extends \MyAAC\Validator {} class Validator extends \MyAAC\Validator {}
function check_name($name, &$errors = '') { function check_name($name, &$errors = '') {
@@ -128,3 +130,23 @@ function Mount_parseNode($node): array
$type = $node->getAttribute('type'); $type = $node->getAttribute('type');
return array('id' => $id, 'clientid' => $clientid, 'name' => $name, 'speed' => $speed, 'premium' => $premium, 'type' => $type); return array('id' => $id, 'clientid' => $clientid, 'name' => $name, 'speed' => $speed, 'premium' => $premium, 'type' => $type);
} }
function load_config_lua(string $file): array
{
$result = Loader::load($file);
if ($result === false) {
log_append('error.log', '[load_config_file] Fatal error: Cannot load config.lua (' . $file . ').');
throw new \RuntimeException('ERROR: Cannot find ' . $file . ' file.');
}
return $result;
}
function configLua($key) {
global $config;
if (is_array($key)) {
return $config['lua'][$key[0]] = $key[1];
}
return @$config['lua'][$key];
}

View File

@@ -18,6 +18,19 @@ if (!isset($config['database_overwrite'])) {
if(!$config['database_overwrite'] && !isset($config['database_user'][0], $config['database_password'][0], $config['database_name'][0])) if(!$config['database_overwrite'] && !isset($config['database_user'][0], $config['database_password'][0], $config['database_name'][0]))
{ {
if (isset($config['server']['database']['mysql'])) { // BlackTek
$config['otserv_version'] = BLACKTEK;
$config['database_type'] = 'mysql';
$config['database_host'] = $config['server']['database']['mysql']['host'];
$config['database_port'] = $config['server']['database']['mysql']['port'];
$config['database_user'] = $config['server']['database']['mysql']['user'];
$config['database_password'] = $config['server']['database']['mysql']['pass'];
$config['database_name'] = $config['server']['database']['mysql']['database'];
if(!isset($config['database_socket'][0]) && !empty(trim($config['server']['database']['mysql']['socket']))) {
$config['database_socket'] = trim($config['server']['database']['mysql']['socket']);
}
$config['database_encryption'] = 'sha1';
}
if(isset($config['lua']['sqlType'])) {// tfs 0.3 if(isset($config['lua']['sqlType'])) {// tfs 0.3
if(isset($config['lua']['mysqlHost'])) {// tfs 0.2 if(isset($config['lua']['mysqlHost'])) {// tfs 0.2
$config['otserv_version'] = TFS_02; $config['otserv_version'] = TFS_02;
@@ -94,7 +107,6 @@ if(!isset($config['database_socket'])) {
$config['database_socket'] = ''; $config['database_socket'] = '';
} }
try { try {
$ots->connect(array( $ots->connect(array(
'host' => $config['database_host'], 'host' => $config['database_host'],

View File

@@ -987,85 +987,6 @@ function log_append($file, $str, array $params = [])
fclose($f); fclose($f);
} }
function load_config_lua($filename)
{
global $config;
$config_file = $filename;
if(!@file_exists($config_file))
{
log_append('error.log', '[load_config_file] Fatal error: Cannot load config.lua (' . $filename . ').');
throw new RuntimeException('ERROR: Cannot find ' . $filename . ' file.');
}
$result = array();
$config_string = str_replace(array("\r\n", "\r"), "\n", file_get_contents($filename));
$lines = explode("\n", $config_string);
if(count($lines) > 0) {
foreach($lines as $ln => $line)
{
$line = trim($line);
if(isset($line[0]) && ($line[0] === '{' || $line[0] === '}')) {
// arrays are not supported yet
// just ignore the error
continue;
}
$tmp_exp = explode('=', $line, 2);
if(str_contains($line, 'dofile')) {
$delimiter = '"';
if(!str_contains($line, $delimiter)) {
$delimiter = "'";
}
$tmp = explode($delimiter, $line);
$result = array_merge($result, load_config_lua($config['server_path'] . $tmp[1]));
}
else if(count($tmp_exp) >= 2) {
$key = trim($tmp_exp[0]);
if(!str_starts_with($key, '--')) {
$value = trim($tmp_exp[1]);
if(str_contains($value, '--')) {// found some deep comment
$value = preg_replace('/--.*$/i', '', $value);
}
if(is_numeric($value))
$result[$key] = (float) $value;
elseif(in_array(@$value[0], array("'", '"')) && in_array(@$value[strlen($value) - 1], array("'", '"')))
$result[$key] = substr(substr($value, 1), 0, -1);
elseif(in_array($value, array('true', 'false')))
$result[$key] = $value === 'true';
elseif(@$value[0] === '{') {
// arrays are not supported yet
// just ignore the error
continue;
}
else
{
foreach($result as $tmp_key => $tmp_value) { // load values defined by other keys, like: dailyFragsToBlackSkull = dailyFragsToRedSkull
$value = str_replace($tmp_key, $tmp_value, $value);
}
try {
$ret = eval("return $value;");
}
catch (Throwable $e) {
throw new RuntimeException('ERROR: Loading config.lua file. Line: ' . ($ln + 1) . ' - Unable to parse value "' . $value . '" - ' . $e->getMessage());
}
if((string) $ret == '' && trim($value) !== '""') {
throw new RuntimeException('ERROR: Loading config.lua file. Line ' . ($ln + 1) . ' is not valid [key: ' . $key . ']');
}
$result[$key] = $ret;
}
}
}
}
}
return array_merge($result, $config['lua'] ?? []);
}
function str_replace_first($search,$replace, $subject) { function str_replace_first($search,$replace, $subject) {
$pos = strpos($subject, $search); $pos = strpos($subject, $search);
if ($pos !== false) { if ($pos !== false) {
@@ -1325,15 +1246,6 @@ function config($key) {
return @$config[$key]; return @$config[$key];
} }
function configLua($key) {
global $config;
if (is_array($key)) {
return $config['lua'][$key[0]] = $key[1];
}
return @$config['lua'][$key];
}
function setting($key) function setting($key)
{ {
$settings = Settings::getInstance(); $settings = Settings::getInstance();

View File

@@ -14,6 +14,7 @@ use MyAAC\CsrfToken;
use MyAAC\Hooks; use MyAAC\Hooks;
use MyAAC\Plugins; use MyAAC\Plugins;
use MyAAC\Models\Town; use MyAAC\Models\Town;
use MyAAC\Server\Config;
use MyAAC\Server\Vocations; use MyAAC\Server\Vocations;
use MyAAC\Settings; use MyAAC\Settings;
@@ -90,28 +91,20 @@ foreach($_REQUEST as $var => $value) {
} }
// load otserv config file // load otserv config file
$config_lua_reload = true;
if($cache->enabled()) { if($cache->enabled()) {
$tmp = null; $tmp = null;
if($cache->fetch('server_path', $tmp) && $tmp == $config['server_path']) { if(!$cache->fetch('server_path', $tmp) || $tmp != config('server_path')) {
$tmp = null; $cache->delete('config_server');
if($cache->fetch('config_lua', $tmp) && $tmp) {
$config['lua'] = unserialize($tmp);
$config_lua_reload = false;
}
} }
} }
if($config_lua_reload) { if (empty($config['server'])) {
$config['lua'] = load_config_lua($config['server_path'] . 'config.lua'); $config['server'] = $config['lua'] = Config::get();
// cache config
if($cache->enabled()) { if($cache->enabled()) {
$cache->set('config_lua', serialize($config['lua']), 2 * 60); $cache->set('server_path', config('server_path'), 10 * 60);
$cache->set('server_path', $config['server_path'], 10 * 60);
} }
} }
unset($tmp);
if(isset($config['lua']['servername'])) if(isset($config['lua']['servername']))
$config['lua']['serverName'] = $config['lua']['servername']; $config['lua']['serverName'] = $config['lua']['servername'];

View File

@@ -67,7 +67,7 @@ $locale['step_database'] = 'Schema importieren';
$locale['step_database_title'] = 'MySQL schema importieren'; $locale['step_database_title'] = 'MySQL schema importieren';
$locale['step_database_importing'] = 'Ihre Datenbank ist MySQL. Datenbankname ist: "$DATABASE_NAME$". Schema wird jetzt importiert...'; $locale['step_database_importing'] = 'Ihre Datenbank ist MySQL. Datenbankname ist: "$DATABASE_NAME$". Schema wird jetzt importiert...';
$locale['step_database_error_path'] = 'Bitte geben Sie den Serverpfad an.'; $locale['step_database_error_path'] = 'Bitte geben Sie den Serverpfad an.';
$locale['step_database_error_config'] = 'Datei config.lua kann nicht gefunden werden. Ist der Serverpfad korrekt? Gehen Sie zurück und überprüfen Sie noch einmal.'; $locale['step_database_error_config'] = 'Datei config.lua oder config/server.toml kann nicht gefunden werden. Ist der Serverpfad korrekt? Gehen Sie zurück und überprüfen Sie noch einmal.';
$locale['step_database_error_database_empty'] = 'Der Datenbanktyp kann nicht aus config.lua ermittelt werden. Ihr OTS wird von diesem AAC nicht unterstützt.'; $locale['step_database_error_database_empty'] = 'Der Datenbanktyp kann nicht aus config.lua ermittelt werden. Ihr OTS wird von diesem AAC nicht unterstützt.';
$locale['step_database_error_only_mysql'] = 'Dieser AAC unterstützt nur MySQL. Aus Ihrer Konfigurationsdatei scheint Ihr OTS die Datenbank $DATABASE_TYPE$ zu verwenden. Bitte ändern Sie Ihre Datenbank in MySQL und folgen Sie dann der Installation erneut.'; $locale['step_database_error_only_mysql'] = 'Dieser AAC unterstützt nur MySQL. Aus Ihrer Konfigurationsdatei scheint Ihr OTS die Datenbank $DATABASE_TYPE$ zu verwenden. Bitte ändern Sie Ihre Datenbank in MySQL und folgen Sie dann der Installation erneut.';
$locale['step_database_error_table'] = 'Die Tabelle $TABLE$ existiert nicht. Bitte importieren Sie zuerst Ihr OTS-Datenbankschema.'; $locale['step_database_error_table'] = 'Die Tabelle $TABLE$ existiert nicht. Bitte importieren Sie zuerst Ihr OTS-Datenbankschema.';

View File

@@ -72,7 +72,7 @@ $locale['step_database_title'] = 'Import MySQL schema';
$locale['step_database_importing'] = 'Your database is MySQL. Database name is: "$DATABASE_NAME$". Importing schema now...'; $locale['step_database_importing'] = 'Your database is MySQL. Database name is: "$DATABASE_NAME$". Importing schema now...';
$locale['step_database_config_saved'] = 'Local configuration has been saved into file: config.local.php'; $locale['step_database_config_saved'] = 'Local configuration has been saved into file: config.local.php';
$locale['step_database_error_path'] = 'Please specify server path.'; $locale['step_database_error_path'] = 'Please specify server path.';
$locale['step_database_error_config'] = 'Cannot find config.lua file. Is your server path correct? Go back and check again.'; $locale['step_database_error_config'] = 'Cannot find config.lua or config/server.toml file. Is your server path correct? Go back and check again.';
$locale['step_database_error_database_empty'] = 'Cannot determine database type from config.lua. Your OTS is unsupported by this AAC.'; $locale['step_database_error_database_empty'] = 'Cannot determine database type from config.lua. Your OTS is unsupported by this AAC.';
$locale['step_database_error_only_mysql'] = 'This AAC supports only MySQL. From your config file it seems that your OTS is using: $DATABASE_TYPE$ database. Please change your database to MySQL and then follow the installation again.'; $locale['step_database_error_only_mysql'] = 'This AAC supports only MySQL. From your config file it seems that your OTS is using: $DATABASE_TYPE$ database. Please change your database to MySQL and then follow the installation again.';
$locale['step_database_error_table'] = 'Table $TABLE$ doesn\'t exist. Please import your OTS database schema first.'; $locale['step_database_error_table'] = 'Table $TABLE$ doesn\'t exist. Please import your OTS database schema first.';

View File

@@ -71,7 +71,7 @@ $locale['step_database_title'] = 'Baza MySQL';
$locale['step_database_importing'] = 'Twoja baza to MySQL. Nazwa bazy danych to: "$DATABASE_NAME$". Importowanie schematu...'; $locale['step_database_importing'] = 'Twoja baza to MySQL. Nazwa bazy danych to: "$DATABASE_NAME$". Importowanie schematu...';
$locale['step_database_config_saved'] = 'Lokalna konfiguracja została zapisana do pliku: config.local.php'; $locale['step_database_config_saved'] = 'Lokalna konfiguracja została zapisana do pliku: config.local.php';
$locale['step_database_error_path'] = 'Proszę podać ścieżkę do serwera.'; $locale['step_database_error_path'] = 'Proszę podać ścieżkę do serwera.';
$locale['step_database_error_config'] = 'Nie można znaleźć pliku config.lua. Czy ścieżka do katalogu serwera jest poprawna? Wróć się i sprawdź ponownie.'; $locale['step_database_error_config'] = 'Nie można znaleźć pliku config.lua lub config/server.toml. Czy ścieżka do katalogu serwera jest poprawna? Wróć się i sprawdź ponownie.';
$locale['step_database_error_database_empty'] = 'Nie można wykryć typu bazy danych z pliku config.lua. Prawdopodobnie Twój OTS nie jest wspierany przez ten AAC.'; $locale['step_database_error_database_empty'] = 'Nie można wykryć typu bazy danych z pliku config.lua. Prawdopodobnie Twój OTS nie jest wspierany przez ten AAC.';
$locale['step_database_error_only_mysql'] = 'Ten AAC wspiera tylko bazy danych MySQL. Z Twojego pliku config wynika, że Twój serwera używa bazy: $DATABASE_TYPE$. Proszę zmienić typ bazy na MySQL i ponownie przystąpić do instalacji.'; $locale['step_database_error_only_mysql'] = 'Ten AAC wspiera tylko bazy danych MySQL. Z Twojego pliku config wynika, że Twój serwera używa bazy: $DATABASE_TYPE$. Proszę zmienić typ bazy na MySQL i ponownie przystąpić do instalacji.';
$locale['step_database_error_table'] = 'Tabela $TABLE$ nie istnieje. Proszę najpierw zaimportować schemat bazy danych serwera OTS.'; $locale['step_database_error_table'] = 'Tabela $TABLE$ nie istnieje. Proszę najpierw zaimportować schemat bazy danych serwera OTS.';

View File

@@ -61,7 +61,7 @@ $locale['step_database'] = 'Importar schema';
$locale['step_database_title'] = 'Importar MySQL schema'; $locale['step_database_title'] = 'Importar MySQL schema';
$locale['step_database_importing'] = 'Seu banco de dados é o MySQL. O nome do banco de dados é: "$DATABASE_NAME$". Importando schema agora...'; $locale['step_database_importing'] = 'Seu banco de dados é o MySQL. O nome do banco de dados é: "$DATABASE_NAME$". Importando schema agora...';
$locale['step_database_error_path'] = 'Por favor, especifique o caminho da pasta do servidor.'; $locale['step_database_error_path'] = 'Por favor, especifique o caminho da pasta do servidor.';
$locale['step_database_error_config'] = 'Não é possível encontrar o arquivo config.lua. O caminho da pasta do seu servidor está correto? Volte e verifique novamente.'; $locale['step_database_error_config'] = 'Não é possível encontrar o arquivo config.lua ou config/server.toml. O caminho da pasta do seu servidor está correto? Volte e verifique novamente.';
$locale['step_database_error_database_empty'] = 'Não é possível determinar o tipo de banco de dados a partir do config.lua. Seu OTS não é suportado por este AAC.'; $locale['step_database_error_database_empty'] = 'Não é possível determinar o tipo de banco de dados a partir do config.lua. Seu OTS não é suportado por este AAC.';
$locale['step_database_error_only_mysql'] = 'Este AAC suporta apenas o MySQL. A partir do seu arquivo de configuração, parece que o seu OTS está usando: $DATABASE_TYPE$ database. Por favor, mude seu banco de dados para o MySQL e siga a instalação novamente.'; $locale['step_database_error_only_mysql'] = 'Este AAC suporta apenas o MySQL. A partir do seu arquivo de configuração, parece que o seu OTS está usando: $DATABASE_TYPE$ database. Por favor, mude seu banco de dados para o MySQL e siga a instalação novamente.';
$locale['step_database_error_table'] = 'A tabela $TABLE$ não existe. Por favor, importe seu schema de banco de dados OTS primeiro.'; $locale['step_database_error_table'] = 'A tabela $TABLE$ não existe. Por favor, importe seu schema de banco de dados OTS primeiro.';

View File

@@ -12,6 +12,7 @@
*/ */
use MyAAC\Cache; use MyAAC\Cache;
use MyAAC\Server\Config;
use MyAAC\Settings; use MyAAC\Settings;
$templates = Cache::remember('templates', 5 * 60, function () { $templates = Cache::remember('templates', 5 * 60, function () {
@@ -1802,8 +1803,8 @@ Sent by MyAAC,<br/>
// test config.lua existence // test config.lua existence
// if fail - revert the setting and inform the user // if fail - revert the setting and inform the user
if (!file_exists($server_path . 'config.lua')) { if (!Config::exists()) {
error('Server Path is invalid - cannot find config.lua in the directory. Setting have been reverted.'); error('Server Path is invalid - cannot find config.lua or config/server.toml in the directory. Setting have been reverted.');
$configToSave['server_path'] = $configOriginal['server_path']; $configToSave['server_path'] = $configOriginal['server_path'];
} }

View File

@@ -2,6 +2,7 @@
namespace MyAAC\Commands; namespace MyAAC\Commands;
use MyAAC\Server\Config;
use POT; use POT;
trait Env trait Env
@@ -21,7 +22,7 @@ trait Env
if($config['server_path'][strlen($config['server_path']) - 1] !== '/') if($config['server_path'][strlen($config['server_path']) - 1] !== '/')
$config['server_path'] .= '/'; $config['server_path'] .= '/';
$config['lua'] = load_config_lua($config['server_path'] . 'config.lua'); $config['server'] = $config['lua'] = Config::get();
// POT // POT
require_once SYSTEM . 'libs/pot/OTS.php'; require_once SYSTEM . 'libs/pot/OTS.php';

View File

@@ -0,0 +1,28 @@
<?php
namespace MyAAC\Server;
use MyAAC\Cache\Cache;
class Config
{
public static function get()
{
return Cache::remember('config_server', 10 * 60, function () {
if (file_exists(config('server_path') . Lua\Config::FILE)) {
$config = new Lua\Config();
}
else {
$config = new TOML\Config();
}
$config->load();
return $config->get();
});
}
public static function exists(): bool {
return file_exists(config('server_path') . Lua\Config::FILE) || file_exists(config('server_path') . 'config/server.toml');
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace MyAAC\Server\Lua;
class Config
{
const FILE = 'config.lua';
private array $config = [];
public function load(): void
{
$file = config('server_path') . self::FILE;
$this->config = Loader::load($file);
if($this->config === false) {
log_append('error.log', '[Config] Fatal error: Cannot load config.lua (' . $file . ').');
throw new \RuntimeException('ERROR: Cannot find ' . $file . ' file.');
}
}
public function get(): array {
return $this->config;
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace MyAAC\Server\Lua;
class Loader
{
public static function load($file): bool|array
{
if(!@file_exists($file)){
return false;
}
$result = [];
$config_string = str_replace(array("\r\n", "\r"), "\n", file_get_contents($file));
$lines = explode("\n", $config_string);
if(count($lines) > 0) {
foreach($lines as $ln => $line) {
$line = trim($line);
if(isset($line[0]) && ($line[0] === '{' || $line[0] === '}')) {
// arrays are not supported yet
// just ignore the error
continue;
}
$tmp_exp = explode('=', $line, 2);
if(str_contains($line, 'dofile')) {
$delimiter = '"';
if(!str_contains($line, $delimiter)) {
$delimiter = "'";
}
$tmp = explode($delimiter, $line);
$result = array_merge($result, self::load(config('server_path') . $tmp[1]));
}
else if(count($tmp_exp) >= 2) {
$key = trim($tmp_exp[0]);
if(!str_starts_with($key, '--')) {
$value = trim($tmp_exp[1]);
if(str_contains($value, '--')) {// found some deep comment
$value = preg_replace('/--.*$/i', '', $value);
}
if(is_numeric($value))
$result[$key] = (float) $value;
elseif(in_array(@$value[0], array("'", '"')) && in_array(@$value[strlen($value) - 1], array("'", '"')))
$result[$key] = substr(substr($value, 1), 0, -1);
elseif(in_array($value, array('true', 'false')))
$result[$key] = $value === 'true';
elseif(@$value[0] === '{') {
// arrays are not supported yet
// just ignore the error
continue;
}
else
{
foreach($result as $tmp_key => $tmp_value) { // load values defined by other keys, like: dailyFragsToBlackSkull = dailyFragsToRedSkull
$value = str_replace($tmp_key, $tmp_value, $value);
}
try {
$ret = eval("return $value;");
}
catch (\Throwable $e) {
throw new \RuntimeException('ERROR: Loading config.lua file. Line: ' . ($ln + 1) . ' - Unable to parse value "' . $value . '" - ' . $e->getMessage());
}
if((string) $ret == '' && trim($value) !== '""') {
throw new \RuntimeException('ERROR: Loading config.lua file. Line ' . ($ln + 1) . ' is not valid [key: ' . $key . ']');
}
$result[$key] = $ret;
}
}
}
}
}
return $result;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace MyAAC\Server\TOML;
use Devium\Toml\Toml;
use RuntimeException;
class Config
{
private array $config = [];
public function load(): void
{
$path = config('server_path') . 'config/';
$files = glob($path . '*.toml');
// filter files we don't need
$ignore = ['account_manager', 'mounts', 'object_pools', 'outfits', 'scripts'];
$files = array_filter($files, function ($file) use ($ignore) {
foreach ($ignore as $item) {
if (str_contains($file, $item)) {
return false;
}
}
return true;
});
foreach ($files as $file) {
$key = basename($file, '.toml');
$toml = file_get_contents($file);
try {
$this->config[$key] = Toml::decode($toml, asArray: true);
}
catch (\Exception $e) {
throw new RuntimeException("Error: Cannot load config/$key.toml. More info in system/logs/error.log file.");
log_append('error.log', "[" . __CLASS__ . "] Fatal error: Cannot load config/$key.toml - $file. Error: " . $e->getMessage());
return;
}
}
$this->config['serverName'] = $this->config['server']['identity']['name'] ?? 'Unknown';
$this->config['freePremium'] = $this->config['server']['accounts']['free_premium'] ?? false;
$this->config['ip'] = $this->config['server']['network']['ip'] ?? '127.0.0.1';
$this->config['worldType'] = $this->config['server']['world']['type'] ?? 'unknown';
}
public function get(): array {
return $this->config;
}
}