Completed
Pull Request — master (#5881)
by Thomas
18:04
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2081 added lines, -2081 removed lines patch added patch discarded remove patch
@@ -62,2086 +62,2086 @@
 block discarded – undo
62 62
  */
63 63
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
64 64
 
65
-	const PERSONAL_CALENDAR_URI = 'personal';
66
-	const PERSONAL_CALENDAR_NAME = 'Personal';
67
-
68
-	/**
69
-	 * We need to specify a max date, because we need to stop *somewhere*
70
-	 *
71
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
72
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
73
-	 * in 2038-01-19 to avoid problems when the date is converted
74
-	 * to a unix timestamp.
75
-	 */
76
-	const MAX_DATE = '2038-01-01';
77
-
78
-	const ACCESS_PUBLIC = 4;
79
-	const CLASSIFICATION_PUBLIC = 0;
80
-	const CLASSIFICATION_PRIVATE = 1;
81
-	const CLASSIFICATION_CONFIDENTIAL = 2;
82
-
83
-	/**
84
-	 * List of CalDAV properties, and how they map to database field names
85
-	 * Add your own properties by simply adding on to this array.
86
-	 *
87
-	 * Note that only string-based properties are supported here.
88
-	 *
89
-	 * @var array
90
-	 */
91
-	public $propertyMap = [
92
-		'{DAV:}displayname'                          => 'displayname',
93
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
94
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
95
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
96
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
97
-	];
98
-
99
-	/**
100
-	 * List of subscription properties, and how they map to database field names.
101
-	 *
102
-	 * @var array
103
-	 */
104
-	public $subscriptionPropertyMap = [
105
-		'{DAV:}displayname'                                           => 'displayname',
106
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
107
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
108
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
109
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
110
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
111
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
112
-	];
113
-
114
-	/** @var array properties to index */
115
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
116
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
117
-		'ORGANIZER'];
118
-
119
-	/** @var array parameters to index */
120
-	public static $indexParameters = [
121
-		'ATTENDEE' => ['CN'],
122
-		'ORGANIZER' => ['CN'],
123
-	];
124
-
125
-	/**
126
-	 * @var string[] Map of uid => display name
127
-	 */
128
-	protected $userDisplayNames;
129
-
130
-	/** @var IDBConnection */
131
-	private $db;
132
-
133
-	/** @var Backend */
134
-	private $sharingBackend;
135
-
136
-	/** @var Principal */
137
-	private $principalBackend;
138
-
139
-	/** @var IUserManager */
140
-	private $userManager;
141
-
142
-	/** @var ISecureRandom */
143
-	private $random;
144
-
145
-	/** @var EventDispatcherInterface */
146
-	private $dispatcher;
147
-
148
-	/** @var bool */
149
-	private $legacyEndpoint;
150
-
151
-	/** @var string */
152
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
153
-
154
-	/**
155
-	 * CalDavBackend constructor.
156
-	 *
157
-	 * @param IDBConnection $db
158
-	 * @param Principal $principalBackend
159
-	 * @param IUserManager $userManager
160
-	 * @param ISecureRandom $random
161
-	 * @param EventDispatcherInterface $dispatcher
162
-	 * @param bool $legacyEndpoint
163
-	 */
164
-	public function __construct(IDBConnection $db,
165
-								Principal $principalBackend,
166
-								IUserManager $userManager,
167
-								ISecureRandom $random,
168
-								EventDispatcherInterface $dispatcher,
169
-								$legacyEndpoint = false) {
170
-		$this->db = $db;
171
-		$this->principalBackend = $principalBackend;
172
-		$this->userManager = $userManager;
173
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
174
-		$this->random = $random;
175
-		$this->dispatcher = $dispatcher;
176
-		$this->legacyEndpoint = $legacyEndpoint;
177
-	}
178
-
179
-	/**
180
-	 * Return the number of calendars for a principal
181
-	 *
182
-	 * By default this excludes the automatically generated birthday calendar
183
-	 *
184
-	 * @param $principalUri
185
-	 * @param bool $excludeBirthday
186
-	 * @return int
187
-	 */
188
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
189
-		$principalUri = $this->convertPrincipal($principalUri, true);
190
-		$query = $this->db->getQueryBuilder();
191
-		$query->select($query->createFunction('COUNT(*)'))
192
-			->from('calendars')
193
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
194
-
195
-		if ($excludeBirthday) {
196
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197
-		}
198
-
199
-		return (int)$query->execute()->fetchColumn();
200
-	}
201
-
202
-	/**
203
-	 * Returns a list of calendars for a principal.
204
-	 *
205
-	 * Every project is an array with the following keys:
206
-	 *  * id, a unique id that will be used by other functions to modify the
207
-	 *    calendar. This can be the same as the uri or a database key.
208
-	 *  * uri, which the basename of the uri with which the calendar is
209
-	 *    accessed.
210
-	 *  * principaluri. The owner of the calendar. Almost always the same as
211
-	 *    principalUri passed to this method.
212
-	 *
213
-	 * Furthermore it can contain webdav properties in clark notation. A very
214
-	 * common one is '{DAV:}displayname'.
215
-	 *
216
-	 * Many clients also require:
217
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
218
-	 * For this property, you can just return an instance of
219
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
220
-	 *
221
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
222
-	 * ACL will automatically be put in read-only mode.
223
-	 *
224
-	 * @param string $principalUri
225
-	 * @return array
226
-	 */
227
-	function getCalendarsForUser($principalUri) {
228
-		$principalUriOriginal = $principalUri;
229
-		$principalUri = $this->convertPrincipal($principalUri, true);
230
-		$fields = array_values($this->propertyMap);
231
-		$fields[] = 'id';
232
-		$fields[] = 'uri';
233
-		$fields[] = 'synctoken';
234
-		$fields[] = 'components';
235
-		$fields[] = 'principaluri';
236
-		$fields[] = 'transparent';
237
-
238
-		// Making fields a comma-delimited list
239
-		$query = $this->db->getQueryBuilder();
240
-		$query->select($fields)->from('calendars')
241
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
242
-				->orderBy('calendarorder', 'ASC');
243
-		$stmt = $query->execute();
244
-
245
-		$calendars = [];
246
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247
-
248
-			$components = [];
249
-			if ($row['components']) {
250
-				$components = explode(',',$row['components']);
251
-			}
252
-
253
-			$calendar = [
254
-				'id' => $row['id'],
255
-				'uri' => $row['uri'],
256
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262
-			];
263
-
264
-			foreach($this->propertyMap as $xmlName=>$dbName) {
265
-				$calendar[$xmlName] = $row[$dbName];
266
-			}
267
-
268
-			$this->addOwnerPrincipal($calendar);
269
-
270
-			if (!isset($calendars[$calendar['id']])) {
271
-				$calendars[$calendar['id']] = $calendar;
272
-			}
273
-		}
274
-
275
-		$stmt->closeCursor();
276
-
277
-		// query for shared calendars
278
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
279
-		$principals = array_map(function($principal) {
280
-			return urldecode($principal);
281
-		}, $principals);
282
-		$principals[]= $principalUri;
283
-
284
-		$fields = array_values($this->propertyMap);
285
-		$fields[] = 'a.id';
286
-		$fields[] = 'a.uri';
287
-		$fields[] = 'a.synctoken';
288
-		$fields[] = 'a.components';
289
-		$fields[] = 'a.principaluri';
290
-		$fields[] = 'a.transparent';
291
-		$fields[] = 's.access';
292
-		$query = $this->db->getQueryBuilder();
293
-		$result = $query->select($fields)
294
-			->from('dav_shares', 's')
295
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
296
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
297
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
298
-			->setParameter('type', 'calendar')
299
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300
-			->execute();
301
-
302
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
-		while($row = $result->fetch()) {
304
-			if ($row['principaluri'] === $principalUri) {
305
-				continue;
306
-			}
307
-
308
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
309
-			if (isset($calendars[$row['id']])) {
310
-				if ($readOnly) {
311
-					// New share can not have more permissions then the old one.
312
-					continue;
313
-				}
314
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
315
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
316
-					// Old share is already read-write, no more permissions can be gained
317
-					continue;
318
-				}
319
-			}
320
-
321
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
322
-			$uri = $row['uri'] . '_shared_by_' . $name;
323
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
324
-			$components = [];
325
-			if ($row['components']) {
326
-				$components = explode(',',$row['components']);
327
-			}
328
-			$calendar = [
329
-				'id' => $row['id'],
330
-				'uri' => $uri,
331
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
-				$readOnlyPropertyName => $readOnly,
338
-			];
339
-
340
-			foreach($this->propertyMap as $xmlName=>$dbName) {
341
-				$calendar[$xmlName] = $row[$dbName];
342
-			}
343
-
344
-			$this->addOwnerPrincipal($calendar);
345
-
346
-			$calendars[$calendar['id']] = $calendar;
347
-		}
348
-		$result->closeCursor();
349
-
350
-		return array_values($calendars);
351
-	}
352
-
353
-	public function getUsersOwnCalendars($principalUri) {
354
-		$principalUri = $this->convertPrincipal($principalUri, true);
355
-		$fields = array_values($this->propertyMap);
356
-		$fields[] = 'id';
357
-		$fields[] = 'uri';
358
-		$fields[] = 'synctoken';
359
-		$fields[] = 'components';
360
-		$fields[] = 'principaluri';
361
-		$fields[] = 'transparent';
362
-		// Making fields a comma-delimited list
363
-		$query = $this->db->getQueryBuilder();
364
-		$query->select($fields)->from('calendars')
365
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
366
-			->orderBy('calendarorder', 'ASC');
367
-		$stmt = $query->execute();
368
-		$calendars = [];
369
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370
-			$components = [];
371
-			if ($row['components']) {
372
-				$components = explode(',',$row['components']);
373
-			}
374
-			$calendar = [
375
-				'id' => $row['id'],
376
-				'uri' => $row['uri'],
377
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
382
-			];
383
-			foreach($this->propertyMap as $xmlName=>$dbName) {
384
-				$calendar[$xmlName] = $row[$dbName];
385
-			}
386
-
387
-			$this->addOwnerPrincipal($calendar);
388
-
389
-			if (!isset($calendars[$calendar['id']])) {
390
-				$calendars[$calendar['id']] = $calendar;
391
-			}
392
-		}
393
-		$stmt->closeCursor();
394
-		return array_values($calendars);
395
-	}
396
-
397
-
398
-	private function getUserDisplayName($uid) {
399
-		if (!isset($this->userDisplayNames[$uid])) {
400
-			$user = $this->userManager->get($uid);
401
-
402
-			if ($user instanceof IUser) {
403
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
404
-			} else {
405
-				$this->userDisplayNames[$uid] = $uid;
406
-			}
407
-		}
408
-
409
-		return $this->userDisplayNames[$uid];
410
-	}
65
+    const PERSONAL_CALENDAR_URI = 'personal';
66
+    const PERSONAL_CALENDAR_NAME = 'Personal';
67
+
68
+    /**
69
+     * We need to specify a max date, because we need to stop *somewhere*
70
+     *
71
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
72
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
73
+     * in 2038-01-19 to avoid problems when the date is converted
74
+     * to a unix timestamp.
75
+     */
76
+    const MAX_DATE = '2038-01-01';
77
+
78
+    const ACCESS_PUBLIC = 4;
79
+    const CLASSIFICATION_PUBLIC = 0;
80
+    const CLASSIFICATION_PRIVATE = 1;
81
+    const CLASSIFICATION_CONFIDENTIAL = 2;
82
+
83
+    /**
84
+     * List of CalDAV properties, and how they map to database field names
85
+     * Add your own properties by simply adding on to this array.
86
+     *
87
+     * Note that only string-based properties are supported here.
88
+     *
89
+     * @var array
90
+     */
91
+    public $propertyMap = [
92
+        '{DAV:}displayname'                          => 'displayname',
93
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
94
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
95
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
96
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
97
+    ];
98
+
99
+    /**
100
+     * List of subscription properties, and how they map to database field names.
101
+     *
102
+     * @var array
103
+     */
104
+    public $subscriptionPropertyMap = [
105
+        '{DAV:}displayname'                                           => 'displayname',
106
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
107
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
108
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
109
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
110
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
111
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
112
+    ];
113
+
114
+    /** @var array properties to index */
115
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
116
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
117
+        'ORGANIZER'];
118
+
119
+    /** @var array parameters to index */
120
+    public static $indexParameters = [
121
+        'ATTENDEE' => ['CN'],
122
+        'ORGANIZER' => ['CN'],
123
+    ];
124
+
125
+    /**
126
+     * @var string[] Map of uid => display name
127
+     */
128
+    protected $userDisplayNames;
129
+
130
+    /** @var IDBConnection */
131
+    private $db;
132
+
133
+    /** @var Backend */
134
+    private $sharingBackend;
135
+
136
+    /** @var Principal */
137
+    private $principalBackend;
138
+
139
+    /** @var IUserManager */
140
+    private $userManager;
141
+
142
+    /** @var ISecureRandom */
143
+    private $random;
144
+
145
+    /** @var EventDispatcherInterface */
146
+    private $dispatcher;
147
+
148
+    /** @var bool */
149
+    private $legacyEndpoint;
150
+
151
+    /** @var string */
152
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
153
+
154
+    /**
155
+     * CalDavBackend constructor.
156
+     *
157
+     * @param IDBConnection $db
158
+     * @param Principal $principalBackend
159
+     * @param IUserManager $userManager
160
+     * @param ISecureRandom $random
161
+     * @param EventDispatcherInterface $dispatcher
162
+     * @param bool $legacyEndpoint
163
+     */
164
+    public function __construct(IDBConnection $db,
165
+                                Principal $principalBackend,
166
+                                IUserManager $userManager,
167
+                                ISecureRandom $random,
168
+                                EventDispatcherInterface $dispatcher,
169
+                                $legacyEndpoint = false) {
170
+        $this->db = $db;
171
+        $this->principalBackend = $principalBackend;
172
+        $this->userManager = $userManager;
173
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
174
+        $this->random = $random;
175
+        $this->dispatcher = $dispatcher;
176
+        $this->legacyEndpoint = $legacyEndpoint;
177
+    }
178
+
179
+    /**
180
+     * Return the number of calendars for a principal
181
+     *
182
+     * By default this excludes the automatically generated birthday calendar
183
+     *
184
+     * @param $principalUri
185
+     * @param bool $excludeBirthday
186
+     * @return int
187
+     */
188
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
189
+        $principalUri = $this->convertPrincipal($principalUri, true);
190
+        $query = $this->db->getQueryBuilder();
191
+        $query->select($query->createFunction('COUNT(*)'))
192
+            ->from('calendars')
193
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
194
+
195
+        if ($excludeBirthday) {
196
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197
+        }
198
+
199
+        return (int)$query->execute()->fetchColumn();
200
+    }
201
+
202
+    /**
203
+     * Returns a list of calendars for a principal.
204
+     *
205
+     * Every project is an array with the following keys:
206
+     *  * id, a unique id that will be used by other functions to modify the
207
+     *    calendar. This can be the same as the uri or a database key.
208
+     *  * uri, which the basename of the uri with which the calendar is
209
+     *    accessed.
210
+     *  * principaluri. The owner of the calendar. Almost always the same as
211
+     *    principalUri passed to this method.
212
+     *
213
+     * Furthermore it can contain webdav properties in clark notation. A very
214
+     * common one is '{DAV:}displayname'.
215
+     *
216
+     * Many clients also require:
217
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
218
+     * For this property, you can just return an instance of
219
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
220
+     *
221
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
222
+     * ACL will automatically be put in read-only mode.
223
+     *
224
+     * @param string $principalUri
225
+     * @return array
226
+     */
227
+    function getCalendarsForUser($principalUri) {
228
+        $principalUriOriginal = $principalUri;
229
+        $principalUri = $this->convertPrincipal($principalUri, true);
230
+        $fields = array_values($this->propertyMap);
231
+        $fields[] = 'id';
232
+        $fields[] = 'uri';
233
+        $fields[] = 'synctoken';
234
+        $fields[] = 'components';
235
+        $fields[] = 'principaluri';
236
+        $fields[] = 'transparent';
237
+
238
+        // Making fields a comma-delimited list
239
+        $query = $this->db->getQueryBuilder();
240
+        $query->select($fields)->from('calendars')
241
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
242
+                ->orderBy('calendarorder', 'ASC');
243
+        $stmt = $query->execute();
244
+
245
+        $calendars = [];
246
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247
+
248
+            $components = [];
249
+            if ($row['components']) {
250
+                $components = explode(',',$row['components']);
251
+            }
252
+
253
+            $calendar = [
254
+                'id' => $row['id'],
255
+                'uri' => $row['uri'],
256
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262
+            ];
263
+
264
+            foreach($this->propertyMap as $xmlName=>$dbName) {
265
+                $calendar[$xmlName] = $row[$dbName];
266
+            }
267
+
268
+            $this->addOwnerPrincipal($calendar);
269
+
270
+            if (!isset($calendars[$calendar['id']])) {
271
+                $calendars[$calendar['id']] = $calendar;
272
+            }
273
+        }
274
+
275
+        $stmt->closeCursor();
276
+
277
+        // query for shared calendars
278
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
279
+        $principals = array_map(function($principal) {
280
+            return urldecode($principal);
281
+        }, $principals);
282
+        $principals[]= $principalUri;
283
+
284
+        $fields = array_values($this->propertyMap);
285
+        $fields[] = 'a.id';
286
+        $fields[] = 'a.uri';
287
+        $fields[] = 'a.synctoken';
288
+        $fields[] = 'a.components';
289
+        $fields[] = 'a.principaluri';
290
+        $fields[] = 'a.transparent';
291
+        $fields[] = 's.access';
292
+        $query = $this->db->getQueryBuilder();
293
+        $result = $query->select($fields)
294
+            ->from('dav_shares', 's')
295
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
296
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
297
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
298
+            ->setParameter('type', 'calendar')
299
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300
+            ->execute();
301
+
302
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
+        while($row = $result->fetch()) {
304
+            if ($row['principaluri'] === $principalUri) {
305
+                continue;
306
+            }
307
+
308
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
309
+            if (isset($calendars[$row['id']])) {
310
+                if ($readOnly) {
311
+                    // New share can not have more permissions then the old one.
312
+                    continue;
313
+                }
314
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
315
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
316
+                    // Old share is already read-write, no more permissions can be gained
317
+                    continue;
318
+                }
319
+            }
320
+
321
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
322
+            $uri = $row['uri'] . '_shared_by_' . $name;
323
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
324
+            $components = [];
325
+            if ($row['components']) {
326
+                $components = explode(',',$row['components']);
327
+            }
328
+            $calendar = [
329
+                'id' => $row['id'],
330
+                'uri' => $uri,
331
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
+                $readOnlyPropertyName => $readOnly,
338
+            ];
339
+
340
+            foreach($this->propertyMap as $xmlName=>$dbName) {
341
+                $calendar[$xmlName] = $row[$dbName];
342
+            }
343
+
344
+            $this->addOwnerPrincipal($calendar);
345
+
346
+            $calendars[$calendar['id']] = $calendar;
347
+        }
348
+        $result->closeCursor();
349
+
350
+        return array_values($calendars);
351
+    }
352
+
353
+    public function getUsersOwnCalendars($principalUri) {
354
+        $principalUri = $this->convertPrincipal($principalUri, true);
355
+        $fields = array_values($this->propertyMap);
356
+        $fields[] = 'id';
357
+        $fields[] = 'uri';
358
+        $fields[] = 'synctoken';
359
+        $fields[] = 'components';
360
+        $fields[] = 'principaluri';
361
+        $fields[] = 'transparent';
362
+        // Making fields a comma-delimited list
363
+        $query = $this->db->getQueryBuilder();
364
+        $query->select($fields)->from('calendars')
365
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
366
+            ->orderBy('calendarorder', 'ASC');
367
+        $stmt = $query->execute();
368
+        $calendars = [];
369
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370
+            $components = [];
371
+            if ($row['components']) {
372
+                $components = explode(',',$row['components']);
373
+            }
374
+            $calendar = [
375
+                'id' => $row['id'],
376
+                'uri' => $row['uri'],
377
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
382
+            ];
383
+            foreach($this->propertyMap as $xmlName=>$dbName) {
384
+                $calendar[$xmlName] = $row[$dbName];
385
+            }
386
+
387
+            $this->addOwnerPrincipal($calendar);
388
+
389
+            if (!isset($calendars[$calendar['id']])) {
390
+                $calendars[$calendar['id']] = $calendar;
391
+            }
392
+        }
393
+        $stmt->closeCursor();
394
+        return array_values($calendars);
395
+    }
396
+
397
+
398
+    private function getUserDisplayName($uid) {
399
+        if (!isset($this->userDisplayNames[$uid])) {
400
+            $user = $this->userManager->get($uid);
401
+
402
+            if ($user instanceof IUser) {
403
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
404
+            } else {
405
+                $this->userDisplayNames[$uid] = $uid;
406
+            }
407
+        }
408
+
409
+        return $this->userDisplayNames[$uid];
410
+    }
411 411
 	
