IMipService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\Schedule;
  8. use OC\URLGenerator;
  9. use OCP\IConfig;
  10. use OCP\IDBConnection;
  11. use OCP\IL10N;
  12. use OCP\L10N\IFactory as L10NFactory;
  13. use OCP\Mail\IEMailTemplate;
  14. use OCP\Security\ISecureRandom;
  15. use Sabre\VObject\Component\VCalendar;
  16. use Sabre\VObject\Component\VEvent;
  17. use Sabre\VObject\DateTimeParser;
  18. use Sabre\VObject\ITip\Message;
  19. use Sabre\VObject\Parameter;
  20. use Sabre\VObject\Property;
  21. use Sabre\VObject\Recur\EventIterator;
  22. class IMipService {
  23. private URLGenerator $urlGenerator;
  24. private IConfig $config;
  25. private IDBConnection $db;
  26. private ISecureRandom $random;
  27. private L10NFactory $l10nFactory;
  28. private IL10N $l10n;
  29. /** @var string[] */
  30. private const STRING_DIFF = [
  31. 'meeting_title' => 'SUMMARY',
  32. 'meeting_description' => 'DESCRIPTION',
  33. 'meeting_url' => 'URL',
  34. 'meeting_location' => 'LOCATION'
  35. ];
  36. public function __construct(URLGenerator $urlGenerator,
  37. IConfig $config,
  38. IDBConnection $db,
  39. ISecureRandom $random,
  40. L10NFactory $l10nFactory) {
  41. $this->urlGenerator = $urlGenerator;
  42. $this->config = $config;
  43. $this->db = $db;
  44. $this->random = $random;
  45. $this->l10nFactory = $l10nFactory;
  46. $default = $this->l10nFactory->findGenericLanguage();
  47. $this->l10n = $this->l10nFactory->get('dav', $default);
  48. }
  49. /**
  50. * @param string|null $senderName
  51. * @param string $default
  52. * @return string
  53. */
  54. public function getFrom(?string $senderName, string $default): string {
  55. if ($senderName === null) {
  56. return $default;
  57. }
  58. return $this->l10n->t('%1$s via %2$s', [$senderName, $default]);
  59. }
  60. public static function readPropertyWithDefault(VEvent $vevent, string $property, string $default) {
  61. if (isset($vevent->$property)) {
  62. $value = $vevent->$property->getValue();
  63. if (!empty($value)) {
  64. return $value;
  65. }
  66. }
  67. return $default;
  68. }
  69. private function generateDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
  70. $strikethrough = "<span style='text-decoration: line-through'>%s</span><br />%s";
  71. if (!isset($vevent->$property)) {
  72. return $default;
  73. }
  74. $newstring = $vevent->$property->getValue();
  75. if(isset($oldVEvent->$property) && $oldVEvent->$property->getValue() !== $newstring) {
  76. $oldstring = $oldVEvent->$property->getValue();
  77. return sprintf($strikethrough, $oldstring, $newstring);
  78. }
  79. return $newstring;
  80. }
  81. /**
  82. * Like generateDiffString() but linkifies the property values if they are urls.
  83. */
  84. private function generateLinkifiedDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
  85. if (!isset($vevent->$property)) {
  86. return $default;
  87. }
  88. /** @var string|null $newString */
  89. $newString = $vevent->$property->getValue();
  90. $oldString = isset($oldVEvent->$property) ? $oldVEvent->$property->getValue() : null;
  91. if ($oldString !== $newString) {
  92. return sprintf(
  93. "<span style='text-decoration: line-through'>%s</span><br />%s",
  94. $this->linkify($oldString) ?? $oldString ?? '',
  95. $this->linkify($newString) ?? $newString ?? ''
  96. );
  97. }
  98. return $this->linkify($newString) ?? $newString;
  99. }
  100. /**
  101. * Convert a given url to a html link element or return null otherwise.
  102. */
  103. private function linkify(?string $url): ?string {
  104. if ($url === null) {
  105. return null;
  106. }
  107. if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
  108. return null;
  109. }
  110. return sprintf('<a href="%1$s">%1$s</a>', htmlspecialchars($url));
  111. }
  112. /**
  113. * @param VEvent $vEvent
  114. * @param VEvent|null $oldVEvent
  115. * @return array
  116. */
  117. public function buildBodyData(VEvent $vEvent, ?VEvent $oldVEvent): array {
  118. $defaultVal = '';
  119. $data = [];
  120. $data['meeting_when'] = $this->generateWhenString($vEvent);
  121. foreach(self::STRING_DIFF as $key => $property) {
  122. $data[$key] = self::readPropertyWithDefault($vEvent, $property, $defaultVal);
  123. }
  124. $data['meeting_url_html'] = self::readPropertyWithDefault($vEvent, 'URL', $defaultVal);
  125. if (($locationHtml = $this->linkify($data['meeting_location'])) !== null) {
  126. $data['meeting_location_html'] = $locationHtml;
  127. }
  128. if(!empty($oldVEvent)) {
  129. $oldMeetingWhen = $this->generateWhenString($oldVEvent);
  130. $data['meeting_title_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'SUMMARY', $data['meeting_title']);
  131. $data['meeting_description_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'DESCRIPTION', $data['meeting_description']);
  132. $data['meeting_location_html'] = $this->generateLinkifiedDiffString($vEvent, $oldVEvent, 'LOCATION', $data['meeting_location']);
  133. $oldUrl = self::readPropertyWithDefault($oldVEvent, 'URL', $defaultVal);
  134. $data['meeting_url_html'] = !empty($oldUrl) && $oldUrl !== $data['meeting_url'] ? sprintf('<a href="%1$s">%1$s</a>', $oldUrl) : $data['meeting_url'];
  135. $data['meeting_when_html'] =
  136. ($oldMeetingWhen !== $data['meeting_when'] && $oldMeetingWhen !== null)
  137. ? sprintf("<span style='text-decoration: line-through'>%s</span><br />%s", $oldMeetingWhen, $data['meeting_when'])
  138. : $data['meeting_when'];
  139. }
  140. return $data;
  141. }
  142. /**
  143. * @param IL10N $this->l10n
  144. * @param VEvent $vevent
  145. * @return false|int|string
  146. */
  147. public function generateWhenString(VEvent $vevent) {
  148. /** @var Property\ICalendar\DateTime $dtstart */
  149. $dtstart = $vevent->DTSTART;
  150. if (isset($vevent->DTEND)) {
  151. /** @var Property\ICalendar\DateTime $dtend */
  152. $dtend = $vevent->DTEND;
  153. } elseif (isset($vevent->DURATION)) {
  154. $isFloating = $dtstart->isFloating();
  155. $dtend = clone $dtstart;
  156. $endDateTime = $dtend->getDateTime();
  157. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  158. $dtend->setDateTime($endDateTime, $isFloating);
  159. } elseif (!$dtstart->hasTime()) {
  160. $isFloating = $dtstart->isFloating();
  161. $dtend = clone $dtstart;
  162. $endDateTime = $dtend->getDateTime();
  163. $endDateTime = $endDateTime->modify('+1 day');
  164. $dtend->setDateTime($endDateTime, $isFloating);
  165. } else {
  166. $dtend = clone $dtstart;
  167. }
  168. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
  169. /** @var \DateTimeImmutable $dtstartDt */
  170. $dtstartDt = $dtstart->getDateTime();
  171. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
  172. /** @var \DateTimeImmutable $dtendDt */
  173. $dtendDt = $dtend->getDateTime();
  174. $diff = $dtstartDt->diff($dtendDt);
  175. $dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM));
  176. $dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM));
  177. if ($dtstart instanceof Property\ICalendar\Date) {
  178. // One day event
  179. if ($diff->days === 1) {
  180. return $this->l10n->l('date', $dtstartDt, ['width' => 'medium']);
  181. }
  182. // DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
  183. // the email should show 2020-01-01 to 2020-01-04.
  184. $dtendDt->modify('-1 day');
  185. //event that spans over multiple days
  186. $localeStart = $this->l10n->l('date', $dtstartDt, ['width' => 'medium']);
  187. $localeEnd = $this->l10n->l('date', $dtendDt, ['width' => 'medium']);
  188. return $localeStart . ' - ' . $localeEnd;
  189. }
  190. /** @var Property\ICalendar\DateTime $dtstart */
  191. /** @var Property\ICalendar\DateTime $dtend */
  192. $isFloating = $dtstart->isFloating();
  193. $startTimezone = $endTimezone = null;
  194. if (!$isFloating) {
  195. $prop = $dtstart->offsetGet('TZID');
  196. if ($prop instanceof Parameter) {
  197. $startTimezone = $prop->getValue();
  198. }
  199. $prop = $dtend->offsetGet('TZID');
  200. if ($prop instanceof Parameter) {
  201. $endTimezone = $prop->getValue();
  202. }
  203. }
  204. $localeStart = $this->l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
  205. $this->l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
  206. // always show full date with timezone if timezones are different
  207. if ($startTimezone !== $endTimezone) {
  208. $localeEnd = $this->l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  209. return $localeStart . ' (' . $startTimezone . ') - ' .
  210. $localeEnd . ' (' . $endTimezone . ')';
  211. }
  212. // show only end time if date is the same
  213. if ($dtstartDt->format('Y-m-d') === $dtendDt->format('Y-m-d')) {
  214. $localeEnd = $this->l10n->l('time', $dtendDt, ['width' => 'short']);
  215. } else {
  216. $localeEnd = $this->l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
  217. $this->l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  218. }
  219. return $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
  220. }
  221. /**
  222. * @param VEvent $vEvent
  223. * @return array
  224. */
  225. public function buildCancelledBodyData(VEvent $vEvent): array {
  226. $defaultVal = '';
  227. $strikethrough = "<span style='text-decoration: line-through'>%s</span>";
  228. $newMeetingWhen = $this->generateWhenString($vEvent);
  229. $newSummary = isset($vEvent->SUMMARY) && (string)$vEvent->SUMMARY !== '' ? (string)$vEvent->SUMMARY : $this->l10n->t('Untitled event');
  230. ;
  231. $newDescription = isset($vEvent->DESCRIPTION) && (string)$vEvent->DESCRIPTION !== '' ? (string)$vEvent->DESCRIPTION : $defaultVal;
  232. $newUrl = isset($vEvent->URL) && (string)$vEvent->URL !== '' ? sprintf('<a href="%1$s">%1$s</a>', $vEvent->URL) : $defaultVal;
  233. $newLocation = isset($vEvent->LOCATION) && (string)$vEvent->LOCATION !== '' ? (string)$vEvent->LOCATION : $defaultVal;
  234. $newLocationHtml = $this->linkify($newLocation) ?? $newLocation;
  235. $data = [];
  236. $data['meeting_when_html'] = $newMeetingWhen === '' ?: sprintf($strikethrough, $newMeetingWhen);
  237. $data['meeting_when'] = $newMeetingWhen;
  238. $data['meeting_title_html'] = sprintf($strikethrough, $newSummary);
  239. $data['meeting_title'] = $newSummary !== '' ? $newSummary: $this->l10n->t('Untitled event');
  240. $data['meeting_description_html'] = $newDescription !== '' ? sprintf($strikethrough, $newDescription) : '';
  241. $data['meeting_description'] = $newDescription;
  242. $data['meeting_url_html'] = $newUrl !== '' ? sprintf($strikethrough, $newUrl) : '';
  243. $data['meeting_url'] = isset($vEvent->URL) ? (string)$vEvent->URL : '';
  244. $data['meeting_location_html'] = $newLocationHtml !== '' ? sprintf($strikethrough, $newLocationHtml) : '';
  245. $data['meeting_location'] = $newLocation;
  246. return $data;
  247. }
  248. /**
  249. * Check if event took place in the past
  250. *
  251. * @param VCalendar $vObject
  252. * @return int
  253. */
  254. public function getLastOccurrence(VCalendar $vObject) {
  255. /** @var VEvent $component */
  256. $component = $vObject->VEVENT;
  257. if (isset($component->RRULE)) {
  258. $it = new EventIterator($vObject, (string)$component->UID);
  259. $maxDate = new \DateTime(IMipPlugin::MAX_DATE);
  260. if ($it->isInfinite()) {
  261. return $maxDate->getTimestamp();
  262. }
  263. $end = $it->getDtEnd();
  264. while ($it->valid() && $end < $maxDate) {
  265. $end = $it->getDtEnd();
  266. $it->next();
  267. }
  268. return $end->getTimestamp();
  269. }
  270. /** @var Property\ICalendar\DateTime $dtStart */
  271. $dtStart = $component->DTSTART;
  272. if (isset($component->DTEND)) {
  273. /** @var Property\ICalendar\DateTime $dtEnd */
  274. $dtEnd = $component->DTEND;
  275. return $dtEnd->getDateTime()->getTimeStamp();
  276. }
  277. if(isset($component->DURATION)) {
  278. /** @var \DateTime $endDate */
  279. $endDate = clone $dtStart->getDateTime();
  280. // $component->DTEND->getDateTime() returns DateTimeImmutable
  281. $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  282. return $endDate->getTimestamp();
  283. }
  284. if(!$dtStart->hasTime()) {
  285. /** @var \DateTime $endDate */
  286. // $component->DTSTART->getDateTime() returns DateTimeImmutable
  287. $endDate = clone $dtStart->getDateTime();
  288. $endDate = $endDate->modify('+1 day');
  289. return $endDate->getTimestamp();
  290. }
  291. // No computation of end time possible - return start date
  292. return $dtStart->getDateTime()->getTimeStamp();
  293. }
  294. /**
  295. * @param Property|null $attendee
  296. */
  297. public function setL10n(?Property $attendee = null) {
  298. if($attendee === null) {
  299. return;
  300. }
  301. $lang = $attendee->offsetGet('LANGUAGE');
  302. if ($lang instanceof Parameter) {
  303. $lang = $lang->getValue();
  304. $this->l10n = $this->l10nFactory->get('dav', $lang);
  305. }
  306. }
  307. /**
  308. * @param Property|null $attendee
  309. * @return bool
  310. */
  311. public function getAttendeeRsvpOrReqForParticipant(?Property $attendee = null) {
  312. if($attendee === null) {
  313. return false;
  314. }
  315. $rsvp = $attendee->offsetGet('RSVP');
  316. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  317. return true;
  318. }
  319. $role = $attendee->offsetGet('ROLE');
  320. // @see https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.16
  321. // Attendees without a role are assumed required and should receive an invitation link even if they have no RSVP set
  322. if ($role === null
  323. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'REQ-PARTICIPANT') === 0))
  324. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'OPT-PARTICIPANT') === 0))
  325. ) {
  326. return true;
  327. }
  328. // RFC 5545 3.2.17: default RSVP is false
  329. return false;
  330. }
  331. /**
  332. * @param IEMailTemplate $template
  333. * @param string $method
  334. * @param string $sender
  335. * @param string $summary
  336. * @param string|null $partstat
  337. * @param bool $isModified
  338. */
  339. public function addSubjectAndHeading(IEMailTemplate $template,
  340. string $method, string $sender, string $summary, bool $isModified, ?Property $replyingAttendee = null): void {
  341. if ($method === IMipPlugin::METHOD_CANCEL) {
  342. // TRANSLATORS Subject for email, when an invitation is cancelled. Ex: "Cancelled: {{Event Name}}"
  343. $template->setSubject($this->l10n->t('Cancelled: %1$s', [$summary]));
  344. $template->addHeading($this->l10n->t('"%1$s" has been canceled', [$summary]));
  345. } elseif ($method === IMipPlugin::METHOD_REPLY) {
  346. // TRANSLATORS Subject for email, when an invitation is replied to. Ex: "Re: {{Event Name}}"
  347. $template->setSubject($this->l10n->t('Re: %1$s', [$summary]));
  348. // Build the strings
  349. $partstat = (isset($replyingAttendee)) ? $replyingAttendee->offsetGet('PARTSTAT') : null;
  350. $partstat = ($partstat instanceof Parameter) ? $partstat->getValue() : null;
  351. switch ($partstat) {
  352. case 'ACCEPTED':
  353. $template->addHeading($this->l10n->t('%1$s has accepted your invitation', [$sender]));
  354. break;
  355. case 'TENTATIVE':
  356. $template->addHeading($this->l10n->t('%1$s has tentatively accepted your invitation', [$sender]));
  357. break;
  358. case 'DECLINED':
  359. $template->addHeading($this->l10n->t('%1$s has declined your invitation', [$sender]));
  360. break;
  361. case null:
  362. default:
  363. $template->addHeading($this->l10n->t('%1$s has responded to your invitation', [$sender]));
  364. break;
  365. }
  366. } elseif ($method === IMipPlugin::METHOD_REQUEST && $isModified) {
  367. // TRANSLATORS Subject for email, when an invitation is updated. Ex: "Invitation updated: {{Event Name}}"
  368. $template->setSubject($this->l10n->t('Invitation updated: %1$s', [$summary]));
  369. $template->addHeading($this->l10n->t('%1$s updated the event "%2$s"', [$sender, $summary]));
  370. } else {
  371. // TRANSLATORS Subject for email, when an invitation is sent. Ex: "Invitation: {{Event Name}}"
  372. $template->setSubject($this->l10n->t('Invitation: %1$s', [$summary]));
  373. $template->addHeading($this->l10n->t('%1$s would like to invite you to "%2$s"', [$sender, $summary]));
  374. }
  375. }
  376. /**
  377. * @param string $path
  378. * @return string
  379. */
  380. public function getAbsoluteImagePath($path): string {
  381. return $this->urlGenerator->getAbsoluteURL(
  382. $this->urlGenerator->imagePath('core', $path)
  383. );
  384. }
  385. /**
  386. * addAttendees: add organizer and attendee names/emails to iMip mail.
  387. *
  388. * Enable with DAV setting: invitation_list_attendees (default: no)
  389. *
  390. * The default is 'no', which matches old behavior, and is privacy preserving.
  391. *
  392. * To enable including attendees in invitation emails:
  393. * % php occ config:app:set dav invitation_list_attendees --value yes
  394. *
  395. * @param IEMailTemplate $template
  396. * @param IL10N $this->l10n
  397. * @param VEvent $vevent
  398. * @author brad2014 on github.com
  399. */
  400. public function addAttendees(IEMailTemplate $template, VEvent $vevent) {
  401. if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
  402. return;
  403. }
  404. if (isset($vevent->ORGANIZER)) {
  405. /** @var Property | Property\ICalendar\CalAddress $organizer */
  406. $organizer = $vevent->ORGANIZER;
  407. $organizerEmail = substr($organizer->getNormalizedValue(), 7);
  408. /** @var string|null $organizerName */
  409. $organizerName = isset($organizer->CN) ? $organizer->CN->getValue() : null;
  410. $organizerHTML = sprintf('<a href="%s">%s</a>',
  411. htmlspecialchars($organizer->getNormalizedValue()),
  412. htmlspecialchars($organizerName ?: $organizerEmail));
  413. $organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
  414. if(isset($organizer['PARTSTAT'])) {
  415. /** @var Parameter $partstat */
  416. $partstat = $organizer['PARTSTAT'];
  417. if(strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
  418. $organizerHTML .= ' ✔︎';
  419. $organizerText .= ' ✔︎';
  420. }
  421. }
  422. $template->addBodyListItem($organizerHTML, $this->l10n->t('Organizer:'),
  423. $this->getAbsoluteImagePath('caldav/organizer.png'),
  424. $organizerText, '', IMipPlugin::IMIP_INDENT);
  425. }
  426. $attendees = $vevent->select('ATTENDEE');
  427. if (count($attendees) === 0) {
  428. return;
  429. }
  430. $attendeesHTML = [];
  431. $attendeesText = [];
  432. foreach ($attendees as $attendee) {
  433. $attendeeEmail = substr($attendee->getNormalizedValue(), 7);
  434. $attendeeName = isset($attendee['CN']) ? $attendee['CN']->getValue() : null;
  435. $attendeeHTML = sprintf('<a href="%s">%s</a>',
  436. htmlspecialchars($attendee->getNormalizedValue()),
  437. htmlspecialchars($attendeeName ?: $attendeeEmail));
  438. $attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
  439. if (isset($attendee['PARTSTAT'])) {
  440. /** @var Parameter $partstat */
  441. $partstat = $attendee['PARTSTAT'];
  442. if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
  443. $attendeeHTML .= ' ✔︎';
  444. $attendeeText .= ' ✔︎';
  445. }
  446. }
  447. $attendeesHTML[] = $attendeeHTML;
  448. $attendeesText[] = $attendeeText;
  449. }
  450. $template->addBodyListItem(implode('<br/>', $attendeesHTML), $this->l10n->t('Attendees:'),
  451. $this->getAbsoluteImagePath('caldav/attendees.png'),
  452. implode("\n", $attendeesText), '', IMipPlugin::IMIP_INDENT);
  453. }
  454. /**
  455. * @param IEMailTemplate $template
  456. * @param VEVENT $vevent
  457. * @param $data
  458. */
  459. public function addBulletList(IEMailTemplate $template, VEvent $vevent, $data) {
  460. $template->addBodyListItem(
  461. $data['meeting_title_html'] ?? $data['meeting_title'], $this->l10n->t('Title:'),
  462. $this->getAbsoluteImagePath('caldav/title.png'), $data['meeting_title'], '', IMipPlugin::IMIP_INDENT);
  463. if ($data['meeting_when'] !== '') {
  464. $template->addBodyListItem($data['meeting_when_html'] ?? $data['meeting_when'], $this->l10n->t('Date and time:'),
  465. $this->getAbsoluteImagePath('caldav/time.png'), $data['meeting_when'], '', IMipPlugin::IMIP_INDENT);
  466. }
  467. if ($data['meeting_location'] !== '') {
  468. $template->addBodyListItem($data['meeting_location_html'] ?? $data['meeting_location'], $this->l10n->t('Location:'),
  469. $this->getAbsoluteImagePath('caldav/location.png'), $data['meeting_location'], '', IMipPlugin::IMIP_INDENT);
  470. }
  471. if ($data['meeting_url'] !== '') {
  472. $template->addBodyListItem($data['meeting_url_html'] ?? $data['meeting_url'], $this->l10n->t('Link:'),
  473. $this->getAbsoluteImagePath('caldav/link.png'), $data['meeting_url'], '', IMipPlugin::IMIP_INDENT);
  474. }
  475. $this->addAttendees($template, $vevent);
  476. /* Put description last, like an email body, since it can be arbitrarily long */
  477. if ($data['meeting_description']) {
  478. $template->addBodyListItem($data['meeting_description_html'] ?? $data['meeting_description'], $this->l10n->t('Description:'),
  479. $this->getAbsoluteImagePath('caldav/description.png'), $data['meeting_description'], '', IMipPlugin::IMIP_INDENT);
  480. }
  481. }
  482. /**
  483. * @param Message $iTipMessage
  484. * @return null|Property
  485. */
  486. public function getCurrentAttendee(Message $iTipMessage): ?Property {
  487. /** @var VEvent $vevent */
  488. $vevent = $iTipMessage->message->VEVENT;
  489. $attendees = $vevent->select('ATTENDEE');
  490. foreach ($attendees as $attendee) {
  491. /** @var Property $attendee */
  492. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  493. return $attendee;
  494. }
  495. }
  496. return null;
  497. }
  498. /**
  499. * @param Message $iTipMessage
  500. * @param VEvent $vevent
  501. * @param int $lastOccurrence
  502. * @return string
  503. */
  504. public function createInvitationToken(Message $iTipMessage, VEvent $vevent, int $lastOccurrence): string {
  505. $token = $this->random->generate(60, ISecureRandom::CHAR_ALPHANUMERIC);
  506. $attendee = $iTipMessage->recipient;
  507. $organizer = $iTipMessage->sender;
  508. $sequence = $iTipMessage->sequence;
  509. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
  510. $vevent->{'RECURRENCE-ID'}->serialize() : null;
  511. $uid = $vevent->{'UID'};
  512. $query = $this->db->getQueryBuilder();
  513. $query->insert('calendar_invitations')
  514. ->values([
  515. 'token' => $query->createNamedParameter($token),
  516. 'attendee' => $query->createNamedParameter($attendee),
  517. 'organizer' => $query->createNamedParameter($organizer),
  518. 'sequence' => $query->createNamedParameter($sequence),
  519. 'recurrenceid' => $query->createNamedParameter($recurrenceId),
  520. 'expiration' => $query->createNamedParameter($lastOccurrence),
  521. 'uid' => $query->createNamedParameter($uid)
  522. ])
  523. ->execute();
  524. return $token;
  525. }
  526. /**
  527. * Create a valid VCalendar object out of the details of
  528. * a VEvent and its associated iTip Message
  529. *
  530. * We do this to filter out all unchanged VEvents
  531. * This is especially important in iTip Messages with recurrences
  532. * and recurrence exceptions
  533. *
  534. * @param Message $iTipMessage
  535. * @param VEvent $vEvent
  536. * @return VCalendar
  537. */
  538. public function generateVCalendar(Message $iTipMessage, VEvent $vEvent): VCalendar {
  539. $vCalendar = new VCalendar();
  540. $vCalendar->add('METHOD', $iTipMessage->method);
  541. foreach ($iTipMessage->message->getComponents() as $component) {
  542. if ($component instanceof VEvent) {
  543. continue;
  544. }
  545. $vCalendar->add(clone $component);
  546. }
  547. $vCalendar->add($vEvent);
  548. return $vCalendar;
  549. }
  550. /**
  551. * @param IEMailTemplate $template
  552. * @param $token
  553. */
  554. public function addResponseButtons(IEMailTemplate $template, $token) {
  555. $template->addBodyButtonGroup(
  556. $this->l10n->t('Accept'),
  557. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
  558. 'token' => $token,
  559. ]),
  560. $this->l10n->t('Decline'),
  561. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
  562. 'token' => $token,
  563. ])
  564. );
  565. }
  566. public function addMoreOptionsButton(IEMailTemplate $template, $token) {
  567. $moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
  568. 'token' => $token,
  569. ]);
  570. $html = vsprintf('<small><a href="%s">%s</a></small>', [
  571. $moreOptionsURL, $this->l10n->t('More options …')
  572. ]);
  573. $text = $this->l10n->t('More options at %s', [$moreOptionsURL]);
  574. $template->addBodyText($html, $text);
  575. }
  576. public function getReplyingAttendee(Message $iTipMessage): ?Property {
  577. /** @var VEvent $vevent */
  578. $vevent = $iTipMessage->message->VEVENT;
  579. $attendees = $vevent->select('ATTENDEE');
  580. foreach ($attendees as $attendee) {
  581. /** @var Property $attendee */
  582. if (strcasecmp($attendee->getValue(), $iTipMessage->sender) === 0) {
  583. return $attendee;
  584. }
  585. }
  586. return null;
  587. }
  588. public function isRoomOrResource(Property $attendee): bool {
  589. $cuType = $attendee->offsetGet('CUTYPE');
  590. if(!$cuType instanceof Parameter) {
  591. return false;
  592. }
  593. $type = $cuType->getValue() ?? 'INDIVIDUAL';
  594. if (\in_array(strtoupper($type), ['RESOURCE', 'ROOM'], true)) {
  595. // Don't send emails to things
  596. return true;
  597. }
  598. return false;
  599. }
  600. }