Issues (203)

class.baserecurrence.php (1 issue)

1
<?php
2
3
/*
4
 * SPDX-License-Identifier: AGPL-3.0-only
5
 * SPDX-FileCopyrightText: Copyright 2005-2016 Zarafa Deutschland GmbH
6
 * SPDX-FileCopyrightText: Copyright 2020-2025 grommunio GmbH
7
 */
8
9
/**
10
 * BaseRecurrence
11
 * this class is superclass for recurrence for appointments and tasks. This class provides all
12
 * basic features of recurrence.
13
 */
14
abstract class BaseRecurrence {
15
	/**
16
	 * @var mixed Mapi Message (may be null if readonly)
17
	 */
18
	public $message;
19
20
	/**
21
	 * @var array Message Properties
22
	 */
23
	public $messageprops;
24
25
	/**
26
	 * @var array list of property tags
27
	 */
28
	public $proptags;
29
30
	/**
31
	 * @var mixed recurrence data of this calendar item
32
	 */
33
	public $recur;
34
35
	/**
36
	 * @var mixed Timezone data of this calendar item
37
	 */
38
	public $tz;
39
40
	/**
41
	 * Constructor.
42
	 *
43
	 * @param resource $store   MAPI Message Store Object
44
	 * @param mixed    $message the MAPI (appointment) message
45
	 */
46
	public function __construct(public $store, $message) {
47
		if (is_array($message)) {
48
			$this->messageprops = $message;
49
		}
50
		else {
51
			$this->message = $message;
52
			$this->messageprops = mapi_getprops($this->message, $this->proptags);
53
		}
54
55
		if (isset($this->messageprops[$this->proptags["recurring_data"]])) {
56
			// There is a possibility that recurr blob can be more than 255 bytes so get full blob through stream interface
57
			if (strlen((string) $this->messageprops[$this->proptags["recurring_data"]]) >= 255) {
58
				$this->getFullRecurrenceBlob();
59
			}
60
61
			$this->recur = $this->parseRecurrence($this->messageprops[$this->proptags["recurring_data"]]);
62
		}
63
		if (isset($this->proptags["timezone_data"], $this->messageprops[$this->proptags["timezone_data"]])) {
64
			$this->tz = $this->parseTimezone($this->messageprops[$this->proptags["timezone_data"]]);
65
		}
66
	}
67
68
	public function getRecurrence() {
69
		return $this->recur;
70
	}
71
72
	public function getFullRecurrenceBlob(): void {
73
		$message = mapi_msgstore_openentry($this->store, $this->messageprops[PR_ENTRYID]);
74
75
		$recurrBlob = '';
76
		$stream = mapi_openproperty($message, $this->proptags["recurring_data"], IID_IStream, 0, 0);
77
		$stat = mapi_stream_stat($stream);
78
79
		for ($i = 0; $i < $stat['cb']; $i += 1024) {
80
			$recurrBlob .= mapi_stream_read($stream, 1024);
81
		}
82
83
		if (!empty($recurrBlob)) {
84
			$this->messageprops[$this->proptags["recurring_data"]] = $recurrBlob;
85
		}
86
	}
87
88
	/**
89
	 * Function for parsing the Recurrence value of a Calendar item.
90
	 *
91
	 * Retrieve it from Named Property 0x8216 as a PT_BINARY and pass the
92
	 * data to this function
93
	 *
94
	 * Returns a structure containing the data:
95
	 *
96
	 * type  - type of recurrence: day=10, week=11, month=12, year=13
97
	 * subtype - type of day recurrence: 2=monthday (ie 21st day of month), 3=nday'th weekdays (ie. 2nd Tuesday and Wednesday)
98
	 * start - unix timestamp of first occurrence
99
	 * end  - unix timestamp of last occurrence (up to and including), so when start == end -> occurrences = 1
100
	 * numoccur     - occurrences (may be very large when there is no end data)
101
	 *
102
	 * then, for each type:
103
	 *
104
	 * Daily:
105
	 *  everyn - every [everyn] days in minutes
106
	 *  regen - regenerating event (like tasks)
107
	 *
108
	 * Weekly:
109
	 *  everyn - every [everyn] weeks in weeks
110
	 *  regen - regenerating event (like tasks)
111
	 *  weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
112
	 *
113
	 * Monthly:
114
	 *  everyn - every [everyn] months
115
	 *  regen - regenerating event (like tasks)
116
	 *
117
	 *  subtype 2:
118
	 *   monthday - on day [monthday] of the month
119
	 *
120
	 *  subtype 3:
121
	 *   weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
122
	 *   nday - on [nday]'th [weekdays] of the month
123
	 *
124
	 * Yearly:
125
	 *  everyn - every [everyn] months (12, 24, 36, ...)
126
	 *  month - in month [month] (although the month is encoded in minutes since the startning of the year ........)
127
	 *  regen - regenerating event (like tasks)
128
	 *
129
	 *  subtype 2:
130
	 *   monthday - on day [monthday] of the month
131
	 *
132
	 *  subtype 3:
133
	 *   weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
134
	 *   nday - on [nday]'th [weekdays] of the month [month]
135
	 *
136
	 * @param string $rdata Binary string
137
	 *
138
	 * @return null|(((false|int|mixed|string)[]|int)[]|int|mixed)[] recurrence data
139
	 *
140
	 * @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, numexceptmod?: mixed, start?: int, end?: int, startocc?: mixed, endocc?: mixed}|null
141
	 */
142
	public function parseRecurrence($rdata) {
143
		if (strlen($rdata) < 10) {
144
			return;
145
		}
146
147
		$ret = [];
148
		$ret["changed_occurrences"] = [];
149
		$ret["deleted_occurrences"] = [];
150
151
		$data = unpack("vReaderVersion/vWriterVersion/vrtype/vrtype2/vCalendarType", $rdata);
152
153
		// Do some recurrence validity checks
154
		if ($data['ReaderVersion'] != 0x3004 || $data['WriterVersion'] != 0x3004) {
155
			return $ret;
156
		}
157
158
		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])) {
159
			return $ret;
160
		}
161
162
		if (!in_array($data["rtype2"], [rptDay, rptWeek, rptMonth, rptMonthNth, rptMonthEnd, rptHjMonth, rptHjMonthNth, rptHjMonthEnd])) {
163
			return $ret;
164
		}
165
166
		if (!in_array($data['CalendarType'], [MAPI_CAL_DEFAULT, MAPI_CAL_GREGORIAN])) {
167
			return $ret;
168
		}
169
170
		$ret["type"] = (int) $data["rtype"] > 0x2000 ? (int) $data["rtype"] - 0x2000 : $data["rtype"];
171
		$ret["subtype"] = $data["rtype2"];
172
		$rdata = substr($rdata, 10);
173
174
		switch ($data["rtype"]) {
175
			case IDC_RCEV_PAT_ORB_DAILY:
176
				if (strlen($rdata) < 12) {
177
					return $ret;
178
				}
179
180
				$data = unpack("Vunknown/Veveryn/Vregen", $rdata);
181
				if ($data["everyn"] > 1438560) { // minutes for 999 days
182
					return $ret;
183
				}
184
				$ret["everyn"] = $data["everyn"];
185
				$ret["regen"] = $data["regen"];
186
187
				switch ($ret["subtype"]) {
188
					case rptDay:
189
						$rdata = substr($rdata, 12);
190
						break;
191
192
					case rptWeek:
193
						$rdata = substr($rdata, 16);
194
						break;
195
				}
196
197
				break;
198
199
			case IDC_RCEV_PAT_ORB_WEEKLY:
200
				if (strlen($rdata) < 16) {
201
					return $ret;
202
				}
203
204
				$data = unpack("Vconst1/Veveryn/Vregen", $rdata);
205
				if ($data["everyn"] > 99) {
206
					return $ret;
207
				}
208
209
				$rdata = substr($rdata, 12);
210
211
				$ret["everyn"] = $data["everyn"];
212
				$ret["regen"] = $data["regen"];
213
				$ret["weekdays"] = 0;
214
215
				if ($data["regen"] == 0) {
216
					$data = unpack("Vweekdays", $rdata);
217
					$rdata = substr($rdata, 4);
218
219
					$ret["weekdays"] = $data["weekdays"];
220
				}
221
				break;
222
223
			case IDC_RCEV_PAT_ORB_MONTHLY:
224
				if (strlen($rdata) < 16) {
225
					return $ret;
226
				}
227
228
				$data = unpack("Vconst1/Veveryn/Vregen/Vmonthday", $rdata);
229
				if ($data["everyn"] > 99) {
230
					return $ret;
231
				}
232
233
				$ret["everyn"] = $data["everyn"];
234
				$ret["regen"] = $data["regen"];
235
236
				if ($ret["subtype"] == rptMonthNth) {
237
					$ret["weekdays"] = $data["monthday"];
238
				}
239
				else {
240
					$ret["monthday"] = $data["monthday"];
241
				}
242
243
				$rdata = substr($rdata, 16);
244
				if ($ret["subtype"] == rptMonthNth) {
245
					$data = unpack("Vnday", $rdata);
246
					// Sanity check for valid values (and opportunistically try to fix)
247
					if ($data["nday"] == 0xFFFFFFFF || $data["nday"] == -1) {
248
						$data["nday"] = 5;
249
					}
250
					elseif ($data["nday"] < 0 || $data["nday"] > 5) {
251
						$data["nday"] = 0;
252
					}
253
					$ret["nday"] = $data["nday"];
254
					$rdata = substr($rdata, 4);
255
				}
256
				break;
257
258
			case IDC_RCEV_PAT_ORB_YEARLY:
259
				if (strlen($rdata) < 16) {
260
					return $ret;
261
				}
262
263
				$data = unpack("Vmonth/Veveryn/Vregen/Vmonthday", $rdata);
264
				// recurring yearly tasks have a period in months multiple by 12
265
				if ($data['regen'] && $data["everyn"] % 12 != 0) {
266
					return $ret;
267
				}
268
				if (!$data['regen'] && $data["everyn"] != 12) {
269
					return $ret;
270
				}
271
272
				$ret["month"] = $data["month"];
273
				$ret["everyn"] = $data["everyn"];
274
				$ret["regen"] = $data["regen"];
275
276
				if ($ret["subtype"] == rptMonthNth) {
277
					$ret["weekdays"] = $data["monthday"];
278
				}
279
				else {
280
					$ret["monthday"] = $data["monthday"];
281
				}
282
283
				$rdata = substr($rdata, 16);
284
285
				if ($ret["subtype"] == rptMonthNth) {
286
					$data = unpack("Vnday", $rdata);
287
					// Sanity check for valid values (and opportunistically try to fix)
288
					if ($data["nday"] == 0xFFFFFFFF || $data["nday"] == -1) {
289
						$data["nday"] = 5;
290
					}
291
					elseif ($data["nday"] < 0 || $data["nday"] > 5) {
292
						$data["nday"] = 0;
293
					}
294
					$ret["nday"] = $data["nday"];
295
					$rdata = substr($rdata, 4);
296
				}
297
				break;
298
		}
