From 1eba4cc5094434d7edde026005c7eac718d281a9 Mon Sep 17 00:00:00 2001 From: slawkens Date: Sun, 19 Apr 2026 16:05:22 +0200 Subject: [PATCH] [WIP] Loading of config .toml's Deprecate load_config_lua, use MyAAC\Server\Lua\Loader::load instead --- common.php | 2 + install/includes/config.php | 41 +++++++++----- install/index.php | 3 +- system/compat/base.php | 22 ++++++++ system/database.php | 14 ++++- system/functions.php | 88 ------------------------------- system/init.php | 19 +++---- system/locale/de/install.php | 2 +- system/locale/en/install.php | 2 +- system/locale/pl/install.php | 2 +- system/locale/pt_br/install.php | 2 +- system/settings.php | 5 +- system/src/Commands/Env.php | 3 +- system/src/Server/Config.php | 28 ++++++++++ system/src/Server/Lua/Config.php | 25 +++++++++ system/src/Server/Lua/Loader.php | 79 +++++++++++++++++++++++++++ system/src/Server/TOML/Config.php | 54 +++++++++++++++++++ 17 files changed, 268 insertions(+), 123 deletions(-) create mode 100644 system/src/Server/Config.php create mode 100644 system/src/Server/Lua/Config.php create mode 100644 system/src/Server/Lua/Loader.php create mode 100644 system/src/Server/TOML/Config.php diff --git a/common.php b/common.php index af48a960..847610ef 100644 --- a/common.php +++ b/common.php @@ -104,6 +104,8 @@ const OTSERV_FIRST = OTSERV; const OTSERV_LAST = OTSERV_06; const TFS_02 = 3; const TFS_03 = 4; +const BLACKTEK_2 = 5; +const BLACKTEK = 6; const TFS_FIRST = TFS_02; const TFS_LAST = TFS_03; diff --git a/install/includes/config.php b/install/includes/config.php index bc6759b3..59033f08 100644 --- a/install/includes/config.php +++ b/install/includes/config.php @@ -1,4 +1,7 @@ load(); + $config['server'] = $tomlConfig->get(); + $config['database_type'] = (isset($config['server']['database']['mysql']) ? 'mysql' : ''); } $config['database_type'] = strtolower($config['database_type']); diff --git a/install/index.php b/install/index.php index c449cf09..0b8eb7e2 100644 --- a/install/index.php +++ b/install/index.php @@ -1,5 +1,6 @@ getAttribute('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]; +} diff --git a/system/database.php b/system/database.php index 8fa8f869..17effd64 100644 --- a/system/database.php +++ b/system/database.php @@ -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 (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']['mysqlHost'])) {// tfs 0.2 $config['otserv_version'] = TFS_02; @@ -94,7 +107,6 @@ if(!isset($config['database_socket'])) { $config['database_socket'] = ''; } - try { $ots->connect(array( 'host' => $config['database_host'], diff --git a/system/functions.php b/system/functions.php index 2a933905..ec46b93b 100644 --- a/system/functions.php +++ b/system/functions.php @@ -987,85 +987,6 @@ function log_append($file, $str, array $params = []) 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) { $pos = strpos($subject, $search); if ($pos !== false) { @@ -1325,15 +1246,6 @@ function 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) { $settings = Settings::getInstance(); diff --git a/system/init.php b/system/init.php index 74a74706..ad43039e 100644 --- a/system/init.php +++ b/system/init.php @@ -14,6 +14,7 @@ use MyAAC\CsrfToken; use MyAAC\Hooks; use MyAAC\Plugins; use MyAAC\Models\Town; +use MyAAC\Server\Config; use MyAAC\Server\Vocations; use MyAAC\Settings; @@ -90,28 +91,20 @@ foreach($_REQUEST as $var => $value) { } // load otserv config file -$config_lua_reload = true; if($cache->enabled()) { $tmp = null; - if($cache->fetch('server_path', $tmp) && $tmp == $config['server_path']) { - $tmp = null; - if($cache->fetch('config_lua', $tmp) && $tmp) { - $config['lua'] = unserialize($tmp); - $config_lua_reload = false; - } + if(!$cache->fetch('server_path', $tmp) || $tmp != config('server_path')) { + $cache->delete('config_server'); } } -if($config_lua_reload) { - $config['lua'] = load_config_lua($config['server_path'] . 'config.lua'); +if (empty($config['server'])) { + $config['server'] = $config['lua'] = Config::get(); - // cache config 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'])) $config['lua']['serverName'] = $config['lua']['servername']; diff --git a/system/locale/de/install.php b/system/locale/de/install.php index b725da9c..81bd03f0 100644 --- a/system/locale/de/install.php +++ b/system/locale/de/install.php @@ -67,7 +67,7 @@ $locale['step_database'] = '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_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_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.'; diff --git a/system/locale/en/install.php b/system/locale/en/install.php index a278cd64..085d8955 100644 --- a/system/locale/en/install.php +++ b/system/locale/en/install.php @@ -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_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_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_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.'; diff --git a/system/locale/pl/install.php b/system/locale/pl/install.php index 34152cfd..7c34474d 100644 --- a/system/locale/pl/install.php +++ b/system/locale/pl/install.php @@ -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_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_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_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.'; diff --git a/system/locale/pt_br/install.php b/system/locale/pt_br/install.php index d6b89dee..658d5001 100644 --- a/system/locale/pt_br/install.php +++ b/system/locale/pt_br/install.php @@ -61,7 +61,7 @@ $locale['step_database'] = 'Importar 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_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_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.'; diff --git a/system/settings.php b/system/settings.php index 7ab35a44..87ce4025 100644 --- a/system/settings.php +++ b/system/settings.php @@ -12,6 +12,7 @@ */ use MyAAC\Cache; +use MyAAC\Server\Config; use MyAAC\Settings; $templates = Cache::remember('templates', 5 * 60, function () { @@ -1802,8 +1803,8 @@ Sent by MyAAC,
// test config.lua existence // if fail - revert the setting and inform the user - if (!file_exists($server_path . 'config.lua')) { - error('Server Path is invalid - cannot find config.lua in the directory. Setting have been reverted.'); + if (!Config::exists()) { + 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']; } diff --git a/system/src/Commands/Env.php b/system/src/Commands/Env.php index e3130806..b311313e 100644 --- a/system/src/Commands/Env.php +++ b/system/src/Commands/Env.php @@ -2,6 +2,7 @@ namespace MyAAC\Commands; +use MyAAC\Server\Config; use POT; trait Env @@ -21,7 +22,7 @@ trait Env if($config['server_path'][strlen($config['server_path']) - 1] !== '/') $config['server_path'] .= '/'; - $config['lua'] = load_config_lua($config['server_path'] . 'config.lua'); + $config['server'] = $config['lua'] = Config::get(); // POT require_once SYSTEM . 'libs/pot/OTS.php'; diff --git a/system/src/Server/Config.php b/system/src/Server/Config.php new file mode 100644 index 00000000..5ddac942 --- /dev/null +++ b/system/src/Server/Config.php @@ -0,0 +1,28 @@ +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'); + } +} diff --git a/system/src/Server/Lua/Config.php b/system/src/Server/Lua/Config.php new file mode 100644 index 00000000..cff9996e --- /dev/null +++ b/system/src/Server/Lua/Config.php @@ -0,0 +1,25 @@ +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; + } +} diff --git a/system/src/Server/Lua/Loader.php b/system/src/Server/Lua/Loader.php new file mode 100644 index 00000000..7e8778c9 --- /dev/null +++ b/system/src/Server/Lua/Loader.php @@ -0,0 +1,79 @@ + 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; + } +} diff --git a/system/src/Server/TOML/Config.php b/system/src/Server/TOML/Config.php new file mode 100644 index 00000000..cdfa678e --- /dev/null +++ b/system/src/Server/TOML/Config.php @@ -0,0 +1,54 @@ +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; + } +} +