From e3d6272276911c4745ce9580c2560ec2fe443757 Mon Sep 17 00:00:00 2001
From: torsten
Date: Sun, 4 Oct 2026 23:15:54 +0200
Subject: [PATCH] migration
---
...r repository metadata might be in English. | 0
CLAUDE.md | 5 +
README.md | 59 ++
docker-compose.yml | 14 +
public/css/style.css | 102 +++
public/{icons => img}/joker.png | Bin
public/index.php | 830 ++++++++++++++++++
schema.sql | 16 +-
src/Core/Mailer.php | 133 +++
src/Models/Game.php | 38 +-
src/Models/Quota.php | 159 +++-
src/Models/Ranking.php | 34 +
src/Models/Round.php | 85 ++
src/Models/Roundmail.php | 240 +++++
src/Models/Season.php | 39 +
src/Models/Setting.php | 45 +
src/Models/Tipp.php | 82 ++
src/Views/admin.php | 36 -
src/Views/admin/accounts.php | 66 ++
src/Views/admin/roundmails.php | 182 ++++
src/Views/admin/rounds.php | 136 +++
src/Views/admin/seasons.php | 122 ++-
src/Views/home.php | 8 +-
src/Views/info/money_ranking.php | 44 +
src/Views/info/money_ranking_detail.php | 41 +
src/Views/info/no_ranking.php | 14 +
src/Views/info/quotas.php | 41 +
src/Views/login.php | 2 +
src/Views/partials/header.php | 45 +-
src/Views/ranking.php | 14 +-
src/Views/register.php | 6 +
src/Views/round.php | 2 +-
src/Views/settings.php | 75 ++
src/Views/tipps/game.php | 40 +
src/Views/tipps/index.php | 82 ++
src/Views/tipps/no_payment.php | 9 +
src/Views/tipps/round.php | 75 ++
37 files changed, 2777 insertions(+), 144 deletions(-)
create mode 100644 --system-prompt=You are a helpful coding assistant. IMPORTANT: Always reply and converse in German, even though code comments or repository metadata might be in English.
create mode 100644 CLAUDE.md
create mode 100644 public/css/style.css
rename public/{icons => img}/joker.png (100%)
create mode 100644 public/index.php
create mode 100644 src/Core/Mailer.php
create mode 100644 src/Models/Roundmail.php
create mode 100644 src/Models/Setting.php
delete mode 100644 src/Views/admin.php
create mode 100644 src/Views/admin/accounts.php
create mode 100644 src/Views/admin/roundmails.php
create mode 100644 src/Views/admin/rounds.php
create mode 100644 src/Views/info/money_ranking.php
create mode 100644 src/Views/info/money_ranking_detail.php
create mode 100644 src/Views/info/no_ranking.php
create mode 100644 src/Views/info/quotas.php
create mode 100644 src/Views/settings.php
create mode 100644 src/Views/tipps/game.php
create mode 100644 src/Views/tipps/index.php
create mode 100644 src/Views/tipps/no_payment.php
create mode 100644 src/Views/tipps/round.php
diff --git a/--system-prompt=You are a helpful coding assistant. IMPORTANT: Always reply and converse in German, even though code comments or repository metadata might be in English. b/--system-prompt=You are a helpful coding assistant. IMPORTANT: Always reply and converse in German, even though code comments or repository metadata might be in English.
new file mode 100644
index 0000000..e69de29
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..bfca78d
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,5 @@
+# Projekt-Anweisungen
+
+- **Sprache:** Antworte und kommuniziere im Terminal immer auf Deutsch.
+- **Architektur:** Dieses Projekt nutzt PHP 8.3 und kein Framework.
+- **Tests:** Führe Tests immer mit `./vendor/bin/phpunit` aus.
diff --git a/README.md b/README.md
index d25cbbd..94da840 100644
--- a/README.md
+++ b/README.md
@@ -44,6 +44,65 @@ docker compose exec app php import.php
Sobald das Skript durchgelaufen ist, sind die sauberen Daten im System und du kannst die Anwendung auf Port 8080 testen.
+## Mailversand
+
+Rundmails und Erinnerungen werden per SMTP verschickt. Konfiguriert wird das über Umgebungsvariablen des App-Containers:
+
+| Variable | Bedeutung |
+|---|---|
+| `SMTP_HOST` | Mailserver (ohne diesen Wert ist der Versand deaktiviert) |
+| `SMTP_PORT` | Port, Standard `587` |
+| `SMTP_ENCRYPTION` | `tls` (STARTTLS, Standard), `ssl` (SMTPS, meist Port 465) oder `none` |
+| `SMTP_USER`, `SMTP_PASS` | Zugangsdaten (leer lassen, wenn der Server keine Anmeldung verlangt) |
+| `MAIL_FROM`, `MAIL_FROM_NAME` | Absender der Mails |
+| `APP_URL` | Öffentliche Adresse des Tippspiels, wird für Links in Mails verwendet |
+| `REMINDER_TOKEN` | Geheimes Token für die Erinnerungs-Route (siehe unten) |
+
+Lokal fängt [Mailpit](http://localhost:8025) alle Mails ab, es wird nichts an echte Adressen verschickt.
+
+## Erinnerungsmails (Cron-Job)
+
+Spieler mit fehlenden Tipps oder fehlendem Joker bekommen automatisch eine Erinnerung. Ausgelöst wird das über eine von außen erreichbare Web-Route, die ein Cron-Job auf einem beliebigen Rechner aufruft:
+
+```bash
+curl -fsS -H "X-Reminder-Token: " "https:///index.php?page=reminder"
+```
+
+Alternativ kann das Token als Parameter übergeben werden, falls der aufrufende Dienst keine Header setzen kann (das Token landet dann allerdings in Server-Logs):
+
+```bash
+curl -fsS "https:///index.php?page=reminder&token="
+```
+
+Beispiel für die crontab, täglich um 18:00 Uhr:
+
+```
+0 18 * * * curl -fsS -H "X-Reminder-Token: geheim" "https://tippspiel.example.de/index.php?page=reminder" >> /var/log/tippspiel-reminder.log 2>&1
+```
+
+**Was bei jedem Aufruf passiert:**
+
+- Es wird die erste tippbare Runde der aktiven Saison ermittelt, also die erste Runde ohne gesperrtes Spiel.
+- Sperrt diese Runde erst in mehr als 48 Stunden, passiert nichts.
+- Andernfalls bekommen alle bezahlten Spieler mit fehlenden Tipps oder fehlendem Joker eine Mail, sofern sie Erinnerungen nicht in ihrem Profil abgeschaltet haben (`users.gets_reminders`).
+- Die Mail wird unter *Administration → Runden-E-Mails versenden* mit Versender „Automailer“ protokolliert.
+- Vorher werden bei jedem Aufruf alle automatischen Erinnerungen (Versender „Automailer“, Betreff „Fehlende Tipps/Joker“) gelöscht, die älter als einen Monat sind. Das passiert auch dann, wenn gerade keine Erinnerung fällig ist, z.B. in der Sommerpause. Rundmails von Administratoren bleiben immer erhalten.
+
+Jeder Aufruf innerhalb des 48-Stunden-Fensters verschickt erneut eine Erinnerung (wie im alten Tippspiel). Deshalb den Cron-Job **höchstens einmal täglich** laufen lassen, dann bekommt jeder Spieler pro Runde ein bis zwei Erinnerungen.
+
+**Antworten der Route** (Klartext, gut für das Cron-Log):
+
+| HTTP-Status | Bedeutung |
+|---|---|
+| `200` | Erfolgreich. Erste Zeile: Anzahl gelöschter alter Erinnerungen, zweite Zeile: Ergebnis des Versands, z.B. `Runde 17: Erinnerung an 3 Empfänger versendet.` oder `... - nichts zu tun.` |
+| `403` | Token fehlt oder ist falsch |
+| `503` | `REMINDER_TOKEN` ist auf dem Server nicht gesetzt, Erinnerungen sind deaktiviert |
+| `500` | Fehler, z.B. Mailserver nicht erreichbar (Meldung steht im Antworttext) |
+
+Mit `curl -f` beendet sich curl bei 4xx/5xx mit einem Fehlercode, sodass Cron-Überwachung Fehlschläge bemerkt.
+
+Ein sicheres Token lässt sich z.B. so erzeugen: `openssl rand -hex 32`
+
## Nützliche Befehle
### Datenbank-Interaktion
diff --git a/docker-compose.yml b/docker-compose.yml
index 5be6e9a..c3526f4 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -11,8 +11,22 @@ services:
- DB_PASS=root
- DB_OLD_NAME=tippspiel_legacy
- DB_NEW_NAME=tippspiel2027
+ # Lokal fängt Mailpit alle Mails ab (Weboberfläche: http://localhost:8025)
+ - SMTP_HOST=mailpit
+ - SMTP_PORT=1025
+ - SMTP_ENCRYPTION=none
+ - MAIL_FROM=hoschis.tippspiel.info@gmail.com
+ - MAIL_FROM_NAME=Hoschis Tippspiel
+ - APP_URL=http://localhost:8080
+ - REMINDER_TOKEN=lokal-geheim
depends_on:
- db
+ - mailpit
+
+ mailpit:
+ image: axllent/mailpit
+ ports:
+ - "8025:8025"
db:
image: mariadb:10.11
diff --git a/public/css/style.css b/public/css/style.css
new file mode 100644
index 0000000..6a4614d
--- /dev/null
+++ b/public/css/style.css
@@ -0,0 +1,102 @@
+/* Globale Stile */
+body { font-family: sans-serif; margin: 2em; }
+nav { background: #f4f4f4; padding: 1em; margin-bottom: 2em; }
+nav a { margin-right: 1em; text-decoration: none; color: #333; font-weight: bold; }
+
+/* Dropdown in der Navigation (Info -> Quoten / Geldrangliste) */
+.nav-dropdown { position: relative; display: inline-block; }
+.nav-dropdown-content {
+ display: none;
+ position: absolute;
+ left: 0;
+ top: 100%;
+ z-index: 10;
+ min-width: 12em;
+ padding: 0.5em 0;
+ background: #f4f4f4;
+ border: 1px solid #ccc;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
+}
+.nav-dropdown-content a { display: block; margin: 0; padding: 0.3em 1em; font-weight: normal; }
+.nav-dropdown-content a:hover { background: #e4e4e4; }
+.nav-dropdown-form { margin: 0.3em 0 0; padding-top: 0.3em; border-top: 1px solid #ccc; }
+.nav-dropdown-form button {
+ display: block;
+ width: 100%;
+ padding: 0.3em 1em;
+ border: none;
+ background: none;
+ color: #333;
+ font: inherit;
+ text-align: left;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.nav-dropdown-form button:hover { background: #e4e4e4; }
+.nav-dropdown-form small { color: #777; }
+.nav-dropdown-content { white-space: nowrap; }
+.nav-dropdown:hover .nav-dropdown-content,
+.nav-dropdown:focus-within .nav-dropdown-content { display: block; }
+
+/* Standard-Tabellen */
+table {
+ border-collapse: collapse;
+ width: 100%;
+ max-width: 800px;
+ margin-top: 1em;
+}
+th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
+th { background-color: #f4f4f4; }
+/* tr:nth-child(even) { background-color: #f9f9f9; } */ /* Deaktiviert, da es mit Zell-Farben interferiert */
+
+/* Utility-Klassen */
+.text-center { text-align: center !important; }
+
+/* Container für breite, scrollbare Tabellen (Rangliste, Rundenansicht) */
+.table-container {
+ width: 100%;
+ overflow-x: auto;
+ margin-top: 20px;
+}
+/* Spezifische Stile für Tabellen in diesem Container */
+.table-container table {
+ width: auto;
+ min-width: 100%;
+}
+
+/* Stile für Zellen in Rangliste/Rundenansicht */
+td.tipp-cell { text-align: center !important; position: relative; }
+td.tipp-cell.col_exact { background-color: orange !important; color: white; } /* Exaktes Ergebnis */
+td.tipp-cell.col_tendenz { background-color: grey !important; color: white; } /* Richtige Tendenz */
+td.tipp-cell.col_joker_exact { background-color: red !important; color: white; } /* Exaktes Ergebnis mit Joker */
+
+.round-filter { margin-bottom: 20px; }
+.joker-icon {
+ width: 1.1em;
+ height: 1.1em;
+ vertical-align: text-bottom;
+ margin-left: 4px;
+}
+th.game-header { white-space: normal; }
+
+/* Legende */
+.legend {
+ margin: 20px 0;
+ padding: 10px;
+ border: 1px solid #ccc;
+ background-color: #f9f9f9;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 15px;
+ align-items: center;
+}
+.legend-item {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+}
+.legend-color {
+ width: 20px;
+ height: 20px;
+ border: 1px solid #666;
+}
diff --git a/public/icons/joker.png b/public/img/joker.png
similarity index 100%
rename from public/icons/joker.png
rename to public/img/joker.png
diff --git a/public/index.php b/public/index.php
new file mode 100644
index 0000000..090d070
--- /dev/null
+++ b/public/index.php
@@ -0,0 +1,830 @@
+getMessage() . "\n";
+ }
+ exit;
+} elseif ($page === 'login') {
+ // Wenn bereits eingeloggt, zur Rangliste weiterleiten
+ if (Auth::check()) {
+ header('Location: /index.php?page=ranking');
+ exit;
+ }
+
+ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ $firstname = $_POST['firstname'] ?? '';
+ $lastname = $_POST['lastname'] ?? '';
+ $password = $_POST['password'] ?? '';
+ if (Auth::login($firstname, $lastname, $password)) {
+ header('Location: /index.php?page=ranking');
+ 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: /index.php?page=ranking');
+ exit;
+ }
+
+ if (!Setting::isRegistrationOpen()) {
+ http_response_code(403);
+ $registrationClosed = true;
+ require __DIR__ . '/../src/Views/register.php';
+ exit;
+ }
+
+ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ $data = [
+ 'firstname' => $_POST['firstname'] ?? '',
+ 'lastname' => $_POST['lastname'] ?? '',
+ 'email' => $_POST['email'] ?? '',
+ 'password' => $_POST['password'] ?? '',
+ ];
+ $password_confirm = $_POST['password_confirm'] ?? '';
+ $error = null;
+
+ if (empty($data['firstname']) || empty($data['lastname']) || empty($data['email']) || empty($data['password'])) {
+ $error = 'Alle Felder sind erforderlich.';
+ } 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: /index.php?page=ranking');
+ 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 ersten tippbaren Runde springen (wie im Legacy)
+ $tippsUrl = function () use ($activeSeason) {
+ $round = Round::getFirstTippable($activeSeason['id']);
+ return '/index.php?page=tipps' . ($round ? '#round-' . $round['id'] : '');
+ };
+
+ if ($page === 'tipps') {
+ $rounds = [];
+ $firstTippableRoundId = null;
+ 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;
+
+ 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());
+ 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;
+ 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());
+ 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 === 'info_quotas') {
+ // Info -> Quoten (Legacy UsersController::show_payouts)
+ Auth::requireLogin();
+ $currentSeason = Season::getCurrent();
+ $payouts = $currentSeason ? Quota::computePayouts($currentSeason['id']) : null;
+ $activeUserCount = $currentSeason ? count(User::getPaid($currentSeason['id'])) : 0;
+ $stake = $currentSeason ? (Quota::getMapBySeason($currentSeason['id'])['einsatz'] ?? 0) : 0;
+ 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::getCurrent();
+ 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::getCurrent();
+ $result = null;
+ $seasonStart = null;
+ if ($currentSeason) {
+ ['result' => $result, 'season_start' => $seasonStart] = Ranking::computeForMoneyRanking($currentSeason['id']);
+ }
+ $moneyRanking = $result ? Ranking::moneyRanking($result) : [];
+ require __DIR__ . '/../src/Views/admin/accounts.php';
+} 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']);
+
+ 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'] = strtoupper(str_replace(' ', '', $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.';
+ } 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' && ($_POST['action'] ?? '') === 'set_registration') {
+ Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1');
+ // 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, '//');
+ 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'] ?? '',
+ ];
+ if ($data['name'] === '' || !ctype_digit((string)$data['rounds']) || (int)$data['rounds'] < 1
+ || !ctype_digit((string)$data['max_identical_jokertipps'])) {
+ throw new \Exception('Name, Runden und maximale Anzahl gleicher Joker 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);
+ Season::setCurrent($newSeasonId);
+ $_SESSION['admin_message'] = "Saison erfolgreich erstellt und als aktiv gesetzt.";
+ } 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);
+ $_SESSION['admin_message'] = "Aktive Saison wurde geändert.";
+ } 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();
+ $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,
+ '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();
+
+ $currentSeason = Season::getCurrent();
+ $seasonId = (int)($_GET['season_id'] ?? ($currentSeason['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();
+
+ 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();
+ $html = Roundmail::textToHtml($text);
+ $failed = Mailer::send($recipients['valid'], $topic, $html, $sender['email'] ?? null);
+ $sent = array_values(array_diff($recipients['valid'], $failed));
+ if (!empty($sent)) {
+ Roundmail::create((int)$sender['id'], $sent, $topic, $html);
+ }
+
+ $_SESSION['admin_message'] = 'Mail an ' . count($sent) . ' Empfänger versendet.';
+ if (!empty($failed)) {
+ $_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $failed);
+ }
+ } 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']);
+
+ if ($compose) {
+ $currentSeason = Season::getCurrent();
+ $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) {
+ $perPage = 20;
+ $totalMails = Roundmail::count();
+ $totalPages = max(1, (int)ceil($totalMails / $perPage));
+ $currentPage = min(max(1, (int)($_GET['p'] ?? 1)), $totalPages);
+ $mails = Roundmail::getPage($perPage, ($currentPage - 1) * $perPage);
+ }
+
+ require __DIR__ . '/../src/Views/admin/roundmails.php';
+} elseif ($page === 'admin_users') {
+ Auth::requireLogin();
+ Auth::requireAdmin();
+
+ $currentSeason = Season::getCurrent();
+ $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 === 'create' || $action === 'update') {
+ $data = [
+ 'firstname' => $_POST['firstname'],
+ 'lastname' => $_POST['lastname'],
+ 'email' => $_POST['email'],
+ 'password' => $_POST['password'],
+ 'admin' => isset($_POST['admin']) ? 1 : 0,
+ ];
+
+ if ($action === 'create') {
+ if (empty($data['password'])) {
+ throw new \Exception('Passwort ist erforderlich.');
+ }
+ User::create($data);
+ $_SESSION['admin_message'] = "Benutzer erfolgreich erstellt.";
+ } elseif ($userId) {
+ 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']);
+ }
+ $editUser = null;
+ if (isset($_GET['edit_id'])) {
+ $editUser = User::findById((int)$_GET['edit_id']);
+ }
+
+ 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 "Fehler: " . htmlspecialchars($e->getMessage()) . "
";
+ }
+} elseif ($page === 'ranking') {
+ Auth::requireLogin();
+ try {
+ $currentSeason = Season::getCurrent();
+ if (!$currentSeason) {
+ throw new \Exception("Keine aktuelle Saison gefunden.");
+ }
+
+ // Auswählbar sind nur gesperrte Runden (erstes Spiel angepfiffen),
+ // Standard ist die letzte Runde mit Ergebnis
+ $allRounds = [];
+ $defaultRound = null;
+ foreach (Round::getBySeason($currentSeason['id']) as $round) {
+ $roundGames = Game::getGamesByRound($round['id']);
+ if (empty($roundGames) || !Game::isLocked($roundGames[0]['kickoff'])) {
+ continue;
+ }
+ $allRounds[] = $round;
+ foreach ($roundGames as $game) {
+ if ((int)$game['score1'] > -1) {
+ $defaultRound = $round;
+ break;
+ }
+ }
+ }
+
+ $selectedRound = $defaultRound ?? ($allRounds[0] ?? null);
+ if (isset($_GET['round_id'])) {
+ foreach ($allRounds as $round) {
+ if ((int)$round['id'] === (int)$_GET['round_id']) {
+ $selectedRound = $round;
+ }
+ }
+ }
+
+ $ranking = [];
+ $games = [];
+ if ($selectedRound) {
+ $result = Ranking::compute($currentSeason['id'], $selectedRound['id']);
+ $ranking = Ranking::roundTable($result);
+ $games = $result['rounds'][$selectedRound['id']]['games'] ?? [];
+ }
+
+ require __DIR__ . '/../src/Views/ranking.php';
+ } catch (Throwable $e) {
+ http_response_code(500);
+ echo "Fehler: " . htmlspecialchars($e->getMessage()) . "
";
+ }
+} elseif ($page === 'home') {
+ Auth::requireLogin();
+ try {
+ $db = Database::getConnection();
+ $userCount = $db->query("SELECT COUNT(*) FROM users")->fetchColumn();
+
+ $currentSeason = Season::getCurrent();
+
+ if ($currentSeason) {
+ $rounds = Round::getBySeason($currentSeason['id']);
+ } else {
+ $rounds = [];
+ }
+
+ // Testdaten für die Startseite
+ $scoreTest = Tipp::getScoreLocal(2, 1, 2, 1, true);
+ $lastRoundId = $db->query("SELECT round_id FROM games WHERE score1 > -1 ORDER BY id DESC LIMIT 1")->fetchColumn();
+
+ if ($lastRoundId) {
+ $games = Game::getGamesByRound($lastRoundId);
+ } else {
+ $games = [];
+ }
+
+ require __DIR__ . '/../src/Views/home.php';
+
+ } catch (Throwable $e) {
+ echo "Fehler: " . $e->getMessage() . "
";
+ }
+} 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";
+}
diff --git a/schema.sql b/schema.sql
index 1a0754b..91ce26a 100644
--- a/schema.sql
+++ b/schema.sql
@@ -13,7 +13,7 @@ CREATE TABLE `users` (
`mobile` varchar(255) DEFAULT NULL,
`deleted` timestamp NULL DEFAULT NULL,
`admin` tinyint(1) NOT NULL DEFAULT '0',
- `remember_token` varchar(100) DEFAULT NULL,
+ `gets_reminders` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
@@ -30,7 +30,8 @@ CREATE TABLE `tipps` (
`joker` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
- PRIMARY KEY (`id`)
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `tipps_user_game_unique` (`user_id`, `game_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `games`;
@@ -63,7 +64,7 @@ CREATE TABLE `seasons` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`rounds` int(11) NOT NULL DEFAULT '36',
- `active` tinyint(1) NOT NULL DEFAULT '1',
+ `max_identical_jokertipps` int(11) NOT NULL DEFAULT '6',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
@@ -73,6 +74,7 @@ DROP TABLE IF EXISTS `settings`;
CREATE TABLE `settings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`current_season_id` int(11) NOT NULL,
+ `registration_open` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
@@ -123,3 +125,11 @@ CREATE TABLE `manual_payouts` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+DROP TABLE IF EXISTS `password_resets`;
+CREATE TABLE `password_resets` (
+ `email` varchar(150) NOT NULL,
+ `token` varchar(100) NOT NULL,
+ `created_at` timestamp NULL DEFAULT NULL,
+ KEY `password_resets_email_index` (`email`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
diff --git a/src/Core/Mailer.php b/src/Core/Mailer.php
new file mode 100644
index 0000000..1cde561
--- /dev/null
+++ b/src/Core/Mailer.php
@@ -0,0 +1,133 @@
+connect();
+
+ $failed = [];
+ try {
+ foreach ($recipients as $to) {
+ try {
+ $mailer->sendOne($to, $subject, $html, $replyTo);
+ } catch (\Exception $e) {
+ $failed[] = $to;
+ $mailer->command('RSET', [250]);
+ }
+ }
+ $mailer->command('QUIT', [221]);
+ } finally {
+ fclose($mailer->socket);
+ }
+ return $failed;
+ }
+
+ private function connect() {
+ $host = getenv('SMTP_HOST');
+ if (!$host) {
+ throw new \Exception('Kein Mailserver konfiguriert (SMTP_HOST fehlt).');
+ }
+ $port = (int)(getenv('SMTP_PORT') ?: 587);
+ $encryption = getenv('SMTP_ENCRYPTION') ?: 'tls';
+
+ $address = ($encryption === 'ssl' ? 'ssl://' : 'tcp://') . $host . ':' . $port;
+ $this->socket = @stream_socket_client($address, $errno, $errstr, 15);
+ if (!$this->socket) {
+ throw new \Exception("Verbindung zum Mailserver fehlgeschlagen: $errstr");
+ }
+ stream_set_timeout($this->socket, 30);
+
+ $this->expect([220]);
+ $hostname = gethostname() ?: 'localhost';
+ $this->command("EHLO $hostname", [250]);
+
+ if ($encryption === 'tls') {
+ $this->command('STARTTLS', [220]);
+ if (!stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
+ throw new \Exception('STARTTLS fehlgeschlagen.');
+ }
+ $this->command("EHLO $hostname", [250]);
+ }
+
+ $user = getenv('SMTP_USER');
+ if ($user) {
+ $this->command('AUTH LOGIN', [334]);
+ $this->command(base64_encode($user), [334]);
+ $this->command(base64_encode((string)getenv('SMTP_PASS')), [235]);
+ }
+ }
+
+ private function sendOne($to, $subject, $html, $replyTo) {
+ $from = getenv('MAIL_FROM') ?: 'noreply@localhost';
+ $fromName = getenv('MAIL_FROM_NAME') ?: 'Tippspiel';
+
+ $this->command('MAIL FROM:<' . $from . '>', [250]);
+ $this->command('RCPT TO:<' . $to . '>', [250, 251]);
+ $this->command('DATA', [354]);
+
+ $headers = [
+ 'Date: ' . date('r'),
+ 'From: ' . self::encodeHeader($fromName) . ' <' . $from . '>',
+ 'To: <' . $to . '>',
+ 'Subject: ' . self::encodeHeader($subject),
+ 'MIME-Version: 1.0',
+ 'Content-Type: text/html; charset=UTF-8',
+ 'Content-Transfer-Encoding: base64',
+ ];
+ if ($replyTo) {
+ $headers[] = 'Reply-To: <' . $replyTo . '>';
+ }
+
+ $body = chunk_split(base64_encode($html), 76, "\r\n");
+ // base64 enthält keine Zeilen, die mit "." beginnen – kein Dot-Stuffing nötig
+ fwrite($this->socket, implode("\r\n", $headers) . "\r\n\r\n" . $body . ".\r\n");
+ $this->expect([250]);
+ }
+
+ private function command($line, array $expectedCodes) {
+ fwrite($this->socket, $line . "\r\n");
+ return $this->expect($expectedCodes);
+ }
+
+ private function expect(array $expectedCodes) {
+ $response = '';
+ while (($line = fgets($this->socket, 515)) !== false) {
+ $response .= $line;
+ // Mehrzeilige Antworten: "250-..." – letzte Zeile hat ein Leerzeichen nach dem Code
+ if (strlen($line) < 4 || $line[3] === ' ') {
+ break;
+ }
+ }
+ $code = (int)substr($response, 0, 3);
+ if (!in_array($code, $expectedCodes, true)) {
+ throw new \Exception('SMTP-Fehler: ' . trim($response));
+ }
+ return $response;
+ }
+
+ private static function encodeHeader($text) {
+ return preg_match('/[^\x20-\x7E]/', $text) ? '=?UTF-8?B?' . base64_encode($text) . '?=' : $text;
+ }
+}
diff --git a/src/Models/Game.php b/src/Models/Game.php
index a0297e6..acb1d4d 100644
--- a/src/Models/Game.php
+++ b/src/Models/Game.php
@@ -50,8 +50,44 @@ class Game {
*/
public static function getGamesByRound($roundId) {
$db = Database::getConnection();
- $stmt = $db->prepare("SELECT * FROM games WHERE round_id = ? ORDER BY kickoff ASC");
+ $stmt = $db->prepare("SELECT * FROM games WHERE round_id = ? ORDER BY kickoff ASC, id ASC");
$stmt->execute([$roundId]);
return $stmt->fetchAll();
}
+
+ /**
+ * Holt ein Spiel anhand der ID.
+ *
+ * @param int $id
+ * @return array|false
+ */
+ public static function getById($id) {
+ $db = Database::getConnection();
+ $stmt = $db->prepare("SELECT * FROM games WHERE id = ?");
+ $stmt->execute([$id]);
+ return $stmt->fetch();
+ }
+
+ /**
+ * Aktualisiert Paarung, Anstoß und Ergebnis eines Spiels (Legacy GamesController::store).
+ * Ein fehlendes Ergebnis wird als -1:-1 gespeichert.
+ *
+ * @param int $id
+ * @param array $data ['team1', 'team2', 'kickoff' (Y-m-d H:i:s), 'score1', 'score2']
+ * @return bool
+ */
+ public static function update($id, array $data) {
+ $db = Database::getConnection();
+ $stmt = $db->prepare(
+ "UPDATE games SET team1 = ?, team2 = ?, kickoff = ?, score1 = ?, score2 = ?, updated_at = NOW() WHERE id = ?"
+ );
+ return $stmt->execute([
+ $data['team1'],
+ $data['team2'],
+ $data['kickoff'],
+ (int)$data['score1'],
+ (int)$data['score2'],
+ $id,
+ ]);
+ }
}
diff --git a/src/Models/Quota.php b/src/Models/Quota.php
index c97a663..2a8fef2 100644
--- a/src/Models/Quota.php
+++ b/src/Models/Quota.php
@@ -5,6 +5,59 @@ namespace App\Models;
use App\Core\Database;
class Quota {
+
+ /** Anzahl der Platzierungen mit Preisgeld (platz1..platz10) */
+ const PLACES = 10;
+
+ /**
+ * Berechnet die Ausschüttungsbeträge einer Saison (portiert aus Legacy Quota::getPayouts).
+ *
+ * - Pott = bezahlte Spieler * Einsatz.
+ * - Tagessieg je Runde: Anteil "tagessieg" / Rundenzahl, auf durch 6 teilbar abgerundet.
+ * Der Rundungsrest fließt in den Platzierungstopf.
+ * - Platz 1..10: Anteil "platzN" des Platzierungstopfs, auf durch 6 teilbar abgerundet.
+ * - Der nicht verteilte Rest des Potts geht an Platz 1.
+ * Grünes Trikot, Pokal und Liga werden nicht mehr berücksichtigt.
+ *
+ * @param int $seasonId
+ * @return array ['tagessieg' => int, 'platz1' => int, ..., 'platz10' => int]
+ */
+ public static function computePayouts($seasonId) {
+ $quotas = self::getMapBySeason($seasonId);
+ $quota = fn($name) => $quotas[$name] ?? 0.0;
+
+ $roundCount = count(Round::getBySeason($seasonId));
+ $pot = count(User::getPaid($seasonId)) * $quota('einsatz');
+
+ $dayWinSum = (int)($pot * $quota('tagessieg') / 100);
+ $dayWin = $roundCount > 0 ? self::get6Divisor((int)($dayWinSum / $roundCount)) : 0;
+
+ $placementPot = (int)($pot * $quota('platzierung') / 100);
+ $placementPot += $dayWinSum - $dayWin * $roundCount;
+
+ $payouts = ['tagessieg' => $dayWin];
+ $distributed = $dayWin * $roundCount;
+ for ($place = 1; $place <= self::PLACES; $place++) {
+ $amount = self::get6Divisor((int)($placementPot * $quota('platz' . $place) / 100));
+ $payouts['platz' . $place] = $amount;
+ $distributed += $amount;
+ }
+
+ // Nicht verteilter Rest an Platz 1
+ $payouts['platz1'] += (int)$pot - $distributed;
+
+ return $payouts;
+ }
+
+ /**
+ * Senkt die Zahl, bis sie durch 6 teilbar ist (Abrundungsvorgabe für Ausschüttungen).
+ * @param int $number
+ * @return int
+ */
+ public static function get6Divisor($number) {
+ return max(0, $number - $number % 6);
+ }
+
/**
* Holt alle Quoten für eine Saison.
* @param int $seasonId
@@ -18,37 +71,101 @@ class Quota {
}
/**
- * Aktualisiert die Quoten für eine Saison.
- * Löscht bestehende und fügt die neuen ein.
+ * Quoten einer Saison als name => prc.
* @param int $seasonId
- * @param array $quotasData
- * @return bool
+ * @return array
*/
- public static function updateForSeason($seasonId, $quotasData) {
+ public static function getMapBySeason($seasonId) {
+ $map = [];
+ foreach (self::getBySeason($seasonId) as $quota) {
+ $map[$quota['name']] = (float)$quota['prc'];
+ }
+ return $map;
+ }
+
+ /**
+ * Namen der pflegbaren Quoten (Legacy SeasonsController::store_quota).
+ * @return string[]
+ */
+ public static function editableNames() {
+ $names = ['einsatz', 'tagessieg', 'platzierung'];
+ for ($place = 1; $place <= self::PLACES; $place++) {
+ $names[] = 'platz' . $place;
+ }
+ return $names;
+ }
+
+ /**
+ * Standardquoten für eine neue Saison (Legacy Quota::createDefaultQuota
+ * ohne Grünes Trikot, Pokal und Liga).
+ * @return array name => prc
+ */
+ public static function defaults() {
+ return [
+ 'einsatz' => 40, 'tagessieg' => 60, 'platzierung' => 40,
+ 'platz1' => 21, 'platz2' => 17, 'platz3' => 13, 'platz4' => 10, 'platz5' => 9,
+ 'platz6' => 8, 'platz7' => 7, 'platz8' => 6, 'platz9' => 5, 'platz10' => 4,
+ ];
+ }
+
+ /**
+ * Prüft die Quoten: alle Werte >= 0, Tagessieg + Platzierung = 100 %,
+ * Platz 1..10 zusammen = 100 %.
+ * @param array $quotas name => prc
+ * @return string|null Fehlermeldung oder null
+ */
+ public static function validate(array $quotas) {
+ foreach (self::editableNames() as $name) {
+ if (!isset($quotas[$name]) || !is_numeric($quotas[$name]) || $quotas[$name] < 0) {
+ return "Ungültiger Wert für \"$name\".";
+ }
+ }
+ if (abs($quotas['tagessieg'] + $quotas['platzierung'] - 100) > 0.001) {
+ return 'Tagessieg und Platzierung müssen zusammen 100 % ergeben.';
+ }
+ $placeSum = 0;
+ for ($place = 1; $place <= self::PLACES; $place++) {
+ $placeSum += $quotas['platz' . $place];
+ }
+ if (abs($placeSum - 100) > 0.001) {
+ return 'Die Platzierungsquoten müssen zusammen 100 % ergeben (aktuell ' . round($placeSum, 2) . ' %).';
+ }
+ return null;
+ }
+
+ /**
+ * Speichert die pflegbaren Quoten einer Saison (Upsert je Name wie Legacy Quota::setQuota).
+ * Andere Einträge (z.B. Legacy gshirt, liga) bleiben unverändert.
+ * @param int $seasonId
+ * @param array $quotas name => prc
+ */
+ public static function saveForSeason($seasonId, array $quotas) {
$db = Database::getConnection();
+ $existing = [];
+ foreach (self::getBySeason($seasonId) as $quota) {
+ $existing[$quota['name']] = (int)$quota['id'];
+ }
+
+ $update = $db->prepare("UPDATE quotas SET prc = ?, `order` = ?, updated_at = NOW() WHERE id = ?");
+ $insert = $db->prepare(
+ "INSERT INTO quotas (season_id, name, `order`, prc, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())"
+ );
+
$db->beginTransaction();
-
try {
- $stmt = $db->prepare("DELETE FROM quotas WHERE season_id = ?");
- $stmt->execute([$seasonId]);
-
- $order = 0;
- if (is_array($quotasData)) {
- foreach ($quotasData as $quota) {
- if (!empty($quota['name']) && isset($quota['prc']) && is_numeric($quota['prc'])) {
- $stmt_insert = $db->prepare(
- "INSERT INTO quotas (season_id, name, `order`, prc, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())"
- );
- $stmt_insert->execute([$seasonId, $quota['name'], $order++, (float)$quota['prc']]);
- }
+ foreach (self::editableNames() as $name) {
+ $prc = (float)$quotas[$name];
+ $order = str_starts_with($name, 'platz') && $name !== 'platzierung' ? (int)substr($name, 5) : 0;
+ if (isset($existing[$name])) {
+ $update->execute([$prc, $order, $existing[$name]]);
+ } else {
+ $insert->execute([$seasonId, $name, $order, $prc]);
}
}
-
$db->commit();
- return true;
} catch (\Exception $e) {
$db->rollBack();
- return false;
+ throw $e;
}
}
}
diff --git a/src/Models/Ranking.php b/src/Models/Ranking.php
index e3a614f..ce9d520 100644
--- a/src/Models/Ranking.php
+++ b/src/Models/Ranking.php
@@ -147,6 +147,7 @@ class Ranking {
$cells[$game['id']] = [
'text' => ($tipp1 < 0 ? 'x' : $tipp1) . ':' . ($tipp2 < 0 ? 'x' : $tipp2),
'joker' => $joker,
+ 'points' => Tipp::getScoreLocal((int)$game['score1'], (int)$game['score2'], $tipp1, $tipp2, $joker),
'color' => Tipp::getCol((int)$game['score1'], (int)$game['score2'], $tipp1, $tipp2, $joker),
];
}
@@ -198,6 +199,39 @@ class Ranking {
return $items;
}
+ /**
+ * Wertung für Geldrangliste und Kontoliste (Legacy UsersController::money_ranking):
+ * gerechnet wird bis zur letzten gesperrten Runde, angezeigt erst, wenn mindestens
+ * eine Runde abgeschlossen ist.
+ *
+ * @param int $seasonId
+ * @return array ['result' => Ergebnis von compute() oder null, 'season_start' => \DateTime|null]
+ */
+ public static function computeForMoneyRanking($seasonId) {
+ $lastLockedRoundId = null;
+ $hasCompletedRound = false;
+ $seasonStart = null;
+ foreach (Round::getBySeason($seasonId) as $round) {
+ $games = Game::getGamesByRound($round['id']);
+ if (empty($games)) {
+ continue;
+ }
+ $seasonStart = $seasonStart ?? Round::getLockTime($games);
+ if (Round::isLocked($games)) {
+ $lastLockedRoundId = (int)$round['id'];
+ }
+ if (Round::isCompleted($games)) {
+ $hasCompletedRound = true;
+ }
+ }
+
+ $result = null;
+ if ($hasCompletedRound && $lastLockedRoundId !== null) {
+ $result = self::compute($seasonId, $lastLockedRoundId);
+ }
+ return ['result' => $result, 'season_start' => $seasonStart];
+ }
+
/**
* Geldrangliste: Summe aller Ausschüttungen je Spieler, absteigend sortiert.
*
diff --git a/src/Models/Round.php b/src/Models/Round.php
index 3e2c124..6adc6d6 100644
--- a/src/Models/Round.php
+++ b/src/Models/Round.php
@@ -38,4 +38,89 @@ class Round {
$stmt = $db->prepare("UPDATE rounds SET name = ?, updated_at = NOW() WHERE id = ?");
return $stmt->execute([$name, $id]);
}
+
+ /**
+ * Speichert den Rundenbericht. Zeilenumbrüche werden wie im Legacy als
gespeichert.
+ *
+ * @param int $id
+ * @param string $report Klartext mit Zeilenumbrüchen
+ * @return bool
+ */
+ public static function updateReport($id, $report) {
+ $report = str_replace(["\r\n", "\r", "\n"], "
", trim($report));
+ $db = Database::getConnection();
+ $stmt = $db->prepare("UPDATE rounds SET report = ?, updated_at = NOW() WHERE id = ?");
+ return $stmt->execute([$report, $id]);
+ }
+
+ /**
+ * Rundenbericht als Klartext für Formulare (Gegenstück zu updateReport).
+ *
+ * @param string|null $report
+ * @return string
+ */
+ public static function reportToText($report) {
+ return str_replace(["
", "
", "
"], "\n", (string)$report);
+ }
+
+ /**
+ * Sperrzeitpunkt der Runde: 1 Minute vor dem frühesten Anstoß (Legacy Round::getLockTime).
+ *
+ * @param array $games Spiele der Runde
+ * @return \DateTime|null
+ */
+ public static function getLockTime(array $games) {
+ if (empty($games)) {
+ return null;
+ }
+ $earliest = min(array_column($games, 'kickoff'));
+ return (new \DateTime($earliest))->modify('-1 minute');
+ }
+
+ /**
+ * Eine Runde ist abgeschlossen, wenn alle Spiele ein Ergebnis haben (Legacy Round::isCompleted).
+ *
+ * @param array $games Spiele der Runde
+ * @return bool
+ */
+ public static function isCompleted(array $games) {
+ foreach ($games as $game) {
+ if ((int)$game['score1'] < 0 || (int)$game['score2'] < 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Eine Runde ist gesperrt, sobald eines ihrer Spiele gesperrt ist (Legacy Round::hasLockedGame).
+ *
+ * @param array $games Spiele der Runde
+ * @return bool
+ */
+ public static function isLocked(array $games) {
+ foreach ($games as $game) {
+ if (Game::isLocked($game['kickoff'])) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Erste Runde der Saison, in der noch kein Spiel gesperrt ist (Legacy Round::getFirstTippableRound).
+ *
+ * @param int $seasonId
+ * @return array|null Runde inkl. 'games'
+ */
+ public static function getFirstTippable($seasonId) {
+ foreach (self::getBySeason($seasonId) as $round) {
+ $games = Game::getGamesByRound($round['id']);
+ if (!self::isLocked($games)) {
+ $round['games'] = $games;
+ return $round;
+ }
+ }
+ return null;
+ }
}
diff --git a/src/Models/Roundmail.php b/src/Models/Roundmail.php
new file mode 100644
index 0000000..f50dc9c
--- /dev/null
+++ b/src/Models/Roundmail.php
@@ -0,0 +1,240 @@
+query("SELECT COUNT(*) FROM roundmails")->fetchColumn();
+ }
+
+ /**
+ * Eine Seite der Mails, neueste zuerst, mit Name des Versenders.
+ *
+ * @param int $limit
+ * @param int $offset
+ * @return array
+ */
+ public static function getPage($limit, $offset) {
+ $db = Database::getConnection();
+ $stmt = $db->prepare(
+ "SELECT m.id, m.send_date, m.topic, m.recipients, COALESCE(u.name, 'Automailer') AS sender_name
+ FROM roundmails m
+ LEFT JOIN users u ON u.id = m.user_id
+ ORDER BY m.send_date DESC, m.id DESC
+ LIMIT ? OFFSET ?"
+ );
+ $stmt->bindValue(1, (int)$limit, \PDO::PARAM_INT);
+ $stmt->bindValue(2, (int)$offset, \PDO::PARAM_INT);
+ $stmt->execute();
+ return $stmt->fetchAll();
+ }
+
+ /**
+ * @param int $id
+ * @return array|false
+ */
+ public static function findById($id) {
+ $db = Database::getConnection();
+ $stmt = $db->prepare(
+ "SELECT m.*, COALESCE(u.name, 'Automailer') AS sender_name
+ FROM roundmails m
+ LEFT JOIN users u ON u.id = m.user_id
+ WHERE m.id = ?"
+ );
+ $stmt->execute([$id]);
+ return $stmt->fetch();
+ }
+
+ /**
+ * Protokolliert eine versendete Mail. Die Nachricht wird wie im Legacy mit
gespeichert.
+ *
+ * @param int $userId
+ * @param string[] $recipients
+ * @param string $topic
+ * @param string $messageHtml
+ * @return int ID
+ */
+ public static function create($userId, array $recipients, $topic, $messageHtml) {
+ $db = Database::getConnection();
+ $stmt = $db->prepare(
+ "INSERT INTO roundmails (user_id, send_date, recipients, topic, message, created_at, updated_at)
+ VALUES (?, CURDATE(), ?, ?, ?, NOW(), NOW())"
+ );
+ $stmt->execute([$userId, implode(',', $recipients), $topic, $messageHtml]);
+ return (int)$db->lastInsertId();
+ }
+
+ /**
+ * Wandelt den Klartext aus dem Formular in das gespeicherte/versendete HTML um
+ * (HTML wird maskiert, Zeilenumbrüche werden zu
, URLs werden verlinkt).
+ *
+ * @param string $text
+ * @return string
+ */
+ public static function textToHtml($text) {
+ $html = htmlspecialchars(trim($text), ENT_QUOTES, 'UTF-8');
+ $html = preg_replace('~https?://[^\s<]+~', '$0', $html);
+ return str_replace(["\r\n", "\r", "\n"], '
', $html);
+ }
+
+ /**
+ * Zerlegt eine Empfängerliste (Komma, Semikolon, Leerzeichen oder Zeilenumbruch getrennt).
+ *
+ * @param string $list
+ * @return array ['valid' => [...], 'invalid' => [...]]
+ */
+ public static function parseRecipients($list) {
+ $result = ['valid' => [], 'invalid' => []];
+ foreach (preg_split('/[\s,;]+/', (string)$list, -1, PREG_SPLIT_NO_EMPTY) as $address) {
+ $key = filter_var($address, FILTER_VALIDATE_EMAIL) ? 'valid' : 'invalid';
+ $result[$key][strtolower($address)] = $address;
+ }
+ $result['valid'] = array_values($result['valid']);
+ $result['invalid'] = array_values($result['invalid']);
+ return $result;
+ }
+
+ /**
+ * Empfängergruppen für die Schnellauswahl (Legacy RoundmailController::show).
+ * Fehlende Tipps/Joker beziehen sich auf die erste tippbare Runde und nur auf bezahlte Spieler.
+ *
+ * @param int $seasonId
+ * @param array|null $tippableRound Ergebnis von Round::getFirstTippable
+ * @return array key => ['label' => ..., 'emails' => [...]]
+ */
+ public static function recipientGroups($seasonId, $tippableRound) {
+ $users = User::getAll();
+ $paidIds = array_flip(array_map('intval', array_column(User::getPaid($seasonId), 'id')));
+
+ $missing = ['tipps' => [], 'joker' => []];
+ if ($tippableRound) {
+ $missing = Tipp::getMissing($tippableRound['id'], array_keys($paidIds));
+ }
+ $missingTipps = array_flip(array_map('intval', $missing['tipps']));
+ $missingJoker = array_flip(array_map('intval', $missing['joker']));
+
+ $groups = [
+ 'admins' => ['label' => 'Alle Administratoren', 'emails' => []],
+ 'active' => ['label' => 'Alle aktiven Spieler', 'emails' => []],
+ 'inactive' => ['label' => 'Alle inaktiven Spieler', 'emails' => []],
+ 'missing_tipps' => ['label' => 'Spieler mit fehlenden Tipps', 'emails' => []],
+ 'missing_joker' => ['label' => 'Spieler mit fehlendem Joker', 'emails' => []],
+ ];
+ foreach ($users as $user) {
+ $id = (int)$user['id'];
+ if (empty($user['email'])) {
+ continue;
+ }
+ if ($user['admin']) {
+ $groups['admins']['emails'][] = $user['email'];
+ }
+ $groups[isset($paidIds[$id]) ? 'active' : 'inactive']['emails'][] = $user['email'];
+ if (isset($missingTipps[$id])) {
+ $groups['missing_tipps']['emails'][] = $user['email'];
+ }
+ if (isset($missingJoker[$id])) {
+ $groups['missing_joker']['emails'][] = $user['email'];
+ }
+ }
+ return $groups;
+ }
+
+ /**
+ * Erinnerungsmail an alle bezahlten Spieler mit fehlenden Tipps oder Joker in der ersten
+ * tippbaren Runde (Legacy RoundmailController::checkReminder). Verschickt nur, wenn die Runde
+ * in weniger als REMINDER_HOURS Stunden sperrt, und nur an Spieler mit gets_reminders = 1.
+ *
+ * @param string $appUrl Basis-URL für den Link in der Mail
+ * @return string Ergebnis als Text (für das Log des Cron-Jobs)
+ */
+ public static function sendReminder($appUrl) {
+ $season = Season::getCurrent();
+ if (!$season) {
+ return 'Keine aktive Saison - nichts zu tun.';
+ }
+ $round = Round::getFirstTippable($season['id']);
+ if (!$round) {
+ return 'Keine tippbare Runde - nichts zu tun.';
+ }
+ $lockTime = Round::getLockTime($round['games']);
+ $warnFrom = (clone $lockTime)->modify('-' . self::REMINDER_HOURS . ' hours');
+ if (new \DateTime() < $warnFrom) {
+ return sprintf('%s sperrt am %s, Erinnerung erst ab %s - nichts zu tun.',
+ $round['name'], $lockTime->format('d.m.Y H:i'), $warnFrom->format('d.m.Y H:i'));
+ }
+
+ $paid = [];
+ foreach (User::getPaid($season['id']) as $user) {
+ if ($user['deleted'] === null && $user['gets_reminders'] && !empty($user['email'])) {
+ $paid[(int)$user['id']] = $user['email'];
+ }
+ }
+ $missing = Tipp::getMissing($round['id'], array_keys($paid));
+ $userIds = array_unique(array_merge($missing['tipps'], $missing['joker']));
+ $recipients = [];
+ foreach ($userIds as $userId) {
+ $recipients[] = $paid[(int)$userId];
+ }
+ if (empty($recipients)) {
+ return $round['name'] . ': alle Tipps und Joker vollständig - keine Erinnerung nötig.';
+ }
+
+ $topic = self::REMINDER_TOPIC;
+ $link = htmlspecialchars(rtrim($appUrl, '/') . '/', ENT_QUOTES, 'UTF-8');
+ $html = 'Es fehlen noch Tipps/Joker für: ' . htmlspecialchars($round['name'], ENT_QUOTES, 'UTF-8')
+ . '
Die Runde sperrt sich: ' . $lockTime->format('d.m.Y H:i')
+ . '
Link zum Spiel: ( Hier klicken )';
+
+ $failed = Mailer::send($recipients, $topic, $html);
+ $sent = array_values(array_diff($recipients, $failed));
+ if (!empty($sent)) {
+ self::create(0, $sent, $topic, $html);
+ }
+
+ $result = sprintf('%s: Erinnerung an %d Empfänger versendet.', $round['name'], count($sent));
+ if (!empty($failed)) {
+ $result .= ' Nicht zustellbar: ' . implode(', ', $failed);
+ }
+ return $result;
+ }
+
+ /**
+ * Löscht automatische Erinnerungsmails (Automailer, Betreff REMINDER_TOPIC), die älter als
+ * REMINDER_RETENTION_MONTHS Monate sind. Rundmails von Admins bleiben unberührt.
+ *
+ * @return int Anzahl gelöschter Mails
+ */
+ public static function deleteOldReminders() {
+ $db = Database::getConnection();
+ $stmt = $db->prepare(
+ "DELETE FROM roundmails
+ WHERE user_id = 0 AND topic = ?
+ AND send_date < CURDATE() - INTERVAL " . (int)self::REMINDER_RETENTION_MONTHS . " MONTH"
+ );
+ $stmt->execute([self::REMINDER_TOPIC]);
+ return $stmt->rowCount();
+ }
+}
diff --git a/src/Models/Season.php b/src/Models/Season.php
index b4c19e6..df332b2 100644
--- a/src/Models/Season.php
+++ b/src/Models/Season.php
@@ -151,6 +151,45 @@ class Season {
return $stmt->execute($params);
}
+ /**
+ * Löscht eine Saison mit allen abhängigen Daten (Tipps, Spiele, Runden,
+ * Quoten, Zahlungen, manuelle Ausschüttungen). Die aktive Saison kann nicht gelöscht werden.
+ *
+ * @param int $id
+ * @throws \Exception wenn die Saison aktiv ist oder nicht existiert
+ */
+ public static function delete($id) {
+ $id = (int)$id;
+ if (!self::findById($id)) {
+ throw new \Exception('Saison nicht gefunden.');
+ }
+ $current = self::getCurrent();
+ if ($current && (int)$current['id'] === $id) {
+ throw new \Exception('Die aktive Saison kann nicht gelöscht werden.');
+ }
+
+ $db = Database::getConnection();
+ $db->beginTransaction();
+ try {
+ $statements = [
+ "DELETE t FROM tipps t JOIN games g ON g.id = t.game_id JOIN rounds r ON r.id = g.round_id WHERE r.season_id = ?",
+ "DELETE g FROM games g JOIN rounds r ON r.id = g.round_id WHERE r.season_id = ?",
+ "DELETE FROM rounds WHERE season_id = ?",
+ "DELETE FROM quotas WHERE season_id = ?",
+ "DELETE FROM payments WHERE season_id = ?",
+ "DELETE FROM manual_payouts WHERE season_id = ?",
+ "DELETE FROM seasons WHERE id = ?",
+ ];
+ foreach ($statements as $sql) {
+ $db->prepare($sql)->execute([$id]);
+ }
+ $db->commit();
+ } catch (\Exception $e) {
+ $db->rollBack();
+ throw $e;
+ }
+ }
+
/**
* Setzt die aktive Saison in der `settings`-Tabelle.
* Es wird (wie im Legacy-Code) immer die erste Zeile von settings verwendet.
diff --git a/src/Models/Setting.php b/src/Models/Setting.php
new file mode 100644
index 0000000..67ba090
--- /dev/null
+++ b/src/Models/Setting.php
@@ -0,0 +1,45 @@
+query("SELECT registration_open FROM settings ORDER BY id LIMIT 1")->fetchColumn();
+ return $value === false || (bool)$value;
+ }
+
+ /**
+ * Schaltet die Registrierung neuer Benutzer ein oder aus.
+ *
+ * @param bool $open
+ * @return bool
+ */
+ public static function setRegistrationOpen($open) {
+ $db = Database::getConnection();
+ $settingsId = $db->query("SELECT id FROM settings ORDER BY id LIMIT 1")->fetchColumn();
+
+ if ($settingsId === false) {
+ $current = Season::getCurrent();
+ $stmt = $db->prepare(
+ "INSERT INTO settings (current_season_id, registration_open, created_at, updated_at) VALUES (?, ?, NOW(), NOW())"
+ );
+ return $stmt->execute([$current ? (int)$current['id'] : 0, $open ? 1 : 0]);
+ }
+
+ $stmt = $db->prepare("UPDATE settings SET registration_open = ?, updated_at = NOW() WHERE id = ?");
+ return $stmt->execute([$open ? 1 : 0, $settingsId]);
+ }
+}
diff --git a/src/Models/Tipp.php b/src/Models/Tipp.php
index 10737ea..562682c 100644
--- a/src/Models/Tipp.php
+++ b/src/Models/Tipp.php
@@ -347,6 +347,88 @@ class Tipp {
return null;
}
+ /**
+ * Speichert einen einzelnen Tipp (Legacy TippsController::store).
+ *
+ * Regeln wie bei saveRound(): Runde nicht gesperrt, Joker-Limit pro Ergebnis und Saison.
+ * Wird der Joker gesetzt, wird er von den anderen Tipps der Runde entfernt.
+ *
+ * @param int $userId
+ * @param int $gameId
+ * @param mixed $score1
+ * @param mixed $score2
+ * @param bool $joker
+ * @return string|null Fehlermeldung oder null bei Erfolg
+ */
+ public static function saveSingle($userId, $gameId, $score1, $score2, $joker) {
+ $db = Database::getConnection();
+
+ $stmt = $db->prepare(
+ "SELECT g.round_id, r.season_id, s.max_identical_jokertipps
+ FROM games g
+ JOIN rounds r ON r.id = g.round_id
+ JOIN seasons s ON s.id = r.season_id
+ WHERE g.id = ?"
+ );
+ $stmt->execute([$gameId]);
+ $info = $stmt->fetch();
+ if (!$info) {
+ return "Spiel nicht gefunden.";
+ }
+ $roundId = (int)$info['round_id'];
+
+ if (Round::isLocked(Game::getGamesByRound($roundId))) {
+ return "Die Runde ist bereits gesperrt, Tipps können nicht mehr geändert werden.";
+ }
+
+ $options = ['options' => ['min_range' => 0, 'max_range' => self::MAX_GOALS]];
+ $s1 = filter_var($score1, FILTER_VALIDATE_INT, $options);
+ $s2 = filter_var($score2, FILTER_VALIDATE_INT, $options);
+ if ($s1 === false || $s2 === false) {
+ return "Bitte ein gültiges Ergebnis (0-" . self::MAX_GOALS . ") eintragen.";
+ }
+
+ if ($joker) {
+ $jokerResult = $s1 . ':' . $s2;
+ $usage = self::getJokerUsage($userId, $info['season_id'], $roundId);
+ $limit = (int)$info['max_identical_jokertipps'];
+ if (($usage[$jokerResult] ?? 0) >= $limit) {
+ return "Das Ergebnis $jokerResult wurde in dieser Saison bereits "
+ . $usage[$jokerResult] . "-mal mit Joker getippt (Maximum: $limit).";
+ }
+ }
+
+ $db->beginTransaction();
+ try {
+ $stmt = $db->prepare(
+ "INSERT INTO tipps (user_id, game_id, score1, score2, joker, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, NOW(), NOW())
+ ON DUPLICATE KEY UPDATE
+ score1 = VALUES(score1),
+ score2 = VALUES(score2),
+ joker = VALUES(joker),
+ updated_at = NOW()"
+ );
+ $stmt->execute([$userId, $gameId, $s1, $s2, $joker ? 1 : 0]);
+
+ if ($joker) {
+ $stmt = $db->prepare(
+ "UPDATE tipps t JOIN games g ON g.id = t.game_id
+ SET t.joker = 0, t.updated_at = NOW()
+ WHERE t.user_id = ? AND g.round_id = ? AND t.game_id <> ? AND t.joker = 1"
+ );
+ $stmt->execute([$userId, $roundId, $gameId]);
+ }
+ $db->commit();
+ } catch (\Exception $e) {
+ $db->rollBack();
+ error_log("Tipp::saveSingle fehlgeschlagen: " . $e->getMessage());
+ return "Der Tipp konnte nicht gespeichert werden.";
+ }
+
+ return null;
+ }
+
/**
* Ermittelt, welche Benutzer in einer Runde noch Tipps oder den Joker vergessen haben
* (für Admin-Benutzerliste, Startseiten-Hinweis, Rundmail-Empfänger und Erinnerungen).
diff --git a/src/Views/admin.php b/src/Views/admin.php
deleted file mode 100644
index 66b9d91..0000000
--- a/src/Views/admin.php
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-Administration
-
-
-
-
-
-
diff --git a/src/Views/admin/accounts.php b/src/Views/admin/accounts.php
new file mode 100644
index 0000000..38a7f14
--- /dev/null
+++ b/src/Views/admin/accounts.php
@@ -0,0 +1,66 @@
+ number_format($amount, 2, ',', '.') . ' €';
+?>
+
+Konto- & Ausschüttungsübersicht
+
+
+ Es gibt noch keine Saison.
+
+ Es gibt noch keine abgeschlossene Runde, daher noch keine Ausschüttungen.
+ Die Saison beginnt am format('d.m.Y H:i'); ?>.
+
+ , Stand:
+ (ohne Platzierungsgeld, das erst nach der letzten Runde feststeht)
+
+
+
+
+
+ | Name |
+ Ausschüttung |
+ Bankname |
+ IBAN |
+ BLZ |
+ Kontonummer |
+
+
+
+ 0 && empty($entry['iban']) && empty($entry['kontonr']);
+ ?>
+ >
+ |
+ |
+ |
+
+
+ |
+ |
+ |
+
+
+
+
+
+ | Summe |
+ |
+ |
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/admin/roundmails.php b/src/Views/admin/roundmails.php
new file mode 100644
index 0000000..d9b0949
--- /dev/null
+++ b/src/Views/admin/roundmails.php
@@ -0,0 +1,182 @@
+
+
+Runden-E-Mails
+
+
+
+
+
+
+
+
+
+
+ Neue Mail
+
+ Es ist kein Mailserver konfiguriert (Umgebungsvariable SMTP_HOST). Versand ist nicht möglich.
+
+
+
+
+
+
+
+
+
+
+ | Datum | |
+ | Versender | |
+ | Empfänger | |
+ | Nachricht | |
+
+
+ Zurück zur Übersicht
+
+
+
+ Neue Mail schreiben
+
+
+
+
+ | Datum |
+ Thema |
+ Versender |
+ Empfänger |
+
+
+
+
+
+ |
+ |
+ |
+ |
+
+
+
+ | Noch keine Mails versendet. |
+
+
+
+
+ 1):
+ $pageUrl = fn($n) => '/index.php?page=admin_roundmails' . ($n > 1 ? '&p=' . $n : '');
+ // Angezeigt werden erste und letzte Seite sowie zwei Seiten um die aktuelle herum
+ $shown = array_unique(array_filter(
+ [1, $currentPage - 2, $currentPage - 1, $currentPage, $currentPage + 1, $currentPage + 2, $totalPages],
+ fn($n) => $n >= 1 && $n <= $totalPages
+ ));
+ sort($shown);
+ ?>
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/admin/rounds.php b/src/Views/admin/rounds.php
new file mode 100644
index 0000000..d8396dd
--- /dev/null
+++ b/src/Views/admin/rounds.php
@@ -0,0 +1,136 @@
+
+
+Spiele & Ergebnisse eintragen
+
+
+
+
+
+
+
+
+
+
+
+ Keine Saison vorhanden. Bitte zuerst unter Saisons verwalten eine Saison anlegen.
+
+ Diese Saison hat keine Runden.
+
+
+
+
+
+
+
+
+
+ >
+
+
+
+
+
+
+ sperrt: format('d.m.Y H:i'); ?>
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/admin/seasons.php b/src/Views/admin/seasons.php
index cad4c98..ff3dc5c 100644
--- a/src/Views/admin/seasons.php
+++ b/src/Views/admin/seasons.php
@@ -24,43 +24,61 @@ require __DIR__ . '/../partials/header.php';
-
+
-
+
+
+ (Runden werden nur beim Anlegen erzeugt; eine Änderung legt keine Runden an oder löscht welche.)
+
-
-
+
+
-
- Quoten
-
- '1. Platz', 'prc' => '50'],
- ['name' => '2. Platz', 'prc' => '30'],
- ['name' => '3. Platz', 'prc' => '20'],
- ];
+ ';
+ echo '';
+ echo ' ' . $unit;
+ if ($amount !== null) {
+ echo ' = ' . number_format($amount, 2, ',', '.') . ' €';
}
+ echo '
';
+ };
+ ?>
+
+ Spiel-Einsatz
+
+
+ bezahlte Spieler, Runden.
+ Beträge berechnet aus den gespeicherten Quoten.
+
+
+ Spielquoten
+ je Runde
';
+ }
+ $quotaInput('platzierung', 'Platzierung', '%', $payouts !== null ? $placementSum : null);
+ ?>
+
+ Platzierungsquoten
+
- foreach ($quotas as $index => $quota): ?>
-
-
-
-
-
-
-
-
-
-
-
-
@@ -69,38 +87,6 @@ require __DIR__ . '/../partials/header.php';
-
-
@@ -116,18 +102,23 @@ document.addEventListener('DOMContentLoaded', function() {
- >
+
>
|
|
- |
+ |
Bearbeiten
-
+
+
|
@@ -146,6 +137,11 @@ document.addEventListener('DOMContentLoaded', function() {
text-align: right;
margin-right: 10px;
}
+.hint {
+ margin-left: calc(150px + 10px);
+ color: #666;
+ font-size: 0.9em;
+}
.form-group button, .form-group a {
margin-left: calc(150px + 10px);
}
diff --git a/src/Views/home.php b/src/Views/home.php
index 7652775..6cefc30 100644
--- a/src/Views/home.php
+++ b/src/Views/home.php
@@ -30,10 +30,10 @@ require __DIR__ . '/partials/header.php';
Debug-Informationen
Versuch, das Joker-Icon zu laden:
- - Pfad im
<img>-Tag: /image.php?file=icons/joker.png
- - Erwarteter physischer Speicherort:
public/icons/joker.png
- - Test-Link: Öffne Icon in neuem Tab
- - Test-Anzeige:

+ - Pfad im
<img>-Tag: /img/joker.png
+ - Erwarteter physischer Speicherort:
public/img/joker.png
+ - Test-Link: Öffne Icon in neuem Tab
+ - Test-Anzeige:

diff --git a/src/Views/info/money_ranking.php b/src/Views/info/money_ranking.php
new file mode 100644
index 0000000..9d25df9
--- /dev/null
+++ b/src/Views/info/money_ranking.php
@@ -0,0 +1,44 @@
+
+
+Geldrangliste
+
+
+
+
+ | Name |
+ Ausschüttung |
+
+
+
+
+ >
+ |
+ € |
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/info/money_ranking_detail.php b/src/Views/info/money_ranking_detail.php
new file mode 100644
index 0000000..759c035
--- /dev/null
+++ b/src/Views/info/money_ranking_detail.php
@@ -0,0 +1,41 @@
+
+
+Ausschüttungsübersicht
+
+
+
+
+ | Quoten-Titel |
+ Ausschüttung |
+
+
+
+
+
+ |
+ € |
+
+
+
+ | Bisher keine Ausschüttungen. |
+
+
+ | Summe |
+ € |
+
+
+
+
+
+Zurück
+
+
+
+
diff --git a/src/Views/info/no_ranking.php b/src/Views/info/no_ranking.php
new file mode 100644
index 0000000..a2c210b
--- /dev/null
+++ b/src/Views/info/no_ranking.php
@@ -0,0 +1,14 @@
+
+
+
+ Es gibt noch keine Tipprunde, die reif für die Anzeige ist.
+
+ Rangliste / Tippvergleich verfügbar ab format('d.m.Y H:i'); ?>.
+
+
+Ok
+
+
diff --git a/src/Views/info/quotas.php b/src/Views/info/quotas.php
new file mode 100644
index 0000000..1f42a0f
--- /dev/null
+++ b/src/Views/info/quotas.php
@@ -0,0 +1,41 @@
+ number_format($amount, 2, ',', '.') . ' €';
+?>
+
+
+ Es gibt noch keine Saison.
+
+
+ Ausschüttungs-Quoten
+
+ Spiel-Einsatz
+
+ | Aktive Spieler | |
+ | Einsatz pro Spieler | |
+
+
+ Spielquoten
+
+
+ Platzierungsquoten
+
+
+
+
+
+
diff --git a/src/Views/login.php b/src/Views/login.php
index 7dec593..ac66865 100644
--- a/src/Views/login.php
+++ b/src/Views/login.php
@@ -38,7 +38,9 @@ require __DIR__ . '/partials/header.php';
+
+
diff --git a/src/Views/partials/header.php b/src/Views/partials/header.php
index 60afdde..52ed3e3 100644
--- a/src/Views/partials/header.php
+++ b/src/Views/partials/header.php
@@ -15,18 +15,47 @@
diff --git a/src/Views/ranking.php b/src/Views/ranking.php
index 2f84c18..eccfd8b 100644
--- a/src/Views/ranking.php
+++ b/src/Views/ranking.php
@@ -66,7 +66,7 @@ if (!isset($currentSeason) || !isset($ranking) || !isset($games) || !isset($allR
🏆 Tagessieger
-

Joker gesetzt
+

Joker gesetzt
Richtiges Ergebnis mit Joker
@@ -96,12 +96,12 @@ if (!isset($currentSeason) || !isset($ranking) || !isset($games) || !isset($allR
| . |
|
- 🏆' : ''; ?> |
- |
- |
+ 🏆' : ''; ?> |
+ |
+ |
-
-
+
+
|
diff --git a/src/Views/register.php b/src/Views/register.php
index 3a8f529..6a26966 100644
--- a/src/Views/register.php
+++ b/src/Views/register.php
@@ -5,6 +5,12 @@ require __DIR__ . '/partials/header.php';
Registrieren
+
+ Die Registrierung neuer Spieler ist derzeit geschlossen. Bitte wende dich an einen Administrator.
+ Zum Login
+
+
+
diff --git a/src/Views/round.php b/src/Views/round.php
index 02dfcf8..dc86384 100644
--- a/src/Views/round.php
+++ b/src/Views/round.php
@@ -68,7 +68,7 @@ require __DIR__ . '/partials/header.php';
-
+
|
diff --git a/src/Views/settings.php b/src/Views/settings.php
new file mode 100644
index 0000000..526af82
--- /dev/null
+++ b/src/Views/settings.php
@@ -0,0 +1,75 @@
+
+
+Spielerdaten
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/tipps/game.php b/src/Views/tipps/game.php
new file mode 100644
index 0000000..d407e62
--- /dev/null
+++ b/src/Views/tipps/game.php
@@ -0,0 +1,40 @@
+
+
+Spieltipp:
+
+
+
+
+
+
+
+
+ Die Runde hat bereits begonnen, der Tipp kann nicht mehr verändert werden.
+ Zu den Tipps
+
+
+
+
+
+
+
diff --git a/src/Views/tipps/index.php b/src/Views/tipps/index.php
new file mode 100644
index 0000000..4f6161f
--- /dev/null
+++ b/src/Views/tipps/index.php
@@ -0,0 +1,82 @@
+
+
+Aktive Saison:
+Tipps
+
+
+
+
+
+ Runde sperrt sich: format('d.m.Y H:i'); ?>
+
+ Bereits verwendete Joker:
+ Maximale Anzahl gleicher Joker:
+
+
+
+
+ | Spiel |
+ Anstoss |
+ Ergebnis |
+ Tipp |
+ Joker |
+ Punkte |
+
+
+
+ -1 ? $tipp1 . ' : ' . $tipp2 : null;
+ ?>
+
+ |
+ |
+ -1 ? (int)$game['score1'] . ' : ' . (int)$game['score2'] : ''; ?> |
+
+
+
+
+
+
+ |
+
+
+
+
+ |
+ |
+
+
+
+
+
+
+ Runde Tippen
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Views/tipps/no_payment.php b/src/Views/tipps/no_payment.php
new file mode 100644
index 0000000..eb55898
--- /dev/null
+++ b/src/Views/tipps/no_payment.php
@@ -0,0 +1,9 @@
+
+
+Dein Zahlungseingang für die Saison wurde noch nicht registriert.
+Ok
+
+
diff --git a/src/Views/tipps/round.php b/src/Views/tipps/round.php
new file mode 100644
index 0000000..5f5a0ed
--- /dev/null
+++ b/src/Views/tipps/round.php
@@ -0,0 +1,75 @@
+
+
+
+
+
+
+
+
+
+ Die Runde ist bereits gesperrt, Tipps können nicht mehr geändert werden.
+ Zu den Tipps
+
+
+
+
+
+
+
+
+