1
0

ReminderService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2019, Thomas Citharel
  5. * @copyright Copyright (c) 2019, Georg Ehrke
  6. *
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Citharel <nextcloud@tcit.fr>
  12. * @author Richard Steinmetz <richard@steinmetz.cloud>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OCA\DAV\CalDAV\Reminder;
  31. use DateTimeImmutable;
  32. use DateTimeZone;
  33. use OCA\DAV\CalDAV\CalDavBackend;
  34. use OCA\DAV\Connector\Sabre\Principal;
  35. use OCP\AppFramework\Utility\ITimeFactory;
  36. use OCP\IConfig;
  37. use OCP\IGroup;
  38. use OCP\IGroupManager;
  39. use OCP\IUser;
  40. use OCP\IUserManager;
  41. use Psr\Log\LoggerInterface;
  42. use Sabre\VObject;
  43. use Sabre\VObject\Component\VAlarm;
  44. use Sabre\VObject\Component\VEvent;
  45. use Sabre\VObject\InvalidDataException;
  46. use Sabre\VObject\ParseException;
  47. use Sabre\VObject\Recur\EventIterator;
  48. use Sabre\VObject\Recur\MaxInstancesExceededException;
  49. use Sabre\VObject\Recur\NoInstancesException;
  50. use function count;
  51. use function strcasecmp;
  52. class ReminderService {
  53. /** @var Backend */
  54. private $backend;
  55. /** @var NotificationProviderManager */
  56. private $notificationProviderManager;
  57. /** @var IUserManager */
  58. private $userManager;
  59. /** @var IGroupManager */
  60. private $groupManager;
  61. /** @var CalDavBackend */
  62. private $caldavBackend;
  63. /** @var ITimeFactory */
  64. private $timeFactory;
  65. /** @var IConfig */
  66. private $config;
  67. /** @var LoggerInterface */
  68. private $logger;
  69. /** @var Principal */
  70. private $principalConnector;
  71. public const REMINDER_TYPE_EMAIL = 'EMAIL';
  72. public const REMINDER_TYPE_DISPLAY = 'DISPLAY';
  73. public const REMINDER_TYPE_AUDIO = 'AUDIO';
  74. /**
  75. * @var String[]
  76. *
  77. * Official RFC5545 reminder types
  78. */
  79. public const REMINDER_TYPES = [
  80. self::REMINDER_TYPE_EMAIL,
  81. self::REMINDER_TYPE_DISPLAY,
  82. self::REMINDER_TYPE_AUDIO
  83. ];
  84. public function __construct(Backend $backend,
  85. NotificationProviderManager $notificationProviderManager,
  86. IUserManager $userManager,
  87. IGroupManager $groupManager,
  88. CalDavBackend $caldavBackend,
  89. ITimeFactory $timeFactory,
  90. IConfig $config,
  91. LoggerInterface $logger,
  92. Principal $principalConnector) {
  93. $this->backend = $backend;
  94. $this->notificationProviderManager = $notificationProviderManager;
  95. $this->userManager = $userManager;
  96. $this->groupManager = $groupManager;
  97. $this->caldavBackend = $caldavBackend;
  98. $this->timeFactory = $timeFactory;
  99. $this->config = $config;
  100. $this->logger = $logger;
  101. $this->principalConnector = $principalConnector;
  102. }
  103. /**
  104. * Process reminders to activate
  105. *
  106. * @throws NotificationProvider\ProviderNotAvailableException
  107. * @throws NotificationTypeDoesNotExistException
  108. */
  109. public function processReminders() :void {
  110. $reminders = $this->backend->getRemindersToProcess();
  111. $this->logger->debug('{numReminders} reminders to process', [
  112. 'numReminders' => count($reminders),
  113. ]);
  114. foreach ($reminders as $reminder) {
  115. $calendarData = is_resource($reminder['calendardata'])
  116. ? stream_get_contents($reminder['calendardata'])
  117. : $reminder['calendardata'];
  118. if (!$calendarData) {
  119. continue;
  120. }
  121. $vcalendar = $this->parseCalendarData($calendarData);
  122. if (!$vcalendar) {
  123. $this->logger->debug('Reminder {id} does not belong to a valid calendar', [
  124. 'id' => $reminder['id'],
  125. ]);
  126. $this->backend->removeReminder($reminder['id']);
  127. continue;
  128. }
  129. $vevent = $this->getVEventByRecurrenceId($vcalendar, $reminder['recurrence_id'], $reminder['is_recurrence_exception']);
  130. if (!$vevent) {
  131. $this->logger->debug('Reminder {id} does not belong to a valid event', [
  132. 'id' => $reminder['id'],
  133. ]);
  134. $this->backend->removeReminder($reminder['id']);
  135. continue;
  136. }
  137. if ($this->wasEventCancelled($vevent)) {
  138. $this->logger->debug('Reminder {id} belongs to a cancelled event', [
  139. 'id' => $reminder['id'],
  140. ]);
  141. $this->deleteOrProcessNext($reminder, $vevent);
  142. continue;
  143. }
  144. if (!$this->notificationProviderManager->hasProvider($reminder['type'])) {
  145. $this->logger->debug('Reminder {id} does not belong to a valid notification provider', [
  146. 'id' => $reminder['id'],
  147. ]);
  148. $this->deleteOrProcessNext($reminder, $vevent);
  149. continue;
  150. }
  151. if ($this->config->getAppValue('dav', 'sendEventRemindersToSharedGroupMembers', 'yes') === 'no') {
  152. $users = $this->getAllUsersWithWriteAccessToCalendar($reminder['calendar_id']);
  153. } else {
  154. $users = [];
  155. }
  156. $user = $this->getUserFromPrincipalURI($reminder['principaluri']);
  157. if ($user) {
  158. $users[] = $user;
  159. }
  160. $userPrincipalEmailAddresses = [];
  161. $userPrincipal = $this->principalConnector->getPrincipalByPath($reminder['principaluri']);
  162. if ($userPrincipal) {
  163. $userPrincipalEmailAddresses = $this->principalConnector->getEmailAddressesOfPrincipal($userPrincipal);
  164. }
  165. $this->logger->debug('Reminder {id} will be sent to {numUsers} users', [
  166. 'id' => $reminder['id'],
  167. 'numUsers' => count($users),
  168. ]);
  169. $notificationProvider = $this->notificationProviderManager->getProvider($reminder['type']);
  170. $notificationProvider->send($vevent, $reminder['displayname'], $userPrincipalEmailAddresses, $users);
  171. $this->deleteOrProcessNext($reminder, $vevent);
  172. }
  173. }
  174. /**
  175. * @param array $objectData
  176. * @throws VObject\InvalidDataException
  177. */
  178. public function onCalendarObjectCreate(array $objectData):void {
  179. // We only support VEvents for now
  180. if (strcasecmp($objectData['component'], 'vevent') !== 0) {
  181. return;
  182. }
  183. $calendarData = is_resource($objectData['calendardata'])
  184. ? stream_get_contents($objectData['calendardata'])
  185. : $objectData['calendardata'];
  186. if (!$calendarData) {
  187. return;
  188. }
  189. $vcalendar = $this->parseCalendarData($calendarData);
  190. if (!$vcalendar) {
  191. return;
  192. }
  193. $calendarTimeZone = $this->getCalendarTimeZone((int) $objectData['calendarid']);
  194. $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
  195. if (count($vevents) === 0) {
  196. return;
  197. }
  198. $uid = (string) $vevents[0]->UID;
  199. $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
  200. $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
  201. $now = $this->timeFactory->getDateTime();
  202. $isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
  203. foreach ($recurrenceExceptions as $recurrenceException) {
  204. $eventHash = $this->getEventHash($recurrenceException);
  205. if (!isset($recurrenceException->VALARM)) {
  206. continue;
  207. }
  208. foreach ($recurrenceException->VALARM as $valarm) {
  209. /** @var VAlarm $valarm */
  210. $alarmHash = $this->getAlarmHash($valarm);
  211. $triggerTime = $valarm->getEffectiveTriggerTime();
  212. $diff = $now->diff($triggerTime);
  213. if ($diff->invert === 1) {
  214. continue;
  215. }
  216. $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $calendarTimeZone,
  217. $eventHash, $alarmHash, true, true);
  218. $this->writeRemindersToDatabase($alarms);
  219. }
  220. }
  221. if ($masterItem) {
  222. $processedAlarms = [];
  223. $masterAlarms = [];
  224. $masterHash = $this->getEventHash($masterItem);
  225. if (!isset($masterItem->VALARM)) {
  226. return;
  227. }
  228. foreach ($masterItem->VALARM as $valarm) {
  229. $masterAlarms[] = $this->getAlarmHash($valarm);
  230. }
  231. try {
  232. $iterator = new EventIterator($vevents, $uid);
  233. } catch (NoInstancesException $e) {
  234. // This event is recurring, but it doesn't have a single
  235. // instance. We are skipping this event from the output
  236. // entirely.
  237. return;
  238. } catch (MaxInstancesExceededException $e) {
  239. // The event has more than 3500 recurring-instances
  240. // so we can ignore it
  241. return;
  242. }
  243. while ($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
  244. $event = $iterator->getEventObject();
  245. // Recurrence-exceptions are handled separately, so just ignore them here
  246. if (\in_array($event, $recurrenceExceptions, true)) {
  247. $iterator->next();
  248. continue;
  249. }
  250. foreach ($event->VALARM as $valarm) {
  251. /** @var VAlarm $valarm */
  252. $alarmHash = $this->getAlarmHash($valarm);
  253. if (\in_array($alarmHash, $processedAlarms, true)) {
  254. continue;
  255. }
  256. if (!\in_array((string) $valarm->ACTION, self::REMINDER_TYPES, true)) {
  257. // Action allows x-name, we don't insert reminders
  258. // into the database if they are not standard
  259. $processedAlarms[] = $alarmHash;
  260. continue;
  261. }
  262. try {
  263. $triggerTime = $valarm->getEffectiveTriggerTime();
  264. /**
  265. * @psalm-suppress DocblockTypeContradiction
  266. * https://github.com/vimeo/psalm/issues/9244
  267. */
  268. if ($triggerTime->getTimezone() === false || $triggerTime->getTimezone()->getName() === 'UTC') {
  269. $triggerTime = new DateTimeImmutable(
  270. $triggerTime->format('Y-m-d H:i:s'),
  271. $calendarTimeZone
  272. );
  273. }
  274. } catch (InvalidDataException $e) {
  275. continue;
  276. }
  277. // If effective trigger time is in the past
  278. // just skip and generate for next event
  279. $diff = $now->diff($triggerTime);
  280. if ($diff->invert === 1) {
  281. // If an absolute alarm is in the past,
  282. // just add it to processedAlarms, so
  283. // we don't extend till eternity
  284. if (!$this->isAlarmRelative($valarm)) {
  285. $processedAlarms[] = $alarmHash;
  286. }
  287. continue;
  288. }
  289. $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $calendarTimeZone, $masterHash, $alarmHash, $isRecurring, false);
  290. $this->writeRemindersToDatabase($alarms);
  291. $processedAlarms[] = $alarmHash;
  292. }
  293. $iterator->next();
  294. }
  295. }
  296. }
  297. /**
  298. * @param array $objectData
  299. * @throws VObject\InvalidDataException
  300. */
  301. public function onCalendarObjectEdit(array $objectData):void {
  302. // TODO - this can be vastly improved
  303. // - get cached reminders
  304. // - ...
  305. $this->onCalendarObjectDelete($objectData);
  306. $this->onCalendarObjectCreate($objectData);
  307. }
  308. /**
  309. * @param array $objectData
  310. * @throws VObject\InvalidDataException
  311. */
  312. public function onCalendarObjectDelete(array $objectData):void {
  313. // We only support VEvents for now
  314. if (strcasecmp($objectData['component'], 'vevent') !== 0) {
  315. return;
  316. }
  317. $this->backend->cleanRemindersForEvent((int) $objectData['id']);
  318. }
  319. /**
  320. * @param VAlarm $valarm
  321. * @param array $objectData
  322. * @param DateTimeZone $calendarTimeZone
  323. * @param string|null $eventHash
  324. * @param string|null $alarmHash
  325. * @param bool $isRecurring
  326. * @param bool $isRecurrenceException
  327. * @return array
  328. */
  329. private function getRemindersForVAlarm(VAlarm $valarm,
  330. array $objectData,
  331. DateTimeZone $calendarTimeZone,
  332. string $eventHash = null,
  333. string $alarmHash = null,
  334. bool $isRecurring = false,
  335. bool $isRecurrenceException = false):array {
  336. if ($eventHash === null) {
  337. $eventHash = $this->getEventHash($valarm->parent);
  338. }
  339. if ($alarmHash === null) {
  340. $alarmHash = $this->getAlarmHash($valarm);
  341. }
  342. $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent);
  343. $isRelative = $this->isAlarmRelative($valarm);
  344. /** @var DateTimeImmutable $notificationDate */
  345. $notificationDate = $valarm->getEffectiveTriggerTime();
  346. /**
  347. * @psalm-suppress DocblockTypeContradiction
  348. * https://github.com/vimeo/psalm/issues/9244
  349. */
  350. if ($notificationDate->getTimezone() === false || $notificationDate->getTimezone()->getName() === 'UTC') {
  351. $notificationDate = new DateTimeImmutable(
  352. $notificationDate->format('Y-m-d H:i:s'),
  353. $calendarTimeZone
  354. );
  355. }
  356. $clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone());
  357. $clonedNotificationDate->setTimestamp($notificationDate->getTimestamp());
  358. $alarms = [];
  359. $alarms[] = [
  360. 'calendar_id' => $objectData['calendarid'],
  361. 'object_id' => $objectData['id'],
  362. 'uid' => (string) $valarm->parent->UID,
  363. 'is_recurring' => $isRecurring,
  364. 'recurrence_id' => $recurrenceId,
  365. 'is_recurrence_exception' => $isRecurrenceException,
  366. 'event_hash' => $eventHash,
  367. 'alarm_hash' => $alarmHash,
  368. 'type' => (string) $valarm->ACTION,
  369. 'is_relative' => $isRelative,
  370. 'notification_date' => $notificationDate->getTimestamp(),
  371. 'is_repeat_based' => false,
  372. ];
  373. $repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
  374. for ($i = 0; $i < $repeat; $i++) {
  375. if ($valarm->DURATION === null) {
  376. continue;
  377. }
  378. $clonedNotificationDate->add($valarm->DURATION->getDateInterval());
  379. $alarms[] = [
  380. 'calendar_id' => $objectData['calendarid'],
  381. 'object_id' => $objectData['id'],
  382. 'uid' => (string) $valarm->parent->UID,
  383. 'is_recurring' => $isRecurring,
  384. 'recurrence_id' => $recurrenceId,
  385. 'is_recurrence_exception' => $isRecurrenceException,
  386. 'event_hash' => $eventHash,
  387. 'alarm_hash' => $alarmHash,
  388. 'type' => (string) $valarm->ACTION,
  389. 'is_relative' => $isRelative,
  390. 'notification_date' => $clonedNotificationDate->getTimestamp(),
  391. 'is_repeat_based' => true,
  392. ];
  393. }
  394. return $alarms;
  395. }
  396. /**
  397. * @param array $reminders
  398. */
  399. private function writeRemindersToDatabase(array $reminders): void {
  400. foreach ($reminders as $reminder) {
  401. $this->backend->insertReminder(
  402. (int) $reminder['calendar_id'],
  403. (int) $reminder['object_id'],
  404. $reminder['uid'],
  405. $reminder['is_recurring'],
  406. (int) $reminder['recurrence_id'],
  407. $reminder['is_recurrence_exception'],
  408. $reminder['event_hash'],
  409. $reminder['alarm_hash'],
  410. $reminder['type'],
  411. $reminder['is_relative'],
  412. (int) $reminder['notification_date'],
  413. $reminder['is_repeat_based']
  414. );
  415. }
  416. }
  417. /**
  418. * @param array $reminder
  419. * @param VEvent $vevent
  420. */
  421. private function deleteOrProcessNext(array $reminder,
  422. VObject\Component\VEvent $vevent):void {
  423. if ($reminder['is_repeat_based'] ||
  424. !$reminder['is_recurring'] ||
  425. !$reminder['is_relative'] ||
  426. $reminder['is_recurrence_exception']) {
  427. $this->backend->removeReminder($reminder['id']);
  428. return;
  429. }
  430. $vevents = $this->getAllVEventsFromVCalendar($vevent->parent);
  431. $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
  432. $now = $this->timeFactory->getDateTime();
  433. $calendarTimeZone = $this->getCalendarTimeZone((int) $reminder['calendar_id']);
  434. try {
  435. $iterator = new EventIterator($vevents, $reminder['uid']);
  436. } catch (NoInstancesException $e) {
  437. // This event is recurring, but it doesn't have a single
  438. // instance. We are skipping this event from the output
  439. // entirely.
  440. return;
  441. }
  442. try {
  443. while ($iterator->valid()) {
  444. $event = $iterator->getEventObject();
  445. // Recurrence-exceptions are handled separately, so just ignore them here
  446. if (\in_array($event, $recurrenceExceptions, true)) {
  447. $iterator->next();
  448. continue;
  449. }
  450. $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($event);
  451. if ($reminder['recurrence_id'] >= $recurrenceId) {
  452. $iterator->next();
  453. continue;
  454. }
  455. foreach ($event->VALARM as $valarm) {
  456. /** @var VAlarm $valarm */
  457. $alarmHash = $this->getAlarmHash($valarm);
  458. if ($alarmHash !== $reminder['alarm_hash']) {
  459. continue;
  460. }
  461. $triggerTime = $valarm->getEffectiveTriggerTime();
  462. // If effective trigger time is in the past
  463. // just skip and generate for next event
  464. $diff = $now->diff($triggerTime);
  465. if ($diff->invert === 1) {
  466. continue;
  467. }
  468. $this->backend->removeReminder($reminder['id']);
  469. $alarms = $this->getRemindersForVAlarm($valarm, [
  470. 'calendarid' => $reminder['calendar_id'],
  471. 'id' => $reminder['object_id'],
  472. ], $calendarTimeZone, $reminder['event_hash'], $alarmHash, true, false);
  473. $this->writeRemindersToDatabase($alarms);
  474. // Abort generating reminders after creating one successfully
  475. return;
  476. }
  477. $iterator->next();
  478. }
  479. } catch (MaxInstancesExceededException $e) {
  480. // Using debug logger as this isn't really an error
  481. $this->logger->debug('Recurrence with too many instances detected, skipping VEVENT', ['exception' => $e]);
  482. }
  483. $this->backend->removeReminder($reminder['id']);
  484. }
  485. /**
  486. * @param int $calendarId
  487. * @return IUser[]
  488. */
  489. private function getAllUsersWithWriteAccessToCalendar(int $calendarId):array {
  490. $shares = $this->caldavBackend->getShares($calendarId);
  491. $users = [];
  492. $userIds = [];
  493. $groups = [];
  494. foreach ($shares as $share) {
  495. // Only consider writable shares
  496. if ($share['readOnly']) {
  497. continue;
  498. }
  499. $principal = explode('/', $share['{http://owncloud.org/ns}principal']);
  500. if ($principal[1] === 'users') {
  501. $user = $this->userManager->get($principal[2]);
  502. if ($user) {
  503. $users[] = $user;
  504. $userIds[] = $principal[2];
  505. }
  506. } elseif ($principal[1] === 'groups') {
  507. $groups[] = $principal[2];
  508. }
  509. }
  510. foreach ($groups as $gid) {
  511. $group = $this->groupManager->get($gid);
  512. if ($group instanceof IGroup) {
  513. foreach ($group->getUsers() as $user) {
  514. if (!\in_array($user->getUID(), $userIds, true)) {
  515. $users[] = $user;
  516. $userIds[] = $user->getUID();
  517. }
  518. }
  519. }
  520. }
  521. return $users;
  522. }
  523. /**
  524. * Gets a hash of the event.
  525. * If the hash changes, we have to update all relative alarms.
  526. *
  527. * @param VEvent $vevent
  528. * @return string
  529. */
  530. private function getEventHash(VEvent $vevent):string {
  531. $properties = [
  532. (string) $vevent->DTSTART->serialize(),
  533. ];
  534. if ($vevent->DTEND) {
  535. $properties[] = (string) $vevent->DTEND->serialize();
  536. }
  537. if ($vevent->DURATION) {
  538. $properties[] = (string) $vevent->DURATION->serialize();
  539. }
  540. if ($vevent->{'RECURRENCE-ID'}) {
  541. $properties[] = (string) $vevent->{'RECURRENCE-ID'}->serialize();
  542. }
  543. if ($vevent->RRULE) {
  544. $properties[] = (string) $vevent->RRULE->serialize();
  545. }
  546. if ($vevent->EXDATE) {
  547. $properties[] = (string) $vevent->EXDATE->serialize();
  548. }
  549. if ($vevent->RDATE) {
  550. $properties[] = (string) $vevent->RDATE->serialize();
  551. }
  552. return md5(implode('::', $properties));
  553. }
  554. /**
  555. * Gets a hash of the alarm.
  556. * If the hash changes, we have to update oc_dav_reminders.
  557. *
  558. * @param VAlarm $valarm
  559. * @return string
  560. */
  561. private function getAlarmHash(VAlarm $valarm):string {
  562. $properties = [
  563. (string) $valarm->ACTION->serialize(),
  564. (string) $valarm->TRIGGER->serialize(),
  565. ];
  566. if ($valarm->DURATION) {
  567. $properties[] = (string) $valarm->DURATION->serialize();
  568. }
  569. if ($valarm->REPEAT) {
  570. $properties[] = (string) $valarm->REPEAT->serialize();
  571. }
  572. return md5(implode('::', $properties));
  573. }
  574. /**
  575. * @param VObject\Component\VCalendar $vcalendar
  576. * @param int $recurrenceId
  577. * @param bool $isRecurrenceException
  578. * @return VEvent|null
  579. */
  580. private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
  581. int $recurrenceId,
  582. bool $isRecurrenceException):?VEvent {
  583. $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
  584. if (count($vevents) === 0) {
  585. return null;
  586. }
  587. $uid = (string) $vevents[0]->UID;
  588. $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
  589. $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
  590. // Handle recurrence-exceptions first, because recurrence-expansion is expensive
  591. if ($isRecurrenceException) {
  592. foreach ($recurrenceExceptions as $recurrenceException) {
  593. if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
  594. return $recurrenceException;
  595. }
  596. }
  597. return null;
  598. }
  599. if ($masterItem) {
  600. try {
  601. $iterator = new EventIterator($vevents, $uid);
  602. } catch (NoInstancesException $e) {
  603. // This event is recurring, but it doesn't have a single
  604. // instance. We are skipping this event from the output
  605. // entirely.
  606. return null;
  607. }
  608. while ($iterator->valid()) {
  609. $event = $iterator->getEventObject();
  610. // Recurrence-exceptions are handled separately, so just ignore them here
  611. if (\in_array($event, $recurrenceExceptions, true)) {
  612. $iterator->next();
  613. continue;
  614. }
  615. if ($this->getEffectiveRecurrenceIdOfVEvent($event) === $recurrenceId) {
  616. return $event;
  617. }
  618. $iterator->next();
  619. }
  620. }
  621. return null;
  622. }
  623. /**
  624. * @param VEvent $vevent
  625. * @return string
  626. */
  627. private function getStatusOfEvent(VEvent $vevent):string {
  628. if ($vevent->STATUS) {
  629. return (string) $vevent->STATUS;
  630. }
  631. // Doesn't say so in the standard,
  632. // but we consider events without a status
  633. // to be confirmed
  634. return 'CONFIRMED';
  635. }
  636. /**
  637. * @param VObject\Component\VEvent $vevent
  638. * @return bool
  639. */
  640. private function wasEventCancelled(VObject\Component\VEvent $vevent):bool {
  641. return $this->getStatusOfEvent($vevent) === 'CANCELLED';
  642. }
  643. /**
  644. * @param string $calendarData
  645. * @return VObject\Component\VCalendar|null
  646. */
  647. private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
  648. try {
  649. return VObject\Reader::read($calendarData,
  650. VObject\Reader::OPTION_FORGIVING);
  651. } catch (ParseException $ex) {
  652. return null;
  653. }
  654. }
  655. /**
  656. * @param string $principalUri
  657. * @return IUser|null
  658. */
  659. private function getUserFromPrincipalURI(string $principalUri):?IUser {
  660. if (!$principalUri) {
  661. return null;
  662. }
  663. if (stripos($principalUri, 'principals/users/') !== 0) {
  664. return null;
  665. }
  666. $userId = substr($principalUri, 17);
  667. return $this->userManager->get($userId);
  668. }
  669. /**
  670. * @param VObject\Component\VCalendar $vcalendar
  671. * @return VObject\Component\VEvent[]
  672. */
  673. private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
  674. $vevents = [];
  675. foreach ($vcalendar->children() as $child) {
  676. if (!($child instanceof VObject\Component)) {
  677. continue;
  678. }
  679. if ($child->name !== 'VEVENT') {
  680. continue;
  681. }
  682. // Ignore invalid events with no DTSTART
  683. if ($child->DTSTART === null) {
  684. continue;
  685. }
  686. $vevents[] = $child;
  687. }
  688. return $vevents;
  689. }
  690. /**
  691. * @param array $vevents
  692. * @return VObject\Component\VEvent[]
  693. */
  694. private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
  695. return array_values(array_filter($vevents, function (VEvent $vevent) {
  696. return $vevent->{'RECURRENCE-ID'} !== null;
  697. }));
  698. }
  699. /**
  700. * @param array $vevents
  701. * @return VEvent|null
  702. */
  703. private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
  704. $elements = array_values(array_filter($vevents, function (VEvent $vevent) {
  705. return $vevent->{'RECURRENCE-ID'} === null;
  706. }));
  707. if (count($elements) === 0) {
  708. return null;
  709. }
  710. if (count($elements) > 1) {
  711. throw new \TypeError('Multiple master objects');
  712. }
  713. return $elements[0];
  714. }
  715. /**
  716. * @param VAlarm $valarm
  717. * @return bool
  718. */
  719. private function isAlarmRelative(VAlarm $valarm):bool {
  720. $trigger = $valarm->TRIGGER;
  721. return $trigger instanceof VObject\Property\ICalendar\Duration;
  722. }
  723. /**
  724. * @param VEvent $vevent
  725. * @return int
  726. */
  727. private function getEffectiveRecurrenceIdOfVEvent(VEvent $vevent):int {
  728. if (isset($vevent->{'RECURRENCE-ID'})) {
  729. return $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp();
  730. }
  731. return $vevent->DTSTART->getDateTime()->getTimestamp();
  732. }
  733. /**
  734. * @param VEvent $vevent
  735. * @return bool
  736. */
  737. private function isRecurring(VEvent $vevent):bool {
  738. return isset($vevent->RRULE) || isset($vevent->RDATE);
  739. }
  740. /**
  741. * @param int $calendarid
  742. *
  743. * @return DateTimeZone
  744. */
  745. private function getCalendarTimeZone(int $calendarid): DateTimeZone {
  746. $calendarInfo = $this->caldavBackend->getCalendarById($calendarid);
  747. $tzProp = '{urn:ietf:params:xml:ns:caldav}calendar-timezone';
  748. if (!isset($calendarInfo[$tzProp])) {
  749. // Defaulting to UTC
  750. return new DateTimeZone('UTC');
  751. }
  752. // This property contains a VCALENDAR with a single VTIMEZONE
  753. /** @var string $timezoneProp */
  754. $timezoneProp = $calendarInfo[$tzProp];
  755. /** @var VObject\Component\VCalendar $vtimezoneObj */
  756. $vtimezoneObj = VObject\Reader::read($timezoneProp);
  757. /** @var VObject\Component\VTimeZone $vtimezone */
  758. $vtimezone = $vtimezoneObj->VTIMEZONE;
  759. return $vtimezone->getTimeZone();
  760. }
  761. }