Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EmailProvider.php « NotificationProvider « Reminder « CalDAV « lib « dav « apps - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7e0020b5f55e92069643f01b60080753d1cef666 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<?php

declare(strict_types=1);

/**
 * @copyright Copyright (c) 2019, Thomas Citharel
 * @copyright Copyright (c) 2019, Georg Ehrke
 *
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 * @author Georg Ehrke <oc.list@georgehrke.com>
 * @author Joas Schilling <coding@schilljs.com>
 * @author Richard Steinmetz <richard@steinmetz.cloud>
 * @author Roeland Jago Douma <roeland@famdouma.nl>
 * @author Thomas Citharel <nextcloud@tcit.fr>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */
namespace OCA\DAV\CalDAV\Reminder\NotificationProvider;

use DateTime;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\L10N\IFactory as L10NFactory;
use OCP\Mail\IEMailTemplate;
use OCP\Mail\IMailer;
use Psr\Log\LoggerInterface;
use Sabre\VObject;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\Parameter;
use Sabre\VObject\Property;

/**
 * Class EmailProvider
 *
 * @package OCA\DAV\CalDAV\Reminder\NotificationProvider
 */
class EmailProvider extends AbstractProvider {

	/** @var string */
	public const NOTIFICATION_TYPE = 'EMAIL';

	/** @var IMailer */
	private $mailer;

	public function __construct(IConfig $config,
								IMailer $mailer,
								LoggerInterface $logger,
								L10NFactory $l10nFactory,
								IURLGenerator $urlGenerator) {
		parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
		$this->mailer = $mailer;
	}

