Passed
Push — master ( 9c2d70...6ef7ba )
by Roeland
10:28
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2558 added lines, -2558 removed lines patch added patch discarded remove patch
@@ -75,2563 +75,2563 @@
 block discarded – undo
75 75
  */
76 76
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
77 77
 
78
-	const CALENDAR_TYPE_CALENDAR = 0;
79
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
-
81
-	const PERSONAL_CALENDAR_URI = 'personal';
82
-	const PERSONAL_CALENDAR_NAME = 'Personal';
83
-
84
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
-
87
-	/**
88
-	 * We need to specify a max date, because we need to stop *somewhere*
89
-	 *
90
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
91
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
-	 * in 2038-01-19 to avoid problems when the date is converted
93
-	 * to a unix timestamp.
94
-	 */
95
-	const MAX_DATE = '2038-01-01';
96
-
97
-	const ACCESS_PUBLIC = 4;
98
-	const CLASSIFICATION_PUBLIC = 0;
99
-	const CLASSIFICATION_PRIVATE = 1;
100
-	const CLASSIFICATION_CONFIDENTIAL = 2;
101
-
102
-	/**
103
-	 * List of CalDAV properties, and how they map to database field names
104
-	 * Add your own properties by simply adding on to this array.
105
-	 *
106
-	 * Note that only string-based properties are supported here.
107
-	 *
108
-	 * @var array
109
-	 */
110
-	public $propertyMap = [
111
-		'{DAV:}displayname'                          => 'displayname',
112
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
-	];
117
-
118
-	/**
119
-	 * List of subscription properties, and how they map to database field names.
120
-	 *
121
-	 * @var array
122
-	 */
123
-	public $subscriptionPropertyMap = [
124
-		'{DAV:}displayname'                                           => 'displayname',
125
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
-	];
132
-
133
-	/** @var array properties to index */
134
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
-		'ORGANIZER'];
137
-
138
-	/** @var array parameters to index */
139
-	public static $indexParameters = [
140
-		'ATTENDEE' => ['CN'],
141
-		'ORGANIZER' => ['CN'],
142
-	];
143
-
144
-	/**
145
-	 * @var string[] Map of uid => display name
146
-	 */
147
-	protected $userDisplayNames;
148
-
149
-	/** @var IDBConnection */
150
-	private $db;
151
-
152
-	/** @var Backend */
153
-	private $calendarSharingBackend;
154
-
155
-	/** @var Principal */
156
-	private $principalBackend;
157
-
158
-	/** @var IUserManager */
159
-	private $userManager;
160
-
161
-	/** @var ISecureRandom */
162
-	private $random;
163
-
164
-	/** @var ILogger */
165
-	private $logger;
166
-
167
-	/** @var EventDispatcherInterface */
168
-	private $dispatcher;
169
-
170
-	/** @var bool */
171
-	private $legacyEndpoint;
172
-
173
-	/** @var string */
174
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
175
-
176
-	/**
177
-	 * CalDavBackend constructor.
178
-	 *
179
-	 * @param IDBConnection $db
180
-	 * @param Principal $principalBackend
181
-	 * @param IUserManager $userManager
182
-	 * @param IGroupManager $groupManager
183
-	 * @param ISecureRandom $random
184
-	 * @param ILogger $logger
185
-	 * @param EventDispatcherInterface $dispatcher
186
-	 * @param bool $legacyEndpoint
187
-	 */
188
-	public function __construct(IDBConnection $db,
189
-								Principal $principalBackend,
190
-								IUserManager $userManager,
191
-								IGroupManager $groupManager,
192
-								ISecureRandom $random,
193
-								ILogger $logger,
194
-								EventDispatcherInterface $dispatcher,
195
-								bool $legacyEndpoint = false) {
196
-		$this->db = $db;
197
-		$this->principalBackend = $principalBackend;
198
-		$this->userManager = $userManager;
199
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
-		$this->random = $random;
201
-		$this->logger = $logger;
202
-		$this->dispatcher = $dispatcher;
203
-		$this->legacyEndpoint = $legacyEndpoint;
204
-	}
205
-
206
-	/**
207
-	 * Return the number of calendars for a principal
208
-	 *
209
-	 * By default this excludes the automatically generated birthday calendar
210
-	 *
211
-	 * @param $principalUri
212
-	 * @param bool $excludeBirthday
213
-	 * @return int
214
-	 */
215
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
-		$principalUri = $this->convertPrincipal($principalUri, true);
217
-		$query = $this->db->getQueryBuilder();
218
-		$query->select($query->func()->count('*'))
219
-			->from('calendars')
220
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
-
222
-		if ($excludeBirthday) {
223
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
-		}
225
-
226
-		return (int)$query->execute()->fetchColumn();
227
-	}
228
-
229
-	/**
230
-	 * Returns a list of calendars for a principal.
231
-	 *
232
-	 * Every project is an array with the following keys:
233
-	 *  * id, a unique id that will be used by other functions to modify the
234
-	 *    calendar. This can be the same as the uri or a database key.
235
-	 *  * uri, which the basename of the uri with which the calendar is
236
-	 *    accessed.
237
-	 *  * principaluri. The owner of the calendar. Almost always the same as
238
-	 *    principalUri passed to this method.
239
-	 *
240
-	 * Furthermore it can contain webdav properties in clark notation. A very
241
-	 * common one is '{DAV:}displayname'.
242
-	 *
243
-	 * Many clients also require:
244
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
-	 * For this property, you can just return an instance of
246
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
-	 *
248
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
-	 * ACL will automatically be put in read-only mode.
250
-	 *
251
-	 * @param string $principalUri
252
-	 * @return array
253
-	 */
254
-	function getCalendarsForUser($principalUri) {
255
-		$principalUriOriginal = $principalUri;
256
-		$principalUri = $this->convertPrincipal($principalUri, true);
257
-		$fields = array_values($this->propertyMap);
258
-		$fields[] = 'id';
259
-		$fields[] = 'uri';
260
-		$fields[] = 'synctoken';
261
-		$fields[] = 'components';
262
-		$fields[] = 'principaluri';
263
-		$fields[] = 'transparent';
264
-
265
-		// Making fields a comma-delimited list
266
-		$query = $this->db->getQueryBuilder();
267
-		$query->select($fields)->from('calendars')
268
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
-				->orderBy('calendarorder', 'ASC');
270
-		$stmt = $query->execute();
271
-
272
-		$calendars = [];
273
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
-
275
-			$components = [];
276
-			if ($row['components']) {
277
-				$components = explode(',',$row['components']);
278
-			}
279
-
280
-			$calendar = [
281
-				'id' => $row['id'],
282
-				'uri' => $row['uri'],
283
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
-			];
290
-
291
-			foreach($this->propertyMap as $xmlName=>$dbName) {
292
-				$calendar[$xmlName] = $row[$dbName];
293
-			}
294
-
295
-			$this->addOwnerPrincipal($calendar);
296
-
297
-			if (!isset($calendars[$calendar['id']])) {
298
-				$calendars[$calendar['id']] = $calendar;
299
-			}
300
-		}
301
-
302
-		$stmt->closeCursor();
303
-
304
-		// query for shared calendars
305
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
-
308
-		$principals = array_map(function($principal) {
309
-			return urldecode($principal);
310
-		}, $principals);
311
-		$principals[]= $principalUri;
312
-
313
-		$fields = array_values($this->propertyMap);
314
-		$fields[] = 'a.id';
315
-		$fields[] = 'a.uri';
316
-		$fields[] = 'a.synctoken';
317
-		$fields[] = 'a.components';
318
-		$fields[] = 'a.principaluri';
319
-		$fields[] = 'a.transparent';
320
-		$fields[] = 's.access';
321
-		$query = $this->db->getQueryBuilder();
322
-		$result = $query->select($fields)
323
-			->from('dav_shares', 's')
324
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
-			->setParameter('type', 'calendar')
328
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
-			->execute();
330
-
331
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
-		while($row = $result->fetch()) {
333
-			if ($row['principaluri'] === $principalUri) {
334
-				continue;
335
-			}
336
-
337
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
-			if (isset($calendars[$row['id']])) {
339
-				if ($readOnly) {
340
-					// New share can not have more permissions then the old one.
341
-					continue;
342
-				}
343
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
-					// Old share is already read-write, no more permissions can be gained
346
-					continue;
347
-				}
348
-			}
349
-
350
-			list(, $name) = Uri\split($row['principaluri']);
351
-			$uri = $row['uri'] . '_shared_by_' . $name;
352
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
-			$components = [];
354
-			if ($row['components']) {
355
-				$components = explode(',',$row['components']);
356
-			}
357
-			$calendar = [
358
-				'id' => $row['id'],
359
-				'uri' => $uri,
360
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
-				$readOnlyPropertyName => $readOnly,
367
-			];
368
-
369
-			foreach($this->propertyMap as $xmlName=>$dbName) {
370
-				$calendar[$xmlName] = $row[$dbName];
371
-			}
372
-
373
-			$this->addOwnerPrincipal($calendar);
374
-
375
-			$calendars[$calendar['id']] = $calendar;
376
-		}
377
-		$result->closeCursor();
378
-
379
-		return array_values($calendars);
380
-	}
381
-
382
-	/**
383
-	 * @param $principalUri
384
-	 * @return array
385
-	 */
386
-	public function getUsersOwnCalendars($principalUri) {
387
-		$principalUri = $this->convertPrincipal($principalUri, true);
388
-		$fields = array_values($this->propertyMap);
389
-		$fields[] = 'id';
390
-		$fields[] = 'uri';
391
-		$fields[] = 'synctoken';
392
-		$fields[] = 'components';
393
-		$fields[] = 'principaluri';
394
-		$fields[] = 'transparent';
395
-		// Making fields a comma-delimited list
396
-		$query = $this->db->getQueryBuilder();
397
-		$query->select($fields)->from('calendars')
398
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
-			->orderBy('calendarorder', 'ASC');
400
-		$stmt = $query->execute();
401
-		$calendars = [];
402
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
-			$components = [];
404
-			if ($row['components']) {
405
-				$components = explode(',',$row['components']);
406
-			}
407
-			$calendar = [
408
-				'id' => $row['id'],
409
-				'uri' => $row['uri'],
410
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
-			];
416
-			foreach($this->propertyMap as $xmlName=>$dbName) {
417
-				$calendar[$xmlName] = $row[$dbName];
418
-			}
419
-
420
-			$this->addOwnerPrincipal($calendar);
421
-
422
-			if (!isset($calendars[$calendar['id']])) {
423
-				$calendars[$calendar['id']] = $calendar;
424
-			}
425
-		}
426
-		$stmt->closeCursor();
427
-		return array_values($calendars);
428
-	}
429
-
430
-
431
-	/**
432
-	 * @param $uid
433
-	 * @return string
434
-	 */
435
-	private function getUserDisplayName($uid) {
436
-		if (!isset($this->userDisplayNames[$uid])) {
437
-			$user = $this->userManager->get($uid);
438
-
439
-			if ($user instanceof IUser) {
440
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
441
-			} else {
442
-				$this->userDisplayNames[$uid] = $uid;
443
-			}
444
-		}
445
-
446
-		return $this->userDisplayNames[$uid];
447
-	}
78
+    const CALENDAR_TYPE_CALENDAR = 0;
79
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
+
81
+    const PERSONAL_CALENDAR_URI = 'personal';
82
+    const PERSONAL_CALENDAR_NAME = 'Personal';
83
+
84
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
+
87
+    /**
88
+     * We need to specify a max date, because we need to stop *somewhere*
89
+     *
90
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
91
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
+     * in 2038-01-19 to avoid problems when the date is converted
93
+     * to a unix timestamp.
94
+     */
95
+    const MAX_DATE = '2038-01-01';
96
+
97
+    const ACCESS_PUBLIC = 4;
98
+    const CLASSIFICATION_PUBLIC = 0;
99
+    const CLASSIFICATION_PRIVATE = 1;
100
+    const CLASSIFICATION_CONFIDENTIAL = 2;
101
+
102
+    /**
103
+     * List of CalDAV properties, and how they map to database field names
104
+     * Add your own properties by simply adding on to this array.
105
+     *
106
+     * Note that only string-based properties are supported here.
107
+     *
108
+     * @var array
109
+     */
110
+    public $propertyMap = [
111
+        '{DAV:}displayname'                          => 'displayname',
112
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
+    ];
117
+
118
+    /**
119
+     * List of subscription properties, and how they map to database field names.
120
+     *
121
+     * @var array
122
+     */
123
+    public $subscriptionPropertyMap = [
124
+        '{DAV:}displayname'                                           => 'displayname',
125
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
+    ];
132
+
133
+    /** @var array properties to index */
134
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
+        'ORGANIZER'];
137
+
138
+    /** @var array parameters to index */
139
+    public static $indexParameters = [
140
+        'ATTENDEE' => ['CN'],
141
+        'ORGANIZER' => ['CN'],
142
+    ];
143
+
144
+    /**
145
+     * @var string[] Map of uid => display name
146
+     */
147
+    protected $userDisplayNames;
148
+
149
+    /** @var IDBConnection */
150
+    private $db;
151
+
152
+    /** @var Backend */
153
+    private $calendarSharingBackend;
154
+
155
+    /** @var Principal */
156
+    private $principalBackend;
157
+
158
+    /** @var IUserManager */
159
+    private $userManager;
160
+
161
+    /** @var ISecureRandom */
162
+    private $random;
163
+
164
+    /** @var ILogger */
165
+    private $logger;
166
+
167
+    /** @var EventDispatcherInterface */
168
+    private $dispatcher;
169
+
170
+    /** @var bool */
171
+    private $legacyEndpoint;
172
+
173
+    /** @var string */
174
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
175
+
176
+    /**
177
+     * CalDavBackend constructor.
178
+     *
179
+     * @param IDBConnection $db
180
+     * @param Principal $principalBackend
181
+     * @param IUserManager $userManager
182
+     * @param IGroupManager $groupManager
183
+     * @param ISecureRandom $random
184
+     * @param ILogger $logger
185
+     * @param EventDispatcherInterface $dispatcher
186
+     * @param bool $legacyEndpoint
187
+     */
188
+    public function __construct(IDBConnection $db,
189
+                                Principal $principalBackend,
190
+                                IUserManager $userManager,
191
+                                IGroupManager $groupManager,
192
+                                ISecureRandom $random,
193
+                                ILogger $logger,
194
+                                EventDispatcherInterface $dispatcher,
195
+                                bool $legacyEndpoint = false) {
196
+        $this->db = $db;
197
+        $this->principalBackend = $principalBackend;
198
+        $this->userManager = $userManager;
199
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
+        $this->random = $random;
201
+        $this->logger = $logger;
202
+        $this->dispatcher = $dispatcher;
203
+        $this->legacyEndpoint = $legacyEndpoint;
204
+    }
205
+
206
+    /**
207
+     * Return the number of calendars for a principal
208
+     *
209
+     * By default this excludes the automatically generated birthday calendar
210
+     *
211
+     * @param $principalUri
212
+     * @param bool $excludeBirthday
213
+     * @return int
214
+     */
215
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
+        $principalUri = $this->convertPrincipal($principalUri, true);
217
+        $query = $this->db->getQueryBuilder();
218
+        $query->select($query->func()->count('*'))
219
+            ->from('calendars')
220
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
+
222
+        if ($excludeBirthday) {
223
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
+        }
225
+
226
+        return (int)$query->execute()->fetchColumn();
227
+    }
228
+
229
+    /**
230
+     * Returns a list of calendars for a principal.
231
+     *
232
+     * Every project is an array with the following keys:
233
+     *  * id, a unique id that will be used by other functions to modify the
234
+     *    calendar. This can be the same as the uri or a database key.
235
+     *  * uri, which the basename of the uri with which the calendar is
236
+     *    accessed.
237
+     *  * principaluri. The owner of the calendar. Almost always the same as
238
+     *    principalUri passed to this method.
239
+     *
240
+     * Furthermore it can contain webdav properties in clark notation. A very
241
+     * common one is '{DAV:}displayname'.
242
+     *
243
+     * Many clients also require:
244
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
+     * For this property, you can just return an instance of
246
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
+     *
248
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
+     * ACL will automatically be put in read-only mode.
250
+     *
251
+     * @param string $principalUri
252
+     * @return array
253
+     */
254
+    function getCalendarsForUser($principalUri) {
255
+        $principalUriOriginal = $principalUri;
256
+        $principalUri = $this->convertPrincipal($principalUri, true);
257
+        $fields = array_values($this->propertyMap);
258
+        $fields[] = 'id';
259
+        $fields[] = 'uri';
260
+        $fields[] = 'synctoken';
261
+        $fields[] = 'components';
262
+        $fields[] = 'principaluri';
263
+        $fields[] = 'transparent';
264
+
265
+        // Making fields a comma-delimited list
266
+        $query = $this->db->getQueryBuilder();
267
+        $query->select($fields)->from('calendars')
268
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
+                ->orderBy('calendarorder', 'ASC');
270
+        $stmt = $query->execute();
271
+
272
+        $calendars = [];
273
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
+
275
+            $components = [];
276
+            if ($row['components']) {
277
+                $components = explode(',',$row['components']);
278
+            }
279
+
280
+            $calendar = [
281
+                'id' => $row['id'],
282
+                'uri' => $row['uri'],
283
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
+            ];
290
+
291
+            foreach($this->propertyMap as $xmlName=>$dbName) {
292
+                $calendar[$xmlName] = $row[$dbName];
293
+            }
294
+
295
+            $this->addOwnerPrincipal($calendar);
296
+
297
+            if (!isset($calendars[$calendar['id']])) {
298
+                $calendars[$calendar['id']] = $calendar;
299
+            }
300
+        }
301
+
302
+        $stmt->closeCursor();
303
+
304
+        // query for shared calendars
305
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
+
308
+        $principals = array_map(function($principal) {
309
+            return urldecode($principal);
310
+        }, $principals);
311
+        $principals[]= $principalUri;
312
+
313
+        $fields = array_values($this->propertyMap);
314
+        $fields[] = 'a.id';
315
+        $fields[] = 'a.uri';
316
+        $fields[] = 'a.synctoken';
317
+        $fields[] = 'a.components';
318
+        $fields[] = 'a.principaluri';
319
+        $fields[] = 'a.transparent';
320
+        $fields[] = 's.access';
321
+        $query = $this->db->getQueryBuilder();
322
+        $result = $query->select($fields)
323
+            ->from('dav_shares', 's')
324
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
+            ->setParameter('type', 'calendar')
328
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
+            ->execute();
330
+
331
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
+        while($row = $result->fetch()) {
333
+            if ($row['principaluri'] === $principalUri) {
334
+                continue;
335
+            }
336
+
337
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
+            if (isset($calendars[$row['id']])) {
339
+                if ($readOnly) {
340
+                    // New share can not have more permissions then the old one.
341
+                    continue;
342
+                }
343
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
+                    // Old share is already read-write, no more permissions can be gained
346
+                    continue;
347
+                }
348
+            }
349
+
350
+            list(, $name) = Uri\split($row['principaluri']);
351
+            $uri = $row['uri'] . '_shared_by_' . $name;
352
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
+            $components = [];
354
+            if ($row['components']) {
355
+                $components = explode(',',$row['components']);
356
+            }
357
+            $calendar = [
358
+                'id' => $row['id'],
359
+                'uri' => $uri,
360
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
+                $readOnlyPropertyName => $readOnly,
367
+            ];
368
+
369
+            foreach($this->propertyMap as $xmlName=>$dbName) {
370
+                $calendar[$xmlName] = $row[$dbName];
371
+            }
372
+
373
+            $this->addOwnerPrincipal($calendar);
374
+
375
+            $calendars[$calendar['id']] = $calendar;
376
+        }
377
+        $result->closeCursor();
378
+
379
+        return array_values($calendars);
380
+    }
381
+
382
+    /**
383
+     * @param $principalUri
384
+     * @return array
385
+     */
386
+    public function getUsersOwnCalendars($principalUri) {
387
+        $principalUri = $this->convertPrincipal($principalUri, true);
388
+        $fields = array_values($this->propertyMap);
389
+        $fields[] = 'id';
390
+        $fields[] = 'uri';
391
+        $fields[] = 'synctoken';
392
+        $fields[] = 'components';
393
+        $fields[] = 'principaluri';
394
+        $fields[] = 'transparent';
395
+        // Making fields a comma-delimited list
396
+        $query = $this->db->getQueryBuilder();
397
+        $query->select($fields)->from('calendars')
398
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
+            ->orderBy('calendarorder', 'ASC');
400
+        $stmt = $query->execute();
401
+        $calendars = [];
402
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
+            $components = [];
404
+            if ($row['components']) {
405
+                $components = explode(',',$row['components']);
406
+            }
407
+            $calendar = [
408
+                'id' => $row['id'],
409
+                'uri' => $row['uri'],
410
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
+            ];
416
+            foreach($this->propertyMap as $xmlName=>$dbName) {
417
+                $calendar[$xmlName] = $row[$dbName];
418
+            }
419
+
420
+            $this->addOwnerPrincipal($calendar);
421
+
422
+            if (!isset($calendars[$calendar['id']])) {
423
+                $calendars[$calendar['id']] = $calendar;
424
+            }
425
+        }
426
+        $stmt->closeCursor();
427
+        return array_values($calendars);
428
+    }
429
+
430
+
431
+    /**
432
+     * @param $uid
433
+     * @return string
434
+     */
435
+    private function getUserDisplayName($uid) {
436
+        if (!isset($this->userDisplayNames[$uid])) {
437
+            $user = $this->userManager->get($uid);
438
+
439
+            if ($user instanceof IUser) {
440
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
441
+            } else {
442
+                $this->userDisplayNames[$uid] = $uid;
443
+            }
444
+        }
445
+
446
+        return $this->userDisplayNames[$uid];
447
+    }
448 448
 	
449
-	/**
450
-	 * @return array
451
-	 */
452
-	public function getPublicCalendars() {
453
-		$fields = array_values($this->propertyMap);
454
-		$fields[] = 'a.id';
455
-		$fields[] = 'a.uri';
456
-		$fields[] = 'a.synctoken';
457
-		$fields[] = 'a.components';
458
-		$fields[] = 'a.principaluri';
459
-		$fields[] = 'a.transparent';
460
-		$fields[] = 's.access';
461
-		$fields[] = 's.publicuri';
462
-		$calendars = [];
463
-		$query = $this->db->getQueryBuilder();
464
-		$result = $query->select($fields)
465
-			->from('dav_shares', 's')
466
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
-			->execute();
470
-
471
-		while($row = $result->fetch()) {
472
-			list(, $name) = Uri\split($row['principaluri']);
473
-			$row['displayname'] = $row['displayname'] . "($name)";
474
-			$components = [];
475
-			if ($row['components']) {
476
-				$components = explode(',',$row['components']);
477
-			}
478
-			$calendar = [
479
-				'id' => $row['id'],
480
-				'uri' => $row['publicuri'],
481
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
-			];
490
-
491
-			foreach($this->propertyMap as $xmlName=>$dbName) {
492
-				$calendar[$xmlName] = $row[$dbName];
493
-			}
494
-
495
-			$this->addOwnerPrincipal($calendar);
496
-
497
-			if (!isset($calendars[$calendar['id']])) {
498
-				$calendars[$calendar['id']] = $calendar;
499
-			}
500
-		}
501
-		$result->closeCursor();
502
-
503
-		return array_values($calendars);
504
-	}
505
-
506
-	/**
507
-	 * @param string $uri
508
-	 * @return array
509
-	 * @throws NotFound
510
-	 */
511
-	public function getPublicCalendar($uri) {
512
-		$fields = array_values($this->propertyMap);
513
-		$fields[] = 'a.id';
514
-		$fields[] = 'a.uri';
515
-		$fields[] = 'a.synctoken';
516
-		$fields[] = 'a.components';
517
-		$fields[] = 'a.principaluri';
518
-		$fields[] = 'a.transparent';
519
-		$fields[] = 's.access';
520
-		$fields[] = 's.publicuri';
521
-		$query = $this->db->getQueryBuilder();
522
-		$result = $query->select($fields)
523
-			->from('dav_shares', 's')
524
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
-			->execute();
529
-
530
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
531
-
532
-		$result->closeCursor();
533
-
534
-		if ($row === false) {
535
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
-		}
537
-
538
-		list(, $name) = Uri\split($row['principaluri']);
539
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
-		$components = [];
541
-		if ($row['components']) {
542
-			$components = explode(',',$row['components']);
543
-		}
544
-		$calendar = [
545
-			'id' => $row['id'],
546
-			'uri' => $row['publicuri'],
547
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
-		];
556
-
557
-		foreach($this->propertyMap as $xmlName=>$dbName) {
558
-			$calendar[$xmlName] = $row[$dbName];
559
-		}
560
-
561
-		$this->addOwnerPrincipal($calendar);
562
-
563
-		return $calendar;
564
-
565
-	}
566
-
567
-	/**
568
-	 * @param string $principal
569
-	 * @param string $uri
570
-	 * @return array|null
571
-	 */
572
-	public function getCalendarByUri($principal, $uri) {
573
-		$fields = array_values($this->propertyMap);
574
-		$fields[] = 'id';
575
-		$fields[] = 'uri';
576
-		$fields[] = 'synctoken';
577
-		$fields[] = 'components';
578
-		$fields[] = 'principaluri';
579
-		$fields[] = 'transparent';
580
-
581
-		// Making fields a comma-delimited list
582
-		$query = $this->db->getQueryBuilder();
583
-		$query->select($fields)->from('calendars')
584
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
-			->setMaxResults(1);
587
-		$stmt = $query->execute();
588
-
589
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
-		$stmt->closeCursor();
591
-		if ($row === false) {
592
-			return null;
593
-		}
594
-
595
-		$components = [];
596
-		if ($row['components']) {
597
-			$components = explode(',',$row['components']);
598
-		}
599
-
600
-		$calendar = [
601
-			'id' => $row['id'],
602
-			'uri' => $row['uri'],
603
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
-		];
609
-
610
-		foreach($this->propertyMap as $xmlName=>$dbName) {
611
-			$calendar[$xmlName] = $row[$dbName];
612
-		}
613
-
614
-		$this->addOwnerPrincipal($calendar);
615
-
616
-		return $calendar;
617
-	}
618
-
619
-	/**
620
-	 * @param $calendarId
621
-	 * @return array|null
622
-	 */
623
-	public function getCalendarById($calendarId) {
624
-		$fields = array_values($this->propertyMap);
625
-		$fields[] = 'id';
626
-		$fields[] = 'uri';
627
-		$fields[] = 'synctoken';
628
-		$fields[] = 'components';
629
-		$fields[] = 'principaluri';
630
-		$fields[] = 'transparent';
631
-
632
-		// Making fields a comma-delimited list
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->select($fields)->from('calendars')
635
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
-			->setMaxResults(1);
637
-		$stmt = $query->execute();
638
-
639
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
-		$stmt->closeCursor();
641
-		if ($row === false) {
642
-			return null;
643
-		}
644
-
645
-		$components = [];
646
-		if ($row['components']) {
647
-			$components = explode(',',$row['components']);
648
-		}
649
-
650
-		$calendar = [
651
-			'id' => $row['id'],
652
-			'uri' => $row['uri'],
653
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
-		];
659
-
660
-		foreach($this->propertyMap as $xmlName=>$dbName) {
661
-			$calendar[$xmlName] = $row[$dbName];
662
-		}
663
-
664
-		$this->addOwnerPrincipal($calendar);
665
-
666
-		return $calendar;
667
-	}
668
-
669
-	/**
670
-	 * @param $subscriptionId
671
-	 */
672
-	public function getSubscriptionById($subscriptionId) {
673
-		$fields = array_values($this->subscriptionPropertyMap);
674
-		$fields[] = 'id';
675
-		$fields[] = 'uri';
676
-		$fields[] = 'source';
677
-		$fields[] = 'synctoken';
678
-		$fields[] = 'principaluri';
679
-		$fields[] = 'lastmodified';
680
-
681
-		$query = $this->db->getQueryBuilder();
682
-		$query->select($fields)
683
-			->from('calendarsubscriptions')
684
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
-			->orderBy('calendarorder', 'asc');
686
-		$stmt =$query->execute();
687
-
688
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
-		$stmt->closeCursor();
690
-		if ($row === false) {
691
-			return null;
692
-		}
693
-
694
-		$subscription = [
695
-			'id'           => $row['id'],
696
-			'uri'          => $row['uri'],
697
-			'principaluri' => $row['principaluri'],
698
-			'source'       => $row['source'],
699
-			'lastmodified' => $row['lastmodified'],
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
-		];
703
-
704
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
-			if (!is_null($row[$dbName])) {
706
-				$subscription[$xmlName] = $row[$dbName];
707
-			}
708
-		}
709
-
710
-		return $subscription;
711
-	}
712
-
713
-	/**
714
-	 * Creates a new calendar for a principal.
715
-	 *
716
-	 * If the creation was a success, an id must be returned that can be used to reference
717
-	 * this calendar in other methods, such as updateCalendar.
718
-	 *
719
-	 * @param string $principalUri
720
-	 * @param string $calendarUri
721
-	 * @param array $properties
722
-	 * @return int
723
-	 * @suppress SqlInjectionChecker
724
-	 */
725
-	function createCalendar($principalUri, $calendarUri, array $properties) {
726
-		$values = [
727
-			'principaluri' => $this->convertPrincipal($principalUri, true),
728
-			'uri'          => $calendarUri,
729
-			'synctoken'    => 1,
730
-			'transparent'  => 0,
731
-			'components'   => 'VEVENT,VTODO',
732
-			'displayname'  => $calendarUri
733
-		];
734
-
735
-		// Default value
736
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
-		if (isset($properties[$sccs])) {
738
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
-			}
741
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
742
-		} else if (isset($properties['components'])) {
743
-			// Allow to provide components internally without having
744
-			// to create a SupportedCalendarComponentSet object
745
-			$values['components'] = $properties['components'];
746
-		}
747
-
748
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
-		if (isset($properties[$transp])) {
750
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
-		}
752
-
753
-		foreach($this->propertyMap as $xmlName=>$dbName) {
754
-			if (isset($properties[$xmlName])) {
755
-				$values[$dbName] = $properties[$xmlName];
756
-			}
757
-		}
758
-
759
-		$query = $this->db->getQueryBuilder();
760
-		$query->insert('calendars');
761
-		foreach($values as $column => $value) {
762
-			$query->setValue($column, $query->createNamedParameter($value));
763
-		}
764
-		$query->execute();
765
-		$calendarId = $query->getLastInsertId();
766
-
767
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
-			[
770
-				'calendarId' => $calendarId,
771
-				'calendarData' => $this->getCalendarById($calendarId),
772
-		]));
773
-
774
-		return $calendarId;
775
-	}
776
-
777
-	/**
778
-	 * Updates properties for a calendar.
779
-	 *
780
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
-	 * To do the actual updates, you must tell this object which properties
782
-	 * you're going to process with the handle() method.
783
-	 *
784
-	 * Calling the handle method is like telling the PropPatch object "I
785
-	 * promise I can handle updating this property".
786
-	 *
787
-	 * Read the PropPatch documentation for more info and examples.
788
-	 *
789
-	 * @param mixed $calendarId
790
-	 * @param PropPatch $propPatch
791
-	 * @return void
792
-	 */
793
-	function updateCalendar($calendarId, PropPatch $propPatch) {
794
-		$supportedProperties = array_keys($this->propertyMap);
795
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
-
797
-		/**
798
-		 * @suppress SqlInjectionChecker
799
-		 */
800
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
801
-			$newValues = [];
802
-			foreach ($mutations as $propertyName => $propertyValue) {
803
-
804
-				switch ($propertyName) {
805
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
806
-						$fieldName = 'transparent';
807
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808
-						break;
809
-					default :
810
-						$fieldName = $this->propertyMap[$propertyName];
811
-						$newValues[$fieldName] = $propertyValue;
812
-						break;
813
-				}
814
-
815
-			}
816
-			$query = $this->db->getQueryBuilder();
817
-			$query->update('calendars');
818
-			foreach ($newValues as $fieldName => $value) {
819
-				$query->set($fieldName, $query->createNamedParameter($value));
820
-			}
821
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
822
-			$query->execute();
823
-
824
-			$this->addChange($calendarId, "", 2);
825
-
826
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
827
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
828
-				[
829
-					'calendarId' => $calendarId,
830
-					'calendarData' => $this->getCalendarById($calendarId),
831
-					'shares' => $this->getShares($calendarId),
832
-					'propertyMutations' => $mutations,
833
-			]));
834
-
835
-			return true;
836
-		});
837
-	}
838
-
839
-	/**
840
-	 * Delete a calendar and all it's objects
841
-	 *
842
-	 * @param mixed $calendarId
843
-	 * @return void
844
-	 */
845
-	function deleteCalendar($calendarId) {
846
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
847
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
848
-			[
849
-				'calendarId' => $calendarId,
850
-				'calendarData' => $this->getCalendarById($calendarId),
851
-				'shares' => $this->getShares($calendarId),
852
-		]));
853
-
854
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
855
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
856
-
857
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
858
-		$stmt->execute([$calendarId]);
859
-
860
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
861
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
862
-
863
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
864
-
865
-		$query = $this->db->getQueryBuilder();
866
-		$query->delete($this->dbObjectPropertiesTable)
867
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
869
-			->execute();
870
-	}
871
-
872
-	/**
873
-	 * Delete all of an user's shares
874
-	 *
875
-	 * @param string $principaluri
876
-	 * @return void
877
-	 */
878
-	function deleteAllSharesByUser($principaluri) {
879
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
880
-	}
881
-
882
-	/**
883
-	 * Returns all calendar objects within a calendar.
884
-	 *
885
-	 * Every item contains an array with the following keys:
886
-	 *   * calendardata - The iCalendar-compatible calendar data
887
-	 *   * uri - a unique key which will be used to construct the uri. This can
888
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
889
-	 *     good idea. This is only the basename, or filename, not the full
890
-	 *     path.
891
-	 *   * lastmodified - a timestamp of the last modification time
892
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
893
-	 *   '"abcdef"')
894
-	 *   * size - The size of the calendar objects, in bytes.
895
-	 *   * component - optional, a string containing the type of object, such
896
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
897
-	 *     the Content-Type header.
898
-	 *
899
-	 * Note that the etag is optional, but it's highly encouraged to return for
900
-	 * speed reasons.
901
-	 *
902
-	 * The calendardata is also optional. If it's not returned
903
-	 * 'getCalendarObject' will be called later, which *is* expected to return
904
-	 * calendardata.
905
-	 *
906
-	 * If neither etag or size are specified, the calendardata will be
907
-	 * used/fetched to determine these numbers. If both are specified the
908
-	 * amount of times this is needed is reduced by a great degree.
909
-	 *
910
-	 * @param mixed $id
911
-	 * @param int $calendarType
912
-	 * @return array
913
-	 */
914
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
915
-		$query = $this->db->getQueryBuilder();
916
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917
-			->from('calendarobjects')
918
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
919
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
920
-		$stmt = $query->execute();
921
-
922
-		$result = [];
923
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924
-			$result[] = [
925
-				'id'           => $row['id'],
926
-				'uri'          => $row['uri'],
927
-				'lastmodified' => $row['lastmodified'],
928
-				'etag'         => '"' . $row['etag'] . '"',
929
-				'calendarid'   => $row['calendarid'],
930
-				'size'         => (int)$row['size'],
931
-				'component'    => strtolower($row['componenttype']),
932
-				'classification'=> (int)$row['classification']
933
-			];
934
-		}
935
-
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * Returns information from a single calendar object, based on it's object
941
-	 * uri.
942
-	 *
943
-	 * The object uri is only the basename, or filename and not a full path.
944
-	 *
945
-	 * The returned array must have the same keys as getCalendarObjects. The
946
-	 * 'calendardata' object is required here though, while it's not required
947
-	 * for getCalendarObjects.
948
-	 *
949
-	 * This method must return null if the object did not exist.
950
-	 *
951
-	 * @param mixed $id
952
-	 * @param string $objectUri
953
-	 * @param int $calendarType
954
-	 * @return array|null
955
-	 */
956
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
957
-		$query = $this->db->getQueryBuilder();
958
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959
-			->from('calendarobjects')
960
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
961
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
962
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
963
-		$stmt = $query->execute();
964
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
965
-
966
-		if(!$row) {
967
-			return null;
968
-		}
969
-
970
-		return [
971
-			'id'            => $row['id'],
972
-			'uri'           => $row['uri'],
973
-			'lastmodified'  => $row['lastmodified'],
974
-			'etag'          => '"' . $row['etag'] . '"',
975
-			'calendarid'    => $row['calendarid'],
976
-			'size'          => (int)$row['size'],
977
-			'calendardata'  => $this->readBlob($row['calendardata']),
978
-			'component'     => strtolower($row['componenttype']),
979
-			'classification'=> (int)$row['classification']
980
-		];
981
-	}
982
-
983
-	/**
984
-	 * Returns a list of calendar objects.
985
-	 *
986
-	 * This method should work identical to getCalendarObject, but instead
987
-	 * return all the calendar objects in the list as an array.
988
-	 *
989
-	 * If the backend supports this, it may allow for some speed-ups.
990
-	 *
991
-	 * @param mixed $calendarId
992
-	 * @param string[] $uris
993
-	 * @param int $calendarType
994
-	 * @return array
995
-	 */
996
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
997
-		if (empty($uris)) {
998
-			return [];
999
-		}
1000
-
1001
-		$chunks = array_chunk($uris, 100);
1002
-		$objects = [];
1003
-
1004
-		$query = $this->db->getQueryBuilder();
1005
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1006
-			->from('calendarobjects')
1007
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1008
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1009
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1010
-
1011
-		foreach ($chunks as $uris) {
1012
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1013
-			$result = $query->execute();
1014
-
1015
-			while ($row = $result->fetch()) {
1016
-				$objects[] = [
1017
-					'id'           => $row['id'],
1018
-					'uri'          => $row['uri'],
1019
-					'lastmodified' => $row['lastmodified'],
1020
-					'etag'         => '"' . $row['etag'] . '"',
1021
-					'calendarid'   => $row['calendarid'],
1022
-					'size'         => (int)$row['size'],
1023
-					'calendardata' => $this->readBlob($row['calendardata']),
1024
-					'component'    => strtolower($row['componenttype']),
1025
-					'classification' => (int)$row['classification']
1026
-				];
1027
-			}
1028
-			$result->closeCursor();
1029
-		}
1030
-
1031
-		return $objects;
1032
-	}
1033
-
1034
-	/**
1035
-	 * Creates a new calendar object.
1036
-	 *
1037
-	 * The object uri is only the basename, or filename and not a full path.
1038
-	 *
1039
-	 * It is possible return an etag from this function, which will be used in
1040
-	 * the response to this PUT request. Note that the ETag must be surrounded
1041
-	 * by double-quotes.
1042
-	 *
1043
-	 * However, you should only really return this ETag if you don't mangle the
1044
-	 * calendar-data. If the result of a subsequent GET to this object is not
1045
-	 * the exact same as this request body, you should omit the ETag.
1046
-	 *
1047
-	 * @param mixed $calendarId
1048
-	 * @param string $objectUri
1049
-	 * @param string $calendarData
1050
-	 * @param int $calendarType
1051
-	 * @return string
1052
-	 */
1053
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1054
-		$extraData = $this->getDenormalizedData($calendarData);
1055
-
1056
-		$q = $this->db->getQueryBuilder();
1057
-		$q->select($q->func()->count('*'))
1058
-			->from('calendarobjects')
1059
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1060
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1061
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1062
-
1063
-		$result = $q->execute();
1064
-		$count = (int) $result->fetchColumn();
1065
-		$result->closeCursor();
1066
-
1067
-		if ($count !== 0) {
1068
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1069
-		}
1070
-
1071
-		$query = $this->db->getQueryBuilder();
1072
-		$query->insert('calendarobjects')
1073
-			->values([
1074
-				'calendarid' => $query->createNamedParameter($calendarId),
1075
-				'uri' => $query->createNamedParameter($objectUri),
1076
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1077
-				'lastmodified' => $query->createNamedParameter(time()),
1078
-				'etag' => $query->createNamedParameter($extraData['etag']),
1079
-				'size' => $query->createNamedParameter($extraData['size']),
1080
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1081
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1082
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1083
-				'classification' => $query->createNamedParameter($extraData['classification']),
1084
-				'uid' => $query->createNamedParameter($extraData['uid']),
1085
-				'calendartype' => $query->createNamedParameter($calendarType),
1086
-			])
1087
-			->execute();
1088
-
1089
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1090
-
1091
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1092
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1093
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1094
-				[
1095
-					'calendarId' => $calendarId,
1096
-					'calendarData' => $this->getCalendarById($calendarId),
1097
-					'shares' => $this->getShares($calendarId),
1098
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1099
-				]
1100
-			));
1101
-		} else {
1102
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1103
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1104
-				[
1105
-					'subscriptionId' => $calendarId,
1106
-					'calendarData' => $this->getCalendarById($calendarId),
1107
-					'shares' => $this->getShares($calendarId),
1108
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1109
-				]
1110
-			));
1111
-		}
1112
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1113
-
1114
-		return '"' . $extraData['etag'] . '"';
1115
-	}
1116
-
1117
-	/**
1118
-	 * Updates an existing calendarobject, based on it's uri.
1119
-	 *
1120
-	 * The object uri is only the basename, or filename and not a full path.
1121
-	 *
1122
-	 * It is possible return an etag from this function, which will be used in
1123
-	 * the response to this PUT request. Note that the ETag must be surrounded
1124
-	 * by double-quotes.
1125
-	 *
1126
-	 * However, you should only really return this ETag if you don't mangle the
1127
-	 * calendar-data. If the result of a subsequent GET to this object is not
1128
-	 * the exact same as this request body, you should omit the ETag.
1129
-	 *
1130
-	 * @param mixed $calendarId
1131
-	 * @param string $objectUri
1132
-	 * @param string $calendarData
1133
-	 * @param int $calendarType
1134
-	 * @return string
1135
-	 */
1136
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1137
-		$extraData = $this->getDenormalizedData($calendarData);
1138
-		$query = $this->db->getQueryBuilder();
1139
-		$query->update('calendarobjects')
1140
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1141
-				->set('lastmodified', $query->createNamedParameter(time()))
1142
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1143
-				->set('size', $query->createNamedParameter($extraData['size']))
1144
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1145
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1146
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1147
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1148
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1149
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1150
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1151
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1152
-			->execute();
1153
-
1154
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1155
-
1156
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1157
-		if (is_array($data)) {
1158
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1159
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1160
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1161
-					[
1162
-						'calendarId' => $calendarId,
1163
-						'calendarData' => $this->getCalendarById($calendarId),
1164
-						'shares' => $this->getShares($calendarId),
1165
-						'objectData' => $data,
1166
-					]
1167
-				));
1168
-			} else {
1169
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1170
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1171
-					[
1172
-						'subscriptionId' => $calendarId,
1173
-						'calendarData' => $this->getCalendarById($calendarId),
1174
-						'shares' => $this->getShares($calendarId),
1175
-						'objectData' => $data,
1176
-					]
1177
-				));
1178
-			}
1179
-		}
1180
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1181
-
1182
-		return '"' . $extraData['etag'] . '"';
1183
-	}
1184
-
1185
-	/**
1186
-	 * @param int $calendarObjectId
1187
-	 * @param int $classification
1188
-	 */
1189
-	public function setClassification($calendarObjectId, $classification) {
1190
-		if (!in_array($classification, [
1191
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1192
-		])) {
1193
-			throw new \InvalidArgumentException();
1194
-		}
1195
-		$query = $this->db->getQueryBuilder();
1196
-		$query->update('calendarobjects')
1197
-			->set('classification', $query->createNamedParameter($classification))
1198
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1199
-			->execute();
1200
-	}
1201
-
1202
-	/**
1203
-	 * Deletes an existing calendar object.
1204
-	 *
1205
-	 * The object uri is only the basename, or filename and not a full path.
1206
-	 *
1207
-	 * @param mixed $calendarId
1208
-	 * @param string $objectUri
1209
-	 * @param int $calendarType
1210
-	 * @return void
1211
-	 */
1212
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1213
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1214
-		if (is_array($data)) {
1215
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1216
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1217
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1218
-					[
1219
-						'calendarId' => $calendarId,
1220
-						'calendarData' => $this->getCalendarById($calendarId),
1221
-						'shares' => $this->getShares($calendarId),
1222
-						'objectData' => $data,
1223
-					]
1224
-				));
1225
-			} else {
1226
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1227
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1228
-					[
1229
-						'subscriptionId' => $calendarId,
1230
-						'calendarData' => $this->getCalendarById($calendarId),
1231
-						'shares' => $this->getShares($calendarId),
1232
-						'objectData' => $data,
1233
-					]
1234
-				));
1235
-			}
1236
-		}
1237
-
1238
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1239
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1240
-
1241
-		$this->purgeProperties($calendarId, $data['id'], $calendarType);
1242
-
1243
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1244
-	}
1245
-
1246
-	/**
1247
-	 * Performs a calendar-query on the contents of this calendar.
1248
-	 *
1249
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1250
-	 * calendar-query it is possible for a client to request a specific set of
1251
-	 * object, based on contents of iCalendar properties, date-ranges and
1252
-	 * iCalendar component types (VTODO, VEVENT).
1253
-	 *
1254
-	 * This method should just return a list of (relative) urls that match this
1255
-	 * query.
1256
-	 *
1257
-	 * The list of filters are specified as an array. The exact array is
1258
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1259
-	 *
1260
-	 * Note that it is extremely likely that getCalendarObject for every path
1261
-	 * returned from this method will be called almost immediately after. You
1262
-	 * may want to anticipate this to speed up these requests.
1263
-	 *
1264
-	 * This method provides a default implementation, which parses *all* the
1265
-	 * iCalendar objects in the specified calendar.
1266
-	 *
1267
-	 * This default may well be good enough for personal use, and calendars
1268
-	 * that aren't very large. But if you anticipate high usage, big calendars
1269
-	 * or high loads, you are strongly advised to optimize certain paths.
1270
-	 *
1271
-	 * The best way to do so is override this method and to optimize
1272
-	 * specifically for 'common filters'.
1273
-	 *
1274
-	 * Requests that are extremely common are:
1275
-	 *   * requests for just VEVENTS
1276
-	 *   * requests for just VTODO
1277
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1278
-	 *
1279
-	 * ..and combinations of these requests. It may not be worth it to try to
1280
-	 * handle every possible situation and just rely on the (relatively
1281
-	 * easy to use) CalendarQueryValidator to handle the rest.
1282
-	 *
1283
-	 * Note that especially time-range-filters may be difficult to parse. A
1284
-	 * time-range filter specified on a VEVENT must for instance also handle
1285
-	 * recurrence rules correctly.
1286
-	 * A good example of how to interprete all these filters can also simply
1287
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1288
-	 * as possible, so it gives you a good idea on what type of stuff you need
1289
-	 * to think of.
1290
-	 *
1291
-	 * @param mixed $id
1292
-	 * @param array $filters
1293
-	 * @param int $calendarType
1294
-	 * @return array
1295
-	 */
1296
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1297
-		$componentType = null;
1298
-		$requirePostFilter = true;
1299
-		$timeRange = null;
1300
-
1301
-		// if no filters were specified, we don't need to filter after a query
1302
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1303
-			$requirePostFilter = false;
1304
-		}
1305
-
1306
-		// Figuring out if there's a component filter
1307
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1308
-			$componentType = $filters['comp-filters'][0]['name'];
1309
-
1310
-			// Checking if we need post-filters
1311
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1312
-				$requirePostFilter = false;
1313
-			}
1314
-			// There was a time-range filter
1315
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1316
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1317
-
1318
-				// If start time OR the end time is not specified, we can do a
1319
-				// 100% accurate mysql query.
1320
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1321
-					$requirePostFilter = false;
1322
-				}
1323
-			}
1324
-
1325
-		}
1326
-		$columns = ['uri'];
1327
-		if ($requirePostFilter) {
1328
-			$columns = ['uri', 'calendardata'];
1329
-		}
1330
-		$query = $this->db->getQueryBuilder();
1331
-		$query->select($columns)
1332
-			->from('calendarobjects')
1333
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1334
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1335
-
1336
-		if ($componentType) {
1337
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1338
-		}
1339
-
1340
-		if ($timeRange && $timeRange['start']) {
1341
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1342
-		}
1343
-		if ($timeRange && $timeRange['end']) {
1344
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1345
-		}
1346
-
1347
-		$stmt = $query->execute();
1348
-
1349
-		$result = [];
1350
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1351
-			if ($requirePostFilter) {
1352
-				// validateFilterForObject will parse the calendar data
1353
-				// catch parsing errors
1354
-				try {
1355
-					$matches = $this->validateFilterForObject($row, $filters);
1356
-				} catch(ParseException $ex) {
1357
-					$this->logger->logException($ex, [
1358
-						'app' => 'dav',
1359
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1360
-					]);
1361
-					continue;
1362
-				} catch (InvalidDataException $ex) {
1363
-					$this->logger->logException($ex, [
1364
-						'app' => 'dav',
1365
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1366
-					]);
1367
-					continue;
1368
-				}
1369
-
1370
-				if (!$matches) {
1371
-					continue;
1372
-				}
1373
-			}
1374
-			$result[] = $row['uri'];
1375
-		}
1376
-
1377
-		return $result;
1378
-	}
1379
-
1380
-	/**
1381
-	 * custom Nextcloud search extension for CalDAV
1382
-	 *
1383
-	 * TODO - this should optionally cover cached calendar objects as well
1384
-	 *
1385
-	 * @param string $principalUri
1386
-	 * @param array $filters
1387
-	 * @param integer|null $limit
1388
-	 * @param integer|null $offset
1389
-	 * @return array
1390
-	 */
1391
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1392
-		$calendars = $this->getCalendarsForUser($principalUri);
1393
-		$ownCalendars = [];
1394
-		$sharedCalendars = [];
1395
-
1396
-		$uriMapper = [];
1397
-
1398
-		foreach($calendars as $calendar) {
1399
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1400
-				$ownCalendars[] = $calendar['id'];
1401
-			} else {
1402
-				$sharedCalendars[] = $calendar['id'];
1403
-			}
1404
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1405
-		}
1406
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1407
-			return [];
1408
-		}
1409
-
1410
-		$query = $this->db->getQueryBuilder();
1411
-		// Calendar id expressions
1412
-		$calendarExpressions = [];
1413
-		foreach($ownCalendars as $id) {
1414
-			$calendarExpressions[] = $query->expr()->andX(
1415
-				$query->expr()->eq('c.calendarid',
1416
-					$query->createNamedParameter($id)),
1417
-				$query->expr()->eq('c.calendartype',
1418
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1419
-		}
1420
-		foreach($sharedCalendars as $id) {
1421
-			$calendarExpressions[] = $query->expr()->andX(
1422
-				$query->expr()->eq('c.calendarid',
1423
-					$query->createNamedParameter($id)),
1424
-				$query->expr()->eq('c.classification',
1425
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1426
-				$query->expr()->eq('c.calendartype',
1427
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1428
-		}
1429
-
1430
-		if (count($calendarExpressions) === 1) {
1431
-			$calExpr = $calendarExpressions[0];
1432
-		} else {
1433
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1434
-		}
1435
-
1436
-		// Component expressions
1437
-		$compExpressions = [];
1438
-		foreach($filters['comps'] as $comp) {
1439
-			$compExpressions[] = $query->expr()
1440
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1441
-		}
1442
-
1443
-		if (count($compExpressions) === 1) {
1444
-			$compExpr = $compExpressions[0];
1445
-		} else {
1446
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1447
-		}
1448
-
1449
-		if (!isset($filters['props'])) {
1450
-			$filters['props'] = [];
1451
-		}
1452
-		if (!isset($filters['params'])) {
1453
-			$filters['params'] = [];
1454
-		}
1455
-
1456
-		$propParamExpressions = [];
1457
-		foreach($filters['props'] as $prop) {
1458
-			$propParamExpressions[] = $query->expr()->andX(
1459
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1460
-				$query->expr()->isNull('i.parameter')
1461
-			);
1462
-		}
1463
-		foreach($filters['params'] as $param) {
1464
-			$propParamExpressions[] = $query->expr()->andX(
1465
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1466
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1467
-			);
1468
-		}
1469
-
1470
-		if (count($propParamExpressions) === 1) {
1471
-			$propParamExpr = $propParamExpressions[0];
1472
-		} else {
1473
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1474
-		}
1475
-
1476
-		$query->select(['c.calendarid', 'c.uri'])
1477
-			->from($this->dbObjectPropertiesTable, 'i')
1478
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1479
-			->where($calExpr)
1480
-			->andWhere($compExpr)
1481
-			->andWhere($propParamExpr)
1482
-			->andWhere($query->expr()->iLike('i.value',
1483
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1484
-
1485
-		if ($offset) {
1486
-			$query->setFirstResult($offset);
1487
-		}
1488
-		if ($limit) {
1489
-			$query->setMaxResults($limit);
1490
-		}
1491
-
1492
-		$stmt = $query->execute();
1493
-
1494
-		$result = [];
1495
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1496
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1497
-			if (!in_array($path, $result)) {
1498
-				$result[] = $path;
1499
-			}
1500
-		}
1501
-
1502
-		return $result;
1503
-	}
1504
-
1505
-	/**
1506
-	 * used for Nextcloud's calendar API
1507
-	 *
1508
-	 * @param array $calendarInfo
1509
-	 * @param string $pattern
1510
-	 * @param array $searchProperties
1511
-	 * @param array $options
1512
-	 * @param integer|null $limit
1513
-	 * @param integer|null $offset
1514
-	 *
1515
-	 * @return array
1516
-	 */
1517
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1518
-						   array $options, $limit, $offset) {
1519
-		$outerQuery = $this->db->getQueryBuilder();
1520
-		$innerQuery = $this->db->getQueryBuilder();
1521
-
1522
-		$innerQuery->selectDistinct('op.objectid')
1523
-			->from($this->dbObjectPropertiesTable, 'op')
1524
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1525
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1526
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1527
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1528
-
1529
-		// only return public items for shared calendars for now
1530
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1531
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1532
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1533
-		}
1534
-
1535
-		$or = $innerQuery->expr()->orX();
1536
-		foreach($searchProperties as $searchProperty) {
1537
-			$or->add($innerQuery->expr()->eq('op.name',
1538
-				$outerQuery->createNamedParameter($searchProperty)));
1539
-		}
1540
-		$innerQuery->andWhere($or);
1541
-
1542
-		if ($pattern !== '') {
1543
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1544
-				$outerQuery->createNamedParameter('%' .
1545
-					$this->db->escapeLikeParameter($pattern) . '%')));
1546
-		}
1547
-
1548
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1549
-			->from('calendarobjects', 'c');
1550
-
1551
-		if (isset($options['timerange'])) {
1552
-			if (isset($options['timerange']['start'])) {
1553
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1554
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1555
-
1556
-			}
1557
-			if (isset($options['timerange']['end'])) {
1558
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1559
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1560
-			}
1561
-		}
1562
-
1563
-		if (isset($options['types'])) {
1564
-			$or = $outerQuery->expr()->orX();
1565
-			foreach($options['types'] as $type) {
1566
-				$or->add($outerQuery->expr()->eq('componenttype',
1567
-					$outerQuery->createNamedParameter($type)));
1568
-			}
1569
-			$outerQuery->andWhere($or);
1570
-		}
1571
-
1572
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1573
-			$outerQuery->createFunction($innerQuery->getSQL())));
1574
-
1575
-		if ($offset) {
1576
-			$outerQuery->setFirstResult($offset);
1577
-		}
1578
-		if ($limit) {
1579
-			$outerQuery->setMaxResults($limit);
1580
-		}
1581
-
1582
-		$result = $outerQuery->execute();
1583
-		$calendarObjects = $result->fetchAll();
1584
-
1585
-		return array_map(function($o) {
1586
-			$calendarData = Reader::read($o['calendardata']);
1587
-			$comps = $calendarData->getComponents();
1588
-			$objects = [];
1589
-			$timezones = [];
1590
-			foreach($comps as $comp) {
1591
-				if ($comp instanceof VTimeZone) {
1592
-					$timezones[] = $comp;
1593
-				} else {
1594
-					$objects[] = $comp;
1595
-				}
1596
-			}
1597
-
1598
-			return [
1599
-				'id' => $o['id'],
1600
-				'type' => $o['componenttype'],
1601
-				'uid' => $o['uid'],
1602
-				'uri' => $o['uri'],
1603
-				'objects' => array_map(function($c) {
1604
-					return $this->transformSearchData($c);
1605
-				}, $objects),
1606
-				'timezones' => array_map(function($c) {
1607
-					return $this->transformSearchData($c);
1608
-				}, $timezones),
1609
-			];
1610
-		}, $calendarObjects);
1611
-	}
1612
-
1613
-	/**
1614
-	 * @param Component $comp
1615
-	 * @return array
1616
-	 */
1617
-	private function transformSearchData(Component $comp) {
1618
-		$data = [];
1619
-		/** @var Component[] $subComponents */
1620
-		$subComponents = $comp->getComponents();
1621
-		/** @var Property[] $properties */
1622
-		$properties = array_filter($comp->children(), function($c) {
1623
-			return $c instanceof Property;
1624
-		});
1625
-		$validationRules = $comp->getValidationRules();
1626
-
1627
-		foreach($subComponents as $subComponent) {
1628
-			$name = $subComponent->name;
1629
-			if (!isset($data[$name])) {
1630
-				$data[$name] = [];
1631
-			}
1632
-			$data[$name][] = $this->transformSearchData($subComponent);
1633
-		}
1634
-
1635
-		foreach($properties as $property) {
1636
-			$name = $property->name;
1637
-			if (!isset($validationRules[$name])) {
1638
-				$validationRules[$name] = '*';
1639
-			}
1640
-
1641
-			$rule = $validationRules[$property->name];
1642
-			if ($rule === '+' || $rule === '*') { // multiple
1643
-				if (!isset($data[$name])) {
1644
-					$data[$name] = [];
1645
-				}
1646
-
1647
-				$data[$name][] = $this->transformSearchProperty($property);
1648
-			} else { // once
1649
-				$data[$name] = $this->transformSearchProperty($property);
1650
-			}
1651
-		}
1652
-
1653
-		return $data;
1654
-	}
1655
-
1656
-	/**
1657
-	 * @param Property $prop
1658
-	 * @return array
1659
-	 */
1660
-	private function transformSearchProperty(Property $prop) {
1661
-		// No need to check Date, as it extends DateTime
1662
-		if ($prop instanceof Property\ICalendar\DateTime) {
1663
-			$value = $prop->getDateTime();
1664
-		} else {
1665
-			$value = $prop->getValue();
1666
-		}
1667
-
1668
-		return [
1669
-			$value,
1670
-			$prop->parameters()
1671
-		];
1672
-	}
1673
-
1674
-	/**
1675
-	 * Searches through all of a users calendars and calendar objects to find
1676
-	 * an object with a specific UID.
1677
-	 *
1678
-	 * This method should return the path to this object, relative to the
1679
-	 * calendar home, so this path usually only contains two parts:
1680
-	 *
1681
-	 * calendarpath/objectpath.ics
1682
-	 *
1683
-	 * If the uid is not found, return null.
1684
-	 *
1685
-	 * This method should only consider * objects that the principal owns, so
1686
-	 * any calendars owned by other principals that also appear in this
1687
-	 * collection should be ignored.
1688
-	 *
1689
-	 * @param string $principalUri
1690
-	 * @param string $uid
1691
-	 * @return string|null
1692
-	 */
1693
-	function getCalendarObjectByUID($principalUri, $uid) {
1694
-
1695
-		$query = $this->db->getQueryBuilder();
1696
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1697
-			->from('calendarobjects', 'co')
1698
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1699
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1700
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1701
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1702
-
1703
-		$stmt = $query->execute();
1704
-
1705
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1706
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1707
-		}
1708
-
1709
-		return null;
1710
-	}
1711
-
1712
-	/**
1713
-	 * The getChanges method returns all the changes that have happened, since
1714
-	 * the specified syncToken in the specified calendar.
1715
-	 *
1716
-	 * This function should return an array, such as the following:
1717
-	 *
1718
-	 * [
1719
-	 *   'syncToken' => 'The current synctoken',
1720
-	 *   'added'   => [
1721
-	 *      'new.txt',
1722
-	 *   ],
1723
-	 *   'modified'   => [
1724
-	 *      'modified.txt',
1725
-	 *   ],
1726
-	 *   'deleted' => [
1727
-	 *      'foo.php.bak',
1728
-	 *      'old.txt'
1729
-	 *   ]
1730
-	 * );
1731
-	 *
1732
-	 * The returned syncToken property should reflect the *current* syncToken
1733
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1734
-	 * property This is * needed here too, to ensure the operation is atomic.
1735
-	 *
1736
-	 * If the $syncToken argument is specified as null, this is an initial
1737
-	 * sync, and all members should be reported.
1738
-	 *
1739
-	 * The modified property is an array of nodenames that have changed since
1740
-	 * the last token.
1741
-	 *
1742
-	 * The deleted property is an array with nodenames, that have been deleted
1743
-	 * from collection.
1744
-	 *
1745
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1746
-	 * 1, you only have to report changes that happened only directly in
1747
-	 * immediate descendants. If it's 2, it should also include changes from
1748
-	 * the nodes below the child collections. (grandchildren)
1749
-	 *
1750
-	 * The $limit argument allows a client to specify how many results should
1751
-	 * be returned at most. If the limit is not specified, it should be treated
1752
-	 * as infinite.
1753
-	 *
1754
-	 * If the limit (infinite or not) is higher than you're willing to return,
1755
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1756
-	 *
1757
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1758
-	 * return null.
1759
-	 *
1760
-	 * The limit is 'suggestive'. You are free to ignore it.
1761
-	 *
1762
-	 * @param string $calendarId
1763
-	 * @param string $syncToken
1764
-	 * @param int $syncLevel
1765
-	 * @param int $limit
1766
-	 * @param int $calendarType
1767
-	 * @return array
1768
-	 */
1769
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1770
-		// Current synctoken
1771
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1772
-		$stmt->execute([ $calendarId ]);
1773
-		$currentToken = $stmt->fetchColumn(0);
1774
-
1775
-		if (is_null($currentToken)) {
1776
-			return null;
1777
-		}
1778
-
1779
-		$result = [
1780
-			'syncToken' => $currentToken,
1781
-			'added'     => [],
1782
-			'modified'  => [],
1783
-			'deleted'   => [],
1784
-		];
1785
-
1786
-		if ($syncToken) {
1787
-
1788
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1789
-			if ($limit>0) {
1790
-				$query.= " LIMIT " . (int)$limit;
1791
-			}
1792
-
1793
-			// Fetching all changes
1794
-			$stmt = $this->db->prepare($query);
1795
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1796
-
1797
-			$changes = [];
1798
-
1799
-			// This loop ensures that any duplicates are overwritten, only the
1800
-			// last change on a node is relevant.
1801
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1802
-
1803
-				$changes[$row['uri']] = $row['operation'];
1804
-
1805
-			}
1806
-
1807
-			foreach($changes as $uri => $operation) {
1808
-
1809
-				switch($operation) {
1810
-					case 1 :
1811
-						$result['added'][] = $uri;
1812
-						break;
1813
-					case 2 :
1814
-						$result['modified'][] = $uri;
1815
-						break;
1816
-					case 3 :
1817
-						$result['deleted'][] = $uri;
1818
-						break;
1819
-				}
1820
-
1821
-			}
1822
-		} else {
1823
-			// No synctoken supplied, this is the initial sync.
1824
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1825
-			$stmt = $this->db->prepare($query);
1826
-			$stmt->execute([$calendarId, $calendarType]);
1827
-
1828
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1829
-		}
1830
-		return $result;
1831
-
1832
-	}
1833
-
1834
-	/**
1835
-	 * Returns a list of subscriptions for a principal.
1836
-	 *
1837
-	 * Every subscription is an array with the following keys:
1838
-	 *  * id, a unique id that will be used by other functions to modify the
1839
-	 *    subscription. This can be the same as the uri or a database key.
1840
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1841
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1842
-	 *    principalUri passed to this method.
1843
-	 *
1844
-	 * Furthermore, all the subscription info must be returned too:
1845
-	 *
1846
-	 * 1. {DAV:}displayname
1847
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1848
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1849
-	 *    should not be stripped).
1850
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1851
-	 *    should not be stripped).
1852
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1853
-	 *    attachments should not be stripped).
1854
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1855
-	 *     Sabre\DAV\Property\Href).
1856
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1857
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1858
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1859
-	 *    (should just be an instance of
1860
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1861
-	 *    default components).
1862
-	 *
1863
-	 * @param string $principalUri
1864
-	 * @return array
1865
-	 */
1866
-	function getSubscriptionsForUser($principalUri) {
1867
-		$fields = array_values($this->subscriptionPropertyMap);
1868
-		$fields[] = 'id';
1869
-		$fields[] = 'uri';
1870
-		$fields[] = 'source';
1871
-		$fields[] = 'principaluri';
1872
-		$fields[] = 'lastmodified';
1873
-		$fields[] = 'synctoken';
1874
-
1875
-		$query = $this->db->getQueryBuilder();
1876
-		$query->select($fields)
1877
-			->from('calendarsubscriptions')
1878
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1879
-			->orderBy('calendarorder', 'asc');
1880
-		$stmt =$query->execute();
1881
-
1882
-		$subscriptions = [];
1883
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1884
-
1885
-			$subscription = [
1886
-				'id'           => $row['id'],
1887
-				'uri'          => $row['uri'],
1888
-				'principaluri' => $row['principaluri'],
1889
-				'source'       => $row['source'],
1890
-				'lastmodified' => $row['lastmodified'],
1891
-
1892
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1893
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1894
-			];
1895
-
1896
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1897
-				if (!is_null($row[$dbName])) {
1898
-					$subscription[$xmlName] = $row[$dbName];
1899
-				}
1900
-			}
1901
-
1902
-			$subscriptions[] = $subscription;
1903
-
1904
-		}
1905
-
1906
-		return $subscriptions;
1907
-	}
1908
-
1909
-	/**
1910
-	 * Creates a new subscription for a principal.
1911
-	 *
1912
-	 * If the creation was a success, an id must be returned that can be used to reference
1913
-	 * this subscription in other methods, such as updateSubscription.
1914
-	 *
1915
-	 * @param string $principalUri
1916
-	 * @param string $uri
1917
-	 * @param array $properties
1918
-	 * @return mixed
1919
-	 */
1920
-	function createSubscription($principalUri, $uri, array $properties) {
1921
-
1922
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1923
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1924
-		}
1925
-
1926
-		$values = [
1927
-			'principaluri' => $principalUri,
1928
-			'uri'          => $uri,
1929
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1930
-			'lastmodified' => time(),
1931
-		];
1932
-
1933
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1934
-
1935
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1936
-			if (array_key_exists($xmlName, $properties)) {
1937
-					$values[$dbName] = $properties[$xmlName];
1938
-					if (in_array($dbName, $propertiesBoolean)) {
1939
-						$values[$dbName] = true;
1940
-				}
1941
-			}
1942
-		}
1943
-
1944
-		$valuesToInsert = array();
1945
-
1946
-		$query = $this->db->getQueryBuilder();
1947
-
1948
-		foreach (array_keys($values) as $name) {
1949
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1950
-		}
1951
-
1952
-		$query->insert('calendarsubscriptions')
1953
-			->values($valuesToInsert)
1954
-			->execute();
1955
-
1956
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1957
-
1958
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1959
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1960
-			[
1961
-				'subscriptionId' => $subscriptionId,
1962
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1963
-			]));
1964
-
1965
-		return $subscriptionId;
1966
-	}
1967
-
1968
-	/**
1969
-	 * Updates a subscription
1970
-	 *
1971
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1972
-	 * To do the actual updates, you must tell this object which properties
1973
-	 * you're going to process with the handle() method.
1974
-	 *
1975
-	 * Calling the handle method is like telling the PropPatch object "I
1976
-	 * promise I can handle updating this property".
1977
-	 *
1978
-	 * Read the PropPatch documentation for more info and examples.
1979
-	 *
1980
-	 * @param mixed $subscriptionId
1981
-	 * @param PropPatch $propPatch
1982
-	 * @return void
1983
-	 */
1984
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1985
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1986
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1987
-
1988
-		/**
1989
-		 * @suppress SqlInjectionChecker
1990
-		 */
1991
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1992
-
1993
-			$newValues = [];
1994
-
1995
-			foreach($mutations as $propertyName=>$propertyValue) {
1996
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1997
-					$newValues['source'] = $propertyValue->getHref();
1998
-				} else {
1999
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2000
-					$newValues[$fieldName] = $propertyValue;
2001
-				}
2002
-			}
2003
-
2004
-			$query = $this->db->getQueryBuilder();
2005
-			$query->update('calendarsubscriptions')
2006
-				->set('lastmodified', $query->createNamedParameter(time()));
2007
-			foreach($newValues as $fieldName=>$value) {
2008
-				$query->set($fieldName, $query->createNamedParameter($value));
2009
-			}
2010
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2011
-				->execute();
2012
-
2013
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2014
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2015
-				[
2016
-					'subscriptionId' => $subscriptionId,
2017
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2018
-					'propertyMutations' => $mutations,
2019
-				]));
2020
-
2021
-			return true;
2022
-
2023
-		});
2024
-	}
2025
-
2026
-	/**
2027
-	 * Deletes a subscription.
2028
-	 *
2029
-	 * @param mixed $subscriptionId
2030
-	 * @return void
2031
-	 */
2032
-	function deleteSubscription($subscriptionId) {
2033
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2034
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2035
-			[
2036
-				'subscriptionId' => $subscriptionId,
2037
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2038
-			]));
2039
-
2040
-		$query = $this->db->getQueryBuilder();
2041
-		$query->delete('calendarsubscriptions')
2042
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2043
-			->execute();
2044
-
2045
-		$query = $this->db->getQueryBuilder();
2046
-		$query->delete('calendarobjects')
2047
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2048
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2049
-			->execute();
2050
-
2051
-		$query->delete('calendarchanges')
2052
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2053
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2054
-			->execute();
2055
-
2056
-		$query->delete($this->dbObjectPropertiesTable)
2057
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2058
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2059
-			->execute();
2060
-	}
2061
-
2062
-	/**
2063
-	 * Returns a single scheduling object for the inbox collection.
2064
-	 *
2065
-	 * The returned array should contain the following elements:
2066
-	 *   * uri - A unique basename for the object. This will be used to
2067
-	 *           construct a full uri.
2068
-	 *   * calendardata - The iCalendar object
2069
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2070
-	 *                    timestamp, or a PHP DateTime object.
2071
-	 *   * etag - A unique token that must change if the object changed.
2072
-	 *   * size - The size of the object, in bytes.
2073
-	 *
2074
-	 * @param string $principalUri
2075
-	 * @param string $objectUri
2076
-	 * @return array
2077
-	 */
2078
-	function getSchedulingObject($principalUri, $objectUri) {
2079
-		$query = $this->db->getQueryBuilder();
2080
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2081
-			->from('schedulingobjects')
2082
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2083
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2084
-			->execute();
2085
-
2086
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2087
-
2088
-		if(!$row) {
2089
-			return null;
2090
-		}
2091
-
2092
-		return [
2093
-				'uri'          => $row['uri'],
2094
-				'calendardata' => $row['calendardata'],
2095
-				'lastmodified' => $row['lastmodified'],
2096
-				'etag'         => '"' . $row['etag'] . '"',
2097
-				'size'         => (int)$row['size'],
2098
-		];
2099
-	}
2100
-
2101
-	/**
2102
-	 * Returns all scheduling objects for the inbox collection.
2103
-	 *
2104
-	 * These objects should be returned as an array. Every item in the array
2105
-	 * should follow the same structure as returned from getSchedulingObject.
2106
-	 *
2107
-	 * The main difference is that 'calendardata' is optional.
2108
-	 *
2109
-	 * @param string $principalUri
2110
-	 * @return array
2111
-	 */
2112
-	function getSchedulingObjects($principalUri) {
2113
-		$query = $this->db->getQueryBuilder();
2114
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2115
-				->from('schedulingobjects')
2116
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2117
-				->execute();
2118
-
2119
-		$result = [];
2120
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2121
-			$result[] = [
2122
-					'calendardata' => $row['calendardata'],
2123
-					'uri'          => $row['uri'],
2124
-					'lastmodified' => $row['lastmodified'],
2125
-					'etag'         => '"' . $row['etag'] . '"',
2126
-					'size'         => (int)$row['size'],
2127
-			];
2128
-		}
2129
-
2130
-		return $result;
2131
-	}
2132
-
2133
-	/**
2134
-	 * Deletes a scheduling object from the inbox collection.
2135
-	 *
2136
-	 * @param string $principalUri
2137
-	 * @param string $objectUri
2138
-	 * @return void
2139
-	 */
2140
-	function deleteSchedulingObject($principalUri, $objectUri) {
2141
-		$query = $this->db->getQueryBuilder();
2142
-		$query->delete('schedulingobjects')
2143
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2144
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2145
-				->execute();
2146
-	}
2147
-
2148
-	/**
2149
-	 * Creates a new scheduling object. This should land in a users' inbox.
2150
-	 *
2151
-	 * @param string $principalUri
2152
-	 * @param string $objectUri
2153
-	 * @param string $objectData
2154
-	 * @return void
2155
-	 */
2156
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2157
-		$query = $this->db->getQueryBuilder();
2158
-		$query->insert('schedulingobjects')
2159
-			->values([
2160
-				'principaluri' => $query->createNamedParameter($principalUri),
2161
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2162
-				'uri' => $query->createNamedParameter($objectUri),
2163
-				'lastmodified' => $query->createNamedParameter(time()),
2164
-				'etag' => $query->createNamedParameter(md5($objectData)),
2165
-				'size' => $query->createNamedParameter(strlen($objectData))
2166
-			])
2167
-			->execute();
2168
-	}
2169
-
2170
-	/**
2171
-	 * Adds a change record to the calendarchanges table.
2172
-	 *
2173
-	 * @param mixed $calendarId
2174
-	 * @param string $objectUri
2175
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2176
-	 * @param int $calendarType
2177
-	 * @return void
2178
-	 */
2179
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2180
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2181
-
2182
-		$query = $this->db->getQueryBuilder();
2183
-		$query->select('synctoken')
2184
-			->from($table)
2185
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2186
-		$syncToken = (int)$query->execute()->fetchColumn();
2187
-
2188
-		$query = $this->db->getQueryBuilder();
2189
-		$query->insert('calendarchanges')
2190
-			->values([
2191
-				'uri' => $query->createNamedParameter($objectUri),
2192
-				'synctoken' => $query->createNamedParameter($syncToken),
2193
-				'calendarid' => $query->createNamedParameter($calendarId),
2194
-				'operation' => $query->createNamedParameter($operation),
2195
-				'calendartype' => $query->createNamedParameter($calendarType),
2196
-			])
2197
-			->execute();
2198
-
2199
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2200
-		$stmt->execute([
2201
-			$calendarId
2202
-		]);
2203
-
2204
-	}
2205
-
2206
-	/**
2207
-	 * Parses some information from calendar objects, used for optimized
2208
-	 * calendar-queries.
2209
-	 *
2210
-	 * Returns an array with the following keys:
2211
-	 *   * etag - An md5 checksum of the object without the quotes.
2212
-	 *   * size - Size of the object in bytes
2213
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2214
-	 *   * firstOccurence
2215
-	 *   * lastOccurence
2216
-	 *   * uid - value of the UID property
2217
-	 *
2218
-	 * @param string $calendarData
2219
-	 * @return array
2220
-	 */
2221
-	public function getDenormalizedData($calendarData) {
2222
-
2223
-		$vObject = Reader::read($calendarData);
2224
-		$componentType = null;
2225
-		$component = null;
2226
-		$firstOccurrence = null;
2227
-		$lastOccurrence = null;
2228
-		$uid = null;
2229
-		$classification = self::CLASSIFICATION_PUBLIC;
2230
-		foreach($vObject->getComponents() as $component) {
2231
-			if ($component->name!=='VTIMEZONE') {
2232
-				$componentType = $component->name;
2233
-				$uid = (string)$component->UID;
2234
-				break;
2235
-			}
2236
-		}
2237
-		if (!$componentType) {
2238
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2239
-		}
2240
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2241
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2242
-			// Finding the last occurrence is a bit harder
2243
-			if (!isset($component->RRULE)) {
2244
-				if (isset($component->DTEND)) {
2245
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2246
-				} elseif (isset($component->DURATION)) {
2247
-					$endDate = clone $component->DTSTART->getDateTime();
2248
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2249
-					$lastOccurrence = $endDate->getTimeStamp();
2250
-				} elseif (!$component->DTSTART->hasTime()) {
2251
-					$endDate = clone $component->DTSTART->getDateTime();
2252
-					$endDate->modify('+1 day');
2253
-					$lastOccurrence = $endDate->getTimeStamp();
2254
-				} else {
2255
-					$lastOccurrence = $firstOccurrence;
2256
-				}
2257
-			} else {
2258
-				$it = new EventIterator($vObject, (string)$component->UID);
2259
-				$maxDate = new \DateTime(self::MAX_DATE);
2260
-				if ($it->isInfinite()) {
2261
-					$lastOccurrence = $maxDate->getTimestamp();
2262
-				} else {
2263
-					$end = $it->getDtEnd();
2264
-					while($it->valid() && $end < $maxDate) {
2265
-						$end = $it->getDtEnd();
2266
-						$it->next();
2267
-
2268
-					}
2269
-					$lastOccurrence = $end->getTimestamp();
2270
-				}
2271
-
2272
-			}
2273
-		}
2274
-
2275
-		if ($component->CLASS) {
2276
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2277
-			switch ($component->CLASS->getValue()) {
2278
-				case 'PUBLIC':
2279
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2280
-					break;
2281
-				case 'CONFIDENTIAL':
2282
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2283
-					break;
2284
-			}
2285
-		}
2286
-		return [
2287
-			'etag' => md5($calendarData),
2288
-			'size' => strlen($calendarData),
2289
-			'componentType' => $componentType,
2290
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2291
-			'lastOccurence'  => $lastOccurrence,
2292
-			'uid' => $uid,
2293
-			'classification' => $classification
2294
-		];
2295
-
2296
-	}
2297
-
2298
-	/**
2299
-	 * @param $cardData
2300
-	 * @return bool|string
2301
-	 */
2302
-	private function readBlob($cardData) {
2303
-		if (is_resource($cardData)) {
2304
-			return stream_get_contents($cardData);
2305
-		}
2306
-
2307
-		return $cardData;
2308
-	}
2309
-
2310
-	/**
2311
-	 * @param IShareable $shareable
2312
-	 * @param array $add
2313
-	 * @param array $remove
2314
-	 */
2315
-	public function updateShares($shareable, $add, $remove) {
2316
-		$calendarId = $shareable->getResourceId();
2317
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2318
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2319
-			[
2320
-				'calendarId' => $calendarId,
2321
-				'calendarData' => $this->getCalendarById($calendarId),
2322
-				'shares' => $this->getShares($calendarId),
2323
-				'add' => $add,
2324
-				'remove' => $remove,
2325
-			]));
2326
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2327
-	}
2328
-
2329
-	/**
2330
-	 * @param int $resourceId
2331
-	 * @param int $calendarType
2332
-	 * @return array
2333
-	 */
2334
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2335
-		return $this->calendarSharingBackend->getShares($resourceId);
2336
-	}
2337
-
2338
-	/**
2339
-	 * @param boolean $value
2340
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2341
-	 * @return string|null
2342
-	 */
2343
-	public function setPublishStatus($value, $calendar) {
2344
-
2345
-		$calendarId = $calendar->getResourceId();
2346
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2347
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2348
-			[
2349
-				'calendarId' => $calendarId,
2350
-				'calendarData' => $this->getCalendarById($calendarId),
2351
-				'public' => $value,
2352
-			]));
2353
-
2354
-		$query = $this->db->getQueryBuilder();
2355
-		if ($value) {
2356
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2357
-			$query->insert('dav_shares')
2358
-				->values([
2359
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2360
-					'type' => $query->createNamedParameter('calendar'),
2361
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2362
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2363
-					'publicuri' => $query->createNamedParameter($publicUri)
2364
-				]);
2365
-			$query->execute();
2366
-			return $publicUri;
2367
-		}
2368
-		$query->delete('dav_shares')
2369
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2370
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2371
-		$query->execute();
2372
-		return null;
2373
-	}
2374
-
2375
-	/**
2376
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2377
-	 * @return mixed
2378
-	 */
2379
-	public function getPublishStatus($calendar) {
2380
-		$query = $this->db->getQueryBuilder();
2381
-		$result = $query->select('publicuri')
2382
-			->from('dav_shares')
2383
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2384
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2385
-			->execute();
2386
-
2387
-		$row = $result->fetch();
2388
-		$result->closeCursor();
2389
-		return $row ? reset($row) : false;
2390
-	}
2391
-
2392
-	/**
2393
-	 * @param int $resourceId
2394
-	 * @param array $acl
2395
-	 * @return array
2396
-	 */
2397
-	public function applyShareAcl($resourceId, $acl) {
2398
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2399
-	}
2400
-
2401
-
2402
-
2403
-	/**
2404
-	 * update properties table
2405
-	 *
2406
-	 * @param int $calendarId
2407
-	 * @param string $objectUri
2408
-	 * @param string $calendarData
2409
-	 * @param int $calendarType
2410
-	 */
2411
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2412
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2413
-
2414
-		try {
2415
-			$vCalendar = $this->readCalendarData($calendarData);
2416
-		} catch (\Exception $ex) {
2417
-			return;
2418
-		}
2419
-
2420
-		$this->purgeProperties($calendarId, $objectId);
2421
-
2422
-		$query = $this->db->getQueryBuilder();
2423
-		$query->insert($this->dbObjectPropertiesTable)
2424
-			->values(
2425
-				[
2426
-					'calendarid' => $query->createNamedParameter($calendarId),
2427
-					'calendartype' => $query->createNamedParameter($calendarType),
2428
-					'objectid' => $query->createNamedParameter($objectId),
2429
-					'name' => $query->createParameter('name'),
2430
-					'parameter' => $query->createParameter('parameter'),
2431
-					'value' => $query->createParameter('value'),
2432
-				]
2433
-			);
2434
-
2435
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2436
-		foreach ($vCalendar->getComponents() as $component) {
2437
-			if (!in_array($component->name, $indexComponents)) {
2438
-				continue;
2439
-			}
2440
-
2441
-			foreach ($component->children() as $property) {
2442
-				if (in_array($property->name, self::$indexProperties)) {
2443
-					$value = $property->getValue();
2444
-					// is this a shitty db?
2445
-					if (!$this->db->supports4ByteText()) {
2446
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2447
-					}
2448
-					$value = mb_substr($value, 0, 254);
2449
-
2450
-					$query->setParameter('name', $property->name);
2451
-					$query->setParameter('parameter', null);
2452
-					$query->setParameter('value', $value);
2453
-					$query->execute();
2454
-				}
2455
-
2456
-				if (array_key_exists($property->name, self::$indexParameters)) {
2457
-					$parameters = $property->parameters();
2458
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2459
-
2460
-					foreach ($parameters as $key => $value) {
2461
-						if (in_array($key, $indexedParametersForProperty)) {
2462
-							// is this a shitty db?
2463
-							if ($this->db->supports4ByteText()) {
2464
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2465
-							}
2466
-							$value = mb_substr($value, 0, 254);
2467
-
2468
-							$query->setParameter('name', $property->name);
2469
-							$query->setParameter('parameter', substr($key, 0, 254));
2470
-							$query->setParameter('value', substr($value, 0, 254));
2471
-							$query->execute();
2472
-						}
2473
-					}
2474
-				}
2475
-			}
2476
-		}
2477
-	}
2478
-
2479
-	/**
2480
-	 * deletes all birthday calendars
2481
-	 */
2482
-	public function deleteAllBirthdayCalendars() {
2483
-		$query = $this->db->getQueryBuilder();
2484
-		$result = $query->select(['id'])->from('calendars')
2485
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2486
-			->execute();
2487
-
2488
-		$ids = $result->fetchAll();
2489
-		foreach($ids as $id) {
2490
-			$this->deleteCalendar($id['id']);
2491
-		}
2492
-	}
2493
-
2494
-	/**
2495
-	 * @param $subscriptionId
2496
-	 */
2497
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2498
-		$query = $this->db->getQueryBuilder();
2499
-		$query->select('uri')
2500
-			->from('calendarobjects')
2501
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2502
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2503
-		$stmt = $query->execute();
2504
-
2505
-		$uris = [];
2506
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2507
-			$uris[] = $row['uri'];
2508
-		}
2509
-		$stmt->closeCursor();
2510
-
2511
-		$query = $this->db->getQueryBuilder();
2512
-		$query->delete('calendarobjects')
2513
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2514
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2515
-			->execute();
2516
-
2517
-		$query->delete('calendarchanges')
2518
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2519
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2520
-			->execute();
2521
-
2522
-		$query->delete($this->dbObjectPropertiesTable)
2523
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2524
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2525
-			->execute();
2526
-
2527
-		foreach($uris as $uri) {
2528
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2529
-		}
2530
-	}
2531
-
2532
-	/**
2533
-	 * Move a calendar from one user to another
2534
-	 *
2535
-	 * @param string $uriName
2536
-	 * @param string $uriOrigin
2537
-	 * @param string $uriDestination
2538
-	 */
2539
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2540
-	{
2541
-		$query = $this->db->getQueryBuilder();
2542
-		$query->update('calendars')
2543
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2544
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2545
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2546
-			->execute();
2547
-	}
2548
-
2549
-	/**
2550
-	 * read VCalendar data into a VCalendar object
2551
-	 *
2552
-	 * @param string $objectData
2553
-	 * @return VCalendar
2554
-	 */
2555
-	protected function readCalendarData($objectData) {
2556
-		return Reader::read($objectData);
2557
-	}
2558
-
2559
-	/**
2560
-	 * delete all properties from a given calendar object
2561
-	 *
2562
-	 * @param int $calendarId
2563
-	 * @param int $objectId
2564
-	 */
2565
-	protected function purgeProperties($calendarId, $objectId) {
2566
-		$query = $this->db->getQueryBuilder();
2567
-		$query->delete($this->dbObjectPropertiesTable)
2568
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2569
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2570
-		$query->execute();
2571
-	}
2572
-
2573
-	/**
2574
-	 * get ID from a given calendar object
2575
-	 *
2576
-	 * @param int $calendarId
2577
-	 * @param string $uri
2578
-	 * @param int $calendarType
2579
-	 * @return int
2580
-	 */
2581
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2582
-		$query = $this->db->getQueryBuilder();
2583
-		$query->select('id')
2584
-			->from('calendarobjects')
2585
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2586
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2587
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2588
-
2589
-		$result = $query->execute();
2590
-		$objectIds = $result->fetch();
2591
-		$result->closeCursor();
2592
-
2593
-		if (!isset($objectIds['id'])) {
2594
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2595
-		}
2596
-
2597
-		return (int)$objectIds['id'];
2598
-	}
2599
-
2600
-	/**
2601
-	 * return legacy endpoint principal name to new principal name
2602
-	 *
2603
-	 * @param $principalUri
2604
-	 * @param $toV2
2605
-	 * @return string
2606
-	 */
2607
-	private function convertPrincipal($principalUri, $toV2) {
2608
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2609
-			list(, $name) = Uri\split($principalUri);
2610
-			if ($toV2 === true) {
2611
-				return "principals/users/$name";
2612
-			}
2613
-			return "principals/$name";
2614
-		}
2615
-		return $principalUri;
2616
-	}
2617
-
2618
-	/**
2619
-	 * adds information about an owner to the calendar data
2620
-	 *
2621
-	 * @param $calendarInfo
2622
-	 */
2623
-	private function addOwnerPrincipal(&$calendarInfo) {
2624
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2625
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2626
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2627
-			$uri = $calendarInfo[$ownerPrincipalKey];
2628
-		} else {
2629
-			$uri = $calendarInfo['principaluri'];
2630
-		}
2631
-
2632
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2633
-		if (isset($principalInformation['{DAV:}displayname'])) {
2634
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2635
-		}
2636
-	}
449
+    /**
450
+     * @return array
451
+     */
452
+    public function getPublicCalendars() {
453
+        $fields = array_values($this->propertyMap);
454
+        $fields[] = 'a.id';
455
+        $fields[] = 'a.uri';
456
+        $fields[] = 'a.synctoken';
457
+        $fields[] = 'a.components';
458
+        $fields[] = 'a.principaluri';
459
+        $fields[] = 'a.transparent';
460
+        $fields[] = 's.access';
461
+        $fields[] = 's.publicuri';
462
+        $calendars = [];
463
+        $query = $this->db->getQueryBuilder();
464
+        $result = $query->select($fields)
465
+            ->from('dav_shares', 's')
466
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
+            ->execute();
470
+
471
+        while($row = $result->fetch()) {
472
+            list(, $name) = Uri\split($row['principaluri']);
473
+            $row['displayname'] = $row['displayname'] . "($name)";
474
+            $components = [];
475
+            if ($row['components']) {
476
+                $components = explode(',',$row['components']);
477
+            }
478
+            $calendar = [
479
+                'id' => $row['id'],
480
+                'uri' => $row['publicuri'],
481
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
+            ];
490
+
491
+            foreach($this->propertyMap as $xmlName=>$dbName) {
492
+                $calendar[$xmlName] = $row[$dbName];
493
+            }
494
+
495
+            $this->addOwnerPrincipal($calendar);
496
+
497
+            if (!isset($calendars[$calendar['id']])) {
498
+                $calendars[$calendar['id']] = $calendar;
499
+            }
500
+        }
501
+        $result->closeCursor();
502
+
503
+        return array_values($calendars);
504
+    }
505
+
506
+    /**
507
+     * @param string $uri
508
+     * @return array
509
+     * @throws NotFound
510
+     */
511
+    public function getPublicCalendar($uri) {
512
+        $fields = array_values($this->propertyMap);
513
+        $fields[] = 'a.id';
514
+        $fields[] = 'a.uri';
515
+        $fields[] = 'a.synctoken';
516
+        $fields[] = 'a.components';
517
+        $fields[] = 'a.principaluri';
518
+        $fields[] = 'a.transparent';
519
+        $fields[] = 's.access';
520
+        $fields[] = 's.publicuri';
521
+        $query = $this->db->getQueryBuilder();
522
+        $result = $query->select($fields)
523
+            ->from('dav_shares', 's')
524
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
+            ->execute();
529
+
530
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
531
+
532
+        $result->closeCursor();
533
+
534
+        if ($row === false) {
535
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
+        }
537
+
538
+        list(, $name) = Uri\split($row['principaluri']);
539
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
+        $components = [];
541
+        if ($row['components']) {
542
+            $components = explode(',',$row['components']);
543
+        }
544
+        $calendar = [
545
+            'id' => $row['id'],
546
+            'uri' => $row['publicuri'],
547
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
+        ];
556
+
557
+        foreach($this->propertyMap as $xmlName=>$dbName) {
558
+            $calendar[$xmlName] = $row[$dbName];
559
+        }
560
+
561
+        $this->addOwnerPrincipal($calendar);
562
+
563
+        return $calendar;
564
+
565
+    }
566
+
567
+    /**
568
+     * @param string $principal
569
+     * @param string $uri
570
+     * @return array|null
571
+     */
572
+    public function getCalendarByUri($principal, $uri) {
573
+        $fields = array_values($this->propertyMap);
574
+        $fields[] = 'id';
575
+        $fields[] = 'uri';
576
+        $fields[] = 'synctoken';
577
+        $fields[] = 'components';
578
+        $fields[] = 'principaluri';
579
+        $fields[] = 'transparent';
580
+
581
+        // Making fields a comma-delimited list
582
+        $query = $this->db->getQueryBuilder();
583
+        $query->select($fields)->from('calendars')
584
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
+            ->setMaxResults(1);
587
+        $stmt = $query->execute();
588
+
589
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
+        $stmt->closeCursor();
591
+        if ($row === false) {
592
+            return null;
593
+        }
594
+
595
+        $components = [];
596
+        if ($row['components']) {
597
+            $components = explode(',',$row['components']);
598
+        }
599
+
600
+        $calendar = [
601
+            'id' => $row['id'],
602
+            'uri' => $row['uri'],
603
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
+        ];
609
+
610
+        foreach($this->propertyMap as $xmlName=>$dbName) {
611
+            $calendar[$xmlName] = $row[$dbName];
612
+        }
613
+
614
+        $this->addOwnerPrincipal($calendar);
615
+
616
+        return $calendar;
617
+    }
618
+
619
+    /**
620
+     * @param $calendarId
621
+     * @return array|null
622
+     */
623
+    public function getCalendarById($calendarId) {
624
+        $fields = array_values($this->propertyMap);
625
+        $fields[] = 'id';
626
+        $fields[] = 'uri';
627
+        $fields[] = 'synctoken';
628
+        $fields[] = 'components';
629
+        $fields[] = 'principaluri';
630
+        $fields[] = 'transparent';
631
+
632
+        // Making fields a comma-delimited list
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->select($fields)->from('calendars')
635
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
+            ->setMaxResults(1);
637
+        $stmt = $query->execute();
638
+
639
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
+        $stmt->closeCursor();
641
+        if ($row === false) {
642
+            return null;
643
+        }
644
+
645
+        $components = [];
646
+        if ($row['components']) {
647
+            $components = explode(',',$row['components']);
648
+        }
649
+
650
+        $calendar = [
651
+            'id' => $row['id'],
652
+            'uri' => $row['uri'],
653
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
+        ];
659
+
660
+        foreach($this->propertyMap as $xmlName=>$dbName) {
661
+            $calendar[$xmlName] = $row[$dbName];
662
+        }
663
+
664
+        $this->addOwnerPrincipal($calendar);
665
+
666
+        return $calendar;
667
+    }
668
+
669
+    /**
670
+     * @param $subscriptionId
671
+     */
672
+    public function getSubscriptionById($subscriptionId) {
673
+        $fields = array_values($this->subscriptionPropertyMap);
674
+        $fields[] = 'id';
675
+        $fields[] = 'uri';
676
+        $fields[] = 'source';
677
+        $fields[] = 'synctoken';
678
+        $fields[] = 'principaluri';
679
+        $fields[] = 'lastmodified';
680
+
681
+        $query = $this->db->getQueryBuilder();
682
+        $query->select($fields)
683
+            ->from('calendarsubscriptions')
684
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
+            ->orderBy('calendarorder', 'asc');
686
+        $stmt =$query->execute();
687
+
688
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
+        $stmt->closeCursor();
690
+        if ($row === false) {
691
+            return null;
692
+        }
693
+
694
+        $subscription = [
695
+            'id'           => $row['id'],
696
+            'uri'          => $row['uri'],
697
+            'principaluri' => $row['principaluri'],
698
+            'source'       => $row['source'],
699
+            'lastmodified' => $row['lastmodified'],
700
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
+        ];
703
+
704
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
+            if (!is_null($row[$dbName])) {
706
+                $subscription[$xmlName] = $row[$dbName];
707
+            }
708
+        }
709
+
710
+        return $subscription;
711
+    }
712
+
713
+    /**
714
+     * Creates a new calendar for a principal.
715
+     *
716
+     * If the creation was a success, an id must be returned that can be used to reference
717
+     * this calendar in other methods, such as updateCalendar.
718
+     *
719
+     * @param string $principalUri
720
+     * @param string $calendarUri
721
+     * @param array $properties
722
+     * @return int
723
+     * @suppress SqlInjectionChecker
724
+     */
725
+    function createCalendar($principalUri, $calendarUri, array $properties) {
726
+        $values = [
727
+            'principaluri' => $this->convertPrincipal($principalUri, true),
728
+            'uri'          => $calendarUri,
729
+            'synctoken'    => 1,
730
+            'transparent'  => 0,
731
+            'components'   => 'VEVENT,VTODO',
732
+            'displayname'  => $calendarUri
733
+        ];
734
+
735
+        // Default value
736
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
+        if (isset($properties[$sccs])) {
738
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
+            }
741
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
742
+        } else if (isset($properties['components'])) {
743
+            // Allow to provide components internally without having
744
+            // to create a SupportedCalendarComponentSet object
745
+            $values['components'] = $properties['components'];
746
+        }
747
+
748
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
+        if (isset($properties[$transp])) {
750
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
+        }
752
+
753
+        foreach($this->propertyMap as $xmlName=>$dbName) {
754
+            if (isset($properties[$xmlName])) {
755
+                $values[$dbName] = $properties[$xmlName];
756
+            }
757
+        }
758
+
759
+        $query = $this->db->getQueryBuilder();
760
+        $query->insert('calendars');
761
+        foreach($values as $column => $value) {
762
+            $query->setValue($column, $query->createNamedParameter($value));
763
+        }
764
+        $query->execute();
765
+        $calendarId = $query->getLastInsertId();
766
+
767
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
+            [
770
+                'calendarId' => $calendarId,
771
+                'calendarData' => $this->getCalendarById($calendarId),
772
+        ]));
773
+
774
+        return $calendarId;
775
+    }
776
+
777
+    /**
778
+     * Updates properties for a calendar.
779
+     *
780
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
+     * To do the actual updates, you must tell this object which properties
782
+     * you're going to process with the handle() method.
783
+     *
784
+     * Calling the handle method is like telling the PropPatch object "I
785
+     * promise I can handle updating this property".
786
+     *
787
+     * Read the PropPatch documentation for more info and examples.
788
+     *
789
+     * @param mixed $calendarId
790
+     * @param PropPatch $propPatch
791
+     * @return void
792
+     */
793
+    function updateCalendar($calendarId, PropPatch $propPatch) {
794
+        $supportedProperties = array_keys($this->propertyMap);
795
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
+
797
+        /**
798
+         * @suppress SqlInjectionChecker
799
+         */
800
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
801
+            $newValues = [];
802
+            foreach ($mutations as $propertyName => $propertyValue) {
803
+
804
+                switch ($propertyName) {
805
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
806
+                        $fieldName = 'transparent';
807
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808
+                        break;
809
+                    default :
810
+                        $fieldName = $this->propertyMap[$propertyName];
811
+                        $newValues[$fieldName] = $propertyValue;
812
+                        break;
813
+                }
814
+
815
+            }
816
+            $query = $this->db->getQueryBuilder();
817
+            $query->update('calendars');
818
+            foreach ($newValues as $fieldName => $value) {
819
+                $query->set($fieldName, $query->createNamedParameter($value));
820
+            }
821
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
822
+            $query->execute();
823
+
824
+            $this->addChange($calendarId, "", 2);
825
+
826
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
827
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
828
+                [
829
+                    'calendarId' => $calendarId,
830
+                    'calendarData' => $this->getCalendarById($calendarId),
831
+                    'shares' => $this->getShares($calendarId),
832
+                    'propertyMutations' => $mutations,
833
+            ]));
834
+
835
+            return true;
836
+        });
837
+    }
838
+
839
+    /**
840
+     * Delete a calendar and all it's objects
841
+     *
842
+     * @param mixed $calendarId
843
+     * @return void
844
+     */
845
+    function deleteCalendar($calendarId) {
846
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
847
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
848
+            [
849
+                'calendarId' => $calendarId,
850
+                'calendarData' => $this->getCalendarById($calendarId),
851
+                'shares' => $this->getShares($calendarId),
852
+        ]));
853
+
854
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
855
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
856
+
857
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
858
+        $stmt->execute([$calendarId]);
859
+
860
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
861
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
862
+
863
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
864
+
865
+        $query = $this->db->getQueryBuilder();
866
+        $query->delete($this->dbObjectPropertiesTable)
867
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
869
+            ->execute();
870
+    }
871
+
872
+    /**
873
+     * Delete all of an user's shares
874
+     *
875
+     * @param string $principaluri
876
+     * @return void
877
+     */
878
+    function deleteAllSharesByUser($principaluri) {
879
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
880
+    }
881
+
882
+    /**
883
+     * Returns all calendar objects within a calendar.
884
+     *
885
+     * Every item contains an array with the following keys:
886
+     *   * calendardata - The iCalendar-compatible calendar data
887
+     *   * uri - a unique key which will be used to construct the uri. This can
888
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
889
+     *     good idea. This is only the basename, or filename, not the full
890
+     *     path.
891
+     *   * lastmodified - a timestamp of the last modification time
892
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
893
+     *   '"abcdef"')
894
+     *   * size - The size of the calendar objects, in bytes.
895
+     *   * component - optional, a string containing the type of object, such
896
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
897
+     *     the Content-Type header.
898
+     *
899
+     * Note that the etag is optional, but it's highly encouraged to return for
900
+     * speed reasons.
901
+     *
902
+     * The calendardata is also optional. If it's not returned
903
+     * 'getCalendarObject' will be called later, which *is* expected to return
904
+     * calendardata.
905
+     *
906
+     * If neither etag or size are specified, the calendardata will be
907
+     * used/fetched to determine these numbers. If both are specified the
908
+     * amount of times this is needed is reduced by a great degree.
909
+     *
910
+     * @param mixed $id
911
+     * @param int $calendarType
912
+     * @return array
913
+     */
914
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
915
+        $query = $this->db->getQueryBuilder();
916
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917
+            ->from('calendarobjects')
918
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
919
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
920
+        $stmt = $query->execute();
921
+
922
+        $result = [];
923
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924
+            $result[] = [
925
+                'id'           => $row['id'],
926
+                'uri'          => $row['uri'],
927
+                'lastmodified' => $row['lastmodified'],
928
+                'etag'         => '"' . $row['etag'] . '"',
929
+                'calendarid'   => $row['calendarid'],
930
+                'size'         => (int)$row['size'],
931
+                'component'    => strtolower($row['componenttype']),
932
+                'classification'=> (int)$row['classification']
933
+            ];
934
+        }
935
+
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * Returns information from a single calendar object, based on it's object
941
+     * uri.
942
+     *
943
+     * The object uri is only the basename, or filename and not a full path.
944
+     *
945
+     * The returned array must have the same keys as getCalendarObjects. The
946
+     * 'calendardata' object is required here though, while it's not required
947
+     * for getCalendarObjects.
948
+     *
949
+     * This method must return null if the object did not exist.
950
+     *
951
+     * @param mixed $id
952
+     * @param string $objectUri
953
+     * @param int $calendarType
954
+     * @return array|null
955
+     */
956
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
957
+        $query = $this->db->getQueryBuilder();
958
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959
+            ->from('calendarobjects')
960
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
961
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
962
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
963
+        $stmt = $query->execute();
964
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
965
+
966
+        if(!$row) {
967
+            return null;
968
+        }
969
+
970
+        return [
971
+            'id'            => $row['id'],
972
+            'uri'           => $row['uri'],
973
+            'lastmodified'  => $row['lastmodified'],
974
+            'etag'          => '"' . $row['etag'] . '"',
975
+            'calendarid'    => $row['calendarid'],
976
+            'size'          => (int)$row['size'],
977
+            'calendardata'  => $this->readBlob($row['calendardata']),
978
+            'component'     => strtolower($row['componenttype']),
979
+            'classification'=> (int)$row['classification']
980
+        ];
981
+    }
982
+
983
+    /**
984
+     * Returns a list of calendar objects.
985
+     *
986
+     * This method should work identical to getCalendarObject, but instead
987
+     * return all the calendar objects in the list as an array.
988
+     *
989
+     * If the backend supports this, it may allow for some speed-ups.
990
+     *
991
+     * @param mixed $calendarId
992
+     * @param string[] $uris
993
+     * @param int $calendarType
994
+     * @return array
995
+     */
996
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
997
+        if (empty($uris)) {
998
+            return [];
999
+        }
1000
+
1001
+        $chunks = array_chunk($uris, 100);
1002
+        $objects = [];
1003
+
1004
+        $query = $this->db->getQueryBuilder();
1005
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1006
+            ->from('calendarobjects')
1007
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1008
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1009
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1010
+
1011
+        foreach ($chunks as $uris) {
1012
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1013
+            $result = $query->execute();
1014
+
1015
+            while ($row = $result->fetch()) {
1016
+                $objects[] = [
1017
+                    'id'           => $row['id'],
1018
+                    'uri'          => $row['uri'],
1019
+                    'lastmodified' => $row['lastmodified'],
1020
+                    'etag'         => '"' . $row['etag'] . '"',
1021
+                    'calendarid'   => $row['calendarid'],
1022
+                    'size'         => (int)$row['size'],
1023
+                    'calendardata' => $this->readBlob($row['calendardata']),
1024
+                    'component'    => strtolower($row['componenttype']),
1025
+                    'classification' => (int)$row['classification']
1026
+                ];
1027
+            }
1028
+            $result->closeCursor();
1029
+        }
1030
+
1031
+        return $objects;
1032
+    }
1033
+
1034
+    /**
1035
+     * Creates a new calendar object.
1036
+     *
1037
+     * The object uri is only the basename, or filename and not a full path.
1038
+     *
1039
+     * It is possible return an etag from this function, which will be used in
1040
+     * the response to this PUT request. Note that the ETag must be surrounded
1041
+     * by double-quotes.
1042
+     *
1043
+     * However, you should only really return this ETag if you don't mangle the
1044
+     * calendar-data. If the result of a subsequent GET to this object is not
1045
+     * the exact same as this request body, you should omit the ETag.
1046
+     *
1047
+     * @param mixed $calendarId
1048
+     * @param string $objectUri
1049
+     * @param string $calendarData
1050
+     * @param int $calendarType
1051
+     * @return string
1052
+     */
1053
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1054
+        $extraData = $this->getDenormalizedData($calendarData);
1055
+
1056
+        $q = $this->db->getQueryBuilder();
1057
+        $q->select($q->func()->count('*'))
1058
+            ->from('calendarobjects')
1059
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1060
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1061
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1062
+
1063
+        $result = $q->execute();
1064
+        $count = (int) $result->fetchColumn();
1065
+        $result->closeCursor();
1066
+
1067
+        if ($count !== 0) {
1068
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1069
+        }
1070
+
1071
+        $query = $this->db->getQueryBuilder();
1072
+        $query->insert('calendarobjects')
1073
+            ->values([
1074
+                'calendarid' => $query->createNamedParameter($calendarId),
1075
+                'uri' => $query->createNamedParameter($objectUri),
1076
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1077
+                'lastmodified' => $query->createNamedParameter(time()),
1078
+                'etag' => $query->createNamedParameter($extraData['etag']),
1079
+                'size' => $query->createNamedParameter($extraData['size']),
1080
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1081
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1082
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1083
+                'classification' => $query->createNamedParameter($extraData['classification']),
1084
+                'uid' => $query->createNamedParameter($extraData['uid']),
1085
+                'calendartype' => $query->createNamedParameter($calendarType),
1086
+            ])
1087
+            ->execute();
1088
+
1089
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1090
+
1091
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1092
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1093
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1094
+                [
1095
+                    'calendarId' => $calendarId,
1096
+                    'calendarData' => $this->getCalendarById($calendarId),
1097
+                    'shares' => $this->getShares($calendarId),
1098
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1099
+                ]
1100
+            ));
1101
+        } else {
1102
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1103
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1104
+                [
1105
+                    'subscriptionId' => $calendarId,
1106
+                    'calendarData' => $this->getCalendarById($calendarId),
1107
+                    'shares' => $this->getShares($calendarId),
1108
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1109
+                ]
1110
+            ));
1111
+        }
1112
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1113
+
1114
+        return '"' . $extraData['etag'] . '"';
1115
+    }
1116
+
1117
+    /**
1118
+     * Updates an existing calendarobject, based on it's uri.
1119
+     *
1120
+     * The object uri is only the basename, or filename and not a full path.
1121
+     *
1122
+     * It is possible return an etag from this function, which will be used in
1123
+     * the response to this PUT request. Note that the ETag must be surrounded
1124
+     * by double-quotes.
1125
+     *
1126
+     * However, you should only really return this ETag if you don't mangle the
1127
+     * calendar-data. If the result of a subsequent GET to this object is not
1128
+     * the exact same as this request body, you should omit the ETag.
1129
+     *
1130
+     * @param mixed $calendarId
1131
+     * @param string $objectUri
1132
+     * @param string $calendarData
1133
+     * @param int $calendarType
1134
+     * @return string
1135
+     */
1136
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1137
+        $extraData = $this->getDenormalizedData($calendarData);
1138
+        $query = $this->db->getQueryBuilder();
1139
+        $query->update('calendarobjects')
1140
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1141
+                ->set('lastmodified', $query->createNamedParameter(time()))
1142
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1143
+                ->set('size', $query->createNamedParameter($extraData['size']))
1144
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1145
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1146
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1147
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1148
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1149
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1150
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1151
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1152
+            ->execute();
1153
+
1154
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1155
+
1156
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1157
+        if (is_array($data)) {
1158
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1159
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1160
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1161
+                    [
1162
+                        'calendarId' => $calendarId,
1163
+                        'calendarData' => $this->getCalendarById($calendarId),
1164
+                        'shares' => $this->getShares($calendarId),
1165
+                        'objectData' => $data,
1166
+                    ]
1167
+                ));
1168
+            } else {
1169
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1170
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1171
+                    [
1172
+                        'subscriptionId' => $calendarId,
1173
+                        'calendarData' => $this->getCalendarById($calendarId),
1174
+                        'shares' => $this->getShares($calendarId),
1175
+                        'objectData' => $data,
1176
+                    ]
1177
+                ));
1178
+            }
1179
+        }
1180
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1181
+
1182
+        return '"' . $extraData['etag'] . '"';
1183
+    }
1184
+
1185
+    /**
1186
+     * @param int $calendarObjectId
1187
+     * @param int $classification
1188
+     */
1189
+    public function setClassification($calendarObjectId, $classification) {
1190
+        if (!in_array($classification, [
1191
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1192
+        ])) {
1193
+            throw new \InvalidArgumentException();
1194
+        }
1195
+        $query = $this->db->getQueryBuilder();
1196
+        $query->update('calendarobjects')
1197
+            ->set('classification', $query->createNamedParameter($classification))
1198
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1199
+            ->execute();
1200
+    }
1201
+
1202
+    /**
1203
+     * Deletes an existing calendar object.
1204
+     *
1205
+     * The object uri is only the basename, or filename and not a full path.
1206
+     *
1207
+     * @param mixed $calendarId
1208
+     * @param string $objectUri
1209
+     * @param int $calendarType
1210
+     * @return void
1211
+     */
1212
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1213
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1214
+        if (is_array($data)) {
1215
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1216
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1217
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1218
+                    [
1219
+                        'calendarId' => $calendarId,
1220
+                        'calendarData' => $this->getCalendarById($calendarId),
1221
+                        'shares' => $this->getShares($calendarId),
1222
+                        'objectData' => $data,
1223
+                    ]
1224
+                ));
1225
+            } else {
1226
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1227
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1228
+                    [
1229
+                        'subscriptionId' => $calendarId,
1230
+                        'calendarData' => $this->getCalendarById($calendarId),
1231
+                        'shares' => $this->getShares($calendarId),
1232
+                        'objectData' => $data,
1233
+                    ]
1234
+                ));
1235
+            }
1236
+        }
1237
+
1238
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1239
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1240
+
1241
+        $this->purgeProperties($calendarId, $data['id'], $calendarType);
1242
+
1243
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1244
+    }
1245
+
1246
+    /**
1247
+     * Performs a calendar-query on the contents of this calendar.
1248
+     *
1249
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1250
+     * calendar-query it is possible for a client to request a specific set of
1251
+     * object, based on contents of iCalendar properties, date-ranges and
1252
+     * iCalendar component types (VTODO, VEVENT).
1253
+     *
1254
+     * This method should just return a list of (relative) urls that match this
1255
+     * query.
1256
+     *
1257
+     * The list of filters are specified as an array. The exact array is
1258
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1259
+     *
1260
+     * Note that it is extremely likely that getCalendarObject for every path
1261
+     * returned from this method will be called almost immediately after. You
1262
+     * may want to anticipate this to speed up these requests.
1263
+     *
1264
+     * This method provides a default implementation, which parses *all* the
1265
+     * iCalendar objects in the specified calendar.
1266
+     *
1267
+     * This default may well be good enough for personal use, and calendars
1268
+     * that aren't very large. But if you anticipate high usage, big calendars
1269
+     * or high loads, you are strongly advised to optimize certain paths.
1270
+     *
1271
+     * The best way to do so is override this method and to optimize
1272
+     * specifically for 'common filters'.
1273
+     *
1274
+     * Requests that are extremely common are:
1275
+     *   * requests for just VEVENTS
1276
+     *   * requests for just VTODO
1277
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1278
+     *
1279
+     * ..and combinations of these requests. It may not be worth it to try to
1280
+     * handle every possible situation and just rely on the (relatively
1281
+     * easy to use) CalendarQueryValidator to handle the rest.
1282
+     *
1283
+     * Note that especially time-range-filters may be difficult to parse. A
1284
+     * time-range filter specified on a VEVENT must for instance also handle
1285
+     * recurrence rules correctly.
1286
+     * A good example of how to interprete all these filters can also simply
1287
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1288
+     * as possible, so it gives you a good idea on what type of stuff you need
1289
+     * to think of.
1290
+     *
1291
+     * @param mixed $id
1292
+     * @param array $filters
1293
+     * @param int $calendarType
1294
+     * @return array
1295
+     */
1296
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1297
+        $componentType = null;
1298
+        $requirePostFilter = true;
1299
+        $timeRange = null;
1300
+
1301
+        // if no filters were specified, we don't need to filter after a query
1302
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1303
+            $requirePostFilter = false;
1304
+        }
1305
+
1306
+        // Figuring out if there's a component filter
1307
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1308
+            $componentType = $filters['comp-filters'][0]['name'];
1309
+
1310
+            // Checking if we need post-filters
1311
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1312
+                $requirePostFilter = false;
1313
+            }
1314
+            // There was a time-range filter
1315
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1316
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1317
+
1318
+                // If start time OR the end time is not specified, we can do a
1319
+                // 100% accurate mysql query.
1320
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1321
+                    $requirePostFilter = false;
1322
+                }
1323
+            }
1324
+
1325
+        }
1326
+        $columns = ['uri'];
1327
+        if ($requirePostFilter) {
1328
+            $columns = ['uri', 'calendardata'];
1329
+        }
1330
+        $query = $this->db->getQueryBuilder();
1331
+        $query->select($columns)
1332
+            ->from('calendarobjects')
1333
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1334
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1335
+
1336
+        if ($componentType) {
1337
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1338
+        }
1339
+
1340
+        if ($timeRange && $timeRange['start']) {
1341
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1342
+        }
1343
+        if ($timeRange && $timeRange['end']) {
1344
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1345
+        }
1346
+
1347
+        $stmt = $query->execute();
1348
+
1349
+        $result = [];
1350
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1351
+            if ($requirePostFilter) {
1352
+                // validateFilterForObject will parse the calendar data
1353
+                // catch parsing errors
1354
+                try {
1355
+                    $matches = $this->validateFilterForObject($row, $filters);
1356
+                } catch(ParseException $ex) {
1357
+                    $this->logger->logException($ex, [
1358
+                        'app' => 'dav',
1359
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1360
+                    ]);
1361
+                    continue;
1362
+                } catch (InvalidDataException $ex) {
1363
+                    $this->logger->logException($ex, [
1364
+                        'app' => 'dav',
1365
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1366
+                    ]);
1367
+                    continue;
1368
+                }
1369
+
1370
+                if (!$matches) {
1371
+                    continue;
1372
+                }
1373
+            }
1374
+            $result[] = $row['uri'];
1375
+        }
1376
+
1377
+        return $result;
1378
+    }
1379
+
1380
+    /**
1381
+     * custom Nextcloud search extension for CalDAV
1382
+     *
1383
+     * TODO - this should optionally cover cached calendar objects as well
1384
+     *
1385
+     * @param string $principalUri
1386
+     * @param array $filters
1387
+     * @param integer|null $limit
1388
+     * @param integer|null $offset
1389
+     * @return array
1390
+     */
1391
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1392
+        $calendars = $this->getCalendarsForUser($principalUri);
1393
+        $ownCalendars = [];
1394
+        $sharedCalendars = [];
1395
+
1396
+        $uriMapper = [];
1397
+
1398
+        foreach($calendars as $calendar) {
1399
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1400
+                $ownCalendars[] = $calendar['id'];
1401
+            } else {
1402
+                $sharedCalendars[] = $calendar['id'];
1403
+            }
1404
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1405
+        }
1406
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1407
+            return [];
1408
+        }
1409
+
1410
+        $query = $this->db->getQueryBuilder();
1411
+        // Calendar id expressions
1412
+        $calendarExpressions = [];
1413
+        foreach($ownCalendars as $id) {
1414
+            $calendarExpressions[] = $query->expr()->andX(
1415
+                $query->expr()->eq('c.calendarid',
1416
+                    $query->createNamedParameter($id)),
1417
+                $query->expr()->eq('c.calendartype',
1418
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1419
+        }
1420
+        foreach($sharedCalendars as $id) {
1421
+            $calendarExpressions[] = $query->expr()->andX(
1422
+                $query->expr()->eq('c.calendarid',
1423
+                    $query->createNamedParameter($id)),
1424
+                $query->expr()->eq('c.classification',
1425
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1426
+                $query->expr()->eq('c.calendartype',
1427
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1428
+        }
1429
+
1430
+        if (count($calendarExpressions) === 1) {
1431
+            $calExpr = $calendarExpressions[0];
1432
+        } else {
1433
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1434
+        }
1435
+
1436
+        // Component expressions
1437
+        $compExpressions = [];
1438
+        foreach($filters['comps'] as $comp) {
1439
+            $compExpressions[] = $query->expr()
1440
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1441
+        }
1442
+
1443
+        if (count($compExpressions) === 1) {
1444
+            $compExpr = $compExpressions[0];
1445
+        } else {
1446
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1447
+        }
1448
+
1449
+        if (!isset($filters['props'])) {
1450
+            $filters['props'] = [];
1451
+        }
1452
+        if (!isset($filters['params'])) {
1453
+            $filters['params'] = [];
1454
+        }
1455
+
1456
+        $propParamExpressions = [];
1457
+        foreach($filters['props'] as $prop) {
1458
+            $propParamExpressions[] = $query->expr()->andX(
1459
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1460
+                $query->expr()->isNull('i.parameter')
1461
+            );
1462
+        }
1463
+        foreach($filters['params'] as $param) {
1464
+            $propParamExpressions[] = $query->expr()->andX(
1465
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1466
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1467
+            );
1468
+        }
1469
+
1470
+        if (count($propParamExpressions) === 1) {
1471
+            $propParamExpr = $propParamExpressions[0];
1472
+        } else {
1473
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1474
+        }
1475
+
1476
+        $query->select(['c.calendarid', 'c.uri'])
1477
+            ->from($this->dbObjectPropertiesTable, 'i')
1478
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1479
+            ->where($calExpr)
1480
+            ->andWhere($compExpr)
1481
+            ->andWhere($propParamExpr)
1482
+            ->andWhere($query->expr()->iLike('i.value',
1483
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1484
+
1485
+        if ($offset) {
1486
+            $query->setFirstResult($offset);
1487
+        }
1488
+        if ($limit) {
1489
+            $query->setMaxResults($limit);
1490
+        }
1491
+
1492
+        $stmt = $query->execute();
1493
+
1494
+        $result = [];
1495
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1496
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1497
+            if (!in_array($path, $result)) {
1498
+                $result[] = $path;
1499
+            }
1500
+        }
1501
+
1502
+        return $result;
1503
+    }
1504
+
1505
+    /**
1506
+     * used for Nextcloud's calendar API
1507
+     *
1508
+     * @param array $calendarInfo
1509
+     * @param string $pattern
1510
+     * @param array $searchProperties
1511
+     * @param array $options
1512
+     * @param integer|null $limit
1513
+     * @param integer|null $offset
1514
+     *
1515
+     * @return array
1516
+     */
1517
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1518
+                            array $options, $limit, $offset) {
1519
+        $outerQuery = $this->db->getQueryBuilder();
1520
+        $innerQuery = $this->db->getQueryBuilder();
1521
+
1522
+        $innerQuery->selectDistinct('op.objectid')
1523
+            ->from($this->dbObjectPropertiesTable, 'op')
1524
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1525
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1526
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1527
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1528
+
1529
+        // only return public items for shared calendars for now
1530
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1531
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1532
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1533
+        }
1534
+
1535
+        $or = $innerQuery->expr()->orX();
1536
+        foreach($searchProperties as $searchProperty) {
1537
+            $or->add($innerQuery->expr()->eq('op.name',
1538
+                $outerQuery->createNamedParameter($searchProperty)));
1539
+        }
1540
+        $innerQuery->andWhere($or);
1541
+
1542
+        if ($pattern !== '') {
1543
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1544
+                $outerQuery->createNamedParameter('%' .
1545
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1546
+        }
1547
+
1548
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1549
+            ->from('calendarobjects', 'c');
1550
+
1551
+        if (isset($options['timerange'])) {
1552
+            if (isset($options['timerange']['start'])) {
1553
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1554
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1555
+
1556
+            }
1557
+            if (isset($options['timerange']['end'])) {
1558
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1559
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1560
+            }
1561
+        }
1562
+
1563
+        if (isset($options['types'])) {
1564
+            $or = $outerQuery->expr()->orX();
1565
+            foreach($options['types'] as $type) {
1566
+                $or->add($outerQuery->expr()->eq('componenttype',
1567
+                    $outerQuery->createNamedParameter($type)));
1568
+            }
1569
+            $outerQuery->andWhere($or);
1570
+        }
1571
+
1572
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1573
+            $outerQuery->createFunction($innerQuery->getSQL())));
1574
+
1575
+        if ($offset) {
1576
+            $outerQuery->setFirstResult($offset);
1577
+        }
1578
+        if ($limit) {
1579
+            $outerQuery->setMaxResults($limit);
1580
+        }
1581
+
1582
+        $result = $outerQuery->execute();
1583
+        $calendarObjects = $result->fetchAll();
1584
+
1585
+        return array_map(function($o) {
1586
+            $calendarData = Reader::read($o['calendardata']);
1587
+            $comps = $calendarData->getComponents();
1588
+            $objects = [];
1589
+            $timezones = [];
1590
+            foreach($comps as $comp) {
1591
+                if ($comp instanceof VTimeZone) {
1592
+                    $timezones[] = $comp;
1593
+                } else {
1594
+                    $objects[] = $comp;
1595
+                }
1596
+            }
1597
+
1598
+            return [
1599
+                'id' => $o['id'],
1600
+                'type' => $o['componenttype'],
1601
+                'uid' => $o['uid'],
1602
+                'uri' => $o['uri'],
1603
+                'objects' => array_map(function($c) {
1604
+                    return $this->transformSearchData($c);
1605
+                }, $objects),
1606
+                'timezones' => array_map(function($c) {
1607
+                    return $this->transformSearchData($c);
1608
+                }, $timezones),
1609
+            ];
1610
+        }, $calendarObjects);
1611
+    }
1612
+
1613
+    /**
1614
+     * @param Component $comp
1615
+     * @return array
1616
+     */
1617
+    private function transformSearchData(Component $comp) {
1618
+        $data = [];
1619
+        /** @var Component[] $subComponents */
1620
+        $subComponents = $comp->getComponents();
1621
+        /** @var Property[] $properties */
1622
+        $properties = array_filter($comp->children(), function($c) {
1623
+            return $c instanceof Property;
1624
+        });
1625
+        $validationRules = $comp->getValidationRules();
1626
+
1627
+        foreach($subComponents as $subComponent) {
1628
+            $name = $subComponent->name;
1629
+            if (!isset($data[$name])) {
1630
+                $data[$name] = [];
1631
+            }
1632
+            $data[$name][] = $this->transformSearchData($subComponent);
1633
+        }
1634
+
1635
+        foreach($properties as $property) {
1636
+            $name = $property->name;
1637
+            if (!isset($validationRules[$name])) {
1638
+                $validationRules[$name] = '*';
1639
+            }
1640
+
1641
+            $rule = $validationRules[$property->name];
1642
+            if ($rule === '+' || $rule === '*') { // multiple
1643
+                if (!isset($data[$name])) {
1644
+                    $data[$name] = [];
1645
+                }
1646
+
1647
+                $data[$name][] = $this->transformSearchProperty($property);
1648
+            } else { // once
1649
+                $data[$name] = $this->transformSearchProperty($property);
1650
+            }
1651
+        }
1652
+
1653
+        return $data;
1654
+    }
1655
+
1656
+    /**
1657
+     * @param Property $prop
1658
+     * @return array
1659
+     */
1660
+    private function transformSearchProperty(Property $prop) {
1661
+        // No need to check Date, as it extends DateTime
1662
+        if ($prop instanceof Property\ICalendar\DateTime) {
1663
+            $value = $prop->getDateTime();
1664
+        } else {
1665
+            $value = $prop->getValue();
1666
+        }
1667
+
1668
+        return [
1669
+            $value,
1670
+            $prop->parameters()
1671
+        ];
1672
+    }
1673
+
1674
+    /**
1675
+     * Searches through all of a users calendars and calendar objects to find
1676
+     * an object with a specific UID.
1677
+     *
1678
+     * This method should return the path to this object, relative to the
1679
+     * calendar home, so this path usually only contains two parts:
1680
+     *
1681
+     * calendarpath/objectpath.ics
1682
+     *
1683
+     * If the uid is not found, return null.
1684
+     *
1685
+     * This method should only consider * objects that the principal owns, so
1686
+     * any calendars owned by other principals that also appear in this
1687
+     * collection should be ignored.
1688
+     *
1689
+     * @param string $principalUri
1690
+     * @param string $uid
1691
+     * @return string|null
1692
+     */
1693
+    function getCalendarObjectByUID($principalUri, $uid) {
1694
+
1695
+        $query = $this->db->getQueryBuilder();
1696
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1697
+            ->from('calendarobjects', 'co')
1698
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1699
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1700
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1701
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1702
+
1703
+        $stmt = $query->execute();
1704
+
1705
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1706
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1707
+        }
1708
+
1709
+        return null;
1710
+    }
1711
+
1712
+    /**
1713
+     * The getChanges method returns all the changes that have happened, since
1714
+     * the specified syncToken in the specified calendar.
1715
+     *
1716
+     * This function should return an array, such as the following:
1717
+     *
1718
+     * [
1719
+     *   'syncToken' => 'The current synctoken',
1720
+     *   'added'   => [
1721
+     *      'new.txt',
1722
+     *   ],
1723
+     *   'modified'   => [
1724
+     *      'modified.txt',
1725
+     *   ],
1726
+     *   'deleted' => [
1727
+     *      'foo.php.bak',
1728
+     *      'old.txt'
1729
+     *   ]
1730
+     * );
1731
+     *
1732
+     * The returned syncToken property should reflect the *current* syncToken
1733
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1734
+     * property This is * needed here too, to ensure the operation is atomic.
1735
+     *
1736
+     * If the $syncToken argument is specified as null, this is an initial
1737
+     * sync, and all members should be reported.
1738
+     *
1739
+     * The modified property is an array of nodenames that have changed since
1740
+     * the last token.
1741
+     *
1742
+     * The deleted property is an array with nodenames, that have been deleted
1743
+     * from collection.
1744
+     *
1745
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1746
+     * 1, you only have to report changes that happened only directly in
1747
+     * immediate descendants. If it's 2, it should also include changes from
1748
+     * the nodes below the child collections. (grandchildren)
1749
+     *
1750
+     * The $limit argument allows a client to specify how many results should
1751
+     * be returned at most. If the limit is not specified, it should be treated
1752
+     * as infinite.
1753
+     *
1754
+     * If the limit (infinite or not) is higher than you're willing to return,
1755
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1756
+     *
1757
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1758
+     * return null.
1759
+     *
1760
+     * The limit is 'suggestive'. You are free to ignore it.
1761
+     *
1762
+     * @param string $calendarId
1763
+     * @param string $syncToken
1764
+     * @param int $syncLevel
1765
+     * @param int $limit
1766
+     * @param int $calendarType
1767
+     * @return array
1768
+     */
1769
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1770
+        // Current synctoken
1771
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1772
+        $stmt->execute([ $calendarId ]);
1773
+        $currentToken = $stmt->fetchColumn(0);
1774
+
1775
+        if (is_null($currentToken)) {
1776
+            return null;
1777
+        }
1778
+
1779
+        $result = [
1780
+            'syncToken' => $currentToken,
1781
+            'added'     => [],
1782
+            'modified'  => [],
1783
+            'deleted'   => [],
1784
+        ];
1785
+
1786
+        if ($syncToken) {
1787
+
1788
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1789
+            if ($limit>0) {
1790
+                $query.= " LIMIT " . (int)$limit;
1791
+            }
1792
+
1793
+            // Fetching all changes
1794
+            $stmt = $this->db->prepare($query);
1795
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1796
+
1797
+            $changes = [];
1798
+
1799
+            // This loop ensures that any duplicates are overwritten, only the
1800
+            // last change on a node is relevant.
1801
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1802
+
1803
+                $changes[$row['uri']] = $row['operation'];
1804
+
1805
+            }
1806
+
1807
+            foreach($changes as $uri => $operation) {
1808
+
1809
+                switch($operation) {
1810
+                    case 1 :
1811
+                        $result['added'][] = $uri;
1812
+                        break;
1813
+                    case 2 :
1814
+                        $result['modified'][] = $uri;
1815
+                        break;
1816
+                    case 3 :
1817
+                        $result['deleted'][] = $uri;
1818
+                        break;
1819
+                }
1820
+
1821
+            }
1822
+        } else {
1823
+            // No synctoken supplied, this is the initial sync.
1824
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1825
+            $stmt = $this->db->prepare($query);
1826
+            $stmt->execute([$calendarId, $calendarType]);
1827
+
1828
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1829
+        }
1830
+        return $result;
1831
+
1832
+    }
1833
+
1834
+    /**
1835
+     * Returns a list of subscriptions for a principal.
1836
+     *
1837
+     * Every subscription is an array with the following keys:
1838
+     *  * id, a unique id that will be used by other functions to modify the
1839
+     *    subscription. This can be the same as the uri or a database key.
1840
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1841
+     *  * principaluri. The owner of the subscription. Almost always the same as
1842
+     *    principalUri passed to this method.
1843
+     *
1844
+     * Furthermore, all the subscription info must be returned too:
1845
+     *
1846
+     * 1. {DAV:}displayname
1847
+     * 2. {http://apple.com/ns/ical/}refreshrate
1848
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1849
+     *    should not be stripped).
1850
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1851
+     *    should not be stripped).
1852
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1853
+     *    attachments should not be stripped).
1854
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1855
+     *     Sabre\DAV\Property\Href).
1856
+     * 7. {http://apple.com/ns/ical/}calendar-color
1857
+     * 8. {http://apple.com/ns/ical/}calendar-order
1858
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1859
+     *    (should just be an instance of
1860
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1861
+     *    default components).
1862
+     *
1863
+     * @param string $principalUri
1864
+     * @return array
1865
+     */
1866
+    function getSubscriptionsForUser($principalUri) {
1867
+        $fields = array_values($this->subscriptionPropertyMap);
1868
+        $fields[] = 'id';
1869
+        $fields[] = 'uri';
1870
+        $fields[] = 'source';
1871
+        $fields[] = 'principaluri';
1872
+        $fields[] = 'lastmodified';
1873
+        $fields[] = 'synctoken';
1874
+
1875
+        $query = $this->db->getQueryBuilder();
1876
+        $query->select($fields)
1877
+            ->from('calendarsubscriptions')
1878
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1879
+            ->orderBy('calendarorder', 'asc');
1880
+        $stmt =$query->execute();
1881
+
1882
+        $subscriptions = [];
1883
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1884
+
1885
+            $subscription = [
1886
+                'id'           => $row['id'],
1887
+                'uri'          => $row['uri'],
1888
+                'principaluri' => $row['principaluri'],
1889
+                'source'       => $row['source'],
1890
+                'lastmodified' => $row['lastmodified'],
1891
+
1892
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1893
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1894
+            ];
1895
+
1896
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1897
+                if (!is_null($row[$dbName])) {
1898
+                    $subscription[$xmlName] = $row[$dbName];
1899
+                }
1900
+            }
1901
+
1902
+            $subscriptions[] = $subscription;
1903
+
1904
+        }
1905
+
1906
+        return $subscriptions;
1907
+    }
1908
+
1909
+    /**
1910
+     * Creates a new subscription for a principal.
1911
+     *
1912
+     * If the creation was a success, an id must be returned that can be used to reference
1913
+     * this subscription in other methods, such as updateSubscription.
1914
+     *
1915
+     * @param string $principalUri
1916
+     * @param string $uri
1917
+     * @param array $properties
1918
+     * @return mixed
1919
+     */
1920
+    function createSubscription($principalUri, $uri, array $properties) {
1921
+
1922
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1923
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1924
+        }
1925
+
1926
+        $values = [
1927
+            'principaluri' => $principalUri,
1928
+            'uri'          => $uri,
1929
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1930
+            'lastmodified' => time(),
1931
+        ];
1932
+
1933
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1934
+
1935
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1936
+            if (array_key_exists($xmlName, $properties)) {
1937
+                    $values[$dbName] = $properties[$xmlName];
1938
+                    if (in_array($dbName, $propertiesBoolean)) {
1939
+                        $values[$dbName] = true;
1940
+                }
1941
+            }
1942
+        }
1943
+
1944
+        $valuesToInsert = array();
1945
+
1946
+        $query = $this->db->getQueryBuilder();
1947
+
1948
+        foreach (array_keys($values) as $name) {
1949
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1950
+        }
1951
+
1952
+        $query->insert('calendarsubscriptions')
1953
+            ->values($valuesToInsert)
1954
+            ->execute();
1955
+
1956
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1957
+
1958
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1959
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1960
+            [
1961
+                'subscriptionId' => $subscriptionId,
1962
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1963
+            ]));
1964
+
1965
+        return $subscriptionId;
1966
+    }
1967
+
1968
+    /**
1969
+     * Updates a subscription
1970
+     *
1971
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1972
+     * To do the actual updates, you must tell this object which properties
1973
+     * you're going to process with the handle() method.
1974
+     *
1975
+     * Calling the handle method is like telling the PropPatch object "I
1976
+     * promise I can handle updating this property".
1977
+     *
1978
+     * Read the PropPatch documentation for more info and examples.
1979
+     *
1980
+     * @param mixed $subscriptionId
1981
+     * @param PropPatch $propPatch
1982
+     * @return void
1983
+     */
1984
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1985
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1986
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1987
+
1988
+        /**
1989
+         * @suppress SqlInjectionChecker
1990
+         */
1991
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1992
+
1993
+            $newValues = [];
1994
+
1995
+            foreach($mutations as $propertyName=>$propertyValue) {
1996
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1997
+                    $newValues['source'] = $propertyValue->getHref();
1998
+                } else {
1999
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2000
+                    $newValues[$fieldName] = $propertyValue;
2001
+                }
2002
+            }
2003
+
2004
+            $query = $this->db->getQueryBuilder();
2005
+            $query->update('calendarsubscriptions')
2006
+                ->set('lastmodified', $query->createNamedParameter(time()));
2007
+            foreach($newValues as $fieldName=>$value) {
2008
+                $query->set($fieldName, $query->createNamedParameter($value));
2009
+            }
2010
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2011
+                ->execute();
2012
+
2013
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2014
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2015
+                [
2016
+                    'subscriptionId' => $subscriptionId,
2017
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2018
+                    'propertyMutations' => $mutations,
2019
+                ]));
2020
+
2021
+            return true;
2022
+
2023
+        });
2024
+    }
2025
+
2026
+    /**
2027
+     * Deletes a subscription.
2028
+     *
2029
+     * @param mixed $subscriptionId
2030
+     * @return void
2031
+     */
2032
+    function deleteSubscription($subscriptionId) {
2033
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2034
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2035
+            [
2036
+                'subscriptionId' => $subscriptionId,
2037
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2038
+            ]));
2039
+
2040
+        $query = $this->db->getQueryBuilder();
2041
+        $query->delete('calendarsubscriptions')
2042
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2043
+            ->execute();
2044
+
2045
+        $query = $this->db->getQueryBuilder();
2046
+        $query->delete('calendarobjects')
2047
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2048
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2049
+            ->execute();
2050
+
2051
+        $query->delete('calendarchanges')
2052
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2053
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2054
+            ->execute();
2055
+
2056
+        $query->delete($this->dbObjectPropertiesTable)
2057
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2058
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2059
+            ->execute();
2060
+    }
2061
+
2062
+    /**
2063
+     * Returns a single scheduling object for the inbox collection.
2064
+     *
2065
+     * The returned array should contain the following elements:
2066
+     *   * uri - A unique basename for the object. This will be used to
2067
+     *           construct a full uri.
2068
+     *   * calendardata - The iCalendar object
2069
+     *   * lastmodified - The last modification date. Can be an int for a unix
2070
+     *                    timestamp, or a PHP DateTime object.
2071
+     *   * etag - A unique token that must change if the object changed.
2072
+     *   * size - The size of the object, in bytes.
2073
+     *
2074
+     * @param string $principalUri
2075
+     * @param string $objectUri
2076
+     * @return array
2077
+     */
2078
+    function getSchedulingObject($principalUri, $objectUri) {
2079
+        $query = $this->db->getQueryBuilder();
2080
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2081
+            ->from('schedulingobjects')
2082
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2083
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2084
+            ->execute();
2085
+
2086
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2087
+
2088
+        if(!$row) {
2089
+            return null;
2090
+        }
2091
+
2092
+        return [
2093
+                'uri'          => $row['uri'],
2094
+                'calendardata' => $row['calendardata'],
2095
+                'lastmodified' => $row['lastmodified'],
2096
+                'etag'         => '"' . $row['etag'] . '"',
2097
+                'size'         => (int)$row['size'],
2098
+        ];
2099
+    }
2100
+
2101
+    /**
2102
+     * Returns all scheduling objects for the inbox collection.
2103
+     *
2104
+     * These objects should be returned as an array. Every item in the array
2105
+     * should follow the same structure as returned from getSchedulingObject.
2106
+     *
2107
+     * The main difference is that 'calendardata' is optional.
2108
+     *
2109
+     * @param string $principalUri
2110
+     * @return array
2111
+     */
2112
+    function getSchedulingObjects($principalUri) {
2113
+        $query = $this->db->getQueryBuilder();
2114
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2115
+                ->from('schedulingobjects')
2116
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2117
+                ->execute();
2118
+
2119
+        $result = [];
2120
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2121
+            $result[] = [
2122
+                    'calendardata' => $row['calendardata'],
2123
+                    'uri'          => $row['uri'],
2124
+                    'lastmodified' => $row['lastmodified'],
2125
+                    'etag'         => '"' . $row['etag'] . '"',
2126
+                    'size'         => (int)$row['size'],
2127
+            ];
2128
+        }
2129
+
2130
+        return $result;
2131
+    }
2132
+
2133
+    /**
2134
+     * Deletes a scheduling object from the inbox collection.
2135
+     *
2136
+     * @param string $principalUri
2137
+     * @param string $objectUri
2138
+     * @return void
2139
+     */
2140
+    function deleteSchedulingObject($principalUri, $objectUri) {
2141
+        $query = $this->db->getQueryBuilder();
2142
+        $query->delete('schedulingobjects')
2143
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2144
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2145
+                ->execute();
2146
+    }
2147
+
2148
+    /**
2149
+     * Creates a new scheduling object. This should land in a users' inbox.
2150
+     *
2151
+     * @param string $principalUri
2152
+     * @param string $objectUri
2153
+     * @param string $objectData
2154
+     * @return void
2155
+     */
2156
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2157
+        $query = $this->db->getQueryBuilder();
2158
+        $query->insert('schedulingobjects')
2159
+            ->values([
2160
+                'principaluri' => $query->createNamedParameter($principalUri),
2161
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2162
+                'uri' => $query->createNamedParameter($objectUri),
2163
+                'lastmodified' => $query->createNamedParameter(time()),
2164
+                'etag' => $query->createNamedParameter(md5($objectData)),
2165
+                'size' => $query->createNamedParameter(strlen($objectData))
2166
+            ])
2167
+            ->execute();
2168
+    }
2169
+
2170
+    /**
2171
+     * Adds a change record to the calendarchanges table.
2172
+     *
2173
+     * @param mixed $calendarId
2174
+     * @param string $objectUri
2175
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2176
+     * @param int $calendarType
2177
+     * @return void
2178
+     */
2179
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2180
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2181
+
2182
+        $query = $this->db->getQueryBuilder();
2183
+        $query->select('synctoken')
2184
+            ->from($table)
2185
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2186
+        $syncToken = (int)$query->execute()->fetchColumn();
2187
+
2188
+        $query = $this->db->getQueryBuilder();
2189
+        $query->insert('calendarchanges')
2190
+            ->values([
2191
+                'uri' => $query->createNamedParameter($objectUri),
2192
+                'synctoken' => $query->createNamedParameter($syncToken),
2193
+                'calendarid' => $query->createNamedParameter($calendarId),
2194
+                'operation' => $query->createNamedParameter($operation),
2195
+                'calendartype' => $query->createNamedParameter($calendarType),
2196
+            ])
2197
+            ->execute();
2198
+
2199
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2200
+        $stmt->execute([
2201
+            $calendarId
2202
+        ]);
2203
+
2204
+    }
2205
+
2206
+    /**
2207
+     * Parses some information from calendar objects, used for optimized
2208
+     * calendar-queries.
2209
+     *
2210
+     * Returns an array with the following keys:
2211
+     *   * etag - An md5 checksum of the object without the quotes.
2212
+     *   * size - Size of the object in bytes
2213
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2214
+     *   * firstOccurence
2215
+     *   * lastOccurence
2216
+     *   * uid - value of the UID property
2217
+     *
2218
+     * @param string $calendarData
2219
+     * @return array
2220
+     */
2221
+    public function getDenormalizedData($calendarData) {
2222
+
2223
+        $vObject = Reader::read($calendarData);
2224
+        $componentType = null;
2225
+        $component = null;
2226
+        $firstOccurrence = null;
2227
+        $lastOccurrence = null;
2228
+        $uid = null;
2229
+        $classification = self::CLASSIFICATION_PUBLIC;
2230
+        foreach($vObject->getComponents() as $component) {
2231
+            if ($component->name!=='VTIMEZONE') {
2232
+                $componentType = $component->name;
2233
+                $uid = (string)$component->UID;
2234
+                break;
2235
+            }
2236
+        }
2237
+        if (!$componentType) {
2238
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2239
+        }
2240
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2241
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2242
+            // Finding the last occurrence is a bit harder
2243
+            if (!isset($component->RRULE)) {
2244
+                if (isset($component->DTEND)) {
2245
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2246
+                } elseif (isset($component->DURATION)) {
2247
+                    $endDate = clone $component->DTSTART->getDateTime();
2248
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2249
+                    $lastOccurrence = $endDate->getTimeStamp();
2250
+                } elseif (!$component->DTSTART->hasTime()) {
2251
+                    $endDate = clone $component->DTSTART->getDateTime();
2252
+                    $endDate->modify('+1 day');
2253
+                    $lastOccurrence = $endDate->getTimeStamp();
2254
+                } else {
2255
+                    $lastOccurrence = $firstOccurrence;
2256
+                }
2257
+            } else {
2258
+                $it = new EventIterator($vObject, (string)$component->UID);
2259
+                $maxDate = new \DateTime(self::MAX_DATE);
2260
+                if ($it->isInfinite()) {
2261
+                    $lastOccurrence = $maxDate->getTimestamp();
2262
+                } else {
2263
+                    $end = $it->getDtEnd();
2264
+                    while($it->valid() && $end < $maxDate) {
2265
+                        $end = $it->getDtEnd();
2266
+                        $it->next();
2267
+
2268
+                    }
2269
+                    $lastOccurrence = $end->getTimestamp();
2270
+                }
2271
+
2272
+            }
2273
+        }
2274
+
2275
+        if ($component->CLASS) {
2276
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2277
+            switch ($component->CLASS->getValue()) {
2278
+                case 'PUBLIC':
2279
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2280
+                    break;
2281
+                case 'CONFIDENTIAL':
2282
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2283
+                    break;
2284
+            }
2285
+        }
2286
+        return [
2287
+            'etag' => md5($calendarData),
2288
+            'size' => strlen($calendarData),
2289
+            'componentType' => $componentType,
2290
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2291
+            'lastOccurence'  => $lastOccurrence,
2292
+            'uid' => $uid,
2293
+            'classification' => $classification
2294
+        ];
2295
+
2296
+    }
2297
+
2298
+    /**
2299
+     * @param $cardData
2300
+     * @return bool|string
2301
+     */
2302
+    private function readBlob($cardData) {
2303
+        if (is_resource($cardData)) {
2304
+            return stream_get_contents($cardData);
2305
+        }
2306
+
2307
+        return $cardData;
2308
+    }
2309
+
2310
+    /**
2311
+     * @param IShareable $shareable
2312
+     * @param array $add
2313
+     * @param array $remove
2314
+     */
2315
+    public function updateShares($shareable, $add, $remove) {
2316
+        $calendarId = $shareable->getResourceId();
2317
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2318
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2319
+            [
2320
+                'calendarId' => $calendarId,
2321
+                'calendarData' => $this->getCalendarById($calendarId),
2322
+                'shares' => $this->getShares($calendarId),
2323
+                'add' => $add,
2324
+                'remove' => $remove,
2325
+            ]));
2326
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2327
+    }
2328
+
2329
+    /**
2330
+     * @param int $resourceId
2331
+     * @param int $calendarType
2332
+     * @return array
2333
+     */
2334
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2335
+        return $this->calendarSharingBackend->getShares($resourceId);
2336
+    }
2337
+
2338
+    /**
2339
+     * @param boolean $value
2340
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2341
+     * @return string|null
2342
+     */
2343
+    public function setPublishStatus($value, $calendar) {
2344
+
2345
+        $calendarId = $calendar->getResourceId();
2346
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2347
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2348
+            [
2349
+                'calendarId' => $calendarId,
2350
+                'calendarData' => $this->getCalendarById($calendarId),
2351
+                'public' => $value,
2352
+            ]));
2353
+
2354
+        $query = $this->db->getQueryBuilder();
2355
+        if ($value) {
2356
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2357
+            $query->insert('dav_shares')
2358
+                ->values([
2359
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2360
+                    'type' => $query->createNamedParameter('calendar'),
2361
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2362
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2363
+                    'publicuri' => $query->createNamedParameter($publicUri)
2364
+                ]);
2365
+            $query->execute();
2366
+            return $publicUri;
2367
+        }
2368
+        $query->delete('dav_shares')
2369
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2370
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2371
+        $query->execute();
2372
+        return null;
2373
+    }
2374
+
2375
+    /**
2376
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2377
+     * @return mixed
2378
+     */
2379
+    public function getPublishStatus($calendar) {
2380
+        $query = $this->db->getQueryBuilder();
2381
+        $result = $query->select('publicuri')
2382
+            ->from('dav_shares')
2383
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2384
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2385
+            ->execute();
2386
+
2387
+        $row = $result->fetch();
2388
+        $result->closeCursor();
2389
+        return $row ? reset($row) : false;
2390
+    }
2391
+
2392
+    /**
2393
+     * @param int $resourceId
2394
+     * @param array $acl
2395
+     * @return array
2396
+     */
2397
+    public function applyShareAcl($resourceId, $acl) {
2398
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2399
+    }
2400
+
2401
+
2402
+
2403
+    /**
2404
+     * update properties table
2405
+     *
2406
+     * @param int $calendarId
2407
+     * @param string $objectUri
2408
+     * @param string $calendarData
2409
+     * @param int $calendarType
2410
+     */
2411
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2412
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2413
+
2414
+        try {
2415
+            $vCalendar = $this->readCalendarData($calendarData);
2416
+        } catch (\Exception $ex) {
2417
+            return;
2418
+        }
2419
+
2420
+        $this->purgeProperties($calendarId, $objectId);
2421
+
2422
+        $query = $this->db->getQueryBuilder();
2423
+        $query->insert($this->dbObjectPropertiesTable)
2424
+            ->values(
2425
+                [
2426
+                    'calendarid' => $query->createNamedParameter($calendarId),
2427
+                    'calendartype' => $query->createNamedParameter($calendarType),
2428
+                    'objectid' => $query->createNamedParameter($objectId),
2429
+                    'name' => $query->createParameter('name'),
2430
+                    'parameter' => $query->createParameter('parameter'),
2431
+                    'value' => $query->createParameter('value'),
2432
+                ]
2433
+            );
2434
+
2435
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2436
+        foreach ($vCalendar->getComponents() as $component) {
2437
+            if (!in_array($component->name, $indexComponents)) {
2438
+                continue;
2439
+            }
2440
+
2441
+            foreach ($component->children() as $property) {
2442
+                if (in_array($property->name, self::$indexProperties)) {
2443
+                    $value = $property->getValue();
2444
+                    // is this a shitty db?
2445
+                    if (!$this->db->supports4ByteText()) {
2446
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2447
+                    }
2448
+                    $value = mb_substr($value, 0, 254);
2449
+
2450
+                    $query->setParameter('name', $property->name);
2451
+                    $query->setParameter('parameter', null);
2452
+                    $query->setParameter('value', $value);
2453
+                    $query->execute();
2454
+                }
2455
+
2456
+                if (array_key_exists($property->name, self::$indexParameters)) {
2457
+                    $parameters = $property->parameters();
2458
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2459
+
2460
+                    foreach ($parameters as $key => $value) {
2461
+                        if (in_array($key, $indexedParametersForProperty)) {
2462
+                            // is this a shitty db?
2463
+                            if ($this->db->supports4ByteText()) {
2464
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2465
+                            }
2466
+                            $value = mb_substr($value, 0, 254);
2467
+
2468
+                            $query->setParameter('name', $property->name);
2469
+                            $query->setParameter('parameter', substr($key, 0, 254));
2470
+                            $query->setParameter('value', substr($value, 0, 254));
2471
+                            $query->execute();
2472
+                        }
2473
+                    }
2474
+                }
2475
+            }
2476
+        }
2477
+    }
2478
+
2479
+    /**
2480
+     * deletes all birthday calendars
2481
+     */
2482
+    public function deleteAllBirthdayCalendars() {
2483
+        $query = $this->db->getQueryBuilder();
2484
+        $result = $query->select(['id'])->from('calendars')
2485
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2486
+            ->execute();
2487
+
2488
+        $ids = $result->fetchAll();
2489
+        foreach($ids as $id) {
2490
+            $this->deleteCalendar($id['id']);
2491
+        }
2492
+    }
2493
+
2494
+    /**
2495
+     * @param $subscriptionId
2496
+     */
2497
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2498
+        $query = $this->db->getQueryBuilder();
2499
+        $query->select('uri')
2500
+            ->from('calendarobjects')
2501
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2502
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2503
+        $stmt = $query->execute();
2504
+
2505
+        $uris = [];
2506
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2507
+            $uris[] = $row['uri'];
2508
+        }
2509
+        $stmt->closeCursor();
2510
+
2511
+        $query = $this->db->getQueryBuilder();
2512
+        $query->delete('calendarobjects')
2513
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2514
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2515
+            ->execute();
2516
+
2517
+        $query->delete('calendarchanges')
2518
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2519
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2520
+            ->execute();
2521
+
2522
+        $query->delete($this->dbObjectPropertiesTable)
2523
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2524
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2525
+            ->execute();
2526
+
2527
+        foreach($uris as $uri) {
2528
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2529
+        }
2530
+    }
2531
+
2532
+    /**
2533
+     * Move a calendar from one user to another
2534
+     *
2535
+     * @param string $uriName
2536
+     * @param string $uriOrigin
2537
+     * @param string $uriDestination
2538
+     */
2539
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2540
+    {
2541
+        $query = $this->db->getQueryBuilder();
2542
+        $query->update('calendars')
2543
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2544
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2545
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2546
+            ->execute();
2547
+    }
2548
+
2549
+    /**
2550
+     * read VCalendar data into a VCalendar object
2551
+     *
2552
+     * @param string $objectData
2553
+     * @return VCalendar
2554
+     */
2555
+    protected function readCalendarData($objectData) {
2556
+        return Reader::read($objectData);
2557
+    }
2558
+
2559
+    /**
2560
+     * delete all properties from a given calendar object
2561
+     *
2562
+     * @param int $calendarId
2563
+     * @param int $objectId
2564
+     */
2565
+    protected function purgeProperties($calendarId, $objectId) {
2566
+        $query = $this->db->getQueryBuilder();
2567
+        $query->delete($this->dbObjectPropertiesTable)
2568
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2569
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2570
+        $query->execute();
2571
+    }
2572
+
2573
+    /**
2574
+     * get ID from a given calendar object
2575
+     *
2576
+     * @param int $calendarId
2577
+     * @param string $uri
2578
+     * @param int $calendarType
2579
+     * @return int
2580
+     */
2581
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2582
+        $query = $this->db->getQueryBuilder();
2583
+        $query->select('id')
2584
+            ->from('calendarobjects')
2585
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2586
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2587
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2588
+
2589
+        $result = $query->execute();
2590
+        $objectIds = $result->fetch();
2591
+        $result->closeCursor();
2592
+
2593
+        if (!isset($objectIds['id'])) {
2594
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2595
+        }
2596
+
2597
+        return (int)$objectIds['id'];
2598
+    }
2599
+
2600
+    /**
2601
+     * return legacy endpoint principal name to new principal name
2602
+     *
2603
+     * @param $principalUri
2604
+     * @param $toV2
2605
+     * @return string
2606
+     */
2607
+    private function convertPrincipal($principalUri, $toV2) {
2608
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2609
+            list(, $name) = Uri\split($principalUri);
2610
+            if ($toV2 === true) {
2611
+                return "principals/users/$name";
2612
+            }
2613
+            return "principals/$name";
2614
+        }
2615
+        return $principalUri;
2616
+    }
2617
+
2618
+    /**
2619
+     * adds information about an owner to the calendar data
2620
+     *
2621
+     * @param $calendarInfo
2622
+     */
2623
+    private function addOwnerPrincipal(&$calendarInfo) {
2624
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2625
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2626
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2627
+            $uri = $calendarInfo[$ownerPrincipalKey];
2628
+        } else {
2629
+            $uri = $calendarInfo['principaluri'];
2630
+        }
2631
+
2632
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2633
+        if (isset($principalInformation['{DAV:}displayname'])) {
2634
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2635
+        }
2636
+    }
2637 2637
 }
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224 224
 		}
225 225
 
226
-		return (int)$query->execute()->fetchColumn();
226
+		return (int) $query->execute()->fetchColumn();
227 227
 	}
228 228
 
229 229
 	/**
@@ -270,25 +270,25 @@  discard block
 block discarded – undo
270 270
 		$stmt = $query->execute();
271 271
 
272 272
 		$calendars = [];
273
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
273
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274 274
 
275 275
 			$components = [];
276 276
 			if ($row['components']) {
277
-				$components = explode(',',$row['components']);
277
+				$components = explode(',', $row['components']);
278 278
 			}
279 279
 
280 280
 			$calendar = [
281 281
 				'id' => $row['id'],
282 282
 				'uri' => $row['uri'],
283 283
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
284
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
285
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
286
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
288
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289 289
 			];
290 290
 
291
-			foreach($this->propertyMap as $xmlName=>$dbName) {
291
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
292 292
 				$calendar[$xmlName] = $row[$dbName];
293 293
 			}
294 294
 
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 		$principals = array_map(function($principal) {
309 309
 			return urldecode($principal);
310 310
 		}, $principals);
311
-		$principals[]= $principalUri;
311
+		$principals[] = $principalUri;
312 312
 
313 313
 		$fields = array_values($this->propertyMap);
314 314
 		$fields[] = 'a.id';
@@ -328,8 +328,8 @@  discard block
 block discarded – undo
328 328
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329 329
 			->execute();
330 330
 
331
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
-		while($row = $result->fetch()) {
331
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
332
+		while ($row = $result->fetch()) {
333 333
 			if ($row['principaluri'] === $principalUri) {
334 334
 				continue;
335 335
 			}
@@ -348,25 +348,25 @@  discard block
 block discarded – undo
348 348
 			}
349 349
 
350 350
 			list(, $name) = Uri\split($row['principaluri']);
351
-			$uri = $row['uri'] . '_shared_by_' . $name;
352
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
351
+			$uri = $row['uri'].'_shared_by_'.$name;
352
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
353 353
 			$components = [];
354 354
 			if ($row['components']) {
355
-				$components = explode(',',$row['components']);
355
+				$components = explode(',', $row['components']);
356 356
 			}
357 357
 			$calendar = [
358 358
 				'id' => $row['id'],
359 359
 				'uri' => $uri,
360 360
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
361
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
362
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
363
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366 366
 				$readOnlyPropertyName => $readOnly,
367 367
 			];
368 368
 
369
-			foreach($this->propertyMap as $xmlName=>$dbName) {
369
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
370 370
 				$calendar[$xmlName] = $row[$dbName];
371 371
 			}
372 372
 
@@ -399,21 +399,21 @@  discard block
 block discarded – undo
399 399
 			->orderBy('calendarorder', 'ASC');
400 400
 		$stmt = $query->execute();
401 401
 		$calendars = [];
402
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
402
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403 403
 			$components = [];
404 404
 			if ($row['components']) {
405
-				$components = explode(',',$row['components']);
405
+				$components = explode(',', $row['components']);
406 406
 			}
407 407
 			$calendar = [
408 408
 				'id' => $row['id'],
409 409
 				'uri' => $row['uri'],
410 410
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
412
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
413
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
415 415
 			];
416
-			foreach($this->propertyMap as $xmlName=>$dbName) {
416
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
417 417
 				$calendar[$xmlName] = $row[$dbName];
418 418
 			}
419 419
 
@@ -468,27 +468,27 @@  discard block
 block discarded – undo
468 468
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469 469
 			->execute();
470 470
 
471
-		while($row = $result->fetch()) {
471
+		while ($row = $result->fetch()) {
472 472
 			list(, $name) = Uri\split($row['principaluri']);
473
-			$row['displayname'] = $row['displayname'] . "($name)";
473
+			$row['displayname'] = $row['displayname']."($name)";
474 474
 			$components = [];
475 475
 			if ($row['components']) {
476
-				$components = explode(',',$row['components']);
476
+				$components = explode(',', $row['components']);
477 477
 			}
478 478
 			$calendar = [
479 479
 				'id' => $row['id'],
480 480
 				'uri' => $row['publicuri'],
481 481
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
482
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
483
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
484
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
486
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
488
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
489 489
 			];
490 490
 
491
-			foreach($this->propertyMap as $xmlName=>$dbName) {
491
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
492 492
 				$calendar[$xmlName] = $row[$dbName];
493 493
 			}
494 494
 
@@ -532,29 +532,29 @@  discard block
 block discarded – undo
532 532
 		$result->closeCursor();
533 533
 
534 534
 		if ($row === false) {
535
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
535
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
536 536
 		}
537 537
 
538 538
 		list(, $name) = Uri\split($row['principaluri']);
539
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
539
+		$row['displayname'] = $row['displayname'].' '."($name)";
540 540
 		$components = [];
541 541
 		if ($row['components']) {
542
-			$components = explode(',',$row['components']);
542
+			$components = explode(',', $row['components']);
543 543
 		}
544 544
 		$calendar = [
545 545
 			'id' => $row['id'],
546 546
 			'uri' => $row['publicuri'],
547 547
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
548
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
549
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
550
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
552
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
554
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
555 555
 		];
556 556
 
557
-		foreach($this->propertyMap as $xmlName=>$dbName) {
557
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
558 558
 			$calendar[$xmlName] = $row[$dbName];
559 559
 		}
560 560
 
@@ -594,20 +594,20 @@  discard block
 block discarded – undo
594 594
 
595 595
 		$components = [];
596 596
 		if ($row['components']) {
597
-			$components = explode(',',$row['components']);
597
+			$components = explode(',', $row['components']);
598 598
 		}
599 599
 
600 600
 		$calendar = [
601 601
 			'id' => $row['id'],
602 602
 			'uri' => $row['uri'],
603 603
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
605
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
606
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
608 608
 		];
609 609
 
610
-		foreach($this->propertyMap as $xmlName=>$dbName) {
610
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
611 611
 			$calendar[$xmlName] = $row[$dbName];
612 612
 		}
613 613
 
@@ -644,20 +644,20 @@  discard block
 block discarded – undo
644 644
 
645 645
 		$components = [];
646 646
 		if ($row['components']) {
647
-			$components = explode(',',$row['components']);
647
+			$components = explode(',', $row['components']);
648 648
 		}
649 649
 
650 650
 		$calendar = [
651 651
 			'id' => $row['id'],
652 652
 			'uri' => $row['uri'],
653 653
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
655
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
656
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
658 658
 		];
659 659
 
660
-		foreach($this->propertyMap as $xmlName=>$dbName) {
660
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
661 661
 			$calendar[$xmlName] = $row[$dbName];
662 662
 		}
663 663
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 			->from('calendarsubscriptions')
684 684
 			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685 685
 			->orderBy('calendarorder', 'asc');
686
-		$stmt =$query->execute();
686
+		$stmt = $query->execute();
687 687
 
688 688
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
689 689
 		$stmt->closeCursor();
@@ -697,11 +697,11 @@  discard block
 block discarded – undo
697 697
 			'principaluri' => $row['principaluri'],
698 698
 			'source'       => $row['source'],
699 699
 			'lastmodified' => $row['lastmodified'],
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
700
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
702 702
 		];
703 703
 
704
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
704
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705 705
 			if (!is_null($row[$dbName])) {
706 706
 				$subscription[$xmlName] = $row[$dbName];
707 707
 			}
@@ -736,21 +736,21 @@  discard block
 block discarded – undo
736 736
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737 737
 		if (isset($properties[$sccs])) {
738 738
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
739
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740 740
 			}
741
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
741
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
742 742
 		} else if (isset($properties['components'])) {
743 743
 			// Allow to provide components internally without having
744 744
 			// to create a SupportedCalendarComponentSet object
745 745
 			$values['components'] = $properties['components'];
746 746
 		}
747 747
 
748
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
748
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
749 749
 		if (isset($properties[$transp])) {
750 750
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751 751
 		}
752 752
 
753
-		foreach($this->propertyMap as $xmlName=>$dbName) {
753
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
754 754
 			if (isset($properties[$xmlName])) {
755 755
 				$values[$dbName] = $properties[$xmlName];
756 756
 			}
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 
759 759
 		$query = $this->db->getQueryBuilder();
760 760
 		$query->insert('calendars');
761
-		foreach($values as $column => $value) {
761
+		foreach ($values as $column => $value) {
762 762
 			$query->setValue($column, $query->createNamedParameter($value));
763 763
 		}
764 764
 		$query->execute();
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 	 */
793 793
 	function updateCalendar($calendarId, PropPatch $propPatch) {
794 794
 		$supportedProperties = array_keys($this->propertyMap);
795
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
795
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
796 796
 
797 797
 		/**
798 798
 		 * @suppress SqlInjectionChecker
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 			foreach ($mutations as $propertyName => $propertyValue) {
803 803
 
804 804
 				switch ($propertyName) {
805
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
805
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
806 806
 						$fieldName = 'transparent';
807 807
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808 808
 						break;
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 	 * @param int $calendarType
912 912
 	 * @return array
913 913
 	 */
914
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
914
+	public function getCalendarObjects($id, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
915 915
 		$query = $this->db->getQueryBuilder();
916 916
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917 917
 			->from('calendarobjects')
@@ -920,16 +920,16 @@  discard block
 block discarded – undo
920 920
 		$stmt = $query->execute();
921 921
 
922 922
 		$result = [];
923
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
923
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924 924
 			$result[] = [
925 925
 				'id'           => $row['id'],
926 926
 				'uri'          => $row['uri'],
927 927
 				'lastmodified' => $row['lastmodified'],
928
-				'etag'         => '"' . $row['etag'] . '"',
928
+				'etag'         => '"'.$row['etag'].'"',
929 929
 				'calendarid'   => $row['calendarid'],
930
-				'size'         => (int)$row['size'],
930
+				'size'         => (int) $row['size'],
931 931
 				'component'    => strtolower($row['componenttype']),
932
-				'classification'=> (int)$row['classification']
932
+				'classification'=> (int) $row['classification']
933 933
 			];
934 934
 		}
935 935
 
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
 	 * @param int $calendarType
954 954
 	 * @return array|null
955 955
 	 */
956
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
956
+	public function getCalendarObject($id, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
957 957
 		$query = $this->db->getQueryBuilder();
958 958
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959 959
 			->from('calendarobjects')
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 		$stmt = $query->execute();
964 964
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
965 965
 
966
-		if(!$row) {
966
+		if (!$row) {
967 967
 			return null;
968 968
 		}
969 969
 
@@ -971,12 +971,12 @@  discard block
 block discarded – undo
971 971
 			'id'            => $row['id'],
972 972
 			'uri'           => $row['uri'],
973 973
 			'lastmodified'  => $row['lastmodified'],
974
-			'etag'          => '"' . $row['etag'] . '"',
974
+			'etag'          => '"'.$row['etag'].'"',
975 975
 			'calendarid'    => $row['calendarid'],
976
-			'size'          => (int)$row['size'],
976
+			'size'          => (int) $row['size'],
977 977
 			'calendardata'  => $this->readBlob($row['calendardata']),
978 978
 			'component'     => strtolower($row['componenttype']),
979
-			'classification'=> (int)$row['classification']
979
+			'classification'=> (int) $row['classification']
980 980
 		];
981 981
 	}
982 982
 
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
 	 * @param int $calendarType
994 994
 	 * @return array
995 995
 	 */
996
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
996
+	public function getMultipleCalendarObjects($id, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
997 997
 		if (empty($uris)) {
998 998
 			return [];
999 999
 		}
@@ -1017,12 +1017,12 @@  discard block
 block discarded – undo
1017 1017
 					'id'           => $row['id'],
1018 1018
 					'uri'          => $row['uri'],
1019 1019
 					'lastmodified' => $row['lastmodified'],
1020
-					'etag'         => '"' . $row['etag'] . '"',
1020
+					'etag'         => '"'.$row['etag'].'"',
1021 1021
 					'calendarid'   => $row['calendarid'],
1022
-					'size'         => (int)$row['size'],
1022
+					'size'         => (int) $row['size'],
1023 1023
 					'calendardata' => $this->readBlob($row['calendardata']),
1024 1024
 					'component'    => strtolower($row['componenttype']),
1025
-					'classification' => (int)$row['classification']
1025
+					'classification' => (int) $row['classification']
1026 1026
 				];
1027 1027
 			}
1028 1028
 			$result->closeCursor();
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
 	 * @param int $calendarType
1051 1051
 	 * @return string
1052 1052
 	 */
1053
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1053
+	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1054 1054
 		$extraData = $this->getDenormalizedData($calendarData);
1055 1055
 
1056 1056
 		$q = $this->db->getQueryBuilder();
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 		}
1112 1112
 		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1113 1113
 
1114
-		return '"' . $extraData['etag'] . '"';
1114
+		return '"'.$extraData['etag'].'"';
1115 1115
 	}
1116 1116
 
1117 1117
 	/**
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 	 * @param int $calendarType
1134 1134
 	 * @return string
1135 1135
 	 */
1136
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1136
+	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1137 1137
 		$extraData = $this->getDenormalizedData($calendarData);
1138 1138
 		$query = $this->db->getQueryBuilder();
1139 1139
 		$query->update('calendarobjects')
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 		}
1180 1180
 		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1181 1181
 
1182
-		return '"' . $extraData['etag'] . '"';
1182
+		return '"'.$extraData['etag'].'"';
1183 1183
 	}
1184 1184
 
1185 1185
 	/**
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 	 * @param int $calendarType
1210 1210
 	 * @return void
1211 1211
 	 */
1212
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1212
+	function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1213 1213
 		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1214 1214
 		if (is_array($data)) {
1215 1215
 			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
@@ -1293,7 +1293,7 @@  discard block
 block discarded – undo
1293 1293
 	 * @param int $calendarType
1294 1294
 	 * @return array
1295 1295
 	 */
1296
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1296
+	public function calendarQuery($id, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1297 1297
 		$componentType = null;
1298 1298
 		$requirePostFilter = true;
1299 1299
 		$timeRange = null;
@@ -1347,13 +1347,13 @@  discard block
 block discarded – undo
1347 1347
 		$stmt = $query->execute();
1348 1348
 
1349 1349
 		$result = [];
1350
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1350
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1351 1351
 			if ($requirePostFilter) {
1352 1352
 				// validateFilterForObject will parse the calendar data
1353 1353
 				// catch parsing errors
1354 1354
 				try {
1355 1355
 					$matches = $this->validateFilterForObject($row, $filters);
1356
-				} catch(ParseException $ex) {
1356
+				} catch (ParseException $ex) {
1357 1357
 					$this->logger->logException($ex, [
1358 1358
 						'app' => 'dav',
1359 1359
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
@@ -1388,14 +1388,14 @@  discard block
 block discarded – undo
1388 1388
 	 * @param integer|null $offset
1389 1389
 	 * @return array
1390 1390
 	 */
1391
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1391
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1392 1392
 		$calendars = $this->getCalendarsForUser($principalUri);
1393 1393
 		$ownCalendars = [];
1394 1394
 		$sharedCalendars = [];
1395 1395
 
1396 1396
 		$uriMapper = [];
1397 1397
 
1398
-		foreach($calendars as $calendar) {
1398
+		foreach ($calendars as $calendar) {
1399 1399
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1400 1400
 				$ownCalendars[] = $calendar['id'];
1401 1401
 			} else {
@@ -1410,14 +1410,14 @@  discard block
 block discarded – undo
1410 1410
 		$query = $this->db->getQueryBuilder();
1411 1411
 		// Calendar id expressions
1412 1412
 		$calendarExpressions = [];
1413
-		foreach($ownCalendars as $id) {
1413
+		foreach ($ownCalendars as $id) {
1414 1414
 			$calendarExpressions[] = $query->expr()->andX(
1415 1415
 				$query->expr()->eq('c.calendarid',
1416 1416
 					$query->createNamedParameter($id)),
1417 1417
 				$query->expr()->eq('c.calendartype',
1418 1418
 						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1419 1419
 		}
1420
-		foreach($sharedCalendars as $id) {
1420
+		foreach ($sharedCalendars as $id) {
1421 1421
 			$calendarExpressions[] = $query->expr()->andX(
1422 1422
 				$query->expr()->eq('c.calendarid',
1423 1423
 					$query->createNamedParameter($id)),
@@ -1435,7 +1435,7 @@  discard block
 block discarded – undo
1435 1435
 
1436 1436
 		// Component expressions
1437 1437
 		$compExpressions = [];
1438
-		foreach($filters['comps'] as $comp) {
1438
+		foreach ($filters['comps'] as $comp) {
1439 1439
 			$compExpressions[] = $query->expr()
1440 1440
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1441 1441
 		}
@@ -1454,13 +1454,13 @@  discard block
 block discarded – undo
1454 1454
 		}
1455 1455
 
1456 1456
 		$propParamExpressions = [];
1457
-		foreach($filters['props'] as $prop) {
1457
+		foreach ($filters['props'] as $prop) {
1458 1458
 			$propParamExpressions[] = $query->expr()->andX(
1459 1459
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1460 1460
 				$query->expr()->isNull('i.parameter')
1461 1461
 			);
1462 1462
 		}
1463
-		foreach($filters['params'] as $param) {
1463
+		foreach ($filters['params'] as $param) {
1464 1464
 			$propParamExpressions[] = $query->expr()->andX(
1465 1465
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1466 1466
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1492,8 +1492,8 @@  discard block
 block discarded – undo
1492 1492
 		$stmt = $query->execute();
1493 1493
 
1494 1494
 		$result = [];
1495
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1496
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1495
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1496
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1497 1497
 			if (!in_array($path, $result)) {
1498 1498
 				$result[] = $path;
1499 1499
 			}
@@ -1533,7 +1533,7 @@  discard block
 block discarded – undo
1533 1533
 		}
1534 1534
 
1535 1535
 		$or = $innerQuery->expr()->orX();
1536
-		foreach($searchProperties as $searchProperty) {
1536
+		foreach ($searchProperties as $searchProperty) {
1537 1537
 			$or->add($innerQuery->expr()->eq('op.name',
1538 1538
 				$outerQuery->createNamedParameter($searchProperty)));
1539 1539
 		}
@@ -1541,8 +1541,8 @@  discard block
 block discarded – undo
1541 1541
 
1542 1542
 		if ($pattern !== '') {
1543 1543
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1544
-				$outerQuery->createNamedParameter('%' .
1545
-					$this->db->escapeLikeParameter($pattern) . '%')));
1544
+				$outerQuery->createNamedParameter('%'.
1545
+					$this->db->escapeLikeParameter($pattern).'%')));
1546 1546
 		}
1547 1547
 
1548 1548
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1562,7 +1562,7 @@  discard block
 block discarded – undo
1562 1562
 
1563 1563
 		if (isset($options['types'])) {
1564 1564
 			$or = $outerQuery->expr()->orX();
1565
-			foreach($options['types'] as $type) {
1565
+			foreach ($options['types'] as $type) {
1566 1566
 				$or->add($outerQuery->expr()->eq('componenttype',
1567 1567
 					$outerQuery->createNamedParameter($type)));
1568 1568
 			}
@@ -1587,7 +1587,7 @@  discard block
 block discarded – undo
1587 1587
 			$comps = $calendarData->getComponents();
1588 1588
 			$objects = [];
1589 1589
 			$timezones = [];
1590
-			foreach($comps as $comp) {
1590
+			foreach ($comps as $comp) {
1591 1591
 				if ($comp instanceof VTimeZone) {
1592 1592
 					$timezones[] = $comp;
1593 1593
 				} else {
@@ -1624,7 +1624,7 @@  discard block
 block discarded – undo
1624 1624
 		});
1625 1625
 		$validationRules = $comp->getValidationRules();
1626 1626
 
1627
-		foreach($subComponents as $subComponent) {
1627
+		foreach ($subComponents as $subComponent) {
1628 1628
 			$name = $subComponent->name;
1629 1629
 			if (!isset($data[$name])) {
1630 1630
 				$data[$name] = [];
@@ -1632,7 +1632,7 @@  discard block
 block discarded – undo
1632 1632
 			$data[$name][] = $this->transformSearchData($subComponent);
1633 1633
 		}
1634 1634
 
1635
-		foreach($properties as $property) {
1635
+		foreach ($properties as $property) {
1636 1636
 			$name = $property->name;
1637 1637
 			if (!isset($validationRules[$name])) {
1638 1638
 				$validationRules[$name] = '*';
@@ -1703,7 +1703,7 @@  discard block
 block discarded – undo
1703 1703
 		$stmt = $query->execute();
1704 1704
 
1705 1705
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1706
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1706
+			return $row['calendaruri'].'/'.$row['objecturi'];
1707 1707
 		}
1708 1708
 
1709 1709
 		return null;
@@ -1766,10 +1766,10 @@  discard block
 block discarded – undo
1766 1766
 	 * @param int $calendarType
1767 1767
 	 * @return array
1768 1768
 	 */
1769
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1769
+	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1770 1770
 		// Current synctoken
1771 1771
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1772
-		$stmt->execute([ $calendarId ]);
1772
+		$stmt->execute([$calendarId]);
1773 1773
 		$currentToken = $stmt->fetchColumn(0);
1774 1774
 
1775 1775
 		if (is_null($currentToken)) {
@@ -1786,8 +1786,8 @@  discard block
 block discarded – undo
1786 1786
 		if ($syncToken) {
1787 1787
 
1788 1788
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1789
-			if ($limit>0) {
1790
-				$query.= " LIMIT " . (int)$limit;
1789
+			if ($limit > 0) {
1790
+				$query .= " LIMIT ".(int) $limit;
1791 1791
 			}
1792 1792
 
1793 1793
 			// Fetching all changes
@@ -1798,15 +1798,15 @@  discard block
 block discarded – undo
1798 1798
 
1799 1799
 			// This loop ensures that any duplicates are overwritten, only the
1800 1800
 			// last change on a node is relevant.
1801
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1801
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1802 1802
 
1803 1803
 				$changes[$row['uri']] = $row['operation'];
1804 1804
 
1805 1805
 			}
1806 1806
 
1807
-			foreach($changes as $uri => $operation) {
1807
+			foreach ($changes as $uri => $operation) {
1808 1808
 
1809
-				switch($operation) {
1809
+				switch ($operation) {
1810 1810
 					case 1 :
1811 1811
 						$result['added'][] = $uri;
1812 1812
 						break;
@@ -1877,10 +1877,10 @@  discard block
 block discarded – undo
1877 1877
 			->from('calendarsubscriptions')
1878 1878
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1879 1879
 			->orderBy('calendarorder', 'asc');
1880
-		$stmt =$query->execute();
1880
+		$stmt = $query->execute();
1881 1881
 
1882 1882
 		$subscriptions = [];
1883
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1883
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1884 1884
 
1885 1885
 			$subscription = [
1886 1886
 				'id'           => $row['id'],
@@ -1889,11 +1889,11 @@  discard block
 block discarded – undo
1889 1889
 				'source'       => $row['source'],
1890 1890
 				'lastmodified' => $row['lastmodified'],
1891 1891
 
1892
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1893
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1892
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1893
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
1894 1894
 			];
1895 1895
 
1896
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1896
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1897 1897
 				if (!is_null($row[$dbName])) {
1898 1898
 					$subscription[$xmlName] = $row[$dbName];
1899 1899
 				}
@@ -1932,7 +1932,7 @@  discard block
 block discarded – undo
1932 1932
 
1933 1933
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1934 1934
 
1935
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1935
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1936 1936
 			if (array_key_exists($xmlName, $properties)) {
1937 1937
 					$values[$dbName] = $properties[$xmlName];
1938 1938
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1992,7 +1992,7 @@  discard block
 block discarded – undo
1992 1992
 
1993 1993
 			$newValues = [];
1994 1994
 
1995
-			foreach($mutations as $propertyName=>$propertyValue) {
1995
+			foreach ($mutations as $propertyName=>$propertyValue) {
1996 1996
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1997 1997
 					$newValues['source'] = $propertyValue->getHref();
1998 1998
 				} else {
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
 			$query = $this->db->getQueryBuilder();
2005 2005
 			$query->update('calendarsubscriptions')
2006 2006
 				->set('lastmodified', $query->createNamedParameter(time()));
2007
-			foreach($newValues as $fieldName=>$value) {
2007
+			foreach ($newValues as $fieldName=>$value) {
2008 2008
 				$query->set($fieldName, $query->createNamedParameter($value));
2009 2009
 			}
2010 2010
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -2085,7 +2085,7 @@  discard block
 block discarded – undo
2085 2085
 
2086 2086
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2087 2087
 
2088
-		if(!$row) {
2088
+		if (!$row) {
2089 2089
 			return null;
2090 2090
 		}
2091 2091
 
@@ -2093,8 +2093,8 @@  discard block
 block discarded – undo
2093 2093
 				'uri'          => $row['uri'],
2094 2094
 				'calendardata' => $row['calendardata'],
2095 2095
 				'lastmodified' => $row['lastmodified'],
2096
-				'etag'         => '"' . $row['etag'] . '"',
2097
-				'size'         => (int)$row['size'],
2096
+				'etag'         => '"'.$row['etag'].'"',
2097
+				'size'         => (int) $row['size'],
2098 2098
 		];
2099 2099
 	}
2100 2100
 
@@ -2117,13 +2117,13 @@  discard block
 block discarded – undo
2117 2117
 				->execute();
2118 2118
 
2119 2119
 		$result = [];
2120
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2120
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2121 2121
 			$result[] = [
2122 2122
 					'calendardata' => $row['calendardata'],
2123 2123
 					'uri'          => $row['uri'],
2124 2124
 					'lastmodified' => $row['lastmodified'],
2125
-					'etag'         => '"' . $row['etag'] . '"',
2126
-					'size'         => (int)$row['size'],
2125
+					'etag'         => '"'.$row['etag'].'"',
2126
+					'size'         => (int) $row['size'],
2127 2127
 			];
2128 2128
 		}
2129 2129
 
@@ -2176,14 +2176,14 @@  discard block
 block discarded – undo
2176 2176
 	 * @param int $calendarType
2177 2177
 	 * @return void
2178 2178
 	 */
2179
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2180
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2179
+	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2180
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2181 2181
 
2182 2182
 		$query = $this->db->getQueryBuilder();
2183 2183
 		$query->select('synctoken')
2184 2184
 			->from($table)
2185 2185
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2186
-		$syncToken = (int)$query->execute()->fetchColumn();
2186
+		$syncToken = (int) $query->execute()->fetchColumn();
2187 2187
 
2188 2188
 		$query = $this->db->getQueryBuilder();
2189 2189
 		$query->insert('calendarchanges')
@@ -2227,10 +2227,10 @@  discard block
 block discarded – undo
2227 2227
 		$lastOccurrence = null;
2228 2228
 		$uid = null;
2229 2229
 		$classification = self::CLASSIFICATION_PUBLIC;
2230
-		foreach($vObject->getComponents() as $component) {
2231
-			if ($component->name!=='VTIMEZONE') {
2230
+		foreach ($vObject->getComponents() as $component) {
2231
+			if ($component->name !== 'VTIMEZONE') {
2232 2232
 				$componentType = $component->name;
2233
-				$uid = (string)$component->UID;
2233
+				$uid = (string) $component->UID;
2234 2234
 				break;
2235 2235
 			}
2236 2236
 		}
@@ -2255,13 +2255,13 @@  discard block
 block discarded – undo
2255 2255
 					$lastOccurrence = $firstOccurrence;
2256 2256
 				}
2257 2257
 			} else {
2258
-				$it = new EventIterator($vObject, (string)$component->UID);
2258
+				$it = new EventIterator($vObject, (string) $component->UID);
2259 2259
 				$maxDate = new \DateTime(self::MAX_DATE);
2260 2260
 				if ($it->isInfinite()) {
2261 2261
 					$lastOccurrence = $maxDate->getTimestamp();
2262 2262
 				} else {
2263 2263
 					$end = $it->getDtEnd();
2264
-					while($it->valid() && $end < $maxDate) {
2264
+					while ($it->valid() && $end < $maxDate) {
2265 2265
 						$end = $it->getDtEnd();
2266 2266
 						$it->next();
2267 2267
 
@@ -2331,7 +2331,7 @@  discard block
 block discarded – undo
2331 2331
 	 * @param int $calendarType
2332 2332
 	 * @return array
2333 2333
 	 */
2334
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2334
+	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2335 2335
 		return $this->calendarSharingBackend->getShares($resourceId);
2336 2336
 	}
2337 2337
 
@@ -2408,7 +2408,7 @@  discard block
 block discarded – undo
2408 2408
 	 * @param string $calendarData
2409 2409
 	 * @param int $calendarType
2410 2410
 	 */
2411
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2411
+	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2412 2412
 		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2413 2413
 
2414 2414
 		try {
@@ -2486,7 +2486,7 @@  discard block
 block discarded – undo
2486 2486
 			->execute();
2487 2487
 
2488 2488
 		$ids = $result->fetchAll();
2489
-		foreach($ids as $id) {
2489
+		foreach ($ids as $id) {
2490 2490
 			$this->deleteCalendar($id['id']);
2491 2491
 		}
2492 2492
 	}
@@ -2503,7 +2503,7 @@  discard block
 block discarded – undo
2503 2503
 		$stmt = $query->execute();
2504 2504
 
2505 2505
 		$uris = [];
2506
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2506
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2507 2507
 			$uris[] = $row['uri'];
2508 2508
 		}
2509 2509
 		$stmt->closeCursor();
@@ -2524,7 +2524,7 @@  discard block
 block discarded – undo
2524 2524
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2525 2525
 			->execute();
2526 2526
 
2527
-		foreach($uris as $uri) {
2527
+		foreach ($uris as $uri) {
2528 2528
 			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2529 2529
 		}
2530 2530
 	}
@@ -2591,10 +2591,10 @@  discard block
 block discarded – undo
2591 2591
 		$result->closeCursor();
2592 2592
 
2593 2593
 		if (!isset($objectIds['id'])) {
2594
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2594
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2595 2595
 		}
2596 2596
 
2597
-		return (int)$objectIds['id'];
2597
+		return (int) $objectIds['id'];
2598 2598
 	}
2599 2599
 
2600 2600
 	/**
@@ -2621,8 +2621,8 @@  discard block
 block discarded – undo
2621 2621
 	 * @param $calendarInfo
2622 2622
 	 */
2623 2623
 	private function addOwnerPrincipal(&$calendarInfo) {
2624
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2625
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2624
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2625
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2626 2626
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2627 2627
 			$uri = $calendarInfo[$ownerPrincipalKey];
2628 2628
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/Notifier.php 2 patches
Indentation   +272 added lines, -272 removed lines patch added patch discarded remove patch
@@ -41,276 +41,276 @@
 block discarded – undo
41 41
  */
42 42
 class Notifier implements INotifier {
43 43
 
44
-	/** @var IFactory */
45
-	private $l10nFactory;
46
-
47
-	/** @var IURLGenerator */
48
-	private $urlGenerator;
49
-
50
-	/** @var IL10N */
51
-	private $l10n;
52
-
53
-	/** @var ITimeFactory */
54
-	private $timeFactory;
55
-
56
-	/**
57
-	 * Notifier constructor.
58
-	 *
59
-	 * @param IFactory $factory
60
-	 * @param IURLGenerator $urlGenerator
61
-	 * @param ITimeFactory $timeFactory
62
-	 */
63
-	public function __construct(IFactory $factory,
64
-								IURLGenerator $urlGenerator,
65
-								ITimeFactory $timeFactory) {
66
-		$this->l10nFactory = $factory;
67
-		$this->urlGenerator = $urlGenerator;
68
-		$this->timeFactory = $timeFactory;
69
-	}
70
-
71
-	/**
72
-	 * Identifier of the notifier, only use [a-z0-9_]
73
-	 *
74
-	 * @return string
75
-	 * @since 17.0.0
76
-	 */
77
-	public function getID():string {
78
-		return Application::APP_ID;
79
-	}
80
-
81
-	/**
82
-	 * Human readable name describing the notifier
83
-	 *
84
-	 * @return string
85
-	 * @since 17.0.0
86
-	 */
87
-	public function getName():string {
88
-		return $this->l10nFactory->get('dav')->t('Calendar');
89
-	}
90
-
91
-	/**
92
-	 * Prepare sending the notification
93
-	 *
94
-	 * @param INotification $notification
95
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
96
-	 * @return INotification
97
-	 * @throws \Exception
98
-	 */
99
-	public function prepare(INotification $notification,
100
-							string $languageCode):INotification {
101
-		if ($notification->getApp() !== Application::APP_ID) {
102
-			throw new \InvalidArgumentException('Notification not from this app');
103
-		}
104
-
105
-		// Read the language from the notification
106
-		$this->l10n = $this->l10nFactory->get('dav', $languageCode);
107
-
108
-		// Handle notifier subjects
109
-		switch($notification->getSubject()) {
110
-			case 'calendar_reminder':
111
-				return $this->prepareReminderNotification($notification);
112
-
113
-			default:
114
-				throw new \InvalidArgumentException('Unknown subject');
115
-
116
-		}
117
-	}
118
-
119
-	/**
120
-	 * @param INotification $notification
121
-	 * @return INotification
122
-	 */
123
-	private function prepareReminderNotification(INotification $notification):INotification {
124
-		$imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg');
125
-		$iconUrl = $this->urlGenerator->getAbsoluteURL($imagePath);
126
-		$notification->setIcon($iconUrl);
127
-
128
-		$this->prepareNotificationSubject($notification);
129
-		$this->prepareNotificationMessage($notification);
130
-
131
-		return $notification;
132
-	}
133
-
134
-	/**
135
-	 * Sets the notification subject based on the parameters set in PushProvider
136
-	 *
137
-	 * @param INotification $notification
138
-	 */
139
-	private function prepareNotificationSubject(INotification $notification): void {
140
-		$parameters = $notification->getSubjectParameters();
141
-
142
-		$startTime = \DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
143
-		$now = $this->timeFactory->getDateTime();
144
-		$title = $this->getTitleFromParameters($parameters);
145
-
146
-		$diff = $startTime->diff($now);
147
-		if ($diff === false) {
148
-			return;
149
-		}
150
-
151
-		$components = [];
152
-		if ($diff->y) {
153
-			$components[] = $this->l10n->n('%n year', '%n years', $diff->y);
154
-		}
155
-		if ($diff->m) {
156
-			$components[] = $this->l10n->n('%n month', '%n months', $diff->m);
157
-		}
158
-		if ($diff->d) {
159
-			$components[] = $this->l10n->n('%n day', '%n days', $diff->d);
160
-		}
161
-		if ($diff->h) {
162
-			$components[] = $this->l10n->n('%n hour', '%n hours', $diff->h);
163
-		}
164
-		if ($diff->i) {
165
-			$components[] = $this->l10n->n('%n minute', '%n minutes', $diff->i);
166
-		}
167
-
168
-		// Limiting to the first three components to prevent
169
-		// the string from getting too long
170
-		$firstThreeComponents = array_slice($components, 0, 2);
171
-		$diffLabel = implode(', ', $firstThreeComponents);
172
-
173
-		if ($diff->invert) {
174
-			$title = $this->l10n->t('%s (in %s)', [$title, $diffLabel]);
175
-		} else {
176
-			$title = $this->l10n->t('%s (%s ago)', [$title, $diffLabel]);
177
-		}
178
-
179
-		$notification->setParsedSubject($title);
180
-	}
181
-
182
-	/**
183
-	 * Sets the notification message based on the parameters set in PushProvider
184
-	 *
185
-	 * @param INotification $notification
186
-	 */
187
-	private function prepareNotificationMessage(INotification $notification): void {
188
-		$parameters = $notification->getMessageParameters();
189
-
190
-		$description = [
191
-			$this->l10n->t('Calendar: %s', $parameters['calendar_displayname']),
192
-			$this->l10n->t('Date: %s', $this->generateDateString($parameters)),
193
-		];
194
-		if ($parameters['description']) {
195
-			$description[] = $this->l10n->t('Description: %s', $parameters['description']);
196
-		}
197
-		if ($parameters['location']) {
198
-			$description[] = $this->l10n->t('Where: %s', $parameters['location']);
199
-		}
200
-
201
-		$message = implode("\r\n", $description);
202
-		$notification->setParsedMessage($message);
203
-	}
204
-
205
-	/**
206
-	 * @param array $parameters
207
-	 * @return string
208
-	 */
209
-	private function getTitleFromParameters(array $parameters):string {
210
-		return $parameters['title'] ?? $this->l10n->t('Untitled event');
211
-	}
212
-
213
-	/**
214
-	 * @param array $parameters
215
-	 * @return string
216
-	 * @throws \Exception
217
-	 */
218
-	private function generateDateString(array $parameters):string {
219
-		$startDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
220
-		$endDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['end_atom']);
221
-		$isAllDay = $parameters['all_day'];
222
-		$diff = $startDateTime->diff($endDateTime);
223
-
224
-		if ($isAllDay) {
225
-			// One day event
226
-			if ($diff->days === 1) {
227
-				return $this->getDateString($startDateTime);
228
-			}
229
-
230
-			return implode(' - ', [
231
-				$this->getDateString($startDateTime),
232
-				$this->getDateString($endDateTime),
233
-			]);
234
-		}
235
-
236
-		$startTimezone = $endTimezone = null;
237
-		if (!$parameters['start_is_floating']) {
238
-			$startTimezone = $parameters['start_timezone'];
239
-			$endTimezone = $parameters['end_timezone'];
240
-		}
241
-
242
-		$localeStart = implode(', ', [
243
-			$this->getWeekDayName($startDateTime),
244
-			$this->getDateTimeString($startDateTime)
245
-		]);
246
-
247
-		// always show full date with timezone if timezones are different
248
-		if ($startTimezone !== $endTimezone) {
249
-			$localeEnd = implode(', ', [
250
-				$this->getWeekDayName($endDateTime),
251
-				$this->getDateTimeString($endDateTime)
252
-			]);
253
-
254
-			return $localeStart
255
-				. ' (' . $startTimezone . ') '
256
-				. ' - '
257
-				. $localeEnd
258
-				. ' (' . $endTimezone . ')';
259
-		}
260
-
261
-		// Show only the time if the day is the same
262
-		$localeEnd = $this->isDayEqual($startDateTime, $endDateTime)
263
-			? $this->getTimeString($endDateTime)
264
-			: implode(', ', [
265
-				$this->getWeekDayName($endDateTime),
266
-				$this->getDateTimeString($endDateTime)
267
-			]);
268
-
269
-		return $localeStart
270
-			. ' - '
271
-			. $localeEnd
272
-			. ' (' . $startTimezone . ')';
273
-	}
274
-
275
-	/**
276
-	 * @param DateTime $dtStart
277
-	 * @param DateTime $dtEnd
278
-	 * @return bool
279
-	 */
280
-	private function isDayEqual(DateTime $dtStart,
281
-								DateTime $dtEnd):bool {
282
-		return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
283
-	}
284
-
285
-	/**
286
-	 * @param DateTime $dt
287
-	 * @return string
288
-	 */
289
-	private function getWeekDayName(DateTime $dt):string {
290
-		return $this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
291
-	}
292
-
293
-	/**
294
-	 * @param DateTime $dt
295
-	 * @return string
296
-	 */
297
-	private function getDateString(DateTime $dt):string {
298
-		return $this->l10n->l('date', $dt, ['width' => 'medium']);
299
-	}
300
-
301
-	/**
302
-	 * @param DateTime $dt
303
-	 * @return string
304
-	 */
305
-	private function getDateTimeString(DateTime $dt):string {
306
-		return $this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
307
-	}
308
-
309
-	/**
310
-	 * @param DateTime $dt
311
-	 * @return string
312
-	 */
313
-	private function getTimeString(DateTime $dt):string {
314
-		return $this->l10n->l('time', $dt, ['width' => 'short']);
315
-	}
44
+    /** @var IFactory */
45
+    private $l10nFactory;
46
+
47
+    /** @var IURLGenerator */
48
+    private $urlGenerator;
49
+
50
+    /** @var IL10N */
51
+    private $l10n;
52
+
53
+    /** @var ITimeFactory */
54
+    private $timeFactory;
55
+
56
+    /**
57
+     * Notifier constructor.
58
+     *
59
+     * @param IFactory $factory
60
+     * @param IURLGenerator $urlGenerator
61
+     * @param ITimeFactory $timeFactory
62
+     */
63
+    public function __construct(IFactory $factory,
64
+                                IURLGenerator $urlGenerator,
65
+                                ITimeFactory $timeFactory) {
66
+        $this->l10nFactory = $factory;
67
+        $this->urlGenerator = $urlGenerator;
68
+        $this->timeFactory = $timeFactory;
69
+    }
70
+
71
+    /**
72
+     * Identifier of the notifier, only use [a-z0-9_]
73
+     *
74
+     * @return string
75
+     * @since 17.0.0
76
+     */
77
+    public function getID():string {
78
+        return Application::APP_ID;
79
+    }
80
+
81
+    /**
82
+     * Human readable name describing the notifier
83
+     *
84
+     * @return string
85
+     * @since 17.0.0
86
+     */
87
+    public function getName():string {
88
+        return $this->l10nFactory->get('dav')->t('Calendar');
89
+    }
90
+
91
+    /**
92
+     * Prepare sending the notification
93
+     *
94
+     * @param INotification $notification
95
+     * @param string $languageCode The code of the language that should be used to prepare the notification
96
+     * @return INotification
97
+     * @throws \Exception
98
+     */
99
+    public function prepare(INotification $notification,
100
+                            string $languageCode):INotification {
101
+        if ($notification->getApp() !== Application::APP_ID) {
102
+            throw new \InvalidArgumentException('Notification not from this app');
103
+        }
104
+
105
+        // Read the language from the notification
106
+        $this->l10n = $this->l10nFactory->get('dav', $languageCode);
107
+
108
+        // Handle notifier subjects
109
+        switch($notification->getSubject()) {
110
+            case 'calendar_reminder':
111
+                return $this->prepareReminderNotification($notification);
112
+
113
+            default:
114
+                throw new \InvalidArgumentException('Unknown subject');
115
+
116
+        }
117
+    }
118
+
119
+    /**
120
+     * @param INotification $notification
121
+     * @return INotification
122
+     */
123
+    private function prepareReminderNotification(INotification $notification):INotification {
124
+        $imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg');
125
+        $iconUrl = $this->urlGenerator->getAbsoluteURL($imagePath);
126
+        $notification->setIcon($iconUrl);
127
+
128
+        $this->prepareNotificationSubject($notification);
129
+        $this->prepareNotificationMessage($notification);
130
+
131
+        return $notification;
132
+    }
133
+
134
+    /**
135
+     * Sets the notification subject based on the parameters set in PushProvider
136
+     *
137
+     * @param INotification $notification
138
+     */
139
+    private function prepareNotificationSubject(INotification $notification): void {
140
+        $parameters = $notification->getSubjectParameters();
141
+
142
+        $startTime = \DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
143
+        $now = $this->timeFactory->getDateTime();
144
+        $title = $this->getTitleFromParameters($parameters);
145
+
146
+        $diff = $startTime->diff($now);
147
+        if ($diff === false) {
148
+            return;
149
+        }
150
+
151
+        $components = [];
152
+        if ($diff->y) {
153
+            $components[] = $this->l10n->n('%n year', '%n years', $diff->y);
154
+        }
155
+        if ($diff->m) {
156
+            $components[] = $this->l10n->n('%n month', '%n months', $diff->m);
157
+        }
158
+        if ($diff->d) {
159
+            $components[] = $this->l10n->n('%n day', '%n days', $diff->d);
160
+        }
161
+        if ($diff->h) {
162
+            $components[] = $this->l10n->n('%n hour', '%n hours', $diff->h);
163
+        }
164
+        if ($diff->i) {
165
+            $components[] = $this->l10n->n('%n minute', '%n minutes', $diff->i);
166
+        }
167
+
168
+        // Limiting to the first three components to prevent
169
+        // the string from getting too long
170
+        $firstThreeComponents = array_slice($components, 0, 2);
171
+        $diffLabel = implode(', ', $firstThreeComponents);
172
+
173
+        if ($diff->invert) {
174
+            $title = $this->l10n->t('%s (in %s)', [$title, $diffLabel]);
175
+        } else {
176
+            $title = $this->l10n->t('%s (%s ago)', [$title, $diffLabel]);
177
+        }
178
+
179
+        $notification->setParsedSubject($title);
180
+    }
181
+
182
+    /**
183
+     * Sets the notification message based on the parameters set in PushProvider
184
+     *
185
+     * @param INotification $notification
186
+     */
187
+    private function prepareNotificationMessage(INotification $notification): void {
188
+        $parameters = $notification->getMessageParameters();
189
+
190
+        $description = [
191
+            $this->l10n->t('Calendar: %s', $parameters['calendar_displayname']),
192
+            $this->l10n->t('Date: %s', $this->generateDateString($parameters)),
193
+        ];
194
+        if ($parameters['description']) {
195
+            $description[] = $this->l10n->t('Description: %s', $parameters['description']);
196
+        }
197
+        if ($parameters['location']) {
198
+            $description[] = $this->l10n->t('Where: %s', $parameters['location']);
199
+        }
200
+
201
+        $message = implode("\r\n", $description);
202
+        $notification->setParsedMessage($message);
203
+    }
204
+
205
+    /**
206
+     * @param array $parameters
207
+     * @return string
208
+     */
209
+    private function getTitleFromParameters(array $parameters):string {
210
+        return $parameters['title'] ?? $this->l10n->t('Untitled event');
211
+    }
212
+
213
+    /**
214
+     * @param array $parameters
215
+     * @return string
216
+     * @throws \Exception
217
+     */
218
+    private function generateDateString(array $parameters):string {
219
+        $startDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
220
+        $endDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['end_atom']);
221
+        $isAllDay = $parameters['all_day'];
222
+        $diff = $startDateTime->diff($endDateTime);
223
+
224
+        if ($isAllDay) {
225
+            // One day event
226
+            if ($diff->days === 1) {
227
+                return $this->getDateString($startDateTime);
228
+            }
229
+
230
+            return implode(' - ', [
231
+                $this->getDateString($startDateTime),
232
+                $this->getDateString($endDateTime),
233
+            ]);
234
+        }
235
+
236
+        $startTimezone = $endTimezone = null;
237
+        if (!$parameters['start_is_floating']) {
238
+            $startTimezone = $parameters['start_timezone'];
239
+            $endTimezone = $parameters['end_timezone'];
240
+        }
241
+
242
+        $localeStart = implode(', ', [
243
+            $this->getWeekDayName($startDateTime),
244
+            $this->getDateTimeString($startDateTime)
245
+        ]);
246
+
247
+        // always show full date with timezone if timezones are different
248
+        if ($startTimezone !== $endTimezone) {
249
+            $localeEnd = implode(', ', [
250
+                $this->getWeekDayName($endDateTime),
251
+                $this->getDateTimeString($endDateTime)
252
+            ]);
253
+
254
+            return $localeStart
255
+                . ' (' . $startTimezone . ') '
256
+                . ' - '
257
+                . $localeEnd
258
+                . ' (' . $endTimezone . ')';
259
+        }
260
+
261
+        // Show only the time if the day is the same
262
+        $localeEnd = $this->isDayEqual($startDateTime, $endDateTime)
263
+            ? $this->getTimeString($endDateTime)
264
+            : implode(', ', [
265
+                $this->getWeekDayName($endDateTime),
266
+                $this->getDateTimeString($endDateTime)
267
+            ]);
268
+
269
+        return $localeStart
270
+            . ' - '
271
+            . $localeEnd
272
+            . ' (' . $startTimezone . ')';
273
+    }
274
+
275
+    /**
276
+     * @param DateTime $dtStart
277
+     * @param DateTime $dtEnd
278
+     * @return bool
279
+     */
280
+    private function isDayEqual(DateTime $dtStart,
281
+                                DateTime $dtEnd):bool {
282
+        return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
283
+    }
284
+
285
+    /**
286
+     * @param DateTime $dt
287
+     * @return string
288
+     */
289
+    private function getWeekDayName(DateTime $dt):string {
290
+        return $this->l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
291
+    }
292
+
293
+    /**
294
+     * @param DateTime $dt
295
+     * @return string
296
+     */
297
+    private function getDateString(DateTime $dt):string {
298
+        return $this->l10n->l('date', $dt, ['width' => 'medium']);
299
+    }
300
+
301
+    /**
302
+     * @param DateTime $dt
303
+     * @return string
304
+     */
305
+    private function getDateTimeString(DateTime $dt):string {
306
+        return $this->l10n->l('datetime', $dt, ['width' => 'medium|short']);
307
+    }
308
+
309
+    /**
310
+     * @param DateTime $dt
311
+     * @return string
312
+     */
313
+    private function getTimeString(DateTime $dt):string {
314
+        return $this->l10n->l('time', $dt, ['width' => 'short']);
315
+    }
316 316
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 		$this->l10n = $this->l10nFactory->get('dav', $languageCode);
107 107
 
108 108
 		// Handle notifier subjects
109
-		switch($notification->getSubject()) {
109
+		switch ($notification->getSubject()) {
110 110
 			case 'calendar_reminder':
111 111
 				return $this->prepareReminderNotification($notification);
112 112
 
@@ -252,10 +252,10 @@  discard block
 block discarded – undo
252 252
 			]);
253 253
 
254 254
 			return $localeStart
255
-				. ' (' . $startTimezone . ') '
255
+				. ' ('.$startTimezone.') '
256 256
 				. ' - '
257 257
 				. $localeEnd
258
-				. ' (' . $endTimezone . ')';
258
+				. ' ('.$endTimezone.')';
259 259
 		}
260 260
 
261 261
 		// Show only the time if the day is the same
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 		return $localeStart
270 270
 			. ' - '
271 271
 			. $localeEnd
272
-			. ' (' . $startTimezone . ')';
272
+			. ' ('.$startTimezone.')';
273 273
 	}
274 274
 
275 275
 	/**
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/INotificationProvider.php 2 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -33,15 +33,15 @@
 block discarded – undo
33 33
  */
34 34
 interface INotificationProvider {
35 35
 
36
-	/**
37
-	 * Send notification
38
-	 *
39
-	 * @param VEvent $vevent
40
-	 * @param string $calendarDisplayName
41
-	 * @param IUser[] $users
42
-	 * @return void
43
-	 */
44
-	public function send(VEvent $vevent,
45
-						 string $calendarDisplayName,
46
-						 array $users=[]): void;
36
+    /**
37
+     * Send notification
38
+     *
39
+     * @param VEvent $vevent
40
+     * @param string $calendarDisplayName
41
+     * @param IUser[] $users
42
+     * @return void
43
+     */
44
+    public function send(VEvent $vevent,
45
+                            string $calendarDisplayName,
46
+                            array $users=[]): void;
47 47
 }
48 48
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -43,5 +43,5 @@
 block discarded – undo
43 43
 	 */
44 44
 	public function send(VEvent $vevent,
45 45
 						 string $calendarDisplayName,
46
-						 array $users=[]): void;
46
+						 array $users = []): void;
47 47
 }
48 48
\ No newline at end of file
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/ReminderService.php 2 patches
Indentation   +718 added lines, -718 removed lines patch added patch discarded remove patch
@@ -40,722 +40,722 @@
 block discarded – undo
40 40
 
41 41
 class ReminderService {
42 42
 
43
-	/** @var Backend */
44
-	private $backend;
45
-
46
-	/** @var NotificationProviderManager */
47
-	private $notificationProviderManager;
48
-
49
-	/** @var IUserManager */
50
-	private $userManager;
51
-
52
-	/** @var IGroupManager */
53
-	private $groupManager;
54
-
55
-	/** @var CalDavBackend */
56
-	private $caldavBackend;
57
-
58
-	/** @var ITimeFactory */
59
-	private $timeFactory;
60
-
61
-	public const REMINDER_TYPE_EMAIL = 'EMAIL';
62
-	public const REMINDER_TYPE_DISPLAY = 'DISPLAY';
63
-	public const REMINDER_TYPE_AUDIO = 'AUDIO';
64
-
65
-	/**
66
-	 * @var String[]
67
-	 *
68
-	 * Official RFC5545 reminder types
69
-	 */
70
-	public const REMINDER_TYPES = [
71
-		self::REMINDER_TYPE_EMAIL,
72
-		self::REMINDER_TYPE_DISPLAY,
73
-		self::REMINDER_TYPE_AUDIO
74
-	];
75
-
76
-	/**
77
-	 * ReminderService constructor.
78
-	 *
79
-	 * @param Backend $backend
80
-	 * @param NotificationProviderManager $notificationProviderManager
81
-	 * @param IUserManager $userManager
82
-	 * @param IGroupManager $groupManager
83
-	 * @param CalDavBackend $caldavBackend
84
-	 * @param ITimeFactory $timeFactory
85
-	 */
86
-	public function __construct(Backend $backend,
87
-								NotificationProviderManager $notificationProviderManager,
88
-								IUserManager $userManager,
89
-								IGroupManager $groupManager,
90
-								CalDavBackend $caldavBackend,
91
-								ITimeFactory $timeFactory) {
92
-		$this->backend = $backend;
93
-		$this->notificationProviderManager = $notificationProviderManager;
94
-		$this->userManager = $userManager;
95
-		$this->groupManager = $groupManager;
96
-		$this->caldavBackend = $caldavBackend;
97
-		$this->timeFactory = $timeFactory;
98
-	}
99
-
100
-	/**
101
-	 * Process reminders to activate
102
-	 *
103
-	 * @throws NotificationProvider\ProviderNotAvailableException
104
-	 * @throws NotificationTypeDoesNotExistException
105
-	 */
106
-	public function processReminders():void {
107
-		$reminders = $this->backend->getRemindersToProcess();
108
-
109
-		foreach($reminders as $reminder) {
110
-			$vcalendar = $this->parseCalendarData($reminder['calendardata']);
111
-			if (!$vcalendar) {
112
-				$this->backend->removeReminder($reminder['id']);
113
-				continue;
114
-			}
115
-
116
-			$vevent = $this->getVEventByRecurrenceId($vcalendar, $reminder['recurrence_id'], $reminder['is_recurrence_exception']);
117
-			if (!$vevent) {
118
-				$this->backend->removeReminder($reminder['id']);
119
-				continue;
120
-			}
121
-
122
-			if ($this->wasEventCancelled($vevent)) {
123
-				$this->deleteOrProcessNext($reminder, $vevent);
124
-				continue;
125
-			}
126
-
127
-			if (!$this->notificationProviderManager->hasProvider($reminder['type'])) {
128
-				$this->deleteOrProcessNext($reminder, $vevent);
129
-				continue;
130
-			}
131
-
132
-			$users = $this->getAllUsersWithWriteAccessToCalendar($reminder['calendar_id']);
133
-			$user = $this->getUserFromPrincipalURI($reminder['principaluri']);
134
-			if ($user) {
135
-				$users[] = $user;
136
-			}
137
-
138
-			$notificationProvider = $this->notificationProviderManager->getProvider($reminder['type']);
139
-			$notificationProvider->send($vevent, $reminder['displayname'], $users);
140
-
141
-			$this->deleteOrProcessNext($reminder, $vevent);
142
-		}
143
-	}
144
-
145
-	/**
146
-	 * @param string $action
147
-	 * @param array $objectData
148
-	 * @throws VObject\InvalidDataException
149
-	 */
150
-	public function onTouchCalendarObject(string $action,
151
-										  array $objectData):void {
152
-		// We only support VEvents for now
153
-		if (strcasecmp($objectData['component'], 'vevent') !== 0) {
154
-			return;
155
-		}
156
-
157
-		switch($action) {
158
-			case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
159
-				$this->onCalendarObjectCreate($objectData);
160
-				break;
161
-
162
-			case '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject':
163
-				$this->onCalendarObjectEdit($objectData);
164
-				break;
165
-
166
-			case '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject':
167
-				$this->onCalendarObjectDelete($objectData);
168
-				break;
169
-
170
-			default:
171
-				break;
172
-		}
173
-	}
174
-
175
-	/**
176
-	 * @param array $objectData
177
-	 */
178
-	private function onCalendarObjectCreate(array $objectData):void {
179
-		/** @var VObject\Component\VCalendar $vcalendar */
180
-		$vcalendar = $this->parseCalendarData($objectData['calendardata']);
181
-		if (!$vcalendar) {
182
-			return;
183
-		}
184
-
185
-		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
186
-		if (count($vevents) === 0) {
187
-			return;
188
-		}
189
-
190
-		$uid = (string) $vevents[0]->UID;
191
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
192
-		$masterItem = $this->getMasterItemFromListOfVEvents($vevents);
193
-		$now = $this->timeFactory->getDateTime();
194
-		$isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
195
-
196
-		foreach($recurrenceExceptions as $recurrenceException) {
197
-			$eventHash = $this->getEventHash($recurrenceException);
198
-
199
-			foreach($recurrenceException->VALARM as $valarm) {
200
-				/** @var VAlarm $valarm */
201
-				$alarmHash = $this->getAlarmHash($valarm);
202
-				$triggerTime = $valarm->getEffectiveTriggerTime();
203
-				$diff = $now->diff($triggerTime);
204
-				if ($diff->invert === 1) {
205
-					continue;
206
-				}
207
-
208
-				$alarms = $this->getRemindersForVAlarm($valarm, $objectData,
209
-					$eventHash, $alarmHash, true, true);
210
-				$this->writeRemindersToDatabase($alarms);
211
-			}
212
-		}
213
-
214
-		if ($masterItem) {
215
-			$processedAlarms = [];
216
-			$masterAlarms = [];
217
-			$masterHash = $this->getEventHash($masterItem);
218
-
219
-			foreach($masterItem->VALARM as $valarm) {
220
-				$masterAlarms[] = $this->getAlarmHash($valarm);
221
-			}
222
-
223
-			try {
224
-				$iterator = new EventIterator($vevents, $uid);
225
-			} catch (NoInstancesException $e) {
226
-				// This event is recurring, but it doesn't have a single
227
-				// instance. We are skipping this event from the output
228
-				// entirely.
229
-				return;
230
-			}
231
-
232
-			while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
233
-				$event = $iterator->getEventObject();
234
-
235
-				// Recurrence-exceptions are handled separately, so just ignore them here
236
-				if (\in_array($event, $recurrenceExceptions, true)) {
237
-					$iterator->next();
238
-					continue;
239
-				}
240
-
241
-				foreach($event->VALARM as $valarm) {
242
-					/** @var VAlarm $valarm */
243
-					$alarmHash = $this->getAlarmHash($valarm);
244
-					if (\in_array($alarmHash, $processedAlarms, true)) {
245
-						continue;
246
-					}
247
-
248
-					if (!\in_array((string) $valarm->ACTION, self::REMINDER_TYPES, true)) {
249
-						// Action allows x-name, we don't insert reminders
250
-						// into the database if they are not standard
251
-						$processedAlarms[] = $alarmHash;
252
-						continue;
253
-					}
254
-
255
-					$triggerTime = $valarm->getEffectiveTriggerTime();
256
-
257
-					// If effective trigger time is in the past
258
-					// just skip and generate for next event
259
-					$diff = $now->diff($triggerTime);
260
-					if ($diff->invert === 1) {
261
-						// If an absolute alarm is in the past,
262
-						// just add it to processedAlarms, so
263
-						// we don't extend till eternity
264
-						if (!$this->isAlarmRelative($valarm)) {
265
-							$processedAlarms[] = $alarmHash;
266
-						}
267
-
268
-						continue;
269
-					}
270
-
271
-					$alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring, false);
272
-					$this->writeRemindersToDatabase($alarms);
273
-					$processedAlarms[] = $alarmHash;
274
-				}
275
-
276
-				$iterator->next();
277
-			}
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * @param array $objectData
283
-	 */
284
-	private function onCalendarObjectEdit(array $objectData):void {
285
-		// TODO - this can be vastly improved
286
-		//  - get cached reminders
287
-		//  - ...
288
-
289
-		$this->onCalendarObjectDelete($objectData);
290
-		$this->onCalendarObjectCreate($objectData);
291
-	}
292
-
293
-	/**
294
-	 * @param array $objectData
295
-	 */
296
-	private function onCalendarObjectDelete(array $objectData):void {
297
-		$this->backend->cleanRemindersForEvent((int) $objectData['id']);
298
-	}
299
-
300
-	/**
301
-	 * @param VAlarm $valarm
302
-	 * @param array $objectData
303
-	 * @param string|null $eventHash
304
-	 * @param string|null $alarmHash
305
-	 * @param bool $isRecurring
306
-	 * @param bool $isRecurrenceException
307
-	 * @return array
308
-	 */
309
-	private function getRemindersForVAlarm(VAlarm $valarm,
310
-										   array $objectData,
311
-										   string $eventHash=null,
312
-										   string $alarmHash=null,
313
-										   bool $isRecurring=false,
314
-										   bool $isRecurrenceException=false):array {
315
-		if ($eventHash === null) {
316
-			$eventHash = $this->getEventHash($valarm->parent);
317
-		}
318
-		if ($alarmHash === null) {
319
-			$alarmHash = $this->getAlarmHash($valarm);
320
-		}
321
-
322
-		$recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent);
323
-		$isRelative = $this->isAlarmRelative($valarm);
324
-		/** @var DateTimeImmutable $notificationDate */
325
-		$notificationDate = $valarm->getEffectiveTriggerTime();
326
-		$clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone());
327
-		$clonedNotificationDate->setTimestamp($notificationDate->getTimestamp());
328
-
329
-		$alarms = [];
330
-
331
-		$alarms[] = [
332
-			'calendar_id' => $objectData['calendarid'],
333
-			'object_id' => $objectData['id'],
334
-			'uid' => (string) $valarm->parent->UID,
335
-			'is_recurring' => $isRecurring,
336
-			'recurrence_id' => $recurrenceId,
337
-			'is_recurrence_exception' => $isRecurrenceException,
338
-			'event_hash' => $eventHash,
339
-			'alarm_hash' => $alarmHash,
340
-			'type' => (string) $valarm->ACTION,
341
-			'is_relative' => $isRelative,
342
-			'notification_date' => $notificationDate->getTimestamp(),
343
-			'is_repeat_based' => false,
344
-		];
345
-
346
-		$repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
347
-		for($i = 0; $i < $repeat; $i++) {
348
-			if ($valarm->DURATION === null) {
349
-				continue;
350
-			}
351
-
352
-			$clonedNotificationDate->add($valarm->DURATION->getDateInterval());
353
-			$alarms[] = [
354
-				'calendar_id' => $objectData['calendarid'],
355
-				'object_id' => $objectData['id'],
356
-				'uid' => (string) $valarm->parent->UID,
357
-				'is_recurring' => $isRecurring,
358
-				'recurrence_id' => $recurrenceId,
359
-				'is_recurrence_exception' => $isRecurrenceException,
360
-				'event_hash' => $eventHash,
361
-				'alarm_hash' => $alarmHash,
362
-				'type' => (string) $valarm->ACTION,
363
-				'is_relative' => $isRelative,
364
-				'notification_date' => $clonedNotificationDate->getTimestamp(),
365
-				'is_repeat_based' => true,
366
-			];
367
-		}
368
-
369
-		return $alarms;
370
-	}
371
-
372
-	/**
373
-	 * @param array $reminders
374
-	 */
375
-	private function writeRemindersToDatabase(array $reminders): void {
376
-		foreach($reminders as $reminder) {
377
-			$this->backend->insertReminder(
378
-				(int) $reminder['calendar_id'],
379
-				(int) $reminder['object_id'],
380
-				$reminder['uid'],
381
-				$reminder['is_recurring'],
382
-				(int) $reminder['recurrence_id'],
383
-				$reminder['is_recurrence_exception'],
384
-				$reminder['event_hash'],
385
-				$reminder['alarm_hash'],
386
-				$reminder['type'],
387
-				$reminder['is_relative'],
388
-				(int) $reminder['notification_date'],
389
-				$reminder['is_repeat_based']
390
-			);
391
-		}
392
-	}
393
-
394
-	/**
395
-	 * @param array $reminder
396
-	 * @param VEvent $vevent
397
-	 */
398
-	private function deleteOrProcessNext(array $reminder,
399
-										 VObject\Component\VEvent $vevent):void {
400
-		if ($reminder['is_repeat_based'] ||
401
-			!$reminder['is_recurring'] ||
402
-			!$reminder['is_relative'] ||
403
-			$reminder['is_recurrence_exception']) {
404
-
405
-			$this->backend->removeReminder($reminder['id']);
406
-			return;
407
-		}
408
-
409
-		$vevents = $this->getAllVEventsFromVCalendar($vevent->parent);
410
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
411
-		$now = $this->timeFactory->getDateTime();
412
-
413
-		try {
414
-			$iterator = new EventIterator($vevents, $reminder['uid']);
415
-		} catch (NoInstancesException $e) {
416
-			// This event is recurring, but it doesn't have a single
417
-			// instance. We are skipping this event from the output
418
-			// entirely.
419
-			return;
420
-		}
421
-
422
-		while($iterator->valid()) {
423
-			$event = $iterator->getEventObject();
424
-
425
-			// Recurrence-exceptions are handled separately, so just ignore them here
426
-			if (\in_array($event, $recurrenceExceptions, true)) {
427
-				$iterator->next();
428
-				continue;
429
-			}
430
-
431
-			$recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($event);
432
-			if ($reminder['recurrence_id'] >= $recurrenceId) {
433
-				$iterator->next();
434
-				continue;
435
-			}
436
-
437
-			foreach($event->VALARM as $valarm) {
438
-				/** @var VAlarm $valarm */
439
-				$alarmHash = $this->getAlarmHash($valarm);
440
-				if ($alarmHash !== $reminder['alarm_hash']) {
441
-					continue;
442
-				}
443
-
444
-				$triggerTime = $valarm->getEffectiveTriggerTime();
445
-
446
-				// If effective trigger time is in the past
447
-				// just skip and generate for next event
448
-				$diff = $now->diff($triggerTime);
449
-				if ($diff->invert === 1) {
450
-					continue;
451
-				}
452
-
453
-				$this->backend->removeReminder($reminder['id']);
454
-				$alarms = $this->getRemindersForVAlarm($valarm, [
455
-					'calendarid' => $reminder['calendar_id'],
456
-					'id' => $reminder['object_id'],
457
-				], $reminder['event_hash'], $alarmHash, true, false);
458
-				$this->writeRemindersToDatabase($alarms);
459
-
460
-				// Abort generating reminders after creating one successfully
461
-				return;
462
-			}
463
-
464
-			$iterator->next();
465
-		}
466
-
467
-		$this->backend->removeReminder($reminder['id']);
468
-	}
469
-
470
-	/**
471
-	 * @param int $calendarId
472
-	 * @return IUser[]
473
-	 */
474
-	private function getAllUsersWithWriteAccessToCalendar(int $calendarId):array {
475
-		$shares = $this->caldavBackend->getShares($calendarId);
476
-
477
-		$users = [];
478
-		$userIds = [];
479
-		$groups = [];
480
-		foreach ($shares as $share) {
481
-			// Only consider writable shares
482
-			if ($share['readOnly']) {
483
-				continue;
484
-			}
485
-
486
-			$principal = explode('/', $share['{http://owncloud.org/ns}principal']);
487
-			if ($principal[1] === 'users') {
488
-				$user = $this->userManager->get($principal[2]);
489
-				if ($user) {
490
-					$users[] = $user;
491
-					$userIds[] = $principal[2];
492
-				}
493
-			} else if ($principal[1] === 'groups') {
494
-				$groups[] = $principal[2];
495
-			}
496
-		}
497
-
498
-		foreach ($groups as $gid) {
499
-			$group = $this->groupManager->get($gid);
500
-			if ($group instanceof IGroup) {
501
-				foreach ($group->getUsers() as $user) {
502
-					if (!\in_array($user->getUID(), $userIds, true)) {
503
-						$users[] = $user;
504
-						$userIds[] = $user->getUID();
505
-					}
506
-				}
507
-			}
508
-		}
509
-
510
-		return $users;
511
-	}
512
-
513
-	/**
514
-	 * Gets a hash of the event.
515
-	 * If the hash changes, we have to update all relative alarms.
516
-	 *
517
-	 * @param VEvent $vevent
518
-	 * @return string
519
-	 */
520
-	private function getEventHash(VEvent $vevent):string {
521
-		$properties = [
522
-			(string) $vevent->DTSTART->serialize(),
523
-		];
524
-
525
-		if ($vevent->DTEND) {
526
-			$properties[] = (string) $vevent->DTEND->serialize();
527
-		}
528
-		if ($vevent->DURATION) {
529
-			$properties[] = (string) $vevent->DURATION->serialize();
530
-		}
531
-		if ($vevent->{'RECURRENCE-ID'}) {
532
-			$properties[] = (string) $vevent->{'RECURRENCE-ID'}->serialize();
533
-		}
534
-		if ($vevent->RRULE) {
535
-			$properties[] = (string) $vevent->RRULE->serialize();
536
-		}
537
-		if ($vevent->EXDATE) {
538
-			$properties[] = (string) $vevent->EXDATE->serialize();
539
-		}
540
-		if ($vevent->RDATE) {
541
-			$properties[] = (string) $vevent->RDATE->serialize();
542
-		}
543
-
544
-		return md5(implode('::', $properties));
545
-	}
546
-
547
-	/**
548
-	 * Gets a hash of the alarm.
549
-	 * If the hash changes, we have to update oc_dav_reminders.
550
-	 *
551
-	 * @param VAlarm $valarm
552
-	 * @return string
553
-	 */
554
-	private function getAlarmHash(VAlarm $valarm):string {
555
-		$properties = [
556
-			(string) $valarm->ACTION->serialize(),
557
-			(string) $valarm->TRIGGER->serialize(),
558
-		];
559
-
560
-		if ($valarm->DURATION) {
561
-			$properties[] = (string) $valarm->DURATION->serialize();
562
-		}
563
-		if ($valarm->REPEAT) {
564
-			$properties[] = (string) $valarm->REPEAT->serialize();
565
-		}
566
-
567
-		return md5(implode('::', $properties));
568
-	}
569
-
570
-	/**
571
-	 * @param VObject\Component\VCalendar $vcalendar
572
-	 * @param int $recurrenceId
573
-	 * @param bool $isRecurrenceException
574
-	 * @return VEvent|null
575
-	 */
576
-	private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
577
-											 int $recurrenceId,
578
-											 bool $isRecurrenceException):?VEvent {
579
-		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
580
-		if (count($vevents) === 0) {
581
-			return null;
582
-		}
583
-
584
-		$uid = (string) $vevents[0]->UID;
585
-		$recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
586
-		$masterItem = $this->getMasterItemFromListOfVEvents($vevents);
587
-
588
-		// Handle recurrence-exceptions first, because recurrence-expansion is expensive
589
-		if ($isRecurrenceException) {
590
-			foreach($recurrenceExceptions as $recurrenceException) {
591
-				if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
592
-					return $recurrenceException;
593
-				}
594
-			}
595
-
596
-			return null;
597
-		}
598
-
599
-		if ($masterItem) {
600
-			try {
601
-				$iterator = new EventIterator($vevents, $uid);
602
-			} catch (NoInstancesException $e) {
603
-				// This event is recurring, but it doesn't have a single
604
-				// instance. We are skipping this event from the output
605
-				// entirely.
606
-				return null;
607
-			}
608
-
609
-			while ($iterator->valid()) {
610
-				$event = $iterator->getEventObject();
611
-
612
-				// Recurrence-exceptions are handled separately, so just ignore them here
613
-				if (\in_array($event, $recurrenceExceptions, true)) {
614
-					$iterator->next();
615
-					continue;
616
-				}
617
-
618
-				if ($this->getEffectiveRecurrenceIdOfVEvent($event) === $recurrenceId) {
619
-					return $event;
620
-				}
621
-
622
-				$iterator->next();
623
-			}
624
-		}
625
-
626
-		return null;
627
-	}
628
-
629
-	/**
630
-	 * @param VEvent $vevent
631
-	 * @return string
632
-	 */
633
-	private function getStatusOfEvent(VEvent $vevent):string {
634
-		if ($vevent->STATUS) {
635
-			return (string) $vevent->STATUS;
636
-		}
637
-
638
-		// Doesn't say so in the standard,
639
-		// but we consider events without a status
640
-		// to be confirmed
641
-		return 'CONFIRMED';
642
-	}
643
-
644
-	/**
645
-	 * @param VObject\Component\VEvent $vevent
646
-	 * @return bool
647
-	 */
648
-	private function wasEventCancelled(VObject\Component\VEvent $vevent):bool {
649
-		return $this->getStatusOfEvent($vevent) === 'CANCELLED';
650
-	}
651
-
652
-	/**
653
-	 * @param string $calendarData
654
-	 * @return VObject\Component\VCalendar|null
655
-	 */
656
-	private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
657
-		try {
658
-			return VObject\Reader::read($calendarData,
659
-				VObject\Reader::OPTION_FORGIVING);
660
-		} catch(ParseException $ex) {
661
-			return null;
662
-		}
663
-	}
664
-
665
-	/**
666
-	 * @param string $principalUri
667
-	 * @return IUser|null
668
-	 */
669
-	private function getUserFromPrincipalURI(string $principalUri):?IUser {
670
-		if (!$principalUri) {
671
-			return null;
672
-		}
673
-
674
-		if (stripos($principalUri, 'principals/users/') !== 0) {
675
-			return null;
676
-		}
677
-
678
-		$userId = substr($principalUri, 17);
679
-		return $this->userManager->get($userId);
680
-	}
681
-
682
-	/**
683
-	 * @param VObject\Component\VCalendar $vcalendar
684
-	 * @return VObject\Component\VEvent[]
685
-	 */
686
-	private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
687
-		$vevents = [];
688
-
689
-		foreach($vcalendar->children() as $child) {
690
-			if (!($child instanceof VObject\Component)) {
691
-				continue;
692
-			}
693
-
694
-			if ($child->name !== 'VEVENT') {
695
-				continue;
696
-			}
697
-
698
-			$vevents[] = $child;
699
-		}
700
-
701
-		return $vevents;
702
-	}
703
-
704
-	/**
705
-	 * @param array $vevents
706
-	 * @return VObject\Component\VEvent[]
707
-	 */
708
-	private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
709
-		return array_values(array_filter($vevents, function(VEvent $vevent) {
710
-			return $vevent->{'RECURRENCE-ID'} !== null;
711
-		}));
712
-	}
713
-
714
-	/**
715
-	 * @param array $vevents
716
-	 * @return VEvent|null
717
-	 */
718
-	private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
719
-		$elements = array_values(array_filter($vevents, function(VEvent $vevent) {
720
-			return $vevent->{'RECURRENCE-ID'} === null;
721
-		}));
722
-
723
-		if (count($elements) === 0) {
724
-			return null;
725
-		}
726
-		if (count($elements) > 1) {
727
-			throw new \TypeError('Multiple master objects');
728
-		}
729
-
730
-		return $elements[0];
731
-	}
732
-
733
-	/**
734
-	 * @param VAlarm $valarm
735
-	 * @return bool
736
-	 */
737
-	private function isAlarmRelative(VAlarm $valarm):bool {
738
-		$trigger = $valarm->TRIGGER;
739
-		return $trigger instanceof VObject\Property\ICalendar\Duration;
740
-	}
741
-
742
-	/**
743
-	 * @param VEvent $vevent
744
-	 * @return int
745
-	 */
746
-	private function getEffectiveRecurrenceIdOfVEvent(VEvent $vevent):int {
747
-		if (isset($vevent->{'RECURRENCE-ID'})) {
748
-			return $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp();
749
-		}
750
-
751
-		return $vevent->DTSTART->getDateTime()->getTimestamp();
752
-	}
753
-
754
-	/**
755
-	 * @param VEvent $vevent
756
-	 * @return bool
757
-	 */
758
-	private function isRecurring(VEvent $vevent):bool {
759
-		return isset($vevent->RRULE) || isset($vevent->RDATE);
760
-	}
43
+    /** @var Backend */
44
+    private $backend;
45
+
46
+    /** @var NotificationProviderManager */
47
+    private $notificationProviderManager;
48
+
49
+    /** @var IUserManager */
50
+    private $userManager;
51
+
52
+    /** @var IGroupManager */
53
+    private $groupManager;
54
+
55
+    /** @var CalDavBackend */
56
+    private $caldavBackend;
57
+
58
+    /** @var ITimeFactory */
59
+    private $timeFactory;
60
+
61
+    public const REMINDER_TYPE_EMAIL = 'EMAIL';
62
+    public const REMINDER_TYPE_DISPLAY = 'DISPLAY';
63
+    public const REMINDER_TYPE_AUDIO = 'AUDIO';
64
+
65
+    /**
66
+     * @var String[]
67
+     *
68
+     * Official RFC5545 reminder types
69
+     */
70
+    public const REMINDER_TYPES = [
71
+        self::REMINDER_TYPE_EMAIL,
72
+        self::REMINDER_TYPE_DISPLAY,
73
+        self::REMINDER_TYPE_AUDIO
74
+    ];
75
+
76
+    /**
77
+     * ReminderService constructor.
78
+     *
79
+     * @param Backend $backend
80
+     * @param NotificationProviderManager $notificationProviderManager
81
+     * @param IUserManager $userManager
82
+     * @param IGroupManager $groupManager
83
+     * @param CalDavBackend $caldavBackend
84
+     * @param ITimeFactory $timeFactory
85
+     */
86
+    public function __construct(Backend $backend,
87
+                                NotificationProviderManager $notificationProviderManager,
88
+                                IUserManager $userManager,
89
+                                IGroupManager $groupManager,
90
+                                CalDavBackend $caldavBackend,
91
+                                ITimeFactory $timeFactory) {
92
+        $this->backend = $backend;
93
+        $this->notificationProviderManager = $notificationProviderManager;
94
+        $this->userManager = $userManager;
95
+        $this->groupManager = $groupManager;
96
+        $this->caldavBackend = $caldavBackend;
97
+        $this->timeFactory = $timeFactory;
98
+    }
99
+
100
+    /**
101
+     * Process reminders to activate
102
+     *
103
+     * @throws NotificationProvider\ProviderNotAvailableException
104
+     * @throws NotificationTypeDoesNotExistException
105
+     */
106
+    public function processReminders():void {
107
+        $reminders = $this->backend->getRemindersToProcess();
108
+
109
+        foreach($reminders as $reminder) {
110
+            $vcalendar = $this->parseCalendarData($reminder['calendardata']);
111
+            if (!$vcalendar) {
112
+                $this->backend->removeReminder($reminder['id']);
113
+                continue;
114
+            }
115
+
116
+            $vevent = $this->getVEventByRecurrenceId($vcalendar, $reminder['recurrence_id'], $reminder['is_recurrence_exception']);
117
+            if (!$vevent) {
118
+                $this->backend->removeReminder($reminder['id']);
119
+                continue;
120
+            }
121
+
122
+            if ($this->wasEventCancelled($vevent)) {
123
+                $this->deleteOrProcessNext($reminder, $vevent);
124
+                continue;
125
+            }
126
+
127
+            if (!$this->notificationProviderManager->hasProvider($reminder['type'])) {
128
+                $this->deleteOrProcessNext($reminder, $vevent);
129
+                continue;
130
+            }
131
+
132
+            $users = $this->getAllUsersWithWriteAccessToCalendar($reminder['calendar_id']);
133
+            $user = $this->getUserFromPrincipalURI($reminder['principaluri']);
134
+            if ($user) {
135
+                $users[] = $user;
136
+            }
137
+
138
+            $notificationProvider = $this->notificationProviderManager->getProvider($reminder['type']);
139
+            $notificationProvider->send($vevent, $reminder['displayname'], $users);
140
+
141
+            $this->deleteOrProcessNext($reminder, $vevent);
142
+        }
143
+    }
144
+
145
+    /**
146
+     * @param string $action
147
+     * @param array $objectData
148
+     * @throws VObject\InvalidDataException
149
+     */
150
+    public function onTouchCalendarObject(string $action,
151
+                                            array $objectData):void {
152
+        // We only support VEvents for now
153
+        if (strcasecmp($objectData['component'], 'vevent') !== 0) {
154
+            return;
155
+        }
156
+
157
+        switch($action) {
158
+            case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
159
+                $this->onCalendarObjectCreate($objectData);
160
+                break;
161
+
162
+            case '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject':
163
+                $this->onCalendarObjectEdit($objectData);
164
+                break;
165
+
166
+            case '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject':
167
+                $this->onCalendarObjectDelete($objectData);
168
+                break;
169
+
170
+            default:
171
+                break;
172
+        }
173
+    }
174
+
175
+    /**
176
+     * @param array $objectData
177
+     */
178
+    private function onCalendarObjectCreate(array $objectData):void {
179
+        /** @var VObject\Component\VCalendar $vcalendar */
180
+        $vcalendar = $this->parseCalendarData($objectData['calendardata']);
181
+        if (!$vcalendar) {
182
+            return;
183
+        }
184
+
185
+        $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
186
+        if (count($vevents) === 0) {
187
+            return;
188
+        }
189
+
190
+        $uid = (string) $vevents[0]->UID;
191
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
192
+        $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
193
+        $now = $this->timeFactory->getDateTime();
194
+        $isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
195
+
196
+        foreach($recurrenceExceptions as $recurrenceException) {
197
+            $eventHash = $this->getEventHash($recurrenceException);
198
+
199
+            foreach($recurrenceException->VALARM as $valarm) {
200
+                /** @var VAlarm $valarm */
201
+                $alarmHash = $this->getAlarmHash($valarm);
202
+                $triggerTime = $valarm->getEffectiveTriggerTime();
203
+                $diff = $now->diff($triggerTime);
204
+                if ($diff->invert === 1) {
205
+                    continue;
206
+                }
207
+
208
+                $alarms = $this->getRemindersForVAlarm($valarm, $objectData,
209
+                    $eventHash, $alarmHash, true, true);
210
+                $this->writeRemindersToDatabase($alarms);
211
+            }
212
+        }
213
+
214
+        if ($masterItem) {
215
+            $processedAlarms = [];
216
+            $masterAlarms = [];
217
+            $masterHash = $this->getEventHash($masterItem);
218
+
219
+            foreach($masterItem->VALARM as $valarm) {
220
+                $masterAlarms[] = $this->getAlarmHash($valarm);
221
+            }
222
+
223
+            try {
224
+                $iterator = new EventIterator($vevents, $uid);
225
+            } catch (NoInstancesException $e) {
226
+                // This event is recurring, but it doesn't have a single
227
+                // instance. We are skipping this event from the output
228
+                // entirely.
229
+                return;
230
+            }
231
+
232
+            while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
233
+                $event = $iterator->getEventObject();
234
+
235
+                // Recurrence-exceptions are handled separately, so just ignore them here
236
+                if (\in_array($event, $recurrenceExceptions, true)) {
237
+                    $iterator->next();
238
+                    continue;
239
+                }
240
+
241
+                foreach($event->VALARM as $valarm) {
242
+                    /** @var VAlarm $valarm */
243
+                    $alarmHash = $this->getAlarmHash($valarm);
244
+                    if (\in_array($alarmHash, $processedAlarms, true)) {
245
+                        continue;
246
+                    }
247
+
248
+                    if (!\in_array((string) $valarm->ACTION, self::REMINDER_TYPES, true)) {
249
+                        // Action allows x-name, we don't insert reminders
250
+                        // into the database if they are not standard
251
+                        $processedAlarms[] = $alarmHash;
252
+                        continue;
253
+                    }
254
+
255
+                    $triggerTime = $valarm->getEffectiveTriggerTime();
256
+
257
+                    // If effective trigger time is in the past
258
+                    // just skip and generate for next event
259
+                    $diff = $now->diff($triggerTime);
260
+                    if ($diff->invert === 1) {
261
+                        // If an absolute alarm is in the past,
262
+                        // just add it to processedAlarms, so
263
+                        // we don't extend till eternity
264
+                        if (!$this->isAlarmRelative($valarm)) {
265
+                            $processedAlarms[] = $alarmHash;
266
+                        }
267
+
268
+                        continue;
269
+                    }
270
+
271
+                    $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring, false);
272
+                    $this->writeRemindersToDatabase($alarms);
273
+                    $processedAlarms[] = $alarmHash;
274
+                }
275
+
276
+                $iterator->next();
277
+            }
278
+        }
279
+    }
280
+
281
+    /**
282
+     * @param array $objectData
283
+     */
284
+    private function onCalendarObjectEdit(array $objectData):void {
285
+        // TODO - this can be vastly improved
286
+        //  - get cached reminders
287
+        //  - ...
288
+
289
+        $this->onCalendarObjectDelete($objectData);
290
+        $this->onCalendarObjectCreate($objectData);
291
+    }
292
+
293
+    /**
294
+     * @param array $objectData
295
+     */
296
+    private function onCalendarObjectDelete(array $objectData):void {
297
+        $this->backend->cleanRemindersForEvent((int) $objectData['id']);
298
+    }
299
+
300
+    /**
301
+     * @param VAlarm $valarm
302
+     * @param array $objectData
303
+     * @param string|null $eventHash
304
+     * @param string|null $alarmHash
305
+     * @param bool $isRecurring
306
+     * @param bool $isRecurrenceException
307
+     * @return array
308
+     */
309
+    private function getRemindersForVAlarm(VAlarm $valarm,
310
+                                            array $objectData,
311
+                                            string $eventHash=null,
312
+                                            string $alarmHash=null,
313
+                                            bool $isRecurring=false,
314
+                                            bool $isRecurrenceException=false):array {
315
+        if ($eventHash === null) {
316
+            $eventHash = $this->getEventHash($valarm->parent);
317
+        }
318
+        if ($alarmHash === null) {
319
+            $alarmHash = $this->getAlarmHash($valarm);
320
+        }
321
+
322
+        $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent);
323
+        $isRelative = $this->isAlarmRelative($valarm);
324
+        /** @var DateTimeImmutable $notificationDate */
325
+        $notificationDate = $valarm->getEffectiveTriggerTime();
326
+        $clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone());
327
+        $clonedNotificationDate->setTimestamp($notificationDate->getTimestamp());
328
+
329
+        $alarms = [];
330
+
331
+        $alarms[] = [
332
+            'calendar_id' => $objectData['calendarid'],
333
+            'object_id' => $objectData['id'],
334
+            'uid' => (string) $valarm->parent->UID,
335
+            'is_recurring' => $isRecurring,
336
+            'recurrence_id' => $recurrenceId,
337
+            'is_recurrence_exception' => $isRecurrenceException,
338
+            'event_hash' => $eventHash,
339
+            'alarm_hash' => $alarmHash,
340
+            'type' => (string) $valarm->ACTION,
341
+            'is_relative' => $isRelative,
342
+            'notification_date' => $notificationDate->getTimestamp(),
343
+            'is_repeat_based' => false,
344
+        ];
345
+
346
+        $repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
347
+        for($i = 0; $i < $repeat; $i++) {
348
+            if ($valarm->DURATION === null) {
349
+                continue;
350
+            }
351
+
352
+            $clonedNotificationDate->add($valarm->DURATION->getDateInterval());
353
+            $alarms[] = [
354
+                'calendar_id' => $objectData['calendarid'],
355
+                'object_id' => $objectData['id'],
356
+                'uid' => (string) $valarm->parent->UID,
357
+                'is_recurring' => $isRecurring,
358
+                'recurrence_id' => $recurrenceId,
359
+                'is_recurrence_exception' => $isRecurrenceException,
360
+                'event_hash' => $eventHash,
361
+                'alarm_hash' => $alarmHash,
362
+                'type' => (string) $valarm->ACTION,
363
+                'is_relative' => $isRelative,
364
+                'notification_date' => $clonedNotificationDate->getTimestamp(),
365
+                'is_repeat_based' => true,
366
+            ];
367
+        }
368
+
369
+        return $alarms;
370
+    }
371
+
372
+    /**
373
+     * @param array $reminders
374
+     */
375
+    private function writeRemindersToDatabase(array $reminders): void {
376
+        foreach($reminders as $reminder) {
377
+            $this->backend->insertReminder(
378
+                (int) $reminder['calendar_id'],
379
+                (int) $reminder['object_id'],
380
+                $reminder['uid'],
381
+                $reminder['is_recurring'],
382
+                (int) $reminder['recurrence_id'],
383
+                $reminder['is_recurrence_exception'],
384
+                $reminder['event_hash'],
385
+                $reminder['alarm_hash'],
386
+                $reminder['type'],
387
+                $reminder['is_relative'],
388
+                (int) $reminder['notification_date'],
389
+                $reminder['is_repeat_based']
390
+            );
391
+        }
392
+    }
393
+
394
+    /**
395
+     * @param array $reminder
396
+     * @param VEvent $vevent
397
+     */
398
+    private function deleteOrProcessNext(array $reminder,
399
+                                            VObject\Component\VEvent $vevent):void {
400
+        if ($reminder['is_repeat_based'] ||
401
+            !$reminder['is_recurring'] ||
402
+            !$reminder['is_relative'] ||
403
+            $reminder['is_recurrence_exception']) {
404
+
405
+            $this->backend->removeReminder($reminder['id']);
406
+            return;
407
+        }
408
+
409
+        $vevents = $this->getAllVEventsFromVCalendar($vevent->parent);
410
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
411
+        $now = $this->timeFactory->getDateTime();
412
+
413
+        try {
414
+            $iterator = new EventIterator($vevents, $reminder['uid']);
415
+        } catch (NoInstancesException $e) {
416
+            // This event is recurring, but it doesn't have a single
417
+            // instance. We are skipping this event from the output
418
+            // entirely.
419
+            return;
420
+        }
421
+
422
+        while($iterator->valid()) {
423
+            $event = $iterator->getEventObject();
424
+
425
+            // Recurrence-exceptions are handled separately, so just ignore them here
426
+            if (\in_array($event, $recurrenceExceptions, true)) {
427
+                $iterator->next();
428
+                continue;
429
+            }
430
+
431
+            $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($event);
432
+            if ($reminder['recurrence_id'] >= $recurrenceId) {
433
+                $iterator->next();
434
+                continue;
435
+            }
436
+
437
+            foreach($event->VALARM as $valarm) {
438
+                /** @var VAlarm $valarm */
439
+                $alarmHash = $this->getAlarmHash($valarm);
440
+                if ($alarmHash !== $reminder['alarm_hash']) {
441
+                    continue;
442
+                }
443
+
444
+                $triggerTime = $valarm->getEffectiveTriggerTime();
445
+
446
+                // If effective trigger time is in the past
447
+                // just skip and generate for next event
448
+                $diff = $now->diff($triggerTime);
449
+                if ($diff->invert === 1) {
450
+                    continue;
451
+                }
452
+
453
+                $this->backend->removeReminder($reminder['id']);
454
+                $alarms = $this->getRemindersForVAlarm($valarm, [
455
+                    'calendarid' => $reminder['calendar_id'],
456
+                    'id' => $reminder['object_id'],
457
+                ], $reminder['event_hash'], $alarmHash, true, false);
458
+                $this->writeRemindersToDatabase($alarms);
459
+
460
+                // Abort generating reminders after creating one successfully
461
+                return;
462
+            }
463
+
464
+            $iterator->next();
465
+        }
466
+
467
+        $this->backend->removeReminder($reminder['id']);
468
+    }
469
+
470
+    /**
471
+     * @param int $calendarId
472
+     * @return IUser[]
473
+     */
474
+    private function getAllUsersWithWriteAccessToCalendar(int $calendarId):array {
475
+        $shares = $this->caldavBackend->getShares($calendarId);
476
+
477
+        $users = [];
478
+        $userIds = [];
479
+        $groups = [];
480
+        foreach ($shares as $share) {
481
+            // Only consider writable shares
482
+            if ($share['readOnly']) {
483
+                continue;
484
+            }
485
+
486
+            $principal = explode('/', $share['{http://owncloud.org/ns}principal']);
487
+            if ($principal[1] === 'users') {
488
+                $user = $this->userManager->get($principal[2]);
489
+                if ($user) {
490
+                    $users[] = $user;
491
+                    $userIds[] = $principal[2];
492
+                }
493
+            } else if ($principal[1] === 'groups') {
494
+                $groups[] = $principal[2];
495
+            }
496
+        }
497
+
498
+        foreach ($groups as $gid) {
499
+            $group = $this->groupManager->get($gid);
500
+            if ($group instanceof IGroup) {
501
+                foreach ($group->getUsers() as $user) {
502
+                    if (!\in_array($user->getUID(), $userIds, true)) {
503
+                        $users[] = $user;
504
+                        $userIds[] = $user->getUID();
505
+                    }
506
+                }
507
+            }
508
+        }
509
+
510
+        return $users;
511
+    }
512
+
513
+    /**
514
+     * Gets a hash of the event.
515
+     * If the hash changes, we have to update all relative alarms.
516
+     *
517
+     * @param VEvent $vevent
518
+     * @return string
519
+     */
520
+    private function getEventHash(VEvent $vevent):string {
521
+        $properties = [
522
+            (string) $vevent->DTSTART->serialize(),
523
+        ];
524
+
525
+        if ($vevent->DTEND) {
526
+            $properties[] = (string) $vevent->DTEND->serialize();
527
+        }
528
+        if ($vevent->DURATION) {
529
+            $properties[] = (string) $vevent->DURATION->serialize();
530
+        }
531
+        if ($vevent->{'RECURRENCE-ID'}) {
532
+            $properties[] = (string) $vevent->{'RECURRENCE-ID'}->serialize();
533
+        }
534
+        if ($vevent->RRULE) {
535
+            $properties[] = (string) $vevent->RRULE->serialize();
536
+        }
537
+        if ($vevent->EXDATE) {
538
+            $properties[] = (string) $vevent->EXDATE->serialize();
539
+        }
540
+        if ($vevent->RDATE) {
541
+            $properties[] = (string) $vevent->RDATE->serialize();
542
+        }
543
+
544
+        return md5(implode('::', $properties));
545
+    }
546
+
547
+    /**
548
+     * Gets a hash of the alarm.
549
+     * If the hash changes, we have to update oc_dav_reminders.
550
+     *
551
+     * @param VAlarm $valarm
552
+     * @return string
553
+     */
554
+    private function getAlarmHash(VAlarm $valarm):string {
555
+        $properties = [
556
+            (string) $valarm->ACTION->serialize(),
557
+            (string) $valarm->TRIGGER->serialize(),
558
+        ];
559
+
560
+        if ($valarm->DURATION) {
561
+            $properties[] = (string) $valarm->DURATION->serialize();
562
+        }
563
+        if ($valarm->REPEAT) {
564
+            $properties[] = (string) $valarm->REPEAT->serialize();
565
+        }
566
+
567
+        return md5(implode('::', $properties));
568
+    }
569
+
570
+    /**
571
+     * @param VObject\Component\VCalendar $vcalendar
572
+     * @param int $recurrenceId
573
+     * @param bool $isRecurrenceException
574
+     * @return VEvent|null
575
+     */
576
+    private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
577
+                                                int $recurrenceId,
578
+                                                bool $isRecurrenceException):?VEvent {
579
+        $vevents = $this->getAllVEventsFromVCalendar($vcalendar);
580
+        if (count($vevents) === 0) {
581
+            return null;
582
+        }
583
+
584
+        $uid = (string) $vevents[0]->UID;
585
+        $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents);
586
+        $masterItem = $this->getMasterItemFromListOfVEvents($vevents);
587
+
588
+        // Handle recurrence-exceptions first, because recurrence-expansion is expensive
589
+        if ($isRecurrenceException) {
590
+            foreach($recurrenceExceptions as $recurrenceException) {
591
+                if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
592
+                    return $recurrenceException;
593
+                }
594
+            }
595
+
596
+            return null;
597
+        }
598
+
599
+        if ($masterItem) {
600
+            try {
601
+                $iterator = new EventIterator($vevents, $uid);
602
+            } catch (NoInstancesException $e) {
603
+                // This event is recurring, but it doesn't have a single
604
+                // instance. We are skipping this event from the output
605
+                // entirely.
606
+                return null;
607
+            }
608
+
609
+            while ($iterator->valid()) {
610
+                $event = $iterator->getEventObject();
611
+
612
+                // Recurrence-exceptions are handled separately, so just ignore them here
613
+                if (\in_array($event, $recurrenceExceptions, true)) {
614
+                    $iterator->next();
615
+                    continue;
616
+                }
617
+
618
+                if ($this->getEffectiveRecurrenceIdOfVEvent($event) === $recurrenceId) {
619
+                    return $event;
620
+                }
621
+
622
+                $iterator->next();
623
+            }
624
+        }
625
+
626
+        return null;
627
+    }
628
+
629
+    /**
630
+     * @param VEvent $vevent
631
+     * @return string
632
+     */
633
+    private function getStatusOfEvent(VEvent $vevent):string {
634
+        if ($vevent->STATUS) {
635
+            return (string) $vevent->STATUS;
636
+        }
637
+
638
+        // Doesn't say so in the standard,
639
+        // but we consider events without a status
640
+        // to be confirmed
641
+        return 'CONFIRMED';
642
+    }
643
+
644
+    /**
645
+     * @param VObject\Component\VEvent $vevent
646
+     * @return bool
647
+     */
648
+    private function wasEventCancelled(VObject\Component\VEvent $vevent):bool {
649
+        return $this->getStatusOfEvent($vevent) === 'CANCELLED';
650
+    }
651
+
652
+    /**
653
+     * @param string $calendarData
654
+     * @return VObject\Component\VCalendar|null
655
+     */
656
+    private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
657
+        try {
658
+            return VObject\Reader::read($calendarData,
659
+                VObject\Reader::OPTION_FORGIVING);
660
+        } catch(ParseException $ex) {
661
+            return null;
662
+        }
663
+    }
664
+
665
+    /**
666
+     * @param string $principalUri
667
+     * @return IUser|null
668
+     */
669
+    private function getUserFromPrincipalURI(string $principalUri):?IUser {
670
+        if (!$principalUri) {
671
+            return null;
672
+        }
673
+
674
+        if (stripos($principalUri, 'principals/users/') !== 0) {
675
+            return null;
676
+        }
677
+
678
+        $userId = substr($principalUri, 17);
679
+        return $this->userManager->get($userId);
680
+    }
681
+
682
+    /**
683
+     * @param VObject\Component\VCalendar $vcalendar
684
+     * @return VObject\Component\VEvent[]
685
+     */
686
+    private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
687
+        $vevents = [];
688
+
689
+        foreach($vcalendar->children() as $child) {
690
+            if (!($child instanceof VObject\Component)) {
691
+                continue;
692
+            }
693
+
694
+            if ($child->name !== 'VEVENT') {
695
+                continue;
696
+            }
697
+
698
+            $vevents[] = $child;
699
+        }
700
+
701
+        return $vevents;
702
+    }
703
+
704
+    /**
705
+     * @param array $vevents
706
+     * @return VObject\Component\VEvent[]
707
+     */
708
+    private function getRecurrenceExceptionFromListOfVEvents(array $vevents):array {
709
+        return array_values(array_filter($vevents, function(VEvent $vevent) {
710
+            return $vevent->{'RECURRENCE-ID'} !== null;
711
+        }));
712
+    }
713
+
714
+    /**
715
+     * @param array $vevents
716
+     * @return VEvent|null
717
+     */
718
+    private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
719
+        $elements = array_values(array_filter($vevents, function(VEvent $vevent) {
720
+            return $vevent->{'RECURRENCE-ID'} === null;
721
+        }));
722
+
723
+        if (count($elements) === 0) {
724
+            return null;
725
+        }
726
+        if (count($elements) > 1) {
727
+            throw new \TypeError('Multiple master objects');
728
+        }
729
+
730
+        return $elements[0];
731
+    }
732
+
733
+    /**
734
+     * @param VAlarm $valarm
735
+     * @return bool
736
+     */
737
+    private function isAlarmRelative(VAlarm $valarm):bool {
738
+        $trigger = $valarm->TRIGGER;
739
+        return $trigger instanceof VObject\Property\ICalendar\Duration;
740
+    }
741
+
742
+    /**
743
+     * @param VEvent $vevent
744
+     * @return int
745
+     */
746
+    private function getEffectiveRecurrenceIdOfVEvent(VEvent $vevent):int {
747
+        if (isset($vevent->{'RECURRENCE-ID'})) {
748
+            return $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp();
749
+        }
750
+
751
+        return $vevent->DTSTART->getDateTime()->getTimestamp();
752
+    }
753
+
754
+    /**
755
+     * @param VEvent $vevent
756
+     * @return bool
757
+     */
758
+    private function isRecurring(VEvent $vevent):bool {
759
+        return isset($vevent->RRULE) || isset($vevent->RDATE);
760
+    }
761 761
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	public function processReminders():void {
107 107
 		$reminders = $this->backend->getRemindersToProcess();
108 108
 
109
-		foreach($reminders as $reminder) {
109
+		foreach ($reminders as $reminder) {
110 110
 			$vcalendar = $this->parseCalendarData($reminder['calendardata']);
111 111
 			if (!$vcalendar) {
112 112
 				$this->backend->removeReminder($reminder['id']);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 			return;
155 155
 		}
156 156
 
157
-		switch($action) {
157
+		switch ($action) {
158 158
 			case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject':
159 159
 				$this->onCalendarObjectCreate($objectData);
160 160
 				break;
@@ -193,10 +193,10 @@  discard block
 block discarded – undo
193 193
 		$now = $this->timeFactory->getDateTime();
194 194
 		$isRecurring = $masterItem ? $this->isRecurring($masterItem) : false;
195 195
 
196
-		foreach($recurrenceExceptions as $recurrenceException) {
196
+		foreach ($recurrenceExceptions as $recurrenceException) {
197 197
 			$eventHash = $this->getEventHash($recurrenceException);
198 198
 
199
-			foreach($recurrenceException->VALARM as $valarm) {
199
+			foreach ($recurrenceException->VALARM as $valarm) {
200 200
 				/** @var VAlarm $valarm */
201 201
 				$alarmHash = $this->getAlarmHash($valarm);
202 202
 				$triggerTime = $valarm->getEffectiveTriggerTime();
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 			$masterAlarms = [];
217 217
 			$masterHash = $this->getEventHash($masterItem);
218 218
 
219
-			foreach($masterItem->VALARM as $valarm) {
219
+			foreach ($masterItem->VALARM as $valarm) {
220 220
 				$masterAlarms[] = $this->getAlarmHash($valarm);
221 221
 			}
222 222
 
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 				return;
230 230
 			}
231 231
 
232
-			while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
232
+			while ($iterator->valid() && count($processedAlarms) < count($masterAlarms)) {
233 233
 				$event = $iterator->getEventObject();
234 234
 
235 235
 				// Recurrence-exceptions are handled separately, so just ignore them here
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 					continue;
239 239
 				}
240 240
 
241
-				foreach($event->VALARM as $valarm) {
241
+				foreach ($event->VALARM as $valarm) {
242 242
 					/** @var VAlarm $valarm */
243 243
 					$alarmHash = $this->getAlarmHash($valarm);
244 244
 					if (\in_array($alarmHash, $processedAlarms, true)) {
@@ -308,10 +308,10 @@  discard block
 block discarded – undo
308 308
 	 */
309 309
 	private function getRemindersForVAlarm(VAlarm $valarm,
310 310
 										   array $objectData,
311
-										   string $eventHash=null,
312
-										   string $alarmHash=null,
313
-										   bool $isRecurring=false,
314
-										   bool $isRecurrenceException=false):array {
311
+										   string $eventHash = null,
312
+										   string $alarmHash = null,
313
+										   bool $isRecurring = false,
314
+										   bool $isRecurrenceException = false):array {
315 315
 		if ($eventHash === null) {
316 316
 			$eventHash = $this->getEventHash($valarm->parent);
317 317
 		}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 		];
345 345
 
346 346
 		$repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
347
-		for($i = 0; $i < $repeat; $i++) {
347
+		for ($i = 0; $i < $repeat; $i++) {
348 348
 			if ($valarm->DURATION === null) {
349 349
 				continue;
350 350
 			}
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 	 * @param array $reminders
374 374
 	 */
375 375
 	private function writeRemindersToDatabase(array $reminders): void {
376
-		foreach($reminders as $reminder) {
376
+		foreach ($reminders as $reminder) {
377 377
 			$this->backend->insertReminder(
378 378
 				(int) $reminder['calendar_id'],
379 379
 				(int) $reminder['object_id'],
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 			return;
420 420
 		}
421 421
 
422
-		while($iterator->valid()) {
422
+		while ($iterator->valid()) {
423 423
 			$event = $iterator->getEventObject();
424 424
 
425 425
 			// Recurrence-exceptions are handled separately, so just ignore them here
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 				continue;
435 435
 			}
436 436
 
437
-			foreach($event->VALARM as $valarm) {
437
+			foreach ($event->VALARM as $valarm) {
438 438
 				/** @var VAlarm $valarm */
439 439
 				$alarmHash = $this->getAlarmHash($valarm);
440 440
 				if ($alarmHash !== $reminder['alarm_hash']) {
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 	 */
576 576
 	private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar,
577 577
 											 int $recurrenceId,
578
-											 bool $isRecurrenceException):?VEvent {
578
+											 bool $isRecurrenceException): ?VEvent {
579 579
 		$vevents = $this->getAllVEventsFromVCalendar($vcalendar);
580 580
 		if (count($vevents) === 0) {
581 581
 			return null;
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
 
588 588
 		// Handle recurrence-exceptions first, because recurrence-expansion is expensive
589 589
 		if ($isRecurrenceException) {
590
-			foreach($recurrenceExceptions as $recurrenceException) {
590
+			foreach ($recurrenceExceptions as $recurrenceException) {
591 591
 				if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) {
592 592
 					return $recurrenceException;
593 593
 				}
@@ -653,11 +653,11 @@  discard block
 block discarded – undo
653 653
 	 * @param string $calendarData
654 654
 	 * @return VObject\Component\VCalendar|null
655 655
 	 */
656
-	private function parseCalendarData(string $calendarData):?VObject\Component\VCalendar {
656
+	private function parseCalendarData(string $calendarData): ?VObject\Component\VCalendar {
657 657
 		try {
658 658
 			return VObject\Reader::read($calendarData,
659 659
 				VObject\Reader::OPTION_FORGIVING);
660
-		} catch(ParseException $ex) {
660
+		} catch (ParseException $ex) {
661 661
 			return null;
662 662
 		}
663 663
 	}
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 	 * @param string $principalUri
667 667
 	 * @return IUser|null
668 668
 	 */
669
-	private function getUserFromPrincipalURI(string $principalUri):?IUser {
669
+	private function getUserFromPrincipalURI(string $principalUri): ?IUser {
670 670
 		if (!$principalUri) {
671 671
 			return null;
672 672
 		}
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 	private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array {
687 687
 		$vevents = [];
688 688
 
689
-		foreach($vcalendar->children() as $child) {
689
+		foreach ($vcalendar->children() as $child) {
690 690
 			if (!($child instanceof VObject\Component)) {
691 691
 				continue;
692 692
 			}
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 	 * @param array $vevents
716 716
 	 * @return VEvent|null
717 717
 	 */
718
-	private function getMasterItemFromListOfVEvents(array $vevents):?VEvent {
718
+	private function getMasterItemFromListOfVEvents(array $vevents): ?VEvent {
719 719
 		$elements = array_values(array_filter($vevents, function(VEvent $vevent) {
720 720
 			return $vevent->{'RECURRENCE-ID'} === null;
721 721
 		}));
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -31,51 +31,51 @@
 block discarded – undo
31 31
  */
32 32
 class NotificationProviderManager {
33 33
 
34
-	/** @var INotificationProvider[] */
35
-	private $providers = [];
34
+    /** @var INotificationProvider[] */
35
+    private $providers = [];
36 36
 
37
-	/**
38
-	 * Checks whether a provider for a given ACTION exists
39
-	 *
40
-	 * @param string $type
41
-	 * @return bool
42
-	 */
43
-	public function hasProvider(string $type):bool {
44
-		return (\in_array($type, ReminderService::REMINDER_TYPES, true)
45
-			&& isset($this->providers[$type]));
46
-	}
37
+    /**
38
+     * Checks whether a provider for a given ACTION exists
39
+     *
40
+     * @param string $type
41
+     * @return bool
42
+     */
43
+    public function hasProvider(string $type):bool {
44
+        return (\in_array($type, ReminderService::REMINDER_TYPES, true)
45
+            && isset($this->providers[$type]));
46
+    }
47 47
 
48
-	/**
49
-	 * Get provider for a given ACTION
50
-	 *
51
-	 * @param string $type
52
-	 * @return INotificationProvider
53
-	 * @throws NotificationProvider\ProviderNotAvailableException
54
-	 * @throws NotificationTypeDoesNotExistException
55
-	 */
56
-	public function getProvider(string $type):INotificationProvider {
57
-		if (in_array($type, ReminderService::REMINDER_TYPES, true)) {
58
-			if (isset($this->providers[$type])) {
59
-				return $this->providers[$type];
60
-			}
61
-			throw new NotificationProvider\ProviderNotAvailableException($type);
62
-		}
63
-		throw new NotificationTypeDoesNotExistException($type);
64
-	}
48
+    /**
49
+     * Get provider for a given ACTION
50
+     *
51
+     * @param string $type
52
+     * @return INotificationProvider
53
+     * @throws NotificationProvider\ProviderNotAvailableException
54
+     * @throws NotificationTypeDoesNotExistException
55
+     */
56
+    public function getProvider(string $type):INotificationProvider {
57
+        if (in_array($type, ReminderService::REMINDER_TYPES, true)) {
58
+            if (isset($this->providers[$type])) {
59
+                return $this->providers[$type];
60
+            }
61
+            throw new NotificationProvider\ProviderNotAvailableException($type);
62
+        }
63
+        throw new NotificationTypeDoesNotExistException($type);
64
+    }
65 65
 
66
-	/**
67
-	 * Registers a new provider
68
-	 *
69
-	 * @param string $providerClassName
70
-	 * @throws \OCP\AppFramework\QueryException
71
-	 */
72
-	public function registerProvider(string $providerClassName):void {
73
-		$provider = \OC::$server->query($providerClassName);
66
+    /**
67
+     * Registers a new provider
68
+     *
69
+     * @param string $providerClassName
70
+     * @throws \OCP\AppFramework\QueryException
71
+     */
72
+    public function registerProvider(string $providerClassName):void {
73
+        $provider = \OC::$server->query($providerClassName);
74 74
 
75
-		if (!$provider instanceof INotificationProvider) {
76
-			throw new \InvalidArgumentException('Invalid notification provider registered');
77
-		}
75
+        if (!$provider instanceof INotificationProvider) {
76
+            throw new \InvalidArgumentException('Invalid notification provider registered');
77
+        }
78 78
 
79
-		$this->providers[$provider::NOTIFICATION_TYPE] = $provider;
80
-	}
79
+        $this->providers[$provider::NOTIFICATION_TYPE] = $provider;
80
+    }
81 81
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/NotificationTypeDoesNotExistException.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -26,15 +26,15 @@
 block discarded – undo
26 26
 
27 27
 class NotificationTypeDoesNotExistException extends \Exception {
28 28
 
29
-	/**
30
-	 * NotificationTypeDoesNotExistException constructor.
31
-	 *
32
-	 * @since 16.0.0
33
-	 *
34
-	 * @param string $type ReminderType
35
-	 */
36
-	public function __construct(string $type) {
37
-		parent::__construct("Type $type is not an accepted type of notification");
38
-	}
29
+    /**
30
+     * NotificationTypeDoesNotExistException constructor.
31
+     *
32
+     * @since 16.0.0
33
+     *
34
+     * @param string $type ReminderType
35
+     */
36
+    public function __construct(string $type) {
37
+        parent::__construct("Type $type is not an accepted type of notification");
38
+    }
39 39
 
40 40
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -43,146 +43,146 @@
 block discarded – undo
43 43
  */
44 44
 abstract class AbstractProvider implements INotificationProvider  {
45 45
 
46
-	/** @var string */
47
-	public const NOTIFICATION_TYPE = '';
48
-
49
-	/** @var ILogger */
50
-	protected $logger;
51
-
52
-	/** @var L10NFactory */
53
-	private $l10nFactory;
54
-
55
-	/** @var IL10N[] */
56
-	private $l10ns;
57
-
58
-	/** @var string */
59
-	private $fallbackLanguage;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var IConfig */
65
-	protected $config;
66
-
67
-	/**
68
-	 * @param ILogger $logger
69
-	 * @param L10NFactory $l10nFactory
70
-	 * @param IConfig $config
71
-	 * @param IUrlGenerator $urlGenerator
72
-	 */
73
-	public function __construct(ILogger $logger,
74
-								L10NFactory $l10nFactory,
75
-								IURLGenerator $urlGenerator,
76
-								IConfig $config) {
77
-		$this->logger = $logger;
78
-		$this->l10nFactory = $l10nFactory;
79
-		$this->urlGenerator = $urlGenerator;
80
-		$this->config = $config;
81
-	}
82
-
83
-	/**
84
-	 * Send notification
85
-	 *
86
-	 * @param VEvent $vevent
87
-	 * @param string $calendarDisplayName
88
-	 * @param IUser[] $users
89
-	 * @return void
90
-	 */
91
-	abstract public function send(VEvent $vevent,
92
-						   string $calendarDisplayName,
93
-						   array $users=[]): void;
94
-
95
-	/**
96
-	 * @return string
97
-	 */
98
-	protected function getFallbackLanguage():string {
99
-		if ($this->fallbackLanguage) {
100
-			return $this->fallbackLanguage;
101
-		}
102
-
103
-		$fallbackLanguage = $this->l10nFactory->findLanguage();
104
-		$this->fallbackLanguage = $fallbackLanguage;
105
-
106
-		return $fallbackLanguage;
107
-	}
108
-
109
-	/**
110
-	 * @param string $lang
111
-	 * @return bool
112
-	 */
113
-	protected function hasL10NForLang(string $lang):bool {
114
-		return $this->l10nFactory->languageExists('dav', $lang);
115
-	}
116
-
117
-	/**
118
-	 * @param string $lang
119
-	 * @return IL10N
120
-	 */
121
-	protected function getL10NForLang(string $lang):IL10N {
122
-		if (isset($this->l10ns[$lang])) {
123
-			return $this->l10ns[$lang];
124
-		}
125
-
126
-		$l10n = $this->l10nFactory->get('dav', $lang);
127
-		$this->l10ns[$lang] = $l10n;
128
-
129
-		return $l10n;
130
-	}
131
-
132
-	/**
133
-	 * @param VEvent $vevent
134
-	 * @return string
135
-	 */
136
-	private function getStatusOfEvent(VEvent $vevent):string {
137
-		if ($vevent->STATUS) {
138
-			return (string) $vevent->STATUS;
139
-		}
140
-
141
-		// Doesn't say so in the standard,
142
-		// but we consider events without a status
143
-		// to be confirmed
144
-		return 'CONFIRMED';
145
-	}
146
-
147
-	/**
148
-	 * @param VEvent $vevent
149
-	 * @return bool
150
-	 */
151
-	protected function isEventTentative(VEvent $vevent):bool {
152
-		return $this->getStatusOfEvent($vevent) === 'TENTATIVE';
153
-	}
154
-
155
-	/**
156
-	 * @param VEvent $vevent
157
-	 * @return Property\ICalendar\DateTime
158
-	 */
159
-	protected function getDTEndFromEvent(VEvent $vevent):Property\ICalendar\DateTime {
160
-		if (isset($vevent->DTEND)) {
161
-			return $vevent->DTEND;
162
-		}
163
-
164
-		if (isset($vevent->DURATION)) {
165
-			$isFloating = $vevent->DTSTART->isFloating();
166
-			/** @var Property\ICalendar\DateTime $end */
167
-			$end = clone $vevent->DTSTART;
168
-			$endDateTime = $end->getDateTime();
169
-			$endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
170
-			$end->setDateTime($endDateTime, $isFloating);
171
-
172
-			return $end;
173
-		}
174
-
175
-		if (!$vevent->DTSTART->hasTime()) {
176
-			$isFloating = $vevent->DTSTART->isFloating();
177
-			/** @var Property\ICalendar\DateTime $end */
178
-			$end = clone $vevent->DTSTART;
179
-			$endDateTime = $end->getDateTime();
180
-			$endDateTime = $endDateTime->modify('+1 day');
181
-			$end->setDateTime($endDateTime, $isFloating);
182
-
183
-			return $end;
184
-		}
185
-
186
-		return clone $vevent->DTSTART;
187
-	}
46
+    /** @var string */
47
+    public const NOTIFICATION_TYPE = '';
48
+
49
+    /** @var ILogger */
50
+    protected $logger;
51
+
52
+    /** @var L10NFactory */
53
+    private $l10nFactory;
54
+
55
+    /** @var IL10N[] */
56
+    private $l10ns;
57
+
58
+    /** @var string */
59
+    private $fallbackLanguage;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var IConfig */
65
+    protected $config;
66
+
67
+    /**
68
+     * @param ILogger $logger
69
+     * @param L10NFactory $l10nFactory
70
+     * @param IConfig $config
71
+     * @param IUrlGenerator $urlGenerator
72
+     */
73
+    public function __construct(ILogger $logger,
74
+                                L10NFactory $l10nFactory,
75
+                                IURLGenerator $urlGenerator,
76
+                                IConfig $config) {
77
+        $this->logger = $logger;
78
+        $this->l10nFactory = $l10nFactory;
79
+        $this->urlGenerator = $urlGenerator;
80
+        $this->config = $config;
81
+    }
82
+
83
+    /**
84
+     * Send notification
85
+     *
86
+     * @param VEvent $vevent
87
+     * @param string $calendarDisplayName
88
+     * @param IUser[] $users
89
+     * @return void
90
+     */
91
+    abstract public function send(VEvent $vevent,
92
+                            string $calendarDisplayName,
93
+                            array $users=[]): void;
94
+
95
+    /**
96
+     * @return string
97
+     */
98
+    protected function getFallbackLanguage():string {
99
+        if ($this->fallbackLanguage) {
100
+            return $this->fallbackLanguage;
101
+        }
102
+
103
+        $fallbackLanguage = $this->l10nFactory->findLanguage();
104
+        $this->fallbackLanguage = $fallbackLanguage;
105
+
106
+        return $fallbackLanguage;
107
+    }
108
+
109
+    /**
110
+     * @param string $lang
111
+     * @return bool
112
+     */
113
+    protected function hasL10NForLang(string $lang):bool {
114
+        return $this->l10nFactory->languageExists('dav', $lang);
115
+    }
116
+
117
+    /**
118
+     * @param string $lang
119
+     * @return IL10N
120
+     */
121
+    protected function getL10NForLang(string $lang):IL10N {
122
+        if (isset($this->l10ns[$lang])) {
123
+            return $this->l10ns[$lang];
124
+        }
125
+
126
+        $l10n = $this->l10nFactory->get('dav', $lang);
127
+        $this->l10ns[$lang] = $l10n;
128
+
129
+        return $l10n;
130
+    }
131
+
132
+    /**
133
+     * @param VEvent $vevent
134
+     * @return string
135
+     */
136
+    private function getStatusOfEvent(VEvent $vevent):string {
137
+        if ($vevent->STATUS) {
138
+            return (string) $vevent->STATUS;
139
+        }
140
+
141
+        // Doesn't say so in the standard,
142
+        // but we consider events without a status
143
+        // to be confirmed
144
+        return 'CONFIRMED';
145
+    }
146
+
147
+    /**
148
+     * @param VEvent $vevent
149
+     * @return bool
150
+     */
151
+    protected function isEventTentative(VEvent $vevent):bool {
152
+        return $this->getStatusOfEvent($vevent) === 'TENTATIVE';
153
+    }
154
+
155
+    /**
156
+     * @param VEvent $vevent
157
+     * @return Property\ICalendar\DateTime
158
+     */
159
+    protected function getDTEndFromEvent(VEvent $vevent):Property\ICalendar\DateTime {
160
+        if (isset($vevent->DTEND)) {
161
+            return $vevent->DTEND;
162
+        }
163
+
164
+        if (isset($vevent->DURATION)) {
165
+            $isFloating = $vevent->DTSTART->isFloating();
166
+            /** @var Property\ICalendar\DateTime $end */
167
+            $end = clone $vevent->DTSTART;
168
+            $endDateTime = $end->getDateTime();
169
+            $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
170
+            $end->setDateTime($endDateTime, $isFloating);
171
+
172
+            return $end;
173
+        }
174
+
175
+        if (!$vevent->DTSTART->hasTime()) {
176
+            $isFloating = $vevent->DTSTART->isFloating();
177
+            /** @var Property\ICalendar\DateTime $end */
178
+            $end = clone $vevent->DTSTART;
179
+            $endDateTime = $end->getDateTime();
180
+            $endDateTime = $endDateTime->modify('+1 day');
181
+            $end->setDateTime($endDateTime, $isFloating);
182
+
183
+            return $end;
184
+        }
185
+
186
+        return clone $vevent->DTSTART;
187
+    }
188 188
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
  *
42 42
  * @package OCA\DAV\CalDAV\Reminder\NotificationProvider
43 43
  */
44
-abstract class AbstractProvider implements INotificationProvider  {
44
+abstract class AbstractProvider implements INotificationProvider {
45 45
 
46 46
 	/** @var string */
47 47
 	public const NOTIFICATION_TYPE = '';
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 	 */
91 91
 	abstract public function send(VEvent $vevent,
92 92
 						   string $calendarDisplayName,
93
-						   array $users=[]): void;
93
+						   array $users = []): void;
94 94
 
95 95
 	/**
96 96
 	 * @return string
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php 2 patches
Indentation   +454 added lines, -454 removed lines patch added patch discarded remove patch
@@ -46,458 +46,458 @@
 block discarded – undo
46 46
  */
47 47
 class EmailProvider extends AbstractProvider {
48 48
 
49
-	/** @var string */
50
-	public const NOTIFICATION_TYPE = 'EMAIL';
51
-
52
-	/** @var IMailer */
53
-	private $mailer;
54
-
55
-	/**
56
-	 * @param IConfig $config
57
-	 * @param IMailer $mailer
58
-	 * @param ILogger $logger
59
-	 * @param L10NFactory $l10nFactory
60
-	 * @param IUrlGenerator $urlGenerator
61
-	 */
62
-	public function __construct(IConfig $config,
63
-								IMailer $mailer,
64
-								ILogger $logger,
65
-								L10NFactory $l10nFactory,
66
-								IURLGenerator $urlGenerator) {
67
-		parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
68
-		$this->mailer = $mailer;
69
-	}
70
-
71
-	/**
72
-	 * Send out notification via email
73
-	 *
74
-	 * @param VEvent $vevent
75
-	 * @param string $calendarDisplayName
76
-	 * @param array $users
77
-	 * @throws \Exception
78
-	 */
79
-	public function send(VEvent $vevent,
80
-						 string $calendarDisplayName,
81
-						 array $users=[]):void {
82
-		$fallbackLanguage = $this->getFallbackLanguage();
83
-
84
-		$emailAddressesOfSharees = $this->getEMailAddressesOfAllUsersWithWriteAccessToCalendar($users);
85
-		$emailAddressesOfAttendees = $this->getAllEMailAddressesFromEvent($vevent);
86
-
87
-		// Quote from php.net:
88
-		// If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
89
-		// => if there are duplicate email addresses, it will always take the system value
90
-		$emailAddresses = array_merge(
91
-			$emailAddressesOfAttendees,
92
-			$emailAddressesOfSharees
93
-		);
94
-
95
-		$sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage);
96
-		$organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);
97
-
98
-		foreach($sortedByLanguage as $lang => $emailAddresses) {
99
-			if (!$this->hasL10NForLang($lang)) {
100
-				$lang = $fallbackLanguage;
101
-			}
102
-			$l10n = $this->getL10NForLang($lang);
103
-			$fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply');
104
-
105
-			$template = $this->mailer->createEMailTemplate('dav.calendarReminder');
106
-			$template->addHeader();
107
-			$this->addSubjectAndHeading($template, $l10n, $vevent);
108
-			$this->addBulletList($template, $l10n, $calendarDisplayName, $vevent);
109
-			$template->addFooter();
110
-
111
-			foreach ($emailAddresses as $emailAddress) {
112
-				$message = $this->mailer->createMessage();
113
-				$message->setFrom([$fromEMail]);
114
-				if ($organizer) {
115
-					$message->setReplyTo($organizer);
116
-				}
117
-				$message->setTo([$emailAddress]);
118
-				$message->useTemplate($template);
119
-
120
-				try {
121
-					$failed = $this->mailer->send($message);
122
-					if ($failed) {
123
-						$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
124
-					}
125
-				} catch (\Exception $ex) {
126
-					$this->logger->logException($ex, ['app' => 'dav']);
127
-				}
128
-			}
129
-		}
130
-	}
131
-
132
-	/**
133
-	 * @param IEMailTemplate $template
134
-	 * @param IL10N $l10n
135
-	 * @param VEvent $vevent
136
-	 */
137
-	private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEvent $vevent):void {
138
-		$template->setSubject('Notification: ' . $this->getTitleFromVEvent($vevent, $l10n));
139
-		$template->addHeading($this->getTitleFromVEvent($vevent, $l10n));
140
-	}
141
-
142
-	/**
143
-	 * @param IEMailTemplate $template
144
-	 * @param IL10N $l10n
145
-	 * @param string $calendarDisplayName
146
-	 * @param array $eventData
147
-	 */
148
-	private function addBulletList(IEMailTemplate $template,
149
-								   IL10N $l10n,
150
-								   string $calendarDisplayName,
151
-								   VEvent $vevent):void {
152
-		$template->addBodyListItem($calendarDisplayName, $l10n->t('Calendar:'),
153
-			$this->getAbsoluteImagePath('actions/info.svg'));
154
-
155
-		$template->addBodyListItem($this->generateDateString($l10n, $vevent), $l10n->t('Date:'),
156
-			$this->getAbsoluteImagePath('places/calendar.svg'));
157
-
158
-		if (isset($vevent->LOCATION)) {
159
-			$template->addBodyListItem((string) $vevent->LOCATION, $l10n->t('Where:'),
160
-				$this->getAbsoluteImagePath('actions/address.svg'));
161
-		}
162
-		if (isset($vevent->DESCRIPTION)) {
163
-			$template->addBodyListItem((string) $vevent->DESCRIPTION, $l10n->t('Description:'),
164
-				$this->getAbsoluteImagePath('actions/more.svg'));
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return string
171
-	 */
172
-	private function getAbsoluteImagePath(string $path):string {
173
-		return $this->urlGenerator->getAbsoluteURL(
174
-			$this->urlGenerator->imagePath('core', $path)
175
-		);
176
-	}
177
-
178
-	/**
179
-	 * @param VEvent $vevent
180
-	 * @return array|null
181
-	 */
182
-	private function getOrganizerEMailAndNameFromEvent(VEvent $vevent):?array {
183
-		if (!$vevent->ORGANIZER) {
184
-			return null;
185
-		}
186
-
187
-		$organizer = $vevent->ORGANIZER;
188
-		if (strcasecmp($organizer->getValue(), 'mailto:') !== 0) {
189
-			return null;
190
-		}
191
-
192
-		$organizerEMail = substr($organizer->getValue(), 7);
193
-
194
-		$name = $organizer->offsetGet('CN');
195
-		if ($name instanceof Parameter) {
196
-			return [$organizerEMail => $name];
197
-		}
198
-
199
-		return [$organizerEMail];
200
-	}
201
-
202
-	/**
203
-	 * @param array $emails
204
-	 * @param string $defaultLanguage
205
-	 * @return array
206
-	 */
207
-	private function sortEMailAddressesByLanguage(array $emails,
208
-												  string $defaultLanguage):array {
209
-		$sortedByLanguage = [];
210
-
211
-		foreach($emails as $emailAddress => $parameters) {
212
-			if (isset($parameters['LANG'])) {
213
-				$lang = $parameters['LANG'];
214
-			} else {
215
-				$lang = $defaultLanguage;
216
-			}
217
-
218
-			if (!isset($sortedByLanguage[$lang])) {
219
-				$sortedByLanguage[$lang] = [];
220
-			}
221
-
222
-			$sortedByLanguage[$lang][] = $emailAddress;
223
-		}
224
-
225
-		return $sortedByLanguage;
226
-	}
227
-
228
-	/**
229
-	 * @param VEvent $vevent
230
-	 * @return array
231
-	 */
232
-	private function getAllEMailAddressesFromEvent(VEvent $vevent):array {
233
-		$emailAddresses = [];
234
-
235
-		if (isset($vevent->ATTENDEE)) {
236
-			foreach ($vevent->ATTENDEE as $attendee) {
237
-				if (!($attendee instanceof VObject\Property)) {
238
-					continue;
239
-				}
240
-
241
-				$cuType = $this->getCUTypeOfAttendee($attendee);
242
-				if (\in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) {
243
-					// Don't send emails to things
244
-					continue;
245
-				}
246
-
247
-				$partstat = $this->getPartstatOfAttendee($attendee);
248
-				if ($partstat === 'DECLINED') {
249
-					// Don't send out emails to people who declined
250
-					continue;
251
-				}
252
-				if ($partstat === 'DELEGATED') {
253
-					$delegates = $attendee->offsetGet('DELEGATED-TO');
254
-					if (!($delegates instanceof VObject\Parameter)) {
255
-						continue;
256
-					}
257
-
258
-					$emailAddressesOfDelegates = $delegates->getParts();
259
-					foreach($emailAddressesOfDelegates as $addressesOfDelegate) {
260
-						if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) {
261
-							$emailAddresses[substr($addressesOfDelegate, 7)] = [];
262
-						}
263
-					}
264
-
265
-					continue;
266
-				}
267
-
268
-				$emailAddressOfAttendee = $this->getEMailAddressOfAttendee($attendee);
269
-				if ($emailAddressOfAttendee !== null) {
270
-					$properties = [];
271
-
272
-					$langProp = $attendee->offsetGet('LANG');
273
-					if ($langProp instanceof VObject\Parameter) {
274
-						$properties['LANG'] = $langProp->getValue();
275
-					}
276
-
277
-					$emailAddresses[$emailAddressOfAttendee] = $properties;
278
-				}
279
-			}
280
-		}
281
-
282
-		if (isset($vevent->ORGANIZER) && $this->hasAttendeeMailURI($vevent->ORGANIZER)) {
283
-			$emailAddresses[$this->getEMailAddressOfAttendee($vevent->ORGANIZER)] = [];
284
-		}
285
-
286
-		return $emailAddresses;
287
-	}
288
-
289
-
290
-
291
-	/**
292
-	 * @param VObject\Property $attendee
293
-	 * @return string
294
-	 */
295
-	private function getCUTypeOfAttendee(VObject\Property $attendee):string {
296
-		$cuType = $attendee->offsetGet('CUTYPE');
297
-		if ($cuType instanceof VObject\Parameter) {
298
-			return strtoupper($cuType->getValue());
299
-		}
300
-
301
-		return 'INDIVIDUAL';
302
-	}
303
-
304
-	/**
305
-	 * @param VObject\Property $attendee
306
-	 * @return string
307
-	 */
308
-	private function getPartstatOfAttendee(VObject\Property $attendee):string {
309
-		$partstat = $attendee->offsetGet('PARTSTAT');
310
-		if ($partstat instanceof VObject\Parameter) {
311
-			return strtoupper($partstat->getValue());
312
-		}
313
-
314
-		return 'NEEDS-ACTION';
315
-	}
316
-
317
-	/**
318
-	 * @param VObject\Property $attendee
319
-	 * @return bool
320
-	 */
321
-	private function hasAttendeeMailURI(VObject\Property $attendee):bool {
322
-		return stripos($attendee->getValue(), 'mailto:') === 0;
323
-	}
324
-
325
-	/**
326
-	 * @param VObject\Property $attendee
327
-	 * @return string|null
328
-	 */
329
-	private function getEMailAddressOfAttendee(VObject\Property $attendee):?string {
330
-		if (!$this->hasAttendeeMailURI($attendee)) {
331
-			return null;
332
-		}
333
-
334
-		return substr($attendee->getValue(), 7);
335
-	}
336
-
337
-	/**
338
-	 * @param array $users
339
-	 * @return array
340
-	 */
341
-	private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array {
342
-		$emailAddresses = [];
343
-
344
-		foreach($users as $user) {
345
-			$emailAddress = $user->getEMailAddress();
346
-			if ($emailAddress) {
347
-				$lang = $this->getLangForUser($user);
348
-				if ($lang) {
349
-					$emailAddresses[$emailAddress] = [
350
-						'LANG' => $lang,
351
-					];
352
-				} else {
353
-					$emailAddresses[$emailAddress] = [];
354
-				}
355
-			}
356
-		}
357
-
358
-		return $emailAddresses;
359
-	}
360
-
361
-	/**
362
-	 * @param IUser $user
363
-	 * @return string
364
-	 */
365
-	private function getLangForUser(IUser $user): ?string {
366
-		return $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
367
-	}
368
-
369
-	/**
370
-	 * @param IL10N $l10n
371
-	 * @param VEvent $vevent
372
-	 * @return string
373
-	 * @throws \Exception
374
-	 */
375
-	private function generateDateString(IL10N $l10n, VEvent $vevent):string {
376
-		$isAllDay = $vevent->DTSTART instanceof Property\ICalendar\Date;
377
-
378
-		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
379
-		/** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
380
-		/** @var \DateTimeImmutable $dtstartDt */
381
-		$dtstartDt = $vevent->DTSTART->getDateTime();
382
-		/** @var \DateTimeImmutable $dtendDt */
383
-		$dtendDt = $this->getDTEndFromEvent($vevent)->getDateTime();
384
-
385
-		$diff = $dtstartDt->diff($dtendDt);
386
-
387
-		/** @phan-suppress-next-line PhanUndeclaredClassMethod */
388
-		$dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
389
-		/** @phan-suppress-next-line PhanUndeclaredClassMethod */
390
-		$dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
391
-
392
-		if ($isAllDay) {
393
-			// One day event
394
-			if ($diff->days === 1) {
395
-				return $this->getDateString($l10n, $dtstartDt);
396
-			}
397
-
398
-			return implode(' - ', [
399
-				$this->getDateString($l10n, $dtstartDt),
400
-				$this->getDateString($l10n, $dtendDt),
401
-			]);
402
-		}
403
-
404
-		$startTimezone = $endTimezone = null;
405
-		if (!$vevent->DTSTART->isFloating()) {
406
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
407
-			$startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName();
408
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
409
-			$endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName();
410
-		}
411
-
412
-		$localeStart = implode(', ', [
413
-			$this->getWeekDayName($l10n, $dtstartDt),
414
-			$this->getDateTimeString($l10n, $dtstartDt)
415
-		]);
416
-
417
-		// always show full date with timezone if timezones are different
418
-		if ($startTimezone !== $endTimezone) {
419
-			$localeEnd = implode(', ', [
420
-				$this->getWeekDayName($l10n, $dtendDt),
421
-				$this->getDateTimeString($l10n, $dtendDt)
422
-			]);
423
-
424
-			return $localeStart
425
-				. ' (' . $startTimezone . ') '
426
-				. ' - '
427
-				. $localeEnd
428
-				. ' (' . $endTimezone . ')';
429
-		}
430
-
431
-		// Show only the time if the day is the same
432
-		$localeEnd = $this->isDayEqual($dtstartDt, $dtendDt)
433
-			? $this->getTimeString($l10n, $dtendDt)
434
-			: implode(', ', [
435
-				$this->getWeekDayName($l10n, $dtendDt),
436
-				$this->getDateTimeString($l10n, $dtendDt)
437
-			]);
438
-
439
-		return $localeStart
440
-			. ' - '
441
-			. $localeEnd
442
-			. ' (' . $startTimezone . ')';
443
-	}
444
-
445
-	/**
446
-	 * @param DateTime $dtStart
447
-	 * @param DateTime $dtEnd
448
-	 * @return bool
449
-	 */
450
-	private function isDayEqual(DateTime $dtStart,
451
-								DateTime $dtEnd):bool {
452
-		return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
453
-	}
454
-
455
-	/**
456
-	 * @param IL10N $l10n
457
-	 * @param DateTime $dt
458
-	 * @return string
459
-	 */
460
-	private function getWeekDayName(IL10N $l10n, DateTime $dt):string {
461
-		return $l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
462
-	}
463
-
464
-	/**
465
-	 * @param IL10N $l10n
466
-	 * @param DateTime $dt
467
-	 * @return string
468
-	 */
469
-	private function getDateString(IL10N $l10n, DateTime $dt):string {
470
-		return $l10n->l('date', $dt, ['width' => 'medium']);
471
-	}
472
-
473
-	/**
474
-	 * @param IL10N $l10n
475
-	 * @param DateTime $dt
476
-	 * @return string
477
-	 */
478
-	private function getDateTimeString(IL10N $l10n, DateTime $dt):string {
479
-		return $l10n->l('datetime', $dt, ['width' => 'medium|short']);
480
-	}
481
-
482
-	/**
483
-	 * @param IL10N $l10n
484
-	 * @param DateTime $dt
485
-	 * @return string
486
-	 */
487
-	private function getTimeString(IL10N $l10n, DateTime $dt):string {
488
-		return $l10n->l('time', $dt, ['width' => 'short']);
489
-	}
490
-
491
-	/**
492
-	 * @param VEvent $vevent
493
-	 * @param IL10N $l10n
494
-	 * @return string
495
-	 */
496
-	private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string {
497
-		if (isset($vevent->SUMMARY)) {
498
-			return (string)$vevent->SUMMARY;
499
-		}
500
-
501
-		return $l10n->t('Untitled event');
502
-	}
49
+    /** @var string */
50
+    public const NOTIFICATION_TYPE = 'EMAIL';
51
+
52
+    /** @var IMailer */
53
+    private $mailer;
54
+
55
+    /**
56
+     * @param IConfig $config
57
+     * @param IMailer $mailer
58
+     * @param ILogger $logger
59
+     * @param L10NFactory $l10nFactory
60
+     * @param IUrlGenerator $urlGenerator
61
+     */
62
+    public function __construct(IConfig $config,
63
+                                IMailer $mailer,
64
+                                ILogger $logger,
65
+                                L10NFactory $l10nFactory,
66
+                                IURLGenerator $urlGenerator) {
67
+        parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
68
+        $this->mailer = $mailer;
69
+    }
70
+
71
+    /**
72
+     * Send out notification via email
73
+     *
74
+     * @param VEvent $vevent
75
+     * @param string $calendarDisplayName
76
+     * @param array $users
77
+     * @throws \Exception
78
+     */
79
+    public function send(VEvent $vevent,
80
+                            string $calendarDisplayName,
81
+                            array $users=[]):void {
82
+        $fallbackLanguage = $this->getFallbackLanguage();
83
+
84
+        $emailAddressesOfSharees = $this->getEMailAddressesOfAllUsersWithWriteAccessToCalendar($users);
85
+        $emailAddressesOfAttendees = $this->getAllEMailAddressesFromEvent($vevent);
86
+
87
+        // Quote from php.net:
88
+        // If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
89
+        // => if there are duplicate email addresses, it will always take the system value
90
+        $emailAddresses = array_merge(
91
+            $emailAddressesOfAttendees,
92
+            $emailAddressesOfSharees
93
+        );
94
+
95
+        $sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage);
96
+        $organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);
97
+
98
+        foreach($sortedByLanguage as $lang => $emailAddresses) {
99
+            if (!$this->hasL10NForLang($lang)) {
100
+                $lang = $fallbackLanguage;
101
+            }
102
+            $l10n = $this->getL10NForLang($lang);
103
+            $fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply');
104
+
105
+            $template = $this->mailer->createEMailTemplate('dav.calendarReminder');
106
+            $template->addHeader();
107
+            $this->addSubjectAndHeading($template, $l10n, $vevent);
108
+            $this->addBulletList($template, $l10n, $calendarDisplayName, $vevent);
109
+            $template->addFooter();
110
+
111
+            foreach ($emailAddresses as $emailAddress) {
112
+                $message = $this->mailer->createMessage();
113
+                $message->setFrom([$fromEMail]);
114
+                if ($organizer) {
115
+                    $message->setReplyTo($organizer);
116
+                }
117
+                $message->setTo([$emailAddress]);
118
+                $message->useTemplate($template);
119
+
120
+                try {
121
+                    $failed = $this->mailer->send($message);
122
+                    if ($failed) {
123
+                        $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
124
+                    }
125
+                } catch (\Exception $ex) {
126
+                    $this->logger->logException($ex, ['app' => 'dav']);
127
+                }
128
+            }
129
+        }
130
+    }
131
+
132
+    /**
133
+     * @param IEMailTemplate $template
134
+     * @param IL10N $l10n
135
+     * @param VEvent $vevent
136
+     */
137
+    private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEvent $vevent):void {
138
+        $template->setSubject('Notification: ' . $this->getTitleFromVEvent($vevent, $l10n));
139
+        $template->addHeading($this->getTitleFromVEvent($vevent, $l10n));
140
+    }
141
+
142
+    /**
143
+     * @param IEMailTemplate $template
144
+     * @param IL10N $l10n
145
+     * @param string $calendarDisplayName
146
+     * @param array $eventData
147
+     */
148
+    private function addBulletList(IEMailTemplate $template,
149
+                                    IL10N $l10n,
150
+                                    string $calendarDisplayName,
151
+                                    VEvent $vevent):void {
152
+        $template->addBodyListItem($calendarDisplayName, $l10n->t('Calendar:'),
153
+            $this->getAbsoluteImagePath('actions/info.svg'));
154
+
155
+        $template->addBodyListItem($this->generateDateString($l10n, $vevent), $l10n->t('Date:'),
156
+            $this->getAbsoluteImagePath('places/calendar.svg'));
157
+
158
+        if (isset($vevent->LOCATION)) {
159
+            $template->addBodyListItem((string) $vevent->LOCATION, $l10n->t('Where:'),
160
+                $this->getAbsoluteImagePath('actions/address.svg'));
161
+        }
162
+        if (isset($vevent->DESCRIPTION)) {
163
+            $template->addBodyListItem((string) $vevent->DESCRIPTION, $l10n->t('Description:'),
164
+                $this->getAbsoluteImagePath('actions/more.svg'));
165
+        }
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return string
171
+     */
172
+    private function getAbsoluteImagePath(string $path):string {
173
+        return $this->urlGenerator->getAbsoluteURL(
174
+            $this->urlGenerator->imagePath('core', $path)
175
+        );
176
+    }
177
+
178
+    /**
179
+     * @param VEvent $vevent
180
+     * @return array|null
181
+     */
182
+    private function getOrganizerEMailAndNameFromEvent(VEvent $vevent):?array {
183
+        if (!$vevent->ORGANIZER) {
184
+            return null;
185
+        }
186
+
187
+        $organizer = $vevent->ORGANIZER;
188
+        if (strcasecmp($organizer->getValue(), 'mailto:') !== 0) {
189
+            return null;
190
+        }
191
+
192
+        $organizerEMail = substr($organizer->getValue(), 7);
193
+
194
+        $name = $organizer->offsetGet('CN');
195
+        if ($name instanceof Parameter) {
196
+            return [$organizerEMail => $name];
197
+        }
198
+
199
+        return [$organizerEMail];
200
+    }
201
+
202
+    /**
203
+     * @param array $emails
204
+     * @param string $defaultLanguage
205
+     * @return array
206
+     */
207
+    private function sortEMailAddressesByLanguage(array $emails,
208
+                                                    string $defaultLanguage):array {
209
+        $sortedByLanguage = [];
210
+
211
+        foreach($emails as $emailAddress => $parameters) {
212
+            if (isset($parameters['LANG'])) {
213
+                $lang = $parameters['LANG'];
214
+            } else {
215
+                $lang = $defaultLanguage;
216
+            }
217
+
218
+            if (!isset($sortedByLanguage[$lang])) {
219
+                $sortedByLanguage[$lang] = [];
220
+            }
221
+
222
+            $sortedByLanguage[$lang][] = $emailAddress;
223
+        }
224
+
225
+        return $sortedByLanguage;
226
+    }
227
+
228
+    /**
229
+     * @param VEvent $vevent
230
+     * @return array
231
+     */
232
+    private function getAllEMailAddressesFromEvent(VEvent $vevent):array {
233
+        $emailAddresses = [];
234
+
235
+        if (isset($vevent->ATTENDEE)) {
236
+            foreach ($vevent->ATTENDEE as $attendee) {
237
+                if (!($attendee instanceof VObject\Property)) {
238
+                    continue;
239
+                }
240
+
241
+                $cuType = $this->getCUTypeOfAttendee($attendee);
242
+                if (\in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) {
243
+                    // Don't send emails to things
244
+                    continue;
245
+                }
246
+
247
+                $partstat = $this->getPartstatOfAttendee($attendee);
248
+                if ($partstat === 'DECLINED') {
249
+                    // Don't send out emails to people who declined
250
+                    continue;
251
+                }
252
+                if ($partstat === 'DELEGATED') {
253
+                    $delegates = $attendee->offsetGet('DELEGATED-TO');
254
+                    if (!($delegates instanceof VObject\Parameter)) {
255
+                        continue;
256
+                    }
257
+
258
+                    $emailAddressesOfDelegates = $delegates->getParts();
259
+                    foreach($emailAddressesOfDelegates as $addressesOfDelegate) {
260
+                        if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) {
261
+                            $emailAddresses[substr($addressesOfDelegate, 7)] = [];
262
+                        }
263
+                    }
264
+
265
+                    continue;
266
+                }
267
+
268
+                $emailAddressOfAttendee = $this->getEMailAddressOfAttendee($attendee);
269
+                if ($emailAddressOfAttendee !== null) {
270
+                    $properties = [];
271
+
272
+                    $langProp = $attendee->offsetGet('LANG');
273
+                    if ($langProp instanceof VObject\Parameter) {
274
+                        $properties['LANG'] = $langProp->getValue();
275
+                    }
276
+
277
+                    $emailAddresses[$emailAddressOfAttendee] = $properties;
278
+                }
279
+            }
280
+        }
281
+
282
+        if (isset($vevent->ORGANIZER) && $this->hasAttendeeMailURI($vevent->ORGANIZER)) {
283
+            $emailAddresses[$this->getEMailAddressOfAttendee($vevent->ORGANIZER)] = [];
284
+        }
285
+
286
+        return $emailAddresses;
287
+    }
288
+
289
+
290
+
291
+    /**
292
+     * @param VObject\Property $attendee
293
+     * @return string
294
+     */
295
+    private function getCUTypeOfAttendee(VObject\Property $attendee):string {
296
+        $cuType = $attendee->offsetGet('CUTYPE');
297
+        if ($cuType instanceof VObject\Parameter) {
298
+            return strtoupper($cuType->getValue());
299
+        }
300
+
301
+        return 'INDIVIDUAL';
302
+    }
303
+
304
+    /**
305
+     * @param VObject\Property $attendee
306
+     * @return string
307
+     */
308
+    private function getPartstatOfAttendee(VObject\Property $attendee):string {
309
+        $partstat = $attendee->offsetGet('PARTSTAT');
310
+        if ($partstat instanceof VObject\Parameter) {
311
+            return strtoupper($partstat->getValue());
312
+        }
313
+
314
+        return 'NEEDS-ACTION';
315
+    }
316
+
317
+    /**
318
+     * @param VObject\Property $attendee
319
+     * @return bool
320
+     */
321
+    private function hasAttendeeMailURI(VObject\Property $attendee):bool {
322
+        return stripos($attendee->getValue(), 'mailto:') === 0;
323
+    }
324
+
325
+    /**
326
+     * @param VObject\Property $attendee
327
+     * @return string|null
328
+     */
329
+    private function getEMailAddressOfAttendee(VObject\Property $attendee):?string {
330
+        if (!$this->hasAttendeeMailURI($attendee)) {
331
+            return null;
332
+        }
333
+
334
+        return substr($attendee->getValue(), 7);
335
+    }
336
+
337
+    /**
338
+     * @param array $users
339
+     * @return array
340
+     */
341
+    private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array {
342
+        $emailAddresses = [];
343
+
344
+        foreach($users as $user) {
345
+            $emailAddress = $user->getEMailAddress();
346
+            if ($emailAddress) {
347
+                $lang = $this->getLangForUser($user);
348
+                if ($lang) {
349
+                    $emailAddresses[$emailAddress] = [
350
+                        'LANG' => $lang,
351
+                    ];
352
+                } else {
353
+                    $emailAddresses[$emailAddress] = [];
354
+                }
355
+            }
356
+        }
357
+
358
+        return $emailAddresses;
359
+    }
360
+
361
+    /**
362
+     * @param IUser $user
363
+     * @return string
364
+     */
365
+    private function getLangForUser(IUser $user): ?string {
366
+        return $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
367
+    }
368
+
369
+    /**
370
+     * @param IL10N $l10n
371
+     * @param VEvent $vevent
372
+     * @return string
373
+     * @throws \Exception
374
+     */
375
+    private function generateDateString(IL10N $l10n, VEvent $vevent):string {
376
+        $isAllDay = $vevent->DTSTART instanceof Property\ICalendar\Date;
377
+
378
+        /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
379
+        /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
380
+        /** @var \DateTimeImmutable $dtstartDt */
381
+        $dtstartDt = $vevent->DTSTART->getDateTime();
382
+        /** @var \DateTimeImmutable $dtendDt */
383
+        $dtendDt = $this->getDTEndFromEvent($vevent)->getDateTime();
384
+
385
+        $diff = $dtstartDt->diff($dtendDt);
386
+
387
+        /** @phan-suppress-next-line PhanUndeclaredClassMethod */
388
+        $dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
389
+        /** @phan-suppress-next-line PhanUndeclaredClassMethod */
390
+        $dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
391
+
392
+        if ($isAllDay) {
393
+            // One day event
394
+            if ($diff->days === 1) {
395
+                return $this->getDateString($l10n, $dtstartDt);
396
+            }
397
+
398
+            return implode(' - ', [
399
+                $this->getDateString($l10n, $dtstartDt),
400
+                $this->getDateString($l10n, $dtendDt),
401
+            ]);
402
+        }
403
+
404
+        $startTimezone = $endTimezone = null;
405
+        if (!$vevent->DTSTART->isFloating()) {
406
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
407
+            $startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName();
408
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
409
+            $endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName();
410
+        }
411
+
412
+        $localeStart = implode(', ', [
413
+            $this->getWeekDayName($l10n, $dtstartDt),
414
+            $this->getDateTimeString($l10n, $dtstartDt)
415
+        ]);
416
+
417
+        // always show full date with timezone if timezones are different
418
+        if ($startTimezone !== $endTimezone) {
419
+            $localeEnd = implode(', ', [
420
+                $this->getWeekDayName($l10n, $dtendDt),
421
+                $this->getDateTimeString($l10n, $dtendDt)
422
+            ]);
423
+
424
+            return $localeStart
425
+                . ' (' . $startTimezone . ') '
426
+                . ' - '
427
+                . $localeEnd
428
+                . ' (' . $endTimezone . ')';
429
+        }
430
+
431
+        // Show only the time if the day is the same
432
+        $localeEnd = $this->isDayEqual($dtstartDt, $dtendDt)
433
+            ? $this->getTimeString($l10n, $dtendDt)
434
+            : implode(', ', [
435
+                $this->getWeekDayName($l10n, $dtendDt),
436
+                $this->getDateTimeString($l10n, $dtendDt)
437
+            ]);
438
+
439
+        return $localeStart
440
+            . ' - '
441
+            . $localeEnd
442
+            . ' (' . $startTimezone . ')';
443
+    }
444
+
445
+    /**
446
+     * @param DateTime $dtStart
447
+     * @param DateTime $dtEnd
448
+     * @return bool
449
+     */
450
+    private function isDayEqual(DateTime $dtStart,
451
+                                DateTime $dtEnd):bool {
452
+        return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
453
+    }
454
+
455
+    /**
456
+     * @param IL10N $l10n
457
+     * @param DateTime $dt
458
+     * @return string
459
+     */
460
+    private function getWeekDayName(IL10N $l10n, DateTime $dt):string {
461
+        return $l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
462
+    }
463
+
464
+    /**
465
+     * @param IL10N $l10n
466
+     * @param DateTime $dt
467
+     * @return string
468
+     */
469
+    private function getDateString(IL10N $l10n, DateTime $dt):string {
470
+        return $l10n->l('date', $dt, ['width' => 'medium']);
471
+    }
472
+
473
+    /**
474
+     * @param IL10N $l10n
475
+     * @param DateTime $dt
476
+     * @return string
477
+     */
478
+    private function getDateTimeString(IL10N $l10n, DateTime $dt):string {
479
+        return $l10n->l('datetime', $dt, ['width' => 'medium|short']);
480
+    }
481
+
482
+    /**
483
+     * @param IL10N $l10n
484
+     * @param DateTime $dt
485
+     * @return string
486
+     */
487
+    private function getTimeString(IL10N $l10n, DateTime $dt):string {
488
+        return $l10n->l('time', $dt, ['width' => 'short']);
489
+    }
490
+
491
+    /**
492
+     * @param VEvent $vevent
493
+     * @param IL10N $l10n
494
+     * @return string
495
+     */
496
+    private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string {
497
+        if (isset($vevent->SUMMARY)) {
498
+            return (string)$vevent->SUMMARY;
499
+        }
500
+
501
+        return $l10n->t('Untitled event');
502
+    }
503 503
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 	 */
79 79
 	public function send(VEvent $vevent,
80 80
 						 string $calendarDisplayName,
81
-						 array $users=[]):void {
81
+						 array $users = []):void {
82 82
 		$fallbackLanguage = $this->getFallbackLanguage();
83 83
 
84 84
 		$emailAddressesOfSharees = $this->getEMailAddressesOfAllUsersWithWriteAccessToCalendar($users);
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		$sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage);
96 96
 		$organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);
97 97
 
98
-		foreach($sortedByLanguage as $lang => $emailAddresses) {
98
+		foreach ($sortedByLanguage as $lang => $emailAddresses) {
99 99
 			if (!$this->hasL10NForLang($lang)) {
100 100
 				$lang = $fallbackLanguage;
101 101
 			}
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 	 * @param VEvent $vevent
136 136
 	 */
137 137
 	private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEvent $vevent):void {
138
-		$template->setSubject('Notification: ' . $this->getTitleFromVEvent($vevent, $l10n));
138
+		$template->setSubject('Notification: '.$this->getTitleFromVEvent($vevent, $l10n));
139 139
 		$template->addHeading($this->getTitleFromVEvent($vevent, $l10n));
140 140
 	}
141 141
 
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 	 * @param VEvent $vevent
180 180
 	 * @return array|null
181 181
 	 */
182
-	private function getOrganizerEMailAndNameFromEvent(VEvent $vevent):?array {
182
+	private function getOrganizerEMailAndNameFromEvent(VEvent $vevent): ?array {
183 183
 		if (!$vevent->ORGANIZER) {
184 184
 			return null;
185 185
 		}
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 												  string $defaultLanguage):array {
209 209
 		$sortedByLanguage = [];
210 210
 
211
-		foreach($emails as $emailAddress => $parameters) {
211
+		foreach ($emails as $emailAddress => $parameters) {
212 212
 			if (isset($parameters['LANG'])) {
213 213
 				$lang = $parameters['LANG'];
214 214
 			} else {
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 					}
257 257
 
258 258
 					$emailAddressesOfDelegates = $delegates->getParts();
259
-					foreach($emailAddressesOfDelegates as $addressesOfDelegate) {
259
+					foreach ($emailAddressesOfDelegates as $addressesOfDelegate) {
260 260
 						if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) {
261 261
 							$emailAddresses[substr($addressesOfDelegate, 7)] = [];
262 262
 						}
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 	 * @param VObject\Property $attendee
327 327
 	 * @return string|null
328 328
 	 */
329
-	private function getEMailAddressOfAttendee(VObject\Property $attendee):?string {
329
+	private function getEMailAddressOfAttendee(VObject\Property $attendee): ?string {
330 330
 		if (!$this->hasAttendeeMailURI($attendee)) {
331 331
 			return null;
332 332
 		}
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 	private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array {
342 342
 		$emailAddresses = [];
343 343
 
344
-		foreach($users as $user) {
344
+		foreach ($users as $user) {
345 345
 			$emailAddress = $user->getEMailAddress();
346 346
 			if ($emailAddress) {
347 347
 				$lang = $this->getLangForUser($user);
@@ -422,10 +422,10 @@  discard block
 block discarded – undo
422 422
 			]);
423 423
 
424 424
 			return $localeStart
425
-				. ' (' . $startTimezone . ') '
425
+				. ' ('.$startTimezone.') '
426 426
 				. ' - '
427 427
 				. $localeEnd
428
-				. ' (' . $endTimezone . ')';
428
+				. ' ('.$endTimezone.')';
429 429
 		}
430 430
 
431 431
 		// Show only the time if the day is the same
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 		return $localeStart
440 440
 			. ' - '
441 441
 			. $localeEnd
442
-			. ' (' . $startTimezone . ')';
442
+			. ' ('.$startTimezone.')';
443 443
 	}
444 444
 
445 445
 	/**
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 	 */
496 496
 	private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string {
497 497
 		if (isset($vevent->SUMMARY)) {
498
-			return (string)$vevent->SUMMARY;
498
+			return (string) $vevent->SUMMARY;
499 499
 		}
500 500
 
501 501
 		return $l10n->t('Untitled event');
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php 2 patches
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -44,96 +44,96 @@
 block discarded – undo
44 44
  */
45 45
 class PushProvider extends AbstractProvider {
46 46
 
47
-	/** @var string */
48
-	public const NOTIFICATION_TYPE = 'DISPLAY';
47
+    /** @var string */
48
+    public const NOTIFICATION_TYPE = 'DISPLAY';
49 49
 
50
-	/** @var IManager */
51
-	private $manager;
50
+    /** @var IManager */
51
+    private $manager;
52 52
 
53
-	/** @var ITimeFactory */
54
-	private $timeFactory;
53
+    /** @var ITimeFactory */
54
+    private $timeFactory;
55 55
 
56
-	/**
57
-	 * @param IConfig $config
58
-	 * @param IManager $manager
59
-	 * @param ILogger $logger
60
-	 * @param L10NFactory $l10nFactory
61
-	 * @param IUrlGenerator $urlGenerator
62
-	 * @param ITimeFactory $timeFactory
63
-	 */
64
-	public function __construct(IConfig $config,
65
-								IManager $manager,
66
-								ILogger $logger,
67
-								L10NFactory $l10nFactory,
68
-								IURLGenerator $urlGenerator,
69
-								ITimeFactory $timeFactory) {
70
-		parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
71
-		$this->manager = $manager;
72
-		$this->timeFactory = $timeFactory;
73
-	}
56
+    /**
57
+     * @param IConfig $config
58
+     * @param IManager $manager
59
+     * @param ILogger $logger
60
+     * @param L10NFactory $l10nFactory
61
+     * @param IUrlGenerator $urlGenerator
62
+     * @param ITimeFactory $timeFactory
63
+     */
64
+    public function __construct(IConfig $config,
65
+                                IManager $manager,
66
+                                ILogger $logger,
67
+                                L10NFactory $l10nFactory,
68
+                                IURLGenerator $urlGenerator,
69
+                                ITimeFactory $timeFactory) {
70
+        parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
71
+        $this->manager = $manager;
72
+        $this->timeFactory = $timeFactory;
73
+    }
74 74
 
75
-	/**
76
-	 * Send push notification to all users.
77
-	 *
78
-	 * @param VEvent $vevent
79
-	 * @param string $calendarDisplayName
80
-	 * @param IUser[] $users
81
-	 * @throws \Exception
82
-	 */
83
-	public function send(VEvent $vevent,
84
-						 string $calendarDisplayName=null,
85
-						 array $users=[]):void {
86
-		$eventDetails = $this->extractEventDetails($vevent);
87
-		$eventDetails['calendar_displayname'] = $calendarDisplayName;
75
+    /**
76
+     * Send push notification to all users.
77
+     *
78
+     * @param VEvent $vevent
79
+     * @param string $calendarDisplayName
80
+     * @param IUser[] $users
81
+     * @throws \Exception
82
+     */
83
+    public function send(VEvent $vevent,
84
+                            string $calendarDisplayName=null,
85
+                            array $users=[]):void {
86
+        $eventDetails = $this->extractEventDetails($vevent);
87
+        $eventDetails['calendar_displayname'] = $calendarDisplayName;
88 88
 
89
-		foreach($users as $user) {
90
-			/** @var INotification $notification */
91
-			$notification = $this->manager->createNotification();
92
-			$notification->setApp(Application::APP_ID)
93
-				->setUser($user->getUID())
94
-				->setDateTime($this->timeFactory->getDateTime())
95
-				->setObject(Application::APP_ID, (string) $vevent->UID)
96
-				->setSubject('calendar_reminder', [
97
-					'title' => $eventDetails['title'],
98
-					'start_atom' => $eventDetails['start_atom']
99
-				])
100
-				->setMessage('calendar_reminder', $eventDetails);
89
+        foreach($users as $user) {
90
+            /** @var INotification $notification */
91
+            $notification = $this->manager->createNotification();
92
+            $notification->setApp(Application::APP_ID)
93
+                ->setUser($user->getUID())
94
+                ->setDateTime($this->timeFactory->getDateTime())
95
+                ->setObject(Application::APP_ID, (string) $vevent->UID)
96
+                ->setSubject('calendar_reminder', [
97
+                    'title' => $eventDetails['title'],
98
+                    'start_atom' => $eventDetails['start_atom']
99
+                ])
100
+                ->setMessage('calendar_reminder', $eventDetails);
101 101
 
102
-			$this->manager->notify($notification);
103
-		}
104
-	}
102
+            $this->manager->notify($notification);
103
+        }
104
+    }
105 105
 
106
-	/**
107
-	 * @var VEvent $vevent
108
-	 * @return array
109
-	 * @throws \Exception
110
-	 */
111
-	protected function extractEventDetails(VEvent $vevent):array {
112
-		/** @var Property\ICalendar\DateTime $start */
113
-		$start = $vevent->DTSTART;
114
-		$end = $this->getDTEndFromEvent($vevent);
106
+    /**
107
+     * @var VEvent $vevent
108
+     * @return array
109
+     * @throws \Exception
110
+     */
111
+    protected function extractEventDetails(VEvent $vevent):array {
112
+        /** @var Property\ICalendar\DateTime $start */
113
+        $start = $vevent->DTSTART;
114
+        $end = $this->getDTEndFromEvent($vevent);
115 115
 
116
-		return [
117
-			'title' => isset($vevent->SUMMARY)
118
-				? ((string) $vevent->SUMMARY)
119
-				: null,
120
-			'description' => isset($vevent->DESCRIPTION)
121
-				? ((string) $vevent->DESCRIPTION)
122
-				: null,
123
-			'location' => isset($vevent->LOCATION)
124
-				? ((string) $vevent->LOCATION)
125
-				: null,
126
-			'all_day' => $start instanceof Property\ICalendar\Date,
127
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
128
-			'start_atom' => $start->getDateTime()->format(\DateTime::ATOM),
129
-			'start_is_floating' => $start->isFloating(),
130
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
131
-			'start_timezone' => $start->getDateTime()->getTimezone()->getName(),
132
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
133
-			'end_atom' => $end->getDateTime()->format(\DateTime::ATOM),
134
-			'end_is_floating' => $end->isFloating(),
135
-			/** @phan-suppress-next-line PhanUndeclaredClassMethod */
136
-			'end_timezone' => $end->getDateTime()->getTimezone()->getName(),
137
-		];
138
-	}
116
+        return [
117
+            'title' => isset($vevent->SUMMARY)
118
+                ? ((string) $vevent->SUMMARY)
119
+                : null,
120
+            'description' => isset($vevent->DESCRIPTION)
121
+                ? ((string) $vevent->DESCRIPTION)
122
+                : null,
123
+            'location' => isset($vevent->LOCATION)
124
+                ? ((string) $vevent->LOCATION)
125
+                : null,
126
+            'all_day' => $start instanceof Property\ICalendar\Date,
127
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
128
+            'start_atom' => $start->getDateTime()->format(\DateTime::ATOM),
129
+            'start_is_floating' => $start->isFloating(),
130
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
131
+            'start_timezone' => $start->getDateTime()->getTimezone()->getName(),
132
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
133
+            'end_atom' => $end->getDateTime()->format(\DateTime::ATOM),
134
+            'end_is_floating' => $end->isFloating(),
135
+            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
136
+            'end_timezone' => $end->getDateTime()->getTimezone()->getName(),
137
+        ];
138
+    }
139 139
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -81,12 +81,12 @@
 block discarded – undo
81 81
 	 * @throws \Exception
82 82
 	 */
83 83
 	public function send(VEvent $vevent,
84
-						 string $calendarDisplayName=null,
85
-						 array $users=[]):void {
84
+						 string $calendarDisplayName = null,
85
+						 array $users = []):void {
86 86
 		$eventDetails = $this->extractEventDetails($vevent);
87 87
 		$eventDetails['calendar_displayname'] = $calendarDisplayName;
88 88
 
89
-		foreach($users as $user) {
89
+		foreach ($users as $user) {
90 90
 			/** @var INotification $notification */
91 91
 			$notification = $this->manager->createNotification();
92 92
 			$notification->setApp(Application::APP_ID)
Please login to merge, or discard this patch.