simplifyRestriction()   F
last analyzed

Complexity

Conditions 43
Paths 126

Size

Total Lines 175
Code Lines 118

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 43
eloc 118
c 2
b 0
f 0
nc 126
nop 1
dl 0
loc 175
rs 3.16

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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-2024 grommunio GmbH
7
 */
8
9
define('NOERROR', 0);
10
define('SECONDS_PER_DAY', 86400);
11
12
// Load all mapi defs
13
mapi_load_mapidefs(1);
14
15
/**
16
 * Function to make a MAPIGUID from a php string.
17
 * The C++ definition for the GUID is:
18
 *  typedef struct _GUID
19
 *  {
20
 *   unsigned long        Data1;
21
 *   unsigned short       Data2;
22
 *   unsigned short       Data3;
23
 *   unsigned char        Data4[8];
24
 *  } GUID;.
25
 *
26
 * A GUID is normally represented in the following form:
27
 *  {00062008-0000-0000-C000-000000000046}
28
 */
29
function makeGuid(string $guid): string {
30
	return pack("vvvv", hexdec(substr($guid, 5, 4)), hexdec(substr($guid, 1, 4)), hexdec(substr($guid, 10, 4)), hexdec(substr($guid, 15, 4))) . hex2bin(substr($guid, 20, 4)) . hex2bin(substr($guid, 25, 12));
31
}
32
33
/**
34
 * Function to get a human readable string from a MAPI error code.
35
 *
36
 * @return string The defined name for the MAPI error code
37
 */
38
function get_mapi_error_name(mixed $errcode = null): string {
39
	static $errorCache = null;
40
41
	if ($errcode === null) {
42
		$errcode = mapi_last_hresult();
43
	}
44
45
	if (strncasecmp((string) $errcode, '0x', 2) === 0) {
46
		$errcode = hexdec($errcode);
47
	}
48
49
	if ($errcode === 0) {
50
		return "NOERROR";
51
	}
52
53
	// Build cache on first call for performance
54
	if ($errorCache === null) {
55
		$errorCache = [];
56
		// Retrieve constants categories, MAPI error names are defined in gromox.
57
		foreach (get_defined_constants(true)['Core'] as $key => $value) {
58
			/*
59
			 * If PHP encounters a number beyond the bounds of the integer type,
60
			 * it will be interpreted as a float instead, so when comparing these error codes
61
			 * we have to manually typecast value to integer, so float will be converted in integer,
62
			 * but still its out of bound for integer limit so it will be auto adjusted to minus value
63
			 */
64
			if (strncmp($key, "MAPI_E_", 7) === 0 ||
65
				strncmp($key, "MAPI_W_", 7) === 0 ||
66
				strncmp($key, "ec", 2) === 0) {
67
				$errorCache[(int) $value] = $key;
68
			}
69
		}
70
	}
71
72
	if (isset($errorCache[$errcode])) {
73
		return $errorCache[$errcode];
74
	}
75
76
	// error code not found, return hex value (this is a fix for 64-bit systems, we can't use the dechex() function for this)
77
	$result = unpack("H*", pack("N", $errcode));
78
79
	return "0x" . $result[1];
80
}
81
82
/**
83
 * Parses properties from an array of strings. Each "string" may be either an ULONG, which is a direct property ID,
84
 * or a string with format "PT_TYPE:{GUID}:StringId" or "PT_TYPE:{GUID}:0xXXXX" for named
85
 * properties.
86
 */
