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

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\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. // Not sending any emails if the system considers the update
  130. // insignificant.
  131. if (!$iTipMessage->significantChange) {
  132. if (!$iTipMessage->scheduleStatus) {
  133. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  134. }
  135. return;
  136. }
  137. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto'
  138. || parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  139. return;
  140. }
  141. // don't send out mails for events that already took place
  142. $lastOccurrence = $this->imipService->getLastOccurrence($iTipMessage->message);
  143. $currentTime = $this->timeFactory->getTime();
  144. if ($lastOccurrence < $currentTime) {
  145. return;
  146. }
  147. // Strip off mailto:
  148. $recipient = substr($iTipMessage->recipient, 7);
  149. if (!$this->mailer->validateMailAddress($recipient)) {
  150. // Nothing to send if the recipient doesn't have a valid email address
  151. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  152. return;
  153. }
  154. $recipientName = $iTipMessage->recipientName ? (string)$iTipMessage->recipientName : null;
  155. $newEvents = $iTipMessage->message;
  156. $oldEvents = $this->getVCalendar();
  157. $modified = $this->eventComparisonService->findModified($newEvents, $oldEvents);
  158. /** @var VEvent $vEvent */
  159. $vEvent = array_pop($modified['new']);
  160. /** @var VEvent $oldVevent */
  161. $oldVevent = !empty($modified['old']) && is_array($modified['old']) ? array_pop($modified['old']) : null;
  162. $isModified = isset($oldVevent);
  163. // No changed events after all - this shouldn't happen if there is significant change yet here we are
  164. // The scheduling status is debatable
  165. if(empty($vEvent)) {
  166. $this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents');
  167. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  168. return;
  169. }
  170. // we (should) have one event component left
  171. // as the ITip\Broker creates one iTip message per change
  172. // and triggers the "schedule" event once per message
  173. // we also might not have an old event as this could be a new
  174. // invitation, or a new recurrence exception
  175. $attendee = $this->imipService->getCurrentAttendee($iTipMessage);
  176. if($attendee === null) {
  177. $uid = $vEvent->UID ?? 'no UID found';
  178. $this->logger->debug('Could not find recipient ' . $recipient . ' as attendee for event with UID ' . $uid);
  179. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  180. return;
  181. }
  182. // Don't send emails to things
  183. if($this->imipService->isRoomOrResource($attendee)) {
  184. $this->logger->debug('No invitation sent as recipient is room or resource', [
  185. 'attendee' => $recipient,
  186. ]);
  187. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  188. return;
  189. }
  190. $this->imipService->setL10n($attendee);
  191. // Build the sender name.
  192. // Due to a bug in sabre, the senderName property for an iTIP message can actually also be a VObject Property
  193. // If the iTIP message senderName is null or empty use the user session name as the senderName
  194. if (($iTipMessage->senderName instanceof Parameter) && !empty(trim($iTipMessage->senderName->getValue()))) {
  195. $senderName = trim($iTipMessage->senderName->getValue());
  196. } elseif (is_string($iTipMessage->senderName) && !empty(trim($iTipMessage->senderName))) {
  197. $senderName = trim($iTipMessage->senderName);
  198. } elseif ($this->userSession->getUser() !== null) {
  199. $senderName = trim($this->userSession->getUser()->getDisplayName());
  200. } else {
  201. $senderName = '';
  202. }
  203. $sender = substr($iTipMessage->sender, 7);
  204. $replyingAttendee = null;
  205. switch (strtolower($iTipMessage->method)) {
  206. case self::METHOD_REPLY:
  207. $method = self::METHOD_REPLY;
  208. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  209. $replyingAttendee = $this->imipService->getReplyingAttendee($iTipMessage);
  210. break;
  211. case self::METHOD_CANCEL:
  212. $method = self::METHOD_CANCEL;
  213. $data = $this->imipService->buildCancelledBodyData($vEvent);
  214. break;
  215. default:
  216. $method = self::METHOD_REQUEST;
  217. $data = $this->imipService->buildBodyData($vEvent, $oldVevent);
  218. break;
  219. }
  220. $data['attendee_name'] = ($recipientName ?: $recipient);
  221. $data['invitee_name'] = ($senderName ?: $sender);
  222. $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
  223. $fromName = $this->imipService->getFrom($senderName, $this->defaults->getName());
  224. $message = $this->mailer->createMessage()
  225. ->setFrom([$fromEMail => $fromName]);
  226. if ($recipientName !== null) {
  227. $message->setTo([$recipient => $recipientName]);
  228. } else {
  229. $message->setTo([$recipient]);
  230. }
  231. if ($senderName !== null) {
  232. $message->setReplyTo([$sender => $senderName]);
  233. } else {
  234. $message->setReplyTo([$sender]);
  235. }
  236. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  237. $template->addHeader();
  238. $this->imipService->addSubjectAndHeading($template, $method, $data['invitee_name'], $data['meeting_title'], $isModified, $replyingAttendee);
  239. $this->imipService->addBulletList($template, $vEvent, $data);
  240. // Only add response buttons to invitation requests: Fix Issue #11230
  241. if (strcasecmp($method, self::METHOD_REQUEST) === 0 && $this->imipService->getAttendeeRsvpOrReqForParticipant($attendee)) {
  242. /*
  243. ** Only offer invitation accept/reject buttons, which link back to the
  244. ** nextcloud server, to recipients who can access the nextcloud server via
  245. ** their internet/intranet. Issue #12156
  246. **
  247. ** The app setting is stored in the appconfig database table.
  248. **
  249. ** For nextcloud servers accessible to the public internet, the default
  250. ** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
  251. **
  252. ** When the nextcloud server is restricted behind a firewall, accessible
  253. ** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
  254. ** to the email address or email domain, or comma separated list of addresses or domains,
  255. ** of recipients who can access the server.
  256. **
  257. ** To always deliver URLs, set invitation_link_recipients to "yes".
  258. ** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
  259. */
  260. $recipientDomain = substr(strrchr($recipient, '@'), 1);
  261. $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
  262. if (strcmp('yes', $invitationLinkRecipients[0]) === 0
  263. || in_array(strtolower($recipient), $invitationLinkRecipients)
  264. || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
  265. $token = $this->imipService->createInvitationToken($iTipMessage, $vEvent, $lastOccurrence);
  266. $this->imipService->addResponseButtons($template, $token);
  267. $this->imipService->addMoreOptionsButton($template, $token);
  268. }
  269. }
  270. $template->addFooter();
  271. $message->useTemplate($template);
  272. $itip_msg = $iTipMessage->message->serialize();
  273. $message->attachInline(
  274. $itip_msg,
  275. 'event.ics',
  276. 'text/calendar; method=' . $iTipMessage->method,
  277. );
  278. try {
  279. $failed = $this->mailer->send($message);
  280. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  281. if (!empty($failed)) {
  282. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  283. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  284. }
  285. } catch (\Exception $ex) {
  286. $this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
  287. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  288. }
  289. }
  290. /**
  291. * @return ?VCalendar
  292. */
  293. public function getVCalendar(): ?VCalendar {
  294. return $this->vCalendar;
  295. }
  296. /**
  297. * @param ?VCalendar $vCalendar
  298. */
  299. public function setVCalendar(?VCalendar $vCalendar): void {
  300. $this->vCalendar = $vCalendar;
  301. }
  302. }