Passed
Push — master ( b1a0d4...6df6fc )
by Roeland
10:53 queued 10s
created

BirthdayService::resetForUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016, ownCloud, Inc.
5
 * @copyright Copyright (c) 2019, Georg Ehrke
6
 *
7
 * @author Achim Königs <[email protected]>
8
 * @author Georg Ehrke <[email protected]>
9
 * @author Joas Schilling <[email protected]>
10
 * @author Robin Appelman <[email protected]>
11
 * @author Roeland Jago Douma <[email protected]>
12
 * @author Thomas Müller <[email protected]>
13
 *
14
 * @license AGPL-3.0
15
 *
16
 * This code is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License, version 3,
18
 * as published by the Free Software Foundation.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
 * GNU Affero General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License, version 3,
26
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
27
 *
28
 */
29
30
namespace OCA\DAV\CalDAV;
31
32
use Exception;
33
use OCA\DAV\CardDAV\CardDavBackend;
34
use OCA\DAV\DAV\GroupPrincipalBackend;
35
use OCP\IConfig;
36
use OCP\IDBConnection;
37
use OCP\IL10N;
38
use Sabre\VObject\Component\VCalendar;
39
use Sabre\VObject\Component\VCard;
40
use Sabre\VObject\DateTimeParser;
41
use Sabre\VObject\Document;
42
use Sabre\VObject\InvalidDataException;
43
use Sabre\VObject\Property\VCard\DateAndOrTime;
44
use Sabre\VObject\Reader;
45
46
/**
47
 * Class BirthdayService
48
 *
49
 * @package OCA\DAV\CalDAV
50
 */
51
class BirthdayService {
52
53
	const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';
54
55
	/** @var GroupPrincipalBackend */
56
	private $principalBackend;
57
58
	/** @var CalDavBackend  */
59
	private $calDavBackEnd;
60
61
	/** @var CardDavBackend  */
62
	private $cardDavBackEnd;
63
64
	/** @var IConfig */
65
	private $config;
66
67
	/** @var IDBConnection */
68
	private $dbConnection;
69
70
	/** @var IL10N */
71
	private $l10n;
72
73
	/**
74
	 * BirthdayService constructor.
75
	 *
76
	 * @param CalDavBackend $calDavBackEnd
77
	 * @param CardDavBackend $cardDavBackEnd
78
	 * @param GroupPrincipalBackend $principalBackend
79
	 * @param IConfig $config
80
	 * @param IDBConnection $dbConnection
81
	 * @param IL10N $l10n
82
	 */
83
	public function __construct(CalDavBackend $calDavBackEnd,
84
								CardDavBackend $cardDavBackEnd,
85
								GroupPrincipalBackend $principalBackend,
86
								IConfig $config,
87
								IDBConnection $dbConnection,
88
								IL10N $l10n) {
89
		$this->calDavBackEnd = $calDavBackEnd;
90
		$this->cardDavBackEnd = $cardDavBackEnd;
91
		$this->principalBackend = $principalBackend;
92
		$this->config = $config;
93
		$this->dbConnection = $dbConnection;
94
		$this->l10n = $l10n;
95
	}
96
97
	/**
98
	 * @param int $addressBookId
99
	 * @param string $cardUri
100
	 * @param string $cardData
101
	 */
102
	public function onCardChanged(int $addressBookId,
103
								  string $cardUri,
104
								  string $cardData) {
105
		if (!$this->isGloballyEnabled()) {
106
			return;
107
		}
108
109
		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
110
		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $book is correct as $this->cardDavBackEnd->g...ookById($addressBookId) targeting OCA\DAV\CardDAV\CardDavB...d::getAddressBookById() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
111
		$targetPrincipals[] = $book['principaluri'];
112
		$datesToSync = [
113
			['postfix' => '', 'field' => 'BDAY'],
114
			['postfix' => '-death', 'field' => 'DEATHDATE'],
115
			['postfix' => '-anniversary', 'field' => 'ANNIVERSARY'],
116
		];
117
118
		foreach ($targetPrincipals as $principalUri) {
119
			if (!$this->isUserEnabled($principalUri)) {
120
				continue;
121
			}
122
123
			$calendar = $this->ensureCalendarExists($principalUri);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $calendar is correct as $this->ensureCalendarExists($principalUri) targeting OCA\DAV\CalDAV\BirthdayS...:ensureCalendarExists() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
124
			foreach ($datesToSync as $type) {
125
				$this->updateCalendar($cardUri, $cardData, $book, (int) $calendar['id'], $type);
0 ignored issues
show
Bug introduced by
$book of type null is incompatible with the type array expected by parameter $book of OCA\DAV\CalDAV\BirthdayService::updateCalendar(). ( Ignorable by Annotation )

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

125
				$this->updateCalendar($cardUri, $cardData, /** @scrutinizer ignore-type */ $book, (int) $calendar['id'], $type);
Loading history...
126
			}
127
		}
128
	}
129
130
	/**
131
	 * @param int $addressBookId
132
	 * @param string $cardUri
133
	 */
134
	public function onCardDeleted(int $addressBookId,
135
								  string $cardUri) {
136
		if (!$this->isGloballyEnabled()) {
137
			return;
138
		}
139
140
		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
141
		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $book is correct as $this->cardDavBackEnd->g...ookById($addressBookId) targeting OCA\DAV\CardDAV\CardDavB...d::getAddressBookById() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
142
		$targetPrincipals[] = $book['principaluri'];
143
		foreach ($targetPrincipals as $principalUri) {
144
			if (!$this->isUserEnabled($principalUri)) {
145
				continue;
146
			}
147
148
			$calendar = $this->ensureCalendarExists($principalUri);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $calendar is correct as $this->ensureCalendarExists($principalUri) targeting OCA\DAV\CalDAV\BirthdayS...:ensureCalendarExists() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
149
			foreach (['', '-death', '-anniversary'] as $tag) {
150
				$objectUri = $book['uri'] . '-' . $cardUri . $tag .'.ics';
151
				$this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri);
152
			}
153
		}
154
	}
