* * @throws ChannelSyncException */ public function parse(string $ics): array { if (! str_contains($ics, 'BEGIN:VCALENDAR')) { throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.'); } $lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics))); $periods = []; $event = null; foreach ($lines as $line) { $line = rtrim($line, "\r"); if ($line === 'BEGIN:VEVENT') { $event = []; continue; } if ($line === 'END:VEVENT') { if ($event !== null && ($period = $this->toPeriod($event))) { $periods[] = $period; } $event = null; continue; } if ($event !== null && str_contains($line, ':')) { [$nameWithParams, $value] = explode(':', $line, 2); $parts = explode(';', $nameWithParams); $event[strtoupper($parts[0])] = ['value' => $value, 'params' => array_slice($parts, 1)]; } } return $periods; } /** * @param array}> $event */ private function toPeriod(array $event): ?ExternalPeriod { if (! isset($event['DTSTART']) || strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') { return null; } $start = $this->toDate($event['DTSTART']); $end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay(); if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) { return null; } $uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString()); return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null)); } /** * @param array{value: string, params: list} $property */ private function toDate(array $property): ?CarbonImmutable { $value = trim($property['value']); if (preg_match('/^\d{8}$/', $value)) { return CarbonImmutable::createFromFormat('!Ymd', $value); } if (preg_match('/^(\d{8})T(\d{6})(Z?)$/', $value, $match)) { $timezone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']); return CarbonImmutable::createFromFormat('YmdHis', $match[1].$match[2], $timezone) ->setTimezone(config('app.timezone')) ->startOfDay(); } return null; } /** * @param list $params */ private function timezone(array $params): string { foreach ($params as $param) { if (str_starts_with(strtoupper($param), 'TZID=')) { $tz = trim(substr($param, 5), '"'); return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone'); } } return config('app.timezone'); } private function unescape(?string $text): ?string { return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text); } }