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