209 lines
9.8 KiB
PHP
209 lines
9.8 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
|
|
{
|
|
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 = [];
|
|
$identities = [];
|
|
$started = false;
|
|
$closed = false;
|
|
foreach ($lines as $line) {
|
|
$line = rtrim($line, "\r");
|
|
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 = [];
|
|
}
|
|
$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.');
|
|
}
|
|
if (! isset($identities[$uid]) && $period !== null) {
|
|
$periods[] = $period;
|
|
}
|
|
$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', 'STATUS'], true)) {
|
|
throw new ChannelSyncException('Doppelte Identitäts- oder Datumsangaben im Kalenderereignis.');
|
|
}
|
|
$event[$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 $periods;
|
|
}
|
|
|
|
/** @param array<string, array{value: string, params: list<string>}> $event */
|
|
private function toPeriod(array $event): ?ExternalPeriod
|
|
{
|
|
$stamp = $event['DTSTAMP']['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).');
|
|
}
|
|
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 : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $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');
|
|
}
|
|
}
|