Plugin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. if (!$this->scheduleReply($this->server->httpRequest)) {
  142. return;
  143. }
  144. /** @var \OCA\DAV\CalDAV\Calendar $calendarNode */
  145. $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
  146. // extract addresses for owner
  147. $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
  148. // determain if request is from a sharee
  149. if ($calendarNode->isShared()) {
  150. // extract addresses for sharee and add to address collection
  151. $addresses = array_merge(
  152. $addresses,
  153. $this->getAddressesForPrincipal($calendarNode->getPrincipalURI())
  154. );
  155. }
  156. // determine if we are updating a calendar event
  157. if (!$isNew) {
  158. // retrieve current calendar event node
  159. /** @var \OCA\DAV\CalDAV\CalendarObject $currentNode */
  160. $currentNode = $this->server->tree->getNodeForPath($request->getPath());
  161. // convert calendar event string data to VCalendar object
  162. /** @var \Sabre\VObject\Component\VCalendar $currentObject */
  163. $currentObject = Reader::read($currentNode->get());
  164. } else {
  165. $currentObject = null;
  166. }
  167. // process request
  168. $this->processICalendarChange($currentObject, $vCal, $addresses, [], $modified);
  169. if ($currentObject) {
  170. // Destroy circular references so PHP will GC the object.
  171. $currentObject->destroy();
  172. }
  173. } catch (SameOrganizerForAllComponentsException $e) {
  174. $this->handleSameOrganizerException($e, $vCal, $calendarPath);
  175. }
  176. }
  177. /**
  178. * @inheritDoc
  179. */
  180. public function beforeUnbind($path): void {
  181. try {
  182. parent::beforeUnbind($path);
  183. } catch (SameOrganizerForAllComponentsException $e) {
  184. $node = $this->server->tree->getNodeForPath($path);
  185. if (!$node instanceof ICalendarObject || $node instanceof ISchedulingObject) {
  186. throw $e;
  187. }
  188. /** @var VCalendar $vCal */
  189. $vCal = Reader::read($node->get());
  190. $this->handleSameOrganizerException($e, $vCal, $path);
  191. }
  192. }
  193. /**
  194. * @inheritDoc
  195. */
  196. public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
  197. /** @var VEvent|null $vevent */
  198. $vevent = $iTipMessage->message->VEVENT ?? null;
  199. // Strip VALARMs from incoming VEVENT
  200. if ($vevent && isset($vevent->VALARM)) {
  201. $vevent->remove('VALARM');
  202. }
  203. parent::scheduleLocalDelivery($iTipMessage);
  204. // We only care when the message was successfully delivered locally
  205. // Log all possible codes returned from the parent method that mean something went wrong
  206. // 3.7, 3.8, 5.0, 5.2
  207. if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
  208. $this->logger->debug('Message not delivered locally with status: ' . $iTipMessage->scheduleStatus);
  209. return;
  210. }
  211. // We only care about request. reply and cancel are properly handled
  212. // by parent::scheduleLocalDelivery already
  213. if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
  214. return;
  215. }
  216. // If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
  217. // it means that it was successfully delivered locally.
  218. // Meaning that the ACL plugin is loaded and that a principal
  219. // exists for the given recipient id, no need to double check
  220. /** @var \Sabre\DAVACL\Plugin $aclPlugin */
  221. $aclPlugin = $this->server->getPlugin('acl');
  222. $principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
  223. $calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
  224. if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
  225. $this->logger->debug('Calendar user type is room or resource, not processing further');
  226. return;
  227. }
  228. $attendee = $this->getCurrentAttendee($iTipMessage);
  229. if (!$attendee) {
  230. $this->logger->debug('No attendee set for scheduling message');
  231. return;
  232. }
  233. // We only respond when a response was actually requested
  234. $rsvp = $this->getAttendeeRSVP($attendee);
  235. if (!$rsvp) {
  236. $this->logger->debug('No RSVP requested for attendee ' . $attendee->getValue());
  237. return;
  238. }
  239. if (!$vevent) {
  240. $this->logger->debug('No VEVENT set to process on scheduling message');
  241. return;
  242. }
  243. // We don't support autoresponses for recurrencing events for now
  244. if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
  245. $this->logger->debug('VEVENT is a recurring event, autoresponding not supported');
  246. return;
  247. }
  248. $dtstart = $vevent->DTSTART;
  249. $dtend = $this->getDTEndFromVEvent($vevent);
  250. $uid = $vevent->UID->getValue();
  251. $sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
  252. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
  253. $message = <<<EOF
  254. BEGIN:VCALENDAR
  255. PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
  256. METHOD:REPLY
  257. VERSION:2.0
  258. BEGIN:VEVENT
  259. ATTENDEE;PARTSTAT=%s:%s
  260. ORGANIZER:%s
  261. UID:%s
  262. SEQUENCE:%s
  263. REQUEST-STATUS:2.0;Success
  264. %sEND:VEVENT
  265. END:VCALENDAR
  266. EOF;
  267. if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
  268. $partStat = 'ACCEPTED';
  269. } else {
  270. $partStat = 'DECLINED';
  271. }
  272. $vObject = Reader::read(vsprintf($message, [
  273. $partStat,
  274. $iTipMessage->recipient,
  275. $iTipMessage->sender,
  276. $uid,
  277. $sequence,
  278. $recurrenceId
  279. ]));
  280. $responseITipMessage = new ITip\Message();
  281. $responseITipMessage->uid = $uid;
  282. $responseITipMessage->component = 'VEVENT';
  283. $responseITipMessage->method = 'REPLY';
  284. $responseITipMessage->sequence = $sequence;
  285. $responseITipMessage->sender = $iTipMessage->recipient;
  286. $responseITipMessage->recipient = $iTipMessage->sender;
  287. $responseITipMessage->message = $vObject;
  288. // We can't dispatch them now already, because the organizers calendar-object
  289. // was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
  290. // send our reply.
  291. $this->schedulingResponses[] = $responseITipMessage;
  292. }
  293. /**
  294. * @param string $uri
  295. */
  296. public function dispatchSchedulingResponses(string $uri):void {
  297. if ($uri !== $this->pathOfCalendarObjectChange) {
  298. return;
  299. }
  300. foreach ($this->schedulingResponses as $schedulingResponse) {
  301. $this->scheduleLocalDelivery($schedulingResponse);
  302. }
  303. }
  304. /**
  305. * Always use the personal calendar as target for scheduled events
  306. *
  307. * @param PropFind $propFind
  308. * @param INode $node
  309. * @return void
  310. */
  311. public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
  312. if ($node instanceof IPrincipal) {
  313. $propFind->handle(self::SCHEDULE_DEFAULT_CALENDAR_URL, function () use ($node) {
  314. /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
  315. $caldavPlugin = $this->server->getPlugin('caldav');
  316. $principalUrl = $node->getPrincipalUrl();
  317. $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
  318. if (!$calendarHomePath) {
  319. return null;
  320. }
  321. $isResourceOrRoom = str_starts_with($principalUrl, 'principals/calendar-resources') ||
  322. str_starts_with($principalUrl, 'principals/calendar-rooms');
  323. if (str_starts_with($principalUrl, 'principals/users')) {
  324. [, $userId] = split($principalUrl);
  325. $uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
  326. $displayName = CalDavBackend::PERSONAL_CALENDAR_NAME;
  327. } elseif ($isResourceOrRoom) {
  328. $uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
  329. $displayName = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
  330. } else {
  331. // How did we end up here?
  332. // TODO - throw exception or just ignore?
  333. return null;
  334. }
  335. /** @var CalendarHome $calendarHome */
  336. $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
  337. $currentCalendarDeleted = false;
  338. if (!$calendarHome->childExists($uri) || $currentCalendarDeleted = $this->isCalendarDeleted($calendarHome, $uri)) {
  339. // If the default calendar doesn't exist
  340. if ($isResourceOrRoom) {
  341. // Resources or rooms can't be in the trashbin, so we're fine
  342. $this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
  343. } else {
  344. // And we're not handling scheduling on resource/room booking
  345. $userCalendars = [];
  346. /**
  347. * If the default calendar of the user isn't set and the
  348. * fallback doesn't match any of the user's calendar
  349. * try to find the first "personal" calendar we can write to
  350. * instead of creating a new one.
  351. * A appropriate personal calendar to receive invites:
  352. * - isn't a calendar subscription
  353. * - user can write to it (no virtual/3rd-party calendars)
  354. * - calendar isn't a share
  355. * - calendar supports VEVENTs
  356. */
  357. foreach ($calendarHome->getChildren() as $node) {
  358. if (!($node instanceof Calendar)) {
  359. continue;
  360. }
  361. try {
  362. $this->defaultCalendarValidator->validateScheduleDefaultCalendar($node);
  363. } catch (DavException $e) {
  364. continue;
  365. }
  366. $userCalendars[] = $node;
  367. }
  368. if (count($userCalendars) > 0) {
  369. // Calendar backend returns calendar by calendarorder property
  370. $uri = $userCalendars[0]->getName();
  371. } else {
  372. // Otherwise if we have really nothing, create a new calendar
  373. if ($currentCalendarDeleted) {
  374. // If the calendar exists but is deleted, we need to purge it first
  375. // This may cause some issues in a non synchronous database setup
  376. $calendar = $this->getCalendar($calendarHome, $uri);
  377. if ($calendar instanceof Calendar) {
  378. $calendar->disableTrashbin();
  379. $calendar->delete();
  380. }
  381. }
  382. $this->createCalendar($calendarHome, $principalUrl, $uri, $displayName);
  383. }
  384. }
  385. }
  386. $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
  387. if (empty($result)) {
  388. return null;
  389. }
  390. return new LocalHref($result[0]['href']);
  391. });
  392. }
  393. }
  394. /**
  395. * Returns a list of addresses that are associated with a principal.
  396. *
  397. * @param string $principal
  398. * @return string|null
  399. */
  400. protected function getCalendarUserTypeForPrincipal($principal):?string {
  401. $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
  402. $properties = $this->server->getProperties(
  403. $principal,
  404. [$calendarUserType]
  405. );
  406. // If we can't find this information, we'll stop processing
  407. if (!isset($properties[$calendarUserType])) {
  408. return null;
  409. }
  410. return $properties[$calendarUserType];
  411. }
  412. /**
  413. * @param ITip\Message $iTipMessage
  414. * @return null|Property
  415. */
  416. private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
  417. /** @var VEvent $vevent */
  418. $vevent = $iTipMessage->message->VEVENT;
  419. $attendees = $vevent->select('ATTENDEE');
  420. foreach ($attendees as $attendee) {
  421. /** @var Property $attendee */
  422. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  423. return $attendee;
  424. }
  425. }
  426. return null;
  427. }
  428. /**
  429. * @param Property|null $attendee
  430. * @return bool
  431. */
  432. private function getAttendeeRSVP(?Property $attendee = null):bool {
  433. if ($attendee !== null) {
  434. $rsvp = $attendee->offsetGet('RSVP');
  435. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  436. return true;
  437. }
  438. }
  439. // RFC 5545 3.2.17: default RSVP is false
  440. return false;
  441. }
  442. /**
  443. * @param VEvent $vevent
  444. * @return Property\ICalendar\DateTime
  445. */
  446. private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
  447. if (isset($vevent->DTEND)) {
  448. return $vevent->DTEND;
  449. }
  450. if (isset($vevent->DURATION)) {
  451. $isFloating = $vevent->DTSTART->isFloating();
  452. /** @var Property\ICalendar\DateTime $end */
  453. $end = clone $vevent->DTSTART;
  454. $endDateTime = $end->getDateTime();
  455. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  456. $end->setDateTime($endDateTime, $isFloating);
  457. return $end;
  458. }
  459. if (!$vevent->DTSTART->hasTime()) {
  460. $isFloating = $vevent->DTSTART->isFloating();
  461. /** @var Property\ICalendar\DateTime $end */
  462. $end = clone $vevent->DTSTART;
  463. $endDateTime = $end->getDateTime();
  464. $endDateTime = $endDateTime->modify('+1 day');
  465. $end->setDateTime($endDateTime, $isFloating);
  466. return $end;
  467. }
  468. return clone $vevent->DTSTART;
  469. }
  470. /**
  471. * @param string $email
  472. * @param \DateTimeInterface $start
  473. * @param \DateTimeInterface $end
  474. * @param string $ignoreUID
  475. * @return bool
  476. */
  477. private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
  478. // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
  479. // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
  480. $aclPlugin = $this->server->getPlugin('acl');
  481. $this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
  482. $result = $aclPlugin->principalSearch(
  483. ['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
  484. [
  485. '{DAV:}principal-URL',
  486. '{' . self::NS_CALDAV . '}calendar-home-set',
  487. '{' . self::NS_CALDAV . '}schedule-inbox-URL',
  488. '{http://sabredav.org/ns}email-address',
  489. ]
  490. );
  491. $this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
  492. // Grabbing the calendar list
  493. $objects = [];
  494. $calendarTimeZone = new DateTimeZone('UTC');
  495. $homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
  496. /** @var \OCA\DAV\CalDAV\Calendar $node */
  497. foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
  498. if (!$node instanceof ICalendar) {
  499. continue;
  500. }
  501. // Getting the list of object uris within the time-range
  502. $urls = $node->calendarQuery([
  503. 'name' => 'VCALENDAR',
  504. 'comp-filters' => [
  505. [
  506. 'name' => 'VEVENT',
  507. 'is-not-defined' => false,
  508. 'time-range' => [
  509. 'start' => $start,
  510. 'end' => $end,
  511. ],
  512. 'comp-filters' => [],
  513. 'prop-filters' => [],
  514. ],
  515. [
  516. 'name' => 'VEVENT',
  517. 'is-not-defined' => false,
  518. 'time-range' => null,
  519. 'comp-filters' => [],
  520. 'prop-filters' => [
  521. [
  522. 'name' => 'UID',
  523. 'is-not-defined' => false,
  524. 'time-range' => null,
  525. 'text-match' => [
  526. 'value' => $ignoreUID,
  527. 'negate-condition' => true,
  528. 'collation' => 'i;octet',
  529. ],
  530. 'param-filters' => [],
  531. ],
  532. ]
  533. ],
  534. ],
  535. 'prop-filters' => [],
  536. 'is-not-defined' => false,
  537. 'time-range' => null,
  538. ]);
  539. foreach ($urls as $url) {
  540. $objects[] = $node->getChild($url)->get();
  541. }
  542. }
  543. $inboxProps = $this->server->getProperties(
  544. $result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
  545. ['{' . self::NS_CALDAV . '}calendar-availability']
  546. );
  547. $vcalendar = new VCalendar();
  548. $vcalendar->METHOD = 'REPLY';
  549. $generator = new FreeBusyGenerator();
  550. $generator->setObjects($objects);
  551. $generator->setTimeRange($start, $end);
  552. $generator->setBaseObject($vcalendar);
  553. $generator->setTimeZone($calendarTimeZone);
  554. if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
  555. $generator->setVAvailability(
  556. Reader::read(
  557. $inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
  558. )
  559. );
  560. }
  561. $result = $generator->getResult();
  562. if (!isset($result->VFREEBUSY)) {
  563. return false;
  564. }
  565. /** @var Component $freeBusyComponent */
  566. $freeBusyComponent = $result->VFREEBUSY;
  567. $freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
  568. // If there is no Free-busy property at all, the time-range is empty and available
  569. if (count($freeBusyProperties) === 0) {
  570. return true;
  571. }
  572. // If more than one Free-Busy property was returned, it means that an event
  573. // starts or ends inside this time-range, so it's not available and we return false
  574. if (count($freeBusyProperties) > 1) {
  575. return false;
  576. }
  577. /** @var Property $freeBusyProperty */
  578. $freeBusyProperty = $freeBusyProperties[0];
  579. if (!$freeBusyProperty->offsetExists('FBTYPE')) {
  580. // If there is no FBTYPE, it means it's busy
  581. return false;
  582. }
  583. $fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
  584. if (!($fbTypeParameter instanceof Parameter)) {
  585. return false;
  586. }
  587. return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
  588. }
  589. /**
  590. * @param string $email
  591. * @return string
  592. */
  593. private function stripOffMailTo(string $email): string {
  594. if (stripos($email, 'mailto:') === 0) {
  595. return substr($email, 7);
  596. }
  597. return $email;
  598. }
  599. private function getCalendar(CalendarHome $calendarHome, string $uri): INode {
  600. return $calendarHome->getChild($uri);
  601. }
  602. private function isCalendarDeleted(CalendarHome $calendarHome, string $uri): bool {
  603. $calendar = $this->getCalendar($calendarHome, $uri);
  604. return $calendar instanceof Calendar && $calendar->isDeleted();
  605. }
  606. private function createCalendar(CalendarHome $calendarHome, string $principalUri, string $uri, string $displayName): void {
  607. $calendarHome->getCalDAVBackend()->createCalendar($principalUri, $uri, [
  608. '{DAV:}displayname' => $displayName,
  609. ]);
  610. }
  611. /**
  612. * Try to handle the given exception gracefully or throw it if necessary.
  613. *
  614. * @throws SameOrganizerForAllComponentsException If the exception should not be ignored
  615. */
  616. private function handleSameOrganizerException(
  617. SameOrganizerForAllComponentsException $e,
  618. VCalendar $vCal,
  619. string $calendarPath,
  620. ): void {
  621. // This is very hacky! However, we want to allow saving events with multiple
  622. // organizers. Those events are not RFC compliant, but sometimes imported from major
  623. // external calendar services (e.g. Google). If the current user is not an organizer of
  624. // the event we ignore the exception as no scheduling messages will be sent anyway.
  625. // It would be cleaner to patch Sabre to validate organizers *after* checking if
  626. // scheduling messages are necessary. Currently, organizers are validated first and
  627. // afterwards the broker checks if messages should be scheduled. So the code will throw
  628. // even if the organizers are not relevant. This is to ensure compliance with RFCs but
  629. // a bit too strict for real world usage.
  630. if (!isset($vCal->VEVENT)) {
  631. throw $e;
  632. }
  633. $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
  634. if (!($calendarNode instanceof IACL)) {
  635. // Should always be an instance of IACL but just to be sure
  636. throw $e;
  637. }
  638. $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
  639. foreach ($vCal->VEVENT as $vevent) {
  640. if (in_array($vevent->ORGANIZER->getNormalizedValue(), $addresses, true)) {
  641. // User is an organizer => throw the exception
  642. throw $e;
  643. }
  644. }
  645. }
  646. }