IMipPlugin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-FileCopyrightText: 2007-2015 fruux GmbH (https://fruux.com/)
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\DAV\CalDAV\Schedule;
  9. use OCA\DAV\CalDAV\CalendarObject;
  10. use OCA\DAV\CalDAV\EventComparisonService;
  11. use OCP\AppFramework\Utility\ITimeFactory;
  12. use OCP\Defaults;
  13. use OCP\IConfig;
  14. use OCP\IUserSession;
  15. use OCP\Mail\IMailer;
  16. use OCP\Util;
  17. use Psr\Log\LoggerInterface;
  18. use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin;
  19. use Sabre\DAV;
  20. use Sabre\DAV\INode;
  21. use Sabre\VObject\Component\VCalendar;
  22. use Sabre\VObject\Component\VEvent;
  23. use Sabre\VObject\ITip\Message;
  24. use Sabre\VObject\Parameter;
  25. use Sabre\VObject\Reader;
  26. /**
  27. * iMIP handler.
  28. *
  29. * This class is responsible for sending out iMIP messages. iMIP is the
  30. * email-based transport for iTIP. iTIP deals with scheduling operations for
  31. * iCalendar objects.
  32. *
  33. * If you want to customize the email that gets sent out, you can do so by
  34. * extending this class and overriding the sendMessage method.
  35. *
  36. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  37. * @author Evert Pot (http://evertpot.com/)
  38. * @license http://sabre.io/license/ Modified BSD License
  39. */
  40. class IMipPlugin extends SabreIMipPlugin {
  41. private IUserSession $userSession;
  42. private IConfig $config;
  43. private IMailer $mailer;
  44. private LoggerInterface $logger;
  45. private ITimeFactory $timeFactory;
  46. private Defaults $defaults;
  47. private ?VCalendar $vCalendar = null;
  48. private IMipService $imipService;
  49. public const MAX_DATE = '2038-01-01';
  50. public const METHOD_REQUEST = 'request';
  51. public const METHOD_REPLY = 'reply';
  52. public const METHOD_CANCEL = 'cancel';
  53. public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
  54. private EventComparisonService $eventComparisonService;
  55. public function __construct(IConfig $config,
  56. IMailer $mailer,
  57. LoggerInterface $logger,
  58. ITimeFactory $timeFactory,
  59. Defaults $defaults,
  60. IUserSession $userSession,
  61. IMipService $imipService,
  62. EventComparisonService $eventComparisonService) {
  63. parent::__construct('');
  64. $this->userSession = $userSession;
  65. $this->config = $config;
  66. $this->mailer = $mailer;
  67. $this->logger = $logger;
  68. $this->timeFactory = $timeFactory;
  69. $this->defaults = $defaults;
  70. $this->imipService = $imipService;
  71. $this->eventComparisonService = $eventComparisonService;
  72. }
  73. public function initialize(DAV\Server $server): void {
  74. parent::initialize($server);
  75. $server->on('beforeWriteContent', [$this, 'beforeWriteContent'], 10);
  76. }
  77. /**
  78. * Check quota before writing content
  79. *
  80. * @param string $uri target file URI
  81. * @param INode $node Sabre Node
  82. * @param resource $data data
  83. * @param bool $modified modified
  84. */
  85. public function beforeWriteContent($uri, INode $node, $data, $modified): void {
  86. if(!$node instanceof CalendarObject) {
  87. return;
  88. }
  89. /** @var VCalendar $vCalendar */
  90. $vCalendar = Reader::read($node->get());
  91. $this->setVCalendar($vCalendar);
  92. }
  93. /**
  94. * Event handler for the 'schedule' event.
  95. *
  96. * @param Message $iTipMessage
  97. * @return void
  98. */
  99. public function schedule(Message $iTipMessage) {
  100. // Not sending any emails if the system considers the update
  101. // insignificant.
  102. if (!$iTipMessage->significantChange) {
  103. if (!$iTipMessage->scheduleStatus) {
  104. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  105. }
  106. return;
  107. }
  108. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto'
  109. || parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  110. return;
  111. }
  112. // don't send out mails for events that already took place
  113. $lastOccurrence = $this->imipService->getLastOccurrence($iTipMessage->message);
  114. $currentTime = $this->timeFactory->getTime();
  115. if ($lastOccurrence < $currentTime) {
  116. return;
  117. }
  118. // Strip off mailto:
  119. $recipient = substr($iTipMessage->recipient, 7);
  120. if (!$this->mailer->validateMailAddress($recipient)) {
  121. // Nothing to send if the recipient doesn't have a valid email address
  122. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  123. return;
  124. }
  125. $recipientName = $iTipMessage->recipientName ? (string)$iTipMessage->recipientName : null;
  126. $newEvents = $iTipMessage->message;
  127. $oldEvents = $this->getVCalendar();
  128. $modified = $this->eventComparisonService->findModified($newEvents, $oldEvents);
  129. /** @var VEvent $vEvent */
  130. $vEvent = array_pop($modified['new']);
  131. /** @var VEvent $oldVevent */
  132. $oldVevent = !empty($modified['old']) && is_array($modified['old']) ? array_pop($modified['old']) : null;
  133. $isModified = isset($oldVevent);
  134. // No changed events after all - this shouldn't happen if there is significant change yet here we are
  135. // The scheduling status is debatable
  136. if(empty($vEvent)) {
  137. $this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents');
  138. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  139. return;
  140. }
  141. // we (should) have one event component left
  142. // as the ITip\Broker creates one iTip message per change
  143. // and triggers the "schedule" event once per message
  144. // we also might not have an old event as this could be a new
  145. // invitation, or a new recurrence exception
  146. $attendee = $this->imipService->getCurrentAttendee($iTipMessage);
  147. if($attendee === null) {
  148. $uid = $vEvent->UID ?? 'no UID found';
  149. $this->logger->debug('Could not find recipient ' . $recipient . ' as attendee for event with UID ' . $uid);
  150. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  151. return;
  152. }
  153. // Don't send emails to things
  154. if($this->imipService->isRoomOrResource($attendee)) {
  155. $this->logger->debug('No invitation sent as recipient is room or resource', [
  156. 'attendee' => $recipient,
  157. ]);
  158. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  159. return;
  160. }
  161. $this->imipService->setL10n($attendee);
  162. // Build the sender name.
  163. // Due to a bug in sabre, the senderName property for an iTIP message can actually also be a VObject Property
  164. // If the iTIP message senderName is null or empty use the user session name as the senderName
  165. if (($iTipMessage->senderName instanceof Parameter) && !empty(trim($iTipMessage->senderName->getValue()))) {
  166. $senderName = trim($iTipMessage->senderName->getValue());
  167. } elseif (is_string($iTipMessage->senderName) && !empty(trim($iTipMessage->senderName))) {
  168. $senderName = trim($iTipMessage->senderName);
  169. } elseif ($this->userSession->getUser() !== null) {
  170. $senderName = trim($this->userSession->getUser()->getDisplayName());
  171. } else {
  172. $senderName = '';
  173. }
  174. $sender = substr($iTipMessage->sender, 7);
  175. $replyingAttendee = null;
  176. switch (strtolower($iTipMessage->method)) {
  177. case self::METHOD_REPLY:
  178. $method = self::METHOD_REPLY;
  179. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  180. $replyingAttendee = $this->imipService->getReplyingAttendee($iTipMessage);
  181. break;
  182. case self::METHOD_CANCEL:
  183. $method = self::METHOD_CANCEL;
  184. $data = $this->imipService->buildCancelledBodyData($vEvent);
  185. break;
  186. default:
  187. $method = self::METHOD_REQUEST;
  188. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  189. break;
  190. }
  191. $data['attendee_name'] = ($recipientName ?: $recipient);
  192. $data['invitee_name'] = ($senderName ?: $sender);
  193. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  194. $fromName = $this->imipService->getFrom($senderName, $this->defaults->getName());
  195. $message = $this->mailer->createMessage()
  196. ->setFrom([$fromEMail => $fromName]);
  197. if ($recipientName !== null) {
  198. $message->setTo([$recipient => $recipientName]);
  199. } else {
  200. $message->setTo([$recipient]);
  201. }
  202. if ($senderName !== null) {
  203. $message->setReplyTo([$sender => $senderName]);
  204. } else {
  205. $message->setReplyTo([$sender]);
  206. }
  207. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  208. $template->addHeader();
  209. $this->imipService->addSubjectAndHeading($template, $method, $data['invitee_name'], $data['meeting_title'], $isModified, $replyingAttendee);
  210. $this->imipService->addBulletList($template, $vEvent, $data);
  211. // Only add response buttons to invitation requests: Fix Issue #11230
  212. if (strcasecmp($method, self::METHOD_REQUEST) === 0 && $this->imipService->getAttendeeRsvpOrReqForParticipant($attendee)) {
  213. /*
  214. ** Only offer invitation accept/reject buttons, which link back to the
  215. ** nextcloud server, to recipients who can access the nextcloud server via
  216. ** their internet/intranet. Issue #12156
  217. **
  218. ** The app setting is stored in the appconfig database table.
  219. **
  220. ** For nextcloud servers accessible to the public internet, the default
  221. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  222. **
  223. ** When the nextcloud server is restricted behind a firewall, accessible
  224. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  225. ** to the email address or email domain, or comma separated list of addresses or domains,
  226. ** of recipients who can access the server.
  227. **
  228. ** To always deliver URLs, set invitation_link_recipients to "yes".
  229. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  230. */
  231. $recipientDomain = substr(strrchr($recipient, '@'), 1);
  232. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  233. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  234. || in_array(strtolower($recipient), $invitationLinkRecipients)
  235. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  236. $token = $this->imipService->createInvitationToken($iTipMessage, $vEvent, $lastOccurrence);
  237. $this->imipService->addResponseButtons($template, $token);
  238. $this->imipService->addMoreOptionsButton($template, $token);
  239. }
  240. }
  241. $template->addFooter();
  242. $message->useTemplate($template);
  243. $itip_msg = $iTipMessage->message->serialize();
  244. $message->attachInline(
  245. $itip_msg,
  246. 'event.ics',
  247. 'text/calendar; method=' . $iTipMessage->method,
  248. );
  249. try {
  250. $failed = $this->mailer->send($message);
  251. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  252. if (!empty($failed)) {
  253. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  254. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  255. }
  256. } catch (\Exception $ex) {
  257. $this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
  258. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  259. }
  260. }
  261. /**
  262. * @return ?VCalendar
  263. */
  264. public function getVCalendar(): ?VCalendar {
  265. return $this->vCalendar;
  266. }
  267. /**
  268. * @param ?VCalendar $vCalendar
  269. */
  270. public function setVCalendar(?VCalendar $vCalendar): void {
  271. $this->vCalendar = $vCalendar;
  272. }
  273. }