412
-	/**
413
-	 * @return array
414
-	 */
415
-	public function getPublicCalendars() {
416
-		$fields = array_values($this->propertyMap);
417
-		$fields[] = 'a.id';
418
-		$fields[] = 'a.uri';
419
-		$fields[] = 'a.synctoken';
420
-		$fields[] = 'a.components';
421
-		$fields[] = 'a.principaluri';
422
-		$fields[] = 'a.transparent';
423
-		$fields[] = 's.access';
424
-		$fields[] = 's.publicuri';
425
-		$calendars = [];
426
-		$query = $this->db->getQueryBuilder();
427
-		$result = $query->select($fields)
428
-			->from('dav_shares', 's')
429
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
430
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
431
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432
-			->execute();
433
-
434
-		while($row = $result->fetch()) {
435
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
436
-			$row['displayname'] = $row['displayname'] . "($name)";
437
-			$components = [];
438
-			if ($row['components']) {
439
-				$components = explode(',',$row['components']);
440
-			}
441
-			$calendar = [
442
-				'id' => $row['id'],
443
-				'uri' => $row['publicuri'],
444
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
452
-			];
453
-
454
-			foreach($this->propertyMap as $xmlName=>$dbName) {
455
-				$calendar[$xmlName] = $row[$dbName];
456
-			}
457
-
458
-			$this->addOwnerPrincipal($calendar);
459
-
460
-			if (!isset($calendars[$calendar['id']])) {
461
-				$calendars[$calendar['id']] = $calendar;
462
-			}
463
-		}
464
-		$result->closeCursor();
465
-
466
-		return array_values($calendars);
467
-	}
468
-
469
-	/**
470
-	 * @param string $uri
471
-	 * @return array
472
-	 * @throws NotFound
473
-	 */
474
-	public function getPublicCalendar($uri) {
475
-		$fields = array_values($this->propertyMap);
476
-		$fields[] = 'a.id';
477
-		$fields[] = 'a.uri';
478
-		$fields[] = 'a.synctoken';
479
-		$fields[] = 'a.components';
480
-		$fields[] = 'a.principaluri';
481
-		$fields[] = 'a.transparent';
482
-		$fields[] = 's.access';
483
-		$fields[] = 's.publicuri';
484
-		$query = $this->db->getQueryBuilder();
485
-		$result = $query->select($fields)
486
-			->from('dav_shares', 's')
487
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
488
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
489
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
490
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
491
-			->execute();
492
-
493
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
494
-
495
-		$result->closeCursor();
496
-
497
-		if ($row === false) {
498
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
499
-		}
500
-
501
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
502
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
503
-		$components = [];
504
-		if ($row['components']) {
505
-			$components = explode(',',$row['components']);
506
-		}
507
-		$calendar = [
508
-			'id' => $row['id'],
509
-			'uri' => $row['publicuri'],
510
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
518
-		];
519
-
520
-		foreach($this->propertyMap as $xmlName=>$dbName) {
521
-			$calendar[$xmlName] = $row[$dbName];
522
-		}
523
-
524
-		$this->addOwnerPrincipal($calendar);
525
-
526
-		return $calendar;
527
-
528
-	}
529
-
530
-	/**
531
-	 * @param string $principal
532
-	 * @param string $uri
533
-	 * @return array|null
534
-	 */
535
-	public function getCalendarByUri($principal, $uri) {
536
-		$fields = array_values($this->propertyMap);
537
-		$fields[] = 'id';
538
-		$fields[] = 'uri';
539
-		$fields[] = 'synctoken';
540
-		$fields[] = 'components';
541
-		$fields[] = 'principaluri';
542
-		$fields[] = 'transparent';
543
-
544
-		// Making fields a comma-delimited list
545
-		$query = $this->db->getQueryBuilder();
546
-		$query->select($fields)->from('calendars')
547
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
548
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
549
-			->setMaxResults(1);
550
-		$stmt = $query->execute();
551
-
552
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
553
-		$stmt->closeCursor();
554
-		if ($row === false) {
555
-			return null;
556
-		}
557
-
558
-		$components = [];
559
-		if ($row['components']) {
560
-			$components = explode(',',$row['components']);
561
-		}
562
-
563
-		$calendar = [
564
-			'id' => $row['id'],
565
-			'uri' => $row['uri'],
566
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
571
-		];
572
-
573
-		foreach($this->propertyMap as $xmlName=>$dbName) {
574
-			$calendar[$xmlName] = $row[$dbName];
575
-		}
576
-
577
-		$this->addOwnerPrincipal($calendar);
578
-
579
-		return $calendar;
580
-	}
581
-
582
-	public function getCalendarById($calendarId) {
583
-		$fields = array_values($this->propertyMap);
584
-		$fields[] = 'id';
585
-		$fields[] = 'uri';
586
-		$fields[] = 'synctoken';
587
-		$fields[] = 'components';
588
-		$fields[] = 'principaluri';
589
-		$fields[] = 'transparent';
590
-
591
-		// Making fields a comma-delimited list
592
-		$query = $this->db->getQueryBuilder();
593
-		$query->select($fields)->from('calendars')
594
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
595
-			->setMaxResults(1);
596
-		$stmt = $query->execute();
597
-
598
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
599
-		$stmt->closeCursor();
600
-		if ($row === false) {
601
-			return null;
602
-		}
603
-
604
-		$components = [];
605
-		if ($row['components']) {
606
-			$components = explode(',',$row['components']);
607
-		}
608
-
609
-		$calendar = [
610
-			'id' => $row['id'],
611
-			'uri' => $row['uri'],
612
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
617
-		];
618
-
619
-		foreach($this->propertyMap as $xmlName=>$dbName) {
620
-			$calendar[$xmlName] = $row[$dbName];
621
-		}
622
-
623
-		$this->addOwnerPrincipal($calendar);
624
-
625
-		return $calendar;
626
-	}
627
-
628
-	/**
629
-	 * Creates a new calendar for a principal.
630
-	 *
631
-	 * If the creation was a success, an id must be returned that can be used to reference
632
-	 * this calendar in other methods, such as updateCalendar.
633
-	 *
634
-	 * @param string $principalUri
635
-	 * @param string $calendarUri
636
-	 * @param array $properties
637
-	 * @return int
638
-	 * @suppress SqlInjectionChecker
639
-	 */
640
-	function createCalendar($principalUri, $calendarUri, array $properties) {
641
-		$values = [
642
-			'principaluri' => $this->convertPrincipal($principalUri, true),
643
-			'uri'          => $calendarUri,
644
-			'synctoken'    => 1,
645
-			'transparent'  => 0,
646
-			'components'   => 'VEVENT,VTODO',
647
-			'displayname'  => $calendarUri
648
-		];
649
-
650
-		// Default value
651
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
652
-		if (isset($properties[$sccs])) {
653
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
654
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
655
-			}
656
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
657
-		}
658
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
659
-		if (isset($properties[$transp])) {
660
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
661
-		}
662
-
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
664
-			if (isset($properties[$xmlName])) {
665
-				$values[$dbName] = $properties[$xmlName];
666
-			}
667
-		}
668
-
669
-		$query = $this->db->getQueryBuilder();
670
-		$query->insert('calendars');
671
-		foreach($values as $column => $value) {
672
-			$query->setValue($column, $query->createNamedParameter($value));
673
-		}
674
-		$query->execute();
675
-		$calendarId = $query->getLastInsertId();
676
-
677
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
678
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
679
-			[
680
-				'calendarId' => $calendarId,
681
-				'calendarData' => $this->getCalendarById($calendarId),
682
-		]));
683
-
684
-		return $calendarId;
685
-	}
686
-
687
-	/**
688
-	 * Updates properties for a calendar.
689
-	 *
690
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
691
-	 * To do the actual updates, you must tell this object which properties
692
-	 * you're going to process with the handle() method.
693
-	 *
694
-	 * Calling the handle method is like telling the PropPatch object "I
695
-	 * promise I can handle updating this property".
696
-	 *
697
-	 * Read the PropPatch documentation for more info and examples.
698
-	 *
699
-	 * @param mixed $calendarId
700
-	 * @param PropPatch $propPatch
701
-	 * @return void
702
-	 */
703
-	function updateCalendar($calendarId, PropPatch $propPatch) {
704
-		$supportedProperties = array_keys($this->propertyMap);
705
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
706
-
707
-		/**
708
-		 * @suppress SqlInjectionChecker
709
-		 */
710
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
711
-			$newValues = [];
712
-			foreach ($mutations as $propertyName => $propertyValue) {
713
-
714
-				switch ($propertyName) {
715
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
716
-						$fieldName = 'transparent';
717
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
718
-						break;
719
-					default :
720
-						$fieldName = $this->propertyMap[$propertyName];
721
-						$newValues[$fieldName] = $propertyValue;
722
-						break;
723
-				}
724
-
725
-			}
726
-			$query = $this->db->getQueryBuilder();
727
-			$query->update('calendars');
728
-			foreach ($newValues as $fieldName => $value) {
729
-				$query->set($fieldName, $query->createNamedParameter($value));
730
-			}
731
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
732
-			$query->execute();
733
-
734
-			$this->addChange($calendarId, "", 2);
735
-
736
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
737
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
738
-				[
739
-					'calendarId' => $calendarId,
740
-					'calendarData' => $this->getCalendarById($calendarId),
741
-					'shares' => $this->getShares($calendarId),
742
-					'propertyMutations' => $mutations,
743
-			]));
744
-
745
-			return true;
746
-		});
747
-	}
748
-
749
-	/**
750
-	 * Delete a calendar and all it's objects
751
-	 *
752
-	 * @param mixed $calendarId
753
-	 * @return void
754
-	 */
755
-	function deleteCalendar($calendarId) {
756
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
757
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
758
-			[
759
-				'calendarId' => $calendarId,
760
-				'calendarData' => $this->getCalendarById($calendarId),
761
-				'shares' => $this->getShares($calendarId),
762
-		]));
763
-
764
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
765
-		$stmt->execute([$calendarId]);
766
-
767
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
768
-		$stmt->execute([$calendarId]);
769
-
770
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
771
-		$stmt->execute([$calendarId]);
772
-
773
-		$this->sharingBackend->deleteAllShares($calendarId);
774
-
775
-		$query = $this->db->getQueryBuilder();
776
-		$query->delete($this->dbObjectPropertiesTable)
777
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
778
-			->execute();
779
-	}
780
-
781
-	/**
782
-	 * Delete all of an user's shares
783
-	 *
784
-	 * @param string $principaluri
785
-	 * @return void
786
-	 */
787
-	function deleteAllSharesByUser($principaluri) {
788
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
789
-	}
790
-
791
-	/**
792
-	 * Returns all calendar objects within a calendar.
793
-	 *
794
-	 * Every item contains an array with the following keys:
795
-	 *   * calendardata - The iCalendar-compatible calendar data
796
-	 *   * uri - a unique key which will be used to construct the uri. This can
797
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
798
-	 *     good idea. This is only the basename, or filename, not the full
799
-	 *     path.
800
-	 *   * lastmodified - a timestamp of the last modification time
801
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
802
-	 *   '"abcdef"')
803
-	 *   * size - The size of the calendar objects, in bytes.
804
-	 *   * component - optional, a string containing the type of object, such
805
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
806
-	 *     the Content-Type header.
807
-	 *
808
-	 * Note that the etag is optional, but it's highly encouraged to return for
809
-	 * speed reasons.
810
-	 *
811
-	 * The calendardata is also optional. If it's not returned
812
-	 * 'getCalendarObject' will be called later, which *is* expected to return
813
-	 * calendardata.
814
-	 *
815
-	 * If neither etag or size are specified, the calendardata will be
816
-	 * used/fetched to determine these numbers. If both are specified the
817
-	 * amount of times this is needed is reduced by a great degree.
818
-	 *
819
-	 * @param mixed $calendarId
820
-	 * @return array
821
-	 */
822
-	function getCalendarObjects($calendarId) {
823
-		$query = $this->db->getQueryBuilder();
824
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
825
-			->from('calendarobjects')
826
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
827
-		$stmt = $query->execute();
828
-
829
-		$result = [];
830
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
831
-			$result[] = [
832
-					'id'           => $row['id'],
833
-					'uri'          => $row['uri'],
834
-					'lastmodified' => $row['lastmodified'],
835
-					'etag'         => '"' . $row['etag'] . '"',
836
-					'calendarid'   => $row['calendarid'],
837
-					'size'         => (int)$row['size'],
838
-					'component'    => strtolower($row['componenttype']),
839
-					'classification'=> (int)$row['classification']
840
-			];
841
-		}
842
-
843
-		return $result;
844
-	}
845
-
846
-	/**
847
-	 * Returns information from a single calendar object, based on it's object
848
-	 * uri.
849
-	 *
850
-	 * The object uri is only the basename, or filename and not a full path.
851
-	 *
852
-	 * The returned array must have the same keys as getCalendarObjects. The
853
-	 * 'calendardata' object is required here though, while it's not required
854
-	 * for getCalendarObjects.
855
-	 *
856
-	 * This method must return null if the object did not exist.
857
-	 *
858
-	 * @param mixed $calendarId
859
-	 * @param string $objectUri
860
-	 * @return array|null
861
-	 */
862
-	function getCalendarObject($calendarId, $objectUri) {
863
-
864
-		$query = $this->db->getQueryBuilder();
865
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
866
-				->from('calendarobjects')
867
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
869
-		$stmt = $query->execute();
870
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
871
-
872
-		if(!$row) return null;
873
-
874
-		return [
875
-				'id'            => $row['id'],
876
-				'uri'           => $row['uri'],
877
-				'lastmodified'  => $row['lastmodified'],
878
-				'etag'          => '"' . $row['etag'] . '"',
879
-				'calendarid'    => $row['calendarid'],
880
-				'size'          => (int)$row['size'],
881
-				'calendardata'  => $this->readBlob($row['calendardata']),
882
-				'component'     => strtolower($row['componenttype']),
883
-				'classification'=> (int)$row['classification']
884
-		];
885
-	}
886
-
887
-	/**
888
-	 * Returns a list of calendar objects.
889
-	 *
890
-	 * This method should work identical to getCalendarObject, but instead
891
-	 * return all the calendar objects in the list as an array.
892
-	 *
893
-	 * If the backend supports this, it may allow for some speed-ups.
894
-	 *
895
-	 * @param mixed $calendarId
896
-	 * @param string[] $uris
897
-	 * @return array
898
-	 */
899
-	function getMultipleCalendarObjects($calendarId, array $uris) {
900
-		if (empty($uris)) {
901
-			return [];
902
-		}
903
-
904
-		$chunks = array_chunk($uris, 100);
905
-		$objects = [];
906
-
907
-		$query = $this->db->getQueryBuilder();
908
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
909
-			->from('calendarobjects')
910
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
911
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
912
-
913
-		foreach ($chunks as $uris) {
914
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
915
-			$result = $query->execute();
916
-
917
-			while ($row = $result->fetch()) {
918
-				$objects[] = [
919
-					'id'           => $row['id'],
920
-					'uri'          => $row['uri'],
921
-					'lastmodified' => $row['lastmodified'],
922
-					'etag'         => '"' . $row['etag'] . '"',
923
-					'calendarid'   => $row['calendarid'],
924
-					'size'         => (int)$row['size'],
925
-					'calendardata' => $this->readBlob($row['calendardata']),
926
-					'component'    => strtolower($row['componenttype']),
927
-					'classification' => (int)$row['classification']
928
-				];
929
-			}
930
-			$result->closeCursor();
931
-		}
932
-		return $objects;
933
-	}
934
-
935
-	/**
936
-	 * Creates a new calendar object.
937
-	 *
938
-	 * The object uri is only the basename, or filename and not a full path.
939
-	 *
940
-	 * It is possible return an etag from this function, which will be used in
941
-	 * the response to this PUT request. Note that the ETag must be surrounded
942
-	 * by double-quotes.
943
-	 *
944
-	 * However, you should only really return this ETag if you don't mangle the
945
-	 * calendar-data. If the result of a subsequent GET to this object is not
946
-	 * the exact same as this request body, you should omit the ETag.
947
-	 *
948
-	 * @param mixed $calendarId
949
-	 * @param string $objectUri
950
-	 * @param string $calendarData
951
-	 * @return string
952
-	 */
953
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
954
-		$extraData = $this->getDenormalizedData($calendarData);
955
-
956
-		$query = $this->db->getQueryBuilder();
957
-		$query->insert('calendarobjects')
958
-			->values([
959
-				'calendarid' => $query->createNamedParameter($calendarId),
960
-				'uri' => $query->createNamedParameter($objectUri),
961
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
962
-				'lastmodified' => $query->createNamedParameter(time()),
963
-				'etag' => $query->createNamedParameter($extraData['etag']),
964
-				'size' => $query->createNamedParameter($extraData['size']),
965
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
966
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
967
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
968
-				'classification' => $query->createNamedParameter($extraData['classification']),
969
-				'uid' => $query->createNamedParameter($extraData['uid']),
970
-			])
971
-			->execute();
972
-
973
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
974
-
975
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
976
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
977
-			[
978
-				'calendarId' => $calendarId,
979
-				'calendarData' => $this->getCalendarById($calendarId),
980
-				'shares' => $this->getShares($calendarId),
981
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
982
-			]
983
-		));
984
-		$this->addChange($calendarId, $objectUri, 1);
985
-
986
-		return '"' . $extraData['etag'] . '"';
987
-	}
988
-
989
-	/**
990
-	 * Updates an existing calendarobject, based on it's uri.
991
-	 *
992
-	 * The object uri is only the basename, or filename and not a full path.
993
-	 *
994
-	 * It is possible return an etag from this function, which will be used in
995
-	 * the response to this PUT request. Note that the ETag must be surrounded
996
-	 * by double-quotes.
997
-	 *
998
-	 * However, you should only really return this ETag if you don't mangle the
999
-	 * calendar-data. If the result of a subsequent GET to this object is not
1000
-	 * the exact same as this request body, you should omit the ETag.
1001
-	 *
1002
-	 * @param mixed $calendarId
1003
-	 * @param string $objectUri
1004
-	 * @param string $calendarData
1005
-	 * @return string
1006
-	 */
1007
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1008
-		$extraData = $this->getDenormalizedData($calendarData);
1009
-
1010
-		$query = $this->db->getQueryBuilder();
1011
-		$query->update('calendarobjects')
1012
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1013
-				->set('lastmodified', $query->createNamedParameter(time()))
1014
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1015
-				->set('size', $query->createNamedParameter($extraData['size']))
1016
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1017
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1018
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1019
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1020
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1021
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1022
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1023
-			->execute();
1024
-
1025
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1026
-
1027
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1028
-		if (is_array($data)) {
1029
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1030
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1031
-				[
1032
-					'calendarId' => $calendarId,
1033
-					'calendarData' => $this->getCalendarById($calendarId),
1034
-					'shares' => $this->getShares($calendarId),
1035
-					'objectData' => $data,
1036
-				]
1037
-			));
1038
-		}
1039
-		$this->addChange($calendarId, $objectUri, 2);
1040
-
1041
-		return '"' . $extraData['etag'] . '"';
1042
-	}
1043
-
1044
-	/**
1045
-	 * @param int $calendarObjectId
1046
-	 * @param int $classification
1047
-	 */
1048
-	public function setClassification($calendarObjectId, $classification) {
1049
-		if (!in_array($classification, [
1050
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1051
-		])) {
1052
-			throw new \InvalidArgumentException();
1053
-		}
1054
-		$query = $this->db->getQueryBuilder();
1055
-		$query->update('calendarobjects')
1056
-			->set('classification', $query->createNamedParameter($classification))
1057
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1058
-			->execute();
1059
-	}
1060
-
1061
-	/**
1062
-	 * Deletes an existing calendar object.
1063
-	 *
1064
-	 * The object uri is only the basename, or filename and not a full path.
1065
-	 *
1066
-	 * @param mixed $calendarId
1067
-	 * @param string $objectUri
1068
-	 * @return void
1069
-	 */
1070
-	function deleteCalendarObject($calendarId, $objectUri) {
1071
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1072
-		if (is_array($data)) {
1073
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1074
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1075
-				[
1076
-					'calendarId' => $calendarId,
1077
-					'calendarData' => $this->getCalendarById($calendarId),
1078
-					'shares' => $this->getShares($calendarId),
1079
-					'objectData' => $data,
1080
-				]
1081
-			));
1082
-		}
1083
-
1084
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1085
-		$stmt->execute([$calendarId, $objectUri]);
1086
-
1087
-		$this->purgeProperties($calendarId, $data['id']);
1088
-
1089
-		$this->addChange($calendarId, $objectUri, 3);
1090
-	}
1091
-
1092
-	/**
1093
-	 * Performs a calendar-query on the contents of this calendar.
1094
-	 *
1095
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1096
-	 * calendar-query it is possible for a client to request a specific set of
1097
-	 * object, based on contents of iCalendar properties, date-ranges and
1098
-	 * iCalendar component types (VTODO, VEVENT).
1099
-	 *
1100
-	 * This method should just return a list of (relative) urls that match this
1101
-	 * query.
1102
-	 *
1103
-	 * The list of filters are specified as an array. The exact array is
1104
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1105
-	 *
1106
-	 * Note that it is extremely likely that getCalendarObject for every path
1107
-	 * returned from this method will be called almost immediately after. You
1108
-	 * may want to anticipate this to speed up these requests.
1109
-	 *
1110
-	 * This method provides a default implementation, which parses *all* the
1111
-	 * iCalendar objects in the specified calendar.
1112
-	 *
1113
-	 * This default may well be good enough for personal use, and calendars
1114
-	 * that aren't very large. But if you anticipate high usage, big calendars
1115
-	 * or high loads, you are strongly advised to optimize certain paths.
1116
-	 *
1117
-	 * The best way to do so is override this method and to optimize
1118
-	 * specifically for 'common filters'.
1119
-	 *
1120
-	 * Requests that are extremely common are:
1121
-	 *   * requests for just VEVENTS
1122
-	 *   * requests for just VTODO
1123
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1124
-	 *
1125
-	 * ..and combinations of these requests. It may not be worth it to try to
1126
-	 * handle every possible situation and just rely on the (relatively
1127
-	 * easy to use) CalendarQueryValidator to handle the rest.
1128
-	 *
1129
-	 * Note that especially time-range-filters may be difficult to parse. A
1130
-	 * time-range filter specified on a VEVENT must for instance also handle
1131
-	 * recurrence rules correctly.
1132
-	 * A good example of how to interprete all these filters can also simply
1133
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1134
-	 * as possible, so it gives you a good idea on what type of stuff you need
1135
-	 * to think of.
1136
-	 *
1137
-	 * @param mixed $calendarId
1138
-	 * @param array $filters
1139
-	 * @return array
1140
-	 */
1141
-	function calendarQuery($calendarId, array $filters) {
1142
-		$componentType = null;
1143
-		$requirePostFilter = true;
1144
-		$timeRange = null;
1145
-
1146
-		// if no filters were specified, we don't need to filter after a query
1147
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1148
-			$requirePostFilter = false;
1149
-		}
1150
-
1151
-		// Figuring out if there's a component filter
1152
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1153
-			$componentType = $filters['comp-filters'][0]['name'];
1154
-
1155
-			// Checking if we need post-filters
1156
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1157
-				$requirePostFilter = false;
1158
-			}
1159
-			// There was a time-range filter
1160
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1161
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1162
-
1163
-				// If start time OR the end time is not specified, we can do a
1164
-				// 100% accurate mysql query.
1165
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1166
-					$requirePostFilter = false;
1167
-				}
1168
-			}
1169
-
1170
-		}
1171
-		$columns = ['uri'];
1172
-		if ($requirePostFilter) {
1173
-			$columns = ['uri', 'calendardata'];
1174
-		}
1175
-		$query = $this->db->getQueryBuilder();
1176
-		$query->select($columns)
1177
-			->from('calendarobjects')
1178
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1179
-
1180
-		if ($componentType) {
1181
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1182
-		}
1183
-
1184
-		if ($timeRange && $timeRange['start']) {
1185
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1186
-		}
1187
-		if ($timeRange && $timeRange['end']) {
1188
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1189
-		}
1190
-
1191
-		$stmt = $query->execute();
1192
-
1193
-		$result = [];
1194
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1195
-			if ($requirePostFilter) {
1196
-				if (!$this->validateFilterForObject($row, $filters)) {
1197
-					continue;
1198
-				}
1199
-			}
1200
-			$result[] = $row['uri'];
1201
-		}
1202
-
1203
-		return $result;
1204
-	}
1205
-
1206
-	/**
1207
-	 * custom Nextcloud search extension for CalDAV
1208
-	 *
1209
-	 * @param string $principalUri
1210
-	 * @param array $filters
1211
-	 * @param integer|null $limit
1212
-	 * @param integer|null $offset
1213
-	 * @return array
1214
-	 */
1215
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1216
-		$calendars = $this->getCalendarsForUser($principalUri);
1217
-		$ownCalendars = [];
1218
-		$sharedCalendars = [];
1219
-
1220
-		$uriMapper = [];
1221
-
1222
-		foreach($calendars as $calendar) {
1223
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1224
-				$ownCalendars[] = $calendar['id'];
1225
-			} else {
1226
-				$sharedCalendars[] = $calendar['id'];
1227
-			}
1228
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1229
-		}
1230
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1231
-			return [];
1232
-		}
1233
-
1234
-		$query = $this->db->getQueryBuilder();
1235
-		// Calendar id expressions
1236
-		$calendarExpressions = [];
1237
-		foreach($ownCalendars as $id) {
1238
-			$calendarExpressions[] = $query->expr()
1239
-				->eq('c.calendarid', $query->createNamedParameter($id));
1240
-		}
1241
-		foreach($sharedCalendars as $id) {
1242
-			$calendarExpressions[] = $query->expr()->andX(
1243
-				$query->expr()->eq('c.calendarid',
1244
-					$query->createNamedParameter($id)),
1245
-				$query->expr()->eq('c.classification',
1246
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1247
-			);
1248
-		}
1249
-
1250
-		if (count($calendarExpressions) === 1) {
1251
-			$calExpr = $calendarExpressions[0];
1252
-		} else {
1253
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1254
-		}
1255
-
1256
-		// Component expressions
1257
-		$compExpressions = [];
1258
-		foreach($filters['comps'] as $comp) {
1259
-			$compExpressions[] = $query->expr()
1260
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1261
-		}
1262
-
1263
-		if (count($compExpressions) === 1) {
1264
-			$compExpr = $compExpressions[0];
1265
-		} else {
1266
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1267
-		}
1268
-
1269
-		if (!isset($filters['props'])) {
1270
-			$filters['props'] = [];
1271
-		}
1272
-		if (!isset($filters['params'])) {
1273
-			$filters['params'] = [];
1274
-		}
1275
-
1276
-		$propParamExpressions = [];
1277
-		foreach($filters['props'] as $prop) {
1278
-			$propParamExpressions[] = $query->expr()->andX(
1279
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1280
-				$query->expr()->isNull('i.parameter')
1281
-			);
1282
-		}
1283
-		foreach($filters['params'] as $param) {
1284
-			$propParamExpressions[] = $query->expr()->andX(
1285
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1286
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1287
-			);
1288
-		}
1289
-
1290
-		if (count($propParamExpressions) === 1) {
1291
-			$propParamExpr = $propParamExpressions[0];
1292
-		} else {
1293
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1294
-		}
1295
-
1296
-		$query->select(['c.calendarid', 'c.uri'])
1297
-			->from($this->dbObjectPropertiesTable, 'i')
1298
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1299
-			->where($calExpr)
1300
-			->andWhere($compExpr)
1301
-			->andWhere($propParamExpr)
1302
-			->andWhere($query->expr()->iLike('i.value',
1303
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1304
-
1305
-		if ($offset) {
1306
-			$query->setFirstResult($offset);
1307
-		}
1308
-		if ($limit) {
1309
-			$query->setMaxResults($limit);
1310
-		}
1311
-
1312
-		$stmt = $query->execute();
1313
-
1314
-		$result = [];
1315
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1316
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1317
-			if (!in_array($path, $result)) {
1318
-				$result[] = $path;
1319
-			}
1320
-		}
1321
-
1322
-		return $result;
1323
-	}
1324
-
1325
-	/**
1326
-	 * Searches through all of a users calendars and calendar objects to find
1327
-	 * an object with a specific UID.
1328
-	 *
1329
-	 * This method should return the path to this object, relative to the
1330
-	 * calendar home, so this path usually only contains two parts:
1331
-	 *
1332
-	 * calendarpath/objectpath.ics
1333
-	 *
1334
-	 * If the uid is not found, return null.
1335
-	 *
1336
-	 * This method should only consider * objects that the principal owns, so
1337
-	 * any calendars owned by other principals that also appear in this
1338
-	 * collection should be ignored.
1339
-	 *
1340
-	 * @param string $principalUri
1341
-	 * @param string $uid
1342
-	 * @return string|null
1343
-	 */
1344
-	function getCalendarObjectByUID($principalUri, $uid) {
1345
-
1346
-		$query = $this->db->getQueryBuilder();
1347
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1348
-			->from('calendarobjects', 'co')
1349
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1350
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1351
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1352
-
1353
-		$stmt = $query->execute();
1354
-
1355
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1357
-		}
1358
-
1359
-		return null;
1360
-	}
1361
-
1362
-	/**
1363
-	 * The getChanges method returns all the changes that have happened, since
1364
-	 * the specified syncToken in the specified calendar.
1365
-	 *
1366
-	 * This function should return an array, such as the following:
1367
-	 *
1368
-	 * [
1369
-	 *   'syncToken' => 'The current synctoken',
1370
-	 *   'added'   => [
1371
-	 *      'new.txt',
1372
-	 *   ],
1373
-	 *   'modified'   => [
1374
-	 *      'modified.txt',
1375
-	 *   ],
1376
-	 *   'deleted' => [
1377
-	 *      'foo.php.bak',
1378
-	 *      'old.txt'
1379
-	 *   ]
1380
-	 * );
1381
-	 *
1382
-	 * The returned syncToken property should reflect the *current* syncToken
1383
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1384
-	 * property This is * needed here too, to ensure the operation is atomic.
1385
-	 *
1386
-	 * If the $syncToken argument is specified as null, this is an initial
1387
-	 * sync, and all members should be reported.
1388
-	 *
1389
-	 * The modified property is an array of nodenames that have changed since
1390
-	 * the last token.
1391
-	 *
1392
-	 * The deleted property is an array with nodenames, that have been deleted
1393
-	 * from collection.
1394
-	 *
1395
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1396
-	 * 1, you only have to report changes that happened only directly in
1397
-	 * immediate descendants. If it's 2, it should also include changes from
1398
-	 * the nodes below the child collections. (grandchildren)
1399
-	 *
1400
-	 * The $limit argument allows a client to specify how many results should
1401
-	 * be returned at most. If the limit is not specified, it should be treated
1402
-	 * as infinite.
1403
-	 *
1404
-	 * If the limit (infinite or not) is higher than you're willing to return,
1405
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1406
-	 *
1407
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1408
-	 * return null.
1409
-	 *
1410
-	 * The limit is 'suggestive'. You are free to ignore it.
1411
-	 *
1412
-	 * @param string $calendarId
1413
-	 * @param string $syncToken
1414
-	 * @param int $syncLevel
1415
-	 * @param int $limit
1416
-	 * @return array
1417
-	 */
1418
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1419
-		// Current synctoken
1420
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1421
-		$stmt->execute([ $calendarId ]);
1422
-		$currentToken = $stmt->fetchColumn(0);
1423
-
1424
-		if (is_null($currentToken)) {
1425
-			return null;
1426
-		}
1427
-
1428
-		$result = [
1429
-			'syncToken' => $currentToken,
1430
-			'added'     => [],
1431
-			'modified'  => [],
1432
-			'deleted'   => [],
1433
-		];
1434
-
1435
-		if ($syncToken) {
1436
-
1437
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1438
-			if ($limit>0) {
1439
-				$query.= " `LIMIT` " . (int)$limit;
1440
-			}
1441
-
1442
-			// Fetching all changes
1443
-			$stmt = $this->db->prepare($query);
1444
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1445
-
1446
-			$changes = [];
1447
-
1448
-			// This loop ensures that any duplicates are overwritten, only the
1449
-			// last change on a node is relevant.
1450
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1451
-
1452
-				$changes[$row['uri']] = $row['operation'];
1453
-
1454
-			}
1455
-
1456
-			foreach($changes as $uri => $operation) {
1457
-
1458
-				switch($operation) {
1459
-					case 1 :
1460
-						$result['added'][] = $uri;
1461
-						break;
1462
-					case 2 :
1463
-						$result['modified'][] = $uri;
1464
-						break;
1465
-					case 3 :
1466
-						$result['deleted'][] = $uri;
1467
-						break;
1468
-				}
1469
-
1470
-			}
1471
-		} else {
1472
-			// No synctoken supplied, this is the initial sync.
1473
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1474
-			$stmt = $this->db->prepare($query);
1475
-			$stmt->execute([$calendarId]);
1476
-
1477
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1478
-		}
1479
-		return $result;
1480
-
1481
-	}
1482
-
1483
-	/**
1484
-	 * Returns a list of subscriptions for a principal.
1485
-	 *
1486
-	 * Every subscription is an array with the following keys:
1487
-	 *  * id, a unique id that will be used by other functions to modify the
1488
-	 *    subscription. This can be the same as the uri or a database key.
1489
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1490
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1491
-	 *    principalUri passed to this method.
1492
-	 *
1493
-	 * Furthermore, all the subscription info must be returned too:
1494
-	 *
1495
-	 * 1. {DAV:}displayname
1496
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1497
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1498
-	 *    should not be stripped).
1499
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1500
-	 *    should not be stripped).
1501
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1502
-	 *    attachments should not be stripped).
1503
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1504
-	 *     Sabre\DAV\Property\Href).
1505
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1506
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1507
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1508
-	 *    (should just be an instance of
1509
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1510
-	 *    default components).
1511
-	 *
1512
-	 * @param string $principalUri
1513
-	 * @return array
1514
-	 */
1515
-	function getSubscriptionsForUser($principalUri) {
1516
-		$fields = array_values($this->subscriptionPropertyMap);
1517
-		$fields[] = 'id';
1518
-		$fields[] = 'uri';
1519
-		$fields[] = 'source';
1520
-		$fields[] = 'principaluri';
1521
-		$fields[] = 'lastmodified';
1522
-
1523
-		$query = $this->db->getQueryBuilder();
1524
-		$query->select($fields)
1525
-			->from('calendarsubscriptions')
1526
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1527
-			->orderBy('calendarorder', 'asc');
1528
-		$stmt =$query->execute();
1529
-
1530
-		$subscriptions = [];
1531
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1532
-
1533
-			$subscription = [
1534
-				'id'           => $row['id'],
1535
-				'uri'          => $row['uri'],
1536
-				'principaluri' => $row['principaluri'],
1537
-				'source'       => $row['source'],
1538
-				'lastmodified' => $row['lastmodified'],
1539
-
1540
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1541
-			];
1542
-
1543
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1544
-				if (!is_null($row[$dbName])) {
1545
-					$subscription[$xmlName] = $row[$dbName];
1546
-				}
1547
-			}
1548
-
1549
-			$subscriptions[] = $subscription;
1550
-
1551
-		}
1552
-
1553
-		return $subscriptions;
1554
-	}
1555
-
1556
-	/**
1557
-	 * Creates a new subscription for a principal.
1558
-	 *
1559
-	 * If the creation was a success, an id must be returned that can be used to reference
1560
-	 * this subscription in other methods, such as updateSubscription.
1561
-	 *
1562
-	 * @param string $principalUri
1563
-	 * @param string $uri
1564
-	 * @param array $properties
1565
-	 * @return mixed
1566
-	 */
1567
-	function createSubscription($principalUri, $uri, array $properties) {
1568
-
1569
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1570
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1571
-		}
1572
-
1573
-		$values = [
1574
-			'principaluri' => $principalUri,
1575
-			'uri'          => $uri,
1576
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1577
-			'lastmodified' => time(),
1578
-		];
1579
-
1580
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1581
-
1582
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1583
-			if (array_key_exists($xmlName, $properties)) {
1584
-					$values[$dbName] = $properties[$xmlName];
1585
-					if (in_array($dbName, $propertiesBoolean)) {
1586
-						$values[$dbName] = true;
1587
-				}
1588
-			}
1589
-		}
1590
-
1591
-		$valuesToInsert = array();
1592
-
1593
-		$query = $this->db->getQueryBuilder();
1594
-
1595
-		foreach (array_keys($values) as $name) {
1596
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1597
-		}
1598
-
1599
-		$query->insert('calendarsubscriptions')
1600
-			->values($valuesToInsert)
1601
-			->execute();
1602
-
1603
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1604
-	}
1605
-
1606
-	/**
1607
-	 * Updates a subscription
1608
-	 *
1609
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1610
-	 * To do the actual updates, you must tell this object which properties
1611
-	 * you're going to process with the handle() method.
1612
-	 *
1613
-	 * Calling the handle method is like telling the PropPatch object "I
1614
-	 * promise I can handle updating this property".
1615
-	 *
1616
-	 * Read the PropPatch documentation for more info and examples.
1617
-	 *
1618
-	 * @param mixed $subscriptionId
1619
-	 * @param PropPatch $propPatch
1620
-	 * @return void
1621
-	 */
1622
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1623
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1624
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1625
-
1626
-		/**
1627
-		 * @suppress SqlInjectionChecker
1628
-		 */
1629
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1630
-
1631
-			$newValues = [];
1632
-
1633
-			foreach($mutations as $propertyName=>$propertyValue) {
1634
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1635
-					$newValues['source'] = $propertyValue->getHref();
1636
-				} else {
1637
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1638
-					$newValues[$fieldName] = $propertyValue;
1639
-				}
1640
-			}
1641
-
1642
-			$query = $this->db->getQueryBuilder();
1643
-			$query->update('calendarsubscriptions')
1644
-				->set('lastmodified', $query->createNamedParameter(time()));
1645
-			foreach($newValues as $fieldName=>$value) {
1646
-				$query->set($fieldName, $query->createNamedParameter($value));
1647
-			}
1648
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1649
-				->execute();
1650
-
1651
-			return true;
1652
-
1653
-		});
1654
-	}
1655
-
1656
-	/**
1657
-	 * Deletes a subscription.
1658
-	 *
1659
-	 * @param mixed $subscriptionId
1660
-	 * @return void
1661
-	 */
1662
-	function deleteSubscription($subscriptionId) {
1663
-		$query = $this->db->getQueryBuilder();
1664
-		$query->delete('calendarsubscriptions')
1665
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1666
-			->execute();
1667
-	}
1668
-
1669
-	/**
1670
-	 * Returns a single scheduling object for the inbox collection.
1671
-	 *
1672
-	 * The returned array should contain the following elements:
1673
-	 *   * uri - A unique basename for the object. This will be used to
1674
-	 *           construct a full uri.
1675
-	 *   * calendardata - The iCalendar object
1676
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1677
-	 *                    timestamp, or a PHP DateTime object.
1678
-	 *   * etag - A unique token that must change if the object changed.
1679
-	 *   * size - The size of the object, in bytes.
1680
-	 *
1681
-	 * @param string $principalUri
1682
-	 * @param string $objectUri
1683
-	 * @return array
1684
-	 */
1685
-	function getSchedulingObject($principalUri, $objectUri) {
1686
-		$query = $this->db->getQueryBuilder();
1687
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1688
-			->from('schedulingobjects')
1689
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1690
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1691
-			->execute();
1692
-
1693
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1694
-
1695
-		if(!$row) {
1696
-			return null;
1697
-		}
1698
-
1699
-		return [
1700
-				'uri'          => $row['uri'],
1701
-				'calendardata' => $row['calendardata'],
1702
-				'lastmodified' => $row['lastmodified'],
1703
-				'etag'         => '"' . $row['etag'] . '"',
1704
-				'size'         => (int)$row['size'],
1705
-		];
1706
-	}
1707
-
1708
-	/**
1709
-	 * Returns all scheduling objects for the inbox collection.
1710
-	 *
1711
-	 * These objects should be returned as an array. Every item in the array
1712
-	 * should follow the same structure as returned from getSchedulingObject.
1713
-	 *
1714
-	 * The main difference is that 'calendardata' is optional.
1715
-	 *
1716
-	 * @param string $principalUri
1717
-	 * @return array
1718
-	 */
1719
-	function getSchedulingObjects($principalUri) {
1720
-		$query = $this->db->getQueryBuilder();
1721
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1722
-				->from('schedulingobjects')
1723
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1724
-				->execute();
1725
-
1726
-		$result = [];
1727
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1728
-			$result[] = [
1729
-					'calendardata' => $row['calendardata'],
1730
-					'uri'          => $row['uri'],
1731
-					'lastmodified' => $row['lastmodified'],
1732
-					'etag'         => '"' . $row['etag'] . '"',
1733
-					'size'         => (int)$row['size'],
1734
-			];
1735
-		}
1736
-
1737
-		return $result;
1738
-	}
1739
-
1740
-	/**
1741
-	 * Deletes a scheduling object from the inbox collection.
1742
-	 *
1743
-	 * @param string $principalUri
1744
-	 * @param string $objectUri
1745
-	 * @return void
1746
-	 */
1747
-	function deleteSchedulingObject($principalUri, $objectUri) {
1748
-		$query = $this->db->getQueryBuilder();
1749
-		$query->delete('schedulingobjects')
1750
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1751
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1752
-				->execute();
1753
-	}
1754
-
1755
-	/**
1756
-	 * Creates a new scheduling object. This should land in a users' inbox.
1757
-	 *
1758
-	 * @param string $principalUri
1759
-	 * @param string $objectUri
1760
-	 * @param string $objectData
1761
-	 * @return void
1762
-	 */
1763
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1764
-		$query = $this->db->getQueryBuilder();
1765
-		$query->insert('schedulingobjects')
1766
-			->values([
1767
-				'principaluri' => $query->createNamedParameter($principalUri),
1768
-				'calendardata' => $query->createNamedParameter($objectData),
1769
-				'uri' => $query->createNamedParameter($objectUri),
1770
-				'lastmodified' => $query->createNamedParameter(time()),
1771
-				'etag' => $query->createNamedParameter(md5($objectData)),
1772
-				'size' => $query->createNamedParameter(strlen($objectData))
1773
-			])
1774
-			->execute();
1775
-	}
1776
-
1777
-	/**
1778
-	 * Adds a change record to the calendarchanges table.
1779
-	 *
1780
-	 * @param mixed $calendarId
1781
-	 * @param string $objectUri
1782
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1783
-	 * @return void
1784
-	 */
1785
-	protected function addChange($calendarId, $objectUri, $operation) {
1786
-
1787
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1788
-		$stmt->execute([
1789
-			$objectUri,
1790
-			$calendarId,
1791
-			$operation,
1792
-			$calendarId
1793
-		]);
1794
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1795
-		$stmt->execute([
1796
-			$calendarId
1797
-		]);
1798
-
1799
-	}
1800
-
1801
-	/**
1802
-	 * Parses some information from calendar objects, used for optimized
1803
-	 * calendar-queries.
1804
-	 *
1805
-	 * Returns an array with the following keys:
1806
-	 *   * etag - An md5 checksum of the object without the quotes.
1807
-	 *   * size - Size of the object in bytes
1808
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1809
-	 *   * firstOccurence
1810
-	 *   * lastOccurence
1811
-	 *   * uid - value of the UID property
1812
-	 *
1813
-	 * @param string $calendarData
1814
-	 * @return array
1815
-	 */
1816
-	public function getDenormalizedData($calendarData) {
1817
-
1818
-		$vObject = Reader::read($calendarData);
1819
-		$componentType = null;
1820
-		$component = null;
1821
-		$firstOccurrence = null;
1822
-		$lastOccurrence = null;
1823
-		$uid = null;
1824
-		$classification = self::CLASSIFICATION_PUBLIC;
1825
-		foreach($vObject->getComponents() as $component) {
1826
-			if ($component->name!=='VTIMEZONE') {
1827
-				$componentType = $component->name;
1828
-				$uid = (string)$component->UID;
1829
-				break;
1830
-			}
1831
-		}
1832
-		if (!$componentType) {
1833
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1834
-		}
1835
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1836
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1837
-			// Finding the last occurrence is a bit harder
1838
-			if (!isset($component->RRULE)) {
1839
-				if (isset($component->DTEND)) {
1840
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1841
-				} elseif (isset($component->DURATION)) {
1842
-					$endDate = clone $component->DTSTART->getDateTime();
1843
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1844
-					$lastOccurrence = $endDate->getTimeStamp();
1845
-				} elseif (!$component->DTSTART->hasTime()) {
1846
-					$endDate = clone $component->DTSTART->getDateTime();
1847
-					$endDate->modify('+1 day');
1848
-					$lastOccurrence = $endDate->getTimeStamp();
1849
-				} else {
1850
-					$lastOccurrence = $firstOccurrence;
1851
-				}
1852
-			} else {
1853
-				$it = new EventIterator($vObject, (string)$component->UID);
1854
-				$maxDate = new \DateTime(self::MAX_DATE);
1855
-				if ($it->isInfinite()) {
1856
-					$lastOccurrence = $maxDate->getTimestamp();
1857
-				} else {
1858
-					$end = $it->getDtEnd();
1859
-					while($it->valid() && $end < $maxDate) {
1860
-						$end = $it->getDtEnd();
1861
-						$it->next();
1862
-
1863
-					}
1864
-					$lastOccurrence = $end->getTimestamp();
1865
-				}
1866
-
1867
-			}
1868
-		}
1869
-
1870
-		if ($component->CLASS) {
1871
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1872
-			switch ($component->CLASS->getValue()) {
1873
-				case 'PUBLIC':
1874
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1875
-					break;
1876
-				case 'CONFIDENTIAL':
1877
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1878
-					break;
1879
-			}
1880
-		}
1881
-		return [
1882
-			'etag' => md5($calendarData),
1883
-			'size' => strlen($calendarData),
1884
-			'componentType' => $componentType,
1885
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1886
-			'lastOccurence'  => $lastOccurrence,
1887
-			'uid' => $uid,
1888
-			'classification' => $classification
1889
-		];
1890
-
1891
-	}
1892
-
1893
-	private function readBlob($cardData) {
1894
-		if (is_resource($cardData)) {
1895
-			return stream_get_contents($cardData);
1896
-		}
1897
-
1898
-		return $cardData;
1899
-	}
1900
-
1901
-	/**
1902
-	 * @param IShareable $shareable
1903
-	 * @param array $add
1904
-	 * @param array $remove
1905
-	 */
1906
-	public function updateShares($shareable, $add, $remove) {
1907
-		$calendarId = $shareable->getResourceId();
1908
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1909
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1910
-			[
1911
-				'calendarId' => $calendarId,
1912
-				'calendarData' => $this->getCalendarById($calendarId),
1913
-				'shares' => $this->getShares($calendarId),
1914
-				'add' => $add,
1915
-				'remove' => $remove,
1916
-			]));
1917
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1918
-	}
1919
-
1920
-	/**
1921
-	 * @param int $resourceId
1922
-	 * @return array
1923
-	 */
1924
-	public function getShares($resourceId) {
1925
-		return $this->sharingBackend->getShares($resourceId);
1926
-	}
1927
-
1928
-	/**
1929
-	 * @param boolean $value
1930
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1931
-	 * @return string|null
1932
-	 */
1933
-	public function setPublishStatus($value, $calendar) {
1934
-		$query = $this->db->getQueryBuilder();
1935
-		if ($value) {
1936
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
1937
-			$query->insert('dav_shares')
1938
-				->values([
1939
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1940
-					'type' => $query->createNamedParameter('calendar'),
1941
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1942
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1943
-					'publicuri' => $query->createNamedParameter($publicUri)
1944
-				]);
1945
-			$query->execute();
1946
-			return $publicUri;
1947
-		}
1948
-		$query->delete('dav_shares')
1949
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1950
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1951
-		$query->execute();
1952
-		return null;
1953
-	}
1954
-
1955
-	/**
1956
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1957
-	 * @return mixed
1958
-	 */
1959
-	public function getPublishStatus($calendar) {
1960
-		$query = $this->db->getQueryBuilder();
1961
-		$result = $query->select('publicuri')
1962
-			->from('dav_shares')
1963
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1964
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1965
-			->execute();
1966
-
1967
-		$row = $result->fetch();
1968
-		$result->closeCursor();
1969
-		return $row ? reset($row) : false;
1970
-	}
1971
-
1972
-	/**
1973
-	 * @param int $resourceId
1974
-	 * @param array $acl
1975
-	 * @return array
1976
-	 */
1977
-	public function applyShareAcl($resourceId, $acl) {
1978
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1979
-	}
1980
-
1981
-
1982
-
1983
-	/**
1984
-	 * update properties table
1985
-	 *
1986
-	 * @param int $calendarId
1987
-	 * @param string $objectUri
1988
-	 * @param string $calendarData
1989
-	 */
1990
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
1991
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
1992
-
1993
-		try {
1994
-			$vCalendar = $this->readCalendarData($calendarData);
1995
-		} catch (\Exception $ex) {
1996
-			return;
1997
-		}
1998
-
1999
-		$this->purgeProperties($calendarId, $objectId);
2000
-
2001
-		$query = $this->db->getQueryBuilder();
2002
-		$query->insert($this->dbObjectPropertiesTable)
2003
-			->values(
2004
-				[
2005
-					'calendarid' => $query->createNamedParameter($calendarId),
2006
-					'objectid' => $query->createNamedParameter($objectId),
2007
-					'name' => $query->createParameter('name'),
2008
-					'parameter' => $query->createParameter('parameter'),
2009
-					'value' => $query->createParameter('value'),
2010
-				]
2011
-			);
2012
-
2013
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2014
-		foreach ($vCalendar->getComponents() as $component) {
2015
-			if (!in_array($component->name, $indexComponents)) {
2016
-				continue;
2017
-			}
2018
-
2019
-			foreach ($component->children() as $property) {
2020
-				if (in_array($property->name, self::$indexProperties)) {
2021
-					$value = $property->getValue();
2022
-					// is this a shitty db?
2023
-					if (!$this->db->supports4ByteText()) {
2024
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2025
-					}
2026
-					$value = substr($value, 0, 254);
2027
-
2028
-					$query->setParameter('name', $property->name);
2029
-					$query->setParameter('parameter', null);
2030
-					$query->setParameter('value', $value);
2031
-					$query->execute();
2032
-				}
2033
-
2034
-				if (in_array($property->name, array_keys(self::$indexParameters))) {
2035
-					$parameters = $property->parameters();
2036
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2037
-
2038
-					foreach ($parameters as $key => $value) {
2039
-						if (in_array($key, $indexedParametersForProperty)) {
2040
-							// is this a shitty db?
2041
-							if ($this->db->supports4ByteText()) {
2042
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2043
-							}
2044
-							$value = substr($value, 0, 254);
2045
-
2046
-							$query->setParameter('name', $property->name);
2047
-							$query->setParameter('parameter', substr($key, 0, 254));
2048
-							$query->setParameter('value', substr($value, 0, 254));
2049
-							$query->execute();
2050
-						}
2051
-					}
2052
-				}
2053
-			}
2054
-		}
2055
-	}
2056
-
2057
-	/**
2058
-	 * Move a calendar from one user to another
2059
-	 *
2060
-	 * @param $uri
2061
-	 * @param $userOrigin
2062
-	 * @param $userDestination
2063
-	 */
2064
-	public function moveCalendar($uri, $userOrigin, $userDestination)
2065
-	{
2066
-		$query = $this->db->getQueryBuilder();
2067
-		$query->update('calendars')
2068
-			->set('principaluri', 'principals/users/' . $userDestination)
2069
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter('principals/users/'. $userOrigin)))
2070
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2071
-			->execute();
2072
-	}
2073
-
2074
-	/**
2075
-	 * read VCalendar data into a VCalendar object
2076
-	 *
2077
-	 * @param string $objectData
2078
-	 * @return VCalendar
2079
-	 */
2080
-	protected function readCalendarData($objectData) {
2081
-		return Reader::read($objectData);
2082
-	}
2083
-
2084
-	/**
2085
-	 * delete all properties from a given calendar object
2086
-	 *
2087
-	 * @param int $calendarId
2088
-	 * @param int $objectId
2089
-	 */
2090
-	protected function purgeProperties($calendarId, $objectId) {
2091
-		$query = $this->db->getQueryBuilder();
2092
-		$query->delete($this->dbObjectPropertiesTable)
2093
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2094
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2095
-		$query->execute();
2096
-	}
2097
-
2098
-	/**
2099
-	 * get ID from a given calendar object
2100
-	 *
2101
-	 * @param int $calendarId
2102
-	 * @param string $uri
2103
-	 * @return int
2104
-	 */
2105
-	protected function getCalendarObjectId($calendarId, $uri) {
2106
-		$query = $this->db->getQueryBuilder();
2107
-		$query->select('id')->from('calendarobjects')
2108
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2109
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2110
-
2111
-		$result = $query->execute();
2112
-		$objectIds = $result->fetch();
2113
-		$result->closeCursor();
2114
-
2115
-		if (!isset($objectIds['id'])) {
2116
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2117
-		}
2118
-
2119
-		return (int)$objectIds['id'];
2120
-	}
2121
-
2122
-	private function convertPrincipal($principalUri, $toV2) {
2123
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2124
-			list(, $name) = URLUtil::splitPath($principalUri);
2125
-			if ($toV2 === true) {
2126
-				return "principals/users/$name";
2127
-			}
2128
-			return "principals/$name";
2129
-		}
2130
-		return $principalUri;
2131
-	}
2132
-
2133
-	private function addOwnerPrincipal(&$calendarInfo) {
2134
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2135
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2136
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2137
-			$uri = $calendarInfo[$ownerPrincipalKey];
2138
-		} else {
2139
-			$uri = $calendarInfo['principaluri'];
2140
-		}
2141
-
2142
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2143
-		if (isset($principalInformation['{DAV:}displayname'])) {
2144
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2145
-		}
2146
-	}
412
+    /**
413
+     * @return array
414
+     */
415
+    public function getPublicCalendars() {
416
+        $fields = array_values($this->propertyMap);
417
+        $fields[] = 'a.id';
418
+        $fields[] = 'a.uri';
419
+        $fields[] = 'a.synctoken';
420
+        $fields[] = 'a.components';
421
+        $fields[] = 'a.principaluri';
422
+        $fields[] = 'a.transparent';
423
+        $fields[] = 's.access';
424
+        $fields[] = 's.publicuri';
425
+        $calendars = [];
426
+        $query = $this->db->getQueryBuilder();
427
+        $result = $query->select($fields)
428
+            ->from('dav_shares', 's')
429
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
430
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
431
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432
+            ->execute();
433
+
434
+        while($row = $result->fetch()) {
435
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
436
+            $row['displayname'] = $row['displayname'] . "($name)";
437
+            $components = [];
438
+            if ($row['components']) {
439
+                $components = explode(',',$row['components']);
440
+            }
441
+            $calendar = [
442
+                'id' => $row['id'],
443
+                'uri' => $row['publicuri'],
444
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
452
+            ];
453
+
454
+            foreach($this->propertyMap as $xmlName=>$dbName) {
455
+                $calendar[$xmlName] = $row[$dbName];
456
+            }
457
+
458
+            $this->addOwnerPrincipal($calendar);
459
+
460
+            if (!isset($calendars[$calendar['id']])) {
461
+                $calendars[$calendar['id']] = $calendar;
462
+            }
463
+        }
464
+        $result->closeCursor();
465
+
466
+        return array_values($calendars);
467
+    }
468
+
469
+    /**
470
+     * @param string $uri
471
+     * @return array
472
+     * @throws NotFound
473
+     */
474
+    public function getPublicCalendar($uri) {
475
+        $fields = array_values($this->propertyMap);
476
+        $fields[] = 'a.id';
477
+        $fields[] = 'a.uri';
478
+        $fields[] = 'a.synctoken';
479
+        $fields[] = 'a.components';
480
+        $fields[] = 'a.principaluri';
481
+        $fields[] = 'a.transparent';
482
+        $fields[] = 's.access';
483
+        $fields[] = 's.publicuri';
484
+        $query = $this->db->getQueryBuilder();
485
+        $result = $query->select($fields)
486
+            ->from('dav_shares', 's')
487
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
488
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
489
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
490
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
491
+            ->execute();
492
+
493
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
494
+
495
+        $result->closeCursor();
496
+
497
+        if ($row === false) {
498
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
499
+        }
500
+
501
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
502
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
503
+        $components = [];
504
+        if ($row['components']) {
505
+            $components = explode(',',$row['components']);
506
+        }
507
+        $calendar = [
508
+            'id' => $row['id'],
509
+            'uri' => $row['publicuri'],
510
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
518
+        ];
519
+
520
+        foreach($this->propertyMap as $xmlName=>$dbName) {
521
+            $calendar[$xmlName] = $row[$dbName];
522
+        }
523
+
524
+        $this->addOwnerPrincipal($calendar);
525
+
526
+        return $calendar;
527
+
528
+    }
529
+
530
+    /**
531
+     * @param string $principal
532
+     * @param string $uri
533
+     * @return array|null
534
+     */
535
+    public function getCalendarByUri($principal, $uri) {
536
+        $fields = array_values($this->propertyMap);
537
+        $fields[] = 'id';
538
+        $fields[] = 'uri';
539
+        $fields[] = 'synctoken';
540
+        $fields[] = 'components';
541
+        $fields[] = 'principaluri';
542
+        $fields[] = 'transparent';
543
+
544
+        // Making fields a comma-delimited list
545
+        $query = $this->db->getQueryBuilder();
546
+        $query->select($fields)->from('calendars')
547
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
548
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
549
+            ->setMaxResults(1);
550
+        $stmt = $query->execute();
551
+
552
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
553
+        $stmt->closeCursor();
554
+        if ($row === false) {
555
+            return null;
556
+        }
557
+
558
+        $components = [];
559
+        if ($row['components']) {
560
+            $components = explode(',',$row['components']);
561
+        }
562
+
563
+        $calendar = [
564
+            'id' => $row['id'],
565
+            'uri' => $row['uri'],
566
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
571
+        ];
572
+
573
+        foreach($this->propertyMap as $xmlName=>$dbName) {
574
+            $calendar[$xmlName] = $row[$dbName];
575
+        }
576
+
577
+        $this->addOwnerPrincipal($calendar);
578
+
579
+        return $calendar;
580
+    }
581
+
582
+    public function getCalendarById($calendarId) {
583
+        $fields = array_values($this->propertyMap);
584
+        $fields[] = 'id';
585
+        $fields[] = 'uri';
586
+        $fields[] = 'synctoken';
587
+        $fields[] = 'components';
588
+        $fields[] = 'principaluri';
589
+        $fields[] = 'transparent';
590
+
591
+        // Making fields a comma-delimited list
592
+        $query = $this->db->getQueryBuilder();
593
+        $query->select($fields)->from('calendars')
594
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
595
+            ->setMaxResults(1);
596
+        $stmt = $query->execute();
597
+
598
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
599
+        $stmt->closeCursor();
600
+        if ($row === false) {
601
+            return null;
602
+        }
603
+
604
+        $components = [];
605
+        if ($row['components']) {
606
+            $components = explode(',',$row['components']);
607
+        }
608
+
609
+        $calendar = [
610
+            'id' => $row['id'],
611
+            'uri' => $row['uri'],
612
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
617
+        ];
618
+
619
+        foreach($this->propertyMap as $xmlName=>$dbName) {
620
+            $calendar[$xmlName] = $row[$dbName];
621
+        }
622
+
623
+        $this->addOwnerPrincipal($calendar);
624
+
625
+        return $calendar;
626
+    }
627
+
628
+    /**
629
+     * Creates a new calendar for a principal.
630
+     *
631
+     * If the creation was a success, an id must be returned that can be used to reference
632
+     * this calendar in other methods, such as updateCalendar.
633
+     *
634
+     * @param string $principalUri
635
+     * @param string $calendarUri
636
+     * @param array $properties
637
+     * @return int
638
+     * @suppress SqlInjectionChecker
639
+     */
640
+    function createCalendar($principalUri, $calendarUri, array $properties) {
641
+        $values = [
642
+            'principaluri' => $this->convertPrincipal($principalUri, true),
643
+            'uri'          => $calendarUri,
644
+            'synctoken'    => 1,
645
+            'transparent'  => 0,
646
+            'components'   => 'VEVENT,VTODO',
647
+            'displayname'  => $calendarUri
648
+        ];
649
+
650
+        // Default value
651
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
652
+        if (isset($properties[$sccs])) {
653
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
654
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
655
+            }
656
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
657
+        }
658
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
659
+        if (isset($properties[$transp])) {
660
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
661
+        }
662
+
663
+        foreach($this->propertyMap as $xmlName=>$dbName) {
664
+            if (isset($properties[$xmlName])) {
665
+                $values[$dbName] = $properties[$xmlName];
666
+            }
667
+        }
668
+
669
+        $query = $this->db->getQueryBuilder();
670
+        $query->insert('calendars');
671
+        foreach($values as $column => $value) {
672
+            $query->setValue($column, $query->createNamedParameter($value));
673
+        }
674
+        $query->execute();
675
+        $calendarId = $query->getLastInsertId();
676
+
677
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
678
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
679
+            [
680
+                'calendarId' => $calendarId,
681
+                'calendarData' => $this->getCalendarById($calendarId),
682
+        ]));
683
+
684
+        return $calendarId;
685
+    }
686
+
687
+    /**
688
+     * Updates properties for a calendar.
689
+     *
690
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
691
+     * To do the actual updates, you must tell this object which properties
692
+     * you're going to process with the handle() method.
693
+     *
694
+     * Calling the handle method is like telling the PropPatch object "I
695
+     * promise I can handle updating this property".
696
+     *
697
+     * Read the PropPatch documentation for more info and examples.
698
+     *
699
+     * @param mixed $calendarId
700
+     * @param PropPatch $propPatch
701
+     * @return void
702
+     */
703
+    function updateCalendar($calendarId, PropPatch $propPatch) {
704
+        $supportedProperties = array_keys($this->propertyMap);
705
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
706
+
707
+        /**
708
+         * @suppress SqlInjectionChecker
709
+         */
710
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
711
+            $newValues = [];
712
+            foreach ($mutations as $propertyName => $propertyValue) {
713
+
714
+                switch ($propertyName) {
715
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
716
+                        $fieldName = 'transparent';
717
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
718
+                        break;
719
+                    default :
720
+                        $fieldName = $this->propertyMap[$propertyName];
721
+                        $newValues[$fieldName] = $propertyValue;
722
+                        break;
723
+                }
724
+
725
+            }
726
+            $query = $this->db->getQueryBuilder();
727
+            $query->update('calendars');
728
+            foreach ($newValues as $fieldName => $value) {
729
+                $query->set($fieldName, $query->createNamedParameter($value));
730
+            }
731
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
732
+            $query->execute();
733
+
734
+            $this->addChange($calendarId, "", 2);
735
+
736
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
737
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
738
+                [
739
+                    'calendarId' => $calendarId,
740
+                    'calendarData' => $this->getCalendarById($calendarId),
741
+                    'shares' => $this->getShares($calendarId),
742
+                    'propertyMutations' => $mutations,
743
+            ]));
744
+
745
+            return true;
746
+        });
747
+    }
748
+
749
+    /**
750
+     * Delete a calendar and all it's objects
751
+     *
752
+     * @param mixed $calendarId
753
+     * @return void
754
+     */
755
+    function deleteCalendar($calendarId) {
756
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
757
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
758
+            [
759
+                'calendarId' => $calendarId,
760
+                'calendarData' => $this->getCalendarById($calendarId),
761
+                'shares' => $this->getShares($calendarId),
762
+        ]));
763
+
764
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
765
+        $stmt->execute([$calendarId]);
766
+
767
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
768
+        $stmt->execute([$calendarId]);
769
+
770
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
771
+        $stmt->execute([$calendarId]);
772
+
773
+        $this->sharingBackend->deleteAllShares($calendarId);
774
+
775
+        $query = $this->db->getQueryBuilder();
776
+        $query->delete($this->dbObjectPropertiesTable)
777
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
778
+            ->execute();
779
+    }
780
+
781
+    /**
782
+     * Delete all of an user's shares
783
+     *
784
+     * @param string $principaluri
785
+     * @return void
786
+     */
787
+    function deleteAllSharesByUser($principaluri) {
788
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
789
+    }
790
+
791
+    /**
792
+     * Returns all calendar objects within a calendar.
793
+     *
794
+     * Every item contains an array with the following keys:
795
+     *   * calendardata - The iCalendar-compatible calendar data
796
+     *   * uri - a unique key which will be used to construct the uri. This can
797
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
798
+     *     good idea. This is only the basename, or filename, not the full
799
+     *     path.
800
+     *   * lastmodified - a timestamp of the last modification time
801
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
802
+     *   '"abcdef"')
803
+     *   * size - The size of the calendar objects, in bytes.
804
+     *   * component - optional, a string containing the type of object, such
805
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
806
+     *     the Content-Type header.
807
+     *
808
+     * Note that the etag is optional, but it's highly encouraged to return for
809
+     * speed reasons.
810
+     *
811
+     * The calendardata is also optional. If it's not returned
812
+     * 'getCalendarObject' will be called later, which *is* expected to return
813
+     * calendardata.
814
+     *
815
+     * If neither etag or size are specified, the calendardata will be
816
+     * used/fetched to determine these numbers. If both are specified the
817
+     * amount of times this is needed is reduced by a great degree.
818
+     *
819
+     * @param mixed $calendarId
820
+     * @return array
821
+     */
822
+    function getCalendarObjects($calendarId) {
823
+        $query = $this->db->getQueryBuilder();
824
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
825
+            ->from('calendarobjects')
826
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
827
+        $stmt = $query->execute();
828
+
829
+        $result = [];
830
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
831
+            $result[] = [
832
+                    'id'           => $row['id'],
833
+                    'uri'          => $row['uri'],
834
+                    'lastmodified' => $row['lastmodified'],
835
+                    'etag'         => '"' . $row['etag'] . '"',
836
+                    'calendarid'   => $row['calendarid'],
837
+                    'size'         => (int)$row['size'],
838
+                    'component'    => strtolower($row['componenttype']),
839
+                    'classification'=> (int)$row['classification']
840
+            ];
841
+        }
842
+
843
+        return $result;
844
+    }
845
+
846
+    /**
847
+     * Returns information from a single calendar object, based on it's object
848
+     * uri.
849
+     *
850
+     * The object uri is only the basename, or filename and not a full path.
851
+     *
852
+     * The returned array must have the same keys as getCalendarObjects. The
853
+     * 'calendardata' object is required here though, while it's not required
854
+     * for getCalendarObjects.
855
+     *
856
+     * This method must return null if the object did not exist.
857
+     *
858
+     * @param mixed $calendarId
859
+     * @param string $objectUri
860
+     * @return array|null
861
+     */
862
+    function getCalendarObject($calendarId, $objectUri) {
863
+
864
+        $query = $this->db->getQueryBuilder();
865
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
866
+                ->from('calendarobjects')
867
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
869
+        $stmt = $query->execute();
870
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
871
+
872
+        if(!$row) return null;
873
+
874
+        return [
875
+                'id'            => $row['id'],
876
+                'uri'           => $row['uri'],
877
+                'lastmodified'  => $row['lastmodified'],
878
+                'etag'          => '"' . $row['etag'] . '"',
879
+                'calendarid'    => $row['calendarid'],
880
+                'size'          => (int)$row['size'],
881
+                'calendardata'  => $this->readBlob($row['calendardata']),
882
+                'component'     => strtolower($row['componenttype']),
883
+                'classification'=> (int)$row['classification']
884
+        ];
885
+    }
886
+
887
+    /**
888
+     * Returns a list of calendar objects.
889
+     *
890
+     * This method should work identical to getCalendarObject, but instead
891
+     * return all the calendar objects in the list as an array.
892
+     *
893
+     * If the backend supports this, it may allow for some speed-ups.
894
+     *
895
+     * @param mixed $calendarId
896
+     * @param string[] $uris
897
+     * @return array
898
+     */
899
+    function getMultipleCalendarObjects($calendarId, array $uris) {
900
+        if (empty($uris)) {
901
+            return [];
902
+        }
903
+
904
+        $chunks = array_chunk($uris, 100);
905
+        $objects = [];
906
+
907
+        $query = $this->db->getQueryBuilder();
908
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
909
+            ->from('calendarobjects')
910
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
911
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
912
+
913
+        foreach ($chunks as $uris) {
914
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
915
+            $result = $query->execute();
916
+
917
+            while ($row = $result->fetch()) {
918
+                $objects[] = [
919
+                    'id'           => $row['id'],
920
+                    'uri'          => $row['uri'],
921
+                    'lastmodified' => $row['lastmodified'],
922
+                    'etag'         => '"' . $row['etag'] . '"',
923
+                    'calendarid'   => $row['calendarid'],
924
+                    'size'         => (int)$row['size'],
925
+                    'calendardata' => $this->readBlob($row['calendardata']),
926
+                    'component'    => strtolower($row['componenttype']),
927
+                    'classification' => (int)$row['classification']
928
+                ];
929
+            }
930
+            $result->closeCursor();
931
+        }
932
+        return $objects;
933
+    }
934
+
935
+    /**
936
+     * Creates a new calendar object.
937
+     *
938
+     * The object uri is only the basename, or filename and not a full path.
939
+     *
940
+     * It is possible return an etag from this function, which will be used in
941
+     * the response to this PUT request. Note that the ETag must be surrounded
942
+     * by double-quotes.
943
+     *
944
+     * However, you should only really return this ETag if you don't mangle the
945
+     * calendar-data. If the result of a subsequent GET to this object is not
946
+     * the exact same as this request body, you should omit the ETag.
947
+     *
948
+     * @param mixed $calendarId
949
+     * @param string $objectUri
950
+     * @param string $calendarData
951
+     * @return string
952
+     */
953
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
954
+        $extraData = $this->getDenormalizedData($calendarData);
955
+
956
+        $query = $this->db->getQueryBuilder();
957
+        $query->insert('calendarobjects')
958
+            ->values([
959
+                'calendarid' => $query->createNamedParameter($calendarId),
960
+                'uri' => $query->createNamedParameter($objectUri),
961
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
962
+                'lastmodified' => $query->createNamedParameter(time()),
963
+                'etag' => $query->createNamedParameter($extraData['etag']),
964
+                'size' => $query->createNamedParameter($extraData['size']),
965
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
966
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
967
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
968
+                'classification' => $query->createNamedParameter($extraData['classification']),
969
+                'uid' => $query->createNamedParameter($extraData['uid']),
970
+            ])
971
+            ->execute();
972
+
973
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
974
+
975
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
976
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
977
+            [
978
+                'calendarId' => $calendarId,
979
+                'calendarData' => $this->getCalendarById($calendarId),
980
+                'shares' => $this->getShares($calendarId),
981
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
982
+            ]
983
+        ));
984
+        $this->addChange($calendarId, $objectUri, 1);
985
+
986
+        return '"' . $extraData['etag'] . '"';
987
+    }
988
+
989
+    /**
990
+     * Updates an existing calendarobject, based on it's uri.
991
+     *
992
+     * The object uri is only the basename, or filename and not a full path.
993
+     *
994
+     * It is possible return an etag from this function, which will be used in
995
+     * the response to this PUT request. Note that the ETag must be surrounded
996
+     * by double-quotes.
997
+     *
998
+     * However, you should only really return this ETag if you don't mangle the
999
+     * calendar-data. If the result of a subsequent GET to this object is not
1000
+     * the exact same as this request body, you should omit the ETag.
1001
+     *
1002
+     * @param mixed $calendarId
1003
+     * @param string $objectUri
1004
+     * @param string $calendarData
1005
+     * @return string
1006
+     */
1007
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1008
+        $extraData = $this->getDenormalizedData($calendarData);
1009
+
1010
+        $query = $this->db->getQueryBuilder();
1011
+        $query->update('calendarobjects')
1012
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1013
+                ->set('lastmodified', $query->createNamedParameter(time()))
1014
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1015
+                ->set('size', $query->createNamedParameter($extraData['size']))
1016
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1017
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1018
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1019
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1020
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1021
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1022
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1023
+            ->execute();
1024
+
1025
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1026
+
1027
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1028
+        if (is_array($data)) {
1029
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1030
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1031
+                [
1032
+                    'calendarId' => $calendarId,
1033
+                    'calendarData' => $this->getCalendarById($calendarId),
1034
+                    'shares' => $this->getShares($calendarId),
1035
+                    'objectData' => $data,
1036
+                ]
1037
+            ));
1038
+        }
1039
+        $this->addChange($calendarId, $objectUri, 2);
1040
+
1041
+        return '"' . $extraData['etag'] . '"';
1042
+    }
1043
+
1044
+    /**
1045
+     * @param int $calendarObjectId
1046
+     * @param int $classification
1047
+     */
1048
+    public function setClassification($calendarObjectId, $classification) {
1049
+        if (!in_array($classification, [
1050
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1051
+        ])) {
1052
+            throw new \InvalidArgumentException();
1053
+        }
1054
+        $query = $this->db->getQueryBuilder();
1055
+        $query->update('calendarobjects')
1056
+            ->set('classification', $query->createNamedParameter($classification))
1057
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1058
+            ->execute();
1059
+    }
1060
+
1061
+    /**
1062
+     * Deletes an existing calendar object.
1063
+     *
1064
+     * The object uri is only the basename, or filename and not a full path.
1065
+     *
1066
+     * @param mixed $calendarId
1067
+     * @param string $objectUri
1068
+     * @return void
1069
+     */
1070
+    function deleteCalendarObject($calendarId, $objectUri) {
1071
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1072
+        if (is_array($data)) {
1073
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1074
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1075
+                [
1076
+                    'calendarId' => $calendarId,
1077
+                    'calendarData' => $this->getCalendarById($calendarId),
1078
+                    'shares' => $this->getShares($calendarId),
1079
+                    'objectData' => $data,
1080
+                ]
1081
+            ));
1082
+        }
1083
+
1084
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1085
+        $stmt->execute([$calendarId, $objectUri]);
1086
+
1087
+        $this->purgeProperties($calendarId, $data['id']);
1088
+
1089
+        $this->addChange($calendarId, $objectUri, 3);
1090
+    }
1091
+
1092
+    /**
1093
+     * Performs a calendar-query on the contents of this calendar.
1094
+     *
1095
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1096
+     * calendar-query it is possible for a client to request a specific set of
1097
+     * object, based on contents of iCalendar properties, date-ranges and
1098
+     * iCalendar component types (VTODO, VEVENT).
1099
+     *
1100
+     * This method should just return a list of (relative) urls that match this
1101
+     * query.
1102
+     *
1103
+     * The list of filters are specified as an array. The exact array is
1104
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1105
+     *
1106
+     * Note that it is extremely likely that getCalendarObject for every path
1107
+     * returned from this method will be called almost immediately after. You
1108
+     * may want to anticipate this to speed up these requests.
1109
+     *
1110
+     * This method provides a default implementation, which parses *all* the
1111
+     * iCalendar objects in the specified calendar.
1112
+     *
1113
+     * This default may well be good enough for personal use, and calendars
1114
+     * that aren't very large. But if you anticipate high usage, big calendars
1115
+     * or high loads, you are strongly advised to optimize certain paths.
1116
+     *
1117
+     * The best way to do so is override this method and to optimize
1118
+     * specifically for 'common filters'.
1119
+     *
1120
+     * Requests that are extremely common are:
1121
+     *   * requests for just VEVENTS
1122
+     *   * requests for just VTODO
1123
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1124
+     *
1125
+     * ..and combinations of these requests. It may not be worth it to try to
1126
+     * handle every possible situation and just rely on the (relatively
1127
+     * easy to use) CalendarQueryValidator to handle the rest.
1128
+     *
1129
+     * Note that especially time-range-filters may be difficult to parse. A
1130
+     * time-range filter specified on a VEVENT must for instance also handle
1131
+     * recurrence rules correctly.
1132
+     * A good example of how to interprete all these filters can also simply
1133
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1134
+     * as possible, so it gives you a good idea on what type of stuff you need
1135
+     * to think of.
1136
+     *
1137
+     * @param mixed $calendarId
1138
+     * @param array $filters
1139
+     * @return array
1140
+     */
1141
+    function calendarQuery($calendarId, array $filters) {
1142
+        $componentType = null;
1143
+        $requirePostFilter = true;
1144
+        $timeRange = null;
1145
+
1146
+        // if no filters were specified, we don't need to filter after a query
1147
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1148
+            $requirePostFilter = false;
1149
+        }
1150
+
1151
+        // Figuring out if there's a component filter
1152
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1153
+            $componentType = $filters['comp-filters'][0]['name'];
1154
+
1155
+            // Checking if we need post-filters
1156
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1157
+                $requirePostFilter = false;
1158
+            }
1159
+            // There was a time-range filter
1160
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1161
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1162
+
1163
+                // If start time OR the end time is not specified, we can do a
1164
+                // 100% accurate mysql query.
1165
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1166
+                    $requirePostFilter = false;
1167
+                }
1168
+            }
1169
+
1170
+        }
1171
+        $columns = ['uri'];
1172
+        if ($requirePostFilter) {
1173
+            $columns = ['uri', 'calendardata'];
1174
+        }
1175
+        $query = $this->db->getQueryBuilder();
1176
+        $query->select($columns)
1177
+            ->from('calendarobjects')
1178
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1179
+
1180
+        if ($componentType) {
1181
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1182
+        }
1183
+
1184
+        if ($timeRange && $timeRange['start']) {
1185
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1186
+        }
1187
+        if ($timeRange && $timeRange['end']) {
1188
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1189
+        }
1190
+
1191
+        $stmt = $query->execute();
1192
+
1193
+        $result = [];
1194
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1195
+            if ($requirePostFilter) {
1196
+                if (!$this->validateFilterForObject($row, $filters)) {
1197
+                    continue;
1198
+                }
1199
+            }
1200
+            $result[] = $row['uri'];
1201
+        }
1202
+
1203
+        return $result;
1204
+    }
1205
+
1206
+    /**
1207
+     * custom Nextcloud search extension for CalDAV
1208
+     *
1209
+     * @param string $principalUri
1210
+     * @param array $filters
1211
+     * @param integer|null $limit
1212
+     * @param integer|null $offset
1213
+     * @return array
1214
+     */
1215
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1216
+        $calendars = $this->getCalendarsForUser($principalUri);
1217
+        $ownCalendars = [];
1218
+        $sharedCalendars = [];
1219
+
1220
+        $uriMapper = [];
1221
+
1222
+        foreach($calendars as $calendar) {
1223
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1224
+                $ownCalendars[] = $calendar['id'];
1225
+            } else {
1226
+                $sharedCalendars[] = $calendar['id'];
1227
+            }
1228
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1229
+        }
1230
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1231
+            return [];
1232
+        }
1233
+
1234
+        $query = $this->db->getQueryBuilder();
1235
+        // Calendar id expressions
1236
+        $calendarExpressions = [];
1237
+        foreach($ownCalendars as $id) {
1238
+            $calendarExpressions[] = $query->expr()
1239
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1240
+        }
1241
+        foreach($sharedCalendars as $id) {
1242
+            $calendarExpressions[] = $query->expr()->andX(
1243
+                $query->expr()->eq('c.calendarid',
1244
+                    $query->createNamedParameter($id)),
1245
+                $query->expr()->eq('c.classification',
1246
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1247
+            );
1248
+        }
1249
+
1250
+        if (count($calendarExpressions) === 1) {
1251
+            $calExpr = $calendarExpressions[0];
1252
+        } else {
1253
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1254
+        }
1255
+
1256
+        // Component expressions
1257
+        $compExpressions = [];
1258
+        foreach($filters['comps'] as $comp) {
1259
+            $compExpressions[] = $query->expr()
1260
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1261
+        }
1262
+
1263
+        if (count($compExpressions) === 1) {
1264
+            $compExpr = $compExpressions[0];
1265
+        } else {
1266
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1267
+        }
1268
+
1269
+        if (!isset($filters['props'])) {
1270
+            $filters['props'] = [];
1271
+        }
1272
+        if (!isset($filters['params'])) {
1273
+            $filters['params'] = [];
1274
+        }
1275
+
1276
+        $propParamExpressions = [];
1277
+        foreach($filters['props'] as $prop) {
1278
+            $propParamExpressions[] = $query->expr()->andX(
1279
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1280
+                $query->expr()->isNull('i.parameter')
1281
+            );
1282
+        }
1283
+        foreach($filters['params'] as $param) {
1284
+            $propParamExpressions[] = $query->expr()->andX(
1285
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1286
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1287
+            );
1288
+        }
1289
+
1290
+        if (count($propParamExpressions) === 1) {
1291
+            $propParamExpr = $propParamExpressions[0];
1292
+        } else {
1293
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1294
+        }
1295
+
1296
+        $query->select(['c.calendarid', 'c.uri'])
1297
+            ->from($this->dbObjectPropertiesTable, 'i')
1298
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1299
+            ->where($calExpr)
1300
+            ->andWhere($compExpr)
1301
+            ->andWhere($propParamExpr)
1302
+            ->andWhere($query->expr()->iLike('i.value',
1303
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1304
+
1305
+        if ($offset) {
1306
+            $query->setFirstResult($offset);
1307
+        }
1308
+        if ($limit) {
1309
+            $query->setMaxResults($limit);
1310
+        }
1311
+
1312
+        $stmt = $query->execute();
1313
+
1314
+        $result = [];
1315
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1316
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1317
+            if (!in_array($path, $result)) {
1318
+                $result[] = $path;
1319
+            }
1320
+        }
1321
+
1322
+        return $result;
1323
+    }
1324
+
1325
+    /**
1326
+     * Searches through all of a users calendars and calendar objects to find
1327
+     * an object with a specific UID.
1328
+     *
1329
+     * This method should return the path to this object, relative to the
1330
+     * calendar home, so this path usually only contains two parts:
1331
+     *
1332
+     * calendarpath/objectpath.ics
1333
+     *
1334
+     * If the uid is not found, return null.
1335
+     *
1336
+     * This method should only consider * objects that the principal owns, so
1337
+     * any calendars owned by other principals that also appear in this
1338
+     * collection should be ignored.
1339
+     *
1340
+     * @param string $principalUri
1341
+     * @param string $uid
1342
+     * @return string|null
1343
+     */
1344
+    function getCalendarObjectByUID($principalUri, $uid) {
1345
+
1346
+        $query = $this->db->getQueryBuilder();
1347
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1348
+            ->from('calendarobjects', 'co')
1349
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1350
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1351
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1352
+
1353
+        $stmt = $query->execute();
1354
+
1355
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1357
+        }
1358
+
1359
+        return null;
1360
+    }
1361
+
1362
+    /**
1363
+     * The getChanges method returns all the changes that have happened, since
1364
+     * the specified syncToken in the specified calendar.
1365
+     *
1366
+     * This function should return an array, such as the following:
1367
+     *
1368
+     * [
1369
+     *   'syncToken' => 'The current synctoken',
1370
+     *   'added'   => [
1371
+     *      'new.txt',
1372
+     *   ],
1373
+     *   'modified'   => [
1374
+     *      'modified.txt',
1375
+     *   ],
1376
+     *   'deleted' => [
1377
+     *      'foo.php.bak',
1378
+     *      'old.txt'
1379
+     *   ]
1380
+     * );
1381
+     *
1382
+     * The returned syncToken property should reflect the *current* syncToken
1383
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1384
+     * property This is * needed here too, to ensure the operation is atomic.
1385
+     *
1386
+     * If the $syncToken argument is specified as null, this is an initial
1387
+     * sync, and all members should be reported.
1388
+     *
1389
+     * The modified property is an array of nodenames that have changed since
1390
+     * the last token.
1391
+     *
1392
+     * The deleted property is an array with nodenames, that have been deleted
1393
+     * from collection.
1394
+     *
1395
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1396
+     * 1, you only have to report changes that happened only directly in
1397
+     * immediate descendants. If it's 2, it should also include changes from
1398
+     * the nodes below the child collections. (grandchildren)
1399
+     *
1400
+     * The $limit argument allows a client to specify how many results should
1401
+     * be returned at most. If the limit is not specified, it should be treated
1402
+     * as infinite.
1403
+     *
1404
+     * If the limit (infinite or not) is higher than you're willing to return,
1405
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1406
+     *
1407
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1408
+     * return null.
1409
+     *
1410
+     * The limit is 'suggestive'. You are free to ignore it.
1411
+     *
1412
+     * @param string $calendarId
1413
+     * @param string $syncToken
1414
+     * @param int $syncLevel
1415
+     * @param int $limit
1416
+     * @return array
1417
+     */
1418
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1419
+        // Current synctoken
1420
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1421
+        $stmt->execute([ $calendarId ]);
1422
+        $currentToken = $stmt->fetchColumn(0);
1423
+
1424
+        if (is_null($currentToken)) {
1425
+            return null;
1426
+        }
1427
+
1428
+        $result = [
1429
+            'syncToken' => $currentToken,
1430
+            'added'     => [],
1431
+            'modified'  => [],
1432
+            'deleted'   => [],
1433
+        ];
1434
+
1435
+        if ($syncToken) {
1436
+
1437
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1438
+            if ($limit>0) {
1439
+                $query.= " `LIMIT` " . (int)$limit;
1440
+            }
1441
+
1442
+            // Fetching all changes
1443
+            $stmt = $this->db->prepare($query);
1444
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1445
+
1446
+            $changes = [];
1447
+
1448
+            // This loop ensures that any duplicates are overwritten, only the
1449
+            // last change on a node is relevant.
1450
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1451
+
1452
+                $changes[$row['uri']] = $row['operation'];
1453
+
1454
+            }
1455
+
1456
+            foreach($changes as $uri => $operation) {
1457
+
1458
+                switch($operation) {
1459
+                    case 1 :
1460
+                        $result['added'][] = $uri;
1461
+                        break;
1462
+                    case 2 :
1463
+                        $result['modified'][] = $uri;
1464
+                        break;
1465
+                    case 3 :
1466
+                        $result['deleted'][] = $uri;
1467
+                        break;
1468
+                }
1469
+
1470
+            }
1471
+        } else {
1472
+            // No synctoken supplied, this is the initial sync.
1473
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1474
+            $stmt = $this->db->prepare($query);
1475
+            $stmt->execute([$calendarId]);
1476
+
1477
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1478
+        }
1479
+        return $result;
1480
+
1481
+    }
1482
+
1483
+    /**
1484
+     * Returns a list of subscriptions for a principal.
1485
+     *
1486
+     * Every subscription is an array with the following keys:
1487
+     *  * id, a unique id that will be used by other functions to modify the
1488
+     *    subscription. This can be the same as the uri or a database key.
1489
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1490
+     *  * principaluri. The owner of the subscription. Almost always the same as
1491
+     *    principalUri passed to this method.
1492
+     *
1493
+     * Furthermore, all the subscription info must be returned too:
1494
+     *
1495
+     * 1. {DAV:}displayname
1496
+     * 2. {http://apple.com/ns/ical/}refreshrate
1497
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1498
+     *    should not be stripped).
1499
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1500
+     *    should not be stripped).
1501
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1502
+     *    attachments should not be stripped).
1503
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1504
+     *     Sabre\DAV\Property\Href).
1505
+     * 7. {http://apple.com/ns/ical/}calendar-color
1506
+     * 8. {http://apple.com/ns/ical/}calendar-order
1507
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1508
+     *    (should just be an instance of
1509
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1510
+     *    default components).
1511
+     *
1512
+     * @param string $principalUri
1513
+     * @return array
1514
+     */
1515
+    function getSubscriptionsForUser($principalUri) {
1516
+        $fields = array_values($this->subscriptionPropertyMap);
1517
+        $fields[] = 'id';
1518
+        $fields[] = 'uri';
1519
+        $fields[] = 'source';
1520
+        $fields[] = 'principaluri';
1521
+        $fields[] = 'lastmodified';
1522
+
1523
+        $query = $this->db->getQueryBuilder();
1524
+        $query->select($fields)
1525
+            ->from('calendarsubscriptions')
1526
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1527
+            ->orderBy('calendarorder', 'asc');
1528
+        $stmt =$query->execute();
1529
+
1530
+        $subscriptions = [];
1531
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1532
+
1533
+            $subscription = [
1534
+                'id'           => $row['id'],
1535
+                'uri'          => $row['uri'],
1536
+                'principaluri' => $row['principaluri'],
1537
+                'source'       => $row['source'],
1538
+                'lastmodified' => $row['lastmodified'],
1539
+
1540
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1541
+            ];
1542
+
1543
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1544
+                if (!is_null($row[$dbName])) {
1545
+                    $subscription[$xmlName] = $row[$dbName];
1546
+                }
1547
+            }
1548
+
1549
+            $subscriptions[] = $subscription;
1550
+
1551
+        }
1552
+
1553
+        return $subscriptions;
1554
+    }
1555
+
1556
+    /**
1557
+     * Creates a new subscription for a principal.
1558
+     *
1559
+     * If the creation was a success, an id must be returned that can be used to reference
1560
+     * this subscription in other methods, such as updateSubscription.
1561
+     *
1562
+     * @param string $principalUri
1563
+     * @param string $uri
1564
+     * @param array $properties
1565
+     * @return mixed
1566
+     */
1567
+    function createSubscription($principalUri, $uri, array $properties) {
1568
+
1569
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1570
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1571
+        }
1572
+
1573
+        $values = [
1574
+            'principaluri' => $principalUri,
1575
+            'uri'          => $uri,
1576
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1577
+            'lastmodified' => time(),
1578
+        ];
1579
+
1580
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1581
+
1582
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1583
+            if (array_key_exists($xmlName, $properties)) {
1584
+                    $values[$dbName] = $properties[$xmlName];
1585
+                    if (in_array($dbName, $propertiesBoolean)) {
1586
+                        $values[$dbName] = true;
1587
+                }
1588
+            }
1589
+        }
1590
+
1591
+        $valuesToInsert = array();
1592
+
1593
+        $query = $this->db->getQueryBuilder();
1594
+
1595
+        foreach (array_keys($values) as $name) {
1596
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1597
+        }
1598
+
1599
+        $query->insert('calendarsubscriptions')
1600
+            ->values($valuesToInsert)
1601
+            ->execute();
1602
+
1603
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1604
+    }
1605
+
1606
+    /**
1607
+     * Updates a subscription
1608
+     *
1609
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1610
+     * To do the actual updates, you must tell this object which properties
1611
+     * you're going to process with the handle() method.
1612
+     *
1613
+     * Calling the handle method is like telling the PropPatch object "I
1614
+     * promise I can handle updating this property".
1615
+     *
1616
+     * Read the PropPatch documentation for more info and examples.
1617
+     *
1618
+     * @param mixed $subscriptionId
1619
+     * @param PropPatch $propPatch
1620
+     * @return void
1621
+     */
1622
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1623
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1624
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1625
+
1626
+        /**
1627
+         * @suppress SqlInjectionChecker
1628
+         */
1629
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1630
+
1631
+            $newValues = [];
1632
+
1633
+            foreach($mutations as $propertyName=>$propertyValue) {
1634
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1635
+                    $newValues['source'] = $propertyValue->getHref();
1636
+                } else {
1637
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1638
+                    $newValues[$fieldName] = $propertyValue;
1639
+                }
1640
+            }
1641
+
1642
+            $query = $this->db->getQueryBuilder();
1643
+            $query->update('calendarsubscriptions')
1644
+                ->set('lastmodified', $query->createNamedParameter(time()));
1645
+            foreach($newValues as $fieldName=>$value) {
1646
+                $query->set($fieldName, $query->createNamedParameter($value));
1647
+            }
1648
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1649
+                ->execute();
1650
+
1651
+            return true;
1652
+
1653
+        });
1654
+    }
1655
+
1656
+    /**
1657
+     * Deletes a subscription.
1658
+     *
1659
+     * @param mixed $subscriptionId
1660
+     * @return void
1661
+     */
1662
+    function deleteSubscription($subscriptionId) {
1663
+        $query = $this->db->getQueryBuilder();
1664
+        $query->delete('calendarsubscriptions')
1665
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1666
+            ->execute();
1667
+    }
1668
+
1669
+    /**
1670
+     * Returns a single scheduling object for the inbox collection.
1671
+     *
1672
+     * The returned array should contain the following elements:
1673
+     *   * uri - A unique basename for the object. This will be used to
1674
+     *           construct a full uri.
1675
+     *   * calendardata - The iCalendar object
1676
+     *   * lastmodified - The last modification date. Can be an int for a unix
1677
+     *                    timestamp, or a PHP DateTime object.
1678
+     *   * etag - A unique token that must change if the object changed.
1679
+     *   * size - The size of the object, in bytes.
1680
+     *
1681
+     * @param string $principalUri
1682
+     * @param string $objectUri
1683
+     * @return array
1684
+     */
1685
+    function getSchedulingObject($principalUri, $objectUri) {
1686
+        $query = $this->db->getQueryBuilder();
1687
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1688
+            ->from('schedulingobjects')
1689
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1690
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1691
+            ->execute();
1692
+
1693
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1694
+
1695
+        if(!$row) {
1696
+            return null;
1697
+        }
1698
+
1699
+        return [
1700
+                'uri'          => $row['uri'],
1701
+                'calendardata' => $row['calendardata'],
1702
+                'lastmodified' => $row['lastmodified'],
1703
+                'etag'         => '"' . $row['etag'] . '"',
1704
+                'size'         => (int)$row['size'],
1705
+        ];
1706
+    }
1707
+
1708
+    /**
1709
+     * Returns all scheduling objects for the inbox collection.
1710
+     *
1711
+     * These objects should be returned as an array. Every item in the array
1712
+     * should follow the same structure as returned from getSchedulingObject.
1713
+     *
1714
+     * The main difference is that 'calendardata' is optional.
1715
+     *
1716
+     * @param string $principalUri
1717
+     * @return array
1718
+     */
1719
+    function getSchedulingObjects($principalUri) {
1720
+        $query = $this->db->getQueryBuilder();
1721
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1722
+                ->from('schedulingobjects')
1723
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1724
+                ->execute();
1725
+
1726
+        $result = [];
1727
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1728
+            $result[] = [
1729
+                    'calendardata' => $row['calendardata'],
1730
+                    'uri'          => $row['uri'],
1731
+                    'lastmodified' => $row['lastmodified'],
1732
+                    'etag'         => '"' . $row['etag'] . '"',
1733
+                    'size'         => (int)$row['size'],
1734
+            ];
1735
+        }
1736
+
1737
+        return $result;
1738
+    }
1739
+
1740
+    /**
1741
+     * Deletes a scheduling object from the inbox collection.
1742
+     *
1743
+     * @param string $principalUri
1744
+     * @param string $objectUri
1745
+     * @return void
1746
+     */
1747
+    function deleteSchedulingObject($principalUri, $objectUri) {
1748
+        $query = $this->db->getQueryBuilder();
1749
+        $query->delete('schedulingobjects')
1750
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1751
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1752
+                ->execute();
1753
+    }
1754
+
1755
+    /**
1756
+     * Creates a new scheduling object. This should land in a users' inbox.
1757
+     *
1758
+     * @param string $principalUri
1759
+     * @param string $objectUri
1760
+     * @param string $objectData
1761
+     * @return void
1762
+     */
1763
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1764
+        $query = $this->db->getQueryBuilder();
1765
+        $query->insert('schedulingobjects')
1766
+            ->values([
1767
+                'principaluri' => $query->createNamedParameter($principalUri),
1768
+                'calendardata' => $query->createNamedParameter($objectData),
1769
+                'uri' => $query->createNamedParameter($objectUri),
1770
+                'lastmodified' => $query->createNamedParameter(time()),
1771
+                'etag' => $query->createNamedParameter(md5($objectData)),
1772
+                'size' => $query->createNamedParameter(strlen($objectData))
1773
+            ])
1774
+            ->execute();
1775
+    }
1776
+
1777
+    /**
1778
+     * Adds a change record to the calendarchanges table.
1779
+     *
1780
+     * @param mixed $calendarId
1781
+     * @param string $objectUri
1782
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1783
+     * @return void
1784
+     */
1785
+    protected function addChange($calendarId, $objectUri, $operation) {
1786
+
1787
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1788
+        $stmt->execute([
1789
+            $objectUri,
1790
+            $calendarId,
1791
+            $operation,
1792
+            $calendarId
1793
+        ]);
1794
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1795
+        $stmt->execute([
1796
+            $calendarId
1797
+        ]);
1798
+
1799
+    }
1800
+
1801
+    /**
1802
+     * Parses some information from calendar objects, used for optimized
1803
+     * calendar-queries.
1804
+     *
1805
+     * Returns an array with the following keys:
1806
+     *   * etag - An md5 checksum of the object without the quotes.
1807
+     *   * size - Size of the object in bytes
1808
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1809
+     *   * firstOccurence
1810
+     *   * lastOccurence
1811
+     *   * uid - value of the UID property
1812
+     *
1813
+     * @param string $calendarData
1814
+     * @return array
1815
+     */
1816
+    public function getDenormalizedData($calendarData) {
1817
+
1818
+        $vObject = Reader::read($calendarData);
1819
+        $componentType = null;
1820
+        $component = null;
1821
+        $firstOccurrence = null;
1822
+        $lastOccurrence = null;
1823
+        $uid = null;
1824
+        $classification = self::CLASSIFICATION_PUBLIC;
1825
+        foreach($vObject->getComponents() as $component) {
1826
+            if ($component->name!=='VTIMEZONE') {
1827
+                $componentType = $component->name;
1828
+                $uid = (string)$component->UID;
1829
+                break;
1830
+            }
1831
+        }
1832
+        if (!$componentType) {
1833
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1834
+        }
1835
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1836
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1837
+            // Finding the last occurrence is a bit harder
1838
+            if (!isset($component->RRULE)) {
1839
+                if (isset($component->DTEND)) {
1840
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1841
+                } elseif (isset($component->DURATION)) {
1842
+                    $endDate = clone $component->DTSTART->getDateTime();
1843
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1844
+                    $lastOccurrence = $endDate->getTimeStamp();
1845
+                } elseif (!$component->DTSTART->hasTime()) {
1846
+                    $endDate = clone $component->DTSTART->getDateTime();
1847
+                    $endDate->modify('+1 day');
1848
+                    $lastOccurrence = $endDate->getTimeStamp();
1849
+                } else {
1850
+                    $lastOccurrence = $firstOccurrence;
1851
+                }
1852
+            } else {
1853
+                $it = new EventIterator($vObject, (string)$component->UID);
1854
+                $maxDate = new \DateTime(self::MAX_DATE);
1855
+                if ($it->isInfinite()) {
1856
+                    $lastOccurrence = $maxDate->getTimestamp();
1857
+                } else {
1858
+                    $end = $it->getDtEnd();
1859
+                    while($it->valid() && $end < $maxDate) {
1860
+                        $end = $it->getDtEnd();
1861
+                        $it->next();
1862
+
1863
+                    }
1864
+                    $lastOccurrence = $end->getTimestamp();
1865
+                }
1866
+
1867
+            }
1868
+        }
1869
+
1870
+        if ($component->CLASS) {
1871
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1872
+            switch ($component->CLASS->getValue()) {
1873
+                case 'PUBLIC':
1874
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1875
+                    break;
1876
+                case 'CONFIDENTIAL':
1877
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1878
+                    break;
1879
+            }
1880
+        }
1881
+        return [
1882
+            'etag' => md5($calendarData),
1883
+            'size' => strlen($calendarData),
1884
+            'componentType' => $componentType,
1885
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1886
+            'lastOccurence'  => $lastOccurrence,
1887
+            'uid' => $uid,
1888
+            'classification' => $classification
1889
+        ];
1890
+
1891
+    }
1892
+
1893
+    private function readBlob($cardData) {
1894
+        if (is_resource($cardData)) {
1895
+            return stream_get_contents($cardData);
1896
+        }
1897
+
1898
+        return $cardData;
1899
+    }
1900
+
1901
+    /**
1902
+     * @param IShareable $shareable
1903
+     * @param array $add
1904
+     * @param array $remove
1905
+     */
1906
+    public function updateShares($shareable, $add, $remove) {
1907
+        $calendarId = $shareable->getResourceId();
1908
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1909
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1910
+            [
1911
+                'calendarId' => $calendarId,
1912
+                'calendarData' => $this->getCalendarById($calendarId),
1913
+                'shares' => $this->getShares($calendarId),
1914
+                'add' => $add,
1915
+                'remove' => $remove,
1916
+            ]));
1917
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1918
+    }
1919
+
1920
+    /**
1921
+     * @param int $resourceId
1922
+     * @return array
1923
+     */
1924
+    public function getShares($resourceId) {
1925
+        return $this->sharingBackend->getShares($resourceId);
1926
+    }
1927
+
1928
+    /**
1929
+     * @param boolean $value
1930
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1931
+     * @return string|null
1932
+     */
1933
+    public function setPublishStatus($value, $calendar) {
1934
+        $query = $this->db->getQueryBuilder();
1935
+        if ($value) {
1936
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
1937
+            $query->insert('dav_shares')
1938
+                ->values([
1939
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1940
+                    'type' => $query->createNamedParameter('calendar'),
1941
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1942
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1943
+                    'publicuri' => $query->createNamedParameter($publicUri)
1944
+                ]);
1945
+            $query->execute();
1946
+            return $publicUri;
1947
+        }
1948
+        $query->delete('dav_shares')
1949
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1950
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1951
+        $query->execute();
1952
+        return null;
1953
+    }
1954
+
1955
+    /**
1956
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1957
+     * @return mixed
1958
+     */
1959
+    public function getPublishStatus($calendar) {
1960
+        $query = $this->db->getQueryBuilder();
1961
+        $result = $query->select('publicuri')
1962
+            ->from('dav_shares')
1963
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1964
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1965
+            ->execute();
1966
+
1967
+        $row = $result->fetch();
1968
+        $result->closeCursor();
1969
+        return $row ? reset($row) : false;
1970
+    }
1971
+
1972
+    /**
1973
+     * @param int $resourceId
1974
+     * @param array $acl
1975
+     * @return array
1976
+     */
1977
+    public function applyShareAcl($resourceId, $acl) {
1978
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1979
+    }
1980
+
1981
+
1982
+
1983
+    /**
1984
+     * update properties table
1985
+     *
1986
+     * @param int $calendarId
1987
+     * @param string $objectUri
1988
+     * @param string $calendarData
1989
+     */
1990
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
1991
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
1992
+
1993
+        try {
1994
+            $vCalendar = $this->readCalendarData($calendarData);
1995
+        } catch (\Exception $ex) {
1996
+            return;
1997
+        }
1998
+
1999
+        $this->purgeProperties($calendarId, $objectId);
2000
+
2001
+        $query = $this->db->getQueryBuilder();
2002
+        $query->insert($this->dbObjectPropertiesTable)
2003
+            ->values(
2004
+                [
2005
+                    'calendarid' => $query->createNamedParameter($calendarId),
2006
+                    'objectid' => $query->createNamedParameter($objectId),
2007
+                    'name' => $query->createParameter('name'),
2008
+                    'parameter' => $query->createParameter('parameter'),
2009
+                    'value' => $query->createParameter('value'),
2010
+                ]
2011
+            );
2012
+
2013
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2014
+        foreach ($vCalendar->getComponents() as $component) {
2015
+            if (!in_array($component->name, $indexComponents)) {
2016
+                continue;
2017
+            }
2018
+
2019
+            foreach ($component->children() as $property) {
2020
+                if (in_array($property->name, self::$indexProperties)) {
2021
+                    $value = $property->getValue();
2022
+                    // is this a shitty db?
2023
+                    if (!$this->db->supports4ByteText()) {
2024
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2025
+                    }
2026
+                    $value = substr($value, 0, 254);
2027
+
2028
+                    $query->setParameter('name', $property->name);
2029
+                    $query->setParameter('parameter', null);
2030
+                    $query->setParameter('value', $value);
2031
+                    $query->execute();
2032
+                }
2033
+
2034
+                if (in_array($property->name, array_keys(self::$indexParameters))) {
2035
+                    $parameters = $property->parameters();
2036
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2037
+
2038
+                    foreach ($parameters as $key => $value) {
2039
+                        if (in_array($key, $indexedParametersForProperty)) {
2040
+                            // is this a shitty db?
2041
+                            if ($this->db->supports4ByteText()) {
2042
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2043
+                            }
2044
+                            $value = substr($value, 0, 254);
2045
+
2046
+                            $query->setParameter('name', $property->name);
2047
+                            $query->setParameter('parameter', substr($key, 0, 254));
2048
+                            $query->setParameter('value', substr($value, 0, 254));
2049
+                            $query->execute();
2050
+                        }
2051
+                    }
2052
+                }
2053
+            }
2054
+        }
2055
+    }
2056
+
2057
+    /**
2058
+     * Move a calendar from one user to another
2059
+     *
2060
+     * @param $uri
2061
+     * @param $userOrigin
2062
+     * @param $userDestination
2063
+     */
2064
+    public function moveCalendar($uri, $userOrigin, $userDestination)
2065
+    {
2066
+        $query = $this->db->getQueryBuilder();
2067
+        $query->update('calendars')
2068
+            ->set('principaluri', 'principals/users/' . $userDestination)
2069
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter('principals/users/'. $userOrigin)))
2070
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2071
+            ->execute();
2072
+    }
2073
+
2074
+    /**
2075
+     * read VCalendar data into a VCalendar object
2076
+     *
2077
+     * @param string $objectData
2078
+     * @return VCalendar
2079
+     */
2080
+    protected function readCalendarData($objectData) {
2081
+        return Reader::read($objectData);
2082
+    }
2083
+
2084
+    /**
2085
+     * delete all properties from a given calendar object
2086
+     *
2087
+     * @param int $calendarId
2088
+     * @param int $objectId
2089
+     */
2090
+    protected function purgeProperties($calendarId, $objectId) {
2091
+        $query = $this->db->getQueryBuilder();
2092
+        $query->delete($this->dbObjectPropertiesTable)
2093
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2094
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2095
+        $query->execute();
2096
+    }
2097
+
2098
+    /**
2099
+     * get ID from a given calendar object
2100
+     *
2101
+     * @param int $calendarId
2102
+     * @param string $uri
2103
+     * @return int
2104
+     */
2105
+    protected function getCalendarObjectId($calendarId, $uri) {
2106
+        $query = $this->db->getQueryBuilder();
2107
+        $query->select('id')->from('calendarobjects')
2108
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2109
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2110
+
2111
+        $result = $query->execute();
2112
+        $objectIds = $result->fetch();
2113
+        $result->closeCursor();
2114
+
2115
+        if (!isset($objectIds['id'])) {
2116
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2117
+        }
2118
+
2119
+        return (int)$objectIds['id'];
2120
+    }
2121
+
2122
+    private function convertPrincipal($principalUri, $toV2) {
2123
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2124
+            list(, $name) = URLUtil::splitPath($principalUri);
2125
+            if ($toV2 === true) {
2126
+                return "principals/users/$name";
2127
+            }
2128
+            return "principals/$name";
2129
+        }
2130
+        return $principalUri;
2131
+    }
2132
+
2133
+    private function addOwnerPrincipal(&$calendarInfo) {
2134
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2135
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2136
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2137
+            $uri = $calendarInfo[$ownerPrincipalKey];
2138
+        } else {
2139
+            $uri = $calendarInfo['principaluri'];
2140
+        }
2141
+
2142
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2143
+        if (isset($principalInformation['{DAV:}displayname'])) {
2144
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2145
+        }
2146
+    }
2147 2147
 }