299
300
		if (strlen($rdata) < 16) {
301
			return $ret;
302
		}
303
304
		$data = unpack("Vterm/Vnumoccur/Vconst2/Vnumexcept", $rdata);
305
		$rdata = substr($rdata, 16);
306
		if (!in_array($data["term"], [IDC_RCEV_PAT_ERB_END, IDC_RCEV_PAT_ERB_AFTERNOCCUR, IDC_RCEV_PAT_ERB_NOEND, 0xFFFFFFFF])) {
307
			return $ret;
308
		}
309
310
		$ret["term"] = (int) $data["term"] > 0x2000 ? (int) $data["term"] - 0x2000 : $data["term"];
311
		$ret["numoccur"] = $data["numoccur"];
312
		$ret["numexcept"] = $data["numexcept"];
313
314
		// exc_base_dates are *all* the base dates that have been either deleted or modified
315
		$exc_base_dates = [];
316
		for ($i = 0; $i < $ret["numexcept"]; ++$i) {
317
			if (strlen($rdata) < 4) {
318
				// We shouldn't arrive here, because that implies
319
				// numexcept does not match the amount of data
320
				// which is available for the exceptions.
321
				return $ret;
322
			}
323
			$data = unpack("Vbasedate", $rdata);
324
			$rdata = substr($rdata, 4);
325
			$exc_base_dates[] = $this->recurDataToUnixData($data["basedate"]);
326
		}
327
328
		if (strlen($rdata) < 4) {
329
			return $ret;
330
		}
331
332
		$data = unpack("Vnumexceptmod", $rdata);
333
		$rdata = substr($rdata, 4);
334
335
		$ret["numexceptmod"] = $data["numexceptmod"];
336
337
		// exc_changed are the base dates of *modified* occurrences. exactly what is modified
338
		// is in the attachments *and* in the data further down this function.
339
		$exc_changed = [];
340
		for ($i = 0; $i < $ret["numexceptmod"]; ++$i) {
341
			if (strlen($rdata) < 4) {
342
				// We shouldn't arrive here, because that implies
343
				// numexceptmod does not match the amount of data
344
				// which is available for the exceptions.
345
				return $ret;
346
			}
347
			$data = unpack("Vstartdate", $rdata);
348
			$rdata = substr($rdata, 4);
349
			$exc_changed[] = $this->recurDataToUnixData($data["startdate"]);
350
		}
351
352
		if (strlen($rdata) < 8) {
353
			return $ret;
354
		}
355
356
		$data = unpack("Vstart/Vend", $rdata);
357
		$rdata = substr($rdata, 8);
358
359
		$ret["start"] = $this->recurDataToUnixData($data["start"]);
360
		$ret["end"] = $this->recurDataToUnixData($data["end"]);
361
362
		// this is where task recurrence stop
363
		if (strlen($rdata) < 16) {
364
			return $ret;
365
		}
366
367
		$data = unpack("Vreaderversion/Vwriterversion/Vstartmin/Vendmin", $rdata);
368
		$rdata = substr($rdata, 16);
369
370
		$ret["startocc"] = $data["startmin"];
371
		$ret["endocc"] = $data["endmin"];
372
		$writerversion = $data["writerversion"];
373
374
		$data = unpack("vnumber", $rdata);
375
		$rdata = substr($rdata, 2);
376
377
		$nexceptions = $data["number"];
378
		$exc_changed_details = [];
379
380
		// Parse n modified exceptions
381
		for ($i = 0; $i < $nexceptions; ++$i) {
382
			$item = [];
383
384
			// Get exception startdate, enddate and basedate (the date at which the occurrence would have started)
385
			$data = unpack("Vstartdate/Venddate/Vbasedate", $rdata);
386
			$rdata = substr($rdata, 12);
387
388
			// Convert recurtimestamp to unix timestamp
389
			$startdate = $this->recurDataToUnixData($data["startdate"]);
390
			$enddate = $this->recurDataToUnixData($data["enddate"]);
391
			$basedate = $this->recurDataToUnixData($data["basedate"]);
392
393
			// Set the right properties
394
			$item["basedate"] = $this->dayStartOf($basedate);
395
			$item["start"] = $startdate;
396
			$item["end"] = $enddate;
397
398
			$data = unpack("vbitmask", $rdata);
399
			$rdata = substr($rdata, 2);
400
			$item["bitmask"] = $data["bitmask"]; // save bitmask for extended exceptions
401
402
			// Bitmask to verify what properties are changed
403
			$bitmask = $data["bitmask"];
404
405
			// ARO_SUBJECT: 0x0001
406
			// Look for field: SubjectLength (2b), SubjectLength2 (2b) and Subject
407
			if ($bitmask & (1 << 0)) {
408
				$data = unpack("vnull_length/vlength", $rdata);
409
				$rdata = substr($rdata, 4);
410
411
				$length = $data["length"];
412
				$item["subject"] = ""; // Normalized subject
413
				for ($j = 0; $j < $length && strlen($rdata); ++$j) {
414
					$data = unpack("Cchar", $rdata);
415
					$rdata = substr($rdata, 1);
416
417
					$item["subject"] .= chr($data["char"]);
418
				}
419
			}
420
421
			// ARO_MEETINGTYPE: 0x0002
422
			if ($bitmask & (1 << 1)) {
423
				$rdata = substr($rdata, 4);
424
				// Attendees modified: no data here (only in attachment)
425
			}
426
427
			// ARO_REMINDERDELTA: 0x0004
428
			// Look for field: ReminderDelta (4b)
429
			if ($bitmask & (1 << 2)) {
430
				$data = unpack("Vremind_before", $rdata);
431
				$rdata = substr($rdata, 4);
432
433
				$item["remind_before"] = $data["remind_before"];
434
			}
435
436
			// ARO_REMINDER: 0x0008
437
			// Look field: ReminderSet (4b)
438
			if ($bitmask & (1 << 3)) {
439
				$data = unpack("Vreminder_set", $rdata);
440
				$rdata = substr($rdata, 4);
441
442
				$item["reminder_set"] = $data["reminder_set"];
443
			}
444
445
			// ARO_LOCATION: 0x0010
446
			// Look for fields: LocationLength (2b), LocationLength2 (2b) and Location
447
			// Similar to ARO_SUBJECT above.
448
			if ($bitmask & (1 << 4)) {
449
				$data = unpack("vnull_length/vlength", $rdata);
450
				$rdata = substr($rdata, 4);
451
452
				$item["location"] = "";
453
454
				$length = $data["length"];
455
				$data = substr($rdata, 0, $length);
456
				$rdata = substr($rdata, $length);
457
458
				$item["location"] .= $data;
459
			}
460
461
			// ARO_BUSYSTATUS: 0x0020
462
			// Look for field: BusyStatus (4b)
463
			if ($bitmask & (1 << 5)) {
464
				$data = unpack("Vbusystatus", $rdata);
465
				$rdata = substr($rdata, 4);
466
467
				$item["busystatus"] = $data["busystatus"];
468
			}
469
470
			// ARO_ATTACHMENT: 0x0040
471
			if ($bitmask & (1 << 6)) {
472
				// no data: RESERVED
473
				$rdata = substr($rdata, 4);
474
			}
475
476
			// ARO_SUBTYPE: 0x0080
477
			// Look for field: SubType (4b). Determines whether it is an allday event.
478
			if ($bitmask & (1 << 7)) {
479
				$data = unpack("Vallday", $rdata);
480
				$rdata = substr($rdata, 4);
481
482
				$item["alldayevent"] = $data["allday"];
483
			}
484
485
			// ARO_APPTCOLOR: 0x0100
486
			// Look for field: AppointmentColor (4b)
487
			if ($bitmask & (1 << 8)) {
488
				$data = unpack("Vlabel", $rdata);
489
				$rdata = substr($rdata, 4);
490
491
				$item["label"] = $data["label"];
492
			}
493
494
			// ARO_EXCEPTIONAL_BODY: 0x0200
495
			if ($bitmask & (1 << 9)) {
496
				// Notes or Attachments modified: no data here (only in attachment)
497
			}
498
499
			array_push($exc_changed_details, $item);
500
		}
501
502
		/**
503
		 * We now have $exc_changed, $exc_base_dates and $exc_changed_details
504
		 * We will ignore $exc_changed, as this information is available in $exc_changed_details
505
		 * also. If an item is in $exc_base_dates and NOT in $exc_changed_details, then the item
506
		 * has been deleted.
507
		 */
508
509
		// Find deleted occurrences
510
		$deleted_occurrences = [];
511
512
		foreach ($exc_base_dates as $base_date) {
513
			$found = false;
514
515
			foreach ($exc_changed_details as $details) {
516
				if ($details["basedate"] == $base_date) {
517
					$found = true;
518
					break;
519
				}
520
			}
521
			if (!$found) {
522
				// item was not in exc_changed_details, so it must be deleted
523
				$deleted_occurrences[] = $base_date;
524
			}
525
		}
526
527
		$ret["deleted_occurrences"] = $deleted_occurrences;
528
		$ret["changed_occurrences"] = $exc_changed_details;
529
530
		// enough data for normal exception (no extended data)
531
		if (strlen($rdata) < 8) {
532
			return $ret;
533
		}
534
535
		$data = unpack("Vreservedsize", $rdata);
536
		$rdata = substr($rdata, 4 + $data["reservedsize"]);
