LuminaWebsite/calendar.php
Maaxxs 406b7643cd Calendar: personal iCal subscription for Google, Outlook and Apple with the raids and entries you can sign up for
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>
2026-09-27 14:11:43 +02:00

369 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Terminkalender: Raids und Event-Erinnerungen im Monatsueberblick - live aus der Bot-API
* (dieselben Daten wie auf den Seiten Raids und Events, keine doppelte Datenhaltung).
* Wiederkehrende Events werden ab ihrem naechsten Termin im Intervall fortgeschrieben.
* Dazu kommen Termine, die Mitglieder selbst eintragen (calendar_entries, calendar_action.php).
*
* Mit der Einstellung "calendar_public" ist der Kalender auch ohne Anmeldung sichtbar - dann nur
* Titel und Uhrzeit, ohne Links, Anmeldungen oder Kanaele.
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/raids_api.php';
require_once __DIR__ . '/includes/events_api.php';
require_once __DIR__ . '/includes/member_profile.php'; // gallery_comment_html() fuer Beschreibungen
require_once __DIR__ . '/includes/calendar_audience.php';
require_once __DIR__ . '/includes/calendar_feed.php';
$me = current_user();
$loggedIn = $me !== null && $me['status'] === 'active';
$isPublic = setting_get('calendar_public') === '1';
if (!$loggedIn && !$isPublic) {
require_login();
}
$showRaids = !$loggedIn || user_has_permission('raids.view');
$showEvents = !$loggedIn || user_has_permission('events.view');
$showMember = !$loggedIn || user_has_permission('members.view');
if (!$showRaids && !$showEvents && !$showMember) {
show_not_found();
}
$canCreate = $loggedIn && user_has_permission('members.view');
$isModerator = $loggedIn && moderation_can();
$myId = $loggedIn ? (int) $me['id'] : 0;
$canTogglePublic = $loggedIn && user_has_permission('events.manage');
// Leitung (calendar.leadership): traegt Termine nur fuer die Leitung ein und sieht interne Termine
$canLead = $loggedIn && calendar_can_lead();
// Angezeigter Monat (?month=2026-09), Standard: aktueller Monat
$monthParam = (string) ($_GET['month'] ?? '');
$monthStart = preg_match('/^\d{4}-\d{2}$/', $monthParam) ? strtotime($monthParam . '-01 00:00:00') : false;
if ($monthStart === false) {
$monthStart = strtotime(date('Y-m-01 00:00:00'));
}
$monthEnd = strtotime('+1 month', $monthStart);
$prevMonth = date('Y-m', strtotime('-1 month', $monthStart));
$nextMonth = date('Y-m', $monthEnd);
$monthNames = [1 => 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
$monthLabel = $monthNames[(int) date('n', $monthStart)] . ' ' . date('Y', $monthStart);
// ---- Termine sammeln: [timestamp, type, title, detail, url] ----
$entries = [];
$errors = [];
if ($showRaids) {
try {
foreach (fetch_raids('all') as $raid) {
$time = (int) ($raid['timestamp'] ?? 0);
if ($time < $monthStart || $time >= $monthEnd) {
continue;
}
// Wie der Kader in der Raid-Nachricht: in einer Gruppe, ohne Abgemeldete und offene Premade-Einladungen
$signups = count(array_filter((array) ($raid['signups'] ?? []), static fn ($s): bool
=> (int) ($s['group'] ?? 0) >= 1 && ($s['class'] ?? '') !== 'Ausstehend'));
$max = (int) ($raid['max_slots'] ?? 0);
$archived = !empty($raid['archived']);
$entries[] = [
'time' => $time,
'type' => 'raid',
'title' => (string) ($raid['title'] ?? 'Raid'),
'detail' => $loggedIn ? $signups . ($max > 0 ? ' / ' . $max : '') . ' angemeldet' : '',
'url' => $loggedIn ? '/raids.php' . ($archived ? '?status=archived' : '') . '#raid-' . (int) $raid['raid_id'] : null,
'past' => $time < time(),
];
}
} catch (Throwable $e) {
$errors[] = 'Raids konnten nicht geladen werden.';
}
}
if ($showEvents) {
try {
foreach (fetch_events() as $event) {
$next = (int) ($event['next_run'] ?? 0);
$interval = (int) ($event['interval_seconds'] ?? 0);
if ($next <= 0) {
continue;
}
// Wiederkehrend: vom naechsten Termin an im Intervall (hoechstens 200 im Monat)
$times = [];
if ($interval > 0) {
$first = $next;
if ($first < $monthStart) {
$first += (int) ceil(($monthStart - $first) / $interval) * $interval;
}
for ($t = $first; $t < $monthEnd && count($times) < 200; $t += $interval) {
$times[] = $t;
}
} elseif ($next >= $monthStart && $next < $monthEnd) {
$times[] = $next;
}
$channel = (string) ($event['channel_name'] ?? '');
foreach ($times as $time) {
$entries[] = [
'time' => $time,
'type' => 'event',
'title' => (string) ($event['name'] ?? 'Event'),
'detail' => $loggedIn ? trim(($interval > 0 ? event_interval_label($interval) : 'einmalig') . ($channel !== '' ? ' · #' . $channel : '')) : '',
'url' => $loggedIn ? '/events.php' : null,
'past' => $time < time(),
];
}
}
} catch (Throwable $e) {
$errors[] = 'Events konnten nicht geladen werden.';
}
}
// ---- Termine der Mitglieder ----
if ($showMember) {
try {
// Noch nicht freigegebene sehen nur der Verfasser und die Moderation, interne Termine nur die
// Leitung (auch im oeffentlichen Kalender nicht).
$stmt = db()->prepare(
"SELECT e.*, COALESCE(NULLIF(u.display_name, ''), u.username) AS author, u.avatar_filename, u.username, u.display_name
FROM calendar_entries e JOIN users u ON u.id = e.user_id
WHERE e.starts_at >= ? AND e.starts_at < ? AND u.status = 'active'
AND (e.status = 'visible' OR e.user_id = ? OR ?)
AND (e.audience <> 'internal' OR ? OR e.user_id = ?)
ORDER BY e.starts_at"
);
$stmt->execute([date('Y-m-d H:i:s', $monthStart), date('Y-m-d H:i:s', $monthEnd), $myId, $isModerator ? 1 : 0, $canLead ? 1 : 0, $myId]);
$memberEntries = $stmt->fetchAll();
$participants = [];
if ($loggedIn && $memberEntries) {
$ids = array_map('intval', array_column($memberEntries, 'id'));
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$p = db()->prepare(
"SELECT p.entry_id, u.id, u.username, u.display_name, u.avatar_filename
FROM calendar_participants p JOIN users u ON u.id = p.user_id
WHERE p.entry_id IN ($placeholders) AND u.status = 'active' ORDER BY p.created_at"
);
$p->execute($ids);
foreach ($p->fetchAll() as $row) {
$participants[(int) $row['entry_id']][] = $row;
}
}
$reportedEntries = $loggedIn ? moderation_my_reports('calendar', array_map('intval', array_column($memberEntries, 'id'))) : [];
foreach ($memberEntries as $row) {
$id = (int) $row['id'];
$time = strtotime((string) $row['starts_at']);
$people = $participants[$id] ?? [];
$entries[] = [
'time' => $time,
'type' => 'member',
'title' => (string) $row['title'],
'detail' => $loggedIn ? 'von ' . $row['author'] . ' · ' . count($people) . ' dabei' : '',
'url' => $loggedIn ? '#termin-' . $id : null,
'past' => $time < time(),
'id' => $id,
'row' => $row,
'people' => $people,
'joined' => in_array($myId, array_map('intval', array_column($people, 'id')), true),
'reported' => isset($reportedEntries[$id]),
'audience' => (string) ($row['audience'] ?? 'all'),
];
}
} catch (PDOException $e) {
// Tabellen kommen erst mit dem naechsten Schema-Abgleich
}
}
usort($entries, static fn (array $a, array $b): int => $a['time'] <=> $b['time']);
$byDay = [];
foreach ($entries as $entry) {
$byDay[date('Y-m-d', $entry['time'])][] = $entry;
}
// Raster: volle Wochen von Montag bis Sonntag
$gridStart = strtotime('monday this week', $monthStart);
$gridEnd = strtotime('+1 day', strtotime('sunday this week', $monthEnd - 1));
$weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
$today = date('Y-m-d');
$dayNames = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
/** Treffpunkt auf der Karte: verstecktes Feld + Knopf, der die Karte zum Auswaehlen oeffnet (assets/js/calendar.js). */
$locationField = static function (?array $row): string {
$link = !empty($row['location_path']) ? map_link_parse((string) $row['location_path']) : null;
return '<div class="calendar-location-field" data-location-field>'
. '<span>Treffpunkt auf der Karte <span class="text-muted">(optional)</span></span>'
. '<input type="hidden" name="location" value="' . e($link['path'] ?? '') . '">'
. '<div class="calendar-location-row">'
. '<span class="calendar-location-chosen' . ($link ? ' is-set' : '') . '" data-location-label>' . ($link ? '📍 ' . e(map_link_label($link)) : 'Kein Ort gewählt') . '</span>'
. '<button type="button" class="button-secondary button-small" data-pick-location>🗺️ Ort auf der Karte wählen</button>'
. '<button type="button" class="button-small calendar-location-clear" data-clear-location' . ($link ? '' : ' hidden') . '>Entfernen</button>'
. '</div></div>';
};
/** Nur fuer die Leitung: fuer wen der Termin ist (includes/calendar_audience.php). */
$audienceField = static function (?array $row): string {
$current = (string) ($row['audience'] ?? 'all');
$options = '';
foreach (CALENDAR_AUDIENCES as $value => $label) {
$options .= '<option value="' . e($value) . '"' . ($value === $current ? ' selected' : '') . '>' . e($label) . '</option>';
}
return '<label>Für wen?<select name="audience">' . $options . '</select></label>';
};
/** Formularfelder fuer "Termin eintragen" und "Bearbeiten". */
$entryFields = static function (?array $row) use ($locationField, $audienceField, $canLead): string {
$start = $row ? date('Y-m-d\TH:i', strtotime((string) $row['starts_at'])) : date('Y-m-d\T20:00', strtotime('+1 day'));
$end = $row && $row['ends_at'] ? date('Y-m-d\TH:i', strtotime((string) $row['ends_at'])) : '';
return '<label>Titel<input type="text" name="title" maxlength="100" required placeholder="z.B. Mobs farmen mit Damaskar" value="' . e((string) ($row['title'] ?? '')) . '"></label>'
. '<div class="calendar-form-row">'
. '<label>Beginn<input type="datetime-local" name="starts_at" required value="' . e($start) . '"></label>'
. '<label><span>Ende <span class="text-muted">(optional)</span></span><input type="datetime-local" name="ends_at" value="' . e($end) . '"></label>'
. '</div>'
. '<label><span>Beschreibung <span class="text-muted">(optional)</span></span><textarea name="description" rows="3" maxlength="1000" placeholder="Worum geht es, wo trefft ihr euch, was braucht man?">'
. e((string) ($row['description'] ?? '')) . '</textarea></label>'
. $locationField($row)
. ($canLead ? $audienceField($row) : '');
};
$pageTitle = 'Kalender';
$containerWide = true;
$publicLayout = !$loggedIn;
include __DIR__ . '/includes/header.php';
?>
<div class="panel calendar-panel">
<div class="calendar-head">
<div>
<h1>Kalender</h1>
<p class="text-muted">
<?= $showRaids && $showEvents ? 'Raids und Events' : ($showRaids ? 'Raids' : 'Events') ?> der Legion im Überblick -
dieselben Termine wie im Discord, immer aktuell<?= $showMember ? ', dazu Termine, die Mitglieder selbst eintragen' : '' ?>.
</p>
</div>
<div class="calendar-nav">
<a class="icon-button" href="/calendar.php?month=<?= e($prevMonth) ?>" title="Voriger Monat" aria-label="Voriger Monat">‹</a>
<strong class="calendar-month"><?= e($monthLabel) ?></strong>
<a class="icon-button" href="/calendar.php?month=<?= e($nextMonth) ?>" title="Nächster Monat" aria-label="Nächster Monat">›</a>
<?php if (date('Y-m', $monthStart) !== date('Y-m')): ?>
<a class="button button-secondary button-small" href="/calendar.php">Heute</a>
<?php endif; ?>
</div>
</div>
<?php if ($canCreate): ?>
<details class="calendar-new">
<summary class="button"><?= icon('calendar') ?> + Termin eintragen</summary>
<form method="post" action="/calendar_action.php" class="calendar-form">
<?= csrf_field() ?>
<input type="hidden" name="action" value="create">
<p class="text-muted">Du veranstaltest etwas? Trag es ein - z.B. „Mobs farmen um 20 Uhr mit Damaskar. Macht euch keine Hoffnung auf Loot.“ Andere können sich mit „Bin dabei“ anschließen.</p>
<?= $entryFields(null) ?>
<div class="actions"><button type="submit" class="button-success">Eintragen</button></div>
</form>
</details>
<?php endif; ?>
<div class="calendar-legend">
<?php if ($showRaids): ?><span class="calendar-chip calendar-raid"><?= icon('calendar') ?> Raid</span><?php endif; ?>
<?php if ($showEvents): ?><span class="calendar-chip calendar-event"><?= icon('bell') ?> Event</span><?php endif; ?>
<?php if ($showMember): ?><span class="calendar-chip calendar-member"><?= icon('users') ?> Von Mitgliedern</span><?php endif; ?>
<?php if ($loggedIn && calendar_feed_allowed($me)): ?>
<?php // Kalender-Abo fuer Google, Outlook & Co. richtet jedes Mitglied im Profil ein (includes/calendar_feed.php) ?>
<a class="calendar-feed-link" href="/profile.php#kalender-abo" title="Raids und Termine automatisch in Google Kalender, Outlook oder Apple Kalender"><?= icon('link') ?> In deinem Kalender abonnieren</a>
<?php endif; ?>
</div>
<?php foreach ($errors as $error): ?>
<div class="alert alert-error"><?= e($error) ?> Bitte später erneut versuchen.</div>
<?php endforeach; ?>
<div class="calendar-grid" role="grid" aria-label="<?= e($monthLabel) ?>">
<?php foreach ($weekdays as $weekday): ?>
<div class="calendar-weekday" role="columnheader"><?= $weekday ?></div>
<?php endforeach; ?>
<?php for ($day = $gridStart; $day < $gridEnd; $day = strtotime('+1 day', $day)): ?>
<?php
$key = date('Y-m-d', $day);
$inMonth = $day >= $monthStart && $day < $monthEnd;
$dayEntries = $byDay[$key] ?? [];
?>
<div class="calendar-day<?= $inMonth ? '' : ' is-outside' ?><?= $key === $today ? ' is-today' : '' ?><?= $dayEntries ? ' has-entries' : '' ?>" role="gridcell">
<span class="calendar-date"><?= (int) date('j', $day) ?></span>
<?php if ($dayEntries): ?>
<?php // Alle Termine des Tages - ab dem vierten scrollt die Zelle (der vierte ist angeschnitten zu sehen) ?>
<div class="calendar-day-entries">
<?php foreach ($dayEntries as $entry): ?>
<?php
$tag = $entry['url'] ? 'a' : 'span';
$isInternal = ($entry['audience'] ?? 'all') === 'internal';
?>
<<?= $tag ?> class="calendar-entry calendar-<?= $entry['type'] ?><?= $entry['past'] ? ' is-past' : '' ?>"
<?= $entry['url'] ? 'href="' . e($entry['url']) . '"' : '' ?>
title="<?= e(date('H:i', $entry['time']) . ' Uhr · ' . ($isInternal ? '🔒 ' : '') . $entry['title'] . ($entry['detail'] !== '' ? ' · ' . $entry['detail'] : '')) ?>">
<span class="calendar-time"><?= date('H:i', $entry['time']) ?></span> <?= $isInternal ? '🔒 ' : '' ?><?= e($entry['title']) ?>
</<?= $tag ?>>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($dayEntries): ?>
<a class="calendar-day-link" href="#tag-<?= e($key) ?>" aria-label="Termine am <?= e(date('d.m.', $day)) ?>"></a>
<span class="calendar-dots" aria-hidden="true">
<?php foreach (array_slice($dayEntries, 0, 4) as $entry): ?><i class="calendar-<?= $entry['type'] ?>"></i><?php endforeach; ?>
</span>
<?php endif; ?>
</div>
<?php endfor; ?>
</div>
</div>
<div class="panel">
<h2>Termine im <?= e($monthLabel) ?> <span class="chip-count"><?= count($entries) ?></span></h2>
<?php if (!$entries): ?>
<p class="text-muted">In diesem Monat stehen keine Termine an.</p>
<?php else: ?>
<ol class="calendar-agenda">
<?php foreach ($byDay as $key => $dayEntries): ?>
<?php $dayTime = strtotime($key); ?>
<li id="tag-<?= e($key) ?>" class="calendar-agenda-day<?= $key === $today ? ' is-today' : '' ?><?= $key < $today ? ' is-past' : '' ?>">
<div class="calendar-agenda-date">
<strong><?= date('d.', $dayTime) ?></strong>
<span><?= $key === $today ? 'Heute' : $dayNames[(int) date('w', $dayTime)] ?></span>
</div>
<div class="calendar-agenda-entries">
<?php foreach ($dayEntries as $entry): ?>
<?php if ($entry['type'] === 'member' && $loggedIn): ?>
<?php include __DIR__ . '/includes/calendar_entry.php'; ?>
<?php continue; ?>
<?php endif; ?>
<?php $tag = $entry['url'] ? 'a' : 'div'; ?>
<<?= $tag ?> class="calendar-agenda-entry calendar-<?= $entry['type'] ?>"<?= $entry['url'] ? ' href="' . e($entry['url']) . '"' : '' ?>>
<span class="calendar-time"><?= date('H:i', $entry['time']) ?> Uhr</span>
<span class="calendar-agenda-title"><?= icon(['raid' => 'calendar', 'event' => 'bell', 'member' => 'users'][$entry['type']]) ?> <?= e($entry['title']) ?></span>
<?php if ($entry['detail'] !== ''): ?><span class="text-muted"><?= e($entry['detail']) ?></span><?php endif; ?>
</<?= $tag ?>>
<?php endforeach; ?>
</div>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php if ($canTogglePublic): ?>
<form class="settings-toggle calendar-public-toggle" method="post" action="/admin/settings_action.php">
<?= csrf_field() ?>
<input type="hidden" name="setting" value="calendar_public">
<label>
<input type="checkbox" name="value" value="1" <?= $isPublic ? 'checked' : '' ?> onchange="this.form.submit()">
<span>Kalender öffentlich zeigen - auch ohne Anmeldung sichtbar (nur Titel und Uhrzeit), mit Link auf der Startseite</span>
</label>
<noscript><button type="submit" class="button-secondary button-small">Speichern</button></noscript>
</form>
<?php endif; ?>
</div>
<?php if ($canCreate): ?>
<!-- Ort auswaehlen: die Karte im Fenster, Klick auf einen Ort, "Uebernehmen" -->
<div class="modal-overlay" id="map-pick-modal" hidden>
<div class="map-pick-dialog">
<div class="map-pick-head">
<strong>🗺️ Treffpunkt auswählen</strong>
<span class="text-muted">Karte wählen, auf den Ort klicken, dann „Diesen Ort übernehmen“.</span>
<button type="button" class="modal-close icon-button" data-close-map-pick title="Schließen" aria-label="Schließen"><?= icon('x') ?></button>
</div>
<iframe title="Karte - Ort auswählen" data-map-frame></iframe>
</div>
</div>
<?php endif; ?>
<script src="<?= e(asset_url('/assets/js/calendar.js')) ?>"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>