Passed
Pull Request — master (#50)
by
unknown
11:31 queued 06:39
created

UploadAttachment::importICSFile()   C

Complexity

Conditions 14
Paths 19

Size

Total Lines 90
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 55
c 1
b 0
f 0
nc 19
nop 2
dl 0
loc 90
rs 6.2666

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
// required to handle php errors
4
require_once __DIR__ . '/exceptions/class.ZarafaErrorException.php';
5
require_once __DIR__ . '/exceptions/class.ZarafaException.php';
6
7
/**
8
 * Upload Attachment
9
 * This file is used to upload.
10
 */
11
class UploadAttachment {
12
	/**
13
	 * A random string that will be generated with every MAPIMessage instance to uniquely identify attachments that
14
	 * belongs to this MAPIMessage, this is mainly used to get recently uploaded attachments for MAPIMessage.
15
	 */
16
	protected $dialogAttachments;
17
18
	/**
19
	 * Entryid of the MAPIStore which holds the message to which we need to import.
20
	 */
21
	protected $storeId;
22
23
	/**
24
	 * Resource of the MAPIStore which holds the message to which we need to import.
25
	 */
26
	protected $store;
27
28
	/**
29
	 * Entryid of the MAPIFolder which holds the message.
30
	 */
31
	protected $destinationFolderId;
32
33
	/**
34
	 * Resource of the MAPIFolder which holds the message which we need to import from file.
35
	 */
36
	protected $destinationFolder;
37
38
	/**
39
	 * A boolean value, set to false by default, to define if the attachment needs to be imported into folder as webapp item.
40
	 */
41
	protected $import;
42
43
	/**
44
	 * Object of AttachmentState class.
45
	 */
46
	protected $attachment_state;
47
48
	/**
49
	 * A boolean value, set to true by default which update the counter of the folder.
50
	 */
51
	protected $allowUpdateCounter;
52
53
	/**
54
	 * A boolean value, set to false by default which extract the attach id concatenated with attachment name
55
	 * from the client side.
56
	 */
57
	protected $ignoreExtractAttachid;
58
59
	/**
60
	 * A string value which stores the module name of the notifier according to the file type.
61
	 */
62
	protected $notifierModule;
63
64
	/**
65
	 * Constructor.
66
	 */
67
	public function __construct() {
68
		$this->dialogAttachments = false;
69
		$this->storeId = false;
70
		$this->destinationFolder = false;
71
		$this->destinationFolderId = false;
72
		$this->store = false;
73
		$this->import = false;
74
		$this->attachment_state = false;
75
		$this->allowUpdateCounter = true;
76
		$this->ignoreExtractAttachid = false;
77
	}
78
79
	/**
80
	 * Function will initialize data for this class object. It will also sanitize data
81
	 * for possible XSS attack because data is received in $_REQUEST.
82
	 *
83
	 * @param array $data parameters received with the request
84
	 */
85
	public function init($data) {
86
		if (isset($data['dialog_attachments'])) {
87
			$this->dialogAttachments = sanitizeValue($data['dialog_attachments'], '', ID_REGEX);
88
		}
89
90
		if (isset($data['store'])) {
91
			$this->storeId = sanitizeValue($data['store'], '', STRING_REGEX);
92
		}
93
94
		if (isset($data['destination_folder'])) {
95
			$this->destinationFolderId = sanitizeValue($data['destination_folder'], '', STRING_REGEX);
96
		}
97
98
		if ($this->storeId) {
99
			$this->store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $this->storeId));
100
		}
101
102
		if (isset($data['import'])) {
103
			$this->import = sanitizeValue($data['import'], '', STRING_REGEX);
104
		}
105
106
		if (isset($data['ignore_extract_attachid'])) {
107
			$this->ignoreExtractAttachid = sanitizeValue($data['ignore_extract_attachid'], '', STRING_REGEX);
108
		}
109
110
		if ($this->attachment_state === false) {
111
			$this->attachment_state = new AttachmentState();
112
		}
113
	}
114
115
	/**
116
	 * Function get Files received in request, extract necessary information
117
	 * and holds the same using an instance of AttachmentState class.
118
	 */
