migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,340 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @copyright Copyright (c) 2017, Georg Ehrke
* @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
* @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
* @copyright 2022 Anna Larch <anna.larch@gmx.net>
*
* @author brad2014 <brad2014@users.noreply.github.com>
* @author Brad Rubenstein <brad@wbr.tech>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Leon Klingele <leon@struktur.de>
* @author Nick Sweeting <git@sweeting.me>
* @author rakekniven <mark.ziegler@rakekniven.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Anna Larch <anna.larch@gmx.net>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\CalDAV\Schedule;
use OCA\DAV\CalDAV\CalendarObject;
use OCA\DAV\CalDAV\EventComparisonService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\Mail\IMailer;
use OCP\Util;
use Psr\Log\LoggerInterface;
use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin;
use Sabre\DAV;
use Sabre\DAV\INode;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\ITip\Message;
use Sabre\VObject\Parameter;
use Sabre\VObject\Reader;
/**
* iMIP handler.
*
* This class is responsible for sending out iMIP messages. iMIP is the
* email-based transport for iTIP. iTIP deals with scheduling operations for
* iCalendar objects.
*
* If you want to customize the email that gets sent out, you can do so by
* extending this class and overriding the sendMessage method.
*
* @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
* @author Evert Pot (http://evertpot.com/)
* @license http://sabre.io/license/ Modified BSD License
*/
class IMipPlugin extends SabreIMipPlugin {
private ?string $userId;
private IConfig $config;
private IMailer $mailer;
private LoggerInterface $logger;
private ITimeFactory $timeFactory;
private Defaults $defaults;
private IUserManager $userManager;
private ?VCalendar $vCalendar = null;
private IMipService $imipService;
public const MAX_DATE = '2038-01-01';
public const METHOD_REQUEST = 'request';
public const METHOD_REPLY = 'reply';
public const METHOD_CANCEL = 'cancel';
public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
private EventComparisonService $eventComparisonService;
public function __construct(IConfig $config,
IMailer $mailer,
LoggerInterface $logger,
ITimeFactory $timeFactory,
Defaults $defaults,
IUserManager $userManager,
$userId,
IMipService $imipService,
EventComparisonService $eventComparisonService) {
parent::__construct('');
$this->userId = $userId;
$this->config = $config;
$this->mailer = $mailer;
$this->logger = $logger;
$this->timeFactory = $timeFactory;
$this->defaults = $defaults;
$this->userManager = $userManager;
$this->imipService = $imipService;
$this->eventComparisonService = $eventComparisonService;
}
public function initialize(DAV\Server $server): void {
parent::initialize($server);
$server->on('beforeWriteContent', [$this, 'beforeWriteContent'], 10);
}
/**
* Check quota before writing content
*
* @param string $uri target file URI
* @param INode $node Sabre Node
* @param resource $data data
* @param bool $modified modified
*/
public function beforeWriteContent($uri, INode $node, $data, $modified): void {
if(!$node instanceof CalendarObject) {
return;
}
/** @var VCalendar $vCalendar */
$vCalendar = Reader::read($node->get());
$this->setVCalendar($vCalendar);
}
/**
* Event handler for the 'schedule' event.
*
* @param Message $iTipMessage
* @return void
*/
public function schedule(Message $iTipMessage) {
// Not sending any emails if the system considers the update
// insignificant.
if (!$iTipMessage->significantChange) {
if (!$iTipMessage->scheduleStatus) {
$iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
}
return;
}
if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto'
|| parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
return;
}
// don't send out mails for events that already took place
$lastOccurrence = $this->imipService->getLastOccurrence($iTipMessage->message);
$currentTime = $this->timeFactory->getTime();
if ($lastOccurrence < $currentTime) {
return;
}
// Strip off mailto:
$recipient = substr($iTipMessage->recipient, 7);
if (!$this->mailer->validateMailAddress($recipient)) {
// Nothing to send if the recipient doesn't have a valid email address
$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
return;
}
$recipientName = $iTipMessage->recipientName ? (string)$iTipMessage->recipientName : null;
$newEvents = $iTipMessage->message;
$oldEvents = $this->getVCalendar();
$modified = $this->eventComparisonService->findModified($newEvents, $oldEvents);
/** @var VEvent $vEvent */
$vEvent = array_pop($modified['new']);
/** @var VEvent $oldVevent */
$oldVevent = !empty($modified['old']) && is_array($modified['old']) ? array_pop($modified['old']) : null;
$isModified = isset($oldVevent);
// No changed events after all - this shouldn't happen if there is significant change yet here we are
// The scheduling status is debatable
if(empty($vEvent)) {
$this->logger->warning('iTip message said the change was significant but comparison did not detect any updated VEvents');
$iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
return;
}
// we (should) have one event component left
// as the ITip\Broker creates one iTip message per change
// and triggers the "schedule" event once per message
// we also might not have an old event as this could be a new
// invitation, or a new recurrence exception
$attendee = $this->imipService->getCurrentAttendee($iTipMessage);
if($attendee === null) {
$uid = $vEvent->UID ?? 'no UID found';
$this->logger->debug('Could not find recipient ' . $recipient . ' as attendee for event with UID ' . $uid);
$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
return;
}
// Don't send emails to things
if($this->imipService->isRoomOrResource($attendee)) {
$this->logger->debug('No invitation sent as recipient is room or resource', [
'attendee' => $recipient,
]);
$iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
return;
}
$this->imipService->setL10n($attendee);
// Build the sender name.
// Due to a bug in sabre, the senderName property for an iTIP message
// can actually also be a VObject Property
/** @var Parameter|string|null $senderName */
$senderName = $iTipMessage->senderName ?: null;
if($senderName instanceof Parameter) {
$senderName = $senderName->getValue() ?? null;
}
// Try to get the sender name from the current user id if available.
if ($this->userId !== null && ($senderName === null || empty(trim($senderName)))) {
$senderName = $this->userManager->getDisplayName($this->userId);
}
$sender = substr($iTipMessage->sender, 7);
$replyingAttendee = null;
switch (strtolower($iTipMessage->method)) {
case self::METHOD_REPLY:
$method = self::METHOD_REPLY;
$data = $this->imipService->buildBodyData($vEvent, $oldVevent);
$replyingAttendee = $this->imipService->getReplyingAttendee($iTipMessage);
break;
case self::METHOD_CANCEL:
$method = self::METHOD_CANCEL;
$data = $this->imipService->buildCancelledBodyData($vEvent);
break;
default:
$method = self::METHOD_REQUEST;
$data = $this->imipService->buildBodyData($vEvent, $oldVevent);
break;
}
$data['attendee_name'] = ($recipientName ?: $recipient);
$data['invitee_name'] = ($senderName ?: $sender);
$fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
$fromName = $this->imipService->getFrom($senderName, $this->defaults->getName());
$message = $this->mailer->createMessage()
->setFrom([$fromEMail => $fromName]);
if ($recipientName !== null) {
$message->setTo([$recipient => $recipientName]);
} else {
$message->setTo([$recipient]);
}
if ($senderName !== null) {
$message->setReplyTo([$sender => $senderName]);
} else {
$message->setReplyTo([$sender]);
}
$template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
$template->addHeader();
$this->imipService->addSubjectAndHeading($template, $method, $data['invitee_name'], $data['meeting_title'], $isModified, $replyingAttendee);
$this->imipService->addBulletList($template, $vEvent, $data);
// Only add response buttons to invitation requests: Fix Issue #11230
if (strcasecmp($method, self::METHOD_REQUEST) === 0 && $this->imipService->getAttendeeRsvpOrReqForParticipant($attendee)) {
/*
** Only offer invitation accept/reject buttons, which link back to the
** nextcloud server, to recipients who can access the nextcloud server via
** their internet/intranet. Issue #12156
**
** The app setting is stored in the appconfig database table.
**
** For nextcloud servers accessible to the public internet, the default
** "invitation_link_recipients" value "yes" (all recipients) is appropriate.
**
** When the nextcloud server is restricted behind a firewall, accessible
** only via an internal network or via vpn, you can set "dav.invitation_link_recipients"
** to the email address or email domain, or comma separated list of addresses or domains,
** of recipients who can access the server.
**
** To always deliver URLs, set invitation_link_recipients to "yes".
** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
*/
$recipientDomain = substr(strrchr($recipient, '@'), 1);
$invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
if (strcmp('yes', $invitationLinkRecipients[0]) === 0
|| in_array(strtolower($recipient), $invitationLinkRecipients)
|| in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
$token = $this->imipService->createInvitationToken($iTipMessage, $vEvent, $lastOccurrence);
$this->imipService->addResponseButtons($template, $token);
$this->imipService->addMoreOptionsButton($template, $token);
}
}
$template->addFooter();
$message->useTemplate($template);
$itip_msg = $iTipMessage->message->serialize();
$message->attachInline(
$itip_msg,
'event.ics',
'text/calendar; method=' . $iTipMessage->method,
);
try {
$failed = $this->mailer->send($message);
$iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
if (!empty($failed)) {
$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
}
} catch (\Exception $ex) {
$this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
}
}
/**
* @return ?VCalendar
*/
public function getVCalendar(): ?VCalendar {
return $this->vCalendar;
}
/**
* @param ?VCalendar $vCalendar
*/
public function setVCalendar(?VCalendar $vCalendar): void {
$this->vCalendar = $vCalendar;
}
}
@@ -0,0 +1,691 @@
<?php
declare(strict_types=1);
/*
* DAV App
*
* @copyright 2022 Anna Larch <anna.larch@gmx.net>
*
* @author Anna Larch <anna.larch@gmx.net>
* @author Richard Steinmetz <richard@steinmetz.cloud>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCA\DAV\CalDAV\Schedule;
use OC\URLGenerator;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IL10N;
use OCP\L10N\IFactory as L10NFactory;
use OCP\Mail\IEMailTemplate;
use OCP\Security\ISecureRandom;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\ITip\Message;
use Sabre\VObject\Parameter;
use Sabre\VObject\Property;
use Sabre\VObject\Recur\EventIterator;
class IMipService {
private URLGenerator $urlGenerator;
private IConfig $config;
private IDBConnection $db;
private ISecureRandom $random;
private L10NFactory $l10nFactory;
private IL10N $l10n;
/** @var string[] */
private const STRING_DIFF = [
'meeting_title' => 'SUMMARY',
'meeting_description' => 'DESCRIPTION',
'meeting_url' => 'URL',
'meeting_location' => 'LOCATION'
];
public function __construct(URLGenerator $urlGenerator,
IConfig $config,
IDBConnection $db,
ISecureRandom $random,
L10NFactory $l10nFactory) {
$this->urlGenerator = $urlGenerator;
$this->config = $config;
$this->db = $db;
$this->random = $random;
$this->l10nFactory = $l10nFactory;
$default = $this->l10nFactory->findGenericLanguage();
$this->l10n = $this->l10nFactory->get('dav', $default);
}
/**
* @param string|null $senderName
* @param string $default
* @return string
*/
public function getFrom(?string $senderName, string $default): string {
if ($senderName === null) {
return $default;
}
return $this->l10n->t('%1$s via %2$s', [$senderName, $default]);
}
public static function readPropertyWithDefault(VEvent $vevent, string $property, string $default) {
if (isset($vevent->$property)) {
$value = $vevent->$property->getValue();
if (!empty($value)) {
return $value;
}
}
return $default;
}
private function generateDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
$strikethrough = "<span style='text-decoration: line-through'>%s</span><br />%s";
if (!isset($vevent->$property)) {
return $default;
}
$newstring = $vevent->$property->getValue();
if(isset($oldVEvent->$property) && $oldVEvent->$property->getValue() !== $newstring) {
$oldstring = $oldVEvent->$property->getValue();
return sprintf($strikethrough, $oldstring, $newstring);
}
return $newstring;
}
/**
* Like generateDiffString() but linkifies the property values if they are urls.
*/
private function generateLinkifiedDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
if (!isset($vevent->$property)) {
return $default;
}
/** @var string|null $newString */
$newString = $vevent->$property->getValue();
$oldString = isset($oldVEvent->$property) ? $oldVEvent->$property->getValue() : null;
if ($oldString !== $newString) {
return sprintf(
"<span style='text-decoration: line-through'>%s</span><br />%s",
$this->linkify($oldString) ?? $oldString ?? '',
$this->linkify($newString) ?? $newString ?? ''
);
}
return $this->linkify($newString) ?? $newString;
}
/**
* Convert a given url to a html link element or return null otherwise.
*/
private function linkify(?string $url): ?string {
if ($url === null) {
return null;
}
if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
return null;
}
return sprintf('<a href="%1$s">%1$s</a>', htmlspecialchars($url));
}
/**
* @param VEvent $vEvent
* @param VEvent|null $oldVEvent
* @return array
*/
public function buildBodyData(VEvent $vEvent, ?VEvent $oldVEvent): array {
$defaultVal = '';
$data = [];
$data['meeting_when'] = $this->generateWhenString($vEvent);
foreach(self::STRING_DIFF as $key => $property) {
$data[$key] = self::readPropertyWithDefault($vEvent, $property, $defaultVal);
}
$data['meeting_url_html'] = self::readPropertyWithDefault($vEvent, 'URL', $defaultVal);
if (($locationHtml = $this->linkify($data['meeting_location'])) !== null) {
$data['meeting_location_html'] = $locationHtml;
}
if(!empty($oldVEvent)) {
$oldMeetingWhen = $this->generateWhenString($oldVEvent);
$data['meeting_title_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'SUMMARY', $data['meeting_title']);
$data['meeting_description_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'DESCRIPTION', $data['meeting_description']);
$data['meeting_location_html'] = $this->generateLinkifiedDiffString($vEvent, $oldVEvent, 'LOCATION', $data['meeting_location']);
$oldUrl = self::readPropertyWithDefault($oldVEvent, 'URL', $defaultVal);
$data['meeting_url_html'] = !empty($oldUrl) && $oldUrl !== $data['meeting_url'] ? sprintf('<a href="%1$s">%1$s</a>', $oldUrl) : $data['meeting_url'];
$data['meeting_when_html'] =
($oldMeetingWhen !== $data['meeting_when'] && $oldMeetingWhen !== null)
? sprintf("<span style='text-decoration: line-through'>%s</span><br />%s", $oldMeetingWhen, $data['meeting_when'])
: $data['meeting_when'];
}
return $data;
}
/**
* @param IL10N $this->l10n
* @param VEvent $vevent
* @return false|int|string
*/
public function generateWhenString(VEvent $vevent) {
/** @var Property\ICalendar\DateTime $dtstart */
$dtstart = $vevent->DTSTART;
if (isset($vevent->DTEND)) {
/** @var Property\ICalendar\DateTime $dtend */
$dtend = $vevent->DTEND;
} elseif (isset($vevent->DURATION)) {
$isFloating = $dtstart->isFloating();
$dtend = clone $dtstart;
$endDateTime = $dtend->getDateTime();
$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
$dtend->setDateTime($endDateTime, $isFloating);
} elseif (!$dtstart->hasTime()) {
$isFloating = $dtstart->isFloating();
$dtend = clone $dtstart;
$endDateTime = $dtend->getDateTime();
$endDateTime = $endDateTime->modify('+1 day');
$dtend->setDateTime($endDateTime, $isFloating);
} else {
$dtend = clone $dtstart;
}
/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
/** @var \DateTimeImmutable $dtstartDt */
$dtstartDt = $dtstart->getDateTime();
/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
/** @var \DateTimeImmutable $dtendDt */
$dtendDt = $dtend->getDateTime();
$diff = $dtstartDt->diff($dtendDt);
$dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM));
$dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM));
if ($dtstart instanceof Property\ICalendar\Date) {
// One day event
if ($diff->days === 1) {
return $this->l10n->l('date', $dtstartDt, ['width' => 'medium']);
}
// DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
// the email should show 2020-01-01 to 2020-01-04.
$dtendDt->modify('-1 day');
//event that spans over multiple days
$localeStart = $this->l10n->l('date', $dtstartDt, ['width' => 'medium']);
$localeEnd = $this->l10n->l('date', $dtendDt, ['width' => 'medium']);
return $localeStart . ' - ' . $localeEnd;
}
/** @var Property\ICalendar\DateTime $dtstart */
/** @var Property\ICalendar\DateTime $dtend */
$isFloating = $dtstart->isFloating();
$startTimezone = $endTimezone = null;
if (!$isFloating) {
$prop = $dtstart->offsetGet('TZID');
if ($prop instanceof Parameter) {
$startTimezone = $prop->getValue();
}
$prop = $dtend->offsetGet('TZID');
if ($prop instanceof Parameter) {
$endTimezone = $prop->getValue();
}
}
$localeStart = $this->l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
$this->l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
// always show full date with timezone if timezones are different
if ($startTimezone !== $endTimezone) {
$localeEnd = $this->l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
return $localeStart . ' (' . $startTimezone . ') - ' .
$localeEnd . ' (' . $endTimezone . ')';
}
// show only end time if date is the same
if ($dtstartDt->format('Y-m-d') === $dtendDt->format('Y-m-d')) {
$localeEnd = $this->l10n->l('time', $dtendDt, ['width' => 'short']);
} else {
$localeEnd = $this->l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
$this->l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
}
return $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
}
/**
* @param VEvent $vEvent
* @return array
*/
public function buildCancelledBodyData(VEvent $vEvent): array {
$defaultVal = '';
$strikethrough = "<span style='text-decoration: line-through'>%s</span>";
$newMeetingWhen = $this->generateWhenString($vEvent);
$newSummary = isset($vEvent->SUMMARY) && (string)$vEvent->SUMMARY !== '' ? (string)$vEvent->SUMMARY : $this->l10n->t('Untitled event');
;
$newDescription = isset($vEvent->DESCRIPTION) && (string)$vEvent->DESCRIPTION !== '' ? (string)$vEvent->DESCRIPTION : $defaultVal;
$newUrl = isset($vEvent->URL) && (string)$vEvent->URL !== '' ? sprintf('<a href="%1$s">%1$s</a>', $vEvent->URL) : $defaultVal;
$newLocation = isset($vEvent->LOCATION) && (string)$vEvent->LOCATION !== '' ? (string)$vEvent->LOCATION : $defaultVal;
$newLocationHtml = $this->linkify($newLocation) ?? $newLocation;
$data = [];
$data['meeting_when_html'] = $newMeetingWhen === '' ?: sprintf($strikethrough, $newMeetingWhen);
$data['meeting_when'] = $newMeetingWhen;
$data['meeting_title_html'] = sprintf($strikethrough, $newSummary);
$data['meeting_title'] = $newSummary !== '' ? $newSummary: $this->l10n->t('Untitled event');
$data['meeting_description_html'] = $newDescription !== '' ? sprintf($strikethrough, $newDescription) : '';
$data['meeting_description'] = $newDescription;
$data['meeting_url_html'] = $newUrl !== '' ? sprintf($strikethrough, $newUrl) : '';
$data['meeting_url'] = isset($vEvent->URL) ? (string)$vEvent->URL : '';
$data['meeting_location_html'] = $newLocationHtml !== '' ? sprintf($strikethrough, $newLocationHtml) : '';
$data['meeting_location'] = $newLocation;
return $data;
}
/**
* Check if event took place in the past
*
* @param VCalendar $vObject
* @return int
*/
public function getLastOccurrence(VCalendar $vObject) {
/** @var VEvent $component */
$component = $vObject->VEVENT;
if (isset($component->RRULE)) {
$it = new EventIterator($vObject, (string)$component->UID);
$maxDate = new \DateTime(IMipPlugin::MAX_DATE);
if ($it->isInfinite()) {
return $maxDate->getTimestamp();
}
$end = $it->getDtEnd();
while ($it->valid() && $end < $maxDate) {
$end = $it->getDtEnd();
$it->next();
}
return $end->getTimestamp();
}
/** @var Property\ICalendar\DateTime $dtStart */
$dtStart = $component->DTSTART;
if (isset($component->DTEND)) {
/** @var Property\ICalendar\DateTime $dtEnd */
$dtEnd = $component->DTEND;
return $dtEnd->getDateTime()->getTimeStamp();
}
if(isset($component->DURATION)) {
/** @var \DateTime $endDate */
$endDate = clone $dtStart->getDateTime();
// $component->DTEND->getDateTime() returns DateTimeImmutable
$endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
return $endDate->getTimestamp();
}
if(!$dtStart->hasTime()) {
/** @var \DateTime $endDate */
// $component->DTSTART->getDateTime() returns DateTimeImmutable
$endDate = clone $dtStart->getDateTime();
$endDate = $endDate->modify('+1 day');
return $endDate->getTimestamp();
}
// No computation of end time possible - return start date
return $dtStart->getDateTime()->getTimeStamp();
}
/**
* @param Property|null $attendee
*/
public function setL10n(?Property $attendee = null) {
if($attendee === null) {
return;
}
$lang = $attendee->offsetGet('LANGUAGE');
if ($lang instanceof Parameter) {
$lang = $lang->getValue();
$this->l10n = $this->l10nFactory->get('dav', $lang);
}
}
/**
* @param Property|null $attendee
* @return bool
*/
public function getAttendeeRsvpOrReqForParticipant(?Property $attendee = null) {
if($attendee === null) {
return false;
}
$rsvp = $attendee->offsetGet('RSVP');
if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
return true;
}
$role = $attendee->offsetGet('ROLE');
// @see https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.16
// Attendees without a role are assumed required and should receive an invitation link even if they have no RSVP set
if ($role === null
|| (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'REQ-PARTICIPANT') === 0))
|| (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'OPT-PARTICIPANT') === 0))
) {
return true;
}
// RFC 5545 3.2.17: default RSVP is false
return false;
}
/**
* @param IEMailTemplate $template
* @param string $method
* @param string $sender
* @param string $summary
* @param string|null $partstat
* @param bool $isModified
*/
public function addSubjectAndHeading(IEMailTemplate $template,
string $method, string $sender, string $summary, bool $isModified, ?Property $replyingAttendee = null): void {
if ($method === IMipPlugin::METHOD_CANCEL) {
// TRANSLATORS Subject for email, when an invitation is cancelled. Ex: "Cancelled: {{Event Name}}"
$template->setSubject($this->l10n->t('Cancelled: %1$s', [$summary]));
$template->addHeading($this->l10n->t('"%1$s" has been canceled', [$summary]));
} elseif ($method === IMipPlugin::METHOD_REPLY) {
// TRANSLATORS Subject for email, when an invitation is replied to. Ex: "Re: {{Event Name}}"
$template->setSubject($this->l10n->t('Re: %1$s', [$summary]));
// Build the strings
$partstat = (isset($replyingAttendee)) ? $replyingAttendee->offsetGet('PARTSTAT') : null;
$partstat = ($partstat instanceof Parameter) ? $partstat->getValue() : null;
switch ($partstat) {
case 'ACCEPTED':
$template->addHeading($this->l10n->t('%1$s has accepted your invitation', [$sender]));
break;
case 'TENTATIVE':
$template->addHeading($this->l10n->t('%1$s has tentatively accepted your invitation', [$sender]));
break;
case 'DECLINED':
$template->addHeading($this->l10n->t('%1$s has declined your invitation', [$sender]));
break;
case null:
default:
$template->addHeading($this->l10n->t('%1$s has responded to your invitation', [$sender]));
break;
}
} elseif ($method === IMipPlugin::METHOD_REQUEST && $isModified) {
// TRANSLATORS Subject for email, when an invitation is updated. Ex: "Invitation updated: {{Event Name}}"
$template->setSubject($this->l10n->t('Invitation updated: %1$s', [$summary]));
$template->addHeading($this->l10n->t('%1$s updated the event "%2$s"', [$sender, $summary]));
} else {
// TRANSLATORS Subject for email, when an invitation is sent. Ex: "Invitation: {{Event Name}}"
$template->setSubject($this->l10n->t('Invitation: %1$s', [$summary]));
$template->addHeading($this->l10n->t('%1$s would like to invite you to "%2$s"', [$sender, $summary]));
}
}
/**
* @param string $path
* @return string
*/
public function getAbsoluteImagePath($path): string {
return $this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->imagePath('core', $path)
);
}
/**
* addAttendees: add organizer and attendee names/emails to iMip mail.
*
* Enable with DAV setting: invitation_list_attendees (default: no)
*
* The default is 'no', which matches old behavior, and is privacy preserving.
*
* To enable including attendees in invitation emails:
* % php occ config:app:set dav invitation_list_attendees --value yes
*
* @param IEMailTemplate $template
* @param IL10N $this->l10n
* @param VEvent $vevent
* @author brad2014 on github.com
*/
public function addAttendees(IEMailTemplate $template, VEvent $vevent) {
if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
return;
}
if (isset($vevent->ORGANIZER)) {
/** @var Property | Property\ICalendar\CalAddress $organizer */
$organizer = $vevent->ORGANIZER;
$organizerEmail = substr($organizer->getNormalizedValue(), 7);
/** @var string|null $organizerName */
$organizerName = isset($organizer->CN) ? $organizer->CN->getValue() : null;
$organizerHTML = sprintf('<a href="%s">%s</a>',
htmlspecialchars($organizer->getNormalizedValue()),
htmlspecialchars($organizerName ?: $organizerEmail));
$organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
if(isset($organizer['PARTSTAT'])) {
/** @var Parameter $partstat */
$partstat = $organizer['PARTSTAT'];
if(strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
$organizerHTML .= ' ✔︎';
$organizerText .= ' ✔︎';
}
}
$template->addBodyListItem($organizerHTML, $this->l10n->t('Organizer:'),
$this->getAbsoluteImagePath('caldav/organizer.png'),
$organizerText, '', IMipPlugin::IMIP_INDENT);
}
$attendees = $vevent->select('ATTENDEE');
if (count($attendees) === 0) {
return;
}
$attendeesHTML = [];
$attendeesText = [];
foreach ($attendees as $attendee) {
$attendeeEmail = substr($attendee->getNormalizedValue(), 7);
$attendeeName = isset($attendee['CN']) ? $attendee['CN']->getValue() : null;
$attendeeHTML = sprintf('<a href="%s">%s</a>',
htmlspecialchars($attendee->getNormalizedValue()),
htmlspecialchars($attendeeName ?: $attendeeEmail));
$attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
if (isset($attendee['PARTSTAT'])) {
/** @var Parameter $partstat */
$partstat = $attendee['PARTSTAT'];
if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
$attendeeHTML .= ' ✔︎';
$attendeeText .= ' ✔︎';
}
}
$attendeesHTML[] = $attendeeHTML;
$attendeesText[] = $attendeeText;
}
$template->addBodyListItem(implode('<br/>', $attendeesHTML), $this->l10n->t('Attendees:'),
$this->getAbsoluteImagePath('caldav/attendees.png'),
implode("\n", $attendeesText), '', IMipPlugin::IMIP_INDENT);
}
/**
* @param IEMailTemplate $template
* @param VEVENT $vevent
* @param $data
*/
public function addBulletList(IEMailTemplate $template, VEvent $vevent, $data) {
$template->addBodyListItem(
$data['meeting_title_html'] ?? $data['meeting_title'], $this->l10n->t('Title:'),
$this->getAbsoluteImagePath('caldav/title.png'), $data['meeting_title'], '', IMipPlugin::IMIP_INDENT);
if ($data['meeting_when'] !== '') {
$template->addBodyListItem($data['meeting_when_html'] ?? $data['meeting_when'], $this->l10n->t('Time:'),
$this->getAbsoluteImagePath('caldav/time.png'), $data['meeting_when'], '', IMipPlugin::IMIP_INDENT);
}
if ($data['meeting_location'] !== '') {
$template->addBodyListItem($data['meeting_location_html'] ?? $data['meeting_location'], $this->l10n->t('Location:'),
$this->getAbsoluteImagePath('caldav/location.png'), $data['meeting_location'], '', IMipPlugin::IMIP_INDENT);
}
if ($data['meeting_url'] !== '') {
$template->addBodyListItem($data['meeting_url_html'] ?? $data['meeting_url'], $this->l10n->t('Link:'),
$this->getAbsoluteImagePath('caldav/link.png'), $data['meeting_url'], '', IMipPlugin::IMIP_INDENT);
}
$this->addAttendees($template, $vevent);
/* Put description last, like an email body, since it can be arbitrarily long */
if ($data['meeting_description']) {
$template->addBodyListItem($data['meeting_description_html'] ?? $data['meeting_description'], $this->l10n->t('Description:'),
$this->getAbsoluteImagePath('caldav/description.png'), $data['meeting_description'], '', IMipPlugin::IMIP_INDENT);
}
}
/**
* @param Message $iTipMessage
* @return null|Property
*/
public function getCurrentAttendee(Message $iTipMessage): ?Property {
/** @var VEvent $vevent */
$vevent = $iTipMessage->message->VEVENT;
$attendees = $vevent->select('ATTENDEE');
foreach ($attendees as $attendee) {
/** @var Property $attendee */
if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
return $attendee;
}
}
return null;
}
/**
* @param Message $iTipMessage
* @param VEvent $vevent
* @param int $lastOccurrence
* @return string
*/
public function createInvitationToken(Message $iTipMessage, VEvent $vevent, int $lastOccurrence): string {
$token = $this->random->generate(60, ISecureRandom::CHAR_ALPHANUMERIC);
$attendee = $iTipMessage->recipient;
$organizer = $iTipMessage->sender;
$sequence = $iTipMessage->sequence;
$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
$vevent->{'RECURRENCE-ID'}->serialize() : null;
$uid = $vevent->{'UID'};
$query = $this->db->getQueryBuilder();
$query->insert('calendar_invitations')
->values([
'token' => $query->createNamedParameter($token),
'attendee' => $query->createNamedParameter($attendee),
'organizer' => $query->createNamedParameter($organizer),
'sequence' => $query->createNamedParameter($sequence),
'recurrenceid' => $query->createNamedParameter($recurrenceId),
'expiration' => $query->createNamedParameter($lastOccurrence),
'uid' => $query->createNamedParameter($uid)
])
->execute();
return $token;
}
/**
* Create a valid VCalendar object out of the details of
* a VEvent and its associated iTip Message
*
* We do this to filter out all unchanged VEvents
* This is especially important in iTip Messages with recurrences
* and recurrence exceptions
*
* @param Message $iTipMessage
* @param VEvent $vEvent
* @return VCalendar
*/
public function generateVCalendar(Message $iTipMessage, VEvent $vEvent): VCalendar {
$vCalendar = new VCalendar();
$vCalendar->add('METHOD', $iTipMessage->method);
foreach ($iTipMessage->message->getComponents() as $component) {
if ($component instanceof VEvent) {
continue;
}
$vCalendar->add(clone $component);
}
$vCalendar->add($vEvent);
return $vCalendar;
}
/**
* @param IEMailTemplate $template
* @param $token
*/
public function addResponseButtons(IEMailTemplate $template, $token) {
$template->addBodyButtonGroup(
$this->l10n->t('Accept'),
$this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
'token' => $token,
]),
$this->l10n->t('Decline'),
$this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
'token' => $token,
])
);
}
public function addMoreOptionsButton(IEMailTemplate $template, $token) {
$moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
'token' => $token,
]);
$html = vsprintf('<small><a href="%s">%s</a></small>', [
$moreOptionsURL, $this->l10n->t('More options …')
]);
$text = $this->l10n->t('More options at %s', [$moreOptionsURL]);
$template->addBodyText($html, $text);
}
public function getReplyingAttendee(Message $iTipMessage): ?Property {
/** @var VEvent $vevent */
$vevent = $iTipMessage->message->VEVENT;
$attendees = $vevent->select('ATTENDEE');
foreach ($attendees as $attendee) {
/** @var Property $attendee */
if (strcasecmp($attendee->getValue(), $iTipMessage->sender) === 0) {
return $attendee;
}
}
return null;
}
public function isRoomOrResource(Property $attendee): bool {
$cuType = $attendee->offsetGet('CUTYPE');
if(!$cuType instanceof Parameter) {
return false;
}
$type = $cuType->getValue() ?? 'INDIVIDUAL';
if (\in_array(strtoupper($type), ['RESOURCE', 'ROOM', 'UNKNOWN'], true)) {
// Don't send emails to things
return true;
}
return false;
}
}
@@ -0,0 +1,699 @@
<?php
/**
* @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl>
* @copyright Copyright (c) 2016, Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Richard Steinmetz <richard@steinmetz.cloud>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\DAV\CalDAV\Schedule;
use DateTimeZone;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\Calendar;
use OCA\DAV\CalDAV\CalendarHome;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
use Sabre\CalDAV\ICalendar;
use Sabre\CalDAV\ICalendarObject;
use Sabre\CalDAV\Schedule\ISchedulingObject;
use Sabre\DAV\INode;
use Sabre\DAV\IProperties;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\DAV\Xml\Property\LocalHref;
use Sabre\DAVACL\IACL;
use Sabre\DAVACL\IPrincipal;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
use Sabre\VObject\Component;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\FreeBusyGenerator;
use Sabre\VObject\ITip;
use Sabre\VObject\ITip\SameOrganizerForAllComponentsException;
use Sabre\VObject\Parameter;
use Sabre\VObject\Property;
use Sabre\VObject\Reader;
use function \Sabre\Uri\split;
class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
/**
* @var IConfig
*/
private $config;
/** @var ITip\Message[] */
private $schedulingResponses = [];
/** @var string|null */
private $pathOfCalendarObjectChange = null;
public const CALENDAR_USER_TYPE = '{' . self::NS_CALDAV . '}calendar-user-type';
public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . Plugin::NS_CALDAV . '}schedule-default-calendar-URL';
private LoggerInterface $logger;
/**
* @param IConfig $config
*/
public function __construct(IConfig $config, LoggerInterface $logger) {
$this->config = $config;
$this->logger = $logger;
}
/**
* Initializes the plugin
*
* @param Server $server
* @return void
*/
public function initialize(Server $server) {
parent::initialize($server);
$server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
$server->on('afterWriteContent', [$this, 'dispatchSchedulingResponses']);
$server->on('afterCreateFile', [$this, 'dispatchSchedulingResponses']);
}
/**
* Allow manual setting of the object change URL
* to support public write
*
* @param string $path
*/
public function setPathOfCalendarObjectChange(string $path): void {
$this->pathOfCalendarObjectChange = $path;
}
/**
* This method handler is invoked during fetching of properties.
*
* We use this event to add calendar-auto-schedule-specific properties.
*
* @param PropFind $propFind
* @param INode $node
* @return void
*/
public function propFind(PropFind $propFind, INode $node) {
if ($node instanceof IPrincipal) {
// overwrite Sabre/Dav's implementation
$propFind->handle(self::CALENDAR_USER_TYPE, function () use ($node) {
if ($node instanceof IProperties) {
$props = $node->getProperties([self::CALENDAR_USER_TYPE]);
if (isset($props[self::CALENDAR_USER_TYPE])) {
return $props[self::CALENDAR_USER_TYPE];
}
}
return 'INDIVIDUAL';
});
}
parent::propFind($propFind, $node);
}
/**
* Returns a list of addresses that are associated with a principal.
*
* @param string $principal
* @return array
*/
protected function getAddressesForPrincipal($principal) {
$result = parent::getAddressesForPrincipal($principal);
if ($result === null) {
$result = [];
}
return $result;
}
/**
* @param RequestInterface $request
* @param ResponseInterface $response
* @param VCalendar $vCal
* @param mixed $calendarPath
* @param mixed $modified
* @param mixed $isNew
*/
public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
// Save the first path we get as a calendar-object-change request
if (!$this->pathOfCalendarObjectChange) {
$this->pathOfCalendarObjectChange = $request->getPath();
}
try {
parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
} catch (SameOrganizerForAllComponentsException $e) {
$this->handleSameOrganizerException($e, $vCal, $calendarPath);
}
}
/**
* @inheritDoc
*/
public function beforeUnbind($path): void {
try {
parent::beforeUnbind($path);
} catch (SameOrganizerForAllComponentsException $e) {
$node = $this->server->tree->getNodeForPath($path);
if (!$node instanceof ICalendarObject || $node instanceof ISchedulingObject) {
throw $e;
}
/** @var VCalendar $vCal */
$vCal = Reader::read($node->get());
$this->handleSameOrganizerException($e, $vCal, $path);
}
}
/**
* @inheritDoc
*/
public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
/** @var VEvent|null $vevent */
$vevent = $iTipMessage->message->VEVENT ?? null;
// Strip VALARMs from incoming VEVENT
if ($vevent && isset($vevent->VALARM)) {
$vevent->remove('VALARM');
}
parent::scheduleLocalDelivery($iTipMessage);
// We only care when the message was successfully delivered locally
// Log all possible codes returned from the parent method that mean something went wrong
// 3.7, 3.8, 5.0, 5.2
if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
$this->logger->debug('Message not delivered locally with status: ' . $iTipMessage->scheduleStatus);
return;
}
// We only care about request. reply and cancel are properly handled
// by parent::scheduleLocalDelivery already
if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
return;
}
// If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
// it means that it was successfully delivered locally.
// Meaning that the ACL plugin is loaded and that a principal
// exists for the given recipient id, no need to double check
/** @var \Sabre\DAVACL\Plugin $aclPlugin */
$aclPlugin = $this->server->getPlugin('acl');
$principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
$calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
$this->logger->debug('Calendar user type is room or resource, not processing further');
return;
}
$attendee = $this->getCurrentAttendee($iTipMessage);
if (!$attendee) {
$this->logger->debug('No attendee set for scheduling message');
return;
}
// We only respond when a response was actually requested
$rsvp = $this->getAttendeeRSVP($attendee);
if (!$rsvp) {
$this->logger->debug('No RSVP requested for attendee ' . $attendee->getValue());
return;
}
if (!$vevent) {
$this->logger->debug('No VEVENT set to process on scheduling message');
return;
}
// We don't support autoresponses for recurrencing events for now
if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
$this->logger->debug('VEVENT is a recurring event, autoresponding not supported');
return;
}
$dtstart = $vevent->DTSTART;
$dtend = $this->getDTEndFromVEvent($vevent);
$uid = $vevent->UID->getValue();
$sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
$message = <<<EOF
BEGIN:VCALENDAR
PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
METHOD:REPLY
VERSION:2.0
BEGIN:VEVENT
ATTENDEE;PARTSTAT=%s:%s
ORGANIZER:%s
UID:%s
SEQUENCE:%s
REQUEST-STATUS:2.0;Success
%sEND:VEVENT
END:VCALENDAR
EOF;
if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
$partStat = 'ACCEPTED';
} else {
$partStat = 'DECLINED';
}
$vObject = Reader::read(vsprintf($message, [
$partStat,
$iTipMessage->recipient,
$iTipMessage->sender,
$uid,
$sequence,
$recurrenceId
]));
$responseITipMessage = new ITip\Message();
$responseITipMessage->uid = $uid;
$responseITipMessage->component = 'VEVENT';
$responseITipMessage->method = 'REPLY';
$responseITipMessage->sequence = $sequence;
$responseITipMessage->sender = $iTipMessage->recipient;
$responseITipMessage->recipient = $iTipMessage->sender;
$responseITipMessage->message = $vObject;
// We can't dispatch them now already, because the organizers calendar-object
// was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
// send our reply.
$this->schedulingResponses[] = $responseITipMessage;
}
/**
* @param string $uri
*/
public function dispatchSchedulingResponses(string $uri):void {
if ($uri !== $this->pathOfCalendarObjectChange) {
return;
}
foreach ($this->schedulingResponses as $schedulingResponse) {
$this->scheduleLocalDelivery($schedulingResponse);
}
}
/**
* Always use the personal calendar as target for scheduled events
*
* @param PropFind $propFind
* @param INode $node
* @return void
*/
public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
if ($node instanceof IPrincipal) {
$propFind->handle(self::SCHEDULE_DEFAULT_CALENDAR_URL, function () use ($node) {
/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
$caldavPlugin = $this->server->getPlugin('caldav');
$principalUrl = $node->getPrincipalUrl();
$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
if (!$calendarHomePath) {
return null;
}
$isResourceOrRoom = str_starts_with($principalUrl, 'principals/calendar-resources') ||
str_starts_with($principalUrl, 'principals/calendar-rooms');
if (str_starts_with($principalUrl, 'principals/users')) {
[, $userId] = split($principalUrl);
$uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
$displayName = CalDavBackend::PERSONAL_CALENDAR_NAME;
} elseif ($isResourceOrRoom) {
$uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
$displayName = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
} else {
// How did we end up here?
// TODO - throw exception or just ignore?
return null;
}
/** @var CalendarHome $calendarHome */
$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
$currentCalendarDeleted = false;
if (!$calendarHome->childExists($uri) || $currentCalendarDeleted = $this->isCalendarDeleted($calendarHome, $uri)) {
// If the default calendar doesn't exist
if ($isResourceOrRoom) {
// Resources or rooms can't be in the trashbin, so we're fine
$this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
} else {
// And we're not handling scheduling on resource/room booking
$userCalendars = [];
/**
* If the default calendar of the user isn't set and the
* fallback doesn't match any of the user's calendar
* try to find the first "personal" calendar we can write to
* instead of creating a new one.
* A appropriate personal calendar to receive invites:
* - isn't a calendar subscription
* - user can write to it (no virtual/3rd-party calendars)
* - calendar isn't a share
*/
foreach ($calendarHome->getChildren() as $node) {
if ($node instanceof Calendar && !$node->isSubscription() && $node->canWrite() && !$node->isShared() && !$node->isDeleted()) {
$userCalendars[] = $node;
}
}
if (count($userCalendars) > 0) {
// Calendar backend returns calendar by calendarorder property
$uri = $userCalendars[0]->getName();
} else {
// Otherwise if we have really nothing, create a new calendar
if ($currentCalendarDeleted) {
// If the calendar exists but is deleted, we need to purge it first
// This may cause some issues in a non synchronous database setup
$calendar = $this->getCalendar($calendarHome, $uri);
if ($calendar instanceof Calendar) {
$calendar->disableTrashbin();
$calendar->delete();
}
}
$this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
}
}
}
$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
if (empty($result)) {
return null;
}
return new LocalHref($result[0]['href']);
});
}
}
/**
* Returns a list of addresses that are associated with a principal.
*
* @param string $principal
* @return string|null
*/
protected function getCalendarUserTypeForPrincipal($principal):?string {
$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
$properties = $this->server->getProperties(
$principal,
[$calendarUserType]
);
// If we can't find this information, we'll stop processing
if (!isset($properties[$calendarUserType])) {
return null;
}
return $properties[$calendarUserType];
}
/**
* @param ITip\Message $iTipMessage
* @return null|Property
*/
private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
/** @var VEvent $vevent */
$vevent = $iTipMessage->message->VEVENT;
$attendees = $vevent->select('ATTENDEE');
foreach ($attendees as $attendee) {
/** @var Property $attendee */
if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
return $attendee;
}
}
return null;
}
/**
* @param Property|null $attendee
* @return bool
*/
private function getAttendeeRSVP(Property $attendee = null):bool {
if ($attendee !== null) {
$rsvp = $attendee->offsetGet('RSVP');
if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
return true;
}
}
// RFC 5545 3.2.17: default RSVP is false
return false;
}
/**
* @param VEvent $vevent
* @return Property\ICalendar\DateTime
*/
private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
if (isset($vevent->DTEND)) {
return $vevent->DTEND;
}
if (isset($vevent->DURATION)) {
$isFloating = $vevent->DTSTART->isFloating();
/** @var Property\ICalendar\DateTime $end */
$end = clone $vevent->DTSTART;
$endDateTime = $end->getDateTime();
$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
$end->setDateTime($endDateTime, $isFloating);
return $end;
}
if (!$vevent->DTSTART->hasTime()) {
$isFloating = $vevent->DTSTART->isFloating();
/** @var Property\ICalendar\DateTime $end */
$end = clone $vevent->DTSTART;
$endDateTime = $end->getDateTime();
$endDateTime = $endDateTime->modify('+1 day');
$end->setDateTime($endDateTime, $isFloating);
return $end;
}
return clone $vevent->DTSTART;
}
/**
* @param string $email
* @param \DateTimeInterface $start
* @param \DateTimeInterface $end
* @param string $ignoreUID
* @return bool
*/
private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
// This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
// and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
$aclPlugin = $this->server->getPlugin('acl');
$this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
$result = $aclPlugin->principalSearch(
['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
[
'{DAV:}principal-URL',
'{' . self::NS_CALDAV . '}calendar-home-set',
'{' . self::NS_CALDAV . '}schedule-inbox-URL',
'{http://sabredav.org/ns}email-address',
]
);
$this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
// Grabbing the calendar list
$objects = [];
$calendarTimeZone = new DateTimeZone('UTC');
$homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
if (!$node instanceof ICalendar) {
continue;
}
// Getting the list of object uris within the time-range
$urls = $node->calendarQuery([
'name' => 'VCALENDAR',
'comp-filters' => [
[
'name' => 'VEVENT',
'is-not-defined' => false,
'time-range' => [
'start' => $start,
'end' => $end,
],
'comp-filters' => [],
'prop-filters' => [],
],
[
'name' => 'VEVENT',
'is-not-defined' => false,
'time-range' => null,
'comp-filters' => [],
'prop-filters' => [
[
'name' => 'UID',
'is-not-defined' => false,
'time-range' => null,
'text-match' => [
'value' => $ignoreUID,
'negate-condition' => true,
'collation' => 'i;octet',
],
'param-filters' => [],
],
]
],
],
'prop-filters' => [],
'is-not-defined' => false,
'time-range' => null,
]);
foreach ($urls as $url) {
$objects[] = $node->getChild($url)->get();
}
}
$inboxProps = $this->server->getProperties(
$result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
['{' . self::NS_CALDAV . '}calendar-availability']
);
$vcalendar = new VCalendar();
$vcalendar->METHOD = 'REPLY';
$generator = new FreeBusyGenerator();
$generator->setObjects($objects);
$generator->setTimeRange($start, $end);
$generator->setBaseObject($vcalendar);
$generator->setTimeZone($calendarTimeZone);
if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
$generator->setVAvailability(
Reader::read(
$inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
)
);
}
$result = $generator->getResult();
if (!isset($result->VFREEBUSY)) {
return false;
}
/** @var Component $freeBusyComponent */
$freeBusyComponent = $result->VFREEBUSY;
$freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
// If there is no Free-busy property at all, the time-range is empty and available
if (count($freeBusyProperties) === 0) {
return true;
}
// If more than one Free-Busy property was returned, it means that an event
// starts or ends inside this time-range, so it's not available and we return false
if (count($freeBusyProperties) > 1) {
return false;
}
/** @var Property $freeBusyProperty */
$freeBusyProperty = $freeBusyProperties[0];
if (!$freeBusyProperty->offsetExists('FBTYPE')) {
// If there is no FBTYPE, it means it's busy
return false;
}
$fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
if (!($fbTypeParameter instanceof Parameter)) {
return false;
}
return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
}
/**
* @param string $email
* @return string
*/
private function stripOffMailTo(string $email): string {
if (stripos($email, 'mailto:') === 0) {
return substr($email, 7);
}
return $email;
}
private function getCalendar(CalendarHome $calendarHome, string $uri): INode {
return $calendarHome->getChild($uri);
}
private function isCalendarDeleted(CalendarHome $calendarHome, string $uri): bool {
$calendar = $this->getCalendar($calendarHome, $uri);
return $calendar instanceof Calendar && $calendar->isDeleted();
}
private function createCalendar(CalendarHome $calendarHome, string $principalUri, string $uri, string $displayName): void {
$calendarHome->getCalDAVBackend()->createCalendar($principalUri, $uri, [
'{DAV:}displayname' => $displayName,
]);
}
/**
* Try to handle the given exception gracefully or throw it if necessary.
*
* @throws SameOrganizerForAllComponentsException If the exception should not be ignored
*/
private function handleSameOrganizerException(
SameOrganizerForAllComponentsException $e,
VCalendar $vCal,
string $calendarPath,
): void {
// This is very hacky! However, we want to allow saving events with multiple
// organizers. Those events are not RFC compliant, but sometimes imported from major
// external calendar services (e.g. Google). If the current user is not an organizer of
// the event we ignore the exception as no scheduling messages will be sent anyway.
// It would be cleaner to patch Sabre to validate organizers *after* checking if
// scheduling messages are necessary. Currently, organizers are validated first and
// afterwards the broker checks if messages should be scheduled. So the code will throw
// even if the organizers are not relevant. This is to ensure compliance with RFCs but
// a bit too strict for real world usage.
if (!isset($vCal->VEVENT)) {
throw $e;
}
$calendarNode = $this->server->tree->getNodeForPath($calendarPath);
if (!($calendarNode instanceof IACL)) {
// Should always be an instance of IACL but just to be sure
throw $e;
}
$addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
foreach ($vCal->VEVENT as $vevent) {
if (in_array($vevent->ORGANIZER->getNormalizedValue(), $addresses, true)) {
// User is an organizer => throw the exception
throw $e;
}
}
}
}