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