Please login to merge, or discard this patch.
Spacing   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197 197
 		}
198 198
 
199
-		return (int)$query->execute()->fetchColumn();
199
+		return (int) $query->execute()->fetchColumn();
200 200
 	}
201 201
 
202 202
 	/**
@@ -243,25 +243,25 @@  discard block
 block discarded – undo
243 243
 		$stmt = $query->execute();
244 244
 
245 245
 		$calendars = [];
246
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
246
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247 247
 
248 248
 			$components = [];
249 249
 			if ($row['components']) {
250
-				$components = explode(',',$row['components']);
250
+				$components = explode(',', $row['components']);
251 251
 			}
252 252
 
253 253
 			$calendar = [
254 254
 				'id' => $row['id'],
255 255
 				'uri' => $row['uri'],
256 256
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
257
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
258
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
259
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
261
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262 262
 			];
263 263
 
264
-			foreach($this->propertyMap as $xmlName=>$dbName) {
264
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
265 265
 				$calendar[$xmlName] = $row[$dbName];
266 266
 			}
267 267
 
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		$principals = array_map(function($principal) {
280 280
 			return urldecode($principal);
281 281
 		}, $principals);
282
-		$principals[]= $principalUri;
282
+		$principals[] = $principalUri;
283 283
 
284 284
 		$fields = array_values($this->propertyMap);
285 285
 		$fields[] = 'a.id';
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300 300
 			->execute();
301 301
 
302
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
-		while($row = $result->fetch()) {
302
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
303
+		while ($row = $result->fetch()) {
304 304
 			if ($row['principaluri'] === $principalUri) {
305 305
 				continue;
306 306
 			}
@@ -319,25 +319,25 @@  discard block
 block discarded – undo
319 319
 			}
320 320
 
321 321
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
322
-			$uri = $row['uri'] . '_shared_by_' . $name;
323
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
322
+			$uri = $row['uri'].'_shared_by_'.$name;
323
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
324 324
 			$components = [];
325 325
 			if ($row['components']) {
326
-				$components = explode(',',$row['components']);
326
+				$components = explode(',', $row['components']);
327 327
 			}
328 328
 			$calendar = [
329 329
 				'id' => $row['id'],
330 330
 				'uri' => $uri,
331 331
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
332
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
333
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
334
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
336
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337 337
 				$readOnlyPropertyName => $readOnly,
338 338
 			];
339 339
 
340
-			foreach($this->propertyMap as $xmlName=>$dbName) {
340
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
341 341
 				$calendar[$xmlName] = $row[$dbName];
342 342
 			}
343 343
 
@@ -366,21 +366,21 @@  discard block
 block discarded – undo
366 366
 			->orderBy('calendarorder', 'ASC');
367 367
 		$stmt = $query->execute();
368 368
 		$calendars = [];
369
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
369
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370 370
 			$components = [];
371 371
 			if ($row['components']) {
372
-				$components = explode(',',$row['components']);
372
+				$components = explode(',', $row['components']);
373 373
 			}
374 374
 			$calendar = [
375 375
 				'id' => $row['id'],
376 376
 				'uri' => $row['uri'],
377 377
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
378
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
379
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
380
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
382 382
 			];
383
-			foreach($this->propertyMap as $xmlName=>$dbName) {
383
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
384 384
 				$calendar[$xmlName] = $row[$dbName];
385 385
 			}
386 386
 
@@ -431,27 +431,27 @@  discard block
 block discarded – undo
431 431
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432 432
 			->execute();
433 433
 
434
-		while($row = $result->fetch()) {
434
+		while ($row = $result->fetch()) {
435 435
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
436
-			$row['displayname'] = $row['displayname'] . "($name)";
436
+			$row['displayname'] = $row['displayname']."($name)";
437 437
 			$components = [];
438 438
 			if ($row['components']) {
439
-				$components = explode(',',$row['components']);
439
+				$components = explode(',', $row['components']);
440 440
 			}
441 441
 			$calendar = [
442 442
 				'id' => $row['id'],
443 443
 				'uri' => $row['publicuri'],
444 444
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
445
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
446
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
447
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
449
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
451
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
452 452
 			];
453 453
 
454
-			foreach($this->propertyMap as $xmlName=>$dbName) {
454
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
455 455
 				$calendar[$xmlName] = $row[$dbName];
456 456
 			}
457 457
 
@@ -495,29 +495,29 @@  discard block
 block discarded – undo
495 495
 		$result->closeCursor();
496 496
 
497 497
 		if ($row === false) {
498
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
498
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
499 499
 		}
500 500
 
501 501
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
502
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
502
+		$row['displayname'] = $row['displayname'].' '."($name)";
503 503
 		$components = [];
504 504
 		if ($row['components']) {
505
-			$components = explode(',',$row['components']);
505
+			$components = explode(',', $row['components']);
506 506
 		}
507 507
 		$calendar = [
508 508
 			'id' => $row['id'],
509 509
 			'uri' => $row['publicuri'],
510 510
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
511
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
512
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
513
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
515
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
517
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
518 518
 		];
519 519
 
520
-		foreach($this->propertyMap as $xmlName=>$dbName) {
520
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
521 521
 			$calendar[$xmlName] = $row[$dbName];
522 522
 		}
523 523
 
@@ -557,20 +557,20 @@  discard block
 block discarded – undo
557 557
 
558 558
 		$components = [];
559 559
 		if ($row['components']) {
560
-			$components = explode(',',$row['components']);
560
+			$components = explode(',', $row['components']);
561 561
 		}
562 562
 
563 563
 		$calendar = [
564 564
 			'id' => $row['id'],
565 565
 			'uri' => $row['uri'],
566 566
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
567
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
568
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
569
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
571 571
 		];
572 572
 
573
-		foreach($this->propertyMap as $xmlName=>$dbName) {
573
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
574 574
 			$calendar[$xmlName] = $row[$dbName];
575 575
 		}
576 576
 
@@ -603,20 +603,20 @@  discard block
 block discarded – undo
603 603
 
604 604
 		$components = [];
605 605
 		if ($row['components']) {
606
-			$components = explode(',',$row['components']);
606
+			$components = explode(',', $row['components']);
607 607
 		}
608 608
 
609 609
 		$calendar = [
610 610
 			'id' => $row['id'],
611 611
 			'uri' => $row['uri'],
612 612
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
613
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
614
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
615
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
617 617
 		];
618 618
 
619
-		foreach($this->propertyMap as $xmlName=>$dbName) {
619
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
620 620
 			$calendar[$xmlName] = $row[$dbName];
621 621
 		}
622 622
 
@@ -651,16 +651,16 @@  discard block
 block discarded – undo
651 651
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
652 652
 		if (isset($properties[$sccs])) {
653 653
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
654
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
654
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
655 655
 			}
656
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
656
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
657 657
 		}
658
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
658
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
659 659
 		if (isset($properties[$transp])) {
660 660
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
661 661
 		}
662 662
 
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
663
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
664 664
 			if (isset($properties[$xmlName])) {
665 665
 				$values[$dbName] = $properties[$xmlName];
666 666
 			}
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 
669 669
 		$query = $this->db->getQueryBuilder();
670 670
 		$query->insert('calendars');
671
-		foreach($values as $column => $value) {
671
+		foreach ($values as $column => $value) {
672 672
 			$query->setValue($column, $query->createNamedParameter($value));
673 673
 		}
674 674
 		$query->execute();
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 	 */
703 703
 	function updateCalendar($calendarId, PropPatch $propPatch) {
704 704
 		$supportedProperties = array_keys($this->propertyMap);
705
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
705
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
706 706
 
707 707
 		/**
708 708
 		 * @suppress SqlInjectionChecker
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
 			foreach ($mutations as $propertyName => $propertyValue) {
713 713
 
714 714
 				switch ($propertyName) {
715
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
715
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
716 716
 						$fieldName = 'transparent';
717 717
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
718 718
 						break;
@@ -827,16 +827,16 @@  discard block
 block discarded – undo
827 827
 		$stmt = $query->execute();
828 828
 
829 829
 		$result = [];
830
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
830
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
831 831
 			$result[] = [
832 832
 					'id'           => $row['id'],
833 833
 					'uri'          => $row['uri'],
834 834
 					'lastmodified' => $row['lastmodified'],
835
-					'etag'         => '"' . $row['etag'] . '"',
835
+					'etag'         => '"'.$row['etag'].'"',
836 836
 					'calendarid'   => $row['calendarid'],
837
-					'size'         => (int)$row['size'],
837
+					'size'         => (int) $row['size'],
838 838
 					'component'    => strtolower($row['componenttype']),
839
-					'classification'=> (int)$row['classification']
839
+					'classification'=> (int) $row['classification']
840 840
 			];
841 841
 		}
842 842
 
@@ -869,18 +869,18 @@  discard block
 block discarded – undo
869 869
 		$stmt = $query->execute();
870 870
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
871 871
 
872
-		if(!$row) return null;
872
+		if (!$row) return null;
873 873
 
874 874
 		return [
875 875
 				'id'            => $row['id'],
876 876
 				'uri'           => $row['uri'],
877 877
 				'lastmodified'  => $row['lastmodified'],
878
-				'etag'          => '"' . $row['etag'] . '"',
878
+				'etag'          => '"'.$row['etag'].'"',
879 879
 				'calendarid'    => $row['calendarid'],
880
-				'size'          => (int)$row['size'],
880
+				'size'          => (int) $row['size'],
881 881
 				'calendardata'  => $this->readBlob($row['calendardata']),
882 882
 				'component'     => strtolower($row['componenttype']),
883
-				'classification'=> (int)$row['classification']
883
+				'classification'=> (int) $row['classification']
884 884
 		];
885 885
 	}
886 886
 
@@ -919,12 +919,12 @@  discard block
 block discarded – undo
919 919
 					'id'           => $row['id'],
920 920
 					'uri'          => $row['uri'],
921 921
 					'lastmodified' => $row['lastmodified'],
922
-					'etag'         => '"' . $row['etag'] . '"',
922
+					'etag'         => '"'.$row['etag'].'"',
923 923
 					'calendarid'   => $row['calendarid'],
924
-					'size'         => (int)$row['size'],
924
+					'size'         => (int) $row['size'],
925 925
 					'calendardata' => $this->readBlob($row['calendardata']),
926 926
 					'component'    => strtolower($row['componenttype']),
927
-					'classification' => (int)$row['classification']
927
+					'classification' => (int) $row['classification']
928 928
 				];
929 929
 			}
930 930
 			$result->closeCursor();
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
 		));
984 984
 		$this->addChange($calendarId, $objectUri, 1);
985 985
 
986
-		return '"' . $extraData['etag'] . '"';
986
+		return '"'.$extraData['etag'].'"';
987 987
 	}
988 988
 
989 989
 	/**
@@ -1038,7 +1038,7 @@  discard block
 block discarded – undo
1038 1038
 		}
1039 1039
 		$this->addChange($calendarId, $objectUri, 2);
1040 1040
 
1041
-		return '"' . $extraData['etag'] . '"';
1041
+		return '"'.$extraData['etag'].'"';
1042 1042
 	}
1043 1043
 
1044 1044
 	/**
@@ -1191,7 +1191,7 @@  discard block
 block discarded – undo
1191 1191
 		$stmt = $query->execute();
1192 1192
 
1193 1193
 		$result = [];
1194
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1194
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1195 1195
 			if ($requirePostFilter) {
1196 1196
 				if (!$this->validateFilterForObject($row, $filters)) {
1197 1197
 					continue;
@@ -1212,14 +1212,14 @@  discard block
 block discarded – undo
1212 1212
 	 * @param integer|null $offset
1213 1213
 	 * @return array
1214 1214
 	 */
1215
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1215
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1216 1216
 		$calendars = $this->getCalendarsForUser($principalUri);
1217 1217
 		$ownCalendars = [];
1218 1218
 		$sharedCalendars = [];
1219 1219
 
1220 1220
 		$uriMapper = [];
1221 1221
 
1222
-		foreach($calendars as $calendar) {
1222
+		foreach ($calendars as $calendar) {
1223 1223
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1224 1224
 				$ownCalendars[] = $calendar['id'];
1225 1225
 			} else {
@@ -1234,11 +1234,11 @@  discard block
 block discarded – undo
1234 1234
 		$query = $this->db->getQueryBuilder();
1235 1235
 		// Calendar id expressions
1236 1236
 		$calendarExpressions = [];
1237
-		foreach($ownCalendars as $id) {
1237
+		foreach ($ownCalendars as $id) {
1238 1238
 			$calendarExpressions[] = $query->expr()
1239 1239
 				->eq('c.calendarid', $query->createNamedParameter($id));
1240 1240
 		}
1241
-		foreach($sharedCalendars as $id) {
1241
+		foreach ($sharedCalendars as $id) {
1242 1242
 			$calendarExpressions[] = $query->expr()->andX(
1243 1243
 				$query->expr()->eq('c.calendarid',
1244 1244
 					$query->createNamedParameter($id)),
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
 
1256 1256
 		// Component expressions
1257 1257
 		$compExpressions = [];
1258
-		foreach($filters['comps'] as $comp) {
1258
+		foreach ($filters['comps'] as $comp) {
1259 1259
 			$compExpressions[] = $query->expr()
1260 1260
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1261 1261
 		}
@@ -1274,13 +1274,13 @@  discard block
 block discarded – undo
1274 1274
 		}
1275 1275
 
1276 1276
 		$propParamExpressions = [];
1277
-		foreach($filters['props'] as $prop) {
1277
+		foreach ($filters['props'] as $prop) {
1278 1278
 			$propParamExpressions[] = $query->expr()->andX(
1279 1279
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1280 1280
 				$query->expr()->isNull('i.parameter')
1281 1281
 			);
1282 1282
 		}
1283
-		foreach($filters['params'] as $param) {
1283
+		foreach ($filters['params'] as $param) {
1284 1284
 			$propParamExpressions[] = $query->expr()->andX(
1285 1285
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1286 1286
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1312,8 +1312,8 @@  discard block
 block discarded – undo
1312 1312
 		$stmt = $query->execute();
1313 1313
 
1314 1314
 		$result = [];
1315
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1316
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1315
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1316
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1317 1317
 			if (!in_array($path, $result)) {
1318 1318
 				$result[] = $path;
1319 1319
 			}
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
 		$stmt = $query->execute();
1354 1354
 
1355 1355
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1356
+			return $row['calendaruri'].'/'.$row['objecturi'];
1357 1357
 		}
1358 1358
 
1359 1359
 		return null;
@@ -1418,7 +1418,7 @@  discard block
 block discarded – undo
1418 1418
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1419 1419
 		// Current synctoken
1420 1420
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1421
-		$stmt->execute([ $calendarId ]);
1421
+		$stmt->execute([$calendarId]);
1422 1422
 		$currentToken = $stmt->fetchColumn(0);
1423 1423
 
1424 1424
 		if (is_null($currentToken)) {
@@ -1435,8 +1435,8 @@  discard block
 block discarded – undo
1435 1435
 		if ($syncToken) {
1436 1436
 
1437 1437
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1438
-			if ($limit>0) {
1439
-				$query.= " `LIMIT` " . (int)$limit;
1438
+			if ($limit > 0) {
1439
+				$query .= " `LIMIT` ".(int) $limit;
1440 1440
 			}
1441 1441
 
1442 1442
 			// Fetching all changes
@@ -1447,15 +1447,15 @@  discard block
 block discarded – undo
1447 1447
 
1448 1448
 			// This loop ensures that any duplicates are overwritten, only the
1449 1449
 			// last change on a node is relevant.
1450
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1450
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1451 1451
 
1452 1452
 				$changes[$row['uri']] = $row['operation'];
1453 1453
 
1454 1454
 			}
1455 1455
 
1456
-			foreach($changes as $uri => $operation) {
1456
+			foreach ($changes as $uri => $operation) {
1457 1457
 
1458
-				switch($operation) {
1458
+				switch ($operation) {
1459 1459
 					case 1 :
1460 1460
 						$result['added'][] = $uri;
1461 1461
 						break;
@@ -1525,10 +1525,10 @@  discard block
 block discarded – undo
1525 1525
 			->from('calendarsubscriptions')
1526 1526
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1527 1527
 			->orderBy('calendarorder', 'asc');
1528
-		$stmt =$query->execute();
1528
+		$stmt = $query->execute();
1529 1529
 
1530 1530
 		$subscriptions = [];
1531
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1531
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1532 1532
 
1533 1533
 			$subscription = [
1534 1534
 				'id'           => $row['id'],
@@ -1537,10 +1537,10 @@  discard block
 block discarded – undo
1537 1537
 				'source'       => $row['source'],
1538 1538
 				'lastmodified' => $row['lastmodified'],
1539 1539
 
1540
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1540
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1541 1541
 			];
1542 1542
 
1543
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1543
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1544 1544
 				if (!is_null($row[$dbName])) {
1545 1545
 					$subscription[$xmlName] = $row[$dbName];
1546 1546
 				}
@@ -1579,7 +1579,7 @@  discard block
 block discarded – undo
1579 1579
 
1580 1580
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1581 1581
 
1582
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1582
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1583 1583
 			if (array_key_exists($xmlName, $properties)) {
1584 1584
 					$values[$dbName] = $properties[$xmlName];
1585 1585
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1630,7 +1630,7 @@  discard block
 block discarded – undo
1630 1630
 
1631 1631
 			$newValues = [];
1632 1632
 
1633
-			foreach($mutations as $propertyName=>$propertyValue) {
1633
+			foreach ($mutations as $propertyName=>$propertyValue) {
1634 1634
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1635 1635
 					$newValues['source'] = $propertyValue->getHref();
1636 1636
 				} else {
@@ -1642,7 +1642,7 @@  discard block
 block discarded – undo
1642 1642
 			$query = $this->db->getQueryBuilder();
1643 1643
 			$query->update('calendarsubscriptions')
1644 1644
 				->set('lastmodified', $query->createNamedParameter(time()));
1645
-			foreach($newValues as $fieldName=>$value) {
1645
+			foreach ($newValues as $fieldName=>$value) {
1646 1646
 				$query->set($fieldName, $query->createNamedParameter($value));
1647 1647
 			}
1648 1648
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1692,7 +1692,7 @@  discard block
 block discarded – undo
1692 1692
 
1693 1693
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1694 1694
 
1695
-		if(!$row) {
1695
+		if (!$row) {
1696 1696
 			return null;
1697 1697
 		}
1698 1698
 
@@ -1700,8 +1700,8 @@  discard block
 block discarded – undo
1700 1700
 				'uri'          => $row['uri'],
1701 1701
 				'calendardata' => $row['calendardata'],
1702 1702
 				'lastmodified' => $row['lastmodified'],
1703
-				'etag'         => '"' . $row['etag'] . '"',
1704
-				'size'         => (int)$row['size'],
1703
+				'etag'         => '"'.$row['etag'].'"',
1704
+				'size'         => (int) $row['size'],
1705 1705
 		];
1706 1706
 	}
1707 1707
 
@@ -1724,13 +1724,13 @@  discard block
 block discarded – undo
1724 1724
 				->execute();
1725 1725
 
1726 1726
 		$result = [];
1727
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1727
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1728 1728
 			$result[] = [
1729 1729
 					'calendardata' => $row['calendardata'],
1730 1730
 					'uri'          => $row['uri'],
1731 1731
 					'lastmodified' => $row['lastmodified'],
1732
-					'etag'         => '"' . $row['etag'] . '"',
1733
-					'size'         => (int)$row['size'],
1732
+					'etag'         => '"'.$row['etag'].'"',
1733
+					'size'         => (int) $row['size'],
1734 1734
 			];
1735 1735
 		}
1736 1736
 
@@ -1822,10 +1822,10 @@  discard block
 block discarded – undo
1822 1822
 		$lastOccurrence = null;
1823 1823
 		$uid = null;
1824 1824
 		$classification = self::CLASSIFICATION_PUBLIC;
1825
-		foreach($vObject->getComponents() as $component) {
1826
-			if ($component->name!=='VTIMEZONE') {
1825
+		foreach ($vObject->getComponents() as $component) {
1826
+			if ($component->name !== 'VTIMEZONE') {
1827 1827
 				$componentType = $component->name;
1828
-				$uid = (string)$component->UID;
1828
+				$uid = (string) $component->UID;
1829 1829
 				break;
1830 1830
 			}
1831 1831
 		}
@@ -1850,13 +1850,13 @@  discard block
 block discarded – undo
1850 1850
 					$lastOccurrence = $firstOccurrence;
1851 1851
 				}
1852 1852
 			} else {
1853
-				$it = new EventIterator($vObject, (string)$component->UID);
1853
+				$it = new EventIterator($vObject, (string) $component->UID);
1854 1854
 				$maxDate = new \DateTime(self::MAX_DATE);
1855 1855
 				if ($it->isInfinite()) {
1856 1856
 					$lastOccurrence = $maxDate->getTimestamp();
1857 1857
 				} else {
1858 1858
 					$end = $it->getDtEnd();
1859
-					while($it->valid() && $end < $maxDate) {
1859
+					while ($it->valid() && $end < $maxDate) {
1860 1860
 						$end = $it->getDtEnd();
1861 1861
 						$it->next();
1862 1862
 
@@ -2065,8 +2065,8 @@  discard block
 block discarded – undo
2065 2065
 	{
2066 2066
 		$query = $this->db->getQueryBuilder();
2067 2067
 		$query->update('calendars')
2068
-			->set('principaluri', 'principals/users/' . $userDestination)
2069
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter('principals/users/'. $userOrigin)))
2068
+			->set('principaluri', 'principals/users/'.$userDestination)
2069
+			->where($query->expr()->eq('principaluri', $query->createNamedParameter('principals/users/'.$userOrigin)))
2070 2070
 			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2071 2071
 			->execute();
2072 2072
 	}
@@ -2113,10 +2113,10 @@  discard block
 block discarded – undo
2113 2113
 		$result->closeCursor();
2114 2114
 
2115 2115
 		if (!isset($objectIds['id'])) {
2116
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2116
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2117 2117
 		}
2118 2118
 
2119
-		return (int)$objectIds['id'];
2119
+		return (int) $objectIds['id'];
2120 2120
 	}
2121 2121
 
2122 2122
 	private function convertPrincipal($principalUri, $toV2) {
@@ -2131,8 +2131,8 @@  discard block
 block discarded – undo
2131 2131
 	}
2132 2132
 
2133 2133
 	private function addOwnerPrincipal(&$calendarInfo) {
2134
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2135
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2134
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2135
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2136 2136
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2137 2137
 			$uri = $calendarInfo[$ownerPrincipalKey];
2138 2138
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/Command/MoveCalendar.php 2 patches
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -34,102 +34,102 @@
 block discarded – undo
34 34
 
35 35
 class MoveCalendar extends Command {
36 36
 
37
-	/** @var IUserManager */
38
-	protected $userManager;
39
-
40
-	/** @var IGroupManager $groupManager */
41
-	private $groupManager;
42
-
43
-	/** @var \OCP\IDBConnection */
44
-	protected $dbConnection;
45
-
46
-	/** @var IL10N */
47
-	protected $l10n;
48
-
49
-	/**
50
-	 * @param IUserManager $userManager
51
-	 * @param IGroupManager $groupManager
52
-	 * @param IDBConnection $dbConnection
53
-	 * @param IL10N $l10n
54
-	 */
55
-	function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection, IL10N $l10n) {
56
-		parent::__construct();
57
-		$this->userManager = $userManager;
58
-		$this->groupManager = $groupManager;
59
-		$this->dbConnection = $dbConnection;
60
-		$this->l10n = $l10n;
61
-	}
62
-
63
-	protected function configure() {
64
-		$this
65
-			->setName('dav:move-calendar')
66
-			->setDescription('Move a calendar from an user to another')
67
-			->addArgument('name',
68
-				InputArgument::REQUIRED,
69
-				'Name of the calendar to move')
70
-			->addArgument('userorigin',
71
-				InputArgument::REQUIRED,
72
-				'User who currently owns the calendar')
73
-			->addArgument('userdestination',
74
-				InputArgument::REQUIRED,
75
-				'User who will receive the calendar')
76
-			->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing shares with groups that the destination user is not in");
77
-	}
78
-
79
-	protected function execute(InputInterface $input, OutputInterface $output) {
80
-		$userOrigin = $input->getArgument('userorigin');
81
-		$userDestination = $input->getArgument('userdestination');
82
-
83
-		if (in_array('system', [$userOrigin, $userDestination], true)) {
84
-			throw new \InvalidArgumentException("User can't be system");
85
-		}
86
-
87
-		if (!$this->userManager->userExists($userOrigin)) {
88
-			throw new \InvalidArgumentException("User <$userOrigin> in unknown.");
89
-		}
90
-
91
-
92
-		if (!$this->userManager->userExists($userDestination)) {
93
-			throw new \InvalidArgumentException("User <$userDestination> in unknown.");
94
-		}
95
-
96
-		$principalBackend = new Principal(
97
-			$this->userManager,
98
-			$this->groupManager
99
-		);
100
-		$random = \OC::$server->getSecureRandom();
101
-		$dispatcher = \OC::$server->getEventDispatcher();
102
-
103
-		$name = $input->getArgument('name');
104
-		$caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $random, $dispatcher);
105
-
106
-		$calendar = $caldav->getCalendarByUri("principals/users/" . $userOrigin, $name);
107
-		if (null === $calendar) {
108
-			throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>.");
109
-		}
110
-
111
-		if (null !== $caldav->getCalendarByUri("principals/users/" . $userDestination, $name)) {
112
-			throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>.");
113
-		}
114
-
115
-		/**
116
-		 * Check that user destination is member of the groups which whom the calendar was shared
117
-		 * If we ask to force the migration, the share with the group is dropped
118
-		 */
119
-		$shares = $caldav->getShares($calendar['id']);
120
-		foreach ($shares as $share) {
121
-			list($prefix, $group) = str_split($share['href'], 28);
122
-			if ('principal:principals/groups/' === $prefix && !$this->groupManager->isInGroup($userDestination, $group)) {
123
-				if ($input->getOption('force')) {
124
-					$caldav->updateShares(new Calendar($caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/' . $group]);
125
-				} else {
126
-					throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$group> with which the calendar <$name> was shared. You may use -f to move the calendar while deleting this share.");
127
-				}
128
-			}
129
-		}
130
-
131
-		$caldav->moveCalendar($name, $userOrigin, $userDestination);
132
-
133
-		$output->writeln("Calendar <$name> was moved from user <$userOrigin> to <$userDestination>");
134
-	}
37
+    /** @var IUserManager */
38
+    protected $userManager;
39
+
40
+    /** @var IGroupManager $groupManager */
41
+    private $groupManager;
42
+
43
+    /** @var \OCP\IDBConnection */
44
+    protected $dbConnection;
45
+
46
+    /** @var IL10N */
47
+    protected $l10n;
48
+
49
+    /**
50
+     * @param IUserManager $userManager
51
+     * @param IGroupManager $groupManager
52
+     * @param IDBConnection $dbConnection
53
+     * @param IL10N $l10n
54
+     */
55
+    function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection, IL10N $l10n) {
56
+        parent::__construct();
57
+        $this->userManager = $userManager;
58
+        $this->groupManager = $groupManager;
59
+        $this->dbConnection = $dbConnection;
60
+        $this->l10n = $l10n;
61
+    }
62
+
63
+    protected function configure() {
64
+        $this
65
+            ->setName('dav:move-calendar')
66
+            ->setDescription('Move a calendar from an user to another')
67
+            ->addArgument('name',
68
+                InputArgument::REQUIRED,
69
+                'Name of the calendar to move')
70
+            ->addArgument('userorigin',
71
+                InputArgument::REQUIRED,
72
+                'User who currently owns the calendar')
73
+            ->addArgument('userdestination',
74
+                InputArgument::REQUIRED,
75
+                'User who will receive the calendar')
76
+            ->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing shares with groups that the destination user is not in");
77
+    }
78
+
79
+    protected function execute(InputInterface $input, OutputInterface $output) {
80
+        $userOrigin = $input->getArgument('userorigin');
81
+        $userDestination = $input->getArgument('userdestination');
82
+
83
+        if (in_array('system', [$userOrigin, $userDestination], true)) {
84
+            throw new \InvalidArgumentException("User can't be system");
85
+        }
86
+
87
+        if (!$this->userManager->userExists($userOrigin)) {
88
+            throw new \InvalidArgumentException("User <$userOrigin> in unknown.");
89
+        }
90
+
91
+
92
+        if (!$this->userManager->userExists($userDestination)) {
93
+            throw new \InvalidArgumentException("User <$userDestination> in unknown.");
94
+        }
95
+
96
+        $principalBackend = new Principal(
97
+            $this->userManager,
98
+            $this->groupManager
99
+        );
100
+        $random = \OC::$server->getSecureRandom();
101
+        $dispatcher = \OC::$server->getEventDispatcher();
102
+
103
+        $name = $input->getArgument('name');
104
+        $caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $random, $dispatcher);
105
+
106
+        $calendar = $caldav->getCalendarByUri("principals/users/" . $userOrigin, $name);
107
+        if (null === $calendar) {
108
+            throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>.");
109
+        }
110
+
111
+        if (null !== $caldav->getCalendarByUri("principals/users/" . $userDestination, $name)) {
112
+            throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>.");
113
+        }
114
+
115
+        /**
116
+         * Check that user destination is member of the groups which whom the calendar was shared
117
+         * If we ask to force the migration, the share with the group is dropped
118
+         */
119
+        $shares = $caldav->getShares($calendar['id']);
120
+        foreach ($shares as $share) {
121
+            list($prefix, $group) = str_split($share['href'], 28);
122
+            if ('principal:principals/groups/' === $prefix && !$this->groupManager->isInGroup($userDestination, $group)) {
123
+                if ($input->getOption('force')) {
124
+                    $caldav->updateShares(new Calendar($caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/' . $group]);
125
+                } else {
126
+                    throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$group> with which the calendar <$name> was shared. You may use -f to move the calendar while deleting this share.");
127
+                }
128
+            }
129
+        }
130
+
131
+        $caldav->moveCalendar($name, $userOrigin, $userDestination);
132
+
133
+        $output->writeln("Calendar <$name> was moved from user <$userOrigin> to <$userDestination>");
134
+    }
135 135
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -103,12 +103,12 @@  discard block
 block discarded – undo
103 103
 		$name = $input->getArgument('name');
104 104
 		$caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $random, $dispatcher);
105 105
 
106
-		$calendar = $caldav->getCalendarByUri("principals/users/" . $userOrigin, $name);
106
+		$calendar = $caldav->getCalendarByUri("principals/users/".$userOrigin, $name);
107 107
 		if (null === $calendar) {
108 108
 			throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>.");
109 109
 		}
110 110
 
111
-		if (null !== $caldav->getCalendarByUri("principals/users/" . $userDestination, $name)) {
111
+		if (null !== $caldav->getCalendarByUri("principals/users/".$userDestination, $name)) {
112 112
 			throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>.");
113 113
 		}
114 114
 
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 			list($prefix, $group) = str_split($share['href'], 28);
122 122
 			if ('principal:principals/groups/' === $prefix && !$this->groupManager->isInGroup($userDestination, $group)) {
123 123
 				if ($input->getOption('force')) {
124
-					$caldav->updateShares(new Calendar($caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/' . $group]);
124
+					$caldav->updateShares(new Calendar($caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/'.$group]);
125 125
 				} else {
126 126
 					throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$group> with which the calendar <$name> was shared. You may use -f to move the calendar while deleting this share.");
127 127
 				}
Please login to merge, or discard this patch.