App-Erinnerungen per Web-Push (VAPID) ergaenzen
This commit is contained in:
parent
af9bb67331
commit
6e30fea4e6
12 changed files with 1160 additions and 19 deletions
437
tippspiel/src/Core/WebPush.php
Normal file
437
tippspiel/src/Core/WebPush.php
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
<?php
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* Web-Push ohne externe Abhängigkeiten.
|
||||
*
|
||||
* Verschlüsselung nach RFC 8291 (Content-Encoding `aes128gcm`) und
|
||||
* Authentifizierung nach RFC 8292 (VAPID, JWT mit ES256). Beides baut nur auf
|
||||
* Erweiterungen auf, die auf dem Shared Host vorhanden sind (openssl, curl).
|
||||
*
|
||||
* Konfiguration über Umgebungsvariablen (SetEnv in public/.htaccess):
|
||||
* VAPID_PUBLIC_KEY base64url des unkomprimierten P-256-Punkts (65 Byte)
|
||||
* VAPID_PRIVATE_KEY base64url des privaten Schlüssels (32 Byte)
|
||||
* VAPID_SUBJECT Kontakt-URI, z. B. mailto:admin@example.org
|
||||
*
|
||||
* Erzeugt werden die Schlüssel mit tools/generate_vapid_keys.py.
|
||||
*/
|
||||
class WebPush {
|
||||
|
||||
/** Wie lange der Push-Dienst eine Nachricht aufbewahren darf, wenn das Gerät offline ist. */
|
||||
const TTL = 86400;
|
||||
|
||||
/** Maximale Größe eines verschlüsselten Datensatzes (RFC 8188). */
|
||||
const RECORD_SIZE = 4096;
|
||||
|
||||
/** Timeout für den Versand (einzelnes Abo, nicht der ganze Lauf) */
|
||||
const TIMEOUT = 10;
|
||||
|
||||
/**
|
||||
* Sind alle für den Versand nötigen Werte konfiguriert?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isConfigured() {
|
||||
$public = self::publicKey();
|
||||
if ($public === null) {
|
||||
return false;
|
||||
}
|
||||
$point = self::base64UrlDecode($public);
|
||||
return $point !== false && strlen($point) === 65 && self::privateKey() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentlicher VAPID-Schlüssel als base64url (für `applicationServerKey` im Browser).
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function publicKey() {
|
||||
$key = getenv('VAPID_PUBLIC_KEY');
|
||||
if ($key === false || trim($key) === '') {
|
||||
return null;
|
||||
}
|
||||
return trim($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kontakt-URI für den VAPID-Claim `sub`. Fällt auf APP_URL zurück.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function subject() {
|
||||
$subject = getenv('VAPID_SUBJECT');
|
||||
if ($subject !== false && trim($subject) !== '') {
|
||||
return trim($subject);
|
||||
}
|
||||
$appUrl = getenv('APP_URL');
|
||||
if ($appUrl !== false && trim($appUrl) !== '') {
|
||||
return trim($appUrl);
|
||||
}
|
||||
return 'https://hoschis-tippspiel.de';
|
||||
}
|
||||
|
||||
/**
|
||||
* Privaten Schlüssel laden. Unterstützt das gespeicherte Format
|
||||
* (base64url des 32-Byte-Skalars) und direkt hinterlegtes PEM.
|
||||
*
|
||||
* @return \OpenSSLAsymmetricKey|resource|null
|
||||
*/
|
||||
private static function privateKey() {
|
||||
$raw = getenv('VAPID_PRIVATE_KEY');
|
||||
if ($raw === false || trim($raw) === '') {
|
||||
return null;
|
||||
}
|
||||
$raw = trim($raw);
|
||||
|
||||
if (strpos($raw, 'BEGIN') !== false) {
|
||||
$key = openssl_pkey_get_private(str_replace('\n', "\n", $raw));
|
||||
return $key === false ? null : $key;
|
||||
}
|
||||
|
||||
$scalar = self::base64UrlDecode($raw);
|
||||
$public = self::publicKey();
|
||||
if ($scalar === false || strlen($scalar) !== 32 || $public === null) {
|
||||
return null;
|
||||
}
|
||||
$point = self::base64UrlDecode($public);
|
||||
if ($point === false || strlen($point) !== 65) {
|
||||
return null;
|
||||
}
|
||||
$key = openssl_pkey_get_private(self::privateKeyPem($scalar, $point));
|
||||
return $key === false ? null : $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft einen Push-Endpunkt: HTTPS, plausibler Host, kein internes Ziel.
|
||||
*
|
||||
* @param string $endpoint
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidEndpoint($endpoint) {
|
||||
if (!is_string($endpoint) || strlen($endpoint) > 1000 || strlen($endpoint) < 10) {
|
||||
return false;
|
||||
}
|
||||
$parts = parse_url($endpoint);
|
||||
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||||
return false;
|
||||
}
|
||||
if (strtolower($parts['scheme']) !== 'https') {
|
||||
return false;
|
||||
}
|
||||
$host = strtolower($parts['host']);
|
||||
if ($host === 'localhost' || substr($host, -6) === '.local') {
|
||||
return false;
|
||||
}
|
||||
if (filter_var($host, FILTER_VALIDATE_IP)) {
|
||||
// Keine privaten/reservierten Adressen (SSRF-Schutz).
|
||||
if (!filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Schlüssel eines Abos, bevor es gespeichert wird.
|
||||
*
|
||||
* @param string $p256dh base64url des Geräteschlüssels (65 Byte, unkomprimierter Punkt)
|
||||
* @param string $auth base64url des Auth-Geheimnisses (16 Byte)
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidKeyMaterial($p256dh, $auth) {
|
||||
$point = self::base64UrlDecode($p256dh);
|
||||
$secret = self::base64UrlDecode($auth);
|
||||
return $point !== false && strlen($point) === 65 && $point[0] === "\x04"
|
||||
&& $secret !== false && strlen($secret) === 16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Versendet eine Nachricht an ein Abo.
|
||||
*
|
||||
* @param array $subscription ['endpoint' => string, 'p256dh' => string, 'auth' => string]
|
||||
* @param array $payload Beliebige JSON-Struktur (Titel, Text, URL)
|
||||
* @return array ['ok' => bool, 'status' => int, 'gone' => bool, 'error' => string]
|
||||
*/
|
||||
public static function send(array $subscription, array $payload) {
|
||||
$result = ['ok' => false, 'status' => 0, 'gone' => false, 'error' => ''];
|
||||
|
||||
if (!self::isConfigured()) {
|
||||
$result['error'] = 'VAPID ist nicht konfiguriert.';
|
||||
return $result;
|
||||
}
|
||||
if (!function_exists('curl_init')) {
|
||||
$result['error'] = 'curl ist nicht verfügbar.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach (['endpoint', 'p256dh', 'auth'] as $field) {
|
||||
if (empty($subscription[$field])) {
|
||||
$result['error'] = 'Abo unvollständig (' . $field . ').';
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
if (!self::isValidEndpoint($subscription['endpoint'])) {
|
||||
$result['error'] = 'Ungültiger Push-Endpunkt.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
try {
|
||||
$body = self::encrypt(json_encode($payload), $subscription['p256dh'], $subscription['auth']);
|
||||
$headers = self::headers($subscription['endpoint']);
|
||||
} catch (\Throwable $e) {
|
||||
$result['error'] = $e->getMessage();
|
||||
return $result;
|
||||
}
|
||||
|
||||
$curl = curl_init($subscription['endpoint']);
|
||||
curl_setopt_array($curl, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => $body,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => self::TIMEOUT,
|
||||
CURLOPT_CONNECTTIMEOUT => 5,
|
||||
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
]);
|
||||
$response = curl_exec($curl);
|
||||
$status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
$error = curl_error($curl);
|
||||
curl_close($curl);
|
||||
|
||||
$result['status'] = $status;
|
||||
if ($response === false) {
|
||||
$result['error'] = $error !== '' ? $error : 'Verbindungsfehler.';
|
||||
return $result;
|
||||
}
|
||||
if ($status === 201 || $status === 202) {
|
||||
$result['ok'] = true;
|
||||
return $result;
|
||||
}
|
||||
|
||||
$result['gone'] = ($status === 404 || $status === 410);
|
||||
$result['error'] = 'HTTP ' . $status;
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die HTTP-Header inklusive VAPID-Autorisierung.
|
||||
*
|
||||
* @param string $endpoint
|
||||
* @return string[]
|
||||
*/
|
||||
private static function headers($endpoint) {
|
||||
$public = self::publicKey();
|
||||
$parts = parse_url($endpoint);
|
||||
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||||
throw new \InvalidArgumentException('Ungültiger Push-Endpunkt.');
|
||||
}
|
||||
$audience = $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '');
|
||||
$jwt = self::vapidJwt($audience, $public);
|
||||
|
||||
return [
|
||||
'Content-Type: application/octet-stream',
|
||||
'Content-Encoding: aes128gcm',
|
||||
'TTL: ' . self::TTL,
|
||||
'Urgency: normal',
|
||||
'Authorization: vapid t=' . $jwt . ', k=' . $public,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Signiert die VAPID-Claims als ES256-JWT.
|
||||
*
|
||||
* @param string $audience Origin des Push-Dienstes
|
||||
* @param string $publicKey base64url des öffentlichen Schlüssels
|
||||
* @return string
|
||||
*/
|
||||
private static function vapidJwt($audience, $publicKey) {
|
||||
$private = self::privateKey();
|
||||
if (!$private) {
|
||||
throw new \RuntimeException('VAPID_PRIVATE_KEY ist ungültig.');
|
||||
}
|
||||
|
||||
$header = self::base64UrlEncode(json_encode(['typ' => 'JWT', 'alg' => 'ES256']));
|
||||
$claims = self::base64UrlEncode(json_encode([
|
||||
'aud' => $audience,
|
||||
'exp' => time() + 43200,
|
||||
'sub' => self::subject(),
|
||||
]));
|
||||
$unsigned = $header . '.' . $claims;
|
||||
|
||||
if (!openssl_sign($unsigned, $signature, $private, OPENSSL_ALGO_SHA256)) {
|
||||
throw new \RuntimeException('VAPID-Signatur fehlgeschlagen.');
|
||||
}
|
||||
|
||||
return $unsigned . '.' . self::base64UrlEncode(self::derToRaw($signature));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschlüsselt die Nutzlast für ein Abo (RFC 8291, aes128gcm).
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string $p256dh base64url des Geräteschlüssels (65 Byte)
|
||||
* @param string $auth base64url des Auth-Geheimnisses (16 Byte)
|
||||
* @return string Binärer Request-Body
|
||||
*/
|
||||
public static function encrypt($payload, $p256dh, $auth) {
|
||||
$uaPublic = self::base64UrlDecode($p256dh);
|
||||
$authSecret = self::base64UrlDecode($auth);
|
||||
if ($uaPublic === false || strlen($uaPublic) !== 65) {
|
||||
throw new \InvalidArgumentException('p256dh ist ungültig.');
|
||||
}
|
||||
if ($authSecret === false || strlen($authSecret) !== 16) {
|
||||
throw new \InvalidArgumentException('auth ist ungültig.');
|
||||
}
|
||||
|
||||
// Einmaliges Server-Schlüsselpaar für diese Nachricht
|
||||
$ephemeral = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
|
||||
if (!$ephemeral) {
|
||||
throw new \RuntimeException('Temporärer EC-Schlüssel konnte nicht erzeugt werden.');
|
||||
}
|
||||
$details = openssl_pkey_get_details($ephemeral);
|
||||
$asPublic = "\x04" . $details['ec']['x'] . $details['ec']['y'];
|
||||
|
||||
$uaKey = openssl_pkey_get_public(self::publicKeyPem($uaPublic));
|
||||
if (!$uaKey) {
|
||||
throw new \InvalidArgumentException('p256dh ist kein gültiger P-256-Punkt.');
|
||||
}
|
||||
$shared = openssl_pkey_derive($uaKey, $ephemeral, 32);
|
||||
if ($shared === false) {
|
||||
throw new \RuntimeException('ECDH-Schlüsselaustausch fehlgeschlagen.');
|
||||
}
|
||||
|
||||
$prkKey = hash_hmac('sha256', $shared, $authSecret, true);
|
||||
$ikm = self::hkdfExpand($prkKey, "WebPush: info\x00" . $uaPublic . $asPublic, 32);
|
||||
|
||||
$salt = random_bytes(16);
|
||||
$prk = hash_hmac('sha256', $ikm, $salt, true);
|
||||
$cek = self::hkdfExpand($prk, "Content-Encoding: aes128gcm\x00", 16);
|
||||
$nonce = self::hkdfExpand($prk, "Content-Encoding: nonce\x00", 12);
|
||||
|
||||
$plain = $payload . "\x02";
|
||||
$header = $salt . pack('N', self::RECORD_SIZE) . chr(65) . $asPublic;
|
||||
$cipher = openssl_encrypt($plain, 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag, $header, 16);
|
||||
if ($cipher === false) {
|
||||
throw new \RuntimeException('Verschlüsselung fehlgeschlagen.');
|
||||
}
|
||||
|
||||
return $header . $cipher . $tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* HKDF-Expand mit HMAC-SHA-256 (RFC 5869).
|
||||
*
|
||||
* @param string $prk Pseudozufälliger Schlüssel (Extract-Ergebnis)
|
||||
* @param string $info Kontext
|
||||
* @param int $length Gewünschte Länge
|
||||
* @return string
|
||||
*/
|
||||
private static function hkdfExpand($prk, $info, $length) {
|
||||
$output = '';
|
||||
$block = '';
|
||||
for ($i = 1; strlen($output) < $length; $i++) {
|
||||
$block = hash_hmac('sha256', $block . $info . chr($i), $prk, true);
|
||||
$output .= $block;
|
||||
}
|
||||
return substr($output, 0, $length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wandelt eine DER-Signatur (SEQUENCE aus r und s) in das für JWS nötige
|
||||
* Rohformat (32 Byte r || 32 Byte s).
|
||||
*
|
||||
* @param string $der
|
||||
* @return string
|
||||
*/
|
||||
private static function derToRaw($der) {
|
||||
$offset = 2;
|
||||
if (ord($der[1]) & 0x80) {
|
||||
$offset += ord($der[1]) & 0x7f;
|
||||
}
|
||||
$rLength = ord($der[$offset + 1]);
|
||||
$r = substr($der, $offset + 2, $rLength);
|
||||
$sOffset = $offset + 2 + $rLength;
|
||||
$sLength = ord($der[$sOffset + 1]);
|
||||
$s = substr($der, $sOffset + 2, $sLength);
|
||||
|
||||
return str_pad(ltrim($r, "\x00"), 32, "\x00", STR_PAD_LEFT)
|
||||
. str_pad(ltrim($s, "\x00"), 32, "\x00", STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut aus dem privaten Skalar und dem öffentlichen Punkt ein SEC1-PEM.
|
||||
*
|
||||
* @param string $scalar 32 Byte
|
||||
* @param string $point Unkomprimierter Punkt (65 Byte)
|
||||
* @return string
|
||||
*/
|
||||
private static function privateKeyPem($scalar, $point) {
|
||||
// SEC1: parameters [0] enthält nur die Kurve, publicKey [1] den Punkt.
|
||||
$curve = self::derTlv(0xa0, self::curveOid());
|
||||
$public = self::derTlv(0xa1, self::derTlv(0x03, "\x00" . $point));
|
||||
$der = self::derTlv(0x30,
|
||||
self::derTlv(0x02, "\x01")
|
||||
. self::derTlv(0x04, $scalar)
|
||||
. $curve
|
||||
. $public
|
||||
);
|
||||
return self::pem('EC PRIVATE KEY', $der);
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut aus einem unkomprimierten Punkt ein SPKI-PEM.
|
||||
*
|
||||
* @param string $point 65 Byte
|
||||
* @return string
|
||||
*/
|
||||
private static function publicKeyPem($point) {
|
||||
$algorithm = self::derTlv(0x30, self::ecOid() . self::curveOid());
|
||||
$der = self::derTlv(0x30, $algorithm . self::derTlv(0x03, "\x00" . $point));
|
||||
return self::pem('PUBLIC KEY', $der);
|
||||
}
|
||||
|
||||
private static function ecOid() {
|
||||
return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x02\x01");
|
||||
}
|
||||
|
||||
private static function curveOid() {
|
||||
return self::derTlv(0x06, "\x2a\x86\x48\xce\x3d\x03\x01\x07");
|
||||
}
|
||||
|
||||
private static function pem($label, $der) {
|
||||
return "-----BEGIN " . $label . "-----\n"
|
||||
. chunk_split(base64_encode($der), 64, "\n")
|
||||
. "-----END " . $label . "-----\n";
|
||||
}
|
||||
|
||||
private static function derTlv($tag, $value) {
|
||||
return chr($tag) . self::derLength(strlen($value)) . $value;
|
||||
}
|
||||
|
||||
private static function derLength($length) {
|
||||
if ($length < 0x80) {
|
||||
return chr($length);
|
||||
}
|
||||
$bytes = ltrim(pack('N', $length), "\x00");
|
||||
return chr(0x80 | strlen($bytes)) . $bytes;
|
||||
}
|
||||
|
||||
private static function base64UrlEncode($data) {
|
||||
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
private static function base64UrlDecode($data) {
|
||||
if (!is_string($data)) {
|
||||
return false;
|
||||
}
|
||||
$data = strtr($data, '-_', '+/');
|
||||
$remainder = strlen($data) % 4;
|
||||
if ($remainder) {
|
||||
$data .= str_repeat('=', 4 - $remainder);
|
||||
}
|
||||
return base64_decode($data, true);
|
||||
}
|
||||
}
|
||||
177
tippspiel/src/Models/PushSubscription.php
Normal file
177
tippspiel/src/Models/PushSubscription.php
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\Database;
|
||||
use App\Core\WebPush;
|
||||
|
||||
/**
|
||||
* Push-Abos für Smartphone-Erinnerungen (Web-Push mit VAPID).
|
||||
*
|
||||
* Ein Spieler kann auf mehreren Geräten Abos haben (Handy, Tablet). Die
|
||||
* Checkbox in den Einstellungen ist der Ein/Aus-Schalter für das Konto:
|
||||
* Abhaken löscht alle Abos. Ein Abo wird über den Endpunkt-Hash identifiziert,
|
||||
* damit dasselbe Gerät nicht doppelt eingetragen wird.
|
||||
*
|
||||
* Die Tabelle wird per tools/migration_push_subscriptions.sql angelegt. Fehlt
|
||||
* sie (z. B. direkt nach einem Deploy vor der Migration), liefern die Methoden
|
||||
* leere Ergebnisse, statt die Einstellungsseite mit einem Fehler abzubrechen.
|
||||
*/
|
||||
class PushSubscription {
|
||||
|
||||
/** Ergebnis von isAvailable(), damit die fehlende Tabelle nur einmal geprüft wird. */
|
||||
private static $available = null;
|
||||
|
||||
/**
|
||||
* Existiert die Tabelle? Ohne Tabelle bleibt das Feature einfach unsichtbar.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isAvailable() {
|
||||
if (self::$available !== null) {
|
||||
return self::$available;
|
||||
}
|
||||
try {
|
||||
Database::getConnection()->query("SELECT 1 FROM push_subscriptions LIMIT 1");
|
||||
self::$available = true;
|
||||
} catch (\PDOException $e) {
|
||||
self::$available = false;
|
||||
}
|
||||
return self::$available;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hat der Spieler ein Abo?
|
||||
*
|
||||
* @param int $userId
|
||||
* @return bool
|
||||
*/
|
||||
public static function hasSubscription($userId) {
|
||||
if (!self::isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
$stmt = Database::getConnection()->prepare("SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?");
|
||||
$stmt->execute([(int)$userId]);
|
||||
return (int)$stmt->fetchColumn() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt das Abo an bzw. aktualisiert es (gleicher Endpunkt = gleiches Gerät).
|
||||
*
|
||||
* @param int $userId
|
||||
* @param string $endpoint
|
||||
* @param string $p256dh
|
||||
* @param string $auth
|
||||
* @return bool
|
||||
*/
|
||||
public static function save($userId, $endpoint, $p256dh, $auth) {
|
||||
if (!self::isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
$stmt = Database::getConnection()->prepare(
|
||||
"INSERT INTO push_subscriptions (user_id, endpoint, endpoint_hash, p256dh, auth, created_at, updated_at)
|
||||
VALUES (:user_id, :endpoint, :endpoint_hash, :p256dh, :auth, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
user_id = :user_id_update,
|
||||
endpoint = :endpoint_update,
|
||||
p256dh = :p256dh_update,
|
||||
auth = :auth_update,
|
||||
updated_at = NOW()"
|
||||
);
|
||||
return $stmt->execute([
|
||||
':user_id' => (int)$userId,
|
||||
':endpoint' => $endpoint,
|
||||
':endpoint_hash' => hash('sha256', $endpoint),
|
||||
':p256dh' => $p256dh,
|
||||
':auth' => $auth,
|
||||
':user_id_update' => (int)$userId,
|
||||
':endpoint_update' => $endpoint,
|
||||
':p256dh_update' => $p256dh,
|
||||
':auth_update' => $auth,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht alle Abos eines Spielers.
|
||||
*
|
||||
* @param int $userId
|
||||
* @return int Anzahl gelöschter Zeilen
|
||||
*/
|
||||
public static function deleteForUser($userId) {
|
||||
if (!self::isAvailable()) {
|
||||
return 0;
|
||||
}
|
||||
$stmt = Database::getConnection()->prepare("DELETE FROM push_subscriptions WHERE user_id = ?");
|
||||
$stmt->execute([(int)$userId]);
|
||||
return $stmt->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht ein Abo anhand des Endpunkts (der Push-Dienst meldet 404/410).
|
||||
*
|
||||
* @param string $endpoint
|
||||
* @return int Anzahl gelöschter Zeilen
|
||||
*/
|
||||
public static function deleteByEndpoint($endpoint) {
|
||||
if (!self::isAvailable()) {
|
||||
return 0;
|
||||
}
|
||||
$stmt = Database::getConnection()->prepare("DELETE FROM push_subscriptions WHERE endpoint_hash = ?");
|
||||
$stmt->execute([hash('sha256', $endpoint)]);
|
||||
return $stmt->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Abos für eine Liste von Spielern.
|
||||
*
|
||||
* @param int[] $userIds
|
||||
* @return array Liste von Abo-Zeilen
|
||||
*/
|
||||
public static function getForUsers(array $userIds) {
|
||||
$userIds = array_values(array_unique(array_map('intval', $userIds)));
|
||||
if (empty($userIds) || !self::isAvailable()) {
|
||||
return [];
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($userIds), '?'));
|
||||
$stmt = Database::getConnection()->prepare(
|
||||
"SELECT * FROM push_subscriptions WHERE user_id IN ($placeholders)"
|
||||
);
|
||||
$stmt->execute($userIds);
|
||||
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Versendet eine Erinnerung an alle Abos der genannten Spieler.
|
||||
*
|
||||
* Abgelaufene Abos (HTTP 404/410) werden dabei entfernt, damit die Liste
|
||||
* nicht mit toten Endpunkten wächst.
|
||||
*
|
||||
* @param int[] $userIds
|
||||
* @param array $payload Titel/Text/URL für die Benachrichtigung
|
||||
* @return array ['sent' => int, 'removed' => int, 'failed' => int]
|
||||
*/
|
||||
public static function sendReminder(array $userIds, array $payload) {
|
||||
$result = ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
if (!WebPush::isConfigured()) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach (self::getForUsers($userIds) as $subscription) {
|
||||
$send = WebPush::send($subscription, $payload);
|
||||
if ($send['ok']) {
|
||||
$result['sent']++;
|
||||
} elseif ($send['gone']) {
|
||||
self::deleteByEndpoint($subscription['endpoint']);
|
||||
$result['removed']++;
|
||||
} else {
|
||||
$result['failed']++;
|
||||
error_log(sprintf(
|
||||
'Push-Erinnerung an Spieler %d fehlgeschlagen: %s',
|
||||
(int)$subscription['user_id'],
|
||||
$send['error']
|
||||
));
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
|
@ -181,9 +181,11 @@ class Roundmail {
|
|||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Erinnerung 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. E-Mail geht nur an Spieler mit
|
||||
* gets_reminders = 1, App-Erinnerungen nur an Spieler mit gespeichertem Push-Abo –
|
||||
* die beiden Kanäle sind unabhängig.
|
||||
*
|
||||
* @param string $appUrl Basis-URL für den Link in der Mail
|
||||
* @return string Ergebnis als Text (für das Log des Cron-Jobs)
|
||||
|
|
@ -204,20 +206,42 @@ class Roundmail {
|
|||
$round['name'], $lockTime->format('d.m.Y H:i'), $warnFrom->format('d.m.Y H:i'));
|
||||
}
|
||||
|
||||
// Alle bezahlten, nicht gelöschten Spieler – unabhängig davon, ob sie
|
||||
// Erinnerungen per E-Mail oder per App wünschen. Erst danach wird je
|
||||
// Kanal gefiltert.
|
||||
$paid = [];
|
||||
foreach (User::getPaid($season['id']) as $user) {
|
||||
if ($user['deleted'] === null && $user['gets_reminders'] && !empty($user['email'])) {
|
||||
$paid[(int)$user['id']] = $user['email'];
|
||||
if ($user['deleted'] === null) {
|
||||
$paid[(int)$user['id']] = $user;
|
||||
}
|
||||
}
|
||||
$missing = Tipp::getMissing($round['id'], array_keys($paid));
|
||||
$userIds = array_unique(array_merge($missing['tipps'], $missing['joker']));
|
||||
$userIds = array_values(array_unique(array_map('intval', array_merge($missing['tipps'], $missing['joker']))));
|
||||
if (empty($userIds)) {
|
||||
return $round['name'] . ': alle Tipps und Joker vollständig - keine Erinnerung nötig.';
|
||||
}
|
||||
|
||||
// E-Mail nur an Spieler, die das ausdrücklich wünschen.
|
||||
$recipients = [];
|
||||
foreach ($userIds as $userId) {
|
||||
$recipients[] = $paid[(int)$userId];
|
||||
$user = $paid[$userId];
|
||||
if ($user['gets_reminders'] && !empty($user['email'])) {
|
||||
$recipients[] = $user['email'];
|
||||
}
|
||||
}
|
||||
if (empty($recipients)) {
|
||||
return $round['name'] . ': alle Tipps und Joker vollständig - keine Erinnerung nötig.';
|
||||
|
||||
// App-Erinnerung ist ein eigener Kanal: Sie hängt an der zweiten
|
||||
// Checkbox (gespeichertes Push-Abo), nicht an gets_reminders.
|
||||
$push = PushSubscription::sendReminder($userIds, [
|
||||
'title' => 'Hoschis Tippspiel',
|
||||
'body' => 'Es fehlen noch Tipps/Joker für ' . $round['name']
|
||||
. '. Die Runde sperrt sich am ' . $lockTime->format('d.m.Y H:i') . '.',
|
||||
'url' => rtrim($appUrl, '/') . '/index.php?page=tipps',
|
||||
'tag' => 'reminder-' . (int)$round['id'],
|
||||
]);
|
||||
|
||||
if (empty($recipients) && $push['sent'] === 0 && $push['failed'] === 0 && $push['removed'] === 0) {
|
||||
return $round['name'] . ': Erinnerung nötig, aber kein Empfänger aktiviert.';
|
||||
}
|
||||
|
||||
$topic = self::REMINDER_TOPIC;
|
||||
|
|
@ -226,16 +250,30 @@ class Roundmail {
|
|||
. '<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, (int)$season['id']);
|
||||
$failed = [];
|
||||
$sent = [];
|
||||
if (!empty($recipients)) {
|
||||
$failed = Mailer::send($recipients, $topic, $html);
|
||||
$sent = array_values(array_diff($recipients, $failed));
|
||||
if (!empty($sent)) {
|
||||
self::create(0, $sent, $topic, $html, (int)$season['id']);
|
||||
}
|
||||
}
|
||||
|
||||
$result = sprintf('%s: Erinnerung an %d Empfänger versendet.', $round['name'], count($sent));
|
||||
$result = !empty($recipients)
|
||||
? sprintf('%s: Erinnerung an %d Empfänger versendet.', $round['name'], count($sent))
|
||||
: sprintf('%s: nur App-Erinnerung (keine E-Mail-Empfänger).', $round['name']);
|
||||
if (!empty($failed)) {
|
||||
$result .= ' Nicht zustellbar: ' . implode(', ', $failed);
|
||||
}
|
||||
if ($push['sent'] > 0 || $push['failed'] > 0 || $push['removed'] > 0) {
|
||||
$result .= sprintf(
|
||||
' Push: %d gesendet, %d fehlgeschlagen, %d abgelaufene Abos entfernt.',
|
||||
$push['sent'],
|
||||
$push['failed'],
|
||||
$push['removed']
|
||||
);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,12 +22,13 @@ require __DIR__ . '/../partials/header.php';
|
|||
<li><strong>Bei der Teilnahme:</strong> Tipps, Joker, Antworten auf Zusatzfragen, Teilnahmestatus und Zahlungseingang pro Saison, Zeitstempel.</li>
|
||||
<li><strong>Beim Aufruf der Seiten:</strong> Server-Logfiles mit IP-Adresse, Datum und Uhrzeit, aufgerufener Adresse, HTTP-Status und Browserkennung.</li>
|
||||
<li><strong>Für E-Mails:</strong> E-Mail-Adresse und der Vermerk, ob Erinnerungen gewünscht sind.</li>
|
||||
<li><strong>Für App-Erinnerungen (optional):</strong> ein technischer Push-Endpunkt des Geräts und zwei Schlüssel, mit denen der Server die Benachrichtigung verschlüsselt. Damit ist keine Telefonnummer und kein Standort verbunden.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Wozu und auf welcher Grundlage</h2>
|
||||
<ul>
|
||||
<li><strong>Durchführung des Tippspiels</strong> – Verwaltung der Teilnehmer, Ranglisten, Auszahlung des Pott: Art. 6 Abs. 1 lit. b DSGVO (Vertrag bzw. Teilnahme).</li>
|
||||
<li><strong>Erinnerungs- und Rundmails</strong> – Hinweis auf fehlende Tipps und organisatorische Mitteilungen: Art. 6 Abs. 1 lit. b DSGVO. Erinnerungen lassen sich im Profil abschalten.</li>
|
||||
<li><strong>Erinnerungs- und Rundmails</strong> – Hinweis auf fehlende Tipps und organisatorische Mitteilungen: Art. 6 Abs. 1 lit. b DSGVO. Erinnerungen lassen sich im Profil abschalten (E-Mail und App getrennt).</li>
|
||||
<li><strong>Server-Logfiles</strong> – Betriebssicherheit und Fehlersuche: Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse).</li>
|
||||
</ul>
|
||||
<p>Die Handynummer dient ausschließlich der kurzfristigen Kontaktaufnahme rund um die Auszahlung. IBAN und PayPal-Adresse werden nur für die Auszahlung des Pott verwendet.</p>
|
||||
|
|
@ -45,6 +46,7 @@ require __DIR__ . '/../partials/header.php';
|
|||
<li><strong>IBAN, PayPal und Handynummer:</strong> werden gelöscht, sobald zwei Saisons lang keine Zahlung mehr erfolgt ist – sie werden nur für die Auszahlung gebraucht. Beim Löschen eines Kontos werden sie sofort entfernt.</li>
|
||||
<li><strong>Name und E-Mail-Adresse:</strong> bleiben nach einer Kontolöschung erhalten, damit die Ranglisten vergangener Saisons nachvollziehbar bleiben (Art. 6 Abs. 1 lit. f DSGVO).</li>
|
||||
<li><strong>Server-Logfiles:</strong> maximal 30 Tage.</li>
|
||||
<li><strong>Push-Abo:</strong> bis zum Abschalten in den Einstellungen. Meldet der Push-Dienst das Gerät als abgelaufen, wird der Eintrag beim nächsten Erinnerungslauf entfernt.</li>
|
||||
<li><strong>Datensicherungen:</strong> regelmäßige Kopien der Datenbank, die nach kurzer Zeit durch neue ersetzt werden.</li>
|
||||
</ul>
|
||||
|
||||
|
|
|
|||
|
|
@ -50,6 +50,15 @@ require __DIR__ . '/partials/header.php';
|
|||
<label for="gets_reminders" class="inline">Ich möchte E-Mail-Erinnerungen erhalten</label>
|
||||
</div>
|
||||
|
||||
<?php // Nur in der installierten App sichtbar; das Skript unten blendet die Zeile ein. ?>
|
||||
<div class="form-group" id="push-reminder-group" hidden
|
||||
data-vapid-key="<?php echo htmlspecialchars((string)$pushPublicKey); ?>">
|
||||
<label for="push_reminders">App-Erinnerung:</label>
|
||||
<input type="checkbox" id="push_reminders" <?php if (!empty($pushEnabled)) echo 'checked'; ?>>
|
||||
<label for="push_reminders" class="inline">Ich möchte Smartphone-Erinnerungen erhalten (App)</label>
|
||||
<p class="settings-hint" id="push-reminder-hint"></p>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<button type="submit">Ok</button>
|
||||
</div>
|
||||
|
|
@ -62,6 +71,151 @@ require __DIR__ . '/partials/header.php';
|
|||
.settings-form input[readonly] { background: #f4f4f4; color: #666; border: 1px solid #ccc; }
|
||||
.settings-form input.wide { width: 25em; max-width: 100%; }
|
||||
.settings-form button { margin-left: 164px; }
|
||||
.settings-hint { margin: 0.3em 0 0 164px; font-size: 0.9em; color: #555; }
|
||||
.settings-hint.is-error { color: #b00020; }
|
||||
@media (max-width: 600px) {
|
||||
.settings-form .form-group > label:first-child { width: auto; display: block; }
|
||||
.settings-form button { margin-left: 0; }
|
||||
.settings-hint { margin-left: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var group = document.getElementById('push-reminder-group');
|
||||
var box = document.getElementById('push_reminders');
|
||||
var hint = document.getElementById('push-reminder-hint');
|
||||
if (!group || !box || !hint) {
|
||||
return;
|
||||
}
|
||||
|
||||
var vapidKey = group.getAttribute('data-vapid-key') || '';
|
||||
var isStandalone = window.matchMedia('(display-mode: standalone)').matches
|
||||
|| window.navigator.standalone === true;
|
||||
var supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
|
||||
|
||||
// Die Checkbox ist ausdrücklich nur für die installierte App gedacht.
|
||||
if (!isStandalone || !supported || !vapidKey) {
|
||||
return;
|
||||
}
|
||||
group.hidden = false;
|
||||
|
||||
function setHint(text, isError) {
|
||||
hint.textContent = text || '';
|
||||
hint.className = 'settings-hint' + (isError ? ' is-error' : '');
|
||||
}
|
||||
|
||||
function keyToBytes(base64url) {
|
||||
var padding = new Array((4 - (base64url.length % 4)) % 4 + 1).join('=');
|
||||
var base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
var raw = window.atob(base64);
|
||||
var bytes = new Uint8Array(raw.length);
|
||||
for (var i = 0; i < raw.length; i++) {
|
||||
bytes[i] = raw.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function post(page, payload) {
|
||||
return fetch('/index.php?page=' + page, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(payload || {})
|
||||
}).then(function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('Server meldet HTTP ' + response.status + '.');
|
||||
}
|
||||
return response.json();
|
||||
});
|
||||
}
|
||||
|
||||
function createSubscription(registration) {
|
||||
return registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: keyToBytes(vapidKey)
|
||||
});
|
||||
}
|
||||
|
||||
function subscribe() {
|
||||
return navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription().then(function (existing) {
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return createSubscription(registration).catch(function (error) {
|
||||
// Abo mit einem alten VAPID-Schlüssel: erneuern.
|
||||
if (error && error.name === 'InvalidStateError') {
|
||||
return registration.pushManager.getSubscription().then(function (old) {
|
||||
return old ? old.unsubscribe() : null;
|
||||
}).then(function () {
|
||||
return createSubscription(registration);
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
box.addEventListener('change', function () {
|
||||
if (box.disabled) {
|
||||
return;
|
||||
}
|
||||
box.disabled = true;
|
||||
setHint('');
|
||||
|
||||
var action;
|
||||
if (box.checked) {
|
||||
action = Notification.requestPermission().then(function (permission) {
|
||||
if (permission !== 'granted') {
|
||||
throw new Error('Benachrichtigungen sind blockiert. Bitte in den Systemeinstellungen erlauben.');
|
||||
}
|
||||
return subscribe();
|
||||
}).then(function (subscription) {
|
||||
if (!subscription) {
|
||||
throw new Error('Abo konnte nicht angelegt werden.');
|
||||
}
|
||||
return post('push_subscribe', subscription.toJSON());
|
||||
}).then(function () {
|
||||
setHint('Erinnerungen erscheinen jetzt auf diesem Gerät.');
|
||||
});
|
||||
} else {
|
||||
action = navigator.serviceWorker.ready.then(function (registration) {
|
||||
return registration.pushManager.getSubscription();
|
||||
}).then(function (subscription) {
|
||||
return subscription ? subscription.unsubscribe() : null;
|
||||
}).then(function () {
|
||||
return post('push_unsubscribe', {});
|
||||
}).then(function () {
|
||||
setHint('Smartphone-Erinnerungen sind ausgeschaltet.');
|
||||
});
|
||||
}
|
||||
|
||||
action.catch(function (error) {
|
||||
if (box.checked) {
|
||||
box.checked = false;
|
||||
}
|
||||
setHint(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true);
|
||||
}).then(function () {
|
||||
box.disabled = false;
|
||||
});
|
||||
});
|
||||
|
||||
// Beim Öffnen das Gerät still nachtragen, wenn Erinnerungen gewünscht sind
|
||||
// und die Erlaubnis schon erteilt ist (z. B. zweites Gerät). Bewusst kein
|
||||
// automatisches Abmelden: Auf einem geteilten Gerät kann das Abo zu einem
|
||||
// anderen Konto gehören.
|
||||
if (box.checked && Notification.permission === 'granted') {
|
||||
subscribe().then(function (subscription) {
|
||||
if (subscription) {
|
||||
return post('push_subscribe', subscription.toJSON());
|
||||
}
|
||||
}).catch(function () {
|
||||
// still: die Einstellungsseite bleibt nutzbar
|
||||
});
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php require __DIR__ . '/partials/footer.php'; ?>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue