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