Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2017, Georg Ehrke <oc.list@georgehrke.com>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Georg Ehrke <oc.list@georgehrke.com>
  8. * @author Anna Larch <anna.larch@gmx.net>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Calendar;
  27. use OC\AppFramework\Bootstrap\Coordinator;
  28. use OCP\AppFramework\Utility\ITimeFactory;
  29. use OCP\Calendar\Exceptions\CalendarException;
  30. use OCP\Calendar\ICalendar;
  31. use OCP\Calendar\ICalendarProvider;
  32. use OCP\Calendar\ICalendarQuery;
  33. use OCP\Calendar\ICreateFromString;
  34. use OCP\Calendar\IHandleImipMessage;
  35. use OCP\Calendar\IManager;
  36. use Psr\Container\ContainerInterface;
  37. use Psr\Log\LoggerInterface;
  38. use Sabre\VObject\Component\VCalendar;
  39. use Sabre\VObject\Component\VEvent;
  40. use Sabre\VObject\Property\VCard\DateTime;
  41. use Sabre\VObject\Reader;
  42. use Throwable;
  43. use function array_map;
  44. use function array_merge;
  45. class Manager implements IManager {
  46. /**
  47. * @var ICalendar[] holds all registered calendars
  48. */
  49. private array $calendars = [];
  50. /**
  51. * @var \Closure[] to call to load/register calendar providers
  52. */
  53. private array $calendarLoaders = [];
  54. public function __construct(
  55. private Coordinator $coordinator,
  56. private ContainerInterface $container,
  57. private LoggerInterface $logger,
  58. private ITimeFactory $timeFactory,
  59. ) {
  60. }
  61. /**
  62. * This function is used to search and find objects within the user's calendars.
  63. * In case $pattern is empty all events/journals/todos will be returned.
  64. *
  65. * @param string $pattern which should match within the $searchProperties
  66. * @param array $searchProperties defines the properties within the query pattern should match
  67. * @param array $options - optional parameters:
  68. * ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
  69. * @param integer|null $limit - limit number of search results
  70. * @param integer|null $offset - offset for paging of search results
  71. * @return array an array of events/journals/todos which are arrays of arrays of key-value-pairs
  72. * @since 13.0.0
  73. */
  74. public function search(
  75. $pattern,
  76. array $searchProperties = [],
  77. array $options = [],
  78. $limit = null,
  79. $offset = null,
  80. ): array {
  81. $this->loadCalendars();
  82. $result = [];
  83. foreach ($this->calendars as $calendar) {
  84. $r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset);
  85. foreach ($r as $o) {
  86. $o['calendar-key'] = $calendar->getKey();
  87. $result[] = $o;
  88. }
  89. }
  90. return $result;
  91. }
  92. /**
  93. * Check if calendars are available
  94. *
  95. * @return bool true if enabled, false if not
  96. * @since 13.0.0
  97. */
  98. public function isEnabled(): bool {
  99. return !empty($this->calendars) || !empty($this->calendarLoaders);
  100. }
  101. /**
  102. * Registers a calendar
  103. *
  104. * @since 13.0.0
  105. */
  106. public function registerCalendar(ICalendar $calendar): void {
  107. $this->calendars[$calendar->getKey()] = $calendar;
  108. }
  109. /**
  110. * Unregisters a calendar
  111. *
  112. * @since 13.0.0
  113. */
  114. public function unregisterCalendar(ICalendar $calendar): void {
  115. unset($this->calendars[$calendar->getKey()]);
  116. }
  117. /**
  118. * In order to improve lazy loading a closure can be registered which will be called in case
  119. * calendars are actually requested
  120. *
  121. * @since 13.0.0
  122. */
  123. public function register(\Closure $callable): void {
  124. $this->calendarLoaders[] = $callable;
  125. }
  126. /**
  127. * @return ICalendar[]
  128. *
  129. * @since 13.0.0
  130. */
  131. public function getCalendars(): array {
  132. $this->loadCalendars();
  133. return array_values($this->calendars);
  134. }
  135. /**
  136. * removes all registered calendar instances
  137. *
  138. * @since 13.0.0
  139. */
  140. public function clear(): void {
  141. $this->calendars = [];
  142. $this->calendarLoaders = [];
  143. }
  144. /**
  145. * loads all calendars
  146. */
  147. private function loadCalendars(): void {
  148. foreach ($this->calendarLoaders as $callable) {
  149. $callable($this);
  150. }
  151. $this->calendarLoaders = [];
  152. }
  153. /**
  154. * @return ICreateFromString[]
  155. */
  156. public function getCalendarsForPrincipal(string $principalUri, array $calendarUris = []): array {
  157. $context = $this->coordinator->getRegistrationContext();
  158. if ($context === null) {
  159. return [];
  160. }
  161. return array_merge(
  162. ...array_map(function ($registration) use ($principalUri, $calendarUris) {
  163. try {
  164. /** @var ICalendarProvider $provider */
  165. $provider = $this->container->get($registration->getService());
  166. } catch (Throwable $e) {
  167. $this->logger->error('Could not load calendar provider ' . $registration->getService() . ': ' . $e->getMessage(), [
  168. 'exception' => $e,
  169. ]);
  170. return [];
  171. }
  172. return $provider->getCalendars($principalUri, $calendarUris);
  173. }, $context->getCalendarProviders())
  174. );
  175. }
  176. public function searchForPrincipal(ICalendarQuery $query): array {
  177. /** @var CalendarQuery $query */
  178. $calendars = $this->getCalendarsForPrincipal(
  179. $query->getPrincipalUri(),
  180. $query->getCalendarUris(),
  181. );
  182. $results = [];
  183. foreach ($calendars as $calendar) {
  184. $r = $calendar->search(
  185. $query->getSearchPattern() ?? '',
  186. $query->getSearchProperties(),
  187. $query->getOptions(),
  188. $query->getLimit(),
  189. $query->getOffset()
  190. );
  191. foreach ($r as $o) {
  192. $o['calendar-key'] = $calendar->getKey();
  193. $results[] = $o;
  194. }
  195. }
  196. return $results;
  197. }
  198. public function newQuery(string $principalUri): ICalendarQuery {
  199. return new CalendarQuery($principalUri);
  200. }
  201. /**
  202. * @throws \OCP\DB\Exception
  203. */
  204. public function handleIMipReply(
  205. string $principalUri,
  206. string $sender,
  207. string $recipient,
  208. string $calendarData,
  209. ): bool {
  210. /** @var VCalendar $vObject|null */
  211. $vObject = Reader::read($calendarData);
  212. if ($vObject === null) {
  213. return false;
  214. }
  215. /** @var VEvent|null $vEvent */
  216. $vEvent = $vObject->{'VEVENT'};
  217. if ($vEvent === null) {
  218. return false;
  219. }
  220. // First, we check if the correct method is passed to us
  221. if (strcasecmp('REPLY', $vObject->{'METHOD'}->getValue()) !== 0) {
  222. $this->logger->warning('Wrong method provided for processing');
  223. return false;
  224. }
  225. // check if mail recipient and organizer are one and the same
  226. $organizer = substr($vEvent->{'ORGANIZER'}->getValue(), 7);
  227. if (strcasecmp($recipient, $organizer) !== 0) {
  228. $this->logger->warning('Recipient and ORGANIZER must be identical');
  229. return false;
  230. }
  231. //check if the event is in the future
  232. /** @var DateTime $eventTime */
  233. $eventTime = $vEvent->{'DTSTART'};
  234. if ($eventTime->getDateTime()->getTimeStamp() < $this->timeFactory->getTime()) { // this might cause issues with recurrences
  235. $this->logger->warning('Only events in the future are processed');
  236. return false;
  237. }
  238. $calendars = $this->getCalendarsForPrincipal($principalUri);
  239. if (empty($calendars)) {
  240. $this->logger->warning('Could not find any calendars for principal ' . $principalUri);
  241. return false;
  242. }
  243. $found = null;
  244. // if the attendee has been found in at least one calendar event with the UID of the iMIP event
  245. // we process it.
  246. // Benefit: no attendee lost
  247. // Drawback: attendees that have been deleted will still be able to update their partstat
  248. foreach ($calendars as $calendar) {
  249. // We should not search in writable calendars
  250. if ($calendar instanceof IHandleImipMessage) {
  251. $o = $calendar->search($sender, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
  252. if (!empty($o)) {
  253. $found = $calendar;
  254. $name = $o[0]['uri'];
  255. break;
  256. }
  257. }
  258. }
  259. if (empty($found)) {
  260. $this->logger->info('Event not found in any calendar for principal ' . $principalUri . 'and UID' . $vEvent->{'UID'}->getValue());
  261. return false;
  262. }
  263. try {
  264. $found->handleIMipMessage($name, $calendarData); // sabre will handle the scheduling behind the scenes
  265. } catch (CalendarException $e) {
  266. $this->logger->error('Could not update calendar for iMIP processing', ['exception' => $e]);
  267. return false;
  268. }
  269. return true;
  270. }
  271. /**
  272. * @since 25.0.0
  273. * @throws \OCP\DB\Exception
  274. */
  275. public function handleIMipCancel(
  276. string $principalUri,
  277. string $sender,
  278. ?string $replyTo,
  279. string $recipient,
  280. string $calendarData,
  281. ): bool {
  282. /** @var VCalendar $vObject|null */
  283. $vObject = Reader::read($calendarData);
  284. if ($vObject === null) {
  285. return false;
  286. }
  287. /** @var VEvent|null $vEvent */
  288. $vEvent = $vObject->{'VEVENT'};
  289. if ($vEvent === null) {
  290. return false;
  291. }
  292. // First, we check if the correct method is passed to us
  293. if (strcasecmp('CANCEL', $vObject->{'METHOD'}->getValue()) !== 0) {
  294. $this->logger->warning('Wrong method provided for processing');
  295. return false;
  296. }
  297. $attendee = substr($vEvent->{'ATTENDEE'}->getValue(), 7);
  298. if (strcasecmp($recipient, $attendee) !== 0) {
  299. $this->logger->warning('Recipient must be an ATTENDEE of this event');
  300. return false;
  301. }
  302. // Thirdly, we need to compare the email address the CANCEL is coming from (in Mail)
  303. // or the Reply- To Address submitted with the CANCEL email
  304. // to the email address in the ORGANIZER.
  305. // We don't want to accept a CANCEL request from just anyone
  306. $organizer = substr($vEvent->{'ORGANIZER'}->getValue(), 7);
  307. $isNotOrganizer = ($replyTo !== null) ? (strcasecmp($sender, $organizer) !== 0 && strcasecmp($replyTo, $organizer) !== 0) : (strcasecmp($sender, $organizer) !== 0);
  308. if ($isNotOrganizer) {
  309. $this->logger->warning('Sender must be the ORGANIZER of this event');
  310. return false;
  311. }
  312. //check if the event is in the future
  313. /** @var DateTime $eventTime */
  314. $eventTime = $vEvent->{'DTSTART'};
  315. if ($eventTime->getDateTime()->getTimeStamp() < $this->timeFactory->getTime()) { // this might cause issues with recurrences
  316. $this->logger->warning('Only events in the future are processed');
  317. return false;
  318. }
  319. // Check if we have a calendar to work with
  320. $calendars = $this->getCalendarsForPrincipal($principalUri);
  321. if (empty($calendars)) {
  322. $this->logger->warning('Could not find any calendars for principal ' . $principalUri);
  323. return false;
  324. }
  325. $found = null;
  326. // if the attendee has been found in at least one calendar event with the UID of the iMIP event
  327. // we process it.
  328. // Benefit: no attendee lost
  329. // Drawback: attendees that have been deleted will still be able to update their partstat
  330. foreach ($calendars as $calendar) {
  331. // We should not search in writable calendars
  332. if ($calendar instanceof IHandleImipMessage) {
  333. $o = $calendar->search($recipient, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
  334. if (!empty($o)) {
  335. $found = $calendar;
  336. $name = $o[0]['uri'];
  337. break;
  338. }
  339. }
  340. }
  341. if (empty($found)) {
  342. $this->logger->info('Event not found in any calendar for principal ' . $principalUri . 'and UID' . $vEvent->{'UID'}->getValue());
  343. // this is a safe operation
  344. // we can ignore events that have been cancelled but were not in the calendar anyway
  345. return true;
  346. }
  347. try {
  348. $found->handleIMipMessage($name, $calendarData); // sabre will handle the scheduling behind the scenes
  349. return true;
  350. } catch (CalendarException $e) {
  351. $this->logger->error('Could not update calendar for iMIP processing', ['exception' => $e]);
  352. return false;
  353. }
  354. }
  355. }