	/**
	 * Send out notification via email
	 *
	 * @param VEvent $vevent
	 * @param string $calendarDisplayName
	 * @param array $users
	 * @throws \Exception
	 */
	public function send(VEvent $vevent,
						 string $calendarDisplayName,
						 array $users = []):void {
		$fallbackLanguage = $this->getFallbackLanguage();

		$emailAddressesOfSharees = $this->getEMailAddressesOfAllUsersWithWriteAccessToCalendar($users);
		$emailAddressesOfAttendees = $this->getAllEMailAddressesFromEvent($vevent);

		// Quote from php.net:
		// If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
		// => if there are duplicate email addresses, it will always take the system value
		$emailAddresses = array_merge(
			$emailAddressesOfAttendees,
			$emailAddressesOfSharees
		);

		$sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage);
		$organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);

		foreach ($sortedByLanguage as $lang => $emailAddresses) {
			if (!$this->hasL10NForLang($lang)) {
				$lang = $fallbackLanguage;
			}
			$l10n = $this->getL10NForLang($lang);
			$fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply');

			$template = $this->mailer->createEMailTemplate('dav.calendarReminder');
			$template->addHeader();
			$this->addSubjectAndHeading($template, $l10n, $vevent);
			$this->addBulletList($template, $l10n, $calendarDisplayName, $vevent);
			$template->addFooter();

			foreach ($emailAddresses as $emailAddress) {
				if (!$this->mailer->validateMailAddress($emailAddress)) {
					$this->logger->error('Email address {address} for reminder notification is incorrect', ['app' => 'dav', 'address' => $emailAddress]);
					continue;
				}

				$message = $this->mailer->createMessage();
				$message->setFrom([$fromEMail]);
				if ($organizer) {
					$message->setReplyTo($organizer);
				}
				$message->setTo([$emailAddress]);
				$message->useTemplate($template);

				try {
					$failed = $this->mailer->send($message);
					if ($failed) {
						$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
					}
				} catch (\Exception $ex) {
					$this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
				}
			}
		}
	}

	/**
	 * @param IEMailTemplate $template
	 * @param IL10N $l10n
	 * @param VEvent $vevent
	 */
	private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEvent $vevent):void {
		$template->setSubject('Notification: ' . $this->getTitleFromVEvent($vevent, $l10n));
		$template->addHeading($this->getTitleFromVEvent($vevent, $l10n));
	}

	/**
	 * @param IEMailTemplate $template
	 * @param IL10N $l10n
	 * @param string $calendarDisplayName
	 * @param array $eventData
	 */
	private function addBulletList(IEMailTemplate $template,
								   IL10N $l10n,
								   string $calendarDisplayName,
								   VEvent $vevent):void {
		$template->addBodyListItem($calendarDisplayName, $l10n->t('Calendar:'),
			$this->getAbsoluteImagePath('actions/info.png'));

		$template->addBodyListItem($this->generateDateString($l10n, $vevent), $l10n->t('Date:'),
			$this->getAbsoluteImagePath('places/calendar.png'));

		if (isset($vevent->LOCATION)) {
			$template->addBodyListItem((string) $vevent->LOCATION, $l10n->t('Where:'),
				$this->getAbsoluteImagePath('actions/address.png'));
		}
		if (isset($vevent->DESCRIPTION)) {
			$template->addBodyListItem((string) $vevent->DESCRIPTION, $l10n->t('Description:'),
				$this->getAbsoluteImagePath('actions/more.png'));
		}
	}

	/**
	 * @param string $path
	 * @return string
	 */
	private function getAbsoluteImagePath(string $path):string {
		return $this->urlGenerator->getAbsoluteURL(
			$this->urlGenerator->imagePath('core', $path)
		);
	}

	/**
	 * @param VEvent $vevent
	 * @return array|null
	 */
	private function getOrganizerEMailAndNameFromEvent(VEvent $vevent):?array {
		if (!$vevent->ORGANIZER) {
			return null;
		}

		$organizer = $vevent->ORGANIZER;
		if (strcasecmp($organizer->getValue(), 'mailto:') !== 0) {
			return null;
		}

		$organizerEMail = substr($organizer->getValue(), 7);

		if ($organizerEMail === false || !$this->mailer->validateMailAddress($organizerEMail)) {
			return null;
		}

		$name = $organizer->offsetGet('CN');
		if ($name instanceof Parameter) {
			return [$organizerEMail => $name];
		}

		return [$organizerEMail];
	}

	/**
	 * @param array $emails
	 * @param string $defaultLanguage
	 * @return array
	 */
	private function sortEMailAddressesByLanguage(array $emails,
												  string $defaultLanguage):array {
		$sortedByLanguage = [];

		foreach ($emails as $emailAddress => $parameters) {
			if (isset($parameters['LANG'])) {
				$lang = $parameters['LANG'];
			} else {
				$lang = $defaultLanguage;
			}

			if (!isset($sortedByLanguage[$lang])) {
				$sortedByLanguage[$lang] = [];
			}

			$sortedByLanguage[$lang][] = $emailAddress;
		}

		return $sortedByLanguage;
	}

	/**
	 * @param VEvent $vevent
	 * @return array
	 */
	private function getAllEMailAddressesFromEvent(VEvent $vevent):array {
		$emailAddresses = [];

		if (isset($vevent->ATTENDEE)) {
			foreach ($vevent->ATTENDEE as $attendee) {
				if (!($attendee instanceof VObject\Property)) {
					continue;
				}

				$cuType = $this->getCUTypeOfAttendee($attendee);
				if (\in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) {
					// Don't send emails to things
					continue;
				}

				$partstat = $this->getPartstatOfAttendee($attendee);
				if ($partstat === 'DECLINED') {
					// Don't send out emails to people who declined
					continue;
				}
				if ($partstat === 'DELEGATED') {
					$delegates = $attendee->offsetGet('DELEGATED-TO');
					if (!($delegates instanceof VObject\Parameter)) {
						continue;
					}

					$emailAddressesOfDelegates = $delegates->getParts();
					foreach ($emailAddressesOfDelegates as $addressesOfDelegate) {
						if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) {
							$emailAddresses[substr($addressesOfDelegate, 7)] = [];
						}
					}

					continue;
				}

				$emailAddressOfAttendee = $this->getEMailAddressOfAttendee($attendee);
				if ($emailAddressOfAttendee !== null) {
					$properties = [];

					$langProp = $attendee->offsetGet('LANG');
					if ($langProp instanceof VObject\Parameter) {
						$properties['LANG'] = $langProp->getValue();
					}

					$emailAddresses[$emailAddressOfAttendee] = $properties;
				}
			}
		}

		if (isset($vevent->ORGANIZER) && $this->hasAttendeeMailURI($vevent->ORGANIZER)) {
			$emailAddresses[$this->getEMailAddressOfAttendee($vevent->ORGANIZER)] = [];
		}

		return $emailAddresses;
	}



	/**
	 * @param VObject\Property $attendee
	 * @return string
	 */
	private function getCUTypeOfAttendee(VObject\Property $attendee):string {
		$cuType = $attendee->offsetGet('CUTYPE');
		if ($cuType instanceof VObject\Parameter) {
			return strtoupper($cuType->getValue());
		}

		return 'INDIVIDUAL';
	}

	/**
	 * @param VObject\Property $attendee
	 * @return string
	 */
	private function getPartstatOfAttendee(VObject\Property $attendee):string {
		$partstat = $attendee->offsetGet('PARTSTAT');
		if ($partstat instanceof VObject\Parameter) {
			return strtoupper($partstat->getValue());
		}

		return 'NEEDS-ACTION';
	}

	/**
	 * @param VObject\Property $attendee
	 * @return bool
	 */
	private function hasAttendeeMailURI(VObject\Property $attendee):bool {
		return stripos($attendee->getValue(), 'mailto:') === 0;
	}

	/**
	 * @param VObject\Property $attendee
	 * @return string|null
	 */
	private function getEMailAddressOfAttendee(VObject\Property $attendee):?string {
		if (!$this->hasAttendeeMailURI($attendee)) {
			return null;
		}

		return substr($attendee->getValue(), 7);
	}

	/**
	 * @param array $users
	 * @return array
	 */
	private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array {
		$emailAddresses = [];

		foreach ($users as $user) {
			$emailAddress = $user->getEMailAddress();
			if ($emailAddress) {
				$lang = $this->l10nFactory->getUserLanguage($user);
				if ($lang) {
					$emailAddresses[$emailAddress] = [
						'LANG' => $lang,
					];
				} else {
					$emailAddresses[$emailAddress] = [];
				}
			}
		}

		return $emailAddresses;
	}

	/**
	 * @param IL10N $l10n
	 * @param VEvent $vevent
	 * @return string
	 * @throws \Exception
	 */
	private function generateDateString(IL10N $l10n, VEvent $vevent):string {
		$isAllDay = $vevent->DTSTART instanceof Property\ICalendar\Date;

		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
		/** @var \DateTimeImmutable $dtstartDt */
		$dtstartDt = $vevent->DTSTART->getDateTime();
		/** @var \DateTimeImmutable $dtendDt */
		$dtendDt = $this->getDTEndFromEvent($vevent)->getDateTime();

		$diff = $dtstartDt->diff($dtendDt);

		$dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM));
		$dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM));

		if ($isAllDay) {
			// One day event
			if ($diff->days === 1) {
				return $this->getDateString($l10n, $dtstartDt);
			}

			return implode(' - ', [
				$this->getDateString($l10n, $dtstartDt),
				$this->getDateString($l10n, $dtendDt),
			]);
		}

		$startTimezone = $endTimezone = null;
		if (!$vevent->DTSTART->isFloating()) {
			$startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName();
			$endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName();
		}

		$localeStart = implode(', ', [
			$this->getWeekDayName($l10n, $dtstartDt),
			$this->getDateTimeString($l10n, $dtstartDt)
		]);

		// always show full date with timezone if timezones are different
		if ($startTimezone !== $endTimezone) {
			$localeEnd = implode(', ', [
				$this->getWeekDayName($l10n, $dtendDt),
				$this->getDateTimeString($l10n, $dtendDt)
			]);

			return $localeStart
				. ' (' . $startTimezone . ') '
				. ' - '
				. $localeEnd
				. ' (' . $endTimezone . ')';
		}

		// Show only the time if the day is the same
		$localeEnd = $this->isDayEqual($dtstartDt, $dtendDt)
			? $this->getTimeString($l10n, $dtendDt)
			: implode(', ', [
				$this->getWeekDayName($l10n, $dtendDt),
				$this->getDateTimeString($l10n, $dtendDt)
			]);

		return $localeStart
			. ' - '
			. $localeEnd
			. ' (' . $startTimezone . ')';
	}

	/**
	 * @param DateTime $dtStart
	 * @param DateTime $dtEnd
	 * @return bool
	 */
	private function isDayEqual(DateTime $dtStart,
								DateTime $dtEnd):bool {
		return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
	}

	/**
	 * @param IL10N $l10n
	 * @param DateTime $dt
	 * @return string
	 */
	private function getWeekDayName(IL10N $l10n, DateTime $dt):string {
		return $l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
	}

	/**
	 * @param IL10N $l10n
	 * @param DateTime $dt
	 * @return string
	 */
	private function getDateString(IL10N $l10n, DateTime $dt):string {
		return $l10n->l('date', $dt, ['width' => 'medium']);
	}

	/**
	 * @param IL10N $l10n
	 * @param DateTime $dt
	 * @return string
	 */
	private function getDateTimeString(IL10N $l10n, DateTime $dt):string {
		return $l10n->l('datetime', $dt, ['width' => 'medium|short']);
	}

	/**
	 * @param IL10N $l10n
	 * @param DateTime $dt
	 * @return string
	 */
	private function getTimeString(IL10N $l10n, DateTime $dt):string {
		return $l10n->l('time', $dt, ['width' => 'short']);
	}

	/**
	 * @param VEvent $vevent
	 * @param IL10N $l10n
	 * @return string
	 */
	private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string {
		if (isset($vevent->SUMMARY)) {
			return (string)$vevent->SUMMARY;
		}

		return $l10n->t('Untitled event');
	}
}