119
	public function processFiles() {
120
		if (isset($_FILES['attachments']['name']) && is_array($_FILES['attachments']['name'])) {
121
			$importStatus = false;
122
			$returnfiles = [];
123
124
			// Parse all information from the updated files,
125
			// validate the contents and add it to the $FILES array.
126
			foreach ($_FILES['attachments']['name'] as $key => $name) {
127
				// validate the FILE object to see if the size doesn't exceed
128
				// the configured MAX_FILE_SIZE
129
				$fileSize = $_FILES['attachments']['size'][$key];
130
				if (isset($_FILES['attachments']['error'][$key]) && $_FILES['attachments']['error'][$key] > 0) {
131
					$errorTitle = _("File is not imported successfully");
132
133
					$errorTitle = match ($_FILES['attachments']['error'][$key]) {
134
						UPLOAD_ERR_INI_SIZE => _('The uploaded file exceeds the upload_max_filesize directive in php.ini.'),
135
						UPLOAD_ERR_FORM_SIZE => _('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
136
						UPLOAD_ERR_PARTIAL => _('The uploaded file was only partially uploaded.'),
137
						UPLOAD_ERR_NO_FILE => _('No file was uploaded. .'),
138
						UPLOAD_ERR_NO_TMP_DIR => _('Missing a temporary folder.'),
139
						UPLOAD_ERR_CANT_WRITE => _('Failed to write file to disk.'),
140
						UPLOAD_ERR_EXTENSION => _('A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.'),
141
						default => throw new ZarafaException($errorTitle),
142
					};
143
144
					throw new ZarafaException($errorTitle);
145
				}
146
				if (isset($fileSize) && !(isset($_POST['MAX_FILE_SIZE']) && $fileSize > $_POST['MAX_FILE_SIZE'])) {
147
					// Parse the filename, strip it from
148
					// any illegal characters.
149
					$filename = mb_basename(stripslashes((string) $_FILES['attachments']['name'][$key]));
150
151
					// set sourcetype as default if sourcetype is unset.
152
					$sourcetype = $_POST['sourcetype'] ?? 'default';
153
154
					/**
155
					 * content-type sent by browser for eml and ics attachments will be
156
					 * message/rfc822 and text/calendar respectively, but these content types are
157
					 * used for message-in-message embedded objects, so we have to send it as
158
					 * application/octet-stream.
159
					 */
160
					$fileType = $_FILES['attachments']['type'][$key];
161
					if ($fileType == 'message/rfc822' || $fileType == 'text/calendar') {
162
						$fileType = 'application/octet-stream';
163
					}
164
165
					// Don't go to extract attachID as passing it from client end is not
166
					// possible with IE/Edge.
167
					if (!isEdge() && $this->ignoreExtractAttachid === false) {
168
						$attachID = substr($filename, -8);
169
						$filename = substr($filename, 0, -8);
170
					}
171
					else {
172
						$attachID = uniqid();
173
					}
174
175
					// Move the uploaded file into the attachment state
176
					$attachTempName = $this->attachment_state->addUploadedAttachmentFile($_REQUEST['dialog_attachments'], $filename, $_FILES['attachments']['tmp_name'][$key], [
177
						'name' => $filename,
178
						'size' => $fileSize,
179
						'type' => $fileType,
180
						'sourcetype' => $sourcetype,
181
						'attach_id' => $attachID,
182
					]);
183
184
					// Allow hooking in to handle import in plugins
185
					$GLOBALS['PluginManager']->triggerHook('server.upload_attachment.upload', [
186
						'tmpname' => $this->attachment_state->getAttachmentPath($attachTempName),
187
						'name' => $filename,
188
						'size' => $fileSize,
189
						'sourcetype' => $sourcetype,
190
						'returnfiles' => &$returnfiles,
191
						'attach_id' => $attachID,
192
					]);
193
194
					// import given files
195
					if ($this->import) {
196
						$importStatus = $this->importFiles($attachTempName, $filename);
197
					}
198
					elseif ($sourcetype === 'contactphoto' || $sourcetype === 'default') {
199
						$fileData = [
200
							'props' => [
201
								'attach_num' => -1,
202
								'tmpname' => $attachTempName,
203
								'attach_id' => $attachID,
204
								'name' => $filename,
205
								'size' => $fileSize,
206
							],
207
						];
208
209
						if ($sourcetype === 'contactphoto') {
210
							$fileData['props']['attachment_contactphoto'] = true;
211
						}
212
213
						$returnfiles[] = $fileData;
214
					}
215
					else {
216
						// Backwards compatibility for Plugins (S/MIME)
217
						$lastKey = count($returnfiles) - 1;
218
						if ($lastKey >= 0) {
219
							$returnfiles[$lastKey]['props']['attach_id'] = $attachID;
220
						}
221
					}
222
				}
223
			}
224
225
			if ($this->import) {
226
				if ($importStatus !== false) {
227
					$this->sendImportResponse($importStatus);
228
				}
229
				else {
230
					throw new ZarafaException(_("File is not imported successfully"));
231
				}
232
			}
233
			else {
234
				$return = [
235
					'success' => true,
236
					'zarafa' => [
237
						sanitizeGetValue('module', '', STRING_REGEX) => [
238
							sanitizeGetValue('moduleid', '', STRING_REGEX) => [
239
								'update' => [
240
									'item' => $returnfiles,
241
								],
242
							],
243
						],
244
					],
245
				];
246
247
				echo json_encode($return);
248
			}
249
		}
250
	}
251
252
	/**
253
	 * Function reads content of the given file and call either importICSFile or importEMLFile
254
	 * function based on the file type.
255
	 *
256
	 * @param string $attachTempName a temporary file name of server location where it actually saved/available
257
	 * @param string $filename       an actual file name
258
	 *
259
	 * @return bool true if the import is successful, false otherwise
260
	 */
261
	public function importFiles($attachTempName, $filename) {
262
		$filepath = $this->attachment_state->getAttachmentPath($attachTempName);
263
		$handle = fopen($filepath, "r");
264
		$attachmentStream = '';
265
		while (!feof($handle)) {
266
			$attachmentStream .= fread($handle, BLOCK_SIZE);
267
		}
268
269
		fclose($handle);
270
		unlink($filepath);
271
272
		$extension = pathinfo($filename, PATHINFO_EXTENSION);
273
274
		// Set the module id of the notifier according to the file type
275
		switch (strtoupper($extension)) {
0 ignored issues
show
Bug introduced by
It seems like $extension can also be of type array; however, parameter $string of strtoupper() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

275
		switch (strtoupper(/** @scrutinizer ignore-type */ $extension)) {
Loading history...
276
			case 'EML':
277
				$this->notifierModule = 'maillistnotifier';
278
279
				return $this->importEMLFile($attachmentStream, $filename);
280
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
281
282
			case 'ICS':
283
			case 'VCS':
284
				$this->notifierModule = 'appointmentlistnotifier';
285
286
				return $this->importICSFile($attachmentStream, $filename);
287
				break;
288
289
			case 'VCF':
290
				$this->notifierModule = 'contactlistnotifier';
291
292
				return $this->importVCFFile($attachmentStream, $filename);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->importVCFF...hmentStream, $filename) returns the type array which is incompatible with the documented return type boolean.
Loading history...
293
				break;
294
		}
295
296
		return false;
297
	}
298
299
	/**
300
	 * Function reads content of the given file and convert the same into
301
	 * a webapp contact or multiple contacts into respective destination folder.
302
	 *
303
	 * @param string $attachmentStream the attachment as a stream
304
	 * @param string $filename         an actual file name
305
	 *
306
	 * @return array the new contact to be imported
307
	 */
308
	public function importVCFFile($attachmentStream, $filename) {
309
		$this->destinationFolder = $this->getDestinationFolder();
310
311
		try {
312
			processVCFStream($attachmentStream);
313
			// Convert vCard 1.0 to a MAPI contact.
314
			$contacts = $this->convertVCFContactsToMapi($this->destinationFolder, $attachmentStream);
315
		}
316
		catch (ZarafaException $e) {
317
			$e->setTitle(_("Import error"));
318
319
			throw $e;
320
		}
321
		catch (Exception $e) {
322
			$destinationFolderProps = mapi_getprops($this->destinationFolder, [PR_DISPLAY_NAME, PR_MDB_PROVIDER]);
323
			$fullyQualifiedFolderName = $destinationFolderProps[PR_DISPLAY_NAME];
324
			if ($destinationFolderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_PUBLIC_GUID) {
325
				$publicStore = $GLOBALS["mapisession"]->getPublicMessageStore();
326
				$publicStoreName = mapi_getprops($publicStore, [PR_DISPLAY_NAME]);
327
				$fullyQualifiedFolderName .= " - " . $publicStoreName[PR_DISPLAY_NAME];
328
			}
329
			elseif ($destinationFolderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_DELEGATE_GUID) {
330
				$otherStore = $GLOBALS['operations']->getOtherStoreFromEntryid($this->destinationFolderId);
331
				$sharedStoreOwnerName = mapi_getprops($otherStore, [PR_MAILBOX_OWNER_NAME]);
332
				$fullyQualifiedFolderName .= " - " . $sharedStoreOwnerName[PR_MAILBOX_OWNER_NAME];
333
			}
334
335
			$message = sprintf(_("Unable to import '%s' to '%s'. "), $filename, $fullyQualifiedFolderName);
336
			if ($e->getCode() === MAPI_E_TABLE_EMPTY) {
337
				$message .= _("There is no contact found in this file.");
338
			}
339
			elseif ($e->getCode() === MAPI_E_CORRUPT_DATA) {
340
				$message .= _("The file is corrupt.");
341
			}
342
			elseif ($e->getCode() === MAPI_E_INVALID_PARAMETER) {
343
				$message .= _("The file is invalid.");
344
			}
345
			else {
346
				$message = sprintf(_("Unable to import '%s'. "), $filename) . $e->getMessage();
347
			}
348
349
			$e = new ZarafaException($message);
350
			$e->setTitle(_("Import error"));
351
352
			throw $e;
353
		}
354
355
		if (is_array($contacts) && !empty($contacts)) {
356
			$newcontact = [];
357
			foreach ($contacts as $contact) {
358
				// As vcf file does not contains fileas, business_address etc properties, we need to set it manually.
359
				// something similar is mentioned in this ticket KC-1509.
360
				$this->processContactData($GLOBALS["mapisession"]->getDefaultMessageStore(), $contact);
361
				mapi_message_savechanges($contact);
362
				$vcf = bin2hex((string) mapi_getprops($contact, [PR_ENTRYID])[PR_ENTRYID]);
363
				array_push($newcontact, $vcf);
364
			}
365
366
			return $newcontact;
367
		}
368
369
		return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
370
	}
371
372
	/**
373
	 * Function checks whether the file to be converted contains a single vCard
374
	 * or multiple vCard entries. It calls the appropriate method and converts the vcf.
375
	 *
376
	 * @param object $destinationFolder the folder which holds the message which we need to import from file
377
	 * @param string $attachmentStream  the attachment as a stream
378
	 *
379
	 * @return array $contacts the array of contact(s) to be imported
380
	 */
381
	public function convertVCFContactsToMapi($destinationFolder, $attachmentStream) {
382
		$contacts = [];
383
384
		// If function 'mapi_vcftomapi2' exists, we can use that for both single and multiple vcf files,
385
		// but if it doesn't exist, we use the old function 'mapi_vcftomapi' for single vcf file.
386
		if (function_exists('mapi_vcftomapi2')) {
387
			$contacts = mapi_vcftomapi2($destinationFolder, $attachmentStream);
388
		}
389
		elseif ($_POST['is_single_import']) {
390
			$newMessage = mapi_folder_createmessage($this->destinationFolder);
391
			$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
392
			$ok = mapi_vcftomapi($GLOBALS['mapisession']->getSession(), $store, $newMessage, $attachmentStream);
393
			if ($ok !== false) {
394
				$contacts = is_array($newMessage) ? $newMessage : [$newMessage];
395
			}
396
		}
397
		else {
398
			// Throw error related to multiple vcf as the function is not available for importing multiple vcf file.
399
			throw new ZarafaException(_("grommunio Web does not support importing multiple VCF with this version."));
400
		}
401
402
		return $contacts;
403
	}
404
405
	/**
406
	 * Helper function which generate the information like 'fileAs','display name' and
407
	 * 'business address' using existing information.
408
	 *
409
	 * @param object $store      Message Store Object
410
	 * @param object $newMessage The newly imported contact from .vcf file.
411
	 */
412
	public function processContactData($store, $newMessage) {
413
		$properties = [];
414
		$properties["subject"] = PR_SUBJECT;
415
		$properties["fileas"] = "PT_STRING8:PSETID_Address:0x8005";
416
		$properties["display_name"] = PR_DISPLAY_NAME;
417
		$properties["address_book_mv"] = "PT_MV_LONG:PSETID_Address:0x8028";
418
		$properties["address_book_long"] = "PT_LONG:PSETID_Address:0x8029";
419
		$properties["business_address"] = "PT_STRING8:PSETID_Address:0x801b";
420
		$properties["email_address_entryid_1"] = "PT_BINARY:PSETID_Address:0x8085";
421
		$properties["email_address_display_name_1"] = "PT_STRING8:PSETID_Address:" . PidLidEmail1DisplayName;
422
		$properties["business_address_street"] = "PT_STRING8:PSETID_Address:" . PidLidWorkAddressStreet;
423
		$properties["business_address_city"] = "PT_STRING8:PSETID_Address:" . PidLidWorkAddressCity;
424
		$properties["business_address_state"] = "PT_STRING8:PSETID_Address:" . PidLidWorkAddressState;
425
		$properties["business_address_postal_code"] = "PT_STRING8:PSETID_Address:" . PidLidWorkAddressPostalCode;
426
		$properties["business_address_country"] = "PT_STRING8:PSETID_Address:" . PidLidWorkAddressCountry;
427
428
		$properties = getPropIdsFromStrings($store, $properties);
429
430
		$contactProps = mapi_getprops($newMessage, $properties);
431
432
		$props = [];
433
434
		// Addresses field value.
435
		$businessAddress = ($contactProps[$properties["business_address_street"]] ?? '') . "\n";
436
		$businessAddress .= ($contactProps[$properties["business_address_city"]] ?? '') . " ";
437
		$businessAddress .= ($contactProps[$properties["business_address_state"]] ?? '') . " ";
438
		$businessAddress .= ($contactProps[$properties["business_address_postal_code"]] ?? '') . "\n";
439
		$businessAddress .= ($contactProps[$properties["business_address_country"]] ?? '') . "\n";
440
441
		if (strlen(trim($businessAddress)) > 0) {
442
			$props[$properties["business_address"]] = $businessAddress;
443
		}
444
445
		// File as field value generator.
446
		if (isset($contactProps[PR_DISPLAY_NAME])) {
447
			$displayName = $contactProps[PR_DISPLAY_NAME] ?? " ";
448
			$displayName = str_replace("\xA0", " ", $displayName);
449
			$str = explode(" ", $displayName);
450
			$prefix = [_('Dr.'), _('Miss'), _('Mr.'), _('Mrs.'), _('Ms.'), _('Prof.')];
451
			$suffix = ['I', 'II', 'III', _('Jr.'), _('Sr.')];
452
453
			foreach ($str as $index => $value) {
454
				$value = preg_replace('/[^.A-Za-z0-9\-]/', '', $value);
455
				if (array_search($value, $prefix, true) !== false) {
456
					$props[PR_DISPLAY_NAME_PREFIX] = $value;
457
					unset($str[$index]);
458
				}
459
				elseif (array_search($value, $suffix, true) !== false) {
460
					$props[PR_GENERATION] = $value;
461
					unset($str[$index]);
462
				}
463
			}
464
465
			$surname = array_slice($str, count($str) - 1);
466
			$remainder = array_slice($str, 0, count($str) - 1);
467
			$fileAs = $surname[0] . ', ';
468
			if (!empty($remainder)) {
469
				$fileAs .= join(" ", $remainder);
470
				if (count($remainder) > 1) {
471
					$middleName = $remainder[count($remainder) - 1];
472
					$props[PR_MIDDLE_NAME] = $middleName;
473
				}
474
			}
475
476
			// Email fieldset information.
477
			if (isset($contactProps[$properties["email_address_display_name_1"]])) {
478
				$emailAddressDisplayNameOne = $fileAs . " ";
479
				$emailAddressDisplayNameOne .= $contactProps[$properties["email_address_display_name_1"]];
480
				$props[$properties["email_address_display_name_1"]] = $emailAddressDisplayNameOne;
481
				$props[$properties["address_book_long"]] = 1;
482
				$props[$properties["address_book_mv"]] = [0 => 0];
483
			}
484
485
			$props[$properties["fileas"]] = $fileAs;
486
			$props[PR_DISPLAY_NAME] = $displayName;
487
			mapi_setprops($newMessage, $props);
488
		}
489
	}
490
491
	/**
492
	 * Function reads content of the given file and convert the same into
493
	 * a webapp appointment into respective destination folder.
494
	 *
495
	 * @param string $attachmentStream the attachment as a stream
496
	 * @param string $filename         an actual file name
497
	 *
498
	 * @return bool true if the import is successful, false otherwise
499
	 */
500
	public function importICSFile($attachmentStream, $filename) {
501
		$this->destinationFolder = $this->getDestinationFolder();
502
503
		try {
504
			$events = $this->convertICSToMapi($attachmentStream);
505
		}
506
		catch (ZarafaException $e) {
507
			$e->setTitle(_("Import error"));
508
509
			throw $e;
510
		}
511
		catch (Exception $e) {
512
			$destinationFolderProps = mapi_getprops($this->destinationFolder, [PR_DISPLAY_NAME, PR_MDB_PROVIDER]);
513
			$fullyQualifiedFolderName = $destinationFolderProps[PR_DISPLAY_NAME];
514
			// Condition true if folder is belongs to Public store.
515
			if ($destinationFolderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_PUBLIC_GUID) {
516
				$publicStore = $GLOBALS["mapisession"]->getPublicMessageStore();
517
				$publicStoreName = mapi_getprops($publicStore, [PR_DISPLAY_NAME]);
518
				$fullyQualifiedFolderName .= " - " . $publicStoreName[PR_DISPLAY_NAME];
519
			}
520
			elseif ($destinationFolderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_DELEGATE_GUID) {
521
				// Condition true if folder is belongs to delegate store.
522
				$otherStore = $GLOBALS['operations']->getOtherStoreFromEntryid($this->destinationFolderId);
523
				$sharedStoreOwnerName = mapi_getprops($otherStore, [PR_MAILBOX_OWNER_NAME]);
524
				$fullyQualifiedFolderName .= " - " . $sharedStoreOwnerName[PR_MAILBOX_OWNER_NAME];
525
			}
526
527
			$message = sprintf(_("Unable to import '%s' to '%s'. "), $filename, $fullyQualifiedFolderName);
528
			if ($e->getCode() === MAPI_E_TABLE_EMPTY) {
529
				$message .= _("There is no appointment found in this file.");
530
			}
531
			elseif ($e->getCode() === MAPI_E_CORRUPT_DATA) {
532
				$message .= _("The file is corrupt.");
533
			}
534
			elseif ($e->getCode() === MAPI_E_INVALID_PARAMETER) {
535
				$message .= _("The file is invalid.");
536
			}
537
			else {
538
				$message = sprintf(_("Unable to import '%s'. "), $filename) . $e->getMessage();
539
			}
540
541
			$e = new ZarafaException($message);
542
			$e->setTitle(_("Import error"));
543
544
			throw $e;
545
		}
546
547
		if (is_array($events) && !empty($events)) {
548
			$newEvents = [];
549
			$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
550
			$propTags = [
551
				"commonstart" => "PT_SYSTIME:PSETID_Common:0x8516",
552
				"commonend" => "PT_SYSTIME:PSETID_Common:0x8517",
553
				"message_class" => PR_MESSAGE_CLASS,
554
				"startdate" => "PT_SYSTIME:PSETID_Appointment:0x820d",
555
				"duedate" => "PT_SYSTIME:PSETID_Appointment:0x820e",
556
			];
557
			$properties = getPropIdsFromStrings($store, $propTags);
558
			foreach ($events as $event) {
559
				$newMessageProps = mapi_getprops($event, $properties);
560
				// Need to set the common start and end date if it is not set because
561
				// common start and end dates are required fields.
562
563
				if (!isset($newMessageProps[$properties["commonstart"]], $newMessageProps[$properties["commonend"]])) {
564
					mapi_setprops($event, [
565
						$properties["commonstart"] => $newMessageProps[$properties["startdate"]],
566
						$properties["commonend"] => $newMessageProps[$properties["duedate"]],
567
					]);
568
				}
569
570
				// Save newly imported event
571
				mapi_message_savechanges($event);
572
573
				$newMessageProps = mapi_getprops($event, [PR_MESSAGE_CLASS]);
574
				if (isset($newMessageProps[PR_MESSAGE_CLASS]) && $newMessageProps[PR_MESSAGE_CLASS] !== 'IPM.Appointment') {
575
					// Convert the Meeting request record to proper appointment record so we can
576
					// properly show the appointment in calendar.
577
					$req = new Meetingrequest($store, $event, $GLOBALS['mapisession']->getSession(), ENABLE_DIRECT_BOOKING);
0 ignored issues
show
Bug introduced by
The type Meetingrequest 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...
578
					$req->doAccept(true, false, false, false, false, false, false, false, false, true);
579
				}
580
581
				$this->allowUpdateCounter = false;
582
				$entryid = bin2hex((string) mapi_getprops($event, [PR_ENTRYID])[PR_ENTRYID]);
583
				array_push($newEvents, $entryid);
584
			}
585
586
			return $newEvents;
587
		}
588
589
		return false;
590
	}
591
592
	/**
593
	 * Function checks whether the file to be converted contains a single event ics
594
	 * or multiple ics event entries.
595
	 *
596
	 * @param string $attachmentStream the attachment as a stream
597
	 *
598
	 * @return array $events the array of calendar items to be imported
599
	 */
600
	public function convertICSToMapi($attachmentStream) {
601
		$events = [];
602
		$addrBook = $GLOBALS['mapisession']->getAddressbook();
603
604
		// If function 'mapi_icaltomapi2' exists, we can use that for both single and multiple ics files,
605
		// but if it doesn't exist, we use the old function 'mapi_icaltomapi' for single ics file.
606
		if (function_exists('mapi_icaltomapi2')) {
607
			$events = mapi_icaltomapi2($addrBook, $this->destinationFolder, $attachmentStream);
608
		}
609
		elseif ($_POST['is_single_import']) {
610
			$newMessage = mapi_folder_createmessage($this->destinationFolder);
611
			$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
612
			$ok = mapi_icaltomapi($GLOBALS['mapisession']->getSession(), $store, $addrBook, $newMessage, $attachmentStream, false);
613
614
			if ($ok !== false) {
615
				array_push($events, $newMessage);
616
			}
617
		}
618
		else {
619
			// Throw error related to multiple ics as the function is not available for importing multiple ics file.
620
			throw new ZarafaException(_("grommunio Web does not support importing multiple ICS with this version."));
621
		}
622
623
		return $events;
624
	}
625
626
	/**
627
	 * Function reads content of the given file and convert the same into
628
	 * a webapp email into respective destination folder.
629
	 *
630
	 * @param string $filename         an actual file name
631
	 * @param mixed  $attachmentStream
632
	 *
633
	 * @return bool true if the import is successful, false otherwise
634
	 */
635
	public function importEMLFile($attachmentStream, $filename) {
636
		if (isBrokenEml($attachmentStream)) {
637
			throw new ZarafaException(sprintf(_("Unable to import '%s'. "), $filename) . _("The EML is not valid"));
638
		}
639
640
		$this->destinationFolder = $this->getDestinationFolder();
641
642
		$newMessage = mapi_folder_createmessage($this->destinationFolder);
643
		$addrBook = $GLOBALS['mapisession']->getAddressbook();
644
		// Convert an RFC822-formatted e-mail to a MAPI Message
645
		$ok = mapi_inetmapi_imtomapi($GLOBALS['mapisession']->getSession(), $this->store, $addrBook, $newMessage, $attachmentStream, []);
646
647
		if ($ok === true) {
648
			// Manually set PR_MESSAGE_DELIVERY_TIME to sent time, since mapi_inetmapi_imtomapi does not set delivery-time
649
			// Either use PR_CLIENT_SUBMIT_TIME or extract date from EML and set PR_MESSAGE_DELIVERY_TIME
650
	 		$props = mapi_getprops($newMessage, [PR_CLIENT_SUBMIT_TIME, PR_MESSAGE_DELIVERY_TIME]);
651
                        if (empty($props[PR_MESSAGE_DELIVERY_TIME])) {
652
				if (!empty($props[PR_CLIENT_SUBMIT_TIME]))
653
                                	mapi_setprops($newMessage, [PR_MESSAGE_DELIVERY_TIME => $props[PR_CLIENT_SUBMIT_TIME]]);
654
				else {
655
					if( preg_match('/^Date:\s*(.+)$/mi', $attachmentStream, $matches)) {
656
        	        			$dateStr = trim($matches[1]);
657
                				$deliverytime = strtotime($dateStr);
658
                				if ($deliverytime) 
659
							mapi_setprops($newMessage, [PR_MESSAGE_DELIVERY_TIME => $deliverytime]);
660
        
661
        				}
662
				}
663
				mapi_message_savechanges($newMessage);
664
			}
665
		
666
			return bin2hex((string) mapi_getprops($newMessage, [PR_ENTRYID])[PR_ENTRYID]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return bin2hex((string)m..._ENTRYID))[PR_ENTRYID]) returns the type string which is incompatible with the documented return type boolean.
Loading history...
667
		}
668
669
		return false;
670
	}
