Asked for: Damaskar's proposal (iCalendar/webcal feed with a personal token URL in the profile, "Feed-URL neu generieren", token blocked when a member leaves or is banned) - "da soll man aber nur die synchronisiert werden für die man sich auch anmelden kann". - calendar_feed.php + includes/calendar_feed.php: calendar_feed.php?t=<48 hex> returns an .ics (RFC 5545, UTC, folded lines, ETag/304) without login, also in maintenance mode. Content = what you can sign up for: active raids (raids.view + linked Discord) with your own state (signed up with class and group, bench, declined, invite pending), archived ones only if you were in; member entries where "Bin dabei" is possible (audience rules of calendar_audience.php), your own and joined ones. Past entries stay 90 days if you took part. No bot event reminders and no names of other members; TRANSP busy/free by participation. - New table calendar_feeds (one per account, schema version 66): token in plain text so the profile can show it again, looked up by its SHA-256; bound to users.session_epoch like "Angemeldet bleiben" (forced logout, lock and deletion request invalidate it). Unknown address 404; invalid address, locked account or no rights 403; leaving the Discord server (checked at most hourly via discord_live_check) deletes the feed; 60 fetches per hour and feed (audit log entry); bot down 503 so the apps keep their last state. No lockout per IP - shared fetchers like Google would be hit by stale addresses. - profile.php: "Kalender-Abo" panel - set up, copy, one-click links for Google Kalender, Outlook and webcal, manual steps per app, last fetch with the app type, new address / end subscription with confirmation; calendar.php links to it. - Privacy page, data export (kalender_abo without the address), account deletion, patch note and README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
450 lines
20 KiB
PHP
450 lines
20 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/**
|
||
* Kalender-Abo (iCalendar/.ics, "webcal"): Jedes Mitglied erzeugt sich unter "Mein Profil" eine eigene, geheime Adresse
|
||
* (calendar_feed.php?t=...), die Google Kalender, Outlook, Apple Kalender & Co. regelmaessig abrufen. Drin steht, wofuer
|
||
* man sich anmelden kann - und wofuer man angemeldet ist:
|
||
* - Raids (raids.view und ein verknuepftes Discord-Konto, ohne das gibt es keine Anmeldung): alle aktiven, dazu
|
||
* archivierte der letzten CALENDAR_FEED_PAST_DAYS Tage, bei denen man angemeldet war
|
||
* - Termine der Mitglieder (members.view): alle, bei denen "Bin dabei" moeglich ist (Zielgruppe wie im Kalender,
|
||
* includes/calendar_audience.php), dazu eigene und solche, bei denen man dabei ist oder war
|
||
* Die Event-Erinnerungen des Bots nicht - fuer die gibt es keine Anmeldung. Namen anderer Mitglieder stehen nicht darin,
|
||
* nur Zahlen: Die Termine landen bei Google, Microsoft oder Apple.
|
||
*
|
||
* Die Adresse gilt, bis das Mitglied eine neue erzeugt oder das Abo beendet. Wie "Angemeldet bleiben" haengt sie an
|
||
* users.session_epoch - "Abmelden erzwingen", Sperren und ein Loeschantrag machen sie sofort ungueltig. Ein gesperrtes
|
||
* Konto oder eins ohne die Rechte bekommt 403 statt Termine; wer den Discord-Server verlassen hat, dessen Abo loescht
|
||
* der naechste Abruf (calendar_feed.php).
|
||
*/
|
||
|
||
require_once __DIR__ . '/calendar_audience.php';
|
||
|
||
// Die Abo-Adresse zeigt immer auf die Hauptadresse mit HTTPS: Sie bleibt monatelang in den Kalender-Apps stehen, die alten
|
||
// Domains haben kein gueltiges Zertifikat, und Google Kalender abonniert nur HTTPS. Nur lokal gilt die aufgerufene Adresse.
|
||
const CALENDAR_FEED_BASE_URL = 'https://lumina-ascendens.de';
|
||
// Vergangene Termine bleiben so lange im Abo, wenn man dabei war - danach verschwinden sie aus dem Kalender
|
||
const CALENDAR_FEED_PAST_DAYS = 90;
|
||
// Raids haben keine Endzeit, Termine der Mitglieder nur optional - so lange dauern sie im Kalender
|
||
const CALENDAR_FEED_RAID_MINUTES = 120;
|
||
const CALENDAR_FEED_ENTRY_MINUTES = 60;
|
||
// Wie oft die Apps nachsehen sollen - nur ein Wunsch: Google Kalender holt Abos ohnehin nur alle paar Stunden
|
||
const CALENDAR_FEED_REFRESH = 'PT1H';
|
||
// Hoechstens so viele Abrufe je Abo in einer Stunde (Apple Kalender alle 5 Minuten auf drei Geraeten waeren 36)
|
||
const CALENDAR_FEED_MAX_FETCHES = 60;
|
||
// Mitgliedschaft auf Discord bei einem Abruf hoechstens einmal pro Stunde neu pruefen (discord_live_check)
|
||
const CALENDAR_FEED_MEMBER_CHECK = 3600;
|
||
|
||
/** Hat das Konto eine Berechtigung? Wie user_has_permission(), aber fuer ein beliebiges Konto (der Abruf hat keine Sitzung). */
|
||
function calendar_feed_can(array $user, string $key): bool
|
||
{
|
||
if (($user['status'] ?? '') !== 'active') {
|
||
return false;
|
||
}
|
||
if (!empty($user['is_admin']) || is_developer($user)) {
|
||
return true;
|
||
}
|
||
return in_array($key, user_permission_keys((int) $user['id']), true);
|
||
}
|
||
|
||
/** Gibt es fuer das Konto etwas zu abonnieren? Raids (Anmeldung nur mit Discord) oder Termine der Mitglieder. */
|
||
function calendar_feed_allowed(array $user): bool
|
||
{
|
||
return (!empty($user['discord_id']) && calendar_feed_can($user, 'raids.view')) || calendar_feed_can($user, 'members.view');
|
||
}
|
||
|
||
/** Das Abo eines Kontos (auch ein ungueltig gewordenes, siehe calendar_feed_active()) oder null. */
|
||
function calendar_feed_get(int $userId): ?array
|
||
{
|
||
try {
|
||
$stmt = db()->prepare('SELECT f.*, u.session_epoch AS user_epoch FROM calendar_feeds f JOIN users u ON u.id = f.user_id WHERE f.user_id = ?');
|
||
$stmt->execute([$userId]);
|
||
$feed = $stmt->fetch();
|
||
} catch (PDOException $e) {
|
||
return null; // Tabelle kommt erst mit dem naechsten Schema-Abgleich
|
||
}
|
||
return $feed ?: null;
|
||
}
|
||
|
||
/** Gilt die Adresse noch? Nach "Abmelden erzwingen", einer Sperre oder einem Loeschantrag nicht mehr. */
|
||
function calendar_feed_active(array $feed): bool
|
||
{
|
||
return (int) $feed['session_epoch'] === (int) $feed['user_epoch'];
|
||
}
|
||
|
||
/** Neue Adresse erzeugen - die bisherige gilt ab sofort nicht mehr. */
|
||
function calendar_feed_renew(int $userId): void
|
||
{
|
||
$token = bin2hex(random_bytes(24));
|
||
$pdo = db();
|
||
$epoch = $pdo->prepare('SELECT session_epoch FROM users WHERE id = ?');
|
||
$epoch->execute([$userId]);
|
||
$pdo->prepare(
|
||
'INSERT INTO calendar_feeds (user_id, token, token_hash, session_epoch) VALUES (?, ?, ?, ?)
|
||
ON DUPLICATE KEY UPDATE token = VALUES(token), token_hash = VALUES(token_hash), session_epoch = VALUES(session_epoch),
|
||
created_at = NOW(), last_used_at = NULL, last_client = NULL'
|
||
)->execute([$userId, $token, hash('sha256', $token), (int) $epoch->fetchColumn()]);
|
||
}
|
||
|
||
function calendar_feed_delete(int $userId): void
|
||
{
|
||
db()->prepare('DELETE FROM calendar_feeds WHERE user_id = ?')->execute([$userId]);
|
||
}
|
||
|
||
/** Abo zu einer Adresse, samt Konto - oder null. Nachgeschlagen wird ueber den Hash (keine Zeitunterschiede je Zeichen). */
|
||
function calendar_feed_find(string $token): ?array
|
||
{
|
||
if (!preg_match('/^[0-9a-f]{48}$/', $token)) {
|
||
return null;
|
||
}
|
||
try {
|
||
$stmt = db()->prepare(
|
||
'SELECT f.user_id, f.token, f.session_epoch, u.session_epoch AS user_epoch, u.status, u.discord_synced_at
|
||
FROM calendar_feeds f JOIN users u ON u.id = f.user_id WHERE f.token_hash = ?'
|
||
);
|
||
$stmt->execute([hash('sha256', $token)]);
|
||
$feed = $stmt->fetch();
|
||
} catch (PDOException $e) {
|
||
return null;
|
||
}
|
||
return $feed && hash_equals((string) $feed['token'], $token) ? $feed : null;
|
||
}
|
||
|
||
/** Erfolgreichen Abruf vermerken: wann und mit welcher Art Kalender-App (nur der Name, nicht die ganze Kennung). */
|
||
function calendar_feed_touch(int $userId, string $userAgent): void
|
||
{
|
||
try {
|
||
db()->prepare('UPDATE calendar_feeds SET last_used_at = NOW(), last_client = ? WHERE user_id = ?')
|
||
->execute([calendar_feed_client_name($userAgent), $userId]);
|
||
} catch (PDOException $e) {
|
||
// nur Statistik fuer "Mein Profil"
|
||
}
|
||
}
|
||
|
||
/** Welche Kalender-App abruft, grob aus der Browser-Kennung - so erkennt das Mitglied, ob seine Adresse woanders benutzt wird. */
|
||
function calendar_feed_client_name(string $userAgent): string
|
||
{
|
||
$clients = [
|
||
'Google' => 'Google Kalender', // Google-Calendar-Importer
|
||
'Outlook' => 'Outlook',
|
||
'Exchange' => 'Outlook',
|
||
'Microsoft' => 'Outlook',
|
||
'dataaccessd' => 'Apple Kalender',
|
||
'CalendarAgent' => 'Apple Kalender',
|
||
'iOS/' => 'Apple Kalender',
|
||
'macOS/' => 'Apple Kalender',
|
||
'Mac OS X/' => 'Apple Kalender',
|
||
'Thunderbird' => 'Thunderbird',
|
||
'ICSx' => 'ICSx⁵ (Android)',
|
||
'DAVx' => 'DAVx⁵ (Android)',
|
||
];
|
||
foreach ($clients as $needle => $name) {
|
||
if (stripos($userAgent, $needle) !== false) {
|
||
return $name;
|
||
}
|
||
}
|
||
return str_starts_with($userAgent, 'Mozilla/') ? 'Browser' : 'andere Kalender-App';
|
||
}
|
||
|
||
/** https://lumina-ascendens.de - lokal (localhost, *.test) die aufgerufene Adresse, damit sich das Abo testen laesst. */
|
||
function calendar_feed_base_url(): string
|
||
{
|
||
$host = strtolower((string) preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
|
||
$local = in_array($host, ['localhost', '127.0.0.1', '[::1]'], true) || preg_match('/\.(localhost|test)$/', $host) === 1;
|
||
return $local ? site_url('') : CALENDAR_FEED_BASE_URL;
|
||
}
|
||
|
||
function calendar_feed_url(string $token): string
|
||
{
|
||
return calendar_feed_base_url() . '/calendar_feed.php?t=' . $token;
|
||
}
|
||
|
||
/**
|
||
* Links, die das Abo direkt in einer Kalender-App hinzufuegen (Formate wie beim verbreiteten "add-to-calendar-button").
|
||
*
|
||
* @return array{webcal: string, google: string, outlook: string}
|
||
*/
|
||
function calendar_feed_app_links(string $url): array
|
||
{
|
||
$webcal = (string) preg_replace('~^https?://~', 'webcal://', $url);
|
||
return [
|
||
'webcal' => $webcal,
|
||
'google' => 'https://calendar.google.com/calendar/u/0/r?cid=' . rawurlencode($webcal),
|
||
'outlook' => 'https://outlook.live.com/calendar/0/addfromweb/?url=' . rawurlencode($webcal) . '&name=' . rawurlencode('Lumina Ascendens'),
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Die Termine eines Abos, nach Beginn sortiert.
|
||
*
|
||
* @param array $user Konto (id, status, is_admin, discord_id)
|
||
* @return array<int, array<string, mixed>> je Termin: uid, start, end, stamp, title, description, location, url, category,
|
||
* tentative, busy
|
||
* @throws RuntimeException wenn der Bot nicht antwortet - dann lieber gar keine Antwort als ein Kalender ohne Raids
|
||
*/
|
||
function calendar_feed_entries(array $user): array
|
||
{
|
||
$now = time();
|
||
$since = $now - CALENDAR_FEED_PAST_DAYS * 86400;
|
||
$base = calendar_feed_base_url();
|
||
$entries = [];
|
||
|
||
$discordId = (string) ($user['discord_id'] ?? '');
|
||
if ($discordId !== '' && calendar_feed_can($user, 'raids.view')) {
|
||
require_once __DIR__ . '/raids_api.php';
|
||
foreach (fetch_raids('all') as $raid) {
|
||
$entry = calendar_feed_raid_entry($raid, $discordId, $now, $since, $base);
|
||
if ($entry !== null) {
|
||
$entries[] = $entry;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (calendar_feed_can($user, 'members.view')) {
|
||
foreach (calendar_feed_member_entries($user, $now, $since, $base) as $entry) {
|
||
$entries[] = $entry;
|
||
}
|
||
}
|
||
|
||
usort($entries, static fn (array $a, array $b): int => [$a['start'], $a['uid']] <=> [$b['start'], $b['uid']]);
|
||
return $entries;
|
||
}
|
||
|
||
/** Ein Raid fuers Abo - null, wenn er nicht hineingehoert (vorbei ohne dich, abgesagt, zu alt). */
|
||
function calendar_feed_raid_entry(array $raid, string $discordId, int $now, int $since, string $base): ?array
|
||
{
|
||
$raidId = (int) ($raid['raid_id'] ?? 0);
|
||
$start = (int) ($raid['timestamp'] ?? 0);
|
||
if ($raidId <= 0 || $start < $since) {
|
||
return null;
|
||
}
|
||
$archived = !empty($raid['archived']) || !empty($raid['archived_at']);
|
||
$groupNames = array_values(array_filter(array_map('trim', explode(',', (string) ($raid['groups'] ?? '')))));
|
||
|
||
// Wie der Kader in der Raid-Nachricht: in einer Gruppe, ohne Abgemeldete und offene Premade-Einladungen
|
||
$mine = null;
|
||
$count = 0;
|
||
foreach ((array) ($raid['signups'] ?? []) as $signup) {
|
||
if ((int) ($signup['group'] ?? 0) >= 1 && ($signup['class'] ?? '') !== 'Ausstehend') {
|
||
$count++;
|
||
}
|
||
if ((string) ($signup['user_id'] ?? '') === $discordId) {
|
||
$mine = $signup;
|
||
}
|
||
}
|
||
// Gruppen wie im Bot: >= 1 echte Gruppe, 0 Ersatzbank, -1 abgemeldet; "Ausstehend" = Premade-Einladung noch offen
|
||
$myGroup = (int) ($mine['group'] ?? -1);
|
||
$myClass = (string) ($mine['class'] ?? '');
|
||
$signedUp = $mine !== null && $myGroup >= 0 && $myClass !== 'Ausstehend';
|
||
// Archiviert heisst vorbei (oder vorher abgesagt): Er bleibt nur, wenn du dabei warst und er schon begonnen hatte
|
||
if ($archived && (!$signedUp || $start > $now)) {
|
||
return null;
|
||
}
|
||
|
||
if ($mine === null) {
|
||
$status = 'Du bist noch nicht angemeldet.';
|
||
} elseif ($myGroup < 0) {
|
||
$status = '❌ Du hast abgesagt.';
|
||
} elseif (!$signedUp) {
|
||
$status = '⏳ Du bist mit deiner Premade eingeladen – die Einladung ist noch offen.';
|
||
} else {
|
||
$status = '✅ Du bist angemeldet: ' . ($myClass !== '' ? $myClass . ' ' : '')
|
||
. ($myGroup === 0 ? 'auf der Ersatzbank.' : 'in ' . ($groupNames[$myGroup - 1] ?? 'Gruppe ' . $myGroup) . '.');
|
||
}
|
||
$max = (int) ($raid['max_slots'] ?? 0);
|
||
$lines = [$status, 'Angemeldet: ' . $count . ($max > 0 ? ' von ' . $max : '')];
|
||
$requirements = trim((string) ($raid['requirements'] ?? ''));
|
||
if ($requirements !== '') {
|
||
$lines[] = 'Anforderungen: ' . $requirements;
|
||
}
|
||
$gearscore = trim((string) ($raid['gearscore'] ?? ''));
|
||
if ($gearscore !== '') {
|
||
$lines[] = 'Gearscore: ' . raid_gearscore_label($gearscore);
|
||
}
|
||
if ($archived) {
|
||
$lines[] = 'Der Raid ist vorbei und archiviert.';
|
||
}
|
||
$url = $base . '/raids.php' . ($archived ? '?status=archived' : '') . '#raid-' . $raidId;
|
||
$lines[] = '';
|
||
$lines[] = ($archived || $signedUp ? 'Zum Raid: ' : 'Anmelden: ') . $url;
|
||
|
||
$title = trim((string) ($raid['title'] ?? ''));
|
||
return [
|
||
'uid' => 'raid-' . $raidId,
|
||
'start' => $start,
|
||
'end' => $start + CALENDAR_FEED_RAID_MINUTES * 60,
|
||
// Die raid_id ist die ID der Discord-Nachricht und verraet, wann der Raid gepostet wurde
|
||
'stamp' => raid_posted_at($raidId),
|
||
'title' => $title === '' ? 'Raid' : (stripos($title, 'raid') === false ? 'Raid: ' . $title : $title),
|
||
'description' => implode("\n", $lines),
|
||
'location' => '',
|
||
'url' => $url,
|
||
'category' => 'Raid',
|
||
'tentative' => false,
|
||
'busy' => $signedUp,
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Termine der Mitglieder fuers Abo: alle, bei denen du "Bin dabei" klicken kannst, deine eigenen und die, bei denen du
|
||
* dabei bist oder warst. Sichtbarkeit wie im Kalender (calendar.php): freigegeben oder eigene, interne nur fuer die Leitung.
|
||
*
|
||
* @return array<int, array<string, mixed>>
|
||
*/
|
||
function calendar_feed_member_entries(array $user, int $now, int $since, string $base): array
|
||
{
|
||
$userId = (int) $user['id'];
|
||
$canLead = calendar_feed_can($user, 'calendar.leadership');
|
||
$stmt = db()->prepare(
|
||
"SELECT e.id, e.user_id, e.title, e.description, e.starts_at, e.ends_at, e.location_path, e.audience, e.status,
|
||
e.created_at, e.updated_at,
|
||
(SELECT COUNT(*) FROM calendar_participants p JOIN users pu ON pu.id = p.user_id
|
||
WHERE p.entry_id = e.id AND pu.status = 'active') AS people,
|
||
EXISTS (SELECT 1 FROM calendar_participants p WHERE p.entry_id = e.id AND p.user_id = ?) AS joined
|
||
FROM calendar_entries e JOIN users u ON u.id = e.user_id
|
||
WHERE e.starts_at >= ? AND u.status = 'active'
|
||
AND (e.status = 'visible' OR e.user_id = ?)
|
||
AND (e.audience <> 'internal' OR ? OR e.user_id = ?)
|
||
ORDER BY e.starts_at, e.id"
|
||
);
|
||
$stmt->execute([$userId, date('Y-m-d H:i:s', $since), $userId, $canLead ? 1 : 0, $userId]);
|
||
|
||
$entries = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$id = (int) $row['id'];
|
||
$start = (int) strtotime((string) $row['starts_at']);
|
||
$isHost = (int) $row['user_id'] === $userId;
|
||
$joined = (bool) $row['joined'];
|
||
$pending = $row['status'] !== 'visible';
|
||
// "Bin dabei" gibt es wie auf der Website nur vor dem Beginn
|
||
$canJoin = $start >= $now && !$pending && calendar_can_join($row, $canLead);
|
||
if (!$isHost && !$joined && !$canJoin) {
|
||
continue;
|
||
}
|
||
|
||
$audience = (string) ($row['audience'] ?? 'all');
|
||
$lines = [$isHost ? '✅ Du hast den Termin eingetragen.' : ($joined ? '✅ Du bist dabei.' : 'Du bist noch nicht dabei – mitmachen mit „Bin dabei“ auf der Website.')];
|
||
if ($pending) {
|
||
$lines[] = '⏳ Wartet noch auf die Freigabe durch die Moderation – die anderen sehen ihn noch nicht.';
|
||
}
|
||
if ($audience === 'internal') {
|
||
$lines[] = '🔒 Intern – nur die Leitung sieht diesen Termin.';
|
||
} elseif ($audience === 'leadership') {
|
||
$lines[] = 'Teilnehmen kann nur die Leitung.';
|
||
}
|
||
$lines[] = 'Dabei: ' . (int) $row['people'];
|
||
$link = !empty($row['location_path']) ? map_link_parse((string) $row['location_path']) : null;
|
||
if ($link !== null) {
|
||
$lines[] = 'Treffpunkt: ' . map_link_label($link) . ' – ' . $base . $link['path'];
|
||
}
|
||
$description = trim(str_replace("\r\n", "\n", (string) ($row['description'] ?? '')));
|
||
if ($description !== '') {
|
||
$lines[] = '';
|
||
$lines[] = $description;
|
||
}
|
||
$url = $base . '/calendar.php?month=' . date('Y-m', $start) . '#termin-' . $id;
|
||
$lines[] = '';
|
||
$lines[] = 'Zum Termin: ' . $url;
|
||
|
||
$end = !empty($row['ends_at']) ? (int) strtotime((string) $row['ends_at']) : 0;
|
||
$entries[] = [
|
||
'uid' => 'termin-' . $id,
|
||
'start' => $start,
|
||
'end' => $end > $start ? $end : $start + CALENDAR_FEED_ENTRY_MINUTES * 60,
|
||
'stamp' => (int) strtotime((string) ($row['updated_at'] ?: $row['created_at'])),
|
||
'title' => ($audience === 'internal' ? '🔒 ' : '') . (string) $row['title'],
|
||
'description' => implode("\n", $lines),
|
||
// Ein Ort im Spiel - mit "(Aion 2)", damit Kalender-Apps keine echte Adresse daraus machen
|
||
'location' => $link !== null ? map_link_label($link) . ' (Aion 2)' : '',
|
||
'url' => $url,
|
||
'category' => 'Termin',
|
||
'tentative' => $pending,
|
||
'busy' => $joined || $isHost,
|
||
];
|
||
}
|
||
return $entries;
|
||
}
|
||
|
||
/**
|
||
* Die Termine als iCalendar-Datei (RFC 5545). Zeiten in UTC - die Apps rechnen sie in die eigene Zeitzone um. Die Ausgabe
|
||
* haengt nur an den Terminen (kein "jetzt" darin), damit ein unveraenderter Kalender dieselbe Datei ergibt (ETag).
|
||
*
|
||
* @param array<int, array<string, mixed>> $entries aus calendar_feed_entries()
|
||
*/
|
||
function calendar_feed_ics(array $entries): string
|
||
{
|
||
$domain = (string) parse_url(CALENDAR_FEED_BASE_URL, PHP_URL_HOST);
|
||
$about = 'Raids und Termine der Legion Lumina Ascendens, bei denen du mitmachen kannst.';
|
||
$lines = [
|
||
'BEGIN:VCALENDAR',
|
||
'VERSION:2.0',
|
||
'PRODID:-//Lumina Ascendens//Kalender-Abo//DE',
|
||
'CALSCALE:GREGORIAN',
|
||
'METHOD:PUBLISH',
|
||
'NAME:Lumina Ascendens',
|
||
'X-WR-CALNAME:Lumina Ascendens',
|
||
'DESCRIPTION:' . ical_text($about),
|
||
'X-WR-CALDESC:' . ical_text($about),
|
||
'X-WR-TIMEZONE:Europe/Berlin',
|
||
'REFRESH-INTERVAL;VALUE=DURATION:' . CALENDAR_FEED_REFRESH,
|
||
'X-PUBLISHED-TTL:' . CALENDAR_FEED_REFRESH,
|
||
// Gold wie auf der Website (COLOR kennt nur CSS-Farbnamen, Apple nimmt den genauen Wert)
|
||
'COLOR:goldenrod',
|
||
'X-APPLE-CALENDAR-COLOR:#C9A227',
|
||
];
|
||
foreach ($entries as $entry) {
|
||
$lines[] = 'BEGIN:VEVENT';
|
||
$lines[] = 'UID:' . $entry['uid'] . '@' . $domain;
|
||
$lines[] = 'DTSTAMP:' . ical_utc((int) $entry['stamp']);
|
||
$lines[] = 'DTSTART:' . ical_utc((int) $entry['start']);
|
||
$lines[] = 'DTEND:' . ical_utc((int) $entry['end']);
|
||
$lines[] = 'SUMMARY:' . ical_text((string) $entry['title']);
|
||
$lines[] = 'DESCRIPTION:' . ical_text((string) $entry['description']);
|
||
if ($entry['location'] !== '') {
|
||
$lines[] = 'LOCATION:' . ical_text((string) $entry['location']);
|
||
}
|
||
$lines[] = 'URL:' . $entry['url'];
|
||
$lines[] = 'CATEGORIES:' . ical_text((string) $entry['category']);
|
||
$lines[] = 'STATUS:' . ($entry['tentative'] ? 'TENTATIVE' : 'CONFIRMED');
|
||
// Wo du dabei bist, zeigt dich dein Kalender als beschaeftigt, sonst als frei (Outlook liest das zweite Feld)
|
||
$lines[] = 'TRANSP:' . ($entry['busy'] ? 'OPAQUE' : 'TRANSPARENT');
|
||
$lines[] = 'X-MICROSOFT-CDO-BUSYSTATUS:' . ($entry['busy'] ? 'BUSY' : 'FREE');
|
||
$lines[] = 'END:VEVENT';
|
||
}
|
||
$lines[] = 'END:VCALENDAR';
|
||
return implode("\r\n", array_map('ical_fold', $lines)) . "\r\n";
|
||
}
|
||
|
||
/** Zeitpunkt als UTC-Zeit fuer iCalendar (20260927T180000Z). */
|
||
function ical_utc(int $timestamp): string
|
||
{
|
||
return gmdate('Ymd\THis\Z', $timestamp);
|
||
}
|
||
|
||
/** Text fuer iCalendar: Backslash, Semikolon, Komma und Zeilenumbrueche maskieren, Steuerzeichen entfernen. */
|
||
function ical_text(string $text): string
|
||
{
|
||
$text = mb_scrub(str_replace(["\r\n", "\r"], "\n", $text), 'UTF-8');
|
||
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/', '', $text);
|
||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
|
||
}
|
||
|
||
/** Zeilen ueber 75 Bytes umbrechen (RFC 5545, Abschnitt 3.1) - ohne ein UTF-8-Zeichen zu zerteilen. */
|
||
function ical_fold(string $line): string
|
||
{
|
||
if (strlen($line) <= 75) {
|
||
return $line;
|
||
}
|
||
$folded = '';
|
||
$current = '';
|
||
$limit = 75;
|
||
foreach (mb_str_split($line, 1, 'UTF-8') as $char) {
|
||
if (strlen($current) + strlen($char) > $limit) {
|
||
$folded .= $current . "\r\n ";
|
||
$current = '';
|
||
$limit = 74; // Folgezeilen beginnen mit einem Leerzeichen
|
||
}
|
||
$current .= $char;
|
||
}
|
||
return $folded . $current;
|
||
}
|