1: <?php
2: declare(strict_types=1);
3:
4: namespace om\ICal;
5:
6: use DateInterval;
7: use DateTimeInterface;
8: use Generator;
9: use om\ICal\Exception\ResourceLimitException;
10: use om\ICal\Value\CalAddress;
11: use om\ICal\Value\Conference;
12: use om\ICal\Value\DateTimeValue;
13: use om\ICal\Value\Image;
14: use om\ICal\Value\Link;
15: use om\ICal\Value\Relation;
16: use om\ICal\Value\ValueParser;
17: use om\RRule\RecurrenceSet;
18: use om\RRule\Rule;
19:
20: /**
21: * Common part of events, tasks, journal entries and free/busy components.
22: *
23: * All properties stay available through property(); getters return typed values.
24: * A recurring item knows its overrides (components with the same UID and a RECURRENCE-ID),
25: * so occurrencesBetween() returns the complete series.
26: */
27: abstract class Item {
28: /** @var array<string, mixed> typed values already converted (the component is immutable) */
29: private array $memo = [];
30: /**
31: * @param list<Item> $overrides
32: * @internal use Calendar::events() and similar methods
33: */
34: public function __construct(
35: public readonly Component $component,
36: protected readonly Calendar $calendar,
37: private readonly array $overrides = [],
38: ) {
39: }
40:
41: /**
42: * Duration of one occurrence.
43: */
44: abstract public function duration(): DateInterval;
45:
46: /**
47: * End of the (first) occurrence.
48: */
49: public function end(): ?DateTimeValue {
50: return $this->start()?->add($this->duration());
51: }
52:
53: public function property(string $name): ?Property {
54: return $this->component->property($name);
55: }
56:
57: /**
58: * @return list<Property>
59: */
60: public function properties(string $name): array {
61: return $this->component->properties($name);
62: }
63:
64: /**
65: * Typed value of the first property with the name, see ValueParser::value().
66: */
67: public function value(string $name): mixed {
68: $property = $this->property($name);
69: return $property === null ? null : $this->calendar->values()->value($property);
70: }
71:
72: public function calendar(): Calendar {
73: return $this->calendar;
74: }
75:
76: public function uid(): ?string {
77: return $this->text('UID');
78: }
79:
80: public function summary(): ?string {
81: return $this->text('SUMMARY');
82: }
83:
84: public function description(): ?string {
85: return $this->text('DESCRIPTION');
86: }
87:
88: /**
89: * LOCATION text; see locations() for VLOCATION components.
90: */
91: public function location(): ?string {
92: return $this->text('LOCATION');
93: }
94:
95: /**
96: * VLOCATION components (RFC 9073).
97: *
98: * @return list<Location>
99: */
100: public function locations(): array {
101: return array_map(fn(Component $component): Location => new Location($component, $this->calendar), $this->component->components('VLOCATION'));
102: }
103:
104: /**
105: * STATUS in upper case, e.g. CONFIRMED, TENTATIVE, CANCELLED, NEEDS-ACTION, COMPLETED.
106: */
107: public function status(): ?string {
108: $status = $this->text('STATUS');
109: return $status === null ? null : strtoupper($status);
110: }
111:
112: public function isCancelled(): bool {
113: return $this->remember('cancelled', fn() => $this->status() === 'CANCELLED');
114: }
115:
116: /**
117: * CLASS: PUBLIC (default), PRIVATE or CONFIDENTIAL.
118: */
119: public function classification(): string {
120: return strtoupper($this->text('CLASS') ?? 'PUBLIC');
121: }
122:
123: public function url(): ?string {
124: return $this->property('URL')?->value;
125: }
126:
127: public function sequence(): int {
128: return $this->integer('SEQUENCE') ?? 0;
129: }
130:
131: public function priority(): ?int {
132: return $this->integer('PRIORITY');
133: }
134:
135: /**
136: * @return list<string>
137: */
138: public function categories(): array {
139: $categories = [];
140: foreach ($this->properties('CATEGORIES') as $property) {
141: array_push($categories, ...$this->calendar->values()->texts($property));
142: }
143: return $categories;
144: }
145:
146: /**
147: * COLOR (RFC 7986): a CSS3 color name.
148: */
149: public function color(): ?string {
150: return $this->text('COLOR');
151: }
152:
153: /**
154: * IMAGE properties (RFC 7986); images with invalid binary data are skipped.
155: *
156: * @return list<Image>
157: */
158: public function images(): array {
159: return array_values(array_filter(array_map($this->calendar->values()->image(...), $this->properties('IMAGE'))));
160: }
161:
162: /**
163: * CONFERENCE properties (RFC 7986).
164: *
165: * @return list<Conference>
166: */
167: public function conferences(): array {
168: return array_map(fn(Property $property): Conference => new Conference($this->calendar->values()->uri($property), $property->parameters), $this->properties('CONFERENCE'));
169: }
170:
171: /**
172: * LINK properties (RFC 9253).
173: *
174: * @return list<Link>
175: */
176: public function links(): array {
177: return array_map(fn(Property $property): Link => new Link($this->reference($property), $property->parameters), $this->properties('LINK'));
178: }
179:
180: /**
181: * RELATED-TO properties with the relation types and GAP of RFC 9253.
182: *
183: * @return list<Relation>
184: */
185: public function relatedTo(): array {
186: return array_map(fn(Property $property): Relation => new Relation($this->reference($property), $property->parameters), $this->properties('RELATED-TO'));
187: }
188:
189: public function created(): ?DateTimeValue {
190: return $this->date('CREATED');
191: }
192:
193: public function lastModified(): ?DateTimeValue {
194: return $this->date('LAST-MODIFIED');
195: }
196:
197: public function stamp(): ?DateTimeValue {
198: return $this->date('DTSTAMP');
199: }
200:
201: public function organizer(): ?CalAddress {
202: $property = $this->property('ORGANIZER');
203: return $property === null ? null : $this->calendar->values()->calAddress($property);
204: }
205:
206: /**
207: * @return list<CalAddress>
208: */
209: public function attendees(): array {
210: return array_map(fn(Property $property): CalAddress => $this->calendar->values()->calAddress($property), $this->properties('ATTENDEE'));
211: }
212:
213: public function start(): ?DateTimeValue {
214: return $this->remember('start', fn() => $this->date('DTSTART'));
215: }
216:
217: public function isAllDay(): bool {
218: return $this->start()?->isDate() ?? false;
219: }
220:
221: /**
222: * @return list<Alarm>
223: */
224: public function alarms(): array {
225: return array_map(fn(Component $component): Alarm => new Alarm($component, $this->calendar), $this->component->components('VALARM'));
226: }
227:
228: public function recurrenceRule(): ?Rule {
229: return $this->recurrenceRules()[0] ?? null;
230: }
231:
232: /**
233: * All valid RRULE properties; several rules are combined (RFC 2445 allowed that).
234: *
235: * @return list<Rule>
236: */
237: public function recurrenceRules(): array {
238: $rules = [];
239: foreach ($this->properties('RRULE') as $property) {
240: if (($rule = $this->calendar->values()->recur($property)) !== null) {
241: $rules[] = $rule;
242: }
243: }
244: return $rules;
245: }
246:
247: /**
248: * RDATE values.
249: *
250: * @return list<DateTimeValue>
251: */
252: public function recurrenceDates(): array {
253: return $this->dates('RDATE');
254: }
255:
256: /**
257: * EXDATE values.
258: *
259: * @return list<DateTimeValue>
260: */
261: public function exceptionDates(): array {
262: return $this->dates('EXDATE');
263: }
264:
265: public function isRecurring(): bool {
266: return $this->has('RRULE') || $this->has('RDATE');
267: }
268:
269: public function recurrenceId(): ?DateTimeValue {
270: return $this->remember('recurrenceId', fn() => $this->date('RECURRENCE-ID'));
271: }
272:
273: /**
274: * True for a component modifying an instance of a recurring item (it has a RECURRENCE-ID).
275: */
276: public function isOverride(): bool {
277: return $this->has('RECURRENCE-ID');
278: }
279:
280: /**
281: * RANGE=THISANDFUTURE: the override applies to its instance and all later ones.
282: */
283: public function isThisAndFuture(): bool {
284: return strtoupper($this->property('RECURRENCE-ID')?->parameter('RANGE') ?? '') === 'THISANDFUTURE';
285: }
286:
287: /**
288: * Components modifying instances of this recurring item, in the order of the calendar.
289: *
290: * Of several revisions of one instance, only the current one is returned (see currentRevisions()).
291: *
292: * @return list<Item>
293: */
294: public function overrides(): array {
295: return $this->remember('overrides', fn(): array => self::currentRevisions($this->overrides, $this->start()));
296: }
297:
298: /**
299: * Overrides without their superseded revisions: of several with the same RECURRENCE-ID and RANGE,
300: * the one with the highest SEQUENCE (RFC 5545, section 3.8.7.4) is kept, the later one when they are equal.
301: *
302: * @param list<Item> $overrides of one UID
303: * @param ?DateTimeValue $start DTSTART of the recurring item, the first RECURRENCE-ID without it
304: * @return list<Item>
305: * @internal used by Calendar
306: */
307: public static function currentRevisions(array $overrides, ?DateTimeValue $start = null): array {
308: if (count($overrides) < 2) {
309: return $overrides;
310: }
311: $current = $superseded = [];
312: $space = null;
313: foreach ($overrides as $index => $override) {
314: $id = $override->recurrenceId();
315: if ($id === null) {
316: continue;
317: }
318: $start ??= $id;
319: $space ??= new TimeSpace($start);
320: // the instance is matched as by the expansion: an instant, or a day for a date in a timed series
321: $key = ($override->isThisAndFuture() ? 'range ' : '')
322: . ($id->isDate() && !$start->isDate() ? 'day ' . $id->format('Ymd') : 'at ' . $space->toBase($id));
323: if (isset($current[$key])) {
324: $loser = $override->sequence() >= $overrides[$current[$key]]->sequence() ? $current[$key] : $index;
325: $superseded[$loser] = true;
326: if ($loser === $index) {
327: continue;
328: }
329: }
330: $current[$key] = $index;
331: }
332: return $superseded === [] ? $overrides : array_values(array_diff_key($overrides, $superseded));
333: }
334:
335: /**
336: * Occurrences overlapping [$from, $to), in chronological order.
337: *
338: * Dates and floating times are compared with the local time of $from and $to.
339: * Cancelled instances (STATUS:CANCELLED overrides) are skipped unless requested.
340: *
341: * @return Generator<int, Occurrence>
342: */
343: public function occurrencesBetween(DateTimeInterface $from, DateTimeInterface $to, bool $includeCancelled = false): Generator {
344: return $this->expand($from, $to, $includeCancelled, PHP_INT_MAX);
345: }
346:
347: /**
348: * The first occurrences, optionally from the given moment.
349: *
350: * @return Generator<int, Occurrence>
351: */
352: public function occurrences(int $limit = 1000, ?DateTimeInterface $from = null, bool $includeCancelled = false): Generator {
353: return $this->expand($from, null, $includeCancelled, $limit);
354: }
355:
356: /**
357: * @return Generator<int, Occurrence>
358: */
359: private function expand(?DateTimeInterface $from, ?DateTimeInterface $to, bool $includeCancelled, int $limit): Generator {
360: $start = $this->start();
361: if ($start === null || $limit < 1) {
362: return;
363: }
364: $space = new TimeSpace($start);
365: $fromTs = $from === null ? null : $space->window($from);
366: $toTs = $to === null ? null : $space->window($to);
367:
368: // a single item without overrides; with overrides it is a recurrence set of DTSTART alone
369: if (!$this->isRecurring() && $this->overrides === []) {
370: $occurrence = new Occurrence($start, $start->add($this->duration()), $this, $this);
371: if (($includeCancelled || !$this->isCancelled()) && $space->overlaps($occurrence, $fromTs, $toTs)) {
372: yield $occurrence;
373: }
374: return;
375: }
376:
377: // overrides: single ones replace their instance, RANGE=THISANDFUTURE ones also change later instances
378: $singles = $replaced = $replacedDays = $ranges = [];
379: $earliest = 0; // the largest shift of a range to an earlier time, in seconds
380: foreach ($this->overrides() as $override) {
381: $id = $override->recurrenceId();
382: if ($id === null) {
383: continue;
384: }
385: $overrideStart = $override->start();
386: $durationOf = $overrideStart === null ? $this : $override; // without DTSTART the instance keeps its time and length
387: if ($override->isThisAndFuture()) {
388: // the shift of the local time in the timezone of the series (RECURRENCE-ID may be in UTC)
389: $shift = $overrideStart === null ? 0 : $this->localTime($space, $overrideStart) - $this->localTime($space, $id);
390: $ranges[$space->toBase($id)] = [$override, $shift, $durationOf];
391: $earliest = max($earliest, -$shift);
392: continue;
393: }
394: $id->isDate() && !$start->isDate() ? $replacedDays[$id->format('Ymd')] = true : $replaced[$space->toBase($id)] = true;
395: $overrideStart ??= $space->fromBase($space->toBase($id));
396: $occurrence = new Occurrence($overrideStart, $overrideStart->add($durationOf->duration()), $override, $this, $id);
397: if (($includeCancelled || !$override->isCancelled()) && $space->overlaps($occurrence, $fromTs, $toTs)) {
398: $singles[] = $occurrence;
399: }
400: }
401: ksort($ranges);
402: // an instance may move into the window from its end (DST changes add at most a few hours)
403: $slack = $earliest === 0 ? 0 : $earliest + 7200;
404:
405: $exdays = $exdates = [];
406: foreach ($this->exceptionDates() as $date) {
407: if ($date->isDate() && !$start->isDate()) {
408: $exdays[] = $date->format('Ymd');
409: } else {
410: $exdates[] = $space->toBase($date);
411: }
412: }
413: $limits = $this->calendar->recurrenceLimits();
414: $set = new RecurrenceSet(
415: $space->start(),
416: // a rule of another calendar system (RFC 7529) is not expanded, the item keeps DTSTART and RDATE
417: array_values(array_filter($this->recurrenceRules(), static fn(Rule $rule): bool => $rule->isGregorian())),
418: rdates: array_map($space->toBase(...), $this->recurrenceDates()),
419: exdates: $exdates,
420: exdays: $exdays,
421: until: $toTs === null ? null : $toTs - 1 + $slack,
422: maxIterations: $limits->maxIterations,
423: );
424:
425: // occurrences are buffered while a later instance may still move before them
426: $buffer = new OccurrenceBuffer($space, $singles);
427: $count = 0;
428: foreach ($set as $timestamp) {
429: if ($toTs !== null && $timestamp >= $toTs + $slack) {
430: break;
431: }
432: $id = $space->fromBase($timestamp);
433: if (!isset($replaced[$timestamp]) && ($replacedDays === [] || !isset($replacedDays[$id->format('Ymd')]))) {
434: [$item, $occurrenceStart, $durationOf] = [$this, $id, $this];
435: foreach ($ranges as $rangeId => [$range, $shift, $rangeDuration]) {
436: if ($rangeId > $timestamp) {
437: break;
438: }
439: [$item, $occurrenceStart, $durationOf] = [$range, $space->shift($id, $shift), $rangeDuration];
440: }
441: $occurrence = new Occurrence($occurrenceStart, $occurrenceStart->add($durationOf->duration()), $item, $this, $id);
442: if (($includeCancelled || !$item->isCancelled()) && $space->overlaps($occurrence, $fromTs, $toTs)) {
443: $buffer->add($occurrence);
444: }
445: }
446: foreach ($buffer->ready($timestamp - $slack) as $occurrence) {
447: yield $occurrence;
448: if (++$count >= $limit) {
449: return;
450: }
451: if ($count > $limits->maxInstances) {
452: throw ResourceLimitException::create('recurrence.limit', "Recurrence occurrence limit of {$limits->maxInstances} exceeded.");
453: }
454: }
455: }
456: foreach ($buffer->ready(PHP_INT_MAX) as $occurrence) {
457: yield $occurrence;
458: if (++$count >= $limit) {
459: return;
460: }
461: if ($count > $limits->maxInstances) {
462: throw ResourceLimitException::create('recurrence.limit', "Recurrence occurrence limit of {$limits->maxInstances} exceeded.");
463: }
464: }
465: }
466:
467: private function localTime(TimeSpace $space, DateTimeValue $value): int {
468: return $space->fromBase($space->toBase($value))->wallClockAsUtc()->getTimestamp();
469: }
470:
471: /**
472: * @template T
473: * @param callable(): T $calculate
474: * @return T
475: */
476: protected function remember(string $key, callable $calculate): mixed {
477: if (!array_key_exists($key, $this->memo)) {
478: $this->memo[$key] = $calculate();
479: }
480: return $this->memo[$key];
481: }
482:
483: protected function has(string $name): bool {
484: return $this->component->has($name);
485: }
486:
487: protected function text(string $name): ?string {
488: $property = $this->property($name);
489: return $property === null ? null : $this->calendar->values()->text($property);
490: }
491:
492: /**
493: * A URI or an XML reference, otherwise a UID or text (LINK and RELATED-TO of RFC 9253).
494: */
495: private function reference(Property $property): string {
496: $values = $this->calendar->values();
497: return in_array(ValueParser::type($property), ['URI', 'XML-REFERENCE'], true) ? $values->uri($property) : $values->text($property);
498: }
499:
500: protected function integer(string $name): ?int {
501: $property = $this->property($name);
502: return $property === null ? null : $this->calendar->values()->integer($property);
503: }
504:
505: protected function date(string $name): ?DateTimeValue {
506: $property = $this->property($name);
507: return $property === null ? null : $this->calendar->values()->dateTime($property);
508: }
509:
510: /**
511: * @return list<DateTimeValue>
512: */
513: protected function dates(string $name): array {
514: $dates = [];
515: foreach ($this->properties($name) as $property) {
516: array_push($dates, ...$this->calendar->values()->dateTimes($property));
517: }
518: return $dates;
519: }
520:
521: /**
522: * Duration from DTSTART to DTEND (or DUE): the exact elapsed time for UTC and zoned values,
523: * the wall-clock difference for dates and floating times (RFC 5545, section 3.8.5.3).
524: */
525: protected static function between(DateTimeValue $start, DateTimeValue $end): DateInterval {
526: if ($start->isDate() || $start->isFloating()) {
527: return $start->wallClockAsUtc()->diff($end->wallClockAsUtc());
528: }
529: $seconds = $end->toDateTime(null, $start->timezone())->getTimestamp() - $start->toDateTime()->getTimestamp();
530: // hours, minutes and seconds are elapsed time, days would keep the local time instead
531: $absolute = abs($seconds);
532: $interval = new DateInterval(sprintf('PT%dH%dM%dS', intdiv($absolute, 3600), intdiv($absolute % 3600, 60), $absolute % 60));
533: $interval->invert = $seconds < 0 ? 1 : 0;
534: return $interval;
535: }
536: }
537: