BirthdayService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\DAV\CalDAV;
  9. use Exception;
  10. use OCA\DAV\CardDAV\CardDavBackend;
  11. use OCA\DAV\DAV\GroupPrincipalBackend;
  12. use OCP\IConfig;
  13. use OCP\IDBConnection;
  14. use OCP\IL10N;
  15. use Sabre\VObject\Component\VCalendar;
  16. use Sabre\VObject\Component\VCard;
  17. use Sabre\VObject\DateTimeParser;
  18. use Sabre\VObject\Document;
  19. use Sabre\VObject\InvalidDataException;
  20. use Sabre\VObject\Property\VCard\DateAndOrTime;
  21. use Sabre\VObject\Reader;
  22. /**
  23. * Class BirthdayService
  24. *
  25. * @package OCA\DAV\CalDAV
  26. */
  27. class BirthdayService {
  28. public const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';
  29. public const EXCLUDE_FROM_BIRTHDAY_CALENDAR_PROPERTY_NAME = 'X-NC-EXCLUDE-FROM-BIRTHDAY-CALENDAR';
  30. /**
  31. * BirthdayService constructor.
  32. */
  33. public function __construct(
  34. private CalDavBackend $calDavBackEnd,
  35. private CardDavBackend $cardDavBackEnd,
  36. private GroupPrincipalBackend $principalBackend,
  37. private IConfig $config,
  38. private IDBConnection $dbConnection,
  39. private IL10N $l10n,
  40. ) {
  41. }
  42. public function onCardChanged(int $addressBookId,
  43. string $cardUri,
  44. string $cardData): void {
  45. if (!$this->isGloballyEnabled()) {
  46. return;
  47. }
  48. $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
  49. $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
  50. if ($book === null) {
  51. return;
  52. }
  53. $targetPrincipals[] = $book['principaluri'];
  54. $datesToSync = [
  55. ['postfix' => '', 'field' => 'BDAY'],
  56. ['postfix' => '-death', 'field' => 'DEATHDATE'],
  57. ['postfix' => '-anniversary', 'field' => 'ANNIVERSARY'],
  58. ];
  59. foreach ($targetPrincipals as $principalUri) {
  60. if (!$this->isUserEnabled($principalUri)) {
  61. continue;
  62. }
  63. $reminderOffset = $this->getReminderOffsetForUser($principalUri);
  64. $calendar = $this->ensureCalendarExists($principalUri);
  65. if ($calendar === null) {
  66. return;
  67. }
  68. foreach ($datesToSync as $type) {
  69. $this->updateCalendar($cardUri, $cardData, $book, (int)$calendar['id'], $type, $reminderOffset);
  70. }
  71. }
  72. }
  73. public function onCardDeleted(int $addressBookId,
  74. string $cardUri): void {
  75. if (!$this->isGloballyEnabled()) {
  76. return;
  77. }
  78. $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
  79. $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
  80. $targetPrincipals[] = $book['principaluri'];
  81. foreach ($targetPrincipals as $principalUri) {
  82. if (!$this->isUserEnabled($principalUri)) {
  83. continue;
  84. }
  85. $calendar = $this->ensureCalendarExists($principalUri);
  86. foreach (['', '-death', '-anniversary'] as $tag) {
  87. $objectUri = $book['uri'] . '-' . $cardUri . $tag . '.ics';
  88. $this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri, CalDavBackend::CALENDAR_TYPE_CALENDAR, true);
  89. }
  90. }
  91. }
  92. /**
  93. * @throws \Sabre\DAV\Exception\BadRequest
  94. */
  95. public function ensureCalendarExists(string $principal): ?array {
  96. $calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
  97. if (!is_null($calendar)) {
  98. return $calendar;
  99. }
  100. $this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
  101. '{DAV:}displayname' => $this->l10n->t('Contact birthdays'),
  102. '{http://apple.com/ns/ical/}calendar-color' => '#E9D859',
  103. 'components' => 'VEVENT',
  104. ]);
  105. return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
  106. }
  107. /**
  108. * @param $cardData
  109. * @param $dateField
  110. * @param $postfix
  111. * @param $reminderOffset
  112. * @return VCalendar|null
  113. * @throws InvalidDataException
  114. */
  115. public function buildDateFromContact(string $cardData,
  116. string $dateField,
  117. string $postfix,
  118. ?string $reminderOffset):?VCalendar {
  119. if (empty($cardData)) {
  120. return null;
  121. }
  122. try {
  123. $doc = Reader::read($cardData);
  124. // We're always converting to vCard 4.0 so we can rely on the
  125. // VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
  126. if (!$doc instanceof VCard) {
  127. return null;
  128. }
  129. $doc = $doc->convert(Document::VCARD40);
  130. } catch (Exception $e) {
  131. return null;
  132. }
  133. if (isset($doc->{self::EXCLUDE_FROM_BIRTHDAY_CALENDAR_PROPERTY_NAME})) {
  134. return null;
  135. }
  136. if (!isset($doc->{$dateField})) {
  137. return null;
  138. }
  139. if (!isset($doc->FN)) {
  140. return null;
  141. }
  142. $birthday = $doc->{$dateField};
  143. if (!(string)$birthday) {
  144. return null;
  145. }
  146. // Skip if the BDAY property is not of the right type.
  147. if (!$birthday instanceof DateAndOrTime) {
  148. return null;
  149. }
  150. // Skip if we can't parse the BDAY value.
  151. try {
  152. $dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
  153. } catch (InvalidDataException $e) {
  154. return null;
  155. }
  156. if ($dateParts['year'] !== null) {
  157. $parameters = $birthday->parameters();
  158. $omitYear = (isset($parameters['X-APPLE-OMIT-YEAR'])
  159. && $parameters['X-APPLE-OMIT-YEAR'] === $dateParts['year']);
  160. // '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
  161. if ($omitYear || (int)$dateParts['year'] === 1604) {
  162. $dateParts['year'] = null;
  163. }
  164. }
  165. $originalYear = null;
  166. if ($dateParts['year'] !== null) {
  167. $originalYear = (int)$dateParts['year'];
  168. }
  169. $leapDay = ((int)$dateParts['month'] === 2
  170. && (int)$dateParts['date'] === 29);
  171. if ($dateParts['year'] === null || $originalYear < 1970) {
  172. $birthday = ($leapDay ? '1972-' : '1970-')
  173. . $dateParts['month'] . '-' . $dateParts['date'];
  174. }
  175. try {
  176. if ($birthday instanceof DateAndOrTime) {
  177. $date = $birthday->getDateTime();
  178. } else {
  179. $date = new \DateTimeImmutable($birthday);
  180. }
  181. } catch (Exception $e) {
  182. return null;
  183. }
  184. $summary = $this->formatTitle($dateField, $doc->FN->getValue(), $originalYear, $this->dbConnection->supports4ByteText());
  185. $vCal = new VCalendar();
  186. $vCal->VERSION = '2.0';
  187. $vCal->PRODID = '-//IDN nextcloud.com//Birthday calendar//EN';
  188. $vEvent = $vCal->createComponent('VEVENT');
  189. $vEvent->add('DTSTART');
  190. $vEvent->DTSTART->setDateTime(
  191. $date
  192. );
  193. $vEvent->DTSTART['VALUE'] = 'DATE';
  194. $vEvent->add('DTEND');
  195. $dtEndDate = (new \DateTime())->setTimestamp($date->getTimeStamp());
  196. $dtEndDate->add(new \DateInterval('P1D'));
  197. $vEvent->DTEND->setDateTime(
  198. $dtEndDate
  199. );
  200. $vEvent->DTEND['VALUE'] = 'DATE';
  201. $vEvent->{'UID'} = $doc->UID . $postfix;
  202. $vEvent->{'RRULE'} = 'FREQ=YEARLY';
  203. if ($leapDay) {
  204. /* Sabre\VObject supports BYMONTHDAY only if BYMONTH
  205. * is also set */
  206. $vEvent->{'RRULE'} = 'FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=-1';
  207. }
  208. $vEvent->{'SUMMARY'} = $summary;
  209. $vEvent->{'TRANSP'} = 'TRANSPARENT';
  210. $vEvent->{'X-NEXTCLOUD-BC-FIELD-TYPE'} = $dateField;
  211. $vEvent->{'X-NEXTCLOUD-BC-UNKNOWN-YEAR'} = $dateParts['year'] === null ? '1' : '0';
  212. if ($originalYear !== null) {
  213. $vEvent->{'X-NEXTCLOUD-BC-YEAR'} = (string)$originalYear;
  214. }
  215. if ($reminderOffset) {
  216. $alarm = $vCal->createComponent('VALARM');
  217. $alarm->add($vCal->createProperty('TRIGGER', $reminderOffset, ['VALUE' => 'DURATION']));
  218. $alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
  219. $alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
  220. $vEvent->add($alarm);
  221. }
  222. $vCal->add($vEvent);
  223. return $vCal;
  224. }
  225. /**
  226. * @param string $user
  227. */
  228. public function resetForUser(string $user):void {
  229. $principal = 'principals/users/' . $user;
  230. $calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
  231. if (!$calendar) {
  232. return; // The user's birthday calendar doesn't exist, no need to purge it
  233. }
  234. $calendarObjects = $this->calDavBackEnd->getCalendarObjects($calendar['id'], CalDavBackend::CALENDAR_TYPE_CALENDAR);
  235. foreach ($calendarObjects as $calendarObject) {
  236. $this->calDavBackEnd->deleteCalendarObject($calendar['id'], $calendarObject['uri'], CalDavBackend::CALENDAR_TYPE_CALENDAR, true);
  237. }
  238. }
  239. /**
  240. * @param string $user
  241. * @throws \Sabre\DAV\Exception\BadRequest
  242. */
  243. public function syncUser(string $user):void {
  244. $principal = 'principals/users/' . $user;
  245. $this->ensureCalendarExists($principal);
  246. $books = $this->cardDavBackEnd->getAddressBooksForUser($principal);
  247. foreach ($books as $book) {
  248. $cards = $this->cardDavBackEnd->getCards($book['id']);
  249. foreach ($cards as $card) {
  250. $this->onCardChanged((int)$book['id'], $card['uri'], $card['carddata']);
  251. }
  252. }
  253. }
  254. /**
  255. * @param string $existingCalendarData
  256. * @param VCalendar $newCalendarData
  257. * @return bool
  258. */
  259. public function birthdayEvenChanged(string $existingCalendarData,
  260. VCalendar $newCalendarData):bool {
  261. try {
  262. $existingBirthday = Reader::read($existingCalendarData);
  263. } catch (Exception $ex) {
  264. return true;
  265. }
  266. return (
  267. $newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue() ||
  268. $newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
  269. );
  270. }
  271. /**
  272. * @param integer $addressBookId
  273. * @return mixed
  274. */
  275. protected function getAllAffectedPrincipals(int $addressBookId) {
  276. $targetPrincipals = [];
  277. $shares = $this->cardDavBackEnd->getShares($addressBookId);
  278. foreach ($shares as $share) {
  279. if ($share['{http://owncloud.org/ns}group-share']) {
  280. $users = $this->principalBackend->getGroupMemberSet($share['{http://owncloud.org/ns}principal']);
  281. foreach ($users as $user) {
  282. $targetPrincipals[] = $user['uri'];
  283. }
  284. } else {
  285. $targetPrincipals[] = $share['{http://owncloud.org/ns}principal'];
  286. }
  287. }
  288. return array_values(array_unique($targetPrincipals, SORT_STRING));
  289. }
  290. /**
  291. * @param string $cardUri
  292. * @param string $cardData
  293. * @param array $book
  294. * @param int $calendarId
  295. * @param array $type
  296. * @param string $reminderOffset
  297. * @throws InvalidDataException
  298. * @throws \Sabre\DAV\Exception\BadRequest
  299. */
  300. private function updateCalendar(string $cardUri,
  301. string $cardData,
  302. array $book,
  303. int $calendarId,
  304. array $type,
  305. ?string $reminderOffset):void {
  306. $objectUri = $book['uri'] . '-' . $cardUri . $type['postfix'] . '.ics';
  307. $calendarData = $this->buildDateFromContact($cardData, $type['field'], $type['postfix'], $reminderOffset);
  308. $existing = $this->calDavBackEnd->getCalendarObject($calendarId, $objectUri);
  309. if ($calendarData === null) {
  310. if ($existing !== null) {
  311. $this->calDavBackEnd->deleteCalendarObject($calendarId, $objectUri, CalDavBackend::CALENDAR_TYPE_CALENDAR, true);
  312. }
  313. } else {
  314. if ($existing === null) {
  315. // not found by URI, but maybe by UID
  316. // happens when a contact with birthday is moved to a different address book
  317. $calendarInfo = $this->calDavBackEnd->getCalendarById($calendarId);
  318. $extraData = $this->calDavBackEnd->getDenormalizedData($calendarData->serialize());
  319. if ($calendarInfo && array_key_exists('principaluri', $calendarInfo)) {
  320. $existing2path = $this->calDavBackEnd->getCalendarObjectByUID($calendarInfo['principaluri'], $extraData['uid']);
  321. if ($existing2path !== null && array_key_exists('uri', $calendarInfo)) {
  322. // delete the old birthday entry first so that we do not get duplicate UIDs
  323. $existing2objectUri = substr($existing2path, strlen($calendarInfo['uri']) + 1);
  324. $this->calDavBackEnd->deleteCalendarObject($calendarId, $existing2objectUri, CalDavBackend::CALENDAR_TYPE_CALENDAR, true);
  325. }
  326. }
  327. $this->calDavBackEnd->createCalendarObject($calendarId, $objectUri, $calendarData->serialize());
  328. } else {
  329. if ($this->birthdayEvenChanged($existing['calendardata'], $calendarData)) {
  330. $this->calDavBackEnd->updateCalendarObject($calendarId, $objectUri, $calendarData->serialize());
  331. }
  332. }
  333. }
  334. }
  335. /**
  336. * checks if the admin opted-out of birthday calendars
  337. *
  338. * @return bool
  339. */
  340. private function isGloballyEnabled():bool {
  341. return $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes') === 'yes';
  342. }
  343. /**
  344. * Extracts the userId part of a principal
  345. *
  346. * @param string $userPrincipal
  347. * @return string|null
  348. */
  349. private function principalToUserId(string $userPrincipal):?string {
  350. if (str_starts_with($userPrincipal, 'principals/users/')) {
  351. return substr($userPrincipal, 17);
  352. }
  353. return null;
  354. }
  355. /**
  356. * Checks if the user opted-out of birthday calendars
  357. *
  358. * @param string $userPrincipal The user principal to check for
  359. * @return bool
  360. */
  361. private function isUserEnabled(string $userPrincipal):bool {
  362. $userId = $this->principalToUserId($userPrincipal);
  363. if ($userId !== null) {
  364. $isEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
  365. return $isEnabled === 'yes';
  366. }
  367. // not sure how we got here, just be on the safe side and return true
  368. return true;
  369. }
  370. /**
  371. * Get the reminder offset value for a user. This is a duration string (e.g.
  372. * PT9H) or null if no reminder is wanted.
  373. *
  374. * @param string $userPrincipal
  375. * @return string|null
  376. */
  377. private function getReminderOffsetForUser(string $userPrincipal):?string {
  378. $userId = $this->principalToUserId($userPrincipal);
  379. if ($userId !== null) {
  380. return $this->config->getUserValue($userId, 'dav', 'birthdayCalendarReminderOffset', 'PT9H') ?: null;
  381. }
  382. // not sure how we got here, just be on the safe side and return the default value
  383. return 'PT9H';
  384. }
  385. /**
  386. * Formats title of Birthday event
  387. *
  388. * @param string $field Field name like BDAY, ANNIVERSARY, ...
  389. * @param string $name Name of contact
  390. * @param int|null $year Year of birth, anniversary, ...
  391. * @param bool $supports4Byte Whether or not the database supports 4 byte chars
  392. * @return string The formatted title
  393. */
  394. private function formatTitle(string $field,
  395. string $name,
  396. ?int $year = null,
  397. bool $supports4Byte = true):string {
  398. if ($supports4Byte) {
  399. switch ($field) {
  400. case 'BDAY':
  401. return implode('', [
  402. '🎂 ',
  403. $name,
  404. $year ? (' (' . $year . ')') : '',
  405. ]);
  406. case 'DEATHDATE':
  407. return implode('', [
  408. $this->l10n->t('Death of %s', [$name]),
  409. $year ? (' (' . $year . ')') : '',
  410. ]);
  411. case 'ANNIVERSARY':
  412. return implode('', [
  413. '💍 ',
  414. $name,
  415. $year ? (' (' . $year . ')') : '',
  416. ]);
  417. default:
  418. return '';
  419. }
  420. } else {
  421. switch ($field) {
  422. case 'BDAY':
  423. return implode('', [
  424. $name,
  425. ' ',
  426. $year ? ('(*' . $year . ')') : '*',
  427. ]);
  428. case 'DEATHDATE':
  429. return implode('', [
  430. $this->l10n->t('Death of %s', [$name]),
  431. $year ? (' (' . $year . ')') : '',
  432. ]);
  433. case 'ANNIVERSARY':
  434. return implode('', [
  435. $name,
  436. ' ',
  437. $year ? ('(⚭' . $year . ')') : '⚭',
  438. ]);
  439. default:
  440. return '';
  441. }
  442. }
  443. }
  444. }