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