Plugin.php 22 KB

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