Erster Durchstich mit updates
This commit is contained in:
parent
d3fd60b548
commit
3331f08091
60 changed files with 693 additions and 195 deletions
240
tippspiel/src/Models/Roundmail.php
Normal file
240
tippspiel/src/Models/Roundmail.php
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\Database;
|
||||
use App\Core\Mailer;
|
||||
|
||||
/**
|
||||
* Protokoll der versendeten Rundmails (Legacy Roundmail).
|
||||
* user_id = 0 steht für den Automailer.
|
||||
*/
|
||||
class Roundmail {
|
||||
|
||||
/** Erinnerungen werden erst verschickt, wenn die Runde in weniger als so vielen Stunden sperrt */
|
||||
const REMINDER_HOURS = 48;
|
||||
|
||||
/** Betreff der automatischen Erinnerungsmails */
|
||||
const REMINDER_TOPIC = 'Fehlende Tipps/Joker';
|
||||
|
||||
/** Automatische Erinnerungen werden nach so vielen Monaten aus dem Protokoll gelöscht */
|
||||
const REMINDER_RETENTION_MONTHS = 1;
|
||||
|
||||
/**
|
||||
* Anzahl aller protokollierten Mails.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public static function count() {
|
||||
$db = Database::getConnection();
|
||||
return (int)$db->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 <br/> 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 <br/>, 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<]+~', '<a href="$0">$0</a>', $html);
|
||||
return str_replace(["\r\n", "\r", "\n"], '<br/>', $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')
|
||||
. '<br/>Die Runde sperrt sich: ' . $lockTime->format('d.m.Y H:i')
|
||||
. '<br/><br/>Link zum Spiel: <a href="' . $link . '">( Hier klicken )</a>';
|
||||
|
||||
$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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue