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