87
function getPropIdsFromStrings(mixed $store, array $mapping): array {
88
	$props = [];
89
90
	$ids = ["name" => [], "id" => [], "guid" => [], "type" => []]; // this array stores all the information needed to retrieve a named property
91
	$num = 0;
92
93
	// caching
94
	$guids = [];
95
96
	foreach ($mapping as $name => $val) {
97
		if (is_string($val)) {
98
			$split = explode(":", $val);
99
100
			if (count($split) != 3) { // invalid string, ignore
101
				trigger_error(sprintf("Invalid property: %s \"%s\"", $name, $val), E_USER_NOTICE);
102
103
				continue;
104
			}
105
106
			if (str_starts_with($split[2], "0x")) {
107
				$id = hexdec(substr($split[2], 2));
108
			}
109
			elseif (preg_match('/^[1-9][0-9]{0,12}$/', $split[2])) {
110
				$id = (int) $split[2];
111
			}
112
			else {
113
				$id = $split[2];
114
			}
115
116
			// have we used this guid before?
117
			if (!defined($split[1])) {
118
				if (!array_key_exists($split[1], $guids)) {
119
					$guids[$split[1]] = makeGuid($split[1]);
120
				}
121
				$guid = $guids[$split[1]];
122
			}
123
			else {
124
				$guid = constant($split[1]);
125
			}
126
127
			// temp store info about named prop, so we have to call mapi_getidsfromnames just one time
128
			$ids["name"][$num] = $name;
129
			$ids["id"][$num] = $id;
130
			$ids["guid"][$num] = $guid;
131
			$ids["type"][$num] = $split[0];
132
			++$num;
133
		}
134
		else {
135
			// not a named property
136
			$props[$name] = $val;
137
		}
138
	}
139
140
	if (empty($ids["id"])) {
141
		return $props;
142
	}
143
144
	// get the ids
145
	$named = mapi_getidsfromnames($store, $ids["id"], $ids["guid"]);
146
	foreach ($named as $num => $prop) {
147
		$props[$ids["name"][$num]] = mapi_prop_tag(constant($ids["type"][$num]), mapi_prop_id($prop));
148
	}
149
150
	return $props;
151
}
152
153
/**
154
 * Check whether a call to mapi_getprops returned errors for some properties.
155
 * mapi_getprops function tries to get values of properties requested but somehow if
156
 * if a property value can not be fetched then it changes type of property tag as PT_ERROR
157
 * and returns error for that particular property, probable errors
158
 * that can be returned as value can be MAPI_E_NOT_FOUND, MAPI_E_NOT_ENOUGH_MEMORY.
159
 *
160
 * @return false|mixed Gives back false when there is no error, if there is, gives the error
161
 */
162
function propIsError(int $property, array $propArray): mixed {
163
	$errorTag = mapi_prop_tag(PT_ERROR, mapi_prop_id($property));
164
165
	return $propArray[$errorTag] ?? false;
166
}
167
168
/**
169
 * Note: Static function, more like a utility function.
170
 *
171
 * Gets all the items (including recurring items) in the specified calendar in the given timeframe. Items are
172
 * included as a whole if they overlap the interval <$start, $end> (non-inclusive). This means that if the interval
173
 * is <08:00 - 14:00>, the item [6:00 - 8:00> is NOT included, nor is the item [14:00 - 16:00>. However, the item
174
 * [7:00 - 9:00> is included as a whole, and is NOT capped to [8:00 - 9:00>.
175
 *
176
 * @param resource $store          The store in which the calendar resides
177
 * @param resource $calendar       The calendar to get the items from
178
 * @param int      $viewstart      Timestamp of beginning of view window
179
 * @param int      $viewend        Timestamp of end of view window
180
 * @param array    $propsrequested Array of properties to return
181
 *
182
 * @psalm-return list<mixed>
183
 */