537
538
		for ($i = 0; $i < $nexceptions; ++$i) {
539
			// subject and location in ucs-2 to utf-8
540
			if ($writerversion >= 0x3009) {
541
				$data = unpack("Vsize/Vvalue", $rdata); // size includes sizeof(value)==4
542
				$rdata = substr($rdata, 4 + $data["size"]);
543
			}
544
545
			$data = unpack("Vreservedsize", $rdata);
546
			$rdata = substr($rdata, 4 + $data["reservedsize"]);
547
548
			// ARO_SUBJECT(0x01) | ARO_LOCATION(0x10)
549
			if ($exc_changed_details[$i]["bitmask"] & 0x11) {
550
				$data = unpack("Vstart/Vend/Vorig", $rdata);
551
				$rdata = substr($rdata, 4 * 3);
552
553
				$exc_changed_details[$i]["ex_start_datetime"] = $data["start"];
554
				$exc_changed_details[$i]["ex_end_datetime"] = $data["end"];
555
				$exc_changed_details[$i]["ex_orig_date"] = $data["orig"];
556
			}
557
558
			// ARO_SUBJECT
559
			if ($exc_changed_details[$i]["bitmask"] & 0x01) {
560
				// decode ucs2 string to utf-8
561
				$data = unpack("vlength", $rdata);
562
				$rdata = substr($rdata, 2);
563
				$length = $data["length"];
564
				$data = substr($rdata, 0, $length * 2);
565
				$rdata = substr($rdata, $length * 2);
566
				$subject = iconv("UCS-2LE", "UTF-8", $data);
567
				// replace subject with unicode subject
568
				$exc_changed_details[$i]["subject"] = $subject;
569
			}
570
571
			// ARO_LOCATION
572
			if ($exc_changed_details[$i]["bitmask"] & 0x10) {
573
				// decode ucs2 string to utf-8
574
				$data = unpack("vlength", $rdata);
575
				$rdata = substr($rdata, 2);
576
				$length = $data["length"];
577
				$data = substr($rdata, 0, $length * 2);
578
				$rdata = substr($rdata, $length * 2);
579
				$location = iconv("UCS-2LE", "UTF-8", $data);
580
				// replace subject with unicode subject
581
				$exc_changed_details[$i]["location"] = $location;
582
			}
583
584
			// ARO_SUBJECT(0x01) | ARO_LOCATION(0x10)
585
			if ($exc_changed_details[$i]["bitmask"] & 0x11) {
586
				$data = unpack("Vreservedsize", $rdata);
587
				$rdata = substr($rdata, 4 + $data["reservedsize"]);
588
			}
589
		}
590
591
		// update with extended data
592
		$ret["changed_occurrences"] = $exc_changed_details;
593
594
		return $ret;
595
	}
596
597
	/**
598
	 * Saves the recurrence data to the recurrence property.
599
	 */
