feat: Rewrite of the core: avoid globals where possible

Create services for: login, status, router, database, AnonymousStatistics
Drop gesior.backward_support
Drop compat/pages.php
Drop part of compat/classes.php
Move signature to routes
This commit is contained in:
slawkens 2025-03-09 14:41:41 +01:00
parent 3c1210fefa
commit 2c59c4d8f7
35 changed files with 1054 additions and 1174 deletions

33
aac
View File

@ -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();

View File

@ -1,5 +1,8 @@
<?php
use MyAAC\Services\LoginService;
use MyAAC\Services\StatusService;
// few things we'll need
require '../common.php';
@ -9,7 +12,7 @@ const MYAAC_ADMIN = true;
if(file_exists(BASE . 'install') && (!isset($config['installed']) || !$config['installed']))
{
header('Location: ' . BASE_URL . 'install/');
throw new RuntimeException('Setup detected that <b>install/</b> directory exists. Please visit <a href="' . BASE_URL . 'install">this</a> url to start MyAAC Installation.<br/>Delete <b>install/</b> directory if you already installed MyAAC.<br/>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);

156
index.php
View File

@ -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 '<!-- Generated in: ' . round(microtime(true) - START_TIME, 4) . 'ms -->';
echo PHP_EOL . '<!-- Queries done: ' . $db->queries() . ' -->';
if(function_exists('memory_get_peak_usage')) {
echo PHP_EOL . '<!-- Peak memory usage: ' . convert_bytes(memory_get_peak_usage(true)) . ' -->';
}
}
$hooks->trigger(HOOK_FINISH);
$app = new \MyAAC\App\App();
$app->run();

View File

@ -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);
}

View File

@ -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 {}

View File

