Repository navigation
Expand file tree
/
Copy pathclass.baserecurrence.php
More file actions
2119 lines (1786 loc) · 69.4 KB
/
Copy pathclass.baserecurrence.php
File metadata and controls
2119 lines (1786 loc) · 69.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* SPDX-License-Identifier: AGPL-3.0-only
* SPDX-FileCopyrightText: Copyright 2005-2016 Zarafa Deutschland GmbH
* SPDX-FileCopyrightText: Copyright 2020-2026 grommunio GmbH
*/
/**
* BaseRecurrence
* this class is superclass for recurrence for appointments and tasks. This class provides all
* basic features of recurrence.
*/
abstract class BaseRecurrence {
/**
* @var mixed Mapi Message (may be null if readonly)
*/
public $message;
/**
* @var array Message Properties
*/
public $messageprops;
/**
* @var array list of property tags
*/
public $proptags;
/**
* @var mixed recurrence data of this calendar item
*/
public $recur;
/**
* @var mixed Timezone data of this calendar item
*/
public $tz;
/**
* @var array Cache for gmtime() results keyed by timestamp.
*/
private array $gmtimeCache = [];
/**
* @var array Cache for daysInMonth() results keyed by "date:months".
*/
private array $daysInMonthCache = [];
/**
* @var array Cache for DST boundaries keyed by tm_year and the DST rules.
*/
private array $dstBoundaryCache = [];
/**
* var int First day of week set by the user (default: 1 - Monday)
*/
private int $firstDayOfWeek = 1;
/**
* Constructor.
*
* @param resource $store MAPI Message Store Object
* @param mixed $message the MAPI (appointment) message
*/
public function __construct(public $store, mixed $message) {
if (is_array($message)) {
$this->messageprops = $message;
}
else {
$this->message = $message;
$this->messageprops = mapi_getprops($this->message, $this->proptags);
}
if (isset($this->messageprops[$this->proptags["recurring_data"]])) {
// There is a possibility that recurr blob can be more than 255 bytes so get full blob through stream interface
if (strlen((string) $this->messageprops[$this->proptags["recurring_data"]]) >= 255) {
$this->getFullRecurrenceBlob();
}
$this->recur = $this->parseRecurrence($this->messageprops[$this->proptags["recurring_data"]]);
}
if (isset($this->proptags["timezone_data"], $this->messageprops[$this->proptags["timezone_data"]])) {
$this->tz = $this->parseTimezone($this->messageprops[$this->proptags["timezone_data"]]);
}
// Get the first day of week from the user's settings, fallback to 1 (Monday)
// if it is not explicitely set.
$websettings = readMapiProp($store, PR_EC_WEBACCESS_SETTINGS_JSON, mapi_getprops($store, [PR_EC_WEBACCESS_SETTINGS_JSON]));
if (!empty($websettings)) {
$settings = json_decode($websettings, true);
$this->firstDayOfWeek = $settings['settings']['grommunio']['v1']['main']['week_start'] ?? 1;
}
}
public function getRecurrence(): ?array {
return $this->recur;
}
public function getFullRecurrenceBlob(): void {
$message = mapi_msgstore_openentry($this->store, $this->messageprops[PR_ENTRYID]);
$recurrBlob = '';
$stream = mapi_openproperty($message, $this->proptags["recurring_data"], IID_IStream, 0, 0);
$stat = mapi_stream_stat($stream);
for ($i = 0; $i < $stat['cb']; $i += 1024) {
$recurrBlob .= mapi_stream_read($stream, 1024);
}
if (!empty($recurrBlob)) {
$this->messageprops[$this->proptags["recurring_data"]] = $recurrBlob;
}
}
/**
* Function for parsing the Recurrence value of a Calendar item.
*
* Retrieve it from Named Property 0x8216 as a PT_BINARY and pass the
* data to this function
*
* Returns a structure containing the data:
*
* type - type of recurrence: day=10, week=11, month=12, year=13
* subtype - type of day recurrence: 2=monthday (ie 21st day of month), 3=nday'th weekdays (ie. 2nd Tuesday and Wednesday)
* start - unix timestamp of first occurrence
* end - unix timestamp of last occurrence (up to and including), so when start == end -> occurrences = 1
* numoccur - occurrences (may be very large when there is no end data)
* first_dow - first day-of-week for weekly recurrences (0 = Sunday, 1 = Monday, ...)
*
* then, for each type:
*
* Daily:
* everyn - every [everyn] days in minutes
* regen - regenerating event (like tasks)
*
* Weekly:
* everyn - every [everyn] weeks in weeks
* regen - regenerating event (like tasks)
* weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
*
* Monthly:
* everyn - every [everyn] months
* regen - regenerating event (like tasks)
*
* subtype 2:
* monthday - on day [monthday] of the month
*
* subtype 3:
* weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
* nday - on [nday]'th [weekdays] of the month
*
* Yearly:
* everyn - every [everyn] months (12, 24, 36, ...)
* month - in month [month] (although the month is encoded in minutes since the startning of the year ........)
* regen - regenerating event (like tasks)
*
* subtype 2:
* monthday - on day [monthday] of the month
*
* subtype 3:
* weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
* nday - on [nday]'th [weekdays] of the month [month]
*
* @param string $rdata Binary string
*
* @return null|(((false|int|mixed|string)[]|int)[]|int|mixed)[] recurrence data
*
* @psalm-return array{changed_occurrences: array<int, array{basedate: false|int, start: int, end: int, bitmask: mixed, subject?: false|string, remind_before?: mixed, reminder_set?: mixed, location?: false|string, busystatus?: mixed, alldayevent?: mixed, label?: mixed, ex_start_datetime?: mixed, ex_end_datetime?: mixed, ex_orig_date?: mixed}>, deleted_occurrences: list<int>, type?: int|mixed, subtype?: mixed, month?: mixed, everyn?: mixed, regen?: mixed, monthday?: mixed, weekdays?: 0|mixed, nday?: mixed, term?: int|mixed, numoccur?: mixed, numexcept?: mixed, first_dow?: mixed, numexceptmod?: mixed, start?: int, end?: int, startocc?: mixed, endocc?: mixed}|null
*/
public function parseRecurrence(string $rdata): ?array {
if (strlen($rdata) < 10) {
return null;
}
$ret = [];
$ret["changed_occurrences"] = [];
$ret["deleted_occurrences"] = [];
$data = unpack("vReaderVersion/vWriterVersion/vrtype/vrtype2/vCalendarType", $rdata);
// Do some recurrence validity checks
if ($data['ReaderVersion'] != 0x3004 || $data['WriterVersion'] != 0x3004) {
return $ret;
}
if (!in_array($data["rtype"], [IDC_RCEV_PAT_ORB_DAILY, IDC_RCEV_PAT_ORB_WEEKLY, IDC_RCEV_PAT_ORB_MONTHLY, IDC_RCEV_PAT_ORB_YEARLY], true)) {
return $ret;
}
if (!in_array($data["rtype2"], [rptDay, rptWeek, rptMonth, rptMonthNth, rptMonthEnd, rptHjMonth, rptHjMonthNth, rptHjMonthEnd], true)) {
return $ret;
}
if (!in_array($data['CalendarType'], [MAPI_CAL_DEFAULT, MAPI_CAL_GREGORIAN], true)) {
return $ret;
}
$ret["type"] = (int) $data["rtype"] > 0x2000 ? (int) $data["rtype"] - 0x2000 : $data["rtype"];
$ret["subtype"] = $data["rtype2"];
$blob = $rdata;
$rdata = substr($rdata, 10);
$valid = match ($data["rtype"]) {
IDC_RCEV_PAT_ORB_DAILY => $this->parseDailyPattern($rdata, $ret),
IDC_RCEV_PAT_ORB_WEEKLY => $this->parseWeeklyPattern($rdata, $ret),
default => $this->parseMonthlyPattern(
$rdata,
$ret,
$data["rtype"] == IDC_RCEV_PAT_ORB_YEARLY
),
};
if (!$valid) {
return $ret;
}
$exc_base_dates = $this->parseRecurrenceRange($rdata, $ret);
if ($exc_base_dates === null) {
return $ret;
}
// the exception section is read from the original blob; drop the
// pattern tail so only one copy of the blob is alive during the walk
$offset = strlen($blob) - strlen($rdata);
unset($rdata);
$this->parseAppointmentRecurrence($blob, $ret, $exc_base_dates, $offset);
return $ret;
}
private function parseAppointmentRecurrence(string $rdata, array &$ret, array $exc_base_dates, int $offset): void {
$length = strlen($rdata);
// this is where task recurrence stop
if ($length - $offset < 16) {
return;
}
$data = unpack("Vreaderversion/Vwriterversion/Vstartmin/Vendmin", $rdata, $offset);
// the exception records are read in place; $offset walks the blob
$offset += 16;
$ret["startocc"] = $data["startmin"];
$ret["endocc"] = $data["endmin"];
$writerversion = $data["writerversion"];
// base dates without an exception record are deleted occurrences
$ret["deleted_occurrences"] = $exc_base_dates;
if ($length - $offset < 2) {
return;
}
$nexceptions = unpack("vnumber", $rdata, $offset)["number"];
$offset += 2;
if ($nexceptions === 0) {
return;
}
$exc_changed_details = [];
for ($i = 0; $i < $nexceptions; ++$i) {
$item = $this->parseRecurrenceException($rdata, $offset);
if ($item === null) {
break;
}
$exc_changed_details[] = $item;
}
// Base dates without a modified exception represent deletions.
$changed_dates = array_fill_keys(array_column($exc_changed_details, "basedate"), true);
$ret["deleted_occurrences"] = array_values(array_filter(
$exc_base_dates,
static fn ($date) => !isset($changed_dates[$date])
));
$ret["changed_occurrences"] = $exc_changed_details;
// enough data for normal exception (no extended data); a cut record has none
if (count($exc_changed_details) < $nexceptions || $length - $offset < 8) {
return;
}
if (!$this->skipRecurrenceBlock($rdata, $offset)) {
return;
}
for ($i = 0; $i < $nexceptions; ++$i) {
$item = $this->parseExtendedException(
$rdata,
$offset,
$exc_changed_details[$i],
$writerversion
);
if ($item === null) {
break;
}
$exc_changed_details[$i] = $item;
}
// update with extended data
$ret["changed_occurrences"] = $exc_changed_details;
}
private function parseDailyPattern(string &$rdata, array &$ret): bool {
if (strlen($rdata) < 12) {
return false;
}
$data = unpack("Vunknown/Veveryn/Vregen", $rdata);
if ($data["everyn"] > 1438560) { // minutes for 999 days
return false;
}
$ret["everyn"] = $data["everyn"];
$ret["regen"] = $data["regen"];
switch ($ret["subtype"]) {
case rptDay:
$rdata = substr($rdata, 12);
break;
case rptWeek:
$rdata = substr($rdata, 16);
break;
}
return true;
}
private function parseWeeklyPattern(string &$rdata, array &$ret): bool {
if (strlen($rdata) < 16) {
return false;
}
$data = unpack("Vconst1/Veveryn/Vregen", $rdata);
if ($data["everyn"] > 99) {
return false;
}
$rdata = substr($rdata, 12);
$ret["everyn"] = $data["everyn"];
$ret["regen"] = $data["regen"];
$ret["weekdays"] = 0;
if ($data["regen"] == 0) {
$data = unpack("Vweekdays", $rdata);
$rdata = substr($rdata, 4);
$ret["weekdays"] = $data["weekdays"];
}
return true;
}
private function parseMonthlyPattern(string &$rdata, array &$ret, bool $yearly): bool {
if (strlen($rdata) < 16) {
return false;
}
$data = unpack("Vmonth/Veveryn/Vregen/Vmonthday", $rdata);
if ($yearly) {
// recurring yearly tasks and events have a period in months multiple by 12
if ($data["everyn"] % 12 != 0) {
return false;
}
$ret["month"] = $data["month"];
$ret["everyn"] = $data["everyn"] / 12;
}
else {
if ($data["everyn"] > 99) {
return false;
}
$ret["everyn"] = $data["everyn"];
}
$ret["regen"] = $data["regen"];
$rdata = substr($rdata, 16);
if ($ret["subtype"] != rptMonthNth) {
$ret["monthday"] = $data["monthday"];
return true;
}
$ret["weekdays"] = $data["monthday"];
if (strlen($rdata) < 4) {
return false;
}
$data = unpack("Vnday", $rdata);
// Sanity check for valid values (and opportunistically try to fix)
if ($data["nday"] == 0xFFFFFFFF || $data["nday"] == -1) {
$data["nday"] = 5;
}
elseif ($data["nday"] < 0 || $data["nday"] > 5) {
$data["nday"] = 0;
}
$ret["nday"] = $data["nday"];
$rdata = substr($rdata, 4);
return true;
}
private function parseRecurrenceRange(string &$rdata, array &$ret): ?array {
if (strlen($rdata) < 16) {
return null;
}
$data = unpack("Vterm/Vnumoccur/Vconst2/Vnumexcept", $rdata);
$rdata = substr($rdata, 16);
if (!in_array($data["term"], [IDC_RCEV_PAT_ERB_END, IDC_RCEV_PAT_ERB_AFTERNOCCUR, IDC_RCEV_PAT_ERB_NOEND, 0xFFFFFFFF], true)) {
return null;
}
$ret["term"] = (int) $data["term"] > 0x2000 ? (int) $data["term"] - 0x2000 : $data["term"];
$ret["numoccur"] = $data["numoccur"];
$ret["first_dow"] = $data["const2"];
$ret["numexcept"] = $data["numexcept"];
// exc_base_dates are *all* the base dates that have been either deleted or modified
$exc_base_dates = $this->parseRecurrenceDates($rdata, $ret["numexcept"]);
if ($exc_base_dates === null) {
return null;
}
if (strlen($rdata) < 4) {
return null;
}
$data = unpack("Vnumexceptmod", $rdata);
$rdata = substr($rdata, 4);
$ret["numexceptmod"] = $data["numexceptmod"];
// exc_changed are the base dates of *modified* occurrences. exactly what is modified
if ($this->parseRecurrenceDates($rdata, $ret["numexceptmod"]) === null) {
return null;
}
if (strlen($rdata) < 8) {
return null;
}
$data = unpack("Vstart/Vend", $rdata);
$rdata = substr($rdata, 8);
$ret["start"] = $this->recurDataToUnixData($data["start"]);
$ret["end"] = $this->recurDataToUnixData($data["end"]);
return $exc_base_dates;
}
private function parseRecurrenceDates(string &$rdata, int $count): ?array {
if ($count === 0) {
return [];
}
if ($count > intdiv(strlen($rdata), 4)) {
return null;
}
$dates = [];
for ($offset = 0; $offset < $count; $offset += 256) {
$length = min(256, $count - $offset);
foreach (unpack("V{$length}", $rdata, $offset * 4) as $value) {
$dates[] = $this->recurDataToUnixData($value);
}
}
$rdata = substr($rdata, $count * 4);
return $dates;
}
private function parseRecurrenceException(string $rdata, int &$offset): ?array {
$dataLength = strlen($rdata);
if ($dataLength - $offset < 14) {
return null;
}
$data = unpack("Vstartdate/Venddate/Vbasedate/vbitmask", $rdata, $offset);
$offset += 14;
$bitmask = $data["bitmask"];
$item = [
"basedate" => $this->dayStartOf($this->recurDataToUnixData($data["basedate"])),
"start" => $this->recurDataToUnixData($data["startdate"]),
"end" => $this->recurDataToUnixData($data["enddate"]),
"bitmask" => $bitmask,
];
// ExceptionInfo fields in the order of MS-OXOCAL 2.2.1.44.2
$fields = [
0x01 => "subject", // ARO_SUBJECT
0x02 => null, // ARO_MEETINGTYPE
0x04 => "remind_before", // ARO_REMINDERDELTA
0x08 => "reminder_set", // ARO_REMINDER
0x10 => "location", // ARO_LOCATION
0x20 => "busystatus", // ARO_BUSYSTATUS
0x40 => null, // ARO_ATTACHMENT
0x80 => "alldayevent", // ARO_SUBTYPE
0x100 => "label", // ARO_APPTCOLOR
];
foreach ($fields as $flag => $name) {
if (!($bitmask & $flag)) {
continue;
}
if ($dataLength - $offset < 4) {
return null;
}
$length = 4;
if ($flag & 0x11) {
$size = (int) unpack("vlength", $rdata, $offset + 2)["length"];
$length += $size;
if ($dataLength - $offset < $length) {
return null;
}
$item[$name] = substr($rdata, $offset + 4, $size);
}
elseif ($name !== null) {
$item[$name] = unpack("Vvalue", $rdata, $offset)["value"];
}
$offset += $length;
}
return $item;
}
private function parseExtendedException(string $rdata, int &$offset, array $item, int $writerversion): ?array {
// subject and location in ucs-2 to utf-8
if ($writerversion >= 0x3009) {
if (!$this->skipRecurrenceBlock($rdata, $offset)) {
return null;
}
}
if (!$this->skipRecurrenceBlock($rdata, $offset)) {
return null;
}
// ARO_SUBJECT(0x01) | ARO_LOCATION(0x10)
if ($item["bitmask"] & 0x11) {
if (strlen($rdata) - $offset < 12) {
return null;
}
$data = unpack("Vstart/Vend/Vorig", $rdata, $offset);
$offset += 4 * 3;
$item["ex_start_datetime"] = $data["start"];
$item["ex_end_datetime"] = $data["end"];
$item["ex_orig_date"] = $data["orig"];
}
if ($item["bitmask"] & 0x01) {
$item["subject"] = $this->parseExceptionString($rdata, $offset);
if ($item["subject"] === null) {
return null;
}
}
if ($item["bitmask"] & 0x10) {
$item["location"] = $this->parseExceptionString($rdata, $offset);
if ($item["location"] === null) {
return null;
}
}
// ARO_SUBJECT(0x01) | ARO_LOCATION(0x10)
if ($item["bitmask"] & 0x11) {
if (!$this->skipRecurrenceBlock($rdata, $offset)) {
return null;
}
}
return $item;
}
private function parseExceptionString(string $rdata, int &$offset): false|string|null {
if (strlen($rdata) - $offset < 2) {
return null;
}
$length = (int) unpack("vlength", $rdata, $offset)["length"];
$offset += 2;
if ($length > intdiv(strlen($rdata) - $offset, 2)) {
return null;
}
$data = substr($rdata, $offset, $length * 2);
$offset += $length * 2;
return iconv("UCS-2LE", "UTF-8", $data);
}
private function skipRecurrenceBlock(string $rdata, int &$offset): bool {
if (strlen($rdata) - $offset < 4) {
return false;
}
$size = (int) unpack("Vsize", $rdata, $offset)["size"];
if ($size > strlen($rdata) - $offset - 4) {
return false;
}
$offset += 4 + $size;
return true;
}
/**
* Saves the recurrence data to the recurrence property.
*/
public function saveRecurrence(): void {
// Only save if a message was passed
if (!isset($this->message)) {
return;
}
// Abort if no recurrence was set
if (!isset(
$this->recur["type"],
$this->recur["subtype"],
$this->recur["start"],
$this->recur["end"],
$this->recur["startocc"],
$this->recur["endocc"])
) {
return;
}
$rtype = 0x2000 + (int) $this->recur["type"];
// Don't allow invalid type and subtype values
if (!in_array($rtype, [IDC_RCEV_PAT_ORB_DAILY, IDC_RCEV_PAT_ORB_WEEKLY, IDC_RCEV_PAT_ORB_MONTHLY, IDC_RCEV_PAT_ORB_YEARLY], true)) {
return;
}
if (!in_array((int) $this->recur["subtype"], [rptDay, rptWeek, rptMonth, rptMonthNth, rptMonthEnd, rptHjMonth, rptHjMonthNth, rptHjMonthEnd], true)) {
return;
}
$rdata = pack("vvvvv", 0x3004, 0x3004, $rtype, (int) $this->recur["subtype"], MAPI_CAL_DEFAULT);
$forwardcount = 0;
$restocc = 0;
// Terminate
$term = (int) $this->recur["term"] < 0x2000 ? 0x2000 + (int) $this->recur["term"] : (int) $this->recur["term"];
$pattern = match ($rtype) {
IDC_RCEV_PAT_ORB_DAILY => $this->serializeDailyPattern(),
IDC_RCEV_PAT_ORB_WEEKLY => $this->serializeWeeklyPattern($term, $forwardcount, $restocc),
default => $this->serializeMonthlyPattern($rtype, $term, $forwardcount),
};
if ($pattern === null) {
return;
}
$rdata .= $pattern;
$range = $this->serializeRecurrenceRange($rtype, $term, $forwardcount, $restocc);
if ($range === null) {
return;
}
$rdata .= $range;
$propsToSet = $this->getRecurrenceProperties();
// Default data
// Second item (0x08) indicates the Outlook version (see documentation at the bottom of this file for more information)
if (isset($this->recur["startocc"], $this->recur["endocc"])) {
// Set start and endtime in minutes
$rdata .= pack("VVVV", 0x3006, 0x3009, (int) $this->recur["startocc"], (int) $this->recur["endocc"]);
}
else {
$rdata .= pack("VV", 0x3006, 0x3009);
}
$rdata .= $this->serializeRecurrenceExceptions($this->recur["changed_occurrences"]);
// Set props
$propsToSet[$this->proptags["recurring_data"]] = $rdata;
$propsToSet[$this->proptags["recurring"]] = true;
$propsToSet[$this->proptags["meetingrecurring"]] = true;
$this->setRecurrenceTimezone($propsToSet);
mapi_setprops($this->message, $propsToSet);
}
private function setRecurrenceTimezone(array &$propsToSet): void {
if (isset($this->tz) && $this->tz) {
$timezone = "GMT";
if ($this->tz["timezone"] != 0) {
// Create user readable timezone information
$timezone = sprintf(
"(GMT %s%02d:%02d)",-$this->tz["timezone"] > 0 ? "+" : "-",
abs($this->tz["timezone"] / 60),
abs($this->tz["timezone"] % 60)
);
}
$propsToSet[$this->proptags["timezone_data"]] = $this->getTimezoneData($this->tz);
$propsToSet[$this->proptags["timezone"]] = $timezone;
}
}
private function getRecurrenceProperties(): array {
// UTC date
$utcstart = $this->getClipProp("start");
$utcend = $this->getClipProp("end");
// utc date+time
$utcfirstoccstartdatetime = (isset($this->recur["startocc"])) ? $utcstart + (((int) $this->recur["startocc"]) * 60) : $utcstart;
$utcfirstoccenddatetime = (isset($this->recur["endocc"])) ? $utcstart + (((int) $this->recur["endocc"]) * 60) : $utcstart;
$propsToSet = [];
// update reminder time
$propsToSet[$this->proptags["reminder_time"]] = $utcfirstoccstartdatetime;
// update first occurrence date
$propsToSet[$this->proptags["startdate"]] = $propsToSet[$this->proptags["commonstart"]] = $utcfirstoccstartdatetime;
$propsToSet[$this->proptags["duedate"]] = $propsToSet[$this->proptags["commonend"]] = $utcfirstoccenddatetime;
// Set Outlook properties, if it is an appointment
if (isset($this->messageprops[$this->proptags["message_class"]]) && $this->messageprops[$this->proptags["message_class"]] == "IPM.Appointment") {
// update real begin and real end date
$propsToSet[$this->proptags["startdate_recurring"]] = $utcstart;
$propsToSet[$this->proptags["enddate_recurring"]] = $utcend;
// recurrencetype
// Strange enough is the property recurrencetype, (type-0x9) and not the CDO recurrencetype
$propsToSet[$this->proptags["recurrencetype"]] = ((int) $this->recur["type"]) - 0x9;
// set named prop 'side_effects' to 369, needed for Outlook to ask for single or total recurrence when deleting
$propsToSet[$this->proptags["side_effects"]] = 369;
}
else {
$propsToSet[$this->proptags["side_effects"]] = 3441;
}
$this->setRecurrenceReminder($propsToSet);
return $propsToSet;
}
private function setRecurrenceReminder(array &$propsToSet): void {
// FlagDueBy is datetime of the first reminder occurrence. Outlook gives on this time a reminder popup dialog
// Any change of the recurrence (including changing and deleting exceptions) causes the flagdueby to be reset
// to the 'next' occurrence; this makes sure that deleting the next occurrence will correctly set the reminder to
// the occurrence after that. The 'next' occurrence is defined as being the first occurrence that starts at moment X (server time)
// with the reminder flag set.
$reminderprops = mapi_getprops($this->message, [$this->proptags["reminder_minutes"], $this->proptags["flagdueby"]]);
if (isset($reminderprops[$this->proptags["reminder_minutes"]])) {
$occ = false;
$occurrences = $this->getItems(time(), 0x7FF00000, 3, true);
for ($i = 0, $len = count($occurrences); $i < $len; ++$i) {
// This will actually also give us appointments that have already started, but not yet ended. Since we want the next
// reminder that occurs after time(), we may have to skip the first few entries. We get 3 entries since that is the maximum
// number that would be needed (assuming reminder for item X cannot be before the previous occurrence starts). Worst case:
// time() is currently after start but before end of item, but reminder of next item has already passed (reminder for next item
// can be DURING the previous item, eg daily allday events). In that case, the first and second items must be skipped.
if (($occurrences[$i][$this->proptags["startdate"]] - $reminderprops[$this->proptags["reminder_minutes"]] * 60) > time()) {
$occ = $occurrences[$i];
break;
}
}
if ($occ) {
if (isset($reminderprops[$this->proptags["flagdueby"]])) {
$propsToSet[$this->proptags["flagdueby"]] = $reminderprops[$this->proptags["flagdueby"]];
}
else {
$propsToSet[$this->proptags["flagdueby"]] = $occ[$this->proptags["startdate"]] - ($reminderprops[$this->proptags["reminder_minutes"]] * 60);
}
}
else {
// Last reminder passed, no reminders any more.
$propsToSet[$this->proptags["reminder"]] = false;
$propsToSet[$this->proptags["flagdueby"]] = 0x7FF00000;
}
}
}
private function serializeRecurrenceEnd(int $rtype, int $term, mixed $forwardcount, mixed $restocc): string {
// Set enddate
switch ($term) {
// After the given enddate
case IDC_RCEV_PAT_ERB_END:
$rdata = pack("V", $this->unixDataToRecurData((int) $this->recur["end"]));
break;
// After a number of times
case IDC_RCEV_PAT_ERB_AFTERNOCCUR:
// @todo: calculate enddate with intval($this->recur["startocc"]) + intval($this->recur["duration"]) > 24 hour
$occenddate = (int) $this->recur["start"];
$occenddate = match ($rtype) {
IDC_RCEV_PAT_ORB_DAILY => $this->getDailyEndDate($occenddate),
IDC_RCEV_PAT_ORB_WEEKLY => $this->getWeeklyEndDate($occenddate, $forwardcount, $restocc),
default => $this->getMonthlyEndDate($occenddate, $forwardcount),
};
if (defined("PHP_INT_MAX") && $occenddate > PHP_INT_MAX) {
$occenddate = PHP_INT_MAX;
}
$this->recur["end"] = $occenddate;
$rdata = pack("V", $this->unixDataToRecurData((int) $this->recur["end"]));
break;
// Never ends
case IDC_RCEV_PAT_ERB_NOEND:
default:
$this->recur["end"] = 0x7FFFFFFF; // max date -> 2038
$rdata = pack("V", 0x5AE980DF);
break;
}
return $rdata;
}
private function getDailyEndDate(int $occenddate): float|int {
if ($this->recur["subtype"] == rptWeek) {
// Daily every workday: the start counts when it falls on a workday,
// every full week after that holds five
$restocc = (int) $this->recur["numoccur"];
if ($restocc <= 0) {
return $occenddate;
}
// Get starting weekday
$nowtime = $this->gmtime($occenddate);
$wday = $nowtime["tm_wday"];
$days = match ($wday) {
0 => 1, // Sunday -> Monday
6 => 2, // Saturday -> Monday
default => 0,
};
$wday = ($wday + $days) % 7;
--$restocc;
$days += intdiv($restocc, 5) * 7 + $restocc % 5;
if ($wday + $restocc % 5 > 5) {
$days += 2; // skips a weekend
}
$occenddate += $days * 24 * 60 * 60;
}
else {
// -1 because the first day already counts (from 1-1-1980 to 1-1-1980 is 1 occurrence)
$occenddate += (((int) $this->recur["everyn"]) * 60 * ((int) $this->recur["numoccur"] - 1));
}
return $occenddate;
}
private function getWeeklyEndDate(int $occenddate, mixed $forwardcount, mixed $restocc): float|int {
$weekstart = $this->firstDayOfWeek;
// Needed values
// $forwardcount - number of weeks we can skip forward
// $restocc - number of remaining occurrences after the week skip
// Add the weeks till the last item
$occenddate += ($forwardcount * 7 * 24 * 60 * 60);
$dayofweek = (int) gmdate("w", (int) $occenddate);
// Loop through the last occurrences until we have had them all
for ($j = 1; $restocc > 0; ++$j) {
// Jump to the next week (which may be N weeks away) when going over the week boundary
if ((($dayofweek + $j) % 7) == $weekstart) {
$occenddate += (((int) $this->recur["everyn"]) - 1) * 7 * 24 * 60 * 60;
}
// If this is a matching day, once less occurrence to process
if (((int) $this->recur["weekdays"]) & (1 << (($dayofweek + $j) % 7))) {
--$restocc;
}
// Next day
$occenddate += 24 * 60 * 60;
}
return $occenddate;
}
private function getMonthlyEndDate(int $occenddate, mixed $forwardcount): float|int {
switch ((int) $this->recur["subtype"]) {
case rptMonth: // on D day of every M month
$occenddate = $this->advanceRecurrenceMonths($occenddate, $forwardcount);
// compensation between 28 and 31
if (((int) $this->recur["monthday"]) >= 28 && ((int) $this->recur["monthday"]) <= 31 &&
(int) gmdate("j", $occenddate) < ((int) $this->recur["monthday"])) {
if ((int) gmdate("j", $occenddate) < 28) {
$occenddate -= (int) gmdate("j", $occenddate) * 24 * 60 * 60;
}
else {
$occenddate += ((int) gmdate("t", $occenddate) - (int) gmdate("j", $occenddate)) * 24 * 60 * 60;
}
}
break;
case rptMonthNth: // on Nth weekday of every M month
$nday = (int) $this->recur["nday"]; // 1 tot 5
$weekdays = (int) $this->recur["weekdays"];
$occenddate = $this->advanceRecurrenceMonths($occenddate, $forwardcount);
$occenddate = $this->getMonthWeekdayEndDate($occenddate, $nday, $weekdays);
break; // case rptMonthNth
}
return $occenddate;
}
private function advanceRecurrenceMonths(int $occenddate, mixed $forwardcount): float|int {
$curyear = (int) gmdate("Y", (int) $this->recur["start"]);
$curmonth = (int) gmdate("n", (int) $this->recur["start"]);
// $forwardcount = months; the stored end date is a 32-bit minute count
// that wraps long before the year 9999 anyway
$months = (int) min(max($forwardcount, 0), (10000 - $curyear) * 12);
if ($months <= 0) {
return $occenddate;
}
// gmmktime() takes a year up to 100 for a two-digit one, which gives
// the year 100 a leap day; a whole 400-year cycle has the same months
if ($curyear >= 0 && $curyear <= 100) {
$curyear += 400;
}
// the whole months from the first of the start month on
return $occenddate + gmmktime(0, 0, 0, $curmonth + $months, 1, $curyear) - gmmktime(0, 0, 0, $curmonth, 1, $curyear);
}
private function getMonthWeekdayEndDate(float|int $occenddate, int $nday, int $weekdays): float|int {
if ($nday == 5) {
// Set date on the last day of the last month
$occenddate += ((int) gmdate("t", (int) $occenddate) - (int) gmdate("j", (int) $occenddate)) * 24 * 60 * 60;
}
else {
// Set date on the first day of the last month
$occenddate -= ((int) gmdate("j", (int) $occenddate) - 1) * 24 * 60 * 60;
}
$dayofweek = (int) gmdate("w", (int) $occenddate);
for ($i = 0; $i < 7; ++$i) {
if ($nday == 5 && (($dayofweek - $i) % 7) >= 0 && (1 << (($dayofweek - $i) % 7)) & $weekdays) {
$occenddate -= $i * 24 * 60 * 60;
break;
}
if ($nday != 5 && (1 << (($dayofweek + $i) % 7)) & $weekdays) {
$occenddate += ($i + (($nday - 1) * 7)) * 24 * 60 * 60;
break;
}
}
return $occenddate;
}
private function serializeRecurrenceRange(int $rtype, int $term, mixed $forwardcount, mixed $restocc): ?string {
$rdata = "";
if (!isset($this->recur["term"])) {
return null;
}
$rdata .= pack("V", $term);
switch ($term) {
// After the given enddate
case IDC_RCEV_PAT_ERB_END:
$rdata .= pack("V", 10);
break;
// After a number of times
case IDC_RCEV_PAT_ERB_AFTERNOCCUR:
if (!isset($this->recur["numoccur"])) {
return null;
}
$rdata .= pack("V", (int) $this->recur["numoccur"]);
break;
// Never ends
case IDC_RCEV_PAT_ERB_NOEND:
$rdata .= pack("V", 0);
break;
}
// Persist first day of week (previously saved recurrences maintain the fdow)
$firstDow = $this->recur["first_dow"] ?? $this->firstDayOfWeek;
$rdata .= pack("V", (int) $firstDow);
// Exception data
// Get all exceptions
$deleted_items = $this->recur["deleted_occurrences"];
$changed_items = $this->recur["changed_occurrences"];
if ($deleted_items === [] && $changed_items === []) {
$start = $this->unixDataToRecurData((int) $this->recur["start"]);
return $rdata . pack("VVV", 0, 0, $start) .
$this->serializeRecurrenceEnd($rtype, $term, $forwardcount, $restocc);
}
// Merge deleted and changed items into one list
$items = $deleted_items;
foreach ($changed_items as $changed_item) {
$items[] = $this->dayStartOf($changed_item["basedate"]);
}
sort($items);
// Add the merged list in to the rdata
$rdata .= pack("V", count($items));
foreach ($items as $item) {
$rdata .= pack("V", $this->unixDataToRecurData($item));