Bei ~150 Empfängern lief der synchrone SMTP-Versand in die Zeitlimits des Shared Hosts; bei Abbruch gingen bereits verschickte Mails ins Leere und der Protokolleintrag fehlte. Jetzt verschickt jeder Aufruf 10 Mails, der Fortschritt liegt in der Session und wird pro Empfänger gesichert. Die Fortschrittsseite stößt die Blöcke per fetch an, ein offener Rest lässt sich auf der Übersicht fortsetzen. Ein Cron-Job ist dafür nicht nötig.
1289 lines
53 KiB
PHP
1289 lines
53 KiB
PHP
<?php
|
||
|
||
// Einheitliche Zeitzone: Die Anpfiff-Zeiten in der DB sind deutsche Lokalzeit.
|
||
// Ohne diese Zeile hängt die Tipp-Sperre (Game::isLocked) von der im Server
|
||
// konfigurierten PHP-Zeitzone ab und wäre z. B. bei UTC eine Stunde zu spät.
|
||
date_default_timezone_set('Europe/Berlin');
|
||
|
||
// Lade den minimalistischen Autoloader
|
||
require_once __DIR__ . '/../src/autoload.php';
|
||
|
||
// Unbehandelte Fehler protokollieren und eine lesbare Fehlerseite zeigen,
|
||
// statt einer leeren 500-Antwort (siehe docs/betriebsdiagnose.md).
|
||
App\Core\ErrorHandler::register();
|
||
|
||
// Auth-System initialisieren
|
||
App\Core\Auth::start();
|
||
|
||
// HTML-Seiten nicht cachen: Sie enthalten den Login-Status und dürfen nach
|
||
// Ablauf der Session nicht als veraltete, eingeloggte Ansicht erscheinen.
|
||
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
|
||
header('Pragma: no-cache');
|
||
header('Expires: 0');
|
||
|
||
use App\Core\Database;
|
||
use App\Core\Auth;
|
||
use App\Core\ErrorLog;
|
||
use App\Core\Iban;
|
||
use App\Core\Mailer;
|
||
use App\Core\WebPush;
|
||
use App\Models\Game;
|
||
use App\Models\Tipp;
|
||
use App\Models\User;
|
||
use App\Models\Round;
|
||
use App\Models\Season;
|
||
use App\Models\Ranking;
|
||
use App\Models\Payment;
|
||
use App\Models\Quota;
|
||
use App\Models\Roundmail;
|
||
use App\Models\Setting;
|
||
use App\Models\Team;
|
||
use App\Models\Question;
|
||
use App\Models\FetcherLog;
|
||
use App\Models\PushSubscription;
|
||
|
||
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||
$page = $_GET['page'] ?? null;
|
||
|
||
// Home-Seite erkennen
|
||
if (($uri === '/' || $uri === '/index.php') && $page === null) {
|
||
$page = 'home';
|
||
}
|
||
|
||
// Routing basierend auf Query-Parametern
|
||
if ($page === 'reminder') {
|
||
// Von außen per Cron aufgerufen, ohne Login und ohne Token.
|
||
header('Content-Type: text/plain; charset=UTF-8');
|
||
try {
|
||
$appUrl = getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
|
||
// Fehlerlog begrenzen (No-Op, solange die Datei unter 5 MB bleibt)
|
||
ErrorLog::rotateIfNeeded();
|
||
// Aufräumen läuft bei jedem Aufruf, auch wenn keine Erinnerung fällig ist
|
||
echo Roundmail::deleteOldReminders() . " alte Erinnerungen gelöscht.\n";
|
||
echo Question::deleteOld() . " alte Fragen/Antworten gelöscht.\n";
|
||
echo User::deleteOldAccountData() . " alte Kontodaten gelöscht.\n";
|
||
echo Roundmail::sendReminder($appUrl) . "\n";
|
||
} catch (\Throwable $e) {
|
||
http_response_code(500);
|
||
echo "Fehler: " . $e->getMessage() . "\n";
|
||
}
|
||
exit;
|
||
} elseif ($page === 'fetch_results') {
|
||
// Ergebnis-Fetcher von außen aufrufbar (z.B. cron-job.org), ohne Login.
|
||
header('Content-Type: text/plain; charset=UTF-8');
|
||
try {
|
||
echo FetcherLog::deleteOld() . " alte Fetcher-Log-Einträge gelöscht.\n";
|
||
echo "== Bundesliga/DFB-Pokal (openligadb) ==\n";
|
||
echo \App\Core\ResultFetcher::openligadb(true);
|
||
echo "\n\n== International (API-Football) ==\n";
|
||
echo \App\Core\ResultFetcher::apifootball(true);
|
||
echo "\n";
|
||
} catch (\Throwable $e) {
|
||
http_response_code(500);
|
||
echo "Fehler: " . $e->getMessage() . "\n";
|
||
}
|
||
exit;
|
||
} elseif ($page === 'login') {
|
||
// Wenn bereits eingeloggt, zur Startseite weiterleiten
|
||
if (Auth::check()) {
|
||
header('Location: /');
|
||
exit;
|
||
}
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$firstname = $_POST['firstname'] ?? '';
|
||
$lastname = $_POST['lastname'] ?? '';
|
||
$password = $_POST['password'] ?? '';
|
||
if (Auth::login($firstname, $lastname, $password)) {
|
||
header('Location: /');
|
||
exit;
|
||
} else {
|
||
$error = 'Ungültige Anmeldedaten.';
|
||
require __DIR__ . '/../src/Views/login.php';
|
||
}
|
||
} else {
|
||
require __DIR__ . '/../src/Views/login.php';
|
||
}
|
||
} elseif ($page === 'register') {
|
||
if (Auth::check()) {
|
||
header('Location: /');
|
||
exit;
|
||
}
|
||
|
||
if (!Setting::isRegistrationOpen()) {
|
||
http_response_code(403);
|
||
$registrationClosed = true;
|
||
require __DIR__ . '/../src/Views/register.php';
|
||
exit;
|
||
}
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$data = [
|
||
'firstname' => trim($_POST['firstname'] ?? ''),
|
||
'lastname' => trim($_POST['lastname'] ?? ''),
|
||
'email' => trim($_POST['email'] ?? ''),
|
||
'password' => $_POST['password'] ?? '',
|
||
'iban' => trim($_POST['iban'] ?? ''),
|
||
'paypal' => trim($_POST['paypal'] ?? ''),
|
||
'mobile' => trim($_POST['mobile'] ?? ''),
|
||
];
|
||
$data['iban'] = Iban::normalize($data['iban']);
|
||
$password_confirm = $_POST['password_confirm'] ?? '';
|
||
$error = null;
|
||
|
||
if (
|
||
$data['firstname'] === ''
|
||
|| $data['lastname'] === ''
|
||
|| $data['email'] === ''
|
||
|| $data['mobile'] === ''
|
||
|| $data['password'] === ''
|
||
) {
|
||
$error = 'Bitte fülle alle Pflichtfelder aus.';
|
||
} elseif ($data['iban'] === '' && $data['paypal'] === '') {
|
||
$error = 'Bitte gib eine Zahlungsmöglichkeit an (IBAN oder PayPal).';
|
||
} elseif (empty($_POST['privacy'])) {
|
||
$error = 'Bitte bestätige, dass du die Datenschutzhinweise gelesen hast.';
|
||
} elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) {
|
||
$error = 'Bitte eine gültige IBAN angeben.';
|
||
} elseif ($data['password'] !== $password_confirm) {
|
||
$error = 'Die Passwörter stimmen nicht überein.';
|
||
} elseif (User::findByEmail($data['email'])) {
|
||
$error = 'Diese E-Mail-Adresse ist bereits registriert.';
|
||
} else {
|
||
try {
|
||
if (User::create($data)) {
|
||
// Automatically log in the new user
|
||
if (Auth::login($data['firstname'], $data['lastname'], $data['password'])) {
|
||
header('Location: /');
|
||
exit;
|
||
} else {
|
||
// This should not happen if creation was successful
|
||
$error = 'Anmeldung nach Registrierung fehlgeschlagen. Bitte versuchen Sie, sich manuell anzumelden.';
|
||
require __DIR__ . '/../src/Views/login.php';
|
||
exit;
|
||
}
|
||
} else {
|
||
$error = 'Ein Fehler ist bei der Registrierung aufgetreten.';
|
||
}
|
||
} catch (\Throwable $e) {
|
||
// Could be a unique constraint violation from DB
|
||
$error = 'Ein Datenbankfehler ist aufgetreten. Die E-Mail könnte bereits vergeben sein.';
|
||
}
|
||
}
|
||
|
||
// Show form again with error
|
||
require __DIR__ . '/../src/Views/register.php';
|
||
|
||
} else {
|
||
// Show registration form
|
||
require __DIR__ . '/../src/Views/register.php';
|
||
}
|
||
} elseif ($page === 'logout') {
|
||
Auth::logout();
|
||
header('Location: /index.php?page=login');
|
||
exit;
|
||
} elseif (in_array($page, ['tipps', 'tipp_round', 'tipp_game'], true)) {
|
||
// Tipps abgeben (Legacy TippsController: index, edit4/store4, edit/store)
|
||
Auth::requireLogin();
|
||
$user = Auth::user();
|
||
$activeSeason = Season::getCurrent();
|
||
if (!$activeSeason) {
|
||
header('Location: /');
|
||
exit;
|
||
}
|
||
if (!User::isPaid($user['id'], $activeSeason['id'])) {
|
||
require __DIR__ . '/../src/Views/tipps/no_payment.php';
|
||
exit;
|
||
}
|
||
|
||
// Nach dem Speichern zur gerade getippten Runde springen. Ohne Rundenbezug
|
||
// (z. B. ungültige ID) gilt wie im Legacy die erste tippbare Runde.
|
||
$tippsUrl = function ($roundId = null) use ($activeSeason) {
|
||
if ($roundId) {
|
||
return '/index.php?page=tipps&tipped=' . (int)$roundId . '#round-' . (int)$roundId;
|
||
}
|
||
$round = Round::getFirstTippable($activeSeason['id']);
|
||
return '/index.php?page=tipps' . ($round ? '#round-' . $round['id'] : '');
|
||
};
|
||
|
||
if ($page === 'tipps') {
|
||
$rounds = [];
|
||
$firstTippableRoundId = null;
|
||
// Runde, aus der der Spieler gerade kam (nach dem Speichern gesetzt).
|
||
$tippedRoundId = isset($_GET['tipped']) ? (int)$_GET['tipped'] : 0;
|
||
foreach (Round::getBySeason($activeSeason['id']) as $round) {
|
||
$round['games'] = Game::getGamesByRound($round['id']);
|
||
$round['tipps'] = Tipp::findByUserAndRound($user['id'], $round['id']);
|
||
$round['locked'] = Round::isLocked($round['games']);
|
||
if ($firstTippableRoundId === null && !$round['locked']) {
|
||
$firstTippableRoundId = (int)$round['id'];
|
||
}
|
||
$round['lock_time'] = Round::getLockTime($round['games']);
|
||
$round['joker_usage'] = Tipp::formatJokerUsage(
|
||
Tipp::getJokerUsage($user['id'], $activeSeason['id'], null, $round['id'])
|
||
);
|
||
$rounds[] = $round;
|
||
}
|
||
$maxIdenticalJokertipps = (int)$activeSeason['max_identical_jokertipps'];
|
||
require __DIR__ . '/../src/Views/tipps/index.php';
|
||
exit;
|
||
}
|
||
|
||
if ($page === 'tipp_round') {
|
||
$round = Round::getById((int)($_GET['id'] ?? 0));
|
||
if (!$round || (int)$round['season_id'] !== (int)$activeSeason['id']) {
|
||
header('Location: ' . $tippsUrl());
|
||
exit;
|
||
}
|
||
$games = Game::getGamesByRound($round['id']);
|
||
$error = null;
|
||
$jokerUsage = Tipp::formatJokerUsage(
|
||
Tipp::getJokerUsage($user['id'], $activeSeason['id'], null, $round['id'])
|
||
);
|
||
$maxIdenticalJokertipps = (int)$activeSeason['max_identical_jokertipps'];
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$jokerGameId = isset($_POST['joker']) && $_POST['joker'] !== '' ? (int)$_POST['joker'] : null;
|
||
$error = Tipp::saveRound($user['id'], $round['id'], $_POST['scores'] ?? [], $jokerGameId);
|
||
if ($error === null) {
|
||
header('Location: ' . $tippsUrl($round['id']));
|
||
exit;
|
||
}
|
||
$formScores = $_POST['scores'] ?? [];
|
||
$formJoker = $jokerGameId;
|
||
} else {
|
||
$tipps = Tipp::findByUserAndRound($user['id'], $round['id']);
|
||
$formScores = [];
|
||
$formJoker = null;
|
||
foreach ($games as $game) {
|
||
$tipp = $tipps[$game['id']] ?? null;
|
||
$formScores[$game['id']] = [
|
||
'score1' => $tipp && (int)$tipp['score1'] >= 0 ? $tipp['score1'] : '',
|
||
'score2' => $tipp && (int)$tipp['score2'] >= 0 ? $tipp['score2'] : '',
|
||
];
|
||
if ($tipp && $tipp['joker']) {
|
||
$formJoker = (int)$game['id'];
|
||
}
|
||
}
|
||
}
|
||
$locked = Round::isLocked($games);
|
||
require __DIR__ . '/../src/Views/tipps/round.php';
|
||
exit;
|
||
}
|
||
|
||
// tipp_game: einzelnes Spiel tippen
|
||
$game = Game::getById((int)($_GET['id'] ?? 0));
|
||
$round = $game ? Round::getById($game['round_id']) : null;
|
||
if (!$round || (int)$round['season_id'] !== (int)$activeSeason['id']) {
|
||
header('Location: ' . $tippsUrl());
|
||
exit;
|
||
}
|
||
$error = null;
|
||
$jokerUsage = Tipp::formatJokerUsage(
|
||
Tipp::getJokerUsage($user['id'], $activeSeason['id'], null, $round['id'])
|
||
);
|
||
$maxIdenticalJokertipps = (int)$activeSeason['max_identical_jokertipps'];
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$error = Tipp::saveSingle($user['id'], $game['id'], $_POST['score1'] ?? '', $_POST['score2'] ?? '', isset($_POST['joker']));
|
||
if ($error === null) {
|
||
header('Location: ' . $tippsUrl($round['id']));
|
||
exit;
|
||
}
|
||
$formTipp = ['score1' => $_POST['score1'] ?? '', 'score2' => $_POST['score2'] ?? '', 'joker' => isset($_POST['joker'])];
|
||
} else {
|
||
$tipp = Tipp::findByUserAndRound($user['id'], $round['id'])[$game['id']] ?? null;
|
||
$formTipp = [
|
||
'score1' => $tipp && (int)$tipp['score1'] >= 0 ? $tipp['score1'] : '',
|
||
'score2' => $tipp && (int)$tipp['score2'] >= 0 ? $tipp['score2'] : '',
|
||
'joker' => $tipp && $tipp['joker'],
|
||
];
|
||
}
|
||
$locked = Round::isLocked(Game::getGamesByRound($round['id']));
|
||
require __DIR__ . '/../src/Views/tipps/game.php';
|
||
} elseif ($page === 'datenschutz') {
|
||
// Datenschutzhinweise: öffentlich, ohne Login erreichbar
|
||
require __DIR__ . '/../src/Views/info/privacy.php';
|
||
} elseif ($page === 'guide') {
|
||
// Info -> Anleitung: Regeln mit den Werten der angezeigten Saison
|
||
Auth::requireLogin();
|
||
$currentSeason = Season::getViewSeason();
|
||
$payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null;
|
||
$maxIdenticalJokertipps = (int)($currentSeason['max_identical_jokertipps'] ?? Season::DEFAULT_MAX_IDENTICAL_JOKERTIPPS);
|
||
$jackpot = $currentSeason ? (float)$currentSeason['jackpot'] : 0.0;
|
||
$jackpotStatus = $currentSeason
|
||
? Ranking::getJackpotStatus($currentSeason['id'])
|
||
: ['won' => false, 'amount' => 0.0, 'perWinner' => 0.0, 'winners' => []];
|
||
require __DIR__ . '/../src/Views/info/guide.php';
|
||
} elseif ($page === 'guide_admin') {
|
||
// Info -> Anleitung-Admin: Saison-/Quoten-Verwaltung (nur für Admins)
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
require __DIR__ . '/../src/Views/info/guide_admin.php';
|
||
} elseif ($page === 'info_quotas') {
|
||
// Info -> Quoten (Legacy UsersController::show_payouts)
|
||
Auth::requireLogin();
|
||
$currentSeason = Season::getViewSeason();
|
||
$payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null;
|
||
$activeUserCount = $currentSeason ? count(User::getPaid($currentSeason['id'])) : 0;
|
||
$stake = $currentSeason ? (Quota::getMapBySeason($currentSeason['id'])['einsatz'] ?? 0) : 0;
|
||
$jackpot = $currentSeason ? (float)$currentSeason['jackpot'] : 0.0;
|
||
$jackpotStatus = $currentSeason
|
||
? Ranking::getJackpotStatus($currentSeason['id'])
|
||
: ['won' => false, 'amount' => 0.0, 'perWinner' => 0.0, 'winners' => []];
|
||
require __DIR__ . '/../src/Views/info/quotas.php';
|
||
} elseif ($page === 'money_ranking') {
|
||
// Info -> Geldrangliste (Legacy UsersController::money_ranking / money_ranking_detail)
|
||
Auth::requireLogin();
|
||
$user = Auth::user();
|
||
$currentSeason = Season::getViewSeason();
|
||
if (!$currentSeason) {
|
||
header('Location: /');
|
||
exit;
|
||
}
|
||
if (!$user['admin'] && !User::isPaid($user['id'], $currentSeason['id'])) {
|
||
require __DIR__ . '/../src/Views/tipps/no_payment.php';
|
||
exit;
|
||
}
|
||
|
||
['result' => $result, 'season_start' => $seasonStart] = Ranking::computeForMoneyRanking($currentSeason['id']);
|
||
if (!$result) {
|
||
require __DIR__ . '/../src/Views/info/no_ranking.php';
|
||
exit;
|
||
}
|
||
if (isset($_GET['user_id'])) {
|
||
$detailUserId = (int)$_GET['user_id'];
|
||
if (!isset($result['users'][$detailUserId])) {
|
||
header('Location: /index.php?page=money_ranking');
|
||
exit;
|
||
}
|
||
$detailUser = $result['users'][$detailUserId];
|
||
$payoutItems = Ranking::payoutItems($result)[$detailUserId];
|
||
require __DIR__ . '/../src/Views/info/money_ranking_detail.php';
|
||
} else {
|
||
$moneyRanking = Ranking::moneyRanking($result);
|
||
require __DIR__ . '/../src/Views/info/money_ranking.php';
|
||
}
|
||
} elseif ($page === 'admin_accounts') {
|
||
// Kontoliste mit IBAN (Legacy UsersController::money_ranking_with_iban)
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
$user = Auth::user();
|
||
$currentSeason = Season::getViewSeason();
|
||
$result = null;
|
||
$seasonStart = null;
|
||
if ($currentSeason) {
|
||
['result' => $result, 'season_start' => $seasonStart] = Ranking::computeForMoneyRanking($currentSeason['id']);
|
||
}
|
||
$moneyRanking = $result ? Ranking::moneyRanking($result, true) : [];
|
||
require __DIR__ . '/../src/Views/admin/accounts.php';
|
||
} elseif ($page === 'admin_message') {
|
||
// Aktuelle Mitteilung für die Startseite (nur Admins)
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
Setting::setMessage($_POST['message'] ?? '');
|
||
$_SESSION['admin_message'] = 'Die aktuelle Mitteilung wurde gespeichert.';
|
||
header('Location: /index.php?page=admin_message');
|
||
exit;
|
||
}
|
||
|
||
$flashMessage = $_SESSION['admin_message'] ?? null;
|
||
$error = $_SESSION['admin_error'] ?? null;
|
||
unset($_SESSION['admin_message'], $_SESSION['admin_error']);
|
||
$currentMessage = Setting::getMessage();
|
||
|
||
require __DIR__ . '/../src/Views/admin/message.php';
|
||
} elseif ($page === 'admin_fetcher_activity') {
|
||
// Aktivitätslog des Ergebnis-Fetchers (nur Admins)
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
$from = $_GET['from'] ?? date('Y-m-d', strtotime('-7 days'));
|
||
$to = $_GET['to'] ?? date('Y-m-d');
|
||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
|
||
$from = date('Y-m-d', strtotime('-7 days'));
|
||
$to = date('Y-m-d');
|
||
}
|
||
|
||
$entries = FetcherLog::getRange($from, $to);
|
||
|
||
require __DIR__ . '/../src/Views/admin/fetcher_activity.php';
|
||
} elseif (in_array($page, ['push_subscribe', 'push_unsubscribe', 'push_test'], true)) {
|
||
// Push-Abo speichern/löschen und Test-Erinnerung (JSON, nur eingeloggt).
|
||
header('Content-Type: application/json; charset=UTF-8');
|
||
|
||
if (!Auth::check()) {
|
||
http_response_code(401);
|
||
echo json_encode(['error' => 'Nicht angemeldet.']);
|
||
exit;
|
||
}
|
||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||
http_response_code(405);
|
||
echo json_encode(['error' => 'Nur POST erlaubt.']);
|
||
exit;
|
||
}
|
||
|
||
try {
|
||
if (!WebPush::isConfigured() || !PushSubscription::isAvailable()) {
|
||
http_response_code(503);
|
||
echo json_encode(['error' => 'App-Erinnerungen sind derzeit nicht verfügbar.']);
|
||
exit;
|
||
}
|
||
|
||
$input = json_decode(file_get_contents('php://input'), true);
|
||
if (!is_array($input)) {
|
||
$input = [];
|
||
}
|
||
|
||
if ($page === 'push_unsubscribe') {
|
||
PushSubscription::deleteForUser((int)Auth::id());
|
||
echo json_encode(['ok' => true]);
|
||
exit;
|
||
}
|
||
|
||
if ($page === 'push_test') {
|
||
// Nur das Gerät testen, auf dem der Knopf gedrückt wurde. Kurze Sperre
|
||
// gegen versehentliches Mehrfachklicken.
|
||
$now = time();
|
||
if (isset($_SESSION['push_test_at']) && $now - (int)$_SESSION['push_test_at'] < 5) {
|
||
http_response_code(429);
|
||
echo json_encode(['error' => 'Bitte kurz warten, dann erneut testen.']);
|
||
exit;
|
||
}
|
||
$_SESSION['push_test_at'] = $now;
|
||
|
||
$endpoint = (string)($input['endpoint'] ?? '');
|
||
$subscription = PushSubscription::findForUserAndEndpoint((int)Auth::id(), $endpoint);
|
||
if (!$subscription) {
|
||
http_response_code(409);
|
||
echo json_encode(['error' => 'Dieses Gerät ist nicht als Abo hinterlegt. Bitte den Haken aus- und wieder einschalten.']);
|
||
exit;
|
||
}
|
||
|
||
// Gleicher Text wie im echten Erinnerungslauf, damit die Vorschau stimmt.
|
||
$appUrl = getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
|
||
$season = Season::getCurrent();
|
||
$round = $season ? Round::getFirstTippable($season['id']) : null;
|
||
if ($round) {
|
||
$payload = Roundmail::pushPayload($round, Round::getLockTime($round['games']), $appUrl);
|
||
} else {
|
||
$payload = [
|
||
'title' => 'Hoschis Tippspiel',
|
||
'body' => 'Test-Erinnerung: Es fehlen noch Tipps/Joker.',
|
||
'url' => rtrim($appUrl, '/') . '/index.php?page=tipps',
|
||
];
|
||
}
|
||
// Eigener Tag: Der Test soll eine echte Erinnerung nicht ersetzen.
|
||
$payload['tag'] = 'reminder-test';
|
||
|
||
$send = WebPush::send($subscription, $payload);
|
||
if ($send['ok']) {
|
||
echo json_encode(['ok' => true, 'sent' => 1]);
|
||
} elseif ($send['gone']) {
|
||
PushSubscription::deleteByEndpoint($endpoint);
|
||
http_response_code(410);
|
||
echo json_encode(['error' => 'Das Abo ist abgelaufen und wurde entfernt. Bitte den Haken aus- und wieder einschalten.']);
|
||
} else {
|
||
http_response_code(502);
|
||
echo json_encode(['error' => 'Push-Dienst nicht erreichbar: ' . $send['error']]);
|
||
}
|
||
exit;
|
||
}
|
||
|
||
$endpoint = (string)($input['endpoint'] ?? '');
|
||
$keys = is_array($input['keys'] ?? null) ? $input['keys'] : [];
|
||
$p256dh = (string)($keys['p256dh'] ?? '');
|
||
$authKey = (string)($keys['auth'] ?? '');
|
||
|
||
if (!WebPush::isValidEndpoint($endpoint)
|
||
|| !WebPush::isValidKeyMaterial($p256dh, $authKey)) {
|
||
http_response_code(400);
|
||
echo json_encode(['error' => 'Ungültiges Abo.']);
|
||
exit;
|
||
}
|
||
|
||
PushSubscription::save((int)Auth::id(), $endpoint, $p256dh, $authKey);
|
||
echo json_encode(['ok' => true]);
|
||
} catch (\Throwable $e) {
|
||
error_log('Push-Abo konnte nicht gespeichert werden: ' . $e);
|
||
http_response_code(500);
|
||
echo json_encode(['error' => 'Speichern fehlgeschlagen.']);
|
||
}
|
||
exit;
|
||
} elseif ($page === 'settings') {
|
||
// Eigene Spielerdaten (Legacy UsersController::useredit / storeUserEdit)
|
||
Auth::requireLogin();
|
||
$user = Auth::user();
|
||
$error = null;
|
||
$message = $_SESSION['settings_message'] ?? null;
|
||
unset($_SESSION['settings_message']);
|
||
|
||
// Zweite Checkbox (nur in der installierten App sichtbar): Zustand des Push-Abos
|
||
// und öffentlicher VAPID-Schlüssel für pushManager.subscribe(). Ohne Tabelle
|
||
// (Migration noch nicht gelaufen) bleibt die Zeile unsichtbar.
|
||
$pushPublicKey = PushSubscription::isAvailable() && WebPush::isConfigured() ? WebPush::publicKey() : null;
|
||
$pushEnabled = PushSubscription::hasSubscription((int)$user['id']);
|
||
|
||
// IBAN für die Anzeige entschlüsseln (in der DB liegt nur der Ciphertext)
|
||
try {
|
||
$user['iban'] = \App\Core\Crypto::decrypt($user['iban']);
|
||
} catch (\Throwable $e) {
|
||
$user['iban'] = '';
|
||
$error = 'Die hinterlegte IBAN konnte nicht entschlüsselt werden.';
|
||
}
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$data = [
|
||
'email' => trim($_POST['email'] ?? ''),
|
||
'gets_reminders' => isset($_POST['gets_reminders']),
|
||
];
|
||
foreach (User::BANK_FIELDS as $field) {
|
||
$data[$field] = $_POST[$field] ?? '';
|
||
}
|
||
$data['iban'] = Iban::normalize($data['iban']);
|
||
|
||
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
|
||
$error = 'Bitte eine gültige E-Mail-Adresse eintragen.';
|
||
} elseif (User::emailExists($data['email'], $user['id'])) {
|
||
$error = 'Diese E-Mail-Adresse wird bereits von einem anderen Spieler verwendet.';
|
||
} elseif ($data['iban'] !== '' && !Iban::isValid($data['iban'])) {
|
||
$error = 'Bitte eine gültige IBAN angeben.';
|
||
} else {
|
||
User::updateProfile($user['id'], $data);
|
||
$_SESSION['settings_message'] = 'Deine Daten wurden gespeichert.';
|
||
header('Location: /index.php?page=settings');
|
||
exit;
|
||
}
|
||
// Eingaben bei Fehler erhalten
|
||
$user = array_merge($user, $data);
|
||
}
|
||
require __DIR__ . '/../src/Views/settings.php';
|
||
} elseif ($page === 'admin') {
|
||
// Die Admin-Punkte stehen im Popup-Menü der Navigation; hier wird nur noch
|
||
// der Registrierungsschalter aus dem Menü verarbeitet.
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$action = $_POST['action'] ?? '';
|
||
// Zurück zur Seite, auf der das Menü benutzt wurde (nur lokale Pfade)
|
||
$return = (string)($_POST['return'] ?? '');
|
||
$isLocal = str_starts_with($return, '/') && !str_starts_with($return, '//');
|
||
|
||
if ($action === 'set_registration') {
|
||
Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1');
|
||
} elseif ($action === 'set_view_season') {
|
||
// Persönliche Saison-Ansicht des Admins umschalten (wirkt nur auf ihn)
|
||
Season::setViewSeason($_POST['season_id'] ?? null);
|
||
}
|
||
|
||
header('Location: ' . ($isLocal ? $return : '/index.php?page=admin_users'));
|
||
exit;
|
||
}
|
||
header('Location: /index.php?page=admin_users');
|
||
exit;
|
||
} elseif ($page === 'admin_seasons') {
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
$message = null;
|
||
$error = null;
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$action = $_POST['action'] ?? '';
|
||
$seasonId = $_POST['id'] ?? null;
|
||
$redirect = '/index.php?page=admin_seasons';
|
||
|
||
try {
|
||
if ($action === 'create' || $action === 'update') {
|
||
$data = [
|
||
'name' => trim($_POST['name'] ?? ''),
|
||
'rounds' => $_POST['rounds'] ?? '',
|
||
'max_identical_jokertipps' => $_POST['max_identical_jokertipps'] ?? '',
|
||
'jackpot' => str_replace(',', '.', trim($_POST['jackpot'] ?? '')),
|
||
];
|
||
if ($data['name'] === '' || !ctype_digit((string)$data['rounds']) || (int)$data['rounds'] < 1
|
||
|| !ctype_digit((string)$data['max_identical_jokertipps'])
|
||
|| !is_numeric($data['jackpot']) || (float)$data['jackpot'] < 0) {
|
||
throw new \Exception('Name, Runden, maximale Anzahl gleicher Joker und Jackpot sind erforderlich.');
|
||
}
|
||
|
||
$quotasToSave = [];
|
||
foreach (Quota::editableNames() as $name) {
|
||
$quotasToSave[$name] = str_replace(',', '.', trim($_POST['quotas'][$name] ?? ''));
|
||
}
|
||
$quotaError = Quota::validate($quotasToSave);
|
||
if ($quotaError) {
|
||
throw new \Exception($quotaError);
|
||
}
|
||
|
||
if ($action === 'create') {
|
||
$newSeasonId = Season::create($data);
|
||
if (!$newSeasonId) {
|
||
throw new \Exception("Saison konnte nicht erstellt werden.");
|
||
}
|
||
Quota::saveForSeason($newSeasonId, $quotasToSave);
|
||
// Nur die persönliche Ansicht des Admins umschalten – die für
|
||
// alle Spieler aktive Saison bleibt unverändert.
|
||
Season::setViewSeason($newSeasonId);
|
||
$_SESSION['admin_message'] = "Saison erfolgreich erstellt und für dich als Ansicht gesetzt. Für alle Spieler bleibt die bisherige Saison aktiv.";
|
||
} elseif ($seasonId) {
|
||
Season::update($seasonId, $data);
|
||
Quota::saveForSeason($seasonId, $quotasToSave);
|
||
$_SESSION['admin_message'] = "Saison erfolgreich aktualisiert.";
|
||
$redirect = '/index.php?page=admin_seasons&edit_id=' . (int)$seasonId;
|
||
}
|
||
} elseif ($action === 'set_current' && $seasonId) {
|
||
Season::setCurrent($seasonId);
|
||
Season::setViewSeason($seasonId);
|
||
$_SESSION['admin_message'] = "Saison wurde für alle Spieler als aktiv gesetzt.";
|
||
} elseif ($action === 'view' && $seasonId) {
|
||
Season::setViewSeason($seasonId);
|
||
$_SESSION['admin_message'] = "Saison wird jetzt nur für dich angezeigt.";
|
||
} elseif ($action === 'delete' && $seasonId) {
|
||
Season::delete($seasonId);
|
||
$_SESSION['admin_message'] = "Saison wurde gelöscht.";
|
||
}
|
||
} catch (\Throwable $e) {
|
||
$_SESSION['admin_error'] = "Fehler: " . $e->getMessage();
|
||
$_SESSION['admin_form'] = $_POST;
|
||
if ($action === 'update' && $seasonId) {
|
||
$redirect = '/index.php?page=admin_seasons&edit_id=' . (int)$seasonId;
|
||
}
|
||
}
|
||
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
if (isset($_SESSION['admin_message'])) {
|
||
$message = $_SESSION['admin_message'];
|
||
unset($_SESSION['admin_message']);
|
||
}
|
||
if (isset($_SESSION['admin_error'])) {
|
||
$error = $_SESSION['admin_error'];
|
||
unset($_SESSION['admin_error']);
|
||
}
|
||
$failedForm = $_SESSION['admin_form'] ?? null;
|
||
unset($_SESSION['admin_form']);
|
||
|
||
$seasons = Season::getAll();
|
||
$currentSeason = Season::getCurrent();
|
||
$viewSeason = Season::getViewSeason();
|
||
$editSeason = isset($_GET['edit_id']) ? Season::findById((int)$_GET['edit_id']) : null;
|
||
$payouts = null;
|
||
|
||
// Formularwerte: Bearbeiten = Werte der Saison, Neu = Werte der aktiven Saison bzw. Legacy-Defaults
|
||
$template = $editSeason ?: $currentSeason;
|
||
$formValues = [
|
||
'name' => $editSeason['name'] ?? '',
|
||
'rounds' => $template['rounds'] ?? 48,
|
||
'max_identical_jokertipps' => $template['max_identical_jokertipps'] ?? Season::DEFAULT_MAX_IDENTICAL_JOKERTIPPS,
|
||
'jackpot' => $template['jackpot'] ?? Season::DEFAULT_JACKPOT,
|
||
'quotas' => array_merge(Quota::defaults(), $template ? Quota::getMapBySeason($template['id']) : []),
|
||
];
|
||
if ($editSeason) {
|
||
$payouts = Quota::computePayouts($editSeason['id']);
|
||
$paidUserCount = count(User::getPaid($editSeason['id']));
|
||
$roundCount = count(Round::getBySeason($editSeason['id']));
|
||
}
|
||
if ($failedForm) {
|
||
$formValues = array_merge($formValues, array_intersect_key($failedForm, $formValues));
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/admin/seasons.php';
|
||
} elseif ($page === 'admin_rounds') {
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
$activeSeason = Season::getCurrent();
|
||
$viewSeason = Season::getViewSeason();
|
||
$seasonId = (int)($_GET['season_id'] ?? ($viewSeason ? (int)$viewSeason['id'] : 0));
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$roundId = (int)($_POST['round_id'] ?? 0);
|
||
$redirect = '/index.php?page=admin_rounds&season_id=' . $seasonId . '#round-' . $roundId;
|
||
|
||
try {
|
||
$round = Round::getById($roundId);
|
||
if (!$round) {
|
||
throw new \Exception('Runde nicht gefunden.');
|
||
}
|
||
$name = trim($_POST['name'] ?? '');
|
||
if ($name === '') {
|
||
throw new \Exception('Der Rundenname darf nicht leer sein.');
|
||
}
|
||
|
||
// Erst alle Spiele prüfen, dann speichern
|
||
$gamesToSave = [];
|
||
foreach ($_POST['games'] ?? [] as $gameId => $input) {
|
||
$game = Game::getById((int)$gameId);
|
||
if (!$game || (int)$game['round_id'] !== $roundId) {
|
||
throw new \Exception('Spiel gehört nicht zu dieser Runde.');
|
||
}
|
||
$label = $game['team1'] . ' : ' . $game['team2'];
|
||
|
||
$team1 = trim($input['team1'] ?? '');
|
||
$team2 = trim($input['team2'] ?? '');
|
||
if ($team1 === '' || $team2 === '') {
|
||
throw new \Exception("Mannschaften fehlen bei \"$label\".");
|
||
}
|
||
|
||
$kickoff = \DateTime::createFromFormat('Y-m-d\\TH:i', $input['kickoff'] ?? '')
|
||
?: \DateTime::createFromFormat('Y-m-d\\TH:i:s', $input['kickoff'] ?? '');
|
||
if (!$kickoff) {
|
||
throw new \Exception("Ungültiger Anstoß bei \"$label\".");
|
||
}
|
||
|
||
$score1 = trim($input['score1'] ?? '');
|
||
$score2 = trim($input['score2'] ?? '');
|
||
if ($score1 === '' && $score2 === '') {
|
||
$score1 = $score2 = -1;
|
||
} elseif (ctype_digit($score1) && ctype_digit($score2)) {
|
||
$score1 = (int)$score1;
|
||
$score2 = (int)$score2;
|
||
} else {
|
||
throw new \Exception("Ergebnis bei \"$label\" muss aus zwei Zahlen bestehen oder ganz leer sein.");
|
||
}
|
||
|
||
$gamesToSave[(int)$gameId] = [
|
||
'team1' => $team1,
|
||
'team2' => $team2,
|
||
'kickoff' => $kickoff->format('Y-m-d H:i:00'),
|
||
'score1' => $score1,
|
||
'score2' => $score2,
|
||
];
|
||
}
|
||
|
||
$db = Database::getConnection();
|
||
$db->beginTransaction();
|
||
try {
|
||
Round::updateName($roundId, $name);
|
||
Round::updateReport($roundId, $_POST['report'] ?? '');
|
||
foreach ($gamesToSave as $gameId => $data) {
|
||
Game::update($gameId, $data);
|
||
}
|
||
$db->commit();
|
||
} catch (\Throwable $e) {
|
||
$db->rollBack();
|
||
throw $e;
|
||
}
|
||
$_SESSION['admin_message'] = "\"$name\" wurde gespeichert.";
|
||
} catch (\Throwable $e) {
|
||
$_SESSION['admin_error'] = "Fehler: " . $e->getMessage();
|
||
$_SESSION['admin_form'] = $_POST;
|
||
}
|
||
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
$message = $_SESSION['admin_message'] ?? null;
|
||
$error = $_SESSION['admin_error'] ?? null;
|
||
$failedForm = $_SESSION['admin_form'] ?? null;
|
||
unset($_SESSION['admin_message'], $_SESSION['admin_error'], $_SESSION['admin_form']);
|
||
|
||
$seasons = Season::getAll();
|
||
$season = Season::findById($seasonId);
|
||
$rounds = [];
|
||
$firstIncompleteRoundId = null;
|
||
if ($season) {
|
||
foreach (Round::getBySeason($seasonId) as $round) {
|
||
$round['games'] = Game::getGamesByRound($round['id']);
|
||
$round['completed'] = Round::isCompleted($round['games']);
|
||
$round['lock_time'] = Round::getLockTime($round['games']);
|
||
if ($firstIncompleteRoundId === null && !$round['completed']) {
|
||
$firstIncompleteRoundId = (int)$round['id'];
|
||
}
|
||
$rounds[] = $round;
|
||
}
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/admin/rounds.php';
|
||
} elseif ($page === 'admin_roundmails') {
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
// Versand erfolgt blockweise aus dem Browser: Ein Request verschickt nur
|
||
// BATCH_SIZE Mails. So bleibt jeder Aufruf deutlich unter den Zeitlimits
|
||
// des Shared Hosts, und ein Abbruch verliert höchstens einen Block.
|
||
$jobKey = 'roundmail_job';
|
||
$batchSize = 10;
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'batch') {
|
||
@set_time_limit(120);
|
||
ignore_user_abort(true);
|
||
$wantsJson = ($_POST['format'] ?? '') === 'json';
|
||
$job = $_SESSION[$jobKey] ?? null;
|
||
|
||
if (!$job) {
|
||
if ($wantsJson) {
|
||
header('Content-Type: application/json');
|
||
echo json_encode(['done' => true, 'redirect' => '/index.php?page=admin_roundmails']);
|
||
exit;
|
||
}
|
||
header('Location: /index.php?page=admin_roundmails');
|
||
exit;
|
||
}
|
||
|
||
$batch = array_splice($job['queue'], 0, $batchSize);
|
||
$error = null;
|
||
try {
|
||
Mailer::send($batch, $job['topic'], $job['html'], $job['reply_to'],
|
||
function ($email, $ok) use (&$job, $jobKey) {
|
||
$job[$ok ? 'sent' : 'failed'][] = $email;
|
||
$_SESSION[$jobKey] = $job;
|
||
// Fortschritt sofort sichern: bricht der Request ab, ist er erhalten
|
||
session_write_close();
|
||
session_start();
|
||
});
|
||
} catch (\Throwable $e) {
|
||
// Der Block gilt als nicht versendet und wird beim nächsten Aufruf wiederholt
|
||
$job['queue'] = array_merge($batch, $job['queue']);
|
||
$error = $e->getMessage();
|
||
}
|
||
|
||
$total = count($job['queue']) + count($job['sent']) + count($job['failed']);
|
||
$done = empty($job['queue']);
|
||
$redirect = '/index.php?page=admin_roundmails';
|
||
|
||
if ($done) {
|
||
if (!empty($job['sent'])) {
|
||
Roundmail::create((int)$job['user_id'], $job['sent'], $job['topic'], $job['html'], (int)$job['season_id']);
|
||
}
|
||
$_SESSION['admin_message'] = 'Mail an ' . count($job['sent']) . ' Empfänger versendet.';
|
||
if (!empty($job['failed'])) {
|
||
$_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $job['failed']);
|
||
}
|
||
unset($_SESSION[$jobKey]);
|
||
} else {
|
||
$_SESSION[$jobKey] = $job;
|
||
$redirect = '/index.php?page=admin_roundmails&send=1';
|
||
}
|
||
|
||
if ($wantsJson) {
|
||
header('Content-Type: application/json');
|
||
echo json_encode([
|
||
'done' => $done,
|
||
'sent' => count($job['sent']),
|
||
'failed' => count($job['failed']),
|
||
'total' => $total,
|
||
'remaining' => count($job['queue']),
|
||
'error' => $error,
|
||
'redirect' => $redirect,
|
||
]);
|
||
exit;
|
||
}
|
||
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$redirect = '/index.php?page=admin_roundmails';
|
||
try {
|
||
$topic = trim($_POST['topic'] ?? '');
|
||
$text = trim($_POST['message'] ?? '');
|
||
$recipients = Roundmail::parseRecipients($_POST['recipients'] ?? '');
|
||
if ($topic === '' || $text === '') {
|
||
throw new \Exception('Thema und Nachricht sind erforderlich.');
|
||
}
|
||
if (!empty($recipients['invalid'])) {
|
||
throw new \Exception('Ungültige E-Mail-Adressen: ' . implode(', ', $recipients['invalid']));
|
||
}
|
||
if (empty($recipients['valid'])) {
|
||
throw new \Exception('Keine Empfänger angegeben.');
|
||
}
|
||
|
||
$sender = Auth::user();
|
||
$currentSeason = Season::getViewSeason();
|
||
$_SESSION[$jobKey] = [
|
||
'user_id' => (int)$sender['id'],
|
||
'reply_to' => $sender['email'] ?? null,
|
||
'topic' => $topic,
|
||
'html' => Roundmail::textToHtml($text),
|
||
'season_id' => $currentSeason ? (int)$currentSeason['id'] : 0,
|
||
'queue' => array_values($recipients['valid']),
|
||
'sent' => [],
|
||
'failed' => [],
|
||
];
|
||
$_SESSION['admin_message'] = 'Versand läuft: ' . count($recipients['valid']) . ' Empfänger.';
|
||
$redirect = '/index.php?page=admin_roundmails&send=1';
|
||
} catch (\Throwable $e) {
|
||
$_SESSION['admin_error'] = 'Fehler: ' . $e->getMessage();
|
||
$_SESSION['admin_form'] = $_POST;
|
||
$redirect = '/index.php?page=admin_roundmails&new=1';
|
||
}
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
$message = $_SESSION['admin_message'] ?? null;
|
||
$error = $_SESSION['admin_error'] ?? null;
|
||
$failedForm = $_SESSION['admin_form'] ?? null;
|
||
unset($_SESSION['admin_message'], $_SESSION['admin_error'], $_SESSION['admin_form']);
|
||
|
||
$viewMail = isset($_GET['id']) ? Roundmail::findById((int)$_GET['id']) : null;
|
||
$compose = isset($_GET['new']);
|
||
$excludeReminders = ($_GET['hide_reminders'] ?? '') === '1';
|
||
|
||
// Offener Versand aus einer früheren Sitzung (Abbruch, Timeout, Browser zu)
|
||
$sendJob = $_SESSION[$jobKey] ?? null;
|
||
$sending = isset($_GET['send']) && $sendJob;
|
||
if ($sending) {
|
||
$sendTotal = count($sendJob['queue']) + count($sendJob['sent']) + count($sendJob['failed']);
|
||
}
|
||
|
||
if ($compose) {
|
||
$currentSeason = Season::getViewSeason();
|
||
$tippableRound = $currentSeason ? Round::getFirstTippable($currentSeason['id']) : null;
|
||
$recipientGroups = $currentSeason ? Roundmail::recipientGroups($currentSeason['id'], $tippableRound) : [];
|
||
$baseUrl = rtrim(getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')), '/');
|
||
$tippLink = $baseUrl . '/';
|
||
$mailConfigured = (bool)getenv('SMTP_HOST');
|
||
} elseif (!$viewMail && !$sending) {
|
||
$perPage = 20;
|
||
$totalMails = Roundmail::count($excludeReminders);
|
||
$totalPages = max(1, (int)ceil($totalMails / $perPage));
|
||
$currentPage = min(max(1, (int)($_GET['p'] ?? 1)), $totalPages);
|
||
$mails = Roundmail::getPage($perPage, ($currentPage - 1) * $perPage, $excludeReminders);
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/admin/roundmails.php';
|
||
} elseif ($page === 'admin_users') {
|
||
Auth::requireLogin();
|
||
Auth::requireAdmin();
|
||
|
||
$currentSeason = Season::getViewSeason();
|
||
$message = null;
|
||
$error = null;
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$action = $_POST['action'] ?? '';
|
||
$userId = $_POST['id'] ?? null;
|
||
$redirect = '/index.php?page=admin_users';
|
||
|
||
try {
|
||
if ($action === 'update' && $userId) {
|
||
// Passwort nur ändern, wenn die Änderung ausdrücklich per
|
||
// Checkbox aktiviert wurde. Sonst kann ein vom Browser
|
||
// automatisch ausgefülltes Passwortfeld das Passwort
|
||
// unbeabsichtigt überschreiben.
|
||
$changePassword = ($_POST['change_password'] ?? '') === '1';
|
||
if ($changePassword && trim((string)($_POST['password'] ?? '')) === '') {
|
||
throw new \Exception('Bitte ein neues Passwort eingeben oder die Passwortänderung abwählen.');
|
||
}
|
||
|
||
$data = [
|
||
'firstname' => $_POST['firstname'],
|
||
'lastname' => $_POST['lastname'],
|
||
'email' => $_POST['email'],
|
||
'password' => $changePassword ? ($_POST['password'] ?? '') : '',
|
||
'iban' => Iban::normalize(trim($_POST['iban'] ?? '')),
|
||
'paypal' => trim($_POST['paypal'] ?? ''),
|
||
'mobile' => trim($_POST['mobile'] ?? ''),
|
||
'admin' => isset($_POST['admin']) ? 1 : 0,
|
||
];
|
||
|
||
if ($data['iban'] !== '' && !Iban::isValid($data['iban'])) {
|
||
throw new \Exception('Bitte eine gültige IBAN angeben.');
|
||
}
|
||
|
||
User::update($userId, $data);
|
||
if ($currentSeason) {
|
||
Payment::setPaidStatus($userId, $currentSeason['id'], isset($_POST['has_paid']));
|
||
}
|
||
$_SESSION['admin_message'] = "Benutzer erfolgreich aktualisiert.";
|
||
} elseif ($action === 'delete' && $userId) {
|
||
User::delete($userId);
|
||
$_SESSION['admin_message'] = "Benutzer erfolgreich gelöscht.";
|
||
}
|
||
} catch (\Throwable $e) {
|
||
$_SESSION['admin_error'] = "Fehler: " . $e->getMessage();
|
||
if ($action === 'update' && $userId) {
|
||
$redirect = '/index.php?page=admin_users&edit_id=' . $userId;
|
||
}
|
||
}
|
||
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
if (isset($_SESSION['admin_message'])) {
|
||
$message = $_SESSION['admin_message'];
|
||
unset($_SESSION['admin_message']);
|
||
}
|
||
if (isset($_SESSION['admin_error'])) {
|
||
$error = $_SESSION['admin_error'];
|
||
unset($_SESSION['admin_error']);
|
||
}
|
||
|
||
$users = User::getAll();
|
||
$payments = [];
|
||
if ($currentSeason) {
|
||
$payments = Payment::getPaymentsBySeason($currentSeason['id']);
|
||
}
|
||
|
||
// Status der anstehenden (ersten tippbaren) Runde für die Benutzerliste:
|
||
// fehlende Tipps und fehlender Joker je Benutzer.
|
||
$tippableRound = $currentSeason ? Round::getFirstTippable($currentSeason['id']) : null;
|
||
$missingTipps = [];
|
||
$missingJoker = [];
|
||
if ($tippableRound && !empty($users)) {
|
||
$missing = Tipp::getMissing(
|
||
(int)$tippableRound['id'],
|
||
array_map(function ($user) {
|
||
return (int)$user['id'];
|
||
}, $users)
|
||
);
|
||
$missingTipps = array_flip($missing['tipps']);
|
||
$missingJoker = array_flip($missing['joker']);
|
||
}
|
||
$editUser = null;
|
||
if (isset($_GET['edit_id'])) {
|
||
$editUser = User::findById((int)$_GET['edit_id']);
|
||
if ($editUser) {
|
||
// IBAN liegt verschlüsselt in der DB und wird nur für das Formular entschlüsselt.
|
||
try {
|
||
$editUser['iban'] = \App\Core\Crypto::decrypt($editUser['iban']);
|
||
} catch (\Throwable $e) {
|
||
$editUser['iban'] = '';
|
||
$error = 'Die hinterlegte IBAN konnte nicht entschlüsselt werden.';
|
||
}
|
||
}
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/admin/users.php';
|
||
} elseif ($page === 'round' && isset($_GET['id'])) {
|
||
Auth::requireLogin();
|
||
try {
|
||
$roundId = (int)$_GET['id'];
|
||
$selectedRound = Round::getById($roundId);
|
||
|
||
if (!$selectedRound) {
|
||
http_response_code(404);
|
||
echo "404 Not Found: Runde nicht gefunden.";
|
||
exit;
|
||
}
|
||
|
||
// Alle Runden der Saison holen
|
||
$allRoundsInSeason = Round::getBySeason($selectedRound['season_id']);
|
||
|
||
$roundsToShow = [];
|
||
$all_game_ids = [];
|
||
foreach ($allRoundsInSeason as $round) {
|
||
if ($round['id'] <= $selectedRound['id']) {
|
||
$gamesOfRound = Game::getGamesByRound($round['id']);
|
||
$round['games'] = $gamesOfRound;
|
||
$roundsToShow[] = $round;
|
||
if (!empty($gamesOfRound)) {
|
||
$all_game_ids = array_merge($all_game_ids, array_column($gamesOfRound, 'id'));
|
||
}
|
||
}
|
||
}
|
||
|
||
// Hole alle zahlenden User der Saison
|
||
$db = Database::getConnection();
|
||
$stmt_users = $db->prepare("SELECT u.id, u.name FROM users u JOIN payments p ON u.id = p.user_id WHERE p.season_id = ? AND u.deleted IS NULL AND p.paid_date IS NOT NULL ORDER BY u.name ASC");
|
||
$stmt_users->execute([$selectedRound['season_id']]);
|
||
$users = $stmt_users->fetchAll(\PDO::FETCH_ASSOC);
|
||
|
||
// Hole alle relevanten Tipps
|
||
$tipps_map = [];
|
||
if (!empty($all_game_ids) && !empty($users)) {
|
||
$user_ids = array_column($users, 'id');
|
||
$game_placeholders = implode(',', array_fill(0, count($all_game_ids), '?'));
|
||
$user_placeholders = implode(',', array_fill(0, count($user_ids), '?'));
|
||
|
||
$stmt_tipps = $db->prepare("
|
||
SELECT user_id, game_id, score1 AS tipp1, score2 AS tipp2, joker
|
||
FROM tipps
|
||
WHERE game_id IN ($game_placeholders) AND user_id IN ($user_placeholders)
|
||
");
|
||
$stmt_tipps->execute(array_merge($all_game_ids, $user_ids));
|
||
|
||
foreach ($stmt_tipps->fetchAll(\PDO::FETCH_ASSOC) as $tipp) {
|
||
$tipps_map[$tipp['user_id']][$tipp['game_id']] = $tipp;
|
||
}
|
||
}
|
||
|
||
// Lade das View-Template für die Rundenansicht
|
||
require __DIR__ . '/../src/Views/round.php';
|
||
} catch (Throwable $e) {
|
||
http_response_code(500);
|
||
echo "<p style='color:red;'>Fehler: " . htmlspecialchars($e->getMessage()) . "</p>";
|
||
}
|
||
} elseif ($page === 'ranking') {
|
||
Auth::requireLogin();
|
||
try {
|
||
$currentSeason = Season::getViewSeason();
|
||
if (!$currentSeason) {
|
||
throw new \Exception("Keine aktuelle Saison gefunden.");
|
||
}
|
||
|
||
// Auswählbar sind nur gesperrte Runden (erstes Spiel angepfiffen),
|
||
// Standard ist die zuletzt gesperrte Runde (Legacy Round::getLastLockedRoundId).
|
||
// Nicht die letzte Runde mit Ergebnis: Bei laufender Runde ohne Ergebnis
|
||
// würde sonst die vorherige, bereits abgeschlossene Runde erscheinen.
|
||
$allRounds = [];
|
||
foreach (Round::getBySeason($currentSeason['id']) as $round) {
|
||
$roundGames = Game::getGamesByRound($round['id']);
|
||
if (empty($roundGames) || !Game::isLocked($roundGames[0]['kickoff'])) {
|
||
continue;
|
||
}
|
||
$allRounds[] = $round;
|
||
}
|
||
|
||
$selectedRound = !empty($allRounds) ? $allRounds[count($allRounds) - 1] : null;
|
||
if (isset($_GET['round_id'])) {
|
||
foreach ($allRounds as $round) {
|
||
if ((int)$round['id'] === (int)$_GET['round_id']) {
|
||
$selectedRound = $round;
|
||
}
|
||
}
|
||
}
|
||
|
||
$ranking = [];
|
||
$games = [];
|
||
$teamLogos = [];
|
||
$roundCompleted = false;
|
||
$isFinalRound = false;
|
||
$roundHasJackpot = false;
|
||
if ($selectedRound) {
|
||
$result = Ranking::compute($currentSeason['id'], $selectedRound['id']);
|
||
$ranking = Ranking::roundTable($result);
|
||
$games = $result['rounds'][$selectedRound['id']]['games'] ?? [];
|
||
$roundCompleted = (bool)($result['rounds'][$selectedRound['id']]['completed'] ?? false);
|
||
$isFinalRound = (bool)$result['is_final'];
|
||
$roundEntries = $result['rounds'][$selectedRound['id']]['entries'] ?? [];
|
||
foreach ($roundEntries as $entry) {
|
||
if (($entry['jackpot_payout'] ?? 0) > 0) {
|
||
$roundHasJackpot = true;
|
||
break;
|
||
}
|
||
}
|
||
|
||
$teamIds = [];
|
||
foreach ($games as $game) {
|
||
if (!empty($game['team1_id'])) $teamIds[] = (int)$game['team1_id'];
|
||
if (!empty($game['team2_id'])) $teamIds[] = (int)$game['team2_id'];
|
||
}
|
||
if (!empty($teamIds)) {
|
||
$teamLogos = Team::logoMap($teamIds);
|
||
}
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/ranking.php';
|
||
} catch (Throwable $e) {
|
||
http_response_code(500);
|
||
echo "<p style='color:red;'>Fehler: " . htmlspecialchars($e->getMessage()) . "</p>";
|
||
}
|
||
} elseif ($page === 'questions') {
|
||
// Fragen an die Admins (Legacy: kein direkter Vorgänger, neu für 2027)
|
||
Auth::requireLogin();
|
||
$user = Auth::user();
|
||
$isAdmin = (bool)$user['admin'];
|
||
|
||
$message = $_SESSION['questions_message'] ?? null;
|
||
$error = $_SESSION['questions_error'] ?? null;
|
||
unset($_SESSION['questions_message'], $_SESSION['questions_error']);
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
$action = $_POST['action'] ?? '';
|
||
$redirect = '/index.php?page=questions';
|
||
|
||
if ($action === 'ask') {
|
||
$questionText = trim($_POST['question'] ?? '');
|
||
if ($questionText === '') {
|
||
$_SESSION['questions_error'] = 'Bitte gib eine Frage ein.';
|
||
} else {
|
||
Question::create((int)$user['id'], $questionText);
|
||
$_SESSION['questions_message'] = 'Deine Frage wurde an die Admins gesendet.';
|
||
}
|
||
} elseif ($action === 'answer') {
|
||
if (!$isAdmin) {
|
||
header('Location: /');
|
||
exit;
|
||
}
|
||
$questionId = (int)($_POST['id'] ?? 0);
|
||
$answerText = trim($_POST['answer'] ?? '');
|
||
$question = Question::findById($questionId);
|
||
if (!$question) {
|
||
$_SESSION['questions_error'] = 'Frage nicht gefunden.';
|
||
} elseif ($question['answer'] !== null) {
|
||
$_SESSION['questions_error'] = 'Die Frage wurde bereits beantwortet.';
|
||
} elseif ($answerText === '') {
|
||
$_SESSION['questions_error'] = 'Bitte gib eine Antwort ein.';
|
||
$redirect .= '&answer_id=' . $questionId;
|
||
} else {
|
||
Question::answer($questionId, $answerText, (int)$user['id']);
|
||
$_SESSION['questions_message'] = 'Antwort wurde gespeichert.';
|
||
}
|
||
}
|
||
|
||
header('Location: ' . $redirect);
|
||
exit;
|
||
}
|
||
|
||
// Beim Ansehen werden die eigenen Antworten als gesehen markiert.
|
||
// Für Admins bleibt die Frage offen, bis sie beantwortet ist – das
|
||
// Admin-Leuchten hängt nicht mehr vom Ansehen der Fragenseite ab.
|
||
Question::markAnswersSeen((int)$user['id']);
|
||
|
||
$questions = $isAdmin ? Question::findAllForAdmin() : Question::findByUser((int)$user['id']);
|
||
|
||
$answerQuestion = null;
|
||
if ($isAdmin && isset($_GET['answer_id'])) {
|
||
$answerQuestion = Question::findById((int)$_GET['answer_id']);
|
||
if (!$answerQuestion || $answerQuestion['answer'] !== null) {
|
||
$answerQuestion = null;
|
||
}
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/questions.php';
|
||
} elseif ($page === 'home') {
|
||
Auth::requireLogin();
|
||
try {
|
||
$currentSeason = Season::getViewSeason();
|
||
$message = Setting::getMessage();
|
||
// Profil-Warnungen gelten immer, nicht nur im Zeitfenster vor dem Lock.
|
||
$profileWarnings = User::getProfileWarnings((int)Auth::id());
|
||
// Erste offene Runde einmal ermitteln und für Startseiten-Call-to-Action
|
||
// und den Lock-Hinweis gemeinsam nutzen.
|
||
$tippableRound = $currentSeason
|
||
? Round::getFirstTippable((int)$currentSeason['id'])
|
||
: null;
|
||
$lockWarning = $currentSeason
|
||
? Round::getLockWarning((int)$currentSeason['id'], (int)Auth::id(), $tippableRound)
|
||
: null;
|
||
$rounds = [];
|
||
$roundSummaries = [];
|
||
|
||
if ($currentSeason) {
|
||
foreach (Round::getBySeason($currentSeason['id']) as $round) {
|
||
if (Round::isCompleted(Game::getGamesByRound($round['id']))) {
|
||
$rounds[] = $round;
|
||
}
|
||
}
|
||
$rounds = array_reverse($rounds);
|
||
|
||
// Gewinne und Besonderheiten je Runde automatisch aus der Wertung
|
||
if (!empty($rounds)) {
|
||
$result = Ranking::compute($currentSeason['id'], (int)$rounds[0]['id']);
|
||
$roundSummaries = Ranking::roundSummary($result);
|
||
}
|
||
}
|
||
|
||
require __DIR__ . '/../src/Views/home.php';
|
||
|
||
} catch (Throwable $e) {
|
||
echo "<p style='color:red;'>Fehler: " . $e->getMessage() . "</p>";
|
||
}
|
||
} elseif ($uri === '/api/status') {
|
||
header('Content-Type: application/json');
|
||
echo json_encode(['status' => 'ok', 'version' => '2027.1']);
|
||
} else {
|
||
http_response_code(404);
|
||
echo "404 Not Found";
|
||
}
|