Test Failed
Branch master (1ac602)
by Mike
02:45
created

compareEntryIds()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
c 1
b 0
f 0
nop 2
dl 0
loc 11
rs 10
nc 3
1
<?php
2
/*
3
 * SPDX-License-Identifier: AGPL-3.0-only
4
 * SPDX-FileCopyrightText: Copyright 2005-2016 Zarafa Deutschland GmbH
5
 * SPDX-FileCopyrightText: Copyright 2020-2022 grommunio GmbH
6
 */
7
8
/**
9
 * Function to make a MAPIGUID from a php string.
10
 * The C++ definition for the GUID is:
11
 *  typedef struct _GUID
12
 *  {
13
 *   unsigned long        Data1;
14
 *   unsigned short       Data2;
15
 *   unsigned short       Data3;
16
 *   unsigned char        Data4[8];
17
 *  } GUID;.
18
 *
19
 * A GUID is normally represented in the following form:
20
 * 	{00062008-0000-0000-C000-000000000046}
21
 *
22
 * @param string GUID
0 ignored issues
show
Bug introduced by
The type GUID was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
 * @param mixed $guid
24
 */
25
function makeGuid($guid) {
26
	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));
27
}
28
29
/**
30
 * Function to get a human readable string from a MAPI error code.
31
 *
32
 *@param int $errcode the MAPI error code, if not given, we use mapi_last_hresult
33
 *
34
 *@return string The defined name for the MAPI error code
35
 */
36
function get_mapi_error_name($errcode = null) {
37
	if ($errcode === null) {
38
		$errcode = mapi_last_hresult();
39
	}
40
41
	if ($errcode !== 0) {
42
		// Retrieve constants categories, MAPI error names are defined
43
		// in the 'user' category, since the grommunio code defines it in mapicode.php.
44
		foreach (get_defined_constants(true)['user'] as $key => $value) {
45
			/*
46
			 * If PHP encounters a number beyond the bounds of the integer type,
47
			 * it will be interpreted as a float instead, so when comparing these error codes
48
			 * we have to manually typecast value to integer, so float will be converted in integer,
49
			 * but still its out of bound for integer limit so it will be auto adjusted to minus value
50
			 */
51
			if ($errcode == (int) $value) {
52
				// Check that we have an actual MAPI error or warning definition
53
				$prefix = substr($key, 0, 7);
54
				if ($prefix == "MAPI_E_" || $prefix == "MAPI_W_") {
55
					return $key;
56
				}
57
			}
58
		}
59
	}
60
	else {
61
		return "NOERROR";
62
	}
63
64
	// error code not found, return hex value (this is a fix for 64-bit systems, we can't use the dechex() function for this)
65
	$result = unpack("H*", pack("N", $errcode));
66
67
	return "0x" . $result[1];
68
}
69
70
/**
71
 * Parses properties from an array of strings. Each "string" may be either an ULONG, which is a direct property ID,
72
 * or a string with format "PT_TYPE:{GUID}:StringId" or "PT_TYPE:{GUID}:0xXXXX" for named
73
 * properties.
74
 *
75
 * @returns array of properties
76
 *
77
 * @param mixed $store
78
 * @param mixed $mapping
79
 */
80
function getPropIdsFromStrings($store, $mapping) {
81
	$props = [];
82
83
	$ids = ["name" => [], "id" => [], "guid" => [], "type" => []]; // this array stores all the information needed to retrieve a named property
84
	$num = 0;
85
86
	// caching
87
	$guids = [];
88
89
	foreach ($mapping as $name => $val) {
90
		if (is_string($val)) {
91
			$split = explode(":", $val);
92
93
			if (count($split) != 3) { // invalid string, ignore
94
				trigger_error(sprintf("Invalid property: %s \"%s\"", $name, $val), E_USER_NOTICE);
95
96
				continue;
97
			}
98
99
			if (substr($split[2], 0, 2) == "0x") {
100
				$id = hexdec(substr($split[2], 2));
101
			}
102
			else {
103
				$id = $split[2];
104
			}
105
106
			// have we used this guid before?
107
			if (!defined($split[1])) {
108
				if (!array_key_exists($split[1], $guids)) {
109
					$guids[$split[1]] = makeguid($split[1]);
110
				}
111
				$guid = $guids[$split[1]];
112
			}
113
			else {
114
				$guid = constant($split[1]);
115
			}
116
117
			// temp store info about named prop, so we have to call mapi_getidsfromnames just one time
118
			$ids["name"][$num] = $name;
119
			$ids["id"][$num] = $id;
120
			$ids["guid"][$num] = $guid;
121
			$ids["type"][$num] = $split[0];
122
			++$num;
123
		}
124
		else {
125
			// not a named property
126
			$props[$name] = $val;
127
		}
128
	}
129
130
	if (empty($ids["id"])) {
131
		return $props;
132
	}
133
134
	// get the ids
135
	$named = mapi_getidsfromnames($store, $ids["id"], $ids["guid"]);
0 ignored issues
show
Bug introduced by
The function mapi_getidsfromnames was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

135
	$named = /** @scrutinizer ignore-call */ mapi_getidsfromnames($store, $ids["id"], $ids["guid"]);
Loading history...
136
	foreach ($named as $num => $prop) {
137
		$props[$ids["name"][$num]] = mapi_prop_tag(constant($ids["type"][$num]), mapi_prop_id($prop));
0 ignored issues
show
Bug introduced by
The function mapi_prop_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

137
		$props[$ids["name"][$num]] = mapi_prop_tag(constant($ids["type"][$num]), /** @scrutinizer ignore-call */ mapi_prop_id($prop));
Loading history...
Bug introduced by
The function mapi_prop_tag was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

137
		$props[$ids["name"][$num]] = /** @scrutinizer ignore-call */ mapi_prop_tag(constant($ids["type"][$num]), mapi_prop_id($prop));
Loading history...
138
	}
139
140
	return $props;
141
}
142
143
/**
144
 * Check whether a call to mapi_getprops returned errors for some properties.
145
 * mapi_getprops function tries to get values of properties requested but somehow if
146
 * if a property value can not be fetched then it changes type of property tag as PT_ERROR
147
 * and returns error for that particular property, probable errors
148
 * that can be returned as value can be MAPI_E_NOT_FOUND, MAPI_E_NOT_ENOUGH_MEMORY.
149
 *
150
 * @param long  $property  Property to check for error
0 ignored issues
show
Bug introduced by
The type long was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
151
 * @param array $propArray An array of properties
152
 *
153
 * @return mixed Gives back false when there is no error, if there is, gives the error
154
 */
