Manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 */
  211. $vObject = Reader::read($calendarData);
  212. /** @var VEvent $vEvent */
  213. $vEvent = $vObject->{'VEVENT'};
  214. // First, we check if the correct method is passed to us
  215. if (strcasecmp('REPLY', $vObject->{'METHOD'}->getValue()) !== 0) {
  216. $this->logger->warning('Wrong method provided for processing');
  217. return false;
  218. }
  219. // check if mail recipient and organizer are one and the same
  220. $organizer = substr($vEvent->{'ORGANIZER'}->getValue(), 7);
  221. if (strcasecmp($recipient, $organizer) !== 0) {
  222. $this->logger->warning('Recipient and ORGANIZER must be identical');
  223. return false;
  224. }
  225. //check if the event is in the future
  226. /** @var DateTime $eventTime */
  227. $eventTime = $vEvent->{'DTSTART'};
  228. if ($eventTime->getDateTime()->getTimeStamp() < $this->timeFactory->getTime()) { // this might cause issues with recurrences
  229. $this->logger->warning('Only events in the future are processed');
  230. return false;
  231. }
  232. $calendars = $this->getCalendarsForPrincipal($principalUri);
  233. if (empty($calendars)) {
  234. $this->logger->warning('Could not find any calendars for principal ' . $principalUri);
  235. return false;
  236. }
  237. $found = null;
  238. // if the attendee has been found in at least one calendar event with the UID of the iMIP event
  239. // we process it.
  240. // Benefit: no attendee lost
  241. // Drawback: attendees that have been deleted will still be able to update their partstat
  242. foreach ($calendars as $calendar) {
  243. // We should not search in writable calendars
  244. if ($calendar instanceof IHandleImipMessage) {
  245. $o = $calendar->search($sender, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
  246. if (!empty($o)) {
  247. $found = $calendar;
  248. $name = $o[0]['uri'];
  249. break;
  250. }
  251. }
  252. }
  253. if (empty($found)) {
  254. $this->logger->info('Event not found in any calendar for principal ' . $principalUri . 'and UID' . $vEvent->{'UID'}->getValue());
  255. return false;
  256. }
  257. try {
  258. $found->handleIMipMessage($name, $calendarData); // sabre will handle the scheduling behind the scenes
  259. } catch (CalendarException $e) {
  260. $this->logger->error('Could not update calendar for iMIP processing', ['exception' => $e]);
  261. return false;
  262. }
  263. return true;
  264. }
  265. /**
  266. * @since 25.0.0
  267. * @throws \OCP\DB\Exception
  268. */
  269. public function handleIMipCancel(
  270. string $principalUri,
  271. string $sender,
  272. ?string $replyTo,
  273. string $recipient,
  274. string $calendarData,
  275. ): bool {
  276. $vObject = Reader::read($calendarData);
  277. /** @var VEvent $vEvent */
  278. $vEvent = $vObject->{'VEVENT'};
  279. // First, we check if the correct method is passed to us
  280. if (strcasecmp('CANCEL', $vObject->{'METHOD'}->getValue()) !== 0) {
  281. $this->logger->warning('Wrong method provided for processing');
  282. return false;
  283. }
  284. $attendee = substr($vEvent->{'ATTENDEE'}->getValue(), 7);
  285. if (strcasecmp($recipient, $attendee) !== 0) {
  286. $this->logger->warning('Recipient must be an ATTENDEE of this event');
  287. return false;
  288. }
  289. // Thirdly, we need to compare the email address the CANCEL is coming from (in Mail)
  290. // or the Reply- To Address submitted with the CANCEL email
  291. // to the email address in the ORGANIZER.
  292. // We don't want to accept a CANCEL request from just anyone
  293. $organizer = substr($vEvent->{'ORGANIZER'}->getValue(), 7);
  294. $isNotOrganizer = ($replyTo !== null) ? (strcasecmp($sender, $organizer) !== 0 && strcasecmp($replyTo, $organizer) !== 0) : (strcasecmp($sender, $organizer) !== 0);
  295. if ($isNotOrganizer) {
  296. $this->logger->warning('Sender must be the ORGANIZER of this event');
  297. return false;
  298. }
  299. //check if the event is in the future
  300. /** @var DateTime $eventTime */
  301. $eventTime = $vEvent->{'DTSTART'};
  302. if ($eventTime->getDateTime()->getTimeStamp() < $this->timeFactory->getTime()) { // this might cause issues with recurrences
  303. $this->logger->warning('Only events in the future are processed');
  304. return false;
  305. }
  306. // Check if we have a calendar to work with
  307. $calendars = $this->getCalendarsForPrincipal($principalUri);
  308. if (empty($calendars)) {
  309. $this->logger->warning('Could not find any calendars for principal ' . $principalUri);
  310. return false;
  311. }
  312. $found = null;
  313. // if the attendee has been found in at least one calendar event with the UID of the iMIP event
  314. // we process it.
  315. // Benefit: no attendee lost
  316. // Drawback: attendees that have been deleted will still be able to update their partstat
  317. foreach ($calendars as $calendar) {
  318. // We should not search in writable calendars
  319. if ($calendar instanceof IHandleImipMessage) {
  320. $o = $calendar->search($recipient, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
  321. if (!empty($o)) {
  322. $found = $calendar;
  323. $name = $o[0]['uri'];
  324. break;
  325. }
  326. }
  327. }
  328. if (empty($found)) {
  329. $this->logger->info('Event not found in any calendar for principal ' . $principalUri . 'and UID' . $vEvent->{'UID'}->getValue());
  330. // this is a safe operation
  331. // we can ignore events that have been cancelled but were not in the calendar anyway
  332. return true;
  333. }
  334. try {
  335. $found->handleIMipMessage($name, $calendarData); // sabre will handle the scheduling behind the scenes
  336. return true;
  337. } catch (CalendarException $e) {
  338. $this->logger->error('Could not update calendar for iMIP processing', ['exception' => $e]);
  339. return false;
  340. }
  341. }
  342. }