600
	public function saveRecurrence(): void {
601
		// Only save if a message was passed
602
		if (!isset($this->message)) {
603
			return;
604
		}
605
606
		// Abort if no recurrence was set
607
		if (!isset(
608
			$this->recur["type"],
609
			$this->recur["subtype"],
610
			$this->recur["start"],
611
			$this->recur["end"],
612
			$this->recur["startocc"],
613
			$this->recur["endocc"])
614
		) {
615
			return;
616
		}
617
618
		$rtype = 0x2000 + (int) $this->recur["type"];
619
620
		// Don't allow invalid type and subtype values
621
		if (!in_array($rtype, [IDC_RCEV_PAT_ORB_DAILY, IDC_RCEV_PAT_ORB_WEEKLY, IDC_RCEV_PAT_ORB_MONTHLY, IDC_RCEV_PAT_ORB_YEARLY])) {
622
			return;
623
		}
624
625
		if (!in_array((int) $this->recur["subtype"], [rptDay, rptWeek, rptMonth, rptMonthNth, rptMonthEnd, rptHjMonth, rptHjMonthNth, rptHjMonthEnd])) {
626
			return;
627
		}
628
629
		$rdata = pack("vvvvv", 0x3004, 0x3004, $rtype, (int) $this->recur["subtype"], MAPI_CAL_DEFAULT);
630
		$weekstart = 1; // monday
631
		$forwardcount = 0;
632
		$count = 0;
633
		$restocc = 0;
634
		$dayofweek = (int) gmdate("w", (int) $this->recur["start"]); // 0 (for Sunday) through 6 (for Saturday)
635
636
		// Terminate
637
		$term = (int) $this->recur["term"] < 0x2000 ? 0x2000 + (int) $this->recur["term"] : (int) $this->recur["term"];
638
639
		switch ($rtype) {
640
			case IDC_RCEV_PAT_ORB_DAILY:
641
				if (!isset($this->recur["everyn"]) || (int) $this->recur["everyn"] > 1438560 || (int) $this->recur["everyn"] < 0) { // minutes for 999 days
642
					return;
643
				}
644
645
				if ($this->recur["subtype"] == rptWeek) {
646
					// Daily every workday
647
					$rdata .= pack("VVVV", 6 * 24 * 60, 1, 0, 0x3E);
648
				}
649
				else {
650
					// Calc first occ
651
					$firstocc = $this->unixDataToRecurData($this->recur["start"]) % ((int) $this->recur["everyn"]);
652
653
					$rdata .= pack("VVV", $firstocc, (int) $this->recur["everyn"], $this->recur["regen"] ? 1 : 0);
654
				}
655
				break;
656
657
			case IDC_RCEV_PAT_ORB_WEEKLY:
658
				if (!isset($this->recur["everyn"]) || $this->recur["everyn"] > 99 || (int) $this->recur["everyn"] < 0) {
659
					return;
660
				}
661
662
				if (!$this->recur["regen"] && !isset($this->recur["weekdays"])) {
663
					return;
664
				}
665
666
				// No need to calculate startdate if sliding flag was set.
667
				if (!$this->recur['regen']) {
668
					// Calculate start date of recurrence
669
670
					// Find the first day that matches one of the weekdays selected
671
					$daycount = 0;
672
					$dayskip = -1;
673
					for ($j = 0; $j < 7; ++$j) {
674
						if (((int) $this->recur["weekdays"]) & (1 << (($dayofweek + $j) % 7))) {
675
							if ($dayskip == -1) {
676
								$dayskip = $j;
677
							}
678
679
							++$daycount;
680
						}
681
					}
682
683
					// $dayskip is the number of days to skip from the startdate until the first occurrence
684
					// $daycount is the number of days per week that an occurrence occurs
685
686
					$weekskip = 0;
687
					if (($dayofweek < $weekstart && $dayskip > 0) || ($dayofweek + $dayskip) > 6) {
688
						$weekskip = 1;
689
					}
690
691
					// Check if the recurrence ends after a number of occurrences, in that case we must calculate the
692
					// remaining occurrences based on the start of the recurrence.
693
					if ($term == IDC_RCEV_PAT_ERB_AFTERNOCCUR) {
694
						// $weekskip is the amount of weeks to skip from the startdate before the first occurrence
695
						// $forwardcount is the maximum number of week occurrences we can go ahead after the first occurrence that
696
						// is still inside the recurrence. We subtract one to make sure that the last week is never forwarded over
697
						// (eg when numoccur = 2, and daycount = 1)
698
						$forwardcount = floor((int) ($this->recur["numoccur"] - 1) / $daycount);
699
700
						// $restocc is the number of occurrences left after $forwardcount whole weeks of occurrences, minus one
701
						// for the occurrence on the first day
702
						$restocc = ((int) $this->recur["numoccur"]) - ($forwardcount * $daycount) - 1;
703
704
						// $forwardcount is now the number of weeks we can go forward and still be inside the recurrence
705
						$forwardcount *= (int) $this->recur["everyn"];
706
					}
707
708
					// The real start is start + dayskip + weekskip-1 (since dayskip will already bring us into the next week)
709
					$this->recur["start"] = ((int) $this->recur["start"]) + ($dayskip * 24 * 60 * 60) + ($weekskip * (((int) $this->recur["everyn"]) - 1) * 7 * 24 * 60 * 60);
710
				}
711
712
				// Calc first occ
713
				$firstocc = $this->unixDataToRecurData($this->recur["start"]) % (((int) $this->recur["everyn"]) * 7 * 24 * 60);
714
715
				$firstocc -= (((int) gmdate("w", (int) $this->recur["start"])) - 1) * 24 * 60;
716
717
				if ($this->recur["regen"]) {
718
					$rdata .= pack("VVV", $firstocc, (int) $this->recur["everyn"], 1);
719
				}
720
				else {
721
					$rdata .= pack("VVVV", $firstocc, (int) $this->recur["everyn"], 0, (int) $this->recur["weekdays"]);
722
				}
723
				break;
724
725
			case IDC_RCEV_PAT_ORB_MONTHLY:
726
			case IDC_RCEV_PAT_ORB_YEARLY:
727
				if (!isset($this->recur["everyn"])) {
728
					return;
729
				}
730
				if ($rtype == IDC_RCEV_PAT_ORB_YEARLY && !isset($this->recur["month"])) {
731
					return;
732
				}
733
734
				if ($rtype == IDC_RCEV_PAT_ORB_MONTHLY) {
735
					$everyn = (int) $this->recur["everyn"];
736
					if ($everyn > 99 || $everyn < 0) {
737
						return;
738
					}
739
				}
740
				else {
741
					$everyn = $this->recur["regen"] ? ((int) $this->recur["everyn"]) * 12 : 12;
742
				}
743
744
				// Get montday/month/year of original start
745
				$curmonthday = gmdate("j", (int) $this->recur["start"]);
746
				$curyear = gmdate("Y", (int) $this->recur["start"]);
747
				$curmonth = gmdate("n", (int) $this->recur["start"]);
748
749
				// Check if the recurrence ends after a number of occurrences, in that case we must calculate the
750
				// remaining occurrences based on the start of the recurrence.
751
				if ($term == IDC_RCEV_PAT_ERB_AFTERNOCCUR) {
752
					// $forwardcount is the number of occurrences we can skip and still be inside the recurrence range (minus
753
					// one to make sure there are always at least one occurrence left)
754
					$forwardcount = ((((int) $this->recur["numoccur"]) - 1) * $everyn);
755
				}
756
757
				// Get month for yearly on D'th day of month M
758
				if ($rtype == IDC_RCEV_PAT_ORB_YEARLY) {
759
					$selmonth = floor(((int) $this->recur["month"]) / (24 * 60 * 29)) + 1; // 1=jan, 2=feb, eg
760
				}
761
762
				switch ((int) $this->recur["subtype"]) {
763
					// on D day of every M month
764
					case rptMonth:
765
						if (!isset($this->recur["monthday"])) {
766
							return;
767
						}
768
						// Recalc startdate
769
770
						// Set on the right begin day
771
772
						// Go the beginning of the month
773
						$this->recur["start"] -= ($curmonthday - 1) * 24 * 60 * 60;
774
						// Go the the correct month day
775
						$this->recur["start"] += (((int) $this->recur["monthday"]) - 1) * 24 * 60 * 60;
776
777
						// If the previous calculation gave us a start date different than the original start date, then we need to skip to the first occurrence
778
						if (($rtype == IDC_RCEV_PAT_ORB_MONTHLY && ((int) $this->recur["monthday"]) < $curmonthday) ||
779
							($rtype == IDC_RCEV_PAT_ORB_YEARLY && ($selmonth != $curmonth || ($selmonth == $curmonth && ((int) $this->recur["monthday"]) < $curmonthday)))) {
780
							if ($rtype == IDC_RCEV_PAT_ORB_YEARLY) {
781
								if ($curmonth > $selmonth) {// go to next occurrence in 'everyn' months minus difference in first occurrence and original date
782
									$count = $everyn - ($curmonth - $selmonth);
783
								}
784
								elseif ($curmonth < $selmonth) {// go to next occurrence upto difference in first occurrence and original date
785
									$count = $selmonth - $curmonth;
786
								}
787
								else {
788
									// Go to next occurrence while recurrence start date is greater than occurrence date but within same month
789
									if (((int) $this->recur["monthday"]) < $curmonthday) {
790
										$count = $everyn;
791
									}
792
								}
793
							}
794
							else {
795
								$count = $everyn; // Monthly, go to next occurrence in 'everyn' months
796
							}
797
798
							// Forward by $count months. This is done by getting the number of days in that month and forwarding that many days
799
							for ($i = 0; $i < $count; ++$i) {
800
								$this->recur["start"] += $this->getMonthInSeconds($curyear, $curmonth);
801
802
								if ($curmonth == 12) {
803
									++$curyear;
804
									$curmonth = 0;
805
								}
806
								++$curmonth;
807
							}
808
						}
809
810
						// "start" is now pointing to the first occurrence, except that it will overshoot if the
811
						// month in which it occurs has less days than specified as the day of the month. So 31st
812
						// of each month will overshoot in february (29 days). We compensate for that by checking
813
						// if the day of the month we got is wrong, and then back up to the last day of the previous
814
						// month.
815
						if (((int) $this->recur["monthday"]) >= 28 && ((int) $this->recur["monthday"]) <= 31 &&
816
							gmdate("j", (int) $this->recur["start"]) < ((int) $this->recur["monthday"])) {
817
							$this->recur["start"] -= gmdate("j", (int) $this->recur["start"]) * 24 * 60 * 60;
818
						}
819
820
						// "start" is now the first occurrence
821
						if ($rtype == IDC_RCEV_PAT_ORB_MONTHLY) {
822
							// Calc first occ
823
							$monthIndex = ((((12 % $everyn) * ((((int) gmdate("Y", $this->recur["start"])) - 1601) % $everyn)) % $everyn) + (((int) gmdate("n", $this->recur["start"])) - 1)) % $everyn;
824
825
							$firstocc = 0;
826
							for ($i = 0; $i < $monthIndex; ++$i) {
827
								$firstocc += $this->getMonthInSeconds(1601 + floor($i / 12), ($i % 12) + 1) / 60;
828
							}
829
830
							$rdata .= pack("VVVV", $firstocc, $everyn, $this->recur["regen"], (int) $this->recur["monthday"]);
831
						}
832
						else {
833
							// Calc first occ
834
							$firstocc = 0;
835
							$monthIndex = (int) gmdate("n", $this->recur["start"]);
836
							for ($i = 1; $i < $monthIndex; ++$i) {
837
								$firstocc += $this->getMonthInSeconds(1601 + floor($i / 12), $i) / 60;
838
							}
839
840
							$rdata .= pack("VVVV", $firstocc, $everyn, $this->recur["regen"], (int) $this->recur["monthday"]);
841
						}
842
						break;
843
844
					case rptMonthNth:
845
						// monthly: on Nth weekday of every M month
846
						// yearly: on Nth weekday of M month
847
						if (!isset($this->recur["weekdays"], $this->recur["nday"])) {
848
							return;
849
						}
850
851
						$weekdays = (int) $this->recur["weekdays"];
852
						$nday = (int) $this->recur["nday"];
853
854
						// Calc startdate
855
						$monthbegindow = (int) $this->recur["start"];
856
857
						if ($nday == 5) {
858
							// Set date on the last day of the last month
859
							$monthbegindow += (gmdate("t", $monthbegindow) - gmdate("j", $monthbegindow)) * 24 * 60 * 60;
860
						}
861
						else {
862
							// Set on the first day of the month
863
							$monthbegindow -= ((gmdate("j", $monthbegindow) - 1) * 24 * 60 * 60);
864
						}
865
866
						if ($rtype == IDC_RCEV_PAT_ORB_YEARLY) {
867
							// Set on right month
868
							if ($selmonth < $curmonth) {
869
								$tmp = 12 - $curmonth + $selmonth;
870
							}
871
							else {
872
								$tmp = ($selmonth - $curmonth);
873
							}
874
875
							for ($i = 0; $i < $tmp; ++$i) {
876
								$monthbegindow += $this->getMonthInSeconds($curyear, $curmonth);
877
878
								if ($curmonth == 12) {
879
									++$curyear;
880
									$curmonth = 0;
881
								}
882
								++$curmonth;
883
							}
884
						}
885
						else {
886
							// Check or you exist in the right month
887
888
							$dayofweek = gmdate("w", $monthbegindow);
889
							for ($i = 0; $i < 7; ++$i) {
890
								if ($nday == 5 && (($dayofweek - $i) % 7 >= 0) && (1 << (($dayofweek - $i) % 7)) & $weekdays) {
891
									$day = gmdate("j", $monthbegindow) - $i;
892
									break;
893
								}
894
								if ($nday != 5 && (1 << (($dayofweek + $i) % 7)) & $weekdays) {
895
									$day = (($nday - 1) * 7) + ($i + 1);
896
									break;
897
								}
898
							}
899
900
							// Goto the next X month
901
							if (isset($day) && ($day < gmdate("j", (int) $this->recur["start"]))) {
902
								if ($nday == 5) {
903
									$monthbegindow += 24 * 60 * 60;
904
									if ($curmonth == 12) {
905
										++$curyear;
906
										$curmonth = 0;
907
									}
908
									++$curmonth;
909
								}
910
911
								for ($i = 0; $i < $everyn; ++$i) {
912
									$monthbegindow += $this->getMonthInSeconds($curyear, $curmonth);
913
914
									if ($curmonth == 12) {
915
										++$curyear;
916
										$curmonth = 0;
917
									}
918
									++$curmonth;
919
								}
920
921
								if ($nday == 5) {
922
									$monthbegindow -= 24 * 60 * 60;
923
								}
924
							}
925
						}
926
927
						// FIXME: weekstart?
928
929
						$day = 0;
930
						// Set start on the right day
931
						$dayofweek = gmdate("w", $monthbegindow);
932
						for ($i = 0; $i < 7; ++$i) {
933
							if ($nday == 5 && (($dayofweek - $i) % 7) >= 0 && (1 << (($dayofweek - $i) % 7)) & $weekdays) {
934
								$day = $i;
935
								break;
936
							}
937
							if ($nday != 5 && (1 << (($dayofweek + $i) % 7)) & $weekdays) {
938
								$day = ($nday - 1) * 7 + ($i + 1);
939
								break;
940
							}
941
						}
942
						if ($nday == 5) {
943
							$monthbegindow -= $day * 24 * 60 * 60;
944
						}
945
						else {
946
							$monthbegindow += ($day - 1) * 24 * 60 * 60;
947
						}
948
949
						$firstocc = 0;
950
						if ($rtype == IDC_RCEV_PAT_ORB_MONTHLY) {
951
							// Calc first occ
952
							$monthIndex = ((((12 % $everyn) * (((int) gmdate("Y", $this->recur["start"]) - 1601) % $everyn)) % $everyn) + (((int) gmdate("n", $this->recur["start"])) - 1)) % $everyn;
953
954
							for ($i = 0; $i < $monthIndex; ++$i) {
955
								$firstocc += $this->getMonthInSeconds(1601 + floor($i / 12), ($i % 12) + 1) / 60;
956
							}
957
958
							$rdata .= pack("VVVVV", $firstocc, $everyn, 0, $weekdays, $nday);
959
						}
960
						else {
961
							// Calc first occ
962
							$monthIndex = (int) gmdate("n", $this->recur["start"]);
963
964
							for ($i = 1; $i < $monthIndex; ++$i) {
965
								$firstocc += $this->getMonthInSeconds(1601 + floor($i / 12), $i) / 60;
966
							}
967
968
							$rdata .= pack("VVVVV", $firstocc, $everyn, 0, $weekdays, $nday);
969
						}
970
						break;
971
				}
972
				break;
973
		}
974
975
		if (!isset($this->recur["term"])) {
976
			return;
977
		}
978
979
		$rdata .= pack("V", $term);
980
981
		switch ($term) {
982
			// After the given enddate
983
			case IDC_RCEV_PAT_ERB_END:
984
				$rdata .= pack("V", 10);
985
				break;
986
987
				// After a number of times
988
			case IDC_RCEV_PAT_ERB_AFTERNOCCUR:
989
				if (!isset($this->recur["numoccur"])) {
990
					return;
991
				}
992
993
				$rdata .= pack("V", (int) $this->recur["numoccur"]);
994
				break;
995
996
				// Never ends
997
			case IDC_RCEV_PAT_ERB_NOEND:
998
				$rdata .= pack("V", 0);
999
				break;
1000
		}
1001
1002
		// Strange little thing for the recurrence type "every workday"
1003
		if ($rtype == IDC_RCEV_PAT_ORB_WEEKLY && ((int) $this->recur["subtype"]) == 1) {
1004
			$rdata .= pack("V", 1);
1005
		}
1006
		else { // Other recurrences
1007
			$rdata .= pack("V", 0);
1008
		}
1009
1010
		// Exception data
1011
1012
		// Get all exceptions
1013
		$deleted_items = $this->recur["deleted_occurrences"];
1014
		$changed_items = $this->recur["changed_occurrences"];
1015
1016
		// Merge deleted and changed items into one list
1017
		$items = $deleted_items;
1018
1019
		foreach ($changed_items as $changed_item) {
1020
			array_push($items, $this->dayStartOf($changed_item["basedate"]));
1021
		}
1022
1023
		sort($items);
1024
1025
		// Add the merged list in to the rdata
1026
		$rdata .= pack("V", count($items));
1027
		foreach ($items as $item) {
1028
			$rdata .= pack("V", $this->unixDataToRecurData($item));
1029
		}
1030
1031
		// Loop through the changed exceptions (not deleted)
1032
		$rdata .= pack("V", count($changed_items));
1033
		$items = [];
1034
1035
		foreach ($changed_items as $changed_item) {
1036
			$items[] = $this->dayStartOf($changed_item["start"]);
1037
		}
1038
1039
		sort($items);
1040
1041
		// Add the changed items list int the rdata
1042
		foreach ($items as $item) {
1043
			$rdata .= pack("V", $this->unixDataToRecurData($item));
1044
		}
1045
1046
		// Set start date
1047
		$rdata .= pack("V", $this->unixDataToRecurData((int) $this->recur["start"]));
1048
1049
		// Set enddate
1050
		switch ($term) {
1051
			// After the given enddate
1052
			case IDC_RCEV_PAT_ERB_END:
1053
				$rdata .= pack("V", $this->unixDataToRecurData((int) $this->recur["end"]));
1054
				break;
1055
1056
				// After a number of times
1057
			case IDC_RCEV_PAT_ERB_AFTERNOCCUR:
1058
				// @todo: calculate enddate with intval($this->recur["startocc"]) + intval($this->recur["duration"]) > 24 hour
1059
				$occenddate = (int) $this->recur["start"];
1060
1061
				switch ($rtype) {
1062
					case IDC_RCEV_PAT_ORB_DAILY:
1063
						if ($this->recur["subtype"] == rptWeek) {
1064
							// Daily every workday
1065
							$restocc = (int) $this->recur["numoccur"];
1066
1067
							// Get starting weekday
1068
							$nowtime = $this->gmtime($occenddate);
1069
							$j = $nowtime["tm_wday"];
1070
1071
							while (1) {
1072
								if (($j % 7) > 0 && ($j % 7) < 6) {
1073
									--$restocc;
1074
								}
1075
1076
								++$j;
1077
1078
								if ($restocc <= 0) {
1079
									break;
1080
								}
1081
1082
								$occenddate += 24 * 60 * 60;
1083
							}
1084
						}
1085
						else {
1086
							// -1 because the first day already counts (from 1-1-1980 to 1-1-1980 is 1 occurrence)
1087
							$occenddate += (((int) $this->recur["everyn"]) * 60 * ((int) $this->recur["numoccur"] - 1));
1088
						}
1089
						break;
1090
1091
					case IDC_RCEV_PAT_ORB_WEEKLY:
1092
						// Needed values
1093
						// $forwardcount - number of weeks we can skip forward
1094
						// $restocc - number of remaining occurrences after the week skip
1095
1096
						// Add the weeks till the last item
1097
						$occenddate += ($forwardcount * 7 * 24 * 60 * 60);
1098
1099
						$dayofweek = gmdate("w", $occenddate);
1100
1101
						// Loop through the last occurrences until we have had them all
1102
						for ($j = 1; $restocc > 0; ++$j) {
1103
							// Jump to the next week (which may be N weeks away) when going over the week boundary
1104
							if ((($dayofweek + $j) % 7) == $weekstart) {
1105
								$occenddate += (((int) $this->recur["everyn"]) - 1) * 7 * 24 * 60 * 60;
1106
							}
1107
1108
							// If this is a matching day, once less occurrence to process
1109
							if (((int) $this->recur["weekdays"]) & (1 << (($dayofweek + $j) % 7))) {
1110
								--$restocc;
1111
							}
1112
1113
							// Next day
1114
							$occenddate += 24 * 60 * 60;
1115
						}
1116
1117
						break;
1118
1119
					case IDC_RCEV_PAT_ORB_MONTHLY:
1120
					case IDC_RCEV_PAT_ORB_YEARLY:
1121
						$curyear = gmdate("Y", (int) $this->recur["start"]);
1122
						$curmonth = gmdate("n", (int) $this->recur["start"]);
1123
						// $forwardcount = months
1124
1125
						switch ((int) $this->recur["subtype"]) {
1126
							case rptMonth: // on D day of every M month
1127
								while ($forwardcount > 0) {
1128
									$occenddate += $this->getMonthInSeconds($curyear, $curmonth);
1129
1130
									if ($curmonth >= 12) {
1131
										$curmonth = 1;
1132
										++$curyear;
1133
									}
1134
									else {
1135
										++$curmonth;
1136
									}
1137
									--$forwardcount;
1138
								}
1139
1140
								// compensation between 28 and 31
1141
								if (((int) $this->recur["monthday"]) >= 28 && ((int) $this->recur["monthday"]) <= 31 &&
1142
									gmdate("j", $occenddate) < ((int) $this->recur["monthday"])) {
1143
									if (gmdate("j", $occenddate) < 28) {
1144
										$occenddate -= gmdate("j", $occenddate) * 24 * 60 * 60;
1145
									}
1146
									else {
1147
										$occenddate += (gmdate("t", $occenddate) - gmdate("j", $occenddate)) * 24 * 60 * 60;
1148
									}
1149
								}
1150
1151
								break;
1152
1153
							case rptMonthNth: // on Nth weekday of every M month
1154
								$nday = (int) $this->recur["nday"]; // 1 tot 5
1155
								$weekdays = (int) $this->recur["weekdays"];
1156
1157
								while ($forwardcount > 0) {
1158
									$occenddate += $this->getMonthInSeconds($curyear, $curmonth);
1159
									if ($curmonth >= 12) {
1160
										$curmonth = 1;
1161
										++$curyear;
1162
									}
1163
									else {
1164
										++$curmonth;
1165
									}
1166
1167
									--$forwardcount;
1168
								}
1169
1170
								if ($nday == 5) {
1171
									// Set date on the last day of the last month
1172
									$occenddate += (gmdate("t", $occenddate) - gmdate("j", $occenddate)) * 24 * 60 * 60;
1173
								}
1174
								else {
1175
									// Set date on the first day of the last month
1176
									$occenddate -= (gmdate("j", $occenddate) - 1) * 24 * 60 * 60;
1177
								}
1178
1179
								$dayofweek = gmdate("w", $occenddate);
1180
								for ($i = 0; $i < 7; ++$i) {
1181
									if ($nday == 5 && (($dayofweek - $i) % 7) >= 0 && (1 << (($dayofweek - $i) % 7)) & $weekdays) {
1182
										$occenddate -= $i * 24 * 60 * 60;
1183
										break;
1184
									}
1185
									if ($nday != 5 && (1 << (($dayofweek + $i) % 7)) & $weekdays) {
1186
										$occenddate += ($i + (($nday - 1) * 7)) * 24 * 60 * 60;
1187
										break;
1188
									}
1189
								}
1190
1191
								break; // case rptMonthNth
1192
						}
1193
1194
						break;
1195
				}
1196
1197
				if (defined("PHP_INT_MAX") && $occenddate > PHP_INT_MAX) {
1198
					$occenddate = PHP_INT_MAX;
1199
				}
1200
1201
				$this->recur["end"] = $occenddate;
1202
1203
				$rdata .= pack("V", $this->unixDataToRecurData((int) $this->recur["end"]));
1204
				break;
1205
1206
				// Never ends
1207
			case IDC_RCEV_PAT_ERB_NOEND:
1208
			default:
1209
				$this->recur["end"] = 0x7FFFFFFF; // max date -> 2038
1210
				$rdata .= pack("V", 0x5AE980DF);
1211
				break;
1212
		}
1213
1214
		// UTC date
1215
		$utcstart = $this->toGMT($this->tz, (int) $this->recur["start"]);
1216
		$utcend = $this->toGMT($this->tz, (int) $this->recur["end"]);
1217
1218
		// utc date+time
1219
		$utcfirstoccstartdatetime = (isset($this->recur["startocc"])) ? $utcstart + (((int) $this->recur["startocc"]) * 60) : $utcstart;
1220
		$utcfirstoccenddatetime = (isset($this->recur["endocc"])) ? $utcstart + (((int) $this->recur["endocc"]) * 60) : $utcstart;
1221
1222
		$propsToSet = [];
1223
		// update reminder time
1224
		$propsToSet[$this->proptags["reminder_time"]] = $utcfirstoccstartdatetime;
1225
1226
		// update first occurrence date
1227
		$propsToSet[$this->proptags["startdate"]] = $propsToSet[$this->proptags["commonstart"]] = $utcfirstoccstartdatetime;
1228
		$propsToSet[$this->proptags["duedate"]] = $propsToSet[$this->proptags["commonend"]] = $utcfirstoccenddatetime;
1229
1230
		// Set Outlook properties, if it is an appointment
1231
		if (isset($this->messageprops[$this->proptags["message_class"]]) && $this->messageprops[$this->proptags["message_class"]] == "IPM.Appointment") {
1232
			// update real begin and real end date
1233
			$propsToSet[$this->proptags["startdate_recurring"]] = $utcstart;
1234
			$propsToSet[$this->proptags["enddate_recurring"]] = $utcend;
1235
1236
			// recurrencetype
1237
			// Strange enough is the property recurrencetype, (type-0x9) and not the CDO recurrencetype
1238
			$propsToSet[$this->proptags["recurrencetype"]] = ((int) $this->recur["type"]) - 0x9;
1239
1240
			// set named prop 'side_effects' to 369, needed for Outlook to ask for single or total recurrence when deleting
1241
			$propsToSet[$this->proptags["side_effects"]] = 369;
1242
		}
1243
		else {
1244
			$propsToSet[$this->proptags["side_effects"]] = 3441;
1245
		}
1246
1247
		// FlagDueBy is datetime of the first reminder occurrence. Outlook gives on this time a reminder popup dialog
1248
		// Any change of the recurrence (including changing and deleting exceptions) causes the flagdueby to be reset
1249
		// to the 'next' occurrence; this makes sure that deleting the next occurrence will correctly set the reminder to
1250
		// the occurrence after that. The 'next' occurrence is defined as being the first occurrence that starts at moment X (server time)
1251
		// with the reminder flag set.
1252
		$reminderprops = mapi_getprops($this->message, [$this->proptags["reminder_minutes"], $this->proptags["flagdueby"]]);
1253
		if (isset($reminderprops[$this->proptags["reminder_minutes"]])) {
1254
			$occ = false;
1255
			$occurrences = $this->getItems(time(), 0x7FF00000, 3, true);
1256
1257
			for ($i = 0, $len = count($occurrences); $i < $len; ++$i) {
1258
				// This will actually also give us appointments that have already started, but not yet ended. Since we want the next
1259
				// reminder that occurs after time(), we may have to skip the first few entries. We get 3 entries since that is the maximum
1260
				// number that would be needed (assuming reminder for item X cannot be before the previous occurrence starts). Worst case:
1261
				// time() is currently after start but before end of item, but reminder of next item has already passed (reminder for next item
1262
				// can be DURING the previous item, eg daily allday events). In that case, the first and second items must be skipped.
1263
1264
				if (($occurrences[$i][$this->proptags["startdate"]] - $reminderprops[$this->proptags["reminder_minutes"]] * 60) > time()) {
1265
					$occ = $occurrences[$i];
1266
					break;
1267
				}
1268
			}
1269
1270
			if ($occ) {
1271
				if (isset($reminderprops[$this->proptags["flagdueby"]])) {
1272
					$propsToSet[$this->proptags["flagdueby"]] = $reminderprops[$this->proptags["flagdueby"]];
1273
				}
1274
				else {
1275
					$propsToSet[$this->proptags["flagdueby"]] = $occ[$this->proptags["startdate"]] - ($reminderprops[$this->proptags["reminder_minutes"]] * 60);
1276
				}
1277
			}
1278
			else {
1279
				// Last reminder passed, no reminders any more.
1280
				$propsToSet[$this->proptags["reminder"]] = false;
1281
				$propsToSet[$this->proptags["flagdueby"]] = 0x7FF00000;
1282
			}
1283
		}
1284
1285
		// Default data
1286
		// Second item (0x08) indicates the Outlook version (see documentation at the bottom of this file for more information)
1287
		$rdata .= pack("VV", 0x3006, 0x3008);
1288
		if (isset($this->recur["startocc"], $this->recur["endocc"])) {
1289
			// Set start and endtime in minutes
1290
			$rdata .= pack("VV", (int) $this->recur["startocc"], (int) $this->recur["endocc"]);
1291
		}
1292
1293
		// Detailed exception data
1294
1295
		$changed_items = $this->recur["changed_occurrences"];
1296
1297
		$rdata .= pack("v", count($changed_items));
1298
1299
		foreach ($changed_items as $changed_item) {
1300
			// Set start and end time of exception
1301
			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["start"]));