184
function getCalendarItems(mixed $store, mixed $calendar, int $viewstart, int $viewend, array $propsrequested): array {
185
	$result = [];
186
	$properties = getPropIdsFromStrings($store, [
187
		"duedate" => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentEndWhole,
188
		"startdate" => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentStartWhole,
189
		"enddate_recurring" => "PT_SYSTIME:PSETID_Appointment:" . PidLidClipEnd,
190
		"recurring" => "PT_BOOLEAN:PSETID_Appointment:" . PidLidRecurring,
191
		"recurring_data" => "PT_BINARY:PSETID_Appointment:" . PidLidAppointmentRecur,
192
		"timezone_data" => "PT_BINARY:PSETID_Appointment:" . PidLidTimeZoneStruct,
193
		"label" => "PT_LONG:PSETID_Appointment:0x8214",
194
	]);
195
196
	// Create a restriction that will discard rows of appointments that are definitely not in our
197
	// requested time frame
198
199
	$table = mapi_folder_getcontentstable($calendar);
200
201
	$restriction =
202
		// OR
203
		[
204
			RES_OR,
205
			[
206
				[RES_AND,	// Normal items: itemEnd must be after viewStart, itemStart must be before viewEnd
207
					[
208
						[
209
							RES_PROPERTY,
210
							[
211
								RELOP => RELOP_GT,
212
								ULPROPTAG => $properties["duedate"],
213
								VALUE => $viewstart,
214
							],
215
						],
216
						[
217
							RES_PROPERTY,
218
							[
219
								RELOP => RELOP_LT,
220
								ULPROPTAG => $properties["startdate"],
221
								VALUE => $viewend,
222
							],
223
						],
224
					],
225
				],
226
				// OR
227
				[
228
					RES_PROPERTY,
229
					[
230
						RELOP => RELOP_EQ,
231
						ULPROPTAG => $properties["recurring"],
232
						VALUE => true,
233
					],
234
				],
235
			],	// EXISTS OR
236
		];		// global OR
237
238
	// Get requested properties, plus whatever we need
239
	$proplist = [PR_ENTRYID, $properties["recurring"], $properties["recurring_data"], $properties["timezone_data"]];
240
	$proplist = array_merge($proplist, $propsrequested);
241
242
	$rows = mapi_table_queryallrows($table, $proplist, $restriction);
243
244
	// $rows now contains all the items that MAY be in the window; a recurring item needs expansion before including in the output.
245
246
	foreach ($rows as $row) {
247
		$items = [];
248
249
		if (isset($row[$properties["recurring"]]) && $row[$properties["recurring"]]) {
250
			// Recurring item
251
			$rec = new Recurrence($store, $row);
252
253
			// GetItems guarantees that the item overlaps the interval <$viewstart, $viewend>
254
			$occurrences = $rec->getItems($viewstart, $viewend);
255
			foreach ($occurrences as $occurrence) {
256
				// The occurrence takes all properties from the main row, but overrides some properties (like start and end obviously)
257
				$item = $occurrence + $row;
258
				$items[] = $item;
259
			}
260
		}
261
		else {
262
			// Normal item, it matched the search criteria and therefore overlaps the interval <$viewstart, $viewend>
263
			$items[] = $row;
264
		}
265
266
		$result = array_merge($result, $items);
267
	}
268
269
	// All items are guaranteed to overlap the interval <$viewstart, $viewend>. Note that we may be returning a few extra
270
	// properties that the caller did not request (recurring, etc). This shouldn't be a problem though.
271
	return $result;
272
}
273
274
/**
275
 * Compares two entryIds. It is possible to have two different entryIds that should match as they
276
 * represent the same object (in multiserver environments).
277
 *
278
 * @return bool Result of the comparison
279
 */
280
function compareEntryIds(mixed $entryId1, mixed $entryId2): bool {
281
	if (!is_string($entryId1) || !is_string($entryId2)) {
282
		return false;
283
	}
284
285
	// if normal comparison succeeds then we can directly say that entryids are same
286
	return $entryId1 === $entryId2;
287
}
288
289
/**
290
 * Creates a goid from an ical uuid.
291
 *
292
 * @return string binary string representation of goid
293
 */
294
function getGoidFromUid(string $uid): string {
295
	return hex2bin("040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000" .
296
				bin2hex(pack("V", 12 + strlen($uid)) . "vCal-Uid" . pack("V", 1) . $uid));
297
}
298
299
/**
300
 * Returns zero terminated goid. It is required for backwards compatibility.
301
 *
302
 * @return string an OL compatible GlobalObjectID
303
 */
304
function getGoidFromUidZero(string $uid): string {
305
	if (strlen((string) $uid) <= 64) {
306
		return hex2bin("040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000" .
307
			bin2hex(pack("V", 13 + strlen((string) $uid)) . "vCal-Uid" . pack("V", 1) . $uid) . "00");
308
	}
309
310
	return hex2bin((string) $uid);
311
}
312
313
/**
314
 * Creates an ical uuid from a goid.
315
 *
316
 * @return null|string ical uuid
317
 */
