diff --git a/aac b/aac
index d4ce7b7d..e4cf028c 100644
--- a/aac
+++ b/aac
@@ -3,34 +3,5 @@
require_once __DIR__ . '/common.php';
-if(!IS_CLI) {
- echo 'This script can be run only in command line mode.';
- exit(1);
-}
-
-require_once SYSTEM . 'functions.php';
-
-define('SELF_NAME', basename(__FILE__));
-
-use MyAAC\Plugins;
-use Symfony\Component\Console\Application;
-
-$application = new Application('MyAAC', MYAAC_VERSION);
-
-$commandsGlob = glob(SYSTEM . 'src/Commands/*.php');
-foreach ($commandsGlob as $item) {
- $name = pathinfo($item, PATHINFO_FILENAME);
- if ($name == 'Command') { // ignore base Command class
- continue;
- }
-
- $commandPre = '\\MyAAC\Commands\\';
- $application->add(new ($commandPre . $name));
-}
-
-$pluginCommands = Plugins::getCommands();
-foreach ($pluginCommands as $item) {
- $application->add(require $item);
-}
-
-$application->run();
+$console = new \MyAAC\App\Console();
+$console->run();
diff --git a/admin/index.php b/admin/index.php
index 15ab133c..3ebb195e 100644
--- a/admin/index.php
+++ b/admin/index.php
@@ -1,5 +1,8 @@
install/ directory exists. Please visit this url to start MyAAC Installation.
Delete install/ directory if you already installed MyAAC.
Remember to REFRESH this page when you\'re done!');
+ exit;
}
$content = '';
@@ -26,8 +29,13 @@ require SYSTEM . 'functions.php';
require SYSTEM . 'init.php';
require __DIR__ . '/includes/debugbar.php';
-require SYSTEM . 'status.php';
-require SYSTEM . 'login.php';
+
+$loginService = new LoginService();
+$logged = $loginService->checkLogin();
+
+$statusService = new StatusService();
+$status = $statusService->checkStatus();
+
require __DIR__ . '/includes/functions.php';
$twig->addGlobal('config', $config);
diff --git a/index.php b/index.php
index 0a42deed..a5c1ebce 100644
--- a/index.php
+++ b/index.php
@@ -24,160 +24,8 @@
* @link https://my-aac.org
*/
-use MyAAC\UsageStatistics;
-use MyAAC\Visitors;
-
require_once 'common.php';
require_once SYSTEM . 'functions.php';
-$uri = $_SERVER['REQUEST_URI'];
-if(false !== strpos($uri, 'index.php')) {
- $uri = str_replace_first('/index.php', '', $uri);
-}
-
-if(0 === strpos($uri, '/')) {
- $uri = str_replace_first('/', '', $uri);
-}
-
-if(preg_match("/^[A-Za-z0-9-_%'+\/]+\.png$/i", $uri)) {
- if (!empty(BASE_DIR)) {
- $tmp = explode('.', str_replace_first(str_replace_first('/', '', BASE_DIR) . '/', '', $uri));
- }
- else {
- $tmp = explode('.', $uri);
- }
-
- $_REQUEST['name'] = urldecode($tmp[0]);
-
- chdir(TOOLS . 'signature');
- include TOOLS . 'signature/index.php';
- exit();
-}
-
-if(preg_match("/^(.*)\.(gif|jpg|png|jpeg|tiff|bmp|css|js|less|map|html|zip|rar|gz|ttf|woff|ico)$/i", $_SERVER['REQUEST_URI'])) {
- http_response_code(404);
- exit;
-}
-
-if((!isset($config['installed']) || !$config['installed']) && file_exists(BASE . 'install'))
-{
- header('Location: ' . BASE_URL . 'install/');
- exit();
-}
-
-$template_place_holders = array();
-
-require_once SYSTEM . 'init.php';
-
-require_once SYSTEM . 'template.php';
-require_once SYSTEM . 'login.php';
-require_once SYSTEM . 'status.php';
-
-$twig->addGlobal('config', $config);
-$twig->addGlobal('status', $status);
-
-$hooks->trigger(HOOK_STARTUP);
-
-// backward support for gesior
-if(setting('core.backward_support')) {
- define('INITIALIZED', true);
- $SQL = $db;
- $layout_header = template_header();
- $layout_name = $template_path;
- $news_content = '';
- $tickers_content = '';
- $main_content = '';
-
- $config['access_admin_panel'] = 2;
- $group_id_of_acc_logged = 0;
- if($logged && $account_logged)
- $group_id_of_acc_logged = $account_logged->getGroupId();
-
- $config['site'] = &$config;
- $config['server'] = &$config['lua'];
- $config['site']['shop_system'] = setting('core.gifts_system');
- $config['site']['gallery_page'] = true;
-
- if(!isset($config['vdarkborder']))
- $config['vdarkborder'] = '#505050';
- if(!isset($config['darkborder']))
- $config['darkborder'] = '#D4C0A1';
- if(!isset($config['lightborder']))
- $config['lightborder'] = '#F1E0C6';
-
- $config['site']['download_page'] = true;
- $config['site']['serverinfo_page'] = true;
- $config['site']['screenshot_page'] = true;
-
- $forumSetting = setting('core.forum');
- if($forumSetting != '')
- $config['forum_link'] = (strtolower($forumSetting) === 'site' ? getLink('forum') : $forumSetting);
-
- foreach($status as $key => $value)
- $config['status']['serverStatus_' . $key] = $value;
-}
-
-require_once SYSTEM . 'router.php';
-
-// anonymous usage statistics
-// sent only when user agrees
-if(setting('core.anonymous_usage_statistics')) {
- $report_time = 30 * 24 * 60 * 60; // report one time per 30 days
- $should_report = true;
-
- $value = '';
- if($cache->enabled() && $cache->fetch('last_usage_report', $value)) {
- $should_report = time() > (int)$value + $report_time;
- }
- else {
- $value = '';
- if(fetchDatabaseConfig('last_usage_report', $value)) {
- $should_report = time() > (int)$value + $report_time;
- if($cache->enabled()) {
- $cache->set('last_usage_report', $value, 60 * 60);
- }
- }
- else {
- registerDatabaseConfig('last_usage_report', time() - ($report_time - (7 * 24 * 60 * 60))); // first report after a week
- $should_report = false;
- }
- }
-
- if($should_report) {
- UsageStatistics::report();
-
- updateDatabaseConfig('last_usage_report', time());
- if($cache->enabled()) {
- $cache->set('last_usage_report', time(), 60 * 60);
- }
- }
-}
-
-if(setting('core.views_counter'))
- require_once SYSTEM . 'counter.php';
-
-if(setting('core.visitors_counter')) {
- $visitors = new Visitors(setting('core.visitors_counter_ttl'));
-}
-
-/**
- * @var OTS_Account $account_logged
- */
-if ($logged && admin()) {
- $content .= $twig->render('admin-bar.html.twig', [
- 'username' => USE_ACCOUNT_NAME ? $account_logged->getName() : $account_logged->getId()
- ]);
-}
-$title_full = (isset($title) ? $title . ' - ' : '') . $config['lua']['serverName'];
-require $template_path . '/' . $template_index;
-
-echo base64_decode('PCEtLSBQb3dlcmVkIGJ5IE15QUFDIDo6IGh0dHBzOi8vd3d3Lm15LWFhYy5vcmcvIC0tPg==') . PHP_EOL;
-if(superAdmin()) {
- echo '';
- echo PHP_EOL . '';
- if(function_exists('memory_get_peak_usage')) {
- echo PHP_EOL . '';
- }
-}
-
-$hooks->trigger(HOOK_FINISH);
+$app = new \MyAAC\App\App();
+$app->run();
diff --git a/system/compat/base.php b/system/compat/base.php
index d29c9f3a..92bfc92c 100644
--- a/system/compat/base.php
+++ b/system/compat/base.php
@@ -9,72 +9,6 @@
*/
defined('MYAAC') or die('Direct access not allowed!');
-class Validator extends \MyAAC\Validator {}
-
-function check_name($name, &$errors = '') {
- if(Validator::characterName($name))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function check_account_id($id, &$errors = '') {
- if(Validator::accountId($id))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function check_account_name($name, &$errors = '') {
- if(Validator::accountName($name))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function check_name_new_char($name, &$errors = '') {
- if(Validator::newCharacterName($name))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function check_rank_name($name, &$errors = '') {
- if(Validator::rankName($name))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function check_guild_name($name, &$errors = '') {
- if(Validator::guildName($name))
- return true;
-
- $errors = Validator::getLastError();
- return false;
-}
-
-function news_place() {
- return tickers();
-}
-
-function tableExist($table)
-{
- global $db;
- return $db->hasTable($table);
-}
-
-function fieldExist($field, $table)
-{
- global $db;
- return $db->hasColumn($table, $field);
-}
-
function getCreatureImgPath($creature): string {
return getMonsterImgPath($creature);
}
diff --git a/system/compat/classes.php b/system/compat/classes.php
index 65d436bd..85f51f8d 100644
--- a/system/compat/classes.php
+++ b/system/compat/classes.php
@@ -38,3 +38,4 @@ class GuildRank extends OTS_GuildRank {}
class House extends OTS_House {}
class Cache extends \MyAAC\Cache\Cache {}
+class Validator extends \MyAAC\Validator {}
diff --git a/system/compat/pages.php b/system/compat/pages.php
deleted file mode 100644
index cb90d62f..00000000
--- a/system/compat/pages.php
+++ /dev/null
@@ -1,60 +0,0 @@
-
- * @copyright 2019 MyAAC
- * @link https://my-aac.org
- */
-defined('MYAAC') or die('Direct access not allowed!');
-switch($page)
-{
- case 'adminpanel':
- header('Location: ' . ADMIN_URL);
- die;
-
- case 'createaccount':
- $page = 'account/create';
- break;
-
- case 'accountmanagement':
- $page = 'account/manage';
- break;
-
- case 'lostaccount':
- $page = 'account/lost';
- break;
-
- case 'whoisonline':
- $page = 'online';
- break;
-
- case 'latestnews':
- $page = 'news';
- break;
-
- case 'archive':
- case 'newsarchive':
- $page = 'news/archive';
- break;
-
- case 'tibiarules':
- $page = 'rules';
- break;
-
- case 'killstatistics':
- $page = 'last-kills';
- break;
-
- case 'buypoints':
- $page = 'points';
- break;
-
- case 'shopsystem':
- $page = 'gifts';
- break;
-
- default:
- break;
-}
diff --git a/system/database.php b/system/database.php
deleted file mode 100644
index b9dc6cc6..00000000
--- a/system/database.php
+++ /dev/null
@@ -1,141 +0,0 @@
-
- * @copyright 2019 MyAAC
- * @link https://my-aac.org
- */
-
-use Illuminate\Database\Capsule\Manager as Capsule;
-
-defined('MYAAC') or die('Direct access not allowed!');
-
-if (!isset($config['database_overwrite'])) {
- $config['database_overwrite'] = false;
-}
-
-if(!$config['database_overwrite'] && !isset($config['database_user'][0], $config['database_password'][0], $config['database_name'][0]))
-{
- if(isset($config['lua']['sqlType'])) {// tfs 0.3
- if(isset($config['lua']['mysqlHost'])) {// tfs 0.2
- $config['otserv_version'] = TFS_02;
- $config['database_type'] = 'mysql';
- $config['database_host'] = $config['lua']['mysqlHost'];
- $config['database_port'] = $config['lua']['mysqlPort'];
- $config['database_user'] = $config['lua']['mysqlUser'];
- $config['database_password'] = $config['lua']['mysqlPass'];
- $config['database_name'] = $config['lua']['mysqlDatabase'];
- $config['database_encryption'] = $config['lua']['passwordType'];
- }
- else {
- $config['otserv_version'] = TFS_03;
- $config['database_type'] = $config['lua']['sqlType'];
- $config['database_host'] = $config['lua']['sqlHost'];
- $config['database_port'] = $config['lua']['sqlPort'];
- $config['database_user'] = $config['lua']['sqlUser'];
- $config['database_password'] = $config['lua']['sqlPass'];
- $config['database_name'] = $config['lua']['sqlDatabase'];
-
- $config['database_encryption'] = $config['lua']['encryptionType'];
- if(!isset($config['database_encryption']) || empty($config['database_encryption'])) // before 0.3.6
- $config['database_encryption'] = $config['lua']['passwordType'];
- }
- }
- else if(isset($config['lua']['mysqlHost'])) // tfs 1.0
- {
- $config['otserv_version'] = TFS_02;
- $config['database_type'] = 'mysql';
- $config['database_host'] = $config['lua']['mysqlHost'];
- $config['database_port'] = $config['lua']['mysqlPort'];
- $config['database_user'] = $config['lua']['mysqlUser'];
- $config['database_password'] = $config['lua']['mysqlPass'];
- $config['database_name'] = $config['lua']['mysqlDatabase'];
- if(!isset($config['database_socket'][0])) {
- $config['database_socket'] = isset($config['lua']['mysqlSock']) ? trim($config['lua']['mysqlSock']) : '';
- }
- $config['database_encryption'] = 'sha1';
- }
- else if(isset($config['lua']['database_type'])) // otserv
- {
- $config['otserv_version'] = OTSERV;
- $config['database_type'] = $config['lua']['database_type'];
- $config['database_host'] = $config['lua']['database_host'];
- $config['database_port'] = $config['lua']['database_port'];
- $config['database_user'] = $config['lua']['database_username'];
- $config['database_password'] = $config['lua']['database_password'];
- $config['database_name'] = $config['lua']['database_schema'];
- $config['database_encryption'] = isset($config['lua']['passwordtype']) ? $config['lua']['passwordtype'] : $config['lua']['password_type'];
- $config['database_salt'] = isset($config['lua']['passwordsalt']) ? $config['lua']['passwordsalt'] : $config['lua']['password_salt'];
- }
- else if(isset($config['lua']['sql_host'])) // otserv 0.6.3 / 0.6.4
- {
- $config['otserv_version'] = OTSERV_06;
- $config['database_type'] = $config['lua']['sql_type'];
- $config['database_host'] = $config['lua']['sql_host'];
- $config['database_port'] = $config['lua']['sql_port'];
- $config['database_user'] = $config['lua']['sql_user'];
- $config['database_password'] = $config['lua']['sql_pass'];
- $config['database_name'] = $config['lua']['sql_db'];
- $config['database_encryption'] = isset($config['lua']['passwordtype']) ? $config['lua']['passwordtype'] : $config['lua']['password_type'];
- $config['database_salt'] = isset($config['lua']['passwordsalt']) ? $config['lua']['passwordsalt'] : $config['lua']['password_salt'];
- }
-}
-
-if(isset($config['lua']['useMD5Passwords']) && getBoolean($config['lua']['useMD5Passwords']))
- $config['database_encryption'] = 'md5';
-
-if(!isset($config['database_log'])) {
- $config['database_log'] = false;
-}
-
-if(!isset($config['database_socket'])) {
- $config['database_socket'] = '';
-}
-
-
-try {
- $ots->connect(array(
- 'host' => $config['database_host'],
- 'user' => $config['database_user'],
- 'password' => $config['database_password'],
- 'database' => $config['database_name'],
- 'log' => $config['database_log'],
- 'socket' => @$config['database_socket'],
- 'persistent' => @$config['database_persistent']
- ));
-
- global $db;
- $db = POT::getInstance()->getDBHandle();
- $capsule = new Capsule;
- $capsule->addConnection([
- 'driver' => 'mysql',
- 'database' => $config['database_name'],
- ]);
-
- $capsule->getConnection()->setPdo($db);
- $capsule->getConnection()->setReadPdo($db);
-
- $capsule->setAsGlobal();
- $capsule->bootEloquent();
-
- $eloquentConnection = $capsule->getConnection();
-
-} catch (Exception $e) {
- if(isset($cache) && $cache->enabled()) {
- $cache->delete('config_lua');
- }
-
- if(defined('MYAAC_INSTALL')) {
- $error = $e->getMessage();
- return; // installer will take care of this
- }
-
- throw new RuntimeException('ERROR: Cannot connect to MySQL database.
' .
- 'Possible reasons:' .
- '
' . getDatabaseConfig('site_closed_message') . '
Site is under maintenance (closed mode). Only privileged users can see it.
'; - -$ignore = false; - -/** @var boolean $logged */ -/** @var OTS_Account $account_logged */ -$logged_access = 0; -if($logged && $account_logged && $account_logged->isLoaded()) { - $logged_access = $account_logged->getAccess(); -} - -/** - * Routes loading - */ -$dispatcher = FastRoute\cachedDispatcher(function (FastRoute\RouteCollector $r) { - $routes = require SYSTEM . 'routes.php'; - - $routesFinal = []; - foreach(getDatabasePages() as $page) { - $routesFinal[] = ['*', $page, '__database__/' . $page, 100]; - } - - Plugins::clearWarnings(); - foreach (Plugins::getRoutes() as $route) { - $routesFinal[] = [$route[0], $route[1], $route[2], $route[3] ?? 1000]; -/* - echo ''; - var_dump($route[1], $route[3], $route[2]); - echo '/'; -*/ - } - - foreach ($routes as $route) { - if (!str_contains($route[2], '__redirect__') && !str_contains($route[2], '__database__')) { - $routesFinal[] = [$route[0], $route[1], 'system/pages/' . $route[2], $route[3] ?? 10000]; - } - else { - $routesFinal[] = [$route[0], $route[1], $route[2], $route[3] ?? 10000]; - } - } - - // sort required for the next step (filter) - usort($routesFinal, function ($a, $b) - { - // key 3 is priority - if ($a[3] == $b[3]) { - return 0; - } - - return ($a[3] < $b[3]) ? -1 : 1; - }); - - // remove duplicates - // if same route pattern, but different priority - $routesFinal = array_filter($routesFinal, function ($a) { - $aliases = [ - [':int', ':string', ':alphanum'], - [':\d+', ':[A-Za-z0-9-_%+\' ]+', ':[A-Za-z0-9]+'], - ]; - - // apply aliases - $a[1] = str_replace($aliases[0], $aliases[1], $a[1]); - - static $duplicates = []; - if (isset($duplicates[$a[1]])) { - return false; - } - - $duplicates[$a[1]] = true; - return true; - }); -/* - echo ''; - var_dump($routesFinal); - echo ''; - die; -*/ - foreach ($routesFinal as $route) { - if ($route[0] === '*') { - $route[0] = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']; - } - else { - if (is_string($route[0])) { - $route[0] = explode(',', $route[0]); - } - - $toUpperCase = function(string $value): string { - return trim(strtoupper($value)); - }; - - // convert to upper case, fast-route accepts only upper case - $route[0] = array_map($toUpperCase, $route[0]); - } - - $aliases = [ - [':int', ':string', ':alphanum'], - [':\d+', ':[A-Za-z0-9-_%+\' ]+', ':[A-Za-z0-9]+'], - ]; - - // apply aliases - $route[1] = str_replace($aliases[0], $aliases[1], $route[1]); - - $r->addRoute($route[0], $route[1], $route[2]); - } - - if (config('env') === 'dev') { - foreach(Plugins::getWarnings() as $warning) { - log_append('router.log', $warning); - } - } -}, - [ - 'cacheFile' => CACHE . 'route.cache', - 'cacheDisabled' => config('env') === 'dev', - ] -); - -// Fetch method and URI -$httpMethod = $_SERVER['REQUEST_METHOD']; - -$found = true; - -// old support for pages like /?subtopic=accountmanagement -$page = $_REQUEST['p'] ?? ($_REQUEST['subtopic'] ?? ''); -if(!empty($page) && preg_match('/^[A-z0-9\-]+$/', $page)) { - if (isset($_REQUEST['p'])) { // some plugins may require this - $_REQUEST['subtopic'] = $_REQUEST['p']; - } - - if (setting('core.backward_support')) { - require SYSTEM . 'compat/pages.php'; - } - - $file = loadPageFromFileSystem($page, $found); - if(!$found) { - $file = false; - } -} -else { - $routeInfo = $dispatcher->dispatch($httpMethod, $uri); - switch ($routeInfo[0]) { - case FastRoute\Dispatcher::NOT_FOUND: - // ... 404 Not Found - /** - * Fallback to load page from templates/ or system/pages/ directory - */ - $page = $uri; - if (preg_match('/^[A-z0-9\/\-]+$/', $page)) { - $file = loadPageFromFileSystem($page, $found); - } else { - $found = false; - } - - break; - - case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: - // ... 405 Method Not Allowed - $page = '405'; - $allowedMethods = $routeInfo[1]; - $file = SYSTEM . 'pages/405.php'; - break; - - case FastRoute\Dispatcher::FOUND: - $path = $routeInfo[1]; - $vars = $routeInfo[2]; - - $_REQUEST = array_merge($_REQUEST, $vars); - $_GET = array_merge($_GET, $vars); - extract($vars); - - if (str_contains($path, '__database__/')) { - $pageName = str_replace('__database__/', '', $path); - - $success = false; - $tmp_content = getCustomPage($pageName, $success); - if ($success) { - $content .= $tmp_content; - if (hasFlag(FLAG_CONTENT_PAGES) || superAdmin()) { - $pageInfo = getCustomPageInfo($pageName); - $content = $twig->render('admin.links.html.twig', ['page' => 'pages', 'id' => $pageInfo !== null ? $pageInfo['id'] : 0, 'hide' => $pageInfo !== null ? $pageInfo['hide'] : '0'] - ) . $content; - } - - $page = $pageName; - $file = false; - } - } else if (str_contains($path, '__redirect__/')) { - $path = str_replace('__redirect__/', '', $path); - header('Location: ' . BASE_URL . $path); - exit; - } else { - // parse for define PAGE - $tmp = BASE_DIR; - $uri = $_SERVER['REQUEST_URI']; - if (strlen($tmp) > 0) { - $uri = str_replace(BASE_DIR . '/', '', $uri); - } - - if (false !== $pos = strpos($uri, '?')) { - $uri = substr($uri, 0, $pos); - } - if (str_starts_with($uri, '/')) { - $uri = str_replace_first('/', '', $uri); - } - - $page = str_replace('index.php/', '', $uri); - if (empty($page)) { - $page = 'news'; - } - - $file = BASE . $path; - } - - unset($tmp, $uri); - break; - } -} - -if (!$found) { - $page = '404'; - $file = SYSTEM . 'pages/404.php'; -} - -define('PAGE', $page); - -ob_start(); -if($hooks->trigger(HOOK_BEFORE_PAGE)) { - if(!$ignore && $file !== false) - require $file; -} - -unset($file); - -if(setting('core.backward_support') && isset($main_content[0])) - $content .= $main_content; - -$content .= ob_get_contents(); -ob_end_clean(); -$hooks->trigger(HOOK_AFTER_PAGE); - -if(!isset($title)) { - $title = str_replace('index.php/', '', $page); - $title = ucfirst($title); -} - -if(setting('core.backward_support')) { - $main_content = $content; - $topic = $title; -} - -unset($page); - -function getDatabasePages($withHidden = false): array -{ - global $logged_access; - $pages = Pages::where('access', '<=', $logged_access)->when(!$withHidden, function ($q) { - $q->isPublic(); - })->get('name'); - - $ret = []; - foreach($pages as $page) { - $ret[] = $page->name; - } - - return $ret; -} - -function loadPageFromFileSystem($page, &$found): string -{ - $file = SYSTEM . 'pages/' . $page . '.php'; - if (!is_file($file)) { - // feature: convert camelCase to snake_case - // so instead of forum/move_thread - // we can write: forum/moveThread - $file = SYSTEM . 'pages/' . camelCaseToUnderscore($page) . '.php'; - if (!is_file($file)) { - // feature: load pages from templates/ dir - global $template_path; - $file = $template_path . '/pages/' . $page . '.php'; - if (!is_file($file)) { - $found = false; - } - } - } - - return $file; -} diff --git a/system/routes.php b/system/routes.php index 13cee37f..b4244e57 100644 --- a/system/routes.php +++ b/system/routes.php @@ -14,6 +14,8 @@ return [ ['GET', 'news/archive/{id:int}', 'news/archive.php'], ['GET', 'news/{id:int}', 'news/archive.php'], + ['GET', '{name:string}.png', 'signature.php'], + // block access to some files ['*', 'account/base', '404.php', 10], // this is to block account/base.php ['*', 'forum/base', '404.php', 10], diff --git a/system/settings.php b/system/settings.php index dcd32ebc..56722b0a 100644 --- a/system/settings.php +++ b/system/settings.php @@ -213,11 +213,9 @@ return [ 'default' => 'myaac_', ], 'backward_support' => [ + 'hidden' => true, 'name' => 'Gesior Backward Support', 'type' => 'boolean', - 'desc' => 'gesior backward support (templates & pages)
' . - 'allows using gesior templates and pages with myaac
' . - 'might bring some performance when disabled', 'default' => true, ], 'anonymous_usage_statistics' => [ diff --git a/system/src/App/Admin.php b/system/src/App/Admin.php new file mode 100644 index 00000000..5cfb0dd7 --- /dev/null +++ b/system/src/App/Admin.php @@ -0,0 +1,8 @@ +isLoggedIn = $loginService->checkLogin(); + + $statusService = new StatusService(); + $status = $statusService->checkStatus(); + + global $config; + + $twig = app()->get('twig'); + $twig->addGlobal('config', $config); + $twig->addGlobal('status', $status); + + $hooks = app()->get('hooks'); + $hooks->trigger(HOOK_STARTUP); + + $routerService = new RouterService(); + $handleRouting = $routerService->handleRouting(); + + $title = $handleRouting['title']; + $content = $handleRouting['content']; + + $anonymouseStatisticsService = new AnonymousStatisticsService(); + $anonymouseStatisticsService->checkReport(); + + if(setting('core.views_counter')) { + require_once SYSTEM . 'counter.php'; + } + + if(setting('core.visitors_counter')) { + global $visitors; + $visitors = new Visitors(setting('core.visitors_counter_ttl')); + } + + global $content; + /** + * @var \OTS_Account $account_logged + */ + if ($this->isLoggedIn && admin()) { + $content .= $twig->render('admin-bar.html.twig', [ + 'username' => USE_ACCOUNT_NAME ? $account_logged->getName() : $account_logged->getId() + ]); + } + + global $template_path, $template_index; + $title_full = (isset($title) ? $title . ' - ' : '') . $config['lua']['serverName']; + require $template_path . '/' . $template_index; + + echo base64_decode('PCEtLSBQb3dlcmVkIGJ5IE15QUFDIDo6IGh0dHBzOi8vd3d3Lm15LWFhYy5vcmcvIC0tPg==') . PHP_EOL; + if(superAdmin()) { + echo ''; + echo PHP_EOL . ''; + if(function_exists('memory_get_peak_usage')) { + echo PHP_EOL . ''; + } + } + + $hooks->trigger(HOOK_FINISH); + } + + public function setLoggedIn($loggedIn): void { + $this->isLoggedIn = $loggedIn; + } + + public function isLoggedIn(): bool { + return $this->isLoggedIn; + } + + public function get($what) + { + if ($what == 'db') { + $what = 'database'; + } + + if (!isset($this->instances[$what])) { + switch ($what) { + case 'cache': + $this->instances[$what] = \MyAAC\Cache\Cache::getInstance(); + break; + + case 'database': + $databaseService = new DatabaseService(); + $this->instances[$what] = $databaseService->getConnectionHandle(); + break; + + case 'hooks': + $this->instances[$what] = new Hooks(); + break; + + case 'settings': + $this->instances[$what] = Settings::getInstance(); + break; + + case 'twig': + $dev_mode = (config('env') === 'dev'); + $this->instances[$what] = new Environment($this->get('twig-loader'), array( + 'cache' => CACHE . 'twig/', + 'auto_reload' => $dev_mode, + 'debug' => $dev_mode + )); + break; + + case 'twig-loader': + $this->instances[$what] = new FilesystemLoader(SYSTEM . 'templates'); + break; + } + } + + return $this->instances[$what]; + } +} diff --git a/system/src/App/Console.php b/system/src/App/Console.php new file mode 100644 index 00000000..24767392 --- /dev/null +++ b/system/src/App/Console.php @@ -0,0 +1,41 @@ +add(new ($commandPre . $name)); + } + + $pluginCommands = Plugins::getCommands(); + foreach ($pluginCommands as $item) { + $application->add(require $item); + } + + $application->run(); + } +} diff --git a/system/src/CreateCharacter.php b/system/src/CreateCharacter.php index 594eda9d..89443e71 100644 --- a/system/src/CreateCharacter.php +++ b/system/src/CreateCharacter.php @@ -235,7 +235,7 @@ class CreateCharacter } } - global $hooks; + $hooks = app()->get('hooks'); if (!$hooks->trigger(HOOK_ACCOUNT_CREATE_CHARACTER_AFTER, [ 'account' => $account, diff --git a/system/src/News.php b/system/src/News.php index 5ef7a086..15849d85 100644 --- a/system/src/News.php +++ b/system/src/News.php @@ -49,7 +49,7 @@ class News 'article_image' => ($type == 3 ? $article_image : '') ]; - global $hooks; + $hooks = app()->get('hooks'); if (!$hooks->trigger(HOOK_ADMIN_NEWS_ADD_PRE, $params)) { return false; } @@ -86,7 +86,7 @@ class News 'article_image' => ($type == 3 ? $article_image : ''), ]; - global $hooks; + $hooks = app()->get('hooks'); if (!$hooks->trigger(HOOK_ADMIN_NEWS_UPDATE_PRE, $params)) { return false; } @@ -105,7 +105,7 @@ class News static public function delete($id, &$errors) { - global $hooks; + $hooks = app()->get('hooks'); if(isset($id)) { $row = ModelsNews::find($id); @@ -140,7 +140,7 @@ class News static public function toggleHide($id, &$errors, &$status) { - global $hooks; + $hooks = app()->get('hooks'); if(isset($id)) { $row = ModelsNews::find($id); diff --git a/system/src/Plugins.php b/system/src/Plugins.php index 243ced24..aba192c2 100644 --- a/system/src/Plugins.php +++ b/system/src/Plugins.php @@ -716,7 +716,7 @@ class Plugins { } } - $cache = Cache::getInstance(); + $cache = app()->get('cache'); if($cache->enabled()) { $cache->delete('templates'); $cache->delete('hooks'); diff --git a/system/src/Services/AnonymousStatisticsService.php b/system/src/Services/AnonymousStatisticsService.php new file mode 100644 index 00000000..17735a9f --- /dev/null +++ b/system/src/Services/AnonymousStatisticsService.php @@ -0,0 +1,52 @@ +get('cache'); + + $value = ''; + if($cache->enabled() && $cache->fetch('last_usage_report', $value)) { + $should_report = time() > (int)$value + $report_time; + } + else { + $value = ''; + if(fetchDatabaseConfig('last_usage_report', $value)) { + $should_report = time() > (int)$value + $report_time; + if($cache->enabled()) { + $cache->set('last_usage_report', $value, 60 * 60); + } + } + else { + registerDatabaseConfig('last_usage_report', time() - ($report_time - (7 * 24 * 60 * 60))); // first report after a week + $should_report = false; + } + } + + if($should_report) { + UsageStatistics::report(); + + updateDatabaseConfig('last_usage_report', time()); + if($cache->enabled()) { + $cache->set('last_usage_report', time(), 60 * 60); + } + } + } +} diff --git a/system/src/Services/DatabaseService.php b/system/src/Services/DatabaseService.php new file mode 100644 index 00000000..9aa70d49 --- /dev/null +++ b/system/src/Services/DatabaseService.php @@ -0,0 +1,153 @@ +db)) { + $this->connect(); + } + + return $this->db; + } + + public function connect(): void + { + global $config; + + if (!isset($config['database_overwrite'])) { + $config['database_overwrite'] = false; + } + + if(!$config['database_overwrite'] && !isset($config['database_user'][0], $config['database_password'][0], $config['database_name'][0])) { + if(isset($config['lua']['sqlType'])) {// tfs 0.3 + if(isset($config['lua']['mysqlHost'])) {// tfs 0.2 + $config['otserv_version'] = TFS_02; + $config['database_type'] = 'mysql'; + $config['database_host'] = $config['lua']['mysqlHost']; + $config['database_port'] = $config['lua']['mysqlPort']; + $config['database_user'] = $config['lua']['mysqlUser']; + $config['database_password'] = $config['lua']['mysqlPass']; + $config['database_name'] = $config['lua']['mysqlDatabase']; + $config['database_encryption'] = $config['lua']['passwordType']; + } + else { + $config['otserv_version'] = TFS_03; + $config['database_type'] = $config['lua']['sqlType']; + $config['database_host'] = $config['lua']['sqlHost']; + $config['database_port'] = $config['lua']['sqlPort']; + $config['database_user'] = $config['lua']['sqlUser']; + $config['database_password'] = $config['lua']['sqlPass']; + $config['database_name'] = $config['lua']['sqlDatabase']; + + $config['database_encryption'] = $config['lua']['encryptionType']; + if(!isset($config['database_encryption']) || empty($config['database_encryption'])) // before 0.3.6 + $config['database_encryption'] = $config['lua']['passwordType']; + } + } + else if(isset($config['lua']['mysqlHost'])) // tfs 1.0 + { + $config['otserv_version'] = TFS_02; + $config['database_type'] = 'mysql'; + $config['database_host'] = $config['lua']['mysqlHost']; + $config['database_port'] = $config['lua']['mysqlPort']; + $config['database_user'] = $config['lua']['mysqlUser']; + $config['database_password'] = $config['lua']['mysqlPass']; + $config['database_name'] = $config['lua']['mysqlDatabase']; + if(!isset($config['database_socket'][0])) { + $config['database_socket'] = isset($config['lua']['mysqlSock']) ? trim($config['lua']['mysqlSock']) : ''; + } + $config['database_encryption'] = 'sha1'; + } + else if(isset($config['lua']['database_type'])) // otserv + { + $config['otserv_version'] = OTSERV; + $config['database_type'] = $config['lua']['database_type']; + $config['database_host'] = $config['lua']['database_host']; + $config['database_port'] = $config['lua']['database_port']; + $config['database_user'] = $config['lua']['database_username']; + $config['database_password'] = $config['lua']['database_password']; + $config['database_name'] = $config['lua']['database_schema']; + $config['database_encryption'] = isset($config['lua']['passwordtype']) ? $config['lua']['passwordtype'] : $config['lua']['password_type']; + $config['database_salt'] = isset($config['lua']['passwordsalt']) ? $config['lua']['passwordsalt'] : $config['lua']['password_salt']; + } + else if(isset($config['lua']['sql_host'])) // otserv 0.6.3 / 0.6.4 + { + $config['otserv_version'] = OTSERV_06; + $config['database_type'] = $config['lua']['sql_type']; + $config['database_host'] = $config['lua']['sql_host']; + $config['database_port'] = $config['lua']['sql_port']; + $config['database_user'] = $config['lua']['sql_user']; + $config['database_password'] = $config['lua']['sql_pass']; + $config['database_name'] = $config['lua']['sql_db']; + $config['database_encryption'] = isset($config['lua']['passwordtype']) ? $config['lua']['passwordtype'] : $config['lua']['password_type']; + $config['database_salt'] = isset($config['lua']['passwordsalt']) ? $config['lua']['passwordsalt'] : $config['lua']['password_salt']; + } + } + + if(isset($config['lua']['useMD5Passwords']) && getBoolean($config['lua']['useMD5Passwords'])) + $config['database_encryption'] = 'md5'; + + if(!isset($config['database_log'])) { + $config['database_log'] = false; + } + + if(!isset($config['database_socket'])) { + $config['database_socket'] = ''; + } + + $ots = \POT::getInstance(); + $cache = app()->get('cache'); + + try { + $ots->connect([ + 'host' => $config['database_host'], + 'user' => $config['database_user'], + 'password' => $config['database_password'], + 'database' => $config['database_name'], + 'log' => $config['database_log'], + 'socket' => @$config['database_socket'], + 'persistent' => @$config['database_persistent'] + ]); + + global $eloquentConnection; + $this->db = $ots->getDBHandle(); + + $capsule = new Capsule; + $capsule->addConnection([ + 'driver' => 'mysql', + 'database' => $config['database_name'], + ]); + + $capsule->getConnection()->setPdo($this->db); + $capsule->getConnection()->setReadPdo($this->db); + + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + + $eloquentConnection = $capsule->getConnection(); + } catch (\Exception $e) { + if(isset($cache) && $cache->enabled()) { + $cache->delete('config_lua'); + } + + if(defined('MYAAC_INSTALL')) { + $error = $e->getMessage(); + return; // installer will take care of this + } + + throw new \RuntimeException('ERROR: Cannot connect to MySQL database.
' . + 'Possible reasons:' . + '
Site is under maintenance (closed mode). Only privileged users can see it.
'; + + $ignore = false; + + /** @var boolean $logged */ + /** @var \OTS_Account $account_logged */ + global $logged_access; + $logged_access = 0; + if($logged && $account_logged && $account_logged->isLoaded()) { + $logged_access = $account_logged->getAccess(); + } + + /** + * Routes loading + */ + $dispatcher = \FastRoute\cachedDispatcher(function (\FastRoute\RouteCollector $r) { + $routes = require SYSTEM . 'routes.php'; + + $routesFinal = []; + foreach($this->getDatabasePages() as $page) { + $routesFinal[] = ['*', $page, '__database__/' . $page, 100]; + } + + Plugins::clearWarnings(); + foreach (Plugins::getRoutes() as $route) { + $routesFinal[] = [$route[0], $route[1], $route[2], $route[3] ?? 1000]; + /* + echo ''; + var_dump($route[1], $route[3], $route[2]); + echo '/'; + */ + } + + foreach ($routes as $route) { + if (!str_contains($route[2], '__redirect__') && !str_contains($route[2], '__database__')) { + $routesFinal[] = [$route[0], $route[1], 'system/pages/' . $route[2], $route[3] ?? 10000]; + } + else { + $routesFinal[] = [$route[0], $route[1], $route[2], $route[3] ?? 10000]; + } + } + + // sort required for the next step (filter) + usort($routesFinal, function ($a, $b) + { + // key 3 is priority + if ($a[3] == $b[3]) { + return 0; + } + + return ($a[3] < $b[3]) ? -1 : 1; + }); + + // remove duplicates + // if same route pattern, but different priority + $routesFinal = array_filter($routesFinal, function ($a) { + $aliases = [ + [':int', ':string', ':alphanum'], + [':\d+', ':[A-Za-z0-9-_%+\' ]+', ':[A-Za-z0-9]+'], + ]; + + // apply aliases + $a[1] = str_replace($aliases[0], $aliases[1], $a[1]); + + static $duplicates = []; + if (isset($duplicates[$a[1]])) { + return false; + } + + $duplicates[$a[1]] = true; + return true; + }); + /* + echo ''; + var_dump($routesFinal); + echo ''; + die; + */ + foreach ($routesFinal as $route) { + if ($route[0] === '*') { + $route[0] = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']; + } + else { + if (is_string($route[0])) { + $route[0] = explode(',', $route[0]); + } + + $toUpperCase = function(string $value): string { + return trim(strtoupper($value)); + }; + + // convert to upper case, fast-route accepts only upper case + $route[0] = array_map($toUpperCase, $route[0]); + } + + $aliases = [ + [':int', ':string', ':alphanum'], + [':\d+', ':[A-Za-z0-9-_%+\' ]+', ':[A-Za-z0-9]+'], + ]; + + // apply aliases + $route[1] = str_replace($aliases[0], $aliases[1], $route[1]); + + $r->addRoute($route[0], $route[1], $route[2]); + } + + if (config('env') === 'dev') { + foreach(Plugins::getWarnings() as $warning) { + log_append('router.log', $warning); + } + } + }, + [ + 'cacheFile' => CACHE . 'route.cache', + 'cacheDisabled' => config('env') === 'dev', + ] + ); + + // Fetch method and URI + $httpMethod = $_SERVER['REQUEST_METHOD']; + + $found = true; + + // old support for pages like /?subtopic=accountmanagement + $page = $_REQUEST['p'] ?? ($_REQUEST['subtopic'] ?? ''); + if(!empty($page) && preg_match('/^[A-z0-9\-]+$/', $page)) { + if (isset($_REQUEST['p'])) { // some plugins may require this + $_REQUEST['subtopic'] = $_REQUEST['p']; + } + + $file = $this->loadPageFromFileSystem($page, $found); + if(!$found) { + $file = false; + } + } + else { + $routeInfo = $dispatcher->dispatch($httpMethod, $uri); + switch ($routeInfo[0]) { + case \FastRoute\Dispatcher::NOT_FOUND: + // ... 404 Not Found + /** + * Fallback to load page from templates/ or system/pages/ directory + */ + $page = $uri; + if (preg_match('/^[A-z0-9\/\-]+$/', $page)) { + $file = $this->loadPageFromFileSystem($page, $found); + } else { + $found = false; + } + + break; + + case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: + // ... 405 Method Not Allowed + $page = '405'; + $allowedMethods = $routeInfo[1]; + $file = SYSTEM . 'pages/405.php'; + break; + + case \FastRoute\Dispatcher::FOUND: + $path = $routeInfo[1]; + $vars = $routeInfo[2]; + + $_REQUEST = array_merge($_REQUEST, $vars); + $_GET = array_merge($_GET, $vars); + extract($vars); + + if (str_contains($path, '__database__/')) { + $pageName = str_replace('__database__/', '', $path); + + $success = false; + $tmp_content = getCustomPage($pageName, $success); + if ($success) { + $content .= $tmp_content; + if (hasFlag(FLAG_CONTENT_PAGES) || superAdmin()) { + $pageInfo = getCustomPageInfo($pageName); + $content = $twig->render('admin.links.html.twig', ['page' => 'pages', 'id' => $pageInfo !== null ? $pageInfo['id'] : 0, 'hide' => $pageInfo !== null ? $pageInfo['hide'] : '0'] + ) . $content; + } + + $page = $pageName; + $file = false; + } + } else if (str_contains($path, '__redirect__/')) { + $path = str_replace('__redirect__/', '', $path); + header('Location: ' . BASE_URL . $path); + exit; + } else { + // parse for define PAGE + $tmp = BASE_DIR; + $uri = $_SERVER['REQUEST_URI']; + if (strlen($tmp) > 0) { + $uri = str_replace(BASE_DIR . '/', '', $uri); + } + + if (false !== $pos = strpos($uri, '?')) { + $uri = substr($uri, 0, $pos); + } + if (str_starts_with($uri, '/')) { + $uri = str_replace_first('/', '', $uri); + } + + $page = str_replace('index.php/', '', $uri); + if (empty($page)) { + $page = 'news'; + } + + $file = BASE . $path; + } + + unset($tmp, $uri); + break; + } + } + + if (!$found) { + $page = '404'; + $file = SYSTEM . 'pages/404.php'; + } + + define('PAGE', $page); + + ob_start(); + + global $config; + $hooks = app()->get('hooks'); + + if($hooks->trigger(HOOK_BEFORE_PAGE)) { + if(!$ignore && $file !== false) { + require $file; + } + } + + $content .= ob_get_contents(); + ob_end_clean(); + $hooks->trigger(HOOK_AFTER_PAGE); + + if(!isset($title)) { + $title = str_replace('index.php/', '', $page); + $title = ucfirst($title); + } + + return [ + 'title' => $title, + 'content' => $content, + ]; + } + + public function getDatabasePages($withHidden = false): array + { + global $logged_access; + $pages = Pages::where('access', '<=', $logged_access)->when(!$withHidden, function ($q) { + $q->isPublic(); + })->get('name'); + + $ret = []; + foreach($pages as $page) { + $ret[] = $page->name; + } + + return $ret; + } + + private function loadPageFromFileSystem($page, &$found): string + { + $file = SYSTEM . 'pages/' . $page . '.php'; + if (!is_file($file)) { + // feature: load pages from templates/ dir + global $template_path; + $file = $template_path . '/pages/' . $page . '.php'; + if (!is_file($file)) { + $found = false; + } + } + + return $file; + } +} diff --git a/system/src/Services/StatusService.php b/system/src/Services/StatusService.php new file mode 100644 index 00000000..b7e1cf6a --- /dev/null +++ b/system/src/Services/StatusService.php @@ -0,0 +1,134 @@ +get('cache'); + if($cache->enabled()) { + $tmp = ''; + if($cache->fetch('status', $tmp)) { + return unserialize($tmp); + } + } + + $status_query = Config::where('name', 'LIKE', '%status%')->get(); + if (!$status_query || !$status_query->count()) { + foreach($status as $key => $value) { + registerDatabaseConfig('status_' . $key, $value); + } + } else { + foreach($status_query as $tmp) { + $status[str_replace('status_', '', $tmp->name)] = $tmp->value; + } + } + + if(isset($config['lua']['statustimeout'])) { + $config['lua']['statusTimeout'] = $config['lua']['statustimeout']; + } + + // get status timeout from server config + $status_timeout = eval('return ' . $config['lua']['statusTimeout'] . ';') / 1000 + 1; + $status_interval = setting('core.status_interval'); + if($status_interval && $status_timeout < $status_interval) { + $status_timeout = $status_interval; + } + + if($status['lastCheck'] + $status_timeout < time()) { + return $this->updateStatus(); + } + + $cache = app()->get('cache'); + } + + public function updateStatus(): array + { + $db = app()->get('db'); + $cache = app()->get('cache'); + + // get server status and save it to database + $serverInfo = new \OTS_ServerInfo(setting('core.status_ip'), setting('core.status_port')); + $serverStatus = $serverInfo->status(); + if(!$serverStatus) { + $status['online'] = false; + $status['players'] = 0; + $status['playersMax'] = 0; + } + else { + $status['lastCheck'] = time(); // this should be set only if server respond + + $status['online'] = true; + $status['players'] = $serverStatus->getOnlinePlayers(); // counts all players logged in-game, or only connected clients (if enabled on server side) + $status['playersMax'] = $serverStatus->getMaxPlayers(); + + // for status afk thing + if (setting('core.online_afk')) { + // get amount of players that are currently logged in-game, including disconnected clients (exited) + if($db->hasTable('players_online')) { // tfs 1.x + $status['playersTotal'] = PlayerOnline::count(); + } + else { + $status['playersTotal'] = Player::online()->count(); + } + } + + $uptime = $status['uptime'] = $serverStatus->getUptime(); + $m = date('m', $uptime); + $m = $m > 1 ? "$m months, " : ($m == 1 ? 'month, ' : ''); + $d = date('d', $uptime); + $d = $d > 1 ? "$d days, " : ($d == 1 ? 'day, ' : ''); + $h = date('H', $uptime); + $min = date('i', $uptime); + $status['uptimeReadable'] = "{$m}{$d}{$h}h {$min}m"; + + $status['monsters'] = $serverStatus->getMonstersCount(); + $status['motd'] = $serverStatus->getMOTD(); + + $status['mapAuthor'] = $serverStatus->getMapAuthor(); + $status['mapName'] = $serverStatus->getMapName(); + $status['mapWidth'] = $serverStatus->getMapWidth(); + $status['mapHeight'] = $serverStatus->getMapHeight(); + + $status['server'] = $serverStatus->getServer(); + $status['serverVersion'] = $serverStatus->getServerVersion(); + $status['clientVersion'] = $serverStatus->getClientVersion(); + } + + if($cache->enabled()) { + $cache->set('status', serialize($status), 120); + } + + $tmpVal = null; + foreach($status as $key => $value) { + if(fetchDatabaseConfig('status_' . $key, $tmpVal)) { + updateDatabaseConfig('status_' . $key, $value); + } + else { + registerDatabaseConfig('status_' . $key, $value); + } + } + } +} diff --git a/system/src/Settings.php b/system/src/Settings.php index e243687e..34b7b68c 100644 --- a/system/src/Settings.php +++ b/system/src/Settings.php @@ -57,7 +57,7 @@ class Settings implements \ArrayAccess $settings = $this->settingsFile[$pluginName]; - global $hooks; + $hooks = app()->get('hooks'); if (!$hooks->trigger(HOOK_ADMIN_SETTINGS_BEFORE_SAVE, [ 'name' => $pluginName, 'values' => $values, diff --git a/system/status.php b/system/status.php deleted file mode 100644 index 835f204d..00000000 --- a/system/status.php +++ /dev/null @@ -1,180 +0,0 @@ - - * @copyright 2019 MyAAC - * @link https://my-aac.org - */ - -use MyAAC\Cache\Cache; -use MyAAC\Models\Config; -use MyAAC\Models\PlayerOnline; -use MyAAC\Models\Player; - -defined('MYAAC') or die('Direct access not allowed!'); - -$status = array(); -$status['online'] = false; -$status['players'] = 0; -$status['playersMax'] = 0; -$status['lastCheck'] = 0; -$status['uptime'] = '0h 0m'; -$status['monsters'] = 0; - -if(setting('core.status_enabled') === false) { - return; -} - -/** - * @var array $config - */ -$status_ip = $config['lua']['ip']; -if(isset($config['lua']['statusProtocolPort'])) { - $config['lua']['loginPort'] = $config['lua']['statusProtocolPort']; - $config['lua']['statusPort'] = $config['lua']['statusProtocolPort']; - $status_port = $config['lua']['statusProtocolPort']; -} -else if(isset($config['lua']['status_port'])) { - $config['lua']['loginPort'] = $config['lua']['status_port']; - $config['lua']['statusPort'] = $config['lua']['status_port']; - $status_port = $config['lua']['status_port']; -} - -// ip check -$settingIP = setting('core.status_ip'); -if(isset($settingIP[0])) -{ - $status_ip = $settingIP; -} -elseif(!isset($status_ip[0])) // try localhost if no ip specified -{ - $status_ip = '127.0.0.1'; -} - -// port check -$status_port = $config['lua']['statusPort']; -$settingPort = setting('core.status_port'); -if(isset($settingPort[0])) { - $status_port = $settingPort; -} -elseif(!isset($status_port[0])) // try 7171 if no port specified -{ - $status_port = 7171; -} - -$fetch_from_db = true; -/** - * @var Cache $cache - */ -if($cache->enabled()) -{ - $tmp = ''; - if($cache->fetch('status', $tmp)) - { - $status = unserialize($tmp); - $fetch_from_db = false; - } -} - -if($fetch_from_db) -{ - $status_query = Config::where('name', 'LIKE', '%status%')->get(); - if (!$status_query || !$status_query->count()) { - foreach($status as $key => $value) { - registerDatabaseConfig('status_' . $key, $value); - } - } else { - foreach($status_query as $tmp) { - $status[str_replace('status_', '', $tmp->name)] = $tmp->value; - } - } -} - -if(isset($config['lua']['statustimeout'])) - $config['lua']['statusTimeout'] = $config['lua']['statustimeout']; - -// get status timeout from server config -$status_timeout = eval('return ' . $config['lua']['statusTimeout'] . ';') / 1000 + 1; -$status_interval = setting('core.status_interval'); -if($status_interval && $status_timeout < $status_interval) { - $status_timeout = $status_interval; -} - -/** - * @var int $status_timeout - */ -if($status['lastCheck'] + $status_timeout < time()) { - updateStatus(); -} - -function updateStatus() { - global $db, $cache, $config, $status, $status_ip, $status_port; - - // get server status and save it to database - $serverInfo = new OTS_ServerInfo($status_ip, $status_port); - $serverStatus = $serverInfo->status(); - if(!$serverStatus) - { - $status['online'] = false; - $status['players'] = 0; - $status['playersMax'] = 0; - } - else - { - $status['lastCheck'] = time(); // this should be set only if server respond - - $status['online'] = true; - $status['players'] = $serverStatus->getOnlinePlayers(); // counts all players logged in-game, or only connected clients (if enabled on server side) - $status['playersMax'] = $serverStatus->getMaxPlayers(); - - // for status afk thing - if (setting('core.online_afk')) - { - $status['playersTotal'] = 0; - // get amount of players that are currently logged in-game, including disconnected clients (exited) - if($db->hasTable('players_online')) { // tfs 1.x - $status['playersTotal'] = PlayerOnline::count(); - } - else { - $status['playersTotal'] = Player::online()->count(); - } - } - - $uptime = $status['uptime'] = $serverStatus->getUptime(); - $m = date('m', $uptime); - $m = $m > 1 ? "$m months, " : ($m == 1 ? 'month, ' : ''); - $d = date('d', $uptime); - $d = $d > 1 ? "$d days, " : ($d == 1 ? 'day, ' : ''); - $h = date('H', $uptime); - $min = date('i', $uptime); - $status['uptimeReadable'] = "{$m}{$d}{$h}h {$min}m"; - - $status['monsters'] = $serverStatus->getMonstersCount(); - $status['motd'] = $serverStatus->getMOTD(); - - $status['mapAuthor'] = $serverStatus->getMapAuthor(); - $status['mapName'] = $serverStatus->getMapName(); - $status['mapWidth'] = $serverStatus->getMapWidth(); - $status['mapHeight'] = $serverStatus->getMapHeight(); - - $status['server'] = $serverStatus->getServer(); - $status['serverVersion'] = $serverStatus->getServerVersion(); - $status['clientVersion'] = $serverStatus->getClientVersion(); - } - - if($cache->enabled()) { - $cache->set('status', serialize($status), 120); - } - - $tmpVal = null; - foreach($status as $key => $value) { - if(fetchDatabaseConfig('status_' . $key, $tmpVal)) { - updateDatabaseConfig('status_' . $key, $value); - } - else { - registerDatabaseConfig('status_' . $key, $value); - } - } -} diff --git a/system/template.php b/system/template.php index 08ff2e7d..1fa12517 100644 --- a/system/template.php +++ b/system/template.php @@ -24,7 +24,7 @@ if(setting('core.template_allow_change')) //setcookie('template', $template_name, 0, BASE_DIR . '/', $_SERVER["SERVER_NAME"]); $template_name = $_GET['template']; - $cache = Cache::getInstance(); + $cache = app()->get('cache'); if($cache->enabled()) { $cache->delete('template_menus'); } @@ -49,13 +49,10 @@ if(setting('core.template_allow_change')) } } +global $template_path, $template_index; + $themes = Plugins::getThemes(); -if (isset($themes[$template_name])) { - $template_path = $themes[$template_name]; -} -else { - $template_path = 'templates/' . $template_name; -} +$template_path = $themes[$template_name] ?? 'templates/' . $template_name; if(file_exists(BASE . $template_path . '/index.php')) { $template_index = 'index.php'; @@ -63,9 +60,6 @@ if(file_exists(BASE . $template_path . '/index.php')) { elseif(file_exists(BASE . $template_path . '/template.php')) { $template_index = 'template.php'; } -elseif(setting('core.backward_support') && file_exists(BASE . $template_path . '/layout.php')) { - $template_index = 'layout.php'; -} else { $template_name = 'kathrine'; $template_path = 'templates/' . $template_name; @@ -79,58 +73,17 @@ if(file_exists(BASE . $template_path . '/config.php')) { require BASE . $template_path . '/config.php'; } -$tmp = ''; -if ($cache->enabled() && $cache->fetch('template_ini_' . $template_name, $tmp)) { - $template_ini = unserialize($tmp); -} -else { +$template_ini = Cache::remember('template_ini_' . $template_name, 10 * 60, function() use ($template_path) { $file = BASE . $template_path . '/config.ini'; - $exists = file_exists($file); - if ($exists || (setting('core.backward_support') && file_exists(BASE . $template_path . '/layout_config.ini'))) { - if (!$exists) { - $file = BASE . $template_path . '/layout_config.ini'; - } - - $template_ini = parse_ini_file($file); - unset($file); - - if ($cache->enabled()) { - $cache->set('template_ini_' . $template_name, serialize($template_ini), 10 * 60); - } + if (!file_exists($file)) { + return []; } -} -if (isset($template_ini)) { - foreach ($template_ini as $key => $value) { - $config[$key] = $value; - } -} + return parse_ini_file($file); +}); -$template = array(); -$template['link_account_manage'] = getLink('account/manage'); -$template['link_account_create'] = getLink('account/create'); -$template['link_account_lost'] = getLink('account/lost'); -$template['link_account_logout'] = getLink('account/logout'); - -$template['link_news_archive'] = getLink('news/archive'); - -$links = array('news', 'changelog', 'rules', 'downloads', 'characters', 'online', 'highscores', 'powergamers', 'lastkills' => 'last-kills', 'houses', 'guilds', 'wars', 'polls', 'bans', 'team', 'creatures' => 'monsters', 'monsters', 'spells', 'commands', 'exp-stages', 'freeHouses', 'serverInfo', 'exp-table', 'faq', 'points', 'gifts', 'bugtracker', 'gallery'); -foreach($links as $key => $value) { - $key = is_string($key) ? $key : $value; - $template['link_' . $key] = getLink($value); -} - -$template['link_screenshots'] = getLink('gallery'); -$template['link_movies'] = getLink('videos'); - -$template['link_gifts_history'] = getLink('gifts', 'history'); -$forumSetting = setting('core.forum'); -if($forumSetting != '') -{ - if(strtolower($forumSetting) == 'site') - $template['link_forum'] = ""; - else - $template['link_forum'] = ""; +foreach ($template_ini as $key => $value) { + $config[$key] = $value; } $twig->addGlobal('template_name', $template_name); diff --git a/system/twig.php b/system/twig.php index fc3125fe..71478c52 100644 --- a/system/twig.php +++ b/system/twig.php @@ -9,22 +9,15 @@ */ defined('MYAAC') or die('Direct access not allowed!'); -use MyAAC\CsrfToken; -use Twig\Environment as Twig_Environment; use Twig\Extension\DebugExtension as Twig_DebugExtension; -use Twig\Loader\FilesystemLoader as Twig_FilesystemLoader; use Twig\TwigFilter; use Twig\TwigFunction; global $twig, $twig_loader; $dev_mode = (config('env') === 'dev'); -$twig_loader = new Twig_FilesystemLoader(SYSTEM . 'templates'); -$twig = new Twig_Environment($twig_loader, array( - 'cache' => CACHE . 'twig/', - 'auto_reload' => $dev_mode, - 'debug' => $dev_mode -)); +$twig_loader = app()->get('twig-loader'); +$twig = app()->get('twig'); $twig_loader->addPath(PLUGINS); @@ -86,7 +79,7 @@ $function = new TwigFunction('getMonsterLink', function ($s, $p = true) { $twig->addFunction($function); $function = new TwigFunction('getGuildLink', function ($s, $p = true) { - return getGuildLink($s, $p); + return getGuildLink($s, $p); }); $twig->addFunction($function); @@ -96,8 +89,6 @@ $function = new TwigFunction('truncate', function ($s, $n) { $twig->addFunction($function); $function = new TwigFunction('hook', function ($context, $hook, array $params = []) { - global $hooks; - if(is_string($hook)) { if (defined($hook)) { $hook = constant($hook); @@ -109,7 +100,9 @@ $function = new TwigFunction('hook', function ($context, $hook, array $params = } } - $params['context'] = $context; + $params['context'] = $context;# + + $hooks = app()->get('hooks'); $hooks->trigger($hook, $params); }, ['needs_context' => true]); $twig->addFunction($function); @@ -152,4 +145,5 @@ $filter = new TwigFilter('urlencode', function ($s) { $twig->addFilter($filter); unset($function, $filter); +$hooks = app()->get('hooks'); $hooks->trigger(HOOK_TWIG, ['twig' => $twig, 'twig_loader' => $twig_loader]);