1302
			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["end"]));
1303
			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["basedate"]));
1304
1305
			// Bitmask
1306
			$bitmask = 0;
1307
1308
			// Check for changed strings
1309
			if (isset($changed_item["subject"])) {
1310
				$bitmask |= 1 << 0;
1311
			}
1312
1313
			if (isset($changed_item["remind_before"])) {
1314
				$bitmask |= 1 << 2;
1315
			}
1316
1317
			if (isset($changed_item["reminder_set"])) {
1318
				$bitmask |= 1 << 3;
1319
			}
1320
1321
			if (isset($changed_item["location"])) {
1322
				$bitmask |= 1 << 4;
1323
			}
1324
1325
			if (isset($changed_item["busystatus"])) {
1326
				$bitmask |= 1 << 5;
1327
			}
1328
1329
			if (isset($changed_item["alldayevent"])) {
1330
				$bitmask |= 1 << 7;
1331
			}
1332
1333
			if (isset($changed_item["label"])) {
1334
				$bitmask |= 1 << 8;
1335
			}
1336
1337
			$rdata .= pack("v", $bitmask);
1338
1339
			// Set "subject"
1340
			if (isset($changed_item["subject"])) {
1341
				// convert utf-8 to non-unicode blob string (us-ascii?)
1342
				$subject = iconv("UTF-8", "windows-1252//TRANSLIT", $changed_item["subject"]);
1343
				$length = strlen($subject);
1344
				$rdata .= pack("vv", $length + 1, $length);
1345
				$rdata .= pack("a" . $length, $subject);
1346
			}