318
function getUidFromGoid(string $goid): ?string {
319
	// check if "vCal-Uid" is somewhere in outlookid case-insensitive
320
	$uid = stristr($goid, "vCal-Uid");
321
	if ($uid !== false) {
322
		// get the length of the ical id - go back 4 position from where "vCal-Uid" was found
323
		$begin = unpack("V", substr($goid, strlen($uid) * (-1) - 4, 4));
324
325
		// remove "vCal-Uid" and packed "1" and use the ical id length
326
		return trim(substr($uid, 12, $begin[1] - 12));
327
	}
328
329
	return null;
330
}
331
332
/**
333
 * Converts a MAPI property tag into a human readable value.
334
 *
335
 * This depends on the definition of the property tag in core
336
 *
337
 * @example prop2Str(0x0037001e) => 'PR_SUBJECT'
338
 *
339
 * @return string the symbolic name of the property tag
340
 */
341
function prop2Str(mixed $property): string {
342
	static $propertyCache = null;
343
344
	if (is_int($property)) {
345
		// Build cache on first call for performance
346
		if ($propertyCache === null) {
347
			$propertyCache = [];
348
			foreach (get_defined_constants(true)['Core'] as $key => $value) {
349
				if (str_starts_with($key, 'PR_')) {
350
					$propertyCache[$value] = $key;
351
				}
352
			}
353
		}
354
355
		return $propertyCache[$property] ?? sprintf("0x%08X", $property);
356
	}
357
358
	return $property;
359
}
360
361
/**
362
 * Converts RELOP constant to human readable string.
363
 */
364
function relOpToString(int $relOp): string {
365
	return match ($relOp) {
366
		RELOP_LT => "RELOP_LT",
367
		RELOP_LE => "RELOP_LE",
368
		RELOP_GT => "RELOP_GT",
369
		RELOP_GE => "RELOP_GE",
370
		RELOP_EQ => "RELOP_EQ",
371
		RELOP_NE => "RELOP_NE",
372
		RELOP_RE => "RELOP_RE",
373
		default => "",
374
	};
375
}
376
377
/**
378
 * Converts all constants of restriction into a human readable strings.
379
 */