671
672
	/**
673
	 * Function used get the destination folder in which
674
	 * item gets imported.
675
	 *
676
	 * @return object folder object in which item gets imported
677
	 */
678
	public function getDestinationFolder() {
679
		$destinationFolder = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $destinationFolder is dead and can be removed.
Loading history...
680
681
		try {
682
			$destinationFolder = mapi_msgstore_openentry($this->store, hex2bin((string) $this->destinationFolderId));
683
		}
684
		catch (Exception) {
685
			// Try to find the folder from shared stores in case if it is not found in current user's store
686
			$destinationFolder = mapi_msgstore_openentry($GLOBALS['operations']->getOtherStoreFromEntryid($this->destinationFolderId), hex2bin((string) $this->destinationFolderId));
687
		}
688
689
		return $destinationFolder;
690
	}
691
692
	/**
693
	 * Function deletes uploaded attachment files and send
694
	 * proper response back to client.
695
	 */
696
	public function deleteUploadedFiles() {
697
		$num = sanitizePostValue('attach_num', false, NUMERIC_REGEX);
698
		$attachID = sanitizePostValue('attach_id', false, STRING_REGEX);
699
700
		if ($num === false) {
701
			// string is passed in attachNum so get it
702
			// Parse the filename, strip it from any illegal characters
703
			$num = mb_basename(stripslashes((string) sanitizePostValue('attach_num', '', FILENAME_REGEX)));
704
705
			// Delete the file instance and unregister the file
706
			$this->attachment_state->deleteUploadedAttachmentFile($_REQUEST['dialog_attachments'], $num, $attachID);
707
		}
708
		else {
709
			// Set the correct array structure
710
			$this->attachment_state->addDeletedAttachment($_REQUEST['dialog_attachments'], $num);
711
		}
712
713
		$return = [
714
			// 'success' property is needed for Extjs Ext.form.Action.Submit#success handler
715
			'success' => true,
716
			'zarafa' => [
717
				sanitizeGetValue('module', '', STRING_REGEX) => [
718
					sanitizeGetValue('moduleid', '', STRING_REGEX) => [
719
						'delete' => [
720
							'success' => true,
721
						],
722
					],
723
				],
724
			],
725
		];
726
727
		echo json_encode($return);
728
	}