1347
1348
			if (isset($changed_item["remind_before"])) {
1349
				$rdata .= pack("V", $changed_item["remind_before"]);
1350
			}
1351
1352
			if (isset($changed_item["reminder_set"])) {
1353
				$rdata .= pack("V", $changed_item["reminder_set"]);
1354
			}
1355
1356
			if (isset($changed_item["location"])) {
1357
				$location = iconv("UTF-8", "windows-1252//TRANSLIT", $changed_item["location"]);
1358
				$length = strlen($location);
1359
				$rdata .= pack("vv", $length + 1, $length);
1360
				$rdata .= pack("a" . $length, $location);
1361
			}
1362
1363
			if (isset($changed_item["busystatus"])) {
1364
				$rdata .= pack("V", $changed_item["busystatus"]);
1365
			}
1366
1367
			if (isset($changed_item["alldayevent"])) {
1368
				$rdata .= pack("V", $changed_item["alldayevent"]);
1369
			}
1370
1371
			if (isset($changed_item["label"])) {
1372
				$rdata .= pack("V", $changed_item["label"]);
1373
			}
1374
		}
1375
1376
		$rdata .= pack("V", 0);
1377
1378
		// write extended data
1379
		foreach ($changed_items as $changed_item) {
1380
			$rdata .= pack("V", 0);
1381
			if (isset($changed_item["subject"]) || isset($changed_item["location"])) {
1382
				$rdata .= pack("V", $this->unixDataToRecurData($changed_item["start"]));
1383
				$rdata .= pack("V", $this->unixDataToRecurData($changed_item["end"]));
1384
				$rdata .= pack("V", $this->unixDataToRecurData($changed_item["basedate"]));
1385
			}
1386
1387
			if (isset($changed_item["subject"])) {
1388
				$subject = iconv("UTF-8", "UCS-2LE", $changed_item["subject"]);
1389
				$length = iconv_strlen($subject, "UCS-2LE");
1390
				$rdata .= pack("v", $length);
1391
				$rdata .= pack("a" . $length * 2, $subject);
1392
			}
1393
1394
			if (isset($changed_item["location"])) {
1395
				$location = iconv("UTF-8", "UCS-2LE", $changed_item["location"]);
1396
				$length = iconv_strlen($location, "UCS-2LE");
1397
				$rdata .= pack("v", $length);
1398
				$rdata .= pack("a" . $length * 2, $location);
1399
			}
1400
1401
			if (isset($changed_item["subject"]) || isset($changed_item["location"])) {
1402
				$rdata .= pack("V", 0);
1403
			}
1404
		}
1405
1406
		$rdata .= pack("V", 0);
1407
1408
		// Set props
1409
		$propsToSet[$this->proptags["recurring_data"]] = $rdata;
1410
		$propsToSet[$this->proptags["recurring"]] = true;
1411
		if (isset($this->tz) && $this->tz) {
1412
			$timezone = "GMT";
1413
			if ($this->tz["timezone"] != 0) {
1414
				// Create user readable timezone information
1415
				$timezone = sprintf(
1416
					"(GMT %s%02d:%02d)", -$this->tz["timezone"] > 0 ? "+" : "-",
1417
					abs($this->tz["timezone"] / 60),
1418
					abs($this->tz["timezone"] % 60)
1419
				);
1420
			}
1421
			$propsToSet[$this->proptags["timezone_data"]] = $this->getTimezoneData($this->tz);
1422
			$propsToSet[$this->proptags["timezone"]] = $timezone;
1423
		}
1424
		mapi_setprops($this->message, $propsToSet);
1425
	}
1426
1427
	/**
1428
	 * Function which converts a recurrence date timestamp to an unix date timestamp.
1429
	 *
1430
	 * @author Steve Hardy
1431
	 *
1432
	 * @param int $rdate the date which will be converted
1433
	 *
1434
	 * @return int the converted date
1435
	 */
1436
	public function recurDataToUnixData($rdate) {
1437
		return ($rdate - 194074560) * 60;
1438
	}
1439
1440
	/**
1441
	 * Function which converts an unix date timestamp to recurrence date timestamp.
1442
	 *
1443
	 * @author Johnny Biemans
1444
	 *
1445
	 * @param int $date the date which will be converted
1446
	 *
1447
	 * @return float|int the converted date in minutes
1448
	 */
1449
	public function unixDataToRecurData($date) {
1450
		return ($date / 60) + 194074560;
1451
	}
1452
1453
	/**
1454
	 * gmtime() doesn't exist in standard PHP, so we have to implement it ourselves.
1455
	 *
1456
	 * @author Steve Hardy
1457
	 *
1458
	 * @param mixed $ts
1459
	 *
1460
	 * @return float|int
1461
	 */
1462
	public function GetTZOffset($ts) {
1463
		$Offset = date("O", $ts);
1464
1465
		$Parity = $Offset < 0 ? -1 : 1;
1466
		$Offset = $Parity * $Offset;
1467
		$Offset = ($Offset - ($Offset % 100)) / 100 * 60 + $Offset % 100;
1468
1469
		return $Parity * $Offset;
1470
	}
1471
1472
	/**
1473
	 * gmtime() doesn't exist in standard PHP, so we have to implement it ourselves.
1474
	 *
1475
	 * @author Steve Hardy
1476
	 *
1477
	 * @param int $time
1478
	 *
1479
	 * @return array GMT Time
1480
	 */
1481
	public function gmtime($time) {
1482
		$TZOffset = $this->GetTZOffset($time);
1483
1484
		$t_time = $time - $TZOffset * 60; # Counter adjust for localtime()
1485
1486
		return localtime($t_time, 1);
1487
	}
1488
1489
	/**
1490
	 * @param float|string $year
1491
	 */
1492
	public function isLeapYear($year): bool {
1493
		return $year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0);
1494
	}
1495
1496
	/**
1497
	 * @param float|string $year
1498
	 * @param int|string   $month
1499
	 */
1500
	public function getMonthInSeconds($year, $month): int {
1501
		if (in_array($month, [1, 3, 5, 7, 8, 10, 12])) {
1502
			$day = 31;
1503
		}
1504
		elseif (in_array($month, [4, 6, 9, 11])) {
1505
			$day = 30;
1506
		}
1507
		else {
1508
			$day = 28;
1509
			if ($this->isLeapYear($year) == 1) {
1510
				++$day;
1511
			}
1512
		}
1513
1514
		return $day * 24 * 60 * 60;
1515
	}
1516
1517
	/**
1518
	 * Function to get a date by Year Nr, Month Nr, Week Nr, Day Nr, and hour.
1519
	 *
1520
	 * @param int $year
1521
	 * @param int $month
1522
	 * @param int $week
1523
	 * @param int $day
1524
	 * @param int $hour
1525
	 *
1526
	 * @return int the timestamp of the given date, timezone-independent
1527
	 */
1528
	public function getDateByYearMonthWeekDayHour($year, $month, $week, $day, $hour) {
1529
		// get first day of month
1530
		$date = gmmktime(0, 0, 0, $month, 0, $year + 1900);
1531
1532
		// get wday info
1533
		$gmdate = $this->gmtime($date);
1534
1535
		$date -= $gmdate["tm_wday"] * 24 * 60 * 60; // back up to start of week
1536
1537
		$date += $week * 7 * 24 * 60 * 60; // go to correct week nr
1538
		$date += $day * 24 * 60 * 60;
1539
		$date += $hour * 60 * 60;
1540
1541
		$gmdate = $this->gmtime($date);
1542
1543
		// if we are in the next month, then back up a week, because week '5' means
1544
		// 'last week of month'
1545
1546
		if ($month != $gmdate["tm_mon"] + 1) {
1547
			$date -= 7 * 24 * 60 * 60;
1548
		}
1549
1550
		return $date;
1551
	}
1552
1553
	/**
1554
	 * getTimezone gives the timezone offset (in minutes) of the given
1555
	 * local date/time according to the given TZ info.
1556
	 *
1557
	 * @param mixed $tz
1558
	 * @param mixed $date
1559
	 */
1560
	public function getTimezone($tz, $date) {
1561
		// No timezone -> GMT (+0)
1562
		if (!isset($tz["timezone"])) {
1563
			return 0;
1564
		}
1565
1566
		$dst = false;
1567
		$gmdate = $this->gmtime($date);
1568
1569
		$dststart = $this->getDateByYearMonthWeekDayHour($gmdate["tm_year"], $tz["dststartmonth"], $tz["dststartweek"], 0, $tz["dststarthour"]);
1570
		$dstend = $this->getDateByYearMonthWeekDayHour($gmdate["tm_year"], $tz["dstendmonth"], $tz["dstendweek"], 0, $tz["dstendhour"]);
1571
1572
		if ($dststart <= $dstend) {
1573
			// Northern hemisphere, eg DST is during Mar-Oct
1574
			if ($date > $dststart && $date < $dstend) {
1575
				$dst = true;
1576
			}
1577
		}
1578
		else {
1579
			// Southern hemisphere, eg DST is during Oct-Mar
1580
			if ($date < $dstend || $date > $dststart) {
1581
				$dst = true;
1582
			}
1583
		}
1584
1585
		if ($dst) {
1586
			return $tz["timezone"] + $tz["timezonedst"];
1587
		}
1588
1589
		return $tz["timezone"];
1590
	}
