BirthdayService.php 13 KB

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