155
156
	/**
157
	 * @param string $principal
158
	 * @return array|null
159
	 * @throws \Sabre\DAV\Exception\BadRequest
160
	 */
161
	public function ensureCalendarExists(string $principal):?array {
162
		$calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $calendar is correct as $this->calDavBackEnd->ge...:BIRTHDAY_CALENDAR_URI) targeting OCA\DAV\CalDAV\CalDavBackend::getCalendarByUri() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
163
		if (!is_null($calendar)) {
0 ignored issues
show
introduced by
The condition is_null($calendar) is always true.
Loading history...
164
			return $calendar;
165
		}
166
		$this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
167
			'{DAV:}displayname' => 'Contact birthdays',
168
			'{http://apple.com/ns/ical/}calendar-color' => '#FFFFCA',
169
			'components'   => 'VEVENT',
170
		]);
171
172
		return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->calDavBackEnd->ge...:BIRTHDAY_CALENDAR_URI) targeting OCA\DAV\CalDAV\CalDavBackend::getCalendarByUri() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
173
	}
174
175
	/**
176
	 * @param $cardData
177
	 * @param $dateField
178
	 * @param $postfix
179
	 * @return VCalendar|null
180
	 * @throws InvalidDataException
181
	 */
182
	public function buildDateFromContact(string $cardData,
183
										 string $dateField,
184
										 string $postfix):?VCalendar {
185
		if (empty($cardData)) {
186
			return null;
187
		}
188
		try {
189
			$doc = Reader::read($cardData);
190
			// We're always converting to vCard 4.0 so we can rely on the
191
			// VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
192
			if (!$doc instanceof VCard) {
193
				return null;
194
			}
195
			$doc = $doc->convert(Document::VCARD40);
196
		} catch (Exception $e) {
197
			return null;
198
		}
199
200
		if (!isset($doc->{$dateField})) {
201
			return null;
202
		}
203
		if (!isset($doc->FN)) {
204
			return null;
205
		}
206
		$birthday = $doc->{$dateField};
207
		if (!(string)$birthday) {
208
			return null;
209
		}
210
		// Skip if the BDAY property is not of the right type.
211
		if (!$birthday instanceof DateAndOrTime) {
212
			return null;
213
		}
214
215
		// Skip if we can't parse the BDAY value.
216
		try {
217
			$dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
218
		} catch (InvalidDataException $e) {
219
			return null;
220
		}
221
222
		$unknownYear = false;
223
		$originalYear = null;
224
		if (!$dateParts['year']) {
225
			$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
226
227
			$unknownYear = true;
228
		} else {
229
			$parameters = $birthday->parameters();
230
			if (isset($parameters['X-APPLE-OMIT-YEAR'])) {
231
				$omitYear = $parameters['X-APPLE-OMIT-YEAR'];
232
				if ($dateParts['year'] === $omitYear) {
233
					$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
234
					$unknownYear = true;
235
				}
236
			} else {
237
				$originalYear = (int)$dateParts['year'];
238
239
				if ($originalYear < 1970) {
240
					$birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
241
				}
242
			}
243
		}
244
245
		try {
246
			$date = new \DateTime($birthday);
247
		} catch (Exception $e) {
248
			return null;
249
		}
250
251
		$summary = $this->formatTitle($dateField, $doc->FN->getValue(), $originalYear, $this->dbConnection->supports4ByteText());
252
253
		$vCal = new VCalendar();
254
		$vCal->VERSION = '2.0';
255
		$vEvent = $vCal->createComponent('VEVENT');
256
		$vEvent->add('DTSTART');
257
		$vEvent->DTSTART->setDateTime(
0 ignored issues
show
Bug introduced by
The method setDateTime() does not exist on Sabre\VObject\Property. It seems like you code against a sub-type of Sabre\VObject\Property such as Sabre\VObject\Property\ICalendar\DateTime or Sabre\VObject\Property\VCard\DateAndOrTime. ( Ignorable by Annotation )

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

257
		$vEvent->DTSTART->/** @scrutinizer ignore-call */ 
258
                    setDateTime(
Loading history...
258
			$date
259
		);
260
		$vEvent->DTSTART['VALUE'] = 'DATE';
261
		$vEvent->add('DTEND');
262
		$date->add(new \DateInterval('P1D'));
263
		$vEvent->DTEND->setDateTime(
264
			$date
265
		);
266
		$vEvent->DTEND['VALUE'] = 'DATE';
267
		$vEvent->{'UID'} = $doc->UID . $postfix;
268
		$vEvent->{'RRULE'} = 'FREQ=YEARLY';
269
		$vEvent->{'SUMMARY'} = $summary;
270
		$vEvent->{'TRANSP'} = 'TRANSPARENT';
271
		$vEvent->{'X-NEXTCLOUD-BC-FIELD-TYPE'} = $dateField;
272
		$vEvent->{'X-NEXTCLOUD-BC-UNKNOWN-YEAR'} = $unknownYear ? '1' : '0';
273
		if ($originalYear !== null) {
274
			$vEvent->{'X-NEXTCLOUD-BC-YEAR'} = (string) $originalYear;
275
		}
276
		$alarm = $vCal->createComponent('VALARM');
277
		$alarm->add($vCal->createProperty('TRIGGER', '-PT0M', ['VALUE' => 'DURATION']));
278
		$alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
279
		$alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
280
		$vEvent->add($alarm);
281
		$vCal->add($vEvent);
282
		return $vCal;
283
	}
284
285
	/**
286
	 * @param string $user
287
	 */
288
	public function resetForUser(string $user):void {
289
		$principal = 'principals/users/'.$user;
290
		$calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $calendar is correct as $this->calDavBackEnd->ge...:BIRTHDAY_CALENDAR_URI) targeting OCA\DAV\CalDAV\CalDavBackend::getCalendarByUri() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
291
		$calendarObjects = $this->calDavBackEnd->getCalendarObjects($calendar['id'], CalDavBackend::CALENDAR_TYPE_CALENDAR);
292
293
		foreach($calendarObjects as $calendarObject) {
294
			$this->calDavBackEnd->deleteCalendarObject($calendar['id'], $calendarObject['uri'], CalDavBackend::CALENDAR_TYPE_CALENDAR);
295
		}
296
	}
