You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IMipPlugin.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2017, Georg Ehrke
  5. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  6. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  7. *
  8. * @author brad2014 <brad2014@users.noreply.github.com>
  9. * @author Brad Rubenstein <brad@wbr.tech>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Leon Klingele <leon@struktur.de>
  14. * @author Nick Sweeting <git@sweeting.me>
  15. * @author rakekniven <mark.ziegler@rakekniven.de>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Citharel <nextcloud@tcit.fr>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OCA\DAV\CalDAV\Schedule;
  36. use OCP\AppFramework\Utility\ITimeFactory;
  37. use OCP\Defaults;
  38. use OCP\IConfig;
  39. use OCP\IDBConnection;
  40. use OCP\IL10N;
  41. use OCP\IURLGenerator;
  42. use OCP\IUserManager;
  43. use OCP\L10N\IFactory as L10NFactory;
  44. use OCP\Mail\IEMailTemplate;
  45. use OCP\Mail\IMailer;
  46. use OCP\Security\ISecureRandom;
  47. use OCP\Util;
  48. use Psr\Log\LoggerInterface;
  49. use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin;
  50. use Sabre\VObject\Component\VCalendar;
  51. use Sabre\VObject\Component\VEvent;
  52. use Sabre\VObject\DateTimeParser;
  53. use Sabre\VObject\ITip\Message;
  54. use Sabre\VObject\Parameter;
  55. use Sabre\VObject\Property;
  56. use Sabre\VObject\Recur\EventIterator;
  57. /**
  58. * iMIP handler.
  59. *
  60. * This class is responsible for sending out iMIP messages. iMIP is the
  61. * email-based transport for iTIP. iTIP deals with scheduling operations for
  62. * iCalendar objects.
  63. *
  64. * If you want to customize the email that gets sent out, you can do so by
  65. * extending this class and overriding the sendMessage method.
  66. *
  67. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  68. * @author Evert Pot (http://evertpot.com/)
  69. * @license http://sabre.io/license/ Modified BSD License
  70. */
  71. class IMipPlugin extends SabreIMipPlugin {
  72. /** @var string */
  73. private $userId;
  74. /** @var IConfig */
  75. private $config;
  76. /** @var IMailer */
  77. private $mailer;
  78. private LoggerInterface $logger;
  79. /** @var ITimeFactory */
  80. private $timeFactory;
  81. /** @var L10NFactory */
  82. private $l10nFactory;
  83. /** @var IURLGenerator */
  84. private $urlGenerator;
  85. /** @var ISecureRandom */
  86. private $random;
  87. /** @var IDBConnection */
  88. private $db;
  89. /** @var Defaults */
  90. private $defaults;
  91. /** @var IUserManager */
  92. private $userManager;
  93. public const MAX_DATE = '2038-01-01';
  94. public const METHOD_REQUEST = 'request';
  95. public const METHOD_REPLY = 'reply';
  96. public const METHOD_CANCEL = 'cancel';
  97. public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
  98. public function __construct(IConfig $config, IMailer $mailer,
  99. LoggerInterface $logger,
  100. ITimeFactory $timeFactory, L10NFactory $l10nFactory,
  101. IURLGenerator $urlGenerator, Defaults $defaults,
  102. ISecureRandom $random, IDBConnection $db, IUserManager $userManager,
  103. $userId) {
  104. parent::__construct('');
  105. $this->userId = $userId;
  106. $this->config = $config;
  107. $this->mailer = $mailer;
  108. $this->logger = $logger;
  109. $this->timeFactory = $timeFactory;
  110. $this->l10nFactory = $l10nFactory;
  111. $this->urlGenerator = $urlGenerator;
  112. $this->random = $random;
  113. $this->db = $db;
  114. $this->defaults = $defaults;
  115. $this->userManager = $userManager;
  116. }
  117. /**
  118. * Event handler for the 'schedule' event.
  119. *
  120. * @param Message $iTipMessage
  121. * @return void
  122. */
  123. public function schedule(Message $iTipMessage) {
  124. // Not sending any emails if the system considers the update
  125. // insignificant.
  126. if (!$iTipMessage->significantChange) {
  127. if (!$iTipMessage->scheduleStatus) {
  128. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  129. }
  130. return;
  131. }
  132. $summary = $iTipMessage->message->VEVENT->SUMMARY;
  133. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') {
  134. return;
  135. }
  136. if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  137. return;
  138. }
  139. // don't send out mails for events that already took place
  140. $lastOccurrence = $this->getLastOccurrence($iTipMessage->message);
  141. $currentTime = $this->timeFactory->getTime();
  142. if ($lastOccurrence < $currentTime) {
  143. return;
  144. }
  145. // Strip off mailto:
  146. $sender = substr($iTipMessage->sender, 7);
  147. $recipient = substr($iTipMessage->recipient, 7);
  148. if (!$this->mailer->validateMailAddress($recipient)) {
  149. // Nothing to send if the recipient doesn't have a valid email address
  150. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  151. return;
  152. }
  153. $recipientName = $iTipMessage->recipientName ?: null;
  154. /** @var Parameter|string|null $senderName */
  155. $senderName = $iTipMessage->senderName ?: null;
  156. if($senderName instanceof Parameter) {
  157. $senderName = $senderName->getValue() ?? null;
  158. }
  159. if ($senderName === null || empty(trim($senderName))) {
  160. $senderName = $this->userManager->getDisplayName($this->userId);
  161. }
  162. /** @var VEvent $vevent */
  163. $vevent = $iTipMessage->message->VEVENT;
  164. $attendee = $this->getCurrentAttendee($iTipMessage);
  165. $defaultLang = $this->l10nFactory->findGenericLanguage();
  166. $lang = $this->getAttendeeLangOrDefault($defaultLang, $attendee);
  167. $l10n = $this->l10nFactory->get('dav', $lang);
  168. $meetingAttendeeName = $recipientName ?: $recipient;
  169. $meetingInviteeName = $senderName ?: $sender;
  170. $meetingTitle = $vevent->SUMMARY;
  171. $meetingDescription = $vevent->DESCRIPTION;
  172. $meetingUrl = $vevent->URL;
  173. $meetingLocation = $vevent->LOCATION;
  174. $defaultVal = '--';
  175. $method = self::METHOD_REQUEST;
  176. switch (strtolower($iTipMessage->method)) {
  177. case self::METHOD_REPLY:
  178. $method = self::METHOD_REPLY;
  179. break;
  180. case self::METHOD_CANCEL:
  181. $method = self::METHOD_CANCEL;
  182. break;
  183. }
  184. $data = [
  185. 'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
  186. 'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
  187. 'meeting_title' => (string)$meetingTitle ?: $defaultVal,
  188. 'meeting_description' => (string)$meetingDescription ?: $defaultVal,
  189. 'meeting_url' => (string)$meetingUrl ?: $defaultVal,
  190. ];
  191. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  192. $fromName = $l10n->t('%1$s via %2$s', [$senderName ?? $this->userId, $this->defaults->getName()]);
  193. $message = $this->mailer->createMessage()
  194. ->setFrom([$fromEMail => $fromName])
  195. ->setTo([$recipient => $recipientName])
  196. ->setReplyTo([$sender => $senderName]);
  197. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  198. $template->addHeader();
  199. $summary = ((string) $summary !== '') ? (string) $summary : $l10n->t('Untitled event');
  200. $this->addSubjectAndHeading($template, $l10n, $method, $summary);
  201. $this->addBulletList($template, $l10n, $vevent);
  202. // Only add response buttons to invitation requests: Fix Issue #11230
  203. if (($method == self::METHOD_REQUEST) && $this->getAttendeeRsvpOrReqForParticipant($attendee)) {
  204. /*
  205. ** Only offer invitation accept/reject buttons, which link back to the
  206. ** nextcloud server, to recipients who can access the nextcloud server via
  207. ** their internet/intranet. Issue #12156
  208. **
  209. ** The app setting is stored in the appconfig database table.
  210. **
  211. ** For nextcloud servers accessible to the public internet, the default
  212. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  213. **
  214. ** When the nextcloud server is restricted behind a firewall, accessible
  215. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  216. ** to the email address or email domain, or comma separated list of addresses or domains,
  217. ** of recipients who can access the server.
  218. **
  219. ** To always deliver URLs, set invitation_link_recipients to "yes".
  220. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  221. */
  222. $recipientDomain = substr(strrchr($recipient, "@"), 1);
  223. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  224. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  225. || in_array(strtolower($recipient), $invitationLinkRecipients)
  226. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  227. $this->addResponseButtons($template, $l10n, $iTipMessage, $lastOccurrence);
  228. }
  229. }
  230. $template->addFooter();
  231. $message->useTemplate($template);
  232. $attachment = $this->mailer->createAttachment(
  233. $iTipMessage->message->serialize(),
  234. 'event.ics',// TODO(leon): Make file name unique, e.g. add event id
  235. 'text/calendar; method=' . $iTipMessage->method
  236. );
  237. $message->attach($attachment);
  238. try {
  239. $failed = $this->mailer->send($message);
  240. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  241. if ($failed) {
  242. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  243. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  244. }
  245. } catch (\Exception $ex) {
  246. $this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
  247. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  248. }
  249. }
  250. /**
  251. * check if event took place in the past already
  252. * @param VCalendar $vObject
  253. * @return int
  254. */
  255. private function getLastOccurrence(VCalendar $vObject) {
  256. /** @var VEvent $component */
  257. $component = $vObject->VEVENT;
  258. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  259. // Finding the last occurrence is a bit harder
  260. if (!isset($component->RRULE)) {
  261. if (isset($component->DTEND)) {
  262. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  263. } elseif (isset($component->DURATION)) {
  264. /** @var \DateTime $endDate */
  265. $endDate = clone $component->DTSTART->getDateTime();
  266. // $component->DTEND->getDateTime() returns DateTimeImmutable
  267. $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  268. $lastOccurrence = $endDate->getTimestamp();
  269. } elseif (!$component->DTSTART->hasTime()) {
  270. /** @var \DateTime $endDate */
  271. $endDate = clone $component->DTSTART->getDateTime();
  272. // $component->DTSTART->getDateTime() returns DateTimeImmutable
  273. $endDate = $endDate->modify('+1 day');
  274. $lastOccurrence = $endDate->getTimestamp();
  275. } else {
  276. $lastOccurrence = $firstOccurrence;
  277. }
  278. } else {
  279. $it = new EventIterator($vObject, (string)$component->UID);
  280. $maxDate = new \DateTime(self::MAX_DATE);
  281. if ($it->isInfinite()) {
  282. $lastOccurrence = $maxDate->getTimestamp();
  283. } else {
  284. $end = $it->getDtEnd();
  285. while ($it->valid() && $end < $maxDate) {
  286. $end = $it->getDtEnd();
  287. $it->next();
  288. }
  289. $lastOccurrence = $end->getTimestamp();
  290. }
  291. }
  292. return $lastOccurrence;
  293. }
  294. /**
  295. * @param Message $iTipMessage
  296. * @return null|Property
  297. */
  298. private function getCurrentAttendee(Message $iTipMessage) {
  299. /** @var VEvent $vevent */
  300. $vevent = $iTipMessage->message->VEVENT;
  301. $attendees = $vevent->select('ATTENDEE');
  302. foreach ($attendees as $attendee) {
  303. /** @var Property $attendee */
  304. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  305. return $attendee;
  306. }
  307. }
  308. return null;
  309. }
  310. /**
  311. * @param string $default
  312. * @param Property|null $attendee
  313. * @return string
  314. */
  315. private function getAttendeeLangOrDefault($default, Property $attendee = null) {
  316. if ($attendee !== null) {
  317. $lang = $attendee->offsetGet('LANGUAGE');
  318. if ($lang instanceof Parameter) {
  319. return $lang->getValue();
  320. }
  321. }
  322. return $default;
  323. }
  324. /**
  325. * @param Property|null $attendee
  326. * @return bool
  327. */
  328. private function getAttendeeRsvpOrReqForParticipant(Property $attendee = null) {
  329. if ($attendee !== null) {
  330. $rsvp = $attendee->offsetGet('RSVP');
  331. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  332. return true;
  333. }
  334. $role = $attendee->offsetGet('ROLE');
  335. // @see https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.16
  336. // Attendees without a role are assumed required and should receive an invitation link even if they have no RSVP set
  337. if ($role === null
  338. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'REQ-PARTICIPANT') === 0))
  339. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'OPT-PARTICIPANT') === 0))
  340. ) {
  341. return true;
  342. }
  343. }
  344. // RFC 5545 3.2.17: default RSVP is false
  345. return false;
  346. }
  347. /**
  348. * @param IL10N $l10n
  349. * @param VEvent $vevent
  350. */
  351. private function generateWhenString(IL10N $l10n, VEvent $vevent) {
  352. $dtstart = $vevent->DTSTART;
  353. if (isset($vevent->DTEND)) {
  354. $dtend = $vevent->DTEND;
  355. } elseif (isset($vevent->DURATION)) {
  356. $isFloating = $vevent->DTSTART->isFloating();
  357. $dtend = clone $vevent->DTSTART;
  358. $endDateTime = $dtend->getDateTime();
  359. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  360. $dtend->setDateTime($endDateTime, $isFloating);
  361. } elseif (!$vevent->DTSTART->hasTime()) {
  362. $isFloating = $vevent->DTSTART->isFloating();
  363. $dtend = clone $vevent->DTSTART;
  364. $endDateTime = $dtend->getDateTime();
  365. $endDateTime = $endDateTime->modify('+1 day');
  366. $dtend->setDateTime($endDateTime, $isFloating);
  367. } else {
  368. $dtend = clone $vevent->DTSTART;
  369. }
  370. $isAllDay = $dtstart instanceof Property\ICalendar\Date;
  371. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
  372. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
  373. /** @var \DateTimeImmutable $dtstartDt */
  374. $dtstartDt = $dtstart->getDateTime();
  375. /** @var \DateTimeImmutable $dtendDt */
  376. $dtendDt = $dtend->getDateTime();
  377. $diff = $dtstartDt->diff($dtendDt);
  378. $dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM));
  379. $dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM));
  380. if ($isAllDay) {
  381. // One day event
  382. if ($diff->days === 1) {
  383. return $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  384. }
  385. // DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
  386. // the email should show 2020-01-01 to 2020-01-04.
  387. $dtendDt->modify('-1 day');
  388. //event that spans over multiple days
  389. $localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  390. $localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
  391. return $localeStart . ' - ' . $localeEnd;
  392. }
  393. /** @var Property\ICalendar\DateTime $dtstart */
  394. /** @var Property\ICalendar\DateTime $dtend */
  395. $isFloating = $dtstart->isFloating();
  396. $startTimezone = $endTimezone = null;
  397. if (!$isFloating) {
  398. $prop = $dtstart->offsetGet('TZID');
  399. if ($prop instanceof Parameter) {
  400. $startTimezone = $prop->getValue();
  401. }
  402. $prop = $dtend->offsetGet('TZID');
  403. if ($prop instanceof Parameter) {
  404. $endTimezone = $prop->getValue();
  405. }
  406. }
  407. $localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
  408. $l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
  409. // always show full date with timezone if timezones are different
  410. if ($startTimezone !== $endTimezone) {
  411. $localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  412. return $localeStart . ' (' . $startTimezone . ') - ' .
  413. $localeEnd . ' (' . $endTimezone . ')';
  414. }
  415. // show only end time if date is the same
  416. if ($this->isDayEqual($dtstartDt, $dtendDt)) {
  417. $localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
  418. } else {
  419. $localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
  420. $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  421. }
  422. return $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
  423. }
  424. /**
  425. * @param \DateTime $dtStart
  426. * @param \DateTime $dtEnd
  427. * @return bool
  428. */
  429. private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) {
  430. return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
  431. }
  432. /**
  433. * @param IEMailTemplate $template
  434. * @param IL10N $l10n
  435. * @param string $method
  436. * @param string $summary
  437. */
  438. private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
  439. $method, $summary) {
  440. if ($method === self::METHOD_CANCEL) {
  441. // TRANSLATORS Subject for email, when an invitation is cancelled. Ex: "Cancelled: {{Event Name}}"
  442. $template->setSubject($l10n->t('Cancelled: %1$s', [$summary]));
  443. $template->addHeading($l10n->t('Invitation canceled'));
  444. } elseif ($method === self::METHOD_REPLY) {
  445. // TRANSLATORS Subject for email, when an invitation is updated. Ex: "Re: {{Event Name}}"
  446. $template->setSubject($l10n->t('Re: %1$s', [$summary]));
  447. $template->addHeading($l10n->t('Invitation updated'));
  448. } else {
  449. // TRANSLATORS Subject for email, when an invitation is sent. Ex: "Invitation: {{Event Name}}"
  450. $template->setSubject($l10n->t('Invitation: %1$s', [$summary]));
  451. $template->addHeading($l10n->t('Invitation'));
  452. }
  453. }
  454. /**
  455. * @param IEMailTemplate $template
  456. * @param IL10N $l10n
  457. * @param VEVENT $vevent
  458. */
  459. private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) {
  460. if ($vevent->SUMMARY) {
  461. $template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'),
  462. $this->getAbsoluteImagePath('caldav/title.png'), '', '', self::IMIP_INDENT);
  463. }
  464. $meetingWhen = $this->generateWhenString($l10n, $vevent);
  465. if ($meetingWhen) {
  466. $template->addBodyListItem($meetingWhen, $l10n->t('Time:'),
  467. $this->getAbsoluteImagePath('caldav/time.png'), '', '', self::IMIP_INDENT);
  468. }
  469. if ($vevent->LOCATION) {
  470. $template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'),
  471. $this->getAbsoluteImagePath('caldav/location.png'), '', '', self::IMIP_INDENT);
  472. }
  473. if ($vevent->URL) {
  474. $url = $vevent->URL->getValue();
  475. $template->addBodyListItem(sprintf('<a href="%s">%s</a>',
  476. htmlspecialchars($url),
  477. htmlspecialchars($url)),
  478. $l10n->t('Link:'),
  479. $this->getAbsoluteImagePath('caldav/link.png'),
  480. $url, '', self::IMIP_INDENT);
  481. }
  482. $this->addAttendees($template, $l10n, $vevent);
  483. /* Put description last, like an email body, since it can be arbitrarily long */
  484. if ($vevent->DESCRIPTION) {
  485. $template->addBodyListItem($vevent->DESCRIPTION->getValue(), $l10n->t('Description:'),
  486. $this->getAbsoluteImagePath('caldav/description.png'), '', '', self::IMIP_INDENT);
  487. }
  488. }
  489. /**
  490. * addAttendees: add organizer and attendee names/emails to iMip mail.
  491. *
  492. * Enable with DAV setting: invitation_list_attendees (default: no)
  493. *
  494. * The default is 'no', which matches old behavior, and is privacy preserving.
  495. *
  496. * To enable including attendees in invitation emails:
  497. * % php occ config:app:set dav invitation_list_attendees --value yes
  498. *
  499. * @param IEMailTemplate $template
  500. * @param IL10N $l10n
  501. * @param Message $iTipMessage
  502. * @param int $lastOccurrence
  503. * @author brad2014 on github.com
  504. */
  505. private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) {
  506. if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
  507. return;
  508. }
  509. if (isset($vevent->ORGANIZER)) {
  510. /** @var Property\ICalendar\CalAddress $organizer */
  511. $organizer = $vevent->ORGANIZER;
  512. $organizerURI = $organizer->getNormalizedValue();
  513. [$scheme,$organizerEmail] = explode(':', $organizerURI, 2); # strip off scheme mailto:
  514. /** @var string|null $organizerName */
  515. $organizerName = isset($organizer['CN']) ? $organizer['CN'] : null;
  516. $organizerHTML = sprintf('<a href="%s">%s</a>',
  517. htmlspecialchars($organizerURI),
  518. htmlspecialchars($organizerName ?: $organizerEmail));
  519. $organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
  520. if (isset($organizer['PARTSTAT'])) {
  521. /** @var Parameter $partstat */
  522. $partstat = $organizer['PARTSTAT'];
  523. if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
  524. $organizerHTML .= ' ✔︎';
  525. $organizerText .= ' ✔︎';
  526. }
  527. }
  528. $template->addBodyListItem($organizerHTML, $l10n->t('Organizer:'),
  529. $this->getAbsoluteImagePath('caldav/organizer.png'),
  530. $organizerText, '', self::IMIP_INDENT);
  531. }
  532. $attendees = $vevent->select('ATTENDEE');
  533. if (count($attendees) === 0) {
  534. return;
  535. }
  536. $attendeesHTML = [];
  537. $attendeesText = [];
  538. foreach ($attendees as $attendee) {
  539. $attendeeURI = $attendee->getNormalizedValue();
  540. [$scheme,$attendeeEmail] = explode(':', $attendeeURI, 2); # strip off scheme mailto:
  541. $attendeeName = isset($attendee['CN']) ? $attendee['CN'] : null;
  542. $attendeeHTML = sprintf('<a href="%s">%s</a>',
  543. htmlspecialchars($attendeeURI),
  544. htmlspecialchars($attendeeName ?: $attendeeEmail));
  545. $attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
  546. if (isset($attendee['PARTSTAT'])
  547. && strcasecmp($attendee['PARTSTAT'], 'ACCEPTED') === 0) {
  548. $attendeeHTML .= ' ✔︎';
  549. $attendeeText .= ' ✔︎';
  550. }
  551. array_push($attendeesHTML, $attendeeHTML);
  552. array_push($attendeesText, $attendeeText);
  553. }
  554. $template->addBodyListItem(implode('<br/>', $attendeesHTML), $l10n->t('Attendees:'),
  555. $this->getAbsoluteImagePath('caldav/attendees.png'),
  556. implode("\n", $attendeesText), '', self::IMIP_INDENT);
  557. }
  558. /**
  559. * @param IEMailTemplate $template
  560. * @param IL10N $l10n
  561. * @param Message $iTipMessage
  562. * @param int $lastOccurrence
  563. */
  564. private function addResponseButtons(IEMailTemplate $template, IL10N $l10n,
  565. Message $iTipMessage, $lastOccurrence) {
  566. $token = $this->createInvitationToken($iTipMessage, $lastOccurrence);
  567. $template->addBodyButtonGroup(
  568. $l10n->t('Accept'),
  569. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
  570. 'token' => $token,
  571. ]),
  572. $l10n->t('Decline'),
  573. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
  574. 'token' => $token,
  575. ])
  576. );
  577. $moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
  578. 'token' => $token,
  579. ]);
  580. $html = vsprintf('<small><a href="%s">%s</a></small>', [
  581. $moreOptionsURL, $l10n->t('More options …')
  582. ]);
  583. $text = $l10n->t('More options at %s', [$moreOptionsURL]);
  584. $template->addBodyText($html, $text);
  585. }
  586. /**
  587. * @param string $path
  588. * @return string
  589. */
  590. private function getAbsoluteImagePath($path) {
  591. return $this->urlGenerator->getAbsoluteURL(
  592. $this->urlGenerator->imagePath('core', $path)
  593. );
  594. }
  595. /**
  596. * @param Message $iTipMessage
  597. * @param int $lastOccurrence
  598. * @return string
  599. */
  600. private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string {
  601. $token = $this->random->generate(60, ISecureRandom::CHAR_ALPHANUMERIC);
  602. /** @var VEvent $vevent */
  603. $vevent = $iTipMessage->message->VEVENT;
  604. $attendee = $iTipMessage->recipient;
  605. $organizer = $iTipMessage->sender;
  606. $sequence = $iTipMessage->sequence;
  607. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
  608. $vevent->{'RECURRENCE-ID'}->serialize() : null;
  609. $uid = $vevent->{'UID'};
  610. $query = $this->db->getQueryBuilder();
  611. $query->insert('calendar_invitations')
  612. ->values([
  613. 'token' => $query->createNamedParameter($token),
  614. 'attendee' => $query->createNamedParameter($attendee),
  615. 'organizer' => $query->createNamedParameter($organizer),
  616. 'sequence' => $query->createNamedParameter($sequence),
  617. 'recurrenceid' => $query->createNamedParameter($recurrenceId),
  618. 'expiration' => $query->createNamedParameter($lastOccurrence),
  619. 'uid' => $query->createNamedParameter($uid)
  620. ])
  621. ->execute();
  622. return $token;
  623. }
  624. }