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

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