IMipPlugin.php 12 KB

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