Robo Admin

This commit is contained in:
torsten 2026-10-23 17:28:29 +02:00
parent a73358d2f1
commit 1c712d0781
20 changed files with 1194 additions and 55 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
.aider*
.DS_Store
tools/export_kontodaten_*.csv

View file

@ -207,6 +207,18 @@ a:hover { color: var(--pitch-dark); }
}
.nav-dropdown-form button:hover { background: var(--pitch-light); }
.nav-dropdown-form small { color: var(--muted); }
.nav-season-form { padding: 0.45em 1.1em; }
.nav-season-form label {
display: block;
margin-bottom: 0.25em;
font-family: var(--font-display);
font-weight: 700;
font-size: 0.72em;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--muted);
}
.nav-season-form select { width: 100%; }
.nav-dropdown:hover .nav-dropdown-content,
.nav-dropdown:focus-within .nav-dropdown-content { display: block; }

View file

@ -21,6 +21,7 @@ use App\Models\Roundmail;
use App\Models\Setting;
use App\Models\Team;
use App\Models\Question;
use App\Models\FetcherLog;
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$page = $_GET['page'] ?? null;
@ -57,6 +58,21 @@ if ($page === 'reminder') {
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()) {
@ -253,9 +269,9 @@ if ($page === 'reminder') {
$locked = Round::isLocked(Game::getGamesByRound($round['id']));
require __DIR__ . '/../src/Views/tipps/game.php';
} elseif ($page === 'guide') {
// Info -> Anleitung: Regeln mit den Werten der aktiven Saison
// Info -> Anleitung: Regeln mit den Werten der angezeigten Saison
Auth::requireLogin();
$currentSeason = Season::getCurrent();
$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;
@ -271,7 +287,7 @@ if ($page === 'reminder') {
} elseif ($page === 'info_quotas') {
// Info -> Quoten (Legacy UsersController::show_payouts)
Auth::requireLogin();
$currentSeason = Season::getCurrent();
$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;
@ -284,7 +300,7 @@ if ($page === 'reminder') {
// Info -> Geldrangliste (Legacy UsersController::money_ranking / money_ranking_detail)
Auth::requireLogin();
$user = Auth::user();
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
if (!$currentSeason) {
header('Location: /');
exit;
@ -317,7 +333,7 @@ if ($page === 'reminder') {
Auth::requireLogin();
Auth::requireAdmin();
$user = Auth::user();
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
$result = null;
$seasonStart = null;
if ($currentSeason) {
@ -343,6 +359,21 @@ if ($page === 'reminder') {
$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 ($page === 'settings') {
// Eigene Spielerdaten (Legacy UsersController::useredit / storeUserEdit)
Auth::requireLogin();
@ -389,11 +420,19 @@ if ($page === 'reminder') {
Auth::requireLogin();
Auth::requireAdmin();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_registration') {
Setting::setRegistrationOpen(($_POST['registration_open'] ?? '') === '1');
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;
}
@ -440,8 +479,10 @@ if ($page === 'reminder') {
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.";
// 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);
@ -450,7 +491,11 @@ if ($page === 'reminder') {
}
} elseif ($action === 'set_current' && $seasonId) {
Season::setCurrent($seasonId);
$_SESSION['admin_message'] = "Aktive Saison wurde geändert.";
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.";
@ -480,6 +525,7 @@ if ($page === 'reminder') {
$seasons = Season::getAll();
$currentSeason = Season::getCurrent();
$viewSeason = Season::getViewSeason();
$editSeason = isset($_GET['edit_id']) ? Season::findById((int)$_GET['edit_id']) : null;
$payouts = null;
@ -506,8 +552,9 @@ if ($page === 'reminder') {
Auth::requireLogin();
Auth::requireAdmin();
$currentSeason = Season::getCurrent();
$seasonId = (int)($_GET['season_id'] ?? ($currentSeason['id'] ?? 0));
$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);
@ -630,7 +677,7 @@ if ($page === 'reminder') {
}
$sender = Auth::user();
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
$html = Roundmail::textToHtml($text);
$failed = Mailer::send($recipients['valid'], $topic, $html, $sender['email'] ?? null);
$sent = array_values(array_diff($recipients['valid'], $failed));
@ -661,7 +708,7 @@ if ($page === 'reminder') {
$excludeReminders = ($_GET['hide_reminders'] ?? '') === '1';
if ($compose) {
$currentSeason = Season::getCurrent();
$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')), '/');
@ -680,7 +727,7 @@ if ($page === 'reminder') {
Auth::requireLogin();
Auth::requireAdmin();
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
$message = null;
$error = null;
@ -801,7 +848,7 @@ if ($page === 'reminder') {
} elseif ($page === 'ranking') {
Auth::requireLogin();
try {
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
if (!$currentSeason) {
throw new \Exception("Keine aktuelle Saison gefunden.");
}
@ -936,7 +983,7 @@ if ($page === 'reminder') {
} elseif ($page === 'home') {
Auth::requireLogin();
try {
$currentSeason = Season::getCurrent();
$currentSeason = Season::getViewSeason();
$message = Setting::getMessage();
if ($currentSeason) {

View file

@ -0,0 +1,535 @@
<?php
namespace App\Core;
use App\Models\FetcherLog;
use App\Models\Team;
/**
* Holt Spielergebnisse automatisch von externen Diensten und trägt sie in die
* `games`-Tabelle ein. Wird sowohl von den CLI-Skripten (tools/) als auch von
* der Web-Route (index.php?page=fetch_results, z. B. via cron-job.org) aufgerufen.
*
* Zwei Aufgaben:
* - Erkennung: Spiele im Fenster [heute .. heute+2] werden der externen Quelle
* zugeordnet und als `fetcher_matched = 1` markiert (Roboter-Icon in der
* Rundenverwaltung). Die Markierung bleibt dauerhaft bestehen.
* - Ergebnisse: Für bereits angepfiffene Spiele wird der (Live-/End-)Stand
* eingetragen, sobald die Quelle ihn liefert.
*
* Luxus-Feature: Fehlende oder nicht zugeordnete Ergebnisse pflegen die Admins
* manuell nach.
*/
class ResultFetcher {
const OPENLIGADB = 'https://api.openligadb.de';
const LEAGUES = ['bl1', 'bl2', 'bl3', 'dfb'];
const API_BASE = 'https://v3.football.api-sports.io';
/**
* Bundesliga (1./2./3. Liga + DFB-Pokal) über openligadb.
*
* @param bool $apply false = Dry-Run, true = eintragen
* @param bool $check true = Gegenkontrolle gegen vorhandene Endergebnisse
* @return string Zusammenfassung als Text
*/
public static function openligadb(bool $apply = false, bool $check = false): string {
// openligadb liefert naive Ortszeit (deutsch); damit strtotime()/date()
// korrekt rechnen, muss die Zeitzone Europa/Berlin aktiv sein.
date_default_timezone_set('Europe/Berlin');
$overrides = [
'1 fc heidenheim 1846' => 'fc-heidenheim',
'dsc arminia bielefeld' => 'arminia-bielefeld',
'sv 07 elversberg' => 'sv-elversberg',
'tsg 1899 hoffenheim ii' => 'tsg-hoffenheim-ii',
];
$out = [];
try {
$db = Database::getConnection();
$now = time();
$today = date('Y-m-d');
$from = $today . ' 00:00:00';
$to = date('Y-m-d 00:00:00', strtotime('+3 days'));
$stmt = $db->prepare(
"SELECT g.id, g.team1, g.team2, g.kickoff, g.score1, g.score2, g.fetcher_matched,
r.name AS round_name, s.name AS season_name,
t1.key AS k1, t2.key AS k2, t1.type AS t1t, t2.type AS t2t
FROM games g
JOIN rounds r ON r.id = g.round_id
JOIN seasons s ON s.id = r.season_id
LEFT JOIN teams t1 ON t1.id = g.team1_id
LEFT JOIN teams t2 ON t2.id = g.team2_id
WHERE g.kickoff >= ? AND g.kickoff < ?
ORDER BY g.kickoff"
);
$stmt->execute([$from, $to]);
$games = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$targets = [];
foreach ($games as $g) {
if (($g['t1t'] ?? '') !== 'club' || ($g['t2t'] ?? '') !== 'club') {
continue;
}
$targets[] = $g;
}
$seasonYears = [];
foreach ($targets as $g) {
$seasonYears[self::seasonYearFor($g['kickoff'])] = true;
}
if (empty($seasonYears)) {
return 'Keine Vereins-Spiele im Fenster (heute +2 Tage).';
}
$lookup = [];
$unresolvedTeams = [];
foreach (self::LEAGUES as $league) {
foreach (array_keys($seasonYears) as $season) {
$matches = self::openligaGet("/getmatchdata/$league/$season");
if ($matches === null) {
$out[] = "WARNUNG: Konnte $league/$season nicht laden.";
continue;
}
foreach ($matches as $m) {
$matchTs = strtotime((string)$m['matchDateTime']);
$finished = !empty($m['matchIsFinished']);
$score = null;
if ($finished) {
$end = null;
foreach ($m['matchResults'] ?? [] as $r) {
if ((int)$r['resultTypeID'] === 2) {
$end = $r;
}
}
if ($end !== null) {
$score = [(int)$end['pointsTeam1'], (int)$end['pointsTeam2']];
}
} elseif ($matchTs !== false && $matchTs <= $now) {
$goals = $m['goals'] ?? [];
$last = end($goals);
$score = [$last ? (int)$last['scoreTeam1'] : 0, $last ? (int)$last['scoreTeam2'] : 0];
}
// zukünftige Spiele: $score bleibt null, werden aber trotzdem
// in den Lookup aufgenommen (für die Erkennung/Roboter).
$k1 = self::openligaTeamKey($m['team1'], $overrides);
$k2 = self::openligaTeamKey($m['team2'], $overrides);
if ($k1 === null) {
$unresolvedTeams[$m['team1']['teamName']] = true;
}
if ($k2 === null) {
$unresolvedTeams[$m['team2']['teamName']] = true;
}
if ($k1 === null || $k2 === null) {
continue;
}
$date = substr((string)$m['matchDateTime'], 0, 10);
$lookup[$k1 . '|' . $k2 . '|' . $date] = [
'score' => $score, 'finished' => $finished,
];
}
}
}
$matched = 0;
$marked = 0;
$filled = 0;
$liveCount = 0;
$finalCount = 0;
$unmatched = [];
$mismatches = [];
$markStmt = $db->prepare(
"UPDATE games SET fetcher_matched = 1, updated_at = NOW() WHERE id = ? AND fetcher_matched <> 1"
);
$updStmt = $db->prepare("UPDATE games SET score1 = ?, score2 = ?, updated_at = NOW() WHERE id = ?");
foreach ($targets as $g) {
$k1 = $g['k1'];
$k2 = $g['k2'];
if ($k1 === null || $k2 === null) {
continue;
}
$date = substr((string)$g['kickoff'], 0, 10);
$key = $k1 . '|' . $k2 . '|' . $date;
if (!isset($lookup[$key])) {
$unmatched[] = sprintf('%s vs %s (%s)', $g['team1'], $g['team2'], $date);
continue;
}
$matched++;
$row = $lookup[$key];
$score = $row['score'];
$finished = $row['finished'];
if ($check) {
if (!$finished) {
continue;
}
if ((int)$g['score1'] !== $score[0] || (int)$g['score2'] !== $score[1]) {
$mismatches[] = sprintf(
'%s vs %s (%s): openligadb %d:%d, DB %d:%d',
$g['team1'], $g['team2'], $date, $score[0], $score[1],
(int)$g['score1'], (int)$g['score2']
);
}
continue;
}
// Erkennung (Roboter) dauerhaft merken.
if (!$g['fetcher_matched']) {
$marked++;
if ($apply) {
$markStmt->execute([$g['id']]);
FetcherLog::create(FetcherLog::ACTION_IDENTIFIED, sprintf('%s vs %s', $g['team1'], $g['team2']));
}
}
if ($score === null) {
continue; // noch kein Ergebnis (zukünftiges Spiel)
}
if ((int)$g['score1'] === $score[0] && (int)$g['score2'] === $score[1]) {
continue;
}
$kind = $finished ? 'Ende' : 'Live';
$out[] = sprintf(
'%s vs %s (%s): %d:%d [%s]%s',
$g['team1'], $g['team2'], $date, $score[0], $score[1], $kind,
$apply ? '' : ' [Dry-Run]'
);
if ($apply) {
$old = ((int)$g['score1'] >= 0 && (int)$g['score2'] >= 0)
? sprintf('%d:%d', $g['score1'], $g['score2'])
: '-:-';
$updStmt->execute([$score[0], $score[1], $g['id']]);
FetcherLog::create(FetcherLog::ACTION_RESULT, sprintf(
'%s vs %s: %s → %d:%d [%s]',
$g['team1'], $g['team2'], $old, $score[0], $score[1], $kind
));
$filled++;
if ($finished) {
$finalCount++;
} else {
$liveCount++;
}
}
}
$out[] = 'Zuordenbare Spiele: ' . $matched;
$out[] = 'Neu als erkannt markiert: ' . $marked . ($apply ? '' : ' [Dry-Run]');
if ($apply) {
$out[] = 'Geschrieben: ' . $filled . ' (Live: ' . $liveCount . ', Endergebnis: ' . $finalCount . ')';
}
if ($check) {
$out[] = 'Abweichungen zur DB: ' . count($mismatches);
foreach ($mismatches as $m) {
$out[] = ' - ' . $m;
}
}
if (!empty($unmatched)) {
$out[] = 'Nicht zugeordnet (' . count($unmatched) . '):';
foreach ($unmatched as $u) {
$out[] = ' - ' . $u;
}
}
if (!empty($unresolvedTeams)) {
$out[] = 'Nicht aufgelöste openligadb-Teams:';
foreach (array_keys($unresolvedTeams) as $name) {
$out[] = ' - ' . $name;
}
}
} catch (\Throwable $e) {
$out[] = 'Fehler: ' . $e->getMessage();
}
return implode("\n", $out);
}
/**
* Länderspiele + Europapokal über API-Football (api-sports.io).
*
* @param bool $apply false = Dry-Run, true = eintragen
* @param bool $check true = Gegenkontrolle gegen vorhandene Endergebnisse
* @return string Zusammenfassung als Text
*/
public static function apifootball(bool $apply = false, bool $check = false): string {
// "heute" muss der deutschen Ortszeit entsprechen (Kickoffs sind deutsch).
date_default_timezone_set('Europe/Berlin');
$nameMap = [
'germany' => 'de', 'netherlands' => 'nl', 'italy' => 'it', 'belgium' => 'be',
'england' => 'eng', 'spain' => 'es', 'czech republic' => 'cz', 'czechia' => 'cz',
'croatia' => 'hr', 'greece' => 'gr', 'norway' => 'no', 'portugal' => 'pt',
'france' => 'fr', 'turkey' => 'tr', 'turkiye' => 'tr', 'ireland' => 'ie',
'austria' => 'at', 'denmark' => 'dk', 'serbia' => 'rs', 'cyprus' => 'cy',
'latvia' => 'lv', 'andorra' => 'ad', 'argentina' => 'ar', 'armenia' => 'am',
'bolivia' => 'bo', 'bosnia and herzegovina' => 'ba', 'bosnia-herzegovina' => 'ba',
'brazil' => 'br', 'costa rica' => 'cr', 'ecuador' => 'ec', 'finland' => 'fi',
'ghana' => 'gh', 'iceland' => 'is', 'israel' => 'il', 'japan' => 'jp',
'cameroon' => 'cm', 'qatar' => 'qa', 'liechtenstein' => 'li', 'malta' => 'mt',
'mexico' => 'mx', 'northern ireland' => 'gb-nir', 'north macedonia' => 'mk',
'macedonia' => 'mk', 'poland' => 'pl', 'romania' => 'ro', 'russia' => 'ru',
'san marino' => 'sm', 'scotland' => 'gb-sct', 'sweden' => 'se',
'switzerland' => 'ch', 'senegal' => 'sn', 'slovakia' => 'sk', 'slovenia' => 'si',
'south korea' => 'kr', 'suriname' => 'sr', 'ukraine' => 'ua', 'hungary' => 'hu',
'uruguay' => 'uy', 'united states' => 'us', 'usa' => 'us', 'wales' => 'gb-wls',
'bayern munich' => 'fc-bayern-muenchen',
'paris saint germain' => 'paris-saint-germain',
];
$internationalClubs = array_flip([
'arsenal', 'as-roma', 'atletico-madrid', 'barcelona', 'villarreal', 'manchester-city',
'paris-saint-germain', 'psv', 'real-madrid', 'napoli', 'slovan-bratislava', 'fenerbahce',
'bodo-glimt', 'como', 'fiorentina', 'ac-milan', 'ajax', 'as-monaco', 'aston-villa',
'atalanta', 'athletic-bilbao', 'basaksehir', 'benfica', 'besiktas', 'real-betis',
'celtic', 'club-brugge', 'crystal-palace', 'dinamo-zagreb', 'dynamo-kyiv', 'espanyol',
'bologna', 'chelsea', 'getafe', 'copenhagen', 'liverpool', 'midtjylland', 'porto',
'sevilla', 'valencia', 'ferencvaros', 'feyenoord', 'krasnodar', 'galatasaray', 'rangers',
'inter-milan', 'juventus', 'gent', 'lazio', 'lokomotiv-moscow', 'maccabi-tel-aviv',
'manchester-united', 'molde', 'newcastle', 'nottingham-forest', 'nice', 'olympiacos',
'lyon', 'marseille', 'omonia', 'lille', 'paok', 'qarabag', 'rayo-vallecano',
'rb-salzburg', 'real-sociedad', 'red-star-belgrade', 'shakhtar-donetsk',
'sheriff-tiraspol', 'slavia-prague', 'sparta-prague', 'braga', 'sporting-cp',
'sturm-graz', 'tottenham', 'west-ham', 'wolves', 'young-boys', 'zenit',
]);
$out = [];
try {
$key = getenv('APIFOOTBALL_KEY');
if ($key === false || $key === '') {
return 'Fehler: APIFOOTBALL_KEY ist nicht gesetzt.';
}
$db = Database::getConnection();
$today = date('Y-m-d');
$from = $today . ' 00:00:00';
$to = date('Y-m-d 00:00:00', strtotime('+3 days'));
$stmt = $db->prepare(
"SELECT g.id, g.team1, g.team2, g.kickoff, g.score1, g.score2, g.fetcher_matched,
r.name AS round_name, s.name AS season_name,
t1.key AS k1, t2.key AS k2, t1.type AS t1t, t2.type AS t2t
FROM games g
JOIN rounds r ON r.id = g.round_id
JOIN seasons s ON s.id = r.season_id
LEFT JOIN teams t1 ON t1.id = g.team1_id
LEFT JOIN teams t2 ON t2.id = g.team2_id
WHERE g.kickoff >= ? AND g.kickoff < ?
ORDER BY g.kickoff"
);
$stmt->execute([$from, $to]);
$games = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$targets = [];
foreach ($games as $g) {
$t1t = $g['t1t'] ?? '';
$t2t = $g['t2t'] ?? '';
if ($t1t === 'national' && $t2t === 'national') {
$targets[] = $g;
} elseif ($t1t === 'club' && $t2t === 'club'
&& (isset($internationalClubs[$g['k1']]) || isset($internationalClubs[$g['k2']]))) {
$targets[] = $g;
}
}
if (empty($targets)) {
return 'Keine Länderspiele/European-Cup-Spiele im Fenster (heute +2 Tage).';
}
$lookup = [];
// Free-Tier erlaubt nur "gestern..morgen", daher Fehler pro Datum tolerieren.
foreach ([$today, date('Y-m-d', strtotime('+1 day')), date('Y-m-d', strtotime('+2 days'))] as $date) {
$data = self::apiGet('/fixtures?date=' . $date, $key);
if ($data === null || isset($data['errors']['plan'])) {
continue;
}
foreach ($data['response'] ?? [] as $fx) {
$status = (string)($fx['fixture']['status']['short'] ?? '');
$finished = in_array($status, ['FT', 'AET', 'PEN'], true);
$live = in_array($status, ['1H', 'HT', '2H', 'ET', 'BT', 'LIVE'], true);
$future = in_array($status, ['NS', 'TBD'], true);
if (!$finished && !$live && !$future) {
continue;
}
$score = null;
if ($finished || $live) {
$goals = $fx['goals'] ?? [];
if (!isset($goals['home']) || !isset($goals['away'])) {
continue;
}
$score = [(int)$goals['home'], (int)$goals['away']];
}
$k1 = self::apiTeamKey($fx['teams']['home'] ?? [], $nameMap);
$k2 = self::apiTeamKey($fx['teams']['away'] ?? [], $nameMap);
if ($k1 === null || $k2 === null) {
continue;
}
$dateKey = substr((string)$fx['fixture']['date'], 0, 10);
$lookup[$k1 . '|' . $k2 . '|' . $dateKey] = [
'score' => $score, 'finished' => $finished,
];
}
}
$matched = 0;
$marked = 0;
$filled = 0;
$liveCount = 0;
$finalCount = 0;
$unmatched = [];
$mismatches = [];
$markStmt = $db->prepare(
"UPDATE games SET fetcher_matched = 1, updated_at = NOW() WHERE id = ? AND fetcher_matched <> 1"
);
$updStmt = $db->prepare("UPDATE games SET score1 = ?, score2 = ?, updated_at = NOW() WHERE id = ?");
foreach ($targets as $g) {
$k1 = $g['k1'];
$k2 = $g['k2'];
if ($k1 === null || $k2 === null) {
continue;
}
$date = substr((string)$g['kickoff'], 0, 10);
$key = $k1 . '|' . $k2 . '|' . $date;
if (!isset($lookup[$key])) {
$unmatched[] = sprintf('%s vs %s (%s)', $g['team1'], $g['team2'], $date);
continue;
}
$matched++;
$row = $lookup[$key];
$score = $row['score'];
$finished = $row['finished'];
if ($check) {
if (!$finished) {
continue;
}
if ((int)$g['score1'] !== $score[0] || (int)$g['score2'] !== $score[1]) {
$mismatches[] = sprintf(
'%s vs %s (%s): API %d:%d, DB %d:%d',
$g['team1'], $g['team2'], $date, $score[0], $score[1],
(int)$g['score1'], (int)$g['score2']
);
}
continue;
}
if (!$g['fetcher_matched']) {
$marked++;
if ($apply) {
$markStmt->execute([$g['id']]);
FetcherLog::create(FetcherLog::ACTION_IDENTIFIED, sprintf('%s vs %s', $g['team1'], $g['team2']));
}
}
if ($score === null) {
continue;
}
if ((int)$g['score1'] === $score[0] && (int)$g['score2'] === $score[1]) {
continue;
}
$kind = $finished ? 'Ende' : 'Live';
$out[] = sprintf(
'%s vs %s (%s): %d:%d [%s]%s',
$g['team1'], $g['team2'], $date, $score[0], $score[1], $kind,
$apply ? '' : ' [Dry-Run]'
);
if ($apply) {
$old = ((int)$g['score1'] >= 0 && (int)$g['score2'] >= 0)
? sprintf('%d:%d', $g['score1'], $g['score2'])
: '-:-';
$updStmt->execute([$score[0], $score[1], $g['id']]);
FetcherLog::create(FetcherLog::ACTION_RESULT, sprintf(
'%s vs %s: %s → %d:%d [%s]',
$g['team1'], $g['team2'], $old, $score[0], $score[1], $kind
));
$filled++;
if ($finished) {
$finalCount++;
} else {
$liveCount++;
}
}
}
$out[] = 'Zuordenbare Spiele: ' . $matched;
$out[] = 'Neu als erkannt markiert: ' . $marked . ($apply ? '' : ' [Dry-Run]');
if ($apply) {
$out[] = 'Geschrieben: ' . $filled . ' (Live: ' . $liveCount . ', Endergebnis: ' . $finalCount . ')';
}
if ($check) {
$out[] = 'Abweichungen zur DB: ' . count($mismatches);
foreach ($mismatches as $m) {
$out[] = ' - ' . $m;
}
}
if (!empty($unmatched)) {
$out[] = 'Nicht zugeordnet (' . count($unmatched) . '):';
foreach ($unmatched as $u) {
$out[] = ' - ' . $u;
}
}
} catch (\Throwable $e) {
$out[] = 'Fehler: ' . $e->getMessage();
}
return implode("\n", $out);
}
private static function openligaGet(string $path): ?array {
$json = @file_get_contents(self::OPENLIGADB . $path);
if ($json === false) {
return null;
}
$data = json_decode($json, true);
return is_array($data) ? $data : null;
}
private static function openligaTeamKey(array $teamObj, array $overrides): ?string {
$team = Team::resolve((string)($teamObj['teamName'] ?? ''));
if (!$team) {
$team = Team::resolve((string)($teamObj['shortName'] ?? ''));
}
if ($team) {
return $team['key'];
}
$normalized = Team::normalize((string)($teamObj['teamName'] ?? ''));
if ($normalized !== '' && isset($overrides[$normalized])) {
return $overrides[$normalized];
}
return null;
}
private static function seasonYearFor(string $kickoff): int {
$ts = strtotime($kickoff);
$year = (int)date('Y', $ts);
$month = (int)date('n', $ts);
return $month < 7 ? $year - 1 : $year;
}
private static function apiGet(string $path, string $key): ?array {
$ctx = stream_context_create([
'http' => [
'header' => "x-apisports-key: $key\r\n",
'ignore_errors' => true,
'timeout' => 25,
],
]);
$json = @file_get_contents(self::API_BASE . $path, false, $ctx);
if ($json === false) {
return null;
}
$data = json_decode($json, true);
return is_array($data) ? $data : null;
}
private static function apiTeamKey(array $teamObj, array $nameMap): ?string {
$name = (string)($teamObj['name'] ?? '');
$team = Team::resolve($name);
if ($team) {
return $team['key'];
}
$normalized = Team::normalize($name);
if ($normalized !== '' && isset($nameMap[$normalized])) {
return $nameMap[$normalized];
}
return null;
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace App\Models;
use App\Core\Database;
/**
* Protokoll der Aktivitäten des Ergebnis-Fetchers (Robo-Admin):
* erste Identifikation eines Spiels sowie jede Ergebnisänderung.
*/
class FetcherLog {
const ACTION_IDENTIFIED = 'identified';
const ACTION_RESULT = 'result';
/** Einträge, die älter als so viele Tage sind, werden automatisch aufgeräumt. */
const RETENTION_DAYS = 30;
/**
* Schreibt einen Log-Eintrag.
*
* @param string $action self::ACTION_*
* @param string $message Beschreibung (z. B. "Team A vs Team B: 1:0 → 2:1 [Ende]")
* @return bool
*/
public static function create(string $action, string $message) {
$db = Database::getConnection();
$stmt = $db->prepare(
"INSERT INTO fetcher_log (created_at, action, message) VALUES (NOW(), ?, ?)"
);
return $stmt->execute([$action, $message]);
}
/**
* Alle Einträge im Zeitraum [fromDate, toDate] (jeweils ganze Tage), neueste zuerst.
*
* @param string $fromDate Y-m-d
* @param string $toDate Y-m-d
* @return array
*/
public static function getRange(string $fromDate, string $toDate) {
$db = Database::getConnection();
$from = $fromDate . ' 00:00:00';
$to = date('Y-m-d 00:00:00', strtotime($toDate . ' +1 day'));
$stmt = $db->prepare(
"SELECT * FROM fetcher_log WHERE created_at >= ? AND created_at < ? ORDER BY created_at DESC, id DESC"
);
$stmt->execute([$from, $to]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Löscht Einträge, die älter als RETENTION_DAYS Tage sind.
*
* @return int Anzahl gelöschter Einträge
*/
public static function deleteOld() {
$db = Database::getConnection();
$stmt = $db->prepare(
"DELETE FROM fetcher_log WHERE created_at < NOW() - INTERVAL " . (int)self::RETENTION_DAYS . " DAY"
);
$stmt->execute();
return $stmt->rowCount();
}
}

View file

@ -16,8 +16,10 @@ class Season {
const GAMES_PER_ROUND = 4;
/**
* Holt die aktuell selektierte Saison (settings.current_season_id).
* Fallback: Die Saison mit der höchsten ID.
* Holt die global aktive Saison (settings.current_season_id), die für
* alle Spieler gilt. Fallback: Die Saison mit der höchsten ID.
*
* @return array|false
*/
public static function getCurrent() {
$db = Database::getConnection();
@ -37,6 +39,52 @@ class Season {
return $stmt->fetch();
}
/**
* Holt die Saison, die der aktuelle Admin persönlich "ansehen" möchte.
* Diese Ansicht ist nur in der Session des Admins gespeichert und wirkt
* sich nicht auf andere Spieler aus. Fallback: die global aktive Saison.
*
* @return array|false
*/
public static function getViewSeason() {
$viewId = self::viewSeasonId();
if ($viewId !== null) {
$season = self::findById($viewId);
if ($season) {
return $season;
}
unset($_SESSION['admin_view_season_id']);
}
return self::getCurrent();
}
/**
* Liefert die ID der persönlich ausgewählten Saison oder null, wenn keine
* persönliche Auswahl getroffen wurde (dann gilt die global aktive Saison).
*
* @return int|null
*/
public static function viewSeasonId() {
return isset($_SESSION['admin_view_season_id']) ? (int)$_SESSION['admin_view_season_id'] : null;
}
/**
* Setzt die persönliche Saison-Ansicht des Admins (nur in dessen Session).
* $id = null/''/0 setzt die Ansicht zurück auf die global aktive Saison.
*
* @param int|string|null $id
* @return void
*/
public static function setViewSeason($id) {
if ($id === null || $id === '' || (int)$id <= 0) {
unset($_SESSION['admin_view_season_id']);
return;
}
if (self::findById((int)$id)) {
$_SESSION['admin_view_season_id'] = (int)$id;
}
}
/**
* Holt alle Saisons.
*
@ -197,6 +245,10 @@ class Season {
$db->prepare($sql)->execute([$id]);
}
$db->commit();
if (self::viewSeasonId() === $id) {
unset($_SESSION['admin_view_season_id']);
}
} catch (\Exception $e) {
$db->rollBack();
throw $e;

View file

@ -0,0 +1,64 @@
<?php
$pageTitle = 'Robo-Admin Aktivität';
require __DIR__ . '/../partials/header.php';
$actionLabels = [
'identified' => ['Identifiziert', 'badge-identified'],
'result' => ['Ergebnis geändert', 'badge-result'],
];
?>
<h1>Robo-Admin Aktivität</h1>
<form method="get" action="/index.php" class="activity-filter">
<input type="hidden" name="page" value="admin_fetcher_activity">
<label for="from">Von:</label>
<input type="date" id="from" name="from" value="<?php echo htmlspecialchars($from); ?>">
<label for="to">Bis:</label>
<input type="date" id="to" name="to" value="<?php echo htmlspecialchars($to); ?>">
<button type="submit">Zeigen</button>
</form>
<?php if (empty($entries)): ?>
<p class="activity-empty">Keine Aktivitäten im gewählten Zeitraum.</p>
<?php else: ?>
<table class="activity-table">
<thead>
<tr>
<th>Zeitpunkt</th>
<th>Handlung</th>
<th>Beschreibung</th>
</tr>
</thead>
<tbody>
<?php foreach ($entries as $entry): ?>
<?php [$label, $class] = $actionLabels[$entry['action']] ?? ['Aktivität', '']; ?>
<tr>
<td class="nowrap"><?php echo date('d.m.Y H:i', strtotime($entry['created_at'])); ?></td>
<td class="nowrap"><span class="badge <?php echo $class; ?>"><?php echo htmlspecialchars($label); ?></span></td>
<td><?php echo htmlspecialchars($entry['message']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<style>
.activity-filter { margin: 1em 0 1.5em; display: flex; align-items: center; gap: 0.5em; flex-wrap: wrap; }
.activity-filter label { font-weight: bold; }
.activity-filter input[type="date"] { padding: 0.3em 0.5em; }
.activity-table { max-width: 900px; }
.activity-table td.nowrap { white-space: nowrap; }
.activity-empty { color: var(--muted); }
.badge {
display: inline-block;
padding: 0.1em 0.6em;
border-radius: 999px;
font-size: 0.85em;
font-weight: bold;
}
.badge-identified { background: var(--pitch-light); color: var(--pitch-dark); }
.badge-result { background: #fff3cd; color: #856404; }
</style>
<?php require __DIR__ . '/../partials/footer.php'; ?>

View file

@ -33,7 +33,7 @@ $teamLogo = function ($name) {
<select id="season_id" name="season_id" onchange="this.form.submit()">
<?php foreach ($seasons as $s): ?>
<option value="<?php echo (int)$s['id']; ?>" <?php if ((int)$s['id'] === $seasonId) echo 'selected'; ?>>
<?php echo htmlspecialchars($s['name']); ?><?php if ($currentSeason && (int)$currentSeason['id'] === (int)$s['id']) echo ' (aktiv)'; ?>
<?php echo htmlspecialchars($s['name']); ?><?php if ($activeSeason && (int)$activeSeason['id'] === (int)$s['id']) echo ' (aktiv)'; ?>
</option>
<?php endforeach; ?>
</select>
@ -110,6 +110,11 @@ $teamLogo = function ($name) {
:
<input type="number" min="0" name="<?php echo $field; ?>[score2]"
value="<?php echo htmlspecialchars($in['score2'] ?? ((int)$game['score2'] < 0 ? '' : $game['score2'])); ?>">
<?php if (!empty($game['fetcher_matched'])): ?>
<i class="fa-solid fa-robot fetcher-badge" title="Vom Fetcher erkannt"></i>
<?php else: ?>
<i class="fa-solid fa-circle-question fetcher-badge fetcher-unknown" title="Nicht vom Fetcher erkannt"></i>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
@ -146,6 +151,9 @@ $teamLogo = function ($name) {
.round-admin textarea { width: 100%; max-width: 800px; }
.round-admin .form-group { margin: 0.8em 0; }
.round-admin .hint { color: #666; font-size: 0.8em; }
.fetcher-badge { margin-left: 0.5em; vertical-align: middle; cursor: help; }
.fa-robot.fetcher-badge { color: var(--pitch); }
.fetcher-unknown { color: var(--bronze); }
</style>
<script>
@ -159,7 +167,10 @@ $teamLogo = function ($name) {
}
document.querySelectorAll('input[type="datetime-local"]').forEach(function (input) {
input.dataset.iso = input.value;
// Fallback auf das value-Attribut: manche Browser liefern für
// datetime-local-Felder in eingeklappten <details> ein leeres
// `input.value`, obwohl das Attribut gesetzt ist.
input.dataset.iso = input.value || input.getAttribute('value') || '';
function showText() {
if (document.activeElement === input) return;

View file

@ -94,12 +94,20 @@ require __DIR__ . '/../partials/header.php';
<!-- Season List -->
<h2>Saison-Liste</h2>
<p class="season-hint">
<strong>Zwei getrennte Schalter:</strong> Mit <em>„Anzeigen"</em> (oder der Auswahl
„Saison ansehen" im Admin-Menü) wechselst du die Saison <strong>nur für dich</strong> –
alle anderen Spieler sehen weiterhin die aktive Saison. Mit <em>„Für alle aktivieren"</em>
stellst du die Saison <strong>für alle Spieler</strong> um. Beim Anlegen einer neuen Saison
wird nur deine eigene Ansicht umgestellt.
</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Runden</th>
<th>Aktiv</th>
<th>Ansicht</th>
<th>Aktionen</th>
</tr>
</thead>
@ -109,20 +117,32 @@ require __DIR__ . '/../partials/header.php';
<td><?php echo htmlspecialchars($season['name']); ?></td>
<td><?php echo htmlspecialchars($season['rounds']); ?></td>
<td><?php echo (int)$currentSeason['id'] === (int)$season['id'] ? 'Ja' : 'Nein'; ?></td>
<td><?php echo (int)$viewSeason['id'] === (int)$season['id'] ? 'Ja' : 'Nein'; ?></td>
<td>
<a href="/index.php?page=admin_seasons&edit_id=<?php echo $season['id']; ?>">Bearbeiten</a>
<?php if ((int)$currentSeason['id'] !== (int)$season['id']): ?>
<form action="/index.php?page=admin_seasons" method="post" style="display: inline;">
<input type="hidden" name="action" value="set_current">
<input type="hidden" name="id" value="<?php echo $season['id']; ?>">
<button type="submit" class="link-button">Als aktiv setzen</button>
</form>
<form action="/index.php?page=admin_seasons" method="post" style="display: inline;" onsubmit="return confirm(<?php echo htmlspecialchars(json_encode('Saison "' . $season['name'] . '" mit allen Runden, Spielen, Tipps, Zahlungen und Quoten endgültig löschen?'), ENT_QUOTES); ?>);">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?php echo $season['id']; ?>">
<button type="submit" class="link-button">Löschen</button>
</form>
<?php endif; ?>
<div class="season-actions">
<a href="/index.php?page=admin_seasons&edit_id=<?php echo $season['id']; ?>">Bearbeiten</a>
<?php if ((int)$viewSeason['id'] === (int)$season['id']): ?>
<span class="season-current">(Anzeige)</span>
<?php else: ?>
<form action="/index.php?page=admin_seasons" method="post">
<input type="hidden" name="action" value="view">
<input type="hidden" name="id" value="<?php echo $season['id']; ?>">
<button type="submit" class="link-button">Anzeigen</button>
</form>
<?php endif; ?>
<?php if ((int)$currentSeason['id'] !== (int)$season['id']): ?>
<form action="/index.php?page=admin_seasons" method="post" onsubmit="return confirm(<?php echo htmlspecialchars(json_encode('Saison "' . $season['name'] . '" für ALLE Spieler als aktive Saison setzen?'), ENT_QUOTES); ?>);">
<input type="hidden" name="action" value="set_current">
<input type="hidden" name="id" value="<?php echo $season['id']; ?>">
<button type="submit" class="link-button">Für alle aktivieren</button>
</form>
<form action="/index.php?page=admin_seasons" method="post" onsubmit="return confirm(<?php echo htmlspecialchars(json_encode('Saison "' . $season['name'] . '" mit allen Runden, Spielen, Tipps, Zahlungen und Quoten endgültig löschen?'), ENT_QUOTES); ?>);">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?php echo $season['id']; ?>">
<button type="submit" class="link-button">Löschen</button>
</form>
<?php endif; ?>
</div>
</td>
</tr>
<?php endforeach; ?>
@ -150,6 +170,35 @@ require __DIR__ . '/../partials/header.php';
color: #666;
font-size: 0.9em;
}
.season-hint {
max-width: 560px;
margin: 1em auto 0;
padding: 0.8em 1em;
background: #f7faf8;
border: 1px solid var(--line);
border-left: 5px solid var(--pitch);
border-radius: 8px;
text-align: left;
color: #333;
}
.season-actions {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.45em;
font-size: 0.85em;
white-space: nowrap;
}
.season-actions form {
display: block;
max-width: none;
margin: 0;
text-align: left;
}
.season-current {
color: var(--muted);
font-size: 0.9em;
}
.form-group button, .form-group a {
margin-left: calc(150px + 10px);
}

View file

@ -16,7 +16,7 @@ $euro = fn($amount) => number_format($amount, 2, ',', '.') . ' €';
<nav class="guide-toc">
<a href="#saison-anlegen">Saison anlegen</a>
<a href="#saison-umschalten">Saison umschalten</a>
<a href="#saison-ansicht">Saison ansehen &amp; umschalten</a>
<a href="#quoten">Quoten</a>
</nav>
@ -31,7 +31,9 @@ $euro = fn($amount) => number_format($amount, 2, ',', '.') . ' €';
</ul>
</li>
<li>Lege die Quoten fest (siehe <a href="#quoten">Abschnitt Quoten</a>). Es gelten die Standardwerte, du kannst sie aber anpassen.</li>
<li>Klicke <strong>„Anlegen"</strong>. Die Saison wird erstellt und automatisch als <strong>aktiv</strong> gesetzt.</li>
<li>Klicke <strong>„Anlegen"</strong>. Die Saison wird erstellt und <strong>nur für dich</strong> als Ansicht gesetzt.
Die für alle Spieler aktive Saison bleibt unverändert – so kannst du die neue Saison in Ruhe
vorbereiten, ohne dass andere sie schon sehen.</li>
</ol>
<div class="example">
<strong>Wichtig nach dem Anlegen:</strong> Die Saison enthält zunächst nur Platzhalter-Runden
@ -41,11 +43,38 @@ $euro = fn($amount) => number_format($amount, 2, ',', '.') . ' €';
Erst dadurch werden die Runden tippbar und später (nach dem Anpfiff) gesperrt.
</div>
<h2 id="saison-umschalten">2. Saison umschalten &amp; verwalten</h2>
<h2 id="saison-ansicht">2. Saison ansehen &amp; umschalten</h2>
<p>Es gibt zwei getrennte Schalter, damit du als Admin eine Saison vorbereiten oder ansehen kannst,
ohne alle Spieler umzuschalten:</p>
<h3>2.1 Saison nur für dich ansehen</h3>
<ul>
<li>Die <strong>Saison-Liste</strong> zeigt alle Saisons; die aktive ist fett markiert (Spalte „Aktiv").</li>
<li>Mit <strong>„Als aktiv setzen"</strong> wechselst du die aktive Saison. Alle Bereiche
(Startseite, Tipps, Rangliste, Quoten, Erinnerungen) beziehen sich danach auf die neue Saison.</li>
<li>Im Admin-Menü (<em>Administration</em>) wählst du unter <strong>„Saison ansehen"</strong> die Saison aus,
in der du arbeiten möchtest. Alternativ klickst du in der Saison-Liste auf <strong>„Anzeigen"</strong>.</li>
<li>Diese Auswahl ist <strong>nur in deiner Sitzung</strong> gespeichert und wirkt sich <strong>nicht</strong>
auf andere Spieler aus.</li>
<li>Die persönliche Ansicht wirkt auf die Verwaltungsseiten
(<em>Spiele &amp; Ergebnisse eintragen</em>, <em>Benutzer verwalten</em>, <em>Kontoliste</em>,
<em>Runden-E-Mails versenden</em>) sowie auf die reinen Ansichtsseiten
(<em>Startseite</em>, <em>Rangliste</em>, <em>Geldrangliste</em>, <em>Quoten</em>,
<em>Anleitung</em>). Nur die <em>Tippabgabe</em> bleibt immer bei der für alle aktiven
Saison – getippt wird nur in der laufenden Saison.</li>
<li>Mit „Aktive Saison (alle)" stellst du deine Ansicht wieder auf die für alle aktive Saison zurück.</li>
</ul>
<h3>2.2 Saison für alle aktivieren</h3>
<ul>
<li>In der Saison-Liste schaltest du mit <strong>„Für alle aktivieren"</strong> die aktive Saison um.
Nach einer Sicherheitsabfrage sehen <strong>alle Bereiche</strong>
(Startseite, Tipps, Rangliste, Quoten, Erinnerungen) die neue Saison.</li>
<li>Diesen Schritt machst du bewusst erst dann, wenn die Saison tatsächlich starten soll –
z.&nbsp;B. wenn die echten Paarungen eingetragen sind.</li>
</ul>
<h3>2.3 Saisons verwalten</h3>
<ul>
<li>Die <strong>Saison-Liste</strong> zeigt alle Saisons; die aktive ist fett markiert (Spalte „Aktiv"),
deine persönliche Ansicht in der Spalte „Ansicht".</li>
<li>Über <strong>„Bearbeiten"</strong> kannst du Name, Rundenanzahl, Joker-Limit und Quoten nachträglich anpassen.
Hinweis: Eine Änderung der Rundenanzahl legt keine neuen Runden an und löscht keine.</li>
<li><strong>„Löschen"</strong> entfernt eine Saison samt Runden, Spielen, Tipps, Zahlungen und Quoten.

View file

@ -7,6 +7,7 @@ $myId = (int)$user['id'];
<div class="money-centered">
<h1>Geldrangliste</h1>
<p class="money-season"><?php echo htmlspecialchars($currentSeason['name']); ?></p>
<table class="money-table">
<thead>
@ -38,6 +39,7 @@ if (!location.hash) {
<style>
.money-centered { text-align: center; }
.money-season { margin: 0 0 0.6em; color: var(--muted); }
.money-table { width: auto; min-width: 400px; margin: 1em auto 0; text-align: left; }
.money-table td.amount { text-align: right; }
.money-table tr.me td { background: #fff3cd; font-weight: bold; }

View file

@ -30,16 +30,35 @@ if (App\Core\Auth::check()) {
<nav class="site-nav">
<a href="/" class="brand"><span class="brand-ball">⚽</span> Tippspiel <span class="brand-year">2027</span></a>
<a href="/index.php?page=questions"<?php if ($questionsGlow): ?> class="is-glowing"<?php endif; ?>>Fragen</a>
<?php if (App\Core\Auth::isAdmin()): $registrationOpen = App\Models\Setting::isRegistrationOpen(); ?>
<?php if (App\Core\Auth::isAdmin()):
$registrationOpen = App\Models\Setting::isRegistrationOpen();
$navSeasons = App\Models\Season::getAll();
$navActiveSeason = App\Models\Season::getCurrent();
$navViewSeasonId = App\Models\Season::viewSeasonId();
?>
<span class="nav-dropdown">
<a href="#" onclick="return false;">Administration</a>
<span class="nav-dropdown-content">
<form method="post" action="/index.php?page=admin" class="nav-dropdown-form nav-season-form">
<input type="hidden" name="action" value="set_view_season">
<input type="hidden" name="return" value="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/'); ?>">
<label for="nav-season-select">Saison ansehen:</label>
<select id="nav-season-select" name="season_id" onchange="this.form.submit()">
<option value="" <?php if ($navViewSeasonId === null) echo 'selected'; ?>>Aktive Saison (alle)</option>
<?php foreach ($navSeasons as $s): ?>
<option value="<?php echo (int)$s['id']; ?>" <?php if ($navViewSeasonId !== null && (int)$s['id'] === $navViewSeasonId) echo 'selected'; ?>>
<?php echo htmlspecialchars($s['name']); ?><?php if ($navActiveSeason && (int)$navActiveSeason['id'] === (int)$s['id']) echo ' (aktiv)'; ?>
</option>
<?php endforeach; ?>
</select>
</form>
<a href="/index.php?page=admin_users">Benutzer verwalten</a>
<a href="/index.php?page=admin_seasons">Saisons verwalten</a>
<a href="/index.php?page=admin_rounds">Spiele &amp; Ergebnisse eintragen</a>
<a href="/index.php?page=admin_roundmails">Runden-E-Mails versenden</a>
<a href="/index.php?page=admin_accounts">Kontoliste</a>
<a href="/index.php?page=admin_message">Aktuelle Mitteilung</a>
<a href="/index.php?page=admin_fetcher_activity">Robo-Admin Aktivität</a>
<form method="post" action="/index.php?page=admin" class="nav-dropdown-form">
<input type="hidden" name="action" value="set_registration">
<input type="hidden" name="registration_open" value="<?php echo $registrationOpen ? '0' : '1'; ?>">

View file

@ -0,0 +1,48 @@
<?php
// Leert die Kontofelder (iban, bankname, blz, kontonr) aller Benutzer.
// Vorher sollte export_accounts.php gelaufen sein, um die Daten zu sichern.
//
// Aufruf (im App-Container):
// docker compose exec app php clear_account_fields.php [datenbank]
//
// Standard-Ziel: die Quell-DB (DB_OLD_NAME, Standard "tippspiel_legacy").
// Das optionale Argument überschreibt den Datenbanknamen (z.B. tippspiel2027
// oder die Live-DB), damit derselbe Schritt später auch dort ausgeführt werden kann.
$host = getenv('DB_HOST') ?: '127.0.0.1';
$user = getenv('DB_USER') ?: 'root';
$pass = getenv('DB_PASS') ?: '';
$targetDb = $argv[1] ?? (getenv('DB_OLD_NAME') ?: 'tippspiel_legacy');
if (!preg_match('/^[A-Za-z0-9_]+$/', $targetDb)) {
die("Fehler: Ungültiger Datenbankname '$targetDb'.\n");
}
try {
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$existsStmt = $pdo->prepare(
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?"
);
$existsStmt->execute([$targetDb]);
if (!$existsStmt->fetchColumn()) {
die("Fehler: Datenbank '$targetDb' nicht gefunden.\n");
}
$stmt = $pdo->prepare(
"UPDATE `$targetDb`.`users`
SET iban = NULL, bankname = NULL, blz = NULL, kontonr = NULL"
);
$stmt->execute();
echo "Kontofelder (iban, bankname, blz, kontonr) in '$targetDb' geleert.\n";
echo "Betroffene Zeilen: " . $stmt->rowCount() . "\n";
} catch (PDOException $e) {
die("Datenbankfehler: " . $e->getMessage() . "\n");
} catch (\Throwable $e) {
die("Fehler: " . $e->getMessage() . "\n");
}

View file

@ -72,6 +72,7 @@ def build_htaccess(creds):
"SetEnv APP_URL " + APP_URL,
"SetEnv IBAN_KEY " + creds.get("iban_key", ""),
"SetEnv REMINDER_TOKEN " + creds.get("reminder_token", ""),
"SetEnv APIFOOTBALL_KEY " + creds.get("apifootball_key", ""),
"",
]
)

View file

@ -25,6 +25,8 @@ services:
# MUSS mit "iban_key" in docs/testsystem_credentials.txt übereinstimmen:
# die lokale DB wird verschlüsselt und per deploy_test.py zur Remote synct.
- IBAN_KEY=/eG0tnvUGe02AR3ABgIJyMQdujnilxK7NkXhQubd3Rw=
# API Key für api-sports.io
- APIFOOTBALL_KEY=269586edd11d7fde903f692810326004
depends_on:
- db
- mailpit
@ -44,4 +46,4 @@ services:
- db_data:/var/lib/mysql
volumes:
db_data:
db_data:

114
tools/export_accounts.php Normal file
View file

@ -0,0 +1,114 @@
<?php
// Exportiert die Kontodaten (user_id, iban, blz, bankname, kontonr) sowie die
// Mobilnummer (mobile) aller Spieler, die in der aktuellen oder der letzten
// Saison aktiv waren (Zahlung geleistet), aus der Quell-Datenbank (Legacy) in
// eine lokale CSV-Datei.
//
// Hintergrund: Diese Daten sollen lokal gesichert werden, bevor für einen
// Übergangszeitraum die Kontoinformationen (iban, blz, bankname) der User
// entfernt werden. Die Quell-DB enthält die Werte noch im Klartext.
//
// Aufruf (im App-Container):
// docker compose exec app php export_accounts.php [ausgabepfad.csv]
//
// Standard-Ausgabepfad: tools/export_kontodaten_<zeitstempel>.csv
$host = getenv('DB_HOST') ?: '127.0.0.1';
$user = getenv('DB_USER') ?: 'root';
$pass = getenv('DB_PASS') ?: '';
$srcDbName = getenv('DB_OLD_NAME') ?: 'tippspiel_legacy';
$out = $argv[1] ?? (__DIR__ . '/export_kontodaten_' . date('Ymd_His') . '.csv');
try {
$pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Aktuelle Saison ermitteln
$currentId = (int)$pdo->query(
"SELECT current_season_id FROM `$srcDbName`.`settings` ORDER BY id LIMIT 1"
)->fetchColumn();
if ($currentId <= 0) {
die("Fehler: Keine aktive Saison in der Quell-DB '$srcDbName' gefunden.\n");
}
// Letzte Saison = höchste ID unterhalb der aktuellen
$stmt = $pdo->prepare("SELECT MAX(id) FROM `$srcDbName`.`seasons` WHERE id < ?");
$stmt->execute([$currentId]);
$lastId = (int)$stmt->fetchColumn();
$seasonIds = array_values(array_unique(array_filter([$currentId, $lastId])));
$placeholders = implode(',', array_fill(0, count($seasonIds), '?'));
// Alle User, die in einer der beiden Saisons bezahlt haben (paid_date gesetzt)
$sql = "SELECT u.id AS user_id, u.name, u.email, u.iban, u.bankname, u.blz, u.kontonr, u.mobile,
p.season_id
FROM `$srcDbName`.`users` u
JOIN `$srcDbName`.`payments` p ON p.user_id = u.id AND p.paid_date IS NOT NULL
WHERE p.season_id IN ($placeholders)
ORDER BY u.id, p.season_id";
$stmt = $pdo->prepare($sql);
$stmt->execute($seasonIds);
$users = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = (int)$row['user_id'];
if (!isset($users[$id])) {
$users[$id] = [
'user_id' => $id,
'name' => (string)$row['name'],
'email' => (string)$row['email'],
'iban' => (string)$row['iban'],
'bankname' => $row['bankname'] !== null ? (string)$row['bankname'] : '',
'blz' => $row['blz'] !== null ? (string)$row['blz'] : '',
'kontonr' => $row['kontonr'] !== null ? (string)$row['kontonr'] : '',
'mobile' => $row['mobile'] !== null ? (string)$row['mobile'] : '',
'seasons' => [],
];
}
$users[$id]['seasons'][] = (int)$row['season_id'];
}
$fh = fopen($out, 'w');
if ($fh === false) {
die("Fehler: Ausgabedatei '$out' kann nicht geöffnet werden.\n");
}
// UTF-8 BOM, damit Umlaute in Excel korrekt angezeigt werden
fwrite($fh, "\xEF\xBB\xBF");
$header = ['user_id', 'name', 'email', 'iban', 'bankname', 'blz', 'kontonr', 'mobile', 'aktiv_aktuell', 'aktiv_letzte'];
fputcsv($fh, $header, ';', '"', '\\');
$count = 0;
foreach ($users as $u) {
$seasons = array_unique($u['seasons']);
fputcsv($fh, [
$u['user_id'],
$u['name'],
$u['email'],
$u['iban'],
$u['bankname'],
$u['blz'],
$u['kontonr'],
$u['mobile'],
in_array($currentId, $seasons) ? 1 : 0,
in_array($lastId, $seasons) ? 1 : 0,
], ';', '"', '\\');
$count++;
}
fclose($fh);
echo "Export abgeschlossen.\n";
echo "Quell-DB: $srcDbName\n";
echo "Aktuelle Saison: $currentId, letzte Saison: " . ($lastId > 0 ? (string)$lastId : '-') . "\n";
echo "$count Spieler exportiert.\n";
echo "Ausgabedatei: $out\n";
} catch (PDOException $e) {
die("Datenbankfehler: " . $e->getMessage() . "\n");
} catch (\Throwable $e) {
die("Fehler: " . $e->getMessage() . "\n");
}

View file

@ -0,0 +1,19 @@
<?php
// CLI-Wrapper für den Ergebnis-Fetcher (Länderspiele/Europapokal via API-Football).
// Die eigentliche Logik liegt in App\Core\ResultFetcher und wird auch von der
// Web-Route index.php?page=fetch_results aufgerufen (für cron-job.org).
//
// Aufruf (im App-Container):
// docker compose exec app php fetch_results_apifootball.php # Dry-Run
// docker compose exec app php fetch_results_apifootball.php --apply # eintragen
// docker compose exec app php fetch_results_apifootball.php --check # Gegenkontrolle
require __DIR__ . '/src/autoload.php';
use App\Core\ResultFetcher;
$apply = in_array('--apply', $argv, true);
$check = in_array('--check', $argv, true);
echo ResultFetcher::apifootball($apply, $check) . "\n";

View file

@ -0,0 +1,19 @@
<?php
// CLI-Wrapper für den Ergebnis-Fetcher (Bundesliga/DFB-Pokal via openligadb).
// Die eigentliche Logik liegt in App\Core\ResultFetcher und wird auch von der
// Web-Route index.php?page=fetch_results aufgerufen (für cron-job.org).
//
// Aufruf (im App-Container):
// docker compose exec app php fetch_results_openligadb.php # Dry-Run
// docker compose exec app php fetch_results_openligadb.php --apply # eintragen
// docker compose exec app php fetch_results_openligadb.php --check # Gegenkontrolle
require __DIR__ . '/src/autoload.php';
use App\Core\ResultFetcher;
$apply = in_array('--apply', $argv, true);
$check = in_array('--check', $argv, true);
echo ResultFetcher::openligadb($apply, $check) . "\n";

View file

@ -45,6 +45,7 @@ CREATE TABLE `games` (
`score1` int(11) NOT NULL DEFAULT '-1',
`score2` int(11) NOT NULL DEFAULT '-1',
`kickoff` datetime NOT NULL,
`fetcher_matched` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
@ -171,6 +172,15 @@ CREATE TABLE `manual_payouts` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `fetcher_log`;
CREATE TABLE `fetcher_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`action` varchar(20) NOT NULL,
`message` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `password_resets`;
CREATE TABLE `password_resets` (
`email` varchar(150) NOT NULL,

View file

@ -1,12 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
# Synchronisiert alle 5 Minuten die Legacy-Live-DB in das Testsystem.
# Synchronisiert alle 5 Minuten nur die Tipps der Legacy-Live-DB in das Testsystem.
#
# Ablauf pro Zyklus:
# 1. Dump der Legacy-Live-DB erzeugen (dump_pfosten.py)
# 2. Dump lokal importieren und nach tippspiel2027 migrieren (import_from_dump.sh)
# 3. Nur den DB-Teil von deploy_test.py ausführen (--db-only, kein FTP-Upload)
# 1. Dump der Tabelle `tipps` aus der Legacy-Live-DB (nur Daten, kein Schema)
# 2. Remote-Test-DB-Tabelle `tipps` leeren
# 3. Dump in die Remote-Test-DB einspielen (Schema bleibt unverändert)
#
# Aufruf:
# ./sync_live_to_test.sh Endlosschleife (alle 5 Minuten)
@ -16,20 +16,60 @@ set -euo pipefail
# SYNC_INTERVAL=60 ./sync_live_to_test.sh
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DUMP_SCRIPT="/home/torsten/repos/tippspiel/tools/dump_pfosten.py"
IMPORT_SCRIPT="$TOOLS_DIR/import_from_dump.sh"
DEPLOY_SCRIPT="$TOOLS_DIR/deploy_test.py"
REPO_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
CRED_FILE="$REPO_ROOT/docs/testsystem_credentials.txt"
# Legacy-Live-DB (Quelle)
LEGACY_HOST="${LEGACY_HOST:-hoschis-tippspiel.de}"
LEGACY_USER="${LEGACY_USER:-d0274241}"
LEGACY_PASS="${LEGACY_PASS:-superpfosten!}"
LEGACY_DB="${LEGACY_DB:-d0274241}"
# Remote-Test-DB (Ziel) - DB-Name und Passwort kommen aus den Credentials
REMOTE_HOST="${REMOTE_HOST:-programmschmiede.de}"
REMOTE_PORT="${REMOTE_PORT:-3306}"
REMOTE_USER="${REMOTE_USER:-d0489c69}"
INTERVAL="${SYNC_INTERVAL:-300}"
read_cred() {
local key="$1"
local val
val="$(grep -E "^[[:space:]]*${key}[[:space:]]*=" "$CRED_FILE" | tail -1 | sed -E 's/^[^=]*=[[:space:]]*//' | tr -d '\r')"
if [[ -z "$val" ]]; then
echo "Fehler: Eintrag '$key' fehlt in $CRED_FILE" >&2
exit 1
fi
printf '%s' "$val"
}
run_once() {
echo "[$(date '+%F %T')] Dump der Legacy-Live-DB..."
python3 "$DUMP_SCRIPT"
local remote_db remote_pw dump_file
remote_db="$(read_cred mysql_db)"
remote_pw="$(read_cred mysql_pw)"
dump_file="$(mktemp /tmp/tipps_sync_XXXXXX.sql)"
trap 'rm -f "$dump_file"' RETURN
echo "[$(date '+%F %T')] Import + Migration..."
"$IMPORT_SCRIPT"
echo "[$(date '+%F %T')] Dump der Tabelle 'tipps' aus der Legacy-Live-DB..."
MYSQL_PWD="$LEGACY_PASS" mysqldump \
--no-tablespaces --column-statistics=0 \
--no-create-info --complete-insert \
--skip-add-locks --skip-comments --skip-triggers \
-h "$LEGACY_HOST" -u "$LEGACY_USER" "$LEGACY_DB" tipps > "$dump_file"
echo "[$(date '+%F %T')] DB-Sync zum Testsystem..."
python3 "$DEPLOY_SCRIPT" --db-only
if ! grep -q "INSERT INTO" "$dump_file"; then
echo "Fehler: Dump enthält keine Tipps (kein INSERT INTO)." >&2
exit 1
fi
echo "[$(date '+%F %T')] Leere 'tipps' in der Remote-Test-DB..."
MYSQL_PWD="$remote_pw" mysql \
-h "$REMOTE_HOST" -P "$REMOTE_PORT" -u "$REMOTE_USER" "$remote_db" \
-e "TRUNCATE TABLE \`tipps\`;"
echo "[$(date '+%F %T')] Spiele Tipps in die Remote-Test-DB ein..."
MYSQL_PWD="$remote_pw" mysql \
-h "$REMOTE_HOST" -P "$REMOTE_PORT" -u "$REMOTE_USER" "$remote_db" < "$dump_file"
echo "[$(date '+%F %T')] Zyklus abgeschlossen."
}