IMipPlugin.php 13 KB

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