380
function simplifyRestriction(mixed $restriction): mixed {
381
	if (!is_array($restriction)) {
382
		return $restriction;
383
	}
384
385
	switch ($restriction[0]) {
386
		case RES_AND:
387
			$restriction[0] = "RES_AND";
388
			if (isset($restriction[1][0]) && is_array($restriction[1][0])) {
389
				foreach ($restriction[1] as &$res) {
390
					$res = simplifyRestriction($res);
391
				}
392
				unset($res);
393
			}
394
			elseif (isset($restriction[1]) && $restriction[1]) {
395
				$restriction[1] = simplifyRestriction($restriction[1]);
396
			}
397
			break;
398
399
		case RES_OR:
400
			$restriction[0] = "RES_OR";
401
			if (isset($restriction[1][0]) && is_array($restriction[1][0])) {
402
				foreach ($restriction[1] as &$res) {
403
					$res = simplifyRestriction($res);
404
				}
405
				unset($res);
406
			}
407
			elseif (isset($restriction[1]) && $restriction[1]) {
408
				$restriction[1] = simplifyRestriction($restriction[1]);
409
			}
410
			break;
411
412
		case RES_NOT:
413
			$restriction[0] = "RES_NOT";
414
			$restriction[1][0] = simplifyRestriction($restriction[1][0]);
415
			break;
416
417
		case RES_COMMENT:
418
			$restriction[0] = "RES_COMMENT";
419
			$res = simplifyRestriction($restriction[1][RESTRICTION]);
420
			$props = $restriction[1][PROPS];
421
422
			foreach ($props as &$prop) {
423
				$propTag = $prop[ULPROPTAG];
424
				$propValue = $prop[VALUE];
425
426
				unset($prop);
427
428
				$prop["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
429
				$prop["VALUE"] = is_array($propValue) ? $propValue[$propTag] : $propValue;
430
			}
431
			unset($prop, $restriction[1]);
432
433
			$restriction[1]["RESTRICTION"] = $res;
434
			$restriction[1]["PROPS"] = $props;
435
			break;
436
437
		case RES_PROPERTY:
438
			$restriction[0] = "RES_PROPERTY";
439
			$propTag = $restriction[1][ULPROPTAG];
440
			$propValue = $restriction[1][VALUE];
441
			$relOp = $restriction[1][RELOP];
442
443
			unset($restriction[1]);
444
445
			$restriction[1]["RELOP"] = relOpToString($relOp);
446
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
447
			$restriction[1]["VALUE"] = is_array($propValue) ? $propValue[$propTag] : $propValue;
448
			break;
449
450
		case RES_CONTENT:
451
			$restriction[0] = "RES_CONTENT";
452
			$propTag = $restriction[1][ULPROPTAG];
453
			$propValue = $restriction[1][VALUE];
454
			$fuzzyLevel = $restriction[1][FUZZYLEVEL];
455
456
			unset($restriction[1]);
457
458
			// fuzzy level flags
459
			$levels = [];
460
461
			if (($fuzzyLevel & FL_SUBSTRING) == FL_SUBSTRING) {
462
				$levels[] = "FL_SUBSTRING";
463
			}
464
			elseif (($fuzzyLevel & FL_PREFIX) == FL_PREFIX) {
465
				$levels[] = "FL_PREFIX";
466
			}
467
			else {
468
				$levels[] = "FL_FULLSTRING";
469
			}
470
471
			if (($fuzzyLevel & FL_IGNORECASE) == FL_IGNORECASE) {
472
				$levels[] = "FL_IGNORECASE";
473
			}
474
475
			if (($fuzzyLevel & FL_IGNORENONSPACE) == FL_IGNORENONSPACE) {
476
				$levels[] = "FL_IGNORENONSPACE";
477
			}
478
479
			if (($fuzzyLevel & FL_LOOSE) == FL_LOOSE) {
480
				$levels[] = "FL_LOOSE";
481
			}
482
483
			$fuzzyLevelFlags = implode(" | ", $levels);
484
485
			$restriction[1]["FUZZYLEVEL"] = $fuzzyLevelFlags;
486
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
487
			$restriction[1]["VALUE"] = is_array($propValue) ? $propValue[$propTag] : $propValue;
488
			break;
489
490
		case RES_COMPAREPROPS:
491
			$propTag1 = $restriction[1][ULPROPTAG1];
492
			$propTag2 = $restriction[1][ULPROPTAG2];
493
494
			unset($restriction[1]);
495
496
			$restriction[1]["ULPROPTAG1"] = is_string($propTag1) ? $propTag1 : prop2Str($propTag1);
497
			$restriction[1]["ULPROPTAG2"] = is_string($propTag2) ? $propTag2 : prop2Str($propTag2);
498
			break;
499
500
		case RES_BITMASK:
501
			$restriction[0] = "RES_BITMASK";
502
			$propTag = $restriction[1][ULPROPTAG];
503
			$maskType = $restriction[1][ULTYPE];
504
			$maskValue = $restriction[1][ULMASK];
505
506
			unset($restriction[1]);
507
508
			// relop flags
509
			$maskTypeFlags = "";
510
			if ($maskType == BMR_EQZ) {
511
				$maskTypeFlags = "BMR_EQZ";
512
			}
513
			elseif ($maskType == BMR_NEZ) {
514
				$maskTypeFlags = "BMR_NEZ";
515
			}
516
517
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
518
			$restriction[1]["ULTYPE"] = $maskTypeFlags;
519
			$restriction[1]["ULMASK"] = $maskValue;
520
			break;
521
522
		case RES_SIZE:
523
			$restriction[0] = "RES_SIZE";
524
			$propTag = $restriction[1][ULPROPTAG];
525
			$propValue = $restriction[1][CB];
526
			$relOp = $restriction[1][RELOP];
527
528
			unset($restriction[1]);
529
530
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
531
			$restriction[1]["RELOP"] = relOpToString($relOp);
532
			$restriction[1]["CB"] = $propValue;
533
			break;
534
535
		case RES_EXIST:
536
			$propTag = $restriction[1][ULPROPTAG];
537
538
			unset($restriction[1]);
539
540
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
541
			break;
542
543
		case RES_SUBRESTRICTION:
544
			$propTag = $restriction[1][ULPROPTAG];
545
			$res = simplifyRestriction($restriction[1][RESTRICTION]);
546
547
			unset($restriction[1]);
548
549
			$restriction[1]["ULPROPTAG"] = is_string($propTag) ? $propTag : prop2Str($propTag);
550
			$restriction[1]["RESTRICTION"] = $res;
551
			break;
552
	}
553
554
	return $restriction;
555
}
556