Passed
Push — master ( bbb39c...5026d2 )
by Christoph
27:34 queued 12:27
created
apps/dav/lib/CalDAV/Schedule/Plugin.php 1 patch
Indentation   +486 added lines, -486 removed lines patch added patch discarded remove patch
@@ -55,165 +55,165 @@  discard block
 block discarded – undo
55 55
 
56 56
 class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
57 57
 
58
-	/**
59
-	 * @var IConfig
60
-	 */
61
-	private $config;
62
-
63
-	/** @var ITip\Message[] */
64
-	private $schedulingResponses = [];
65
-
66
-	/** @var string|null */
67
-	private $pathOfCalendarObjectChange = null;
68
-
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
-
72
-	/**
73
-	 * @param IConfig $config
74
-	 */
75
-	public function __construct(IConfig $config) {
76
-		$this->config = $config;
77
-	}
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
-	/**
93
-	 * This method handler is invoked during fetching of properties.
94
-	 *
95
-	 * We use this event to add calendar-auto-schedule-specific properties.
96
-	 *
97
-	 * @param PropFind $propFind
98
-	 * @param INode $node
99
-	 * @return void
100
-	 */
101
-	public function propFind(PropFind $propFind, INode $node) {
102
-		if ($node instanceof IPrincipal) {
103
-			// overwrite Sabre/Dav's implementation
104
-			$propFind->handle(self::CALENDAR_USER_TYPE, function () use ($node) {
105
-				if ($node instanceof IProperties) {
106
-					$props = $node->getProperties([self::CALENDAR_USER_TYPE]);
107
-
108
-					if (isset($props[self::CALENDAR_USER_TYPE])) {
109
-						return $props[self::CALENDAR_USER_TYPE];
110
-					}
111
-				}
112
-
113
-				return 'INDIVIDUAL';
114
-			});
115
-		}
116
-
117
-		parent::propFind($propFind, $node);
118
-	}
119
-
120
-	/**
121
-	 * Returns a list of addresses that are associated with a principal.
122
-	 *
123
-	 * @param string $principal
124
-	 * @return array
125
-	 */
126
-	protected function getAddressesForPrincipal($principal) {
127
-		$result = parent::getAddressesForPrincipal($principal);
128
-
129
-		if ($result === null) {
130
-			$result = [];
131
-		}
132
-
133
-		return $result;
134
-	}
135
-
136
-	/**
137
-	 * @param RequestInterface $request
138
-	 * @param ResponseInterface $response
139
-	 * @param VCalendar $vCal
140
-	 * @param mixed $calendarPath
141
-	 * @param mixed $modified
142
-	 * @param mixed $isNew
143
-	 */
144
-	public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
145
-		// Save the first path we get as a calendar-object-change request
146
-		if (!$this->pathOfCalendarObjectChange) {
147
-			$this->pathOfCalendarObjectChange = $request->getPath();
148
-		}
149
-
150
-		parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
151
-	}
152
-
153
-	/**
154
-	 * @inheritDoc
155
-	 */
156
-	public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
157
-		parent::scheduleLocalDelivery($iTipMessage);
158
-
159
-		// We only care when the message was successfully delivered locally
160
-		if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
161
-			return;
162
-		}
163
-
164
-		// We only care about request. reply and cancel are properly handled
165
-		// by parent::scheduleLocalDelivery already
166
-		if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
167
-			return;
168
-		}
169
-
170
-		// If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
171
-		// it means that it was successfully delivered locally.
172
-		// Meaning that the ACL plugin is loaded and that a principial
173
-		// exists for the given recipient id, no need to double check
174
-		/** @var \Sabre\DAVACL\Plugin $aclPlugin */
175
-		$aclPlugin = $this->server->getPlugin('acl');
176
-		$principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
177
-		$calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
178
-		if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
179
-			return;
180
-		}
181
-
182
-		$attendee = $this->getCurrentAttendee($iTipMessage);
183
-		if (!$attendee) {
184
-			return;
185
-		}
186
-
187
-		// We only respond when a response was actually requested
188
-		$rsvp = $this->getAttendeeRSVP($attendee);
189
-		if (!$rsvp) {
190
-			return;
191
-		}
192
-
193
-		if (!isset($iTipMessage->message)) {
194
-			return;
195
-		}
196
-
197
-		$vcalendar = $iTipMessage->message;
198
-		if (!isset($vcalendar->VEVENT)) {
199
-			return;
200
-		}
201
-
202
-		/** @var Component $vevent */
203
-		$vevent = $vcalendar->VEVENT;
204
-
205
-		// We don't support autoresponses for recurrencing events for now
206
-		if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
207
-			return;
208
-		}
209
-
210
-		$dtstart = $vevent->DTSTART;
211
-		$dtend = $this->getDTEndFromVEvent($vevent);
212
-		$uid = $vevent->UID->getValue();
213
-		$sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
214
-		$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
215
-
216
-		$message = <<<EOF
58
+    /**
59
+     * @var IConfig
60
+     */
61
+    private $config;
62
+
63
+    /** @var ITip\Message[] */
64
+    private $schedulingResponses = [];
65
+
66
+    /** @var string|null */
67
+    private $pathOfCalendarObjectChange = null;
68
+
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
+
72
+    /**
73
+     * @param IConfig $config
74
+     */
75
+    public function __construct(IConfig $config) {
76
+        $this->config = $config;
77
+    }
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
+    /**
93
+     * This method handler is invoked during fetching of properties.
94
+     *
95
+     * We use this event to add calendar-auto-schedule-specific properties.
96
+     *
97
+     * @param PropFind $propFind
98
+     * @param INode $node
99
+     * @return void
100
+     */
101
+    public function propFind(PropFind $propFind, INode $node) {
102
+        if ($node instanceof IPrincipal) {
103
+            // overwrite Sabre/Dav's implementation
104
+            $propFind->handle(self::CALENDAR_USER_TYPE, function () use ($node) {
105
+                if ($node instanceof IProperties) {
106
+                    $props = $node->getProperties([self::CALENDAR_USER_TYPE]);
107
+
108
+                    if (isset($props[self::CALENDAR_USER_TYPE])) {
109
+                        return $props[self::CALENDAR_USER_TYPE];
110
+                    }
111
+                }
112
+
113
+                return 'INDIVIDUAL';
114
+            });
115
+        }
116
+
117
+        parent::propFind($propFind, $node);
118
+    }
119
+
120
+    /**
121
+     * Returns a list of addresses that are associated with a principal.
122
+     *
123
+     * @param string $principal
124
+     * @return array
125
+     */
126
+    protected function getAddressesForPrincipal($principal) {
127
+        $result = parent::getAddressesForPrincipal($principal);
128
+
129
+        if ($result === null) {
130
+            $result = [];
131
+        }
132
+
133
+        return $result;
134
+    }
135
+
136
+    /**
137
+     * @param RequestInterface $request
138
+     * @param ResponseInterface $response
139
+     * @param VCalendar $vCal
140
+     * @param mixed $calendarPath
141
+     * @param mixed $modified
142
+     * @param mixed $isNew
143
+     */
144
+    public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
145
+        // Save the first path we get as a calendar-object-change request
146
+        if (!$this->pathOfCalendarObjectChange) {
147
+            $this->pathOfCalendarObjectChange = $request->getPath();
148
+        }
149
+
150
+        parent::calendarObjectChange($request, $response, $vCal, $calendarPath, $modified, $isNew);
151
+    }
152
+
153
+    /**
154
+     * @inheritDoc
155
+     */
156
+    public function scheduleLocalDelivery(ITip\Message $iTipMessage):void {
157
+        parent::scheduleLocalDelivery($iTipMessage);
158
+
159
+        // We only care when the message was successfully delivered locally
160
+        if ($iTipMessage->scheduleStatus !== '1.2;Message delivered locally') {
161
+            return;
162
+        }
163
+
164
+        // We only care about request. reply and cancel are properly handled
165
+        // by parent::scheduleLocalDelivery already
166
+        if (strcasecmp($iTipMessage->method, 'REQUEST') !== 0) {
167
+            return;
168
+        }
169
+
170
+        // If parent::scheduleLocalDelivery set scheduleStatus to 1.2,
171
+        // it means that it was successfully delivered locally.
172
+        // Meaning that the ACL plugin is loaded and that a principial
173
+        // exists for the given recipient id, no need to double check
174
+        /** @var \Sabre\DAVACL\Plugin $aclPlugin */
175
+        $aclPlugin = $this->server->getPlugin('acl');
176
+        $principalUri = $aclPlugin->getPrincipalByUri($iTipMessage->recipient);
177
+        $calendarUserType = $this->getCalendarUserTypeForPrincipal($principalUri);
178
+        if (strcasecmp($calendarUserType, 'ROOM') !== 0 && strcasecmp($calendarUserType, 'RESOURCE') !== 0) {
179
+            return;
180
+        }
181
+
182
+        $attendee = $this->getCurrentAttendee($iTipMessage);
183
+        if (!$attendee) {
184
+            return;
185
+        }
186
+
187
+        // We only respond when a response was actually requested
188
+        $rsvp = $this->getAttendeeRSVP($attendee);
189
+        if (!$rsvp) {
190
+            return;
191
+        }
192
+
193
+        if (!isset($iTipMessage->message)) {
194
+            return;
195
+        }
196
+
197
+        $vcalendar = $iTipMessage->message;
198
+        if (!isset($vcalendar->VEVENT)) {
199
+            return;
200
+        }
201
+
202
+        /** @var Component $vevent */
203
+        $vevent = $vcalendar->VEVENT;
204
+
205
+        // We don't support autoresponses for recurrencing events for now
206
+        if (isset($vevent->RRULE) || isset($vevent->RDATE)) {
207
+            return;
208
+        }
209
+
210
+        $dtstart = $vevent->DTSTART;
211
+        $dtend = $this->getDTEndFromVEvent($vevent);
212
+        $uid = $vevent->UID->getValue();
213
+        $sequence = isset($vevent->SEQUENCE) ? $vevent->SEQUENCE->getValue() : 0;
214
+        $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->serialize() : '';
215
+
216
+        $message = <<<EOF
217 217
 BEGIN:VCALENDAR
218 218
 PRODID:-//Nextcloud/Nextcloud CalDAV Server//EN
219 219
 METHOD:REPLY
@@ -228,331 +228,331 @@  discard block
 block discarded – undo
228 228
 END:VCALENDAR
229 229
 EOF;
230 230
 
231
-		if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
232
-			$partStat = 'ACCEPTED';
233
-		} else {
234
-			$partStat = 'DECLINED';
235
-		}
236
-
237
-		$vObject = Reader::read(vsprintf($message, [
238
-			$partStat,
239
-			$iTipMessage->recipient,
240
-			$iTipMessage->sender,
241
-			$uid,
242
-			$sequence,
243
-			$recurrenceId
244
-		]));
245
-
246
-		$responseITipMessage = new ITip\Message();
247
-		$responseITipMessage->uid = $uid;
248
-		$responseITipMessage->component = 'VEVENT';
249
-		$responseITipMessage->method = 'REPLY';
250
-		$responseITipMessage->sequence = $sequence;
251
-		$responseITipMessage->sender = $iTipMessage->recipient;
252
-		$responseITipMessage->recipient = $iTipMessage->sender;
253
-		$responseITipMessage->message = $vObject;
254
-
255
-		// We can't dispatch them now already, because the organizers calendar-object
256
-		// was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
257
-		// send our reply.
258
-		$this->schedulingResponses[] = $responseITipMessage;
259
-	}
260
-
261
-	/**
262
-	 * @param string $uri
263
-	 */
264
-	public function dispatchSchedulingResponses(string $uri):void {
265
-		if ($uri !== $this->pathOfCalendarObjectChange) {
266
-			return;
267
-		}
268
-
269
-		foreach ($this->schedulingResponses as $schedulingResponse) {
270
-			$this->scheduleLocalDelivery($schedulingResponse);
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * Always use the personal calendar as target for scheduled events
276
-	 *
277
-	 * @param PropFind $propFind
278
-	 * @param INode $node
279
-	 * @return void
280
-	 */
281
-	public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
282
-		if ($node instanceof IPrincipal) {
283
-			$propFind->handle(self::SCHEDULE_DEFAULT_CALENDAR_URL, function () use ($node) {
284
-				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
285
-				$caldavPlugin = $this->server->getPlugin('caldav');
286
-				$principalUrl = $node->getPrincipalUrl();
287
-
288
-				$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
289
-				if (!$calendarHomePath) {
290
-					return null;
291
-				}
292
-
293
-				if (strpos($principalUrl, 'principals/users') === 0) {
294
-					[, $userId] = split($principalUrl);
295
-					$uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
296
-					$displayName = CalDavBackend::PERSONAL_CALENDAR_NAME;
297
-				} elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
298
-						  strpos($principalUrl, 'principals/calendar-rooms') === 0) {
299
-					$uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
300
-					$displayName = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
301
-				} else {
302
-					// How did we end up here?
303
-					// TODO - throw exception or just ignore?
304
-					return null;
305
-				}
306
-
307
-				/** @var CalendarHome $calendarHome */
308
-				$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
309
-				if (!$calendarHome->childExists($uri)) {
310
-					$calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
311
-						'{DAV:}displayname' => $displayName,
312
-					]);
313
-				}
314
-
315
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
316
-				if (empty($result)) {
317
-					return null;
318
-				}
319
-
320
-				return new LocalHref($result[0]['href']);
321
-			});
322
-		}
323
-	}
324
-
325
-	/**
326
-	 * Returns a list of addresses that are associated with a principal.
327
-	 *
328
-	 * @param string $principal
329
-	 * @return string|null
330
-	 */
331
-	protected function getCalendarUserTypeForPrincipal($principal):?string {
332
-		$calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
333
-		$properties = $this->server->getProperties(
334
-			$principal,
335
-			[$calendarUserType]
336
-		);
337
-
338
-		// If we can't find this information, we'll stop processing
339
-		if (!isset($properties[$calendarUserType])) {
340
-			return null;
341
-		}
342
-
343
-		return $properties[$calendarUserType];
344
-	}
345
-
346
-	/**
347
-	 * @param ITip\Message $iTipMessage
348
-	 * @return null|Property
349
-	 */
350
-	private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
351
-		/** @var VEvent $vevent */
352
-		$vevent = $iTipMessage->message->VEVENT;
353
-		$attendees = $vevent->select('ATTENDEE');
354
-		foreach ($attendees as $attendee) {
355
-			/** @var Property $attendee */
356
-			if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
357
-				return $attendee;
358
-			}
359
-		}
360
-		return null;
361
-	}
362
-
363
-	/**
364
-	 * @param Property|null $attendee
365
-	 * @return bool
366
-	 */
367
-	private function getAttendeeRSVP(Property $attendee = null):bool {
368
-		if ($attendee !== null) {
369
-			$rsvp = $attendee->offsetGet('RSVP');
370
-			if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
371
-				return true;
372
-			}
373
-		}
374
-		// RFC 5545 3.2.17: default RSVP is false
375
-		return false;
376
-	}
377
-
378
-	/**
379
-	 * @param VEvent $vevent
380
-	 * @return Property\ICalendar\DateTime
381
-	 */
382
-	private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
383
-		if (isset($vevent->DTEND)) {
384
-			return $vevent->DTEND;
385
-		}
386
-
387
-		if (isset($vevent->DURATION)) {
388
-			$isFloating = $vevent->DTSTART->isFloating();
389
-			/** @var Property\ICalendar\DateTime $end */
390
-			$end = clone $vevent->DTSTART;
391
-			$endDateTime = $end->getDateTime();
392
-			$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
393
-			$end->setDateTime($endDateTime, $isFloating);
394
-			return $end;
395
-		}
396
-
397
-		if (!$vevent->DTSTART->hasTime()) {
398
-			$isFloating = $vevent->DTSTART->isFloating();
399
-			/** @var Property\ICalendar\DateTime $end */
400
-			$end = clone $vevent->DTSTART;
401
-			$endDateTime = $end->getDateTime();
402
-			$endDateTime = $endDateTime->modify('+1 day');
403
-			$end->setDateTime($endDateTime, $isFloating);
404
-			return $end;
405
-		}
406
-
407
-		return clone $vevent->DTSTART;
408
-	}
409
-
410
-	/**
411
-	 * @param string $email
412
-	 * @param \DateTimeInterface $start
413
-	 * @param \DateTimeInterface $end
414
-	 * @param string $ignoreUID
415
-	 * @return bool
416
-	 */
417
-	private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
418
-		// This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
419
-		// and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
420
-
421
-		$aclPlugin = $this->server->getPlugin('acl');
422
-		$this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
423
-
424
-		$result = $aclPlugin->principalSearch(
425
-			['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
426
-			[
427
-				'{DAV:}principal-URL',
428
-				'{' . self::NS_CALDAV . '}calendar-home-set',
429
-				'{' . self::NS_CALDAV . '}schedule-inbox-URL',
430
-				'{http://sabredav.org/ns}email-address',
431
-
432
-			]
433
-		);
434
-		$this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
435
-
436
-
437
-		// Grabbing the calendar list
438
-		$objects = [];
439
-		$calendarTimeZone = new DateTimeZone('UTC');
440
-
441
-		$homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
442
-		foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
443
-			if (!$node instanceof ICalendar) {
444
-				continue;
445
-			}
446
-
447
-			// Getting the list of object uris within the time-range
448
-			$urls = $node->calendarQuery([
449
-				'name' => 'VCALENDAR',
450
-				'comp-filters' => [
451
-					[
452
-						'name' => 'VEVENT',
453
-						'is-not-defined' => false,
454
-						'time-range' => [
455
-							'start' => $start,
456
-							'end' => $end,
457
-						],
458
-						'comp-filters' => [],
459
-						'prop-filters' => [],
460
-					],
461
-					[
462
-						'name' => 'VEVENT',
463
-						'is-not-defined' => false,
464
-						'time-range' => null,
465
-						'comp-filters' => [],
466
-						'prop-filters' => [
467
-							[
468
-								'name' => 'UID',
469
-								'is-not-defined' => false,
470
-								'time-range' => null,
471
-								'text-match' => [
472
-									'value' => $ignoreUID,
473
-									'negate-condition' => true,
474
-									'collation' => 'i;octet',
475
-								],
476
-								'param-filters' => [],
477
-							],
478
-						]
479
-					],
480
-				],
481
-				'prop-filters' => [],
482
-				'is-not-defined' => false,
483
-				'time-range' => null,
484
-			]);
485
-
486
-			foreach ($urls as $url) {
487
-				$objects[] = $node->getChild($url)->get();
488
-			}
489
-		}
490
-
491
-		$inboxProps = $this->server->getProperties(
492
-			$result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
493
-			['{' . self::NS_CALDAV . '}calendar-availability']
494
-		);
495
-
496
-		$vcalendar = new VCalendar();
497
-		$vcalendar->METHOD = 'REPLY';
498
-
499
-		$generator = new FreeBusyGenerator();
500
-		$generator->setObjects($objects);
501
-		$generator->setTimeRange($start, $end);
502
-		$generator->setBaseObject($vcalendar);
503
-		$generator->setTimeZone($calendarTimeZone);
504
-
505
-		if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
506
-			$generator->setVAvailability(
507
-				Reader::read(
508
-					$inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
509
-				)
510
-			);
511
-		}
512
-
513
-		$result = $generator->getResult();
514
-		if (!isset($result->VFREEBUSY)) {
515
-			return false;
516
-		}
517
-
518
-		/** @var Component $freeBusyComponent */
519
-		$freeBusyComponent = $result->VFREEBUSY;
520
-		$freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
521
-		// If there is no Free-busy property at all, the time-range is empty and available
522
-		if (count($freeBusyProperties) === 0) {
523
-			return true;
524
-		}
525
-
526
-		// If more than one Free-Busy property was returned, it means that an event
527
-		// starts or ends inside this time-range, so it's not availabe and we return false
528
-		if (count($freeBusyProperties) > 1) {
529
-			return false;
530
-		}
531
-
532
-		/** @var Property $freeBusyProperty */
533
-		$freeBusyProperty = $freeBusyProperties[0];
534
-		if (!$freeBusyProperty->offsetExists('FBTYPE')) {
535
-			// If there is no FBTYPE, it means it's busy
536
-			return false;
537
-		}
538
-
539
-		$fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
540
-		if (!($fbTypeParameter instanceof Parameter)) {
541
-			return false;
542
-		}
543
-
544
-		return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
545
-	}
546
-
547
-	/**
548
-	 * @param string $email
549
-	 * @return string
550
-	 */
551
-	private function stripOffMailTo(string $email): string {
552
-		if (stripos($email, 'mailto:') === 0) {
553
-			return substr($email, 7);
554
-		}
555
-
556
-		return $email;
557
-	}
231
+        if ($this->isAvailableAtTime($attendee->getValue(), $dtstart->getDateTime(), $dtend->getDateTime(), $uid)) {
232
+            $partStat = 'ACCEPTED';
233
+        } else {
234
+            $partStat = 'DECLINED';
235
+        }
236
+
237
+        $vObject = Reader::read(vsprintf($message, [
238
+            $partStat,
239
+            $iTipMessage->recipient,
240
+            $iTipMessage->sender,
241
+            $uid,
242
+            $sequence,
243
+            $recurrenceId
244
+        ]));
245
+
246
+        $responseITipMessage = new ITip\Message();
247
+        $responseITipMessage->uid = $uid;
248
+        $responseITipMessage->component = 'VEVENT';
249
+        $responseITipMessage->method = 'REPLY';
250
+        $responseITipMessage->sequence = $sequence;
251
+        $responseITipMessage->sender = $iTipMessage->recipient;
252
+        $responseITipMessage->recipient = $iTipMessage->sender;
253
+        $responseITipMessage->message = $vObject;
254
+
255
+        // We can't dispatch them now already, because the organizers calendar-object
256
+        // was not yet created. Hence Sabre/DAV won't find a calendar-object, when we
257
+        // send our reply.
258
+        $this->schedulingResponses[] = $responseITipMessage;
259
+    }
260
+
261
+    /**
262
+     * @param string $uri
263
+     */
264
+    public function dispatchSchedulingResponses(string $uri):void {
265
+        if ($uri !== $this->pathOfCalendarObjectChange) {
266
+            return;
267
+        }
268
+
269
+        foreach ($this->schedulingResponses as $schedulingResponse) {
270
+            $this->scheduleLocalDelivery($schedulingResponse);
271
+        }
272
+    }
273
+
274
+    /**
275
+     * Always use the personal calendar as target for scheduled events
276
+     *
277
+     * @param PropFind $propFind
278
+     * @param INode $node
279
+     * @return void
280
+     */
281
+    public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
282
+        if ($node instanceof IPrincipal) {
283
+            $propFind->handle(self::SCHEDULE_DEFAULT_CALENDAR_URL, function () use ($node) {
284
+                /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
285
+                $caldavPlugin = $this->server->getPlugin('caldav');
286
+                $principalUrl = $node->getPrincipalUrl();
287
+
288
+                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
289
+                if (!$calendarHomePath) {
290
+                    return null;
291
+                }
292
+
293
+                if (strpos($principalUrl, 'principals/users') === 0) {
294
+                    [, $userId] = split($principalUrl);
295
+                    $uri = $this->config->getUserValue($userId, 'dav', 'defaultCalendar', CalDavBackend::PERSONAL_CALENDAR_URI);
296
+                    $displayName = CalDavBackend::PERSONAL_CALENDAR_NAME;
297
+                } elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
298
+                          strpos($principalUrl, 'principals/calendar-rooms') === 0) {
299
+                    $uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
300
+                    $displayName = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
301
+                } else {
302
+                    // How did we end up here?
303
+                    // TODO - throw exception or just ignore?
304
+                    return null;
305
+                }
306
+
307
+                /** @var CalendarHome $calendarHome */
308
+                $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
309
+                if (!$calendarHome->childExists($uri)) {
310
+                    $calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
311
+                        '{DAV:}displayname' => $displayName,
312
+                    ]);
313
+                }
314
+
315
+                $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
316
+                if (empty($result)) {
317
+                    return null;
318
+                }
319
+
320
+                return new LocalHref($result[0]['href']);
321
+            });
322
+        }
323
+    }
324
+
325
+    /**
326
+     * Returns a list of addresses that are associated with a principal.
327
+     *
328
+     * @param string $principal
329
+     * @return string|null
330
+     */
331
+    protected function getCalendarUserTypeForPrincipal($principal):?string {
332
+        $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type';
333
+        $properties = $this->server->getProperties(
334
+            $principal,
335
+            [$calendarUserType]
336
+        );
337
+
338
+        // If we can't find this information, we'll stop processing
339
+        if (!isset($properties[$calendarUserType])) {
340
+            return null;
341
+        }
342
+
343
+        return $properties[$calendarUserType];
344
+    }
345
+
346
+    /**
347
+     * @param ITip\Message $iTipMessage
348
+     * @return null|Property
349
+     */
350
+    private function getCurrentAttendee(ITip\Message $iTipMessage):?Property {
351
+        /** @var VEvent $vevent */
352
+        $vevent = $iTipMessage->message->VEVENT;
353
+        $attendees = $vevent->select('ATTENDEE');
354
+        foreach ($attendees as $attendee) {
355
+            /** @var Property $attendee */
356
+            if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
357
+                return $attendee;
358
+            }
359
+        }
360
+        return null;
361
+    }
362
+
363
+    /**
364
+     * @param Property|null $attendee
365
+     * @return bool
366
+     */
367
+    private function getAttendeeRSVP(Property $attendee = null):bool {
368
+        if ($attendee !== null) {
369
+            $rsvp = $attendee->offsetGet('RSVP');
370
+            if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
371
+                return true;
372
+            }
373
+        }
374
+        // RFC 5545 3.2.17: default RSVP is false
375
+        return false;
376
+    }
377
+
378
+    /**
379
+     * @param VEvent $vevent
380
+     * @return Property\ICalendar\DateTime
381
+     */
382
+    private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime {
383
+        if (isset($vevent->DTEND)) {
384
+            return $vevent->DTEND;
385
+        }
386
+
387
+        if (isset($vevent->DURATION)) {
388
+            $isFloating = $vevent->DTSTART->isFloating();
389
+            /** @var Property\ICalendar\DateTime $end */
390
+            $end = clone $vevent->DTSTART;
391
+            $endDateTime = $end->getDateTime();
392
+            $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
393
+            $end->setDateTime($endDateTime, $isFloating);
394
+            return $end;
395
+        }
396
+
397
+        if (!$vevent->DTSTART->hasTime()) {
398
+            $isFloating = $vevent->DTSTART->isFloating();
399
+            /** @var Property\ICalendar\DateTime $end */
400
+            $end = clone $vevent->DTSTART;
401
+            $endDateTime = $end->getDateTime();
402
+            $endDateTime = $endDateTime->modify('+1 day');
403
+            $end->setDateTime($endDateTime, $isFloating);
404
+            return $end;
405
+        }
406
+
407
+        return clone $vevent->DTSTART;
408
+    }
409
+
410
+    /**
411
+     * @param string $email
412
+     * @param \DateTimeInterface $start
413
+     * @param \DateTimeInterface $end
414
+     * @param string $ignoreUID
415
+     * @return bool
416
+     */
417
+    private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool {
418
+        // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery
419
+        // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail
420
+
421
+        $aclPlugin = $this->server->getPlugin('acl');
422
+        $this->server->removeListener('propFind', [$aclPlugin, 'propFind']);
423
+
424
+        $result = $aclPlugin->principalSearch(
425
+            ['{http://sabredav.org/ns}email-address' => $this->stripOffMailTo($email)],
426
+            [
427
+                '{DAV:}principal-URL',
428
+                '{' . self::NS_CALDAV . '}calendar-home-set',
429
+                '{' . self::NS_CALDAV . '}schedule-inbox-URL',
430
+                '{http://sabredav.org/ns}email-address',
431
+
432
+            ]
433
+        );
434
+        $this->server->on('propFind', [$aclPlugin, 'propFind'], 20);
435
+
436
+
437
+        // Grabbing the calendar list
438
+        $objects = [];
439
+        $calendarTimeZone = new DateTimeZone('UTC');
440
+
441
+        $homePath = $result[0][200]['{' . self::NS_CALDAV . '}calendar-home-set']->getHref();
442
+        foreach ($this->server->tree->getNodeForPath($homePath)->getChildren() as $node) {
443
+            if (!$node instanceof ICalendar) {
444
+                continue;
445
+            }
446
+
447
+            // Getting the list of object uris within the time-range
448
+            $urls = $node->calendarQuery([
449
+                'name' => 'VCALENDAR',
450
+                'comp-filters' => [
451
+                    [
452
+                        'name' => 'VEVENT',
453
+                        'is-not-defined' => false,
454
+                        'time-range' => [
455
+                            'start' => $start,
456
+                            'end' => $end,
457
+                        ],
458
+                        'comp-filters' => [],
459
+                        'prop-filters' => [],
460
+                    ],
461
+                    [
462
+                        'name' => 'VEVENT',
463
+                        'is-not-defined' => false,
464
+                        'time-range' => null,
465
+                        'comp-filters' => [],
466
+                        'prop-filters' => [
467
+                            [
468
+                                'name' => 'UID',
469
+                                'is-not-defined' => false,
470
+                                'time-range' => null,
471
+                                'text-match' => [
472
+                                    'value' => $ignoreUID,
473
+                                    'negate-condition' => true,
474
+                                    'collation' => 'i;octet',
475
+                                ],
476
+                                'param-filters' => [],
477
+                            ],
478
+                        ]
479
+                    ],
480
+                ],
481
+                'prop-filters' => [],
482
+                'is-not-defined' => false,
483
+                'time-range' => null,
484
+            ]);
485
+
486
+            foreach ($urls as $url) {
487
+                $objects[] = $node->getChild($url)->get();
488
+            }
489
+        }
490
+
491
+        $inboxProps = $this->server->getProperties(
492
+            $result[0][200]['{' . self::NS_CALDAV . '}schedule-inbox-URL']->getHref(),
493
+            ['{' . self::NS_CALDAV . '}calendar-availability']
494
+        );
495
+
496
+        $vcalendar = new VCalendar();
497
+        $vcalendar->METHOD = 'REPLY';
498
+
499
+        $generator = new FreeBusyGenerator();
500
+        $generator->setObjects($objects);
501
+        $generator->setTimeRange($start, $end);
502
+        $generator->setBaseObject($vcalendar);
503
+        $generator->setTimeZone($calendarTimeZone);
504
+
505
+        if (isset($inboxProps['{' . self::NS_CALDAV . '}calendar-availability'])) {
506
+            $generator->setVAvailability(
507
+                Reader::read(
508
+                    $inboxProps['{' . self::NS_CALDAV . '}calendar-availability']
509
+                )
510
+            );
511
+        }
512
+
513
+        $result = $generator->getResult();
514
+        if (!isset($result->VFREEBUSY)) {
515
+            return false;
516
+        }
517
+
518
+        /** @var Component $freeBusyComponent */
519
+        $freeBusyComponent = $result->VFREEBUSY;
520
+        $freeBusyProperties = $freeBusyComponent->select('FREEBUSY');
521
+        // If there is no Free-busy property at all, the time-range is empty and available
522
+        if (count($freeBusyProperties) === 0) {
523
+            return true;
524
+        }
525
+
526
+        // If more than one Free-Busy property was returned, it means that an event
527
+        // starts or ends inside this time-range, so it's not availabe and we return false
528
+        if (count($freeBusyProperties) > 1) {
529
+            return false;
530
+        }
531
+
532
+        /** @var Property $freeBusyProperty */
533
+        $freeBusyProperty = $freeBusyProperties[0];
534
+        if (!$freeBusyProperty->offsetExists('FBTYPE')) {
535
+            // If there is no FBTYPE, it means it's busy
536
+            return false;
537
+        }
538
+
539
+        $fbTypeParameter = $freeBusyProperty->offsetGet('FBTYPE');
540
+        if (!($fbTypeParameter instanceof Parameter)) {
541
+            return false;
542
+        }
543
+
544
+        return (strcasecmp($fbTypeParameter->getValue(), 'FREE') === 0);
545
+    }
546
+
547
+    /**
548
+     * @param string $email
549
+     * @return string
550
+     */
551
+    private function stripOffMailTo(string $email): string {
552
+        if (stripos($email, 'mailto:') === 0) {
553
+            return substr($email, 7);
554
+        }
555
+
556
+        return $email;
557
+    }
558 558
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Schedule/IMipPlugin.php 2 patches
Indentation   +624 added lines, -624 removed lines patch added patch discarded remove patch
@@ -70,194 +70,194 @@  discard block
 block discarded – undo
70 70
  */
71 71
 class IMipPlugin extends SabreIMipPlugin {
72 72
 
73
-	/** @var string */
74
-	private $userId;
75
-
76
-	/** @var IConfig */
77
-	private $config;
78
-
79
-	/** @var IMailer */
80
-	private $mailer;
81
-
82
-	/** @var ILogger */
83
-	private $logger;
84
-
85
-	/** @var ITimeFactory */
86
-	private $timeFactory;
87
-
88
-	/** @var L10NFactory */
89
-	private $l10nFactory;
90
-
91
-	/** @var IURLGenerator */
92
-	private $urlGenerator;
93
-
94
-	/** @var ISecureRandom */
95
-	private $random;
96
-
97
-	/** @var IDBConnection */
98
-	private $db;
99
-
100
-	/** @var Defaults */
101
-	private $defaults;
102
-
103
-	/** @var IUserManager */
104
-	private $userManager;
105
-
106
-	public const MAX_DATE = '2038-01-01';
107
-
108
-	public const METHOD_REQUEST = 'request';
109
-	public const METHOD_REPLY = 'reply';
110
-	public const METHOD_CANCEL = 'cancel';
111
-	public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
112
-
113
-	/**
114
-	 * @param IConfig $config
115
-	 * @param IMailer $mailer
116
-	 * @param ILogger $logger
117
-	 * @param ITimeFactory $timeFactory
118
-	 * @param L10NFactory $l10nFactory
119
-	 * @param IUrlGenerator $urlGenerator
120
-	 * @param Defaults $defaults
121
-	 * @param ISecureRandom $random
122
-	 * @param IDBConnection $db
123
-	 * @param string $userId
124
-	 */
125
-	public function __construct(IConfig $config, IMailer $mailer, ILogger $logger,
126
-								ITimeFactory $timeFactory, L10NFactory $l10nFactory,
127
-								IURLGenerator $urlGenerator, Defaults $defaults,
128
-								ISecureRandom $random, IDBConnection $db, IUserManager $userManager,
129
-								$userId) {
130
-		parent::__construct('');
131
-		$this->userId = $userId;
132
-		$this->config = $config;
133
-		$this->mailer = $mailer;
134
-		$this->logger = $logger;
135
-		$this->timeFactory = $timeFactory;
136
-		$this->l10nFactory = $l10nFactory;
137
-		$this->urlGenerator = $urlGenerator;
138
-		$this->random = $random;
139
-		$this->db = $db;
140
-		$this->defaults = $defaults;
141
-		$this->userManager = $userManager;
142
-	}
143
-
144
-	/**
145
-	 * Event handler for the 'schedule' event.
146
-	 *
147
-	 * @param Message $iTipMessage
148
-	 * @return void
149
-	 */
150
-	public function schedule(Message $iTipMessage) {
151
-
152
-		// Not sending any emails if the system considers the update
153
-		// insignificant.
154
-		if (!$iTipMessage->significantChange) {
155
-			if (!$iTipMessage->scheduleStatus) {
156
-				$iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
157
-			}
158
-			return;
159
-		}
160
-
161
-		$summary = $iTipMessage->message->VEVENT->SUMMARY;
162
-
163
-		if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') {
164
-			return;
165
-		}
166
-
167
-		if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
168
-			return;
169
-		}
170
-
171
-		// don't send out mails for events that already took place
172
-		$lastOccurrence = $this->getLastOccurrence($iTipMessage->message);
173
-		$currentTime = $this->timeFactory->getTime();
174
-		if ($lastOccurrence < $currentTime) {
175
-			return;
176
-		}
177
-
178
-		// Strip off mailto:
179
-		$sender = substr($iTipMessage->sender, 7);
180
-		$recipient = substr($iTipMessage->recipient, 7);
181
-		if ($recipient === false || !$this->mailer->validateMailAddress($recipient)) {
182
-			// Nothing to send if the recipient doesn't have a valid email address
183
-			$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
184
-			return;
185
-		}
186
-
187
-		$senderName = $iTipMessage->senderName ?: null;
188
-		$recipientName = $iTipMessage->recipientName ?: null;
189
-
190
-		if ($senderName === null || empty(trim($senderName))) {
191
-			$user = $this->userManager->get($this->userId);
192
-			if ($user) {
193
-				// getDisplayName automatically uses the uid
194
-				// if no display-name is set
195
-				$senderName = $user->getDisplayName();
196
-			}
197
-		}
198
-
199
-		/** @var VEvent $vevent */
200
-		$vevent = $iTipMessage->message->VEVENT;
201
-
202
-		$attendee = $this->getCurrentAttendee($iTipMessage);
203
-		$defaultLang = $this->l10nFactory->findLanguage();
204
-		$lang = $this->getAttendeeLangOrDefault($defaultLang, $attendee);
205
-		$l10n = $this->l10nFactory->get('dav', $lang);
206
-
207
-		$meetingAttendeeName = $recipientName ?: $recipient;
208
-		$meetingInviteeName = $senderName ?: $sender;
209
-
210
-		$meetingTitle = $vevent->SUMMARY;
211
-		$meetingDescription = $vevent->DESCRIPTION;
212
-
213
-
214
-		$meetingUrl = $vevent->URL;
215
-		$meetingLocation = $vevent->LOCATION;
216
-
217
-		$defaultVal = '--';
218
-
219
-		$method = self::METHOD_REQUEST;
220
-		switch (strtolower($iTipMessage->method)) {
221
-			case self::METHOD_REPLY:
222
-				$method = self::METHOD_REPLY;
223
-				break;
224
-			case self::METHOD_CANCEL:
225
-				$method = self::METHOD_CANCEL;
226
-				break;
227
-		}
228
-
229
-		$data = [
230
-			'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
231
-			'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
232
-			'meeting_title' => (string)$meetingTitle ?: $defaultVal,
233
-			'meeting_description' => (string)$meetingDescription ?: $defaultVal,
234
-			'meeting_url' => (string)$meetingUrl ?: $defaultVal,
235
-		];
236
-
237
-		$fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
238
-		$fromName = $l10n->t('%1$s via %2$s', [$senderName, $this->defaults->getName()]);
239
-
240
-		$message = $this->mailer->createMessage()
241
-			->setFrom([$fromEMail => $fromName])
242
-			->setTo([$recipient => $recipientName]);
243
-
244
-		if ($sender !== false) {
245
-			$message->setReplyTo([$sender => $senderName]);
246
-		}
247
-
248
-		$template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
249
-		$template->addHeader();
250
-
251
-		$summary = ((string) $summary !== '') ? (string) $summary : $l10n->t('Untitled event');
252
-
253
-		$this->addSubjectAndHeading($template, $l10n, $method, $summary);
254
-		$this->addBulletList($template, $l10n, $vevent);
255
-
256
-
257
-		// Only add response buttons to invitation requests: Fix Issue #11230
258
-		if (($method == self::METHOD_REQUEST) && $this->getAttendeeRSVP($attendee)) {
73
+    /** @var string */
74
+    private $userId;
75
+
76
+    /** @var IConfig */
77
+    private $config;
78
+
79
+    /** @var IMailer */
80
+    private $mailer;
81
+
82
+    /** @var ILogger */
83
+    private $logger;
84
+
85
+    /** @var ITimeFactory */
86
+    private $timeFactory;
87
+
88
+    /** @var L10NFactory */
89
+    private $l10nFactory;
90
+
91
+    /** @var IURLGenerator */
92
+    private $urlGenerator;
93
+
94
+    /** @var ISecureRandom */
95
+    private $random;
96
+
97
+    /** @var IDBConnection */
98
+    private $db;
99
+
100
+    /** @var Defaults */
101
+    private $defaults;
102
+
103
+    /** @var IUserManager */
104
+    private $userManager;
105
+
106
+    public const MAX_DATE = '2038-01-01';
107
+
108
+    public const METHOD_REQUEST = 'request';
109
+    public const METHOD_REPLY = 'reply';
110
+    public const METHOD_CANCEL = 'cancel';
111
+    public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages
112
+
113
+    /**
114
+     * @param IConfig $config
115
+     * @param IMailer $mailer
116
+     * @param ILogger $logger
117
+     * @param ITimeFactory $timeFactory
118
+     * @param L10NFactory $l10nFactory
119
+     * @param IUrlGenerator $urlGenerator
120
+     * @param Defaults $defaults
121
+     * @param ISecureRandom $random
122
+     * @param IDBConnection $db
123
+     * @param string $userId
124
+     */
125
+    public function __construct(IConfig $config, IMailer $mailer, ILogger $logger,
126
+                                ITimeFactory $timeFactory, L10NFactory $l10nFactory,
127
+                                IURLGenerator $urlGenerator, Defaults $defaults,
128
+                                ISecureRandom $random, IDBConnection $db, IUserManager $userManager,
129
+                                $userId) {
130
+        parent::__construct('');
131
+        $this->userId = $userId;
132
+        $this->config = $config;
133
+        $this->mailer = $mailer;
134
+        $this->logger = $logger;
135
+        $this->timeFactory = $timeFactory;
136
+        $this->l10nFactory = $l10nFactory;
137
+        $this->urlGenerator = $urlGenerator;
138
+        $this->random = $random;
139
+        $this->db = $db;
140
+        $this->defaults = $defaults;
141
+        $this->userManager = $userManager;
142
+    }
143
+
144
+    /**
145
+     * Event handler for the 'schedule' event.
146
+     *
147
+     * @param Message $iTipMessage
148
+     * @return void
149
+     */
150
+    public function schedule(Message $iTipMessage) {
151
+
152
+        // Not sending any emails if the system considers the update
153
+        // insignificant.
154
+        if (!$iTipMessage->significantChange) {
155
+            if (!$iTipMessage->scheduleStatus) {
156
+                $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
157
+            }
158
+            return;
159
+        }
160
+
161
+        $summary = $iTipMessage->message->VEVENT->SUMMARY;
162
+
163
+        if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') {
164
+            return;
165
+        }
166
+
167
+        if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
168
+            return;
169
+        }
170
+
171
+        // don't send out mails for events that already took place
172
+        $lastOccurrence = $this->getLastOccurrence($iTipMessage->message);
173
+        $currentTime = $this->timeFactory->getTime();
174
+        if ($lastOccurrence < $currentTime) {
175
+            return;
176
+        }
177
+
178
+        // Strip off mailto:
179
+        $sender = substr($iTipMessage->sender, 7);
180
+        $recipient = substr($iTipMessage->recipient, 7);
181
+        if ($recipient === false || !$this->mailer->validateMailAddress($recipient)) {
182
+            // Nothing to send if the recipient doesn't have a valid email address
183
+            $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
184
+            return;
185
+        }
186
+
187
+        $senderName = $iTipMessage->senderName ?: null;
188
+        $recipientName = $iTipMessage->recipientName ?: null;
189
+
190
+        if ($senderName === null || empty(trim($senderName))) {
191
+            $user = $this->userManager->get($this->userId);
192
+            if ($user) {
193
+                // getDisplayName automatically uses the uid
194
+                // if no display-name is set
195
+                $senderName = $user->getDisplayName();
196
+            }
197
+        }
198
+
199
+        /** @var VEvent $vevent */
200
+        $vevent = $iTipMessage->message->VEVENT;
201
+
202
+        $attendee = $this->getCurrentAttendee($iTipMessage);
203
+        $defaultLang = $this->l10nFactory->findLanguage();
204
+        $lang = $this->getAttendeeLangOrDefault($defaultLang, $attendee);
205
+        $l10n = $this->l10nFactory->get('dav', $lang);
206
+
207
+        $meetingAttendeeName = $recipientName ?: $recipient;
208
+        $meetingInviteeName = $senderName ?: $sender;
209
+
210
+        $meetingTitle = $vevent->SUMMARY;
211
+        $meetingDescription = $vevent->DESCRIPTION;
212
+
213
+
214
+        $meetingUrl = $vevent->URL;
215
+        $meetingLocation = $vevent->LOCATION;
216
+
217
+        $defaultVal = '--';
218
+
219
+        $method = self::METHOD_REQUEST;
220
+        switch (strtolower($iTipMessage->method)) {
221
+            case self::METHOD_REPLY:
222
+                $method = self::METHOD_REPLY;
223
+                break;
224
+            case self::METHOD_CANCEL:
225
+                $method = self::METHOD_CANCEL;
226
+                break;
227
+        }
228
+
229
+        $data = [
230
+            'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
231
+            'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
232
+            'meeting_title' => (string)$meetingTitle ?: $defaultVal,
233
+            'meeting_description' => (string)$meetingDescription ?: $defaultVal,
234
+            'meeting_url' => (string)$meetingUrl ?: $defaultVal,
235
+        ];
236
+
237
+        $fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
238
+        $fromName = $l10n->t('%1$s via %2$s', [$senderName, $this->defaults->getName()]);
239
+
240
+        $message = $this->mailer->createMessage()
241
+            ->setFrom([$fromEMail => $fromName])
242
+            ->setTo([$recipient => $recipientName]);
243
+
244
+        if ($sender !== false) {
245
+            $message->setReplyTo([$sender => $senderName]);
246
+        }
247
+
248
+        $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
249
+        $template->addHeader();
250
+
251
+        $summary = ((string) $summary !== '') ? (string) $summary : $l10n->t('Untitled event');
252
+
253
+        $this->addSubjectAndHeading($template, $l10n, $method, $summary);
254
+        $this->addBulletList($template, $l10n, $vevent);
255
+
256
+
257
+        // Only add response buttons to invitation requests: Fix Issue #11230
258
+        if (($method == self::METHOD_REQUEST) && $this->getAttendeeRSVP($attendee)) {
259 259
 
260
-			/*
260
+            /*
261 261
 			** Only offer invitation accept/reject buttons, which link back to the
262 262
 			** nextcloud server, to recipients who can access the nextcloud server via
263 263
 			** their internet/intranet.  Issue #12156
@@ -276,441 +276,441 @@  discard block
 block discarded – undo
276 276
 			** To suppress URLs entirely, set invitation_link_recipients to boolean "no".
277 277
 			*/
278 278
 
279
-			$recipientDomain = substr(strrchr($recipient, "@"), 1);
280
-			$invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
281
-
282
-			if (strcmp('yes', $invitationLinkRecipients[0]) === 0
283
-				 || in_array(strtolower($recipient), $invitationLinkRecipients)
284
-				 || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
285
-				$this->addResponseButtons($template, $l10n, $iTipMessage, $lastOccurrence);
286
-			}
287
-		}
288
-
289
-		$template->addFooter();
290
-
291
-		$message->useTemplate($template);
292
-
293
-		$attachment = $this->mailer->createAttachment(
294
-			$iTipMessage->message->serialize(),
295
-			'event.ics',// TODO(leon): Make file name unique, e.g. add event id
296
-			'text/calendar; method=' . $iTipMessage->method
297
-		);
298
-		$message->attach($attachment);
299
-
300
-		try {
301
-			$failed = $this->mailer->send($message);
302
-			$iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
303
-			if ($failed) {
304
-				$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
305
-				$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
306
-			}
307
-		} catch (\Exception $ex) {
308
-			$this->logger->logException($ex, ['app' => 'dav']);
309
-			$iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * check if event took place in the past already
315
-	 * @param VCalendar $vObject
316
-	 * @return int
317
-	 */
318
-	private function getLastOccurrence(VCalendar $vObject) {
319
-		/** @var VEvent $component */
320
-		$component = $vObject->VEVENT;
321
-
322
-		$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
323
-		// Finding the last occurrence is a bit harder
324
-		if (!isset($component->RRULE)) {
325
-			if (isset($component->DTEND)) {
326
-				$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
327
-			} elseif (isset($component->DURATION)) {
328
-				/** @var \DateTime $endDate */
329
-				$endDate = clone $component->DTSTART->getDateTime();
330
-				// $component->DTEND->getDateTime() returns DateTimeImmutable
331
-				$endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
332
-				$lastOccurrence = $endDate->getTimestamp();
333
-			} elseif (!$component->DTSTART->hasTime()) {
334
-				/** @var \DateTime $endDate */
335
-				$endDate = clone $component->DTSTART->getDateTime();
336
-				// $component->DTSTART->getDateTime() returns DateTimeImmutable
337
-				$endDate = $endDate->modify('+1 day');
338
-				$lastOccurrence = $endDate->getTimestamp();
339
-			} else {
340
-				$lastOccurrence = $firstOccurrence;
341
-			}
342
-		} else {
343
-			$it = new EventIterator($vObject, (string)$component->UID);
344
-			$maxDate = new \DateTime(self::MAX_DATE);
345
-			if ($it->isInfinite()) {
346
-				$lastOccurrence = $maxDate->getTimestamp();
347
-			} else {
348
-				$end = $it->getDtEnd();
349
-				while ($it->valid() && $end < $maxDate) {
350
-					$end = $it->getDtEnd();
351
-					$it->next();
352
-				}
353
-				$lastOccurrence = $end->getTimestamp();
354
-			}
355
-		}
356
-
357
-		return $lastOccurrence;
358
-	}
359
-
360
-	/**
361
-	 * @param Message $iTipMessage
362
-	 * @return null|Property
363
-	 */
364
-	private function getCurrentAttendee(Message $iTipMessage) {
365
-		/** @var VEvent $vevent */
366
-		$vevent = $iTipMessage->message->VEVENT;
367
-		$attendees = $vevent->select('ATTENDEE');
368
-		foreach ($attendees as $attendee) {
369
-			/** @var Property $attendee */
370
-			if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
371
-				return $attendee;
372
-			}
373
-		}
374
-		return null;
375
-	}
376
-
377
-	/**
378
-	 * @param string $default
379
-	 * @param Property|null $attendee
380
-	 * @return string
381
-	 */
382
-	private function getAttendeeLangOrDefault($default, Property $attendee = null) {
383
-		if ($attendee !== null) {
384
-			$lang = $attendee->offsetGet('LANGUAGE');
385
-			if ($lang instanceof Parameter) {
386
-				return $lang->getValue();
387
-			}
388
-		}
389
-		return $default;
390
-	}
391
-
392
-	/**
393
-	 * @param Property|null $attendee
394
-	 * @return bool
395
-	 */
396
-	private function getAttendeeRSVP(Property $attendee = null) {
397
-		if ($attendee !== null) {
398
-			$rsvp = $attendee->offsetGet('RSVP');
399
-			if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
400
-				return true;
401
-			}
402
-		}
403
-		// RFC 5545 3.2.17: default RSVP is false
404
-		return false;
405
-	}
406
-
407
-	/**
408
-	 * @param IL10N $l10n
409
-	 * @param VEvent $vevent
410
-	 */
411
-	private function generateWhenString(IL10N $l10n, VEvent $vevent) {
412
-		$dtstart = $vevent->DTSTART;
413
-		if (isset($vevent->DTEND)) {
414
-			$dtend = $vevent->DTEND;
415
-		} elseif (isset($vevent->DURATION)) {
416
-			$isFloating = $vevent->DTSTART->isFloating();
417
-			$dtend = clone $vevent->DTSTART;
418
-			$endDateTime = $dtend->getDateTime();
419
-			$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
420
-			$dtend->setDateTime($endDateTime, $isFloating);
421
-		} elseif (!$vevent->DTSTART->hasTime()) {
422
-			$isFloating = $vevent->DTSTART->isFloating();
423
-			$dtend = clone $vevent->DTSTART;
424
-			$endDateTime = $dtend->getDateTime();
425
-			$endDateTime = $endDateTime->modify('+1 day');
426
-			$dtend->setDateTime($endDateTime, $isFloating);
427
-		} else {
428
-			$dtend = clone $vevent->DTSTART;
429
-		}
430
-
431
-		$isAllDay = $dtstart instanceof Property\ICalendar\Date;
432
-
433
-		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
434
-		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
435
-		/** @var \DateTimeImmutable $dtstartDt */
436
-		$dtstartDt = $dtstart->getDateTime();
437
-		/** @var \DateTimeImmutable $dtendDt */
438
-		$dtendDt = $dtend->getDateTime();
439
-
440
-		$diff = $dtstartDt->diff($dtendDt);
441
-
442
-		$dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
443
-		$dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
444
-
445
-		if ($isAllDay) {
446
-			// One day event
447
-			if ($diff->days === 1) {
448
-				return $l10n->l('date', $dtstartDt, ['width' => 'medium']);
449
-			}
450
-
451
-			// DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
452
-			// the email should show 2020-01-01 to 2020-01-04.
453
-			$dtendDt->modify('-1 day');
454
-
455
-			//event that spans over multiple days
456
-			$localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
457
-			$localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
458
-
459
-			return $localeStart . ' - ' . $localeEnd;
460
-		}
461
-
462
-		/** @var Property\ICalendar\DateTime $dtstart */
463
-		/** @var Property\ICalendar\DateTime $dtend */
464
-		$isFloating = $dtstart->isFloating();
465
-		$startTimezone = $endTimezone = null;
466
-		if (!$isFloating) {
467
-			$prop = $dtstart->offsetGet('TZID');
468
-			if ($prop instanceof Parameter) {
469
-				$startTimezone = $prop->getValue();
470
-			}
471
-
472
-			$prop = $dtend->offsetGet('TZID');
473
-			if ($prop instanceof Parameter) {
474
-				$endTimezone = $prop->getValue();
475
-			}
476
-		}
477
-
478
-		$localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
479
-			$l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
480
-
481
-		// always show full date with timezone if timezones are different
482
-		if ($startTimezone !== $endTimezone) {
483
-			$localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
484
-
485
-			return $localeStart . ' (' . $startTimezone . ') - ' .
486
-				$localeEnd . ' (' . $endTimezone . ')';
487
-		}
488
-
489
-		// show only end time if date is the same
490
-		if ($this->isDayEqual($dtstartDt, $dtendDt)) {
491
-			$localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
492
-		} else {
493
-			$localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
494
-				$l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
495
-		}
496
-
497
-		return  $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
498
-	}
499
-
500
-	/**
501
-	 * @param \DateTime $dtStart
502
-	 * @param \DateTime $dtEnd
503
-	 * @return bool
504
-	 */
505
-	private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) {
506
-		return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
507
-	}
508
-
509
-	/**
510
-	 * @param IEMailTemplate $template
511
-	 * @param IL10N $l10n
512
-	 * @param string $method
513
-	 * @param string $summary
514
-	 */
515
-	private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
516
-										  $method, $summary) {
517
-		if ($method === self::METHOD_CANCEL) {
518
-			$template->setSubject('Canceled: ' . $summary);
519
-			$template->addHeading($l10n->t('Invitation canceled'));
520
-		} elseif ($method === self::METHOD_REPLY) {
521
-			$template->setSubject('Re: ' . $summary);
522
-			$template->addHeading($l10n->t('Invitation updated'));
523
-		} else {
524
-			$template->setSubject('Invitation: ' . $summary);
525
-			$template->addHeading($l10n->t('Invitation'));
526
-		}
527
-	}
528
-
529
-	/**
530
-	 * @param IEMailTemplate $template
531
-	 * @param IL10N $l10n
532
-	 * @param VEVENT $vevent
533
-	 */
534
-	private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) {
535
-		if ($vevent->SUMMARY) {
536
-			$template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'),
537
-				$this->getAbsoluteImagePath('caldav/title.svg'),'','',self::IMIP_INDENT);
538
-		}
539
-		$meetingWhen = $this->generateWhenString($l10n, $vevent);
540
-		if ($meetingWhen) {
541
-			$template->addBodyListItem($meetingWhen, $l10n->t('Time:'),
542
-				$this->getAbsoluteImagePath('caldav/time.svg'),'','',self::IMIP_INDENT);
543
-		}
544
-		if ($vevent->LOCATION) {
545
-			$template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'),
546
-				$this->getAbsoluteImagePath('caldav/location.svg'),'','',self::IMIP_INDENT);
547
-		}
548
-		if ($vevent->URL) {
549
-			$url = $vevent->URL->getValue();
550
-			$template->addBodyListItem(sprintf('<a href="%s">%s</a>',
551
-					htmlspecialchars($url),
552
-					htmlspecialchars($url)),
553
-				$l10n->t('Link:'),
554
-				$this->getAbsoluteImagePath('caldav/link.svg'),
555
-				$url,'',self::IMIP_INDENT);
556
-		}
557
-
558
-		$this->addAttendees($template, $l10n, $vevent);
559
-
560
-		/* Put description last, like an email body, since it can be arbitrarily long */
561
-		if ($vevent->DESCRIPTION) {
562
-			$template->addBodyListItem($vevent->DESCRIPTION->getValue(), $l10n->t('Description:'),
563
-				$this->getAbsoluteImagePath('caldav/description.svg'),'','',self::IMIP_INDENT);
564
-		}
565
-	}
566
-
567
-	/**
568
-	 * addAttendees: add organizer and attendee names/emails to iMip mail.
569
-	 *
570
-	 * Enable with DAV setting: invitation_list_attendees (default: no)
571
-	 *
572
-	 * The default is 'no', which matches old behavior, and is privacy preserving.
573
-	 *
574
-	 * To enable including attendees in invitation emails:
575
-	 *   % php occ config:app:set dav invitation_list_attendees --value yes
576
-	 *
577
-	 * @param IEMailTemplate $template
578
-	 * @param IL10N $l10n
579
-	 * @param Message $iTipMessage
580
-	 * @param int $lastOccurrence
581
-	 * @author brad2014 on github.com
582
-	 */
583
-
584
-	private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) {
585
-		if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
586
-			return;
587
-		}
588
-
589
-		if (isset($vevent->ORGANIZER)) {
590
-			/** @var Property\ICalendar\CalAddress $organizer */
591
-			$organizer = $vevent->ORGANIZER;
592
-			$organizerURI = $organizer->getNormalizedValue();
593
-			[$scheme,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto:
594
-			/** @var string|null $organizerName */
595
-			$organizerName = isset($organizer['CN']) ? $organizer['CN'] : null;
596
-			$organizerHTML = sprintf('<a href="%s">%s</a>',
597
-				htmlspecialchars($organizerURI),
598
-				htmlspecialchars($organizerName ?: $organizerEmail));
599
-			$organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
600
-			if (isset($organizer['PARTSTAT'])) {
601
-				/** @var Parameter $partstat */
602
-				$partstat = $organizer['PARTSTAT'];
603
-				if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
604
-					$organizerHTML .= ' ✔︎';
605
-					$organizerText .= ' ✔︎';
606
-				}
607
-			}
608
-			$template->addBodyListItem($organizerHTML, $l10n->t('Organizer:'),
609
-				$this->getAbsoluteImagePath('caldav/organizer.svg'),
610
-				$organizerText,'',self::IMIP_INDENT);
611
-		}
612
-
613
-		$attendees = $vevent->select('ATTENDEE');
614
-		if (count($attendees) === 0) {
615
-			return;
616
-		}
617
-
618
-		$attendeesHTML = [];
619
-		$attendeesText = [];
620
-		foreach ($attendees as $attendee) {
621
-			$attendeeURI = $attendee->getNormalizedValue();
622
-			[$scheme,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto:
623
-			$attendeeName = isset($attendee['CN']) ? $attendee['CN'] : null;
624
-			$attendeeHTML = sprintf('<a href="%s">%s</a>',
625
-				htmlspecialchars($attendeeURI),
626
-				htmlspecialchars($attendeeName ?: $attendeeEmail));
627
-			$attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
628
-			if (isset($attendee['PARTSTAT'])
629
-				&& strcasecmp($attendee['PARTSTAT'], 'ACCEPTED') === 0) {
630
-				$attendeeHTML .= ' ✔︎';
631
-				$attendeeText .= ' ✔︎';
632
-			}
633
-			array_push($attendeesHTML, $attendeeHTML);
634
-			array_push($attendeesText, $attendeeText);
635
-		}
636
-
637
-		$template->addBodyListItem(implode('<br/>',$attendeesHTML), $l10n->t('Attendees:'),
638
-			$this->getAbsoluteImagePath('caldav/attendees.svg'),
639
-			implode("\n",$attendeesText),'',self::IMIP_INDENT);
640
-	}
641
-
642
-	/**
643
-	 * @param IEMailTemplate $template
644
-	 * @param IL10N $l10n
645
-	 * @param Message $iTipMessage
646
-	 * @param int $lastOccurrence
647
-	 */
648
-	private function addResponseButtons(IEMailTemplate $template, IL10N $l10n,
649
-										Message $iTipMessage, $lastOccurrence) {
650
-		$token = $this->createInvitationToken($iTipMessage, $lastOccurrence);
651
-
652
-		$template->addBodyButtonGroup(
653
-			$l10n->t('Accept'),
654
-			$this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
655
-				'token' => $token,
656
-			]),
657
-			$l10n->t('Decline'),
658
-			$this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
659
-				'token' => $token,
660
-			])
661
-		);
662
-
663
-		$moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
664
-			'token' => $token,
665
-		]);
666
-		$html = vsprintf('<small><a href="%s">%s</a></small>', [
667
-			$moreOptionsURL, $l10n->t('More options …')
668
-		]);
669
-		$text = $l10n->t('More options at %s', [$moreOptionsURL]);
670
-
671
-		$template->addBodyText($html, $text);
672
-	}
673
-
674
-	/**
675
-	 * @param string $path
676
-	 * @return string
677
-	 */
678
-	private function getAbsoluteImagePath($path) {
679
-		return $this->urlGenerator->getAbsoluteURL(
680
-			$this->urlGenerator->imagePath('core', $path)
681
-		);
682
-	}
683
-
684
-	/**
685
-	 * @param Message $iTipMessage
686
-	 * @param int $lastOccurrence
687
-	 * @return string
688
-	 */
689
-	private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string {
690
-		$token = $this->random->generate(60, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
691
-
692
-		/** @var VEvent $vevent */
693
-		$vevent = $iTipMessage->message->VEVENT;
694
-		$attendee = $iTipMessage->recipient;
695
-		$organizer = $iTipMessage->sender;
696
-		$sequence = $iTipMessage->sequence;
697
-		$recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
698
-			$vevent->{'RECURRENCE-ID'}->serialize() : null;
699
-		$uid = $vevent->{'UID'};
700
-
701
-		$query = $this->db->getQueryBuilder();
702
-		$query->insert('calendar_invitations')
703
-			->values([
704
-				'token' => $query->createNamedParameter($token),
705
-				'attendee' => $query->createNamedParameter($attendee),
706
-				'organizer' => $query->createNamedParameter($organizer),
707
-				'sequence' => $query->createNamedParameter($sequence),
708
-				'recurrenceid' => $query->createNamedParameter($recurrenceId),
709
-				'expiration' => $query->createNamedParameter($lastOccurrence),
710
-				'uid' => $query->createNamedParameter($uid)
711
-			])
712
-			->execute();
713
-
714
-		return $token;
715
-	}
279
+            $recipientDomain = substr(strrchr($recipient, "@"), 1);
280
+            $invitationLinkRecipients = explode(',', preg_replace('/\s+/', '', strtolower($this->config->getAppValue('dav', 'invitation_link_recipients', 'yes'))));
281
+
282
+            if (strcmp('yes', $invitationLinkRecipients[0]) === 0
283
+                 || in_array(strtolower($recipient), $invitationLinkRecipients)
284
+                 || in_array(strtolower($recipientDomain), $invitationLinkRecipients)) {
285
+                $this->addResponseButtons($template, $l10n, $iTipMessage, $lastOccurrence);
286
+            }
287
+        }
288
+
289
+        $template->addFooter();
290
+
291
+        $message->useTemplate($template);
292
+
293
+        $attachment = $this->mailer->createAttachment(
294
+            $iTipMessage->message->serialize(),
295
+            'event.ics',// TODO(leon): Make file name unique, e.g. add event id
296
+            'text/calendar; method=' . $iTipMessage->method
297
+        );
298
+        $message->attach($attachment);
299
+
300
+        try {
301
+            $failed = $this->mailer->send($message);
302
+            $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
303
+            if ($failed) {
304
+                $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
305
+                $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
306
+            }
307
+        } catch (\Exception $ex) {
308
+            $this->logger->logException($ex, ['app' => 'dav']);
309
+            $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
310
+        }
311
+    }
312
+
313
+    /**
314
+     * check if event took place in the past already
315
+     * @param VCalendar $vObject
316
+     * @return int
317
+     */
318
+    private function getLastOccurrence(VCalendar $vObject) {
319
+        /** @var VEvent $component */
320
+        $component = $vObject->VEVENT;
321
+
322
+        $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
323
+        // Finding the last occurrence is a bit harder
324
+        if (!isset($component->RRULE)) {
325
+            if (isset($component->DTEND)) {
326
+                $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
327
+            } elseif (isset($component->DURATION)) {
328
+                /** @var \DateTime $endDate */
329
+                $endDate = clone $component->DTSTART->getDateTime();
330
+                // $component->DTEND->getDateTime() returns DateTimeImmutable
331
+                $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
332
+                $lastOccurrence = $endDate->getTimestamp();
333
+            } elseif (!$component->DTSTART->hasTime()) {
334
+                /** @var \DateTime $endDate */
335
+                $endDate = clone $component->DTSTART->getDateTime();
336
+                // $component->DTSTART->getDateTime() returns DateTimeImmutable
337
+                $endDate = $endDate->modify('+1 day');
338
+                $lastOccurrence = $endDate->getTimestamp();
339
+            } else {
340
+                $lastOccurrence = $firstOccurrence;
341
+            }
342
+        } else {
343
+            $it = new EventIterator($vObject, (string)$component->UID);
344
+            $maxDate = new \DateTime(self::MAX_DATE);
345
+            if ($it->isInfinite()) {
346
+                $lastOccurrence = $maxDate->getTimestamp();
347
+            } else {
348
+                $end = $it->getDtEnd();
349
+                while ($it->valid() && $end < $maxDate) {
350
+                    $end = $it->getDtEnd();
351
+                    $it->next();
352
+                }
353
+                $lastOccurrence = $end->getTimestamp();
354
+            }
355
+        }
356
+
357
+        return $lastOccurrence;
358
+    }
359
+
360
+    /**
361
+     * @param Message $iTipMessage
362
+     * @return null|Property
363
+     */
364
+    private function getCurrentAttendee(Message $iTipMessage) {
365
+        /** @var VEvent $vevent */
366
+        $vevent = $iTipMessage->message->VEVENT;
367
+        $attendees = $vevent->select('ATTENDEE');
368
+        foreach ($attendees as $attendee) {
369
+            /** @var Property $attendee */
370
+            if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
371
+                return $attendee;
372
+            }
373
+        }
374
+        return null;
375
+    }
376
+
377
+    /**
378
+     * @param string $default
379
+     * @param Property|null $attendee
380
+     * @return string
381
+     */
382
+    private function getAttendeeLangOrDefault($default, Property $attendee = null) {
383
+        if ($attendee !== null) {
384
+            $lang = $attendee->offsetGet('LANGUAGE');
385
+            if ($lang instanceof Parameter) {
386
+                return $lang->getValue();
387
+            }
388
+        }
389
+        return $default;
390
+    }
391
+
392
+    /**
393
+     * @param Property|null $attendee
394
+     * @return bool
395
+     */
396
+    private function getAttendeeRSVP(Property $attendee = null) {
397
+        if ($attendee !== null) {
398
+            $rsvp = $attendee->offsetGet('RSVP');
399
+            if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
400
+                return true;
401
+            }
402
+        }
403
+        // RFC 5545 3.2.17: default RSVP is false
404
+        return false;
405
+    }
406
+
407
+    /**
408
+     * @param IL10N $l10n
409
+     * @param VEvent $vevent
410
+     */
411
+    private function generateWhenString(IL10N $l10n, VEvent $vevent) {
412
+        $dtstart = $vevent->DTSTART;
413
+        if (isset($vevent->DTEND)) {
414
+            $dtend = $vevent->DTEND;
415
+        } elseif (isset($vevent->DURATION)) {
416
+            $isFloating = $vevent->DTSTART->isFloating();
417
+            $dtend = clone $vevent->DTSTART;
418
+            $endDateTime = $dtend->getDateTime();
419
+            $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
420
+            $dtend->setDateTime($endDateTime, $isFloating);
421
+        } elseif (!$vevent->DTSTART->hasTime()) {
422
+            $isFloating = $vevent->DTSTART->isFloating();
423
+            $dtend = clone $vevent->DTSTART;
424
+            $endDateTime = $dtend->getDateTime();
425
+            $endDateTime = $endDateTime->modify('+1 day');
426
+            $dtend->setDateTime($endDateTime, $isFloating);
427
+        } else {
428
+            $dtend = clone $vevent->DTSTART;
429
+        }
430
+
431
+        $isAllDay = $dtstart instanceof Property\ICalendar\Date;
432
+
433
+        /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
434
+        /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
435
+        /** @var \DateTimeImmutable $dtstartDt */
436
+        $dtstartDt = $dtstart->getDateTime();
437
+        /** @var \DateTimeImmutable $dtendDt */
438
+        $dtendDt = $dtend->getDateTime();
439
+
440
+        $diff = $dtstartDt->diff($dtendDt);
441
+
442
+        $dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
443
+        $dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
444
+
445
+        if ($isAllDay) {
446
+            // One day event
447
+            if ($diff->days === 1) {
448
+                return $l10n->l('date', $dtstartDt, ['width' => 'medium']);
449
+            }
450
+
451
+            // DTEND is exclusive, so if the ics data says 2020-01-01 to 2020-01-05,
452
+            // the email should show 2020-01-01 to 2020-01-04.
453
+            $dtendDt->modify('-1 day');
454
+
455
+            //event that spans over multiple days
456
+            $localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
457
+            $localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
458
+
459
+            return $localeStart . ' - ' . $localeEnd;
460
+        }
461
+
462
+        /** @var Property\ICalendar\DateTime $dtstart */
463
+        /** @var Property\ICalendar\DateTime $dtend */
464
+        $isFloating = $dtstart->isFloating();
465
+        $startTimezone = $endTimezone = null;
466
+        if (!$isFloating) {
467
+            $prop = $dtstart->offsetGet('TZID');
468
+            if ($prop instanceof Parameter) {
469
+                $startTimezone = $prop->getValue();
470
+            }
471
+
472
+            $prop = $dtend->offsetGet('TZID');
473
+            if ($prop instanceof Parameter) {
474
+                $endTimezone = $prop->getValue();
475
+            }
476
+        }
477
+
478
+        $localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
479
+            $l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
480
+
481
+        // always show full date with timezone if timezones are different
482
+        if ($startTimezone !== $endTimezone) {
483
+            $localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
484
+
485
+            return $localeStart . ' (' . $startTimezone . ') - ' .
486
+                $localeEnd . ' (' . $endTimezone . ')';
487
+        }
488
+
489
+        // show only end time if date is the same
490
+        if ($this->isDayEqual($dtstartDt, $dtendDt)) {
491
+            $localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
492
+        } else {
493
+            $localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
494
+                $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
495
+        }
496
+
497
+        return  $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
498
+    }
499
+
500
+    /**
501
+     * @param \DateTime $dtStart
502
+     * @param \DateTime $dtEnd
503
+     * @return bool
504
+     */
505
+    private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) {
506
+        return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
507
+    }
508
+
509
+    /**
510
+     * @param IEMailTemplate $template
511
+     * @param IL10N $l10n
512
+     * @param string $method
513
+     * @param string $summary
514
+     */
515
+    private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
516
+                                            $method, $summary) {
517
+        if ($method === self::METHOD_CANCEL) {
518
+            $template->setSubject('Canceled: ' . $summary);
519
+            $template->addHeading($l10n->t('Invitation canceled'));
520
+        } elseif ($method === self::METHOD_REPLY) {
521
+            $template->setSubject('Re: ' . $summary);
522
+            $template->addHeading($l10n->t('Invitation updated'));
523
+        } else {
524
+            $template->setSubject('Invitation: ' . $summary);
525
+            $template->addHeading($l10n->t('Invitation'));
526
+        }
527
+    }
528
+
529
+    /**
530
+     * @param IEMailTemplate $template
531
+     * @param IL10N $l10n
532
+     * @param VEVENT $vevent
533
+     */
534
+    private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) {
535
+        if ($vevent->SUMMARY) {
536
+            $template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'),
537
+                $this->getAbsoluteImagePath('caldav/title.svg'),'','',self::IMIP_INDENT);
538
+        }
539
+        $meetingWhen = $this->generateWhenString($l10n, $vevent);
540
+        if ($meetingWhen) {
541
+            $template->addBodyListItem($meetingWhen, $l10n->t('Time:'),
542
+                $this->getAbsoluteImagePath('caldav/time.svg'),'','',self::IMIP_INDENT);
543
+        }
544
+        if ($vevent->LOCATION) {
545
+            $template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'),
546
+                $this->getAbsoluteImagePath('caldav/location.svg'),'','',self::IMIP_INDENT);
547
+        }
548
+        if ($vevent->URL) {
549
+            $url = $vevent->URL->getValue();
550
+            $template->addBodyListItem(sprintf('<a href="%s">%s</a>',
551
+                    htmlspecialchars($url),
552
+                    htmlspecialchars($url)),
553
+                $l10n->t('Link:'),
554
+                $this->getAbsoluteImagePath('caldav/link.svg'),
555
+                $url,'',self::IMIP_INDENT);
556
+        }
557
+
558
+        $this->addAttendees($template, $l10n, $vevent);
559
+
560
+        /* Put description last, like an email body, since it can be arbitrarily long */
561
+        if ($vevent->DESCRIPTION) {
562
+            $template->addBodyListItem($vevent->DESCRIPTION->getValue(), $l10n->t('Description:'),
563
+                $this->getAbsoluteImagePath('caldav/description.svg'),'','',self::IMIP_INDENT);
564
+        }
565
+    }
566
+
567
+    /**
568
+     * addAttendees: add organizer and attendee names/emails to iMip mail.
569
+     *
570
+     * Enable with DAV setting: invitation_list_attendees (default: no)
571
+     *
572
+     * The default is 'no', which matches old behavior, and is privacy preserving.
573
+     *
574
+     * To enable including attendees in invitation emails:
575
+     *   % php occ config:app:set dav invitation_list_attendees --value yes
576
+     *
577
+     * @param IEMailTemplate $template
578
+     * @param IL10N $l10n
579
+     * @param Message $iTipMessage
580
+     * @param int $lastOccurrence
581
+     * @author brad2014 on github.com
582
+     */
583
+
584
+    private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) {
585
+        if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
586
+            return;
587
+        }
588
+
589
+        if (isset($vevent->ORGANIZER)) {
590
+            /** @var Property\ICalendar\CalAddress $organizer */
591
+            $organizer = $vevent->ORGANIZER;
592
+            $organizerURI = $organizer->getNormalizedValue();
593
+            [$scheme,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto:
594
+            /** @var string|null $organizerName */
595
+            $organizerName = isset($organizer['CN']) ? $organizer['CN'] : null;
596
+            $organizerHTML = sprintf('<a href="%s">%s</a>',
597
+                htmlspecialchars($organizerURI),
598
+                htmlspecialchars($organizerName ?: $organizerEmail));
599
+            $organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
600
+            if (isset($organizer['PARTSTAT'])) {
601
+                /** @var Parameter $partstat */
602
+                $partstat = $organizer['PARTSTAT'];
603
+                if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
604
+                    $organizerHTML .= ' ✔︎';
605
+                    $organizerText .= ' ✔︎';
606
+                }
607
+            }
608
+            $template->addBodyListItem($organizerHTML, $l10n->t('Organizer:'),
609
+                $this->getAbsoluteImagePath('caldav/organizer.svg'),
610
+                $organizerText,'',self::IMIP_INDENT);
611
+        }
612
+
613
+        $attendees = $vevent->select('ATTENDEE');
614
+        if (count($attendees) === 0) {
615
+            return;
616
+        }
617
+
618
+        $attendeesHTML = [];
619
+        $attendeesText = [];
620
+        foreach ($attendees as $attendee) {
621
+            $attendeeURI = $attendee->getNormalizedValue();
622
+            [$scheme,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto:
623
+            $attendeeName = isset($attendee['CN']) ? $attendee['CN'] : null;
624
+            $attendeeHTML = sprintf('<a href="%s">%s</a>',
625
+                htmlspecialchars($attendeeURI),
626
+                htmlspecialchars($attendeeName ?: $attendeeEmail));
627
+            $attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
628
+            if (isset($attendee['PARTSTAT'])
629
+                && strcasecmp($attendee['PARTSTAT'], 'ACCEPTED') === 0) {
630
+                $attendeeHTML .= ' ✔︎';
631
+                $attendeeText .= ' ✔︎';
632
+            }
633
+            array_push($attendeesHTML, $attendeeHTML);
634
+            array_push($attendeesText, $attendeeText);
635
+        }
636
+
637
+        $template->addBodyListItem(implode('<br/>',$attendeesHTML), $l10n->t('Attendees:'),
638
+            $this->getAbsoluteImagePath('caldav/attendees.svg'),
639
+            implode("\n",$attendeesText),'',self::IMIP_INDENT);
640
+    }
641
+
642
+    /**
643
+     * @param IEMailTemplate $template
644
+     * @param IL10N $l10n
645
+     * @param Message $iTipMessage
646
+     * @param int $lastOccurrence
647
+     */
648
+    private function addResponseButtons(IEMailTemplate $template, IL10N $l10n,
649
+                                        Message $iTipMessage, $lastOccurrence) {
650
+        $token = $this->createInvitationToken($iTipMessage, $lastOccurrence);
651
+
652
+        $template->addBodyButtonGroup(
653
+            $l10n->t('Accept'),
654
+            $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
655
+                'token' => $token,
656
+            ]),
657
+            $l10n->t('Decline'),
658
+            $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
659
+                'token' => $token,
660
+            ])
661
+        );
662
+
663
+        $moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
664
+            'token' => $token,
665
+        ]);
666
+        $html = vsprintf('<small><a href="%s">%s</a></small>', [
667
+            $moreOptionsURL, $l10n->t('More options …')
668
+        ]);
669
+        $text = $l10n->t('More options at %s', [$moreOptionsURL]);
670
+
671
+        $template->addBodyText($html, $text);
672
+    }
673
+
674
+    /**
675
+     * @param string $path
676
+     * @return string
677
+     */
678
+    private function getAbsoluteImagePath($path) {
679
+        return $this->urlGenerator->getAbsoluteURL(
680
+            $this->urlGenerator->imagePath('core', $path)
681
+        );
682
+    }
683
+
684
+    /**
685
+     * @param Message $iTipMessage
686
+     * @param int $lastOccurrence
687
+     * @return string
688
+     */
689
+    private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string {
690
+        $token = $this->random->generate(60, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
691
+
692
+        /** @var VEvent $vevent */
693
+        $vevent = $iTipMessage->message->VEVENT;
694
+        $attendee = $iTipMessage->recipient;
695
+        $organizer = $iTipMessage->sender;
696
+        $sequence = $iTipMessage->sequence;
697
+        $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
698
+            $vevent->{'RECURRENCE-ID'}->serialize() : null;
699
+        $uid = $vevent->{'UID'};
700
+
701
+        $query = $this->db->getQueryBuilder();
702
+        $query->insert('calendar_invitations')
703
+            ->values([
704
+                'token' => $query->createNamedParameter($token),
705
+                'attendee' => $query->createNamedParameter($attendee),
706
+                'organizer' => $query->createNamedParameter($organizer),
707
+                'sequence' => $query->createNamedParameter($sequence),
708
+                'recurrenceid' => $query->createNamedParameter($recurrenceId),
709
+                'expiration' => $query->createNamedParameter($lastOccurrence),
710
+                'uid' => $query->createNamedParameter($uid)
711
+            ])
712
+            ->execute();
713
+
714
+        return $token;
715
+    }
716 716
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -227,11 +227,11 @@  discard block
 block discarded – undo
227 227
 		}
228 228
 
229 229
 		$data = [
230
-			'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
231
-			'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
232
-			'meeting_title' => (string)$meetingTitle ?: $defaultVal,
233
-			'meeting_description' => (string)$meetingDescription ?: $defaultVal,
234
-			'meeting_url' => (string)$meetingUrl ?: $defaultVal,
230
+			'attendee_name' => (string) $meetingAttendeeName ?: $defaultVal,
231
+			'invitee_name' => (string) $meetingInviteeName ?: $defaultVal,
232
+			'meeting_title' => (string) $meetingTitle ?: $defaultVal,
233
+			'meeting_description' => (string) $meetingDescription ?: $defaultVal,
234
+			'meeting_url' => (string) $meetingUrl ?: $defaultVal,
235 235
 		];
236 236
 
237 237
 		$fromEMail = Util::getDefaultEmailAddress('invitations-noreply');
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 			$message->setReplyTo([$sender => $senderName]);
246 246
 		}
247 247
 
248
-		$template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
248
+		$template = $this->mailer->createEMailTemplate('dav.calendarInvite.'.$method, $data);
249 249
 		$template->addHeader();
250 250
 
251 251
 		$summary = ((string) $summary !== '') ? (string) $summary : $l10n->t('Untitled event');
@@ -292,8 +292,8 @@  discard block
 block discarded – undo
292 292
 
293 293
 		$attachment = $this->mailer->createAttachment(
294 294
 			$iTipMessage->message->serialize(),
295
-			'event.ics',// TODO(leon): Make file name unique, e.g. add event id
296
-			'text/calendar; method=' . $iTipMessage->method
295
+			'event.ics', // TODO(leon): Make file name unique, e.g. add event id
296
+			'text/calendar; method='.$iTipMessage->method
297 297
 		);
298 298
 		$message->attach($attachment);
299 299
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 				$lastOccurrence = $firstOccurrence;
341 341
 			}
342 342
 		} else {
343
-			$it = new EventIterator($vObject, (string)$component->UID);
343
+			$it = new EventIterator($vObject, (string) $component->UID);
344 344
 			$maxDate = new \DateTime(self::MAX_DATE);
345 345
 			if ($it->isInfinite()) {
346 346
 				$lastOccurrence = $maxDate->getTimestamp();
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 			$localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
457 457
 			$localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
458 458
 
459
-			return $localeStart . ' - ' . $localeEnd;
459
+			return $localeStart.' - '.$localeEnd;
460 460
 		}
461 461
 
462 462
 		/** @var Property\ICalendar\DateTime $dtstart */
@@ -475,26 +475,26 @@  discard block
 block discarded – undo
475 475
 			}
476 476
 		}
477 477
 
478
-		$localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
478
+		$localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']).', '.
479 479
 			$l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
480 480
 
481 481
 		// always show full date with timezone if timezones are different
482 482
 		if ($startTimezone !== $endTimezone) {
483 483
 			$localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
484 484
 
485
-			return $localeStart . ' (' . $startTimezone . ') - ' .
486
-				$localeEnd . ' (' . $endTimezone . ')';
485
+			return $localeStart.' ('.$startTimezone.') - '.
486
+				$localeEnd.' ('.$endTimezone.')';
487 487
 		}
488 488
 
489 489
 		// show only end time if date is the same
490 490
 		if ($this->isDayEqual($dtstartDt, $dtendDt)) {
491 491
 			$localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
492 492
 		} else {
493
-			$localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
493
+			$localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']).', '.
494 494
 				$l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
495 495
 		}
496 496
 
497
-		return  $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
497
+		return  $localeStart.' - '.$localeEnd.' ('.$startTimezone.')';
498 498
 	}
499 499
 
500 500
 	/**
@@ -515,13 +515,13 @@  discard block
 block discarded – undo
515 515
 	private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
516 516
 										  $method, $summary) {
517 517
 		if ($method === self::METHOD_CANCEL) {
518
-			$template->setSubject('Canceled: ' . $summary);
518
+			$template->setSubject('Canceled: '.$summary);
519 519
 			$template->addHeading($l10n->t('Invitation canceled'));
520 520
 		} elseif ($method === self::METHOD_REPLY) {
521
-			$template->setSubject('Re: ' . $summary);
521
+			$template->setSubject('Re: '.$summary);
522 522
 			$template->addHeading($l10n->t('Invitation updated'));
523 523
 		} else {
524
-			$template->setSubject('Invitation: ' . $summary);
524
+			$template->setSubject('Invitation: '.$summary);
525 525
 			$template->addHeading($l10n->t('Invitation'));
526 526
 		}
527 527
 	}
@@ -534,16 +534,16 @@  discard block
 block discarded – undo
534 534
 	private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) {
535 535
 		if ($vevent->SUMMARY) {
536 536
 			$template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'),
537
-				$this->getAbsoluteImagePath('caldav/title.svg'),'','',self::IMIP_INDENT);
537
+				$this->getAbsoluteImagePath('caldav/title.svg'), '', '', self::IMIP_INDENT);
538 538
 		}
539 539
 		$meetingWhen = $this->generateWhenString($l10n, $vevent);
540 540
 		if ($meetingWhen) {
541 541
 			$template->addBodyListItem($meetingWhen, $l10n->t('Time:'),
542
-				$this->getAbsoluteImagePath('caldav/time.svg'),'','',self::IMIP_INDENT);
542
+				$this->getAbsoluteImagePath('caldav/time.svg'), '', '', self::IMIP_INDENT);
543 543
 		}
544 544
 		if ($vevent->LOCATION) {
545 545
 			$template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'),
546
-				$this->getAbsoluteImagePath('caldav/location.svg'),'','',self::IMIP_INDENT);
546
+				$this->getAbsoluteImagePath('caldav/location.svg'), '', '', self::IMIP_INDENT);
547 547
 		}
548 548
 		if ($vevent->URL) {
549 549
 			$url = $vevent->URL->getValue();
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
 					htmlspecialchars($url)),
553 553
 				$l10n->t('Link:'),
554 554
 				$this->getAbsoluteImagePath('caldav/link.svg'),
555
-				$url,'',self::IMIP_INDENT);
555
+				$url, '', self::IMIP_INDENT);
556 556
 		}
557 557
 
558 558
 		$this->addAttendees($template, $l10n, $vevent);
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 		/* Put description last, like an email body, since it can be arbitrarily long */
561 561
 		if ($vevent->DESCRIPTION) {
562 562
 			$template->addBodyListItem($vevent->DESCRIPTION->getValue(), $l10n->t('Description:'),
563
-				$this->getAbsoluteImagePath('caldav/description.svg'),'','',self::IMIP_INDENT);
563
+				$this->getAbsoluteImagePath('caldav/description.svg'), '', '', self::IMIP_INDENT);
564 564
 		}
565 565
 	}
566 566
 
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 			/** @var Property\ICalendar\CalAddress $organizer */
591 591
 			$organizer = $vevent->ORGANIZER;
592 592
 			$organizerURI = $organizer->getNormalizedValue();
593
-			[$scheme,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto:
593
+			[$scheme, $organizerEmail] = explode(':', $organizerURI, 2); # strip off scheme mailto:
594 594
 			/** @var string|null $organizerName */
595 595
 			$organizerName = isset($organizer['CN']) ? $organizer['CN'] : null;
596 596
 			$organizerHTML = sprintf('<a href="%s">%s</a>',
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 			}
608 608
 			$template->addBodyListItem($organizerHTML, $l10n->t('Organizer:'),
609 609
 				$this->getAbsoluteImagePath('caldav/organizer.svg'),
610
-				$organizerText,'',self::IMIP_INDENT);
610
+				$organizerText, '', self::IMIP_INDENT);
611 611
 		}
612 612
 
613 613
 		$attendees = $vevent->select('ATTENDEE');
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
 		$attendeesText = [];
620 620
 		foreach ($attendees as $attendee) {
621 621
 			$attendeeURI = $attendee->getNormalizedValue();
622
-			[$scheme,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto:
622
+			[$scheme, $attendeeEmail] = explode(':', $attendeeURI, 2); # strip off scheme mailto:
623 623
 			$attendeeName = isset($attendee['CN']) ? $attendee['CN'] : null;
624 624
 			$attendeeHTML = sprintf('<a href="%s">%s</a>',
625 625
 				htmlspecialchars($attendeeURI),
@@ -634,9 +634,9 @@  discard block
 block discarded – undo
634 634
 			array_push($attendeesText, $attendeeText);
635 635
 		}
636 636
 
637
-		$template->addBodyListItem(implode('<br/>',$attendeesHTML), $l10n->t('Attendees:'),
637
+		$template->addBodyListItem(implode('<br/>', $attendeesHTML), $l10n->t('Attendees:'),
638 638
 			$this->getAbsoluteImagePath('caldav/attendees.svg'),
639
-			implode("\n",$attendeesText),'',self::IMIP_INDENT);
639
+			implode("\n", $attendeesText), '', self::IMIP_INDENT);
640 640
 	}
641 641
 
642 642
 	/**
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 	 * @return string
688 688
 	 */
689 689
 	private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string {
690
-		$token = $this->random->generate(60, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
690
+		$token = $this->random->generate(60, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
691 691
 
692 692
 		/** @var VEvent $vevent */
693 693
 		$vevent = $iTipMessage->message->VEVENT;
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2769 added lines, -2769 removed lines patch added patch discarded remove patch
@@ -96,2773 +96,2773 @@
 block discarded – undo
96 96
  * @package OCA\DAV\CalDAV
97 97
  */
98 98
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
99
-	public const CALENDAR_TYPE_CALENDAR = 0;
100
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
101
-
102
-	public const PERSONAL_CALENDAR_URI = 'personal';
103
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
104
-
105
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
106
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
107
-
108
-	/**
109
-	 * We need to specify a max date, because we need to stop *somewhere*
110
-	 *
111
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
112
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
113
-	 * in 2038-01-19 to avoid problems when the date is converted
114
-	 * to a unix timestamp.
115
-	 */
116
-	public const MAX_DATE = '2038-01-01';
117
-
118
-	public const ACCESS_PUBLIC = 4;
119
-	public const CLASSIFICATION_PUBLIC = 0;
120
-	public const CLASSIFICATION_PRIVATE = 1;
121
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
122
-
123
-	/**
124
-	 * List of CalDAV properties, and how they map to database field names
125
-	 * Add your own properties by simply adding on to this array.
126
-	 *
127
-	 * Note that only string-based properties are supported here.
128
-	 *
129
-	 * @var array
130
-	 */
131
-	public $propertyMap = [
132
-		'{DAV:}displayname' => 'displayname',
133
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
134
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
135
-		'{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
136
-		'{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
137
-	];
138
-
139
-	/**
140
-	 * List of subscription properties, and how they map to database field names.
141
-	 *
142
-	 * @var array
143
-	 */
144
-	public $subscriptionPropertyMap = [
145
-		'{DAV:}displayname' => 'displayname',
146
-		'{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
147
-		'{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
148
-		'{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
149
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
150
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
151
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
152
-	];
153
-
154
-	/** @var array properties to index */
155
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
156
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
157
-		'ORGANIZER'];
158
-
159
-	/** @var array parameters to index */
160
-	public static $indexParameters = [
161
-		'ATTENDEE' => ['CN'],
162
-		'ORGANIZER' => ['CN'],
163
-	];
164
-
165
-	/**
166
-	 * @var string[] Map of uid => display name
167
-	 */
168
-	protected $userDisplayNames;
169
-
170
-	/** @var IDBConnection */
171
-	private $db;
172
-
173
-	/** @var Backend */
174
-	private $calendarSharingBackend;
175
-
176
-	/** @var Principal */
177
-	private $principalBackend;
178
-
179
-	/** @var IUserManager */
180
-	private $userManager;
181
-
182
-	/** @var ISecureRandom */
183
-	private $random;
184
-
185
-	/** @var ILogger */
186
-	private $logger;
187
-
188
-	/** @var IEventDispatcher */
189
-	private $dispatcher;
190
-
191
-	/** @var EventDispatcherInterface */
192
-	private $legacyDispatcher;
193
-
194
-	/** @var bool */
195
-	private $legacyEndpoint;
196
-
197
-	/** @var string */
198
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
199
-
200
-	/**
201
-	 * CalDavBackend constructor.
202
-	 *
203
-	 * @param IDBConnection $db
204
-	 * @param Principal $principalBackend
205
-	 * @param IUserManager $userManager
206
-	 * @param IGroupManager $groupManager
207
-	 * @param ISecureRandom $random
208
-	 * @param ILogger $logger
209
-	 * @param IEventDispatcher $dispatcher
210
-	 * @param EventDispatcherInterface $legacyDispatcher
211
-	 * @param bool $legacyEndpoint
212
-	 */
213
-	public function __construct(IDBConnection $db,
214
-								Principal $principalBackend,
215
-								IUserManager $userManager,
216
-								IGroupManager $groupManager,
217
-								ISecureRandom $random,
218
-								ILogger $logger,
219
-								IEventDispatcher $dispatcher,
220
-								EventDispatcherInterface $legacyDispatcher,
221
-								bool $legacyEndpoint = false) {
222
-		$this->db = $db;
223
-		$this->principalBackend = $principalBackend;
224
-		$this->userManager = $userManager;
225
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
226
-		$this->random = $random;
227
-		$this->logger = $logger;
228
-		$this->dispatcher = $dispatcher;
229
-		$this->legacyDispatcher = $legacyDispatcher;
230
-		$this->legacyEndpoint = $legacyEndpoint;
231
-	}
232
-
233
-	/**
234
-	 * Return the number of calendars for a principal
235
-	 *
236
-	 * By default this excludes the automatically generated birthday calendar
237
-	 *
238
-	 * @param $principalUri
239
-	 * @param bool $excludeBirthday
240
-	 * @return int
241
-	 */
242
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
243
-		$principalUri = $this->convertPrincipal($principalUri, true);
244
-		$query = $this->db->getQueryBuilder();
245
-		$query->select($query->func()->count('*'))
246
-			->from('calendars');
247
-
248
-		if ($principalUri === '') {
249
-			$query->where($query->expr()->emptyString('principaluri'));
250
-		} else {
251
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
252
-		}
253
-
254
-		if ($excludeBirthday) {
255
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
256
-		}
257
-
258
-		$result = $query->execute();
259
-		$column = (int)$result->fetchOne();
260
-		$result->closeCursor();
261
-		return $column;
262
-	}
263
-
264
-	/**
265
-	 * Returns a list of calendars for a principal.
266
-	 *
267
-	 * Every project is an array with the following keys:
268
-	 *  * id, a unique id that will be used by other functions to modify the
269
-	 *    calendar. This can be the same as the uri or a database key.
270
-	 *  * uri, which the basename of the uri with which the calendar is
271
-	 *    accessed.
272
-	 *  * principaluri. The owner of the calendar. Almost always the same as
273
-	 *    principalUri passed to this method.
274
-	 *
275
-	 * Furthermore it can contain webdav properties in clark notation. A very
276
-	 * common one is '{DAV:}displayname'.
277
-	 *
278
-	 * Many clients also require:
279
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
280
-	 * For this property, you can just return an instance of
281
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
282
-	 *
283
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
284
-	 * ACL will automatically be put in read-only mode.
285
-	 *
286
-	 * @param string $principalUri
287
-	 * @return array
288
-	 */
289
-	public function getCalendarsForUser($principalUri) {
290
-		$principalUriOriginal = $principalUri;
291
-		$principalUri = $this->convertPrincipal($principalUri, true);
292
-		$fields = array_values($this->propertyMap);
293
-		$fields[] = 'id';
294
-		$fields[] = 'uri';
295
-		$fields[] = 'synctoken';
296
-		$fields[] = 'components';
297
-		$fields[] = 'principaluri';
298
-		$fields[] = 'transparent';
299
-
300
-		// Making fields a comma-delimited list
301
-		$query = $this->db->getQueryBuilder();
302
-		$query->select($fields)
303
-			->from('calendars')
304
-			->orderBy('calendarorder', 'ASC');
305
-
306
-		if ($principalUri === '') {
307
-			$query->where($query->expr()->emptyString('principaluri'));
308
-		} else {
309
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
310
-		}
311
-
312
-		$result = $query->execute();
313
-
314
-		$calendars = [];
315
-		while ($row = $result->fetch()) {
316
-			$row['principaluri'] = (string) $row['principaluri'];
317
-			$components = [];
318
-			if ($row['components']) {
319
-				$components = explode(',',$row['components']);
320
-			}
321
-
322
-			$calendar = [
323
-				'id' => $row['id'],
324
-				'uri' => $row['uri'],
325
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
326
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
327
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
328
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
329
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
330
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
331
-			];
332
-
333
-			foreach ($this->propertyMap as $xmlName => $dbName) {
334
-				$calendar[$xmlName] = $row[$dbName];
335
-			}
336
-
337
-			$this->addOwnerPrincipal($calendar);
338
-
339
-			if (!isset($calendars[$calendar['id']])) {
340
-				$calendars[$calendar['id']] = $calendar;
341
-			}
342
-		}
343
-		$result->closeCursor();
344
-
345
-		// query for shared calendars
346
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
347
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
348
-
349
-		$principals[] = $principalUri;
350
-
351
-		$fields = array_values($this->propertyMap);
352
-		$fields[] = 'a.id';
353
-		$fields[] = 'a.uri';
354
-		$fields[] = 'a.synctoken';
355
-		$fields[] = 'a.components';
356
-		$fields[] = 'a.principaluri';
357
-		$fields[] = 'a.transparent';
358
-		$fields[] = 's.access';
359
-		$query = $this->db->getQueryBuilder();
360
-		$query->select($fields)
361
-			->from('dav_shares', 's')
362
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
363
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
364
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
365
-			->setParameter('type', 'calendar')
366
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
367
-
368
-		$result = $query->execute();
369
-
370
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
371
-		while ($row = $result->fetch()) {
372
-			$row['principaluri'] = (string) $row['principaluri'];
373
-			if ($row['principaluri'] === $principalUri) {
374
-				continue;
375
-			}
376
-
377
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
378
-			if (isset($calendars[$row['id']])) {
379
-				if ($readOnly) {
380
-					// New share can not have more permissions then the old one.
381
-					continue;
382
-				}
383
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
384
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
385
-					// Old share is already read-write, no more permissions can be gained
386
-					continue;
387
-				}
388
-			}
389
-
390
-			[, $name] = Uri\split($row['principaluri']);
391
-			$uri = $row['uri'] . '_shared_by_' . $name;
392
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
393
-			$components = [];
394
-			if ($row['components']) {
395
-				$components = explode(',',$row['components']);
396
-			}
397
-			$calendar = [
398
-				'id' => $row['id'],
399
-				'uri' => $uri,
400
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
401
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
402
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
403
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
404
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
405
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
406
-				$readOnlyPropertyName => $readOnly,
407
-			];
408
-
409
-			foreach ($this->propertyMap as $xmlName => $dbName) {
410
-				$calendar[$xmlName] = $row[$dbName];
411
-			}
412
-
413
-			$this->addOwnerPrincipal($calendar);
414
-
415
-			$calendars[$calendar['id']] = $calendar;
416
-		}
417
-		$result->closeCursor();
418
-
419
-		return array_values($calendars);
420
-	}
421
-
422
-	/**
423
-	 * @param $principalUri
424
-	 * @return array
425
-	 */
426
-	public function getUsersOwnCalendars($principalUri) {
427
-		$principalUri = $this->convertPrincipal($principalUri, true);
428
-		$fields = array_values($this->propertyMap);
429
-		$fields[] = 'id';
430
-		$fields[] = 'uri';
431
-		$fields[] = 'synctoken';
432
-		$fields[] = 'components';
433
-		$fields[] = 'principaluri';
434
-		$fields[] = 'transparent';
435
-		// Making fields a comma-delimited list
436
-		$query = $this->db->getQueryBuilder();
437
-		$query->select($fields)->from('calendars')
438
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
439
-			->orderBy('calendarorder', 'ASC');
440
-		$stmt = $query->execute();
441
-		$calendars = [];
442
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
443
-			$row['principaluri'] = (string) $row['principaluri'];
444
-			$components = [];
445
-			if ($row['components']) {
446
-				$components = explode(',',$row['components']);
447
-			}
448
-			$calendar = [
449
-				'id' => $row['id'],
450
-				'uri' => $row['uri'],
451
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
452
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
453
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
454
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
455
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
456
-			];
457
-			foreach ($this->propertyMap as $xmlName => $dbName) {
458
-				$calendar[$xmlName] = $row[$dbName];
459
-			}
460
-
461
-			$this->addOwnerPrincipal($calendar);
462
-
463
-			if (!isset($calendars[$calendar['id']])) {
464
-				$calendars[$calendar['id']] = $calendar;
465
-			}
466
-		}
467
-		$stmt->closeCursor();
468
-		return array_values($calendars);
469
-	}
470
-
471
-
472
-	/**
473
-	 * @param $uid
474
-	 * @return string
475
-	 */
476
-	private function getUserDisplayName($uid) {
477
-		if (!isset($this->userDisplayNames[$uid])) {
478
-			$user = $this->userManager->get($uid);
479
-
480
-			if ($user instanceof IUser) {
481
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
482
-			} else {
483
-				$this->userDisplayNames[$uid] = $uid;
484
-			}
485
-		}
486
-
487
-		return $this->userDisplayNames[$uid];
488
-	}
489
-
490
-	/**
491
-	 * @return array
492
-	 */
493
-	public function getPublicCalendars() {
494
-		$fields = array_values($this->propertyMap);
495
-		$fields[] = 'a.id';
496
-		$fields[] = 'a.uri';
497
-		$fields[] = 'a.synctoken';
498
-		$fields[] = 'a.components';
499
-		$fields[] = 'a.principaluri';
500
-		$fields[] = 'a.transparent';
501
-		$fields[] = 's.access';
502
-		$fields[] = 's.publicuri';
503
-		$calendars = [];
504
-		$query = $this->db->getQueryBuilder();
505
-		$result = $query->select($fields)
506
-			->from('dav_shares', 's')
507
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
508
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
509
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
510
-			->execute();
511
-
512
-		while ($row = $result->fetch()) {
513
-			$row['principaluri'] = (string) $row['principaluri'];
514
-			[, $name] = Uri\split($row['principaluri']);
515
-			$row['displayname'] = $row['displayname'] . "($name)";
516
-			$components = [];
517
-			if ($row['components']) {
518
-				$components = explode(',',$row['components']);
519
-			}
520
-			$calendar = [
521
-				'id' => $row['id'],
522
-				'uri' => $row['publicuri'],
523
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
524
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
525
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
526
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
527
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
528
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
529
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
530
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
531
-			];
532
-
533
-			foreach ($this->propertyMap as $xmlName => $dbName) {
534
-				$calendar[$xmlName] = $row[$dbName];
535
-			}
536
-
537
-			$this->addOwnerPrincipal($calendar);
538
-
539
-			if (!isset($calendars[$calendar['id']])) {
540
-				$calendars[$calendar['id']] = $calendar;
541
-			}
542
-		}
543
-		$result->closeCursor();
544
-
545
-		return array_values($calendars);
546
-	}
547
-
548
-	/**
549
-	 * @param string $uri
550
-	 * @return array
551
-	 * @throws NotFound
552
-	 */
553
-	public function getPublicCalendar($uri) {
554
-		$fields = array_values($this->propertyMap);
555
-		$fields[] = 'a.id';
556
-		$fields[] = 'a.uri';
557
-		$fields[] = 'a.synctoken';
558
-		$fields[] = 'a.components';
559
-		$fields[] = 'a.principaluri';
560
-		$fields[] = 'a.transparent';
561
-		$fields[] = 's.access';
562
-		$fields[] = 's.publicuri';
563
-		$query = $this->db->getQueryBuilder();
564
-		$result = $query->select($fields)
565
-			->from('dav_shares', 's')
566
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
567
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
568
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
569
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
570
-			->execute();
571
-
572
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
573
-
574
-		$result->closeCursor();
575
-
576
-		if ($row === false) {
577
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
578
-		}
579
-
580
-		$row['principaluri'] = (string) $row['principaluri'];
581
-		[, $name] = Uri\split($row['principaluri']);
582
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
583
-		$components = [];
584
-		if ($row['components']) {
585
-			$components = explode(',',$row['components']);
586
-		}
587
-		$calendar = [
588
-			'id' => $row['id'],
589
-			'uri' => $row['publicuri'],
590
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
591
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
592
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
593
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
594
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
595
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
596
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
597
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
598
-		];
599
-
600
-		foreach ($this->propertyMap as $xmlName => $dbName) {
601
-			$calendar[$xmlName] = $row[$dbName];
602
-		}
603
-
604
-		$this->addOwnerPrincipal($calendar);
605
-
606
-		return $calendar;
607
-	}
608
-
609
-	/**
610
-	 * @param string $principal
611
-	 * @param string $uri
612
-	 * @return array|null
613
-	 */
614
-	public function getCalendarByUri($principal, $uri) {
615
-		$fields = array_values($this->propertyMap);
616
-		$fields[] = 'id';
617
-		$fields[] = 'uri';
618
-		$fields[] = 'synctoken';
619
-		$fields[] = 'components';
620
-		$fields[] = 'principaluri';
621
-		$fields[] = 'transparent';
622
-
623
-		// Making fields a comma-delimited list
624
-		$query = $this->db->getQueryBuilder();
625
-		$query->select($fields)->from('calendars')
626
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
627
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
628
-			->setMaxResults(1);
629
-		$stmt = $query->execute();
630
-
631
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
632
-		$stmt->closeCursor();
633
-		if ($row === false) {
634
-			return null;
635
-		}
636
-
637
-		$row['principaluri'] = (string) $row['principaluri'];
638
-		$components = [];
639
-		if ($row['components']) {
640
-			$components = explode(',',$row['components']);
641
-		}
642
-
643
-		$calendar = [
644
-			'id' => $row['id'],
645
-			'uri' => $row['uri'],
646
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
647
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
648
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
649
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
650
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
651
-		];
652
-
653
-		foreach ($this->propertyMap as $xmlName => $dbName) {
654
-			$calendar[$xmlName] = $row[$dbName];
655
-		}
656
-
657
-		$this->addOwnerPrincipal($calendar);
658
-
659
-		return $calendar;
660
-	}
661
-
662
-	/**
663
-	 * @param $calendarId
664
-	 * @return array|null
665
-	 */
666
-	public function getCalendarById($calendarId) {
667
-		$fields = array_values($this->propertyMap);
668
-		$fields[] = 'id';
669
-		$fields[] = 'uri';
670
-		$fields[] = 'synctoken';
671
-		$fields[] = 'components';
672
-		$fields[] = 'principaluri';
673
-		$fields[] = 'transparent';
674
-
675
-		// Making fields a comma-delimited list
676
-		$query = $this->db->getQueryBuilder();
677
-		$query->select($fields)->from('calendars')
678
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
679
-			->setMaxResults(1);
680
-		$stmt = $query->execute();
681
-
682
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
683
-		$stmt->closeCursor();
684
-		if ($row === false) {
685
-			return null;
686
-		}
687
-
688
-		$row['principaluri'] = (string) $row['principaluri'];
689
-		$components = [];
690
-		if ($row['components']) {
691
-			$components = explode(',',$row['components']);
692
-		}
693
-
694
-		$calendar = [
695
-			'id' => $row['id'],
696
-			'uri' => $row['uri'],
697
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
698
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
699
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
701
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
702
-		];
703
-
704
-		foreach ($this->propertyMap as $xmlName => $dbName) {
705
-			$calendar[$xmlName] = $row[$dbName];
706
-		}
707
-
708
-		$this->addOwnerPrincipal($calendar);
709
-
710
-		return $calendar;
711
-	}
712
-
713
-	/**
714
-	 * @param $subscriptionId
715
-	 */
716
-	public function getSubscriptionById($subscriptionId) {
717
-		$fields = array_values($this->subscriptionPropertyMap);
718
-		$fields[] = 'id';
719
-		$fields[] = 'uri';
720
-		$fields[] = 'source';
721
-		$fields[] = 'synctoken';
722
-		$fields[] = 'principaluri';
723
-		$fields[] = 'lastmodified';
724
-
725
-		$query = $this->db->getQueryBuilder();
726
-		$query->select($fields)
727
-			->from('calendarsubscriptions')
728
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
729
-			->orderBy('calendarorder', 'asc');
730
-		$stmt = $query->execute();
731
-
732
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
733
-		$stmt->closeCursor();
734
-		if ($row === false) {
735
-			return null;
736
-		}
737
-
738
-		$row['principaluri'] = (string) $row['principaluri'];
739
-		$subscription = [
740
-			'id' => $row['id'],
741
-			'uri' => $row['uri'],
742
-			'principaluri' => $row['principaluri'],
743
-			'source' => $row['source'],
744
-			'lastmodified' => $row['lastmodified'],
745
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
746
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
747
-		];
748
-
749
-		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
750
-			if (!is_null($row[$dbName])) {
751
-				$subscription[$xmlName] = $row[$dbName];
752
-			}
753
-		}
754
-
755
-		return $subscription;
756
-	}
757
-
758
-	/**
759
-	 * Creates a new calendar for a principal.
760
-	 *
761
-	 * If the creation was a success, an id must be returned that can be used to reference
762
-	 * this calendar in other methods, such as updateCalendar.
763
-	 *
764
-	 * @param string $principalUri
765
-	 * @param string $calendarUri
766
-	 * @param array $properties
767
-	 * @return int
768
-	 */
769
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
770
-		$values = [
771
-			'principaluri' => $this->convertPrincipal($principalUri, true),
772
-			'uri' => $calendarUri,
773
-			'synctoken' => 1,
774
-			'transparent' => 0,
775
-			'components' => 'VEVENT,VTODO',
776
-			'displayname' => $calendarUri
777
-		];
778
-
779
-		// Default value
780
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
781
-		if (isset($properties[$sccs])) {
782
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
783
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
784
-			}
785
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
786
-		} elseif (isset($properties['components'])) {
787
-			// Allow to provide components internally without having
788
-			// to create a SupportedCalendarComponentSet object
789
-			$values['components'] = $properties['components'];
790
-		}
791
-
792
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
793
-		if (isset($properties[$transp])) {
794
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
795
-		}
796
-
797
-		foreach ($this->propertyMap as $xmlName => $dbName) {
798
-			if (isset($properties[$xmlName])) {
799
-				$values[$dbName] = $properties[$xmlName];
800
-			}
801
-		}
802
-
803
-		$query = $this->db->getQueryBuilder();
804
-		$query->insert('calendars');
805
-		foreach ($values as $column => $value) {
806
-			$query->setValue($column, $query->createNamedParameter($value));
807
-		}
808
-		$query->execute();
809
-		$calendarId = $query->getLastInsertId();
810
-
811
-		$calendarData = $this->getCalendarById($calendarId);
812
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
813
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
814
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
815
-			[
816
-				'calendarId' => $calendarId,
817
-				'calendarData' => $calendarData,
818
-			]));
819
-
820
-		return $calendarId;
821
-	}
822
-
823
-	/**
824
-	 * Updates properties for a calendar.
825
-	 *
826
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
827
-	 * To do the actual updates, you must tell this object which properties
828
-	 * you're going to process with the handle() method.
829
-	 *
830
-	 * Calling the handle method is like telling the PropPatch object "I
831
-	 * promise I can handle updating this property".
832
-	 *
833
-	 * Read the PropPatch documentation for more info and examples.
834
-	 *
835
-	 * @param mixed $calendarId
836
-	 * @param PropPatch $propPatch
837
-	 * @return void
838
-	 */
839
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
840
-		$supportedProperties = array_keys($this->propertyMap);
841
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
842
-
843
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
844
-			$newValues = [];
845
-			foreach ($mutations as $propertyName => $propertyValue) {
846
-				switch ($propertyName) {
847
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
848
-						$fieldName = 'transparent';
849
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
850
-						break;
851
-					default:
852
-						$fieldName = $this->propertyMap[$propertyName];
853
-						$newValues[$fieldName] = $propertyValue;
854
-						break;
855
-				}
856
-			}
857
-			$query = $this->db->getQueryBuilder();
858
-			$query->update('calendars');
859
-			foreach ($newValues as $fieldName => $value) {
860
-				$query->set($fieldName, $query->createNamedParameter($value));
861
-			}
862
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
863
-			$query->execute();
864
-
865
-			$this->addChange($calendarId, "", 2);
866
-
867
-			$calendarData = $this->getCalendarById($calendarId);
868
-			$shares = $this->getShares($calendarId);
869
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
870
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
871
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
872
-				[
873
-					'calendarId' => $calendarId,
874
-					'calendarData' => $calendarData,
875
-					'shares' => $shares,
876
-					'propertyMutations' => $mutations,
877
-				]));
878
-
879
-			return true;
880
-		});
881
-	}
882
-
883
-	/**
884
-	 * Delete a calendar and all it's objects
885
-	 *
886
-	 * @param mixed $calendarId
887
-	 * @return void
888
-	 */
889
-	public function deleteCalendar($calendarId) {
890
-		$calendarData = $this->getCalendarById($calendarId);
891
-		$shares = $this->getShares($calendarId);
892
-
893
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
894
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
895
-			[
896
-				'calendarId' => $calendarId,
897
-				'calendarData' => $calendarData,
898
-				'shares' => $shares,
899
-			]));
900
-
901
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
902
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
903
-
904
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
905
-		$stmt->execute([$calendarId]);
906
-
907
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
908
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
909
-
910
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
911
-
912
-		$query = $this->db->getQueryBuilder();
913
-		$query->delete($this->dbObjectPropertiesTable)
914
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
915
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
916
-			->execute();
917
-
918
-		if ($calendarData) {
919
-			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
920
-		}
921
-	}
922
-
923
-	/**
924
-	 * Delete all of an user's shares
925
-	 *
926
-	 * @param string $principaluri
927
-	 * @return void
928
-	 */
929
-	public function deleteAllSharesByUser($principaluri) {
930
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
931
-	}
932
-
933
-	/**
934
-	 * Returns all calendar objects within a calendar.
935
-	 *
936
-	 * Every item contains an array with the following keys:
937
-	 *   * calendardata - The iCalendar-compatible calendar data
938
-	 *   * uri - a unique key which will be used to construct the uri. This can
939
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
940
-	 *     good idea. This is only the basename, or filename, not the full
941
-	 *     path.
942
-	 *   * lastmodified - a timestamp of the last modification time
943
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
944
-	 *   '"abcdef"')
945
-	 *   * size - The size of the calendar objects, in bytes.
946
-	 *   * component - optional, a string containing the type of object, such
947
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
948
-	 *     the Content-Type header.
949
-	 *
950
-	 * Note that the etag is optional, but it's highly encouraged to return for
951
-	 * speed reasons.
952
-	 *
953
-	 * The calendardata is also optional. If it's not returned
954
-	 * 'getCalendarObject' will be called later, which *is* expected to return
955
-	 * calendardata.
956
-	 *
957
-	 * If neither etag or size are specified, the calendardata will be
958
-	 * used/fetched to determine these numbers. If both are specified the
959
-	 * amount of times this is needed is reduced by a great degree.
960
-	 *
961
-	 * @param mixed $calendarId
962
-	 * @param int $calendarType
963
-	 * @return array
964
-	 */
965
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
966
-		$query = $this->db->getQueryBuilder();
967
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
968
-			->from('calendarobjects')
969
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
970
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
971
-		$stmt = $query->execute();
972
-
973
-		$result = [];
974
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
975
-			$result[] = [
976
-				'id' => $row['id'],
977
-				'uri' => $row['uri'],
978
-				'lastmodified' => $row['lastmodified'],
979
-				'etag' => '"' . $row['etag'] . '"',
980
-				'calendarid' => $row['calendarid'],
981
-				'size' => (int)$row['size'],
982
-				'component' => strtolower($row['componenttype']),
983
-				'classification' => (int)$row['classification']
984
-			];
985
-		}
986
-		$stmt->closeCursor();
987
-
988
-		return $result;
989
-	}
990
-
991
-	/**
992
-	 * Returns information from a single calendar object, based on it's object
993
-	 * uri.
994
-	 *
995
-	 * The object uri is only the basename, or filename and not a full path.
996
-	 *
997
-	 * The returned array must have the same keys as getCalendarObjects. The
998
-	 * 'calendardata' object is required here though, while it's not required
999
-	 * for getCalendarObjects.
1000
-	 *
1001
-	 * This method must return null if the object did not exist.
1002
-	 *
1003
-	 * @param mixed $calendarId
1004
-	 * @param string $objectUri
1005
-	 * @param int $calendarType
1006
-	 * @return array|null
1007
-	 */
1008
-	public function getCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1009
-		$query = $this->db->getQueryBuilder();
1010
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1011
-			->from('calendarobjects')
1012
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1013
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1014
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1015
-		$stmt = $query->execute();
1016
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1017
-		$stmt->closeCursor();
1018
-
1019
-		if (!$row) {
1020
-			return null;
1021
-		}
1022
-
1023
-		return [
1024
-			'id' => $row['id'],
1025
-			'uri' => $row['uri'],
1026
-			'lastmodified' => $row['lastmodified'],
1027
-			'etag' => '"' . $row['etag'] . '"',
1028
-			'calendarid' => $row['calendarid'],
1029
-			'size' => (int)$row['size'],
1030
-			'calendardata' => $this->readBlob($row['calendardata']),
1031
-			'component' => strtolower($row['componenttype']),
1032
-			'classification' => (int)$row['classification']
1033
-		];
1034
-	}
1035
-
1036
-	/**
1037
-	 * Returns a list of calendar objects.
1038
-	 *
1039
-	 * This method should work identical to getCalendarObject, but instead
1040
-	 * return all the calendar objects in the list as an array.
1041
-	 *
1042
-	 * If the backend supports this, it may allow for some speed-ups.
1043
-	 *
1044
-	 * @param mixed $calendarId
1045
-	 * @param string[] $uris
1046
-	 * @param int $calendarType
1047
-	 * @return array
1048
-	 */
1049
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1050
-		if (empty($uris)) {
1051
-			return [];
1052
-		}
1053
-
1054
-		$chunks = array_chunk($uris, 100);
1055
-		$objects = [];
1056
-
1057
-		$query = $this->db->getQueryBuilder();
1058
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1059
-			->from('calendarobjects')
1060
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1061
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1062
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1063
-
1064
-		foreach ($chunks as $uris) {
1065
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1066
-			$result = $query->execute();
1067
-
1068
-			while ($row = $result->fetch()) {
1069
-				$objects[] = [
1070
-					'id' => $row['id'],
1071
-					'uri' => $row['uri'],
1072
-					'lastmodified' => $row['lastmodified'],
1073
-					'etag' => '"' . $row['etag'] . '"',
1074
-					'calendarid' => $row['calendarid'],
1075
-					'size' => (int)$row['size'],
1076
-					'calendardata' => $this->readBlob($row['calendardata']),
1077
-					'component' => strtolower($row['componenttype']),
1078
-					'classification' => (int)$row['classification']
1079
-				];
1080
-			}
1081
-			$result->closeCursor();
1082
-		}
1083
-
1084
-		return $objects;
1085
-	}
1086
-
1087
-	/**
1088
-	 * Creates a new calendar object.
1089
-	 *
1090
-	 * The object uri is only the basename, or filename and not a full path.
1091
-	 *
1092
-	 * It is possible return an etag from this function, which will be used in
1093
-	 * the response to this PUT request. Note that the ETag must be surrounded
1094
-	 * by double-quotes.
1095
-	 *
1096
-	 * However, you should only really return this ETag if you don't mangle the
1097
-	 * calendar-data. If the result of a subsequent GET to this object is not
1098
-	 * the exact same as this request body, you should omit the ETag.
1099
-	 *
1100
-	 * @param mixed $calendarId
1101
-	 * @param string $objectUri
1102
-	 * @param string $calendarData
1103
-	 * @param int $calendarType
1104
-	 * @return string
1105
-	 */
1106
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1107
-		$extraData = $this->getDenormalizedData($calendarData);
1108
-
1109
-		$q = $this->db->getQueryBuilder();
1110
-		$q->select($q->func()->count('*'))
1111
-			->from('calendarobjects')
1112
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1113
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1114
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1115
-
1116
-		$result = $q->execute();
1117
-		$count = (int) $result->fetchOne();
1118
-		$result->closeCursor();
1119
-
1120
-		if ($count !== 0) {
1121
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1122
-		}
1123
-
1124
-		$query = $this->db->getQueryBuilder();
1125
-		$query->insert('calendarobjects')
1126
-			->values([
1127
-				'calendarid' => $query->createNamedParameter($calendarId),
1128
-				'uri' => $query->createNamedParameter($objectUri),
1129
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1130
-				'lastmodified' => $query->createNamedParameter(time()),
1131
-				'etag' => $query->createNamedParameter($extraData['etag']),
1132
-				'size' => $query->createNamedParameter($extraData['size']),
1133
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1134
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1135
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1136
-				'classification' => $query->createNamedParameter($extraData['classification']),
1137
-				'uid' => $query->createNamedParameter($extraData['uid']),
1138
-				'calendartype' => $query->createNamedParameter($calendarType),
1139
-			])
1140
-			->execute();
1141
-
1142
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1143
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1144
-
1145
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1146
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1147
-			$calendarRow = $this->getCalendarById($calendarId);
1148
-			$shares = $this->getShares($calendarId);
1149
-
1150
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1151
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1152
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1153
-				[
1154
-					'calendarId' => $calendarId,
1155
-					'calendarData' => $calendarRow,
1156
-					'shares' => $shares,
1157
-					'objectData' => $objectRow,
1158
-				]
1159
-			));
1160
-		} else {
1161
-			$subscriptionRow = $this->getSubscriptionById($calendarId);
1162
-
1163
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1164
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1165
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1166
-				[
1167
-					'subscriptionId' => $calendarId,
1168
-					'calendarData' => $subscriptionRow,
1169
-					'shares' => [],
1170
-					'objectData' => $objectRow,
1171
-				]
1172
-			));
1173
-		}
1174
-
1175
-		return '"' . $extraData['etag'] . '"';
1176
-	}
1177
-
1178
-	/**
1179
-	 * Updates an existing calendarobject, based on it's uri.
1180
-	 *
1181
-	 * The object uri is only the basename, or filename and not a full path.
1182
-	 *
1183
-	 * It is possible return an etag from this function, which will be used in
1184
-	 * the response to this PUT request. Note that the ETag must be surrounded
1185
-	 * by double-quotes.
1186
-	 *
1187
-	 * However, you should only really return this ETag if you don't mangle the
1188
-	 * calendar-data. If the result of a subsequent GET to this object is not
1189
-	 * the exact same as this request body, you should omit the ETag.
1190
-	 *
1191
-	 * @param mixed $calendarId
1192
-	 * @param string $objectUri
1193
-	 * @param string $calendarData
1194
-	 * @param int $calendarType
1195
-	 * @return string
1196
-	 */
1197
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1198
-		$extraData = $this->getDenormalizedData($calendarData);
1199
-		$query = $this->db->getQueryBuilder();
1200
-		$query->update('calendarobjects')
1201
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1202
-				->set('lastmodified', $query->createNamedParameter(time()))
1203
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1204
-				->set('size', $query->createNamedParameter($extraData['size']))
1205
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1206
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1207
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1208
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1209
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1210
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1211
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1212
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1213
-			->execute();
1214
-
1215
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1216
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1217
-
1218
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1219
-		if (is_array($objectRow)) {
1220
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1221
-				$calendarRow = $this->getCalendarById($calendarId);
1222
-				$shares = $this->getShares($calendarId);
1223
-
1224
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1225
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1226
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1227
-					[
1228
-						'calendarId' => $calendarId,
1229
-						'calendarData' => $calendarRow,
1230
-						'shares' => $shares,
1231
-						'objectData' => $objectRow,
1232
-					]
1233
-				));
1234
-			} else {
1235
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1236
-
1237
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1238
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1239
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1240
-					[
1241
-						'subscriptionId' => $calendarId,
1242
-						'calendarData' => $subscriptionRow,
1243
-						'shares' => [],
1244
-						'objectData' => $objectRow,
1245
-					]
1246
-				));
1247
-			}
1248
-		}
1249
-
1250
-		return '"' . $extraData['etag'] . '"';
1251
-	}
1252
-
1253
-	/**
1254
-	 * @param int $calendarObjectId
1255
-	 * @param int $classification
1256
-	 */
1257
-	public function setClassification($calendarObjectId, $classification) {
1258
-		if (!in_array($classification, [
1259
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1260
-		])) {
1261
-			throw new \InvalidArgumentException();
1262
-		}
1263
-		$query = $this->db->getQueryBuilder();
1264
-		$query->update('calendarobjects')
1265
-			->set('classification', $query->createNamedParameter($classification))
1266
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1267
-			->execute();
1268
-	}
1269
-
1270
-	/**
1271
-	 * Deletes an existing calendar object.
1272
-	 *
1273
-	 * The object uri is only the basename, or filename and not a full path.
1274
-	 *
1275
-	 * @param mixed $calendarId
1276
-	 * @param string $objectUri
1277
-	 * @param int $calendarType
1278
-	 * @return void
1279
-	 */
1280
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1281
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1282
-		if (is_array($data)) {
1283
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1284
-				$calendarRow = $this->getCalendarById($calendarId);
1285
-				$shares = $this->getShares($calendarId);
1286
-
1287
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1288
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1289
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1290
-					[
1291
-						'calendarId' => $calendarId,
1292
-						'calendarData' => $calendarRow,
1293
-						'shares' => $shares,
1294
-						'objectData' => $data,
1295
-					]
1296
-				));
1297
-			} else {
1298
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1299
-
1300
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1301
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1302
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1303
-					[
1304
-						'subscriptionId' => $calendarId,
1305
-						'calendarData' => $subscriptionRow,
1306
-						'shares' => [],
1307
-						'objectData' => $data,
1308
-					]
1309
-				));
1310
-			}
1311
-		}
1312
-
1313
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1314
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1315
-
1316
-		if (is_array($data)) {
1317
-			$this->purgeProperties($calendarId, $data['id'], $calendarType);
1318
-		}
1319
-
1320
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1321
-	}
1322
-
1323
-	/**
1324
-	 * Performs a calendar-query on the contents of this calendar.
1325
-	 *
1326
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1327
-	 * calendar-query it is possible for a client to request a specific set of
1328
-	 * object, based on contents of iCalendar properties, date-ranges and
1329
-	 * iCalendar component types (VTODO, VEVENT).
1330
-	 *
1331
-	 * This method should just return a list of (relative) urls that match this
1332
-	 * query.
1333
-	 *
1334
-	 * The list of filters are specified as an array. The exact array is
1335
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1336
-	 *
1337
-	 * Note that it is extremely likely that getCalendarObject for every path
1338
-	 * returned from this method will be called almost immediately after. You
1339
-	 * may want to anticipate this to speed up these requests.
1340
-	 *
1341
-	 * This method provides a default implementation, which parses *all* the
1342
-	 * iCalendar objects in the specified calendar.
1343
-	 *
1344
-	 * This default may well be good enough for personal use, and calendars
1345
-	 * that aren't very large. But if you anticipate high usage, big calendars
1346
-	 * or high loads, you are strongly advised to optimize certain paths.
1347
-	 *
1348
-	 * The best way to do so is override this method and to optimize
1349
-	 * specifically for 'common filters'.
1350
-	 *
1351
-	 * Requests that are extremely common are:
1352
-	 *   * requests for just VEVENTS
1353
-	 *   * requests for just VTODO
1354
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1355
-	 *
1356
-	 * ..and combinations of these requests. It may not be worth it to try to
1357
-	 * handle every possible situation and just rely on the (relatively
1358
-	 * easy to use) CalendarQueryValidator to handle the rest.
1359
-	 *
1360
-	 * Note that especially time-range-filters may be difficult to parse. A
1361
-	 * time-range filter specified on a VEVENT must for instance also handle
1362
-	 * recurrence rules correctly.
1363
-	 * A good example of how to interprete all these filters can also simply
1364
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1365
-	 * as possible, so it gives you a good idea on what type of stuff you need
1366
-	 * to think of.
1367
-	 *
1368
-	 * @param mixed $calendarId
1369
-	 * @param array $filters
1370
-	 * @param int $calendarType
1371
-	 * @return array
1372
-	 */
1373
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1374
-		$componentType = null;
1375
-		$requirePostFilter = true;
1376
-		$timeRange = null;
1377
-
1378
-		// if no filters were specified, we don't need to filter after a query
1379
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1380
-			$requirePostFilter = false;
1381
-		}
1382
-
1383
-		// Figuring out if there's a component filter
1384
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1385
-			$componentType = $filters['comp-filters'][0]['name'];
1386
-
1387
-			// Checking if we need post-filters
1388
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1389
-				$requirePostFilter = false;
1390
-			}
1391
-			// There was a time-range filter
1392
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1393
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1394
-
1395
-				// If start time OR the end time is not specified, we can do a
1396
-				// 100% accurate mysql query.
1397
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1398
-					$requirePostFilter = false;
1399
-				}
1400
-			}
1401
-		}
1402
-		$columns = ['uri'];
1403
-		if ($requirePostFilter) {
1404
-			$columns = ['uri', 'calendardata'];
1405
-		}
1406
-		$query = $this->db->getQueryBuilder();
1407
-		$query->select($columns)
1408
-			->from('calendarobjects')
1409
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1410
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1411
-
1412
-		if ($componentType) {
1413
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1414
-		}
1415
-
1416
-		if ($timeRange && $timeRange['start']) {
1417
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1418
-		}
1419
-		if ($timeRange && $timeRange['end']) {
1420
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1421
-		}
1422
-
1423
-		$stmt = $query->execute();
1424
-
1425
-		$result = [];
1426
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1427
-			if ($requirePostFilter) {
1428
-				// validateFilterForObject will parse the calendar data
1429
-				// catch parsing errors
1430
-				try {
1431
-					$matches = $this->validateFilterForObject($row, $filters);
1432
-				} catch (ParseException $ex) {
1433
-					$this->logger->logException($ex, [
1434
-						'app' => 'dav',
1435
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1436
-					]);
1437
-					continue;
1438
-				} catch (InvalidDataException $ex) {
1439
-					$this->logger->logException($ex, [
1440
-						'app' => 'dav',
1441
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1442
-					]);
1443
-					continue;
1444
-				}
1445
-
1446
-				if (!$matches) {
1447
-					continue;
1448
-				}
1449
-			}
1450
-			$result[] = $row['uri'];
1451
-		}
1452
-
1453
-		return $result;
1454
-	}
1455
-
1456
-	/**
1457
-	 * custom Nextcloud search extension for CalDAV
1458
-	 *
1459
-	 * TODO - this should optionally cover cached calendar objects as well
1460
-	 *
1461
-	 * @param string $principalUri
1462
-	 * @param array $filters
1463
-	 * @param integer|null $limit
1464
-	 * @param integer|null $offset
1465
-	 * @return array
1466
-	 */
1467
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1468
-		$calendars = $this->getCalendarsForUser($principalUri);
1469
-		$ownCalendars = [];
1470
-		$sharedCalendars = [];
1471
-
1472
-		$uriMapper = [];
1473
-
1474
-		foreach ($calendars as $calendar) {
1475
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1476
-				$ownCalendars[] = $calendar['id'];
1477
-			} else {
1478
-				$sharedCalendars[] = $calendar['id'];
1479
-			}
1480
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1481
-		}
1482
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1483
-			return [];
1484
-		}
1485
-
1486
-		$query = $this->db->getQueryBuilder();
1487
-		// Calendar id expressions
1488
-		$calendarExpressions = [];
1489
-		foreach ($ownCalendars as $id) {
1490
-			$calendarExpressions[] = $query->expr()->andX(
1491
-				$query->expr()->eq('c.calendarid',
1492
-					$query->createNamedParameter($id)),
1493
-				$query->expr()->eq('c.calendartype',
1494
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1495
-		}
1496
-		foreach ($sharedCalendars as $id) {
1497
-			$calendarExpressions[] = $query->expr()->andX(
1498
-				$query->expr()->eq('c.calendarid',
1499
-					$query->createNamedParameter($id)),
1500
-				$query->expr()->eq('c.classification',
1501
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1502
-				$query->expr()->eq('c.calendartype',
1503
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1504
-		}
1505
-
1506
-		if (count($calendarExpressions) === 1) {
1507
-			$calExpr = $calendarExpressions[0];
1508
-		} else {
1509
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1510
-		}
1511
-
1512
-		// Component expressions
1513
-		$compExpressions = [];
1514
-		foreach ($filters['comps'] as $comp) {
1515
-			$compExpressions[] = $query->expr()
1516
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1517
-		}
1518
-
1519
-		if (count($compExpressions) === 1) {
1520
-			$compExpr = $compExpressions[0];
1521
-		} else {
1522
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1523
-		}
1524
-
1525
-		if (!isset($filters['props'])) {
1526
-			$filters['props'] = [];
1527
-		}
1528
-		if (!isset($filters['params'])) {
1529
-			$filters['params'] = [];
1530
-		}
1531
-
1532
-		$propParamExpressions = [];
1533
-		foreach ($filters['props'] as $prop) {
1534
-			$propParamExpressions[] = $query->expr()->andX(
1535
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1536
-				$query->expr()->isNull('i.parameter')
1537
-			);
1538
-		}
1539
-		foreach ($filters['params'] as $param) {
1540
-			$propParamExpressions[] = $query->expr()->andX(
1541
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1542
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1543
-			);
1544
-		}
1545
-
1546
-		if (count($propParamExpressions) === 1) {
1547
-			$propParamExpr = $propParamExpressions[0];
1548
-		} else {
1549
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1550
-		}
1551
-
1552
-		$query->select(['c.calendarid', 'c.uri'])
1553
-			->from($this->dbObjectPropertiesTable, 'i')
1554
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1555
-			->where($calExpr)
1556
-			->andWhere($compExpr)
1557
-			->andWhere($propParamExpr)
1558
-			->andWhere($query->expr()->iLike('i.value',
1559
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1560
-
1561
-		if ($offset) {
1562
-			$query->setFirstResult($offset);
1563
-		}
1564
-		if ($limit) {
1565
-			$query->setMaxResults($limit);
1566
-		}
1567
-
1568
-		$stmt = $query->execute();
1569
-
1570
-		$result = [];
1571
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1572
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1573
-			if (!in_array($path, $result)) {
1574
-				$result[] = $path;
1575
-			}
1576
-		}
1577
-
1578
-		return $result;
1579
-	}
1580
-
1581
-	/**
1582
-	 * used for Nextcloud's calendar API
1583
-	 *
1584
-	 * @param array $calendarInfo
1585
-	 * @param string $pattern
1586
-	 * @param array $searchProperties
1587
-	 * @param array $options
1588
-	 * @param integer|null $limit
1589
-	 * @param integer|null $offset
1590
-	 *
1591
-	 * @return array
1592
-	 */
1593
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1594
-						   array $options, $limit, $offset) {
1595
-		$outerQuery = $this->db->getQueryBuilder();
1596
-		$innerQuery = $this->db->getQueryBuilder();
1597
-
1598
-		$innerQuery->selectDistinct('op.objectid')
1599
-			->from($this->dbObjectPropertiesTable, 'op')
1600
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1601
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1602
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1603
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1604
-
1605
-		// only return public items for shared calendars for now
1606
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1607
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1608
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1609
-		}
1610
-
1611
-		$or = $innerQuery->expr()->orX();
1612
-		foreach ($searchProperties as $searchProperty) {
1613
-			$or->add($innerQuery->expr()->eq('op.name',
1614
-				$outerQuery->createNamedParameter($searchProperty)));
1615
-		}
1616
-		$innerQuery->andWhere($or);
1617
-
1618
-		if ($pattern !== '') {
1619
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1620
-				$outerQuery->createNamedParameter('%' .
1621
-					$this->db->escapeLikeParameter($pattern) . '%')));
1622
-		}
1623
-
1624
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1625
-			->from('calendarobjects', 'c');
1626
-
1627
-		if (isset($options['timerange'])) {
1628
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1629
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1630
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1631
-			}
1632
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1633
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1634
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1635
-			}
1636
-		}
1637
-
1638
-		if (isset($options['types'])) {
1639
-			$or = $outerQuery->expr()->orX();
1640
-			foreach ($options['types'] as $type) {
1641
-				$or->add($outerQuery->expr()->eq('componenttype',
1642
-					$outerQuery->createNamedParameter($type)));
1643
-			}
1644
-			$outerQuery->andWhere($or);
1645
-		}
1646
-
1647
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1648
-			$outerQuery->createFunction($innerQuery->getSQL())));
1649
-
1650
-		if ($offset) {
1651
-			$outerQuery->setFirstResult($offset);
1652
-		}
1653
-		if ($limit) {
1654
-			$outerQuery->setMaxResults($limit);
1655
-		}
1656
-
1657
-		$result = $outerQuery->execute();
1658
-		$calendarObjects = $result->fetchAll();
1659
-
1660
-		return array_map(function ($o) {
1661
-			$calendarData = Reader::read($o['calendardata']);
1662
-			$comps = $calendarData->getComponents();
1663
-			$objects = [];
1664
-			$timezones = [];
1665
-			foreach ($comps as $comp) {
1666
-				if ($comp instanceof VTimeZone) {
1667
-					$timezones[] = $comp;
1668
-				} else {
1669
-					$objects[] = $comp;
1670
-				}
1671
-			}
1672
-
1673
-			return [
1674
-				'id' => $o['id'],
1675
-				'type' => $o['componenttype'],
1676
-				'uid' => $o['uid'],
1677
-				'uri' => $o['uri'],
1678
-				'objects' => array_map(function ($c) {
1679
-					return $this->transformSearchData($c);
1680
-				}, $objects),
1681
-				'timezones' => array_map(function ($c) {
1682
-					return $this->transformSearchData($c);
1683
-				}, $timezones),
1684
-			];
1685
-		}, $calendarObjects);
1686
-	}
1687
-
1688
-	/**
1689
-	 * @param Component $comp
1690
-	 * @return array
1691
-	 */
1692
-	private function transformSearchData(Component $comp) {
1693
-		$data = [];
1694
-		/** @var Component[] $subComponents */
1695
-		$subComponents = $comp->getComponents();
1696
-		/** @var Property[] $properties */
1697
-		$properties = array_filter($comp->children(), function ($c) {
1698
-			return $c instanceof Property;
1699
-		});
1700
-		$validationRules = $comp->getValidationRules();
1701
-
1702
-		foreach ($subComponents as $subComponent) {
1703
-			$name = $subComponent->name;
1704
-			if (!isset($data[$name])) {
1705
-				$data[$name] = [];
1706
-			}
1707
-			$data[$name][] = $this->transformSearchData($subComponent);
1708
-		}
1709
-
1710
-		foreach ($properties as $property) {
1711
-			$name = $property->name;
1712
-			if (!isset($validationRules[$name])) {
1713
-				$validationRules[$name] = '*';
1714
-			}
1715
-
1716
-			$rule = $validationRules[$property->name];
1717
-			if ($rule === '+' || $rule === '*') { // multiple
1718
-				if (!isset($data[$name])) {
1719
-					$data[$name] = [];
1720
-				}
1721
-
1722
-				$data[$name][] = $this->transformSearchProperty($property);
1723
-			} else { // once
1724
-				$data[$name] = $this->transformSearchProperty($property);
1725
-			}
1726
-		}
1727
-
1728
-		return $data;
1729
-	}
1730
-
1731
-	/**
1732
-	 * @param Property $prop
1733
-	 * @return array
1734
-	 */
1735
-	private function transformSearchProperty(Property $prop) {
1736
-		// No need to check Date, as it extends DateTime
1737
-		if ($prop instanceof Property\ICalendar\DateTime) {
1738
-			$value = $prop->getDateTime();
1739
-		} else {
1740
-			$value = $prop->getValue();
1741
-		}
1742
-
1743
-		return [
1744
-			$value,
1745
-			$prop->parameters()
1746
-		];
1747
-	}
1748
-
1749
-	/**
1750
-	 * @param string $principalUri
1751
-	 * @param string $pattern
1752
-	 * @param array $componentTypes
1753
-	 * @param array $searchProperties
1754
-	 * @param array $searchParameters
1755
-	 * @param array $options
1756
-	 * @return array
1757
-	 */
1758
-	public function searchPrincipalUri(string $principalUri,
1759
-									   string $pattern,
1760
-									   array $componentTypes,
1761
-									   array $searchProperties,
1762
-									   array $searchParameters,
1763
-									   array $options = []): array {
1764
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1765
-
1766
-		$calendarObjectIdQuery = $this->db->getQueryBuilder();
1767
-		$calendarOr = $calendarObjectIdQuery->expr()->orX();
1768
-		$searchOr = $calendarObjectIdQuery->expr()->orX();
1769
-
1770
-		// Fetch calendars and subscription
1771
-		$calendars = $this->getCalendarsForUser($principalUri);
1772
-		$subscriptions = $this->getSubscriptionsForUser($principalUri);
1773
-		foreach ($calendars as $calendar) {
1774
-			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
1775
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1776
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1777
-
1778
-			// If it's shared, limit search to public events
1779
-			if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
1780
-				&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1781
-				$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1782
-			}
1783
-
1784
-			$calendarOr->add($calendarAnd);
1785
-		}
1786
-		foreach ($subscriptions as $subscription) {
1787
-			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1788
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1789
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1790
-
1791
-			// If it's shared, limit search to public events
1792
-			if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
1793
-				&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1794
-				$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1795
-			}
1796
-
1797
-			$calendarOr->add($subscriptionAnd);
1798
-		}
1799
-
1800
-		foreach ($searchProperties as $property) {
1801
-			$propertyAnd = $calendarObjectIdQuery->expr()->andX();
1802
-			$propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1803
-			$propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1804
-
1805
-			$searchOr->add($propertyAnd);
1806
-		}
1807
-		foreach ($searchParameters as $property => $parameter) {
1808
-			$parameterAnd = $calendarObjectIdQuery->expr()->andX();
1809
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1810
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
1811
-
1812
-			$searchOr->add($parameterAnd);
1813
-		}
1814
-
1815
-		if ($calendarOr->count() === 0) {
1816
-			return [];
1817
-		}
1818
-		if ($searchOr->count() === 0) {
1819
-			return [];
1820
-		}
1821
-
1822
-		$calendarObjectIdQuery->selectDistinct('cob.objectid')
1823
-			->from($this->dbObjectPropertiesTable, 'cob')
1824
-			->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1825
-			->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1826
-			->andWhere($calendarOr)
1827
-			->andWhere($searchOr);
1828
-
1829
-		if ('' !== $pattern) {
1830
-			if (!$escapePattern) {
1831
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1832
-			} else {
1833
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1834
-			}
1835
-		}
1836
-
1837
-		if (isset($options['limit'])) {
1838
-			$calendarObjectIdQuery->setMaxResults($options['limit']);
1839
-		}
1840
-		if (isset($options['offset'])) {
1841
-			$calendarObjectIdQuery->setFirstResult($options['offset']);
1842
-		}
1843
-
1844
-		$result = $calendarObjectIdQuery->execute();
1845
-		$matches = $result->fetchAll();
1846
-		$result->closeCursor();
1847
-		$matches = array_map(static function (array $match):int {
1848
-			return (int) $match['objectid'];
1849
-		}, $matches);
1850
-
1851
-		$query = $this->db->getQueryBuilder();
1852
-		$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1853
-			->from('calendarobjects')
1854
-			->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1855
-
1856
-		$result = $query->execute();
1857
-		$calendarObjects = $result->fetchAll();
1858
-		$result->closeCursor();
1859
-
1860
-		return array_map(function (array $array): array {
1861
-			$array['calendarid'] = (int)$array['calendarid'];
1862
-			$array['calendartype'] = (int)$array['calendartype'];
1863
-			$array['calendardata'] = $this->readBlob($array['calendardata']);
1864
-
1865
-			return $array;
1866
-		}, $calendarObjects);
1867
-	}
1868
-
1869
-	/**
1870
-	 * Searches through all of a users calendars and calendar objects to find
1871
-	 * an object with a specific UID.
1872
-	 *
1873
-	 * This method should return the path to this object, relative to the
1874
-	 * calendar home, so this path usually only contains two parts:
1875
-	 *
1876
-	 * calendarpath/objectpath.ics
1877
-	 *
1878
-	 * If the uid is not found, return null.
1879
-	 *
1880
-	 * This method should only consider * objects that the principal owns, so
1881
-	 * any calendars owned by other principals that also appear in this
1882
-	 * collection should be ignored.
1883
-	 *
1884
-	 * @param string $principalUri
1885
-	 * @param string $uid
1886
-	 * @return string|null
1887
-	 */
1888
-	public function getCalendarObjectByUID($principalUri, $uid) {
1889
-		$query = $this->db->getQueryBuilder();
1890
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1891
-			->from('calendarobjects', 'co')
1892
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1893
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1894
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1895
-
1896
-		$stmt = $query->execute();
1897
-
1898
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1899
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1900
-		}
1901
-
1902
-		return null;
1903
-	}
1904
-
1905
-	/**
1906
-	 * The getChanges method returns all the changes that have happened, since
1907
-	 * the specified syncToken in the specified calendar.
1908
-	 *
1909
-	 * This function should return an array, such as the following:
1910
-	 *
1911
-	 * [
1912
-	 *   'syncToken' => 'The current synctoken',
1913
-	 *   'added'   => [
1914
-	 *      'new.txt',
1915
-	 *   ],
1916
-	 *   'modified'   => [
1917
-	 *      'modified.txt',
1918
-	 *   ],
1919
-	 *   'deleted' => [
1920
-	 *      'foo.php.bak',
1921
-	 *      'old.txt'
1922
-	 *   ]
1923
-	 * );
1924
-	 *
1925
-	 * The returned syncToken property should reflect the *current* syncToken
1926
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1927
-	 * property This is * needed here too, to ensure the operation is atomic.
1928
-	 *
1929
-	 * If the $syncToken argument is specified as null, this is an initial
1930
-	 * sync, and all members should be reported.
1931
-	 *
1932
-	 * The modified property is an array of nodenames that have changed since
1933
-	 * the last token.
1934
-	 *
1935
-	 * The deleted property is an array with nodenames, that have been deleted
1936
-	 * from collection.
1937
-	 *
1938
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1939
-	 * 1, you only have to report changes that happened only directly in
1940
-	 * immediate descendants. If it's 2, it should also include changes from
1941
-	 * the nodes below the child collections. (grandchildren)
1942
-	 *
1943
-	 * The $limit argument allows a client to specify how many results should
1944
-	 * be returned at most. If the limit is not specified, it should be treated
1945
-	 * as infinite.
1946
-	 *
1947
-	 * If the limit (infinite or not) is higher than you're willing to return,
1948
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1949
-	 *
1950
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1951
-	 * return null.
1952
-	 *
1953
-	 * The limit is 'suggestive'. You are free to ignore it.
1954
-	 *
1955
-	 * @param string $calendarId
1956
-	 * @param string $syncToken
1957
-	 * @param int $syncLevel
1958
-	 * @param int|null $limit
1959
-	 * @param int $calendarType
1960
-	 * @return array
1961
-	 */
1962
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1963
-		// Current synctoken
1964
-		$qb = $this->db->getQueryBuilder();
1965
-		$qb->select('synctoken')
1966
-			->from('calendars')
1967
-			->where(
1968
-				$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
1969
-			);
1970
-		$stmt = $qb->execute();
1971
-		$currentToken = $stmt->fetchOne();
1972
-
1973
-		if ($currentToken === false) {
1974
-			return null;
1975
-		}
1976
-
1977
-		$result = [
1978
-			'syncToken' => $currentToken,
1979
-			'added' => [],
1980
-			'modified' => [],
1981
-			'deleted' => [],
1982
-		];
1983
-
1984
-		if ($syncToken) {
1985
-			$qb = $this->db->getQueryBuilder();
1986
-
1987
-			$qb->select('uri', 'operation')
1988
-				->from('calendarchanges')
1989
-				->where(
1990
-					$qb->expr()->andX(
1991
-						$qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
1992
-						$qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
1993
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1994
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
1995
-					)
1996
-				)->orderBy('synctoken');
1997
-			if (is_int($limit) && $limit > 0) {
1998
-				$qb->setMaxResults($limit);
1999
-			}
2000
-
2001
-			// Fetching all changes
2002
-			$stmt = $qb->execute();
2003
-
2004
-			$changes = [];
2005
-
2006
-			// This loop ensures that any duplicates are overwritten, only the
2007
-			// last change on a node is relevant.
2008
-			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2009
-				$changes[$row['uri']] = $row['operation'];
2010
-			}
2011
-
2012
-			foreach ($changes as $uri => $operation) {
2013
-				switch ($operation) {
2014
-					case 1:
2015
-						$result['added'][] = $uri;
2016
-						break;
2017
-					case 2:
2018
-						$result['modified'][] = $uri;
2019
-						break;
2020
-					case 3:
2021
-						$result['deleted'][] = $uri;
2022
-						break;
2023
-				}
2024
-			}
2025
-		} else {
2026
-			// No synctoken supplied, this is the initial sync.
2027
-			$qb = $this->db->getQueryBuilder();
2028
-			$qb->select('uri')
2029
-				->from('calendarobjects')
2030
-				->where(
2031
-					$qb->expr()->andX(
2032
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2033
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2034
-					)
2035
-				);
2036
-			$stmt = $qb->execute();
2037
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2038
-		}
2039
-		return $result;
2040
-	}
2041
-
2042
-	/**
2043
-	 * Returns a list of subscriptions for a principal.
2044
-	 *
2045
-	 * Every subscription is an array with the following keys:
2046
-	 *  * id, a unique id that will be used by other functions to modify the
2047
-	 *    subscription. This can be the same as the uri or a database key.
2048
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2049
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2050
-	 *    principalUri passed to this method.
2051
-	 *
2052
-	 * Furthermore, all the subscription info must be returned too:
2053
-	 *
2054
-	 * 1. {DAV:}displayname
2055
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2056
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2057
-	 *    should not be stripped).
2058
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2059
-	 *    should not be stripped).
2060
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2061
-	 *    attachments should not be stripped).
2062
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2063
-	 *     Sabre\DAV\Property\Href).
2064
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2065
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2066
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2067
-	 *    (should just be an instance of
2068
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2069
-	 *    default components).
2070
-	 *
2071
-	 * @param string $principalUri
2072
-	 * @return array
2073
-	 */
2074
-	public function getSubscriptionsForUser($principalUri) {
2075
-		$fields = array_values($this->subscriptionPropertyMap);
2076
-		$fields[] = 'id';
2077
-		$fields[] = 'uri';
2078
-		$fields[] = 'source';
2079
-		$fields[] = 'principaluri';
2080
-		$fields[] = 'lastmodified';
2081
-		$fields[] = 'synctoken';
2082
-
2083
-		$query = $this->db->getQueryBuilder();
2084
-		$query->select($fields)
2085
-			->from('calendarsubscriptions')
2086
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2087
-			->orderBy('calendarorder', 'asc');
2088
-		$stmt = $query->execute();
2089
-
2090
-		$subscriptions = [];
2091
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2092
-			$subscription = [
2093
-				'id' => $row['id'],
2094
-				'uri' => $row['uri'],
2095
-				'principaluri' => $row['principaluri'],
2096
-				'source' => $row['source'],
2097
-				'lastmodified' => $row['lastmodified'],
2098
-
2099
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2100
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2101
-			];
2102
-
2103
-			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2104
-				if (!is_null($row[$dbName])) {
2105
-					$subscription[$xmlName] = $row[$dbName];
2106
-				}
2107
-			}
2108
-
2109
-			$subscriptions[] = $subscription;
2110
-		}
2111
-
2112
-		return $subscriptions;
2113
-	}
2114
-
2115
-	/**
2116
-	 * Creates a new subscription for a principal.
2117
-	 *
2118
-	 * If the creation was a success, an id must be returned that can be used to reference
2119
-	 * this subscription in other methods, such as updateSubscription.
2120
-	 *
2121
-	 * @param string $principalUri
2122
-	 * @param string $uri
2123
-	 * @param array $properties
2124
-	 * @return mixed
2125
-	 */
2126
-	public function createSubscription($principalUri, $uri, array $properties) {
2127
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2128
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2129
-		}
2130
-
2131
-		$values = [
2132
-			'principaluri' => $principalUri,
2133
-			'uri' => $uri,
2134
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2135
-			'lastmodified' => time(),
2136
-		];
2137
-
2138
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2139
-
2140
-		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2141
-			if (array_key_exists($xmlName, $properties)) {
2142
-				$values[$dbName] = $properties[$xmlName];
2143
-				if (in_array($dbName, $propertiesBoolean)) {
2144
-					$values[$dbName] = true;
2145
-				}
2146
-			}
2147
-		}
2148
-
2149
-		$valuesToInsert = [];
2150
-
2151
-		$query = $this->db->getQueryBuilder();
2152
-
2153
-		foreach (array_keys($values) as $name) {
2154
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2155
-		}
2156
-
2157
-		$query->insert('calendarsubscriptions')
2158
-			->values($valuesToInsert)
2159
-			->execute();
2160
-
2161
-		$subscriptionId = $query->getLastInsertId();
2162
-
2163
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2164
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2165
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2166
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2167
-			[
2168
-				'subscriptionId' => $subscriptionId,
2169
-				'subscriptionData' => $subscriptionRow,
2170
-			]));
2171
-
2172
-		return $subscriptionId;
2173
-	}
2174
-
2175
-	/**
2176
-	 * Updates a subscription
2177
-	 *
2178
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2179
-	 * To do the actual updates, you must tell this object which properties
2180
-	 * you're going to process with the handle() method.
2181
-	 *
2182
-	 * Calling the handle method is like telling the PropPatch object "I
2183
-	 * promise I can handle updating this property".
2184
-	 *
2185
-	 * Read the PropPatch documentation for more info and examples.
2186
-	 *
2187
-	 * @param mixed $subscriptionId
2188
-	 * @param PropPatch $propPatch
2189
-	 * @return void
2190
-	 */
2191
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2192
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2193
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2194
-
2195
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2196
-			$newValues = [];
2197
-
2198
-			foreach ($mutations as $propertyName => $propertyValue) {
2199
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2200
-					$newValues['source'] = $propertyValue->getHref();
2201
-				} else {
2202
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2203
-					$newValues[$fieldName] = $propertyValue;
2204
-				}
2205
-			}
2206
-
2207
-			$query = $this->db->getQueryBuilder();
2208
-			$query->update('calendarsubscriptions')
2209
-				->set('lastmodified', $query->createNamedParameter(time()));
2210
-			foreach ($newValues as $fieldName => $value) {
2211
-				$query->set($fieldName, $query->createNamedParameter($value));
2212
-			}
2213
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2214
-				->execute();
2215
-
2216
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2217
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2218
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2219
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2220
-				[
2221
-					'subscriptionId' => $subscriptionId,
2222
-					'subscriptionData' => $subscriptionRow,
2223
-					'propertyMutations' => $mutations,
2224
-				]));
2225
-
2226
-			return true;
2227
-		});
2228
-	}
2229
-
2230
-	/**
2231
-	 * Deletes a subscription.
2232
-	 *
2233
-	 * @param mixed $subscriptionId
2234
-	 * @return void
2235
-	 */
2236
-	public function deleteSubscription($subscriptionId) {
2237
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2238
-
2239
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2240
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2241
-			[
2242
-				'subscriptionId' => $subscriptionId,
2243
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2244
-			]));
2245
-
2246
-		$query = $this->db->getQueryBuilder();
2247
-		$query->delete('calendarsubscriptions')
2248
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2249
-			->execute();
2250
-
2251
-		$query = $this->db->getQueryBuilder();
2252
-		$query->delete('calendarobjects')
2253
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2254
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2255
-			->execute();
2256
-
2257
-		$query->delete('calendarchanges')
2258
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2259
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2260
-			->execute();
2261
-
2262
-		$query->delete($this->dbObjectPropertiesTable)
2263
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2264
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2265
-			->execute();
2266
-
2267
-		if ($subscriptionRow) {
2268
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2269
-		}
2270
-	}
2271
-
2272
-	/**
2273
-	 * Returns a single scheduling object for the inbox collection.
2274
-	 *
2275
-	 * The returned array should contain the following elements:
2276
-	 *   * uri - A unique basename for the object. This will be used to
2277
-	 *           construct a full uri.
2278
-	 *   * calendardata - The iCalendar object
2279
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2280
-	 *                    timestamp, or a PHP DateTime object.
2281
-	 *   * etag - A unique token that must change if the object changed.
2282
-	 *   * size - The size of the object, in bytes.
2283
-	 *
2284
-	 * @param string $principalUri
2285
-	 * @param string $objectUri
2286
-	 * @return array
2287
-	 */
2288
-	public function getSchedulingObject($principalUri, $objectUri) {
2289
-		$query = $this->db->getQueryBuilder();
2290
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2291
-			->from('schedulingobjects')
2292
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2293
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2294
-			->execute();
2295
-
2296
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2297
-
2298
-		if (!$row) {
2299
-			return null;
2300
-		}
2301
-
2302
-		return [
2303
-			'uri' => $row['uri'],
2304
-			'calendardata' => $row['calendardata'],
2305
-			'lastmodified' => $row['lastmodified'],
2306
-			'etag' => '"' . $row['etag'] . '"',
2307
-			'size' => (int)$row['size'],
2308
-		];
2309
-	}
2310
-
2311
-	/**
2312
-	 * Returns all scheduling objects for the inbox collection.
2313
-	 *
2314
-	 * These objects should be returned as an array. Every item in the array
2315
-	 * should follow the same structure as returned from getSchedulingObject.
2316
-	 *
2317
-	 * The main difference is that 'calendardata' is optional.
2318
-	 *
2319
-	 * @param string $principalUri
2320
-	 * @return array
2321
-	 */
2322
-	public function getSchedulingObjects($principalUri) {
2323
-		$query = $this->db->getQueryBuilder();
2324
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2325
-				->from('schedulingobjects')
2326
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2327
-				->execute();
2328
-
2329
-		$result = [];
2330
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2331
-			$result[] = [
2332
-				'calendardata' => $row['calendardata'],
2333
-				'uri' => $row['uri'],
2334
-				'lastmodified' => $row['lastmodified'],
2335
-				'etag' => '"' . $row['etag'] . '"',
2336
-				'size' => (int)$row['size'],
2337
-			];
2338
-		}
2339
-
2340
-		return $result;
2341
-	}
2342
-
2343
-	/**
2344
-	 * Deletes a scheduling object from the inbox collection.
2345
-	 *
2346
-	 * @param string $principalUri
2347
-	 * @param string $objectUri
2348
-	 * @return void
2349
-	 */
2350
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2351
-		$query = $this->db->getQueryBuilder();
2352
-		$query->delete('schedulingobjects')
2353
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2354
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2355
-				->execute();
2356
-	}
2357
-
2358
-	/**
2359
-	 * Creates a new scheduling object. This should land in a users' inbox.
2360
-	 *
2361
-	 * @param string $principalUri
2362
-	 * @param string $objectUri
2363
-	 * @param string $objectData
2364
-	 * @return void
2365
-	 */
2366
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2367
-		$query = $this->db->getQueryBuilder();
2368
-		$query->insert('schedulingobjects')
2369
-			->values([
2370
-				'principaluri' => $query->createNamedParameter($principalUri),
2371
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2372
-				'uri' => $query->createNamedParameter($objectUri),
2373
-				'lastmodified' => $query->createNamedParameter(time()),
2374
-				'etag' => $query->createNamedParameter(md5($objectData)),
2375
-				'size' => $query->createNamedParameter(strlen($objectData))
2376
-			])
2377
-			->execute();
2378
-	}
2379
-
2380
-	/**
2381
-	 * Adds a change record to the calendarchanges table.
2382
-	 *
2383
-	 * @param mixed $calendarId
2384
-	 * @param string $objectUri
2385
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2386
-	 * @param int $calendarType
2387
-	 * @return void
2388
-	 */
2389
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2390
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2391
-
2392
-		$query = $this->db->getQueryBuilder();
2393
-		$query->select('synctoken')
2394
-			->from($table)
2395
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2396
-		$result = $query->execute();
2397
-		$syncToken = (int)$result->fetchOne();
2398
-		$result->closeCursor();
2399
-
2400
-		$query = $this->db->getQueryBuilder();
2401
-		$query->insert('calendarchanges')
2402
-			->values([
2403
-				'uri' => $query->createNamedParameter($objectUri),
2404
-				'synctoken' => $query->createNamedParameter($syncToken),
2405
-				'calendarid' => $query->createNamedParameter($calendarId),
2406
-				'operation' => $query->createNamedParameter($operation),
2407
-				'calendartype' => $query->createNamedParameter($calendarType),
2408
-			])
2409
-			->execute();
2410
-
2411
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2412
-		$stmt->execute([
2413
-			$calendarId
2414
-		]);
2415
-	}
2416
-
2417
-	/**
2418
-	 * Parses some information from calendar objects, used for optimized
2419
-	 * calendar-queries.
2420
-	 *
2421
-	 * Returns an array with the following keys:
2422
-	 *   * etag - An md5 checksum of the object without the quotes.
2423
-	 *   * size - Size of the object in bytes
2424
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2425
-	 *   * firstOccurence
2426
-	 *   * lastOccurence
2427
-	 *   * uid - value of the UID property
2428
-	 *
2429
-	 * @param string $calendarData
2430
-	 * @return array
2431
-	 */
2432
-	public function getDenormalizedData($calendarData) {
2433
-		$vObject = Reader::read($calendarData);
2434
-		$vEvents = [];
2435
-		$componentType = null;
2436
-		$component = null;
2437
-		$firstOccurrence = null;
2438
-		$lastOccurrence = null;
2439
-		$uid = null;
2440
-		$classification = self::CLASSIFICATION_PUBLIC;
2441
-		$hasDTSTART = false;
2442
-		foreach ($vObject->getComponents() as $component) {
2443
-			if ($component->name !== 'VTIMEZONE') {
2444
-				// Finding all VEVENTs, and track them
2445
-				if ($component->name === 'VEVENT') {
2446
-					array_push($vEvents, $component);
2447
-					if ($component->DTSTART) {
2448
-						$hasDTSTART = true;
2449
-					}
2450
-				}
2451
-				// Track first component type and uid
2452
-				if ($uid === null) {
2453
-					$componentType = $component->name;
2454
-					$uid = (string)$component->UID;
2455
-				}
2456
-			}
2457
-		}
2458
-		if (!$componentType) {
2459
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2460
-		}
2461
-
2462
-		if ($hasDTSTART) {
2463
-			$component = $vEvents[0];
2464
-
2465
-			// Finding the last occurrence is a bit harder
2466
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
2467
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2468
-				if (isset($component->DTEND)) {
2469
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2470
-				} elseif (isset($component->DURATION)) {
2471
-					$endDate = clone $component->DTSTART->getDateTime();
2472
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2473
-					$lastOccurrence = $endDate->getTimeStamp();
2474
-				} elseif (!$component->DTSTART->hasTime()) {
2475
-					$endDate = clone $component->DTSTART->getDateTime();
2476
-					$endDate->modify('+1 day');
2477
-					$lastOccurrence = $endDate->getTimeStamp();
2478
-				} else {
2479
-					$lastOccurrence = $firstOccurrence;
2480
-				}
2481
-			} else {
2482
-				$it = new EventIterator($vEvents);
2483
-				$maxDate = new DateTime(self::MAX_DATE);
2484
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
2485
-				if ($it->isInfinite()) {
2486
-					$lastOccurrence = $maxDate->getTimestamp();
2487
-				} else {
2488
-					$end = $it->getDtEnd();
2489
-					while ($it->valid() && $end < $maxDate) {
2490
-						$end = $it->getDtEnd();
2491
-						$it->next();
2492
-					}
2493
-					$lastOccurrence = $end->getTimestamp();
2494
-				}
2495
-			}
2496
-		}
2497
-
2498
-		if ($component->CLASS) {
2499
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2500
-			switch ($component->CLASS->getValue()) {
2501
-				case 'PUBLIC':
2502
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2503
-					break;
2504
-				case 'CONFIDENTIAL':
2505
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2506
-					break;
2507
-			}
2508
-		}
2509
-		return [
2510
-			'etag' => md5($calendarData),
2511
-			'size' => strlen($calendarData),
2512
-			'componentType' => $componentType,
2513
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2514
-			'lastOccurence' => $lastOccurrence,
2515
-			'uid' => $uid,
2516
-			'classification' => $classification
2517
-		];
2518
-	}
2519
-
2520
-	/**
2521
-	 * @param $cardData
2522
-	 * @return bool|string
2523
-	 */
2524
-	private function readBlob($cardData) {
2525
-		if (is_resource($cardData)) {
2526
-			return stream_get_contents($cardData);
2527
-		}
2528
-
2529
-		return $cardData;
2530
-	}
2531
-
2532
-	/**
2533
-	 * @param IShareable $shareable
2534
-	 * @param array $add
2535
-	 * @param array $remove
2536
-	 */
2537
-	public function updateShares($shareable, $add, $remove) {
2538
-		$calendarId = $shareable->getResourceId();
2539
-		$calendarRow = $this->getCalendarById($calendarId);
2540
-		$oldShares = $this->getShares($calendarId);
2541
-
2542
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2543
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2544
-			[
2545
-				'calendarId' => $calendarId,
2546
-				'calendarData' => $calendarRow,
2547
-				'shares' => $oldShares,
2548
-				'add' => $add,
2549
-				'remove' => $remove,
2550
-			]));
2551
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2552
-
2553
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2554
-	}
2555
-
2556
-	/**
2557
-	 * @param int $resourceId
2558
-	 * @param int $calendarType
2559
-	 * @return array
2560
-	 */
2561
-	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2562
-		return $this->calendarSharingBackend->getShares($resourceId);
2563
-	}
2564
-
2565
-	/**
2566
-	 * @param boolean $value
2567
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2568
-	 * @return string|null
2569
-	 */
2570
-	public function setPublishStatus($value, $calendar) {
2571
-		$calendarId = $calendar->getResourceId();
2572
-		$calendarData = $this->getCalendarById($calendarId);
2573
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2574
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2575
-			[
2576
-				'calendarId' => $calendarId,
2577
-				'calendarData' => $calendarData,
2578
-				'public' => $value,
2579
-			]));
2580
-
2581
-		$query = $this->db->getQueryBuilder();
2582
-		if ($value) {
2583
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2584
-			$query->insert('dav_shares')
2585
-				->values([
2586
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2587
-					'type' => $query->createNamedParameter('calendar'),
2588
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2589
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2590
-					'publicuri' => $query->createNamedParameter($publicUri)
2591
-				]);
2592
-			$query->execute();
2593
-
2594
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2595
-			return $publicUri;
2596
-		}
2597
-		$query->delete('dav_shares')
2598
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2599
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2600
-		$query->execute();
2601
-
2602
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2603
-		return null;
2604
-	}
2605
-
2606
-	/**
2607
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2608
-	 * @return mixed
2609
-	 */
2610
-	public function getPublishStatus($calendar) {
2611
-		$query = $this->db->getQueryBuilder();
2612
-		$result = $query->select('publicuri')
2613
-			->from('dav_shares')
2614
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2615
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2616
-			->execute();
2617
-
2618
-		$row = $result->fetch();
2619
-		$result->closeCursor();
2620
-		return $row ? reset($row) : false;
2621
-	}
2622
-
2623
-	/**
2624
-	 * @param int $resourceId
2625
-	 * @param array $acl
2626
-	 * @return array
2627
-	 */
2628
-	public function applyShareAcl($resourceId, $acl) {
2629
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2630
-	}
2631
-
2632
-
2633
-
2634
-	/**
2635
-	 * update properties table
2636
-	 *
2637
-	 * @param int $calendarId
2638
-	 * @param string $objectUri
2639
-	 * @param string $calendarData
2640
-	 * @param int $calendarType
2641
-	 */
2642
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2643
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2644
-
2645
-		try {
2646
-			$vCalendar = $this->readCalendarData($calendarData);
2647
-		} catch (\Exception $ex) {
2648
-			return;
2649
-		}
2650
-
2651
-		$this->purgeProperties($calendarId, $objectId);
2652
-
2653
-		$query = $this->db->getQueryBuilder();
2654
-		$query->insert($this->dbObjectPropertiesTable)
2655
-			->values(
2656
-				[
2657
-					'calendarid' => $query->createNamedParameter($calendarId),
2658
-					'calendartype' => $query->createNamedParameter($calendarType),
2659
-					'objectid' => $query->createNamedParameter($objectId),
2660
-					'name' => $query->createParameter('name'),
2661
-					'parameter' => $query->createParameter('parameter'),
2662
-					'value' => $query->createParameter('value'),
2663
-				]
2664
-			);
2665
-
2666
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2667
-		foreach ($vCalendar->getComponents() as $component) {
2668
-			if (!in_array($component->name, $indexComponents)) {
2669
-				continue;
2670
-			}
2671
-
2672
-			foreach ($component->children() as $property) {
2673
-				if (in_array($property->name, self::$indexProperties)) {
2674
-					$value = $property->getValue();
2675
-					// is this a shitty db?
2676
-					if (!$this->db->supports4ByteText()) {
2677
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2678
-					}
2679
-					$value = mb_substr($value, 0, 254);
2680
-
2681
-					$query->setParameter('name', $property->name);
2682
-					$query->setParameter('parameter', null);
2683
-					$query->setParameter('value', $value);
2684
-					$query->execute();
2685
-				}
2686
-
2687
-				if (array_key_exists($property->name, self::$indexParameters)) {
2688
-					$parameters = $property->parameters();
2689
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2690
-
2691
-					foreach ($parameters as $key => $value) {
2692
-						if (in_array($key, $indexedParametersForProperty)) {
2693
-							// is this a shitty db?
2694
-							if ($this->db->supports4ByteText()) {
2695
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2696
-							}
2697
-
2698
-							$query->setParameter('name', $property->name);
2699
-							$query->setParameter('parameter', mb_substr($key, 0, 254));
2700
-							$query->setParameter('value', mb_substr($value, 0, 254));
2701
-							$query->execute();
2702
-						}
2703
-					}
2704
-				}
2705
-			}
2706
-		}
2707
-	}
2708
-
2709
-	/**
2710
-	 * deletes all birthday calendars
2711
-	 */
2712
-	public function deleteAllBirthdayCalendars() {
2713
-		$query = $this->db->getQueryBuilder();
2714
-		$result = $query->select(['id'])->from('calendars')
2715
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2716
-			->execute();
2717
-
2718
-		$ids = $result->fetchAll();
2719
-		foreach ($ids as $id) {
2720
-			$this->deleteCalendar($id['id']);
2721
-		}
2722
-	}
2723
-
2724
-	/**
2725
-	 * @param $subscriptionId
2726
-	 */
2727
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2728
-		$query = $this->db->getQueryBuilder();
2729
-		$query->select('uri')
2730
-			->from('calendarobjects')
2731
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2732
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2733
-		$stmt = $query->execute();
2734
-
2735
-		$uris = [];
2736
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2737
-			$uris[] = $row['uri'];
2738
-		}
2739
-		$stmt->closeCursor();
2740
-
2741
-		$query = $this->db->getQueryBuilder();
2742
-		$query->delete('calendarobjects')
2743
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2744
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2745
-			->execute();
2746
-
2747
-		$query->delete('calendarchanges')
2748
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2749
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2750
-			->execute();
2751
-
2752
-		$query->delete($this->dbObjectPropertiesTable)
2753
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2754
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2755
-			->execute();
2756
-
2757
-		foreach ($uris as $uri) {
2758
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2759
-		}
2760
-	}
2761
-
2762
-	/**
2763
-	 * Move a calendar from one user to another
2764
-	 *
2765
-	 * @param string $uriName
2766
-	 * @param string $uriOrigin
2767
-	 * @param string $uriDestination
2768
-	 * @param string $newUriName (optional) the new uriName
2769
-	 */
2770
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
2771
-		$query = $this->db->getQueryBuilder();
2772
-		$query->update('calendars')
2773
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2774
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
2775
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2776
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2777
-			->execute();
2778
-	}
2779
-
2780
-	/**
2781
-	 * read VCalendar data into a VCalendar object
2782
-	 *
2783
-	 * @param string $objectData
2784
-	 * @return VCalendar
2785
-	 */
2786
-	protected function readCalendarData($objectData) {
2787
-		return Reader::read($objectData);
2788
-	}
2789
-
2790
-	/**
2791
-	 * delete all properties from a given calendar object
2792
-	 *
2793
-	 * @param int $calendarId
2794
-	 * @param int $objectId
2795
-	 */
2796
-	protected function purgeProperties($calendarId, $objectId) {
2797
-		$query = $this->db->getQueryBuilder();
2798
-		$query->delete($this->dbObjectPropertiesTable)
2799
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2800
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2801
-		$query->execute();
2802
-	}
2803
-
2804
-	/**
2805
-	 * get ID from a given calendar object
2806
-	 *
2807
-	 * @param int $calendarId
2808
-	 * @param string $uri
2809
-	 * @param int $calendarType
2810
-	 * @return int
2811
-	 */
2812
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2813
-		$query = $this->db->getQueryBuilder();
2814
-		$query->select('id')
2815
-			->from('calendarobjects')
2816
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2817
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2818
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2819
-
2820
-		$result = $query->execute();
2821
-		$objectIds = $result->fetch();
2822
-		$result->closeCursor();
2823
-
2824
-		if (!isset($objectIds['id'])) {
2825
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2826
-		}
2827
-
2828
-		return (int)$objectIds['id'];
2829
-	}
2830
-
2831
-	/**
2832
-	 * return legacy endpoint principal name to new principal name
2833
-	 *
2834
-	 * @param $principalUri
2835
-	 * @param $toV2
2836
-	 * @return string
2837
-	 */
2838
-	private function convertPrincipal($principalUri, $toV2) {
2839
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2840
-			[, $name] = Uri\split($principalUri);
2841
-			if ($toV2 === true) {
2842
-				return "principals/users/$name";
2843
-			}
2844
-			return "principals/$name";
2845
-		}
2846
-		return $principalUri;
2847
-	}
2848
-
2849
-	/**
2850
-	 * adds information about an owner to the calendar data
2851
-	 *
2852
-	 * @param $calendarInfo
2853
-	 */
2854
-	private function addOwnerPrincipal(&$calendarInfo) {
2855
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2856
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2857
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2858
-			$uri = $calendarInfo[$ownerPrincipalKey];
2859
-		} else {
2860
-			$uri = $calendarInfo['principaluri'];
2861
-		}
2862
-
2863
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2864
-		if (isset($principalInformation['{DAV:}displayname'])) {
2865
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2866
-		}
2867
-	}
99
+    public const CALENDAR_TYPE_CALENDAR = 0;
100
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
101
+
102
+    public const PERSONAL_CALENDAR_URI = 'personal';
103
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
104
+
105
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
106
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
107
+
108
+    /**
109
+     * We need to specify a max date, because we need to stop *somewhere*
110
+     *
111
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
112
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
113
+     * in 2038-01-19 to avoid problems when the date is converted
114
+     * to a unix timestamp.
115
+     */
116
+    public const MAX_DATE = '2038-01-01';
117
+
118
+    public const ACCESS_PUBLIC = 4;
119
+    public const CLASSIFICATION_PUBLIC = 0;
120
+    public const CLASSIFICATION_PRIVATE = 1;
121
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
122
+
123
+    /**
124
+     * List of CalDAV properties, and how they map to database field names
125
+     * Add your own properties by simply adding on to this array.
126
+     *
127
+     * Note that only string-based properties are supported here.
128
+     *
129
+     * @var array
130
+     */
131
+    public $propertyMap = [
132
+        '{DAV:}displayname' => 'displayname',
133
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
134
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
135
+        '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
136
+        '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
137
+    ];
138
+
139
+    /**
140
+     * List of subscription properties, and how they map to database field names.
141
+     *
142
+     * @var array
143
+     */
144
+    public $subscriptionPropertyMap = [
145
+        '{DAV:}displayname' => 'displayname',
146
+        '{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
147
+        '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
148
+        '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
149
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
150
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
151
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
152
+    ];
153
+
154
+    /** @var array properties to index */
155
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
156
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
157
+        'ORGANIZER'];
158
+
159
+    /** @var array parameters to index */
160
+    public static $indexParameters = [
161
+        'ATTENDEE' => ['CN'],
162
+        'ORGANIZER' => ['CN'],
163
+    ];
164
+
165
+    /**
166
+     * @var string[] Map of uid => display name
167
+     */
168
+    protected $userDisplayNames;
169
+
170
+    /** @var IDBConnection */
171
+    private $db;
172
+
173
+    /** @var Backend */
174
+    private $calendarSharingBackend;
175
+
176
+    /** @var Principal */
177
+    private $principalBackend;
178
+
179
+    /** @var IUserManager */
180
+    private $userManager;
181
+
182
+    /** @var ISecureRandom */
183
+    private $random;
184
+
185
+    /** @var ILogger */
186
+    private $logger;
187
+
188
+    /** @var IEventDispatcher */
189
+    private $dispatcher;
190
+
191
+    /** @var EventDispatcherInterface */
192
+    private $legacyDispatcher;
193
+
194
+    /** @var bool */
195
+    private $legacyEndpoint;
196
+
197
+    /** @var string */
198
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
199
+
200
+    /**
201
+     * CalDavBackend constructor.
202
+     *
203
+     * @param IDBConnection $db
204
+     * @param Principal $principalBackend
205
+     * @param IUserManager $userManager
206
+     * @param IGroupManager $groupManager
207
+     * @param ISecureRandom $random
208
+     * @param ILogger $logger
209
+     * @param IEventDispatcher $dispatcher
210
+     * @param EventDispatcherInterface $legacyDispatcher
211
+     * @param bool $legacyEndpoint
212
+     */
213
+    public function __construct(IDBConnection $db,
214
+                                Principal $principalBackend,
215
+                                IUserManager $userManager,
216
+                                IGroupManager $groupManager,
217
+                                ISecureRandom $random,
218
+                                ILogger $logger,
219
+                                IEventDispatcher $dispatcher,
220
+                                EventDispatcherInterface $legacyDispatcher,
221
+                                bool $legacyEndpoint = false) {
222
+        $this->db = $db;
223
+        $this->principalBackend = $principalBackend;
224
+        $this->userManager = $userManager;
225
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
226
+        $this->random = $random;
227
+        $this->logger = $logger;
228
+        $this->dispatcher = $dispatcher;
229
+        $this->legacyDispatcher = $legacyDispatcher;
230
+        $this->legacyEndpoint = $legacyEndpoint;
231
+    }
232
+
233
+    /**
234
+     * Return the number of calendars for a principal
235
+     *
236
+     * By default this excludes the automatically generated birthday calendar
237
+     *
238
+     * @param $principalUri
239
+     * @param bool $excludeBirthday
240
+     * @return int
241
+     */
242
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
243
+        $principalUri = $this->convertPrincipal($principalUri, true);
244
+        $query = $this->db->getQueryBuilder();
245
+        $query->select($query->func()->count('*'))
246
+            ->from('calendars');
247
+
248
+        if ($principalUri === '') {
249
+            $query->where($query->expr()->emptyString('principaluri'));
250
+        } else {
251
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
252
+        }
253
+
254
+        if ($excludeBirthday) {
255
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
256
+        }
257
+
258
+        $result = $query->execute();
259
+        $column = (int)$result->fetchOne();
260
+        $result->closeCursor();
261
+        return $column;
262
+    }
263
+
264
+    /**
265
+     * Returns a list of calendars for a principal.
266
+     *
267
+     * Every project is an array with the following keys:
268
+     *  * id, a unique id that will be used by other functions to modify the
269
+     *    calendar. This can be the same as the uri or a database key.
270
+     *  * uri, which the basename of the uri with which the calendar is
271
+     *    accessed.
272
+     *  * principaluri. The owner of the calendar. Almost always the same as
273
+     *    principalUri passed to this method.
274
+     *
275
+     * Furthermore it can contain webdav properties in clark notation. A very
276
+     * common one is '{DAV:}displayname'.
277
+     *
278
+     * Many clients also require:
279
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
280
+     * For this property, you can just return an instance of
281
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
282
+     *
283
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
284
+     * ACL will automatically be put in read-only mode.
285
+     *
286
+     * @param string $principalUri
287
+     * @return array
288
+     */
289
+    public function getCalendarsForUser($principalUri) {
290
+        $principalUriOriginal = $principalUri;
291
+        $principalUri = $this->convertPrincipal($principalUri, true);
292
+        $fields = array_values($this->propertyMap);
293
+        $fields[] = 'id';
294
+        $fields[] = 'uri';
295
+        $fields[] = 'synctoken';
296
+        $fields[] = 'components';
297
+        $fields[] = 'principaluri';
298
+        $fields[] = 'transparent';
299
+
300
+        // Making fields a comma-delimited list
301
+        $query = $this->db->getQueryBuilder();
302
+        $query->select($fields)
303
+            ->from('calendars')
304
+            ->orderBy('calendarorder', 'ASC');
305
+
306
+        if ($principalUri === '') {
307
+            $query->where($query->expr()->emptyString('principaluri'));
308
+        } else {
309
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
310
+        }
311
+
312
+        $result = $query->execute();
313
+
314
+        $calendars = [];
315
+        while ($row = $result->fetch()) {
316
+            $row['principaluri'] = (string) $row['principaluri'];
317
+            $components = [];
318
+            if ($row['components']) {
319
+                $components = explode(',',$row['components']);
320
+            }
321
+
322
+            $calendar = [
323
+                'id' => $row['id'],
324
+                'uri' => $row['uri'],
325
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
326
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
327
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
328
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
329
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
330
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
331
+            ];
332
+
333
+            foreach ($this->propertyMap as $xmlName => $dbName) {
334
+                $calendar[$xmlName] = $row[$dbName];
335
+            }
336
+
337
+            $this->addOwnerPrincipal($calendar);
338
+
339
+            if (!isset($calendars[$calendar['id']])) {
340
+                $calendars[$calendar['id']] = $calendar;
341
+            }
342
+        }
343
+        $result->closeCursor();
344
+
345
+        // query for shared calendars
346
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
347
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
348
+
349
+        $principals[] = $principalUri;
350
+
351
+        $fields = array_values($this->propertyMap);
352
+        $fields[] = 'a.id';
353
+        $fields[] = 'a.uri';
354
+        $fields[] = 'a.synctoken';
355
+        $fields[] = 'a.components';
356
+        $fields[] = 'a.principaluri';
357
+        $fields[] = 'a.transparent';
358
+        $fields[] = 's.access';
359
+        $query = $this->db->getQueryBuilder();
360
+        $query->select($fields)
361
+            ->from('dav_shares', 's')
362
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
363
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
364
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
365
+            ->setParameter('type', 'calendar')
366
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
367
+
368
+        $result = $query->execute();
369
+
370
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
371
+        while ($row = $result->fetch()) {
372
+            $row['principaluri'] = (string) $row['principaluri'];
373
+            if ($row['principaluri'] === $principalUri) {
374
+                continue;
375
+            }
376
+
377
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
378
+            if (isset($calendars[$row['id']])) {
379
+                if ($readOnly) {
380
+                    // New share can not have more permissions then the old one.
381
+                    continue;
382
+                }
383
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
384
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
385
+                    // Old share is already read-write, no more permissions can be gained
386
+                    continue;
387
+                }
388
+            }
389
+
390
+            [, $name] = Uri\split($row['principaluri']);
391
+            $uri = $row['uri'] . '_shared_by_' . $name;
392
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
393
+            $components = [];
394
+            if ($row['components']) {
395
+                $components = explode(',',$row['components']);
396
+            }
397
+            $calendar = [
398
+                'id' => $row['id'],
399
+                'uri' => $uri,
400
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
401
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
402
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
403
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
404
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
405
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
406
+                $readOnlyPropertyName => $readOnly,
407
+            ];
408
+
409
+            foreach ($this->propertyMap as $xmlName => $dbName) {
410
+                $calendar[$xmlName] = $row[$dbName];
411
+            }
412
+
413
+            $this->addOwnerPrincipal($calendar);
414
+
415
+            $calendars[$calendar['id']] = $calendar;
416
+        }
417
+        $result->closeCursor();
418
+
419
+        return array_values($calendars);
420
+    }
421
+
422
+    /**
423
+     * @param $principalUri
424
+     * @return array
425
+     */
426
+    public function getUsersOwnCalendars($principalUri) {
427
+        $principalUri = $this->convertPrincipal($principalUri, true);
428
+        $fields = array_values($this->propertyMap);
429
+        $fields[] = 'id';
430
+        $fields[] = 'uri';
431
+        $fields[] = 'synctoken';
432
+        $fields[] = 'components';
433
+        $fields[] = 'principaluri';
434
+        $fields[] = 'transparent';
435
+        // Making fields a comma-delimited list
436
+        $query = $this->db->getQueryBuilder();
437
+        $query->select($fields)->from('calendars')
438
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
439
+            ->orderBy('calendarorder', 'ASC');
440
+        $stmt = $query->execute();
441
+        $calendars = [];
442
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
443
+            $row['principaluri'] = (string) $row['principaluri'];
444
+            $components = [];
445
+            if ($row['components']) {
446
+                $components = explode(',',$row['components']);
447
+            }
448
+            $calendar = [
449
+                'id' => $row['id'],
450
+                'uri' => $row['uri'],
451
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
452
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
453
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
454
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
455
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
456
+            ];
457
+            foreach ($this->propertyMap as $xmlName => $dbName) {
458
+                $calendar[$xmlName] = $row[$dbName];
459
+            }
460
+
461
+            $this->addOwnerPrincipal($calendar);
462
+
463
+            if (!isset($calendars[$calendar['id']])) {
464
+                $calendars[$calendar['id']] = $calendar;
465
+            }
466
+        }
467
+        $stmt->closeCursor();
468
+        return array_values($calendars);
469
+    }
470
+
471
+
472
+    /**
473
+     * @param $uid
474
+     * @return string
475
+     */
476
+    private function getUserDisplayName($uid) {
477
+        if (!isset($this->userDisplayNames[$uid])) {
478
+            $user = $this->userManager->get($uid);
479
+
480
+            if ($user instanceof IUser) {
481
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
482
+            } else {
483
+                $this->userDisplayNames[$uid] = $uid;
484
+            }
485
+        }
486
+
487
+        return $this->userDisplayNames[$uid];
488
+    }
489
+
490
+    /**
491
+     * @return array
492
+     */
493
+    public function getPublicCalendars() {
494
+        $fields = array_values($this->propertyMap);
495
+        $fields[] = 'a.id';
496
+        $fields[] = 'a.uri';
497
+        $fields[] = 'a.synctoken';
498
+        $fields[] = 'a.components';
499
+        $fields[] = 'a.principaluri';
500
+        $fields[] = 'a.transparent';
501
+        $fields[] = 's.access';
502
+        $fields[] = 's.publicuri';
503
+        $calendars = [];
504
+        $query = $this->db->getQueryBuilder();
505
+        $result = $query->select($fields)
506
+            ->from('dav_shares', 's')
507
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
508
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
509
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
510
+            ->execute();
511
+
512
+        while ($row = $result->fetch()) {
513
+            $row['principaluri'] = (string) $row['principaluri'];
514
+            [, $name] = Uri\split($row['principaluri']);
515
+            $row['displayname'] = $row['displayname'] . "($name)";
516
+            $components = [];
517
+            if ($row['components']) {
518
+                $components = explode(',',$row['components']);
519
+            }
520
+            $calendar = [
521
+                'id' => $row['id'],
522
+                'uri' => $row['publicuri'],
523
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
524
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
525
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
526
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
527
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
528
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
529
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
530
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
531
+            ];
532
+
533
+            foreach ($this->propertyMap as $xmlName => $dbName) {
534
+                $calendar[$xmlName] = $row[$dbName];
535
+            }
536
+
537
+            $this->addOwnerPrincipal($calendar);
538
+
539
+            if (!isset($calendars[$calendar['id']])) {
540
+                $calendars[$calendar['id']] = $calendar;
541
+            }
542
+        }
543
+        $result->closeCursor();
544
+
545
+        return array_values($calendars);
546
+    }
547
+
548
+    /**
549
+     * @param string $uri
550
+     * @return array
551
+     * @throws NotFound
552
+     */
553
+    public function getPublicCalendar($uri) {
554
+        $fields = array_values($this->propertyMap);
555
+        $fields[] = 'a.id';
556
+        $fields[] = 'a.uri';
557
+        $fields[] = 'a.synctoken';
558
+        $fields[] = 'a.components';
559
+        $fields[] = 'a.principaluri';
560
+        $fields[] = 'a.transparent';
561
+        $fields[] = 's.access';
562
+        $fields[] = 's.publicuri';
563
+        $query = $this->db->getQueryBuilder();
564
+        $result = $query->select($fields)
565
+            ->from('dav_shares', 's')
566
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
567
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
568
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
569
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
570
+            ->execute();
571
+
572
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
573
+
574
+        $result->closeCursor();
575
+
576
+        if ($row === false) {
577
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
578
+        }
579
+
580
+        $row['principaluri'] = (string) $row['principaluri'];
581
+        [, $name] = Uri\split($row['principaluri']);
582
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
583
+        $components = [];
584
+        if ($row['components']) {
585
+            $components = explode(',',$row['components']);
586
+        }
587
+        $calendar = [
588
+            'id' => $row['id'],
589
+            'uri' => $row['publicuri'],
590
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
591
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
592
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
593
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
594
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
595
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
596
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
597
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
598
+        ];
599
+
600
+        foreach ($this->propertyMap as $xmlName => $dbName) {
601
+            $calendar[$xmlName] = $row[$dbName];
602
+        }
603
+
604
+        $this->addOwnerPrincipal($calendar);
605
+
606
+        return $calendar;
607
+    }
608
+
609
+    /**
610
+     * @param string $principal
611
+     * @param string $uri
612
+     * @return array|null
613
+     */
614
+    public function getCalendarByUri($principal, $uri) {
615
+        $fields = array_values($this->propertyMap);
616
+        $fields[] = 'id';
617
+        $fields[] = 'uri';
618
+        $fields[] = 'synctoken';
619
+        $fields[] = 'components';
620
+        $fields[] = 'principaluri';
621
+        $fields[] = 'transparent';
622
+
623
+        // Making fields a comma-delimited list
624
+        $query = $this->db->getQueryBuilder();
625
+        $query->select($fields)->from('calendars')
626
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
627
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
628
+            ->setMaxResults(1);
629
+        $stmt = $query->execute();
630
+
631
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
632
+        $stmt->closeCursor();
633
+        if ($row === false) {
634
+            return null;
635
+        }
636
+
637
+        $row['principaluri'] = (string) $row['principaluri'];
638
+        $components = [];
639
+        if ($row['components']) {
640
+            $components = explode(',',$row['components']);
641
+        }
642
+
643
+        $calendar = [
644
+            'id' => $row['id'],
645
+            'uri' => $row['uri'],
646
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
647
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
648
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
649
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
650
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
651
+        ];
652
+
653
+        foreach ($this->propertyMap as $xmlName => $dbName) {
654
+            $calendar[$xmlName] = $row[$dbName];
655
+        }
656
+
657
+        $this->addOwnerPrincipal($calendar);
658
+
659
+        return $calendar;
660
+    }
661
+
662
+    /**
663
+     * @param $calendarId
664
+     * @return array|null
665
+     */
666
+    public function getCalendarById($calendarId) {
667
+        $fields = array_values($this->propertyMap);
668
+        $fields[] = 'id';
669
+        $fields[] = 'uri';
670
+        $fields[] = 'synctoken';
671
+        $fields[] = 'components';
672
+        $fields[] = 'principaluri';
673
+        $fields[] = 'transparent';
674
+
675
+        // Making fields a comma-delimited list
676
+        $query = $this->db->getQueryBuilder();
677
+        $query->select($fields)->from('calendars')
678
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
679
+            ->setMaxResults(1);
680
+        $stmt = $query->execute();
681
+
682
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
683
+        $stmt->closeCursor();
684
+        if ($row === false) {
685
+            return null;
686
+        }
687
+
688
+        $row['principaluri'] = (string) $row['principaluri'];
689
+        $components = [];
690
+        if ($row['components']) {
691
+            $components = explode(',',$row['components']);
692
+        }
693
+
694
+        $calendar = [
695
+            'id' => $row['id'],
696
+            'uri' => $row['uri'],
697
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
698
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
699
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
700
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
701
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
702
+        ];
703
+
704
+        foreach ($this->propertyMap as $xmlName => $dbName) {
705
+            $calendar[$xmlName] = $row[$dbName];
706
+        }
707
+
708
+        $this->addOwnerPrincipal($calendar);
709
+
710
+        return $calendar;
711
+    }
712
+
713
+    /**
714
+     * @param $subscriptionId
715
+     */
716
+    public function getSubscriptionById($subscriptionId) {
717
+        $fields = array_values($this->subscriptionPropertyMap);
718
+        $fields[] = 'id';
719
+        $fields[] = 'uri';
720
+        $fields[] = 'source';
721
+        $fields[] = 'synctoken';
722
+        $fields[] = 'principaluri';
723
+        $fields[] = 'lastmodified';
724
+
725
+        $query = $this->db->getQueryBuilder();
726
+        $query->select($fields)
727
+            ->from('calendarsubscriptions')
728
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
729
+            ->orderBy('calendarorder', 'asc');
730
+        $stmt = $query->execute();
731
+
732
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
733
+        $stmt->closeCursor();
734
+        if ($row === false) {
735
+            return null;
736
+        }
737
+
738
+        $row['principaluri'] = (string) $row['principaluri'];
739
+        $subscription = [
740
+            'id' => $row['id'],
741
+            'uri' => $row['uri'],
742
+            'principaluri' => $row['principaluri'],
743
+            'source' => $row['source'],
744
+            'lastmodified' => $row['lastmodified'],
745
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
746
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
747
+        ];
748
+
749
+        foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
750
+            if (!is_null($row[$dbName])) {
751
+                $subscription[$xmlName] = $row[$dbName];
752
+            }
753
+        }
754
+
755
+        return $subscription;
756
+    }
757
+
758
+    /**
759
+     * Creates a new calendar for a principal.
760
+     *
761
+     * If the creation was a success, an id must be returned that can be used to reference
762
+     * this calendar in other methods, such as updateCalendar.
763
+     *
764
+     * @param string $principalUri
765
+     * @param string $calendarUri
766
+     * @param array $properties
767
+     * @return int
768
+     */
769
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
770
+        $values = [
771
+            'principaluri' => $this->convertPrincipal($principalUri, true),
772
+            'uri' => $calendarUri,
773
+            'synctoken' => 1,
774
+            'transparent' => 0,
775
+            'components' => 'VEVENT,VTODO',
776
+            'displayname' => $calendarUri
777
+        ];
778
+
779
+        // Default value
780
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
781
+        if (isset($properties[$sccs])) {
782
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
783
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
784
+            }
785
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
786
+        } elseif (isset($properties['components'])) {
787
+            // Allow to provide components internally without having
788
+            // to create a SupportedCalendarComponentSet object
789
+            $values['components'] = $properties['components'];
790
+        }
791
+
792
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
793
+        if (isset($properties[$transp])) {
794
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
795
+        }
796
+
797
+        foreach ($this->propertyMap as $xmlName => $dbName) {
798
+            if (isset($properties[$xmlName])) {
799
+                $values[$dbName] = $properties[$xmlName];
800
+            }
801
+        }
802
+
803
+        $query = $this->db->getQueryBuilder();
804
+        $query->insert('calendars');
805
+        foreach ($values as $column => $value) {
806
+            $query->setValue($column, $query->createNamedParameter($value));
807
+        }
808
+        $query->execute();
809
+        $calendarId = $query->getLastInsertId();
810
+
811
+        $calendarData = $this->getCalendarById($calendarId);
812
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
813
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
814
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
815
+            [
816
+                'calendarId' => $calendarId,
817
+                'calendarData' => $calendarData,
818
+            ]));
819
+
820
+        return $calendarId;
821
+    }
822
+
823
+    /**
824
+     * Updates properties for a calendar.
825
+     *
826
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
827
+     * To do the actual updates, you must tell this object which properties
828
+     * you're going to process with the handle() method.
829
+     *
830
+     * Calling the handle method is like telling the PropPatch object "I
831
+     * promise I can handle updating this property".
832
+     *
833
+     * Read the PropPatch documentation for more info and examples.
834
+     *
835
+     * @param mixed $calendarId
836
+     * @param PropPatch $propPatch
837
+     * @return void
838
+     */
839
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
840
+        $supportedProperties = array_keys($this->propertyMap);
841
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
842
+
843
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
844
+            $newValues = [];
845
+            foreach ($mutations as $propertyName => $propertyValue) {
846
+                switch ($propertyName) {
847
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
848
+                        $fieldName = 'transparent';
849
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
850
+                        break;
851
+                    default:
852
+                        $fieldName = $this->propertyMap[$propertyName];
853
+                        $newValues[$fieldName] = $propertyValue;
854
+                        break;
855
+                }
856
+            }
857
+            $query = $this->db->getQueryBuilder();
858
+            $query->update('calendars');
859
+            foreach ($newValues as $fieldName => $value) {
860
+                $query->set($fieldName, $query->createNamedParameter($value));
861
+            }
862
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
863
+            $query->execute();
864
+
865
+            $this->addChange($calendarId, "", 2);
866
+
867
+            $calendarData = $this->getCalendarById($calendarId);
868
+            $shares = $this->getShares($calendarId);
869
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
870
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
871
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
872
+                [
873
+                    'calendarId' => $calendarId,
874
+                    'calendarData' => $calendarData,
875
+                    'shares' => $shares,
876
+                    'propertyMutations' => $mutations,
877
+                ]));
878
+
879
+            return true;
880
+        });
881
+    }
882
+
883
+    /**
884
+     * Delete a calendar and all it's objects
885
+     *
886
+     * @param mixed $calendarId
887
+     * @return void
888
+     */
889
+    public function deleteCalendar($calendarId) {
890
+        $calendarData = $this->getCalendarById($calendarId);
891
+        $shares = $this->getShares($calendarId);
892
+
893
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
894
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
895
+            [
896
+                'calendarId' => $calendarId,
897
+                'calendarData' => $calendarData,
898
+                'shares' => $shares,
899
+            ]));
900
+
901
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
902
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
903
+
904
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
905
+        $stmt->execute([$calendarId]);
906
+
907
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
908
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
909
+
910
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
911
+
912
+        $query = $this->db->getQueryBuilder();
913
+        $query->delete($this->dbObjectPropertiesTable)
914
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
915
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
916
+            ->execute();
917
+
918
+        if ($calendarData) {
919
+            $this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
920
+        }
921
+    }
922
+
923
+    /**
924
+     * Delete all of an user's shares
925
+     *
926
+     * @param string $principaluri
927
+     * @return void
928
+     */
929
+    public function deleteAllSharesByUser($principaluri) {
930
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
931
+    }
932
+
933
+    /**
934
+     * Returns all calendar objects within a calendar.
935
+     *
936
+     * Every item contains an array with the following keys:
937
+     *   * calendardata - The iCalendar-compatible calendar data
938
+     *   * uri - a unique key which will be used to construct the uri. This can
939
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
940
+     *     good idea. This is only the basename, or filename, not the full
941
+     *     path.
942
+     *   * lastmodified - a timestamp of the last modification time
943
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
944
+     *   '"abcdef"')
945
+     *   * size - The size of the calendar objects, in bytes.
946
+     *   * component - optional, a string containing the type of object, such
947
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
948
+     *     the Content-Type header.
949
+     *
950
+     * Note that the etag is optional, but it's highly encouraged to return for
951
+     * speed reasons.
952
+     *
953
+     * The calendardata is also optional. If it's not returned
954
+     * 'getCalendarObject' will be called later, which *is* expected to return
955
+     * calendardata.
956
+     *
957
+     * If neither etag or size are specified, the calendardata will be
958
+     * used/fetched to determine these numbers. If both are specified the
959
+     * amount of times this is needed is reduced by a great degree.
960
+     *
961
+     * @param mixed $calendarId
962
+     * @param int $calendarType
963
+     * @return array
964
+     */
965
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
966
+        $query = $this->db->getQueryBuilder();
967
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
968
+            ->from('calendarobjects')
969
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
970
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
971
+        $stmt = $query->execute();
972
+
973
+        $result = [];
974
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
975
+            $result[] = [
976
+                'id' => $row['id'],
977
+                'uri' => $row['uri'],
978
+                'lastmodified' => $row['lastmodified'],
979
+                'etag' => '"' . $row['etag'] . '"',
980
+                'calendarid' => $row['calendarid'],
981
+                'size' => (int)$row['size'],
982
+                'component' => strtolower($row['componenttype']),
983
+                'classification' => (int)$row['classification']
984
+            ];
985
+        }
986
+        $stmt->closeCursor();
987
+
988
+        return $result;
989
+    }
990
+
991
+    /**
992
+     * Returns information from a single calendar object, based on it's object
993
+     * uri.
994
+     *
995
+     * The object uri is only the basename, or filename and not a full path.
996
+     *
997
+     * The returned array must have the same keys as getCalendarObjects. The
998
+     * 'calendardata' object is required here though, while it's not required
999
+     * for getCalendarObjects.
1000
+     *
1001
+     * This method must return null if the object did not exist.
1002
+     *
1003
+     * @param mixed $calendarId
1004
+     * @param string $objectUri
1005
+     * @param int $calendarType
1006
+     * @return array|null
1007
+     */
1008
+    public function getCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1009
+        $query = $this->db->getQueryBuilder();
1010
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1011
+            ->from('calendarobjects')
1012
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1013
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1014
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1015
+        $stmt = $query->execute();
1016
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1017
+        $stmt->closeCursor();
1018
+
1019
+        if (!$row) {
1020
+            return null;
1021
+        }
1022
+
1023
+        return [
1024
+            'id' => $row['id'],
1025
+            'uri' => $row['uri'],
1026
+            'lastmodified' => $row['lastmodified'],
1027
+            'etag' => '"' . $row['etag'] . '"',
1028
+            'calendarid' => $row['calendarid'],
1029
+            'size' => (int)$row['size'],
1030
+            'calendardata' => $this->readBlob($row['calendardata']),
1031
+            'component' => strtolower($row['componenttype']),
1032
+            'classification' => (int)$row['classification']
1033
+        ];
1034
+    }
1035
+
1036
+    /**
1037
+     * Returns a list of calendar objects.
1038
+     *
1039
+     * This method should work identical to getCalendarObject, but instead
1040
+     * return all the calendar objects in the list as an array.
1041
+     *
1042
+     * If the backend supports this, it may allow for some speed-ups.
1043
+     *
1044
+     * @param mixed $calendarId
1045
+     * @param string[] $uris
1046
+     * @param int $calendarType
1047
+     * @return array
1048
+     */
1049
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1050
+        if (empty($uris)) {
1051
+            return [];
1052
+        }
1053
+
1054
+        $chunks = array_chunk($uris, 100);
1055
+        $objects = [];
1056
+
1057
+        $query = $this->db->getQueryBuilder();
1058
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1059
+            ->from('calendarobjects')
1060
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1061
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1062
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1063
+
1064
+        foreach ($chunks as $uris) {
1065
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1066
+            $result = $query->execute();
1067
+
1068
+            while ($row = $result->fetch()) {
1069
+                $objects[] = [
1070
+                    'id' => $row['id'],
1071
+                    'uri' => $row['uri'],
1072
+                    'lastmodified' => $row['lastmodified'],
1073
+                    'etag' => '"' . $row['etag'] . '"',
1074
+                    'calendarid' => $row['calendarid'],
1075
+                    'size' => (int)$row['size'],
1076
+                    'calendardata' => $this->readBlob($row['calendardata']),
1077
+                    'component' => strtolower($row['componenttype']),
1078
+                    'classification' => (int)$row['classification']
1079
+                ];
1080
+            }
1081
+            $result->closeCursor();
1082
+        }
1083
+
1084
+        return $objects;
1085
+    }
1086
+
1087
+    /**
1088
+     * Creates a new calendar object.
1089
+     *
1090
+     * The object uri is only the basename, or filename and not a full path.
1091
+     *
1092
+     * It is possible return an etag from this function, which will be used in
1093
+     * the response to this PUT request. Note that the ETag must be surrounded
1094
+     * by double-quotes.
1095
+     *
1096
+     * However, you should only really return this ETag if you don't mangle the
1097
+     * calendar-data. If the result of a subsequent GET to this object is not
1098
+     * the exact same as this request body, you should omit the ETag.
1099
+     *
1100
+     * @param mixed $calendarId
1101
+     * @param string $objectUri
1102
+     * @param string $calendarData
1103
+     * @param int $calendarType
1104
+     * @return string
1105
+     */
1106
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1107
+        $extraData = $this->getDenormalizedData($calendarData);
1108
+
1109
+        $q = $this->db->getQueryBuilder();
1110
+        $q->select($q->func()->count('*'))
1111
+            ->from('calendarobjects')
1112
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1113
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1114
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1115
+
1116
+        $result = $q->execute();
1117
+        $count = (int) $result->fetchOne();
1118
+        $result->closeCursor();
1119
+
1120
+        if ($count !== 0) {
1121
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1122
+        }
1123
+
1124
+        $query = $this->db->getQueryBuilder();
1125
+        $query->insert('calendarobjects')
1126
+            ->values([
1127
+                'calendarid' => $query->createNamedParameter($calendarId),
1128
+                'uri' => $query->createNamedParameter($objectUri),
1129
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1130
+                'lastmodified' => $query->createNamedParameter(time()),
1131
+                'etag' => $query->createNamedParameter($extraData['etag']),
1132
+                'size' => $query->createNamedParameter($extraData['size']),
1133
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1134
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1135
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1136
+                'classification' => $query->createNamedParameter($extraData['classification']),
1137
+                'uid' => $query->createNamedParameter($extraData['uid']),
1138
+                'calendartype' => $query->createNamedParameter($calendarType),
1139
+            ])
1140
+            ->execute();
1141
+
1142
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1143
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1144
+
1145
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1146
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1147
+            $calendarRow = $this->getCalendarById($calendarId);
1148
+            $shares = $this->getShares($calendarId);
1149
+
1150
+            $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1151
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1152
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1153
+                [
1154
+                    'calendarId' => $calendarId,
1155
+                    'calendarData' => $calendarRow,
1156
+                    'shares' => $shares,
1157
+                    'objectData' => $objectRow,
1158
+                ]
1159
+            ));
1160
+        } else {
1161
+            $subscriptionRow = $this->getSubscriptionById($calendarId);
1162
+
1163
+            $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1164
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1165
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1166
+                [
1167
+                    'subscriptionId' => $calendarId,
1168
+                    'calendarData' => $subscriptionRow,
1169
+                    'shares' => [],
1170
+                    'objectData' => $objectRow,
1171
+                ]
1172
+            ));
1173
+        }
1174
+
1175
+        return '"' . $extraData['etag'] . '"';
1176
+    }
1177
+
1178
+    /**
1179
+     * Updates an existing calendarobject, based on it's uri.
1180
+     *
1181
+     * The object uri is only the basename, or filename and not a full path.
1182
+     *
1183
+     * It is possible return an etag from this function, which will be used in
1184
+     * the response to this PUT request. Note that the ETag must be surrounded
1185
+     * by double-quotes.
1186
+     *
1187
+     * However, you should only really return this ETag if you don't mangle the
1188
+     * calendar-data. If the result of a subsequent GET to this object is not
1189
+     * the exact same as this request body, you should omit the ETag.
1190
+     *
1191
+     * @param mixed $calendarId
1192
+     * @param string $objectUri
1193
+     * @param string $calendarData
1194
+     * @param int $calendarType
1195
+     * @return string
1196
+     */
1197
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1198
+        $extraData = $this->getDenormalizedData($calendarData);
1199
+        $query = $this->db->getQueryBuilder();
1200
+        $query->update('calendarobjects')
1201
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1202
+                ->set('lastmodified', $query->createNamedParameter(time()))
1203
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1204
+                ->set('size', $query->createNamedParameter($extraData['size']))
1205
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1206
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1207
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1208
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1209
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1210
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1211
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1212
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1213
+            ->execute();
1214
+
1215
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1216
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1217
+
1218
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1219
+        if (is_array($objectRow)) {
1220
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1221
+                $calendarRow = $this->getCalendarById($calendarId);
1222
+                $shares = $this->getShares($calendarId);
1223
+
1224
+                $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1225
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1226
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1227
+                    [
1228
+                        'calendarId' => $calendarId,
1229
+                        'calendarData' => $calendarRow,
1230
+                        'shares' => $shares,
1231
+                        'objectData' => $objectRow,
1232
+                    ]
1233
+                ));
1234
+            } else {
1235
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1236
+
1237
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1238
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1239
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1240
+                    [
1241
+                        'subscriptionId' => $calendarId,
1242
+                        'calendarData' => $subscriptionRow,
1243
+                        'shares' => [],
1244
+                        'objectData' => $objectRow,
1245
+                    ]
1246
+                ));
1247
+            }
1248
+        }
1249
+
1250
+        return '"' . $extraData['etag'] . '"';
1251
+    }
1252
+
1253
+    /**
1254
+     * @param int $calendarObjectId
1255
+     * @param int $classification
1256
+     */
1257
+    public function setClassification($calendarObjectId, $classification) {
1258
+        if (!in_array($classification, [
1259
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1260
+        ])) {
1261
+            throw new \InvalidArgumentException();
1262
+        }
1263
+        $query = $this->db->getQueryBuilder();
1264
+        $query->update('calendarobjects')
1265
+            ->set('classification', $query->createNamedParameter($classification))
1266
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1267
+            ->execute();
1268
+    }
1269
+
1270
+    /**
1271
+     * Deletes an existing calendar object.
1272
+     *
1273
+     * The object uri is only the basename, or filename and not a full path.
1274
+     *
1275
+     * @param mixed $calendarId
1276
+     * @param string $objectUri
1277
+     * @param int $calendarType
1278
+     * @return void
1279
+     */
1280
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1281
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1282
+        if (is_array($data)) {
1283
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1284
+                $calendarRow = $this->getCalendarById($calendarId);
1285
+                $shares = $this->getShares($calendarId);
1286
+
1287
+                $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1288
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1289
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1290
+                    [
1291
+                        'calendarId' => $calendarId,
1292
+                        'calendarData' => $calendarRow,
1293
+                        'shares' => $shares,
1294
+                        'objectData' => $data,
1295
+                    ]
1296
+                ));
1297
+            } else {
1298
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1299
+
1300
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1301
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1302
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1303
+                    [
1304
+                        'subscriptionId' => $calendarId,
1305
+                        'calendarData' => $subscriptionRow,
1306
+                        'shares' => [],
1307
+                        'objectData' => $data,
1308
+                    ]
1309
+                ));
1310
+            }
1311
+        }
1312
+
1313
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1314
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1315
+
1316
+        if (is_array($data)) {
1317
+            $this->purgeProperties($calendarId, $data['id'], $calendarType);
1318
+        }
1319
+
1320
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1321
+    }
1322
+
1323
+    /**
1324
+     * Performs a calendar-query on the contents of this calendar.
1325
+     *
1326
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1327
+     * calendar-query it is possible for a client to request a specific set of
1328
+     * object, based on contents of iCalendar properties, date-ranges and
1329
+     * iCalendar component types (VTODO, VEVENT).
1330
+     *
1331
+     * This method should just return a list of (relative) urls that match this
1332
+     * query.
1333
+     *
1334
+     * The list of filters are specified as an array. The exact array is
1335
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1336
+     *
1337
+     * Note that it is extremely likely that getCalendarObject for every path
1338
+     * returned from this method will be called almost immediately after. You
1339
+     * may want to anticipate this to speed up these requests.
1340
+     *
1341
+     * This method provides a default implementation, which parses *all* the
1342
+     * iCalendar objects in the specified calendar.
1343
+     *
1344
+     * This default may well be good enough for personal use, and calendars
1345
+     * that aren't very large. But if you anticipate high usage, big calendars
1346
+     * or high loads, you are strongly advised to optimize certain paths.
1347
+     *
1348
+     * The best way to do so is override this method and to optimize
1349
+     * specifically for 'common filters'.
1350
+     *
1351
+     * Requests that are extremely common are:
1352
+     *   * requests for just VEVENTS
1353
+     *   * requests for just VTODO
1354
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1355
+     *
1356
+     * ..and combinations of these requests. It may not be worth it to try to
1357
+     * handle every possible situation and just rely on the (relatively
1358
+     * easy to use) CalendarQueryValidator to handle the rest.
1359
+     *
1360
+     * Note that especially time-range-filters may be difficult to parse. A
1361
+     * time-range filter specified on a VEVENT must for instance also handle
1362
+     * recurrence rules correctly.
1363
+     * A good example of how to interprete all these filters can also simply
1364
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1365
+     * as possible, so it gives you a good idea on what type of stuff you need
1366
+     * to think of.
1367
+     *
1368
+     * @param mixed $calendarId
1369
+     * @param array $filters
1370
+     * @param int $calendarType
1371
+     * @return array
1372
+     */
1373
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1374
+        $componentType = null;
1375
+        $requirePostFilter = true;
1376
+        $timeRange = null;
1377
+
1378
+        // if no filters were specified, we don't need to filter after a query
1379
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1380
+            $requirePostFilter = false;
1381
+        }
1382
+
1383
+        // Figuring out if there's a component filter
1384
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1385
+            $componentType = $filters['comp-filters'][0]['name'];
1386
+
1387
+            // Checking if we need post-filters
1388
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1389
+                $requirePostFilter = false;
1390
+            }
1391
+            // There was a time-range filter
1392
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1393
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1394
+
1395
+                // If start time OR the end time is not specified, we can do a
1396
+                // 100% accurate mysql query.
1397
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1398
+                    $requirePostFilter = false;
1399
+                }
1400
+            }
1401
+        }
1402
+        $columns = ['uri'];
1403
+        if ($requirePostFilter) {
1404
+            $columns = ['uri', 'calendardata'];
1405
+        }
1406
+        $query = $this->db->getQueryBuilder();
1407
+        $query->select($columns)
1408
+            ->from('calendarobjects')
1409
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1410
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1411
+
1412
+        if ($componentType) {
1413
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1414
+        }
1415
+
1416
+        if ($timeRange && $timeRange['start']) {
1417
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1418
+        }
1419
+        if ($timeRange && $timeRange['end']) {
1420
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1421
+        }
1422
+
1423
+        $stmt = $query->execute();
1424
+
1425
+        $result = [];
1426
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1427
+            if ($requirePostFilter) {
1428
+                // validateFilterForObject will parse the calendar data
1429
+                // catch parsing errors
1430
+                try {
1431
+                    $matches = $this->validateFilterForObject($row, $filters);
1432
+                } catch (ParseException $ex) {
1433
+                    $this->logger->logException($ex, [
1434
+                        'app' => 'dav',
1435
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1436
+                    ]);
1437
+                    continue;
1438
+                } catch (InvalidDataException $ex) {
1439
+                    $this->logger->logException($ex, [
1440
+                        'app' => 'dav',
1441
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1442
+                    ]);
1443
+                    continue;
1444
+                }
1445
+
1446
+                if (!$matches) {
1447
+                    continue;
1448
+                }
1449
+            }
1450
+            $result[] = $row['uri'];
1451
+        }
1452
+
1453
+        return $result;
1454
+    }
1455
+
1456
+    /**
1457
+     * custom Nextcloud search extension for CalDAV
1458
+     *
1459
+     * TODO - this should optionally cover cached calendar objects as well
1460
+     *
1461
+     * @param string $principalUri
1462
+     * @param array $filters
1463
+     * @param integer|null $limit
1464
+     * @param integer|null $offset
1465
+     * @return array
1466
+     */
1467
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1468
+        $calendars = $this->getCalendarsForUser($principalUri);
1469
+        $ownCalendars = [];
1470
+        $sharedCalendars = [];
1471
+
1472
+        $uriMapper = [];
1473
+
1474
+        foreach ($calendars as $calendar) {
1475
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1476
+                $ownCalendars[] = $calendar['id'];
1477
+            } else {
1478
+                $sharedCalendars[] = $calendar['id'];
1479
+            }
1480
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1481
+        }
1482
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1483
+            return [];
1484
+        }
1485
+
1486
+        $query = $this->db->getQueryBuilder();
1487
+        // Calendar id expressions
1488
+        $calendarExpressions = [];
1489
+        foreach ($ownCalendars as $id) {
1490
+            $calendarExpressions[] = $query->expr()->andX(
1491
+                $query->expr()->eq('c.calendarid',
1492
+                    $query->createNamedParameter($id)),
1493
+                $query->expr()->eq('c.calendartype',
1494
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1495
+        }
1496
+        foreach ($sharedCalendars as $id) {
1497
+            $calendarExpressions[] = $query->expr()->andX(
1498
+                $query->expr()->eq('c.calendarid',
1499
+                    $query->createNamedParameter($id)),
1500
+                $query->expr()->eq('c.classification',
1501
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1502
+                $query->expr()->eq('c.calendartype',
1503
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1504
+        }
1505
+
1506
+        if (count($calendarExpressions) === 1) {
1507
+            $calExpr = $calendarExpressions[0];
1508
+        } else {
1509
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1510
+        }
1511
+
1512
+        // Component expressions
1513
+        $compExpressions = [];
1514
+        foreach ($filters['comps'] as $comp) {
1515
+            $compExpressions[] = $query->expr()
1516
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1517
+        }
1518
+
1519
+        if (count($compExpressions) === 1) {
1520
+            $compExpr = $compExpressions[0];
1521
+        } else {
1522
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1523
+        }
1524
+
1525
+        if (!isset($filters['props'])) {
1526
+            $filters['props'] = [];
1527
+        }
1528
+        if (!isset($filters['params'])) {
1529
+            $filters['params'] = [];
1530
+        }
1531
+
1532
+        $propParamExpressions = [];
1533
+        foreach ($filters['props'] as $prop) {
1534
+            $propParamExpressions[] = $query->expr()->andX(
1535
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1536
+                $query->expr()->isNull('i.parameter')
1537
+            );
1538
+        }
1539
+        foreach ($filters['params'] as $param) {
1540
+            $propParamExpressions[] = $query->expr()->andX(
1541
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1542
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1543
+            );
1544
+        }
1545
+
1546
+        if (count($propParamExpressions) === 1) {
1547
+            $propParamExpr = $propParamExpressions[0];
1548
+        } else {
1549
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1550
+        }
1551
+
1552
+        $query->select(['c.calendarid', 'c.uri'])
1553
+            ->from($this->dbObjectPropertiesTable, 'i')
1554
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1555
+            ->where($calExpr)
1556
+            ->andWhere($compExpr)
1557
+            ->andWhere($propParamExpr)
1558
+            ->andWhere($query->expr()->iLike('i.value',
1559
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1560
+
1561
+        if ($offset) {
1562
+            $query->setFirstResult($offset);
1563
+        }
1564
+        if ($limit) {
1565
+            $query->setMaxResults($limit);
1566
+        }
1567
+
1568
+        $stmt = $query->execute();
1569
+
1570
+        $result = [];
1571
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1572
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1573
+            if (!in_array($path, $result)) {
1574
+                $result[] = $path;
1575
+            }
1576
+        }
1577
+
1578
+        return $result;
1579
+    }
1580
+
1581
+    /**
1582
+     * used for Nextcloud's calendar API
1583
+     *
1584
+     * @param array $calendarInfo
1585
+     * @param string $pattern
1586
+     * @param array $searchProperties
1587
+     * @param array $options
1588
+     * @param integer|null $limit
1589
+     * @param integer|null $offset
1590
+     *
1591
+     * @return array
1592
+     */
1593
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1594
+                            array $options, $limit, $offset) {
1595
+        $outerQuery = $this->db->getQueryBuilder();
1596
+        $innerQuery = $this->db->getQueryBuilder();
1597
+
1598
+        $innerQuery->selectDistinct('op.objectid')
1599
+            ->from($this->dbObjectPropertiesTable, 'op')
1600
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1601
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1602
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1603
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1604
+
1605
+        // only return public items for shared calendars for now
1606
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1607
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1608
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1609
+        }
1610
+
1611
+        $or = $innerQuery->expr()->orX();
1612
+        foreach ($searchProperties as $searchProperty) {
1613
+            $or->add($innerQuery->expr()->eq('op.name',
1614
+                $outerQuery->createNamedParameter($searchProperty)));
1615
+        }
1616
+        $innerQuery->andWhere($or);
1617
+
1618
+        if ($pattern !== '') {
1619
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1620
+                $outerQuery->createNamedParameter('%' .
1621
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1622
+        }
1623
+
1624
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1625
+            ->from('calendarobjects', 'c');
1626
+
1627
+        if (isset($options['timerange'])) {
1628
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1629
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1630
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1631
+            }
1632
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1633
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1634
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1635
+            }
1636
+        }
1637
+
1638
+        if (isset($options['types'])) {
1639
+            $or = $outerQuery->expr()->orX();
1640
+            foreach ($options['types'] as $type) {
1641
+                $or->add($outerQuery->expr()->eq('componenttype',
1642
+                    $outerQuery->createNamedParameter($type)));
1643
+            }
1644
+            $outerQuery->andWhere($or);
1645
+        }
1646
+
1647
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1648
+            $outerQuery->createFunction($innerQuery->getSQL())));
1649
+
1650
+        if ($offset) {
1651
+            $outerQuery->setFirstResult($offset);
1652
+        }
1653
+        if ($limit) {
1654
+            $outerQuery->setMaxResults($limit);
1655
+        }
1656
+
1657
+        $result = $outerQuery->execute();
1658
+        $calendarObjects = $result->fetchAll();
1659
+
1660
+        return array_map(function ($o) {
1661
+            $calendarData = Reader::read($o['calendardata']);
1662
+            $comps = $calendarData->getComponents();
1663
+            $objects = [];
1664
+            $timezones = [];
1665
+            foreach ($comps as $comp) {
1666
+                if ($comp instanceof VTimeZone) {
1667
+                    $timezones[] = $comp;
1668
+                } else {
1669
+                    $objects[] = $comp;
1670
+                }
1671
+            }
1672
+
1673
+            return [
1674
+                'id' => $o['id'],
1675
+                'type' => $o['componenttype'],
1676
+                'uid' => $o['uid'],
1677
+                'uri' => $o['uri'],
1678
+                'objects' => array_map(function ($c) {
1679
+                    return $this->transformSearchData($c);
1680
+                }, $objects),
1681
+                'timezones' => array_map(function ($c) {
1682
+                    return $this->transformSearchData($c);
1683
+                }, $timezones),
1684
+            ];
1685
+        }, $calendarObjects);
1686
+    }
1687
+
1688
+    /**
1689
+     * @param Component $comp
1690
+     * @return array
1691
+     */
1692
+    private function transformSearchData(Component $comp) {
1693
+        $data = [];
1694
+        /** @var Component[] $subComponents */
1695
+        $subComponents = $comp->getComponents();
1696
+        /** @var Property[] $properties */
1697
+        $properties = array_filter($comp->children(), function ($c) {
1698
+            return $c instanceof Property;
1699
+        });
1700
+        $validationRules = $comp->getValidationRules();
1701
+
1702
+        foreach ($subComponents as $subComponent) {
1703
+            $name = $subComponent->name;
1704
+            if (!isset($data[$name])) {
1705
+                $data[$name] = [];
1706
+            }
1707
+            $data[$name][] = $this->transformSearchData($subComponent);
1708
+        }
1709
+
1710
+        foreach ($properties as $property) {
1711
+            $name = $property->name;
1712
+            if (!isset($validationRules[$name])) {
1713
+                $validationRules[$name] = '*';
1714
+            }
1715
+
1716
+            $rule = $validationRules[$property->name];
1717
+            if ($rule === '+' || $rule === '*') { // multiple
1718
+                if (!isset($data[$name])) {
1719
+                    $data[$name] = [];
1720
+                }
1721
+
1722
+                $data[$name][] = $this->transformSearchProperty($property);
1723
+            } else { // once
1724
+                $data[$name] = $this->transformSearchProperty($property);
1725
+            }
1726
+        }
1727
+
1728
+        return $data;
1729
+    }
1730
+
1731
+    /**
1732
+     * @param Property $prop
1733
+     * @return array
1734
+     */
1735
+    private function transformSearchProperty(Property $prop) {
1736
+        // No need to check Date, as it extends DateTime
1737
+        if ($prop instanceof Property\ICalendar\DateTime) {
1738
+            $value = $prop->getDateTime();
1739
+        } else {
1740
+            $value = $prop->getValue();
1741
+        }
1742
+
1743
+        return [
1744
+            $value,
1745
+            $prop->parameters()
1746
+        ];
1747
+    }
1748
+
1749
+    /**
1750
+     * @param string $principalUri
1751
+     * @param string $pattern
1752
+     * @param array $componentTypes
1753
+     * @param array $searchProperties
1754
+     * @param array $searchParameters
1755
+     * @param array $options
1756
+     * @return array
1757
+     */
1758
+    public function searchPrincipalUri(string $principalUri,
1759
+                                        string $pattern,
1760
+                                        array $componentTypes,
1761
+                                        array $searchProperties,
1762
+                                        array $searchParameters,
1763
+                                        array $options = []): array {
1764
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1765
+
1766
+        $calendarObjectIdQuery = $this->db->getQueryBuilder();
1767
+        $calendarOr = $calendarObjectIdQuery->expr()->orX();
1768
+        $searchOr = $calendarObjectIdQuery->expr()->orX();
1769
+
1770
+        // Fetch calendars and subscription
1771
+        $calendars = $this->getCalendarsForUser($principalUri);
1772
+        $subscriptions = $this->getSubscriptionsForUser($principalUri);
1773
+        foreach ($calendars as $calendar) {
1774
+            $calendarAnd = $calendarObjectIdQuery->expr()->andX();
1775
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1776
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1777
+
1778
+            // If it's shared, limit search to public events
1779
+            if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
1780
+                && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1781
+                $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1782
+            }
1783
+
1784
+            $calendarOr->add($calendarAnd);
1785
+        }
1786
+        foreach ($subscriptions as $subscription) {
1787
+            $subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1788
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1789
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1790
+
1791
+            // If it's shared, limit search to public events
1792
+            if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
1793
+                && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1794
+                $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1795
+            }
1796
+
1797
+            $calendarOr->add($subscriptionAnd);
1798
+        }
1799
+
1800
+        foreach ($searchProperties as $property) {
1801
+            $propertyAnd = $calendarObjectIdQuery->expr()->andX();
1802
+            $propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1803
+            $propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1804
+
1805
+            $searchOr->add($propertyAnd);
1806
+        }
1807
+        foreach ($searchParameters as $property => $parameter) {
1808
+            $parameterAnd = $calendarObjectIdQuery->expr()->andX();
1809
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1810
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
1811
+
1812
+            $searchOr->add($parameterAnd);
1813
+        }
1814
+
1815
+        if ($calendarOr->count() === 0) {
1816
+            return [];
1817
+        }
1818
+        if ($searchOr->count() === 0) {
1819
+            return [];
1820
+        }
1821
+
1822
+        $calendarObjectIdQuery->selectDistinct('cob.objectid')
1823
+            ->from($this->dbObjectPropertiesTable, 'cob')
1824
+            ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1825
+            ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1826
+            ->andWhere($calendarOr)
1827
+            ->andWhere($searchOr);
1828
+
1829
+        if ('' !== $pattern) {
1830
+            if (!$escapePattern) {
1831
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1832
+            } else {
1833
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1834
+            }
1835
+        }
1836
+
1837
+        if (isset($options['limit'])) {
1838
+            $calendarObjectIdQuery->setMaxResults($options['limit']);
1839
+        }
1840
+        if (isset($options['offset'])) {
1841
+            $calendarObjectIdQuery->setFirstResult($options['offset']);
1842
+        }
1843
+
1844
+        $result = $calendarObjectIdQuery->execute();
1845
+        $matches = $result->fetchAll();
1846
+        $result->closeCursor();
1847
+        $matches = array_map(static function (array $match):int {
1848
+            return (int) $match['objectid'];
1849
+        }, $matches);
1850
+
1851
+        $query = $this->db->getQueryBuilder();
1852
+        $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1853
+            ->from('calendarobjects')
1854
+            ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1855
+
1856
+        $result = $query->execute();
1857
+        $calendarObjects = $result->fetchAll();
1858
+        $result->closeCursor();
1859
+
1860
+        return array_map(function (array $array): array {
1861
+            $array['calendarid'] = (int)$array['calendarid'];
1862
+            $array['calendartype'] = (int)$array['calendartype'];
1863
+            $array['calendardata'] = $this->readBlob($array['calendardata']);
1864
+
1865
+            return $array;
1866
+        }, $calendarObjects);
1867
+    }
1868
+
1869
+    /**
1870
+     * Searches through all of a users calendars and calendar objects to find
1871
+     * an object with a specific UID.
1872
+     *
1873
+     * This method should return the path to this object, relative to the
1874
+     * calendar home, so this path usually only contains two parts:
1875
+     *
1876
+     * calendarpath/objectpath.ics
1877
+     *
1878
+     * If the uid is not found, return null.
1879
+     *
1880
+     * This method should only consider * objects that the principal owns, so
1881
+     * any calendars owned by other principals that also appear in this
1882
+     * collection should be ignored.
1883
+     *
1884
+     * @param string $principalUri
1885
+     * @param string $uid
1886
+     * @return string|null
1887
+     */
1888
+    public function getCalendarObjectByUID($principalUri, $uid) {
1889
+        $query = $this->db->getQueryBuilder();
1890
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1891
+            ->from('calendarobjects', 'co')
1892
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1893
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1894
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1895
+
1896
+        $stmt = $query->execute();
1897
+
1898
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1899
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1900
+        }
1901
+
1902
+        return null;
1903
+    }
1904
+
1905
+    /**
1906
+     * The getChanges method returns all the changes that have happened, since
1907
+     * the specified syncToken in the specified calendar.
1908
+     *
1909
+     * This function should return an array, such as the following:
1910
+     *
1911
+     * [
1912
+     *   'syncToken' => 'The current synctoken',
1913
+     *   'added'   => [
1914
+     *      'new.txt',
1915
+     *   ],
1916
+     *   'modified'   => [
1917
+     *      'modified.txt',
1918
+     *   ],
1919
+     *   'deleted' => [
1920
+     *      'foo.php.bak',
1921
+     *      'old.txt'
1922
+     *   ]
1923
+     * );
1924
+     *
1925
+     * The returned syncToken property should reflect the *current* syncToken
1926
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1927
+     * property This is * needed here too, to ensure the operation is atomic.
1928
+     *
1929
+     * If the $syncToken argument is specified as null, this is an initial
1930
+     * sync, and all members should be reported.
1931
+     *
1932
+     * The modified property is an array of nodenames that have changed since
1933
+     * the last token.
1934
+     *
1935
+     * The deleted property is an array with nodenames, that have been deleted
1936
+     * from collection.
1937
+     *
1938
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1939
+     * 1, you only have to report changes that happened only directly in
1940
+     * immediate descendants. If it's 2, it should also include changes from
1941
+     * the nodes below the child collections. (grandchildren)
1942
+     *
1943
+     * The $limit argument allows a client to specify how many results should
1944
+     * be returned at most. If the limit is not specified, it should be treated
1945
+     * as infinite.
1946
+     *
1947
+     * If the limit (infinite or not) is higher than you're willing to return,
1948
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1949
+     *
1950
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1951
+     * return null.
1952
+     *
1953
+     * The limit is 'suggestive'. You are free to ignore it.
1954
+     *
1955
+     * @param string $calendarId
1956
+     * @param string $syncToken
1957
+     * @param int $syncLevel
1958
+     * @param int|null $limit
1959
+     * @param int $calendarType
1960
+     * @return array
1961
+     */
1962
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1963
+        // Current synctoken
1964
+        $qb = $this->db->getQueryBuilder();
1965
+        $qb->select('synctoken')
1966
+            ->from('calendars')
1967
+            ->where(
1968
+                $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
1969
+            );
1970
+        $stmt = $qb->execute();
1971
+        $currentToken = $stmt->fetchOne();
1972
+
1973
+        if ($currentToken === false) {
1974
+            return null;
1975
+        }
1976
+
1977
+        $result = [
1978
+            'syncToken' => $currentToken,
1979
+            'added' => [],
1980
+            'modified' => [],
1981
+            'deleted' => [],
1982
+        ];
1983
+
1984
+        if ($syncToken) {
1985
+            $qb = $this->db->getQueryBuilder();
1986
+
1987
+            $qb->select('uri', 'operation')
1988
+                ->from('calendarchanges')
1989
+                ->where(
1990
+                    $qb->expr()->andX(
1991
+                        $qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
1992
+                        $qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
1993
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1994
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
1995
+                    )
1996
+                )->orderBy('synctoken');
1997
+            if (is_int($limit) && $limit > 0) {
1998
+                $qb->setMaxResults($limit);
1999
+            }
2000
+
2001
+            // Fetching all changes
2002
+            $stmt = $qb->execute();
2003
+
2004
+            $changes = [];
2005
+
2006
+            // This loop ensures that any duplicates are overwritten, only the
2007
+            // last change on a node is relevant.
2008
+            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2009
+                $changes[$row['uri']] = $row['operation'];
2010
+            }
2011
+
2012
+            foreach ($changes as $uri => $operation) {
2013
+                switch ($operation) {
2014
+                    case 1:
2015
+                        $result['added'][] = $uri;
2016
+                        break;
2017
+                    case 2:
2018
+                        $result['modified'][] = $uri;
2019
+                        break;
2020
+                    case 3:
2021
+                        $result['deleted'][] = $uri;
2022
+                        break;
2023
+                }
2024
+            }
2025
+        } else {
2026
+            // No synctoken supplied, this is the initial sync.
2027
+            $qb = $this->db->getQueryBuilder();
2028
+            $qb->select('uri')
2029
+                ->from('calendarobjects')
2030
+                ->where(
2031
+                    $qb->expr()->andX(
2032
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2033
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2034
+                    )
2035
+                );
2036
+            $stmt = $qb->execute();
2037
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2038
+        }
2039
+        return $result;
2040
+    }
2041
+
2042
+    /**
2043
+     * Returns a list of subscriptions for a principal.
2044
+     *
2045
+     * Every subscription is an array with the following keys:
2046
+     *  * id, a unique id that will be used by other functions to modify the
2047
+     *    subscription. This can be the same as the uri or a database key.
2048
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2049
+     *  * principaluri. The owner of the subscription. Almost always the same as
2050
+     *    principalUri passed to this method.
2051
+     *
2052
+     * Furthermore, all the subscription info must be returned too:
2053
+     *
2054
+     * 1. {DAV:}displayname
2055
+     * 2. {http://apple.com/ns/ical/}refreshrate
2056
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2057
+     *    should not be stripped).
2058
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2059
+     *    should not be stripped).
2060
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2061
+     *    attachments should not be stripped).
2062
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2063
+     *     Sabre\DAV\Property\Href).
2064
+     * 7. {http://apple.com/ns/ical/}calendar-color
2065
+     * 8. {http://apple.com/ns/ical/}calendar-order
2066
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2067
+     *    (should just be an instance of
2068
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2069
+     *    default components).
2070
+     *
2071
+     * @param string $principalUri
2072
+     * @return array
2073
+     */
2074
+    public function getSubscriptionsForUser($principalUri) {
2075
+        $fields = array_values($this->subscriptionPropertyMap);
2076
+        $fields[] = 'id';
2077
+        $fields[] = 'uri';
2078
+        $fields[] = 'source';
2079
+        $fields[] = 'principaluri';
2080
+        $fields[] = 'lastmodified';
2081
+        $fields[] = 'synctoken';
2082
+
2083
+        $query = $this->db->getQueryBuilder();
2084
+        $query->select($fields)
2085
+            ->from('calendarsubscriptions')
2086
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2087
+            ->orderBy('calendarorder', 'asc');
2088
+        $stmt = $query->execute();
2089
+
2090
+        $subscriptions = [];
2091
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2092
+            $subscription = [
2093
+                'id' => $row['id'],
2094
+                'uri' => $row['uri'],
2095
+                'principaluri' => $row['principaluri'],
2096
+                'source' => $row['source'],
2097
+                'lastmodified' => $row['lastmodified'],
2098
+
2099
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2100
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2101
+            ];
2102
+
2103
+            foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2104
+                if (!is_null($row[$dbName])) {
2105
+                    $subscription[$xmlName] = $row[$dbName];
2106
+                }
2107
+            }
2108
+
2109
+            $subscriptions[] = $subscription;
2110
+        }
2111
+
2112
+        return $subscriptions;
2113
+    }
2114
+
2115
+    /**
2116
+     * Creates a new subscription for a principal.
2117
+     *
2118
+     * If the creation was a success, an id must be returned that can be used to reference
2119
+     * this subscription in other methods, such as updateSubscription.
2120
+     *
2121
+     * @param string $principalUri
2122
+     * @param string $uri
2123
+     * @param array $properties
2124
+     * @return mixed
2125
+     */
2126
+    public function createSubscription($principalUri, $uri, array $properties) {
2127
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2128
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2129
+        }
2130
+
2131
+        $values = [
2132
+            'principaluri' => $principalUri,
2133
+            'uri' => $uri,
2134
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2135
+            'lastmodified' => time(),
2136
+        ];
2137
+
2138
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2139
+
2140
+        foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2141
+            if (array_key_exists($xmlName, $properties)) {
2142
+                $values[$dbName] = $properties[$xmlName];
2143
+                if (in_array($dbName, $propertiesBoolean)) {
2144
+                    $values[$dbName] = true;
2145
+                }
2146
+            }
2147
+        }
2148
+
2149
+        $valuesToInsert = [];
2150
+
2151
+        $query = $this->db->getQueryBuilder();
2152
+
2153
+        foreach (array_keys($values) as $name) {
2154
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2155
+        }
2156
+
2157
+        $query->insert('calendarsubscriptions')
2158
+            ->values($valuesToInsert)
2159
+            ->execute();
2160
+
2161
+        $subscriptionId = $query->getLastInsertId();
2162
+
2163
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2164
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2165
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2166
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2167
+            [
2168
+                'subscriptionId' => $subscriptionId,
2169
+                'subscriptionData' => $subscriptionRow,
2170
+            ]));
2171
+
2172
+        return $subscriptionId;
2173
+    }
2174
+
2175
+    /**
2176
+     * Updates a subscription
2177
+     *
2178
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2179
+     * To do the actual updates, you must tell this object which properties
2180
+     * you're going to process with the handle() method.
2181
+     *
2182
+     * Calling the handle method is like telling the PropPatch object "I
2183
+     * promise I can handle updating this property".
2184
+     *
2185
+     * Read the PropPatch documentation for more info and examples.
2186
+     *
2187
+     * @param mixed $subscriptionId
2188
+     * @param PropPatch $propPatch
2189
+     * @return void
2190
+     */
2191
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2192
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2193
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2194
+
2195
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2196
+            $newValues = [];
2197
+
2198
+            foreach ($mutations as $propertyName => $propertyValue) {
2199
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2200
+                    $newValues['source'] = $propertyValue->getHref();
2201
+                } else {
2202
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2203
+                    $newValues[$fieldName] = $propertyValue;
2204
+                }
2205
+            }
2206
+
2207
+            $query = $this->db->getQueryBuilder();
2208
+            $query->update('calendarsubscriptions')
2209
+                ->set('lastmodified', $query->createNamedParameter(time()));
2210
+            foreach ($newValues as $fieldName => $value) {
2211
+                $query->set($fieldName, $query->createNamedParameter($value));
2212
+            }
2213
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2214
+                ->execute();
2215
+
2216
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2217
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2218
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2219
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2220
+                [
2221
+                    'subscriptionId' => $subscriptionId,
2222
+                    'subscriptionData' => $subscriptionRow,
2223
+                    'propertyMutations' => $mutations,
2224
+                ]));
2225
+
2226
+            return true;
2227
+        });
2228
+    }
2229
+
2230
+    /**
2231
+     * Deletes a subscription.
2232
+     *
2233
+     * @param mixed $subscriptionId
2234
+     * @return void
2235
+     */
2236
+    public function deleteSubscription($subscriptionId) {
2237
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2238
+
2239
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2240
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2241
+            [
2242
+                'subscriptionId' => $subscriptionId,
2243
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2244
+            ]));
2245
+
2246
+        $query = $this->db->getQueryBuilder();
2247
+        $query->delete('calendarsubscriptions')
2248
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2249
+            ->execute();
2250
+
2251
+        $query = $this->db->getQueryBuilder();
2252
+        $query->delete('calendarobjects')
2253
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2254
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2255
+            ->execute();
2256
+
2257
+        $query->delete('calendarchanges')
2258
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2259
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2260
+            ->execute();
2261
+
2262
+        $query->delete($this->dbObjectPropertiesTable)
2263
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2264
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2265
+            ->execute();
2266
+
2267
+        if ($subscriptionRow) {
2268
+            $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2269
+        }
2270
+    }
2271
+
2272
+    /**
2273
+     * Returns a single scheduling object for the inbox collection.
2274
+     *
2275
+     * The returned array should contain the following elements:
2276
+     *   * uri - A unique basename for the object. This will be used to
2277
+     *           construct a full uri.
2278
+     *   * calendardata - The iCalendar object
2279
+     *   * lastmodified - The last modification date. Can be an int for a unix
2280
+     *                    timestamp, or a PHP DateTime object.
2281
+     *   * etag - A unique token that must change if the object changed.
2282
+     *   * size - The size of the object, in bytes.
2283
+     *
2284
+     * @param string $principalUri
2285
+     * @param string $objectUri
2286
+     * @return array
2287
+     */
2288
+    public function getSchedulingObject($principalUri, $objectUri) {
2289
+        $query = $this->db->getQueryBuilder();
2290
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2291
+            ->from('schedulingobjects')
2292
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2293
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2294
+            ->execute();
2295
+
2296
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2297
+
2298
+        if (!$row) {
2299
+            return null;
2300
+        }
2301
+
2302
+        return [
2303
+            'uri' => $row['uri'],
2304
+            'calendardata' => $row['calendardata'],
2305
+            'lastmodified' => $row['lastmodified'],
2306
+            'etag' => '"' . $row['etag'] . '"',
2307
+            'size' => (int)$row['size'],
2308
+        ];
2309
+    }
2310
+
2311
+    /**
2312
+     * Returns all scheduling objects for the inbox collection.
2313
+     *
2314
+     * These objects should be returned as an array. Every item in the array
2315
+     * should follow the same structure as returned from getSchedulingObject.
2316
+     *
2317
+     * The main difference is that 'calendardata' is optional.
2318
+     *
2319
+     * @param string $principalUri
2320
+     * @return array
2321
+     */
2322
+    public function getSchedulingObjects($principalUri) {
2323
+        $query = $this->db->getQueryBuilder();
2324
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2325
+                ->from('schedulingobjects')
2326
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2327
+                ->execute();
2328
+
2329
+        $result = [];
2330
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2331
+            $result[] = [
2332
+                'calendardata' => $row['calendardata'],
2333
+                'uri' => $row['uri'],
2334
+                'lastmodified' => $row['lastmodified'],
2335
+                'etag' => '"' . $row['etag'] . '"',
2336
+                'size' => (int)$row['size'],
2337
+            ];
2338
+        }
2339
+
2340
+        return $result;
2341
+    }
2342
+
2343
+    /**
2344
+     * Deletes a scheduling object from the inbox collection.
2345
+     *
2346
+     * @param string $principalUri
2347
+     * @param string $objectUri
2348
+     * @return void
2349
+     */
2350
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2351
+        $query = $this->db->getQueryBuilder();
2352
+        $query->delete('schedulingobjects')
2353
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2354
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2355
+                ->execute();
2356
+    }
2357
+
2358
+    /**
2359
+     * Creates a new scheduling object. This should land in a users' inbox.
2360
+     *
2361
+     * @param string $principalUri
2362
+     * @param string $objectUri
2363
+     * @param string $objectData
2364
+     * @return void
2365
+     */
2366
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2367
+        $query = $this->db->getQueryBuilder();
2368
+        $query->insert('schedulingobjects')
2369
+            ->values([
2370
+                'principaluri' => $query->createNamedParameter($principalUri),
2371
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2372
+                'uri' => $query->createNamedParameter($objectUri),
2373
+                'lastmodified' => $query->createNamedParameter(time()),
2374
+                'etag' => $query->createNamedParameter(md5($objectData)),
2375
+                'size' => $query->createNamedParameter(strlen($objectData))
2376
+            ])
2377
+            ->execute();
2378
+    }
2379
+
2380
+    /**
2381
+     * Adds a change record to the calendarchanges table.
2382
+     *
2383
+     * @param mixed $calendarId
2384
+     * @param string $objectUri
2385
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2386
+     * @param int $calendarType
2387
+     * @return void
2388
+     */
2389
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2390
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2391
+
2392
+        $query = $this->db->getQueryBuilder();
2393
+        $query->select('synctoken')
2394
+            ->from($table)
2395
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2396
+        $result = $query->execute();
2397
+        $syncToken = (int)$result->fetchOne();
2398
+        $result->closeCursor();
2399
+
2400
+        $query = $this->db->getQueryBuilder();
2401
+        $query->insert('calendarchanges')
2402
+            ->values([
2403
+                'uri' => $query->createNamedParameter($objectUri),
2404
+                'synctoken' => $query->createNamedParameter($syncToken),
2405
+                'calendarid' => $query->createNamedParameter($calendarId),
2406
+                'operation' => $query->createNamedParameter($operation),
2407
+                'calendartype' => $query->createNamedParameter($calendarType),
2408
+            ])
2409
+            ->execute();
2410
+
2411
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2412
+        $stmt->execute([
2413
+            $calendarId
2414
+        ]);
2415
+    }
2416
+
2417
+    /**
2418
+     * Parses some information from calendar objects, used for optimized
2419
+     * calendar-queries.
2420
+     *
2421
+     * Returns an array with the following keys:
2422
+     *   * etag - An md5 checksum of the object without the quotes.
2423
+     *   * size - Size of the object in bytes
2424
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2425
+     *   * firstOccurence
2426
+     *   * lastOccurence
2427
+     *   * uid - value of the UID property
2428
+     *
2429
+     * @param string $calendarData
2430
+     * @return array
2431
+     */
2432
+    public function getDenormalizedData($calendarData) {
2433
+        $vObject = Reader::read($calendarData);
2434
+        $vEvents = [];
2435
+        $componentType = null;
2436
+        $component = null;
2437
+        $firstOccurrence = null;
2438
+        $lastOccurrence = null;
2439
+        $uid = null;
2440
+        $classification = self::CLASSIFICATION_PUBLIC;
2441
+        $hasDTSTART = false;
2442
+        foreach ($vObject->getComponents() as $component) {
2443
+            if ($component->name !== 'VTIMEZONE') {
2444
+                // Finding all VEVENTs, and track them
2445
+                if ($component->name === 'VEVENT') {
2446
+                    array_push($vEvents, $component);
2447
+                    if ($component->DTSTART) {
2448
+                        $hasDTSTART = true;
2449
+                    }
2450
+                }
2451
+                // Track first component type and uid
2452
+                if ($uid === null) {
2453
+                    $componentType = $component->name;
2454
+                    $uid = (string)$component->UID;
2455
+                }
2456
+            }
2457
+        }
2458
+        if (!$componentType) {
2459
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2460
+        }
2461
+
2462
+        if ($hasDTSTART) {
2463
+            $component = $vEvents[0];
2464
+
2465
+            // Finding the last occurrence is a bit harder
2466
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
2467
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2468
+                if (isset($component->DTEND)) {
2469
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2470
+                } elseif (isset($component->DURATION)) {
2471
+                    $endDate = clone $component->DTSTART->getDateTime();
2472
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2473
+                    $lastOccurrence = $endDate->getTimeStamp();
2474
+                } elseif (!$component->DTSTART->hasTime()) {
2475
+                    $endDate = clone $component->DTSTART->getDateTime();
2476
+                    $endDate->modify('+1 day');
2477
+                    $lastOccurrence = $endDate->getTimeStamp();
2478
+                } else {
2479
+                    $lastOccurrence = $firstOccurrence;
2480
+                }
2481
+            } else {
2482
+                $it = new EventIterator($vEvents);
2483
+                $maxDate = new DateTime(self::MAX_DATE);
2484
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
2485
+                if ($it->isInfinite()) {
2486
+                    $lastOccurrence = $maxDate->getTimestamp();
2487
+                } else {
2488
+                    $end = $it->getDtEnd();
2489
+                    while ($it->valid() && $end < $maxDate) {
2490
+                        $end = $it->getDtEnd();
2491
+                        $it->next();
2492
+                    }
2493
+                    $lastOccurrence = $end->getTimestamp();
2494
+                }
2495
+            }
2496
+        }
2497
+
2498
+        if ($component->CLASS) {
2499
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2500
+            switch ($component->CLASS->getValue()) {
2501
+                case 'PUBLIC':
2502
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2503
+                    break;
2504
+                case 'CONFIDENTIAL':
2505
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2506
+                    break;
2507
+            }
2508
+        }
2509
+        return [
2510
+            'etag' => md5($calendarData),
2511
+            'size' => strlen($calendarData),
2512
+            'componentType' => $componentType,
2513
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2514
+            'lastOccurence' => $lastOccurrence,
2515
+            'uid' => $uid,
2516
+            'classification' => $classification
2517
+        ];
2518
+    }
2519
+
2520
+    /**
2521
+     * @param $cardData
2522
+     * @return bool|string
2523
+     */
2524
+    private function readBlob($cardData) {
2525
+        if (is_resource($cardData)) {
2526
+            return stream_get_contents($cardData);
2527
+        }
2528
+
2529
+        return $cardData;
2530
+    }
2531
+
2532
+    /**
2533
+     * @param IShareable $shareable
2534
+     * @param array $add
2535
+     * @param array $remove
2536
+     */
2537
+    public function updateShares($shareable, $add, $remove) {
2538
+        $calendarId = $shareable->getResourceId();
2539
+        $calendarRow = $this->getCalendarById($calendarId);
2540
+        $oldShares = $this->getShares($calendarId);
2541
+
2542
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2543
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2544
+            [
2545
+                'calendarId' => $calendarId,
2546
+                'calendarData' => $calendarRow,
2547
+                'shares' => $oldShares,
2548
+                'add' => $add,
2549
+                'remove' => $remove,
2550
+            ]));
2551
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2552
+
2553
+        $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2554
+    }
2555
+
2556
+    /**
2557
+     * @param int $resourceId
2558
+     * @param int $calendarType
2559
+     * @return array
2560
+     */
2561
+    public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2562
+        return $this->calendarSharingBackend->getShares($resourceId);
2563
+    }
2564
+
2565
+    /**
2566
+     * @param boolean $value
2567
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2568
+     * @return string|null
2569
+     */
2570
+    public function setPublishStatus($value, $calendar) {
2571
+        $calendarId = $calendar->getResourceId();
2572
+        $calendarData = $this->getCalendarById($calendarId);
2573
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2574
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2575
+            [
2576
+                'calendarId' => $calendarId,
2577
+                'calendarData' => $calendarData,
2578
+                'public' => $value,
2579
+            ]));
2580
+
2581
+        $query = $this->db->getQueryBuilder();
2582
+        if ($value) {
2583
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2584
+            $query->insert('dav_shares')
2585
+                ->values([
2586
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2587
+                    'type' => $query->createNamedParameter('calendar'),
2588
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2589
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2590
+                    'publicuri' => $query->createNamedParameter($publicUri)
2591
+                ]);
2592
+            $query->execute();
2593
+
2594
+            $this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2595
+            return $publicUri;
2596
+        }
2597
+        $query->delete('dav_shares')
2598
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2599
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2600
+        $query->execute();
2601
+
2602
+        $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2603
+        return null;
2604
+    }
2605
+
2606
+    /**
2607
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2608
+     * @return mixed
2609
+     */
2610
+    public function getPublishStatus($calendar) {
2611
+        $query = $this->db->getQueryBuilder();
2612
+        $result = $query->select('publicuri')
2613
+            ->from('dav_shares')
2614
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2615
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2616
+            ->execute();
2617
+
2618
+        $row = $result->fetch();
2619
+        $result->closeCursor();
2620
+        return $row ? reset($row) : false;
2621
+    }
2622
+
2623
+    /**
2624
+     * @param int $resourceId
2625
+     * @param array $acl
2626
+     * @return array
2627
+     */
2628
+    public function applyShareAcl($resourceId, $acl) {
2629
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2630
+    }
2631
+
2632
+
2633
+
2634
+    /**
2635
+     * update properties table
2636
+     *
2637
+     * @param int $calendarId
2638
+     * @param string $objectUri
2639
+     * @param string $calendarData
2640
+     * @param int $calendarType
2641
+     */
2642
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2643
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2644
+
2645
+        try {
2646
+            $vCalendar = $this->readCalendarData($calendarData);
2647
+        } catch (\Exception $ex) {
2648
+            return;
2649
+        }
2650
+
2651
+        $this->purgeProperties($calendarId, $objectId);
2652
+
2653
+        $query = $this->db->getQueryBuilder();
2654
+        $query->insert($this->dbObjectPropertiesTable)
2655
+            ->values(
2656
+                [
2657
+                    'calendarid' => $query->createNamedParameter($calendarId),
2658
+                    'calendartype' => $query->createNamedParameter($calendarType),
2659
+                    'objectid' => $query->createNamedParameter($objectId),
2660
+                    'name' => $query->createParameter('name'),
2661
+                    'parameter' => $query->createParameter('parameter'),
2662
+                    'value' => $query->createParameter('value'),
2663
+                ]
2664
+            );
2665
+
2666
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2667
+        foreach ($vCalendar->getComponents() as $component) {
2668
+            if (!in_array($component->name, $indexComponents)) {
2669
+                continue;
2670
+            }
2671
+
2672
+            foreach ($component->children() as $property) {
2673
+                if (in_array($property->name, self::$indexProperties)) {
2674
+                    $value = $property->getValue();
2675
+                    // is this a shitty db?
2676
+                    if (!$this->db->supports4ByteText()) {
2677
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2678
+                    }
2679
+                    $value = mb_substr($value, 0, 254);
2680
+
2681
+                    $query->setParameter('name', $property->name);
2682
+                    $query->setParameter('parameter', null);
2683
+                    $query->setParameter('value', $value);
2684
+                    $query->execute();
2685
+                }
2686
+
2687
+                if (array_key_exists($property->name, self::$indexParameters)) {
2688
+                    $parameters = $property->parameters();
2689
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2690
+
2691
+                    foreach ($parameters as $key => $value) {
2692
+                        if (in_array($key, $indexedParametersForProperty)) {
2693
+                            // is this a shitty db?
2694
+                            if ($this->db->supports4ByteText()) {
2695
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2696
+                            }
2697
+
2698
+                            $query->setParameter('name', $property->name);
2699
+                            $query->setParameter('parameter', mb_substr($key, 0, 254));
2700
+                            $query->setParameter('value', mb_substr($value, 0, 254));
2701
+                            $query->execute();
2702
+                        }
2703
+                    }
2704
+                }
2705
+            }
2706
+        }
2707
+    }
2708
+
2709
+    /**
2710
+     * deletes all birthday calendars
2711
+     */
2712
+    public function deleteAllBirthdayCalendars() {
2713
+        $query = $this->db->getQueryBuilder();
2714
+        $result = $query->select(['id'])->from('calendars')
2715
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2716
+            ->execute();
2717
+
2718
+        $ids = $result->fetchAll();
2719
+        foreach ($ids as $id) {
2720
+            $this->deleteCalendar($id['id']);
2721
+        }
2722
+    }
2723
+
2724
+    /**
2725
+     * @param $subscriptionId
2726
+     */
2727
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2728
+        $query = $this->db->getQueryBuilder();
2729
+        $query->select('uri')
2730
+            ->from('calendarobjects')
2731
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2732
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2733
+        $stmt = $query->execute();
2734
+
2735
+        $uris = [];
2736
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2737
+            $uris[] = $row['uri'];
2738
+        }
2739
+        $stmt->closeCursor();
2740
+
2741
+        $query = $this->db->getQueryBuilder();
2742
+        $query->delete('calendarobjects')
2743
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2744
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2745
+            ->execute();
2746
+
2747
+        $query->delete('calendarchanges')
2748
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2749
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2750
+            ->execute();
2751
+
2752
+        $query->delete($this->dbObjectPropertiesTable)
2753
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2754
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2755
+            ->execute();
2756
+
2757
+        foreach ($uris as $uri) {
2758
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2759
+        }
2760
+    }
2761
+
2762
+    /**
2763
+     * Move a calendar from one user to another
2764
+     *
2765
+     * @param string $uriName
2766
+     * @param string $uriOrigin
2767
+     * @param string $uriDestination
2768
+     * @param string $newUriName (optional) the new uriName
2769
+     */
2770
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
2771
+        $query = $this->db->getQueryBuilder();
2772
+        $query->update('calendars')
2773
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2774
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
2775
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2776
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2777
+            ->execute();
2778
+    }
2779
+
2780
+    /**
2781
+     * read VCalendar data into a VCalendar object
2782
+     *
2783
+     * @param string $objectData
2784
+     * @return VCalendar
2785
+     */
2786
+    protected function readCalendarData($objectData) {
2787
+        return Reader::read($objectData);
2788
+    }
2789
+
2790
+    /**
2791
+     * delete all properties from a given calendar object
2792
+     *
2793
+     * @param int $calendarId
2794
+     * @param int $objectId
2795
+     */
2796
+    protected function purgeProperties($calendarId, $objectId) {
2797
+        $query = $this->db->getQueryBuilder();
2798
+        $query->delete($this->dbObjectPropertiesTable)
2799
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2800
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2801
+        $query->execute();
2802
+    }
2803
+
2804
+    /**
2805
+     * get ID from a given calendar object
2806
+     *
2807
+     * @param int $calendarId
2808
+     * @param string $uri
2809
+     * @param int $calendarType
2810
+     * @return int
2811
+     */
2812
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2813
+        $query = $this->db->getQueryBuilder();
2814
+        $query->select('id')
2815
+            ->from('calendarobjects')
2816
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2817
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2818
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2819
+
2820
+        $result = $query->execute();
2821
+        $objectIds = $result->fetch();
2822
+        $result->closeCursor();
2823
+
2824
+        if (!isset($objectIds['id'])) {
2825
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2826
+        }
2827
+
2828
+        return (int)$objectIds['id'];
2829
+    }
2830
+
2831
+    /**
2832
+     * return legacy endpoint principal name to new principal name
2833
+     *
2834
+     * @param $principalUri
2835
+     * @param $toV2
2836
+     * @return string
2837
+     */
2838
+    private function convertPrincipal($principalUri, $toV2) {
2839
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2840
+            [, $name] = Uri\split($principalUri);
2841
+            if ($toV2 === true) {
2842
+                return "principals/users/$name";
2843
+            }
2844
+            return "principals/$name";
2845
+        }
2846
+        return $principalUri;
2847
+    }
2848
+
2849
+    /**
2850
+     * adds information about an owner to the calendar data
2851
+     *
2852
+     * @param $calendarInfo
2853
+     */
2854
+    private function addOwnerPrincipal(&$calendarInfo) {
2855
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2856
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2857
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2858
+            $uri = $calendarInfo[$ownerPrincipalKey];
2859
+        } else {
2860
+            $uri = $calendarInfo['principaluri'];
2861
+        }
2862
+
2863
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2864
+        if (isset($principalInformation['{DAV:}displayname'])) {
2865
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2866
+        }
2867
+    }
2868 2868
 }
Please login to merge, or discard this patch.
Spacing   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 		}
257 257
 
258 258
 		$result = $query->execute();
259
-		$column = (int)$result->fetchOne();
259
+		$column = (int) $result->fetchOne();
260 260
 		$result->closeCursor();
261 261
 		return $column;
262 262
 	}
@@ -316,18 +316,18 @@  discard block
 block discarded – undo
316 316
 			$row['principaluri'] = (string) $row['principaluri'];
317 317
 			$components = [];
318 318
 			if ($row['components']) {
319
-				$components = explode(',',$row['components']);
319
+				$components = explode(',', $row['components']);
320 320
 			}
321 321
 
322 322
 			$calendar = [
323 323
 				'id' => $row['id'],
324 324
 				'uri' => $row['uri'],
325 325
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
326
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
327
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
328
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
329
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
330
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
326
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
327
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
328
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
329
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
330
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
331 331
 			];
332 332
 
333 333
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 
368 368
 		$result = $query->execute();
369 369
 
370
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
370
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
371 371
 		while ($row = $result->fetch()) {
372 372
 			$row['principaluri'] = (string) $row['principaluri'];
373 373
 			if ($row['principaluri'] === $principalUri) {
@@ -388,21 +388,21 @@  discard block
 block discarded – undo
388 388
 			}
389 389
 
390 390
 			[, $name] = Uri\split($row['principaluri']);
391
-			$uri = $row['uri'] . '_shared_by_' . $name;
392
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
391
+			$uri = $row['uri'].'_shared_by_'.$name;
392
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
393 393
 			$components = [];
394 394
 			if ($row['components']) {
395
-				$components = explode(',',$row['components']);
395
+				$components = explode(',', $row['components']);
396 396
 			}
397 397
 			$calendar = [
398 398
 				'id' => $row['id'],
399 399
 				'uri' => $uri,
400 400
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
401
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
402
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
403
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
404
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
405
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
401
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
402
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
403
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
404
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
405
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
406 406
 				$readOnlyPropertyName => $readOnly,
407 407
 			];
408 408
 
@@ -443,16 +443,16 @@  discard block
 block discarded – undo
443 443
 			$row['principaluri'] = (string) $row['principaluri'];
444 444
 			$components = [];
445 445
 			if ($row['components']) {
446
-				$components = explode(',',$row['components']);
446
+				$components = explode(',', $row['components']);
447 447
 			}
448 448
 			$calendar = [
449 449
 				'id' => $row['id'],
450 450
 				'uri' => $row['uri'],
451 451
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
452
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
453
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
454
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
455
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
452
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
453
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
454
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
455
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
456 456
 			];
457 457
 			foreach ($this->propertyMap as $xmlName => $dbName) {
458 458
 				$calendar[$xmlName] = $row[$dbName];
@@ -512,22 +512,22 @@  discard block
 block discarded – undo
512 512
 		while ($row = $result->fetch()) {
513 513
 			$row['principaluri'] = (string) $row['principaluri'];
514 514
 			[, $name] = Uri\split($row['principaluri']);
515
-			$row['displayname'] = $row['displayname'] . "($name)";
515
+			$row['displayname'] = $row['displayname']."($name)";
516 516
 			$components = [];
517 517
 			if ($row['components']) {
518
-				$components = explode(',',$row['components']);
518
+				$components = explode(',', $row['components']);
519 519
 			}
520 520
 			$calendar = [
521 521
 				'id' => $row['id'],
522 522
 				'uri' => $row['publicuri'],
523 523
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
524
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
525
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
526
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
527
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
528
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
529
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
530
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
524
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
525
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
526
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
527
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
528
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
529
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
530
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
531 531
 			];
532 532
 
533 533
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -574,27 +574,27 @@  discard block
 block discarded – undo
574 574
 		$result->closeCursor();
575 575
 
576 576
 		if ($row === false) {
577
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
577
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
578 578
 		}
579 579
 
580 580
 		$row['principaluri'] = (string) $row['principaluri'];
581 581
 		[, $name] = Uri\split($row['principaluri']);
582
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
582
+		$row['displayname'] = $row['displayname'].' '."($name)";
583 583
 		$components = [];
584 584
 		if ($row['components']) {
585
-			$components = explode(',',$row['components']);
585
+			$components = explode(',', $row['components']);
586 586
 		}
587 587
 		$calendar = [
588 588
 			'id' => $row['id'],
589 589
 			'uri' => $row['publicuri'],
590 590
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
591
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
592
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
593
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
594
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
595
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
596
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
597
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
591
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
592
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
593
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
594
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
595
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
596
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
597
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
598 598
 		];
599 599
 
600 600
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -637,17 +637,17 @@  discard block
 block discarded – undo
637 637
 		$row['principaluri'] = (string) $row['principaluri'];
638 638
 		$components = [];
639 639
 		if ($row['components']) {
640
-			$components = explode(',',$row['components']);
640
+			$components = explode(',', $row['components']);
641 641
 		}
642 642
 
643 643
 		$calendar = [
644 644
 			'id' => $row['id'],
645 645
 			'uri' => $row['uri'],
646 646
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
647
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
648
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
649
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
650
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
647
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
648
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
649
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
650
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
651 651
 		];
652 652
 
653 653
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -688,17 +688,17 @@  discard block
 block discarded – undo
688 688
 		$row['principaluri'] = (string) $row['principaluri'];
689 689
 		$components = [];
690 690
 		if ($row['components']) {
691
-			$components = explode(',',$row['components']);
691
+			$components = explode(',', $row['components']);
692 692
 		}
693 693
 
694 694
 		$calendar = [
695 695
 			'id' => $row['id'],
696 696
 			'uri' => $row['uri'],
697 697
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
698
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
699
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
701
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
698
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
699
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
700
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
701
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
702 702
 		];
703 703
 
704 704
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -742,8 +742,8 @@  discard block
 block discarded – undo
742 742
 			'principaluri' => $row['principaluri'],
743 743
 			'source' => $row['source'],
744 744
 			'lastmodified' => $row['lastmodified'],
745
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
746
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
745
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
746
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
747 747
 		];
748 748
 
749 749
 		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -780,16 +780,16 @@  discard block
 block discarded – undo
780 780
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
781 781
 		if (isset($properties[$sccs])) {
782 782
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
783
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
783
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
784 784
 			}
785
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
785
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
786 786
 		} elseif (isset($properties['components'])) {
787 787
 			// Allow to provide components internally without having
788 788
 			// to create a SupportedCalendarComponentSet object
789 789
 			$values['components'] = $properties['components'];
790 790
 		}
791 791
 
792
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
792
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
793 793
 		if (isset($properties[$transp])) {
794 794
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
795 795
 		}
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
 		$calendarId = $query->getLastInsertId();
810 810
 
811 811
 		$calendarData = $this->getCalendarById($calendarId);
812
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
812
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
813 813
 		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
814 814
 			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
815 815
 			[
@@ -838,13 +838,13 @@  discard block
 block discarded – undo
838 838
 	 */
839 839
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
840 840
 		$supportedProperties = array_keys($this->propertyMap);
841
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
842 842
 
843
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
843
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
844 844
 			$newValues = [];
845 845
 			foreach ($mutations as $propertyName => $propertyValue) {
846 846
 				switch ($propertyName) {
847
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
847
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
848 848
 						$fieldName = 'transparent';
849 849
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
850 850
 						break;
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 
867 867
 			$calendarData = $this->getCalendarById($calendarId);
868 868
 			$shares = $this->getShares($calendarId);
869
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
869
+			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int) $calendarId, $calendarData, $shares, $mutations));
870 870
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
871 871
 				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
872 872
 				[
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 			->execute();
917 917
 
918 918
 		if ($calendarData) {
919
-			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
919
+			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int) $calendarId, $calendarData, $shares));
920 920
 		}
921 921
 	}
922 922
 
@@ -976,11 +976,11 @@  discard block
 block discarded – undo
976 976
 				'id' => $row['id'],
977 977
 				'uri' => $row['uri'],
978 978
 				'lastmodified' => $row['lastmodified'],
979
-				'etag' => '"' . $row['etag'] . '"',
979
+				'etag' => '"'.$row['etag'].'"',
980 980
 				'calendarid' => $row['calendarid'],
981
-				'size' => (int)$row['size'],
981
+				'size' => (int) $row['size'],
982 982
 				'component' => strtolower($row['componenttype']),
983
-				'classification' => (int)$row['classification']
983
+				'classification' => (int) $row['classification']
984 984
 			];
985 985
 		}
986 986
 		$stmt->closeCursor();
@@ -1024,12 +1024,12 @@  discard block
 block discarded – undo
1024 1024
 			'id' => $row['id'],
1025 1025
 			'uri' => $row['uri'],
1026 1026
 			'lastmodified' => $row['lastmodified'],
1027
-			'etag' => '"' . $row['etag'] . '"',
1027
+			'etag' => '"'.$row['etag'].'"',
1028 1028
 			'calendarid' => $row['calendarid'],
1029
-			'size' => (int)$row['size'],
1029
+			'size' => (int) $row['size'],
1030 1030
 			'calendardata' => $this->readBlob($row['calendardata']),
1031 1031
 			'component' => strtolower($row['componenttype']),
1032
-			'classification' => (int)$row['classification']
1032
+			'classification' => (int) $row['classification']
1033 1033
 		];
1034 1034
 	}
1035 1035
 
@@ -1070,12 +1070,12 @@  discard block
 block discarded – undo
1070 1070
 					'id' => $row['id'],
1071 1071
 					'uri' => $row['uri'],
1072 1072
 					'lastmodified' => $row['lastmodified'],
1073
-					'etag' => '"' . $row['etag'] . '"',
1073
+					'etag' => '"'.$row['etag'].'"',
1074 1074
 					'calendarid' => $row['calendarid'],
1075
-					'size' => (int)$row['size'],
1075
+					'size' => (int) $row['size'],
1076 1076
 					'calendardata' => $this->readBlob($row['calendardata']),
1077 1077
 					'component' => strtolower($row['componenttype']),
1078
-					'classification' => (int)$row['classification']
1078
+					'classification' => (int) $row['classification']
1079 1079
 				];
1080 1080
 			}
1081 1081
 			$result->closeCursor();
@@ -1147,7 +1147,7 @@  discard block
 block discarded – undo
1147 1147
 			$calendarRow = $this->getCalendarById($calendarId);
1148 1148
 			$shares = $this->getShares($calendarId);
1149 1149
 
1150
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1150
+			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1151 1151
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1152 1152
 				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1153 1153
 				[
@@ -1160,7 +1160,7 @@  discard block
 block discarded – undo
1160 1160
 		} else {
1161 1161
 			$subscriptionRow = $this->getSubscriptionById($calendarId);
1162 1162
 
1163
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1163
+			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1164 1164
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1165 1165
 				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1166 1166
 				[
@@ -1172,7 +1172,7 @@  discard block
 block discarded – undo
1172 1172
 			));
1173 1173
 		}
1174 1174
 
1175
-		return '"' . $extraData['etag'] . '"';
1175
+		return '"'.$extraData['etag'].'"';
1176 1176
 	}
1177 1177
 
1178 1178
 	/**
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
 				$calendarRow = $this->getCalendarById($calendarId);
1222 1222
 				$shares = $this->getShares($calendarId);
1223 1223
 
1224
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1224
+				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1225 1225
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1226 1226
 					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1227 1227
 					[
@@ -1234,7 +1234,7 @@  discard block
 block discarded – undo
1234 1234
 			} else {
1235 1235
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1236 1236
 
1237
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1237
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1238 1238
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1239 1239
 					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1240 1240
 					[
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
 			}
1248 1248
 		}
1249 1249
 
1250
-		return '"' . $extraData['etag'] . '"';
1250
+		return '"'.$extraData['etag'].'"';
1251 1251
 	}
1252 1252
 
1253 1253
 	/**
@@ -1284,7 +1284,7 @@  discard block
 block discarded – undo
1284 1284
 				$calendarRow = $this->getCalendarById($calendarId);
1285 1285
 				$shares = $this->getShares($calendarId);
1286 1286
 
1287
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1287
+				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int) $calendarId, $calendarRow, $shares, $data));
1288 1288
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1289 1289
 					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1290 1290
 					[
@@ -1297,7 +1297,7 @@  discard block
 block discarded – undo
1297 1297
 			} else {
1298 1298
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1299 1299
 
1300
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1300
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int) $calendarId, $subscriptionRow, [], $data));
1301 1301
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1302 1302
 					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1303 1303
 					[
@@ -1569,7 +1569,7 @@  discard block
 block discarded – undo
1569 1569
 
1570 1570
 		$result = [];
1571 1571
 		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1572
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1572
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1573 1573
 			if (!in_array($path, $result)) {
1574 1574
 				$result[] = $path;
1575 1575
 			}
@@ -1617,8 +1617,8 @@  discard block
 block discarded – undo
1617 1617
 
1618 1618
 		if ($pattern !== '') {
1619 1619
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1620
-				$outerQuery->createNamedParameter('%' .
1621
-					$this->db->escapeLikeParameter($pattern) . '%')));
1620
+				$outerQuery->createNamedParameter('%'.
1621
+					$this->db->escapeLikeParameter($pattern).'%')));
1622 1622
 		}
1623 1623
 
1624 1624
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1657,7 +1657,7 @@  discard block
 block discarded – undo
1657 1657
 		$result = $outerQuery->execute();
1658 1658
 		$calendarObjects = $result->fetchAll();
1659 1659
 
1660
-		return array_map(function ($o) {
1660
+		return array_map(function($o) {
1661 1661
 			$calendarData = Reader::read($o['calendardata']);
1662 1662
 			$comps = $calendarData->getComponents();
1663 1663
 			$objects = [];
@@ -1675,10 +1675,10 @@  discard block
 block discarded – undo
1675 1675
 				'type' => $o['componenttype'],
1676 1676
 				'uid' => $o['uid'],
1677 1677
 				'uri' => $o['uri'],
1678
-				'objects' => array_map(function ($c) {
1678
+				'objects' => array_map(function($c) {
1679 1679
 					return $this->transformSearchData($c);
1680 1680
 				}, $objects),
1681
-				'timezones' => array_map(function ($c) {
1681
+				'timezones' => array_map(function($c) {
1682 1682
 					return $this->transformSearchData($c);
1683 1683
 				}, $timezones),
1684 1684
 			];
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
 		/** @var Component[] $subComponents */
1695 1695
 		$subComponents = $comp->getComponents();
1696 1696
 		/** @var Property[] $properties */
1697
-		$properties = array_filter($comp->children(), function ($c) {
1697
+		$properties = array_filter($comp->children(), function($c) {
1698 1698
 			return $c instanceof Property;
1699 1699
 		});
1700 1700
 		$validationRules = $comp->getValidationRules();
@@ -1772,7 +1772,7 @@  discard block
 block discarded – undo
1772 1772
 		$subscriptions = $this->getSubscriptionsForUser($principalUri);
1773 1773
 		foreach ($calendars as $calendar) {
1774 1774
 			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
1775
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1775
+			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])));
1776 1776
 			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1777 1777
 
1778 1778
 			// If it's shared, limit search to public events
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
 		}
1786 1786
 		foreach ($subscriptions as $subscription) {
1787 1787
 			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1788
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1788
+			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])));
1789 1789
 			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1790 1790
 
1791 1791
 			// If it's shared, limit search to public events
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
 			if (!$escapePattern) {
1831 1831
 				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1832 1832
 			} else {
1833
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1833
+				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
1834 1834
 			}
1835 1835
 		}
1836 1836
 
@@ -1844,7 +1844,7 @@  discard block
 block discarded – undo
1844 1844
 		$result = $calendarObjectIdQuery->execute();
1845 1845
 		$matches = $result->fetchAll();
1846 1846
 		$result->closeCursor();
1847
-		$matches = array_map(static function (array $match):int {
1847
+		$matches = array_map(static function(array $match):int {
1848 1848
 			return (int) $match['objectid'];
1849 1849
 		}, $matches);
1850 1850
 
@@ -1857,9 +1857,9 @@  discard block
 block discarded – undo
1857 1857
 		$calendarObjects = $result->fetchAll();
1858 1858
 		$result->closeCursor();
1859 1859
 
1860
-		return array_map(function (array $array): array {
1861
-			$array['calendarid'] = (int)$array['calendarid'];
1862
-			$array['calendartype'] = (int)$array['calendartype'];
1860
+		return array_map(function(array $array): array {
1861
+			$array['calendarid'] = (int) $array['calendarid'];
1862
+			$array['calendartype'] = (int) $array['calendartype'];
1863 1863
 			$array['calendardata'] = $this->readBlob($array['calendardata']);
1864 1864
 
1865 1865
 			return $array;
@@ -1896,7 +1896,7 @@  discard block
 block discarded – undo
1896 1896
 		$stmt = $query->execute();
1897 1897
 
1898 1898
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1899
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1899
+			return $row['calendaruri'].'/'.$row['objecturi'];
1900 1900
 		}
1901 1901
 
1902 1902
 		return null;
@@ -2096,8 +2096,8 @@  discard block
 block discarded – undo
2096 2096
 				'source' => $row['source'],
2097 2097
 				'lastmodified' => $row['lastmodified'],
2098 2098
 
2099
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2100
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2099
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2100
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
2101 2101
 			];
2102 2102
 
2103 2103
 			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -2192,7 +2192,7 @@  discard block
 block discarded – undo
2192 2192
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2193 2193
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2194 2194
 
2195
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2195
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2196 2196
 			$newValues = [];
2197 2197
 
2198 2198
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2214,7 +2214,7 @@  discard block
 block discarded – undo
2214 2214
 				->execute();
2215 2215
 
2216 2216
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2217
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2217
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2218 2218
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2219 2219
 				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2220 2220
 				[
@@ -2265,7 +2265,7 @@  discard block
 block discarded – undo
2265 2265
 			->execute();
2266 2266
 
2267 2267
 		if ($subscriptionRow) {
2268
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2268
+			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2269 2269
 		}
2270 2270
 	}
2271 2271
 
@@ -2303,8 +2303,8 @@  discard block
 block discarded – undo
2303 2303
 			'uri' => $row['uri'],
2304 2304
 			'calendardata' => $row['calendardata'],
2305 2305
 			'lastmodified' => $row['lastmodified'],
2306
-			'etag' => '"' . $row['etag'] . '"',
2307
-			'size' => (int)$row['size'],
2306
+			'etag' => '"'.$row['etag'].'"',
2307
+			'size' => (int) $row['size'],
2308 2308
 		];
2309 2309
 	}
2310 2310
 
@@ -2332,8 +2332,8 @@  discard block
 block discarded – undo
2332 2332
 				'calendardata' => $row['calendardata'],
2333 2333
 				'uri' => $row['uri'],
2334 2334
 				'lastmodified' => $row['lastmodified'],
2335
-				'etag' => '"' . $row['etag'] . '"',
2336
-				'size' => (int)$row['size'],
2335
+				'etag' => '"'.$row['etag'].'"',
2336
+				'size' => (int) $row['size'],
2337 2337
 			];
2338 2338
 		}
2339 2339
 
@@ -2387,14 +2387,14 @@  discard block
 block discarded – undo
2387 2387
 	 * @return void
2388 2388
 	 */
2389 2389
 	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2390
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2390
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2391 2391
 
2392 2392
 		$query = $this->db->getQueryBuilder();
2393 2393
 		$query->select('synctoken')
2394 2394
 			->from($table)
2395 2395
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2396 2396
 		$result = $query->execute();
2397
-		$syncToken = (int)$result->fetchOne();
2397
+		$syncToken = (int) $result->fetchOne();
2398 2398
 		$result->closeCursor();
2399 2399
 
2400 2400
 		$query = $this->db->getQueryBuilder();
@@ -2451,7 +2451,7 @@  discard block
 block discarded – undo
2451 2451
 				// Track first component type and uid
2452 2452
 				if ($uid === null) {
2453 2453
 					$componentType = $component->name;
2454
-					$uid = (string)$component->UID;
2454
+					$uid = (string) $component->UID;
2455 2455
 				}
2456 2456
 			}
2457 2457
 		}
@@ -2550,7 +2550,7 @@  discard block
 block discarded – undo
2550 2550
 			]));
2551 2551
 		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2552 2552
 
2553
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2553
+		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int) $calendarId, $calendarRow, $oldShares, $add, $remove));
2554 2554
 	}
2555 2555
 
2556 2556
 	/**
@@ -2591,7 +2591,7 @@  discard block
 block discarded – undo
2591 2591
 				]);
2592 2592
 			$query->execute();
2593 2593
 
2594
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2594
+			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int) $calendarId, $calendarData, $publicUri));
2595 2595
 			return $publicUri;
2596 2596
 		}
2597 2597
 		$query->delete('dav_shares')
@@ -2599,7 +2599,7 @@  discard block
 block discarded – undo
2599 2599
 			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2600 2600
 		$query->execute();
2601 2601
 
2602
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2602
+		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int) $calendarId, $calendarData));
2603 2603
 		return null;
2604 2604
 	}
2605 2605
 
@@ -2822,10 +2822,10 @@  discard block
 block discarded – undo
2822 2822
 		$result->closeCursor();
2823 2823
 
2824 2824
 		if (!isset($objectIds['id'])) {
2825
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2825
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2826 2826
 		}
2827 2827
 
2828
-		return (int)$objectIds['id'];
2828
+		return (int) $objectIds['id'];
2829 2829
 	}
2830 2830
 
2831 2831
 	/**
@@ -2852,8 +2852,8 @@  discard block
 block discarded – undo
2852 2852
 	 * @param $calendarInfo
2853 2853
 	 */
2854 2854
 	private function addOwnerPrincipal(&$calendarInfo) {
2855
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2856
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2855
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2856
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2857 2857
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2858 2858
 			$uri = $calendarInfo[$ownerPrincipalKey];
2859 2859
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/AppInfo/Application.php 1 patch
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -81,333 +81,333 @@
 block discarded – undo
81 81
 use function strpos;
82 82
 
83 83
 class Application extends App implements IBootstrap {
84
-	public const APP_ID = 'dav';
84
+    public const APP_ID = 'dav';
85 85
 
86
-	public function __construct() {
87
-		parent::__construct(self::APP_ID);
88
-	}
86
+    public function __construct() {
87
+        parent::__construct(self::APP_ID);
88
+    }
89 89
 
90
-	public function register(IRegistrationContext $context): void {
91
-		$context->registerServiceAlias('CardDAVSyncService', SyncService::class);
92
-		$context->registerService(PhotoCache::class, function (ContainerInterface $c) {
93
-			/** @var IServerContainer $server */
94
-			$server = $c->get(IServerContainer::class);
90
+    public function register(IRegistrationContext $context): void {
91
+        $context->registerServiceAlias('CardDAVSyncService', SyncService::class);
92
+        $context->registerService(PhotoCache::class, function (ContainerInterface $c) {
93
+            /** @var IServerContainer $server */
94
+            $server = $c->get(IServerContainer::class);
95 95
 
96
-			return new PhotoCache(
97
-				$server->getAppDataDir('dav-photocache'),
98
-				$c->get(ILogger::class)
99
-			);
100
-		});
96
+            return new PhotoCache(
97
+                $server->getAppDataDir('dav-photocache'),
98
+                $c->get(ILogger::class)
99
+            );
100
+        });
101 101
 
102
-		/*
102
+        /*
103 103
 		 * Register capabilities
104 104
 		 */
105
-		$context->registerCapability(Capabilities::class);
105
+        $context->registerCapability(Capabilities::class);
106 106
 
107
-		/*
107
+        /*
108 108
 		 * Register Search Providers
109 109
 		 */
110
-		$context->registerSearchProvider(ContactsSearchProvider::class);
111
-		$context->registerSearchProvider(EventsSearchProvider::class);
112
-		$context->registerSearchProvider(TasksSearchProvider::class);
113
-
114
-		/**
115
-		 * Register event listeners
116
-		 */
117
-		$context->registerEventListener(CalendarObjectCreatedEvent::class, CalendarContactInteractionListener::class);
118
-		$context->registerEventListener(CalendarObjectUpdatedEvent::class, CalendarContactInteractionListener::class);
119
-		$context->registerEventListener(CalendarShareUpdatedEvent::class, CalendarContactInteractionListener::class);
120
-	}
121
-
122
-	public function boot(IBootContext $context): void {
123
-		// Load all dav apps
124
-		\OC_App::loadApps(['dav']);
125
-
126
-		$context->injectFn([$this, 'registerHooks']);
127
-		$context->injectFn([$this, 'registerContactsManager']);
128
-		$context->injectFn([$this, 'registerCalendarManager']);
129
-		$context->injectFn([$this, 'registerNotifier']);
130
-		$context->injectFn([$this, 'registerCalendarReminders']);
131
-	}
132
-
133
-	public function registerHooks(HookManager $hm,
134
-								   EventDispatcherInterface $dispatcher,
135
-								   IAppContainer $container,
136
-								   IServerContainer $serverContainer) {
137
-		$hm->setup();
138
-
139
-		// first time login event setup
140
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
141
-			if ($event instanceof GenericEvent) {
142
-				$hm->firstLogin($event->getSubject());
143
-			}
144
-		});
145
-
146
-		$birthdayListener = function ($event) use ($container): void {
147
-			if ($event instanceof GenericEvent) {
148
-				/** @var BirthdayService $b */
149
-				$b = $container->query(BirthdayService::class);
150
-				$b->onCardChanged(
151
-					(int) $event->getArgument('addressBookId'),
152
-					(string) $event->getArgument('cardUri'),
153
-					(string) $event->getArgument('cardData')
154
-				);
155
-			}
156
-		};
157
-
158
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $birthdayListener);
159
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $birthdayListener);
160
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function ($event) use ($container) {
161
-			if ($event instanceof GenericEvent) {
162
-				/** @var BirthdayService $b */
163
-				$b = $container->query(BirthdayService::class);
164
-				$b->onCardDeleted(
165
-					(int) $event->getArgument('addressBookId'),
166
-					(string) $event->getArgument('cardUri')
167
-				);
168
-			}
169
-		});
170
-
171
-		$clearPhotoCache = function ($event) use ($container): void {
172
-			if ($event instanceof GenericEvent) {
173
-				/** @var PhotoCache $p */
174
-				$p = $container->query(PhotoCache::class);
175
-				$p->delete(
176
-					$event->getArgument('addressBookId'),
177
-					$event->getArgument('cardUri')
178
-				);
179
-			}
180
-		};
181
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $clearPhotoCache);
182
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $clearPhotoCache);
183
-
184
-		$dispatcher->addListener('OC\AccountManager::userUpdated', function (GenericEvent $event) use ($container) {
185
-			$user = $event->getSubject();
186
-			/** @var SyncService $syncService */
187
-			$syncService = $container->query(SyncService::class);
188
-			$syncService->updateUser($user);
189
-		});
190
-
191
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function (GenericEvent $event) use ($container) {
192
-			/** @var Backend $backend */
193
-			$backend = $container->query(Backend::class);
194
-			$backend->onCalendarAdd(
195
-				$event->getArgument('calendarData')
196
-			);
197
-		});
198
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function (GenericEvent $event) use ($container) {
199
-			/** @var Backend $backend */
200
-			$backend = $container->query(Backend::class);
201
-			$backend->onCalendarUpdate(
202
-				$event->getArgument('calendarData'),
203
-				$event->getArgument('shares'),
204
-				$event->getArgument('propertyMutations')
205
-			);
206
-		});
207
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function (GenericEvent $event) use ($container) {
208
-			/** @var Backend $backend */
209
-			$backend = $container->query(Backend::class);
210
-			$backend->onCalendarDelete(
211
-				$event->getArgument('calendarData'),
212
-				$event->getArgument('shares')
213
-			);
214
-
215
-			/** @var ReminderBackend $reminderBackend */
216
-			$reminderBackend = $container->query(ReminderBackend::class);
217
-			$reminderBackend->cleanRemindersForCalendar(
218
-				(int) $event->getArgument('calendarId')
219
-			);
220
-		});
221
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function (GenericEvent $event) use ($container) {
222
-			/** @var Backend $backend */
223
-			$backend = $container->query(Backend::class);
224
-			$backend->onCalendarUpdateShares(
225
-				$event->getArgument('calendarData'),
226
-				$event->getArgument('shares'),
227
-				$event->getArgument('add'),
228
-				$event->getArgument('remove')
229
-			);
230
-
231
-			// Here we should recalculate if reminders should be sent to new or old sharees
232
-		});
233
-
234
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', function (GenericEvent $event) use ($container) {
235
-			/** @var Backend $backend */
236
-			$backend = $container->query(Backend::class);
237
-			$backend->onCalendarPublication(
238
-				$event->getArgument('calendarData'),
239
-				$event->getArgument('public')
240
-			);
241
-		});
242
-
243
-		$listener = function (GenericEvent $event, $eventName) use ($container): void {
244
-			/** @var Backend $backend */
245
-			$backend = $container->query(Backend::class);
246
-
247
-			$subject = Event::SUBJECT_OBJECT_ADD;
248
-			if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
249
-				$subject = Event::SUBJECT_OBJECT_UPDATE;
250
-			} elseif ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
251
-				$subject = Event::SUBJECT_OBJECT_DELETE;
252
-			}
253
-			$backend->onTouchCalendarObject(
254
-				$subject,
255
-				$event->getArgument('calendarData'),
256
-				$event->getArgument('shares'),
257
-				$event->getArgument('objectData')
258
-			);
259
-
260
-			/** @var ReminderService $reminderBackend */
261
-			$reminderService = $container->query(ReminderService::class);
262
-
263
-			$reminderService->onTouchCalendarObject(
264
-				$eventName,
265
-				$event->getArgument('objectData')
266
-			);
267
-		};
268
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
269
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
270
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
271
-
272
-		/**
273
-		 * In case the user has set their default calendar to this one
274
-		 */
275
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function (GenericEvent $event) use ($serverContainer) {
276
-			/** @var IConfig $config */
277
-			$config = $serverContainer->getConfig();
278
-			$principalUri = $event->getArgument('calendarData')['principaluri'];
279
-			if (strpos($principalUri, 'principals/users') === 0) {
280
-				[, $UID] = \Sabre\Uri\split($principalUri);
281
-				$uri = $event->getArgument('calendarData')['uri'];
282
-				if ($config->getUserValue($UID, 'dav', 'defaultCalendar') === $uri) {
283
-					$config->deleteUserValue($UID, 'dav', 'defaultCalendar');
284
-				}
285
-			}
286
-		});
287
-
288
-		$dispatcher->addListener('OCP\Federation\TrustedServerEvent::remove',
289
-			function (GenericEvent $event) {
290
-				/** @var CardDavBackend $cardDavBackend */
291
-				$cardDavBackend = \OC::$server->query(CardDavBackend::class);
292
-				$addressBookUri = $event->getSubject();
293
-				$addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
294
-				if (!is_null($addressBook)) {
295
-					$cardDavBackend->deleteAddressBook($addressBook['id']);
296
-				}
297
-			}
298
-		);
299
-
300
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
301
-			function (GenericEvent $event) use ($container, $serverContainer) {
302
-				$jobList = $serverContainer->getJobList();
303
-				$subscriptionData = $event->getArgument('subscriptionData');
304
-
305
-				/**
306
-				 * Initial subscription refetch
307
-				 *
308
-				 * @var RefreshWebcalService $refreshWebcalService
309
-				 */
310
-				$refreshWebcalService = $container->query(RefreshWebcalService::class);
311
-				$refreshWebcalService->refreshSubscription(
312
-					(string) $subscriptionData['principaluri'],
313
-					(string) $subscriptionData['uri']
314
-				);
315
-
316
-				$jobList->add(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
317
-					'principaluri' => $subscriptionData['principaluri'],
318
-					'uri' => $subscriptionData['uri']
319
-				]);
320
-			}
321
-		);
322
-
323
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
324
-			function (GenericEvent $event) use ($container, $serverContainer) {
325
-				$jobList = $serverContainer->getJobList();
326
-				$subscriptionData = $event->getArgument('subscriptionData');
327
-
328
-				$jobList->remove(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
329
-					'principaluri' => $subscriptionData['principaluri'],
330
-					'uri' => $subscriptionData['uri']
331
-				]);
332
-
333
-				/** @var CalDavBackend $calDavBackend */
334
-				$calDavBackend = $container->query(CalDavBackend::class);
335
-				$calDavBackend->purgeAllCachedEventsForSubscription($subscriptionData['id']);
336
-			}
337
-		);
338
-
339
-		$eventHandler = function () use ($container, $serverContainer): void {
340
-			try {
341
-				/** @var UpdateCalendarResourcesRoomsBackgroundJob $job */
342
-				$job = $container->query(UpdateCalendarResourcesRoomsBackgroundJob::class);
343
-				$job->run([]);
344
-				$serverContainer->getJobList()->setLastRun($job);
345
-			} catch (Exception $ex) {
346
-				$serverContainer->getLogger()->logException($ex);
347
-			}
348
-		};
349
-
350
-		$dispatcher->addListener('\OCP\Calendar\Resource\ForceRefreshEvent', $eventHandler);
351
-		$dispatcher->addListener('\OCP\Calendar\Room\ForceRefreshEvent', $eventHandler);
352
-	}
353
-
354
-	public function registerContactsManager(IContactsManager $cm, IAppContainer $container): void {
355
-		$cm->register(function () use ($container, $cm): void {
356
-			$user = \OC::$server->getUserSession()->getUser();
357
-			if (!is_null($user)) {
358
-				$this->setupContactsProvider($cm, $container, $user->getUID());
359
-			} else {
360
-				$this->setupSystemContactsProvider($cm, $container);
361
-			}
362
-		});
363
-	}
364
-
365
-	private function setupContactsProvider(IContactsManager $contactsManager,
366
-										   IAppContainer $container,
367
-										   string $userID): void {
368
-		/** @var ContactsManager $cm */
369
-		$cm = $container->query(ContactsManager::class);
370
-		$urlGenerator = $container->getServer()->getURLGenerator();
371
-		$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
372
-	}
373
-
374
-	private function setupSystemContactsProvider(IContactsManager $contactsManager,
375
-												 IAppContainer $container): void {
376
-		/** @var ContactsManager $cm */
377
-		$cm = $container->query(ContactsManager::class);
378
-		$urlGenerator = $container->getServer()->getURLGenerator();
379
-		$cm->setupSystemContactsProvider($contactsManager, $urlGenerator);
380
-	}
381
-
382
-	public function registerCalendarManager(ICalendarManager $calendarManager,
383
-											 IAppContainer $container): void {
384
-		$calendarManager->register(function () use ($container, $calendarManager) {
385
-			$user = \OC::$server->getUserSession()->getUser();
386
-			if ($user !== null) {
387
-				$this->setupCalendarProvider($calendarManager, $container, $user->getUID());
388
-			}
389
-		});
390
-	}
391
-
392
-	private function setupCalendarProvider(ICalendarManager $calendarManager,
393
-										   IAppContainer $container,
394
-										   $userId) {
395
-		$cm = $container->query(CalendarManager::class);
396
-		$cm->setupCalendarProvider($calendarManager, $userId);
397
-	}
398
-
399
-	public function registerNotifier(INotificationManager $manager): void {
400
-		$manager->registerNotifierService(Notifier::class);
401
-	}
402
-
403
-	public function registerCalendarReminders(NotificationProviderManager $manager,
404
-											   ILogger $logger): void {
405
-		try {
406
-			$manager->registerProvider(AudioProvider::class);
407
-			$manager->registerProvider(EmailProvider::class);
408
-			$manager->registerProvider(PushProvider::class);
409
-		} catch (Throwable $ex) {
410
-			$logger->logException($ex);
411
-		}
412
-	}
110
+        $context->registerSearchProvider(ContactsSearchProvider::class);
111
+        $context->registerSearchProvider(EventsSearchProvider::class);
112
+        $context->registerSearchProvider(TasksSearchProvider::class);
113
+
114
+        /**
115
+         * Register event listeners
116
+         */
117
+        $context->registerEventListener(CalendarObjectCreatedEvent::class, CalendarContactInteractionListener::class);
118
+        $context->registerEventListener(CalendarObjectUpdatedEvent::class, CalendarContactInteractionListener::class);
119
+        $context->registerEventListener(CalendarShareUpdatedEvent::class, CalendarContactInteractionListener::class);
120
+    }
121
+
122
+    public function boot(IBootContext $context): void {
123
+        // Load all dav apps
124
+        \OC_App::loadApps(['dav']);
125
+
126
+        $context->injectFn([$this, 'registerHooks']);
127
+        $context->injectFn([$this, 'registerContactsManager']);
128
+        $context->injectFn([$this, 'registerCalendarManager']);
129
+        $context->injectFn([$this, 'registerNotifier']);
130
+        $context->injectFn([$this, 'registerCalendarReminders']);
131
+    }
132
+
133
+    public function registerHooks(HookManager $hm,
134
+                                    EventDispatcherInterface $dispatcher,
135
+                                    IAppContainer $container,
136
+                                    IServerContainer $serverContainer) {
137
+        $hm->setup();
138
+
139
+        // first time login event setup
140
+        $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
141
+            if ($event instanceof GenericEvent) {
142
+                $hm->firstLogin($event->getSubject());
143
+            }
144
+        });
145
+
146
+        $birthdayListener = function ($event) use ($container): void {
147
+            if ($event instanceof GenericEvent) {
148
+                /** @var BirthdayService $b */
149
+                $b = $container->query(BirthdayService::class);
150
+                $b->onCardChanged(
151
+                    (int) $event->getArgument('addressBookId'),
152
+                    (string) $event->getArgument('cardUri'),
153
+                    (string) $event->getArgument('cardData')
154
+                );
155
+            }
156
+        };
157
+
158
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $birthdayListener);
159
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $birthdayListener);
160
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function ($event) use ($container) {
161
+            if ($event instanceof GenericEvent) {
162
+                /** @var BirthdayService $b */
163
+                $b = $container->query(BirthdayService::class);
164
+                $b->onCardDeleted(
165
+                    (int) $event->getArgument('addressBookId'),
166
+                    (string) $event->getArgument('cardUri')
167
+                );
168
+            }
169
+        });
170
+
171
+        $clearPhotoCache = function ($event) use ($container): void {
172
+            if ($event instanceof GenericEvent) {
173
+                /** @var PhotoCache $p */
174
+                $p = $container->query(PhotoCache::class);
175
+                $p->delete(
176
+                    $event->getArgument('addressBookId'),
177
+                    $event->getArgument('cardUri')
178
+                );
179
+            }
180
+        };
181
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $clearPhotoCache);
182
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $clearPhotoCache);
183
+
184
+        $dispatcher->addListener('OC\AccountManager::userUpdated', function (GenericEvent $event) use ($container) {
185
+            $user = $event->getSubject();
186
+            /** @var SyncService $syncService */
187
+            $syncService = $container->query(SyncService::class);
188
+            $syncService->updateUser($user);
189
+        });
190
+
191
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function (GenericEvent $event) use ($container) {
192
+            /** @var Backend $backend */
193
+            $backend = $container->query(Backend::class);
194
+            $backend->onCalendarAdd(
195
+                $event->getArgument('calendarData')
196
+            );
197
+        });
198
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function (GenericEvent $event) use ($container) {
199
+            /** @var Backend $backend */
200
+            $backend = $container->query(Backend::class);
201
+            $backend->onCalendarUpdate(
202
+                $event->getArgument('calendarData'),
203
+                $event->getArgument('shares'),
204
+                $event->getArgument('propertyMutations')
205
+            );
206
+        });
207
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function (GenericEvent $event) use ($container) {
208
+            /** @var Backend $backend */
209
+            $backend = $container->query(Backend::class);
210
+            $backend->onCalendarDelete(
211
+                $event->getArgument('calendarData'),
212
+                $event->getArgument('shares')
213
+            );
214
+
215
+            /** @var ReminderBackend $reminderBackend */
216
+            $reminderBackend = $container->query(ReminderBackend::class);
217
+            $reminderBackend->cleanRemindersForCalendar(
218
+                (int) $event->getArgument('calendarId')
219
+            );
220
+        });
221
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function (GenericEvent $event) use ($container) {
222
+            /** @var Backend $backend */
223
+            $backend = $container->query(Backend::class);
224
+            $backend->onCalendarUpdateShares(
225
+                $event->getArgument('calendarData'),
226
+                $event->getArgument('shares'),
227
+                $event->getArgument('add'),
228
+                $event->getArgument('remove')
229
+            );
230
+
231
+            // Here we should recalculate if reminders should be sent to new or old sharees
232
+        });
233
+
234
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', function (GenericEvent $event) use ($container) {
235
+            /** @var Backend $backend */
236
+            $backend = $container->query(Backend::class);
237
+            $backend->onCalendarPublication(
238
+                $event->getArgument('calendarData'),
239
+                $event->getArgument('public')
240
+            );
241
+        });
242
+
243
+        $listener = function (GenericEvent $event, $eventName) use ($container): void {
244
+            /** @var Backend $backend */
245
+            $backend = $container->query(Backend::class);
246
+
247
+            $subject = Event::SUBJECT_OBJECT_ADD;
248
+            if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
249
+                $subject = Event::SUBJECT_OBJECT_UPDATE;
250
+            } elseif ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
251
+                $subject = Event::SUBJECT_OBJECT_DELETE;
252
+            }
253
+            $backend->onTouchCalendarObject(
254
+                $subject,
255
+                $event->getArgument('calendarData'),
256
+                $event->getArgument('shares'),
257
+                $event->getArgument('objectData')
258
+            );
259
+
260
+            /** @var ReminderService $reminderBackend */
261
+            $reminderService = $container->query(ReminderService::class);
262
+
263
+            $reminderService->onTouchCalendarObject(
264
+                $eventName,
265
+                $event->getArgument('objectData')
266
+            );
267
+        };
268
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
269
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
270
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
271
+
272
+        /**
273
+         * In case the user has set their default calendar to this one
274
+         */
275
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function (GenericEvent $event) use ($serverContainer) {
276
+            /** @var IConfig $config */
277
+            $config = $serverContainer->getConfig();
278
+            $principalUri = $event->getArgument('calendarData')['principaluri'];
279
+            if (strpos($principalUri, 'principals/users') === 0) {
280
+                [, $UID] = \Sabre\Uri\split($principalUri);
281
+                $uri = $event->getArgument('calendarData')['uri'];
282
+                if ($config->getUserValue($UID, 'dav', 'defaultCalendar') === $uri) {
283
+                    $config->deleteUserValue($UID, 'dav', 'defaultCalendar');
284
+                }
285
+            }
286
+        });
287
+
288
+        $dispatcher->addListener('OCP\Federation\TrustedServerEvent::remove',
289
+            function (GenericEvent $event) {
290
+                /** @var CardDavBackend $cardDavBackend */
291
+                $cardDavBackend = \OC::$server->query(CardDavBackend::class);
292
+                $addressBookUri = $event->getSubject();
293
+                $addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri);
294
+                if (!is_null($addressBook)) {
295
+                    $cardDavBackend->deleteAddressBook($addressBook['id']);
296
+                }
297
+            }
298
+        );
299
+
300
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
301
+            function (GenericEvent $event) use ($container, $serverContainer) {
302
+                $jobList = $serverContainer->getJobList();
303
+                $subscriptionData = $event->getArgument('subscriptionData');
304
+
305
+                /**
306
+                 * Initial subscription refetch
307
+                 *
308
+                 * @var RefreshWebcalService $refreshWebcalService
309
+                 */
310
+                $refreshWebcalService = $container->query(RefreshWebcalService::class);
311
+                $refreshWebcalService->refreshSubscription(
312
+                    (string) $subscriptionData['principaluri'],
313
+                    (string) $subscriptionData['uri']
314
+                );
315
+
316
+                $jobList->add(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
317
+                    'principaluri' => $subscriptionData['principaluri'],
318
+                    'uri' => $subscriptionData['uri']
319
+                ]);
320
+            }
321
+        );
322
+
323
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
324
+            function (GenericEvent $event) use ($container, $serverContainer) {
325
+                $jobList = $serverContainer->getJobList();
326
+                $subscriptionData = $event->getArgument('subscriptionData');
327
+
328
+                $jobList->remove(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [
329
+                    'principaluri' => $subscriptionData['principaluri'],
330
+                    'uri' => $subscriptionData['uri']
331
+                ]);
332
+
333
+                /** @var CalDavBackend $calDavBackend */
334
+                $calDavBackend = $container->query(CalDavBackend::class);
335
+                $calDavBackend->purgeAllCachedEventsForSubscription($subscriptionData['id']);
336
+            }
337
+        );
338
+
339
+        $eventHandler = function () use ($container, $serverContainer): void {
340
+            try {
341
+                /** @var UpdateCalendarResourcesRoomsBackgroundJob $job */
342
+                $job = $container->query(UpdateCalendarResourcesRoomsBackgroundJob::class);
343
+                $job->run([]);
344
+                $serverContainer->getJobList()->setLastRun($job);
345
+            } catch (Exception $ex) {
346
+                $serverContainer->getLogger()->logException($ex);
347
+            }
348
+        };
349
+
350
+        $dispatcher->addListener('\OCP\Calendar\Resource\ForceRefreshEvent', $eventHandler);
351
+        $dispatcher->addListener('\OCP\Calendar\Room\ForceRefreshEvent', $eventHandler);
352
+    }
353
+
354
+    public function registerContactsManager(IContactsManager $cm, IAppContainer $container): void {
355
+        $cm->register(function () use ($container, $cm): void {
356
+            $user = \OC::$server->getUserSession()->getUser();
357
+            if (!is_null($user)) {
358
+                $this->setupContactsProvider($cm, $container, $user->getUID());
359
+            } else {
360
+                $this->setupSystemContactsProvider($cm, $container);
361
+            }
362
+        });
363
+    }
364
+
365
+    private function setupContactsProvider(IContactsManager $contactsManager,
366
+                                            IAppContainer $container,
367
+                                            string $userID): void {
368
+        /** @var ContactsManager $cm */
369
+        $cm = $container->query(ContactsManager::class);
370
+        $urlGenerator = $container->getServer()->getURLGenerator();
371
+        $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
372
+    }
373
+
374
+    private function setupSystemContactsProvider(IContactsManager $contactsManager,
375
+                                                    IAppContainer $container): void {
376
+        /** @var ContactsManager $cm */
377
+        $cm = $container->query(ContactsManager::class);
378
+        $urlGenerator = $container->getServer()->getURLGenerator();
379
+        $cm->setupSystemContactsProvider($contactsManager, $urlGenerator);
380
+    }
381
+
382
+    public function registerCalendarManager(ICalendarManager $calendarManager,
383
+                                                IAppContainer $container): void {
384
+        $calendarManager->register(function () use ($container, $calendarManager) {
385
+            $user = \OC::$server->getUserSession()->getUser();
386
+            if ($user !== null) {
387
+                $this->setupCalendarProvider($calendarManager, $container, $user->getUID());
388
+            }
389
+        });
390
+    }
391
+
392
+    private function setupCalendarProvider(ICalendarManager $calendarManager,
393
+                                            IAppContainer $container,
394
+                                            $userId) {
395
+        $cm = $container->query(CalendarManager::class);
396
+        $cm->setupCalendarProvider($calendarManager, $userId);
397
+    }
398
+
399
+    public function registerNotifier(INotificationManager $manager): void {
400
+        $manager->registerNotifierService(Notifier::class);
401
+    }
402
+
403
+    public function registerCalendarReminders(NotificationProviderManager $manager,
404
+                                                ILogger $logger): void {
405
+        try {
406
+            $manager->registerProvider(AudioProvider::class);
407
+            $manager->registerProvider(EmailProvider::class);
408
+            $manager->registerProvider(PushProvider::class);
409
+        } catch (Throwable $ex) {
410
+            $logger->logException($ex);
411
+        }
412
+    }
413 413
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 2 patches
Indentation   +1061 added lines, -1061 removed lines patch added patch discarded remove patch
@@ -61,1075 +61,1075 @@
 block discarded – undo
61 61
  * @package OCA\FederatedFileSharing
62 62
  */
63 63
 class FederatedShareProvider implements IShareProvider {
64
-	public const SHARE_TYPE_REMOTE = 6;
65
-
66
-	/** @var IDBConnection */
67
-	private $dbConnection;
68
-
69
-	/** @var AddressHandler */
70
-	private $addressHandler;
71
-
72
-	/** @var Notifications */
73
-	private $notifications;
74
-
75
-	/** @var TokenHandler */
76
-	private $tokenHandler;
77
-
78
-	/** @var IL10N */
79
-	private $l;
80
-
81
-	/** @var ILogger */
82
-	private $logger;
83
-
84
-	/** @var IRootFolder */
85
-	private $rootFolder;
86
-
87
-	/** @var IConfig */
88
-	private $config;
89
-
90
-	/** @var string */
91
-	private $externalShareTable = 'share_external';
92
-
93
-	/** @var IUserManager */
94
-	private $userManager;
95
-
96
-	/** @var ICloudIdManager */
97
-	private $cloudIdManager;
98
-
99
-	/** @var \OCP\GlobalScale\IConfig */
100
-	private $gsConfig;
101
-
102
-	/** @var ICloudFederationProviderManager */
103
-	private $cloudFederationProviderManager;
104
-
105
-	/** @var array list of supported share types */
106
-	private $supportedShareType = [IShare::TYPE_REMOTE_GROUP, IShare::TYPE_REMOTE, IShare::TYPE_CIRCLE];
107
-
108
-	/**
109
-	 * DefaultShareProvider constructor.
110
-	 *
111
-	 * @param IDBConnection $connection
112
-	 * @param AddressHandler $addressHandler
113
-	 * @param Notifications $notifications
114
-	 * @param TokenHandler $tokenHandler
115
-	 * @param IL10N $l10n
116
-	 * @param ILogger $logger
117
-	 * @param IRootFolder $rootFolder
118
-	 * @param IConfig $config
119
-	 * @param IUserManager $userManager
120
-	 * @param ICloudIdManager $cloudIdManager
121
-	 * @param \OCP\GlobalScale\IConfig $globalScaleConfig
122
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
123
-	 */
124
-	public function __construct(
125
-			IDBConnection $connection,
126
-			AddressHandler $addressHandler,
127
-			Notifications $notifications,
128
-			TokenHandler $tokenHandler,
129
-			IL10N $l10n,
130
-			ILogger $logger,
131
-			IRootFolder $rootFolder,
132
-			IConfig $config,
133
-			IUserManager $userManager,
134
-			ICloudIdManager $cloudIdManager,
135
-			\OCP\GlobalScale\IConfig $globalScaleConfig,
136
-			ICloudFederationProviderManager $cloudFederationProviderManager
137
-	) {
138
-		$this->dbConnection = $connection;
139
-		$this->addressHandler = $addressHandler;
140
-		$this->notifications = $notifications;
141
-		$this->tokenHandler = $tokenHandler;
142
-		$this->l = $l10n;
143
-		$this->logger = $logger;
144
-		$this->rootFolder = $rootFolder;
145
-		$this->config = $config;
146
-		$this->userManager = $userManager;
147
-		$this->cloudIdManager = $cloudIdManager;
148
-		$this->gsConfig = $globalScaleConfig;
149
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
150
-	}
151
-
152
-	/**
153
-	 * Return the identifier of this provider.
154
-	 *
155
-	 * @return string Containing only [a-zA-Z0-9]
156
-	 */
157
-	public function identifier() {
158
-		return 'ocFederatedSharing';
159
-	}
160
-
161
-	/**
162
-	 * Share a path
163
-	 *
164
-	 * @param IShare $share
165
-	 * @return IShare The share object
166
-	 * @throws ShareNotFound
167
-	 * @throws \Exception
168
-	 */
169
-	public function create(IShare $share) {
170
-		$shareWith = $share->getSharedWith();
171
-		$itemSource = $share->getNodeId();
172
-		$itemType = $share->getNodeType();
173
-		$permissions = $share->getPermissions();
174
-		$sharedBy = $share->getSharedBy();
175
-		$shareType = $share->getShareType();
176
-
177
-		if ($shareType === IShare::TYPE_REMOTE_GROUP &&
178
-			!$this->isOutgoingServer2serverGroupShareEnabled()
179
-		) {
180
-			$message = 'It is not allowed to send federated group shares from this server.';
181
-			$message_t = $this->l->t('It is not allowed to send federated group shares from this server.');
182
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
183
-			throw new \Exception($message_t);
184
-		}
185
-
186
-		/*
64
+    public const SHARE_TYPE_REMOTE = 6;
65
+
66
+    /** @var IDBConnection */
67
+    private $dbConnection;
68
+
69
+    /** @var AddressHandler */
70
+    private $addressHandler;
71
+
72
+    /** @var Notifications */
73
+    private $notifications;
74
+
75
+    /** @var TokenHandler */
76
+    private $tokenHandler;
77
+
78
+    /** @var IL10N */
79
+    private $l;
80
+
81
+    /** @var ILogger */
82
+    private $logger;
83
+
84
+    /** @var IRootFolder */
85
+    private $rootFolder;
86
+
87
+    /** @var IConfig */
88
+    private $config;
89
+
90
+    /** @var string */
91
+    private $externalShareTable = 'share_external';
92
+
93
+    /** @var IUserManager */
94
+    private $userManager;
95
+
96
+    /** @var ICloudIdManager */
97
+    private $cloudIdManager;
98
+
99
+    /** @var \OCP\GlobalScale\IConfig */
100
+    private $gsConfig;
101
+
102
+    /** @var ICloudFederationProviderManager */
103
+    private $cloudFederationProviderManager;
104
+
105
+    /** @var array list of supported share types */
106
+    private $supportedShareType = [IShare::TYPE_REMOTE_GROUP, IShare::TYPE_REMOTE, IShare::TYPE_CIRCLE];
107
+
108
+    /**
109
+     * DefaultShareProvider constructor.
110
+     *
111
+     * @param IDBConnection $connection
112
+     * @param AddressHandler $addressHandler
113
+     * @param Notifications $notifications
114
+     * @param TokenHandler $tokenHandler
115
+     * @param IL10N $l10n
116
+     * @param ILogger $logger
117
+     * @param IRootFolder $rootFolder
118
+     * @param IConfig $config
119
+     * @param IUserManager $userManager
120
+     * @param ICloudIdManager $cloudIdManager
121
+     * @param \OCP\GlobalScale\IConfig $globalScaleConfig
122
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
123
+     */
124
+    public function __construct(
125
+            IDBConnection $connection,
126
+            AddressHandler $addressHandler,
127
+            Notifications $notifications,
128
+            TokenHandler $tokenHandler,
129
+            IL10N $l10n,
130
+            ILogger $logger,
131
+            IRootFolder $rootFolder,
132
+            IConfig $config,
133
+            IUserManager $userManager,
134
+            ICloudIdManager $cloudIdManager,
135
+            \OCP\GlobalScale\IConfig $globalScaleConfig,
136
+            ICloudFederationProviderManager $cloudFederationProviderManager
137
+    ) {
138
+        $this->dbConnection = $connection;
139
+        $this->addressHandler = $addressHandler;
140
+        $this->notifications = $notifications;
141
+        $this->tokenHandler = $tokenHandler;
142
+        $this->l = $l10n;
143
+        $this->logger = $logger;
144
+        $this->rootFolder = $rootFolder;
145
+        $this->config = $config;
146
+        $this->userManager = $userManager;
147
+        $this->cloudIdManager = $cloudIdManager;
148
+        $this->gsConfig = $globalScaleConfig;
149
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
150
+    }
151
+
152
+    /**
153
+     * Return the identifier of this provider.
154
+     *
155
+     * @return string Containing only [a-zA-Z0-9]
156
+     */
157
+    public function identifier() {
158
+        return 'ocFederatedSharing';
159
+    }
160
+
161
+    /**
162
+     * Share a path
163
+     *
164
+     * @param IShare $share
165
+     * @return IShare The share object
166
+     * @throws ShareNotFound
167
+     * @throws \Exception
168
+     */
169
+    public function create(IShare $share) {
170
+        $shareWith = $share->getSharedWith();
171
+        $itemSource = $share->getNodeId();
172
+        $itemType = $share->getNodeType();
173
+        $permissions = $share->getPermissions();
174
+        $sharedBy = $share->getSharedBy();
175
+        $shareType = $share->getShareType();
176
+
177
+        if ($shareType === IShare::TYPE_REMOTE_GROUP &&
178
+            !$this->isOutgoingServer2serverGroupShareEnabled()
179
+        ) {
180
+            $message = 'It is not allowed to send federated group shares from this server.';
181
+            $message_t = $this->l->t('It is not allowed to send federated group shares from this server.');
182
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
183
+            throw new \Exception($message_t);
184
+        }
185
+
186
+        /*
187 187
 		 * Check if file is not already shared with the remote user
188 188
 		 */
189
-		$alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE, $share->getNode(), 1, 0);
190
-		$alreadySharedGroup = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE_GROUP, $share->getNode(), 1, 0);
191
-		if (!empty($alreadyShared) || !empty($alreadySharedGroup)) {
192
-			$message = 'Sharing %1$s failed, because this item is already shared with %2$s';
193
-			$message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with %2$s', [$share->getNode()->getName(), $shareWith]);
194
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
195
-			throw new \Exception($message_t);
196
-		}
197
-
198
-
199
-		// don't allow federated shares if source and target server are the same
200
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
201
-		$currentServer = $this->addressHandler->generateRemoteURL();
202
-		$currentUser = $sharedBy;
203
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
204
-			$message = 'Not allowed to create a federated share with the same user.';
205
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
206
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
207
-			throw new \Exception($message_t);
208
-		}
209
-
210
-
211
-		$share->setSharedWith($cloudId->getId());
212
-
213
-		try {
214
-			$remoteShare = $this->getShareFromExternalShareTable($share);
215
-		} catch (ShareNotFound $e) {
216
-			$remoteShare = null;
217
-		}
218
-
219
-		if ($remoteShare) {
220
-			try {
221
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
222
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time(), $shareType);
223
-				$share->setId($shareId);
224
-				[$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId);
225
-				// remote share was create successfully if we get a valid token as return
226
-				$send = is_string($token) && $token !== '';
227
-			} catch (\Exception $e) {
228
-				// fall back to old re-share behavior if the remote server
229
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
230
-				$this->removeShareFromTable($share);
231
-				$shareId = $this->createFederatedShare($share);
232
-			}
233
-			if ($send) {
234
-				$this->updateSuccessfulReshare($shareId, $token);
235
-				$this->storeRemoteId($shareId, $remoteId);
236
-			} else {
237
-				$this->removeShareFromTable($share);
238
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
239
-				throw new \Exception($message_t);
240
-			}
241
-		} else {
242
-			$shareId = $this->createFederatedShare($share);
243
-		}
244
-
245
-		$data = $this->getRawShare($shareId);
246
-		return $this->createShareObject($data);
247
-	}
248
-
249
-	/**
250
-	 * create federated share and inform the recipient
251
-	 *
252
-	 * @param IShare $share
253
-	 * @return int
254
-	 * @throws ShareNotFound
255
-	 * @throws \Exception
256
-	 */
257
-	protected function createFederatedShare(IShare $share) {
258
-		$token = $this->tokenHandler->generateToken();
259
-		$shareId = $this->addShareToDB(
260
-			$share->getNodeId(),
261
-			$share->getNodeType(),
262
-			$share->getSharedWith(),
263
-			$share->getSharedBy(),
264
-			$share->getShareOwner(),
265
-			$share->getPermissions(),
266
-			$token,
267
-			$share->getShareType()
268
-		);
269
-
270
-		$failure = false;
271
-
272
-		try {
273
-			$sharedByFederatedId = $share->getSharedBy();
274
-			if ($this->userManager->userExists($sharedByFederatedId)) {
275
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
276
-				$sharedByFederatedId = $cloudId->getId();
277
-			}
278
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
279
-			$send = $this->notifications->sendRemoteShare(
280
-				$token,
281
-				$share->getSharedWith(),
282
-				$share->getNode()->getName(),
283
-				$shareId,
284
-				$share->getShareOwner(),
285
-				$ownerCloudId->getId(),
286
-				$share->getSharedBy(),
287
-				$sharedByFederatedId,
288
-				$share->getShareType()
289
-			);
290
-
291
-			if ($send === false) {
292
-				$failure = true;
293
-			}
294
-		} catch (\Exception $e) {
295
-			$this->logger->logException($e, [
296
-				'message' => 'Failed to notify remote server of federated share, removing share.',
297
-				'level' => ILogger::ERROR,
298
-				'app' => 'federatedfilesharing',
299
-			]);
300
-			$failure = true;
301
-		}
302
-
303
-		if ($failure) {
304
-			$this->removeShareFromTableById($shareId);
305
-			$message_t = $this->l->t('Sharing %1$s failed, could not find %2$s, maybe the server is currently unreachable or uses a self-signed certificate.',
306
-				[$share->getNode()->getName(), $share->getSharedWith()]);
307
-			throw new \Exception($message_t);
308
-		}
309
-
310
-		return $shareId;
311
-	}
312
-
313
-	/**
314
-	 * @param string $shareWith
315
-	 * @param IShare $share
316
-	 * @param string $shareId internal share Id
317
-	 * @return array
318
-	 * @throws \Exception
319
-	 */
320
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
321
-		$remoteShare = $this->getShareFromExternalShareTable($share);
322
-		$token = $remoteShare['share_token'];
323
-		$remoteId = $remoteShare['remote_id'];
324
-		$remote = $remoteShare['remote'];
325
-
326
-		[$token, $remoteId] = $this->notifications->requestReShare(
327
-			$token,
328
-			$remoteId,
329
-			$shareId,
330
-			$remote,
331
-			$shareWith,
332
-			$share->getPermissions(),
333
-			$share->getNode()->getName()
334
-		);
335
-
336
-		return [$token, $remoteId];
337
-	}
338
-
339
-	/**
340
-	 * get federated share from the share_external table but exclude mounted link shares
341
-	 *
342
-	 * @param IShare $share
343
-	 * @return array
344
-	 * @throws ShareNotFound
345
-	 */
346
-	protected function getShareFromExternalShareTable(IShare $share) {
347
-		$query = $this->dbConnection->getQueryBuilder();
348
-		$query->select('*')->from($this->externalShareTable)
349
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
350
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
351
-		$qResult = $query->execute();
352
-		$result = $qResult->fetchAll();
353
-		$qResult->closeCursor();
354
-
355
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
356
-			return $result[0];
357
-		}
358
-
359
-		throw new ShareNotFound('share not found in share_external table');
360
-	}
361
-
362
-	/**
363
-	 * add share to the database and return the ID
364
-	 *
365
-	 * @param int $itemSource
366
-	 * @param string $itemType
367
-	 * @param string $shareWith
368
-	 * @param string $sharedBy
369
-	 * @param string $uidOwner
370
-	 * @param int $permissions
371
-	 * @param string $token
372
-	 * @param int $shareType
373
-	 * @return int
374
-	 */
375
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $shareType) {
376
-		$qb = $this->dbConnection->getQueryBuilder();
377
-		$qb->insert('share')
378
-			->setValue('share_type', $qb->createNamedParameter($shareType))
379
-			->setValue('item_type', $qb->createNamedParameter($itemType))
380
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
381
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
382
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
383
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
384
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
385
-			->setValue('permissions', $qb->createNamedParameter($permissions))
386
-			->setValue('token', $qb->createNamedParameter($token))
387
-			->setValue('stime', $qb->createNamedParameter(time()));
388
-
389
-		/*
189
+        $alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE, $share->getNode(), 1, 0);
190
+        $alreadySharedGroup = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE_GROUP, $share->getNode(), 1, 0);
191
+        if (!empty($alreadyShared) || !empty($alreadySharedGroup)) {
192
+            $message = 'Sharing %1$s failed, because this item is already shared with %2$s';
193
+            $message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with %2$s', [$share->getNode()->getName(), $shareWith]);
194
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
195
+            throw new \Exception($message_t);
196
+        }
197
+
198
+
199
+        // don't allow federated shares if source and target server are the same
200
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
201
+        $currentServer = $this->addressHandler->generateRemoteURL();
202
+        $currentUser = $sharedBy;
203
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
204
+            $message = 'Not allowed to create a federated share with the same user.';
205
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
206
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
207
+            throw new \Exception($message_t);
208
+        }
209
+
210
+
211
+        $share->setSharedWith($cloudId->getId());
212
+
213
+        try {
214
+            $remoteShare = $this->getShareFromExternalShareTable($share);
215
+        } catch (ShareNotFound $e) {
216
+            $remoteShare = null;
217
+        }
218
+
219
+        if ($remoteShare) {
220
+            try {
221
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
222
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time(), $shareType);
223
+                $share->setId($shareId);
224
+                [$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId);
225
+                // remote share was create successfully if we get a valid token as return
226
+                $send = is_string($token) && $token !== '';
227
+            } catch (\Exception $e) {
228
+                // fall back to old re-share behavior if the remote server
229
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
230
+                $this->removeShareFromTable($share);
231
+                $shareId = $this->createFederatedShare($share);
232
+            }
233
+            if ($send) {
234
+                $this->updateSuccessfulReshare($shareId, $token);
235
+                $this->storeRemoteId($shareId, $remoteId);
236
+            } else {
237
+                $this->removeShareFromTable($share);
238
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
239
+                throw new \Exception($message_t);
240
+            }
241
+        } else {
242
+            $shareId = $this->createFederatedShare($share);
243
+        }
244
+
245
+        $data = $this->getRawShare($shareId);
246
+        return $this->createShareObject($data);
247
+    }
248
+
249
+    /**
250
+     * create federated share and inform the recipient
251
+     *
252
+     * @param IShare $share
253
+     * @return int
254
+     * @throws ShareNotFound
255
+     * @throws \Exception
256
+     */
257
+    protected function createFederatedShare(IShare $share) {
258
+        $token = $this->tokenHandler->generateToken();
259
+        $shareId = $this->addShareToDB(
260
+            $share->getNodeId(),
261
+            $share->getNodeType(),
262
+            $share->getSharedWith(),
263
+            $share->getSharedBy(),
264
+            $share->getShareOwner(),
265
+            $share->getPermissions(),
266
+            $token,
267
+            $share->getShareType()
268
+        );
269
+
270
+        $failure = false;
271
+
272
+        try {
273
+            $sharedByFederatedId = $share->getSharedBy();
274
+            if ($this->userManager->userExists($sharedByFederatedId)) {
275
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
276
+                $sharedByFederatedId = $cloudId->getId();
277
+            }
278
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
279
+            $send = $this->notifications->sendRemoteShare(
280
+                $token,
281
+                $share->getSharedWith(),
282
+                $share->getNode()->getName(),
283
+                $shareId,
284
+                $share->getShareOwner(),
285
+                $ownerCloudId->getId(),
286
+                $share->getSharedBy(),
287
+                $sharedByFederatedId,
288
+                $share->getShareType()
289
+            );
290
+
291
+            if ($send === false) {
292
+                $failure = true;
293
+            }
294
+        } catch (\Exception $e) {
295
+            $this->logger->logException($e, [
296
+                'message' => 'Failed to notify remote server of federated share, removing share.',
297
+                'level' => ILogger::ERROR,
298
+                'app' => 'federatedfilesharing',
299
+            ]);
300
+            $failure = true;
301
+        }
302
+
303
+        if ($failure) {
304
+            $this->removeShareFromTableById($shareId);
305
+            $message_t = $this->l->t('Sharing %1$s failed, could not find %2$s, maybe the server is currently unreachable or uses a self-signed certificate.',
306
+                [$share->getNode()->getName(), $share->getSharedWith()]);
307
+            throw new \Exception($message_t);
308
+        }
309
+
310
+        return $shareId;
311
+    }
312
+
313
+    /**
314
+     * @param string $shareWith
315
+     * @param IShare $share
316
+     * @param string $shareId internal share Id
317
+     * @return array
318
+     * @throws \Exception
319
+     */
320
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
321
+        $remoteShare = $this->getShareFromExternalShareTable($share);
322
+        $token = $remoteShare['share_token'];
323
+        $remoteId = $remoteShare['remote_id'];
324
+        $remote = $remoteShare['remote'];
325
+
326
+        [$token, $remoteId] = $this->notifications->requestReShare(
327
+            $token,
328
+            $remoteId,
329
+            $shareId,
330
+            $remote,
331
+            $shareWith,
332
+            $share->getPermissions(),
333
+            $share->getNode()->getName()
334
+        );
335
+
336
+        return [$token, $remoteId];
337
+    }
338
+
339
+    /**
340
+     * get federated share from the share_external table but exclude mounted link shares
341
+     *
342
+     * @param IShare $share
343
+     * @return array
344
+     * @throws ShareNotFound
345
+     */
346
+    protected function getShareFromExternalShareTable(IShare $share) {
347
+        $query = $this->dbConnection->getQueryBuilder();
348
+        $query->select('*')->from($this->externalShareTable)
349
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
350
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
351
+        $qResult = $query->execute();
352
+        $result = $qResult->fetchAll();
353
+        $qResult->closeCursor();
354
+
355
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
356
+            return $result[0];
357
+        }
358
+
359
+        throw new ShareNotFound('share not found in share_external table');
360
+    }
361
+
362
+    /**
363
+     * add share to the database and return the ID
364
+     *
365
+     * @param int $itemSource
366
+     * @param string $itemType
367
+     * @param string $shareWith
368
+     * @param string $sharedBy
369
+     * @param string $uidOwner
370
+     * @param int $permissions
371
+     * @param string $token
372
+     * @param int $shareType
373
+     * @return int
374
+     */
375
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $shareType) {
376
+        $qb = $this->dbConnection->getQueryBuilder();
377
+        $qb->insert('share')
378
+            ->setValue('share_type', $qb->createNamedParameter($shareType))
379
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
380
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
381
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
382
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
383
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
384
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
385
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
386
+            ->setValue('token', $qb->createNamedParameter($token))
387
+            ->setValue('stime', $qb->createNamedParameter(time()));
388
+
389
+        /*
390 390
 		 * Added to fix https://github.com/owncloud/core/issues/22215
391 391
 		 * Can be removed once we get rid of ajax/share.php
392 392
 		 */
393
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
394
-
395
-		$qb->execute();
396
-		$id = $qb->getLastInsertId();
397
-
398
-		return (int)$id;
399
-	}
400
-
401
-	/**
402
-	 * Update a share
403
-	 *
404
-	 * @param IShare $share
405
-	 * @return IShare The share object
406
-	 */
407
-	public function update(IShare $share) {
408
-		/*
393
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
394
+
395
+        $qb->execute();
396
+        $id = $qb->getLastInsertId();
397
+
398
+        return (int)$id;
399
+    }
400
+
401
+    /**
402
+     * Update a share
403
+     *
404
+     * @param IShare $share
405
+     * @return IShare The share object
406
+     */
407
+    public function update(IShare $share) {
408
+        /*
409 409
 		 * We allow updating the permissions of federated shares
410 410
 		 */
411
-		$qb = $this->dbConnection->getQueryBuilder();
412
-		$qb->update('share')
413
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
414
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
415
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
416
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
417
-				->execute();
418
-
419
-		// send the updated permission to the owner/initiator, if they are not the same
420
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
421
-			$this->sendPermissionUpdate($share);
422
-		}
423
-
424
-		return $share;
425
-	}
426
-
427
-	/**
428
-	 * send the updated permission to the owner/initiator, if they are not the same
429
-	 *
430
-	 * @param IShare $share
431
-	 * @throws ShareNotFound
432
-	 * @throws \OC\HintException
433
-	 */
434
-	protected function sendPermissionUpdate(IShare $share) {
435
-		$remoteId = $this->getRemoteId($share);
436
-		// if the local user is the owner we send the permission change to the initiator
437
-		if ($this->userManager->userExists($share->getShareOwner())) {
438
-			[, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
439
-		} else { // ... if not we send the permission change to the owner
440
-			[, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
441
-		}
442
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
443
-	}
444
-
445
-
446
-	/**
447
-	 * update successful reShare with the correct token
448
-	 *
449
-	 * @param int $shareId
450
-	 * @param string $token
451
-	 */
452
-	protected function updateSuccessfulReShare($shareId, $token) {
453
-		$query = $this->dbConnection->getQueryBuilder();
454
-		$query->update('share')
455
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
456
-			->set('token', $query->createNamedParameter($token))
457
-			->execute();
458
-	}
459
-
460
-	/**
461
-	 * store remote ID in federated reShare table
462
-	 *
463
-	 * @param $shareId
464
-	 * @param $remoteId
465
-	 */
466
-	public function storeRemoteId(int $shareId, string $remoteId): void {
467
-		$query = $this->dbConnection->getQueryBuilder();
468
-		$query->insert('federated_reshares')
469
-			->values(
470
-				[
471
-					'share_id' => $query->createNamedParameter($shareId),
472
-					'remote_id' => $query->createNamedParameter($remoteId),
473
-				]
474
-			);
475
-		$query->execute();
476
-	}
477
-
478
-	/**
479
-	 * get share ID on remote server for federated re-shares
480
-	 *
481
-	 * @param IShare $share
482
-	 * @return string
483
-	 * @throws ShareNotFound
484
-	 */
485
-	public function getRemoteId(IShare $share): string {
486
-		$query = $this->dbConnection->getQueryBuilder();
487
-		$query->select('remote_id')->from('federated_reshares')
488
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
489
-		$result = $query->execute();
490
-		$data = $result->fetch();
491
-		$result->closeCursor();
492
-
493
-		if (!is_array($data) || !isset($data['remote_id'])) {
494
-			throw new ShareNotFound();
495
-		}
496
-
497
-		return (string)$data['remote_id'];
498
-	}
499
-
500
-	/**
501
-	 * @inheritdoc
502
-	 */
503
-	public function move(IShare $share, $recipient) {
504
-		/*
411
+        $qb = $this->dbConnection->getQueryBuilder();
412
+        $qb->update('share')
413
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
414
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
415
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
416
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
417
+                ->execute();
418
+
419
+        // send the updated permission to the owner/initiator, if they are not the same
420
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
421
+            $this->sendPermissionUpdate($share);
422
+        }
423
+
424
+        return $share;
425
+    }
426
+
427
+    /**
428
+     * send the updated permission to the owner/initiator, if they are not the same
429
+     *
430
+     * @param IShare $share
431
+     * @throws ShareNotFound
432
+     * @throws \OC\HintException
433
+     */
434
+    protected function sendPermissionUpdate(IShare $share) {
435
+        $remoteId = $this->getRemoteId($share);
436
+        // if the local user is the owner we send the permission change to the initiator
437
+        if ($this->userManager->userExists($share->getShareOwner())) {
438
+            [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
439
+        } else { // ... if not we send the permission change to the owner
440
+            [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
441
+        }
442
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
443
+    }
444
+
445
+
446
+    /**
447
+     * update successful reShare with the correct token
448
+     *
449
+     * @param int $shareId
450
+     * @param string $token
451
+     */
452
+    protected function updateSuccessfulReShare($shareId, $token) {
453
+        $query = $this->dbConnection->getQueryBuilder();
454
+        $query->update('share')
455
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
456
+            ->set('token', $query->createNamedParameter($token))
457
+            ->execute();
458
+    }
459
+
460
+    /**
461
+     * store remote ID in federated reShare table
462
+     *
463
+     * @param $shareId
464
+     * @param $remoteId
465
+     */
466
+    public function storeRemoteId(int $shareId, string $remoteId): void {
467
+        $query = $this->dbConnection->getQueryBuilder();
468
+        $query->insert('federated_reshares')
469
+            ->values(
470
+                [
471
+                    'share_id' => $query->createNamedParameter($shareId),
472
+                    'remote_id' => $query->createNamedParameter($remoteId),
473
+                ]
474
+            );
475
+        $query->execute();
476
+    }
477
+
478
+    /**
479
+     * get share ID on remote server for federated re-shares
480
+     *
481
+     * @param IShare $share
482
+     * @return string
483
+     * @throws ShareNotFound
484
+     */
485
+    public function getRemoteId(IShare $share): string {
486
+        $query = $this->dbConnection->getQueryBuilder();
487
+        $query->select('remote_id')->from('federated_reshares')
488
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
489
+        $result = $query->execute();
490
+        $data = $result->fetch();
491
+        $result->closeCursor();
492
+
493
+        if (!is_array($data) || !isset($data['remote_id'])) {
494
+            throw new ShareNotFound();
495
+        }
496
+
497
+        return (string)$data['remote_id'];
498
+    }
499
+
500
+    /**
501
+     * @inheritdoc
502
+     */
503
+    public function move(IShare $share, $recipient) {
504
+        /*
505 505
 		 * This function does nothing yet as it is just for outgoing
506 506
 		 * federated shares.
507 507
 		 */
508
-		return $share;
509
-	}
510
-
511
-	/**
512
-	 * Get all children of this share
513
-	 *
514
-	 * @param IShare $parent
515
-	 * @return IShare[]
516
-	 */
517
-	public function getChildren(IShare $parent) {
518
-		$children = [];
519
-
520
-		$qb = $this->dbConnection->getQueryBuilder();
521
-		$qb->select('*')
522
-			->from('share')
523
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
524
-			->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
525
-			->orderBy('id');
526
-
527
-		$cursor = $qb->execute();
528
-		while ($data = $cursor->fetch()) {
529
-			$children[] = $this->createShareObject($data);
530
-		}
531
-		$cursor->closeCursor();
532
-
533
-		return $children;
534
-	}
535
-
536
-	/**
537
-	 * Delete a share (owner unShares the file)
538
-	 *
539
-	 * @param IShare $share
540
-	 * @throws ShareNotFound
541
-	 * @throws \OC\HintException
542
-	 */
543
-	public function delete(IShare $share) {
544
-		[, $remote] = $this->addressHandler->splitUserRemote($share->getSharedWith());
545
-
546
-		// if the local user is the owner we can send the unShare request directly...
547
-		if ($this->userManager->userExists($share->getShareOwner())) {
548
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
549
-			$this->revokeShare($share, true);
550
-		} else { // ... if not we need to correct ID for the unShare request
551
-			$remoteId = $this->getRemoteId($share);
552
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
553
-			$this->revokeShare($share, false);
554
-		}
555
-
556
-		// only remove the share when all messages are send to not lose information
557
-		// about the share to early
558
-		$this->removeShareFromTable($share);
559
-	}
560
-
561
-	/**
562
-	 * in case of a re-share we need to send the other use (initiator or owner)
563
-	 * a message that the file was unshared
564
-	 *
565
-	 * @param IShare $share
566
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
567
-	 * @throws ShareNotFound
568
-	 * @throws \OC\HintException
569
-	 */
570
-	protected function revokeShare($share, $isOwner) {
571
-		if ($this->userManager->userExists($share->getShareOwner()) && $this->userManager->userExists($share->getSharedBy())) {
572
-			// If both the owner and the initiator of the share are local users we don't have to notify anybody else
573
-			return;
574
-		}
575
-
576
-		// also send a unShare request to the initiator, if this is a different user than the owner
577
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
578
-			if ($isOwner) {
579
-				[, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
580
-			} else {
581
-				[, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
582
-			}
583
-			$remoteId = $this->getRemoteId($share);
584
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
585
-		}
586
-	}
587
-
588
-	/**
589
-	 * remove share from table
590
-	 *
591
-	 * @param IShare $share
592
-	 */
593
-	public function removeShareFromTable(IShare $share) {
594
-		$this->removeShareFromTableById($share->getId());
595
-	}
596
-
597
-	/**
598
-	 * remove share from table
599
-	 *
600
-	 * @param string $shareId
601
-	 */
602
-	private function removeShareFromTableById($shareId) {
603
-		$qb = $this->dbConnection->getQueryBuilder();
604
-		$qb->delete('share')
605
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)))
606
-			->andWhere($qb->expr()->neq('share_type', $qb->createNamedParameter(IShare::TYPE_CIRCLE)));
607
-		$qb->execute();
608
-
609
-		$qb->delete('federated_reshares')
610
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
611
-		$qb->execute();
612
-	}
613
-
614
-	/**
615
-	 * @inheritdoc
616
-	 */
617
-	public function deleteFromSelf(IShare $share, $recipient) {
618
-		// nothing to do here. Technically deleteFromSelf in the context of federated
619
-		// shares is a umount of an external storage. This is handled here
620
-		// apps/files_sharing/lib/external/manager.php
621
-		// TODO move this code over to this app
622
-	}
623
-
624
-	public function restore(IShare $share, string $recipient): IShare {
625
-		throw new GenericShareException('not implemented');
626
-	}
627
-
628
-
629
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
630
-		$qb = $this->dbConnection->getQueryBuilder();
631
-		$qb->select('*')
632
-			->from('share', 's')
633
-			->andWhere($qb->expr()->orX(
634
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
635
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
636
-			))
637
-			->andWhere(
638
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE))
639
-			);
640
-
641
-		/**
642
-		 * Reshares for this user are shares where they are the owner.
643
-		 */
644
-		if ($reshares === false) {
645
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
646
-		} else {
647
-			$qb->andWhere(
648
-				$qb->expr()->orX(
649
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
650
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
651
-				)
652
-			);
653
-		}
654
-
655
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
656
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
657
-
658
-		$qb->orderBy('id');
659
-
660
-		$cursor = $qb->execute();
661
-		$shares = [];
662
-		while ($data = $cursor->fetch()) {
663
-			$shares[$data['fileid']][] = $this->createShareObject($data);
664
-		}
665
-		$cursor->closeCursor();
666
-
667
-		return $shares;
668
-	}
669
-
670
-	/**
671
-	 * @inheritdoc
672
-	 */
673
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
674
-		$qb = $this->dbConnection->getQueryBuilder();
675
-		$qb->select('*')
676
-			->from('share');
677
-
678
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
679
-
680
-		/**
681
-		 * Reshares for this user are shares where they are the owner.
682
-		 */
683
-		if ($reshares === false) {
684
-			//Special case for old shares created via the web UI
685
-			$or1 = $qb->expr()->andX(
686
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
687
-				$qb->expr()->isNull('uid_initiator')
688
-			);
689
-
690
-			$qb->andWhere(
691
-				$qb->expr()->orX(
692
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
693
-					$or1
694
-				)
695
-			);
696
-		} else {
697
-			$qb->andWhere(
698
-				$qb->expr()->orX(
699
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
700
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
701
-				)
702
-			);
703
-		}
704
-
705
-		if ($node !== null) {
706
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
707
-		}
708
-
709
-		if ($limit !== -1) {
710
-			$qb->setMaxResults($limit);
711
-		}
712
-
713
-		$qb->setFirstResult($offset);
714
-		$qb->orderBy('id');
715
-
716
-		$cursor = $qb->execute();
717
-		$shares = [];
718
-		while ($data = $cursor->fetch()) {
719
-			$shares[] = $this->createShareObject($data);
720
-		}
721
-		$cursor->closeCursor();
722
-
723
-		return $shares;
724
-	}
725
-
726
-	/**
727
-	 * @inheritdoc
728
-	 */
729
-	public function getShareById($id, $recipientId = null) {
730
-		$qb = $this->dbConnection->getQueryBuilder();
731
-
732
-		$qb->select('*')
733
-			->from('share')
734
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
735
-			->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
736
-
737
-		$cursor = $qb->execute();
738
-		$data = $cursor->fetch();
739
-		$cursor->closeCursor();
740
-
741
-		if ($data === false) {
742
-			throw new ShareNotFound('Can not find share with ID: ' . $id);
743
-		}
744
-
745
-		try {
746
-			$share = $this->createShareObject($data);
747
-		} catch (InvalidShare $e) {
748
-			throw new ShareNotFound();
749
-		}
750
-
751
-		return $share;
752
-	}
753
-
754
-	/**
755
-	 * Get shares for a given path
756
-	 *
757
-	 * @param \OCP\Files\Node $path
758
-	 * @return IShare[]
759
-	 */
760
-	public function getSharesByPath(Node $path) {
761
-		$qb = $this->dbConnection->getQueryBuilder();
762
-
763
-		// get federated user shares
764
-		$cursor = $qb->select('*')
765
-			->from('share')
766
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
767
-			->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
768
-			->execute();
769
-
770
-		$shares = [];
771
-		while ($data = $cursor->fetch()) {
772
-			$shares[] = $this->createShareObject($data);
773
-		}
774
-		$cursor->closeCursor();
775
-
776
-		return $shares;
777
-	}
778
-
779
-	/**
780
-	 * @inheritdoc
781
-	 */
782
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
783
-		/** @var IShare[] $shares */
784
-		$shares = [];
785
-
786
-		//Get shares directly with this user
787
-		$qb = $this->dbConnection->getQueryBuilder();
788
-		$qb->select('*')
789
-			->from('share');
790
-
791
-		// Order by id
792
-		$qb->orderBy('id');
793
-
794
-		// Set limit and offset
795
-		if ($limit !== -1) {
796
-			$qb->setMaxResults($limit);
797
-		}
798
-		$qb->setFirstResult($offset);
799
-
800
-		$qb->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
801
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
802
-
803
-		// Filter by node if provided
804
-		if ($node !== null) {
805
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
806
-		}
807
-
808
-		$cursor = $qb->execute();
809
-
810
-		while ($data = $cursor->fetch()) {
811
-			$shares[] = $this->createShareObject($data);
812
-		}
813
-		$cursor->closeCursor();
814
-
815
-
816
-		return $shares;
817
-	}
818
-
819
-	/**
820
-	 * Get a share by token
821
-	 *
822
-	 * @param string $token
823
-	 * @return IShare
824
-	 * @throws ShareNotFound
825
-	 */
826
-	public function getShareByToken($token) {
827
-		$qb = $this->dbConnection->getQueryBuilder();
828
-
829
-		$cursor = $qb->select('*')
830
-			->from('share')
831
-			->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
832
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
833
-			->execute();
834
-
835
-		$data = $cursor->fetch();
836
-
837
-		if ($data === false) {
838
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
839
-		}
840
-
841
-		try {
842
-			$share = $this->createShareObject($data);
843
-		} catch (InvalidShare $e) {
844
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
845
-		}
846
-
847
-		return $share;
848
-	}
849
-
850
-	/**
851
-	 * get database row of a give share
852
-	 *
853
-	 * @param $id
854
-	 * @return array
855
-	 * @throws ShareNotFound
856
-	 */
857
-	private function getRawShare($id) {
858
-
859
-		// Now fetch the inserted share and create a complete share object
860
-		$qb = $this->dbConnection->getQueryBuilder();
861
-		$qb->select('*')
862
-			->from('share')
863
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
864
-
865
-		$cursor = $qb->execute();
866
-		$data = $cursor->fetch();
867
-		$cursor->closeCursor();
868
-
869
-		if ($data === false) {
870
-			throw new ShareNotFound;
871
-		}
872
-
873
-		return $data;
874
-	}
875
-
876
-	/**
877
-	 * Create a share object from an database row
878
-	 *
879
-	 * @param array $data
880
-	 * @return IShare
881
-	 * @throws InvalidShare
882
-	 * @throws ShareNotFound
883
-	 */
884
-	private function createShareObject($data) {
885
-		$share = new Share($this->rootFolder, $this->userManager);
886
-		$share->setId((int)$data['id'])
887
-			->setShareType((int)$data['share_type'])
888
-			->setPermissions((int)$data['permissions'])
889
-			->setTarget($data['file_target'])
890
-			->setMailSend((bool)$data['mail_send'])
891
-			->setToken($data['token']);
892
-
893
-		$shareTime = new \DateTime();
894
-		$shareTime->setTimestamp((int)$data['stime']);
895
-		$share->setShareTime($shareTime);
896
-		$share->setSharedWith($data['share_with']);
897
-
898
-		if ($data['uid_initiator'] !== null) {
899
-			$share->setShareOwner($data['uid_owner']);
900
-			$share->setSharedBy($data['uid_initiator']);
901
-		} else {
902
-			//OLD SHARE
903
-			$share->setSharedBy($data['uid_owner']);
904
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
905
-
906
-			$owner = $path->getOwner();
907
-			$share->setShareOwner($owner->getUID());
908
-		}
909
-
910
-		$share->setNodeId((int)$data['file_source']);
911
-		$share->setNodeType($data['item_type']);
912
-
913
-		$share->setProviderId($this->identifier());
914
-
915
-		return $share;
916
-	}
917
-
918
-	/**
919
-	 * Get the node with file $id for $user
920
-	 *
921
-	 * @param string $userId
922
-	 * @param int $id
923
-	 * @return \OCP\Files\File|\OCP\Files\Folder
924
-	 * @throws InvalidShare
925
-	 */
926
-	private function getNode($userId, $id) {
927
-		try {
928
-			$userFolder = $this->rootFolder->getUserFolder($userId);
929
-		} catch (NotFoundException $e) {
930
-			throw new InvalidShare();
931
-		}
932
-
933
-		$nodes = $userFolder->getById($id);
934
-
935
-		if (empty($nodes)) {
936
-			throw new InvalidShare();
937
-		}
938
-
939
-		return $nodes[0];
940
-	}
941
-
942
-	/**
943
-	 * A user is deleted from the system
944
-	 * So clean up the relevant shares.
945
-	 *
946
-	 * @param string $uid
947
-	 * @param int $shareType
948
-	 */
949
-	public function userDeleted($uid, $shareType) {
950
-		//TODO: probabaly a good idea to send unshare info to remote servers
951
-
952
-		$qb = $this->dbConnection->getQueryBuilder();
953
-
954
-		$qb->delete('share')
955
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
956
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
957
-			->execute();
958
-	}
959
-
960
-	/**
961
-	 * This provider does not handle groups
962
-	 *
963
-	 * @param string $gid
964
-	 */
965
-	public function groupDeleted($gid) {
966
-		// We don't handle groups here
967
-	}
968
-
969
-	/**
970
-	 * This provider does not handle groups
971
-	 *
972
-	 * @param string $uid
973
-	 * @param string $gid
974
-	 */
975
-	public function userDeletedFromGroup($uid, $gid) {
976
-		// We don't handle groups here
977
-	}
978
-
979
-	/**
980
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
981
-	 *
982
-	 * @return bool
983
-	 */
984
-	public function isOutgoingServer2serverShareEnabled() {
985
-		if ($this->gsConfig->onlyInternalFederation()) {
986
-			return false;
987
-		}
988
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
989
-		return ($result === 'yes');
990
-	}
991
-
992
-	/**
993
-	 * check if users are allowed to mount public links from other Nextclouds
994
-	 *
995
-	 * @return bool
996
-	 */
997
-	public function isIncomingServer2serverShareEnabled() {
998
-		if ($this->gsConfig->onlyInternalFederation()) {
999
-			return false;
1000
-		}
1001
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
1002
-		return ($result === 'yes');
1003
-	}
1004
-
1005
-
1006
-	/**
1007
-	 * check if users from other Nextcloud instances are allowed to send federated group shares
1008
-	 *
1009
-	 * @return bool
1010
-	 */
1011
-	public function isOutgoingServer2serverGroupShareEnabled() {
1012
-		if ($this->gsConfig->onlyInternalFederation()) {
1013
-			return false;
1014
-		}
1015
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no');
1016
-		return ($result === 'yes');
1017
-	}
1018
-
1019
-	/**
1020
-	 * check if users are allowed to receive federated group shares
1021
-	 *
1022
-	 * @return bool
1023
-	 */
1024
-	public function isIncomingServer2serverGroupShareEnabled() {
1025
-		if ($this->gsConfig->onlyInternalFederation()) {
1026
-			return false;
1027
-		}
1028
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_group_share_enabled', 'no');
1029
-		return ($result === 'yes');
1030
-	}
1031
-
1032
-	/**
1033
-	 * check if federated group sharing is supported, therefore the OCM API need to be enabled
1034
-	 *
1035
-	 * @return bool
1036
-	 */
1037
-	public function isFederatedGroupSharingSupported() {
1038
-		return $this->cloudFederationProviderManager->isReady();
1039
-	}
1040
-
1041
-	/**
1042
-	 * Check if querying sharees on the lookup server is enabled
1043
-	 *
1044
-	 * @return bool
1045
-	 */
1046
-	public function isLookupServerQueriesEnabled() {
1047
-		// in a global scale setup we should always query the lookup server
1048
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
1049
-			return true;
1050
-		}
1051
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes');
1052
-		return ($result === 'yes');
1053
-	}
1054
-
1055
-
1056
-	/**
1057
-	 * Check if it is allowed to publish user specific data to the lookup server
1058
-	 *
1059
-	 * @return bool
1060
-	 */
1061
-	public function isLookupServerUploadEnabled() {
1062
-		// in a global scale setup the admin is responsible to keep the lookup server up-to-date
1063
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
1064
-			return false;
1065
-		}
1066
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1067
-		return ($result === 'yes');
1068
-	}
1069
-
1070
-	/**
1071
-	 * @inheritdoc
1072
-	 */
1073
-	public function getAccessList($nodes, $currentAccess) {
1074
-		$ids = [];
1075
-		foreach ($nodes as $node) {
1076
-			$ids[] = $node->getId();
1077
-		}
1078
-
1079
-		$qb = $this->dbConnection->getQueryBuilder();
1080
-		$qb->select('share_with', 'token', 'file_source')
1081
-			->from('share')
1082
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
1083
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1084
-			->andWhere($qb->expr()->orX(
1085
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1086
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1087
-			));
1088
-		$cursor = $qb->execute();
1089
-
1090
-		if ($currentAccess === false) {
1091
-			$remote = $cursor->fetch() !== false;
1092
-			$cursor->closeCursor();
1093
-
1094
-			return ['remote' => $remote];
1095
-		}
1096
-
1097
-		$remote = [];
1098
-		while ($row = $cursor->fetch()) {
1099
-			$remote[$row['share_with']] = [
1100
-				'node_id' => $row['file_source'],
1101
-				'token' => $row['token'],
1102
-			];
1103
-		}
1104
-		$cursor->closeCursor();
1105
-
1106
-		return ['remote' => $remote];
1107
-	}
1108
-
1109
-	public function getAllShares(): iterable {
1110
-		$qb = $this->dbConnection->getQueryBuilder();
1111
-
1112
-		$qb->select('*')
1113
-			->from('share')
1114
-			->where(
1115
-				$qb->expr()->orX(
1116
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE)),
1117
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE_GROUP))
1118
-				)
1119
-			);
1120
-
1121
-		$cursor = $qb->execute();
1122
-		while ($data = $cursor->fetch()) {
1123
-			try {
1124
-				$share = $this->createShareObject($data);
1125
-			} catch (InvalidShare $e) {
1126
-				continue;
1127
-			} catch (ShareNotFound $e) {
1128
-				continue;
1129
-			}
1130
-
1131
-			yield $share;
1132
-		}
1133
-		$cursor->closeCursor();
1134
-	}
508
+        return $share;
509
+    }
510
+
511
+    /**
512
+     * Get all children of this share
513
+     *
514
+     * @param IShare $parent
515
+     * @return IShare[]
516
+     */
517
+    public function getChildren(IShare $parent) {
518
+        $children = [];
519
+
520
+        $qb = $this->dbConnection->getQueryBuilder();
521
+        $qb->select('*')
522
+            ->from('share')
523
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
524
+            ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
525
+            ->orderBy('id');
526
+
527
+        $cursor = $qb->execute();
528
+        while ($data = $cursor->fetch()) {
529
+            $children[] = $this->createShareObject($data);
530
+        }
531
+        $cursor->closeCursor();
532
+
533
+        return $children;
534
+    }
535
+
536
+    /**
537
+     * Delete a share (owner unShares the file)
538
+     *
539
+     * @param IShare $share
540
+     * @throws ShareNotFound
541
+     * @throws \OC\HintException
542
+     */
543
+    public function delete(IShare $share) {
544
+        [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedWith());
545
+
546
+        // if the local user is the owner we can send the unShare request directly...
547
+        if ($this->userManager->userExists($share->getShareOwner())) {
548
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
549
+            $this->revokeShare($share, true);
550
+        } else { // ... if not we need to correct ID for the unShare request
551
+            $remoteId = $this->getRemoteId($share);
552
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
553
+            $this->revokeShare($share, false);
554
+        }
555
+
556
+        // only remove the share when all messages are send to not lose information
557
+        // about the share to early
558
+        $this->removeShareFromTable($share);
559
+    }
560
+
561
+    /**
562
+     * in case of a re-share we need to send the other use (initiator or owner)
563
+     * a message that the file was unshared
564
+     *
565
+     * @param IShare $share
566
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
567
+     * @throws ShareNotFound
568
+     * @throws \OC\HintException
569
+     */
570
+    protected function revokeShare($share, $isOwner) {
571
+        if ($this->userManager->userExists($share->getShareOwner()) && $this->userManager->userExists($share->getSharedBy())) {
572
+            // If both the owner and the initiator of the share are local users we don't have to notify anybody else
573
+            return;
574
+        }
575
+
576
+        // also send a unShare request to the initiator, if this is a different user than the owner
577
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
578
+            if ($isOwner) {
579
+                [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
580
+            } else {
581
+                [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
582
+            }
583
+            $remoteId = $this->getRemoteId($share);
584
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
585
+        }
586
+    }
587
+
588
+    /**
589
+     * remove share from table
590
+     *
591
+     * @param IShare $share
592
+     */
593
+    public function removeShareFromTable(IShare $share) {
594
+        $this->removeShareFromTableById($share->getId());
595
+    }
596
+
597
+    /**
598
+     * remove share from table
599
+     *
600
+     * @param string $shareId
601
+     */
602
+    private function removeShareFromTableById($shareId) {
603
+        $qb = $this->dbConnection->getQueryBuilder();
604
+        $qb->delete('share')
605
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)))
606
+            ->andWhere($qb->expr()->neq('share_type', $qb->createNamedParameter(IShare::TYPE_CIRCLE)));
607
+        $qb->execute();
608
+
609
+        $qb->delete('federated_reshares')
610
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
611
+        $qb->execute();
612
+    }
613
+
614
+    /**
615
+     * @inheritdoc
616
+     */
617
+    public function deleteFromSelf(IShare $share, $recipient) {
618
+        // nothing to do here. Technically deleteFromSelf in the context of federated
619
+        // shares is a umount of an external storage. This is handled here
620
+        // apps/files_sharing/lib/external/manager.php
621
+        // TODO move this code over to this app
622
+    }
623
+
624
+    public function restore(IShare $share, string $recipient): IShare {
625
+        throw new GenericShareException('not implemented');
626
+    }
627
+
628
+
629
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
630
+        $qb = $this->dbConnection->getQueryBuilder();
631
+        $qb->select('*')
632
+            ->from('share', 's')
633
+            ->andWhere($qb->expr()->orX(
634
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
635
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
636
+            ))
637
+            ->andWhere(
638
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE))
639
+            );
640
+
641
+        /**
642
+         * Reshares for this user are shares where they are the owner.
643
+         */
644
+        if ($reshares === false) {
645
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
646
+        } else {
647
+            $qb->andWhere(
648
+                $qb->expr()->orX(
649
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
650
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
651
+                )
652
+            );
653
+        }
654
+
655
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
656
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
657
+
658
+        $qb->orderBy('id');
659
+
660
+        $cursor = $qb->execute();
661
+        $shares = [];
662
+        while ($data = $cursor->fetch()) {
663
+            $shares[$data['fileid']][] = $this->createShareObject($data);
664
+        }
665
+        $cursor->closeCursor();
666
+
667
+        return $shares;
668
+    }
669
+
670
+    /**
671
+     * @inheritdoc
672
+     */
673
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
674
+        $qb = $this->dbConnection->getQueryBuilder();
675
+        $qb->select('*')
676
+            ->from('share');
677
+
678
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
679
+
680
+        /**
681
+         * Reshares for this user are shares where they are the owner.
682
+         */
683
+        if ($reshares === false) {
684
+            //Special case for old shares created via the web UI
685
+            $or1 = $qb->expr()->andX(
686
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
687
+                $qb->expr()->isNull('uid_initiator')
688
+            );
689
+
690
+            $qb->andWhere(
691
+                $qb->expr()->orX(
692
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
693
+                    $or1
694
+                )
695
+            );
696
+        } else {
697
+            $qb->andWhere(
698
+                $qb->expr()->orX(
699
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
700
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
701
+                )
702
+            );
703
+        }
704
+
705
+        if ($node !== null) {
706
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
707
+        }
708
+
709
+        if ($limit !== -1) {
710
+            $qb->setMaxResults($limit);
711
+        }
712
+
713
+        $qb->setFirstResult($offset);
714
+        $qb->orderBy('id');
715
+
716
+        $cursor = $qb->execute();
717
+        $shares = [];
718
+        while ($data = $cursor->fetch()) {
719
+            $shares[] = $this->createShareObject($data);
720
+        }
721
+        $cursor->closeCursor();
722
+
723
+        return $shares;
724
+    }
725
+
726
+    /**
727
+     * @inheritdoc
728
+     */
729
+    public function getShareById($id, $recipientId = null) {
730
+        $qb = $this->dbConnection->getQueryBuilder();
731
+
732
+        $qb->select('*')
733
+            ->from('share')
734
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
735
+            ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
736
+
737
+        $cursor = $qb->execute();
738
+        $data = $cursor->fetch();
739
+        $cursor->closeCursor();
740
+
741
+        if ($data === false) {
742
+            throw new ShareNotFound('Can not find share with ID: ' . $id);
743
+        }
744
+
745
+        try {
746
+            $share = $this->createShareObject($data);
747
+        } catch (InvalidShare $e) {
748
+            throw new ShareNotFound();
749
+        }
750
+
751
+        return $share;
752
+    }
753
+
754
+    /**
755
+     * Get shares for a given path
756
+     *
757
+     * @param \OCP\Files\Node $path
758
+     * @return IShare[]
759
+     */
760
+    public function getSharesByPath(Node $path) {
761
+        $qb = $this->dbConnection->getQueryBuilder();
762
+
763
+        // get federated user shares
764
+        $cursor = $qb->select('*')
765
+            ->from('share')
766
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
767
+            ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
768
+            ->execute();
769
+
770
+        $shares = [];
771
+        while ($data = $cursor->fetch()) {
772
+            $shares[] = $this->createShareObject($data);
773
+        }
774
+        $cursor->closeCursor();
775
+
776
+        return $shares;
777
+    }
778
+
779
+    /**
780
+     * @inheritdoc
781
+     */
782
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
783
+        /** @var IShare[] $shares */
784
+        $shares = [];
785
+
786
+        //Get shares directly with this user
787
+        $qb = $this->dbConnection->getQueryBuilder();
788
+        $qb->select('*')
789
+            ->from('share');
790
+
791
+        // Order by id
792
+        $qb->orderBy('id');
793
+
794
+        // Set limit and offset
795
+        if ($limit !== -1) {
796
+            $qb->setMaxResults($limit);
797
+        }
798
+        $qb->setFirstResult($offset);
799
+
800
+        $qb->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
801
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
802
+
803
+        // Filter by node if provided
804
+        if ($node !== null) {
805
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
806
+        }
807
+
808
+        $cursor = $qb->execute();
809
+
810
+        while ($data = $cursor->fetch()) {
811
+            $shares[] = $this->createShareObject($data);
812
+        }
813
+        $cursor->closeCursor();
814
+
815
+
816
+        return $shares;
817
+    }
818
+
819
+    /**
820
+     * Get a share by token
821
+     *
822
+     * @param string $token
823
+     * @return IShare
824
+     * @throws ShareNotFound
825
+     */
826
+    public function getShareByToken($token) {
827
+        $qb = $this->dbConnection->getQueryBuilder();
828
+
829
+        $cursor = $qb->select('*')
830
+            ->from('share')
831
+            ->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
832
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
833
+            ->execute();
834
+
835
+        $data = $cursor->fetch();
836
+
837
+        if ($data === false) {
838
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
839
+        }
840
+
841
+        try {
842
+            $share = $this->createShareObject($data);
843
+        } catch (InvalidShare $e) {
844
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
845
+        }
846
+
847
+        return $share;
848
+    }
849
+
850
+    /**
851
+     * get database row of a give share
852
+     *
853
+     * @param $id
854
+     * @return array
855
+     * @throws ShareNotFound
856
+     */
857
+    private function getRawShare($id) {
858
+
859
+        // Now fetch the inserted share and create a complete share object
860
+        $qb = $this->dbConnection->getQueryBuilder();
861
+        $qb->select('*')
862
+            ->from('share')
863
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
864
+
865
+        $cursor = $qb->execute();
866
+        $data = $cursor->fetch();
867
+        $cursor->closeCursor();
868
+
869
+        if ($data === false) {
870
+            throw new ShareNotFound;
871
+        }
872
+
873
+        return $data;
874
+    }
875
+
876
+    /**
877
+     * Create a share object from an database row
878
+     *
879
+     * @param array $data
880
+     * @return IShare
881
+     * @throws InvalidShare
882
+     * @throws ShareNotFound
883
+     */
884
+    private function createShareObject($data) {
885
+        $share = new Share($this->rootFolder, $this->userManager);
886
+        $share->setId((int)$data['id'])
887
+            ->setShareType((int)$data['share_type'])
888
+            ->setPermissions((int)$data['permissions'])
889
+            ->setTarget($data['file_target'])
890
+            ->setMailSend((bool)$data['mail_send'])
891
+            ->setToken($data['token']);
892
+
893
+        $shareTime = new \DateTime();
894
+        $shareTime->setTimestamp((int)$data['stime']);
895
+        $share->setShareTime($shareTime);
896
+        $share->setSharedWith($data['share_with']);
897
+
898
+        if ($data['uid_initiator'] !== null) {
899
+            $share->setShareOwner($data['uid_owner']);
900
+            $share->setSharedBy($data['uid_initiator']);
901
+        } else {
902
+            //OLD SHARE
903
+            $share->setSharedBy($data['uid_owner']);
904
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
905
+
906
+            $owner = $path->getOwner();
907
+            $share->setShareOwner($owner->getUID());
908
+        }
909
+
910
+        $share->setNodeId((int)$data['file_source']);
911
+        $share->setNodeType($data['item_type']);
912
+
913
+        $share->setProviderId($this->identifier());
914
+
915
+        return $share;
916
+    }
917
+
918
+    /**
919
+     * Get the node with file $id for $user
920
+     *
921
+     * @param string $userId
922
+     * @param int $id
923
+     * @return \OCP\Files\File|\OCP\Files\Folder
924
+     * @throws InvalidShare
925
+     */
926
+    private function getNode($userId, $id) {
927
+        try {
928
+            $userFolder = $this->rootFolder->getUserFolder($userId);
929
+        } catch (NotFoundException $e) {
930
+            throw new InvalidShare();
931
+        }
932
+
933
+        $nodes = $userFolder->getById($id);
934
+
935
+        if (empty($nodes)) {
936
+            throw new InvalidShare();
937
+        }
938
+
939
+        return $nodes[0];
940
+    }
941
+
942
+    /**
943
+     * A user is deleted from the system
944
+     * So clean up the relevant shares.
945
+     *
946
+     * @param string $uid
947
+     * @param int $shareType
948
+     */
949
+    public function userDeleted($uid, $shareType) {
950
+        //TODO: probabaly a good idea to send unshare info to remote servers
951
+
952
+        $qb = $this->dbConnection->getQueryBuilder();
953
+
954
+        $qb->delete('share')
955
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
956
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
957
+            ->execute();
958
+    }
959
+
960
+    /**
961
+     * This provider does not handle groups
962
+     *
963
+     * @param string $gid
964
+     */
965
+    public function groupDeleted($gid) {
966
+        // We don't handle groups here
967
+    }
968
+
969
+    /**
970
+     * This provider does not handle groups
971
+     *
972
+     * @param string $uid
973
+     * @param string $gid
974
+     */
975
+    public function userDeletedFromGroup($uid, $gid) {
976
+        // We don't handle groups here
977
+    }
978
+
979
+    /**
980
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
981
+     *
982
+     * @return bool
983
+     */
984
+    public function isOutgoingServer2serverShareEnabled() {
985
+        if ($this->gsConfig->onlyInternalFederation()) {
986
+            return false;
987
+        }
988
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
989
+        return ($result === 'yes');
990
+    }
991
+
992
+    /**
993
+     * check if users are allowed to mount public links from other Nextclouds
994
+     *
995
+     * @return bool
996
+     */
997
+    public function isIncomingServer2serverShareEnabled() {
998
+        if ($this->gsConfig->onlyInternalFederation()) {
999
+            return false;
1000
+        }
1001
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
1002
+        return ($result === 'yes');
1003
+    }
1004
+
1005
+
1006
+    /**
1007
+     * check if users from other Nextcloud instances are allowed to send federated group shares
1008
+     *
1009
+     * @return bool
1010
+     */
1011
+    public function isOutgoingServer2serverGroupShareEnabled() {
1012
+        if ($this->gsConfig->onlyInternalFederation()) {
1013
+            return false;
1014
+        }
1015
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no');
1016
+        return ($result === 'yes');
1017
+    }
1018
+
1019
+    /**
1020
+     * check if users are allowed to receive federated group shares
1021
+     *
1022
+     * @return bool
1023
+     */
1024
+    public function isIncomingServer2serverGroupShareEnabled() {
1025
+        if ($this->gsConfig->onlyInternalFederation()) {
1026
+            return false;
1027
+        }
1028
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_group_share_enabled', 'no');
1029
+        return ($result === 'yes');
1030
+    }
1031
+
1032
+    /**
1033
+     * check if federated group sharing is supported, therefore the OCM API need to be enabled
1034
+     *
1035
+     * @return bool
1036
+     */
1037
+    public function isFederatedGroupSharingSupported() {
1038
+        return $this->cloudFederationProviderManager->isReady();
1039
+    }
1040
+
1041
+    /**
1042
+     * Check if querying sharees on the lookup server is enabled
1043
+     *
1044
+     * @return bool
1045
+     */
1046
+    public function isLookupServerQueriesEnabled() {
1047
+        // in a global scale setup we should always query the lookup server
1048
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
1049
+            return true;
1050
+        }
1051
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes');
1052
+        return ($result === 'yes');
1053
+    }
1054
+
1055
+
1056
+    /**
1057
+     * Check if it is allowed to publish user specific data to the lookup server
1058
+     *
1059
+     * @return bool
1060
+     */
1061
+    public function isLookupServerUploadEnabled() {
1062
+        // in a global scale setup the admin is responsible to keep the lookup server up-to-date
1063
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
1064
+            return false;
1065
+        }
1066
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1067
+        return ($result === 'yes');
1068
+    }
1069
+
1070
+    /**
1071
+     * @inheritdoc
1072
+     */
1073
+    public function getAccessList($nodes, $currentAccess) {
1074
+        $ids = [];
1075
+        foreach ($nodes as $node) {
1076
+            $ids[] = $node->getId();
1077
+        }
1078
+
1079
+        $qb = $this->dbConnection->getQueryBuilder();
1080
+        $qb->select('share_with', 'token', 'file_source')
1081
+            ->from('share')
1082
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
1083
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1084
+            ->andWhere($qb->expr()->orX(
1085
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1086
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1087
+            ));
1088
+        $cursor = $qb->execute();
1089
+
1090
+        if ($currentAccess === false) {
1091
+            $remote = $cursor->fetch() !== false;
1092
+            $cursor->closeCursor();
1093
+
1094
+            return ['remote' => $remote];
1095
+        }
1096
+
1097
+        $remote = [];
1098
+        while ($row = $cursor->fetch()) {
1099
+            $remote[$row['share_with']] = [
1100
+                'node_id' => $row['file_source'],
1101
+                'token' => $row['token'],
1102
+            ];
1103
+        }
1104
+        $cursor->closeCursor();
1105
+
1106
+        return ['remote' => $remote];
1107
+    }
1108
+
1109
+    public function getAllShares(): iterable {
1110
+        $qb = $this->dbConnection->getQueryBuilder();
1111
+
1112
+        $qb->select('*')
1113
+            ->from('share')
1114
+            ->where(
1115
+                $qb->expr()->orX(
1116
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE)),
1117
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE_GROUP))
1118
+                )
1119
+            );
1120
+
1121
+        $cursor = $qb->execute();
1122
+        while ($data = $cursor->fetch()) {
1123
+            try {
1124
+                $share = $this->createShareObject($data);
1125
+            } catch (InvalidShare $e) {
1126
+                continue;
1127
+            } catch (ShareNotFound $e) {
1128
+                continue;
1129
+            }
1130
+
1131
+            yield $share;
1132
+        }
1133
+        $cursor->closeCursor();
1134
+    }
1135 1135
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 		if ($remoteShare) {
220 220
 			try {
221 221
 				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
222
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time(), $shareType);
222
+				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_'.time(), $shareType);
223 223
 				$share->setId($shareId);
224 224
 				[$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId);
225 225
 				// remote share was create successfully if we get a valid token as return
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 		$result = $qResult->fetchAll();
353 353
 		$qResult->closeCursor();
354 354
 
355
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
355
+		if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) {
356 356
 			return $result[0];
357 357
 		}
358 358
 
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 		$qb->execute();
396 396
 		$id = $qb->getLastInsertId();
397 397
 
398
-		return (int)$id;
398
+		return (int) $id;
399 399
 	}
400 400
 
401 401
 	/**
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 	public function getRemoteId(IShare $share): string {
486 486
 		$query = $this->dbConnection->getQueryBuilder();
487 487
 		$query->select('remote_id')->from('federated_reshares')
488
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
488
+			->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId())));
489 489
 		$result = $query->execute();
490 490
 		$data = $result->fetch();
491 491
 		$result->closeCursor();
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 			throw new ShareNotFound();
495 495
 		}
496 496
 
497
-		return (string)$data['remote_id'];
497
+		return (string) $data['remote_id'];
498 498
 	}
499 499
 
500 500
 	/**
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 			);
653 653
 		}
654 654
 
655
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
655
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
656 656
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
657 657
 
658 658
 		$qb->orderBy('id');
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
 		$cursor->closeCursor();
740 740
 
741 741
 		if ($data === false) {
742
-			throw new ShareNotFound('Can not find share with ID: ' . $id);
742
+			throw new ShareNotFound('Can not find share with ID: '.$id);
743 743
 		}
744 744
 
745 745
 		try {
@@ -883,15 +883,15 @@  discard block
 block discarded – undo
883 883
 	 */
884 884
 	private function createShareObject($data) {
885 885
 		$share = new Share($this->rootFolder, $this->userManager);
886
-		$share->setId((int)$data['id'])
887
-			->setShareType((int)$data['share_type'])
888
-			->setPermissions((int)$data['permissions'])
886
+		$share->setId((int) $data['id'])
887
+			->setShareType((int) $data['share_type'])
888
+			->setPermissions((int) $data['permissions'])
889 889
 			->setTarget($data['file_target'])
890
-			->setMailSend((bool)$data['mail_send'])
890
+			->setMailSend((bool) $data['mail_send'])
891 891
 			->setToken($data['token']);
892 892
 
893 893
 		$shareTime = new \DateTime();
894
-		$shareTime->setTimestamp((int)$data['stime']);
894
+		$shareTime->setTimestamp((int) $data['stime']);
895 895
 		$share->setShareTime($shareTime);
896 896
 		$share->setSharedWith($data['share_with']);
897 897
 
@@ -901,13 +901,13 @@  discard block
 block discarded – undo
901 901
 		} else {
902 902
 			//OLD SHARE
903 903
 			$share->setSharedBy($data['uid_owner']);
904
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
904
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
905 905
 
906 906
 			$owner = $path->getOwner();
907 907
 			$share->setShareOwner($owner->getUID());
908 908
 		}
909 909
 
910
-		$share->setNodeId((int)$data['file_source']);
910
+		$share->setNodeId((int) $data['file_source']);
911 911
 		$share->setNodeType($data['item_type']);
912 912
 
913 913
 		$share->setProviderId($this->identifier());
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 1 patch
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -50,420 +50,420 @@
 block discarded – undo
50 50
 
51 51
 class RequestHandlerController extends OCSController {
52 52
 
53
-	/** @var FederatedShareProvider */
54
-	private $federatedShareProvider;
55
-
56
-	/** @var IDBConnection */
57
-	private $connection;
58
-
59
-	/** @var Share\IManager */
60
-	private $shareManager;
61
-
62
-	/** @var Notifications */
63
-	private $notifications;
64
-
65
-	/** @var AddressHandler */
66
-	private $addressHandler;
67
-
68
-	/** @var  IUserManager */
69
-	private $userManager;
70
-
71
-	/** @var string */
72
-	private $shareTable = 'share';
73
-
74
-	/** @var ICloudIdManager */
75
-	private $cloudIdManager;
76
-
77
-	/** @var ILogger */
78
-	private $logger;
79
-
80
-	/** @var ICloudFederationFactory */
81
-	private $cloudFederationFactory;
82
-
83
-	/** @var ICloudFederationProviderManager */
84
-	private $cloudFederationProviderManager;
85
-
86
-	/**
87
-	 * Server2Server constructor.
88
-	 *
89
-	 * @param string $appName
90
-	 * @param IRequest $request
91
-	 * @param FederatedShareProvider $federatedShareProvider
92
-	 * @param IDBConnection $connection
93
-	 * @param Share\IManager $shareManager
94
-	 * @param Notifications $notifications
95
-	 * @param AddressHandler $addressHandler
96
-	 * @param IUserManager $userManager
97
-	 * @param ICloudIdManager $cloudIdManager
98
-	 * @param ILogger $logger
99
-	 * @param ICloudFederationFactory $cloudFederationFactory
100
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
101
-	 */
102
-	public function __construct($appName,
103
-								IRequest $request,
104
-								FederatedShareProvider $federatedShareProvider,
105
-								IDBConnection $connection,
106
-								Share\IManager $shareManager,
107
-								Notifications $notifications,
108
-								AddressHandler $addressHandler,
109
-								IUserManager $userManager,
110
-								ICloudIdManager $cloudIdManager,
111
-								ILogger $logger,
112
-								ICloudFederationFactory $cloudFederationFactory,
113
-								ICloudFederationProviderManager $cloudFederationProviderManager
114
-	) {
115
-		parent::__construct($appName, $request);
116
-
117
-		$this->federatedShareProvider = $federatedShareProvider;
118
-		$this->connection = $connection;
119
-		$this->shareManager = $shareManager;
120
-		$this->notifications = $notifications;
121
-		$this->addressHandler = $addressHandler;
122
-		$this->userManager = $userManager;
123
-		$this->cloudIdManager = $cloudIdManager;
124
-		$this->logger = $logger;
125
-		$this->cloudFederationFactory = $cloudFederationFactory;
126
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
127
-	}
128
-
129
-	/**
130
-	 * @NoCSRFRequired
131
-	 * @PublicPage
132
-	 *
133
-	 * create a new share
134
-	 *
135
-	 * @return Http\DataResponse
136
-	 * @throws OCSException
137
-	 */
138
-	public function createShare() {
139
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
140
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
141
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
142
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
143
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
144
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
145
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
146
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
147
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
148
-
149
-		if ($ownerFederatedId === null) {
150
-			$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
151
-		}
152
-		// if the owner of the share and the initiator are the same user
153
-		// we also complete the federated share ID for the initiator
154
-		if ($sharedByFederatedId === null && $owner === $sharedBy) {
155
-			$sharedByFederatedId = $ownerFederatedId;
156
-		}
157
-
158
-		$share = $this->cloudFederationFactory->getCloudFederationShare(
159
-			$shareWith,
160
-			$name,
161
-			'',
162
-			$remoteId,
163
-			$ownerFederatedId,
164
-			$owner,
165
-			$sharedByFederatedId,
166
-			$sharedBy,
167
-			$token,
168
-			'user',
169
-			'file'
170
-		);
171
-
172
-		try {
173
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
174
-			$provider->shareReceived($share);
175
-		} catch (ProviderDoesNotExistsException $e) {
176
-			throw new OCSException('Server does not support federated cloud sharing', 503);
177
-		} catch (ProviderCouldNotAddShareException $e) {
178
-			throw new OCSException($e->getMessage(), 400);
179
-		} catch (\Exception $e) {
180
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
181
-		}
182
-
183
-		return new Http\DataResponse();
184
-	}
185
-
186
-	/**
187
-	 * @NoCSRFRequired
188
-	 * @PublicPage
189
-	 *
190
-	 * create re-share on behalf of another user
191
-	 *
192
-	 * @param int $id
193
-	 * @return Http\DataResponse
194
-	 * @throws OCSBadRequestException
195
-	 * @throws OCSException
196
-	 * @throws OCSForbiddenException
197
-	 */
198
-	public function reShare($id) {
199
-		$token = $this->request->getParam('token', null);
200
-		$shareWith = $this->request->getParam('shareWith', null);
201
-		$permission = (int)$this->request->getParam('permission', null);
202
-		$remoteId = (int)$this->request->getParam('remoteId', null);
203
-
204
-		if ($id === null ||
205
-			$token === null ||
206
-			$shareWith === null ||
207
-			$permission === null ||
208
-			$remoteId === null
209
-		) {
210
-			throw new OCSBadRequestException();
211
-		}
212
-
213
-		$notification = [
214
-			'sharedSecret' => $token,
215
-			'shareWith' => $shareWith,
216
-			'senderId' => $remoteId,
217
-			'message' => 'Recipient of a share ask the owner to reshare the file'
218
-		];
219
-
220
-		try {
221
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
222
-			[$newToken, $localId] = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
223
-			return new Http\DataResponse([
224
-				'token' => $newToken,
225
-				'remoteId' => $localId
226
-			]);
227
-		} catch (ProviderDoesNotExistsException $e) {
228
-			throw new OCSException('Server does not support federated cloud sharing', 503);
229
-		} catch (ShareNotFound $e) {
230
-			$this->logger->debug('Share not found: ' . $e->getMessage());
231
-		} catch (\Exception $e) {
232
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
233
-		}
234
-
235
-		throw new OCSBadRequestException();
236
-	}
237
-
238
-
239
-	/**
240
-	 * @NoCSRFRequired
241
-	 * @PublicPage
242
-	 *
243
-	 * accept server-to-server share
244
-	 *
245
-	 * @param int $id
246
-	 * @return Http\DataResponse
247
-	 * @throws OCSException
248
-	 * @throws ShareNotFound
249
-	 * @throws \OC\HintException
250
-	 */
251
-	public function acceptShare($id) {
252
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
253
-
254
-		$notification = [
255
-			'sharedSecret' => $token,
256
-			'message' => 'Recipient accept the share'
257
-		];
258
-
259
-		try {
260
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
261
-			$provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
262
-		} catch (ProviderDoesNotExistsException $e) {
263
-			throw new OCSException('Server does not support federated cloud sharing', 503);
264
-		} catch (ShareNotFound $e) {
265
-			$this->logger->debug('Share not found: ' . $e->getMessage());
266
-		} catch (\Exception $e) {
267
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
268
-		}
269
-
270
-		return new Http\DataResponse();
271
-	}
272
-
273
-	/**
274
-	 * @NoCSRFRequired
275
-	 * @PublicPage
276
-	 *
277
-	 * decline server-to-server share
278
-	 *
279
-	 * @param int $id
280
-	 * @return Http\DataResponse
281
-	 * @throws OCSException
282
-	 */
283
-	public function declineShare($id) {
284
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
285
-
286
-		$notification = [
287
-			'sharedSecret' => $token,
288
-			'message' => 'Recipient declined the share'
289
-		];
290
-
291
-		try {
292
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
293
-			$provider->notificationReceived('SHARE_DECLINED', $id, $notification);
294
-		} catch (ProviderDoesNotExistsException $e) {
295
-			throw new OCSException('Server does not support federated cloud sharing', 503);
296
-		} catch (ShareNotFound $e) {
297
-			$this->logger->debug('Share not found: ' . $e->getMessage());
298
-		} catch (\Exception $e) {
299
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
300
-		}
301
-
302
-		return new Http\DataResponse();
303
-	}
304
-
305
-	/**
306
-	 * @NoCSRFRequired
307
-	 * @PublicPage
308
-	 *
309
-	 * remove server-to-server share if it was unshared by the owner
310
-	 *
311
-	 * @param int $id
312
-	 * @return Http\DataResponse
313
-	 * @throws OCSException
314
-	 */
315
-	public function unshare($id) {
316
-		if (!$this->isS2SEnabled()) {
317
-			throw new OCSException('Server does not support federated cloud sharing', 503);
318
-		}
319
-
320
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
321
-
322
-		try {
323
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
324
-			$notification = ['sharedSecret' => $token];
325
-			$provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
326
-		} catch (\Exception $e) {
327
-			$this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
328
-		}
329
-
330
-		return new Http\DataResponse();
331
-	}
332
-
333
-	private function cleanupRemote($remote) {
334
-		$remote = substr($remote, strpos($remote, '://') + 3);
335
-
336
-		return rtrim($remote, '/');
337
-	}
338
-
339
-
340
-	/**
341
-	 * @NoCSRFRequired
342
-	 * @PublicPage
343
-	 *
344
-	 * federated share was revoked, either by the owner or the re-sharer
345
-	 *
346
-	 * @param int $id
347
-	 * @return Http\DataResponse
348
-	 * @throws OCSBadRequestException
349
-	 */
350
-	public function revoke($id) {
351
-		$token = $this->request->getParam('token');
352
-
353
-		try {
354
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
355
-			$notification = ['sharedSecret' => $token];
356
-			$provider->notificationReceived('RESHARE_UNDO', $id, $notification);
357
-			return new Http\DataResponse();
358
-		} catch (\Exception $e) {
359
-			throw new OCSBadRequestException();
360
-		}
361
-	}
362
-
363
-	/**
364
-	 * check if server-to-server sharing is enabled
365
-	 *
366
-	 * @param bool $incoming
367
-	 * @return bool
368
-	 */
369
-	private function isS2SEnabled($incoming = false) {
370
-		$result = \OCP\App::isEnabled('files_sharing');
371
-
372
-		if ($incoming) {
373
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
374
-		} else {
375
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
376
-		}
377
-
378
-		return $result;
379
-	}
380
-
381
-	/**
382
-	 * @NoCSRFRequired
383
-	 * @PublicPage
384
-	 *
385
-	 * update share information to keep federated re-shares in sync
386
-	 *
387
-	 * @param int $id
388
-	 * @return Http\DataResponse
389
-	 * @throws OCSBadRequestException
390
-	 */
391
-	public function updatePermissions($id) {
392
-		$token = $this->request->getParam('token', null);
393
-		$ncPermissions = $this->request->getParam('permissions', null);
394
-
395
-		try {
396
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
397
-			$ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
398
-			$notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
399
-			$provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
400
-		} catch (\Exception $e) {
401
-			$this->logger->debug($e->getMessage());
402
-			throw new OCSBadRequestException();
403
-		}
404
-
405
-		return new Http\DataResponse();
406
-	}
407
-
408
-	/**
409
-	 * translate Nextcloud permissions to OCM Permissions
410
-	 *
411
-	 * @param $ncPermissions
412
-	 * @return array
413
-	 */
414
-	protected function ncPermissions2ocmPermissions($ncPermissions) {
415
-		$ocmPermissions = [];
416
-
417
-		if ($ncPermissions & Constants::PERMISSION_SHARE) {
418
-			$ocmPermissions[] = 'share';
419
-		}
420
-
421
-		if ($ncPermissions & Constants::PERMISSION_READ) {
422
-			$ocmPermissions[] = 'read';
423
-		}
424
-
425
-		if (($ncPermissions & Constants::PERMISSION_CREATE) ||
426
-			($ncPermissions & Constants::PERMISSION_UPDATE)) {
427
-			$ocmPermissions[] = 'write';
428
-		}
429
-
430
-		return $ocmPermissions;
431
-	}
432
-
433
-	/**
434
-	 * @NoCSRFRequired
435
-	 * @PublicPage
436
-	 *
437
-	 * change the owner of a server-to-server share
438
-	 *
439
-	 * @param int $id
440
-	 * @return Http\DataResponse
441
-	 * @throws \InvalidArgumentException
442
-	 * @throws OCSException
443
-	 */
444
-	public function move($id) {
445
-		if (!$this->isS2SEnabled()) {
446
-			throw new OCSException('Server does not support federated cloud sharing', 503);
447
-		}
448
-
449
-		$token = $this->request->getParam('token');
450
-		$remote = $this->request->getParam('remote');
451
-		$newRemoteId = $this->request->getParam('remote_id', $id);
452
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
453
-
454
-		$qb = $this->connection->getQueryBuilder();
455
-		$query = $qb->update('share_external')
456
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
457
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
458
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
459
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
460
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
461
-		$affected = $query->execute();
462
-
463
-		if ($affected > 0) {
464
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
465
-		} else {
466
-			throw new OCSBadRequestException('Share not found or token invalid');
467
-		}
468
-	}
53
+    /** @var FederatedShareProvider */
54
+    private $federatedShareProvider;
55
+
56
+    /** @var IDBConnection */
57
+    private $connection;
58
+
59
+    /** @var Share\IManager */
60
+    private $shareManager;
61
+
62
+    /** @var Notifications */
63
+    private $notifications;
64
+
65
+    /** @var AddressHandler */
66
+    private $addressHandler;
67
+
68
+    /** @var  IUserManager */
69
+    private $userManager;
70
+
71
+    /** @var string */
72
+    private $shareTable = 'share';
73
+
74
+    /** @var ICloudIdManager */
75
+    private $cloudIdManager;
76
+
77
+    /** @var ILogger */
78
+    private $logger;
79
+
80
+    /** @var ICloudFederationFactory */
81
+    private $cloudFederationFactory;
82
+
83
+    /** @var ICloudFederationProviderManager */
84
+    private $cloudFederationProviderManager;
85
+
86
+    /**
87
+     * Server2Server constructor.
88
+     *
89
+     * @param string $appName
90
+     * @param IRequest $request
91
+     * @param FederatedShareProvider $federatedShareProvider
92
+     * @param IDBConnection $connection
93
+     * @param Share\IManager $shareManager
94
+     * @param Notifications $notifications
95
+     * @param AddressHandler $addressHandler
96
+     * @param IUserManager $userManager
97
+     * @param ICloudIdManager $cloudIdManager
98
+     * @param ILogger $logger
99
+     * @param ICloudFederationFactory $cloudFederationFactory
100
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
101
+     */
102
+    public function __construct($appName,
103
+                                IRequest $request,
104
+                                FederatedShareProvider $federatedShareProvider,
105
+                                IDBConnection $connection,
106
+                                Share\IManager $shareManager,
107
+                                Notifications $notifications,
108
+                                AddressHandler $addressHandler,
109
+                                IUserManager $userManager,
110
+                                ICloudIdManager $cloudIdManager,
111
+                                ILogger $logger,
112
+                                ICloudFederationFactory $cloudFederationFactory,
113
+                                ICloudFederationProviderManager $cloudFederationProviderManager
114
+    ) {
115
+        parent::__construct($appName, $request);
116
+
117
+        $this->federatedShareProvider = $federatedShareProvider;
118
+        $this->connection = $connection;
119
+        $this->shareManager = $shareManager;
120
+        $this->notifications = $notifications;
121
+        $this->addressHandler = $addressHandler;
122
+        $this->userManager = $userManager;
123
+        $this->cloudIdManager = $cloudIdManager;
124
+        $this->logger = $logger;
125
+        $this->cloudFederationFactory = $cloudFederationFactory;
126
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
127
+    }
128
+
129
+    /**
130
+     * @NoCSRFRequired
131
+     * @PublicPage
132
+     *
133
+     * create a new share
134
+     *
135
+     * @return Http\DataResponse
136
+     * @throws OCSException
137
+     */
138
+    public function createShare() {
139
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
140
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
141
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
142
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
143
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
144
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
145
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
146
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
147
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
148
+
149
+        if ($ownerFederatedId === null) {
150
+            $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
151
+        }
152
+        // if the owner of the share and the initiator are the same user
153
+        // we also complete the federated share ID for the initiator
154
+        if ($sharedByFederatedId === null && $owner === $sharedBy) {
155
+            $sharedByFederatedId = $ownerFederatedId;
156
+        }
157
+
158
+        $share = $this->cloudFederationFactory->getCloudFederationShare(
159
+            $shareWith,
160
+            $name,
161
+            '',
162
+            $remoteId,
163
+            $ownerFederatedId,
164
+            $owner,
165
+            $sharedByFederatedId,
166
+            $sharedBy,
167
+            $token,
168
+            'user',
169
+            'file'
170
+        );
171
+
172
+        try {
173
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
174
+            $provider->shareReceived($share);
175
+        } catch (ProviderDoesNotExistsException $e) {
176
+            throw new OCSException('Server does not support federated cloud sharing', 503);
177
+        } catch (ProviderCouldNotAddShareException $e) {
178
+            throw new OCSException($e->getMessage(), 400);
179
+        } catch (\Exception $e) {
180
+            throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
181
+        }
182
+
183
+        return new Http\DataResponse();
184
+    }
185
+
186
+    /**
187
+     * @NoCSRFRequired
188
+     * @PublicPage
189
+     *
190
+     * create re-share on behalf of another user
191
+     *
192
+     * @param int $id
193
+     * @return Http\DataResponse
194
+     * @throws OCSBadRequestException
195
+     * @throws OCSException
196
+     * @throws OCSForbiddenException
197
+     */
198
+    public function reShare($id) {
199
+        $token = $this->request->getParam('token', null);
200
+        $shareWith = $this->request->getParam('shareWith', null);
201
+        $permission = (int)$this->request->getParam('permission', null);
202
+        $remoteId = (int)$this->request->getParam('remoteId', null);
203
+
204
+        if ($id === null ||
205
+            $token === null ||
206
+            $shareWith === null ||
207
+            $permission === null ||
208
+            $remoteId === null
209
+        ) {
210
+            throw new OCSBadRequestException();
211
+        }
212
+
213
+        $notification = [
214
+            'sharedSecret' => $token,
215
+            'shareWith' => $shareWith,
216
+            'senderId' => $remoteId,
217
+            'message' => 'Recipient of a share ask the owner to reshare the file'
218
+        ];
219
+
220
+        try {
221
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
222
+            [$newToken, $localId] = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
223
+            return new Http\DataResponse([
224
+                'token' => $newToken,
225
+                'remoteId' => $localId
226
+            ]);
227
+        } catch (ProviderDoesNotExistsException $e) {
228
+            throw new OCSException('Server does not support federated cloud sharing', 503);
229
+        } catch (ShareNotFound $e) {
230
+            $this->logger->debug('Share not found: ' . $e->getMessage());
231
+        } catch (\Exception $e) {
232
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
233
+        }
234
+
235
+        throw new OCSBadRequestException();
236
+    }
237
+
238
+
239
+    /**
240
+     * @NoCSRFRequired
241
+     * @PublicPage
242
+     *
243
+     * accept server-to-server share
244
+     *
245
+     * @param int $id
246
+     * @return Http\DataResponse
247
+     * @throws OCSException
248
+     * @throws ShareNotFound
249
+     * @throws \OC\HintException
250
+     */
251
+    public function acceptShare($id) {
252
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
253
+
254
+        $notification = [
255
+            'sharedSecret' => $token,
256
+            'message' => 'Recipient accept the share'
257
+        ];
258
+
259
+        try {
260
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
261
+            $provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
262
+        } catch (ProviderDoesNotExistsException $e) {
263
+            throw new OCSException('Server does not support federated cloud sharing', 503);
264
+        } catch (ShareNotFound $e) {
265
+            $this->logger->debug('Share not found: ' . $e->getMessage());
266
+        } catch (\Exception $e) {
267
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
268
+        }
269
+
270
+        return new Http\DataResponse();
271
+    }
272
+
273
+    /**
274
+     * @NoCSRFRequired
275
+     * @PublicPage
276
+     *
277
+     * decline server-to-server share
278
+     *
279
+     * @param int $id
280
+     * @return Http\DataResponse
281
+     * @throws OCSException
282
+     */
283
+    public function declineShare($id) {
284
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
285
+
286
+        $notification = [
287
+            'sharedSecret' => $token,
288
+            'message' => 'Recipient declined the share'
289
+        ];
290
+
291
+        try {
292
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
293
+            $provider->notificationReceived('SHARE_DECLINED', $id, $notification);
294
+        } catch (ProviderDoesNotExistsException $e) {
295
+            throw new OCSException('Server does not support federated cloud sharing', 503);
296
+        } catch (ShareNotFound $e) {
297
+            $this->logger->debug('Share not found: ' . $e->getMessage());
298
+        } catch (\Exception $e) {
299
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
300
+        }
301
+
302
+        return new Http\DataResponse();
303
+    }
304
+
305
+    /**
306
+     * @NoCSRFRequired
307
+     * @PublicPage
308
+     *
309
+     * remove server-to-server share if it was unshared by the owner
310
+     *
311
+     * @param int $id
312
+     * @return Http\DataResponse
313
+     * @throws OCSException
314
+     */
315
+    public function unshare($id) {
316
+        if (!$this->isS2SEnabled()) {
317
+            throw new OCSException('Server does not support federated cloud sharing', 503);
318
+        }
319
+
320
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
321
+
322
+        try {
323
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
324
+            $notification = ['sharedSecret' => $token];
325
+            $provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
326
+        } catch (\Exception $e) {
327
+            $this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
328
+        }
329
+
330
+        return new Http\DataResponse();
331
+    }
332
+
333
+    private function cleanupRemote($remote) {
334
+        $remote = substr($remote, strpos($remote, '://') + 3);
335
+
336
+        return rtrim($remote, '/');
337
+    }
338
+
339
+
340
+    /**
341
+     * @NoCSRFRequired
342
+     * @PublicPage
343
+     *
344
+     * federated share was revoked, either by the owner or the re-sharer
345
+     *
346
+     * @param int $id
347
+     * @return Http\DataResponse
348
+     * @throws OCSBadRequestException
349
+     */
350
+    public function revoke($id) {
351
+        $token = $this->request->getParam('token');
352
+
353
+        try {
354
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
355
+            $notification = ['sharedSecret' => $token];
356
+            $provider->notificationReceived('RESHARE_UNDO', $id, $notification);
357
+            return new Http\DataResponse();
358
+        } catch (\Exception $e) {
359
+            throw new OCSBadRequestException();
360
+        }
361
+    }
362
+
363
+    /**
364
+     * check if server-to-server sharing is enabled
365
+     *
366
+     * @param bool $incoming
367
+     * @return bool
368
+     */
369
+    private function isS2SEnabled($incoming = false) {
370
+        $result = \OCP\App::isEnabled('files_sharing');
371
+
372
+        if ($incoming) {
373
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
374
+        } else {
375
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
376
+        }
377
+
378
+        return $result;
379
+    }
380
+
381
+    /**
382
+     * @NoCSRFRequired
383
+     * @PublicPage
384
+     *
385
+     * update share information to keep federated re-shares in sync
386
+     *
387
+     * @param int $id
388
+     * @return Http\DataResponse
389
+     * @throws OCSBadRequestException
390
+     */
391
+    public function updatePermissions($id) {
392
+        $token = $this->request->getParam('token', null);
393
+        $ncPermissions = $this->request->getParam('permissions', null);
394
+
395
+        try {
396
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
397
+            $ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
398
+            $notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
399
+            $provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
400
+        } catch (\Exception $e) {
401
+            $this->logger->debug($e->getMessage());
402
+            throw new OCSBadRequestException();
403
+        }
404
+
405
+        return new Http\DataResponse();
406
+    }
407
+
408
+    /**
409
+     * translate Nextcloud permissions to OCM Permissions
410
+     *
411
+     * @param $ncPermissions
412
+     * @return array
413
+     */
414
+    protected function ncPermissions2ocmPermissions($ncPermissions) {
415
+        $ocmPermissions = [];
416
+
417
+        if ($ncPermissions & Constants::PERMISSION_SHARE) {
418
+            $ocmPermissions[] = 'share';
419
+        }
420
+
421
+        if ($ncPermissions & Constants::PERMISSION_READ) {
422
+            $ocmPermissions[] = 'read';
423
+        }
424
+
425
+        if (($ncPermissions & Constants::PERMISSION_CREATE) ||
426
+            ($ncPermissions & Constants::PERMISSION_UPDATE)) {
427
+            $ocmPermissions[] = 'write';
428
+        }
429
+
430
+        return $ocmPermissions;
431
+    }
432
+
433
+    /**
434
+     * @NoCSRFRequired
435
+     * @PublicPage
436
+     *
437
+     * change the owner of a server-to-server share
438
+     *
439
+     * @param int $id
440
+     * @return Http\DataResponse
441
+     * @throws \InvalidArgumentException
442
+     * @throws OCSException
443
+     */
444
+    public function move($id) {
445
+        if (!$this->isS2SEnabled()) {
446
+            throw new OCSException('Server does not support federated cloud sharing', 503);
447
+        }
448
+
449
+        $token = $this->request->getParam('token');
450
+        $remote = $this->request->getParam('remote');
451
+        $newRemoteId = $this->request->getParam('remote_id', $id);
452
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
453
+
454
+        $qb = $this->connection->getQueryBuilder();
455
+        $query = $qb->update('share_external')
456
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
457
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
458
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
459
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
460
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
461
+        $affected = $query->execute();
462
+
463
+        if ($affected > 0) {
464
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
465
+        } else {
466
+            throw new OCSBadRequestException('Share not found or token invalid');
467
+        }
468
+    }
469 469
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 1 patch
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -56,177 +56,177 @@
 block discarded – undo
56 56
  */
57 57
 class MountPublicLinkController extends Controller {
58 58
 
59
-	/** @var FederatedShareProvider */
60
-	private $federatedShareProvider;
61
-
62
-	/** @var AddressHandler */
63
-	private $addressHandler;
64
-
65
-	/** @var IManager  */
66
-	private $shareManager;
67
-
68
-	/** @var  ISession */
69
-	private $session;
70
-
71
-	/** @var IL10N */
72
-	private $l;
73
-
74
-	/** @var IUserSession */
75
-	private $userSession;
76
-
77
-	/** @var IClientService */
78
-	private $clientService;
79
-
80
-	/** @var ICloudIdManager  */
81
-	private $cloudIdManager;
82
-
83
-	/**
84
-	 * MountPublicLinkController constructor.
85
-	 *
86
-	 * @param string $appName
87
-	 * @param IRequest $request
88
-	 * @param FederatedShareProvider $federatedShareProvider
89
-	 * @param IManager $shareManager
90
-	 * @param AddressHandler $addressHandler
91
-	 * @param ISession $session
92
-	 * @param IL10N $l
93
-	 * @param IUserSession $userSession
94
-	 * @param IClientService $clientService
95
-	 * @param ICloudIdManager $cloudIdManager
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								FederatedShareProvider $federatedShareProvider,
100
-								IManager $shareManager,
101
-								AddressHandler $addressHandler,
102
-								ISession $session,
103
-								IL10N $l,
104
-								IUserSession $userSession,
105
-								IClientService $clientService,
106
-								ICloudIdManager $cloudIdManager
107
-	) {
108
-		parent::__construct($appName, $request);
109
-
110
-		$this->federatedShareProvider = $federatedShareProvider;
111
-		$this->shareManager = $shareManager;
112
-		$this->addressHandler = $addressHandler;
113
-		$this->session = $session;
114
-		$this->l = $l;
115
-		$this->userSession = $userSession;
116
-		$this->clientService = $clientService;
117
-		$this->cloudIdManager = $cloudIdManager;
118
-	}
119
-
120
-	/**
121
-	 * send federated share to a user of a public link
122
-	 *
123
-	 * @NoCSRFRequired
124
-	 * @PublicPage
125
-	 * @BruteForceProtection(action=publicLink2FederatedShare)
126
-	 *
127
-	 * @param string $shareWith
128
-	 * @param string $token
129
-	 * @param string $password
130
-	 * @return JSONResponse
131
-	 */
132
-	public function createFederatedShare($shareWith, $token, $password = '') {
133
-		if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
134
-			return new JSONResponse(
135
-				['message' => 'This server doesn\'t support outgoing federated shares'],
136
-				Http::STATUS_BAD_REQUEST
137
-			);
138
-		}
139
-
140
-		try {
141
-			[, $server] = $this->addressHandler->splitUserRemote($shareWith);
142
-			$share = $this->shareManager->getShareByToken($token);
143
-		} catch (HintException $e) {
144
-			return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
145
-		}
146
-
147
-		// make sure that user is authenticated in case of a password protected link
148
-		$storedPassword = $share->getPassword();
149
-		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
150
-			$this->shareManager->checkPassword($share, $password);
151
-		if (!empty($storedPassword) && !$authenticated) {
152
-			$response = new JSONResponse(
153
-				['message' => 'No permission to access the share'],
154
-				Http::STATUS_BAD_REQUEST
155
-			);
156
-			$response->throttle();
157
-			return $response;
158
-		}
159
-
160
-		$share->setSharedWith($shareWith);
161
-		$share->setShareType(IShare::TYPE_REMOTE);
162
-
163
-		try {
164
-			$this->federatedShareProvider->create($share);
165
-		} catch (\Exception $e) {
166
-			\OC::$server->getLogger()->logException($e, [
167
-				'level' => ILogger::WARN,
168
-				'app' => 'federatedfilesharing',
169
-			]);
170
-			return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
171
-		}
172
-
173
-		return new JSONResponse(['remoteUrl' => $server]);
174
-	}
175
-
176
-	/**
177
-	 * ask other server to get a federated share
178
-	 *
179
-	 * @NoAdminRequired
180
-	 *
181
-	 * @param string $token
182
-	 * @param string $remote
183
-	 * @param string $password
184
-	 * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
185
-	 * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
186
-	 * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
187
-	 * @return JSONResponse
188
-	 */
189
-	public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
190
-		// check if server admin allows to mount public links from other servers
191
-		if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
192
-			return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
193
-		}
194
-
195
-		$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
196
-
197
-		$httpClient = $this->clientService->newClient();
198
-
199
-		try {
200
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
201
-				[
202
-					'body' =>
203
-						[
204
-							'token' => $token,
205
-							'shareWith' => rtrim($cloudId->getId(), '/'),
206
-							'password' => $password
207
-						],
208
-					'connect_timeout' => 10,
209
-				]
210
-			);
211
-		} catch (\Exception $e) {
212
-			if (empty($password)) {
213
-				$message = $this->l->t("Couldn't establish a federated share.");
214
-			} else {
215
-				$message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
216
-			}
217
-			return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
218
-		}
219
-
220
-		$body = $response->getBody();
221
-		$result = json_decode($body, true);
222
-
223
-		if (is_array($result) && isset($result['remoteUrl'])) {
224
-			return new JSONResponse(['message' => $this->l->t('Federated Share request sent, you will receive an invitation. Check your notifications.')]);
225
-		}
226
-
227
-		// if we doesn't get the expected response we assume that we try to add
228
-		// a federated share from a Nextcloud <= 9 server
229
-		$message = $this->l->t("Couldn't establish a federated share, it looks like the server to federate with is too old (Nextcloud <= 9).");
230
-		return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
231
-	}
59
+    /** @var FederatedShareProvider */
60
+    private $federatedShareProvider;
61
+
62
+    /** @var AddressHandler */
63
+    private $addressHandler;
64
+
65
+    /** @var IManager  */
66
+    private $shareManager;
67
+
68
+    /** @var  ISession */
69
+    private $session;
70
+
71
+    /** @var IL10N */
72
+    private $l;
73
+
74
+    /** @var IUserSession */
75
+    private $userSession;
76
+
77
+    /** @var IClientService */
78
+    private $clientService;
79
+
80
+    /** @var ICloudIdManager  */
81
+    private $cloudIdManager;
82
+
83
+    /**
84
+     * MountPublicLinkController constructor.
85
+     *
86
+     * @param string $appName
87
+     * @param IRequest $request
88
+     * @param FederatedShareProvider $federatedShareProvider
89
+     * @param IManager $shareManager
90
+     * @param AddressHandler $addressHandler
91
+     * @param ISession $session
92
+     * @param IL10N $l
93
+     * @param IUserSession $userSession
94
+     * @param IClientService $clientService
95
+     * @param ICloudIdManager $cloudIdManager
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                FederatedShareProvider $federatedShareProvider,
100
+                                IManager $shareManager,
101
+                                AddressHandler $addressHandler,
102
+                                ISession $session,
103
+                                IL10N $l,
104
+                                IUserSession $userSession,
105
+                                IClientService $clientService,
106
+                                ICloudIdManager $cloudIdManager
107
+    ) {
108
+        parent::__construct($appName, $request);
109
+
110
+        $this->federatedShareProvider = $federatedShareProvider;
111
+        $this->shareManager = $shareManager;
112
+        $this->addressHandler = $addressHandler;
113
+        $this->session = $session;
114
+        $this->l = $l;
115
+        $this->userSession = $userSession;
116
+        $this->clientService = $clientService;
117
+        $this->cloudIdManager = $cloudIdManager;
118
+    }
119
+
120
+    /**
121
+     * send federated share to a user of a public link
122
+     *
123
+     * @NoCSRFRequired
124
+     * @PublicPage
125
+     * @BruteForceProtection(action=publicLink2FederatedShare)
126
+     *
127
+     * @param string $shareWith
128
+     * @param string $token
129
+     * @param string $password
130
+     * @return JSONResponse
131
+     */
132
+    public function createFederatedShare($shareWith, $token, $password = '') {
133
+        if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
134
+            return new JSONResponse(
135
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
136
+                Http::STATUS_BAD_REQUEST
137
+            );
138
+        }
139
+
140
+        try {
141
+            [, $server] = $this->addressHandler->splitUserRemote($shareWith);
142
+            $share = $this->shareManager->getShareByToken($token);
143
+        } catch (HintException $e) {
144
+            return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
145
+        }
146
+
147
+        // make sure that user is authenticated in case of a password protected link
148
+        $storedPassword = $share->getPassword();
149
+        $authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
150
+            $this->shareManager->checkPassword($share, $password);
151
+        if (!empty($storedPassword) && !$authenticated) {
152
+            $response = new JSONResponse(
153
+                ['message' => 'No permission to access the share'],
154
+                Http::STATUS_BAD_REQUEST
155
+            );
156
+            $response->throttle();
157
+            return $response;
158
+        }
159
+
160
+        $share->setSharedWith($shareWith);
161
+        $share->setShareType(IShare::TYPE_REMOTE);
162
+
163
+        try {
164
+            $this->federatedShareProvider->create($share);
165
+        } catch (\Exception $e) {
166
+            \OC::$server->getLogger()->logException($e, [
167
+                'level' => ILogger::WARN,
168
+                'app' => 'federatedfilesharing',
169
+            ]);
170
+            return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
171
+        }
172
+
173
+        return new JSONResponse(['remoteUrl' => $server]);
174
+    }
175
+
176
+    /**
177
+     * ask other server to get a federated share
178
+     *
179
+     * @NoAdminRequired
180
+     *
181
+     * @param string $token
182
+     * @param string $remote
183
+     * @param string $password
184
+     * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
185
+     * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
186
+     * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
187
+     * @return JSONResponse
188
+     */
189
+    public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
190
+        // check if server admin allows to mount public links from other servers
191
+        if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
192
+            return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
193
+        }
194
+
195
+        $cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
196
+
197
+        $httpClient = $this->clientService->newClient();
198
+
199
+        try {
200
+            $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
201
+                [
202
+                    'body' =>
203
+                        [
204
+                            'token' => $token,
205
+                            'shareWith' => rtrim($cloudId->getId(), '/'),
206
+                            'password' => $password
207
+                        ],
208
+                    'connect_timeout' => 10,
209
+                ]
210
+            );
211
+        } catch (\Exception $e) {
212
+            if (empty($password)) {
213
+                $message = $this->l->t("Couldn't establish a federated share.");
214
+            } else {
215
+                $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
216
+            }
217
+            return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
218
+        }
219
+
220
+        $body = $response->getBody();
221
+        $result = json_decode($body, true);
222
+
223
+        if (is_array($result) && isset($result['remoteUrl'])) {
224
+            return new JSONResponse(['message' => $this->l->t('Federated Share request sent, you will receive an invitation. Check your notifications.')]);
225
+        }
226
+
227
+        // if we doesn't get the expected response we assume that we try to add
228
+        // a federated share from a Nextcloud <= 9 server
229
+        $message = $this->l->t("Couldn't establish a federated share, it looks like the server to federate with is too old (Nextcloud <= 9).");
230
+        return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
231
+    }
232 232
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/OCM/CloudFederationProviderFiles.php 2 patches
Indentation   +776 added lines, -776 removed lines patch added patch discarded remove patch
@@ -62,780 +62,780 @@
 block discarded – undo
62 62
 
63 63
 class CloudFederationProviderFiles implements ICloudFederationProvider {
64 64
 
65
-	/** @var IAppManager */
66
-	private $appManager;
67
-
68
-	/** @var FederatedShareProvider */
69
-	private $federatedShareProvider;
70
-
71
-	/** @var AddressHandler */
72
-	private $addressHandler;
73
-
74
-	/** @var ILogger */
75
-	private $logger;
76
-
77
-	/** @var IUserManager */
78
-	private $userManager;
79
-
80
-	/** @var IManager */
81
-	private $shareManager;
82
-
83
-	/** @var ICloudIdManager */
84
-	private $cloudIdManager;
85
-
86
-	/** @var IActivityManager */
87
-	private $activityManager;
88
-
89
-	/** @var INotificationManager */
90
-	private $notificationManager;
91
-
92
-	/** @var IURLGenerator */
93
-	private $urlGenerator;
94
-
95
-	/** @var ICloudFederationFactory */
96
-	private $cloudFederationFactory;
97
-
98
-	/** @var ICloudFederationProviderManager */
99
-	private $cloudFederationProviderManager;
100
-
101
-	/** @var IDBConnection */
102
-	private $connection;
103
-
104
-	/** @var IGroupManager */
105
-	private $groupManager;
106
-
107
-	/**
108
-	 * CloudFederationProvider constructor.
109
-	 *
110
-	 * @param IAppManager $appManager
111
-	 * @param FederatedShareProvider $federatedShareProvider
112
-	 * @param AddressHandler $addressHandler
113
-	 * @param ILogger $logger
114
-	 * @param IUserManager $userManager
115
-	 * @param IManager $shareManager
116
-	 * @param ICloudIdManager $cloudIdManager
117
-	 * @param IActivityManager $activityManager
118
-	 * @param INotificationManager $notificationManager
119
-	 * @param IURLGenerator $urlGenerator
120
-	 * @param ICloudFederationFactory $cloudFederationFactory
121
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
122
-	 * @param IDBConnection $connection
123
-	 * @param IGroupManager $groupManager
124
-	 */
125
-	public function __construct(IAppManager $appManager,
126
-								FederatedShareProvider $federatedShareProvider,
127
-								AddressHandler $addressHandler,
128
-								ILogger $logger,
129
-								IUserManager $userManager,
130
-								IManager $shareManager,
131
-								ICloudIdManager $cloudIdManager,
132
-								IActivityManager $activityManager,
133
-								INotificationManager $notificationManager,
134
-								IURLGenerator $urlGenerator,
135
-								ICloudFederationFactory $cloudFederationFactory,
136
-								ICloudFederationProviderManager $cloudFederationProviderManager,
137
-								IDBConnection $connection,
138
-								IGroupManager $groupManager
139
-	) {
140
-		$this->appManager = $appManager;
141
-		$this->federatedShareProvider = $federatedShareProvider;
142
-		$this->addressHandler = $addressHandler;
143
-		$this->logger = $logger;
144
-		$this->userManager = $userManager;
145
-		$this->shareManager = $shareManager;
146
-		$this->cloudIdManager = $cloudIdManager;
147
-		$this->activityManager = $activityManager;
148
-		$this->notificationManager = $notificationManager;
149
-		$this->urlGenerator = $urlGenerator;
150
-		$this->cloudFederationFactory = $cloudFederationFactory;
151
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
152
-		$this->connection = $connection;
153
-		$this->groupManager = $groupManager;
154
-	}
155
-
156
-
157
-
158
-	/**
159
-	 * @return string
160
-	 */
161
-	public function getShareType() {
162
-		return 'file';
163
-	}
164
-
165
-	/**
166
-	 * share received from another server
167
-	 *
168
-	 * @param ICloudFederationShare $share
169
-	 * @return string provider specific unique ID of the share
170
-	 *
171
-	 * @throws ProviderCouldNotAddShareException
172
-	 * @throws \OCP\AppFramework\QueryException
173
-	 * @throws \OC\HintException
174
-	 * @since 14.0.0
175
-	 */
176
-	public function shareReceived(ICloudFederationShare $share) {
177
-		if (!$this->isS2SEnabled(true)) {
178
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
179
-		}
180
-
181
-		$protocol = $share->getProtocol();
182
-		if ($protocol['name'] !== 'webdav') {
183
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
184
-		}
185
-
186
-		[$ownerUid, $remote] = $this->addressHandler->splitUserRemote($share->getOwner());
187
-		// for backward compatibility make sure that the remote url stored in the
188
-		// database ends with a trailing slash
189
-		if (substr($remote, -1) !== '/') {
190
-			$remote = $remote . '/';
191
-		}
192
-
193
-		$token = $share->getShareSecret();
194
-		$name = $share->getResourceName();
195
-		$owner = $share->getOwnerDisplayName();
196
-		$sharedBy = $share->getSharedByDisplayName();
197
-		$shareWith = $share->getShareWith();
198
-		$remoteId = $share->getProviderId();
199
-		$sharedByFederatedId = $share->getSharedBy();
200
-		$ownerFederatedId = $share->getOwner();
201
-		$shareType = $this->mapShareTypeToNextcloud($share->getShareType());
202
-
203
-		// if no explicit information about the person who created the share was send
204
-		// we assume that the share comes from the owner
205
-		if ($sharedByFederatedId === null) {
206
-			$sharedBy = $owner;
207
-			$sharedByFederatedId = $ownerFederatedId;
208
-		}
209
-
210
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
211
-			if (!Util::isValidFileName($name)) {
212
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
213
-			}
214
-
215
-			// FIXME this should be a method in the user management instead
216
-			if ($shareType === IShare::TYPE_USER) {
217
-				$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
218
-				Util::emitHook(
219
-					'\OCA\Files_Sharing\API\Server2Server',
220
-					'preLoginNameUsedAsUserName',
221
-					['uid' => &$shareWith]
222
-				);
223
-				$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
224
-
225
-				if (!$this->userManager->userExists($shareWith)) {
226
-					throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
227
-				}
228
-
229
-				\OC_Util::setupFS($shareWith);
230
-			}
231
-
232
-			if ($shareType === IShare::TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
233
-				throw new ProviderCouldNotAddShareException('Group does not exists', '',Http::STATUS_BAD_REQUEST);
234
-			}
235
-
236
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
237
-				\OC::$server->getDatabaseConnection(),
238
-				Filesystem::getMountManager(),
239
-				Filesystem::getLoader(),
240
-				\OC::$server->getHTTPClientService(),
241
-				\OC::$server->getNotificationManager(),
242
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
243
-				\OC::$server->getCloudFederationProviderManager(),
244
-				\OC::$server->getCloudFederationFactory(),
245
-				\OC::$server->getGroupManager(),
246
-				\OC::$server->getUserManager(),
247
-				$shareWith,
248
-				\OC::$server->query(IEventDispatcher::class)
249
-			);
250
-
251
-			try {
252
-				$externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
253
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
254
-
255
-				if ($shareType === IShare::TYPE_USER) {
256
-					$event = $this->activityManager->generateEvent();
257
-					$event->setApp('files_sharing')
258
-						->setType('remote_share')
259
-						->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
260
-						->setAffectedUser($shareWith)
261
-						->setObject('remote_share', (int)$shareId, $name);
262
-					\OC::$server->getActivityManager()->publish($event);
263
-					$this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
264
-				} else {
265
-					$groupMembers = $this->groupManager->get($shareWith)->getUsers();
266
-					foreach ($groupMembers as $user) {
267
-						$event = $this->activityManager->generateEvent();
268
-						$event->setApp('files_sharing')
269
-							->setType('remote_share')
270
-							->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
271
-							->setAffectedUser($user->getUID())
272
-							->setObject('remote_share', (int)$shareId, $name);
273
-						\OC::$server->getActivityManager()->publish($event);
274
-						$this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
275
-					}
276
-				}
277
-				return $shareId;
278
-			} catch (\Exception $e) {
279
-				$this->logger->logException($e, [
280
-					'message' => 'Server can not add remote share.',
281
-					'level' => ILogger::ERROR,
282
-					'app' => 'files_sharing'
283
-				]);
284
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
285
-			}
286
-		}
287
-
288
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
289
-	}
290
-
291
-	/**
292
-	 * notification received from another server
293
-	 *
294
-	 * @param string $notificationType (e.g. SHARE_ACCEPTED)
295
-	 * @param string $providerId id of the share
296
-	 * @param array $notification payload of the notification
297
-	 * @return array data send back to the sender
298
-	 *
299
-	 * @throws ActionNotSupportedException
300
-	 * @throws AuthenticationFailedException
301
-	 * @throws BadRequestException
302
-	 * @throws \OC\HintException
303
-	 * @since 14.0.0
304
-	 */
305
-	public function notificationReceived($notificationType, $providerId, array $notification) {
306
-		switch ($notificationType) {
307
-			case 'SHARE_ACCEPTED':
308
-				return $this->shareAccepted($providerId, $notification);
309
-			case 'SHARE_DECLINED':
310
-				return $this->shareDeclined($providerId, $notification);
311
-			case 'SHARE_UNSHARED':
312
-				return $this->unshare($providerId, $notification);
313
-			case 'REQUEST_RESHARE':
314
-				return $this->reshareRequested($providerId, $notification);
315
-			case 'RESHARE_UNDO':
316
-				return $this->undoReshare($providerId, $notification);
317
-			case 'RESHARE_CHANGE_PERMISSION':
318
-				return $this->updateResharePermissions($providerId, $notification);
319
-		}
320
-
321
-
322
-		throw new BadRequestException([$notificationType]);
323
-	}
324
-
325
-	/**
326
-	 * map OCM share type (strings) to Nextcloud internal share types (integer)
327
-	 *
328
-	 * @param string $shareType
329
-	 * @return int
330
-	 */
331
-	private function mapShareTypeToNextcloud($shareType) {
332
-		$result = IShare::TYPE_USER;
333
-		if ($shareType === 'group') {
334
-			$result = IShare::TYPE_GROUP;
335
-		}
336
-
337
-		return $result;
338
-	}
339
-
340
-	private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name): void {
341
-		$notification = $this->notificationManager->createNotification();
342
-		$notification->setApp('files_sharing')
343
-			->setUser($shareWith)
344
-			->setDateTime(new \DateTime())
345
-			->setObject('remote_share', $shareId)
346
-			->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
347
-
348
-		$declineAction = $notification->createAction();
349
-		$declineAction->setLabel('decline')
350
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
351
-		$notification->addAction($declineAction);
352
-
353
-		$acceptAction = $notification->createAction();
354
-		$acceptAction->setLabel('accept')
355
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
356
-		$notification->addAction($acceptAction);
357
-
358
-		$this->notificationManager->notify($notification);
359
-	}
360
-
361
-	/**
362
-	 * process notification that the recipient accepted a share
363
-	 *
364
-	 * @param string $id
365
-	 * @param array $notification
366
-	 * @return array
367
-	 * @throws ActionNotSupportedException
368
-	 * @throws AuthenticationFailedException
369
-	 * @throws BadRequestException
370
-	 * @throws \OC\HintException
371
-	 */
372
-	private function shareAccepted($id, array $notification) {
373
-		if (!$this->isS2SEnabled()) {
374
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
375
-		}
376
-
377
-		if (!isset($notification['sharedSecret'])) {
378
-			throw new BadRequestException(['sharedSecret']);
379
-		}
380
-
381
-		$token = $notification['sharedSecret'];
382
-
383
-		$share = $this->federatedShareProvider->getShareById($id);
384
-
385
-		$this->verifyShare($share, $token);
386
-		$this->executeAcceptShare($share);
387
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
388
-			[, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
389
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
390
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
391
-			$notification->setMessage(
392
-				'SHARE_ACCEPTED',
393
-				'file',
394
-				$remoteId,
395
-				[
396
-					'sharedSecret' => $token,
397
-					'message' => 'Recipient accepted the re-share'
398
-				]
399
-
400
-			);
401
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
402
-		}
403
-
404
-		return [];
405
-	}
406
-
407
-	/**
408
-	 * @param IShare $share
409
-	 * @throws ShareNotFound
410
-	 */
411
-	protected function executeAcceptShare(IShare $share) {
412
-		try {
413
-			$fileId = (int)$share->getNode()->getId();
414
-			[$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
415
-		} catch (\Exception $e) {
416
-			throw new ShareNotFound();
417
-		}
418
-
419
-		$event = $this->activityManager->generateEvent();
420
-		$event->setApp('files_sharing')
421
-			->setType('remote_share')
422
-			->setAffectedUser($this->getCorrectUid($share))
423
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
424
-			->setObject('files', $fileId, $file)
425
-			->setLink($link);
426
-		$this->activityManager->publish($event);
427
-	}
428
-
429
-	/**
430
-	 * process notification that the recipient declined a share
431
-	 *
432
-	 * @param string $id
433
-	 * @param array $notification
434
-	 * @return array
435
-	 * @throws ActionNotSupportedException
436
-	 * @throws AuthenticationFailedException
437
-	 * @throws BadRequestException
438
-	 * @throws ShareNotFound
439
-	 * @throws \OC\HintException
440
-	 *
441
-	 */
442
-	protected function shareDeclined($id, array $notification) {
443
-		if (!$this->isS2SEnabled()) {
444
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
445
-		}
446
-
447
-		if (!isset($notification['sharedSecret'])) {
448
-			throw new BadRequestException(['sharedSecret']);
449
-		}
450
-
451
-		$token = $notification['sharedSecret'];
452
-
453
-		$share = $this->federatedShareProvider->getShareById($id);
454
-
455
-		$this->verifyShare($share, $token);
456
-
457
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
458
-			[, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
459
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
460
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
461
-			$notification->setMessage(
462
-				'SHARE_DECLINED',
463
-				'file',
464
-				$remoteId,
465
-				[
466
-					'sharedSecret' => $token,
467
-					'message' => 'Recipient declined the re-share'
468
-				]
469
-
470
-			);
471
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
472
-		}
473
-
474
-		$this->executeDeclineShare($share);
475
-
476
-		return [];
477
-	}
478
-
479
-	/**
480
-	 * delete declined share and create a activity
481
-	 *
482
-	 * @param IShare $share
483
-	 * @throws ShareNotFound
484
-	 */
485
-	protected function executeDeclineShare(IShare $share) {
486
-		$this->federatedShareProvider->removeShareFromTable($share);
487
-
488
-		try {
489
-			$fileId = (int)$share->getNode()->getId();
490
-			[$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
491
-		} catch (\Exception $e) {
492
-			throw new ShareNotFound();
493
-		}
494
-
495
-		$event = $this->activityManager->generateEvent();
496
-		$event->setApp('files_sharing')
497
-			->setType('remote_share')
498
-			->setAffectedUser($this->getCorrectUid($share))
499
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
500
-			->setObject('files', $fileId, $file)
501
-			->setLink($link);
502
-		$this->activityManager->publish($event);
503
-	}
504
-
505
-	/**
506
-	 * received the notification that the owner unshared a file from you
507
-	 *
508
-	 * @param string $id
509
-	 * @param array $notification
510
-	 * @return array
511
-	 * @throws AuthenticationFailedException
512
-	 * @throws BadRequestException
513
-	 */
514
-	private function undoReshare($id, array $notification) {
515
-		if (!isset($notification['sharedSecret'])) {
516
-			throw new BadRequestException(['sharedSecret']);
517
-		}
518
-		$token = $notification['sharedSecret'];
519
-
520
-		$share = $this->federatedShareProvider->getShareById($id);
521
-
522
-		$this->verifyShare($share, $token);
523
-		$this->federatedShareProvider->removeShareFromTable($share);
524
-		return [];
525
-	}
526
-
527
-	/**
528
-	 * unshare file from self
529
-	 *
530
-	 * @param string $id
531
-	 * @param array $notification
532
-	 * @return array
533
-	 * @throws ActionNotSupportedException
534
-	 * @throws BadRequestException
535
-	 */
536
-	private function unshare($id, array $notification) {
537
-		if (!$this->isS2SEnabled(true)) {
538
-			throw new ActionNotSupportedException("incoming shares disabled!");
539
-		}
540
-
541
-		if (!isset($notification['sharedSecret'])) {
542
-			throw new BadRequestException(['sharedSecret']);
543
-		}
544
-		$token = $notification['sharedSecret'];
545
-
546
-		$qb = $this->connection->getQueryBuilder();
547
-		$qb->select('*')
548
-			->from('share_external')
549
-			->where(
550
-				$qb->expr()->andX(
551
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
552
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
553
-				)
554
-			);
555
-
556
-		$result = $qb->execute();
557
-		$share = $result->fetch();
558
-		$result->closeCursor();
559
-
560
-		if ($token && $id && !empty($share)) {
561
-			$remote = $this->cleanupRemote($share['remote']);
562
-
563
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
564
-			$mountpoint = $share['mountpoint'];
565
-			$user = $share['user'];
566
-
567
-			$qb = $this->connection->getQueryBuilder();
568
-			$qb->delete('share_external')
569
-				->where(
570
-					$qb->expr()->andX(
571
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
572
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
573
-					)
574
-				);
575
-
576
-			$qb->execute();
577
-
578
-			// delete all child in case of a group share
579
-			$qb = $this->connection->getQueryBuilder();
580
-			$qb->delete('share_external')
581
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id'])));
582
-			$qb->execute();
583
-
584
-			if ((int)$share['share_type'] === IShare::TYPE_USER) {
585
-				if ($share['accepted']) {
586
-					$path = trim($mountpoint, '/');
587
-				} else {
588
-					$path = trim($share['name'], '/');
589
-				}
590
-				$notification = $this->notificationManager->createNotification();
591
-				$notification->setApp('files_sharing')
592
-					->setUser($share['user'])
593
-					->setObject('remote_share', (int)$share['id']);
594
-				$this->notificationManager->markProcessed($notification);
595
-
596
-				$event = $this->activityManager->generateEvent();
597
-				$event->setApp('files_sharing')
598
-					->setType('remote_share')
599
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
600
-					->setAffectedUser($user)
601
-					->setObject('remote_share', (int)$share['id'], $path);
602
-				\OC::$server->getActivityManager()->publish($event);
603
-			}
604
-		}
605
-
606
-		return [];
607
-	}
608
-
609
-	private function cleanupRemote($remote) {
610
-		$remote = substr($remote, strpos($remote, '://') + 3);
611
-
612
-		return rtrim($remote, '/');
613
-	}
614
-
615
-	/**
616
-	 * recipient of a share request to re-share the file with another user
617
-	 *
618
-	 * @param string $id
619
-	 * @param array $notification
620
-	 * @return array
621
-	 * @throws AuthenticationFailedException
622
-	 * @throws BadRequestException
623
-	 * @throws ProviderCouldNotAddShareException
624
-	 * @throws ShareNotFound
625
-	 */
626
-	protected function reshareRequested($id, array $notification) {
627
-		if (!isset($notification['sharedSecret'])) {
628
-			throw new BadRequestException(['sharedSecret']);
629
-		}
630
-		$token = $notification['sharedSecret'];
631
-
632
-		if (!isset($notification['shareWith'])) {
633
-			throw new BadRequestException(['shareWith']);
634
-		}
635
-		$shareWith = $notification['shareWith'];
636
-
637
-		if (!isset($notification['senderId'])) {
638
-			throw new BadRequestException(['senderId']);
639
-		}
640
-		$senderId = $notification['senderId'];
641
-
642
-		$share = $this->federatedShareProvider->getShareById($id);
643
-		// don't allow to share a file back to the owner
644
-		try {
645
-			[$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
646
-			$owner = $share->getShareOwner();
647
-			$currentServer = $this->addressHandler->generateRemoteURL();
648
-			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
649
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
650
-			}
651
-		} catch (\Exception $e) {
652
-			throw new ProviderCouldNotAddShareException($e->getMessage());
653
-		}
654
-
655
-		$this->verifyShare($share, $token);
656
-
657
-		// check if re-sharing is allowed
658
-		if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
659
-			// the recipient of the initial share is now the initiator for the re-share
660
-			$share->setSharedBy($share->getSharedWith());
661
-			$share->setSharedWith($shareWith);
662
-			$result = $this->federatedShareProvider->create($share);
663
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
664
-			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
665
-		} else {
666
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
667
-		}
668
-	}
669
-
670
-	/**
671
-	 * update permission of a re-share so that the share dialog shows the right
672
-	 * permission if the owner or the sender changes the permission
673
-	 *
674
-	 * @param string $id
675
-	 * @param array $notification
676
-	 * @return array
677
-	 * @throws AuthenticationFailedException
678
-	 * @throws BadRequestException
679
-	 */
680
-	protected function updateResharePermissions($id, array $notification) {
681
-		if (!isset($notification['sharedSecret'])) {
682
-			throw new BadRequestException(['sharedSecret']);
683
-		}
684
-		$token = $notification['sharedSecret'];
685
-
686
-		if (!isset($notification['permission'])) {
687
-			throw new BadRequestException(['permission']);
688
-		}
689
-		$ocmPermissions = $notification['permission'];
690
-
691
-		$share = $this->federatedShareProvider->getShareById($id);
692
-
693
-		$ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
694
-
695
-		$this->verifyShare($share, $token);
696
-		$this->updatePermissionsInDatabase($share, $ncPermission);
697
-
698
-		return [];
699
-	}
700
-
701
-	/**
702
-	 * translate OCM Permissions to Nextcloud permissions
703
-	 *
704
-	 * @param array $ocmPermissions
705
-	 * @return int
706
-	 * @throws BadRequestException
707
-	 */
708
-	protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
709
-		$ncPermissions = 0;
710
-		foreach ($ocmPermissions as $permission) {
711
-			switch (strtolower($permission)) {
712
-				case 'read':
713
-					$ncPermissions += Constants::PERMISSION_READ;
714
-					break;
715
-				case 'write':
716
-					$ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
717
-					break;
718
-				case 'share':
719
-					$ncPermissions += Constants::PERMISSION_SHARE;
720
-					break;
721
-				default:
722
-					throw new BadRequestException(['permission']);
723
-			}
724
-		}
725
-
726
-		return $ncPermissions;
727
-	}
728
-
729
-	/**
730
-	 * update permissions in database
731
-	 *
732
-	 * @param IShare $share
733
-	 * @param int $permissions
734
-	 */
735
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
736
-		$query = $this->connection->getQueryBuilder();
737
-		$query->update('share')
738
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
739
-			->set('permissions', $query->createNamedParameter($permissions))
740
-			->execute();
741
-	}
742
-
743
-
744
-	/**
745
-	 * get file
746
-	 *
747
-	 * @param string $user
748
-	 * @param int $fileSource
749
-	 * @return array with internal path of the file and a absolute link to it
750
-	 */
751
-	private function getFile($user, $fileSource) {
752
-		\OC_Util::setupFS($user);
753
-
754
-		try {
755
-			$file = Filesystem::getPath($fileSource);
756
-		} catch (NotFoundException $e) {
757
-			$file = null;
758
-		}
759
-		$args = Filesystem::is_dir($file) ? ['dir' => $file] : ['dir' => dirname($file), 'scrollto' => $file];
760
-		$link = Util::linkToAbsolute('files', 'index.php', $args);
761
-
762
-		return [$file, $link];
763
-	}
764
-
765
-	/**
766
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
767
-	 *
768
-	 * @param IShare $share
769
-	 * @return string
770
-	 */
771
-	protected function getCorrectUid(IShare $share) {
772
-		if ($this->userManager->userExists($share->getShareOwner())) {
773
-			return $share->getShareOwner();
774
-		}
775
-
776
-		return $share->getSharedBy();
777
-	}
778
-
779
-
780
-
781
-	/**
782
-	 * check if we got the right share
783
-	 *
784
-	 * @param IShare $share
785
-	 * @param string $token
786
-	 * @return bool
787
-	 * @throws AuthenticationFailedException
788
-	 */
789
-	protected function verifyShare(IShare $share, $token) {
790
-		if (
791
-			$share->getShareType() === IShare::TYPE_REMOTE &&
792
-			$share->getToken() === $token
793
-		) {
794
-			return true;
795
-		}
796
-
797
-		if ($share->getShareType() === IShare::TYPE_CIRCLE) {
798
-			try {
799
-				$knownShare = $this->shareManager->getShareByToken($token);
800
-				if ($knownShare->getId() === $share->getId()) {
801
-					return true;
802
-				}
803
-			} catch (ShareNotFound $e) {
804
-			}
805
-		}
806
-
807
-		throw new AuthenticationFailedException();
808
-	}
809
-
810
-
811
-
812
-	/**
813
-	 * check if server-to-server sharing is enabled
814
-	 *
815
-	 * @param bool $incoming
816
-	 * @return bool
817
-	 */
818
-	private function isS2SEnabled($incoming = false) {
819
-		$result = $this->appManager->isEnabledForUser('files_sharing');
820
-
821
-		if ($incoming) {
822
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
823
-		} else {
824
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
825
-		}
826
-
827
-		return $result;
828
-	}
829
-
830
-
831
-	/**
832
-	 * get the supported share types, e.g. "user", "group", etc.
833
-	 *
834
-	 * @return array
835
-	 *
836
-	 * @since 14.0.0
837
-	 */
838
-	public function getSupportedShareTypes() {
839
-		return ['user', 'group'];
840
-	}
65
+    /** @var IAppManager */
66
+    private $appManager;
67
+
68
+    /** @var FederatedShareProvider */
69
+    private $federatedShareProvider;
70
+
71
+    /** @var AddressHandler */
72
+    private $addressHandler;
73
+
74
+    /** @var ILogger */
75
+    private $logger;
76
+
77
+    /** @var IUserManager */
78
+    private $userManager;
79
+
80
+    /** @var IManager */
81
+    private $shareManager;
82
+
83
+    /** @var ICloudIdManager */
84
+    private $cloudIdManager;
85
+
86
+    /** @var IActivityManager */
87
+    private $activityManager;
88
+
89
+    /** @var INotificationManager */
90
+    private $notificationManager;
91
+
92
+    /** @var IURLGenerator */
93
+    private $urlGenerator;
94
+
95
+    /** @var ICloudFederationFactory */
96
+    private $cloudFederationFactory;
97
+
98
+    /** @var ICloudFederationProviderManager */
99
+    private $cloudFederationProviderManager;
100
+
101
+    /** @var IDBConnection */
102
+    private $connection;
103
+
104
+    /** @var IGroupManager */
105
+    private $groupManager;
106
+
107
+    /**
108
+     * CloudFederationProvider constructor.
109
+     *
110
+     * @param IAppManager $appManager
111
+     * @param FederatedShareProvider $federatedShareProvider
112
+     * @param AddressHandler $addressHandler
113
+     * @param ILogger $logger
114
+     * @param IUserManager $userManager
115
+     * @param IManager $shareManager
116
+     * @param ICloudIdManager $cloudIdManager
117
+     * @param IActivityManager $activityManager
118
+     * @param INotificationManager $notificationManager
119
+     * @param IURLGenerator $urlGenerator
120
+     * @param ICloudFederationFactory $cloudFederationFactory
121
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
122
+     * @param IDBConnection $connection
123
+     * @param IGroupManager $groupManager
124
+     */
125
+    public function __construct(IAppManager $appManager,
126
+                                FederatedShareProvider $federatedShareProvider,
127
+                                AddressHandler $addressHandler,
128
+                                ILogger $logger,
129
+                                IUserManager $userManager,
130
+                                IManager $shareManager,
131
+                                ICloudIdManager $cloudIdManager,
132
+                                IActivityManager $activityManager,
133
+                                INotificationManager $notificationManager,
134
+                                IURLGenerator $urlGenerator,
135
+                                ICloudFederationFactory $cloudFederationFactory,
136
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
137
+                                IDBConnection $connection,
138
+                                IGroupManager $groupManager
139
+    ) {
140
+        $this->appManager = $appManager;
141
+        $this->federatedShareProvider = $federatedShareProvider;
142
+        $this->addressHandler = $addressHandler;
143
+        $this->logger = $logger;
144
+        $this->userManager = $userManager;
145
+        $this->shareManager = $shareManager;
146
+        $this->cloudIdManager = $cloudIdManager;
147
+        $this->activityManager = $activityManager;
148
+        $this->notificationManager = $notificationManager;
149
+        $this->urlGenerator = $urlGenerator;
150
+        $this->cloudFederationFactory = $cloudFederationFactory;
151
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
152
+        $this->connection = $connection;
153
+        $this->groupManager = $groupManager;
154
+    }
155
+
156
+
157
+
158
+    /**
159
+     * @return string
160
+     */
161
+    public function getShareType() {
162
+        return 'file';
163
+    }
164
+
165
+    /**
166
+     * share received from another server
167
+     *
168
+     * @param ICloudFederationShare $share
169
+     * @return string provider specific unique ID of the share
170
+     *
171
+     * @throws ProviderCouldNotAddShareException
172
+     * @throws \OCP\AppFramework\QueryException
173
+     * @throws \OC\HintException
174
+     * @since 14.0.0
175
+     */
176
+    public function shareReceived(ICloudFederationShare $share) {
177
+        if (!$this->isS2SEnabled(true)) {
178
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
179
+        }
180
+
181
+        $protocol = $share->getProtocol();
182
+        if ($protocol['name'] !== 'webdav') {
183
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
184
+        }
185
+
186
+        [$ownerUid, $remote] = $this->addressHandler->splitUserRemote($share->getOwner());
187
+        // for backward compatibility make sure that the remote url stored in the
188
+        // database ends with a trailing slash
189
+        if (substr($remote, -1) !== '/') {
190
+            $remote = $remote . '/';
191
+        }
192
+
193
+        $token = $share->getShareSecret();
194
+        $name = $share->getResourceName();
195
+        $owner = $share->getOwnerDisplayName();
196
+        $sharedBy = $share->getSharedByDisplayName();
197
+        $shareWith = $share->getShareWith();
198
+        $remoteId = $share->getProviderId();
199
+        $sharedByFederatedId = $share->getSharedBy();
200
+        $ownerFederatedId = $share->getOwner();
201
+        $shareType = $this->mapShareTypeToNextcloud($share->getShareType());
202
+
203
+        // if no explicit information about the person who created the share was send
204
+        // we assume that the share comes from the owner
205
+        if ($sharedByFederatedId === null) {
206
+            $sharedBy = $owner;
207
+            $sharedByFederatedId = $ownerFederatedId;
208
+        }
209
+
210
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
211
+            if (!Util::isValidFileName($name)) {
212
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
213
+            }
214
+
215
+            // FIXME this should be a method in the user management instead
216
+            if ($shareType === IShare::TYPE_USER) {
217
+                $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
218
+                Util::emitHook(
219
+                    '\OCA\Files_Sharing\API\Server2Server',
220
+                    'preLoginNameUsedAsUserName',
221
+                    ['uid' => &$shareWith]
222
+                );
223
+                $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
224
+
225
+                if (!$this->userManager->userExists($shareWith)) {
226
+                    throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
227
+                }
228
+
229
+                \OC_Util::setupFS($shareWith);
230
+            }
231
+
232
+            if ($shareType === IShare::TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
233
+                throw new ProviderCouldNotAddShareException('Group does not exists', '',Http::STATUS_BAD_REQUEST);
234
+            }
235
+
236
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
237
+                \OC::$server->getDatabaseConnection(),
238
+                Filesystem::getMountManager(),
239
+                Filesystem::getLoader(),
240
+                \OC::$server->getHTTPClientService(),
241
+                \OC::$server->getNotificationManager(),
242
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
243
+                \OC::$server->getCloudFederationProviderManager(),
244
+                \OC::$server->getCloudFederationFactory(),
245
+                \OC::$server->getGroupManager(),
246
+                \OC::$server->getUserManager(),
247
+                $shareWith,
248
+                \OC::$server->query(IEventDispatcher::class)
249
+            );
250
+
251
+            try {
252
+                $externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
253
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
254
+
255
+                if ($shareType === IShare::TYPE_USER) {
256
+                    $event = $this->activityManager->generateEvent();
257
+                    $event->setApp('files_sharing')
258
+                        ->setType('remote_share')
259
+                        ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
260
+                        ->setAffectedUser($shareWith)
261
+                        ->setObject('remote_share', (int)$shareId, $name);
262
+                    \OC::$server->getActivityManager()->publish($event);
263
+                    $this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
264
+                } else {
265
+                    $groupMembers = $this->groupManager->get($shareWith)->getUsers();
266
+                    foreach ($groupMembers as $user) {
267
+                        $event = $this->activityManager->generateEvent();
268
+                        $event->setApp('files_sharing')
269
+                            ->setType('remote_share')
270
+                            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
271
+                            ->setAffectedUser($user->getUID())
272
+                            ->setObject('remote_share', (int)$shareId, $name);
273
+                        \OC::$server->getActivityManager()->publish($event);
274
+                        $this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
275
+                    }
276
+                }
277
+                return $shareId;
278
+            } catch (\Exception $e) {
279
+                $this->logger->logException($e, [
280
+                    'message' => 'Server can not add remote share.',
281
+                    'level' => ILogger::ERROR,
282
+                    'app' => 'files_sharing'
283
+                ]);
284
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
285
+            }
286
+        }
287
+
288
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
289
+    }
290
+
291
+    /**
292
+     * notification received from another server
293
+     *
294
+     * @param string $notificationType (e.g. SHARE_ACCEPTED)
295
+     * @param string $providerId id of the share
296
+     * @param array $notification payload of the notification
297
+     * @return array data send back to the sender
298
+     *
299
+     * @throws ActionNotSupportedException
300
+     * @throws AuthenticationFailedException
301
+     * @throws BadRequestException
302
+     * @throws \OC\HintException
303
+     * @since 14.0.0
304
+     */
305
+    public function notificationReceived($notificationType, $providerId, array $notification) {
306
+        switch ($notificationType) {
307
+            case 'SHARE_ACCEPTED':
308
+                return $this->shareAccepted($providerId, $notification);
309
+            case 'SHARE_DECLINED':
310
+                return $this->shareDeclined($providerId, $notification);
311
+            case 'SHARE_UNSHARED':
312
+                return $this->unshare($providerId, $notification);
313
+            case 'REQUEST_RESHARE':
314
+                return $this->reshareRequested($providerId, $notification);
315
+            case 'RESHARE_UNDO':
316
+                return $this->undoReshare($providerId, $notification);
317
+            case 'RESHARE_CHANGE_PERMISSION':
318
+                return $this->updateResharePermissions($providerId, $notification);
319
+        }
320
+
321
+
322
+        throw new BadRequestException([$notificationType]);
323
+    }
324
+
325
+    /**
326
+     * map OCM share type (strings) to Nextcloud internal share types (integer)
327
+     *
328
+     * @param string $shareType
329
+     * @return int
330
+     */
331
+    private function mapShareTypeToNextcloud($shareType) {
332
+        $result = IShare::TYPE_USER;
333
+        if ($shareType === 'group') {
334
+            $result = IShare::TYPE_GROUP;
335
+        }
336
+
337
+        return $result;
338
+    }
339
+
340
+    private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name): void {
341
+        $notification = $this->notificationManager->createNotification();
342
+        $notification->setApp('files_sharing')
343
+            ->setUser($shareWith)
344
+            ->setDateTime(new \DateTime())
345
+            ->setObject('remote_share', $shareId)
346
+            ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
347
+
348
+        $declineAction = $notification->createAction();
349
+        $declineAction->setLabel('decline')
350
+            ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
351
+        $notification->addAction($declineAction);
352
+
353
+        $acceptAction = $notification->createAction();
354
+        $acceptAction->setLabel('accept')
355
+            ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
356
+        $notification->addAction($acceptAction);
357
+
358
+        $this->notificationManager->notify($notification);
359
+    }
360
+
361
+    /**
362
+     * process notification that the recipient accepted a share
363
+     *
364
+     * @param string $id
365
+     * @param array $notification
366
+     * @return array
367
+     * @throws ActionNotSupportedException
368
+     * @throws AuthenticationFailedException
369
+     * @throws BadRequestException
370
+     * @throws \OC\HintException
371
+     */
372
+    private function shareAccepted($id, array $notification) {
373
+        if (!$this->isS2SEnabled()) {
374
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
375
+        }
376
+
377
+        if (!isset($notification['sharedSecret'])) {
378
+            throw new BadRequestException(['sharedSecret']);
379
+        }
380
+
381
+        $token = $notification['sharedSecret'];
382
+
383
+        $share = $this->federatedShareProvider->getShareById($id);
384
+
385
+        $this->verifyShare($share, $token);
386
+        $this->executeAcceptShare($share);
387
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
388
+            [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
389
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
390
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
391
+            $notification->setMessage(
392
+                'SHARE_ACCEPTED',
393
+                'file',
394
+                $remoteId,
395
+                [
396
+                    'sharedSecret' => $token,
397
+                    'message' => 'Recipient accepted the re-share'
398
+                ]
399
+
400
+            );
401
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
402
+        }
403
+
404
+        return [];
405
+    }
406
+
407
+    /**
408
+     * @param IShare $share
409
+     * @throws ShareNotFound
410
+     */
411
+    protected function executeAcceptShare(IShare $share) {
412
+        try {
413
+            $fileId = (int)$share->getNode()->getId();
414
+            [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
415
+        } catch (\Exception $e) {
416
+            throw new ShareNotFound();
417
+        }
418
+
419
+        $event = $this->activityManager->generateEvent();
420
+        $event->setApp('files_sharing')
421
+            ->setType('remote_share')
422
+            ->setAffectedUser($this->getCorrectUid($share))
423
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
424
+            ->setObject('files', $fileId, $file)
425
+            ->setLink($link);
426
+        $this->activityManager->publish($event);
427
+    }
428
+
429
+    /**
430
+     * process notification that the recipient declined a share
431
+     *
432
+     * @param string $id
433
+     * @param array $notification
434
+     * @return array
435
+     * @throws ActionNotSupportedException
436
+     * @throws AuthenticationFailedException
437
+     * @throws BadRequestException
438
+     * @throws ShareNotFound
439
+     * @throws \OC\HintException
440
+     *
441
+     */
442
+    protected function shareDeclined($id, array $notification) {
443
+        if (!$this->isS2SEnabled()) {
444
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
445
+        }
446
+
447
+        if (!isset($notification['sharedSecret'])) {
448
+            throw new BadRequestException(['sharedSecret']);
449
+        }
450
+
451
+        $token = $notification['sharedSecret'];
452
+
453
+        $share = $this->federatedShareProvider->getShareById($id);
454
+
455
+        $this->verifyShare($share, $token);
456
+
457
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
458
+            [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
459
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
460
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
461
+            $notification->setMessage(
462
+                'SHARE_DECLINED',
463
+                'file',
464
+                $remoteId,
465
+                [
466
+                    'sharedSecret' => $token,
467
+                    'message' => 'Recipient declined the re-share'
468
+                ]
469
+
470
+            );
471
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
472
+        }
473
+
474
+        $this->executeDeclineShare($share);
475
+
476
+        return [];
477
+    }
478
+
479
+    /**
480
+     * delete declined share and create a activity
481
+     *
482
+     * @param IShare $share
483
+     * @throws ShareNotFound
484
+     */
485
+    protected function executeDeclineShare(IShare $share) {
486
+        $this->federatedShareProvider->removeShareFromTable($share);
487
+
488
+        try {
489
+            $fileId = (int)$share->getNode()->getId();
490
+            [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
491
+        } catch (\Exception $e) {
492
+            throw new ShareNotFound();
493
+        }
494
+
495
+        $event = $this->activityManager->generateEvent();
496
+        $event->setApp('files_sharing')
497
+            ->setType('remote_share')
498
+            ->setAffectedUser($this->getCorrectUid($share))
499
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
500
+            ->setObject('files', $fileId, $file)
501
+            ->setLink($link);
502
+        $this->activityManager->publish($event);
503
+    }
504
+
505
+    /**
506
+     * received the notification that the owner unshared a file from you
507
+     *
508
+     * @param string $id
509
+     * @param array $notification
510
+     * @return array
511
+     * @throws AuthenticationFailedException
512
+     * @throws BadRequestException
513
+     */
514
+    private function undoReshare($id, array $notification) {
515
+        if (!isset($notification['sharedSecret'])) {
516
+            throw new BadRequestException(['sharedSecret']);
517
+        }
518
+        $token = $notification['sharedSecret'];
519
+
520
+        $share = $this->federatedShareProvider->getShareById($id);
521
+
522
+        $this->verifyShare($share, $token);
523
+        $this->federatedShareProvider->removeShareFromTable($share);
524
+        return [];
525
+    }
526
+
527
+    /**
528
+     * unshare file from self
529
+     *
530
+     * @param string $id
531
+     * @param array $notification
532
+     * @return array
533
+     * @throws ActionNotSupportedException
534
+     * @throws BadRequestException
535
+     */
536
+    private function unshare($id, array $notification) {
537
+        if (!$this->isS2SEnabled(true)) {
538
+            throw new ActionNotSupportedException("incoming shares disabled!");
539
+        }
540
+
541
+        if (!isset($notification['sharedSecret'])) {
542
+            throw new BadRequestException(['sharedSecret']);
543
+        }
544
+        $token = $notification['sharedSecret'];
545
+
546
+        $qb = $this->connection->getQueryBuilder();
547
+        $qb->select('*')
548
+            ->from('share_external')
549
+            ->where(
550
+                $qb->expr()->andX(
551
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
552
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
553
+                )
554
+            );
555
+
556
+        $result = $qb->execute();
557
+        $share = $result->fetch();
558
+        $result->closeCursor();
559
+
560
+        if ($token && $id && !empty($share)) {
561
+            $remote = $this->cleanupRemote($share['remote']);
562
+
563
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
564
+            $mountpoint = $share['mountpoint'];
565
+            $user = $share['user'];
566
+
567
+            $qb = $this->connection->getQueryBuilder();
568
+            $qb->delete('share_external')
569
+                ->where(
570
+                    $qb->expr()->andX(
571
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
572
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
573
+                    )
574
+                );
575
+
576
+            $qb->execute();
577
+
578
+            // delete all child in case of a group share
579
+            $qb = $this->connection->getQueryBuilder();
580
+            $qb->delete('share_external')
581
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id'])));
582
+            $qb->execute();
583
+
584
+            if ((int)$share['share_type'] === IShare::TYPE_USER) {
585
+                if ($share['accepted']) {
586
+                    $path = trim($mountpoint, '/');
587
+                } else {
588
+                    $path = trim($share['name'], '/');
589
+                }
590
+                $notification = $this->notificationManager->createNotification();
591
+                $notification->setApp('files_sharing')
592
+                    ->setUser($share['user'])
593
+                    ->setObject('remote_share', (int)$share['id']);
594
+                $this->notificationManager->markProcessed($notification);
595
+
596
+                $event = $this->activityManager->generateEvent();
597
+                $event->setApp('files_sharing')
598
+                    ->setType('remote_share')
599
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
600
+                    ->setAffectedUser($user)
601
+                    ->setObject('remote_share', (int)$share['id'], $path);
602
+                \OC::$server->getActivityManager()->publish($event);
603
+            }
604
+        }
605
+
606
+        return [];
607
+    }
608
+
609
+    private function cleanupRemote($remote) {
610
+        $remote = substr($remote, strpos($remote, '://') + 3);
611
+
612
+        return rtrim($remote, '/');
613
+    }
614
+
615
+    /**
616
+     * recipient of a share request to re-share the file with another user
617
+     *
618
+     * @param string $id
619
+     * @param array $notification
620
+     * @return array
621
+     * @throws AuthenticationFailedException
622
+     * @throws BadRequestException
623
+     * @throws ProviderCouldNotAddShareException
624
+     * @throws ShareNotFound
625
+     */
626
+    protected function reshareRequested($id, array $notification) {
627
+        if (!isset($notification['sharedSecret'])) {
628
+            throw new BadRequestException(['sharedSecret']);
629
+        }
630
+        $token = $notification['sharedSecret'];
631
+
632
+        if (!isset($notification['shareWith'])) {
633
+            throw new BadRequestException(['shareWith']);
634
+        }
635
+        $shareWith = $notification['shareWith'];
636
+
637
+        if (!isset($notification['senderId'])) {
638
+            throw new BadRequestException(['senderId']);
639
+        }
640
+        $senderId = $notification['senderId'];
641
+
642
+        $share = $this->federatedShareProvider->getShareById($id);
643
+        // don't allow to share a file back to the owner
644
+        try {
645
+            [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
646
+            $owner = $share->getShareOwner();
647
+            $currentServer = $this->addressHandler->generateRemoteURL();
648
+            if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
649
+                throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
650
+            }
651
+        } catch (\Exception $e) {
652
+            throw new ProviderCouldNotAddShareException($e->getMessage());
653
+        }
654
+
655
+        $this->verifyShare($share, $token);
656
+
657
+        // check if re-sharing is allowed
658
+        if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
659
+            // the recipient of the initial share is now the initiator for the re-share
660
+            $share->setSharedBy($share->getSharedWith());
661
+            $share->setSharedWith($shareWith);
662
+            $result = $this->federatedShareProvider->create($share);
663
+            $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
664
+            return ['token' => $result->getToken(), 'providerId' => $result->getId()];
665
+        } else {
666
+            throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
667
+        }
668
+    }
669
+
670
+    /**
671
+     * update permission of a re-share so that the share dialog shows the right
672
+     * permission if the owner or the sender changes the permission
673
+     *
674
+     * @param string $id
675
+     * @param array $notification
676
+     * @return array
677
+     * @throws AuthenticationFailedException
678
+     * @throws BadRequestException
679
+     */
680
+    protected function updateResharePermissions($id, array $notification) {
681
+        if (!isset($notification['sharedSecret'])) {
682
+            throw new BadRequestException(['sharedSecret']);
683
+        }
684
+        $token = $notification['sharedSecret'];
685
+
686
+        if (!isset($notification['permission'])) {
687
+            throw new BadRequestException(['permission']);
688
+        }
689
+        $ocmPermissions = $notification['permission'];
690
+
691
+        $share = $this->federatedShareProvider->getShareById($id);
692
+
693
+        $ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
694
+
695
+        $this->verifyShare($share, $token);
696
+        $this->updatePermissionsInDatabase($share, $ncPermission);
697
+
698
+        return [];
699
+    }
700
+
701
+    /**
702
+     * translate OCM Permissions to Nextcloud permissions
703
+     *
704
+     * @param array $ocmPermissions
705
+     * @return int
706
+     * @throws BadRequestException
707
+     */
708
+    protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
709
+        $ncPermissions = 0;
710
+        foreach ($ocmPermissions as $permission) {
711
+            switch (strtolower($permission)) {
712
+                case 'read':
713
+                    $ncPermissions += Constants::PERMISSION_READ;
714
+                    break;
715
+                case 'write':
716
+                    $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
717
+                    break;
718
+                case 'share':
719
+                    $ncPermissions += Constants::PERMISSION_SHARE;
720
+                    break;
721
+                default:
722
+                    throw new BadRequestException(['permission']);
723
+            }
724
+        }
725
+
726
+        return $ncPermissions;
727
+    }
728
+
729
+    /**
730
+     * update permissions in database
731
+     *
732
+     * @param IShare $share
733
+     * @param int $permissions
734
+     */
735
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
736
+        $query = $this->connection->getQueryBuilder();
737
+        $query->update('share')
738
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
739
+            ->set('permissions', $query->createNamedParameter($permissions))
740
+            ->execute();
741
+    }
742
+
743
+
744
+    /**
745
+     * get file
746
+     *
747
+     * @param string $user
748
+     * @param int $fileSource
749
+     * @return array with internal path of the file and a absolute link to it
750
+     */
751
+    private function getFile($user, $fileSource) {
752
+        \OC_Util::setupFS($user);
753
+
754
+        try {
755
+            $file = Filesystem::getPath($fileSource);
756
+        } catch (NotFoundException $e) {
757
+            $file = null;
758
+        }
759
+        $args = Filesystem::is_dir($file) ? ['dir' => $file] : ['dir' => dirname($file), 'scrollto' => $file];
760
+        $link = Util::linkToAbsolute('files', 'index.php', $args);
761
+
762
+        return [$file, $link];
763
+    }
764
+
765
+    /**
766
+     * check if we are the initiator or the owner of a re-share and return the correct UID
767
+     *
768
+     * @param IShare $share
769
+     * @return string
770
+     */
771
+    protected function getCorrectUid(IShare $share) {
772
+        if ($this->userManager->userExists($share->getShareOwner())) {
773
+            return $share->getShareOwner();
774
+        }
775
+
776
+        return $share->getSharedBy();
777
+    }
778
+
779
+
780
+
781
+    /**
782
+     * check if we got the right share
783
+     *
784
+     * @param IShare $share
785
+     * @param string $token
786
+     * @return bool
787
+     * @throws AuthenticationFailedException
788
+     */
789
+    protected function verifyShare(IShare $share, $token) {
790
+        if (
791
+            $share->getShareType() === IShare::TYPE_REMOTE &&
792
+            $share->getToken() === $token
793
+        ) {
794
+            return true;
795
+        }
796
+
797
+        if ($share->getShareType() === IShare::TYPE_CIRCLE) {
798
+            try {
799
+                $knownShare = $this->shareManager->getShareByToken($token);
800
+                if ($knownShare->getId() === $share->getId()) {
801
+                    return true;
802
+                }
803
+            } catch (ShareNotFound $e) {
804
+            }
805
+        }
806
+
807
+        throw new AuthenticationFailedException();
808
+    }
809
+
810
+
811
+
812
+    /**
813
+     * check if server-to-server sharing is enabled
814
+     *
815
+     * @param bool $incoming
816
+     * @return bool
817
+     */
818
+    private function isS2SEnabled($incoming = false) {
819
+        $result = $this->appManager->isEnabledForUser('files_sharing');
820
+
821
+        if ($incoming) {
822
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
823
+        } else {
824
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
825
+        }
826
+
827
+        return $result;
828
+    }
829
+
830
+
831
+    /**
832
+     * get the supported share types, e.g. "user", "group", etc.
833
+     *
834
+     * @return array
835
+     *
836
+     * @since 14.0.0
837
+     */
838
+    public function getSupportedShareTypes() {
839
+        return ['user', 'group'];
840
+    }
841 841
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 		// for backward compatibility make sure that the remote url stored in the
188 188
 		// database ends with a trailing slash
189 189
 		if (substr($remote, -1) !== '/') {
190
-			$remote = $remote . '/';
190
+			$remote = $remote.'/';
191 191
 		}
192 192
 
193 193
 		$token = $share->getShareSecret();
@@ -214,23 +214,23 @@  discard block
 block discarded – undo
214 214
 
215 215
 			// FIXME this should be a method in the user management instead
216 216
 			if ($shareType === IShare::TYPE_USER) {
217
-				$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
217
+				$this->logger->debug('shareWith before, '.$shareWith, ['app' => 'files_sharing']);
218 218
 				Util::emitHook(
219 219
 					'\OCA\Files_Sharing\API\Server2Server',
220 220
 					'preLoginNameUsedAsUserName',
221 221
 					['uid' => &$shareWith]
222 222
 				);
223
-				$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
223
+				$this->logger->debug('shareWith after, '.$shareWith, ['app' => 'files_sharing']);
224 224
 
225 225
 				if (!$this->userManager->userExists($shareWith)) {
226
-					throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
226
+					throw new ProviderCouldNotAddShareException('User does not exists', '', Http::STATUS_BAD_REQUEST);
227 227
 				}
228 228
 
229 229
 				\OC_Util::setupFS($shareWith);
230 230
 			}
231 231
 
232 232
 			if ($shareType === IShare::TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
233
-				throw new ProviderCouldNotAddShareException('Group does not exists', '',Http::STATUS_BAD_REQUEST);
233
+				throw new ProviderCouldNotAddShareException('Group does not exists', '', Http::STATUS_BAD_REQUEST);
234 234
 			}
235 235
 
236 236
 			$externalManager = new \OCA\Files_Sharing\External\Manager(
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 			);
250 250
 
251 251
 			try {
252
-				$externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
252
+				$externalManager->addShare($remote, $token, '', $name, $owner, $shareType, false, $shareWith, $remoteId);
253 253
 				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
254 254
 
255 255
 				if ($shareType === IShare::TYPE_USER) {
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 						->setType('remote_share')
259 259
 						->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
260 260
 						->setAffectedUser($shareWith)
261
-						->setObject('remote_share', (int)$shareId, $name);
261
+						->setObject('remote_share', (int) $shareId, $name);
262 262
 					\OC::$server->getActivityManager()->publish($event);
263 263
 					$this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
264 264
 				} else {
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 							->setType('remote_share')
270 270
 							->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
271 271
 							->setAffectedUser($user->getUID())
272
-							->setObject('remote_share', (int)$shareId, $name);
272
+							->setObject('remote_share', (int) $shareId, $name);
273 273
 						\OC::$server->getActivityManager()->publish($event);
274 274
 						$this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
275 275
 					}
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 					'level' => ILogger::ERROR,
282 282
 					'app' => 'files_sharing'
283 283
 				]);
284
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
284
+				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from '.$remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
285 285
 			}
286 286
 		}
287 287
 
@@ -347,12 +347,12 @@  discard block
 block discarded – undo
347 347
 
348 348
 		$declineAction = $notification->createAction();
349 349
 		$declineAction->setLabel('decline')
350
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
350
+			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
351 351
 		$notification->addAction($declineAction);
352 352
 
353 353
 		$acceptAction = $notification->createAction();
354 354
 		$acceptAction->setLabel('accept')
355
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
355
+			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
356 356
 		$notification->addAction($acceptAction);
357 357
 
358 358
 		$this->notificationManager->notify($notification);
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 	 */
411 411
 	protected function executeAcceptShare(IShare $share) {
412 412
 		try {
413
-			$fileId = (int)$share->getNode()->getId();
413
+			$fileId = (int) $share->getNode()->getId();
414 414
 			[$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
415 415
 		} catch (\Exception $e) {
416 416
 			throw new ShareNotFound();
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 		$this->federatedShareProvider->removeShareFromTable($share);
487 487
 
488 488
 		try {
489
-			$fileId = (int)$share->getNode()->getId();
489
+			$fileId = (int) $share->getNode()->getId();
490 490
 			[$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
491 491
 		} catch (\Exception $e) {
492 492
 			throw new ShareNotFound();
@@ -578,10 +578,10 @@  discard block
 block discarded – undo
578 578
 			// delete all child in case of a group share
579 579
 			$qb = $this->connection->getQueryBuilder();
580 580
 			$qb->delete('share_external')
581
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id'])));
581
+				->where($qb->expr()->eq('parent', $qb->createNamedParameter((int) $share['id'])));
582 582
 			$qb->execute();
583 583
 
584
-			if ((int)$share['share_type'] === IShare::TYPE_USER) {
584
+			if ((int) $share['share_type'] === IShare::TYPE_USER) {
585 585
 				if ($share['accepted']) {
586 586
 					$path = trim($mountpoint, '/');
587 587
 				} else {
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 				$notification = $this->notificationManager->createNotification();
591 591
 				$notification->setApp('files_sharing')
592 592
 					->setUser($share['user'])
593
-					->setObject('remote_share', (int)$share['id']);
593
+					->setObject('remote_share', (int) $share['id']);
594 594
 				$this->notificationManager->markProcessed($notification);
595 595
 
596 596
 				$event = $this->activityManager->generateEvent();
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 					->setType('remote_share')
599 599
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
600 600
 					->setAffectedUser($user)
601
-					->setObject('remote_share', (int)$share['id'], $path);
601
+					->setObject('remote_share', (int) $share['id'], $path);
602 602
 				\OC::$server->getActivityManager()->publish($event);
603 603
 			}
604 604
 		}
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 			$owner = $share->getShareOwner();
647 647
 			$currentServer = $this->addressHandler->generateRemoteURL();
648 648
 			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
649
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
649
+				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: '.$id);
650 650
 			}
651 651
 		} catch (\Exception $e) {
652 652
 			throw new ProviderCouldNotAddShareException($e->getMessage());
@@ -660,10 +660,10 @@  discard block
 block discarded – undo
660 660
 			$share->setSharedBy($share->getSharedWith());
661 661
 			$share->setSharedWith($shareWith);
662 662
 			$result = $this->federatedShareProvider->create($share);
663
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
663
+			$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $senderId);
664 664
 			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
665 665
 		} else {
666
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
666
+			throw new ProviderCouldNotAddShareException('resharing not allowed for share: '.$id);
667 667
 		}
668 668
 	}
669 669
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 1 patch
Indentation   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -37,403 +37,403 @@
 block discarded – undo
37 37
 use OCP\OCS\IDiscoveryService;
38 38
 
39 39
 class Notifications {
40
-	public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
41
-
42
-	/** @var AddressHandler */
43
-	private $addressHandler;
44
-
45
-	/** @var IClientService */
46
-	private $httpClientService;
47
-
48
-	/** @var IDiscoveryService */
49
-	private $discoveryService;
50
-
51
-	/** @var IJobList  */
52
-	private $jobList;
53
-
54
-	/** @var ICloudFederationProviderManager */
55
-	private $federationProviderManager;
56
-
57
-	/** @var ICloudFederationFactory */
58
-	private $cloudFederationFactory;
59
-
60
-	/** @var IEventDispatcher */
61
-	private $eventDispatcher;
62
-
63
-	public function __construct(
64
-		AddressHandler $addressHandler,
65
-		IClientService $httpClientService,
66
-		IDiscoveryService $discoveryService,
67
-		IJobList $jobList,
68
-		ICloudFederationProviderManager $federationProviderManager,
69
-		ICloudFederationFactory $cloudFederationFactory,
70
-		IEventDispatcher $eventDispatcher
71
-	) {
72
-		$this->addressHandler = $addressHandler;
73
-		$this->httpClientService = $httpClientService;
74
-		$this->discoveryService = $discoveryService;
75
-		$this->jobList = $jobList;
76
-		$this->federationProviderManager = $federationProviderManager;
77
-		$this->cloudFederationFactory = $cloudFederationFactory;
78
-		$this->eventDispatcher = $eventDispatcher;
79
-	}
80
-
81
-	/**
82
-	 * send server-to-server share to remote server
83
-	 *
84
-	 * @param string $token
85
-	 * @param string $shareWith
86
-	 * @param string $name
87
-	 * @param string $remoteId
88
-	 * @param string $owner
89
-	 * @param string $ownerFederatedId
90
-	 * @param string $sharedBy
91
-	 * @param string $sharedByFederatedId
92
-	 * @param int $shareType (can be a remote user or group share)
93
-	 * @return bool
94
-	 * @throws \OC\HintException
95
-	 * @throws \OC\ServerNotAvailableException
96
-	 */
97
-	public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
98
-		[$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
99
-
100
-		if ($user && $remote) {
101
-			$local = $this->addressHandler->generateRemoteURL();
102
-
103
-			$fields = [
104
-				'shareWith' => $user,
105
-				'token' => $token,
106
-				'name' => $name,
107
-				'remoteId' => $remoteId,
108
-				'owner' => $owner,
109
-				'ownerFederatedId' => $ownerFederatedId,
110
-				'sharedBy' => $sharedBy,
111
-				'sharedByFederatedId' => $sharedByFederatedId,
112
-				'remote' => $local,
113
-				'shareType' => $shareType
114
-			];
115
-
116
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
-			$status = json_decode($result['result'], true);
118
-
119
-			$ocsStatus = isset($status['ocs']);
120
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
-
122
-			if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
123
-				$event = new FederatedShareAddedEvent($remote);
124
-				$this->eventDispatcher->dispatchTyped($event);
125
-				return true;
126
-			}
127
-		}
128
-
129
-		return false;
130
-	}
131
-
132
-	/**
133
-	 * ask owner to re-share the file with the given user
134
-	 *
135
-	 * @param string $token
136
-	 * @param string $id remote Id
137
-	 * @param string $shareId internal share Id
138
-	 * @param string $remote remote address of the owner
139
-	 * @param string $shareWith
140
-	 * @param int $permission
141
-	 * @param string $filename
142
-	 * @return array|false
143
-	 * @throws \OC\HintException
144
-	 * @throws \OC\ServerNotAvailableException
145
-	 */
146
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
-		$fields = [
148
-			'shareWith' => $shareWith,
149
-			'token' => $token,
150
-			'permission' => $permission,
151
-			'remoteId' => $shareId,
152
-		];
153
-
154
-		$ocmFields = $fields;
155
-		$ocmFields['remoteId'] = (string)$id;
156
-		$ocmFields['localId'] = $shareId;
157
-		$ocmFields['name'] = $filename;
158
-
159
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
160
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
161
-			return [$ocmResult['token'], $ocmResult['providerId']];
162
-		}
163
-
164
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
165
-		$status = json_decode($result['result'], true);
166
-
167
-		$httpRequestSuccessful = $result['success'];
168
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
169
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
170
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
171
-
172
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
173
-			return [
174
-				$status['ocs']['data']['token'],
175
-				$status['ocs']['data']['remoteId']
176
-			];
177
-		}
178
-
179
-		return false;
180
-	}
181
-
182
-	/**
183
-	 * send server-to-server unshare to remote server
184
-	 *
185
-	 * @param string $remote url
186
-	 * @param string $id share id
187
-	 * @param string $token
188
-	 * @return bool
189
-	 */
190
-	public function sendRemoteUnShare($remote, $id, $token) {
191
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
192
-	}
193
-
194
-	/**
195
-	 * send server-to-server unshare to remote server
196
-	 *
197
-	 * @param string $remote url
198
-	 * @param string $id share id
199
-	 * @param string $token
200
-	 * @return bool
201
-	 */
202
-	public function sendRevokeShare($remote, $id, $token) {
203
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
204
-	}
205
-
206
-	/**
207
-	 * send notification to remote server if the permissions was changed
208
-	 *
209
-	 * @param string $remote
210
-	 * @param string $remoteId
211
-	 * @param string $token
212
-	 * @param int $permissions
213
-	 * @return bool
214
-	 */
215
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
216
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
217
-	}
218
-
219
-	/**
220
-	 * forward accept reShare to remote server
221
-	 *
222
-	 * @param string $remote
223
-	 * @param string $remoteId
224
-	 * @param string $token
225
-	 */
226
-	public function sendAcceptShare($remote, $remoteId, $token) {
227
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
228
-	}
229
-
230
-	/**
231
-	 * forward decline reShare to remote server
232
-	 *
233
-	 * @param string $remote
234
-	 * @param string $remoteId
235
-	 * @param string $token
236
-	 */
237
-	public function sendDeclineShare($remote, $remoteId, $token) {
238
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
239
-	}
240
-
241
-	/**
242
-	 * inform remote server whether server-to-server share was accepted/declined
243
-	 *
244
-	 * @param string $remote
245
-	 * @param string $token
246
-	 * @param string $remoteId Share id on the remote host
247
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
248
-	 * @param array $data
249
-	 * @param int $try
250
-	 * @return boolean
251
-	 */
252
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
253
-		$fields = [
254
-			'token' => $token,
255
-			'remoteId' => $remoteId
256
-		];
257
-		foreach ($data as $key => $value) {
258
-			$fields[$key] = $value;
259
-		}
260
-
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
-		$status = json_decode($result['result'], true);
263
-
264
-		if ($result['success'] &&
265
-			($status['ocs']['meta']['statuscode'] === 100 ||
266
-				$status['ocs']['meta']['statuscode'] === 200
267
-			)
268
-		) {
269
-			return true;
270
-		} elseif ($try === 0) {
271
-			// only add new job on first try
272
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
-				[
274
-					'remote' => $remote,
275
-					'remoteId' => $remoteId,
276
-					'token' => $token,
277
-					'action' => $action,
278
-					'data' => json_encode($data),
279
-					'try' => $try,
280
-					'lastRun' => $this->getTimestamp()
281
-				]
282
-			);
283
-		}
284
-
285
-		return false;
286
-	}
287
-
288
-
289
-	/**
290
-	 * return current timestamp
291
-	 *
292
-	 * @return int
293
-	 */
294
-	protected function getTimestamp() {
295
-		return time();
296
-	}
297
-
298
-	/**
299
-	 * try http post with the given protocol, if no protocol is given we pick
300
-	 * the secure one (https)
301
-	 *
302
-	 * @param string $remoteDomain
303
-	 * @param string $urlSuffix
304
-	 * @param array $fields post parameters
305
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
-	 * @return array
307
-	 * @throws \Exception
308
-	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
310
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
311
-			$remoteDomain = 'https://' . $remoteDomain;
312
-		}
313
-
314
-		$result = [
315
-			'success' => false,
316
-			'result' => '',
317
-		];
318
-
319
-		// if possible we use the new OCM API
320
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
321
-		if (is_array($ocmResult)) {
322
-			$result['success'] = true;
323
-			$result['result'] = json_encode([
324
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
325
-			return $result;
326
-		}
327
-
328
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
329
-	}
330
-
331
-	/**
332
-	 * try old federated sharing API if the OCM api doesn't work
333
-	 *
334
-	 * @param $remoteDomain
335
-	 * @param $urlSuffix
336
-	 * @param array $fields
337
-	 * @return mixed
338
-	 * @throws \Exception
339
-	 */
340
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
341
-		$result = [
342
-			'success' => false,
343
-			'result' => '',
344
-		];
345
-
346
-		// Fall back to old API
347
-		$client = $this->httpClientService->newClient();
348
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
349
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
350
-		try {
351
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
352
-				'body' => $fields,
353
-				'timeout' => 10,
354
-				'connect_timeout' => 10,
355
-			]);
356
-			$result['result'] = $response->getBody();
357
-			$result['success'] = true;
358
-		} catch (\Exception $e) {
359
-			// if flat re-sharing is not supported by the remote server
360
-			// we re-throw the exception and fall back to the old behaviour.
361
-			// (flat re-shares has been introduced in Nextcloud 9.1)
362
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
363
-				throw $e;
364
-			}
365
-		}
366
-
367
-		return $result;
368
-	}
369
-
370
-	/**
371
-	 * send action regarding federated sharing to the remote server using the OCM API
372
-	 *
373
-	 * @param $remoteDomain
374
-	 * @param $fields
375
-	 * @param $action
376
-	 *
377
-	 * @return bool
378
-	 */
379
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
380
-		switch ($action) {
381
-			case 'share':
382
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
383
-					$fields['shareWith'] . '@' . $remoteDomain,
384
-					$fields['name'],
385
-					'',
386
-					$fields['remoteId'],
387
-					$fields['ownerFederatedId'],
388
-					$fields['owner'],
389
-					$fields['sharedByFederatedId'],
390
-					$fields['sharedBy'],
391
-					$fields['token'],
392
-					$fields['shareType'],
393
-					'file'
394
-				);
395
-				return $this->federationProviderManager->sendShare($share);
396
-			case 'reshare':
397
-				// ask owner to reshare a file
398
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
399
-				$notification->setMessage('REQUEST_RESHARE',
400
-					'file',
401
-					$fields['remoteId'],
402
-					[
403
-						'sharedSecret' => $fields['token'],
404
-						'shareWith' => $fields['shareWith'],
405
-						'senderId' => $fields['localId'],
406
-						'shareType' => $fields['shareType'],
407
-						'message' => 'Ask owner to reshare the file'
408
-					]
409
-				);
410
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
411
-			case 'unshare':
412
-				//owner unshares the file from the recipient again
413
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
414
-				$notification->setMessage('SHARE_UNSHARED',
415
-					'file',
416
-					$fields['remoteId'],
417
-					[
418
-						'sharedSecret' => $fields['token'],
419
-						'messgage' => 'file is no longer shared with you'
420
-					]
421
-				);
422
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
423
-			case 'reshare_undo':
424
-				// if a reshare was unshared we send the information to the initiator/owner
425
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
426
-				$notification->setMessage('RESHARE_UNDO',
427
-					'file',
428
-					$fields['remoteId'],
429
-					[
430
-						'sharedSecret' => $fields['token'],
431
-						'message' => 'reshare was revoked'
432
-					]
433
-				);
434
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
435
-		}
436
-
437
-		return false;
438
-	}
40
+    public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
41
+
42
+    /** @var AddressHandler */
43
+    private $addressHandler;
44
+
45
+    /** @var IClientService */
46
+    private $httpClientService;
47
+
48
+    /** @var IDiscoveryService */
49
+    private $discoveryService;
50
+
51
+    /** @var IJobList  */
52
+    private $jobList;
53
+
54
+    /** @var ICloudFederationProviderManager */
55
+    private $federationProviderManager;
56
+
57
+    /** @var ICloudFederationFactory */
58
+    private $cloudFederationFactory;
59
+
60
+    /** @var IEventDispatcher */
61
+    private $eventDispatcher;
62
+
63
+    public function __construct(
64
+        AddressHandler $addressHandler,
65
+        IClientService $httpClientService,
66
+        IDiscoveryService $discoveryService,
67
+        IJobList $jobList,
68
+        ICloudFederationProviderManager $federationProviderManager,
69
+        ICloudFederationFactory $cloudFederationFactory,
70
+        IEventDispatcher $eventDispatcher
71
+    ) {
72
+        $this->addressHandler = $addressHandler;
73
+        $this->httpClientService = $httpClientService;
74
+        $this->discoveryService = $discoveryService;
75
+        $this->jobList = $jobList;
76
+        $this->federationProviderManager = $federationProviderManager;
77
+        $this->cloudFederationFactory = $cloudFederationFactory;
78
+        $this->eventDispatcher = $eventDispatcher;
79
+    }
80
+
81
+    /**
82
+     * send server-to-server share to remote server
83
+     *
84
+     * @param string $token
85
+     * @param string $shareWith
86
+     * @param string $name
87
+     * @param string $remoteId
88
+     * @param string $owner
89
+     * @param string $ownerFederatedId
90
+     * @param string $sharedBy
91
+     * @param string $sharedByFederatedId
92
+     * @param int $shareType (can be a remote user or group share)
93
+     * @return bool
94
+     * @throws \OC\HintException
95
+     * @throws \OC\ServerNotAvailableException
96
+     */
97
+    public function sendRemoteShare($token, $shareWith, $name, $remoteId, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
98
+        [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
99
+
100
+        if ($user && $remote) {
101
+            $local = $this->addressHandler->generateRemoteURL();
102
+
103
+            $fields = [
104
+                'shareWith' => $user,
105
+                'token' => $token,
106
+                'name' => $name,
107
+                'remoteId' => $remoteId,
108
+                'owner' => $owner,
109
+                'ownerFederatedId' => $ownerFederatedId,
110
+                'sharedBy' => $sharedBy,
111
+                'sharedByFederatedId' => $sharedByFederatedId,
112
+                'remote' => $local,
113
+                'shareType' => $shareType
114
+            ];
115
+
116
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
+            $status = json_decode($result['result'], true);
118
+
119
+            $ocsStatus = isset($status['ocs']);
120
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
+
122
+            if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
123
+                $event = new FederatedShareAddedEvent($remote);
124
+                $this->eventDispatcher->dispatchTyped($event);
125
+                return true;
126
+            }
127
+        }
128
+
129
+        return false;
130
+    }
131
+
132
+    /**
133
+     * ask owner to re-share the file with the given user
134
+     *
135
+     * @param string $token
136
+     * @param string $id remote Id
137
+     * @param string $shareId internal share Id
138
+     * @param string $remote remote address of the owner
139
+     * @param string $shareWith
140
+     * @param int $permission
141
+     * @param string $filename
142
+     * @return array|false
143
+     * @throws \OC\HintException
144
+     * @throws \OC\ServerNotAvailableException
145
+     */
146
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
+        $fields = [
148
+            'shareWith' => $shareWith,
149
+            'token' => $token,
150
+            'permission' => $permission,
151
+            'remoteId' => $shareId,
152
+        ];
153
+
154
+        $ocmFields = $fields;
155
+        $ocmFields['remoteId'] = (string)$id;
156
+        $ocmFields['localId'] = $shareId;
157
+        $ocmFields['name'] = $filename;
158
+
159
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
160
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
161
+            return [$ocmResult['token'], $ocmResult['providerId']];
162
+        }
163
+
164
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
165
+        $status = json_decode($result['result'], true);
166
+
167
+        $httpRequestSuccessful = $result['success'];
168
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
169
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
170
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
171
+
172
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
173
+            return [
174
+                $status['ocs']['data']['token'],
175
+                $status['ocs']['data']['remoteId']
176
+            ];
177
+        }
178
+
179
+        return false;
180
+    }
181
+
182
+    /**
183
+     * send server-to-server unshare to remote server
184
+     *
185
+     * @param string $remote url
186
+     * @param string $id share id
187
+     * @param string $token
188
+     * @return bool
189
+     */
190
+    public function sendRemoteUnShare($remote, $id, $token) {
191
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
192
+    }
193
+
194
+    /**
195
+     * send server-to-server unshare to remote server
196
+     *
197
+     * @param string $remote url
198
+     * @param string $id share id
199
+     * @param string $token
200
+     * @return bool
201
+     */
202
+    public function sendRevokeShare($remote, $id, $token) {
203
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
204
+    }
205
+
206
+    /**
207
+     * send notification to remote server if the permissions was changed
208
+     *
209
+     * @param string $remote
210
+     * @param string $remoteId
211
+     * @param string $token
212
+     * @param int $permissions
213
+     * @return bool
214
+     */
215
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
216
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
217
+    }
218
+
219
+    /**
220
+     * forward accept reShare to remote server
221
+     *
222
+     * @param string $remote
223
+     * @param string $remoteId
224
+     * @param string $token
225
+     */
226
+    public function sendAcceptShare($remote, $remoteId, $token) {
227
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
228
+    }
229
+
230
+    /**
231
+     * forward decline reShare to remote server
232
+     *
233
+     * @param string $remote
234
+     * @param string $remoteId
235
+     * @param string $token
236
+     */
237
+    public function sendDeclineShare($remote, $remoteId, $token) {
238
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
239
+    }
240
+
241
+    /**
242
+     * inform remote server whether server-to-server share was accepted/declined
243
+     *
244
+     * @param string $remote
245
+     * @param string $token
246
+     * @param string $remoteId Share id on the remote host
247
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
248
+     * @param array $data
249
+     * @param int $try
250
+     * @return boolean
251
+     */
252
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
253
+        $fields = [
254
+            'token' => $token,
255
+            'remoteId' => $remoteId
256
+        ];
257
+        foreach ($data as $key => $value) {
258
+            $fields[$key] = $value;
259
+        }
260
+
261
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
+        $status = json_decode($result['result'], true);
263
+
264
+        if ($result['success'] &&
265
+            ($status['ocs']['meta']['statuscode'] === 100 ||
266
+                $status['ocs']['meta']['statuscode'] === 200
267
+            )
268
+        ) {
269
+            return true;
270
+        } elseif ($try === 0) {
271
+            // only add new job on first try
272
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
+                [
274
+                    'remote' => $remote,
275
+                    'remoteId' => $remoteId,
276
+                    'token' => $token,
277
+                    'action' => $action,
278
+                    'data' => json_encode($data),
279
+                    'try' => $try,
280
+                    'lastRun' => $this->getTimestamp()
281
+                ]
282
+            );
283
+        }
284
+
285
+        return false;
286
+    }
287
+
288
+
289
+    /**
290
+     * return current timestamp
291
+     *
292
+     * @return int
293
+     */
294
+    protected function getTimestamp() {
295
+        return time();
296
+    }
297
+
298
+    /**
299
+     * try http post with the given protocol, if no protocol is given we pick
300
+     * the secure one (https)
301
+     *
302
+     * @param string $remoteDomain
303
+     * @param string $urlSuffix
304
+     * @param array $fields post parameters
305
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
+     * @return array
307
+     * @throws \Exception
308
+     */
309
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
310
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
311
+            $remoteDomain = 'https://' . $remoteDomain;
312
+        }
313
+
314
+        $result = [
315
+            'success' => false,
316
+            'result' => '',
317
+        ];
318
+
319
+        // if possible we use the new OCM API
320
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
321
+        if (is_array($ocmResult)) {
322
+            $result['success'] = true;
323
+            $result['result'] = json_encode([
324
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
325
+            return $result;
326
+        }
327
+
328
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
329
+    }
330
+
331
+    /**
332
+     * try old federated sharing API if the OCM api doesn't work
333
+     *
334
+     * @param $remoteDomain
335
+     * @param $urlSuffix
336
+     * @param array $fields
337
+     * @return mixed
338
+     * @throws \Exception
339
+     */
340
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
341
+        $result = [
342
+            'success' => false,
343
+            'result' => '',
344
+        ];
345
+
346
+        // Fall back to old API
347
+        $client = $this->httpClientService->newClient();
348
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
349
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
350
+        try {
351
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
352
+                'body' => $fields,
353
+                'timeout' => 10,
354
+                'connect_timeout' => 10,
355
+            ]);
356
+            $result['result'] = $response->getBody();
357
+            $result['success'] = true;
358
+        } catch (\Exception $e) {
359
+            // if flat re-sharing is not supported by the remote server
360
+            // we re-throw the exception and fall back to the old behaviour.
361
+            // (flat re-shares has been introduced in Nextcloud 9.1)
362
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
363
+                throw $e;
364
+            }
365
+        }
366
+
367
+        return $result;
368
+    }
369
+
370
+    /**
371
+     * send action regarding federated sharing to the remote server using the OCM API
372
+     *
373
+     * @param $remoteDomain
374
+     * @param $fields
375
+     * @param $action
376
+     *
377
+     * @return bool
378
+     */
379
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
380
+        switch ($action) {
381
+            case 'share':
382
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
383
+                    $fields['shareWith'] . '@' . $remoteDomain,
384
+                    $fields['name'],
385
+                    '',
386
+                    $fields['remoteId'],
387
+                    $fields['ownerFederatedId'],
388
+                    $fields['owner'],
389
+                    $fields['sharedByFederatedId'],
390
+                    $fields['sharedBy'],
391
+                    $fields['token'],
392
+                    $fields['shareType'],
393
+                    'file'
394
+                );
395
+                return $this->federationProviderManager->sendShare($share);
396
+            case 'reshare':
397
+                // ask owner to reshare a file
398
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
399
+                $notification->setMessage('REQUEST_RESHARE',
400
+                    'file',
401
+                    $fields['remoteId'],
402
+                    [
403
+                        'sharedSecret' => $fields['token'],
404
+                        'shareWith' => $fields['shareWith'],
405
+                        'senderId' => $fields['localId'],
406
+                        'shareType' => $fields['shareType'],
407
+                        'message' => 'Ask owner to reshare the file'
408
+                    ]
409
+                );
410
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
411
+            case 'unshare':
412
+                //owner unshares the file from the recipient again
413
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
414
+                $notification->setMessage('SHARE_UNSHARED',
415
+                    'file',
416
+                    $fields['remoteId'],
417
+                    [
418
+                        'sharedSecret' => $fields['token'],
419
+                        'messgage' => 'file is no longer shared with you'
420
+                    ]
421
+                );
422
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
423
+            case 'reshare_undo':
424
+                // if a reshare was unshared we send the information to the initiator/owner
425
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
426
+                $notification->setMessage('RESHARE_UNDO',
427
+                    'file',
428
+                    $fields['remoteId'],
429
+                    [
430
+                        'sharedSecret' => $fields['token'],
431
+                        'message' => 'reshare was revoked'
432
+                    ]
433
+                );
434
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
435
+        }
436
+
437
+        return false;
438
+    }
439 439
 }
Please login to merge, or discard this patch.