IMipPlugin.php 12 KB

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