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 Joas Schilling <coding@schilljs.com>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  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. namespace OCA\DAV\CalDAV;
  30. use Exception;
  31. use OCA\DAV\CardDAV\CardDavBackend;
  32. use OCA\DAV\DAV\GroupPrincipalBackend;
  33. use OCP\IConfig;
  34. use OCP\IDBConnection;
  35. use OCP\IL10N;
  36. use Sabre\VObject\Component\VCalendar;
  37. use Sabre\VObject\Component\VCard;
  38. use Sabre\VObject\DateTimeParser;
  39. use Sabre\VObject\Document;
  40. use Sabre\VObject\InvalidDataException;
  41. use Sabre\VObject\Property\VCard\DateAndOrTime;
  42. use Sabre\VObject\Reader;
  43. /**
  44. * Class BirthdayService
  45. *
  46. * @package OCA\DAV\CalDAV
  47. */
  48. class BirthdayService {
  49. const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';
  50. /** @var GroupPrincipalBackend */
  51. private $principalBackend;
  52. /** @var CalDavBackend */
  53. private $calDavBackEnd;
  54. /** @var CardDavBackend */
  55. private $cardDavBackEnd;
  56. /** @var IConfig */
  57. private $config;
  58. /** @var IDBConnection */
  59. private $dbConnection;
  60. /** @var IL10N */
  61. private $l10n;
  62. /**
  63. * BirthdayService constructor.
  64. *
  65. * @param CalDavBackend $calDavBackEnd
  66. * @param CardDavBackend $cardDavBackEnd
  67. * @param GroupPrincipalBackend $principalBackend
  68. * @param IConfig $config
  69. * @param IDBConnection $dbConnection
  70. * @param IL10N $l10n
  71. */
  72. public function __construct(CalDavBackend $calDavBackEnd,
  73. CardDavBackend $cardDavBackEnd,
  74. GroupPrincipalBackend $principalBackend,
  75. IConfig $config,
  76. IDBConnection $dbConnection,
  77. IL10N $l10n) {
  78. $this->calDavBackEnd = $calDavBackEnd;
  79. $this->cardDavBackEnd = $cardDavBackEnd;
  80. $this->principalBackend = $principalBackend;
  81. $this->config = $config;
  82. $this->dbConnection = $dbConnection;
  83. $this->l10n = $l10n;
  84. }
  85. /**
  86. * @param int $addressBookId
  87. * @param string $cardUri
  88. * @param string $cardData
  89. */
  90. public function onCardChanged(int $addressBookId,
  91. string $cardUri,
  92. string $cardData) {
  93. if (!$this->isGloballyEnabled()) {
  94. return;
  95. }
  96. $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
  97. $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
  98. $targetPrincipals[] = $book['principaluri'];
  99. $datesToSync = [
  100. ['postfix' => '', 'field' => 'BDAY'],
  101. ['postfix' => '-death', 'field' => 'DEATHDATE'],
  102. ['postfix' => '-anniversary', 'field' => 'ANNIVERSARY'],
  103. ];
  104. foreach ($targetPrincipals as $principalUri) {
  105. if (!$this->isUserEnabled($principalUri)) {
  106. continue;
  107. }
  108. $calendar = $this->ensureCalendarExists($principalUri);
  109. foreach ($datesToSync as $type) {
  110. $this->updateCalendar($cardUri, $cardData, $book, (int) $calendar['id'], $type);
  111. }
  112. }
  113. }
  114. /**
  115. * @param int $addressBookId
  116. * @param string $cardUri
  117. */
  118. public function onCardDeleted(int $addressBookId,
  119. string $cardUri) {
  120. if (!$this->isGloballyEnabled()) {
  121. return;
  122. }
  123. $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
  124. $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
  125. $targetPrincipals[] = $book['principaluri'];
  126. foreach ($targetPrincipals as $principalUri) {
  127. if (!$this->isUserEnabled($principalUri)) {
  128. continue;
  129. }
  130. $calendar = $this->ensureCalendarExists($principalUri);
  131. foreach (['', '-death', '-anniversary'] as $tag) {
  132. $objectUri = $book['uri'] . '-' . $cardUri . $tag .'.ics';
  133. $this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri);
  134. }
  135. }
  136. }
  137. /**
  138. * @param string $principal
  139. * @return array|null
  140. * @throws \Sabre\DAV\Exception\BadRequest
  141. */
  142. public function ensureCalendarExists(string $principal):?array {
  143. $calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
  144. if (!is_null($calendar)) {
  145. return $calendar;
  146. }
  147. $this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
  148. '{DAV:}displayname' => 'Contact birthdays',
  149. '{http://apple.com/ns/ical/}calendar-color' => '#FFFFCA',
  150. 'components' => 'VEVENT',
  151. ]);
  152. return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
  153. }
  154. /**
  155. * @param $cardData
  156. * @param $dateField
  157. * @param $postfix
  158. * @return VCalendar|null
  159. * @throws InvalidDataException
  160. */
  161. public function buildDateFromContact(string $cardData,
  162. string $dateField,
  163. string $postfix):?VCalendar {
  164. if (empty($cardData)) {
  165. return null;
  166. }
  167. try {
  168. $doc = Reader::read($cardData);
  169. // We're always converting to vCard 4.0 so we can rely on the
  170. // VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
  171. if (!$doc instanceof VCard) {
  172. return null;
  173. }
  174. $doc = $doc->convert(Document::VCARD40);
  175. } catch (Exception $e) {
  176. return null;
  177. }
  178. if (!isset($doc->{$dateField})) {
  179. return null;
  180. }
  181. if (!isset($doc->FN)) {
  182. return null;
  183. }
  184. $birthday = $doc->{$dateField};
  185. if (!(string)$birthday) {
  186. return null;
  187. }
  188. // Skip if the BDAY property is not of the right type.
  189. if (!$birthday instanceof DateAndOrTime) {
  190. return null;
  191. }
  192. // Skip if we can't parse the BDAY value.
  193. try {
  194. $dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
  195. } catch (InvalidDataException $e) {
  196. return null;
  197. }
  198. $unknownYear = false;
  199. $originalYear = null;
  200. if (!$dateParts['year']) {
  201. $birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
  202. $unknownYear = true;
  203. } else {
  204. $parameters = $birthday->parameters();
  205. if (isset($parameters['X-APPLE-OMIT-YEAR'])) {
  206. $omitYear = $parameters['X-APPLE-OMIT-YEAR'];
  207. if ($dateParts['year'] === $omitYear) {
  208. $birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
  209. $unknownYear = true;
  210. }
  211. } else {
  212. $originalYear = (int)$dateParts['year'];
  213. if ($originalYear < 1970) {
  214. $birthday = '1970-' . $dateParts['month'] . '-' . $dateParts['date'];
  215. }
  216. }
  217. }
  218. try {
  219. if ($birthday instanceof DateAndOrTime) {
  220. $date = $birthday->getDateTime();
  221. } else {
  222. $date = new \DateTimeImmutable($birthday);
  223. }
  224. } catch (Exception $e) {
  225. return null;
  226. }
  227. $summary = $this->formatTitle($dateField, $doc->FN->getValue(), $originalYear, $this->dbConnection->supports4ByteText());
  228. $vCal = new VCalendar();
  229. $vCal->VERSION = '2.0';
  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. }