1591
1592
	/**
1593
	 * parseTimezone parses the timezone as specified in named property 0x8233
1594
	 * in Outlook calendar messages. Returns the timezone in minutes negative
1595
	 * offset (GMT +2:00 -> -120).
1596
	 *
1597
	 * @param mixed $data
1598
	 *
1599
	 * @return null|array|false
1600
	 */
1601
	public function parseTimezone($data) {
1602
		if (strlen((string) $data) < 48) {
1603
			return;
1604
		}
1605
1606
		return unpack("ltimezone/lunk/ltimezonedst/lunk/ldstendmonth/vdstendweek/vdstendhour/lunk/lunk/vunk/ldststartmonth/vdststartweek/vdststarthour/lunk/vunk", (string) $data);
1607
	}
1608
1609
	/**
1610
	 * @param mixed $tz
1611
	 *
1612
	 * @return false|string
1613
	 */
1614
	public function getTimezoneData($tz) {
1615
		return pack("lllllvvllvlvvlv", $tz["timezone"], 0, $tz["timezonedst"], 0, $tz["dstendmonth"], $tz["dstendweek"], $tz["dstendhour"], 0, 0, 0, $tz["dststartmonth"], $tz["dststartweek"], $tz["dststarthour"], 0, 0);
1616
	}
1617
1618
	/**
1619
	 * toGMT returns a timestamp in GMT time for the time and timezone given.
1620
	 *
1621
	 * @param mixed $tz
1622
	 * @param mixed $date
1623
	 */
1624
	public function toGMT($tz, $date) {
1625
		if (!isset($tz['timezone'])) {
1626
			return $date;
1627
		}
1628
		$offset = $this->getTimezone($tz, $date);
1629
1630
		return $date + $offset * 60;
1631
	}
1632
1633
	/**
1634
	 * fromGMT returns a timestamp in the local timezone given from the GMT time given.
1635
	 *
1636
	 * @param mixed $tz
1637
	 * @param mixed $date
1638
	 */
1639
	public function fromGMT($tz, $date) {
1640
		$offset = $this->getTimezone($tz, $date);
1641
1642
		return $date - $offset * 60;
1643
	}
1644
1645
	/**
1646
	 * Function to get timestamp of the beginning of the day of the timestamp given.
1647
	 *
1648
	 * @param mixed $date
1649
	 *
1650
	 * @return false|int timestamp referring to same day but at 00:00:00
1651
	 */
1652
	public function dayStartOf($date) {
1653
		$time1 = $this->gmtime($date);
1654
1655
		return gmmktime(0, 0, 0, $time1["tm_mon"] + 1, $time1["tm_mday"], $time1["tm_year"] + 1900);
1656
	}
1657
1658
	/**
1659
	 * Function to get timestamp of the beginning of the month of the timestamp given.
1660
	 *
1661
	 * @param mixed $date
1662
	 *
1663
	 * @return false|int Timestamp referring to same month but on the first day, and at 00:00:00
1664
	 */
1665
	public function monthStartOf($date) {
1666
		$time1 = $this->gmtime($date);
1667
1668
		return gmmktime(0, 0, 0, $time1["tm_mon"] + 1, 1, $time1["tm_year"] + 1900);
1669
	}
1670
1671
	/**
1672
	 * Function to get timestamp of the beginning of the year of the timestamp given.
1673
	 *
1674
	 * @param mixed $date
1675
	 *
1676
	 * @return false|int Timestamp referring to the same year but on Jan 01, at 00:00:00
1677
	 */
1678
	public function yearStartOf($date) {
1679
		$time1 = $this->gmtime($date);
1680
1681
		return gmmktime(0, 0, 0, 1, 1, $time1["tm_year"] + 1900);
1682
	}
1683
1684
	/**
1685
	 * Function which returns the items in a given interval. This included expansion of the recurrence and
1686
	 * processing of exceptions (modified and deleted).
1687
	 *
1688
	 * @param int   $start         start time of the interval (GMT)
1689
	 * @param int   $end           end time of the interval (GMT)
1690
	 * @param mixed $limit
1691
	 * @param mixed $remindersonly
1692
	 *
1693
	 * @return (array|mixed)[]
1694
	 *
1695
	 * @psalm-return array<int, T|array>
1696
	 */
