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 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2017, Georg Ehrke
  5. *
  6. * @author brad2014 <brad2014@users.noreply.github.com>
  7. * @author Brad Rubenstein <brad@wbr.tech>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Georg Ehrke <oc.list@georgehrke.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Leon Klingele <leon@struktur.de>
  12. * @author rakekniven <mark.ziegler@rakekniven.de>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Thomas Citharel <nextcloud@tcit.fr>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OCA\DAV\CalDAV\Schedule;
  33. use OCP\AppFramework\Utility\ITimeFactory;
  34. use OCP\Defaults;
  35. use OCP\IConfig;
  36. use OCP\IDBConnection;
  37. use OCP\IL10N;
  38. use OCP\ILogger;
  39. use OCP\IURLGenerator;
  40. use OCP\IUserManager;
  41. use OCP\L10N\IFactory as L10NFactory;
  42. use OCP\Mail\IEMailTemplate;
  43. use OCP\Mail\IMailer;
  44. use OCP\Security\ISecureRandom;
  45. use OCP\Util;
  46. use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin;
  47. use Sabre\VObject\Component\VCalendar;
  48. use Sabre\VObject\Component\VEvent;
  49. use Sabre\VObject\DateTimeParser;
  50. use Sabre\VObject\ITip\Message;
  51. use Sabre\VObject\Parameter;
  52. use Sabre\VObject\Property;
  53. use Sabre\VObject\Recur\EventIterator;
  54. /**
  55. * iMIP handler.
  56. *
  57. * This class is responsible for sending out iMIP messages. iMIP is the
  58. * email-based transport for iTIP. iTIP deals with scheduling operations for
  59. * iCalendar objects.
  60. *
  61. * If you want to customize the email that gets sent out, you can do so by
  62. * extending this class and overriding the sendMessage method.
  63. *
  64. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  65. * @author Evert Pot (http://evertpot.com/)
  66. * @license http://sabre.io/license/ Modified BSD License
  67. */
  68. class IMipPlugin extends SabreIMipPlugin {
  69. /** @var string */
  70. private $userId;
  71. /** @var IConfig */
  72. private $config;
  73. /** @var IMailer */
  74. private $mailer;
  75. /** @var ILogger */
  76. private $logger;
  77. /** @var ITimeFactory */
  78. private $timeFactory;
  79. /** @var L10NFactory */
  80. private $l10nFactory;
  81. /** @var IURLGenerator */
  82. private $urlGenerator;
  83. /** @var ISecureRandom */
  84. private $random;
  85. /** @var IDBConnection */
  86. private $db;
  87. /** @var Defaults */
  88. private $defaults;
  89. /** @var IUserManager */
  90. private $userManager;
  91. public const MAX_DATE = '2038-01-01';
  92. public const METHOD_REQUEST = 'request';
  93. public const METHOD_REPLY = 'reply';
  94. public const METHOD_CANCEL = 'cancel';
  95. public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
  96. /**
  97. * @param IConfig $config
  98. * @param IMailer $mailer
  99. * @param ILogger $logger
  100. * @param ITimeFactory $timeFactory
  101. * @param L10NFactory $l10nFactory
  102. * @param IUrlGenerator $urlGenerator
  103. * @param Defaults $defaults
  104. * @param ISecureRandom $random
  105. * @param IDBConnection $db
  106. * @param string $userId
  107. */
  108. public function __construct(IConfig $config, IMailer $mailer, ILogger $logger,
  109. ITimeFactory $timeFactory, L10NFactory $l10nFactory,
  110. IURLGenerator $urlGenerator, Defaults $defaults,
  111. ISecureRandom $random, IDBConnection $db, IUserManager $userManager,
  112. $userId) {
  113. parent::__construct('');
  114. $this->userId = $userId;
  115. $this->config = $config;
  116. $this->mailer = $mailer;
  117. $this->logger = $logger;
  118. $this->timeFactory = $timeFactory;
  119. $this->l10nFactory = $l10nFactory;
  120. $this->urlGenerator = $urlGenerator;
  121. $this->random = $random;
  122. $this->db = $db;
  123. $this->defaults = $defaults;
  124. $this->userManager = $userManager;
  125. }
  126. /**
  127. * Event handler for the 'schedule' event.
  128. *
  129. * @param Message $iTipMessage
  130. * @return void
  131. */
  132. public function schedule(Message $iTipMessage) {
  133. // Not sending any emails if the system considers the update
  134. // insignificant.
  135. if (!$iTipMessage->significantChange) {
  136. if (!$iTipMessage->scheduleStatus) {
  137. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  138. }
  139. return;
  140. }
  141. $summary = $iTipMessage->message->VEVENT->SUMMARY;
  142. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') {
  143. return;
  144. }
  145. if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  146. return;
  147. }
  148. // don't send out mails for events that already took place
  149. $lastOccurrence = $this->getLastOccurrence($iTipMessage->message);
  150. $currentTime = $this->timeFactory->getTime();
  151. if ($lastOccurrence < $currentTime) {
  152. return;
  153. }
  154. // Strip off mailto:
  155. $sender = substr($iTipMessage->sender, 7);
  156. $recipient = substr($iTipMessage->recipient, 7);
  157. if ($recipient === false || !$this->mailer->validateMailAddress($recipient)) {
  158. // Nothing to send if the recipient doesn't have a valid email address
  159. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  160. return;
  161. }
  162. $senderName = $iTipMessage->senderName ?: null;
  163. $recipientName = $iTipMessage->recipientName ?: null;
  164. if ($senderName === null || empty(trim($senderName))) {
  165. $user = $this->userManager->get($this->userId);
  166. if ($user) {
  167. // getDisplayName automatically uses the uid
  168. // if no display-name is set
  169. $senderName = $user->getDisplayName();
  170. }
  171. }
  172. /** @var VEvent $vevent */
  173. $vevent = $iTipMessage->message->VEVENT;
  174. $attendee = $this->getCurrentAttendee($iTipMessage);
  175. $defaultLang = $this->l10nFactory->findLanguage();
  176. $lang = $this->getAttendeeLangOrDefault($defaultLang, $attendee);
  177. $l10n = $this->l10nFactory->get('dav', $lang);
  178. $meetingAttendeeName = $recipientName ?: $recipient;
  179. $meetingInviteeName = $senderName ?: $sender;
  180. $meetingTitle = $vevent->SUMMARY;
  181. $meetingDescription = $vevent->DESCRIPTION;
  182. $meetingUrl = $vevent->URL;
  183. $meetingLocation = $vevent->LOCATION;
  184. $defaultVal = '--';
  185. $method = self::METHOD_REQUEST;
  186. switch (strtolower($iTipMessage->method)) {
  187. case self::METHOD_REPLY:
  188. $method = self::METHOD_REPLY;
  189. break;
  190. case self::METHOD_CANCEL:
  191. $method = self::METHOD_CANCEL;
  192. break;
  193. }
  194. $data = [
  195. 'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
  196. 'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
  197. 'meeting_title' => (string)$meetingTitle ?: $defaultVal,
  198. 'meeting_description' => (string)$meetingDescription ?: $defaultVal,
  199. 'meeting_url' => (string)$meetingUrl ?: $defaultVal,
  200. ];
  201. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  202. $fromName = $l10n->t('%1$s via %2$s', [$senderName, $this->defaults->getName()]);
  203. $message = $this->mailer->createMessage()
  204. ->setFrom([$fromEMail => $fromName])
  205. ->setTo([$recipient => $recipientName]);
  206. if ($sender !== false) {
  207. $message->setReplyTo([$sender => $senderName]);
  208. }
  209. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  210. $template->addHeader();
  211. $summary = ((string) $summary !== '') ? (string) $summary : $l10n->t('Untitled event');
  212. $this->addSubjectAndHeading($template, $l10n, $method, $summary);
  213. $this->addBulletList($template, $l10n, $vevent);
  214. // Only add response buttons to invitation requests: Fix Issue #11230
  215. if (($method == self::METHOD_REQUEST) && $this->getAttendeeRSVP($attendee)) {
  216. /*
  217. ** Only offer invitation accept/reject buttons, which link back to the
  218. ** nextcloud server, to recipients who can access the nextcloud server via
  219. ** their internet/intranet. Issue #12156
  220. **
  221. ** The app setting is stored in the appconfig database table.
  222. **
  223. ** For nextcloud servers accessible to the public internet, the default
  224. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  225. **
  226. ** When the nextcloud server is restricted behind a firewall, accessible
  227. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  228. ** to the email address or email domain, or comma separated list of addresses or domains,
  229. ** of recipients who can access the server.
  230. **
  231. ** To always deliver URLs, set invitation_link_recipients to "yes".
  232. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  233. */
  234. $recipientDomain = substr(strrchr($recipient, "@"), 1);
  235. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  236. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  237. || in_array(strtolower($recipient), $invitationLinkRecipients)
  238. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  239. $this->addResponseButtons($template, $l10n, $iTipMessage, $lastOccurrence);
  240. }
  241. }
  242. $template->addFooter();
  243. $message->useTemplate($template);
  244. $attachment = $this->mailer->createAttachment(
  245. $iTipMessage->message->serialize(),
  246. 'event.ics',// TODO(leon): Make file name unique, e.g. add event id
  247. 'text/calendar; method=' . $iTipMessage->method
  248. );
  249. $message->attach($attachment);
  250. try {
  251. $failed = $this->mailer->send($message);
  252. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  253. if ($failed) {
  254. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  255. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  256. }
  257. } catch (\Exception $ex) {
  258. $this->logger->logException($ex, ['app' => 'dav']);
  259. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  260. }
  261. }
  262. /**
  263. * check if event took place in the past already
  264. * @param VCalendar $vObject
  265. * @return int
  266. */
  267. private function getLastOccurrence(VCalendar $vObject) {
  268. /** @var VEvent $component */
  269. $component = $vObject->VEVENT;
  270. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  271. // Finding the last occurrence is a bit harder
  272. if (!isset($component->RRULE)) {
  273. if (isset($component->DTEND)) {
  274. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  275. } elseif (isset($component->DURATION)) {
  276. /** @var \DateTime $endDate */
  277. $endDate = clone $component->DTSTART->getDateTime();
  278. // $component->DTEND->getDateTime() returns DateTimeImmutable
  279. $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  280. $lastOccurrence = $endDate->getTimestamp();
  281. } elseif (!$component->DTSTART->hasTime()) {
  282. /** @var \DateTime $endDate */
  283. $endDate = clone $component->DTSTART->getDateTime();
  284. // $component->DTSTART->getDateTime() returns DateTimeImmutable
  285. $endDate = $endDate->modify('+1 day');
  286. $lastOccurrence = $endDate->getTimestamp();
  287. } else {
  288. $lastOccurrence = $firstOccurrence;
  289. }
  290. } else {
  291. $it = new EventIterator($vObject, (string)$component->UID);
  292. $maxDate = new \DateTime(self::MAX_DATE);
  293. if ($it->isInfinite()) {
  294. $lastOccurrence = $maxDate->getTimestamp();
  295. } else {
  296. $end = $it->getDtEnd();
  297. while ($it->valid() && $end < $maxDate) {
  298. $end = $it->getDtEnd();
  299. $it->next();
  300. }
  301. $lastOccurrence = $end->getTimestamp();
  302. }
  303. }
  304. return $lastOccurrence;
  305. }
  306. /**
  307. * @param Message $iTipMessage
  308. * @return null|Property
  309. */
  310. private function getCurrentAttendee(Message $iTipMessage) {
  311. /** @var VEvent $vevent */
  312. $vevent = $iTipMessage->message->VEVENT;
  313. $attendees = $vevent->select('ATTENDEE');
  314. foreach ($attendees as $attendee) {
  315. /** @var Property $attendee */
  316. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  317. return $attendee;
  318. }
  319. }
  320. return null;
  321. }
  322. /**
  323. * @param string $default
  324. * @param Property|null $attendee
  325. * @return string
  326. */
  327. private function getAttendeeLangOrDefault($default, Property $attendee = null) {
  328. if ($attendee !== null) {
  329. $lang = $attendee->offsetGet('LANGUAGE');
  330. if ($lang instanceof Parameter) {
  331. return $lang->getValue();
  332. }
  333. }
  334. return $default;
  335. }
  336. /**
  337. * @param Property|null $attendee
  338. * @return bool
  339. */
  340. private function getAttendeeRSVP(Property $attendee = null) {
  341. if ($attendee !== null) {
  342. $rsvp = $attendee->offsetGet('RSVP');
  343. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  344. return true;
  345. }
  346. }
  347. // RFC 5545 3.2.17: default RSVP is false
  348. return false;
  349. }
  350. /**
  351. * @param IL10N $l10n
  352. * @param VEvent $vevent
  353. */
  354. private function generateWhenString(IL10N $l10n, VEvent $vevent) {
  355. $dtstart = $vevent->DTSTART;
  356. if (isset($vevent->DTEND)) {
  357. $dtend = $vevent->DTEND;
  358. } elseif (isset($vevent->DURATION)) {
  359. $isFloating = $vevent->DTSTART->isFloating();
  360. $dtend = clone $vevent->DTSTART;
  361. $endDateTime = $dtend->getDateTime();
  362. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  363. $dtend->setDateTime($endDateTime, $isFloating);
  364. } elseif (!$vevent->DTSTART->hasTime()) {
  365. $isFloating = $vevent->DTSTART->isFloating();
  366. $dtend = clone $vevent->DTSTART;
  367. $endDateTime = $dtend->getDateTime();
  368. $endDateTime = $endDateTime->modify('+1 day');
  369. $dtend->setDateTime($endDateTime, $isFloating);
  370. } else {
  371. $dtend = clone $vevent->DTSTART;
  372. }
  373. $isAllDay = $dtstart instanceof Property\ICalendar\Date;
  374. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
  375. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
  376. /** @var \DateTimeImmutable $dtstartDt */
  377. $dtstartDt = $dtstart->getDateTime();
  378. /** @var \DateTimeImmutable $dtendDt */
  379. $dtendDt = $dtend->getDateTime();
  380. $diff = $dtstartDt->diff($dtendDt);
  381. $dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
  382. $dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
  383. if ($isAllDay) {
  384. // One day event
  385. if ($diff->days === 1) {
  386. return $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  387. }
  388. // DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
  389. // the email should show 2020-01-01 to 2020-01-04.
  390. $dtendDt->modify('-1 day');
  391. //event that spans over multiple days
  392. $localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  393. $localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
  394. return $localeStart . ' - ' . $localeEnd;
  395. }
  396. /** @var Property\ICalendar\DateTime $dtstart */
  397. /** @var Property\ICalendar\DateTime $dtend */
  398. $isFloating = $dtstart->isFloating();
  399. $startTimezone = $endTimezone = null;
  400. if (!$isFloating) {
  401. $prop = $dtstart->offsetGet('TZID');
  402. if ($prop instanceof Parameter) {
  403. $startTimezone = $prop->getValue();
  404. }
  405. $prop = $dtend->offsetGet('TZID');
  406. if ($prop instanceof Parameter) {
  407. $endTimezone = $prop->getValue();
  408. }
  409. }
  410. $localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
  411. $l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
  412. // always show full date with timezone if timezones are different
  413. if ($startTimezone !== $endTimezone) {
  414. $localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  415. return $localeStart . ' (' . $startTimezone . ') - ' .
  416. $localeEnd . ' (' . $endTimezone . ')';
  417. }
  418. // show only end time if date is the same
  419. if ($this->isDayEqual($dtstartDt, $dtendDt)) {
  420. $localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
  421. } else {
  422. $localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
  423. $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  424. }
  425. return $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
  426. }
  427. /**
  428. * @param \DateTime $dtStart
  429. * @param \DateTime $dtEnd
  430. * @return bool
  431. */
  432. private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) {
  433. return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
  434. }
  435. /**
  436. * @param IEMailTemplate $template
  437. * @param IL10N $l10n
  438. * @param string $method
  439. * @param string $summary
  440. */
  441. private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
  442. $method, $summary) {
  443. if ($method === self::METHOD_CANCEL) {
  444. $template->setSubject('Canceled: ' . $summary);
  445. $template->addHeading($l10n->t('Invitation canceled'));
  446. } elseif ($method === self::METHOD_REPLY) {
  447. $template->setSubject('Re: ' . $summary);
  448. $template->addHeading($l10n->t('Invitation updated'));
  449. } else {
  450. $template->setSubject('Invitation: ' . $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.svg'),'','',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.svg'),'','',self::IMIP_INDENT);
  468. }
  469. if ($vevent->LOCATION) {
  470. $template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'),
  471. $this->getAbsoluteImagePath('caldav/location.svg'),'','',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.svg'),
  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.svg'),'','',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.svg'),
  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.svg'),
  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_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  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. }