729
730
	/**
731
	 * Function adds embedded/icsfile attachment and send
732
	 * proper response back to client.
733
	 */
734
	public function addingEmbeddedAttachments() {
735
		$attachID = $_POST['attach_id'];
736
		$attachTampName = $this->attachment_state->addEmbeddedAttachment($_REQUEST['dialog_attachments'], [
737
			'entryid' => sanitizePostValue('entryid', '', ID_REGEX),
738
			'store_entryid' => sanitizePostValue('store_entryid', '', ID_REGEX),
739
			'sourcetype' => intval($_POST['attach_method'], 10) === ATTACH_EMBEDDED_MSG ? 'embedded' : 'icsfile',
740
			'attach_id' => $attachID,
741
		]);
742
743
		$returnfiles[] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$returnfiles was never initialized. Although not strictly required by PHP, it is generally a good practice to add $returnfiles = array(); before regardless.
Loading history...
744
			'props' => [
745
				'attach_num' => -1,
746
				'tmpname' => $attachTampName,
747
				'attach_id' => $attachID,
748
				// we are not using this data here, so we can safely use $_POST directly without any sanitization
749
				// this is only needed to identify response for a particular attachment record on client side
750
				'name' => $_POST['name'],
751
			],
752
		];
753
754
		$return = [
755
			// 'success' property is needed for Extjs Ext.form.Action.Submit#success handler
756
			'success' => true,
757
			'zarafa' => [
758
				sanitizeGetValue('module', '', STRING_REGEX) => [
759
					sanitizeGetValue('moduleid', '', STRING_REGEX) => [
760
						'update' => [
761
							'item' => $returnfiles,
762
						],
763
					],
764
				],
765
			],
766
		];