@ -1,60 +0,0 @@
<?php
/**
* Compat pages (backward support for Gesior AAC)
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @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;
}

View File

@ -1,141 +0,0 @@
<?php
/**
* Database connection
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @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.<br/>' .
'Possible reasons:' .
'<ul>' .
'<li>MySQL is not configured propertly in <i>config.lua</i>.</li>' .
'<li>MySQL server is not running.</li>' .
'</ul>' . $e->getMessage());
}

View File

@ -9,6 +9,7 @@
*/
defined('MYAAC') or die('Direct access not allowed!');
use MyAAC\App\App;
use MyAAC\Cache\Cache;
use MyAAC\CsrfToken;
use MyAAC\Items;
@ -599,10 +600,8 @@ function template_form()
return $twig->render('forms.change_template.html.twig', ['options' => $options]);
}
function getStyle($i)
{
global $config;
return is_int($i / 2) ? $config['darkborder'] : $config['lightborder'];
function getStyle($i) {
return is_int($i / 2) ? config('darkborder') : config('lightborder');
}
$vowels = array('e', 'y', 'u', 'i', 'o', 'a');
@ -1210,7 +1209,7 @@ function clearCache()
{
News::clearCache();
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
$keysToClear = [
'status', 'templates',
@ -1260,7 +1259,7 @@ function clearCache()
// routes cache
clearRouteCache();
global $hooks;
$hooks = app()->get('hooks');
$hooks->trigger(HOOK_CACHE_CLEAR, ['cache' => Cache::getInstance()]);
return true;
@ -1314,9 +1313,6 @@ function getCustomPage($name, &$success): string
$tmp = $page['body'];
global $config;
if(setting('core.backward_support')) {
global $SQL, $main_content, $subtopic;
}
ob_start();
eval($tmp);
@ -1685,6 +1681,15 @@ function getAccountIdentityColumn(): string
return 'id';
}
function app() {
static $_app;
if (!isset($_app)) {
$_app = new App();
}
return $_app;
}
// validator functions
require_once SYSTEM . 'compat/base.php';

View File

@ -17,8 +17,8 @@ use MyAAC\Settings;
defined('MYAAC') or die('Direct access not allowed!');
global $config;
if(!isset($config['installed']) || !$config['installed']) {
$configInstalled = config('installed');
if(!isset($configInstalled) || !$configInstalled) {
throw new RuntimeException('MyAAC has not been installed yet or there was error during installation. Please install again.');
}
@ -30,25 +30,22 @@ if (config('env') === 'dev' || getBoolean(config('enable_debugbar'))) {
$debugBar = new StandardDebugBar();
}
if(empty($config['server_path'])) {
$configServerPath = config('server_path');
if(empty($configServerPath)) {
throw new RuntimeException('Server Path has been not set. Go to config.php and set it.');
}
// take care of trailing slash at the end
if($config['server_path'][strlen($config['server_path']) - 1] !== '/')
$config['server_path'] .= '/';
if($configServerPath[strlen($configServerPath) - 1] !== '/') {
config(['server_path', $configServerPath . '/']);
}
// enable gzip compression if supported by the browser
if(isset($config['gzip_output']) && $config['gzip_output'] && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && str_contains($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && function_exists('ob_gzhandler'))
ob_start('ob_gzhandler');
// cache
global $cache;
$cache = Cache::getInstance();
// event system
global $hooks;
$hooks = new Hooks();
$hooks = app()->get('hooks');
$hooks->load();
$hooks->trigger(HOOK_INIT);
@ -81,9 +78,10 @@ foreach($_REQUEST as $var => $value) {
// load otserv config file
$config_lua_reload = true;
$cache = app()->get('cache');
if($cache->enabled()) {
$tmp = null;
if($cache->fetch('server_path', $tmp) && $tmp == $config['server_path']) {
if($cache->fetch('server_path', $tmp) && $tmp == config('server_path')) {
$tmp = null;
if($cache->fetch('config_lua', $tmp) && $tmp) {
$config['lua'] = unserialize($tmp);
@ -93,31 +91,33 @@ if($cache->enabled()) {
}
if($config_lua_reload) {
$config['lua'] = load_config_lua($config['server_path'] . 'config.lua');
config(['lua', load_config_lua(config('server_path') . 'config.lua')]);
// 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('config_lua', serialize(config('lua')), 2 * 60);
$cache->set('server_path', config('server_path'), 10 * 60);
}
}
unset($tmp);
if(isset($config['lua']['servername']))
$config['lua']['serverName'] = $config['lua']['servername'];
if(configLua('servername') !== null) {
$config['lua']['serverName'] = configLua('servername');
}
if(isset($config['lua']['houserentperiod']))
$config['lua']['houseRentPeriod'] = $config['lua']['houserentperiod'];
if(configLua('houserentperiod') !== null) {
$config['lua']['houseRentPeriod'] = configLua('houserentperiod');
}
// localize data/ directory based on data directory set in config.lua
foreach(array('dataDirectory', 'data_directory', 'datadir') as $key) {
if(!isset($config['lua'][$key][0])) {
if(!isset(configLua($key)[0])) {
break;
}
$foundValue = $config['lua'][$key];
$foundValue = configLua('lua')[$key];
if($foundValue[0] !== '/') {
$foundValue = $config['server_path'] . $foundValue;
$foundValue = config('server_path') . $foundValue;
}
if($foundValue[strlen($foundValue) - 1] !== '/') {// do not forget about trailing slash
@ -126,7 +126,7 @@ foreach(array('dataDirectory', 'data_directory', 'datadir') as $key) {
}
if(!isset($foundValue)) {
$foundValue = $config['server_path'] . 'data/';
$foundValue = config('server_path') . 'data/';
}
$config['data_path'] = $foundValue;
@ -134,9 +134,9 @@ unset($foundValue);
// POT
require_once SYSTEM . 'libs/pot/OTS.php';
$ots = POT::getInstance();
$eloquentConnection = null;
require_once SYSTEM . 'database.php';
global $db;
$db = app()->get('db');
// verify myaac tables exists in database
if(!defined('MYAAC_INSTALL') && !$db->hasTable('myaac_account_actions')) {

View File

@ -98,7 +98,7 @@ class OTS_DB_MySQL extends OTS_Base_DB
}
global $config;
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
$tmp = null;
$need_revalidation = true;
@ -150,7 +150,7 @@ class OTS_DB_MySQL extends OTS_Base_DB
{
global $config;
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
if ($this->clearCacheAfter) {
$cache->delete('database_tables');

View File

@ -33,7 +33,7 @@ class OTS_Groups_List implements IteratorAggregate, Countable
*/
public function __construct($file = '')
{
global $db;
$db = app()->get('db');
if($db->hasTable('groups')) { // read groups from database
foreach($db->query('SELECT `id`, `name`, `access` FROM `groups`;') as $group)
{
@ -47,10 +47,8 @@ class OTS_Groups_List implements IteratorAggregate, Countable
return;
}
if(!isset($file[0]))
{
global $config;
$file = $config['data_path'] . 'XML/groups.xml';
if(!isset($file[0])) {
$file = config('data_path') . 'XML/groups.xml';
}
if(!@file_exists($file)) {
@ -59,7 +57,7 @@ class OTS_Groups_List implements IteratorAggregate, Countable
return;
}
$cache = Cache::getInstance();
$cache = app()->get('cache');
$data = array();
if($cache->enabled())

View File

@ -655,8 +655,7 @@ class OTS_Player extends OTS_Row_DAO
//if($path == '')
// $path = $config['data_path'].'XML/groups.xml';
if( !isset($this->data['group_id']) )
{
if(!isset($this->data['group_id'])) {
throw new E_OTS_NotLoaded();
}
@ -665,8 +664,9 @@ class OTS_Player extends OTS_Row_DAO
global $groups;
$tmp = $groups->getGroup($this->data['group_id']);
if($tmp)
if($tmp) {
return $tmp;
}
return new OTS_Group();
// echo 'error while loading group..';

View File

@ -1,41 +0,0 @@
<?php
/**
* Login manager
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @copyright 2019 MyAAC
* @link https://my-aac.org
*/
defined('MYAAC') or die('Direct access not allowed!');
$logged = false;
$logged_flags = 0;
$account_logged = new OTS_Account();
// stay-logged with sessions
$current_session = getSession('account');
if($current_session)
{
$account_logged->load($current_session);
if($account_logged->isLoaded() && $account_logged->getPassword() == getSession('password')
//&& (!isset($_SESSION['admin']) || admin())
&& (getSession('remember_me') || getSession('last_visit') > time() - 15 * 60)) { // login for 15 minutes if "remember me" is not used
$logged = true;
}
else {
unsetSession('account');
unset($account_logged);
}
}
if($logged) {
$logged_flags = $account_logged->getWebFlags();
$twig->addGlobal('logged', true);
$twig->addGlobal('account_logged', $account_logged);
}
setSession('last_visit', time());
if(defined('PAGE')) {
setSession('last_page', PAGE);
}
setSession('last_uri', $_SERVER['REQUEST_URI']);

View File

@ -8,7 +8,7 @@ use MyAAC\Cache\Cache;
$up = function () use ($db) {
$db->dropTable(TABLE_PREFIX . 'hooks');
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
$cache->delete('hooks');
}
@ -17,7 +17,7 @@ $up = function () use ($db) {
$down = function () use ($db) {
$db->exec(file_get_contents(__DIR__ . '/28-hooks.sql'));
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
$cache->delete('hooks');
}

View File

@ -15,9 +15,9 @@ defined('MYAAC') or die('Direct access not allowed!');
$title = 'Characters';
$groups = new OTS_Groups_List();
function generate_search_form($autofocus = false)
function generate_search_form($autofocus = false): string
{
global $config, $twig;
$twig = app()->get('twig');
return $twig->render('characters.form.html.twig', array(
'link' => getLink('characters'),
'autofocus' => $autofocus
@ -26,7 +26,9 @@ function generate_search_form($autofocus = false)
function retrieve_former_name($name)
{
global $oldName, $db;
global $oldName;
$db = app()->get('db');
if($db->hasTable('player_namelocks') && $db->hasColumn('player_namelocks', 'name')) {
$newNameSql = $db->query('SELECT `name`, `new_name` FROM `player_namelocks` WHERE `name` = ' . $db->quote($name));
@ -42,8 +44,9 @@ function retrieve_former_name($name)
}
$name = '';
if(isset($_REQUEST['name']))
if(isset($_REQUEST['name'])) {
$name = urldecode(stripslashes(ucwords(strtolower($_REQUEST['name']))));
}
if(empty($name))
{
@ -63,14 +66,14 @@ if(!$player->isLoaded())
{
$tmp_zmienna = "";
$tmp_name = retrieve_former_name($name);
while(!empty($tmp_name))
{
while(!empty($tmp_name)) {
$tmp_zmienna = $tmp_name;
$tmp_name = retrieve_former_name($tmp_zmienna);
}
if(!empty($tmp_zmienna))
if(!empty($tmp_zmienna)) {
$player->find($tmp_zmienna);
}
}
if($player->isLoaded() && !$player->isDeleted())

View File

@ -15,6 +15,7 @@ $last_kills = array();
$players_deaths_count = 0;
$tmp = null;
$cache = app()->get('cache');
if($cache->enabled() && $cache->fetch('last_kills', $tmp)) {
$last_kills = unserialize($tmp);
}

View File

@ -0,0 +1,6 @@
<?php
defined('MYAAC') or die('Direct access not allowed!');
chdir(TOOLS . 'signature');
include TOOLS . 'signature/index.php';
exit;

View File

@ -1,363 +0,0 @@
<?php
/**
* Router
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @copyright 2023 MyAAC
* @link https://my-aac.org
*/
use MyAAC\Models\Pages;
use MyAAC\Plugins;
defined('MYAAC') or die('Direct access not allowed!');
if(!isset($content[0]))
$content = '';
// check if site has been closed
$load_it = true;
$site_closed = false;
if(fetchDatabaseConfig('site_closed', $site_closed)) {
$site_closed = ($site_closed == 1);
if($site_closed) {
if(!admin())
{
$title = getDatabaseConfig('site_closed_title');
$content .= '<p class="note">' . getDatabaseConfig('site_closed_message') . '</p><br/>';
$load_it = false;
}
if(!$logged)
{
ob_start();
require SYSTEM . 'pages/account/manage.php';
$content .= ob_get_contents();
ob_end_clean();
$load_it = false;
}
}
}
define('SITE_CLOSED', $site_closed);
// Strip query string (?foo=bar) and decode URI
/** @var string $uri */
if (false !== $pos = strpos($uri, '?')) {
if ($pos !== 1) {
$uri = substr($uri, 0, $pos);
}
else {
$uri = str_replace_first('?', '', $uri);
}
}
$uri = rawurldecode($uri);
if (BASE_DIR !== '') {
$tmp = str_replace_first('/', '', BASE_DIR);
$uri = str_replace_first($tmp, '', $uri);
}
if(0 === strpos($uri, '/')) {
$uri = str_replace_first('/', '', $uri);
}
define('URI', $uri);
if(!$load_it) {
// ignore warnings in some functions/plugins
// page is not loaded anyway
define('PAGE', '');
return;
}
/** @var string $content */
if(SITE_CLOSED && admin())
$content .= '<p class="note">Site is under maintenance (closed mode). Only privileged users can see it.</p>';
$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 '<pre>';
var_dump($route[1], $route[3], $route[2]);
echo '/<pre>';
*/
}
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 '<pre>';
var_dump($routesFinal);
echo '</pre>';
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;
}

View File

@ -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],

View File

@ -213,11 +213,9 @@ return [
'default' => 'myaac_',
],
'backward_support' => [
'hidden' => true,
'name' => 'Gesior Backward Support',
'type' => 'boolean',
'desc' => 'gesior backward support (templates & pages)<br/>' .
'allows using gesior templates and pages with myaac<br/>' .
'might bring some performance when disabled',
'default' => true,
],
'anonymous_usage_statistics' => [

8
system/src/App/Admin.php Normal file
View File

@ -0,0 +1,8 @@
<?php
namespace MyAAC\App;
class Admin
{
}

144
system/src/App/App.php Normal file
View File

@ -0,0 +1,144 @@
<?php
namespace MyAAC\App;
use MyAAC\Hooks;
use MyAAC\Services\AnonymousStatisticsService;
use MyAAC\Services\DatabaseService;
use MyAAC\Services\LoginService;
use MyAAC\Services\RouterService;
use MyAAC\Services\StatusService;
use MyAAC\Settings;
use MyAAC\Visitors;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
class App
{
private bool $isLoggedIn = false;
private array $instances = [];
public function run(): void
{
$configInstalled = config('installed');
if((!isset($configInstalled) || !$configInstalled) && file_exists(BASE . 'install')) {
header('Location: ' . BASE_URL . 'install/');
exit();
}
$template_place_holders = [];
require_once SYSTEM . 'init.php';
require_once SYSTEM . 'template.php';
$loginService = new LoginService();
$this->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 '<!-- Generated in: ' . round(microtime(true) - START_TIME, 4) . 'ms -->';
echo PHP_EOL . '<!-- Queries done: ' . $db->queries() . ' -->';
if(function_exists('memory_get_peak_usage')) {
echo PHP_EOL . '<!-- Peak memory usage: ' . convert_bytes(memory_get_peak_usage(true)) . ' -->';
}
}
$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];
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace MyAAC\App;
use MyAAC\Plugins;
use Symfony\Component\Console\Application;
class Console
{
public function run(): void
{
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__));
$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();
}
}

View File

@ -235,7 +235,7 @@ class CreateCharacter
}
}
global $hooks;
$hooks = app()->get('hooks');
if (!$hooks->trigger(HOOK_ACCOUNT_CREATE_CHARACTER_AFTER,
[
'account' => $account,

View File

@ -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);

View File

@ -716,7 +716,7 @@ class Plugins {
}
}
$cache = Cache::getInstance();
$cache = app()->get('cache');
if($cache->enabled()) {
$cache->delete('templates');
$cache->delete('hooks');

View File

@ -0,0 +1,52 @@
<?php
namespace MyAAC\Services;
use MyAAC\Cache\Cache;
use MyAAC\UsageStatistics;
/*
* anonymous usage statistics
* sent only when user agrees
*/
class AnonymousStatisticsService
{
public function checkReport(): void
{
if(!setting('core.anonymous_usage_statistics')) {
return;
}
$report_time = 30 * 24 * 60 * 60; // report one time per 30 days
$should_report = true;
$cache = app()->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);
}
}
}
}

View File

@ -0,0 +1,153 @@
<?php
namespace MyAAC\Services;
use Illuminate\Database\Capsule\Manager as Capsule;
class DatabaseService
{
private $db;
public function getConnectionHandle()
{
if (!isset($this->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.<br/>' .
'Possible reasons:' .
'<ul>' .
'<li>MySQL is not configured propertly in <i>config.lua</i>.</li>' .
'<li>MySQL server is not running.</li>' .
'</ul>' . $e->getMessage());
}
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace MyAAC\Services;
class LoginService
{
public function checkLogin(): bool
{
global $logged, $logged_flags, $account_logged;
$logged = false;
$logged_flags = 0;
$account_logged = new \OTS_Account();
// stay-logged with sessions
$current_session = getSession('account');
if($current_session) {
$account_logged->load($current_session);
if($account_logged->isLoaded() && $account_logged->getPassword() == getSession('password')
//&& (!isset($_SESSION['admin']) || admin())
&& (getSession('remember_me') || getSession('last_visit') > time() - 15 * 60)) { // login for 15 minutes if "remember me" is not used
$logged = true;
}
else {
unsetSession('account');
unset($account_logged);
}
}
if($logged) {
$logged_flags = $account_logged->getWebFlags();
$twig = app()->get('twig');
$twig->addGlobal('logged', true);
$twig->addGlobal('account_logged', $account_logged);
}
setSession('last_visit', time());
if(defined('PAGE')) {
setSession('last_page', PAGE);
}
setSession('last_uri', $_SERVER['REQUEST_URI']);
app()->setLoggedIn($logged);
return $logged;
}
}

View File

@ -0,0 +1,364 @@
<?php
namespace MyAAC\Services;
use MyAAC\Models\Pages;
use MyAAC\Plugins;
class RouterService
{
public function handleRouting(): array
{
global $content, $logged, $db, $twig, $template_path, $template;
if(!isset($content[0])) {
$content = '';
}
// check if site has been closed
$load_it = true;
$site_closed = false;
if(fetchDatabaseConfig('site_closed', $site_closed)) {
$site_closed = ($site_closed == 1);
if($site_closed) {
if(!admin()) {
$title = getDatabaseConfig('site_closed_title');
$content .= '<p class="note">' . getDatabaseConfig('site_closed_message') . '</p><br/>';
$load_it = false;
}
if(!$logged) {
ob_start();
require SYSTEM . 'pages/account/manage.php';
$content .= ob_get_contents();
ob_end_clean();
$load_it = false;
}
}
}
define('SITE_CLOSED', $site_closed);
$uri = $_SERVER['REQUEST_URI'];
if(str_contains($uri, 'index.php')) {
/** @var TYPE_NAME $uri */
$uri = str_replace_first('/index.php', '', $uri);
}
if(str_starts_with($uri, '/')) {
$uri = str_replace_first('/', '', $uri);
}
// Strip query string (?foo=bar) and decode URI
/** @var string $uri */
if (false !== $pos = strpos($uri, '?')) {
if ($pos !== 1) {
$uri = substr($uri, 0, $pos);
}
else {
$uri = str_replace_first('?', '', $uri);
}
}
$uri = rawurldecode($uri);
if (BASE_DIR !== '') {
$tmp = str_replace_first('/', '', BASE_DIR);
$uri = str_replace_first($tmp, '', $uri);
}
if(0 === strpos($uri, '/')) {
$uri = str_replace_first('/', '', $uri);
}
define('URI', $uri);
if(!$load_it) {
// ignore warnings in some functions/plugins
// page is not loaded anyway
define('PAGE', '');
return [
'title' => 'Maintenance mode',
'content' => $content,
];
}
/** @var string $content */
if(SITE_CLOSED && admin())
$content .= '<p class="note">Site is under maintenance (closed mode). Only privileged users can see it.</p>';
$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 '<pre>';
var_dump($route[1], $route[3], $route[2]);
echo '/<pre>';
*/
}
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 '<pre>';
var_dump($routesFinal);
echo '</pre>';
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;
}
}

View File

@ -0,0 +1,134 @@
<?php
namespace MyAAC\Services;
use MyAAC\Cache\Cache;
use MyAAC\Models\Config;
use MyAAC\Models\Player;
use MyAAC\Models\PlayerOnline;
class StatusService
{
public function checkStatus(): array
{
$status = [];
$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 $status;
}
$fetch_from_db = true;
/**
* @var Cache $cache
*/
$cache = app()->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);
}
}
}
}

View File

@ -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,

View File

@ -1,180 +0,0 @@
<?php
/**
* Server status
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @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);
}
}
}

View File

@ -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'] = "<a href='" . getLink('forum') . "'>";
else
$template['link_forum'] = "<a href='" . $forumSetting . "' target='_blank'>";
foreach ($template_ini as $key => $value) {
$config[$key] = $value;
}
$twig->addGlobal('template_name', $template_name);

View File

@ -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]);