Plugin.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\DAV\CalDAV\Schedule;
  7. use DateTimeZone;
  8. use OCA\DAV\CalDAV\CalDavBackend;
  9. use OCA\DAV\CalDAV\Calendar;
  10. use OCA\DAV\CalDAV\CalendarHome;
  11. use OCA\DAV\CalDAV\DefaultCalendarValidator;
  12. use OCP\IConfig;
  13. use Psr\Log\LoggerInterface;
  14. use Sabre\CalDAV\ICalendar;
  15. use Sabre\CalDAV\ICalendarObject;
  16. use Sabre\CalDAV\Schedule\ISchedulingObject;
  17. use Sabre\DAV\Exception as DavException;
  18. use Sabre\DAV\INode;
  19. use Sabre\DAV\IProperties;
  20. use Sabre\DAV\PropFind;
  21. use Sabre\DAV\Server;
  22. use Sabre\DAV\Xml\Property\LocalHref;
  23. use Sabre\DAVACL\IACL;
  24. use Sabre\DAVACL\IPrincipal;
  25. use Sabre\HTTP\RequestInterface;
  26. use Sabre\HTTP\ResponseInterface;
  27. use Sabre\VObject\Component;
  28. use Sabre\VObject\Component\VCalendar;
  29. use Sabre\VObject\Component\VEvent;
  30. use Sabre\VObject\DateTimeParser;
  31. use Sabre\VObject\FreeBusyGenerator;
  32. use Sabre\VObject\ITip;
  33. use Sabre\VObject\ITip\SameOrganizerForAllComponentsException;
  34. use Sabre\VObject\Parameter;
  35. use Sabre\VObject\Property;
  36. use Sabre\VObject\Reader;
  37. use function Sabre\Uri\split;
  38. class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
  39. /**
  40. * @var IConfig
  41. */
  42. private $config;
  43. /** @var ITip\Message[] */
  44. private $schedulingResponses = [];
  45. /** @var string|null */
  46. private $pathOfCalendarObjectChange = null;
  47. public const CALENDAR_USER_TYPE = '{' . self::NS_CALDAV . '}calendar-user-type';
  48. public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . Plugin::NS_CALDAV . '}schedule-default-calendar-URL';
  49. private LoggerInterface $logger;
  50. private DefaultCalendarValidator $defaultCalendarValidator;
  51. /**
  52. * @param IConfig $config
  53. */
  54. public function __construct(IConfig $config, LoggerInterface $logger, DefaultCalendarValidator $defaultCalendarValidator) {
  55. $this->config = $config;
  56. $this->logger = $logger;
  57. $this->defaultCalendarValidator = $defaultCalendarValidator;
  58. }
  59. /**
  60. * Initializes the plugin
  61. *
  62. * @param Server $server
  63. * @return void
  64. */
  65. public function initialize(Server $server) {
  66. parent::initialize($server);
  67. $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
  68. $server->on('afterWriteContent', [$this, 'dispatchSchedulingResponses']);
  69. $server->on('afterCreateFile', [$this, 'dispatchSchedulingResponses']);
  70. // We allow mutating the default calendar URL through the CustomPropertiesBackend
  71. // (oc_properties table)
  72. $server->protectedProperties = array_filter(
  73. $server->protectedProperties,
  74. static fn (string $property) => $property !== self::SCHEDULE_DEFAULT_CALENDAR_URL,
  75. );
  76. }
  77. /**
  78. * Allow manual setting of the object change URL
  79. * to support public write
  80. *
  81. * @param string $path
  82. */
  83. public function setPathOfCalendarObjectChange(string $path): void {
  84. $this->pathOfCalendarObjectChange = $path;
  85. }
  86. /**
  87. * This method handler is invoked during fetching of properties.
  88. *
  89. * We use this event to add calendar-auto-schedule-specific properties.
  90. *
  91. * @param PropFind $propFind
  92. * @param INode $node
  93. * @return void
  94. */
  95. public function propFind(PropFind $propFind, INode $node) {
  96. if ($node instanceof IPrincipal) {
  97. // overwrite Sabre/Dav's implementation
  98. $propFind->handle(self::CALENDAR_USER_TYPE, function () use ($node) {
  99. if ($node instanceof IProperties) {
  100. $props = $node->getProperties([self::CALENDAR_USER_TYPE]);
  101. if (isset($props[self::CALENDAR_USER_TYPE])) {
  102. return $props[self::CALENDAR_USER_TYPE];
  103. }
  104. }
  105. return 'INDIVIDUAL';
  106. });
  107. }
  108. parent::propFind($propFind, $node);
  109. }
  110. /**
  111. * Returns a list of addresses that are associated with a principal.
  112. *
  113. * @param string $principal
  114. * @return array
  115. */
  116. protected function getAddressesForPrincipal($principal) {
  117. $result = parent::getAddressesForPrincipal($principal);
  118. if ($result === null) {
  119. $result = [];
  120. }
  121. // iterate through items and html decode values
  122. foreach ($result as $key => $value) {
  123. $result[$key] = urldecode($value);
  124. }
  125. return $result;
  126. }
  127. /**
  128. * @param RequestInterface $request
  129. * @param ResponseInterface $response
  130. * @param VCalendar $vCal
  131. * @param mixed $calendarPath
  132. * @param mixed $modified
  133. * @param mixed $isNew
  134. */
  135. public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
  136. // Save the first path we get as a calendar-object-change request
  137. if (!$this->pathOfCalendarObjectChange) {
  138. $this->pathOfCalendarObjectChange = $request->getPath();
  139. }
  140. try {
  141. parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
  142. } catch (SameOrganizerForAllComponentsException $e) {
  143. $this->handleSameOrganizerException($e, $vCal, $calendarPath);
  144. }
  145. }
  146. /**
  147. * @inheritDoc
  148. */
  149. public function beforeUnbind($path): void {
  150. try {
  151. parent::beforeUnbind($path);
  152. } catch (SameOrganizerForAllComponentsException $e) {
  153. $node = $this->server->tree->getNodeForPath($path);
  154. if (!$node instanceof ICalendarObject || $node instanceof ISchedulingObject) {
  155. throw $e;
  156. }
  157. /** @var VCalendar $vCal */
  158. $vCal = Reader::read($node->get());
  159. $this->handleSameOrganizerException($e, $vCal, $path);
  160. }
  161. }
  162. /**
  163. * @inheritDoc
  164. */
  165. public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
  166. /** @var VEvent|null $vevent */
  167. $vevent = $iTipMessage->message->VEVENT ?? null;
  168. // Strip VALARMs from incoming VEVENT
  169. if ($vevent && isset($vevent->VALARM)) {
  170. $vevent->remove('VALARM');
  171. }
  172. parent::scheduleLocalDelivery($iTipMessage);
  173. // We only care when the message was successfully delivered locally
  174. // Log all possible codes returned from the parent method that mean something went wrong
  175. // 3.7, 3.8, 5.0, 5.2
  176. if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
  177. $this->logger->debug('Message not delivered locally with status: ' . $iTipMessage->scheduleStatus);
  178. return;
  179. }
  180. // We only care about request. reply and cancel are properly handled
  181. // by parent::scheduleLocalDelivery already
  182. if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
  183. return;
  184. }
  185. // If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
  186. // it means that it was successfully delivered locally.
  187. // Meaning that the ACL plugin is loaded and that a principal
  188. // exists for the given recipient id, no need to double check
  189. /** @var \Sabre\DAVACL\Plugin $aclPlugin */
  190. $aclPlugin = $this->server->getPlugin('acl');
  191. $principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
  192. $calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
  193. if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
  194. $this->logger->debug('Calendar user type is room or resource, not processing further');
  195. return;
  196. }
  197. $attendee = $this->getCurrentAttendee($iTipMessage);
  198. if (!$attendee) {
  199. $this->logger->debug('No attendee set for scheduling message');
  200. return;
  201. }
  202. // We only respond when a response was actually requested
  203. $rsvp = $this->getAttendeeRSVP($attendee);
  204. if (!$rsvp) {
  205. $this->logger->debug('No RSVP requested for attendee ' . $attendee->getValue());
  206. return;
  207. }
  208. if (!$vevent) {
  209. $this->logger->debug('No VEVENT set to process on scheduling message');
  210. return;
  211. }
  212. // We don't support autoresponses for recurrencing events for now
  213. if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
  214. $this->logger->debug('VEVENT is a recurring event, autoresponding not supported');
  215. return;
  216. }
  217. $dtstart = $vevent->DTSTART;
  218. $dtend = $this->getDTEndFromVEvent($vevent);
  219. $uid = $vevent->UID->getValue();
  220. $sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
  221. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
  222. $message = <<<EOF
  223. BEGIN:VCALENDAR
  224. PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
  225. METHOD:REPLY
  226. VERSION:2.0
  227. BEGIN:VEVENT
  228. ATTENDEE;PARTSTAT=%s:%s
  229. ORGANIZER:%s
  230. UID:%s
  231. SEQUENCE:%s
  232. REQUEST-STATUS:2.0;Success
  233. %sEND:VEVENT
  234. END:VCALENDAR
  235. EOF;
  236. if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
  237. $partStat = 'ACCEPTED';
  238. } else {
  239. $partStat = 'DECLINED';
  240. }
  241. $vObject = Reader::read(vsprintf($message, [
  242. $partStat,
  243. $iTipMessage->recipient,
  244. $iTipMessage->sender,
  245. $uid,
  246. $sequence,
  247. $recurrenceId
  248. ]));
  249. $responseITipMessage = new ITip\Message();
  250. $responseITipMessage->uid = $uid;
  251. $responseITipMessage->component = 'VEVENT';
  252. $responseITipMessage->method = 'REPLY';
  253. $responseITipMessage->sequence = $sequence;
  254. $responseITipMessage->sender = $iTipMessage->recipient;
  255. $responseITipMessage->recipient = $iTipMessage->sender;
  256. $responseITipMessage->message = $vObject;
  257. // We can't dispatch them now already, because the organizers calendar-object
  258. // was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
  259. // send our reply.
  260. $this->schedulingResponses[] = $responseITipMessage;
  261. }
  262. /**
  263. * @param string $uri
  264. */
  265. public function dispatchSchedulingResponses(string $uri):void {
  266. if ($uri !== $this->pathOfCalendarObjectChange) {
  267. return;
  268. }
  269. foreach ($this->schedulingResponses as $schedulingResponse) {
  270. $this->scheduleLocalDelivery($schedulingResponse);
  271. }
  272. }
  273. /**
  274. * Always use the personal calendar as target for scheduled events
  275. *
  276. * @param PropFind $propFind
  277. * @param INode $node
  278. * @return void
  279. */
  280. public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
  281. if ($node instanceof IPrincipal) {
  282. $propFind->handle(self::SCHEDULE_DEFAULT_CALENDAR_URL, function () use ($node) {
  283. /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
  284. $caldavPlugin = $this->server->getPlugin('caldav');
  285. $principalUrl = $node->getPrincipalUrl();
  286. $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
  287. if (!$calendarHomePath) {
  288. return null;
  289. }
  290. $isResourceOrRoom = str_starts_with($principalUrl, 'principals/calendar-resources') ||
  291. str_starts_with($principalUrl, 'principals/calendar-rooms');
  292. if (str_starts_with($principalUrl, 'principals/users')) {
  293. [, $userId] = split($principalUrl);
  294. $uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
  295. $displayName = CalDavBackend::PERSONAL_CALENDAR_NAME;
  296. } elseif ($isResourceOrRoom) {
  297. $uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
  298. $displayName = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
  299. } else {
  300. // How did we end up here?
  301. // TODO - throw exception or just ignore?
  302. return null;
  303. }
  304. /** @var CalendarHome $calendarHome */
  305. $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
  306. $currentCalendarDeleted = false;
  307. if (!$calendarHome->childExists($uri) || $currentCalendarDeleted = $this->isCalendarDeleted($calendarHome, $uri)) {
  308. // If the default calendar doesn't exist
  309. if ($isResourceOrRoom) {
  310. // Resources or rooms can't be in the trashbin, so we're fine
  311. $this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
  312. } else {
  313. // And we're not handling scheduling on resource/room booking
  314. $userCalendars = [];
  315. /**
  316. * If the default calendar of the user isn't set and the
  317. * fallback doesn't match any of the user's calendar
  318. * try to find the first "personal" calendar we can write to
  319. * instead of creating a new one.
  320. * A appropriate personal calendar to receive invites:
  321. * - isn't a calendar subscription
  322. * - user can write to it (no virtual/3rd-party calendars)
  323. * - calendar isn't a share
  324. * - calendar supports VEVENTs
  325. */
  326. foreach ($calendarHome->getChildren() as $node) {
  327. if (!($node instanceof Calendar)) {
  328. continue;
  329. }
  330. try {
  331. $this->defaultCalendarValidator->validateScheduleDefaultCalendar($node);
  332. } catch (DavException $e) {
  333. continue;
  334. }
  335. $userCalendars[] = $node;
  336. }
  337. if (count($userCalendars) > 0) {
  338. // Calendar backend returns calendar by calendarorder property
  339. $uri = $userCalendars[0]->getName();
  340. } else {
  341. // Otherwise if we have really nothing, create a new calendar
  342. if ($currentCalendarDeleted) {
  343. // If the calendar exists but is deleted, we need to purge it first
  344. // This may cause some issues in a non synchronous database setup
  345. $calendar = $this->getCalendar($calendarHome, $uri);
  346. if ($calendar instanceof Calendar) {
  347. $calendar->disableTrashbin();
  348. $calendar->delete();
  349. }
  350. }
  351. $this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
  352. }
  353. }
  354. }
  355. $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
  356. if (empty($result)) {
  357. return null;
  358. }
  359. return new LocalHref($result[0]['href']);
  360. });
  361. }
  362. }
  363. /**
  364. * Returns a list of addresses that are associated with a principal.
  365. *
  366. * @param string $principal
  367. * @return string|null
  368. */
  369. protected function getCalendarUserTypeForPrincipal($principal):?string {
  370. $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
  371. $properties = $this->server->getProperties(
  372. $principal,
  373. [$calendarUserType]
  374. );
  375. // If we can't find this information, we'll stop processing
  376. if (!isset($properties[$calendarUserType])) {
  377. return null;
  378. }
  379. return $properties[$calendarUserType];
  380. }
  381. /**
  382. * @param ITip\Message $iTipMessage
  383. * @return null|Property
  384. */
  385. private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
  386. /** @var VEvent $vevent */
  387. $vevent = $iTipMessage->message->VEVENT;
  388. $attendees = $vevent->select('ATTENDEE');
  389. foreach ($attendees as $attendee) {
  390. /** @var Property $attendee */
  391. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  392. return $attendee;
  393. }
  394. }
  395. return null;
  396. }
  397. /**
  398. * @param Property|null $attendee
  399. * @return bool
  400. */
  401. private function getAttendeeRSVP(?Property $attendee = null):bool {
  402. if ($attendee !== null) {
  403. $rsvp = $attendee->offsetGet('RSVP');
  404. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  405. return true;
  406. }
  407. }
  408. // RFC 5545 3.2.17: default RSVP is false
  409. return false;
  410. }
  411. /**
  412. * @param VEvent $vevent
  413. * @return Property\ICalendar\DateTime
  414. */
  415. private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
  416. if (isset($vevent->DTEND)) {
  417. return $vevent->DTEND;
  418. }
  419. if (isset($vevent->DURATION)) {
  420. $isFloating = $vevent->DTSTART->isFloating();
  421. /** @var Property\ICalendar\DateTime $end */
  422. $end = clone $vevent->DTSTART;
  423. $endDateTime = $end->getDateTime();
  424. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  425. $end->setDateTime($endDateTime, $isFloating);
  426. return $end;
  427. }
  428. if (!$vevent->DTSTART->hasTime()) {
  429. $isFloating = $vevent->DTSTART->isFloating();
  430. /** @var Property\ICalendar\DateTime $end */
  431. $end = clone $vevent->DTSTART;
  432. $endDateTime = $end->getDateTime();
  433. $endDateTime = $endDateTime->modify('+1 day');
  434. $end->setDateTime($endDateTime, $isFloating);
  435. return $end;
  436. }
  437. return clone $vevent->DTSTART;
  438. }
  439. /**
  440. * @param string $email
  441. * @param \DateTimeInterface $start
  442. * @param \DateTimeInterface $end
  443. * @param string $ignoreUID
  444. * @return bool
  445. */
  446. private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
  447. // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
  448. // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
  449. $aclPlugin = $this->server->getPlugin('acl');
  450. $this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
  451. $result = $aclPlugin->principalSearch(
  452. ['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
  453. [
  454. '{DAV:}principal-URL',
  455. '{' . self::NS_CALDAV . '}calendar-home-set',
  456. '{' . self::NS_CALDAV . '}schedule-inbox-URL',
  457. '{http://sabredav.org/ns}email-address',
  458. ]
  459. );
  460. $this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
  461. // Grabbing the calendar list
  462. $objects = [];
  463. $calendarTimeZone = new DateTimeZone('UTC');
  464. $homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
  465. foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
  466. if (!$node instanceof ICalendar) {
  467. continue;
  468. }
  469. // Getting the list of object uris within the time-range
  470. $urls = $node->calendarQuery([
  471. 'name' => 'VCALENDAR',
  472. 'comp-filters' => [
  473. [
  474. 'name' => 'VEVENT',
  475. 'is-not-defined' => false,
  476. 'time-range' => [
  477. 'start' => $start,
  478. 'end' => $end,
  479. ],
  480. 'comp-filters' => [],
  481. 'prop-filters' => [],
  482. ],
  483. [
  484. 'name' => 'VEVENT',
  485. 'is-not-defined' => false,
  486. 'time-range' => null,
  487. 'comp-filters' => [],
  488. 'prop-filters' => [
  489. [
  490. 'name' => 'UID',
  491. 'is-not-defined' => false,
  492. 'time-range' => null,
  493. 'text-match' => [
  494. 'value' => $ignoreUID,
  495. 'negate-condition' => true,
  496. 'collation' => 'i;octet',
  497. ],
  498. 'param-filters' => [],
  499. ],
  500. ]
  501. ],
  502. ],
  503. 'prop-filters' => [],
  504. 'is-not-defined' => false,
  505. 'time-range' => null,
  506. ]);
  507. foreach ($urls as $url) {
  508. $objects[] = $node->getChild($url)->get();
  509. }
  510. }
  511. $inboxProps = $this->server->getProperties(
  512. $result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
  513. ['{' . self::NS_CALDAV . '}calendar-availability']
  514. );
  515. $vcalendar = new VCalendar();
  516. $vcalendar->METHOD = 'REPLY';
  517. $generator = new FreeBusyGenerator();
  518. $generator->setObjects($objects);
  519. $generator->setTimeRange($start, $end);
  520. $generator->setBaseObject($vcalendar);
  521. $generator->setTimeZone($calendarTimeZone);
  522. if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
  523. $generator->setVAvailability(
  524. Reader::read(
  525. $inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
  526. )
  527. );
  528. }
  529. $result = $generator->getResult();
  530. if (!isset($result->VFREEBUSY)) {
  531. return false;
  532. }
  533. /** @var Component $freeBusyComponent */
  534. $freeBusyComponent = $result->VFREEBUSY;
  535. $freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
  536. // If there is no Free-busy property at all, the time-range is empty and available
  537. if (count($freeBusyProperties) === 0) {
  538. return true;
  539. }
  540. // If more than one Free-Busy property was returned, it means that an event
  541. // starts or ends inside this time-range, so it's not available and we return false
  542. if (count($freeBusyProperties) > 1) {
  543. return false;
  544. }
  545. /** @var Property $freeBusyProperty */
  546. $freeBusyProperty = $freeBusyProperties[0];
  547. if (!$freeBusyProperty->offsetExists('FBTYPE')) {
  548. // If there is no FBTYPE, it means it's busy
  549. return false;
  550. }
  551. $fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
  552. if (!($fbTypeParameter instanceof Parameter)) {
  553. return false;
  554. }
  555. return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
  556. }
  557. /**
  558. * @param string $email
  559. * @return string
  560. */
  561. private function stripOffMailTo(string $email): string {
  562. if (stripos($email, 'mailto:') === 0) {
  563. return substr($email, 7);
  564. }
  565. return $email;
  566. }
  567. private function getCalendar(CalendarHome $calendarHome, string $uri): INode {
  568. return $calendarHome->getChild($uri);
  569. }
  570. private function isCalendarDeleted(CalendarHome $calendarHome, string $uri): bool {
  571. $calendar = $this->getCalendar($calendarHome, $uri);
  572. return $calendar instanceof Calendar && $calendar->isDeleted();
  573. }
  574. private function createCalendar(CalendarHome $calendarHome, string $principalUri, string $uri, string $displayName): void {
  575. $calendarHome->getCalDAVBackend()->createCalendar($principalUri, $uri, [
  576. '{DAV:}displayname' => $displayName,
  577. ]);
  578. }
  579. /**
  580. * Try to handle the given exception gracefully or throw it if necessary.
  581. *
  582. * @throws SameOrganizerForAllComponentsException If the exception should not be ignored
  583. */
  584. private function handleSameOrganizerException(
  585. SameOrganizerForAllComponentsException $e,
  586. VCalendar $vCal,
  587. string $calendarPath,
  588. ): void {
  589. // This is very hacky! However, we want to allow saving events with multiple
  590. // organizers. Those events are not RFC compliant, but sometimes imported from major
  591. // external calendar services (e.g. Google). If the current user is not an organizer of
  592. // the event we ignore the exception as no scheduling messages will be sent anyway.
  593. // It would be cleaner to patch Sabre to validate organizers *after* checking if
  594. // scheduling messages are necessary. Currently, organizers are validated first and
  595. // afterwards the broker checks if messages should be scheduled. So the code will throw
  596. // even if the organizers are not relevant. This is to ensure compliance with RFCs but
  597. // a bit too strict for real world usage.
  598. if (!isset($vCal->VEVENT)) {
  599. throw $e;
  600. }
  601. $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
  602. if (!($calendarNode instanceof IACL)) {
  603. // Should always be an instance of IACL but just to be sure
  604. throw $e;
  605. }
  606. $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
  607. foreach ($vCal->VEVENT as $vevent) {
  608. if (in_array($vevent->ORGANIZER->getNormalizedValue(), $addresses, true)) {
  609. // User is an organizer => throw the exception
  610. throw $e;
  611. }
  612. }
  613. }
  614. }