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