297
298
	/**
299
	 * @param string $user
300
	 * @throws \Sabre\DAV\Exception\BadRequest
301
	 */
302
	public function syncUser(string $user):void {
303
		$principal = 'principals/users/'.$user;
304
		$this->ensureCalendarExists($principal);
305
		$books = $this->cardDavBackEnd->getAddressBooksForUser($principal);
306
		foreach($books as $book) {
307
			$cards = $this->cardDavBackEnd->getCards($book['id']);
308
			foreach($cards as $card) {
309
				$this->onCardChanged($book['id'], $card['uri'], $card['carddata']);
310
			}
311
		}
312
	}
313
314
	/**
315
	 * @param string $existingCalendarData
316
	 * @param VCalendar $newCalendarData
317
	 * @return bool
318
	 */
319
	public function birthdayEvenChanged(string $existingCalendarData,
320
										VCalendar $newCalendarData):bool {
321
		try {
322
			$existingBirthday = Reader::read($existingCalendarData);
323
		} catch (Exception $ex) {
324
			return true;
325
		}
326
327
		return (
328
			$newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue() ||
0 ignored issues
show
Bug introduced by
The property DTSTART does not seem to exist on Sabre\VObject\Property.
Loading history...
329
			$newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
0 ignored issues
show
Bug introduced by
The property SUMMARY does not seem to exist on Sabre\VObject\Property.
Loading history...
330
		);
331
	}
332
333
	/**
334
	 * @param integer $addressBookId
335
	 * @return mixed
336
	 */
