Passed
Push — master ( f66da6...7a87af )
by
unknown
02:36 queued 15s
created

mapi.util.php (8 issues)

Labels
Severity
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-2024 grommunio GmbH
6
 */
7
8
define('NOERROR', 0);
9
10
// Load all mapi defs
11
if (function_exists('mapi_load_mapidefs')) {
12
    mapi_load_mapidefs(1);
13
} else {
14
    // code analysis with non-mapi php builds
15
    require 'dev/autoloader.php';
16
}
17
18
/**
19
 * Function to make a MAPIGUID from a php string.
20
 * The C++ definition for the GUID is:
21
 *  typedef struct _GUID
22
 *  {
23
 *   unsigned long        Data1;
24
 *   unsigned short       Data2;
25
 *   unsigned short       Data3;
26
 *   unsigned char        Data4[8];
27
 *  } GUID;.
28
 *
29
 * A GUID is normally represented in the following form:
30
 *  {00062008-0000-0000-C000-000000000046}
31
 *
32
 * @param string $guid
33
 */
34
function makeGuid($guid): string {
35
	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));
36
}
37
38
/**
39
 * Function to get a human readable string from a MAPI error code.
40
 *
41
 * @param mixed $errcode the MAPI error code, if not given, we use mapi_last_hresult
42
 *
43
 * @return string The defined name for the MAPI error code
44
 */
45
function get_mapi_error_name($errcode = null) {
46
	if ($errcode === null) {
47
		$errcode = mapi_last_hresult();
0 ignored issues
show
The function mapi_last_hresult 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

47
		$errcode = /** @scrutinizer ignore-call */ mapi_last_hresult();
Loading history...
48
	}
49
50
	if (strcasecmp(substr($errcode, 0, 2), '0x') === 0) {
51
		$errcode = hexdec($errcode);
52
	}
53
54
	if ($errcode !== 0) {
55
		// Retrieve constants categories, MAPI error names are defined in gromox.
56
		foreach (get_defined_constants(true)['Core'] as $key => $value) {
57
			/*
58
			 * If PHP encounters a number beyond the bounds of the integer type,
59
			 * it will be interpreted as a float instead, so when comparing these error codes
60
			 * we have to manually typecast value to integer, so float will be converted in integer,
61
			 * but still its out of bound for integer limit so it will be auto adjusted to minus value
62
			 */
63
			if ($errcode == (int) $value) {
64
				// Check that we have an actual MAPI error or warning definition
65
				$prefix = substr($key, 0, 7);
66
				if ($prefix == "MAPI_E_" || $prefix == "MAPI_W_") {
67
					return $key;
68
				}
69
				$prefix = substr($key, 0, 2);
70
				if ($prefix == "ec") {
71
					return $key;
72
				}
73
			}
74
		}
75
	}
76
	else {
77
		return "NOERROR";
78
	}
79
80
	// error code not found, return hex value (this is a fix for 64-bit systems, we can't use the dechex() function for this)
81
	$result = unpack("H*", pack("N", $errcode));
82
83
	return "0x" . $result[1];
84
}
85
86
/**
87
 * Parses properties from an array of strings. Each "string" may be either an ULONG, which is a direct property ID,
88
 * or a string with format "PT_TYPE:{GUID}:StringId" or "PT_TYPE:{GUID}:0xXXXX" for named
89
 * properties.
90
 *
91
 * @param mixed $store
92
 * @param mixed $mapping
93
 *
94
 * @return array
95
 */