1697
	public function getItems($start, $end, $limit = 0, $remindersonly = false): array {
1698
		$items = [];
1699
		$firstday = 0;
1700
1701
		if (!isset($this->recur)) {
1702
			return $items;
1703
		}
1704
1705
		// Optimization: remindersonly and default reminder is off; since only exceptions with reminder set will match, just look which
1706
		// exceptions are in range and have a reminder set
1707
		if ($remindersonly && (!isset($this->messageprops[$this->proptags["reminder"]]) || $this->messageprops[$this->proptags["reminder"]] == false)) {
1708
			// Sort exceptions by start time
1709
			uasort($this->recur["changed_occurrences"], $this->sortExceptionStart(...));
1710
1711
			// Loop through all changed exceptions
1712
			foreach ($this->recur["changed_occurrences"] as $exception) {
1713
				// Check reminder set
1714
				if (!isset($exception["reminder"]) || $exception["reminder"] == false) {
1715
					continue;
1716
				}
1717
1718
				// Convert to GMT
1719
				$occstart = $this->toGMT($this->tz, $exception["start"]);
1720
				$occend = $this->toGMT($this->tz, $exception["end"]);
1721
1722
				// Check range criterium
1723
				if ($occstart > $end || $occend < $start) {
1724
					continue;
1725
				}
1726
1727
				// OK, add to items.
1728
				array_push($items, $this->getExceptionProperties($exception));
1729
				if ($limit && (count($items) == $limit)) {
1730
					break;
1731
				}
1732
			}
1733
1734
			uasort($items, $this->sortStarttime(...));
1735
1736
			return $items;
1737
		}
1738
1739
		// From here on, the dates of the occurrences are calculated in local time, so the days we're looking
1740
		// at are calculated from the local time dates of $start and $end
1741
1742
		if (isset($this->recur['regen'], $this->action['datecompleted']) && $this->recur['regen']) {
1743
			$daystart = $this->dayStartOf($this->action['datecompleted']);
1744
		}
1745
		else {
1746
			$daystart = $this->dayStartOf($this->recur["start"]); // start on first day of occurrence
1747
		}
1748
1749
		// Calculate the last day on which we want to be looking at a recurrence; this is either the end of the view
1750
		// or the end of the recurrence, whichever comes first
1751
		if ($end > $this->toGMT($this->tz, $this->recur["end"])) {
1752
			$rangeend = $this->toGMT($this->tz, $this->recur["end"]);
1753
		}
1754
		else {
1755
			$rangeend = $end;
1756
		}
1757
1758
		$dayend = $this->dayStartOf($this->fromGMT($this->tz, $rangeend));
1759
1760
		// Loop through the entire recurrence range of dates, and check for each occurrence whether it is in the view range.
1761
		$recurType = (int) $this->recur["type"] < 0x2000 ? (int) $this->recur["type"] + 0x2000 : (int) $this->recur["type"];
1762
1763
		switch ($recurType) {
1764
			case IDC_RCEV_PAT_ORB_DAILY:
1765
				if ($this->recur["everyn"] <= 0) {
1766
					$this->recur["everyn"] = 1440;
1767
				}
1768
1769
				if ($this->recur["subtype"] == rptDay) {
1770
					// Every Nth day
1771
					for ($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += 60 * $this->recur["everyn"]) {
1772
						$this->processOccurrenceItem($items, $start, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1773
					}
1774
					break;
1775
				}
1776
				// Every workday
1777
				for ($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += 60 * 1440) {
1778
					$nowtime = $this->gmtime($now);
1779
					if ($nowtime["tm_wday"] > 0 && $nowtime["tm_wday"] < 6) { // only add items in the given timespace
1780
						$this->processOccurrenceItem($items, $start, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1781
					}
1782
				}
1783
				break;
1784
1785
			case IDC_RCEV_PAT_ORB_WEEKLY:
1786
				if ($this->recur["everyn"] <= 0) {
1787
					$this->recur["everyn"] = 1;
1788
				}
1789
1790
				// If sliding flag is set then move to 'n' weeks
1791
				if ($this->recur['regen']) {
1792
					$daystart += (60 * 60 * 24 * 7 * $this->recur["everyn"]);
1793
				}
1794
1795
				for ($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += (60 * 60 * 24 * 7 * $this->recur["everyn"])) {
1796
					if ($this->recur['regen']) {
1797
						$this->processOccurrenceItem($items, $start, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1798
						break;
1799
					}
1800
					// Loop through the whole following week to the first occurrence of the week, add each day that is specified
1801
					for ($wday = 0; $wday < 7; ++$wday) {
1802
						$daynow = $now + $wday * 60 * 60 * 24;
1803
						// checks weather the next coming day in recurring pattern is less than or equal to end day of the recurring item
1804
						if ($daynow > $dayend) {
1805
							continue;
1806
						}
1807
						$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
1808
						if ($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) { // Selected ?
1809
							$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1810
						}
1811
					}
1812
				}
1813
				break;
1814
1815
			case IDC_RCEV_PAT_ORB_MONTHLY:
1816
				if ($this->recur["everyn"] <= 0) {
1817
					$this->recur["everyn"] = 1;
1818
				}
1819
1820
				// Loop through all months from start to end of occurrence, starting at beginning of first month
1821
				for ($now = $this->monthStartOf($daystart); $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += $this->daysInMonth($now, $this->recur["everyn"]) * 24 * 60 * 60) {
1822
					if (isset($this->recur["monthday"]) && ($this->recur['monthday'] != "undefined") && !$this->recur['regen']) { // Day M of every N months
1823
						$difference = 1;
1824
						if ($this->daysInMonth($now, $this->recur["everyn"]) < $this->recur["monthday"]) {
1825
							$difference = $this->recur["monthday"] - $this->daysInMonth($now, $this->recur["everyn"]) + 1;
1826
						}
1827
						$daynow = $now + (($this->recur["monthday"] - $difference) * 24 * 60 * 60);
1828
						// checks weather the next coming day in recurrence pattern is less than or equal to end day of the recurring item
1829
						if ($daynow <= $dayend) {
1830
							$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1831
						}
1832
					}
1833
					elseif (isset($this->recur["nday"], $this->recur["weekdays"])) { // Nth [weekday] of every N months
1834
						// Sanitize input
1835
						if ($this->recur["weekdays"] == 0) {
1836
							$this->recur["weekdays"] = 1;
1837
						}
1838
1839
						// If nday is not set to the last day in the month
1840
						if ($this->recur["nday"] < 5) {
1841
							// keep the track of no. of time correct selection pattern (like 2nd weekday, 4th friday, etc.) is matched
1842
							$ndaycounter = 0;
1843
							// Find matching weekday in this month
1844
							for ($day = 0, $total = $this->daysInMonth($now, 1); $day < $total; ++$day) {
1845
								$daynow = $now + $day * 60 * 60 * 24;
1846
								$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
1847
1848
								if ($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) { // Selected ?
1849
									++$ndaycounter;
1850
								}
1851
								// check the selected pattern is same as asked Nth weekday,If so set the firstday
1852
								if ($this->recur["nday"] == $ndaycounter) {
1853
									$firstday = $day;
1854
									break;
1855
								}
1856
							}
1857
							// $firstday is the day of the month on which the asked pattern of nth weekday matches
1858
							$daynow = $now + $firstday * 60 * 60 * 24;
1859
						}
1860
						else {
1861
							// Find last day in the month ($now is the firstday of the month)
1862
							$NumDaysInMonth = $this->daysInMonth($now, 1);
1863
							$daynow = $now + (($NumDaysInMonth - 1) * 24 * 60 * 60);
1864
1865
							$nowtime = $this->gmtime($daynow);
1866
							while (($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) == 0) {
1867
								$daynow -= 86400;
1868
								$nowtime = $this->gmtime($daynow);
1869
							}
1870
						}
1871
1872
						/*
1873
						* checks weather the next coming day in recurrence pattern is less than or equal to end day of the			* recurring item.Also check weather the coming day in recurrence pattern is greater than or equal to start * of recurring pattern, so that appointment that fall under the recurrence range are only displayed.
1874
						*/
1875
						if ($daynow <= $dayend && $daynow >= $daystart) {
1876
							$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1877
						}
1878
					}
1879
					elseif ($this->recur['regen']) {
1880
						$next_month_start = $now + ($this->daysInMonth($now, 1) * 24 * 60 * 60);
1881
						$now = $daystart + ($this->daysInMonth($next_month_start, $this->recur['everyn']) * 24 * 60 * 60);
1882
1883
						if ($now <= $dayend) {
1884
							$this->processOccurrenceItem($items, $daystart, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1885
						}
1886
					}
1887
				}
1888
				break;
1889
1890
			case IDC_RCEV_PAT_ORB_YEARLY:
1891
				if ($this->recur["everyn"] <= 0) {
1892
					$this->recur["everyn"] = 12;
1893
				}
1894
1895
				for ($now = $this->yearStartOf($daystart); $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += $this->daysInMonth($now, $this->recur["everyn"]) * 24 * 60 * 60) {
1896
					if (isset($this->recur["monthday"]) && !$this->recur['regen']) { // same as monthly, but in a specific month
1897
						// recur["month"] is in minutes since the beginning of the year
1898
						$month = $this->monthOfYear($this->recur["month"]); // $month is now month of year [0..11]
1899
						$monthday = $this->recur["monthday"]; // $monthday is day of the month [1..31]
1900
						$monthstart = $now + $this->daysInMonth($now, $month) * 24 * 60 * 60; // $monthstart is the timestamp of the beginning of the month
1901
						if ($monthday > $this->daysInMonth($monthstart, 1)) {
1902
							$monthday = $this->daysInMonth($monthstart, 1);
1903
						}	// Cap $monthday on month length (eg 28 feb instead of 29 feb)
1904
						$daynow = $monthstart + ($monthday - 1) * 24 * 60 * 60;
1905
						$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1906
					}
1907
					elseif (isset($this->recur["nday"], $this->recur["weekdays"])) { // Nth [weekday] in month X of every N years
1908
						// Go the correct month
1909
						$monthnow = $now + $this->daysInMonth($now, $this->monthOfYear($this->recur["month"])) * 24 * 60 * 60;
1910
1911
						// Find first matching weekday in this month
1912
						for ($wday = 0; $wday < 7; ++$wday) {
1913
							$daynow = $monthnow + $wday * 60 * 60 * 24;
1914
							$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
1915
1916
							if ($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) { // Selected ?
1917
								$firstday = $wday;
1918
								break;
1919
							}
1920
						}
1921
1922
						// Same as above (monthly)
1923
						$daynow = $monthnow + ($firstday + ($this->recur["nday"] - 1) * 7) * 60 * 60 * 24;
1924
1925
						while ($this->monthStartOf($daynow) != $this->monthStartOf($monthnow)) {
1926
							$daynow -= 7 * 60 * 60 * 24;
1927
						}
1928
1929
						$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1930
					}
1931
					elseif ($this->recur['regen']) {
1932
						$year_starttime = $this->gmtime($now);
1933
						$is_next_leapyear = $this->isLeapYear($year_starttime['tm_year'] + 1900 + 1);	// +1 next year
1934
						$now = $daystart + ($is_next_leapyear ? 31622400 /* Leap year in seconds */ : 31536000 /* year in seconds */);
1935
1936
						if ($now <= $dayend) {
1937
							$this->processOccurrenceItem($items, $daystart, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
1938
						}
1939
					}
1940
				}
1941
				break;
1942
		}
1943
		// to get all exception items
1944
		if (!empty($this->recur['changed_occurrences'])) {
1945
			$this->processExceptionItems($items, $start, $end);
0 ignored issues
show
The method processExceptionItems() does not exist on BaseRecurrence. It seems like you code against a sub-type of BaseRecurrence such as Recurrence. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1945
			$this->/** @scrutinizer ignore-call */ 
1946
          processExceptionItems($items, $start, $end);
Loading history...
1946
		}
1947
1948
		// sort items on starttime
1949
		usort($items, $this->sortStarttime(...));
1950
1951
		// Return the MAPI-compatible list of items for this object
1952
		return $items;
1953
	}
1954
1955
	/**
1956
	 * @psalm-return -1|0|1
1957
	 *
1958
	 * @param mixed $a
1959
	 * @param mixed $b
1960
	 */
1961
	public function sortStarttime($a, $b): int {
1962
		$aTime = $a[$this->proptags["startdate"]];
1963
		$bTime = $b[$this->proptags["startdate"]];
1964
1965
		return $aTime == $bTime ? 0 : ($aTime > $bTime ? 1 : -1);
1966
	}
1967
1968
	/**
1969
	 * daysInMonth.
1970
	 *
1971
	 * Returns the number of days in the upcoming number of months. If you specify 1 month as
1972
	 * $months it will give you the number of days in the month of $date. If you specify more it
1973
	 * will also count the days in the upcoming months and add that to the number of days. So
1974
	 * if you have a date in march and you specify $months as 2 it will return 61.
1975
	 *
1976
	 * @param int $date   specified date as timestamp from which you want to know the number
1977
	 *                    of days in the month
1978
	 * @param int $months number of months you want to know the number of days in
1979
	 *
1980
	 * @return float|int number of days in the specified amount of months
1981
	 */
1982
	public function daysInMonth($date, $months) {
1983
		$days = 0;
1984
1985
		for ($i = 0; $i < $months; ++$i) {
1986
			$days += date("t", $date + $days * 24 * 60 * 60);
1987
		}
1988
1989
		return $days;
1990
	}
1991
1992
	// Converts MAPI-style 'minutes' into the month of the year [0..11]
1993
	public function monthOfYear($minutes) {
1994
		$d = gmmktime(0, 0, 0, 1, 1, 2001); // The year 2001 was a non-leap year, and the minutes provided are always in non-leap-year-minutes
1995
1996
		$d += $minutes * 60;
1997
1998
		$dtime = $this->gmtime($d);
1999
2000
		return $dtime["tm_mon"];
2001
	}
2002
2003
	/**
2004
	 * @psalm-return -1|0|1
2005
	 *
2006
	 * @param mixed $a
2007
	 * @param mixed $b
2008
	 */
2009
	public function sortExceptionStart($a, $b): int {
2010
		return $a["start"] == $b["start"] ? 0 : ($a["start"] > $b["start"] ? 1 : -1);
2011
	}
2012
2013
	/**
2014
	 * Function to get all properties of a single changed exception.
2015
	 *
2016
	 * @param mixed $exception
2017
	 *
2018
	 * @return (mixed|true)[] associative array of properties for the exception
2019
	 *
2020
	 * @psalm-return array<mixed|true>
2021
	 */
2022
	public function getExceptionProperties($exception): array {
2023
		// Exception has same properties as main object, with some properties overridden:
2024
		$item = $this->messageprops;
2025
2026
		// Special properties
2027
		$item["exception"] = true;
2028
		$item["basedate"] = $exception["basedate"]; // note that the basedate is always in local time !
2029
2030
		// MAPI-compatible properties (you can handle an exception as a normal calendar item like this)
2031
		$item[$this->proptags["startdate"]] = $this->toGMT($this->tz, $exception["start"]);
2032
		$item[$this->proptags["duedate"]] = $this->toGMT($this->tz, $exception["end"]);
2033
		$item[$this->proptags["commonstart"]] = $item[$this->proptags["startdate"]];
2034
		$item[$this->proptags["commonend"]] = $item[$this->proptags["duedate"]];
2035
2036
		if (isset($exception["subject"])) {
2037
			$item[$this->proptags["subject"]] = $exception["subject"];
2038
		}
2039
2040
		if (isset($exception["label"])) {
2041
			$item[$this->proptags["label"]] = $exception["label"];
2042
		}
2043
2044
		if (isset($exception["alldayevent"])) {
2045
			$item[$this->proptags["alldayevent"]] = $exception["alldayevent"];
2046
		}
2047
2048
		if (isset($exception["location"])) {
2049
			$item[$this->proptags["location"]] = $exception["location"];
2050
		}
2051
2052
		if (isset($exception["remind_before"])) {
2053
			$item[$this->proptags["reminder_minutes"]] = $exception["remind_before"];
2054
		}
2055
2056
		if (isset($exception["reminder_set"])) {
2057
			$item[$this->proptags["reminder"]] = $exception["reminder_set"];
2058
		}
2059
2060
		if (isset($exception["busystatus"])) {
2061
			$item[$this->proptags["busystatus"]] = $exception["busystatus"];
2062
		}
2063
2064
		return $item;
2065
	}
2066
2067
	/**
2068
	 * @param false|int $start
2069
	 * @param false|int $basedate
2070
	 * @param mixed     $startocc
2071
	 * @param mixed     $endocc
2072
	 * @param mixed     $tz
2073
	 * @param mixed     $reminderonly
2074
	 */
2075
	abstract public function processOccurrenceItem(array &$items, $start, int $end, $basedate, $startocc, $endocc, $tz, $reminderonly);
2076
}
2077