IMipService.php 24 KB

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