Made config functions into a static class.

This commit is contained in:
flash 2019-12-03 19:52:20 +01:00
parent e1211859a6
commit 7cfdfc6bd8
18 changed files with 123 additions and 131 deletions

View file

@ -2,8 +2,8 @@
> Misuzu can and will steal your lunch money.
## Requirements
- PHP 7.3
- MariaDB 10.3
- PHP 7.4
- MariaDB 10.4
- [Composer](https://getcomposer.org/)
- [node.js](https://nodejs.org/) (for the typescript and less compilers)
- [Yarn](https://yarnpkg.com/)

View file

@ -7,7 +7,7 @@ use PDO;
define('MSZ_STARTUP', microtime(true));
define('MSZ_ROOT', __DIR__);
define('MSZ_DEBUG', is_file(MSZ_ROOT . '/.debug'));
define('MSZ_PHP_MIN_VER', '7.3.0');
define('MSZ_PHP_MIN_VER', '7.4.0');
if(version_compare(PHP_VERSION, MSZ_PHP_MIN_VER, '<')) {
die('Misuzu requires <i>at least</i> PHP <b>' . MSZ_PHP_MIN_VER . '</b> to run.');
@ -39,7 +39,6 @@ require_once 'src/audit_log.php';
require_once 'src/changelog.php';
require_once 'src/colour.php';
require_once 'src/comments.php';
require_once 'src/config.php';
require_once 'src/csrf.php';
require_once 'src/emotes.php';
require_once 'src/general.php';
@ -101,27 +100,27 @@ DB::init(DB::buildDSN($dbConfig), $dbConfig['username'] ?? '', $dbConfig['passwo
",
]);
config_init();
Config::init();
mail_settings([
'method' => config_get('mail.method', MSZ_CFG_STR),
'host' => config_get('mail.host', MSZ_CFG_STR),
'port' => config_get('mail.port', MSZ_CFG_INT, 587),
'encryption' => config_get('mail.encryption', MSZ_CFG_STR),
'username' => config_get('mail.username', MSZ_CFG_STR),
'password' => config_get('mail.password', MSZ_CFG_STR),
'sender_email' => config_get('mail.sender.address', MSZ_CFG_STR),
'sender_name' => config_get('mail.sender.name', MSZ_CFG_STR),
'method' => Config::get('mail.method', Config::TYPE_STR),
'host' => Config::get('mail.host', Config::TYPE_STR),
'port' => Config::get('mail.port', Config::TYPE_INT, 587),
'encryption' => Config::get('mail.encryption', Config::TYPE_STR),
'username' => Config::get('mail.username', Config::TYPE_STR),
'password' => Config::get('mail.password', Config::TYPE_STR),
'sender_email' => Config::get('mail.sender.address', Config::TYPE_STR),
'sender_name' => Config::get('mail.sender.name', Config::TYPE_STR),
]);
if(!empty($errorReporter)) {
$errorReporter->setReportInfo(
config_get('error_report.url', MSZ_CFG_STR),
config_get('error_report.secret', MSZ_CFG_STR)
Config::get('error_report.url', Config::TYPE_STR),
Config::get('error_report.secret', Config::TYPE_STR)
);
}
// replace this with a better storage mechanism
define('MSZ_STORAGE', config_get('storage.path', MSZ_CFG_STR, MSZ_ROOT . '/store'));
define('MSZ_STORAGE', Config::get('storage.path', Config::TYPE_STR, MSZ_ROOT . '/store'));
mkdirs(MSZ_STORAGE, true);
if(PHP_SAPI === 'cli') {
@ -346,8 +345,8 @@ MIG;
break;
case 'twitter-auth':
$apiKey = config_get('twitter.api.key', MSZ_CFG_STR);
$apiSecret = config_get('twitter.api.secret', MSZ_CFG_STR);
$apiKey = Config::get('twitter.api.key', Config::TYPE_STR);
$apiSecret = Config::get('twitter.api.secret', Config::TYPE_STR);
if(empty($apiKey) || empty($apiSecret)) {
echo 'No Twitter api keys set in config.' . PHP_EOL;
@ -398,7 +397,7 @@ MIG;
exit;
}
geoip_init(config_get('geoip.database', MSZ_CFG_STR, '/var/lib/GeoIP/GeoLite2-Country.mmdb'));
geoip_init(Config::get('geoip.database', Config::TYPE_STR, '/var/lib/GeoIP/GeoLite2-Country.mmdb'));
if(!MSZ_DEBUG) {
$twigCache = sys_get_temp_dir() . '/msz-tpl-cache-' . md5(MSZ_ROOT);
@ -412,10 +411,10 @@ MIG;
]);
tpl_var('globals', [
'site_name' => config_get('site.name', MSZ_CFG_STR, 'Misuzu'),
'site_description' => config_get('site.desc', MSZ_CFG_STR),
'site_url' => config_get('site.url', MSZ_CFG_STR),
'site_twitter' => config_get('social.twitter', MSZ_CFG_STR),
'site_name' => Config::get('site.name', Config::TYPE_STR, 'Misuzu'),
'site_description' => Config::get('site.desc', Config::TYPE_STR),
'site_url' => Config::get('site.url', Config::TYPE_STR),
'site_twitter' => Config::get('social.twitter', Config::TYPE_STR),
]);
tpl_add_path(MSZ_ROOT . '/templates');
@ -474,19 +473,19 @@ MIG;
}
csrf_settings(
config_get('csrf.secret', MSZ_CFG_STR, 'insecure'),
Config::get('csrf.secret', Config::TYPE_STR, 'insecure'),
empty($userDisplayInfo) ? ip_remote_address() : $cookieData['session_token']
);
if(config_get('private.enabled', MSZ_CFG_BOOL)) {
if(Config::get('private.enabled', Config::TYPE_BOOL)) {
$onLoginPage = $_SERVER['PHP_SELF'] === url('auth-login');
$onPasswordPage = parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH) === url('auth-forgot');
$misuzuBypassLockdown = !empty($misuzuBypassLockdown) || $onLoginPage;
if(!$misuzuBypassLockdown) {
if(user_session_active()) {
$privatePermCat = config_get('private.perm.cat', MSZ_CFG_STR);
$privatePermVal = config_get('private.perm.val', MSZ_CFG_INT);
$privatePermCat = Config::get('private.perm.cat', Config::TYPE_STR);
$privatePermVal = Config::get('private.perm.val', Config::TYPE_INT);
if(!empty($privatePermCat) && $privatePermVal > 0) {
if(!perms_check_user($privatePermCat, $userDisplayInfo['user_id'], $privatePermVal)) {
@ -494,7 +493,7 @@ MIG;
user_session_stop(); // au revoir
}
}
} elseif(!$onLoginPage && !($onPasswordPage && config_get('private.allow_password_reset', MSZ_CFG_BOOL, true))) {
} elseif(!$onLoginPage && !($onPasswordPage && Config::get('private.allow_password_reset', Config::TYPE_BOOL, true))) {
url_redirect('auth-login');
exit;
}

View file

@ -17,9 +17,9 @@ if(!empty($_GET['resolve_user']) && is_string($_GET['resolve_user'])) {
}
$notices = [];
$siteIsPrivate = config_get('private.enable', MSZ_CFG_BOOL);
$loginPermCat = $siteIsPrivate ? config_get('private.perm.cat', MSZ_CFG_STR) : '';
$loginPermVal = $siteIsPrivate ? config_get('private.perm.val', MSZ_CFG_INT) : 0;
$siteIsPrivate = Config::get('private.enable', Config::TYPE_BOOL);
$loginPermCat = $siteIsPrivate ? Config::get('private.perm.cat', Config::TYPE_STR) : '';
$loginPermVal = $siteIsPrivate ? Config::get('private.perm.val', Config::TYPE_INT) : 0;
$ipAddress = ip_remote_address();
$remainingAttempts = user_login_attempts_remaining($ipAddress);
@ -112,8 +112,8 @@ $loginUsername = !empty($_POST['login']['username']) && is_string($_POST['login'
!empty($_GET['username']) && is_string($_GET['username']) ? $_GET['username'] : ''
);
$loginRedirect = $welcomeMode ? url('index') : (!empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : null) ?? $_SERVER['HTTP_REFERER'] ?? url('index');
$sitePrivateMessage = $siteIsPrivate ? config_get('private.msg', MSZ_CFG_STR) : '';
$canResetPassword = $siteIsPrivate ? config_get('private.allow_password_reset', MSZ_CFG_BOOL, true) : true;
$sitePrivateMessage = $siteIsPrivate ? Config::get('private.msg', Config::TYPE_STR) : '';
$canResetPassword = $siteIsPrivate ? Config::get('private.allow_password_reset', Config::TYPE_BOOL, true) : true;
$canRegisterAccount = !$siteIsPrivate;
echo tpl_render('auth.login', [

View file

@ -23,8 +23,8 @@ if($userId > 0 && empty($username)) {
}
$notices = [];
$siteIsPrivate = config_get('private.enable', MSZ_CFG_BOOL);
$canResetPassword = $siteIsPrivate ? config_get('private.allow_password_reset', MSZ_CFG_BOOL, true) : true;
$siteIsPrivate = Config::get('private.enable', Config::TYPE_BOOL);
$canResetPassword = $siteIsPrivate ? Config::get('private.allow_password_reset', Config::TYPE_BOOL, true) : true;
$ipAddress = ip_remote_address();
$remainingAttempts = user_login_attempts_remaining($ipAddress);

View file

@ -18,8 +18,8 @@ $leaderboardIdLength = strlen($leaderboardId);
$leaderboardYear = $leaderboardIdLength === 4 || $leaderboardIdLength === 6 ? substr($leaderboardId, 0, 4) : null;
$leaderboardMonth = $leaderboardIdLength === 6 ? substr($leaderboardId, 4, 2) : null;
$unrankedForums = !empty($_GET['allow_unranked']) ? [] : config_get('forum_leader.unranked.forum', MSZ_CFG_ARR);
$unrankedTopics = !empty($_GET['allow_unranked']) ? [] : config_get('forum_leader.unranked.topic', MSZ_CFG_ARR);
$unrankedForums = !empty($_GET['allow_unranked']) ? [] : Config::get('forum_leader.unranked.forum', Config::TYPE_ARR);
$unrankedTopics = !empty($_GET['allow_unranked']) ? [] : Config::get('forum_leader.unranked.topic', Config::TYPE_ARR);
$leaderboards = forum_leaderboard_categories();
$leaderboard = forum_leaderboard_listing($leaderboardYear, $leaderboardMonth, $unrankedForums, $unrankedTopics);

View file

@ -9,12 +9,12 @@ $showActivityFeed = false; /*user_session_active()
if($showActivityFeed) {
// load activity shit garbage here
} else {
if(config_get('social.embed_linked', MSZ_CFG_BOOL)) {
if(Config::get('social.embed_linked', Config::TYPE_BOOL)) {
tpl_var('linked_data', [
'name' => config_get('site.name', MSZ_CFG_STR, 'Misuzu'),
'url' => config_get('site.url', MSZ_CFG_STR),
'logo' => config_get('site.ext_logo', MSZ_CFG_STR),
'same_as' => config_get('social.linked', MSZ_CFG_ARR),
'name' => Config::get('site.name', Config::TYPE_STR, 'Misuzu'),
'url' => Config::get('site.url', Config::TYPE_STR),
'logo' => Config::get('site.ext_logo', Config::TYPE_STR),
'same_as' => Config::get('social.linked', Config::TYPE_ARR),
]);
}

View file

@ -36,10 +36,10 @@ if(!empty($_POST['post']) && csrf_verify_request()) {
);
if(!$originalPostId && $isFeatured) {
$twitterApiKey = config_get('twitter.api.key', MSZ_CFG_STR);
$twitterApiSecret = config_get('twitter.api.secret', MSZ_CFG_STR);
$twitterToken = config_get('twitter.token.key', MSZ_CFG_STR);
$twitterTokenSecret = config_get('twitter.token.secret', MSZ_CFG_STR);
$twitterApiKey = Config::get('twitter.api.key', Config::TYPE_STR);
$twitterApiSecret = Config::get('twitter.api.secret', Config::TYPE_STR);
$twitterToken = Config::get('twitter.token.key', Config::TYPE_STR);
$twitterTokenSecret = Config::get('twitter.token.secret', Config::TYPE_STR);
if(!empty($twitterApiKey) && !empty($twitterApiSecret)
&& !empty($twitterToken) && !empty($twitterTokenSecret)) {

View file

@ -31,7 +31,7 @@ if(!$posts) {
header("Content-Type: application/{$feedMode}+xml; charset=utf-8");
echo news_feed($feedMode, $posts, [
'title' => config_get('site.name', MSZ_CFG_STR, 'Misuzu') . ' » ' . ($category['category_name'] ?? 'Featured News'),
'title' => Config::get('site.name', Config::TYPE_STR, 'Misuzu') . ' » ' . ($category['category_name'] ?? 'Featured News'),
'subtitle' => $category['category_description'] ?? 'A live featured news feed.',
'html-url' => empty($category) ? url('news-index') : url('news-category', ['category' => $category['category_id']]),
'feed-url' => empty($category) ? url("news-feed-{$feedMode}") : url("news-category-feed-{$feedMode}", ['category' => $category['category_id']]),

View file

@ -35,12 +35,12 @@ if(empty($parsedUrl['scheme'])
return;
}
if(!config_get('media_proxy.enable', MSZ_CFG_BOOL)) {
if(!Config::get('media_proxy.enable', Config::TYPE_BOOL)) {
redirect($proxyUrlDecoded);
return;
}
$proxySecret = config_get('media_proxy.secret', MSZ_CFG_STR, 'insecure');
$proxySecret = Config::get('media_proxy.secret', Config::TYPE_STR, 'insecure');
$expectedHash = hash_hmac('sha256', $proxyUrl, $proxySecret);
if(!hash_equals($expectedHash, $proxyHash)) {

View file

@ -54,7 +54,7 @@ if(!user_relation_set($userId, $subjectId, $relationType)) {
if(($relationType === MSZ_USER_RELATION_NONE || $relationType === MSZ_USER_RELATION_FOLLOW)
&& in_array($subjectId, config_get('relations.replicate', MSZ_CFG_ARR))) {
&& in_array($subjectId, Config::get('relations.replicate', Config::TYPE_ARR))) {
user_relation_set($subjectId, $userId, $relationType);
}

View file

@ -46,7 +46,7 @@ if($isVerifiedRequest && isset($_POST['tfa']['enable']) && (bool)$twoFactorInfo[
'settings_2fa_image' => totp_qrcode(totp_uri(
sprintf(
'%s:%s',
config_get('site.name', MSZ_CFG_STR, 'Misuzu'),
Config::get('site.name', Config::TYPE_STR, 'Misuzu'),
$twoFactorInfo['username']
),
$tfaKey,

View file

@ -21,11 +21,11 @@ $canViewImages = !$userExists
switch($userAssetsMode) {
case 'avatar':
if(!$canViewImages) {
$filename = config_get('avatar.banned', MSZ_CFG_STR, MSZ_ROOT . '/public/images/banned-avatar.png');
$filename = Config::get('avatar.banned', Config::TYPE_STR, MSZ_ROOT . '/public/images/banned-avatar.png');
break;
}
$filename = config_get('avatar.default', MSZ_CFG_STR, MSZ_ROOT . '/public/images/no-avatar.png');
$filename = Config::get('avatar.default', Config::TYPE_STR, MSZ_ROOT . '/public/images/no-avatar.png');
if(!$userExists) {
break;

62
src/Config.php Normal file
View file

@ -0,0 +1,62 @@
<?php
namespace Misuzu;
use PDO;
use PDOException;
class Config {
public const TYPE_ANY = '';
public const TYPE_STR = 'string';
public const TYPE_INT = 'integer';
public const TYPE_BOOL = 'boolean';
public const TYPE_ARR = 'array';
public const DEFAULTS = [
self::TYPE_ANY => null,
self::TYPE_STR => '',
self::TYPE_INT => 0,
self::TYPE_BOOL => false,
self::TYPE_ARR => [],
];
private static $config = [];
public static function init(): void {
try {
$config = DB::prepare('SELECT * FROM `msz_config`')->fetchAll();
} catch(PDOException $ex) {
return;
}
foreach($config as $record) {
self::$config[$record['config_name']] = unserialize($record['config_value']);
}
}
public static function get(string $key, string $type = self::TYPE_ANY, $default = null) {
$value = self::$config[$key] ?? null;
if($type !== self::TYPE_ANY && gettype($value) !== $type)
$value = null;
return $value ?? $default ?? self::DEFAULTS[$type];
}
public static function set(string $key, $value, bool $soft = false): void {
self::$config[$key] = $value;
if(!$soft) {
$value = serialize($value);
DB::prepare('
REPLACE INTO `msz_config`
(`config_name`, `config_value`)
VALUES
(:name, :value)
')->bind('name', $key)
->bind('value', $value)
->execute();
}
}
}

View file

@ -8,7 +8,7 @@ function geoip_init(?string $database = null): void {
$existing->close();
}
geoip_instance(new GeoIPDBReader($database ?? config_get('geoip.database')));
geoip_instance(new GeoIPDBReader($database ?? \Misuzu\Config::get('geoip.database')));
}
function geoip_instance(?GeoIPDBReader $newInstance = null): ?GeoIPDBReader {

View file

@ -61,9 +61,9 @@ function user_avatar_is_allowed_type(int $type): bool {
function user_avatar_default_options(): array {
return [
'max_width' => config_get('avatar.max_width', MSZ_CFG_INT, 1000),
'max_height' => config_get('avatar.max_height', MSZ_CFG_INT, 1000),
'max_size' => config_get('avatar.max_height', MSZ_CFG_INT, 500000),
'max_width' => \Misuzu\Config::get('avatar.max_width', \Misuzu\Config::TYPE_INT, 1000),
'max_height' => \Misuzu\Config::get('avatar.max_height', \Misuzu\Config::TYPE_INT, 1000),
'max_size' => \Misuzu\Config::get('avatar.max_height', \Misuzu\Config::TYPE_INT, 500000),
];
}

View file

@ -93,9 +93,9 @@ function user_background_is_allowed_type(int $type): bool {
function user_background_default_options(): array {
return [
'max_width' => config_get('background.max_width', MSZ_CFG_INT, 3840),
'max_height' => config_get('background.max_height', MSZ_CFG_INT, 2160),
'max_size' => config_get('background.max_height', MSZ_CFG_INT, 1000000),
'max_width' => \Misuzu\Config::get('background.max_width', \Misuzu\Config::TYPE_INT, 3840),
'max_height' => \Misuzu\Config::get('background.max_height', \Misuzu\Config::TYPE_INT, 2160),
'max_size' => \Misuzu\Config::get('background.max_height', \Misuzu\Config::TYPE_INT, 1000000),
];
}

View file

@ -1,69 +0,0 @@
<?php
define('MSZ_CFG_ANY', '');
define('MSZ_CFG_STR', 'string');
define('MSZ_CFG_INT', 'integer');
define('MSZ_CFG_BOOL', 'boolean');
define('MSZ_CFG_ARR', 'array');
define('MSZ_CFG_DEFAULTS', [
MSZ_CFG_ANY => null,
MSZ_CFG_STR => '',
MSZ_CFG_INT => 0,
MSZ_CFG_BOOL => false,
MSZ_CFG_ARR => [],
]);
function config_store(?array $append = null): array {
static $store = [];
if(!is_null($append)) {
$store = array_merge($store, $append);
}
return $store;
}
function config_init(): void {
try {
$dbconfig = \Misuzu\DB::prepare('SELECT * FROM `msz_config`')->fetchAll();
} catch (PDOException $ex) {
return;
}
$config = [];
foreach($dbconfig as $record)
$config[$record['config_name']] = unserialize($record['config_value']);
config_store($config);
}
function config_get(string $key, string $type = MSZ_CFG_ANY, $default = null) {
$value = config_store()[$key] ?? null;
if($type !== MSZ_CFG_ANY && gettype($value) !== $type)
$value = null;
return $value ?? $default ?? MSZ_CFG_DEFAULTS[$type];
}
function config_set(string $key, $value, bool $soft = false): void {
config_store([$key => $value]);
if($soft)
return;
$value = serialize($value);
$saveVal = \Misuzu\DB::prepare('
INSERT INTO `msz_config`
(`config_name`, `config_value`)
VALUES
(:name, :value_1)
ON DUPLICATE KEY UPDATE
`config_value` = :value_2
');
$saveVal->bind('name', $key);
$saveVal->bind('value_1', $value);
$saveVal->bind('value_2', $value);
$saveVal->execute();
}

View file

@ -248,11 +248,11 @@ function url_construct(string $url, array $query = [], ?string $fragment = null)
}
function url_proxy_media(?string $url): ?string {
if(empty($url) || !config_get('media_proxy.enable', MSZ_CFG_BOOL) || is_local_url($url)) {
if(empty($url) || !\Misuzu\Config::get('media_proxy.enable', \Misuzu\Config::TYPE_BOOL) || is_local_url($url)) {
return $url;
}
$secret = config_get('media_proxy.secret', MSZ_CFG_STR, 'insecure');
$secret = \Misuzu\Config::get('media_proxy.secret', \Misuzu\Config::TYPE_STR, 'insecure');
$url = \Misuzu\Base64::encode($url, true);
$hash = hash_hmac('sha256', $url, $secret);