767
768
		echo json_encode($return);
769
	}
770
771
	/**
772
	 * Function adds attachment in case of OOo.
773
	 */
774
	public function uploadWhenWendViaOOO() {
775
		$providedFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $_GET['attachment_id'];
776
777
		// check whether the doc is already moved
778
		if (file_exists($providedFile)) {
779
			$filename = mb_basename(stripslashes((string) $_GET['name']));
780
781
			// Move the uploaded file to the session
782
			$this->attachment_state->addProvidedAttachmentFile($_REQUEST['attachment_id'], $filename, $providedFile, [
783
				'name' => $filename,
784
				'size' => filesize($providedFile),
785
				'type' => mime_content_type($providedFile),
786
				'sourcetype' => 'default',
787
			]);
788
		}
789
		else {
790
			// Check if no files are uploaded with this attachmentid
791
			$this->attachment_state->clearAttachmentFiles($_GET['attachment_id']);
792
		}
793
	}
794
795
	/**
796
	 * Helper function to send proper response for import request only. It sets the appropriate
797
	 * notifier to be sent in the response according to the type of the file to be imported.
798
	 *
799
	 * @param mixed $importStatus
800
	 */
801
	public function sendImportResponse($importStatus) {
802
		$storeProps = mapi_getprops($this->store, [PR_ENTRYID]);
803
		$destinationFolderProps = mapi_getprops($this->destinationFolder, [PR_PARENT_ENTRYID, PR_CONTENT_UNREAD]);
804
		$notifierModuleId = $this->notifierModule . '1';
805
806
		$return = [
807
			'success' => true,
808
			'zarafa' => [
809
				sanitizeGetValue('module', '', STRING_REGEX) => [
810
					sanitizeGetValue('moduleid', '', STRING_REGEX) => [
811
						'import' => [
812
							'success' => true,
813
							'items' => $importStatus,
814
						],
815
					],
816
				],
817
				'hierarchynotifier' => [
818
					'hierarchynotifier1' => [
819
						'folders' => [
820
							'item' => [
821
								0 => [
822
									'entryid' => $this->destinationFolderId,
823
									'parent_entryid' => bin2hex((string) $destinationFolderProps[PR_PARENT_ENTRYID]),
824
									'store_entryid' => bin2hex((string) $storeProps[PR_ENTRYID]),
825
									'props' => [
826
										'content_unread' => $this->allowUpdateCounter ? $destinationFolderProps[PR_CONTENT_UNREAD] + 1 : 0,
827
									],
828
								],
829
							],
830
						],
831
					],
832
				],
833
				$this->notifierModule => [
834
					$notifierModuleId => [
835
						'newobject' => [
836
							'item' => [
837
								0 => [
838
									'content_count' => 2,
839
									'content_unread' => 0,
840
									'display_name' => 'subsubin',
841
									'entryid' => $this->destinationFolderId,
842
									'parent_entryid' => bin2hex((string) $destinationFolderProps[PR_PARENT_ENTRYID]),
843
									'store_entryid' => bin2hex((string) $storeProps[PR_ENTRYID]),
844
								],
845
							],
846
						],
847
					],
848
				],
849
			],
850
		];
851
		echo json_encode($return);
852
	}
