Fix imports, throw exceptions

This commit is contained in:
Valithor Obsidion 2025-08-14 16:49:20 -04:00
parent 4d5c345528
commit d40b826dfa
7 changed files with 91 additions and 65 deletions

View File

@ -13,8 +13,13 @@ declare(strict_types=1);
namespace DragonKnight\Actions;
use DragonKnight\DragonKnight;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\render;
use function DragonKnight\special_to_string;
class Help
{
public static function register_routes(Router $r): Router
@ -509,8 +514,8 @@ class Help
{
return render('layouts/help', [
'content' => $content,
'version' => VERSION,
'build' => BUILD,
'version' => DragonKnight::VERSION,
'build' => DragonKnight::BUILD,
]);
}
}

View File

@ -13,10 +13,20 @@ declare(strict_types=1);
namespace DragonKnight\Actions;
use DragonKnight\Lib;
use DragonKnight\Mail;
use DragonKnight\Router;
use function DragonKnight\db;
use function DragonKnight\env;
use function DragonKnight\is_post;
use function DragonKnight\page_title;
use function DragonKnight\redirect;
use function DragonKnight\render;
use function DragonKnight\token;
use function DragonKnight\ul_from_validate_errors;
use function DragonKnight\user;
use function DragonKnight\validate;
class Users
{
public static function register_routes(Router $r): Router
@ -39,14 +49,14 @@ class Users
{
global $auth;
if (Lib::is_post()) {
$form = Lib::validate($_POST, [
if (is_post()) {
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces'],
'password' => ['length:6-255'],
]);
if (! $form['valid']) {
exit(Lib::ul_from_validate_errors($form['errors']));
exit(ul_from_validate_errors($form['errors']));
}
$good = $auth->login($form['data']['username'], $form['data']['password']);
@ -54,12 +64,12 @@ class Users
exit('Invalid username or password. Please go back and try again.');
}
Lib::redirect('/');
redirect('/');
}
Lib::page_title('Login');
page_title('Login');
return Lib::render('login');
return render('login');
}
/**
@ -69,7 +79,7 @@ class Users
{
global $auth;
$auth->logout();
Lib::redirect('/login');
redirect('/login');
}
/**
@ -78,7 +88,7 @@ class Users
public static function register()
{
if (isset($_POST['submit'])) {
$form = Lib::validate($_POST, [
$form = validate($_POST, [
'username' => ['length:3-18', 'alpha-spaces', 'unique:users,username'],
'email' => ['email', 'unique:users,email'],
'confirm_email' => ['confirm'],
@ -88,37 +98,37 @@ class Users
]);
if (! $form['valid']) {
$err = Lib::ul_from_validate_errors($form['errors']);
$err = ul_from_validate_errors($form['errors']);
$page = "The following error(s) occurred when your account was being made:<br><span style=\"color:red;\">$err</span><br>Please go back and try again.";
} else {
$form = $form['data'];
$password = password_hash($form['password'], PASSWORD_ARGON2ID);
$token = Lib::env('verify_email') ? Lib::token(8) : 'g2g';
Lib::db()->query('INSERT INTO users (verify, username, password, email, charclass) VALUES (?, ?, ?, ?, ?)', [
$token = env('verify_email') ? token(8) : 'g2g';
db()->query('INSERT INTO users (verify, username, password, email, charclass) VALUES (?, ?, ?, ?, ?)', [
$token, $form['username'], $password, $form['email'], $form['charclass'],
]);
if (Lib::env('verify_email')) {
if (env('verify_email')) {
if (self::sendregmail($form['email'], $token)) {
$page = 'Your account was created successfully.<br><br>You should receive an Account Verification email shortly. You will need the verification code contained in that email before you are allowed to log in. Once you have received the email, please visit the <a href="users.php?do=verify">Verification Page</a> to enter your code and start playing.';
} else {
$page = 'Your account was created successfully.<br><br>However, there was a problem sending your verification email. Please check with the game administrator to help resolve this problem.';
}
} else {
$page = 'Your account was created succesfully.<br><br>You may now continue to the <a href="/login">Login Page</a> and continue playing '.Lib::env('game_name').'!';
$page = 'Your account was created succesfully.<br><br>You may now continue to the <a href="/login">Login Page</a> and continue playing '.env('game_name').'!';
}
}
} else {
if (Lib::env('verify_email')) {
if (env('verify_email')) {
$verify_text = '<br><span class="small">A verification code will be sent to the address above, and you will not be able to log in without first entering the code. Please be sure to enter your correct email address.</span>';
} else {
$verify_text = '';
}
$page = Lib::render('register', ['verify_text' => $verify_text]);
$page = render('register', ['verify_text' => $verify_text]);
}
Lib::page_title('Register');
page_title('Register');
return $page;
}
@ -130,17 +140,17 @@ class Users
$e = trim($_POST['email'] ?? '');
$t = trim($_POST['token'] ?? '');
$query = Lib::db()->query('SELECT id FROM users WHERE username=? AND email=? AND verify=? LIMIT 1;', [$u, $e, $t]);
$query = db()->query('SELECT id FROM users WHERE username=? AND email=? AND verify=? LIMIT 1;', [$u, $e, $t]);
if ($query === false) {
exit('Verification failed. Go back, double-check your details, and try again.');
}
Lib::db()->query("UPDATE users SET verify='g2g' WHERE username=?;", [$u]);
db()->query("UPDATE users SET verify='g2g' WHERE username=?;", [$u]);
return 'Your account was verified successfully.<br><br>You may now continue to the <a href="/login">Login Page</a> and start playing the game.<br><br>Thanks for playing!';
}
return Lib::render('verify');
return render('verify');
}
public static function lostpassword()
@ -148,14 +158,14 @@ class Users
if (isset($_POST['submit'])) {
$e = trim($_POST['email'] ?? '');
if (! Lib::db()->exists('users', 'email', $e)) {
if (! db()->exists('users', 'email', $e)) {
exit('No account with that email address.');
}
$newpass = Lib::token(16);
$newpass = token(16);
$hashed = password_hash($newpass, PASSWORD_ARGON2ID);
Lib::db()->query('UPDATE users SET password=? WHERE email=?;', [$hashed, $e]);
db()->query('UPDATE users SET password=? WHERE email=?;', [$hashed, $e]);
if (self::sendpassemail($e, $newpass)) {
return 'Your new password was emailed to the address you provided.<br><br>Once you receive it, you may <a href="/login">Log In</a> and continue playing.<br><br>Thank you.';
@ -164,7 +174,7 @@ class Users
return 'There was an error sending your new password.<br><br>Please check with the game administrator for more information.<br><br>We apologize for the inconvience.';
}
return Lib::render('lostpassword');
return render('lostpassword');
}
public static function changepassword()
@ -177,7 +187,7 @@ class Users
$np = $_POST['new_password'] ?? '';
$np2 = $_POST['new_password2'] ?? '';
$user = Lib::db()->query('SELECT password FROM users WHERE username=? LIMIT 1;', [$u]);
$user = db()->query('SELECT password FROM users WHERE username=? LIMIT 1;', [$u]);
$user = $user->fetchArray(SQLITE3_ASSOC);
if ($user === false) {
exit('No account with that username.');
@ -196,7 +206,7 @@ class Users
}
$realnewpass = password_hash($np, PASSWORD_ARGON2ID);
Lib::db()->query('UPDATE users SET password=? WHERE username=?;', [$realnewpass, $u]);
db()->query('UPDATE users SET password=? WHERE username=?;', [$realnewpass, $u]);
$auth->logout();
@ -206,30 +216,30 @@ class Users
public static function settings()
{
if (Lib::is_post()) {
$form = Lib::validate($_POST, [
if (is_post()) {
$form = validate($_POST, [
'game_skin' => ['in:0,1'],
]);
if (! $form['valid']) {
exit(Lib::ul_from_validate_errors($form['errors']));
exit(ul_from_validate_errors($form['errors']));
}
$form = $form['data'];
Lib::user()->game_skin = $form['game_skin'];
Lib::user()->save();
user()->game_skin = $form['game_skin'];
user()->save();
$alert = '<div class="alert">Settings updated</div>';
return $alert.Lib::render('settings');
return $alert.render('settings');
}
return Lib::render('settings');
return render('settings');
}
public static function sendpassemail($emailaddress, $password)
{
$email = <<<HTML
You or someone using your email address submitted a Lost Password application on the {Lib::env('game_name')} server, located at {Lib::env('game_url')}.
You or someone using your email address submitted a Lost Password application on the {env('game_name')} server, located at {env('game_url')}.
We have issued you a new password so you can log back into the game.
@ -238,15 +248,15 @@ class Users
Thanks for playing.
HTML;
return Mail::send_email($emailaddress, Lib::env('game_name').' Lost Password', $email);
return Mail::send_email($emailaddress, env('game_name').' Lost Password', $email);
}
public static function sendregmail($emailaddress, $vercode)
{
$verurl = Lib::env('game_url').'/verify';
$verurl = env('game_url').'/verify';
$email = <<<HTML
You or someone using your email address recently signed up for an account on the {Lib::env('game_name')} server, located at {Lib::env('game_url')}.
You or someone using your email address recently signed up for an account on the {env('game_name')} server, located at {env('game_url')}.
This email is sent to verify your registration email. In order to begin using your account, you must verify your email address.
Please visit the Verification Page ($verurl) and enter the code below to activate your account.
@ -255,6 +265,6 @@ class Users
If you were not the person who signed up for the game, please disregard this message. You will not be emailed again.
HTML;
return Mail::send_email($emailaddress, Lib::env('game_name').' Account Verification', $email);
return Mail::send_email($emailaddress, env('game_name').' Account Verification', $email);
}
}

View File

@ -16,3 +16,10 @@ namespace DragonKnight;
define('VERSION', '1.2.5');
define('BUILD', 'Reawaken');
define('START', microtime(true));
class DragonKnight
{
public const VERSION = '1.2.5';
public const BUILD = 'Reawaken';
}

View File

@ -28,18 +28,18 @@ class Mail
{
// Default configuration
$config = array_merge([
'from' => Lib::env('admin_email', 'noreply@'.$_SERVER['SERVER_NAME']),
'from' => env('admin_email', 'noreply@'.$_SERVER['SERVER_NAME']),
'log_path' => getcwd().'/logs/email.log',
'method' => 'smtp', // 'smtp' or 'log'
'smtp_host' => Lib::env('smtp_host', 'localhost'),
'smtp_port' => Lib::env('smtp_port', 25),
'smtp_username' => Lib::env('smtp_username', null),
'smtp_password' => Lib::env('smtp_password', null),
'smtp_encryption' => Lib::env('smtp_encryption', null),
'smtp_host' => env('smtp_host', 'localhost'),
'smtp_port' => env('smtp_port', 25),
'smtp_username' => env('smtp_username', null),
'smtp_password' => env('smtp_password', null),
'smtp_encryption' => env('smtp_encryption', null),
], $options);
// Always send to log during debug
if (Lib::env('debug', false)) {
if (env('debug', false)) {
$config['method'] = 'log';
}

View File

@ -35,7 +35,7 @@ function index(): string|false
/**
* Show the user their position on the current world map. Only works with a game size of 250 and the default towns 😅.
*/
function show_map()
function show_map(): void
{
$pos = sprintf(
'<div style="position: absolute; width: 5px; height: 5px; border-radius: 1000px; border: solid 1px black; background-color: red; left: %dpx; top: %dpx;"></div>',
@ -56,7 +56,7 @@ function show_character_info(int $id = 0): string
{
$user = $id !== 0 ? User::find($id) : user();
if ($user === false) {
exit('Failed to show info for user ID '.$id);
throw new \RuntimeException('Failed to show info for user ID '.$id);
}
$level = db()->query("SELECT `{$user->charclass}_exp` FROM levels WHERE id=? LIMIT 1;", [$user->level + 1])->fetchArray(SQLITE3_ASSOC);
@ -82,7 +82,7 @@ function show_character_info(int $id = 0): string
/**
* Handle a POST request to send a new babblebox message.
*/
function babblebox()
function babblebox(): ?string
{
if (is_post()) {
$content = trim($_POST['babble']);
@ -95,6 +95,8 @@ function babblebox()
return babblebox_messages();
}
return null;
}
/**
@ -127,7 +129,7 @@ function db(): Database
{
if (! is_dir($path = getcwd().'/db')) {
error_log('Database folder not found at '.$path.'. Please run the installer first.');
exit();
throw new \RuntimeException('Database folder not found. Please run the installer first.');
}
return $GLOBALS['database'] ??= new Database(getcwd().'/db/database.db');
@ -213,7 +215,9 @@ function display_admin($content, $title)
*/
function game_skin(): int
{
return user() !== false ? user()->game_skin : 0;
return user() !== false
? user()->game_skin
: 0;
}
/**
@ -573,7 +577,7 @@ function env_load(string $filePath): void
/**
* Retrieve an environment variable.
*/
function env(string $key, mixed $default = null): mixed
function env(string $key, mixed $default = null)
{
$v = $_ENV[$key] ?? $_SERVER[$key] ?? (getenv($key) ?: $default);
@ -604,7 +608,9 @@ function get_spells_from_list(array|string $spell_ids): array|false
$rows[] = $row;
}
return ! empty($rows) ? $rows : false;
return ! empty($rows)
? $rows
: false;
}
function generate_stat_bar(int $current, int $max): string
@ -627,15 +633,13 @@ function generate_stat_bar(int $current, int $max): string
function create_stat_table(): string
{
$stat_table = '<div class="stat-table">'.
'<div class="stat-row">'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenthp, (int) user()->maxhp).'<div>HP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currentmp, (int) user()->maxmp).'<div>MP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenttp, (int) user()->maxtp).'<div>TP</div></div>'.
'</div>'.
'</div>';
return $stat_table;
return '<div class="stat-table">'.
'<div class="stat-row">'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenthp, (int) user()->maxhp).'<div>HP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currentmp, (int) user()->maxmp).'<div>MP</div></div>'.
'<div class="stat-col">'.generate_stat_bar((int) user()->currenttp, (int) user()->maxtp).'<div>TP</div></div>'.
'</div>'.
'</div>';
}
/**

View File

@ -41,7 +41,7 @@
<div>Powered by <a href="/" target="_new">Dragon Knight</a></div>
<div>&copy; 2024 Sharkk</div>
<?php echo DragonKnight\Render::debug_db_info(); ?>
<div>Version <?php echo VERSION ?> <?php echo BUILD ?></div>
<div>Version <?php echo DragonKnight\DragonKnight::VERSION ?> <?php echo DragonKnight\DragonKnight::BUILD ?></div>
</footer>
<?php if (DragonKnight\env('debug', false)) {

View File

@ -45,7 +45,7 @@
<div>Powered by <a href="/" target="_new">Dragon Knight</a></div>
<div>&copy; 2024 Sharkk</div>
<?php echo DragonKnight\Render::debug_db_info(); ?>
<div>Version <?php echo VERSION ?> <?php echo BUILD ?></div>
<div>Version <?php echo DragonKnight\DragonKnight::VERSION ?> <?php echo DragonKnight\DragonKnight::BUILD ?></div>
</footer>
<?php if (DragonKnight\env('debug', false)) {