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

BirthdayService.php « CalDAV « lib « dav « apps - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e9f4787a328b01b07f6574163ff867a49fd59636 (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
<?php

declare(strict_types=1);

/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 * @copyright Copyright (c) 2019, Georg Ehrke
 *
 * @author Achim Königs <garfonso@tratschtante.de>
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 * @author Georg Ehrke <oc.list@georgehrke.com>
 * @author Robin Appelman <robin@icewind.nl>
 * @author Sven Strickroth <email@cs-ware.de>
 * @author Thomas Müller <thomas.mueller@tmit.eu>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */

namespace OCA\DAV\CalDAV;

use Exception;
use OCA\DAV\CardDAV\CardDavBackend;
use OCA\DAV\DAV\GroupPrincipalBackend;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IL10N;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VCard;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\Document;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\Property\VCard\DateAndOrTime;
use Sabre\VObject\Reader;

/**
 * Class BirthdayService
 *
 * @package OCA\DAV\CalDAV
 */
class BirthdayService {
	public const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';

	/** @var GroupPrincipalBackend */
	private $principalBackend;

	/** @var CalDavBackend  */
	private $calDavBackEnd;

	/** @var CardDavBackend  */
	private $cardDavBackEnd;

	/** @var IConfig */
	private $config;

	/** @var IDBConnection */
	private $dbConnection;

	/** @var IL10N */
	private $l10n;

	/**
	 * BirthdayService constructor.
	 *
	 * @param CalDavBackend $calDavBackEnd
	 * @param CardDavBackend $cardDavBackEnd
	 * @param GroupPrincipalBackend $principalBackend
	 * @param IConfig $config
	 * @param IDBConnection $dbConnection
	 * @param IL10N $l10n
	 */
	public function __construct(CalDavBackend $calDavBackEnd,
								CardDavBackend $cardDavBackEnd,
								GroupPrincipalBackend $principalBackend,
								IConfig $config,
								IDBConnection $dbConnection,
								IL10N $l10n) {
		$this->calDavBackEnd = $calDavBackEnd;
		$this->cardDavBackEnd = $cardDavBackEnd;
		$this->principalBackend = $principalBackend;
		$this->config = $config;
		$this->dbConnection = $dbConnection;
		$this->l10n = $l10n;
	}

	/**
	 * @param int $addressBookId
	 * @param string $cardUri
	 * @param string $cardData
	 */
	public function onCardChanged(int $addressBookId,
								  string $cardUri,
								  string $cardData) {
		if (!$this->isGloballyEnabled()) {
			return;
		}

		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
		$targetPrincipals[] = $book['principaluri'];
		$datesToSync = [
			['postfix' => '', 'field' => 'BDAY'],
			['postfix' => '-death', 'field' => 'DEATHDATE'],
			['postfix' => '-anniversary', 'field' => 'ANNIVERSARY'],
		];

		foreach ($targetPrincipals as $principalUri) {
			if (!$this->isUserEnabled($principalUri)) {
				continue;
			}

			$calendar = $this->ensureCalendarExists($principalUri);
			foreach ($datesToSync as $type) {
				$this->updateCalendar($cardUri, $cardData, $book, (int) $calendar['id'], $type);
			}
		}
	}

	/**
	 * @param int $addressBookId
	 * @param string $cardUri
	 */
	public function onCardDeleted(int $addressBookId,
								  string $cardUri) {
		if (!$this->isGloballyEnabled()) {
			return;
		}

		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
		$targetPrincipals[] = $book['principaluri'];
		foreach ($targetPrincipals as $principalUri) {
			if (!$this->isUserEnabled($principalUri)) {
				continue;
			}

			$calendar = $this->ensureCalendarExists($principalUri);
			foreach (['', '-death', '-anniversary'] as $tag) {
				$objectUri = $book['uri'] . '-' . $cardUri . $tag .'.ics';
				$this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri);
			}
		}
	}

	/**
	 * @param string $principal
	 * @return array|null
	 * @throws \Sabre\DAV\Exception\BadRequest
	 */
	public function ensureCalendarExists(string $principal):?array {
		$calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
		if (!is_null($calendar)) {
			return $calendar;
		}
		$this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
			'{DAV:}displayname' => $this->l10n->t('Contact birthdays'),
			'{http://apple.com/ns/ical/}calendar-color' => '#E9D859',
			'components' => 'VEVENT',
		]);

		return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
	}

	/**
	 * @param $cardData
	 * @param $dateField
	 * @param $postfix
	 * @return VCalendar|null
	 * @throws InvalidDataException
	 */
	public function buildDateFromContact(string $cardData,
										 string $dateField,
										 string $postfix):?VCalendar {
		if (empty($cardData)) {
			return null;
		}
		try {
			$doc = Reader::read($cardData);
			// We're always converting to vCard 4.0 so we can rely on the
			// VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
			if (!$doc instanceof VCard) {
				return null;
			}
			$doc = $doc->convert(Document::VCARD40);
		} catch (Exception $e) {
			return null;
		}

		if (!isset($doc->{$dateField})) {
			return null;
		}
		if (!isset($doc->FN)) {
			return null;
		}
		$birthday = $doc->{$dateField};
		if (!(string)$birthday) {
			return null;
		}
		// Skip if the BDAY property is not of the right type.
		if (!$birthday instanceof DateAndOrTime) {
			return null;
		}

		// Skip if we can't parse the BDAY value.
		try {
			$dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
		} catch (InvalidDataException $e) {
			return null;
		}

		$unknownYear = false;
		$originalYear = null;
		if (!$dateParts['year']) {
			$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];

			$unknownYear = true;
		} else {
			$parameters = $birthday->parameters();
			if (isset($parameters['X-APPLE-OMIT-YEAR'])) {
				$omitYear = $parameters['X-APPLE-OMIT-YEAR'];
				if ($dateParts['year'] === $omitYear) {
					$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
					$unknownYear = true;
				}
			} else {
				$originalYear = (int)$dateParts['year'];
				// 'X-APPLE-OMIT-YEAR' is not always present, at least iOS 12.4 uses the hard coded date of 1604 (the start of the gregorian calendar) when the year is unknown
				if ($originalYear == 1604) {
					$originalYear = null;
					$unknownYear = true;
					$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
				}
				if ($originalYear < 1970) {
					$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
				}
			}
		}

		try {
			if ($birthday instanceof DateAndOrTime) {
				$date = $birthday->getDateTime();
			} else {
				$date = new \DateTimeImmutable($birthday);
			}
		} catch (Exception $e) {
			return null;
		}

		$summary = $this->formatTitle($dateField, $doc->FN->getValue(), $originalYear, $this->dbConnection->supports4ByteText());

		$vCal = new VCalendar();
		$vCal->VERSION = '2.0';
		$vCal->PRODID = '-//IDN nextcloud.com//Birthday calendar//EN';
		$vEvent = $vCal->createComponent('VEVENT');
		$vEvent->add('DTSTART');
		$vEvent->DTSTART->setDateTime(
			$date
		);
		$vEvent->DTSTART['VALUE'] = 'DATE';
		$vEvent->add('DTEND');

		$dtEndDate = (new \DateTime())->setTimestamp($date->getTimeStamp());
		$dtEndDate->add(new \DateInterval('P1D'));
		$vEvent->DTEND->setDateTime(
			$dtEndDate
		);

		$vEvent->DTEND['VALUE'] = 'DATE';
		$vEvent->{'UID'} = $doc->UID . $postfix;
		$vEvent->{'RRULE'} = 'FREQ=YEARLY';
		$vEvent->{'SUMMARY'} = $summary;
		$vEvent->{'TRANSP'} = 'TRANSPARENT';
		$vEvent->{'X-NEXTCLOUD-BC-FIELD-TYPE'} = $dateField;
		$vEvent->{'X-NEXTCLOUD-BC-UNKNOWN-YEAR'} = $unknownYear ? '1' : '0';
		if ($originalYear !== null) {
			$vEvent->{'X-NEXTCLOUD-BC-YEAR'} = (string) $originalYear;
		}
		$alarm = $vCal->createComponent('VALARM');
		$alarm->add($vCal->createProperty('TRIGGER', '-PT0M', ['VALUE' => 'DURATION']));
		$alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
		$alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
		$vEvent->add($alarm);
		$vCal->add($vEvent);
		return $vCal;
	}

	/**
	 * @param string $user
	 */
	public function resetForUser(string $user):void {
		$principal = 'principals/users/'.$user;
		$calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
		$calendarObjects = $this->calDavBackEnd->getCalendarObjects($calendar['id'], CalDavBackend::CALENDAR_TYPE_CALENDAR);

		foreach ($calendarObjects as $calendarObject) {
			$this->calDavBackEnd->deleteCalendarObject($calendar['id'], $calendarObject['uri'], CalDavBackend::CALENDAR_TYPE_CALENDAR);
		}
	}

	/**
	 * @param string $user
	 * @throws \Sabre\DAV\Exception\BadRequest
	 */
	public function syncUser(string $user):void {
		$principal = 'principals/users/'.$user;
		$this->ensureCalendarExists($principal);
		$books = $this->cardDavBackEnd->getAddressBooksForUser($principal);
		foreach ($books as $book) {
			$cards = $this->cardDavBackEnd->getCards($book['id']);
			foreach ($cards as $card) {
				$this->onCardChanged((int) $book['id'], $card['uri'], $card['carddata']);
			}
		}
	}

	/**
	 * @param string $existingCalendarData
	 * @param VCalendar $newCalendarData
	 * @return bool
	 */
	public function birthdayEvenChanged(string $existingCalendarData,
										VCalendar $newCalendarData):bool {
		try {
			$existingBirthday = Reader::read($existingCalendarData);
		} catch (Exception $ex) {
			return true;
		}

		return (
			$newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue() ||
			$newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
		);
	}

	/**
	 * @param integer $addressBookId
	 * @return mixed
	 */
	protected function getAllAffectedPrincipals(int $addressBookId) {
		$targetPrincipals = [];
		$shares = $this->cardDavBackEnd->getShares($addressBookId);
		foreach ($shares as $share) {
			if ($share['{http://owncloud.org/ns}group-share']) {
				$users = $this->principalBackend->getGroupMemberSet($share['{http://owncloud.org/ns}principal']);
				foreach ($users as $user) {
					$targetPrincipals[] = $user['uri'];
				}
			} else {
				$targetPrincipals[] = $share['{http://owncloud.org/ns}principal'];
			}
		}
		return array_values(array_unique($targetPrincipals, SORT_STRING));
	}

	/**
	 * @param string $cardUri
	 * @param string $cardData
	 * @param array $book
	 * @param int $calendarId
	 * @param array $type
	 * @throws InvalidDataException
	 * @throws \Sabre\DAV\Exception\BadRequest
	 */
	private function updateCalendar(string $cardUri,
									string $cardData,
									array $book,
									int $calendarId,
									array $type):void {
		$objectUri = $book['uri'] . '-' . $cardUri . $type['postfix'] . '.ics';
		$calendarData = $this->buildDateFromContact($cardData, $type['field'], $type['postfix']);
		$existing = $this->calDavBackEnd->getCalendarObject($calendarId, $objectUri);
		if (is_null($calendarData)) {
			if (!is_null($existing)) {
				$this->calDavBackEnd->deleteCalendarObject($calendarId, $objectUri);
			}
		} else {
			if (is_null($existing)) {
				$this->calDavBackEnd->createCalendarObject($calendarId, $objectUri, $calendarData->serialize());
			} else {
				if ($this->birthdayEvenChanged($existing['calendardata'], $calendarData)) {
					$this->calDavBackEnd->updateCalendarObject($calendarId, $objectUri, $calendarData->serialize());
				}
			}
		}
	}

	/**
	 * checks if the admin opted-out of birthday calendars
	 *
	 * @return bool
	 */
	private function isGloballyEnabled():bool {
		return $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes') === 'yes';
	}

	/**
	 * Checks if the user opted-out of birthday calendars
	 *
	 * @param string $userPrincipal The user principal to check for
	 * @return bool
	 */
	private function isUserEnabled(string $userPrincipal):bool {
		if (strpos($userPrincipal, 'principals/users/') === 0) {
			$userId = substr($userPrincipal, 17);
			$isEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
			return $isEnabled === 'yes';
		}

		// not sure how we got here, just be on the safe side and return true
		return true;
	}

	/**
	 * Formats title of Birthday event
	 *
	 * @param string $field Field name like BDAY, ANNIVERSARY, ...
	 * @param string $name Name of contact
	 * @param int|null $year Year of birth, anniversary, ...
	 * @param bool $supports4Byte Whether or not the database supports 4 byte chars
	 * @return string The formatted title
	 */
	private function formatTitle(string $field,
								 string $name,
								 int $year = null,
								 bool $supports4Byte = true):string {
		if ($supports4Byte) {
			switch ($field) {
				case 'BDAY':
					return implode('', [
						'🎂 ',
						$name,
						$year ? (' (' . $year . ')') : '',
					]);

				case 'DEATHDATE':
					return implode('', [
						$this->l10n->t('Death of %s', [$name]),
						$year ? (' (' . $year . ')') : '',
					]);

				case 'ANNIVERSARY':
					return implode('', [
						'💍 ',
						$name,
						$year ? (' (' . $year . ')') : '',
					]);

				default:
					return '';
			}
		} else {
			switch ($field) {
				case 'BDAY':
					return implode('', [
						$name,
						' ',
						$year ? ('(*' . $year . ')') : '*',
					]);

				case 'DEATHDATE':
					return implode('', [
						$this->l10n->t('Death of %s', [$name]),
						$year ? (' (' . $year . ')') : '',
					]);

				case 'ANNIVERSARY':
					return implode('', [
						$name,
						' ',
						$year ? ('(⚭' . $year . ')') : '⚭',
					]);

				default:
					return '';
			}
		}
	}
}