853
854
	/**
855
	 * Function will encode all the necessary information about the exception
856
	 * into JSON format and send the response back to client.
857
	 *
858
	 * @param object $exception exception object
859
	 * @param string $title     title which used to show as title of exception dialog
860
	 */
861
	public function handleUploadException($exception, $title = null) {
862
		$return = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $return is dead and can be removed.
Loading history...
863
864
		// MAPI_E_NOT_FOUND exception contains generalize exception message.
865
		// Set proper exception message as display message should be user understandable.
866
		if ($exception->getCode() == MAPI_E_NOT_FOUND) {
867
			$exception->setDisplayMessage(_('Could not find message, either it has been moved or deleted.'));
868
		}
869
870
		// Set the headers
871
		header('Expires: 0'); // set expiration time
872
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
873
874
		// Set Content Disposition header
875
		header('Content-Disposition: inline');
876
		// Set content type header
877
		header('Content-Type: text/plain');
878
879
		$return = [
880
			// 'success' property is needed for Extjs Ext.form.Action.Submit#success handler
881
			'success' => false,
882
			'zarafa' => [
883
				'error' => [
884
					'type' => ERROR_GENERAL,
885
					'info' => [
886
						'file' => $exception->getFileLine(),
887
						'title' => $title,
888
						'display_message' => $exception->getDisplayMessage(),
889
						'original_message' => $exception->getMessage(),
890
					],
891
				],
892
			],
893
		];
894
895
		echo json_encode($return);
896
	}
