1
0

BirthdayService.php 13 KB

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