155
function propIsError($property, $propArray) {
156
	if (array_key_exists(mapi_prop_tag(PT_ERROR, mapi_prop_id($property)), $propArray)) {
0 ignored issues
show
Bug introduced by
The function mapi_prop_tag was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

156
	if (array_key_exists(/** @scrutinizer ignore-call */ mapi_prop_tag(PT_ERROR, mapi_prop_id($property)), $propArray)) {
Loading history...
Bug introduced by
The function mapi_prop_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

156
	if (array_key_exists(mapi_prop_tag(PT_ERROR, /** @scrutinizer ignore-call */ mapi_prop_id($property)), $propArray)) {
Loading history...
157
		return $propArray[mapi_prop_tag(PT_ERROR, mapi_prop_id($property))];
158
	}
159
160
	return false;
161
}
162
163
/* Macro Functions for PR_DISPLAY_TYPE_EX values */
164
/**
165
 * check addressbook object is a remote mailuser.
166
 *
167
 * @param mixed $value
168
 */
169
function DTE_IS_REMOTE_VALID($value) {
170
	return (bool) ($value & DTE_FLAG_REMOTE_VALID);
171
}
172
173
/**
174
 * check addressbook object is able to receive permissions.
175
 *
176
 * @param mixed $value
177
 */
178
function DTE_IS_ACL_CAPABLE($value) {
179
	return (bool) ($value & DTE_FLAG_ACL_CAPABLE);
180
}
181
182
function DTE_REMOTE($value) {
183
	return ($value & DTE_MASK_REMOTE) >> 8;
184
}
185
186
function DTE_LOCAL($value) {
187
	return $value & DTE_MASK_LOCAL;
188
}
189
190
/**
191
 * Note: Static function, more like a utility function.
192
 *
193
 * Gets all the items (including recurring items) in the specified calendar in the given timeframe. Items are
194
 * included as a whole if they overlap the interval <$start, $end> (non-inclusive). This means that if the interval
195
 * 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
196
 * [7:00 - 9:00> is included as a whole, and is NOT capped to [8:00 - 9:00>.
197
 *
198
 * @param $store resource The store in which the calendar resides
199
 * @param $calendar resource The calendar to get the items from
200
 * @param $viewstart int Timestamp of beginning of view window
201
 * @param $viewend int Timestamp of end of view window
202
 * @param $propsrequested array Array of properties to return
203
 * @param $rows array Array of rowdata as if they were returned directly from mapi_table_queryrows. Each recurring item is
204
 *                    expanded so that it seems that there are only many single appointments in the table.
205
 */
206
function getCalendarItems($store, $calendar, $viewstart, $viewend, $propsrequested) {
207
	$result = [];
208
	$properties = getPropIdsFromStrings($store, [
209
		"duedate" => "PT_SYSTIME:PSETID_Appointment:0x820e",
210
		"startdate" => "PT_SYSTIME:PSETID_Appointment:0x820d",
211
		"enddate_recurring" => "PT_SYSTIME:PSETID_Appointment:0x8236",
212
		"recurring" => "PT_BOOLEAN:PSETID_Appointment:0x8223",
213
		"recurring_data" => "PT_BINARY:PSETID_Appointment:0x8216",
214
		"timezone_data" => "PT_BINARY:PSETID_Appointment:0x8233",
215
		"label" => "PT_LONG:PSETID_Appointment:0x8214",
216
	]);
217
218
	// Create a restriction that will discard rows of appointments that are definitely not in our
219
	// requested time frame
220
221
	$table = mapi_folder_getcontentstable($calendar);
222
223
	$restriction =
224
		// OR
225
		[
226
			RES_OR,
227
			[
228
				[RES_AND,	// Normal items: itemEnd must be after viewStart, itemStart must be before viewEnd
229
					[
230
						[
231
							RES_PROPERTY,
232
							[
233
								RELOP => RELOP_GT,
234
								ULPROPTAG => $properties["duedate"],
235
								VALUE => $viewstart,
236
							],
237
						],
238
						[
239
							RES_PROPERTY,
240
							[
241
								RELOP => RELOP_LT,
242
								ULPROPTAG => $properties["startdate"],
243
								VALUE => $viewend,
244
							],
245
						],
246
					],
247
				],
248
				// OR
249
				[
250
					RES_PROPERTY,
251
					[
252
						RELOP => RELOP_EQ,
253
						ULPROPTAG => $properties["recurring"],
254
						VALUE => true,
255
					],
256
				],
257
			],	// EXISTS OR
258
		];		// global OR
259
260
	// Get requested properties, plus whatever we need
261
	$proplist = [PR_ENTRYID, $properties["recurring"], $properties["recurring_data"], $properties["timezone_data"]];
262
	$proplist = array_merge($proplist, $propsrequested);
263
264
	$rows = mapi_table_queryallrows($table, $proplist, $restriction);
265
266
	// $rows now contains all the items that MAY be in the window; a recurring item needs expansion before including in the output.
267
268
	foreach ($rows as $row) {
269
		$items = [];
270
271
		if (isset($row[$properties["recurring"]]) && $row[$properties["recurring"]]) {
272
			// Recurring item
273
			$rec = new Recurrence($store, $row);
274
275
			// GetItems guarantees that the item overlaps the interval <$viewstart, $viewend>
276
			$occurrences = $rec->getItems($viewstart, $viewend);
277
			foreach ($occurrences as $occurrence) {
278
				// The occurrence takes all properties from the main row, but overrides some properties (like start and end obviously)
279
				$item = $occurrence + $row;
280
				array_push($items, $item);
281
			}
282
		}
283
		else {
284
			// Normal item, it matched the search criteria and therefore overlaps the interval <$viewstart, $viewend>
285
			array_push($items, $row);
286
		}
287
288
		$result = array_merge($result, $items);
289
	}
290
291
	// All items are guaranteed to overlap the interval <$viewstart, $viewend>. Note that we may be returning a few extra
292
	// properties that the caller did not request (recurring, etc). This shouldn't be a problem though.
293
	return $result;
294
}
295
296
	/**
297
	 * Compares two entryIds. It is possible to have two different entryIds that should match as they
298
	 * represent the same object (in multiserver environments).
299
	 *
300
	 * @param {String} entryId1 EntryID
301
	 * @param {String} entryId2 EntryID
0 ignored issues
show
Bug introduced by
The type entryId2 was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
302
	 * @param mixed $entryId1
303
	 * @param mixed $entryId2
304
	 *
305
	 * @return {Boolean} Result of the comparison
0 ignored issues
show
Documentation Bug introduced by
The doc comment {Boolean} at position 0 could not be parsed: Unknown type name '{' at position 0 in {Boolean}.
Loading history...
306
	 */
307
	function compareEntryIds($entryId1, $entryId2) {
308
		if (!is_string($entryId1) || !is_string($entryId2)) {
309
			return false;
310
		}
311
312
		if ($entryId1 === $entryId2) {
313
			// if normal comparison succeeds then we can directly say that entryids are same
314
			return true;
315
		}
316
317
		return false;
318
	}
319
320
	/**
321
	 * Creates a goid from an ical uuid.
322
	 *
323
	 * @param $uid
324
	 *
325
	 * @return string binary string representation of goid
326
	 */
327
	function getGoidFromUid($uid) {
328
		return hex2bin("040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000" .
329
					bin2hex(pack("V", 12 + strlen($uid)) . "vCal-Uid" . pack("V", 1) . $uid));
330
	}
331
332
	/**
333
	 * Creates an ical uuid from a goid.
334
	 *
335
	 * @param $goid
336
	 *
337
	 * @return string ical uuid
338
	 */
339
	function getUidFromGoid($goid) {
340
		// check if "vCal-Uid" is somewhere in outlookid case-insensitive
341
		$uid = stristr($goid, "vCal-Uid");
342
		if ($uid !== false) {
343
			// get the length of the ical id - go back 4 position from where "vCal-Uid" was found
344
			$begin = unpack("V", substr($goid, strlen($uid) * (-1) - 4, 4));
345
			// remove "vCal-Uid" and packed "1" and use the ical id length
346
			return substr($uid, 12, ($begin[1] - 12));
347
		}
348
349
		return null;
350
	}
351