IMipPlugin.php 12 KB

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