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