Plugin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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 OCA\DAV\CalDAV\DefaultCalendarValidator;
  36. use OCA\DAV\CalDAV\TipBroker;
  37. use OCP\IConfig;
  38. use Psr\Log\LoggerInterface;
  39. use Sabre\CalDAV\ICalendar;
  40. use Sabre\CalDAV\ICalendarObject;
  41. use Sabre\CalDAV\Schedule\ISchedulingObject;
  42. use Sabre\DAV\Exception as DavException;
  43. use Sabre\DAV\INode;
  44. use Sabre\DAV\IProperties;
  45. use Sabre\DAV\PropFind;
  46. use Sabre\DAV\Server;
  47. use Sabre\DAV\Xml\Property\LocalHref;
  48. use Sabre\DAVACL\IACL;
  49. use Sabre\DAVACL\IPrincipal;
  50. use Sabre\HTTP\RequestInterface;
  51. use Sabre\HTTP\ResponseInterface;
  52. use Sabre\VObject\Component;
  53. use Sabre\VObject\Component\VCalendar;
  54. use Sabre\VObject\Component\VEvent;
  55. use Sabre\VObject\DateTimeParser;
  56. use Sabre\VObject\FreeBusyGenerator;
  57. use Sabre\VObject\ITip;
  58. use Sabre\VObject\ITip\SameOrganizerForAllComponentsException;
  59. use Sabre\VObject\Parameter;
  60. use Sabre\VObject\Property;
  61. use Sabre\VObject\Reader;
  62. use function Sabre\Uri\split;
  63. class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
  64. /**
  65. * @var IConfig
  66. */
  67. private $config;
  68. /** @var ITip\Message[] */
  69. private $schedulingResponses = [];
  70. /** @var string|null */
  71. private $pathOfCalendarObjectChange = null;
  72. public const CALENDAR_USER_TYPE = '{' . self::NS_CALDAV . '}calendar-user-type';
  73. public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . Plugin::NS_CALDAV . '}schedule-default-calendar-URL';
  74. private LoggerInterface $logger;
  75. private DefaultCalendarValidator $defaultCalendarValidator;
  76. /**
  77. * @param IConfig $config
  78. */
  79. public function __construct(IConfig $config, LoggerInterface $logger, DefaultCalendarValidator $defaultCalendarValidator) {
  80. $this->config = $config;
  81. $this->logger = $logger;
  82. $this->defaultCalendarValidator = $defaultCalendarValidator;
  83. }
  84. /**
  85. * Initializes the plugin
  86. *
  87. * @param Server $server
  88. * @return void
  89. */
  90. public function initialize(Server $server) {
  91. parent::initialize($server);
  92. $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
  93. $server->on('afterWriteContent', [$this, 'dispatchSchedulingResponses']);
  94. $server->on('afterCreateFile', [$this, 'dispatchSchedulingResponses']);
  95. // We allow mutating the default calendar URL through the CustomPropertiesBackend
  96. // (oc_properties table)
  97. $server->protectedProperties = array_filter(
  98. $server->protectedProperties,
  99. static fn (string $property) => $property !== self::SCHEDULE_DEFAULT_CALENDAR_URL,
  100. );
  101. }
  102. /**
  103. * Returns an instance of the iTip\Broker.
  104. */
  105. protected function createITipBroker(): TipBroker {
  106. return new TipBroker();
  107. }
  108. /**
  109. * Allow manual setting of the object change URL
  110. * to support public write
  111. *
  112. * @param string $path
  113. */
  114. public function setPathOfCalendarObjectChange(string $path): void {
  115. $this->pathOfCalendarObjectChange = $path;
  116. }
  117. /**
  118. * This method handler is invoked during fetching of properties.
  119. *
  120. * We use this event to add calendar-auto-schedule-specific properties.
  121. *
  122. * @param PropFind $propFind
  123. * @param INode $node
  124. * @return void
  125. */
  126. public function propFind(PropFind $propFind, INode $node) {
  127. if ($node instanceof IPrincipal) {
  128. // overwrite Sabre/Dav's implementation
  129. $propFind->handle(self::CALENDAR_USER_TYPE, function () use ($node) {
  130. if ($node instanceof IProperties) {
  131. $props = $node->getProperties([self::CALENDAR_USER_TYPE]);
  132. if (isset($props[self::CALENDAR_USER_TYPE])) {
  133. return $props[self::CALENDAR_USER_TYPE];
  134. }
  135. }
  136. return 'INDIVIDUAL';
  137. });
  138. }
  139. parent::propFind($propFind, $node);
  140. }
  141. /**
  142. * Returns a list of addresses that are associated with a principal.
  143. *
  144. * @param string $principal
  145. * @return array
  146. */
  147. protected function getAddressesForPrincipal($principal) {
  148. $result = parent::getAddressesForPrincipal($principal);
  149. if ($result === null) {
  150. $result = [];
  151. }
  152. // iterate through items and html decode values
  153. foreach ($result as $key => $value) {
  154. $result[$key] = urldecode($value);
  155. }
  156. return $result;
  157. }
  158. /**
  159. * @param RequestInterface $request
  160. * @param ResponseInterface $response
  161. * @param VCalendar $vCal
  162. * @param mixed $calendarPath
  163. * @param mixed $modified
  164. * @param mixed $isNew
  165. */
  166. public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
  167. // Save the first path we get as a calendar-object-change request
  168. if (!$this->pathOfCalendarObjectChange) {
  169. $this->pathOfCalendarObjectChange = $request->getPath();
  170. }
  171. try {
  172. parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
  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. foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
  497. if (!$node instanceof ICalendar) {
  498. continue;
  499. }
  500. // Getting the list of object uris within the time-range
  501. $urls = $node->calendarQuery([
  502. 'name' => 'VCALENDAR',
  503. 'comp-filters' => [
  504. [
  505. 'name' => 'VEVENT',
  506. 'is-not-defined' => false,
  507. 'time-range' => [
  508. 'start' => $start,
  509. 'end' => $end,
  510. ],
  511. 'comp-filters' => [],
  512. 'prop-filters' => [],
  513. ],
  514. [
  515. 'name' => 'VEVENT',
  516. 'is-not-defined' => false,
  517. 'time-range' => null,
  518. 'comp-filters' => [],
  519. 'prop-filters' => [
  520. [
  521. 'name' => 'UID',
  522. 'is-not-defined' => false,
  523. 'time-range' => null,
  524. 'text-match' => [
  525. 'value' => $ignoreUID,
  526. 'negate-condition' => true,
  527. 'collation' => 'i;octet',
  528. ],
  529. 'param-filters' => [],
  530. ],
  531. ]
  532. ],
  533. ],
  534. 'prop-filters' => [],
  535. 'is-not-defined' => false,
  536. 'time-range' => null,
  537. ]);
  538. foreach ($urls as $url) {
  539. $objects[] = $node->getChild($url)->get();
  540. }
  541. }
  542. $inboxProps = $this->server->getProperties(
  543. $result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
  544. ['{' . self::NS_CALDAV . '}calendar-availability']
  545. );
  546. $vcalendar = new VCalendar();
  547. $vcalendar->METHOD = 'REPLY';
  548. $generator = new FreeBusyGenerator();
  549. $generator->setObjects($objects);
  550. $generator->setTimeRange($start, $end);
  551. $generator->setBaseObject($vcalendar);
  552. $generator->setTimeZone($calendarTimeZone);
  553. if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
  554. $generator->setVAvailability(
  555. Reader::read(
  556. $inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
  557. )
  558. );
  559. }
  560. $result = $generator->getResult();
  561. if (!isset($result->VFREEBUSY)) {
  562. return false;
  563. }
  564. /** @var Component $freeBusyComponent */
  565. $freeBusyComponent = $result->VFREEBUSY;
  566. $freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
  567. // If there is no Free-busy property at all, the time-range is empty and available
  568. if (count($freeBusyProperties) === 0) {
  569. return true;
  570. }
  571. // If more than one Free-Busy property was returned, it means that an event
  572. // starts or ends inside this time-range, so it's not available and we return false
  573. if (count($freeBusyProperties) > 1) {
  574. return false;
  575. }
  576. /** @var Property $freeBusyProperty */
  577. $freeBusyProperty = $freeBusyProperties[0];
  578. if (!$freeBusyProperty->offsetExists('FBTYPE')) {
  579. // If there is no FBTYPE, it means it's busy
  580. return false;
  581. }
  582. $fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
  583. if (!($fbTypeParameter instanceof Parameter)) {
  584. return false;
  585. }
  586. return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
  587. }
  588. /**
  589. * @param string $email
  590. * @return string
  591. */
  592. private function stripOffMailTo(string $email): string {
  593. if (stripos($email, 'mailto:') === 0) {
  594. return substr($email, 7);
  595. }
  596. return $email;
  597. }
  598. private function getCalendar(CalendarHome $calendarHome, string $uri): INode {
  599. return $calendarHome->getChild($uri);
  600. }
  601. private function isCalendarDeleted(CalendarHome $calendarHome, string $uri): bool {
  602. $calendar = $this->getCalendar($calendarHome, $uri);
  603. return $calendar instanceof Calendar && $calendar->isDeleted();
  604. }
  605. private function createCalendar(CalendarHome $calendarHome, string $principalUri, string $uri, string $displayName): void {
  606. $calendarHome->getCalDAVBackend()->createCalendar($principalUri, $uri, [
  607. '{DAV:}displayname' => $displayName,
  608. ]);
  609. }
  610. /**
  611. * Try to handle the given exception gracefully or throw it if necessary.
  612. *
  613. * @throws SameOrganizerForAllComponentsException If the exception should not be ignored
  614. */
  615. private function handleSameOrganizerException(
  616. SameOrganizerForAllComponentsException $e,
  617. VCalendar $vCal,
  618. string $calendarPath,
  619. ): void {
  620. // This is very hacky! However, we want to allow saving events with multiple
  621. // organizers. Those events are not RFC compliant, but sometimes imported from major
  622. // external calendar services (e.g. Google). If the current user is not an organizer of
  623. // the event we ignore the exception as no scheduling messages will be sent anyway.
  624. // It would be cleaner to patch Sabre to validate organizers *after* checking if
  625. // scheduling messages are necessary. Currently, organizers are validated first and
  626. // afterwards the broker checks if messages should be scheduled. So the code will throw
  627. // even if the organizers are not relevant. This is to ensure compliance with RFCs but
  628. // a bit too strict for real world usage.
  629. if (!isset($vCal->VEVENT)) {
  630. throw $e;
  631. }
  632. $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
  633. if (!($calendarNode instanceof IACL)) {
  634. // Should always be an instance of IACL but just to be sure
  635. throw $e;
  636. }
  637. $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
  638. foreach ($vCal->VEVENT as $vevent) {
  639. if (in_array($vevent->ORGANIZER->getNormalizedValue(), $addresses, true)) {
  640. // User is an organizer => throw the exception
  641. throw $e;
  642. }
  643. }
  644. }
  645. }