96
function getPropIdsFromStrings($store, $mapping) {
97
	$props = [];
98
99
	$ids = ["name" => [], "id" => [], "guid" => [], "type" => []]; // this array stores all the information needed to retrieve a named property
100
	$num = 0;
101
102
	// caching
103
	$guids = [];
104
105
	foreach ($mapping as $name => $val) {
106
		if (is_string($val)) {
107
			$split = explode(":", $val);
108
109
			if (count($split) != 3) { // invalid string, ignore
110
				trigger_error(sprintf("Invalid property: %s \"%s\"", $name, $val), E_USER_NOTICE);
111
112
				continue;
113
			}
114
115
			if (substr($split[2], 0, 2) == "0x") {
116
				$id = hexdec(substr($split[2], 2));
117
			}
118
			elseif (preg_match('/^[1-9][0-9]{0,12}$/', $split[2])) {
119
				$id = (int) $split[2];
120
			}
121
			else {
122
				$id = $split[2];
123
			}
124
125
			// have we used this guid before?
126
			if (!defined($split[1])) {
127
				if (!array_key_exists($split[1], $guids)) {
128
					$guids[$split[1]] = makeguid($split[1]);
129
				}
130
				$guid = $guids[$split[1]];
131
			}
132
			else {
133
				$guid = constant($split[1]);
134
			}
135
136
			// temp store info about named prop, so we have to call mapi_getidsfromnames just one time
137
			$ids["name"][$num] = $name;
138
			$ids["id"][$num] = $id;
139
			$ids["guid"][$num] = $guid;
140
			$ids["type"][$num] = $split[0];
141
			++$num;
142
		}
143
		else {
144
			// not a named property
145
			$props[$name] = $val;
146
		}
147
	}
148
149
	if (empty($ids["id"])) {
150
		return $props;
151
	}
152
153
	// get the ids
154
	$named = mapi_getidsfromnames($store, $ids["id"], $ids["guid"]);
0 ignored issues
show
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

154
	$named = /** @scrutinizer ignore-call */ mapi_getidsfromnames($store, $ids["id"], $ids["guid"]);
Loading history...
155
	foreach ($named as $num => $prop) {
156
		$props[$ids["name"][$num]] = mapi_prop_tag(constant($ids["type"][$num]), mapi_prop_id($prop));
0 ignored issues
show
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
		$props[$ids["name"][$num]] = /** @scrutinizer ignore-call */ mapi_prop_tag(constant($ids["type"][$num]), mapi_prop_id($prop));
Loading history...
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
		$props[$ids["name"][$num]] = mapi_prop_tag(constant($ids["type"][$num]), /** @scrutinizer ignore-call */ mapi_prop_id($prop));
Loading history...
157
	}
158
159
	return $props;
160
}
161
162
/**
163
 * Check whether a call to mapi_getprops returned errors for some properties.
164
 * mapi_getprops function tries to get values of properties requested but somehow if
165
 * if a property value can not be fetched then it changes type of property tag as PT_ERROR
166
 * and returns error for that particular property, probable errors
167
 * that can be returned as value can be MAPI_E_NOT_FOUND, MAPI_E_NOT_ENOUGH_MEMORY.
168
 *
169
 * @param int   $property  Property to check for error
170
 * @param array $propArray An array of properties
171
 *
172
 * @return bool|mixed Gives back false when there is no error, if there is, gives the error
173
 */
