IMipPlugin.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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\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 IConfig $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
  92. // insignificant.
  93. if (!$iTipMessage->significantChange) {
  94. if (!$iTipMessage->scheduleStatus) {
  95. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  96. }
  97. return;
  98. }
  99. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto'
  100. || parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  101. return;
  102. }
  103. // don't send out mails for events that already took place
  104. $lastOccurrence = $this->imipService->getLastOccurrence($iTipMessage->message);
  105. $currentTime = $this->timeFactory->getTime();
  106. if ($lastOccurrence < $currentTime) {
  107. return;
  108. }
  109. // Strip off mailto:
  110. $recipient = substr($iTipMessage->recipient, 7);
  111. if (!$this->mailer->validateMailAddress($recipient)) {
  112. // Nothing to send if the recipient doesn't have a valid email address
  113. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  114. return;
  115. }
  116. $recipientName = $iTipMessage->recipientName ? (string)$iTipMessage->recipientName : null;
  117. $newEvents = $iTipMessage->message;
  118. $oldEvents = $this->getVCalendar();
  119. $modified = $this->eventComparisonService->findModified($newEvents, $oldEvents);
  120. /** @var VEvent $vEvent */
  121. $vEvent = array_pop($modified['new']);
  122. /** @var VEvent $oldVevent */
  123. $oldVevent = !empty($modified['old']) && is_array($modified['old']) ? array_pop($modified['old']) : null;
  124. $isModified = isset($oldVevent);
  125. // No changed events after all - this shouldn't happen if there is significant change yet here we are
  126. // The scheduling status is debatable
  127. if (empty($vEvent)) {
  128. $this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents');
  129. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  130. return;
  131. }
  132. // we (should) have one event component left
  133. // as the ITip\Broker creates one iTip message per change
  134. // and triggers the "schedule" event once per message
  135. // we also might not have an old event as this could be a new
  136. // invitation, or a new recurrence exception
  137. $attendee = $this->imipService->getCurrentAttendee($iTipMessage);
  138. if ($attendee === null) {
  139. $uid = $vEvent->UID ?? 'no UID found';
  140. $this->logger->debug('Could not find recipient ' . $recipient . ' as attendee for event with UID ' . $uid);
  141. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  142. return;
  143. }
  144. // Don't send emails to things
  145. if ($this->imipService->isRoomOrResource($attendee)) {
  146. $this->logger->debug('No invitation sent as recipient is room or resource', [
  147. 'attendee' => $recipient,
  148. ]);
  149. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  150. return;
  151. }
  152. $this->imipService->setL10n($attendee);
  153. // Build the sender name.
  154. // Due to a bug in sabre, the senderName property for an iTIP message can actually also be a VObject Property
  155. // If the iTIP message senderName is null or empty use the user session name as the senderName
  156. if (($iTipMessage->senderName instanceof Parameter) && !empty(trim($iTipMessage->senderName->getValue()))) {
  157. $senderName = trim($iTipMessage->senderName->getValue());
  158. } elseif (is_string($iTipMessage->senderName) && !empty(trim($iTipMessage->senderName))) {
  159. $senderName = trim($iTipMessage->senderName);
  160. } elseif ($this->userSession->getUser() !== null) {
  161. $senderName = trim($this->userSession->getUser()->getDisplayName());
  162. } else {
  163. $senderName = '';
  164. }
  165. $sender = substr($iTipMessage->sender, 7);
  166. $replyingAttendee = null;
  167. switch (strtolower($iTipMessage->method)) {
  168. case self::METHOD_REPLY:
  169. $method = self::METHOD_REPLY;
  170. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  171. $replyingAttendee = $this->imipService->getReplyingAttendee($iTipMessage);
  172. break;
  173. case self::METHOD_CANCEL:
  174. $method = self::METHOD_CANCEL;
  175. $data = $this->imipService->buildCancelledBodyData($vEvent);
  176. break;
  177. default:
  178. $method = self::METHOD_REQUEST;
  179. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  180. break;
  181. }
  182. $data['attendee_name'] = ($recipientName ?: $recipient);
  183. $data['invitee_name'] = ($senderName ?: $sender);
  184. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  185. $fromName = $this->imipService->getFrom($senderName, $this->defaults->getName());
  186. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  187. $template->addHeader();
  188. $this->imipService->addSubjectAndHeading($template, $method, $data['invitee_name'], $data['meeting_title'], $isModified, $replyingAttendee);
  189. $this->imipService->addBulletList($template, $vEvent, $data);
  190. // Only add response buttons to invitation requests: Fix Issue #11230
  191. if (strcasecmp($method, self::METHOD_REQUEST) === 0 && $this->imipService->getAttendeeRsvpOrReqForParticipant($attendee)) {
  192. /*
  193. ** Only offer invitation accept/reject buttons, which link back to the
  194. ** nextcloud server, to recipients who can access the nextcloud server via
  195. ** their internet/intranet. Issue #12156
  196. **
  197. ** The app setting is stored in the appconfig database table.
  198. **
  199. ** For nextcloud servers accessible to the public internet, the default
  200. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  201. **
  202. ** When the nextcloud server is restricted behind a firewall, accessible
  203. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  204. ** to the email address or email domain, or comma separated list of addresses or domains,
  205. ** of recipients who can access the server.
  206. **
  207. ** To always deliver URLs, set invitation_link_recipients to "yes".
  208. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  209. */
  210. $recipientDomain = substr(strrchr($recipient, '@'), 1);
  211. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  212. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  213. || in_array(strtolower($recipient), $invitationLinkRecipients)
  214. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  215. $token = $this->imipService->createInvitationToken($iTipMessage, $vEvent, $lastOccurrence);
  216. $this->imipService->addResponseButtons($template, $token);
  217. $this->imipService->addMoreOptionsButton($template, $token);
  218. }
  219. }
  220. $template->addFooter();
  221. // convert iTip Message to string
  222. $itip_msg = $iTipMessage->message->serialize();
  223. $user = null;
  224. $mailService = null;
  225. try {
  226. // retrieve user object
  227. $user = $this->userSession->getUser();
  228. // evaluate if user object exist
  229. if ($user !== null) {
  230. // retrieve appropriate service with the same address as sender
  231. $mailService = $this->mailManager->findServiceByAddress($user->getUID(), $sender);
  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. }