Plugin.php 22 KB

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