337
	protected function getAllAffectedPrincipals(int $addressBookId) {
338
		$targetPrincipals = [];
339
		$shares = $this->cardDavBackEnd->getShares($addressBookId);
340
		foreach ($shares as $share) {
341
			if ($share['{http://owncloud.org/ns}group-share']) {
342
				$users = $this->principalBackend->getGroupMemberSet($share['{http://owncloud.org/ns}principal']);
343
				foreach ($users as $user) {
344
					$targetPrincipals[] = $user['uri'];
345
				}
346
			} else {
347
				$targetPrincipals[] = $share['{http://owncloud.org/ns}principal'];
348
			}
349
		}
350
		return array_values(array_unique($targetPrincipals, SORT_STRING));
351
	}
352
353
	/**
354
	 * @param string $cardUri
355
	 * @param string $cardData
356
	 * @param array $book
357
	 * @param int $calendarId
358
	 * @param array $type
359
	 * @throws InvalidDataException
360
	 * @throws \Sabre\DAV\Exception\BadRequest
361
	 */
362
	private function updateCalendar(string $cardUri,
363
									string $cardData,
364
									array $book,
365
									int $calendarId,
366
									array $type):void {
367
		$objectUri = $book['uri'] . '-' . $cardUri . $type['postfix'] . '.ics';
368
		$calendarData = $this->buildDateFromContact($cardData, $type['field'], $type['postfix']);
369
		$existing = $this->calDavBackEnd->getCalendarObject($calendarId, $objectUri);
370
		if (is_null($calendarData)) {
371
			if (!is_null($existing)) {
372
				$this->calDavBackEnd->deleteCalendarObject($calendarId, $objectUri);
373
			}
374
		} else {
375
			if (is_null($existing)) {
376
				$this->calDavBackEnd->createCalendarObject($calendarId, $objectUri, $calendarData->serialize());
377
			} else {
378
				if ($this->birthdayEvenChanged($existing['calendardata'], $calendarData)) {
379
					$this->calDavBackEnd->updateCalendarObject($calendarId, $objectUri, $calendarData->serialize());
380
				}
381
			}
382
		}
383
	}
384
385
	/**
386
	 * checks if the admin opted-out of birthday calendars
387
	 *
388
	 * @return bool
389
	 */
390
	private function isGloballyEnabled():bool {
391
		return $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes') === 'yes';
392
	}
393
394
	/**
395
	 * Checks if the user opted-out of birthday calendars
396
	 *
397
	 * @param string $userPrincipal The user principal to check for
398
	 * @return bool
399
	 */
400
	private function isUserEnabled(string $userPrincipal):bool {
401
		if (strpos($userPrincipal, 'principals/users/') === 0) {
402
			$userId = substr($userPrincipal, 17);
403
			$isEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
404
			return $isEnabled === 'yes';
405
		}
406
407
		// not sure how we got here, just be on the safe side and return true
408
		return true;
409
	}
410
411
	/**
412
	 * Formats title of Birthday event
413
	 *
414
	 * @param string $field Field name like BDAY, ANNIVERSARY, ...
415
	 * @param string $name Name of contact
416
	 * @param int|null $year Year of birth, anniversary, ...
417
	 * @param bool $supports4Byte Whether or not the database supports 4 byte chars
418
	 * @return string The formatted title
419
	 */
420
	private function formatTitle(string $field,
421
								 string $name,
422
								 int $year=null,
423
								 bool $supports4Byte=true):string {
424
		if ($supports4Byte) {
425
			switch ($field) {
426
				case 'BDAY':
427
					return implode('', [
428
						'🎂 ',
429
						$name,
430
						$year ? (' (' . $year . ')') : '',
431
					]);
432
433
				case 'DEATHDATE':
434
					return implode('', [
435
						$this->l10n->t('Death of %s', [$name]),
436
						$year ? (' (' . $year . ')') : '',
437
					]);
438
439
				case 'ANNIVERSARY':
440
					return implode('', [
441
						'💍 ',
442
						$name,
443
						$year ? (' (' . $year . ')') : '',
444
					]);
445
446
				default:
447
					return '';
448
			}
449
		} else {
450
			switch($field) {
451
				case 'BDAY':
452
					return implode('', [
453
						$name,
454
						' ',
455
						$year ? ('(*' . $year . ')') : '*',
456
					]);
457
458
				case 'DEATHDATE':
459
					return implode('', [
460
						$this->l10n->t('Death of %s', [$name]),
461
						$year ? (' (' . $year . ')') : '',
462
					]);
463
464
				case 'ANNIVERSARY':
465
					return implode('', [
466
						$name,
467
						' ',
468
						$year ? ('(⚭' . $year . ')') : '⚭',
469
					]);
470
471
				default:
472
					return '';
473
			}
474
		}
475
	}
476
}
477