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