Files
Lars 2ae48e77fa
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m3s
iCal-Ereignisse mit LAST-MODIFIED statt fehlendem DTSTAMP lesen
2026-10-29 15:53:55 +01:00

245 lines
12 KiB
PHP

<?php
namespace App\Channels\ICal;
use App\Channels\ChannelSyncException;
use App\Channels\ExternalPeriod;
use Carbon\CarbonImmutable;
use Throwable;
/** Complete non-recurring availability snapshots; damaged feeds never become deletions. */
class ICalParser
{
/** @return list<ExternalPeriod> */
public function parse(string $ics): array
{
return array_values(array_filter(array_column($this->parseDocument($ics)['events'], 'period')));
}
/** @return array{events: list<array>, calendar: array} */
public function parseDocument(string $ics): array
{
if (str_starts_with($ics, "\xEF\xBB\xBF")) {
$ics = substr($ics, 3);
}
$ics = preg_replace("/\r?\n[ \t]/", '', $ics);
if (! mb_check_encoding($ics, 'UTF-8') || str_contains($ics, "\0")) {
throw new ChannelSyncException('Kalender enthält ungültige Zeichen.');
}
$lines = explode("\n", str_replace("\r\n", "\n", $ics));
$stack = [];
$calendar = [];
$event = [];
$periods = [];
$properties = [];
$eventLines = [];
$identities = [];
$propertyIdentities = [];
$started = false;
$closed = false;
foreach ($lines as $line) {
$line = rtrim($line, "\r");
if (in_array('VEVENT', $stack, true)) {
$eventLines[] = $line;
}
if ($line === '' && $stack === []) {
continue;
}
if ($closed || ! preg_match('/^((?:[^:"]|"[^"]*")*):(.*)$/D', $line, $match)) {
throw new ChannelSyncException('Kalender ist unvollständig oder enthält ungültige Inhaltszeilen.');
}
$parts = preg_split('/;(?=(?:[^"]*"[^"]*")*[^"]*$)/', $match[1]);
$name = strtoupper(array_shift($parts));
$value = $match[2];
if (! preg_match('/^[A-Z0-9-]+$/D', $name)) {
throw new ChannelSyncException('Ungültige Kalendereigenschaft.');
}
if ($name === 'BEGIN') {
$component = strtoupper($value);
if ($stack === []) {
if ($started || $component !== 'VCALENDAR') {
throw new ChannelSyncException('Die Antwort ist kein vollständiger iCal-Kalender.');
}
$started = true;
} elseif ($component === 'VCALENDAR' || ($component === 'VEVENT' && $stack !== ['VCALENDAR'])) {
throw new ChannelSyncException('Ungültig verschachtelte Kalenderkomponente.');
}
if ($stack === ['VCALENDAR'] && ! in_array($component, ['VEVENT', 'VTIMEZONE'], true)) {
throw new ChannelSyncException('Nicht unterstützte Kalenderkomponente im Belegungsfeed.');
}
if ($component === 'VEVENT') {
$event = [];
$properties = [];
$eventLines = [$line];
}
$stack[] = $component;
continue;
}
if ($name === 'END') {
if ($stack === [] || end($stack) !== strtoupper($value)) {
throw new ChannelSyncException('Kalenderkomponente ist nicht vollständig geschlossen.');
}
if (end($stack) === 'VEVENT') {
$uid = trim($event['UID']['value'] ?? '');
if ($uid === '') {
throw new ChannelSyncException('Ein Kalenderereignis hat keine eindeutige UID.');
}
$period = $this->toPeriod($event);
$identity = $period ? $period->startsOn->toDateString().'|'.$period->endsOn->toDateString() : 'not-occupying';
if (isset($identities[$uid]) && $identities[$uid] !== $identity) {
throw new ChannelSyncException('Eine UID enthält widersprüchliche Ereignisse; bitte den Portalkalender prüfen.');
}
$normalized = $properties;
ksort($normalized);
if (isset($propertyIdentities[$uid]) && $propertyIdentities[$uid] !== $normalized) {
throw new ChannelSyncException('Eine UID enthält widersprüchliche Originalangaben; bitte den Kalender prüfen.');
}
$propertyIdentities[$uid] = $normalized;
if (! isset($identities[$uid])) {
$raw = implode("\r\n", $eventLines)."\r\n";
$enriched = $period === null ? null : new ExternalPeriod($period->uid, $period->startsOn, $period->endsOn, $period->summary, $properties, $raw);
$periods[] = ['uid' => $uid, 'properties' => $properties, 'raw' => $raw, 'period' => $enriched];
}
$identities[$uid] = $identity;
}
array_pop($stack);
if ($stack === []) {
$closed = true;
}
continue;
}
if ($stack === []) {
throw new ChannelSyncException('Inhalt außerhalb des Kalenders.');
}
$property = ['value' => $value, 'params' => $parts];
if ($stack === ['VCALENDAR']) {
if (isset($calendar[$name]) && in_array($name, ['VERSION', 'PRODID', 'METHOD'], true)) {
throw new ChannelSyncException('Doppelte Kalender-Kopfdaten.');
}
$calendar[$name] = $property;
} elseif ($stack === ['VCALENDAR', 'VEVENT']) {
if (isset($event[$name]) && in_array($name, ['UID', 'DTSTART', 'DTEND', 'DTSTAMP', 'LAST-MODIFIED', 'STATUS'], true)) {
throw new ChannelSyncException('Doppelte Identitäts- oder Datumsangaben im Kalenderereignis.');
}
$event[$name] = $property;
}
if (in_array('VEVENT', $stack, true)) {
$prefix = count($stack) > 2 ? implode('.', array_slice($stack, 2)).'.' : '';
$properties[$prefix.$name][] = $property;
}
}
if (! $closed || $stack !== [] || ($calendar['VERSION']['value'] ?? '') !== '2.0' || blank($calendar['PRODID']['value'] ?? null)) {
throw new ChannelSyncException('Kalender ist unvollständig; VERSION, PRODID und geschlossene Komponenten sind erforderlich.');
}
if (isset($calendar['METHOD']) && strtoupper($calendar['METHOD']['value']) !== 'PUBLISH') {
throw new ChannelSyncException('Erwartet wird ein vollständiger Kalenderstand, keine einzelne Kalendernachricht.');
}
return ['events' => $periods, 'calendar' => $calendar];
}
public static function text(string $value): string
{
return preg_replace_callback('/\\\\([nN,;\\\\])/', fn (array $match): string => in_array($match[1], ['n', 'N'], true) ? "\n" : $match[1], $value);
}
/**
* Availability feeds may omit DTSTAMP. Validate event-level LAST-MODIFIED in its place,
* retaining the actual original properties and rejecting an invalid present DTSTAMP.
*
* @param array<string, array{value: string, params: list<string>}> $event
*/
private function toPeriod(array $event): ?ExternalPeriod
{
$stamp = $event['DTSTAMP']['value'] ?? $event['LAST-MODIFIED']['value'] ?? '';
try {
if (! preg_match('/^\d{8}T\d{6}Z$/D', $stamp) || CarbonImmutable::createFromFormat('!Ymd\THis\Z', $stamp, 'UTC')->format('Ymd\THis\Z') !== $stamp) {
throw new \RuntimeException;
}
} catch (Throwable) {
throw new ChannelSyncException('Ein Ereignis benötigt einen gültigen UTC-Zeitstempel (DTSTAMP oder ersatzweise LAST-MODIFIED).');
}
foreach (['RRULE', 'RDATE', 'EXDATE', 'RECURRENCE-ID', 'DURATION'] as $unsupported) {
if (isset($event[$unsupported])) {
throw new ChannelSyncException('Serien oder Dauerangaben werden für diesen Belegungskalender nicht unterstützt.');
}
}
if (strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
return null;
}
if (! isset($event['DTSTART'])) {
throw new ChannelSyncException('Einem Kalenderereignis fehlt die Anreise.');
}
$start = $this->toDate($event['DTSTART']);
if (! isset($event['DTEND']) && ! preg_match('/^\d{8}$/D', $event['DTSTART']['value'])) {
throw new ChannelSyncException('Zeitgebundene Ereignisse benötigen eine ausdrückliche Abreise.');
}
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start->addDay();
if (isset($event['DTEND']) && preg_match('/^\d{8}$/D', $event['DTSTART']['value']) !== preg_match('/^\d{8}$/D', $event['DTEND']['value'])) {
throw new ChannelSyncException('An- und Abreise verwenden verschiedene Datumstypen.');
}
if ($end->lessThanOrEqualTo($start)) {
throw new ChannelSyncException('Ein Kalenderereignis hat keinen positiven Übernachtungszeitraum.');
}
if (strtoupper($event['TRANSP']['value'] ?? '') === 'TRANSPARENT') {
return null;
}
$summary = $event['SUMMARY']['value'] ?? null;
return new ExternalPeriod($event['UID']['value'], $start, $end, $summary === null ? null : self::text($summary));
}
/** @param array{value: string, params: list<string>} $property */
private function toDate(array $property): CarbonImmutable
{
$value = trim($property['value']);
foreach ($property['params'] as $param) {
if (str_starts_with(strtoupper($param), 'VALUE=')) {
$type = strtoupper(trim(substr($param, 6), '"'));
if (! in_array($type, ['DATE', 'DATE-TIME'], true) || ($type === 'DATE') !== (preg_match('/^\d{8}$/D', $value) === 1)) {
throw new ChannelSyncException('Ungültiger Datumswerttyp.');
}
}
if (str_starts_with(strtoupper($param), 'TZID=') && (preg_match('/^\d{8}$/D', $value) || str_ends_with($value, 'Z'))) {
throw new ChannelSyncException('Unzulässige Kombination von Datum und Zeitzone.');
}
}
try {
if (preg_match('/^\d{8}$/D', $value)) {
$date = CarbonImmutable::createFromFormat('!Ymd', $value);
if ($date->format('Ymd') === $value) {
return $date;
}
} elseif (preg_match('/^(\d{8})T(\d{6})(Z?)$/D', $value, $match)) {
$zone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
$date = CarbonImmutable::createFromFormat('!YmdHis', $match[1].$match[2], $zone);
if ($date->format('YmdHis') === $match[1].$match[2]) {
return $date->setTimezone(config('app.timezone'))->startOfDay();
}
}
} catch (Throwable) {
throw new ChannelSyncException('Ungültiges Kalenderdatum oder unbekannte Zeitzone.');
}
throw new ChannelSyncException('Ungültiges Kalenderdatum.');
}
/** @param list<string> $params */
private function timezone(array $params): string
{
foreach ($params as $param) {
if (str_starts_with(strtoupper($param), 'TZID=')) {
$zone = trim(substr($param, 5), '"');
if (! in_array($zone, timezone_identifiers_list(), true)) {
throw new ChannelSyncException('Unbekannte Kalenderzeitzone.');
}
return $zone;
}
}
return config('app.timezone');
}
}