rinkplanner/hub/app/pages.php

739 lines
24 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/** Web-Oberfläche: Routen, Formulare und Admin-Seiten. */
const HUB_RESERVED_USERNAMES = [
'admin', 'administrator', 'root', 'system', 'support', 'moderator',
'rinkplanner', 'hub', 'team', 'test', 'guest', 'gast',
];
function page_handle(string $method, string $path): void
{
$path = '/' . trim($path, '/');
if (!in_array($method, ['GET', 'POST'], true)) {
abort_page(405, t('page.method_not_allowed'));
}
if ($path === '/health') {
health_check();
return;
}
// Sprachwahl über den DE/EN-Umschalter; muss auch ohne Anmeldung gehen.
if ($path === '/language') {
$lang = strtolower(substr(query_string('lang'), 0, 2));
if (in_array($lang, HUB_LOCALES, true)) {
hub_locale_set($lang);
}
redirect(auth_next_url('/'));
}
$user = auth_user();
if ($user !== null && $user['must_change_password'] === 1
&& !in_array($path, ['/account', '/account/password', '/logout', '/language'], true)
) {
flash('info', t('auth.change_password_first'));
redirect('/account');
}
if ($path === '/login') {
page_login($method);
return;
}
if ($path === '/register') {
page_register($method);
return;
}
if ($path === '/logout') {
if ($method !== 'POST' || !csrf_valid()) {
redirect('/');
}
auth_logout();
flash('success', t('auth.logged_out'));
redirect('/login');
}
if ($path === '/') {
page_dashboard($method);
return;
}
if ($path === '/upload') {
page_upload($method);
return;
}
if ($path === '/account') {
page_account($method);
return;
}
if ($path === '/account/password') {
page_account_password($method);
return;
}
if ($path === '/account/tokens') {
page_account_token_create($method);
return;
}
if ($path === '/account/tokens/revoke') {
page_account_token_revoke($method);
return;
}
if ($path === '/admin/invites') {
page_admin_invites($method);
return;
}
if ($path === '/admin/invites/revoke') {
page_admin_invite_revoke($method);
return;
}
if ($path === '/admin/users') {
page_admin_users($method);
return;
}
if ($path === '/admin/users/action') {
page_admin_user_action($method);
return;
}
if ($path === '/admin/routines') {
page_admin_routines($method);
return;
}
if ($path === '/admin/routines/action') {
page_admin_routine_action($method);
return;
}
if ($path === '/admin/audit') {
require_admin_page();
render_page('admin_audit', ['entries' => audit_list(200)], t('page.admin_audit'));
return;
}
if (preg_match('#^/routines/(\d+)$#', $path, $matches) === 1) {
page_routine_detail((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
page_routine_file((int) $matches[1], (string) $matches[2]);
return;
}
if (preg_match('#^/routines/(\d+)/revise$#', $path, $matches) === 1) {
page_routine_revise((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(hide|publish)$#', $path, $matches) === 1) {
page_routine_status((int) $matches[1], (string) $matches[2], $method);
return;
}
abort_page(404, t('page.not_found'));
}
function health_check(): void
{
try {
db()->query('SELECT 1');
header('Content-Type: text/plain; charset=utf-8');
echo "ok\n";
} catch (Throwable) {
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo "db error\n";
}
}
function require_admin_page(): array
{
return auth_require_admin();
}
function page_login(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$error = '';
$login = '';
$next = auth_next_url('/');
if ($method === 'POST') {
csrf_require();
$login = post_string('login');
$password = (string) ($_POST['password'] ?? '');
$result = auth_attempt($login, $password);
if ($result['ok']) {
auth_login($result['user'], isset($_POST['remember']));
redirect(auth_next_url($next));
}
$error = (string) $result['error'];
if (($result['retry'] ?? 0) > 0) {
http_response_code(429);
header('Retry-After: ' . (int) $result['retry']);
}
}
render_page('login', [
'error' => $error,
'login' => $login,
'next' => $next,
], t('page.login'));
}
function username_error(string $username): ?string
{
if (mb_strlen($username, 'UTF-8') < 3 || mb_strlen($username, 'UTF-8') > 32) {
return t('username.length');
}
if (preg_match('/^[a-z0-9](?:[a-z0-9._-]{1,30}[a-z0-9])$/u', $username) !== 1) {
return t('username.charset');
}
if (in_array($username, HUB_RESERVED_USERNAMES, true)) {
return t('username.reserved');
}
return null;
}
function page_register(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$invite = null;
$code = '';
$errors = [];
$input = [
'username' => '',
'display_name' => '',
'email' => '',
];
if ($method === 'GET') {
$code = query_string('code');
$invite = invite_find_valid($code);
if ($invite !== null && !empty($invite['email'])) {
$input['email'] = (string) $invite['email'];
}
} else {
csrf_require();
$code = post_string('code');
$invite = invite_find_valid($code);
$input['username'] = mb_strtolower(post_string('username'));
$input['display_name'] = post_string('display_name');
$input['email'] = post_string('email');
if ($invite === null) {
$errors[] = t('register.invalid_invite');
} elseif (!empty($invite['email']) && $input['email'] === '') {
$input['email'] = (string) $invite['email'];
}
$usernameError = username_error($input['username']);
if ($usernameError !== null) {
$errors[] = $usernameError;
}
if ($input['display_name'] === '') {
$input['display_name'] = $input['username'];
}
if (mb_strlen($input['display_name'], 'UTF-8') > 64) {
$errors[] = t('register.display_name_long');
}
if ($input['email'] !== '' && filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = t('register.email_invalid');
}
if ($invite !== null && !empty($invite['email'])
&& strcasecmp((string) $invite['email'], $input['email']) !== 0
) {
$errors[] = t('register.email_mismatch');
}
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$policy = password_policy_error($password, $input['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = t('register.password_mismatch');
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = t('register.rights_required');
}
if (!$errors && $invite !== null) {
$pdo = db();
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare(
'INSERT INTO users
(username, display_name, email, password_hash, role, status,
must_change_password, auth_epoch, created_at, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)'
);
$now = utc_now();
$stmt->execute([
$input['username'],
$input['display_name'],
$input['email'] !== '' ? $input['email'] : null,
hash_password($password),
'user',
'active',
$now,
$now,
]);
$newId = (int) $pdo->lastInsertId();
if (!invite_consume((int) $invite['id'], $newId)) {
$pdo->rollBack();
$errors[] = t('register.invite_taken');
} else {
audit('invite.use', 'invite', (int) $invite['id'], $input['username'], $newId);
audit('user.register', 'user', $newId, $input['username'], $newId);
$pdo->commit();
}
} catch (PDOException $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
if (str_contains($exception->getMessage(), 'uq_users_username')) {
$errors[] = t('register.username_taken');
} elseif (str_contains($exception->getMessage(), 'uq_users_email')) {
$errors[] = t('register.email_taken');
} else {
throw $exception;
}
}
if (!$errors) {
$user = auth_user_by_id($newId);
if ($user !== null) {
auth_login($user);
flash('success', t('auth.welcome'));
redirect('/');
}
}
}
}
render_page('register', [
'invite' => $invite,
'code' => $code,
'errors' => $errors,
'input' => $input,
], t('page.register'));
}
function page_dashboard(string $method): void
{
$user = auth_require_login();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$mine = query_string('mine') === '1';
$result = routines_query($query, $page, 20, $mine ? (int) $user['id'] : null, $mine);
render_page('dashboard', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
'mine' => $mine,
], t('page.dashboard'));
}
function page_routine_detail(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, t('routine.not_found'));
}
if (!routine_can_view($routine, $user)) {
abort_page(403, t('routine.forbidden'));
}
render_page('routine', [
'routine' => $routine,
'can_edit' => routine_can_edit($routine, $user),
'is_admin' => auth_is_admin($user),
], $routine['title']);
}
function page_routine_file(int $id, string $kind): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, t('routine.not_found'));
}
if (!routine_can_view($routine, $user)) {
abort_page(403, t('routine.forbidden'));
}
routine_send_file($routine, $kind);
}
function page_upload(string $method): void
{
$user = auth_require_login();
$errors = [];
$input = [
'description' => '',
'music_title' => '',
'music_artist' => '',
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = t('upload.quota');
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = t('upload.rights_confirm');
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
if ($duplicate !== null) {
flash('info', t('upload.duplicate'));
redirect('/routines/' . $duplicate);
}
try {
$routineId = routine_create((int) $user['id'], $package);
flash('success', t('upload.published'));
redirect('/routines/' . $routineId);
} catch (Throwable $error) {
hub_log('Upload fehlgeschlagen: ' . $error->getMessage());
$errors[] = t('upload.save_failed');
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => null,
], t('page.upload'));
}
function page_routine_revise(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, t('routine.not_found'));
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, t('routine.edit_forbidden'));
}
$errors = [];
$input = [
'description' => (string) ($routine['description'] ?? ''),
'music_title' => (string) ($routine['music_title'] ?? ''),
'music_artist' => (string) ($routine['music_artist'] ?? ''),
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = t('upload.quota');
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = t('upload.rights_confirm');
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
try {
$revision = routine_add_revision($id, (int) $user['id'], $package);
flash('success', t('revision.saved', ['revision' => $revision]));
redirect('/routines/' . $id);
} catch (Throwable $error) {
hub_log('Revision fehlgeschlagen: ' . $error->getMessage());
$errors[] = t('revision.save_failed');
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => $routine,
], t('page.revision'));
}
function page_routine_status(int $id, string $action, string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/routines/' . $id);
}
csrf_require();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, t('routine.not_found'));
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, t('routine.edit_forbidden'));
}
$status = $action === 'publish' ? 'published' : 'hidden';
routine_set_status($id, $status);
flash('success', $status === 'published' ? t('routine.published_again') : t('routine.hidden_now'));
redirect('/routines/' . $id);
}
function page_account(string $method): void
{
$user = auth_require_login();
render_page('account', [
'tokens' => tokens_list((int) $user['id']),
], t('page.account'));
}
function page_account_password(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$current = (string) ($_POST['current_password'] ?? '');
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$errors = [];
if (!password_verify($current, (string) $user['password_hash'])) {
$errors[] = t('account.current_wrong');
}
$policy = password_policy_error($password, (string) $user['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = t('register.password_mismatch');
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
redirect('/account');
}
db()->prepare(
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0 WHERE id = ?'
)->execute([hash_password($password), utc_now(), (int) $user['id']]);
auth_revoke_sessions((int) $user['id']);
audit('user.password_change', 'user', (int) $user['id']);
flash('success', t('account.password_changed'));
redirect('/account');
}
function page_account_token_create(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$name = post_string('name');
if ($name === '') {
$name = 'App';
}
$created = token_create((int) $user['id'], $name);
flash_secret(t('token.created'), $created['token']);
redirect('/account');
}
function page_account_token_revoke(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$tokenId = (int) post_string('token_id');
if (token_revoke($tokenId, (int) $user['id'])) {
audit('token.revoke', 'token', $tokenId);
flash('success', t('token.revoked'));
} else {
flash('error', t('token.not_found'));
}
redirect('/account');
}
function page_admin_invites(string $method): void
{
$admin = require_admin_page();
if ($method === 'POST') {
csrf_require();
$note = post_string('note');
$email = post_string('email');
$days = (int) post_string('expires_days', '30');
$errors = [];
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = t('register.email_invalid');
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
} else {
$code = invite_create($note, $email, $days, (int) $admin['id']);
$publicUrl = rtrim((string) config('app.public_url', ''), '/');
$link = $publicUrl . '/register?code=' . rawurlencode($code);
flash_secret(t('invite.created_label'), $code . ' – Link: ' . $link);
flash('success', t('invite.created'));
}
redirect('/admin/invites');
}
render_page('admin_invites', [
'invites' => invites_list(),
], t('page.admin_invites'));
}
function page_admin_invite_revoke(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/invites');
}
csrf_require();
$inviteId = (int) post_string('invite_id');
if (invite_revoke($inviteId)) {
audit('invite.revoke', 'invite', $inviteId);
flash('success', t('invite.revoked'));
} else {
flash('error', t('invite.revoke_failed'));
}
redirect('/admin/invites');
}
function page_admin_users(string $method): void
{
require_admin_page();
$users = db()->query(
'SELECT u.*, (SELECT COUNT(*) FROM routines r WHERE r.owner_id = u.id) AS routine_count
FROM users u ORDER BY u.created_at DESC, u.id DESC'
)->fetchAll();
render_page('admin_users', ['users' => $users], t('page.admin_users'));
}
function page_admin_user_action(string $method): void
{
$admin = require_admin_page();
if ($method !== 'POST') {
redirect('/admin/users');
}
csrf_require();
$targetId = (int) post_string('user_id');
$action = post_string('action');
$target = auth_user_by_id($targetId);
if ($target === null) {
flash('error', t('user.not_found'));
redirect('/admin/users');
}
if ($targetId === (int) $admin['id']) {
flash('error', t('user.self_change'));
redirect('/admin/users');
}
if ($action === 'disable') {
db()->prepare("UPDATE users SET status = 'disabled' WHERE id = ?")->execute([$targetId]);
auth_revoke_sessions($targetId);
audit('user.disable', 'user', $targetId, (string) $target['username']);
flash('success', t('user.disabled'));
} elseif ($action === 'enable') {
db()->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$targetId]);
audit('user.enable', 'user', $targetId, (string) $target['username']);
flash('success', t('user.enabled'));
} elseif ($action === 'reset') {
$alphabet = HUB_INVITE_ALPHABET;
$temp = '';
for ($i = 0; $i < 12; $i++) {
$temp .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
db()->prepare(
'UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = ? WHERE id = ?'
)->execute([hash_password($temp), utc_now(), $targetId]);
auth_revoke_sessions($targetId);
audit('user.password_reset', 'user', $targetId, (string) $target['username']);
flash_secret(t('user.temp_password', ['user' => $target['username']]), $temp);
flash('info', t('user.must_change'));
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', t('user.delete_confirm_required'));
redirect('/admin/users');
}
$stmt = db()->prepare('SELECT id FROM routines WHERE owner_id = ?');
$stmt->execute([$targetId]);
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $routineId) {
routine_delete((int) $routineId);
}
db()->prepare('UPDATE invites SET revoked_at = ? WHERE used_by = ? AND revoked_at IS NULL')
->execute([utc_now(), $targetId]);
audit('user.delete', 'user', $targetId, (string) $target['username']);
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$targetId]);
flash('success', t('user.deleted'));
} else {
flash('error', t('action.unknown'));
}
redirect('/admin/users');
}
function page_admin_routines(string $method): void
{
require_admin_page();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$result = routines_query($query, $page, 50, null, true);
render_page('admin_routines', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
], t('page.admin_routines'));
}
function page_admin_routine_action(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/routines');
}
csrf_require();
$routineId = (int) post_string('routine_id');
$action = post_string('action');
$routine = routine_fetch($routineId);
if ($routine === null) {
flash('error', t('routine.not_found_short'));
redirect('/admin/routines');
}
if ($action === 'hide' || $action === 'publish') {
routine_set_status($routineId, $action === 'publish' ? 'published' : 'hidden');
flash('success', t('admin.status_changed'));
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', t('user.delete_confirm_required'));
redirect('/admin/routines');
}
routine_delete($routineId);
flash('success', t('routine.deleted'));
} else {
flash('error', t('action.unknown'));
}
redirect('/admin/routines');
}
function audit_list(int $limit = 200): array
{
$limit = max(1, min($limit, 500));
return db()->query(
"SELECT a.*, u.username AS actor_name
FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
ORDER BY a.created_at DESC, a.id DESC LIMIT $limit"
)->fetchAll();
}