174
function propIsError($property, $propArray) {
175
	if (array_key_exists(mapi_prop_tag(PT_ERROR, mapi_prop_id($property)), $propArray)) {
0 ignored issues
show
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

175
	if (array_key_exists(/** @scrutinizer ignore-call */ mapi_prop_tag(PT_ERROR, mapi_prop_id($property)), $propArray)) {
Loading history...
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

175
	if (array_key_exists(mapi_prop_tag(PT_ERROR, /** @scrutinizer ignore-call */ mapi_prop_id($property)), $propArray)) {
Loading history...
176
		return $propArray[mapi_prop_tag(PT_ERROR, mapi_prop_id($property))];
177
	}
178
179
	return false;
180
}
181
182
/**
183
 * Note: Static function, more like a utility function.
184
 *
185
 * Gets all the items (including recurring items) in the specified calendar in the given timeframe. Items are
186
 * included as a whole if they overlap the interval <$start, $end> (non-inclusive). This means that if the interval
187
 * 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
188
 * [7:00 - 9:00> is included as a whole, and is NOT capped to [8:00 - 9:00>.
189
 *
190
 * @param resource $store          The store in which the calendar resides
191
 * @param resource $calendar       The calendar to get the items from
192
 * @param int      $viewstart      Timestamp of beginning of view window
193
 * @param int      $viewend        Timestamp of end of view window
194
 * @param array    $propsrequested Array of properties to return
195
 *
196
 * @psalm-return list<mixed>
197
 */
198
function getCalendarItems($store, $calendar, $viewstart, $viewend, $propsrequested): array {
199
	$result = [];
200
	$properties = getPropIdsFromStrings($store, [
201
		"duedate" => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentEndWhole,
202
		"startdate" => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentStartWhole,
203
		"enddate_recurring" => "PT_SYSTIME:PSETID_Appointment:" . PidLidClipEnd,
204
		"recurring" => "PT_BOOLEAN:PSETID_Appointment:" . PidLidRecurring,
205
		"recurring_data" => "PT_BINARY:PSETID_Appointment:" . PidLidAppointmentRecur,
206
		"timezone_data" => "PT_BINARY:PSETID_Appointment:" . PidLidTimeZoneStruct,
207
		"label" => "PT_LONG:PSETID_Appointment:0x8214",
208
	]);
209
210
	// Create a restriction that will discard rows of appointments that are definitely not in our
211
	// requested time frame
212
213
	$table = mapi_folder_getcontentstable($calendar);
0 ignored issues
show
The function mapi_folder_getcontentstable 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

213
	$table = /** @scrutinizer ignore-call */ mapi_folder_getcontentstable($calendar);
Loading history...
214
215
	$restriction =
216
		// OR
217
		[
218
			RES_OR,
219
			[
220
				[RES_AND,	// Normal items: itemEnd must be after viewStart, itemStart must be before viewEnd
221
					[
222
						[
223
							RES_PROPERTY,
224
							[
225
								RELOP => RELOP_GT,
226
								ULPROPTAG => $properties["duedate"],
227
								VALUE => $viewstart,
228
							],
229
						],
230
						[
231
							RES_PROPERTY,
232
							[
233
								RELOP => RELOP_LT,
234
								ULPROPTAG => $properties["startdate"],
235
								VALUE => $viewend,
236
							],
237
						],
238
					],
239
				],
240
				// OR
241
				[
242
					RES_PROPERTY,
243
					[
244
						RELOP => RELOP_EQ,
245
						ULPROPTAG => $properties["recurring"],
246
						VALUE => true,
247
					],
248
				],
249
			],	// EXISTS OR
250
		];		// global OR
251
252
	// Get requested properties, plus whatever we need
253
	$proplist = [PR_ENTRYID, $properties["recurring"], $properties["recurring_data"], $properties["timezone_data"]];
254
	$proplist = array_merge($proplist, $propsrequested);
255
256
	$rows = mapi_table_queryallrows($table, $proplist, $restriction);
0 ignored issues
show
The function mapi_table_queryallrows 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

256
	$rows = /** @scrutinizer ignore-call */ mapi_table_queryallrows($table, $proplist, $restriction);
Loading history...
257
258
	// $rows now contains all the items that MAY be in the window; a recurring item needs expansion before including in the output.
259
260
	foreach ($rows as $row) {
261
		$items = [];
262
263
		if (isset($row[$properties["recurring"]]) && $row[$properties["recurring"]]) {
264
			// Recurring item
265
			$rec = new Recurrence($store, $row);
266
267
			// GetItems guarantees that the item overlaps the interval <$viewstart, $viewend>
268
			$occurrences = $rec->getItems($viewstart, $viewend);
269
			foreach ($occurrences as $occurrence) {
270
				// The occurrence takes all properties from the main row, but overrides some properties (like start and end obviously)
271
				$item = $occurrence + $row;
272
				array_push($items, $item);
273
			}
274
		}
275
		else {
276
			// Normal item, it matched the search criteria and therefore overlaps the interval <$viewstart, $viewend>
277
			array_push($items, $row);
278
		}
279
280
		$result = array_merge($result, $items);
281
	}
282
283
	// All items are guaranteed to overlap the interval <$viewstart, $viewend>. Note that we may be returning a few extra
284
	// properties that the caller did not request (recurring, etc). This shouldn't be a problem though.
285
	return $result;
286
}
287
288
/**
289
 * Compares two entryIds. It is possible to have two different entryIds that should match as they
290
 * represent the same object (in multiserver environments).
291
 *
292
 * @param mixed $entryId1 EntryID
293
 * @param mixed $entryId2 EntryID
294
 *
295
 * @return bool Result of the comparison
296
 */
297
function compareEntryIds($entryId1, $entryId2) {
298
	if (!is_string($entryId1) || !is_string($entryId2)) {
299
		return false;
300
	}
301
302
	if ($entryId1 === $entryId2) {
303
		// if normal comparison succeeds then we can directly say that entryids are same
304
		return true;
305
	}
306
307
	return false;
308
}
309
310
/**
311
 * Creates a goid from an ical uuid.
312
 *
313
 * @param string $uid
314
 *
315
 * @return string binary string representation of goid
316
 */
317
function getGoidFromUid($uid) {
318
	return hex2bin("040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000" .
319
				bin2hex(pack("V", 12 + strlen($uid)) . "vCal-Uid" . pack("V", 1) . $uid));
320
}
321
322
/**
323
 * Returns zero terminated goid. It is required for backwards compatibility.
324
 *
325
 * @param mixed $uid
326
 *
327
 * @return string an OL compatible GlobalObjectID
328
 */
329
function getGoidFromUidZero($uid) {
330
	if (strlen($uid) <= 64) {
331
		return hex2bin("040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000" .
332
			bin2hex(pack("V", 13 + strlen($uid)) . "vCal-Uid" . pack("V", 1) . $uid) . "00");
333
	}
334
335
	return hex2bin($uid);
336
}
337
338
/**
339
 * Creates an ical uuid from a goid.
340
 *
341
 * @param string $goid
342
 *
343
 * @return null|string ical uuid
344
 */
345
function getUidFromGoid($goid) {
346
	// check if "vCal-Uid" is somewhere in outlookid case-insensitive
347
	$uid = stristr($goid, "vCal-Uid");
348
	if ($uid !== false) {
349
		// get the length of the ical id - go back 4 position from where "vCal-Uid" was found
350
		$begin = unpack("V", substr($goid, strlen($uid) * (-1) - 4, 4));
351
352
		// remove "vCal-Uid" and packed "1" and use the ical id length
353
		return trim(substr($uid, 12, $begin[1] - 12));
354
	}
355
356
	return null;
357
}
358