897
898
	/**
899
	 * Generic function to check received data and take necessary action.
900
	 */
901
	public function upload() {
902
		$this->attachment_state->open();
903
904
		// Check if dialog_attachments is set
905
		if (isset($_REQUEST['dialog_attachments'])) {
906
			// Check if attachments have been uploaded
907
			if (isset($_FILES['attachments']) && is_array($_FILES['attachments'])) {
908
				// import given files into respective webapp folder
909
				$this->processFiles();
910
			}
911
			elseif (isset($_POST['deleteattachment'])) {
912
				$this->deleteUploadedFiles();
913
			}
914
			elseif (isset($_POST['entryid'])) {	// Check for adding of embedded attachments
915
				$this->addingEmbeddedAttachments();
916
			}
917
		}
918
		elseif ($_GET && isset($_GET['attachment_id'])) { // this is to upload the file to server when the doc is send via OOo
919
			$this->uploadWhenWendViaOOO();
920
		}
921
922
		$this->attachment_state->close();
923
	}
924
}
925
926
// create instance of class
927
$uploadInstance = new UploadAttachment();
928
929
try {
930
	// initialize variables
931
	$uploadInstance->init($_REQUEST);
932
933
	// upload files
934
	$uploadInstance->upload();
935
}
936
catch (ZarafaException $e) {
937
	$uploadInstance->handleUploadException($e, $e->getTitle());
938
}
939
catch (Exception $e) {
940
	$uploadInstance->handleUploadException($e);
941
}
942