1
0

Plugin.php 22 KB

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