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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 ?: 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. // No changed events after all - this shouldn't happen if there is significant change yet here we are
  176. // The scheduling status is debatable
  177. if(empty($vEvent)) {
  178. $this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents');
  179. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  180. return;
  181. }
  182. // we (should) have one event component left
  183. // as the ITip\Broker creates one iTip message per change
  184. // and triggers the "schedule" event once per message
  185. // we also might not have an old event as this could be a new
  186. // invitation, or a new recurrence exception
  187. $attendee = $this->imipService->getCurrentAttendee($iTipMessage);
  188. $this->imipService->setL10n($attendee);
  189. // Build the sender name.
  190. // Due to a bug in sabre, the senderName property for an iTIP message
  191. // can actually also be a VObject Property
  192. /** @var Parameter|string|null $senderName */
  193. $senderName = $iTipMessage->senderName ?: null;
  194. if($senderName instanceof Parameter) {
  195. $senderName = $senderName->getValue() ?? null;
  196. }
  197. if ($senderName === null || empty(trim($senderName))) {
  198. $senderName = $this->userManager->getDisplayName($this->userId);
  199. }
  200. $sender = substr($iTipMessage->sender, 7);
  201. switch (strtolower($iTipMessage->method)) {
  202. case self::METHOD_REPLY:
  203. $method = self::METHOD_REPLY;
  204. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  205. break;
  206. case self::METHOD_CANCEL:
  207. $method = self::METHOD_CANCEL;
  208. $data = $this->imipService->buildCancelledBodyData($vEvent);
  209. break;
  210. default:
  211. $method = self::METHOD_REQUEST;
  212. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  213. break;
  214. }
  215. $data['attendee_name'] = ($recipientName ?: $recipient);
  216. $data['invitee_name'] = ($senderName ?: $sender);
  217. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  218. $fromName = $this->imipService->getFrom($senderName, $this->defaults->getName());
  219. $message = $this->mailer->createMessage()
  220. ->setFrom([$fromEMail => $fromName])
  221. ->setTo([$recipient => $recipientName])
  222. ->setReplyTo([$sender => $senderName]);
  223. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  224. $template->addHeader();
  225. $this->imipService->addSubjectAndHeading($template, $method, $data['invitee_name'], $data['meeting_title']);
  226. $this->imipService->addBulletList($template, $vEvent, $data);
  227. // Only add response buttons to invitation requests: Fix Issue #11230
  228. if (strcasecmp($method, self::METHOD_REQUEST) === 0 && $this->imipService->getAttendeeRsvpOrReqForParticipant($attendee)) {
  229. /*
  230. ** Only offer invitation accept/reject buttons, which link back to the
  231. ** nextcloud server, to recipients who can access the nextcloud server via
  232. ** their internet/intranet. Issue #12156
  233. **
  234. ** The app setting is stored in the appconfig database table.
  235. **
  236. ** For nextcloud servers accessible to the public internet, the default
  237. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  238. **
  239. ** When the nextcloud server is restricted behind a firewall, accessible
  240. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  241. ** to the email address or email domain, or comma separated list of addresses or domains,
  242. ** of recipients who can access the server.
  243. **
  244. ** To always deliver URLs, set invitation_link_recipients to "yes".
  245. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  246. */
  247. $recipientDomain = substr(strrchr($recipient, '@'), 1);
  248. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  249. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  250. || in_array(strtolower($recipient), $invitationLinkRecipients)
  251. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  252. $token = $this->imipService->createInvitationToken($iTipMessage, $vEvent, $lastOccurrence);
  253. $this->imipService->addResponseButtons($template, $token);
  254. $this->imipService->addMoreOptionsButton($template, $token);
  255. }
  256. }
  257. $template->addFooter();
  258. $message->useTemplate($template);
  259. $vCalendar = $this->imipService->generateVCalendar($iTipMessage, $vEvent);
  260. $attachment = $this->mailer->createAttachment(
  261. $vCalendar->serialize(),
  262. 'event.ics',
  263. 'text/calendar; method=' . $iTipMessage->method
  264. );
  265. $message->attach($attachment);
  266. try {
  267. $failed = $this->mailer->send($message);
  268. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  269. if (!empty($failed)) {
  270. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  271. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  272. }
  273. } catch (\Exception $ex) {
  274. $this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
  275. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  276. }
  277. }
  278. /**
  279. * @return ?VCalendar
  280. */
  281. public function getVCalendar(): ?VCalendar {
  282. return $this->vCalendar;
  283. }
  284. /**
  285. * @param ?VCalendar $vCalendar
  286. */
  287. public function setVCalendar(?VCalendar $vCalendar): void {
  288. $this->vCalendar = $vCalendar;
  289. }
  290. }