Passed
Push — master ( 7a1b45...fbf25e )
by Christoph
13:21 queued 10s
created
apps/dav/lib/DAV/GroupPrincipalBackend.php 2 patches
Indentation   +300 added lines, -300 removed lines patch added patch discarded remove patch
@@ -40,304 +40,304 @@
 block discarded – undo
40 40
 use Sabre\DAVACL\PrincipalBackend\BackendInterface;
41 41
 
42 42
 class GroupPrincipalBackend implements BackendInterface {
43
-	public const PRINCIPAL_PREFIX = 'principals/groups';
44
-
45
-	/** @var IGroupManager */
46
-	private $groupManager;
47
-
48
-	/** @var IUserSession */
49
-	private $userSession;
50
-
51
-	/** @var IShareManager */
52
-	private $shareManager;
53
-	/** @var IConfig */
54
-	private $config;
55
-
56
-	/**
57
-	 * @param IGroupManager $IGroupManager
58
-	 * @param IUserSession $userSession
59
-	 * @param IShareManager $shareManager
60
-	 */
61
-	public function __construct(
62
-		IGroupManager $IGroupManager,
63
-		IUserSession $userSession,
64
-		IShareManager $shareManager,
65
-		IConfig $config
66
-	) {
67
-		$this->groupManager = $IGroupManager;
68
-		$this->userSession = $userSession;
69
-		$this->shareManager = $shareManager;
70
-		$this->config = $config;
71
-	}
72
-
73
-	/**
74
-	 * Returns a list of principals based on a prefix.
75
-	 *
76
-	 * This prefix will often contain something like 'principals'. You are only
77
-	 * expected to return principals that are in this base path.
78
-	 *
79
-	 * You are expected to return at least a 'uri' for every user, you can
80
-	 * return any additional properties if you wish so. Common properties are:
81
-	 *   {DAV:}displayname
82
-	 *
83
-	 * @param string $prefixPath
84
-	 * @return string[]
85
-	 */
86
-	public function getPrincipalsByPrefix($prefixPath) {
87
-		$principals = [];
88
-
89
-		if ($prefixPath === self::PRINCIPAL_PREFIX) {
90
-			foreach ($this->groupManager->search('') as $user) {
91
-				$principals[] = $this->groupToPrincipal($user);
92
-			}
93
-		}
94
-
95
-		return $principals;
96
-	}
97
-
98
-	/**
99
-	 * Returns a specific principal, specified by it's path.
100
-	 * The returned structure should be the exact same as from
101
-	 * getPrincipalsByPrefix.
102
-	 *
103
-	 * @param string $path
104
-	 * @return array
105
-	 */
106
-	public function getPrincipalByPath($path) {
107
-		$elements = explode('/', $path,  3);
108
-		if ($elements[0] !== 'principals') {
109
-			return null;
110
-		}
111
-		if ($elements[1] !== 'groups') {
112
-			return null;
113
-		}
114
-		$name = urldecode($elements[2]);
115
-		$group = $this->groupManager->get($name);
116
-
117
-		if (!is_null($group)) {
118
-			return $this->groupToPrincipal($group);
119
-		}
120
-
121
-		return null;
122
-	}
123
-
124
-	/**
125
-	 * Returns the list of members for a group-principal
126
-	 *
127
-	 * @param string $principal
128
-	 * @return string[]
129
-	 * @throws Exception
130
-	 */
131
-	public function getGroupMemberSet($principal) {
132
-		$elements = explode('/', $principal);
133
-		if ($elements[0] !== 'principals') {
134
-			return [];
135
-		}
136
-		if ($elements[1] !== 'groups') {
137
-			return [];
138
-		}
139
-		$name = $elements[2];
140
-		$group = $this->groupManager->get($name);
141
-
142
-		if (is_null($group)) {
143
-			return [];
144
-		}
145
-
146
-		return array_map(function ($user) {
147
-			return $this->userToPrincipal($user);
148
-		}, $group->getUsers());
149
-	}
150
-
151
-	/**
152
-	 * Returns the list of groups a principal is a member of
153
-	 *
154
-	 * @param string $principal
155
-	 * @return array
156
-	 * @throws Exception
157
-	 */
158
-	public function getGroupMembership($principal) {
159
-		return [];
160
-	}
161
-
162
-	/**
163
-	 * Updates the list of group members for a group principal.
164
-	 *
165
-	 * The principals should be passed as a list of uri's.
166
-	 *
167
-	 * @param string $principal
168
-	 * @param string[] $members
169
-	 * @throws Exception
170
-	 */
171
-	public function setGroupMemberSet($principal, array $members) {
172
-		throw new Exception('Setting members of the group is not supported yet');
173
-	}
174
-
175
-	/**
176
-	 * @param string $path
177
-	 * @param PropPatch $propPatch
178
-	 * @return int
179
-	 */
180
-	public function updatePrincipal($path, PropPatch $propPatch) {
181
-		return 0;
182
-	}
183
-
184
-	/**
185
-	 * @param string $prefixPath
186
-	 * @param array $searchProperties
187
-	 * @param string $test
188
-	 * @return array
189
-	 */
190
-	public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
191
-		$results = [];
192
-
193
-		if (\count($searchProperties) === 0) {
194
-			return [];
195
-		}
196
-		if ($prefixPath !== self::PRINCIPAL_PREFIX) {
197
-			return [];
198
-		}
199
-		// If sharing is disabled, return the empty array
200
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
201
-		if (!$shareAPIEnabled) {
202
-			return [];
203
-		}
204
-
205
-		// If sharing is restricted to group members only,
206
-		// return only members that have groups in common
207
-		$restrictGroups = false;
208
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
209
-			$user = $this->userSession->getUser();
210
-			if (!$user) {
211
-				return [];
212
-			}
213
-
214
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
215
-		}
216
-
217
-		$searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
218
-		if ($searchLimit <= 0) {
219
-			$searchLimit = null;
220
-		}
221
-		foreach ($searchProperties as $prop => $value) {
222
-			switch ($prop) {
223
-				case '{DAV:}displayname':
224
-					$groups = $this->groupManager->search($value, $searchLimit);
225
-
226
-					$results[] = array_reduce($groups, function (array $carry, IGroup $group) use ($restrictGroups) {
227
-						$gid = $group->getGID();
228
-						// is sharing restricted to groups only?
229
-						if ($restrictGroups !== false) {
230
-							if (!\in_array($gid, $restrictGroups, true)) {
231
-								return $carry;
232
-							}
233
-						}
234
-
235
-						$carry[] = self::PRINCIPAL_PREFIX . '/' . urlencode($gid);
236
-						return $carry;
237
-					}, []);
238
-					break;
239
-
240
-				case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
241
-					// If you add support for more search properties that qualify as a user-address,
242
-					// please also add them to the array below
243
-					$results[] = $this->searchPrincipals(self::PRINCIPAL_PREFIX, [
244
-					], 'anyof');
245
-					break;
246
-
247
-				default:
248
-					$results[] = [];
249
-					break;
250
-			}
251
-		}
252
-
253
-		// results is an array of arrays, so this is not the first search result
254
-		// but the results of the first searchProperty
255
-		if (count($results) === 1) {
256
-			return $results[0];
257
-		}
258
-
259
-		switch ($test) {
260
-			case 'anyof':
261
-				return array_values(array_unique(array_merge(...$results)));
262
-
263
-			case 'allof':
264
-			default:
265
-				return array_values(array_intersect(...$results));
266
-		}
267
-	}
268
-
269
-	/**
270
-	 * @param string $uri
271
-	 * @param string $principalPrefix
272
-	 * @return string
273
-	 */
274
-	public function findByUri($uri, $principalPrefix) {
275
-		// If sharing is disabled, return the empty array
276
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
277
-		if (!$shareAPIEnabled) {
278
-			return null;
279
-		}
280
-
281
-		// If sharing is restricted to group members only,
282
-		// return only members that have groups in common
283
-		$restrictGroups = false;
284
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
285
-			$user = $this->userSession->getUser();
286
-			if (!$user) {
287
-				return null;
288
-			}
289
-
290
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
291
-		}
292
-
293
-		if (strpos($uri, 'principal:principals/groups/') === 0) {
294
-			$name = urlencode(substr($uri, 28));
295
-			if ($restrictGroups !== false && !\in_array($name, $restrictGroups, true)) {
296
-				return null;
297
-			}
298
-
299
-			return substr($uri, 10);
300
-		}
301
-
302
-		return null;
303
-	}
304
-
305
-	/**
306
-	 * @param IGroup $group
307
-	 * @return array
308
-	 */
309
-	protected function groupToPrincipal($group) {
310
-		$groupId = $group->getGID();
311
-		// getDisplayName returns UID if none
312
-		$displayName = $group->getDisplayName();
313
-
314
-		return [
315
-			'uri' => 'principals/groups/' . urlencode($groupId),
316
-			'{DAV:}displayname' => $displayName,
317
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'GROUP',
318
-		];
319
-	}
320
-
321
-	/**
322
-	 * @param IUser $user
323
-	 * @return array
324
-	 */
325
-	protected function userToPrincipal($user) {
326
-		$userId = $user->getUID();
327
-		// getDisplayName returns UID if none
328
-		$displayName = $user->getDisplayName();
329
-
330
-		$principal = [
331
-			'uri' => 'principals/users/' . $userId,
332
-			'{DAV:}displayname' => $displayName,
333
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
334
-		];
335
-
336
-		$email = $user->getEMailAddress();
337
-		if (!empty($email)) {
338
-			$principal['{http://sabredav.org/ns}email-address'] = $email;
339
-		}
340
-
341
-		return $principal;
342
-	}
43
+    public const PRINCIPAL_PREFIX = 'principals/groups';
44
+
45
+    /** @var IGroupManager */
46
+    private $groupManager;
47
+
48
+    /** @var IUserSession */
49
+    private $userSession;
50
+
51
+    /** @var IShareManager */
52
+    private $shareManager;
53
+    /** @var IConfig */
54
+    private $config;
55
+
56
+    /**
57
+     * @param IGroupManager $IGroupManager
58
+     * @param IUserSession $userSession
59
+     * @param IShareManager $shareManager
60
+     */
61
+    public function __construct(
62
+        IGroupManager $IGroupManager,
63
+        IUserSession $userSession,
64
+        IShareManager $shareManager,
65
+        IConfig $config
66
+    ) {
67
+        $this->groupManager = $IGroupManager;
68
+        $this->userSession = $userSession;
69
+        $this->shareManager = $shareManager;
70
+        $this->config = $config;
71
+    }
72
+
73
+    /**
74
+     * Returns a list of principals based on a prefix.
75
+     *
76
+     * This prefix will often contain something like 'principals'. You are only
77
+     * expected to return principals that are in this base path.
78
+     *
79
+     * You are expected to return at least a 'uri' for every user, you can
80
+     * return any additional properties if you wish so. Common properties are:
81
+     *   {DAV:}displayname
82
+     *
83
+     * @param string $prefixPath
84
+     * @return string[]
85
+     */
86
+    public function getPrincipalsByPrefix($prefixPath) {
87
+        $principals = [];
88
+
89
+        if ($prefixPath === self::PRINCIPAL_PREFIX) {
90
+            foreach ($this->groupManager->search('') as $user) {
91
+                $principals[] = $this->groupToPrincipal($user);
92
+            }
93
+        }
94
+
95
+        return $principals;
96
+    }
97
+
98
+    /**
99
+     * Returns a specific principal, specified by it's path.
100
+     * The returned structure should be the exact same as from
101
+     * getPrincipalsByPrefix.
102
+     *
103
+     * @param string $path
104
+     * @return array
105
+     */
106
+    public function getPrincipalByPath($path) {
107
+        $elements = explode('/', $path,  3);
108
+        if ($elements[0] !== 'principals') {
109
+            return null;
110
+        }
111
+        if ($elements[1] !== 'groups') {
112
+            return null;
113
+        }
114
+        $name = urldecode($elements[2]);
115
+        $group = $this->groupManager->get($name);
116
+
117
+        if (!is_null($group)) {
118
+            return $this->groupToPrincipal($group);
119
+        }
120
+
121
+        return null;
122
+    }
123
+
124
+    /**
125
+     * Returns the list of members for a group-principal
126
+     *
127
+     * @param string $principal
128
+     * @return string[]
129
+     * @throws Exception
130
+     */
131
+    public function getGroupMemberSet($principal) {
132
+        $elements = explode('/', $principal);
133
+        if ($elements[0] !== 'principals') {
134
+            return [];
135
+        }
136
+        if ($elements[1] !== 'groups') {
137
+            return [];
138
+        }
139
+        $name = $elements[2];
140
+        $group = $this->groupManager->get($name);
141
+
142
+        if (is_null($group)) {
143
+            return [];
144
+        }
145
+
146
+        return array_map(function ($user) {
147
+            return $this->userToPrincipal($user);
148
+        }, $group->getUsers());
149
+    }
150
+
151
+    /**
152
+     * Returns the list of groups a principal is a member of
153
+     *
154
+     * @param string $principal
155
+     * @return array
156
+     * @throws Exception
157
+     */
158
+    public function getGroupMembership($principal) {
159
+        return [];
160
+    }
161
+
162
+    /**
163
+     * Updates the list of group members for a group principal.
164
+     *
165
+     * The principals should be passed as a list of uri's.
166
+     *
167
+     * @param string $principal
168
+     * @param string[] $members
169
+     * @throws Exception
170
+     */
171
+    public function setGroupMemberSet($principal, array $members) {
172
+        throw new Exception('Setting members of the group is not supported yet');
173
+    }
174
+
175
+    /**
176
+     * @param string $path
177
+     * @param PropPatch $propPatch
178
+     * @return int
179
+     */
180
+    public function updatePrincipal($path, PropPatch $propPatch) {
181
+        return 0;
182
+    }
183
+
184
+    /**
185
+     * @param string $prefixPath
186
+     * @param array $searchProperties
187
+     * @param string $test
188
+     * @return array
189
+     */
190
+    public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
191
+        $results = [];
192
+
193
+        if (\count($searchProperties) === 0) {
194
+            return [];
195
+        }
196
+        if ($prefixPath !== self::PRINCIPAL_PREFIX) {
197
+            return [];
198
+        }
199
+        // If sharing is disabled, return the empty array
200
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
201
+        if (!$shareAPIEnabled) {
202
+            return [];
203
+        }
204
+
205
+        // If sharing is restricted to group members only,
206
+        // return only members that have groups in common
207
+        $restrictGroups = false;
208
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
209
+            $user = $this->userSession->getUser();
210
+            if (!$user) {
211
+                return [];
212
+            }
213
+
214
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
215
+        }
216
+
217
+        $searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
218
+        if ($searchLimit <= 0) {
219
+            $searchLimit = null;
220
+        }
221
+        foreach ($searchProperties as $prop => $value) {
222
+            switch ($prop) {
223
+                case '{DAV:}displayname':
224
+                    $groups = $this->groupManager->search($value, $searchLimit);
225
+
226
+                    $results[] = array_reduce($groups, function (array $carry, IGroup $group) use ($restrictGroups) {
227
+                        $gid = $group->getGID();
228
+                        // is sharing restricted to groups only?
229
+                        if ($restrictGroups !== false) {
230
+                            if (!\in_array($gid, $restrictGroups, true)) {
231
+                                return $carry;
232
+                            }
233
+                        }
234
+
235
+                        $carry[] = self::PRINCIPAL_PREFIX . '/' . urlencode($gid);
236
+                        return $carry;
237
+                    }, []);
238
+                    break;
239
+
240
+                case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
241
+                    // If you add support for more search properties that qualify as a user-address,
242
+                    // please also add them to the array below
243
+                    $results[] = $this->searchPrincipals(self::PRINCIPAL_PREFIX, [
244
+                    ], 'anyof');
245
+                    break;
246
+
247
+                default:
248
+                    $results[] = [];
249
+                    break;
250
+            }
251
+        }
252
+
253
+        // results is an array of arrays, so this is not the first search result
254
+        // but the results of the first searchProperty
255
+        if (count($results) === 1) {
256
+            return $results[0];
257
+        }
258
+
259
+        switch ($test) {
260
+            case 'anyof':
261
+                return array_values(array_unique(array_merge(...$results)));
262
+
263
+            case 'allof':
264
+            default:
265
+                return array_values(array_intersect(...$results));
266
+        }
267
+    }
268
+
269
+    /**
270
+     * @param string $uri
271
+     * @param string $principalPrefix
272
+     * @return string
273
+     */
274
+    public function findByUri($uri, $principalPrefix) {
275
+        // If sharing is disabled, return the empty array
276
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
277
+        if (!$shareAPIEnabled) {
278
+            return null;
279
+        }
280
+
281
+        // If sharing is restricted to group members only,
282
+        // return only members that have groups in common
283
+        $restrictGroups = false;
284
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
285
+            $user = $this->userSession->getUser();
286
+            if (!$user) {
287
+                return null;
288
+            }
289
+
290
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
291
+        }
292
+
293
+        if (strpos($uri, 'principal:principals/groups/') === 0) {
294
+            $name = urlencode(substr($uri, 28));
295
+            if ($restrictGroups !== false && !\in_array($name, $restrictGroups, true)) {
296
+                return null;
297
+            }
298
+
299
+            return substr($uri, 10);
300
+        }
301
+
302
+        return null;
303
+    }
304
+
305
+    /**
306
+     * @param IGroup $group
307
+     * @return array
308
+     */
309
+    protected function groupToPrincipal($group) {
310
+        $groupId = $group->getGID();
311
+        // getDisplayName returns UID if none
312
+        $displayName = $group->getDisplayName();
313
+
314
+        return [
315
+            'uri' => 'principals/groups/' . urlencode($groupId),
316
+            '{DAV:}displayname' => $displayName,
317
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'GROUP',
318
+        ];
319
+    }
320
+
321
+    /**
322
+     * @param IUser $user
323
+     * @return array
324
+     */
325
+    protected function userToPrincipal($user) {
326
+        $userId = $user->getUID();
327
+        // getDisplayName returns UID if none
328
+        $displayName = $user->getDisplayName();
329
+
330
+        $principal = [
331
+            'uri' => 'principals/users/' . $userId,
332
+            '{DAV:}displayname' => $displayName,
333
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
334
+        ];
335
+
336
+        $email = $user->getEMailAddress();
337
+        if (!empty($email)) {
338
+            $principal['{http://sabredav.org/ns}email-address'] = $email;
339
+        }
340
+
341
+        return $principal;
342
+    }
343 343
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	 * @return array
105 105
 	 */
106 106
 	public function getPrincipalByPath($path) {
107
-		$elements = explode('/', $path,  3);
107
+		$elements = explode('/', $path, 3);
108 108
 		if ($elements[0] !== 'principals') {
109 109
 			return null;
110 110
 		}
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 			return [];
144 144
 		}
145 145
 
146
-		return array_map(function ($user) {
146
+		return array_map(function($user) {
147 147
 			return $this->userToPrincipal($user);
148 148
 		}, $group->getUsers());
149 149
 	}
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 				case '{DAV:}displayname':
224 224
 					$groups = $this->groupManager->search($value, $searchLimit);
225 225
 
226
-					$results[] = array_reduce($groups, function (array $carry, IGroup $group) use ($restrictGroups) {
226
+					$results[] = array_reduce($groups, function(array $carry, IGroup $group) use ($restrictGroups) {
227 227
 						$gid = $group->getGID();
228 228
 						// is sharing restricted to groups only?
229 229
 						if ($restrictGroups !== false) {
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 							}
233 233
 						}
234 234
 
235
-						$carry[] = self::PRINCIPAL_PREFIX . '/' . urlencode($gid);
235
+						$carry[] = self::PRINCIPAL_PREFIX.'/'.urlencode($gid);
236 236
 						return $carry;
237 237
 					}, []);
238 238
 					break;
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 		$displayName = $group->getDisplayName();
313 313
 
314 314
 		return [
315
-			'uri' => 'principals/groups/' . urlencode($groupId),
315
+			'uri' => 'principals/groups/'.urlencode($groupId),
316 316
 			'{DAV:}displayname' => $displayName,
317 317
 			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'GROUP',
318 318
 		];
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 		$displayName = $user->getDisplayName();
329 329
 
330 330
 		$principal = [
331
-			'uri' => 'principals/users/' . $userId,
331
+			'uri' => 'principals/users/'.$userId,
332 332
 			'{DAV:}displayname' => $displayName,
333 333
 			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
334 334
 		];
Please login to merge, or discard this patch.
apps/dav/lib/DAV/Sharing/Backend.php 1 patch
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -35,214 +35,214 @@
 block discarded – undo
35 35
 
36 36
 class Backend {
37 37
 
38
-	/** @var IDBConnection */
39
-	private $db;
40
-	/** @var IUserManager */
41
-	private $userManager;
42
-	/** @var IGroupManager */
43
-	private $groupManager;
44
-	/** @var Principal */
45
-	private $principalBackend;
46
-	/** @var string */
47
-	private $resourceType;
48
-
49
-	public const ACCESS_OWNER = 1;
50
-	public const ACCESS_READ_WRITE = 2;
51
-	public const ACCESS_READ = 3;
52
-
53
-	/**
54
-	 * @param IDBConnection $db
55
-	 * @param IUserManager $userManager
56
-	 * @param IGroupManager $groupManager
57
-	 * @param Principal $principalBackend
58
-	 * @param string $resourceType
59
-	 */
60
-	public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
61
-		$this->db = $db;
62
-		$this->userManager = $userManager;
63
-		$this->groupManager = $groupManager;
64
-		$this->principalBackend = $principalBackend;
65
-		$this->resourceType = $resourceType;
66
-	}
67
-
68
-	/**
69
-	 * @param IShareable $shareable
70
-	 * @param string[] $add
71
-	 * @param string[] $remove
72
-	 */
73
-	public function updateShares(IShareable $shareable, array $add, array $remove) {
74
-		foreach ($add as $element) {
75
-			$principal = $this->principalBackend->findByUri($element['href'], '');
76
-			if ($principal !== '') {
77
-				$this->shareWith($shareable, $element);
78
-			}
79
-		}
80
-		foreach ($remove as $element) {
81
-			$principal = $this->principalBackend->findByUri($element, '');
82
-			if ($principal !== '') {
83
-				$this->unshare($shareable, $element);
84
-			}
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * @param IShareable $shareable
90
-	 * @param string $element
91
-	 */
92
-	private function shareWith($shareable, $element) {
93
-		$user = $element['href'];
94
-		$parts = explode(':', $user, 2);
95
-		if ($parts[0] !== 'principal') {
96
-			return;
97
-		}
98
-
99
-		// don't share with owner
100
-		if ($shareable->getOwner() === $parts[1]) {
101
-			return;
102
-		}
103
-
104
-		$principal = explode('/', $parts[1], 3);
105
-		if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
106
-			// Invalid principal
107
-			return;
108
-		}
109
-
110
-		$principal[2] = urldecode($principal[2]);
111
-		if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
112
-			($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
113
-			// User or group does not exist
114
-			return;
115
-		}
116
-
117
-		// remove the share if it already exists
118
-		$this->unshare($shareable, $element['href']);
119
-		$access = self::ACCESS_READ;
120
-		if (isset($element['readOnly'])) {
121
-			$access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
122
-		}
123
-
124
-		$query = $this->db->getQueryBuilder();
125
-		$query->insert('dav_shares')
126
-			->values([
127
-				'principaluri' => $query->createNamedParameter($parts[1]),
128
-				'type' => $query->createNamedParameter($this->resourceType),
129
-				'access' => $query->createNamedParameter($access),
130
-				'resourceid' => $query->createNamedParameter($shareable->getResourceId())
131
-			]);
132
-		$query->execute();
133
-	}
134
-
135
-	/**
136
-	 * @param $resourceId
137
-	 */
138
-	public function deleteAllShares($resourceId) {
139
-		$query = $this->db->getQueryBuilder();
140
-		$query->delete('dav_shares')
141
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
142
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
143
-			->execute();
144
-	}
145
-
146
-	public function deleteAllSharesByUser($principaluri) {
147
-		$query = $this->db->getQueryBuilder();
148
-		$query->delete('dav_shares')
149
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
150
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
151
-			->execute();
152
-	}
153
-
154
-	/**
155
-	 * @param IShareable $shareable
156
-	 * @param string $element
157
-	 */
158
-	private function unshare($shareable, $element) {
159
-		$parts = explode(':', $element, 2);
160
-		if ($parts[0] !== 'principal') {
161
-			return;
162
-		}
163
-
164
-		// don't share with owner
165
-		if ($shareable->getOwner() === $parts[1]) {
166
-			return;
167
-		}
168
-
169
-		$query = $this->db->getQueryBuilder();
170
-		$query->delete('dav_shares')
171
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
172
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
173
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
174
-		;
175
-		$query->execute();
176
-	}
177
-
178
-	/**
179
-	 * Returns the list of people whom this resource is shared with.
180
-	 *
181
-	 * Every element in this array should have the following properties:
182
-	 *   * href - Often a mailto: address
183
-	 *   * commonName - Optional, for example a first + last name
184
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
185
-	 *   * readOnly - boolean
186
-	 *   * summary - Optional, a description for the share
187
-	 *
188
-	 * @param int $resourceId
189
-	 * @return array
190
-	 */
191
-	public function getShares($resourceId) {
192
-		$query = $this->db->getQueryBuilder();
193
-		$result = $query->select(['principaluri', 'access'])
194
-			->from('dav_shares')
195
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
196
-			->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
197
-			->execute();
198
-
199
-		$shares = [];
200
-		while ($row = $result->fetch()) {
201
-			$p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
202
-			$shares[] = [
203
-				'href' => "principal:${row['principaluri']}",
204
-				'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
205
-				'status' => 1,
206
-				'readOnly' => (int) $row['access'] === self::ACCESS_READ,
207
-				'{http://owncloud.org/ns}principal' => $row['principaluri'],
208
-				'{http://owncloud.org/ns}group-share' => is_null($p)
209
-			];
210
-		}
211
-
212
-		return $shares;
213
-	}
214
-
215
-	/**
216
-	 * For shared resources the sharee is set in the ACL of the resource
217
-	 *
218
-	 * @param int $resourceId
219
-	 * @param array $acl
220
-	 * @return array
221
-	 */
222
-	public function applyShareAcl($resourceId, $acl) {
223
-		$shares = $this->getShares($resourceId);
224
-		foreach ($shares as $share) {
225
-			$acl[] = [
226
-				'privilege' => '{DAV:}read',
227
-				'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
228
-				'protected' => true,
229
-			];
230
-			if (!$share['readOnly']) {
231
-				$acl[] = [
232
-					'privilege' => '{DAV:}write',
233
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
234
-					'protected' => true,
235
-				];
236
-			} elseif ($this->resourceType === 'calendar') {
237
-				// Allow changing the properties of read only calendars,
238
-				// so users can change the visibility.
239
-				$acl[] = [
240
-					'privilege' => '{DAV:}write-properties',
241
-					'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
242
-					'protected' => true,
243
-				];
244
-			}
245
-		}
246
-		return $acl;
247
-	}
38
+    /** @var IDBConnection */
39
+    private $db;
40
+    /** @var IUserManager */
41
+    private $userManager;
42
+    /** @var IGroupManager */
43
+    private $groupManager;
44
+    /** @var Principal */
45
+    private $principalBackend;
46
+    /** @var string */
47
+    private $resourceType;
48
+
49
+    public const ACCESS_OWNER = 1;
50
+    public const ACCESS_READ_WRITE = 2;
51
+    public const ACCESS_READ = 3;
52
+
53
+    /**
54
+     * @param IDBConnection $db
55
+     * @param IUserManager $userManager
56
+     * @param IGroupManager $groupManager
57
+     * @param Principal $principalBackend
58
+     * @param string $resourceType
59
+     */
60
+    public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) {
61
+        $this->db = $db;
62
+        $this->userManager = $userManager;
63
+        $this->groupManager = $groupManager;
64
+        $this->principalBackend = $principalBackend;
65
+        $this->resourceType = $resourceType;
66
+    }
67
+
68
+    /**
69
+     * @param IShareable $shareable
70
+     * @param string[] $add
71
+     * @param string[] $remove
72
+     */
73
+    public function updateShares(IShareable $shareable, array $add, array $remove) {
74
+        foreach ($add as $element) {
75
+            $principal = $this->principalBackend->findByUri($element['href'], '');
76
+            if ($principal !== '') {
77
+                $this->shareWith($shareable, $element);
78
+            }
79
+        }
80
+        foreach ($remove as $element) {
81
+            $principal = $this->principalBackend->findByUri($element, '');
82
+            if ($principal !== '') {
83
+                $this->unshare($shareable, $element);
84
+            }
85
+        }
86
+    }
87
+
88
+    /**
89
+     * @param IShareable $shareable
90
+     * @param string $element
91
+     */
92
+    private function shareWith($shareable, $element) {
93
+        $user = $element['href'];
94
+        $parts = explode(':', $user, 2);
95
+        if ($parts[0] !== 'principal') {
96
+            return;
97
+        }
98
+
99
+        // don't share with owner
100
+        if ($shareable->getOwner() === $parts[1]) {
101
+            return;
102
+        }
103
+
104
+        $principal = explode('/', $parts[1], 3);
105
+        if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
106
+            // Invalid principal
107
+            return;
108
+        }
109
+
110
+        $principal[2] = urldecode($principal[2]);
111
+        if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
112
+            ($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
113
+            // User or group does not exist
114
+            return;
115
+        }
116
+
117
+        // remove the share if it already exists
118
+        $this->unshare($shareable, $element['href']);
119
+        $access = self::ACCESS_READ;
120
+        if (isset($element['readOnly'])) {
121
+            $access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
122
+        }
123
+
124
+        $query = $this->db->getQueryBuilder();
125
+        $query->insert('dav_shares')
126
+            ->values([
127
+                'principaluri' => $query->createNamedParameter($parts[1]),
128
+                'type' => $query->createNamedParameter($this->resourceType),
129
+                'access' => $query->createNamedParameter($access),
130
+                'resourceid' => $query->createNamedParameter($shareable->getResourceId())
131
+            ]);
132
+        $query->execute();
133
+    }
134
+
135
+    /**
136
+     * @param $resourceId
137
+     */
138
+    public function deleteAllShares($resourceId) {
139
+        $query = $this->db->getQueryBuilder();
140
+        $query->delete('dav_shares')
141
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
142
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
143
+            ->execute();
144
+    }
145
+
146
+    public function deleteAllSharesByUser($principaluri) {
147
+        $query = $this->db->getQueryBuilder();
148
+        $query->delete('dav_shares')
149
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
150
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
151
+            ->execute();
152
+    }
153
+
154
+    /**
155
+     * @param IShareable $shareable
156
+     * @param string $element
157
+     */
158
+    private function unshare($shareable, $element) {
159
+        $parts = explode(':', $element, 2);
160
+        if ($parts[0] !== 'principal') {
161
+            return;
162
+        }
163
+
164
+        // don't share with owner
165
+        if ($shareable->getOwner() === $parts[1]) {
166
+            return;
167
+        }
168
+
169
+        $query = $this->db->getQueryBuilder();
170
+        $query->delete('dav_shares')
171
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
172
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
173
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
174
+        ;
175
+        $query->execute();
176
+    }
177
+
178
+    /**
179
+     * Returns the list of people whom this resource is shared with.
180
+     *
181
+     * Every element in this array should have the following properties:
182
+     *   * href - Often a mailto: address
183
+     *   * commonName - Optional, for example a first + last name
184
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
185
+     *   * readOnly - boolean
186
+     *   * summary - Optional, a description for the share
187
+     *
188
+     * @param int $resourceId
189
+     * @return array
190
+     */
191
+    public function getShares($resourceId) {
192
+        $query = $this->db->getQueryBuilder();
193
+        $result = $query->select(['principaluri', 'access'])
194
+            ->from('dav_shares')
195
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
196
+            ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
197
+            ->execute();
198
+
199
+        $shares = [];
200
+        while ($row = $result->fetch()) {
201
+            $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
202
+            $shares[] = [
203
+                'href' => "principal:${row['principaluri']}",
204
+                'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '',
205
+                'status' => 1,
206
+                'readOnly' => (int) $row['access'] === self::ACCESS_READ,
207
+                '{http://owncloud.org/ns}principal' => $row['principaluri'],
208
+                '{http://owncloud.org/ns}group-share' => is_null($p)
209
+            ];
210
+        }
211
+
212
+        return $shares;
213
+    }
214
+
215
+    /**
216
+     * For shared resources the sharee is set in the ACL of the resource
217
+     *
218
+     * @param int $resourceId
219
+     * @param array $acl
220
+     * @return array
221
+     */
222
+    public function applyShareAcl($resourceId, $acl) {
223
+        $shares = $this->getShares($resourceId);
224
+        foreach ($shares as $share) {
225
+            $acl[] = [
226
+                'privilege' => '{DAV:}read',
227
+                'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
228
+                'protected' => true,
229
+            ];
230
+            if (!$share['readOnly']) {
231
+                $acl[] = [
232
+                    'privilege' => '{DAV:}write',
233
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
234
+                    'protected' => true,
235
+                ];
236
+            } elseif ($this->resourceType === 'calendar') {
237
+                // Allow changing the properties of read only calendars,
238
+                // so users can change the visibility.
239
+                $acl[] = [
240
+                    'privilege' => '{DAV:}write-properties',
241
+                    'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
242
+                    'protected' => true,
243
+                ];
244
+            }
245
+        }
246
+        return $acl;
247
+    }
248 248
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 2 patches
Indentation   +1299 added lines, -1299 removed lines patch added patch discarded remove patch
@@ -61,1303 +61,1303 @@
 block discarded – undo
61 61
 use Symfony\Component\EventDispatcher\GenericEvent;
62 62
 
63 63
 class CardDavBackend implements BackendInterface, SyncSupport {
64
-	public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
65
-	public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
66
-
67
-	/** @var Principal */
68
-	private $principalBackend;
69
-
70
-	/** @var string */
71
-	private $dbCardsTable = 'cards';
72
-
73
-	/** @var string */
74
-	private $dbCardsPropertiesTable = 'cards_properties';
75
-
76
-	/** @var IDBConnection */
77
-	private $db;
78
-
79
-	/** @var Backend */
80
-	private $sharingBackend;
81
-
82
-	/** @var array properties to index */
83
-	public static $indexProperties = [
84
-		'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
85
-		'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
86
-
87
-	/**
88
-	 * @var string[] Map of uid => display name
89
-	 */
90
-	protected $userDisplayNames;
91
-
92
-	/** @var IUserManager */
93
-	private $userManager;
94
-
95
-	/** @var IEventDispatcher */
96
-	private $dispatcher;
97
-
98
-	/** @var EventDispatcherInterface */
99
-	private $legacyDispatcher;
100
-
101
-	private $etagCache = [];
102
-
103
-	/**
104
-	 * CardDavBackend constructor.
105
-	 *
106
-	 * @param IDBConnection $db
107
-	 * @param Principal $principalBackend
108
-	 * @param IUserManager $userManager
109
-	 * @param IGroupManager $groupManager
110
-	 * @param IEventDispatcher $dispatcher
111
-	 * @param EventDispatcherInterface $legacyDispatcher
112
-	 */
113
-	public function __construct(IDBConnection $db,
114
-								Principal $principalBackend,
115
-								IUserManager $userManager,
116
-								IGroupManager $groupManager,
117
-								IEventDispatcher $dispatcher,
118
-								EventDispatcherInterface $legacyDispatcher) {
119
-		$this->db = $db;
120
-		$this->principalBackend = $principalBackend;
121
-		$this->userManager = $userManager;
122
-		$this->dispatcher = $dispatcher;
123
-		$this->legacyDispatcher = $legacyDispatcher;
124
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
125
-	}
126
-
127
-	/**
128
-	 * Return the number of address books for a principal
129
-	 *
130
-	 * @param $principalUri
131
-	 * @return int
132
-	 */
133
-	public function getAddressBooksForUserCount($principalUri) {
134
-		$principalUri = $this->convertPrincipal($principalUri, true);
135
-		$query = $this->db->getQueryBuilder();
136
-		$query->select($query->func()->count('*'))
137
-			->from('addressbooks')
138
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
139
-
140
-		$result = $query->execute();
141
-		$column = (int) $result->fetchColumn();
142
-		$result->closeCursor();
143
-		return $column;
144
-	}
145
-
146
-	/**
147
-	 * Returns the list of address books for a specific user.
148
-	 *
149
-	 * Every addressbook should have the following properties:
150
-	 *   id - an arbitrary unique id
151
-	 *   uri - the 'basename' part of the url
152
-	 *   principaluri - Same as the passed parameter
153
-	 *
154
-	 * Any additional clark-notation property may be passed besides this. Some
155
-	 * common ones are :
156
-	 *   {DAV:}displayname
157
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
158
-	 *   {http://calendarserver.org/ns/}getctag
159
-	 *
160
-	 * @param string $principalUri
161
-	 * @return array
162
-	 */
163
-	public function getAddressBooksForUser($principalUri) {
164
-		$principalUriOriginal = $principalUri;
165
-		$principalUri = $this->convertPrincipal($principalUri, true);
166
-		$query = $this->db->getQueryBuilder();
167
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
168
-			->from('addressbooks')
169
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
170
-
171
-		$addressBooks = [];
172
-
173
-		$result = $query->execute();
174
-		while ($row = $result->fetch()) {
175
-			$addressBooks[$row['id']] = [
176
-				'id' => $row['id'],
177
-				'uri' => $row['uri'],
178
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
179
-				'{DAV:}displayname' => $row['displayname'],
180
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
181
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
182
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
183
-			];
184
-
185
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
186
-		}
187
-		$result->closeCursor();
188
-
189
-		// query for shared addressbooks
190
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
191
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
192
-
193
-		$principals[] = $principalUri;
194
-
195
-		$query = $this->db->getQueryBuilder();
196
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
197
-			->from('dav_shares', 's')
198
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
199
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
200
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
201
-			->setParameter('type', 'addressbook')
202
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
203
-			->execute();
204
-
205
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
206
-		while ($row = $result->fetch()) {
207
-			if ($row['principaluri'] === $principalUri) {
208
-				continue;
209
-			}
210
-
211
-			$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
212
-			if (isset($addressBooks[$row['id']])) {
213
-				if ($readOnly) {
214
-					// New share can not have more permissions then the old one.
215
-					continue;
216
-				}
217
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
218
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
219
-					// Old share is already read-write, no more permissions can be gained
220
-					continue;
221
-				}
222
-			}
223
-
224
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
225
-			$uri = $row['uri'] . '_shared_by_' . $name;
226
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
227
-
228
-			$addressBooks[$row['id']] = [
229
-				'id' => $row['id'],
230
-				'uri' => $uri,
231
-				'principaluri' => $principalUriOriginal,
232
-				'{DAV:}displayname' => $displayName,
233
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
234
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
235
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
236
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
237
-				$readOnlyPropertyName => $readOnly,
238
-			];
239
-
240
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
241
-		}
242
-		$result->closeCursor();
243
-
244
-		return array_values($addressBooks);
245
-	}
246
-
247
-	public function getUsersOwnAddressBooks($principalUri) {
248
-		$principalUri = $this->convertPrincipal($principalUri, true);
249
-		$query = $this->db->getQueryBuilder();
250
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
251
-			->from('addressbooks')
252
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
253
-
254
-		$addressBooks = [];
255
-
256
-		$result = $query->execute();
257
-		while ($row = $result->fetch()) {
258
-			$addressBooks[$row['id']] = [
259
-				'id' => $row['id'],
260
-				'uri' => $row['uri'],
261
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
262
-				'{DAV:}displayname' => $row['displayname'],
263
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
264
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
265
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
266
-			];
267
-
268
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
269
-		}
270
-		$result->closeCursor();
271
-
272
-		return array_values($addressBooks);
273
-	}
274
-
275
-	private function getUserDisplayName($uid) {
276
-		if (!isset($this->userDisplayNames[$uid])) {
277
-			$user = $this->userManager->get($uid);
278
-
279
-			if ($user instanceof IUser) {
280
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
281
-			} else {
282
-				$this->userDisplayNames[$uid] = $uid;
283
-			}
284
-		}
285
-
286
-		return $this->userDisplayNames[$uid];
287
-	}
288
-
289
-	/**
290
-	 * @param int $addressBookId
291
-	 */
292
-	public function getAddressBookById($addressBookId) {
293
-		$query = $this->db->getQueryBuilder();
294
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
295
-			->from('addressbooks')
296
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
297
-			->execute();
298
-
299
-		$row = $result->fetch();
300
-		$result->closeCursor();
301
-		if ($row === false) {
302
-			return null;
303
-		}
304
-
305
-		$addressBook = [
306
-			'id' => $row['id'],
307
-			'uri' => $row['uri'],
308
-			'principaluri' => $row['principaluri'],
309
-			'{DAV:}displayname' => $row['displayname'],
310
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
311
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
312
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
313
-		];
314
-
315
-		$this->addOwnerPrincipal($addressBook);
316
-
317
-		return $addressBook;
318
-	}
319
-
320
-	/**
321
-	 * @param $addressBookUri
322
-	 * @return array|null
323
-	 */
324
-	public function getAddressBooksByUri($principal, $addressBookUri) {
325
-		$query = $this->db->getQueryBuilder();
326
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
327
-			->from('addressbooks')
328
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
329
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
330
-			->setMaxResults(1)
331
-			->execute();
332
-
333
-		$row = $result->fetch();
334
-		$result->closeCursor();
335
-		if ($row === false) {
336
-			return null;
337
-		}
338
-
339
-		$addressBook = [
340
-			'id' => $row['id'],
341
-			'uri' => $row['uri'],
342
-			'principaluri' => $row['principaluri'],
343
-			'{DAV:}displayname' => $row['displayname'],
344
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
345
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
346
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
347
-		];
348
-
349
-		$this->addOwnerPrincipal($addressBook);
350
-
351
-		return $addressBook;
352
-	}
353
-
354
-	/**
355
-	 * Updates properties for an address book.
356
-	 *
357
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
358
-	 * To do the actual updates, you must tell this object which properties
359
-	 * you're going to process with the handle() method.
360
-	 *
361
-	 * Calling the handle method is like telling the PropPatch object "I
362
-	 * promise I can handle updating this property".
363
-	 *
364
-	 * Read the PropPatch documentation for more info and examples.
365
-	 *
366
-	 * @param string $addressBookId
367
-	 * @param \Sabre\DAV\PropPatch $propPatch
368
-	 * @return void
369
-	 */
370
-	public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
371
-		$supportedProperties = [
372
-			'{DAV:}displayname',
373
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
374
-		];
375
-
376
-		$propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
377
-			$updates = [];
378
-			foreach ($mutations as $property => $newValue) {
379
-				switch ($property) {
380
-					case '{DAV:}displayname':
381
-						$updates['displayname'] = $newValue;
382
-						break;
383
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
384
-						$updates['description'] = $newValue;
385
-						break;
386
-				}
387
-			}
388
-			$query = $this->db->getQueryBuilder();
389
-			$query->update('addressbooks');
390
-
391
-			foreach ($updates as $key => $value) {
392
-				$query->set($key, $query->createNamedParameter($value));
393
-			}
394
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
395
-				->execute();
396
-
397
-			$this->addChange($addressBookId, "", 2);
398
-
399
-			$addressBookRow = $this->getAddressBookById((int)$addressBookId);
400
-			$shares = $this->getShares($addressBookId);
401
-			$this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
402
-
403
-			return true;
404
-		});
405
-	}
406
-
407
-	/**
408
-	 * Creates a new address book
409
-	 *
410
-	 * @param string $principalUri
411
-	 * @param string $url Just the 'basename' of the url.
412
-	 * @param array $properties
413
-	 * @return int
414
-	 * @throws BadRequest
415
-	 */
416
-	public function createAddressBook($principalUri, $url, array $properties) {
417
-		$values = [
418
-			'displayname' => null,
419
-			'description' => null,
420
-			'principaluri' => $principalUri,
421
-			'uri' => $url,
422
-			'synctoken' => 1
423
-		];
424
-
425
-		foreach ($properties as $property => $newValue) {
426
-			switch ($property) {
427
-				case '{DAV:}displayname':
428
-					$values['displayname'] = $newValue;
429
-					break;
430
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
431
-					$values['description'] = $newValue;
432
-					break;
433
-				default:
434
-					throw new BadRequest('Unknown property: ' . $property);
435
-			}
436
-		}
437
-
438
-		// Fallback to make sure the displayname is set. Some clients may refuse
439
-		// to work with addressbooks not having a displayname.
440
-		if (is_null($values['displayname'])) {
441
-			$values['displayname'] = $url;
442
-		}
443
-
444
-		$query = $this->db->getQueryBuilder();
445
-		$query->insert('addressbooks')
446
-			->values([
447
-				'uri' => $query->createParameter('uri'),
448
-				'displayname' => $query->createParameter('displayname'),
449
-				'description' => $query->createParameter('description'),
450
-				'principaluri' => $query->createParameter('principaluri'),
451
-				'synctoken' => $query->createParameter('synctoken'),
452
-			])
453
-			->setParameters($values)
454
-			->execute();
455
-
456
-		$addressBookId = $query->getLastInsertId();
457
-		$addressBookRow = $this->getAddressBookById($addressBookId);
458
-		$this->dispatcher->dispatchTyped(new AddressBookCreatedEvent((int)$addressBookId, $addressBookRow));
459
-
460
-		return $addressBookId;
461
-	}
462
-
463
-	/**
464
-	 * Deletes an entire addressbook and all its contents
465
-	 *
466
-	 * @param mixed $addressBookId
467
-	 * @return void
468
-	 */
469
-	public function deleteAddressBook($addressBookId) {
470
-		$addressBookData = $this->getAddressBookById($addressBookId);
471
-		$shares = $this->getShares($addressBookId);
472
-
473
-		$query = $this->db->getQueryBuilder();
474
-		$query->delete($this->dbCardsTable)
475
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
476
-			->setParameter('addressbookid', $addressBookId)
477
-			->execute();
478
-
479
-		$query->delete('addressbookchanges')
480
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
481
-			->setParameter('addressbookid', $addressBookId)
482
-			->execute();
483
-
484
-		$query->delete('addressbooks')
485
-			->where($query->expr()->eq('id', $query->createParameter('id')))
486
-			->setParameter('id', $addressBookId)
487
-			->execute();
488
-
489
-		$this->sharingBackend->deleteAllShares($addressBookId);
490
-
491
-		$query->delete($this->dbCardsPropertiesTable)
492
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
493
-			->execute();
494
-
495
-		if ($addressBookData) {
496
-			$this->dispatcher->dispatchTyped(new AddressBookDeletedEvent((int) $addressBookId, $addressBookData, $shares));
497
-		}
498
-	}
499
-
500
-	/**
501
-	 * Returns all cards for a specific addressbook id.
502
-	 *
503
-	 * This method should return the following properties for each card:
504
-	 *   * carddata - raw vcard data
505
-	 *   * uri - Some unique url
506
-	 *   * lastmodified - A unix timestamp
507
-	 *
508
-	 * It's recommended to also return the following properties:
509
-	 *   * etag - A unique etag. This must change every time the card changes.
510
-	 *   * size - The size of the card in bytes.
511
-	 *
512
-	 * If these last two properties are provided, less time will be spent
513
-	 * calculating them. If they are specified, you can also ommit carddata.
514
-	 * This may speed up certain requests, especially with large cards.
515
-	 *
516
-	 * @param mixed $addressBookId
517
-	 * @return array
518
-	 */
519
-	public function getCards($addressBookId) {
520
-		$query = $this->db->getQueryBuilder();
521
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
522
-			->from($this->dbCardsTable)
523
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
524
-
525
-		$cards = [];
526
-
527
-		$result = $query->execute();
528
-		while ($row = $result->fetch()) {
529
-			$row['etag'] = '"' . $row['etag'] . '"';
530
-
531
-			$modified = false;
532
-			$row['carddata'] = $this->readBlob($row['carddata'], $modified);
533
-			if ($modified) {
534
-				$row['size'] = strlen($row['carddata']);
535
-			}
536
-
537
-			$cards[] = $row;
538
-		}
539
-		$result->closeCursor();
540
-
541
-		return $cards;
542
-	}
543
-
544
-	/**
545
-	 * Returns a specific card.
546
-	 *
547
-	 * The same set of properties must be returned as with getCards. The only
548
-	 * exception is that 'carddata' is absolutely required.
549
-	 *
550
-	 * If the card does not exist, you must return false.
551
-	 *
552
-	 * @param mixed $addressBookId
553
-	 * @param string $cardUri
554
-	 * @return array
555
-	 */
556
-	public function getCard($addressBookId, $cardUri) {
557
-		$query = $this->db->getQueryBuilder();
558
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
559
-			->from($this->dbCardsTable)
560
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
561
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
562
-			->setMaxResults(1);
563
-
564
-		$result = $query->execute();
565
-		$row = $result->fetch();
566
-		if (!$row) {
567
-			return false;
568
-		}
569
-		$row['etag'] = '"' . $row['etag'] . '"';
570
-
571
-		$modified = false;
572
-		$row['carddata'] = $this->readBlob($row['carddata'], $modified);
573
-		if ($modified) {
574
-			$row['size'] = strlen($row['carddata']);
575
-		}
576
-
577
-		return $row;
578
-	}
579
-
580
-	/**
581
-	 * Returns a list of cards.
582
-	 *
583
-	 * This method should work identical to getCard, but instead return all the
584
-	 * cards in the list as an array.
585
-	 *
586
-	 * If the backend supports this, it may allow for some speed-ups.
587
-	 *
588
-	 * @param mixed $addressBookId
589
-	 * @param string[] $uris
590
-	 * @return array
591
-	 */
592
-	public function getMultipleCards($addressBookId, array $uris) {
593
-		if (empty($uris)) {
594
-			return [];
595
-		}
596
-
597
-		$chunks = array_chunk($uris, 100);
598
-		$cards = [];
599
-
600
-		$query = $this->db->getQueryBuilder();
601
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
602
-			->from($this->dbCardsTable)
603
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
604
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
605
-
606
-		foreach ($chunks as $uris) {
607
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
608
-			$result = $query->execute();
609
-
610
-			while ($row = $result->fetch()) {
611
-				$row['etag'] = '"' . $row['etag'] . '"';
612
-
613
-				$modified = false;
614
-				$row['carddata'] = $this->readBlob($row['carddata'], $modified);
615
-				if ($modified) {
616
-					$row['size'] = strlen($row['carddata']);
617
-				}
618
-
619
-				$cards[] = $row;
620
-			}
621
-			$result->closeCursor();
622
-		}
623
-		return $cards;
624
-	}
625
-
626
-	/**
627
-	 * Creates a new card.
628
-	 *
629
-	 * The addressbook id will be passed as the first argument. This is the
630
-	 * same id as it is returned from the getAddressBooksForUser method.
631
-	 *
632
-	 * The cardUri is a base uri, and doesn't include the full path. The
633
-	 * cardData argument is the vcard body, and is passed as a string.
634
-	 *
635
-	 * It is possible to return an ETag from this method. This ETag is for the
636
-	 * newly created resource, and must be enclosed with double quotes (that
637
-	 * is, the string itself must contain the double quotes).
638
-	 *
639
-	 * You should only return the ETag if you store the carddata as-is. If a
640
-	 * subsequent GET request on the same card does not have the same body,
641
-	 * byte-by-byte and you did return an ETag here, clients tend to get
642
-	 * confused.
643
-	 *
644
-	 * If you don't return an ETag, you can just return null.
645
-	 *
646
-	 * @param mixed $addressBookId
647
-	 * @param string $cardUri
648
-	 * @param string $cardData
649
-	 * @return string
650
-	 */
651
-	public function createCard($addressBookId, $cardUri, $cardData) {
652
-		$etag = md5($cardData);
653
-		$uid = $this->getUID($cardData);
654
-
655
-		$q = $this->db->getQueryBuilder();
656
-		$q->select('uid')
657
-			->from($this->dbCardsTable)
658
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
659
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
660
-			->setMaxResults(1);
661
-		$result = $q->execute();
662
-		$count = (bool)$result->fetchColumn();
663
-		$result->closeCursor();
664
-		if ($count) {
665
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
666
-		}
667
-
668
-		$query = $this->db->getQueryBuilder();
669
-		$query->insert('cards')
670
-			->values([
671
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
672
-				'uri' => $query->createNamedParameter($cardUri),
673
-				'lastmodified' => $query->createNamedParameter(time()),
674
-				'addressbookid' => $query->createNamedParameter($addressBookId),
675
-				'size' => $query->createNamedParameter(strlen($cardData)),
676
-				'etag' => $query->createNamedParameter($etag),
677
-				'uid' => $query->createNamedParameter($uid),
678
-			])
679
-			->execute();
680
-
681
-		$etagCacheKey = "$addressBookId#$cardUri";
682
-		$this->etagCache[$etagCacheKey] = $etag;
683
-
684
-		$this->addChange($addressBookId, $cardUri, 1);
685
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
686
-
687
-		$addressBookData = $this->getAddressBookById($addressBookId);
688
-		$shares = $this->getShares($addressBookId);
689
-		$objectRow = $this->getCard($addressBookId, $cardUri);
690
-		$this->dispatcher->dispatchTyped(new CardCreatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
691
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
692
-			new GenericEvent(null, [
693
-				'addressBookId' => $addressBookId,
694
-				'cardUri' => $cardUri,
695
-				'cardData' => $cardData]));
696
-
697
-		return '"' . $etag . '"';
698
-	}
699
-
700
-	/**
701
-	 * Updates a card.
702
-	 *
703
-	 * The addressbook id will be passed as the first argument. This is the
704
-	 * same id as it is returned from the getAddressBooksForUser method.
705
-	 *
706
-	 * The cardUri is a base uri, and doesn't include the full path. The
707
-	 * cardData argument is the vcard body, and is passed as a string.
708
-	 *
709
-	 * It is possible to return an ETag from this method. This ETag should
710
-	 * match that of the updated resource, and must be enclosed with double
711
-	 * quotes (that is: the string itself must contain the actual quotes).
712
-	 *
713
-	 * You should only return the ETag if you store the carddata as-is. If a
714
-	 * subsequent GET request on the same card does not have the same body,
715
-	 * byte-by-byte and you did return an ETag here, clients tend to get
716
-	 * confused.
717
-	 *
718
-	 * If you don't return an ETag, you can just return null.
719
-	 *
720
-	 * @param mixed $addressBookId
721
-	 * @param string $cardUri
722
-	 * @param string $cardData
723
-	 * @return string
724
-	 */
725
-	public function updateCard($addressBookId, $cardUri, $cardData) {
726
-		$uid = $this->getUID($cardData);
727
-		$etag = md5($cardData);
728
-		$query = $this->db->getQueryBuilder();
729
-
730
-		// check for recently stored etag and stop if it is the same
731
-		$etagCacheKey = "$addressBookId#$cardUri";
732
-		if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
733
-			return '"' . $etag . '"';
734
-		}
735
-
736
-		$query->update($this->dbCardsTable)
737
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
738
-			->set('lastmodified', $query->createNamedParameter(time()))
739
-			->set('size', $query->createNamedParameter(strlen($cardData)))
740
-			->set('etag', $query->createNamedParameter($etag))
741
-			->set('uid', $query->createNamedParameter($uid))
742
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
743
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
744
-			->execute();
745
-
746
-		$this->etagCache[$etagCacheKey] = $etag;
747
-
748
-		$this->addChange($addressBookId, $cardUri, 2);
749
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
750
-
751
-		$addressBookData = $this->getAddressBookById($addressBookId);
752
-		$shares = $this->getShares($addressBookId);
753
-		$objectRow = $this->getCard($addressBookId, $cardUri);
754
-		$this->dispatcher->dispatchTyped(new CardUpdatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
755
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
756
-			new GenericEvent(null, [
757
-				'addressBookId' => $addressBookId,
758
-				'cardUri' => $cardUri,
759
-				'cardData' => $cardData]));
760
-
761
-		return '"' . $etag . '"';
762
-	}
763
-
764
-	/**
765
-	 * Deletes a card
766
-	 *
767
-	 * @param mixed $addressBookId
768
-	 * @param string $cardUri
769
-	 * @return bool
770
-	 */
771
-	public function deleteCard($addressBookId, $cardUri) {
772
-		$addressBookData = $this->getAddressBookById($addressBookId);
773
-		$shares = $this->getShares($addressBookId);
774
-		$objectRow = $this->getCard($addressBookId, $cardUri);
775
-
776
-		try {
777
-			$cardId = $this->getCardId($addressBookId, $cardUri);
778
-		} catch (\InvalidArgumentException $e) {
779
-			$cardId = null;
780
-		}
781
-		$query = $this->db->getQueryBuilder();
782
-		$ret = $query->delete($this->dbCardsTable)
783
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
784
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
785
-			->execute();
786
-
787
-		$this->addChange($addressBookId, $cardUri, 3);
788
-
789
-		if ($ret === 1) {
790
-			if ($cardId !== null) {
791
-				$this->dispatcher->dispatchTyped(new CardDeletedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
792
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
793
-					new GenericEvent(null, [
794
-						'addressBookId' => $addressBookId,
795
-						'cardUri' => $cardUri]));
796
-
797
-				$this->purgeProperties($addressBookId, $cardId);
798
-			}
799
-			return true;
800
-		}
801
-
802
-		return false;
803
-	}
804
-
805
-	/**
806
-	 * The getChanges method returns all the changes that have happened, since
807
-	 * the specified syncToken in the specified address book.
808
-	 *
809
-	 * This function should return an array, such as the following:
810
-	 *
811
-	 * [
812
-	 *   'syncToken' => 'The current synctoken',
813
-	 *   'added'   => [
814
-	 *      'new.txt',
815
-	 *   ],
816
-	 *   'modified'   => [
817
-	 *      'modified.txt',
818
-	 *   ],
819
-	 *   'deleted' => [
820
-	 *      'foo.php.bak',
821
-	 *      'old.txt'
822
-	 *   ]
823
-	 * ];
824
-	 *
825
-	 * The returned syncToken property should reflect the *current* syncToken
826
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
827
-	 * property. This is needed here too, to ensure the operation is atomic.
828
-	 *
829
-	 * If the $syncToken argument is specified as null, this is an initial
830
-	 * sync, and all members should be reported.
831
-	 *
832
-	 * The modified property is an array of nodenames that have changed since
833
-	 * the last token.
834
-	 *
835
-	 * The deleted property is an array with nodenames, that have been deleted
836
-	 * from collection.
837
-	 *
838
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
839
-	 * 1, you only have to report changes that happened only directly in
840
-	 * immediate descendants. If it's 2, it should also include changes from
841
-	 * the nodes below the child collections. (grandchildren)
842
-	 *
843
-	 * The $limit argument allows a client to specify how many results should
844
-	 * be returned at most. If the limit is not specified, it should be treated
845
-	 * as infinite.
846
-	 *
847
-	 * If the limit (infinite or not) is higher than you're willing to return,
848
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
849
-	 *
850
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
851
-	 * return null.
852
-	 *
853
-	 * The limit is 'suggestive'. You are free to ignore it.
854
-	 *
855
-	 * @param string $addressBookId
856
-	 * @param string $syncToken
857
-	 * @param int $syncLevel
858
-	 * @param int $limit
859
-	 * @return array
860
-	 */
861
-	public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
862
-		// Current synctoken
863
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
864
-		$stmt->execute([$addressBookId]);
865
-		$currentToken = $stmt->fetchColumn(0);
866
-
867
-		if (is_null($currentToken)) {
868
-			return null;
869
-		}
870
-
871
-		$result = [
872
-			'syncToken' => $currentToken,
873
-			'added' => [],
874
-			'modified' => [],
875
-			'deleted' => [],
876
-		];
877
-
878
-		if ($syncToken) {
879
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
880
-			if ($limit > 0) {
881
-				$query .= " LIMIT " . (int)$limit;
882
-			}
883
-
884
-			// Fetching all changes
885
-			$stmt = $this->db->prepare($query);
886
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
887
-
888
-			$changes = [];
889
-
890
-			// This loop ensures that any duplicates are overwritten, only the
891
-			// last change on a node is relevant.
892
-			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
893
-				$changes[$row['uri']] = $row['operation'];
894
-			}
895
-
896
-			foreach ($changes as $uri => $operation) {
897
-				switch ($operation) {
898
-					case 1:
899
-						$result['added'][] = $uri;
900
-						break;
901
-					case 2:
902
-						$result['modified'][] = $uri;
903
-						break;
904
-					case 3:
905
-						$result['deleted'][] = $uri;
906
-						break;
907
-				}
908
-			}
909
-		} else {
910
-			// No synctoken supplied, this is the initial sync.
911
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
912
-			$stmt = $this->db->prepare($query);
913
-			$stmt->execute([$addressBookId]);
914
-
915
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
916
-		}
917
-		return $result;
918
-	}
919
-
920
-	/**
921
-	 * Adds a change record to the addressbookchanges table.
922
-	 *
923
-	 * @param mixed $addressBookId
924
-	 * @param string $objectUri
925
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
926
-	 * @return void
927
-	 */
928
-	protected function addChange($addressBookId, $objectUri, $operation) {
929
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
930
-		$stmt = $this->db->prepare($sql);
931
-		$stmt->execute([
932
-			$objectUri,
933
-			$addressBookId,
934
-			$operation,
935
-			$addressBookId
936
-		]);
937
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
938
-		$stmt->execute([
939
-			$addressBookId
940
-		]);
941
-	}
942
-
943
-	/**
944
-	 * @param resource|string $cardData
945
-	 * @param bool $modified
946
-	 * @return string
947
-	 */
948
-	private function readBlob($cardData, &$modified = false) {
949
-		if (is_resource($cardData)) {
950
-			$cardData = stream_get_contents($cardData);
951
-		}
952
-
953
-		$cardDataArray = explode("\r\n", $cardData);
954
-
955
-		$cardDataFiltered = [];
956
-		$removingPhoto = false;
957
-		foreach ($cardDataArray as $line) {
958
-			if (strpos($line, 'PHOTO:data:') === 0
959
-				&& strpos($line, 'PHOTO:data:image/') !== 0) {
960
-				// Filter out PHOTO data of non-images
961
-				$removingPhoto = true;
962
-				$modified = true;
963
-				continue;
964
-			}
965
-
966
-			if ($removingPhoto) {
967
-				if (strpos($line, ' ') === 0) {
968
-					continue;
969
-				}
970
-				// No leading space means this is a new property
971
-				$removingPhoto = false;
972
-			}
973
-
974
-			$cardDataFiltered[] = $line;
975
-		}
976
-
977
-		return implode("\r\n", $cardDataFiltered);
978
-	}
979
-
980
-	/**
981
-	 * @param IShareable $shareable
982
-	 * @param string[] $add
983
-	 * @param string[] $remove
984
-	 */
985
-	public function updateShares(IShareable $shareable, $add, $remove) {
986
-		$addressBookId = $shareable->getResourceId();
987
-		$addressBookData = $this->getAddressBookById($addressBookId);
988
-		$oldShares = $this->getShares($addressBookId);
989
-
990
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
991
-
992
-		$this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
993
-	}
994
-
995
-	/**
996
-	 * Search contacts in a specific address-book
997
-	 *
998
-	 * @param int $addressBookId
999
-	 * @param string $pattern which should match within the $searchProperties
1000
-	 * @param array $searchProperties defines the properties within the query pattern should match
1001
-	 * @param array $options = array() to define the search behavior
1002
-	 *    - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
1003
-	 *    - 'limit' - Set a numeric limit for the search results
1004
-	 *    - 'offset' - Set the offset for the limited search results
1005
-	 * @return array an array of contacts which are arrays of key-value-pairs
1006
-	 */
1007
-	public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
1008
-		return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
1009
-	}
1010
-
1011
-	/**
1012
-	 * Search contacts in all address-books accessible by a user
1013
-	 *
1014
-	 * @param string $principalUri
1015
-	 * @param string $pattern
1016
-	 * @param array $searchProperties
1017
-	 * @param array $options
1018
-	 * @return array
1019
-	 */
1020
-	public function searchPrincipalUri(string $principalUri,
1021
-									   string $pattern,
1022
-									   array $searchProperties,
1023
-									   array $options = []): array {
1024
-		$addressBookIds = array_map(static function ($row):int {
1025
-			return (int) $row['id'];
1026
-		}, $this->getAddressBooksForUser($principalUri));
1027
-
1028
-		return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
1029
-	}
1030
-
1031
-	/**
1032
-	 * @param array $addressBookIds
1033
-	 * @param string $pattern
1034
-	 * @param array $searchProperties
1035
-	 * @param array $options
1036
-	 * @return array
1037
-	 */
1038
-	private function searchByAddressBookIds(array $addressBookIds,
1039
-											string $pattern,
1040
-											array $searchProperties,
1041
-											array $options = []): array {
1042
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1043
-
1044
-		$query2 = $this->db->getQueryBuilder();
1045
-
1046
-		$addressBookOr = $query2->expr()->orX();
1047
-		foreach ($addressBookIds as $addressBookId) {
1048
-			$addressBookOr->add($query2->expr()->eq('cp.addressbookid', $query2->createNamedParameter($addressBookId)));
1049
-		}
1050
-
1051
-		if ($addressBookOr->count() === 0) {
1052
-			return [];
1053
-		}
1054
-
1055
-		$propertyOr = $query2->expr()->orX();
1056
-		foreach ($searchProperties as $property) {
1057
-			if ($escapePattern) {
1058
-				if ($property === 'EMAIL' && strpos($pattern, ' ') !== false) {
1059
-					// There can be no spaces in emails
1060
-					continue;
1061
-				}
1062
-
1063
-				if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
1064
-					// There can be no chars in cloud ids which are not valid for user ids plus :/
1065
-					// worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
1066
-					continue;
1067
-				}
1068
-			}
1069
-
1070
-			$propertyOr->add($query2->expr()->eq('cp.name', $query2->createNamedParameter($property)));
1071
-		}
1072
-
1073
-		if ($propertyOr->count() === 0) {
1074
-			return [];
1075
-		}
1076
-
1077
-		$query2->selectDistinct('cp.cardid')
1078
-			->from($this->dbCardsPropertiesTable, 'cp')
1079
-			->andWhere($addressBookOr)
1080
-			->andWhere($propertyOr);
1081
-
1082
-		// No need for like when the pattern is empty
1083
-		if ('' !== $pattern) {
1084
-			if (!$escapePattern) {
1085
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
1086
-			} else {
1087
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1088
-			}
1089
-		}
1090
-
1091
-		if (isset($options['limit'])) {
1092
-			$query2->setMaxResults($options['limit']);
1093
-		}
1094
-		if (isset($options['offset'])) {
1095
-			$query2->setFirstResult($options['offset']);
1096
-		}
1097
-
1098
-		$result = $query2->execute();
1099
-		$matches = $result->fetchAll();
1100
-		$result->closeCursor();
1101
-		$matches = array_map(function ($match) {
1102
-			return (int)$match['cardid'];
1103
-		}, $matches);
1104
-
1105
-		$query = $this->db->getQueryBuilder();
1106
-		$query->select('c.addressbookid', 'c.carddata', 'c.uri')
1107
-			->from($this->dbCardsTable, 'c')
1108
-			->where($query->expr()->in('c.id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1109
-
1110
-		$result = $query->execute();
1111
-		$cards = $result->fetchAll();
1112
-
1113
-		$result->closeCursor();
1114
-
1115
-		return array_map(function ($array) {
1116
-			$array['addressbookid'] = (int) $array['addressbookid'];
1117
-			$modified = false;
1118
-			$array['carddata'] = $this->readBlob($array['carddata'], $modified);
1119
-			if ($modified) {
1120
-				$array['size'] = strlen($array['carddata']);
1121
-			}
1122
-			return $array;
1123
-		}, $cards);
1124
-	}
1125
-
1126
-	/**
1127
-	 * @param int $bookId
1128
-	 * @param string $name
1129
-	 * @return array
1130
-	 */
1131
-	public function collectCardProperties($bookId, $name) {
1132
-		$query = $this->db->getQueryBuilder();
1133
-		$result = $query->selectDistinct('value')
1134
-			->from($this->dbCardsPropertiesTable)
1135
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
1136
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
1137
-			->execute();
1138
-
1139
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
1140
-		$result->closeCursor();
1141
-
1142
-		return $all;
1143
-	}
1144
-
1145
-	/**
1146
-	 * get URI from a given contact
1147
-	 *
1148
-	 * @param int $id
1149
-	 * @return string
1150
-	 */
1151
-	public function getCardUri($id) {
1152
-		$query = $this->db->getQueryBuilder();
1153
-		$query->select('uri')->from($this->dbCardsTable)
1154
-			->where($query->expr()->eq('id', $query->createParameter('id')))
1155
-			->setParameter('id', $id);
1156
-
1157
-		$result = $query->execute();
1158
-		$uri = $result->fetch();
1159
-		$result->closeCursor();
1160
-
1161
-		if (!isset($uri['uri'])) {
1162
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
1163
-		}
1164
-
1165
-		return $uri['uri'];
1166
-	}
1167
-
1168
-	/**
1169
-	 * return contact with the given URI
1170
-	 *
1171
-	 * @param int $addressBookId
1172
-	 * @param string $uri
1173
-	 * @returns array
1174
-	 */
1175
-	public function getContact($addressBookId, $uri) {
1176
-		$result = [];
1177
-		$query = $this->db->getQueryBuilder();
1178
-		$query->select('*')->from($this->dbCardsTable)
1179
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1180
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1181
-		$queryResult = $query->execute();
1182
-		$contact = $queryResult->fetch();
1183
-		$queryResult->closeCursor();
1184
-
1185
-		if (is_array($contact)) {
1186
-			$modified = false;
1187
-			$contact['etag'] = '"' . $contact['etag'] . '"';
1188
-			$contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
1189
-			if ($modified) {
1190
-				$contact['size'] = strlen($contact['carddata']);
1191
-			}
1192
-
1193
-			$result = $contact;
1194
-		}
1195
-
1196
-		return $result;
1197
-	}
1198
-
1199
-	/**
1200
-	 * Returns the list of people whom this address book is shared with.
1201
-	 *
1202
-	 * Every element in this array should have the following properties:
1203
-	 *   * href - Often a mailto: address
1204
-	 *   * commonName - Optional, for example a first + last name
1205
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1206
-	 *   * readOnly - boolean
1207
-	 *   * summary - Optional, a description for the share
1208
-	 *
1209
-	 * @return array
1210
-	 */
1211
-	public function getShares($addressBookId) {
1212
-		return $this->sharingBackend->getShares($addressBookId);
1213
-	}
1214
-
1215
-	/**
1216
-	 * update properties table
1217
-	 *
1218
-	 * @param int $addressBookId
1219
-	 * @param string $cardUri
1220
-	 * @param string $vCardSerialized
1221
-	 */
1222
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1223
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1224
-		$vCard = $this->readCard($vCardSerialized);
1225
-
1226
-		$this->purgeProperties($addressBookId, $cardId);
1227
-
1228
-		$query = $this->db->getQueryBuilder();
1229
-		$query->insert($this->dbCardsPropertiesTable)
1230
-			->values(
1231
-				[
1232
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1233
-					'cardid' => $query->createNamedParameter($cardId),
1234
-					'name' => $query->createParameter('name'),
1235
-					'value' => $query->createParameter('value'),
1236
-					'preferred' => $query->createParameter('preferred')
1237
-				]
1238
-			);
1239
-
1240
-		foreach ($vCard->children() as $property) {
1241
-			if (!in_array($property->name, self::$indexProperties)) {
1242
-				continue;
1243
-			}
1244
-			$preferred = 0;
1245
-			foreach ($property->parameters as $parameter) {
1246
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1247
-					$preferred = 1;
1248
-					break;
1249
-				}
1250
-			}
1251
-			$query->setParameter('name', $property->name);
1252
-			$query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1253
-			$query->setParameter('preferred', $preferred);
1254
-			$query->execute();
1255
-		}
1256
-	}
1257
-
1258
-	/**
1259
-	 * read vCard data into a vCard object
1260
-	 *
1261
-	 * @param string $cardData
1262
-	 * @return VCard
1263
-	 */
1264
-	protected function readCard($cardData) {
1265
-		return Reader::read($cardData);
1266
-	}
1267
-
1268
-	/**
1269
-	 * delete all properties from a given card
1270
-	 *
1271
-	 * @param int $addressBookId
1272
-	 * @param int $cardId
1273
-	 */
1274
-	protected function purgeProperties($addressBookId, $cardId) {
1275
-		$query = $this->db->getQueryBuilder();
1276
-		$query->delete($this->dbCardsPropertiesTable)
1277
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1278
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1279
-		$query->execute();
1280
-	}
1281
-
1282
-	/**
1283
-	 * get ID from a given contact
1284
-	 *
1285
-	 * @param int $addressBookId
1286
-	 * @param string $uri
1287
-	 * @return int
1288
-	 */
1289
-	protected function getCardId($addressBookId, $uri) {
1290
-		$query = $this->db->getQueryBuilder();
1291
-		$query->select('id')->from($this->dbCardsTable)
1292
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1293
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1294
-
1295
-		$result = $query->execute();
1296
-		$cardIds = $result->fetch();
1297
-		$result->closeCursor();
1298
-
1299
-		if (!isset($cardIds['id'])) {
1300
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1301
-		}
1302
-
1303
-		return (int)$cardIds['id'];
1304
-	}
1305
-
1306
-	/**
1307
-	 * For shared address books the sharee is set in the ACL of the address book
1308
-	 *
1309
-	 * @param $addressBookId
1310
-	 * @param $acl
1311
-	 * @return array
1312
-	 */
1313
-	public function applyShareAcl($addressBookId, $acl) {
1314
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1315
-	}
1316
-
1317
-	private function convertPrincipal($principalUri, $toV2) {
1318
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1319
-			list(, $name) = \Sabre\Uri\split($principalUri);
1320
-			if ($toV2 === true) {
1321
-				return "principals/users/$name";
1322
-			}
1323
-			return "principals/$name";
1324
-		}
1325
-		return $principalUri;
1326
-	}
1327
-
1328
-	private function addOwnerPrincipal(&$addressbookInfo) {
1329
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1330
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1331
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1332
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1333
-		} else {
1334
-			$uri = $addressbookInfo['principaluri'];
1335
-		}
1336
-
1337
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1338
-		if (isset($principalInformation['{DAV:}displayname'])) {
1339
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1340
-		}
1341
-	}
1342
-
1343
-	/**
1344
-	 * Extract UID from vcard
1345
-	 *
1346
-	 * @param string $cardData the vcard raw data
1347
-	 * @return string the uid
1348
-	 * @throws BadRequest if no UID is available
1349
-	 */
1350
-	private function getUID($cardData) {
1351
-		if ($cardData != '') {
1352
-			$vCard = Reader::read($cardData);
1353
-			if ($vCard->UID) {
1354
-				$uid = $vCard->UID->getValue();
1355
-				return $uid;
1356
-			}
1357
-			// should already be handled, but just in case
1358
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1359
-		}
1360
-		// should already be handled, but just in case
1361
-		throw new BadRequest('vCard can not be empty');
1362
-	}
64
+    public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
65
+    public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
66
+
67
+    /** @var Principal */
68
+    private $principalBackend;
69
+
70
+    /** @var string */
71
+    private $dbCardsTable = 'cards';
72
+
73
+    /** @var string */
74
+    private $dbCardsPropertiesTable = 'cards_properties';
75
+
76
+    /** @var IDBConnection */
77
+    private $db;
78
+
79
+    /** @var Backend */
80
+    private $sharingBackend;
81
+
82
+    /** @var array properties to index */
83
+    public static $indexProperties = [
84
+        'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
85
+        'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
86
+
87
+    /**
88
+     * @var string[] Map of uid => display name
89
+     */
90
+    protected $userDisplayNames;
91
+
92
+    /** @var IUserManager */
93
+    private $userManager;
94
+
95
+    /** @var IEventDispatcher */
96
+    private $dispatcher;
97
+
98
+    /** @var EventDispatcherInterface */
99
+    private $legacyDispatcher;
100
+
101
+    private $etagCache = [];
102
+
103
+    /**
104
+     * CardDavBackend constructor.
105
+     *
106
+     * @param IDBConnection $db
107
+     * @param Principal $principalBackend
108
+     * @param IUserManager $userManager
109
+     * @param IGroupManager $groupManager
110
+     * @param IEventDispatcher $dispatcher
111
+     * @param EventDispatcherInterface $legacyDispatcher
112
+     */
113
+    public function __construct(IDBConnection $db,
114
+                                Principal $principalBackend,
115
+                                IUserManager $userManager,
116
+                                IGroupManager $groupManager,
117
+                                IEventDispatcher $dispatcher,
118
+                                EventDispatcherInterface $legacyDispatcher) {
119
+        $this->db = $db;
120
+        $this->principalBackend = $principalBackend;
121
+        $this->userManager = $userManager;
122
+        $this->dispatcher = $dispatcher;
123
+        $this->legacyDispatcher = $legacyDispatcher;
124
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
125
+    }
126
+
127
+    /**
128
+     * Return the number of address books for a principal
129
+     *
130
+     * @param $principalUri
131
+     * @return int
132
+     */
133
+    public function getAddressBooksForUserCount($principalUri) {
134
+        $principalUri = $this->convertPrincipal($principalUri, true);
135
+        $query = $this->db->getQueryBuilder();
136
+        $query->select($query->func()->count('*'))
137
+            ->from('addressbooks')
138
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
139
+
140
+        $result = $query->execute();
141
+        $column = (int) $result->fetchColumn();
142
+        $result->closeCursor();
143
+        return $column;
144
+    }
145
+
146
+    /**
147
+     * Returns the list of address books for a specific user.
148
+     *
149
+     * Every addressbook should have the following properties:
150
+     *   id - an arbitrary unique id
151
+     *   uri - the 'basename' part of the url
152
+     *   principaluri - Same as the passed parameter
153
+     *
154
+     * Any additional clark-notation property may be passed besides this. Some
155
+     * common ones are :
156
+     *   {DAV:}displayname
157
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
158
+     *   {http://calendarserver.org/ns/}getctag
159
+     *
160
+     * @param string $principalUri
161
+     * @return array
162
+     */
163
+    public function getAddressBooksForUser($principalUri) {
164
+        $principalUriOriginal = $principalUri;
165
+        $principalUri = $this->convertPrincipal($principalUri, true);
166
+        $query = $this->db->getQueryBuilder();
167
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
168
+            ->from('addressbooks')
169
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
170
+
171
+        $addressBooks = [];
172
+
173
+        $result = $query->execute();
174
+        while ($row = $result->fetch()) {
175
+            $addressBooks[$row['id']] = [
176
+                'id' => $row['id'],
177
+                'uri' => $row['uri'],
178
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
179
+                '{DAV:}displayname' => $row['displayname'],
180
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
181
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
182
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
183
+            ];
184
+
185
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
186
+        }
187
+        $result->closeCursor();
188
+
189
+        // query for shared addressbooks
190
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
191
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
192
+
193
+        $principals[] = $principalUri;
194
+
195
+        $query = $this->db->getQueryBuilder();
196
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
197
+            ->from('dav_shares', 's')
198
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
199
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
200
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
201
+            ->setParameter('type', 'addressbook')
202
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
203
+            ->execute();
204
+
205
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
206
+        while ($row = $result->fetch()) {
207
+            if ($row['principaluri'] === $principalUri) {
208
+                continue;
209
+            }
210
+
211
+            $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
212
+            if (isset($addressBooks[$row['id']])) {
213
+                if ($readOnly) {
214
+                    // New share can not have more permissions then the old one.
215
+                    continue;
216
+                }
217
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
218
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
219
+                    // Old share is already read-write, no more permissions can be gained
220
+                    continue;
221
+                }
222
+            }
223
+
224
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
225
+            $uri = $row['uri'] . '_shared_by_' . $name;
226
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
227
+
228
+            $addressBooks[$row['id']] = [
229
+                'id' => $row['id'],
230
+                'uri' => $uri,
231
+                'principaluri' => $principalUriOriginal,
232
+                '{DAV:}displayname' => $displayName,
233
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
234
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
235
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
236
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
237
+                $readOnlyPropertyName => $readOnly,
238
+            ];
239
+
240
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
241
+        }
242
+        $result->closeCursor();
243
+
244
+        return array_values($addressBooks);
245
+    }
246
+
247
+    public function getUsersOwnAddressBooks($principalUri) {
248
+        $principalUri = $this->convertPrincipal($principalUri, true);
249
+        $query = $this->db->getQueryBuilder();
250
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
251
+            ->from('addressbooks')
252
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
253
+
254
+        $addressBooks = [];
255
+
256
+        $result = $query->execute();
257
+        while ($row = $result->fetch()) {
258
+            $addressBooks[$row['id']] = [
259
+                'id' => $row['id'],
260
+                'uri' => $row['uri'],
261
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
262
+                '{DAV:}displayname' => $row['displayname'],
263
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
264
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
265
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
266
+            ];
267
+
268
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
269
+        }
270
+        $result->closeCursor();
271
+
272
+        return array_values($addressBooks);
273
+    }
274
+
275
+    private function getUserDisplayName($uid) {
276
+        if (!isset($this->userDisplayNames[$uid])) {
277
+            $user = $this->userManager->get($uid);
278
+
279
+            if ($user instanceof IUser) {
280
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
281
+            } else {
282
+                $this->userDisplayNames[$uid] = $uid;
283
+            }
284
+        }
285
+
286
+        return $this->userDisplayNames[$uid];
287
+    }
288
+
289
+    /**
290
+     * @param int $addressBookId
291
+     */
292
+    public function getAddressBookById($addressBookId) {
293
+        $query = $this->db->getQueryBuilder();
294
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
295
+            ->from('addressbooks')
296
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
297
+            ->execute();
298
+
299
+        $row = $result->fetch();
300
+        $result->closeCursor();
301
+        if ($row === false) {
302
+            return null;
303
+        }
304
+
305
+        $addressBook = [
306
+            'id' => $row['id'],
307
+            'uri' => $row['uri'],
308
+            'principaluri' => $row['principaluri'],
309
+            '{DAV:}displayname' => $row['displayname'],
310
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
311
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
312
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
313
+        ];
314
+
315
+        $this->addOwnerPrincipal($addressBook);
316
+
317
+        return $addressBook;
318
+    }
319
+
320
+    /**
321
+     * @param $addressBookUri
322
+     * @return array|null
323
+     */
324
+    public function getAddressBooksByUri($principal, $addressBookUri) {
325
+        $query = $this->db->getQueryBuilder();
326
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
327
+            ->from('addressbooks')
328
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
329
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
330
+            ->setMaxResults(1)
331
+            ->execute();
332
+
333
+        $row = $result->fetch();
334
+        $result->closeCursor();
335
+        if ($row === false) {
336
+            return null;
337
+        }
338
+
339
+        $addressBook = [
340
+            'id' => $row['id'],
341
+            'uri' => $row['uri'],
342
+            'principaluri' => $row['principaluri'],
343
+            '{DAV:}displayname' => $row['displayname'],
344
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
345
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
346
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
347
+        ];
348
+
349
+        $this->addOwnerPrincipal($addressBook);
350
+
351
+        return $addressBook;
352
+    }
353
+
354
+    /**
355
+     * Updates properties for an address book.
356
+     *
357
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
358
+     * To do the actual updates, you must tell this object which properties
359
+     * you're going to process with the handle() method.
360
+     *
361
+     * Calling the handle method is like telling the PropPatch object "I
362
+     * promise I can handle updating this property".
363
+     *
364
+     * Read the PropPatch documentation for more info and examples.
365
+     *
366
+     * @param string $addressBookId
367
+     * @param \Sabre\DAV\PropPatch $propPatch
368
+     * @return void
369
+     */
370
+    public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
371
+        $supportedProperties = [
372
+            '{DAV:}displayname',
373
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
374
+        ];
375
+
376
+        $propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
377
+            $updates = [];
378
+            foreach ($mutations as $property => $newValue) {
379
+                switch ($property) {
380
+                    case '{DAV:}displayname':
381
+                        $updates['displayname'] = $newValue;
382
+                        break;
383
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
384
+                        $updates['description'] = $newValue;
385
+                        break;
386
+                }
387
+            }
388
+            $query = $this->db->getQueryBuilder();
389
+            $query->update('addressbooks');
390
+
391
+            foreach ($updates as $key => $value) {
392
+                $query->set($key, $query->createNamedParameter($value));
393
+            }
394
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
395
+                ->execute();
396
+
397
+            $this->addChange($addressBookId, "", 2);
398
+
399
+            $addressBookRow = $this->getAddressBookById((int)$addressBookId);
400
+            $shares = $this->getShares($addressBookId);
401
+            $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
402
+
403
+            return true;
404
+        });
405
+    }
406
+
407
+    /**
408
+     * Creates a new address book
409
+     *
410
+     * @param string $principalUri
411
+     * @param string $url Just the 'basename' of the url.
412
+     * @param array $properties
413
+     * @return int
414
+     * @throws BadRequest
415
+     */
416
+    public function createAddressBook($principalUri, $url, array $properties) {
417
+        $values = [
418
+            'displayname' => null,
419
+            'description' => null,
420
+            'principaluri' => $principalUri,
421
+            'uri' => $url,
422
+            'synctoken' => 1
423
+        ];
424
+
425
+        foreach ($properties as $property => $newValue) {
426
+            switch ($property) {
427
+                case '{DAV:}displayname':
428
+                    $values['displayname'] = $newValue;
429
+                    break;
430
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
431
+                    $values['description'] = $newValue;
432
+                    break;
433
+                default:
434
+                    throw new BadRequest('Unknown property: ' . $property);
435
+            }
436
+        }
437
+
438
+        // Fallback to make sure the displayname is set. Some clients may refuse
439
+        // to work with addressbooks not having a displayname.
440
+        if (is_null($values['displayname'])) {
441
+            $values['displayname'] = $url;
442
+        }
443
+
444
+        $query = $this->db->getQueryBuilder();
445
+        $query->insert('addressbooks')
446
+            ->values([
447
+                'uri' => $query->createParameter('uri'),
448
+                'displayname' => $query->createParameter('displayname'),
449
+                'description' => $query->createParameter('description'),
450
+                'principaluri' => $query->createParameter('principaluri'),
451
+                'synctoken' => $query->createParameter('synctoken'),
452
+            ])
453
+            ->setParameters($values)
454
+            ->execute();
455
+
456
+        $addressBookId = $query->getLastInsertId();
457
+        $addressBookRow = $this->getAddressBookById($addressBookId);
458
+        $this->dispatcher->dispatchTyped(new AddressBookCreatedEvent((int)$addressBookId, $addressBookRow));
459
+
460
+        return $addressBookId;
461
+    }
462
+
463
+    /**
464
+     * Deletes an entire addressbook and all its contents
465
+     *
466
+     * @param mixed $addressBookId
467
+     * @return void
468
+     */
469
+    public function deleteAddressBook($addressBookId) {
470
+        $addressBookData = $this->getAddressBookById($addressBookId);
471
+        $shares = $this->getShares($addressBookId);
472
+
473
+        $query = $this->db->getQueryBuilder();
474
+        $query->delete($this->dbCardsTable)
475
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
476
+            ->setParameter('addressbookid', $addressBookId)
477
+            ->execute();
478
+
479
+        $query->delete('addressbookchanges')
480
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
481
+            ->setParameter('addressbookid', $addressBookId)
482
+            ->execute();
483
+
484
+        $query->delete('addressbooks')
485
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
486
+            ->setParameter('id', $addressBookId)
487
+            ->execute();
488
+
489
+        $this->sharingBackend->deleteAllShares($addressBookId);
490
+
491
+        $query->delete($this->dbCardsPropertiesTable)
492
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
493
+            ->execute();
494
+
495
+        if ($addressBookData) {
496
+            $this->dispatcher->dispatchTyped(new AddressBookDeletedEvent((int) $addressBookId, $addressBookData, $shares));
497
+        }
498
+    }
499
+
500
+    /**
501
+     * Returns all cards for a specific addressbook id.
502
+     *
503
+     * This method should return the following properties for each card:
504
+     *   * carddata - raw vcard data
505
+     *   * uri - Some unique url
506
+     *   * lastmodified - A unix timestamp
507
+     *
508
+     * It's recommended to also return the following properties:
509
+     *   * etag - A unique etag. This must change every time the card changes.
510
+     *   * size - The size of the card in bytes.
511
+     *
512
+     * If these last two properties are provided, less time will be spent
513
+     * calculating them. If they are specified, you can also ommit carddata.
514
+     * This may speed up certain requests, especially with large cards.
515
+     *
516
+     * @param mixed $addressBookId
517
+     * @return array
518
+     */
519
+    public function getCards($addressBookId) {
520
+        $query = $this->db->getQueryBuilder();
521
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
522
+            ->from($this->dbCardsTable)
523
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
524
+
525
+        $cards = [];
526
+
527
+        $result = $query->execute();
528
+        while ($row = $result->fetch()) {
529
+            $row['etag'] = '"' . $row['etag'] . '"';
530
+
531
+            $modified = false;
532
+            $row['carddata'] = $this->readBlob($row['carddata'], $modified);
533
+            if ($modified) {
534
+                $row['size'] = strlen($row['carddata']);
535
+            }
536
+
537
+            $cards[] = $row;
538
+        }
539
+        $result->closeCursor();
540
+
541
+        return $cards;
542
+    }
543
+
544
+    /**
545
+     * Returns a specific card.
546
+     *
547
+     * The same set of properties must be returned as with getCards. The only
548
+     * exception is that 'carddata' is absolutely required.
549
+     *
550
+     * If the card does not exist, you must return false.
551
+     *
552
+     * @param mixed $addressBookId
553
+     * @param string $cardUri
554
+     * @return array
555
+     */
556
+    public function getCard($addressBookId, $cardUri) {
557
+        $query = $this->db->getQueryBuilder();
558
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
559
+            ->from($this->dbCardsTable)
560
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
561
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
562
+            ->setMaxResults(1);
563
+
564
+        $result = $query->execute();
565
+        $row = $result->fetch();
566
+        if (!$row) {
567
+            return false;
568
+        }
569
+        $row['etag'] = '"' . $row['etag'] . '"';
570
+
571
+        $modified = false;
572
+        $row['carddata'] = $this->readBlob($row['carddata'], $modified);
573
+        if ($modified) {
574
+            $row['size'] = strlen($row['carddata']);
575
+        }
576
+
577
+        return $row;
578
+    }
579
+
580
+    /**
581
+     * Returns a list of cards.
582
+     *
583
+     * This method should work identical to getCard, but instead return all the
584
+     * cards in the list as an array.
585
+     *
586
+     * If the backend supports this, it may allow for some speed-ups.
587
+     *
588
+     * @param mixed $addressBookId
589
+     * @param string[] $uris
590
+     * @return array
591
+     */
592
+    public function getMultipleCards($addressBookId, array $uris) {
593
+        if (empty($uris)) {
594
+            return [];
595
+        }
596
+
597
+        $chunks = array_chunk($uris, 100);
598
+        $cards = [];
599
+
600
+        $query = $this->db->getQueryBuilder();
601
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
602
+            ->from($this->dbCardsTable)
603
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
604
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
605
+
606
+        foreach ($chunks as $uris) {
607
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
608
+            $result = $query->execute();
609
+
610
+            while ($row = $result->fetch()) {
611
+                $row['etag'] = '"' . $row['etag'] . '"';
612
+
613
+                $modified = false;
614
+                $row['carddata'] = $this->readBlob($row['carddata'], $modified);
615
+                if ($modified) {
616
+                    $row['size'] = strlen($row['carddata']);
617
+                }
618
+
619
+                $cards[] = $row;
620
+            }
621
+            $result->closeCursor();
622
+        }
623
+        return $cards;
624
+    }
625
+
626
+    /**
627
+     * Creates a new card.
628
+     *
629
+     * The addressbook id will be passed as the first argument. This is the
630
+     * same id as it is returned from the getAddressBooksForUser method.
631
+     *
632
+     * The cardUri is a base uri, and doesn't include the full path. The
633
+     * cardData argument is the vcard body, and is passed as a string.
634
+     *
635
+     * It is possible to return an ETag from this method. This ETag is for the
636
+     * newly created resource, and must be enclosed with double quotes (that
637
+     * is, the string itself must contain the double quotes).
638
+     *
639
+     * You should only return the ETag if you store the carddata as-is. If a
640
+     * subsequent GET request on the same card does not have the same body,
641
+     * byte-by-byte and you did return an ETag here, clients tend to get
642
+     * confused.
643
+     *
644
+     * If you don't return an ETag, you can just return null.
645
+     *
646
+     * @param mixed $addressBookId
647
+     * @param string $cardUri
648
+     * @param string $cardData
649
+     * @return string
650
+     */
651
+    public function createCard($addressBookId, $cardUri, $cardData) {
652
+        $etag = md5($cardData);
653
+        $uid = $this->getUID($cardData);
654
+
655
+        $q = $this->db->getQueryBuilder();
656
+        $q->select('uid')
657
+            ->from($this->dbCardsTable)
658
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
659
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
660
+            ->setMaxResults(1);
661
+        $result = $q->execute();
662
+        $count = (bool)$result->fetchColumn();
663
+        $result->closeCursor();
664
+        if ($count) {
665
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
666
+        }
667
+
668
+        $query = $this->db->getQueryBuilder();
669
+        $query->insert('cards')
670
+            ->values([
671
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
672
+                'uri' => $query->createNamedParameter($cardUri),
673
+                'lastmodified' => $query->createNamedParameter(time()),
674
+                'addressbookid' => $query->createNamedParameter($addressBookId),
675
+                'size' => $query->createNamedParameter(strlen($cardData)),
676
+                'etag' => $query->createNamedParameter($etag),
677
+                'uid' => $query->createNamedParameter($uid),
678
+            ])
679
+            ->execute();
680
+
681
+        $etagCacheKey = "$addressBookId#$cardUri";
682
+        $this->etagCache[$etagCacheKey] = $etag;
683
+
684
+        $this->addChange($addressBookId, $cardUri, 1);
685
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
686
+
687
+        $addressBookData = $this->getAddressBookById($addressBookId);
688
+        $shares = $this->getShares($addressBookId);
689
+        $objectRow = $this->getCard($addressBookId, $cardUri);
690
+        $this->dispatcher->dispatchTyped(new CardCreatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
691
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
692
+            new GenericEvent(null, [
693
+                'addressBookId' => $addressBookId,
694
+                'cardUri' => $cardUri,
695
+                'cardData' => $cardData]));
696
+
697
+        return '"' . $etag . '"';
698
+    }
699
+
700
+    /**
701
+     * Updates a card.
702
+     *
703
+     * The addressbook id will be passed as the first argument. This is the
704
+     * same id as it is returned from the getAddressBooksForUser method.
705
+     *
706
+     * The cardUri is a base uri, and doesn't include the full path. The
707
+     * cardData argument is the vcard body, and is passed as a string.
708
+     *
709
+     * It is possible to return an ETag from this method. This ETag should
710
+     * match that of the updated resource, and must be enclosed with double
711
+     * quotes (that is: the string itself must contain the actual quotes).
712
+     *
713
+     * You should only return the ETag if you store the carddata as-is. If a
714
+     * subsequent GET request on the same card does not have the same body,
715
+     * byte-by-byte and you did return an ETag here, clients tend to get
716
+     * confused.
717
+     *
718
+     * If you don't return an ETag, you can just return null.
719
+     *
720
+     * @param mixed $addressBookId
721
+     * @param string $cardUri
722
+     * @param string $cardData
723
+     * @return string
724
+     */
725
+    public function updateCard($addressBookId, $cardUri, $cardData) {
726
+        $uid = $this->getUID($cardData);
727
+        $etag = md5($cardData);
728
+        $query = $this->db->getQueryBuilder();
729
+
730
+        // check for recently stored etag and stop if it is the same
731
+        $etagCacheKey = "$addressBookId#$cardUri";
732
+        if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
733
+            return '"' . $etag . '"';
734
+        }
735
+
736
+        $query->update($this->dbCardsTable)
737
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
738
+            ->set('lastmodified', $query->createNamedParameter(time()))
739
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
740
+            ->set('etag', $query->createNamedParameter($etag))
741
+            ->set('uid', $query->createNamedParameter($uid))
742
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
743
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
744
+            ->execute();
745
+
746
+        $this->etagCache[$etagCacheKey] = $etag;
747
+
748
+        $this->addChange($addressBookId, $cardUri, 2);
749
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
750
+
751
+        $addressBookData = $this->getAddressBookById($addressBookId);
752
+        $shares = $this->getShares($addressBookId);
753
+        $objectRow = $this->getCard($addressBookId, $cardUri);
754
+        $this->dispatcher->dispatchTyped(new CardUpdatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
755
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
756
+            new GenericEvent(null, [
757
+                'addressBookId' => $addressBookId,
758
+                'cardUri' => $cardUri,
759
+                'cardData' => $cardData]));
760
+
761
+        return '"' . $etag . '"';
762
+    }
763
+
764
+    /**
765
+     * Deletes a card
766
+     *
767
+     * @param mixed $addressBookId
768
+     * @param string $cardUri
769
+     * @return bool
770
+     */
771
+    public function deleteCard($addressBookId, $cardUri) {
772
+        $addressBookData = $this->getAddressBookById($addressBookId);
773
+        $shares = $this->getShares($addressBookId);
774
+        $objectRow = $this->getCard($addressBookId, $cardUri);
775
+
776
+        try {
777
+            $cardId = $this->getCardId($addressBookId, $cardUri);
778
+        } catch (\InvalidArgumentException $e) {
779
+            $cardId = null;
780
+        }
781
+        $query = $this->db->getQueryBuilder();
782
+        $ret = $query->delete($this->dbCardsTable)
783
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
784
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
785
+            ->execute();
786
+
787
+        $this->addChange($addressBookId, $cardUri, 3);
788
+
789
+        if ($ret === 1) {
790
+            if ($cardId !== null) {
791
+                $this->dispatcher->dispatchTyped(new CardDeletedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
792
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
793
+                    new GenericEvent(null, [
794
+                        'addressBookId' => $addressBookId,
795
+                        'cardUri' => $cardUri]));
796
+
797
+                $this->purgeProperties($addressBookId, $cardId);
798
+            }
799
+            return true;
800
+        }
801
+
802
+        return false;
803
+    }
804
+
805
+    /**
806
+     * The getChanges method returns all the changes that have happened, since
807
+     * the specified syncToken in the specified address book.
808
+     *
809
+     * This function should return an array, such as the following:
810
+     *
811
+     * [
812
+     *   'syncToken' => 'The current synctoken',
813
+     *   'added'   => [
814
+     *      'new.txt',
815
+     *   ],
816
+     *   'modified'   => [
817
+     *      'modified.txt',
818
+     *   ],
819
+     *   'deleted' => [
820
+     *      'foo.php.bak',
821
+     *      'old.txt'
822
+     *   ]
823
+     * ];
824
+     *
825
+     * The returned syncToken property should reflect the *current* syncToken
826
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
827
+     * property. This is needed here too, to ensure the operation is atomic.
828
+     *
829
+     * If the $syncToken argument is specified as null, this is an initial
830
+     * sync, and all members should be reported.
831
+     *
832
+     * The modified property is an array of nodenames that have changed since
833
+     * the last token.
834
+     *
835
+     * The deleted property is an array with nodenames, that have been deleted
836
+     * from collection.
837
+     *
838
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
839
+     * 1, you only have to report changes that happened only directly in
840
+     * immediate descendants. If it's 2, it should also include changes from
841
+     * the nodes below the child collections. (grandchildren)
842
+     *
843
+     * The $limit argument allows a client to specify how many results should
844
+     * be returned at most. If the limit is not specified, it should be treated
845
+     * as infinite.
846
+     *
847
+     * If the limit (infinite or not) is higher than you're willing to return,
848
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
849
+     *
850
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
851
+     * return null.
852
+     *
853
+     * The limit is 'suggestive'. You are free to ignore it.
854
+     *
855
+     * @param string $addressBookId
856
+     * @param string $syncToken
857
+     * @param int $syncLevel
858
+     * @param int $limit
859
+     * @return array
860
+     */
861
+    public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
862
+        // Current synctoken
863
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
864
+        $stmt->execute([$addressBookId]);
865
+        $currentToken = $stmt->fetchColumn(0);
866
+
867
+        if (is_null($currentToken)) {
868
+            return null;
869
+        }
870
+
871
+        $result = [
872
+            'syncToken' => $currentToken,
873
+            'added' => [],
874
+            'modified' => [],
875
+            'deleted' => [],
876
+        ];
877
+
878
+        if ($syncToken) {
879
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
880
+            if ($limit > 0) {
881
+                $query .= " LIMIT " . (int)$limit;
882
+            }
883
+
884
+            // Fetching all changes
885
+            $stmt = $this->db->prepare($query);
886
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
887
+
888
+            $changes = [];
889
+
890
+            // This loop ensures that any duplicates are overwritten, only the
891
+            // last change on a node is relevant.
892
+            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
893
+                $changes[$row['uri']] = $row['operation'];
894
+            }
895
+
896
+            foreach ($changes as $uri => $operation) {
897
+                switch ($operation) {
898
+                    case 1:
899
+                        $result['added'][] = $uri;
900
+                        break;
901
+                    case 2:
902
+                        $result['modified'][] = $uri;
903
+                        break;
904
+                    case 3:
905
+                        $result['deleted'][] = $uri;
906
+                        break;
907
+                }
908
+            }
909
+        } else {
910
+            // No synctoken supplied, this is the initial sync.
911
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
912
+            $stmt = $this->db->prepare($query);
913
+            $stmt->execute([$addressBookId]);
914
+
915
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
916
+        }
917
+        return $result;
918
+    }
919
+
920
+    /**
921
+     * Adds a change record to the addressbookchanges table.
922
+     *
923
+     * @param mixed $addressBookId
924
+     * @param string $objectUri
925
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
926
+     * @return void
927
+     */
928
+    protected function addChange($addressBookId, $objectUri, $operation) {
929
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
930
+        $stmt = $this->db->prepare($sql);
931
+        $stmt->execute([
932
+            $objectUri,
933
+            $addressBookId,
934
+            $operation,
935
+            $addressBookId
936
+        ]);
937
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
938
+        $stmt->execute([
939
+            $addressBookId
940
+        ]);
941
+    }
942
+
943
+    /**
944
+     * @param resource|string $cardData
945
+     * @param bool $modified
946
+     * @return string
947
+     */
948
+    private function readBlob($cardData, &$modified = false) {
949
+        if (is_resource($cardData)) {
950
+            $cardData = stream_get_contents($cardData);
951
+        }
952
+
953
+        $cardDataArray = explode("\r\n", $cardData);
954
+
955
+        $cardDataFiltered = [];
956
+        $removingPhoto = false;
957
+        foreach ($cardDataArray as $line) {
958
+            if (strpos($line, 'PHOTO:data:') === 0
959
+                && strpos($line, 'PHOTO:data:image/') !== 0) {
960
+                // Filter out PHOTO data of non-images
961
+                $removingPhoto = true;
962
+                $modified = true;
963
+                continue;
964
+            }
965
+
966
+            if ($removingPhoto) {
967
+                if (strpos($line, ' ') === 0) {
968
+                    continue;
969
+                }
970
+                // No leading space means this is a new property
971
+                $removingPhoto = false;
972
+            }
973
+
974
+            $cardDataFiltered[] = $line;
975
+        }
976
+
977
+        return implode("\r\n", $cardDataFiltered);
978
+    }
979
+
980
+    /**
981
+     * @param IShareable $shareable
982
+     * @param string[] $add
983
+     * @param string[] $remove
984
+     */
985
+    public function updateShares(IShareable $shareable, $add, $remove) {
986
+        $addressBookId = $shareable->getResourceId();
987
+        $addressBookData = $this->getAddressBookById($addressBookId);
988
+        $oldShares = $this->getShares($addressBookId);
989
+
990
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
991
+
992
+        $this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
993
+    }
994
+
995
+    /**
996
+     * Search contacts in a specific address-book
997
+     *
998
+     * @param int $addressBookId
999
+     * @param string $pattern which should match within the $searchProperties
1000
+     * @param array $searchProperties defines the properties within the query pattern should match
1001
+     * @param array $options = array() to define the search behavior
1002
+     *    - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
1003
+     *    - 'limit' - Set a numeric limit for the search results
1004
+     *    - 'offset' - Set the offset for the limited search results
1005
+     * @return array an array of contacts which are arrays of key-value-pairs
1006
+     */
1007
+    public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
1008
+        return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
1009
+    }
1010
+
1011
+    /**
1012
+     * Search contacts in all address-books accessible by a user
1013
+     *
1014
+     * @param string $principalUri
1015
+     * @param string $pattern
1016
+     * @param array $searchProperties
1017
+     * @param array $options
1018
+     * @return array
1019
+     */
1020
+    public function searchPrincipalUri(string $principalUri,
1021
+                                        string $pattern,
1022
+                                        array $searchProperties,
1023
+                                        array $options = []): array {
1024
+        $addressBookIds = array_map(static function ($row):int {
1025
+            return (int) $row['id'];
1026
+        }, $this->getAddressBooksForUser($principalUri));
1027
+
1028
+        return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
1029
+    }
1030
+
1031
+    /**
1032
+     * @param array $addressBookIds
1033
+     * @param string $pattern
1034
+     * @param array $searchProperties
1035
+     * @param array $options
1036
+     * @return array
1037
+     */
1038
+    private function searchByAddressBookIds(array $addressBookIds,
1039
+                                            string $pattern,
1040
+                                            array $searchProperties,
1041
+                                            array $options = []): array {
1042
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1043
+
1044
+        $query2 = $this->db->getQueryBuilder();
1045
+
1046
+        $addressBookOr = $query2->expr()->orX();
1047
+        foreach ($addressBookIds as $addressBookId) {
1048
+            $addressBookOr->add($query2->expr()->eq('cp.addressbookid', $query2->createNamedParameter($addressBookId)));
1049
+        }
1050
+
1051
+        if ($addressBookOr->count() === 0) {
1052
+            return [];
1053
+        }
1054
+
1055
+        $propertyOr = $query2->expr()->orX();
1056
+        foreach ($searchProperties as $property) {
1057
+            if ($escapePattern) {
1058
+                if ($property === 'EMAIL' && strpos($pattern, ' ') !== false) {
1059
+                    // There can be no spaces in emails
1060
+                    continue;
1061
+                }
1062
+
1063
+                if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
1064
+                    // There can be no chars in cloud ids which are not valid for user ids plus :/
1065
+                    // worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
1066
+                    continue;
1067
+                }
1068
+            }
1069
+
1070
+            $propertyOr->add($query2->expr()->eq('cp.name', $query2->createNamedParameter($property)));
1071
+        }
1072
+
1073
+        if ($propertyOr->count() === 0) {
1074
+            return [];
1075
+        }
1076
+
1077
+        $query2->selectDistinct('cp.cardid')
1078
+            ->from($this->dbCardsPropertiesTable, 'cp')
1079
+            ->andWhere($addressBookOr)
1080
+            ->andWhere($propertyOr);
1081
+
1082
+        // No need for like when the pattern is empty
1083
+        if ('' !== $pattern) {
1084
+            if (!$escapePattern) {
1085
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
1086
+            } else {
1087
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1088
+            }
1089
+        }
1090
+
1091
+        if (isset($options['limit'])) {
1092
+            $query2->setMaxResults($options['limit']);
1093
+        }
1094
+        if (isset($options['offset'])) {
1095
+            $query2->setFirstResult($options['offset']);
1096
+        }
1097
+
1098
+        $result = $query2->execute();
1099
+        $matches = $result->fetchAll();
1100
+        $result->closeCursor();
1101
+        $matches = array_map(function ($match) {
1102
+            return (int)$match['cardid'];
1103
+        }, $matches);
1104
+
1105
+        $query = $this->db->getQueryBuilder();
1106
+        $query->select('c.addressbookid', 'c.carddata', 'c.uri')
1107
+            ->from($this->dbCardsTable, 'c')
1108
+            ->where($query->expr()->in('c.id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1109
+
1110
+        $result = $query->execute();
1111
+        $cards = $result->fetchAll();
1112
+
1113
+        $result->closeCursor();
1114
+
1115
+        return array_map(function ($array) {
1116
+            $array['addressbookid'] = (int) $array['addressbookid'];
1117
+            $modified = false;
1118
+            $array['carddata'] = $this->readBlob($array['carddata'], $modified);
1119
+            if ($modified) {
1120
+                $array['size'] = strlen($array['carddata']);
1121
+            }
1122
+            return $array;
1123
+        }, $cards);
1124
+    }
1125
+
1126
+    /**
1127
+     * @param int $bookId
1128
+     * @param string $name
1129
+     * @return array
1130
+     */
1131
+    public function collectCardProperties($bookId, $name) {
1132
+        $query = $this->db->getQueryBuilder();
1133
+        $result = $query->selectDistinct('value')
1134
+            ->from($this->dbCardsPropertiesTable)
1135
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
1136
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
1137
+            ->execute();
1138
+
1139
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
1140
+        $result->closeCursor();
1141
+
1142
+        return $all;
1143
+    }
1144
+
1145
+    /**
1146
+     * get URI from a given contact
1147
+     *
1148
+     * @param int $id
1149
+     * @return string
1150
+     */
1151
+    public function getCardUri($id) {
1152
+        $query = $this->db->getQueryBuilder();
1153
+        $query->select('uri')->from($this->dbCardsTable)
1154
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
1155
+            ->setParameter('id', $id);
1156
+
1157
+        $result = $query->execute();
1158
+        $uri = $result->fetch();
1159
+        $result->closeCursor();
1160
+
1161
+        if (!isset($uri['uri'])) {
1162
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
1163
+        }
1164
+
1165
+        return $uri['uri'];
1166
+    }
1167
+
1168
+    /**
1169
+     * return contact with the given URI
1170
+     *
1171
+     * @param int $addressBookId
1172
+     * @param string $uri
1173
+     * @returns array
1174
+     */
1175
+    public function getContact($addressBookId, $uri) {
1176
+        $result = [];
1177
+        $query = $this->db->getQueryBuilder();
1178
+        $query->select('*')->from($this->dbCardsTable)
1179
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1180
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1181
+        $queryResult = $query->execute();
1182
+        $contact = $queryResult->fetch();
1183
+        $queryResult->closeCursor();
1184
+
1185
+        if (is_array($contact)) {
1186
+            $modified = false;
1187
+            $contact['etag'] = '"' . $contact['etag'] . '"';
1188
+            $contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
1189
+            if ($modified) {
1190
+                $contact['size'] = strlen($contact['carddata']);
1191
+            }
1192
+
1193
+            $result = $contact;
1194
+        }
1195
+
1196
+        return $result;
1197
+    }
1198
+
1199
+    /**
1200
+     * Returns the list of people whom this address book is shared with.
1201
+     *
1202
+     * Every element in this array should have the following properties:
1203
+     *   * href - Often a mailto: address
1204
+     *   * commonName - Optional, for example a first + last name
1205
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1206
+     *   * readOnly - boolean
1207
+     *   * summary - Optional, a description for the share
1208
+     *
1209
+     * @return array
1210
+     */
1211
+    public function getShares($addressBookId) {
1212
+        return $this->sharingBackend->getShares($addressBookId);
1213
+    }
1214
+
1215
+    /**
1216
+     * update properties table
1217
+     *
1218
+     * @param int $addressBookId
1219
+     * @param string $cardUri
1220
+     * @param string $vCardSerialized
1221
+     */
1222
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1223
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1224
+        $vCard = $this->readCard($vCardSerialized);
1225
+
1226
+        $this->purgeProperties($addressBookId, $cardId);
1227
+
1228
+        $query = $this->db->getQueryBuilder();
1229
+        $query->insert($this->dbCardsPropertiesTable)
1230
+            ->values(
1231
+                [
1232
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1233
+                    'cardid' => $query->createNamedParameter($cardId),
1234
+                    'name' => $query->createParameter('name'),
1235
+                    'value' => $query->createParameter('value'),
1236
+                    'preferred' => $query->createParameter('preferred')
1237
+                ]
1238
+            );
1239
+
1240
+        foreach ($vCard->children() as $property) {
1241
+            if (!in_array($property->name, self::$indexProperties)) {
1242
+                continue;
1243
+            }
1244
+            $preferred = 0;
1245
+            foreach ($property->parameters as $parameter) {
1246
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1247
+                    $preferred = 1;
1248
+                    break;
1249
+                }
1250
+            }
1251
+            $query->setParameter('name', $property->name);
1252
+            $query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1253
+            $query->setParameter('preferred', $preferred);
1254
+            $query->execute();
1255
+        }
1256
+    }
1257
+
1258
+    /**
1259
+     * read vCard data into a vCard object
1260
+     *
1261
+     * @param string $cardData
1262
+     * @return VCard
1263
+     */
1264
+    protected function readCard($cardData) {
1265
+        return Reader::read($cardData);
1266
+    }
1267
+
1268
+    /**
1269
+     * delete all properties from a given card
1270
+     *
1271
+     * @param int $addressBookId
1272
+     * @param int $cardId
1273
+     */
1274
+    protected function purgeProperties($addressBookId, $cardId) {
1275
+        $query = $this->db->getQueryBuilder();
1276
+        $query->delete($this->dbCardsPropertiesTable)
1277
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1278
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1279
+        $query->execute();
1280
+    }
1281
+
1282
+    /**
1283
+     * get ID from a given contact
1284
+     *
1285
+     * @param int $addressBookId
1286
+     * @param string $uri
1287
+     * @return int
1288
+     */
1289
+    protected function getCardId($addressBookId, $uri) {
1290
+        $query = $this->db->getQueryBuilder();
1291
+        $query->select('id')->from($this->dbCardsTable)
1292
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1293
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1294
+
1295
+        $result = $query->execute();
1296
+        $cardIds = $result->fetch();
1297
+        $result->closeCursor();
1298
+
1299
+        if (!isset($cardIds['id'])) {
1300
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1301
+        }
1302
+
1303
+        return (int)$cardIds['id'];
1304
+    }
1305
+
1306
+    /**
1307
+     * For shared address books the sharee is set in the ACL of the address book
1308
+     *
1309
+     * @param $addressBookId
1310
+     * @param $acl
1311
+     * @return array
1312
+     */
1313
+    public function applyShareAcl($addressBookId, $acl) {
1314
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1315
+    }
1316
+
1317
+    private function convertPrincipal($principalUri, $toV2) {
1318
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1319
+            list(, $name) = \Sabre\Uri\split($principalUri);
1320
+            if ($toV2 === true) {
1321
+                return "principals/users/$name";
1322
+            }
1323
+            return "principals/$name";
1324
+        }
1325
+        return $principalUri;
1326
+    }
1327
+
1328
+    private function addOwnerPrincipal(&$addressbookInfo) {
1329
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1330
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1331
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1332
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1333
+        } else {
1334
+            $uri = $addressbookInfo['principaluri'];
1335
+        }
1336
+
1337
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1338
+        if (isset($principalInformation['{DAV:}displayname'])) {
1339
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1340
+        }
1341
+    }
1342
+
1343
+    /**
1344
+     * Extract UID from vcard
1345
+     *
1346
+     * @param string $cardData the vcard raw data
1347
+     * @return string the uid
1348
+     * @throws BadRequest if no UID is available
1349
+     */
1350
+    private function getUID($cardData) {
1351
+        if ($cardData != '') {
1352
+            $vCard = Reader::read($cardData);
1353
+            if ($vCard->UID) {
1354
+                $uid = $vCard->UID->getValue();
1355
+                return $uid;
1356
+            }
1357
+            // should already be handled, but just in case
1358
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1359
+        }
1360
+        // should already be handled, but just in case
1361
+        throw new BadRequest('vCard can not be empty');
1362
+    }
1363 1363
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 				'uri' => $row['uri'],
178 178
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
179 179
 				'{DAV:}displayname' => $row['displayname'],
180
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
180
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
181 181
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
182 182
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
183 183
 			];
@@ -202,13 +202,13 @@  discard block
 block discarded – undo
202 202
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
203 203
 			->execute();
204 204
 
205
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
205
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
206 206
 		while ($row = $result->fetch()) {
207 207
 			if ($row['principaluri'] === $principalUri) {
208 208
 				continue;
209 209
 			}
210 210
 
211
-			$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
211
+			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
212 212
 			if (isset($addressBooks[$row['id']])) {
213 213
 				if ($readOnly) {
214 214
 					// New share can not have more permissions then the old one.
@@ -222,18 +222,18 @@  discard block
 block discarded – undo
222 222
 			}
223 223
 
224 224
 			list(, $name) = \Sabre\Uri\split($row['principaluri']);
225
-			$uri = $row['uri'] . '_shared_by_' . $name;
226
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
225
+			$uri = $row['uri'].'_shared_by_'.$name;
226
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
227 227
 
228 228
 			$addressBooks[$row['id']] = [
229 229
 				'id' => $row['id'],
230 230
 				'uri' => $uri,
231 231
 				'principaluri' => $principalUriOriginal,
232 232
 				'{DAV:}displayname' => $displayName,
233
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
233
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
234 234
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
235 235
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
236
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
236
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
237 237
 				$readOnlyPropertyName => $readOnly,
238 238
 			];
239 239
 
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 				'uri' => $row['uri'],
261 261
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
262 262
 				'{DAV:}displayname' => $row['displayname'],
263
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
263
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
264 264
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
265 265
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
266 266
 			];
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 			'uri' => $row['uri'],
308 308
 			'principaluri' => $row['principaluri'],
309 309
 			'{DAV:}displayname' => $row['displayname'],
310
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
310
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
311 311
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
312 312
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
313 313
 		];
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 			'uri' => $row['uri'],
342 342
 			'principaluri' => $row['principaluri'],
343 343
 			'{DAV:}displayname' => $row['displayname'],
344
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
344
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
345 345
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
346 346
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
347 347
 		];
@@ -370,17 +370,17 @@  discard block
 block discarded – undo
370 370
 	public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
371 371
 		$supportedProperties = [
372 372
 			'{DAV:}displayname',
373
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
373
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
374 374
 		];
375 375
 
376
-		$propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
376
+		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
377 377
 			$updates = [];
378 378
 			foreach ($mutations as $property => $newValue) {
379 379
 				switch ($property) {
380 380
 					case '{DAV:}displayname':
381 381
 						$updates['displayname'] = $newValue;
382 382
 						break;
383
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
383
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description':
384 384
 						$updates['description'] = $newValue;
385 385
 						break;
386 386
 				}
@@ -396,9 +396,9 @@  discard block
 block discarded – undo
396 396
 
397 397
 			$this->addChange($addressBookId, "", 2);
398 398
 
399
-			$addressBookRow = $this->getAddressBookById((int)$addressBookId);
399
+			$addressBookRow = $this->getAddressBookById((int) $addressBookId);
400 400
 			$shares = $this->getShares($addressBookId);
401
-			$this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
401
+			$this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int) $addressBookId, $addressBookRow, $shares, $mutations));
402 402
 
403 403
 			return true;
404 404
 		});
@@ -427,11 +427,11 @@  discard block
 block discarded – undo
427 427
 				case '{DAV:}displayname':
428 428
 					$values['displayname'] = $newValue;
429 429
 					break;
430
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
430
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description':
431 431
 					$values['description'] = $newValue;
432 432
 					break;
433 433
 				default:
434
-					throw new BadRequest('Unknown property: ' . $property);
434
+					throw new BadRequest('Unknown property: '.$property);
435 435
 			}
436 436
 		}
437 437
 
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 
456 456
 		$addressBookId = $query->getLastInsertId();
457 457
 		$addressBookRow = $this->getAddressBookById($addressBookId);
458
-		$this->dispatcher->dispatchTyped(new AddressBookCreatedEvent((int)$addressBookId, $addressBookRow));
458
+		$this->dispatcher->dispatchTyped(new AddressBookCreatedEvent((int) $addressBookId, $addressBookRow));
459 459
 
460 460
 		return $addressBookId;
461 461
 	}
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 
527 527
 		$result = $query->execute();
528 528
 		while ($row = $result->fetch()) {
529
-			$row['etag'] = '"' . $row['etag'] . '"';
529
+			$row['etag'] = '"'.$row['etag'].'"';
530 530
 
531 531
 			$modified = false;
532 532
 			$row['carddata'] = $this->readBlob($row['carddata'], $modified);
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 		if (!$row) {
567 567
 			return false;
568 568
 		}
569
-		$row['etag'] = '"' . $row['etag'] . '"';
569
+		$row['etag'] = '"'.$row['etag'].'"';
570 570
 
571 571
 		$modified = false;
572 572
 		$row['carddata'] = $this->readBlob($row['carddata'], $modified);
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 			$result = $query->execute();
609 609
 
610 610
 			while ($row = $result->fetch()) {
611
-				$row['etag'] = '"' . $row['etag'] . '"';
611
+				$row['etag'] = '"'.$row['etag'].'"';
612 612
 
613 613
 				$modified = false;
614 614
 				$row['carddata'] = $this->readBlob($row['carddata'], $modified);
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
660 660
 			->setMaxResults(1);
661 661
 		$result = $q->execute();
662
-		$count = (bool)$result->fetchColumn();
662
+		$count = (bool) $result->fetchColumn();
663 663
 		$result->closeCursor();
664 664
 		if ($count) {
665 665
 			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
@@ -687,14 +687,14 @@  discard block
 block discarded – undo
687 687
 		$addressBookData = $this->getAddressBookById($addressBookId);
688 688
 		$shares = $this->getShares($addressBookId);
689 689
 		$objectRow = $this->getCard($addressBookId, $cardUri);
690
-		$this->dispatcher->dispatchTyped(new CardCreatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
690
+		$this->dispatcher->dispatchTyped(new CardCreatedEvent((int) $addressBookId, $addressBookData, $shares, $objectRow));
691 691
 		$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
692 692
 			new GenericEvent(null, [
693 693
 				'addressBookId' => $addressBookId,
694 694
 				'cardUri' => $cardUri,
695 695
 				'cardData' => $cardData]));
696 696
 
697
-		return '"' . $etag . '"';
697
+		return '"'.$etag.'"';
698 698
 	}
699 699
 
700 700
 	/**
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
 		// check for recently stored etag and stop if it is the same
731 731
 		$etagCacheKey = "$addressBookId#$cardUri";
732 732
 		if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
733
-			return '"' . $etag . '"';
733
+			return '"'.$etag.'"';
734 734
 		}
735 735
 
736 736
 		$query->update($this->dbCardsTable)
@@ -751,14 +751,14 @@  discard block
 block discarded – undo
751 751
 		$addressBookData = $this->getAddressBookById($addressBookId);
752 752
 		$shares = $this->getShares($addressBookId);
753 753
 		$objectRow = $this->getCard($addressBookId, $cardUri);
754
-		$this->dispatcher->dispatchTyped(new CardUpdatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
754
+		$this->dispatcher->dispatchTyped(new CardUpdatedEvent((int) $addressBookId, $addressBookData, $shares, $objectRow));
755 755
 		$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
756 756
 			new GenericEvent(null, [
757 757
 				'addressBookId' => $addressBookId,
758 758
 				'cardUri' => $cardUri,
759 759
 				'cardData' => $cardData]));
760 760
 
761
-		return '"' . $etag . '"';
761
+		return '"'.$etag.'"';
762 762
 	}
763 763
 
764 764
 	/**
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
 
789 789
 		if ($ret === 1) {
790 790
 			if ($cardId !== null) {
791
-				$this->dispatcher->dispatchTyped(new CardDeletedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
791
+				$this->dispatcher->dispatchTyped(new CardDeletedEvent((int) $addressBookId, $addressBookData, $shares, $objectRow));
792 792
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
793 793
 					new GenericEvent(null, [
794 794
 						'addressBookId' => $addressBookId,
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		if ($syncToken) {
879 879
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
880 880
 			if ($limit > 0) {
881
-				$query .= " LIMIT " . (int)$limit;
881
+				$query .= " LIMIT ".(int) $limit;
882 882
 			}
883 883
 
884 884
 			// Fetching all changes
@@ -1021,7 +1021,7 @@  discard block
 block discarded – undo
1021 1021
 									   string $pattern,
1022 1022
 									   array $searchProperties,
1023 1023
 									   array $options = []): array {
1024
-		$addressBookIds = array_map(static function ($row):int {
1024
+		$addressBookIds = array_map(static function($row):int {
1025 1025
 			return (int) $row['id'];
1026 1026
 		}, $this->getAddressBooksForUser($principalUri));
1027 1027
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
 			if (!$escapePattern) {
1085 1085
 				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
1086 1086
 			} else {
1087
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1087
+				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
1088 1088
 			}
1089 1089
 		}
1090 1090
 
@@ -1098,8 +1098,8 @@  discard block
 block discarded – undo
1098 1098
 		$result = $query2->execute();
1099 1099
 		$matches = $result->fetchAll();
1100 1100
 		$result->closeCursor();
1101
-		$matches = array_map(function ($match) {
1102
-			return (int)$match['cardid'];
1101
+		$matches = array_map(function($match) {
1102
+			return (int) $match['cardid'];
1103 1103
 		}, $matches);
1104 1104
 
1105 1105
 		$query = $this->db->getQueryBuilder();
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
 
1113 1113
 		$result->closeCursor();
1114 1114
 
1115
-		return array_map(function ($array) {
1115
+		return array_map(function($array) {
1116 1116
 			$array['addressbookid'] = (int) $array['addressbookid'];
1117 1117
 			$modified = false;
1118 1118
 			$array['carddata'] = $this->readBlob($array['carddata'], $modified);
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
 		$result->closeCursor();
1160 1160
 
1161 1161
 		if (!isset($uri['uri'])) {
1162
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
1162
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
1163 1163
 		}
1164 1164
 
1165 1165
 		return $uri['uri'];
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
 
1185 1185
 		if (is_array($contact)) {
1186 1186
 			$modified = false;
1187
-			$contact['etag'] = '"' . $contact['etag'] . '"';
1187
+			$contact['etag'] = '"'.$contact['etag'].'"';
1188 1188
 			$contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
1189 1189
 			if ($modified) {
1190 1190
 				$contact['size'] = strlen($contact['carddata']);
@@ -1297,10 +1297,10 @@  discard block
 block discarded – undo
1297 1297
 		$result->closeCursor();
1298 1298
 
1299 1299
 		if (!isset($cardIds['id'])) {
1300
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1300
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1301 1301
 		}
1302 1302
 
1303
-		return (int)$cardIds['id'];
1303
+		return (int) $cardIds['id'];
1304 1304
 	}
1305 1305
 
1306 1306
 	/**
@@ -1326,8 +1326,8 @@  discard block
 block discarded – undo
1326 1326
 	}
1327 1327
 
1328 1328
 	private function addOwnerPrincipal(&$addressbookInfo) {
1329
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1330
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1329
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1330
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1331 1331
 		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1332 1332
 			$uri = $addressbookInfo[$ownerPrincipalKey];
1333 1333
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2744 added lines, -2744 removed lines patch added patch discarded remove patch
@@ -95,2748 +95,2748 @@
 block discarded – undo
95 95
  * @package OCA\DAV\CalDAV
96 96
  */
97 97
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
98
-	public const CALENDAR_TYPE_CALENDAR = 0;
99
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
100
-
101
-	public const PERSONAL_CALENDAR_URI = 'personal';
102
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
103
-
104
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
105
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
106
-
107
-	/**
108
-	 * We need to specify a max date, because we need to stop *somewhere*
109
-	 *
110
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
111
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
112
-	 * in 2038-01-19 to avoid problems when the date is converted
113
-	 * to a unix timestamp.
114
-	 */
115
-	public const MAX_DATE = '2038-01-01';
116
-
117
-	public const ACCESS_PUBLIC = 4;
118
-	public const CLASSIFICATION_PUBLIC = 0;
119
-	public const CLASSIFICATION_PRIVATE = 1;
120
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
121
-
122
-	/**
123
-	 * List of CalDAV properties, and how they map to database field names
124
-	 * Add your own properties by simply adding on to this array.
125
-	 *
126
-	 * Note that only string-based properties are supported here.
127
-	 *
128
-	 * @var array
129
-	 */
130
-	public $propertyMap = [
131
-		'{DAV:}displayname' => 'displayname',
132
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
133
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
134
-		'{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
135
-		'{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
136
-	];
137
-
138
-	/**
139
-	 * List of subscription properties, and how they map to database field names.
140
-	 *
141
-	 * @var array
142
-	 */
143
-	public $subscriptionPropertyMap = [
144
-		'{DAV:}displayname' => 'displayname',
145
-		'{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
146
-		'{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
147
-		'{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
148
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
149
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
150
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
151
-	];
152
-
153
-	/** @var array properties to index */
154
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
155
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
156
-		'ORGANIZER'];
157
-
158
-	/** @var array parameters to index */
159
-	public static $indexParameters = [
160
-		'ATTENDEE' => ['CN'],
161
-		'ORGANIZER' => ['CN'],
162
-	];
163
-
164
-	/**
165
-	 * @var string[] Map of uid => display name
166
-	 */
167
-	protected $userDisplayNames;
168
-
169
-	/** @var IDBConnection */
170
-	private $db;
171
-
172
-	/** @var Backend */
173
-	private $calendarSharingBackend;
174
-
175
-	/** @var Principal */
176
-	private $principalBackend;
177
-
178
-	/** @var IUserManager */
179
-	private $userManager;
180
-
181
-	/** @var ISecureRandom */
182
-	private $random;
183
-
184
-	/** @var ILogger */
185
-	private $logger;
186
-
187
-	/** @var IEventDispatcher */
188
-	private $dispatcher;
189
-
190
-	/** @var EventDispatcherInterface */
191
-	private $legacyDispatcher;
192
-
193
-	/** @var bool */
194
-	private $legacyEndpoint;
195
-
196
-	/** @var string */
197
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
198
-
199
-	/**
200
-	 * CalDavBackend constructor.
201
-	 *
202
-	 * @param IDBConnection $db
203
-	 * @param Principal $principalBackend
204
-	 * @param IUserManager $userManager
205
-	 * @param IGroupManager $groupManager
206
-	 * @param ISecureRandom $random
207
-	 * @param ILogger $logger
208
-	 * @param IEventDispatcher $dispatcher
209
-	 * @param EventDispatcherInterface $legacyDispatcher
210
-	 * @param bool $legacyEndpoint
211
-	 */
212
-	public function __construct(IDBConnection $db,
213
-								Principal $principalBackend,
214
-								IUserManager $userManager,
215
-								IGroupManager $groupManager,
216
-								ISecureRandom $random,
217
-								ILogger $logger,
218
-								IEventDispatcher $dispatcher,
219
-								EventDispatcherInterface $legacyDispatcher,
220
-								bool $legacyEndpoint = false) {
221
-		$this->db = $db;
222
-		$this->principalBackend = $principalBackend;
223
-		$this->userManager = $userManager;
224
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
225
-		$this->random = $random;
226
-		$this->logger = $logger;
227
-		$this->dispatcher = $dispatcher;
228
-		$this->legacyDispatcher = $legacyDispatcher;
229
-		$this->legacyEndpoint = $legacyEndpoint;
230
-	}
231
-
232
-	/**
233
-	 * Return the number of calendars for a principal
234
-	 *
235
-	 * By default this excludes the automatically generated birthday calendar
236
-	 *
237
-	 * @param $principalUri
238
-	 * @param bool $excludeBirthday
239
-	 * @return int
240
-	 */
241
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
242
-		$principalUri = $this->convertPrincipal($principalUri, true);
243
-		$query = $this->db->getQueryBuilder();
244
-		$query->select($query->func()->count('*'))
245
-			->from('calendars');
246
-
247
-		if ($principalUri === '') {
248
-			$query->where($query->expr()->emptyString('principaluri'));
249
-		} else {
250
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
251
-		}
252
-
253
-		if ($excludeBirthday) {
254
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
255
-		}
256
-
257
-		$result = $query->execute();
258
-		$column = (int)$result->fetchColumn();
259
-		$result->closeCursor();
260
-		return $column;
261
-	}
262
-
263
-	/**
264
-	 * Returns a list of calendars for a principal.
265
-	 *
266
-	 * Every project is an array with the following keys:
267
-	 *  * id, a unique id that will be used by other functions to modify the
268
-	 *    calendar. This can be the same as the uri or a database key.
269
-	 *  * uri, which the basename of the uri with which the calendar is
270
-	 *    accessed.
271
-	 *  * principaluri. The owner of the calendar. Almost always the same as
272
-	 *    principalUri passed to this method.
273
-	 *
274
-	 * Furthermore it can contain webdav properties in clark notation. A very
275
-	 * common one is '{DAV:}displayname'.
276
-	 *
277
-	 * Many clients also require:
278
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
279
-	 * For this property, you can just return an instance of
280
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
281
-	 *
282
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
283
-	 * ACL will automatically be put in read-only mode.
284
-	 *
285
-	 * @param string $principalUri
286
-	 * @return array
287
-	 */
288
-	public function getCalendarsForUser($principalUri) {
289
-		$principalUriOriginal = $principalUri;
290
-		$principalUri = $this->convertPrincipal($principalUri, true);
291
-		$fields = array_values($this->propertyMap);
292
-		$fields[] = 'id';
293
-		$fields[] = 'uri';
294
-		$fields[] = 'synctoken';
295
-		$fields[] = 'components';
296
-		$fields[] = 'principaluri';
297
-		$fields[] = 'transparent';
298
-
299
-		// Making fields a comma-delimited list
300
-		$query = $this->db->getQueryBuilder();
301
-		$query->select($fields)
302
-			->from('calendars')
303
-			->orderBy('calendarorder', 'ASC');
304
-
305
-		if ($principalUri === '') {
306
-			$query->where($query->expr()->emptyString('principaluri'));
307
-		} else {
308
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
309
-		}
310
-
311
-		$result = $query->execute();
312
-
313
-		$calendars = [];
314
-		while ($row = $result->fetch()) {
315
-			$row['principaluri'] = (string) $row['principaluri'];
316
-			$components = [];
317
-			if ($row['components']) {
318
-				$components = explode(',',$row['components']);
319
-			}
320
-
321
-			$calendar = [
322
-				'id' => $row['id'],
323
-				'uri' => $row['uri'],
324
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
325
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
326
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
327
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
328
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
329
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
330
-			];
331
-
332
-			foreach ($this->propertyMap as $xmlName => $dbName) {
333
-				$calendar[$xmlName] = $row[$dbName];
334
-			}
335
-
336
-			$this->addOwnerPrincipal($calendar);
337
-
338
-			if (!isset($calendars[$calendar['id']])) {
339
-				$calendars[$calendar['id']] = $calendar;
340
-			}
341
-		}
342
-		$result->closeCursor();
343
-
344
-		// query for shared calendars
345
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
346
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
347
-
348
-		$principals[] = $principalUri;
349
-
350
-		$fields = array_values($this->propertyMap);
351
-		$fields[] = 'a.id';
352
-		$fields[] = 'a.uri';
353
-		$fields[] = 'a.synctoken';
354
-		$fields[] = 'a.components';
355
-		$fields[] = 'a.principaluri';
356
-		$fields[] = 'a.transparent';
357
-		$fields[] = 's.access';
358
-		$query = $this->db->getQueryBuilder();
359
-		$query->select($fields)
360
-			->from('dav_shares', 's')
361
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
362
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
363
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
364
-			->setParameter('type', 'calendar')
365
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
366
-
367
-		$result	= $query->execute();
368
-
369
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
370
-		while ($row = $result->fetch()) {
371
-			$row['principaluri'] = (string) $row['principaluri'];
372
-			if ($row['principaluri'] === $principalUri) {
373
-				continue;
374
-			}
375
-
376
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
377
-			if (isset($calendars[$row['id']])) {
378
-				if ($readOnly) {
379
-					// New share can not have more permissions then the old one.
380
-					continue;
381
-				}
382
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
383
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
384
-					// Old share is already read-write, no more permissions can be gained
385
-					continue;
386
-				}
387
-			}
388
-
389
-			list(, $name) = Uri\split($row['principaluri']);
390
-			$uri = $row['uri'] . '_shared_by_' . $name;
391
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
392
-			$components = [];
393
-			if ($row['components']) {
394
-				$components = explode(',',$row['components']);
395
-			}
396
-			$calendar = [
397
-				'id' => $row['id'],
398
-				'uri' => $uri,
399
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
400
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
401
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
402
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
404
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
405
-				$readOnlyPropertyName => $readOnly,
406
-			];
407
-
408
-			foreach ($this->propertyMap as $xmlName => $dbName) {
409
-				$calendar[$xmlName] = $row[$dbName];
410
-			}
411
-
412
-			$this->addOwnerPrincipal($calendar);
413
-
414
-			$calendars[$calendar['id']] = $calendar;
415
-		}
416
-		$result->closeCursor();
417
-
418
-		return array_values($calendars);
419
-	}
420
-
421
-	/**
422
-	 * @param $principalUri
423
-	 * @return array
424
-	 */
425
-	public function getUsersOwnCalendars($principalUri) {
426
-		$principalUri = $this->convertPrincipal($principalUri, true);
427
-		$fields = array_values($this->propertyMap);
428
-		$fields[] = 'id';
429
-		$fields[] = 'uri';
430
-		$fields[] = 'synctoken';
431
-		$fields[] = 'components';
432
-		$fields[] = 'principaluri';
433
-		$fields[] = 'transparent';
434
-		// Making fields a comma-delimited list
435
-		$query = $this->db->getQueryBuilder();
436
-		$query->select($fields)->from('calendars')
437
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
438
-			->orderBy('calendarorder', 'ASC');
439
-		$stmt = $query->execute();
440
-		$calendars = [];
441
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
442
-			$row['principaluri'] = (string) $row['principaluri'];
443
-			$components = [];
444
-			if ($row['components']) {
445
-				$components = explode(',',$row['components']);
446
-			}
447
-			$calendar = [
448
-				'id' => $row['id'],
449
-				'uri' => $row['uri'],
450
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
451
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
452
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
453
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
454
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
455
-			];
456
-			foreach ($this->propertyMap as $xmlName => $dbName) {
457
-				$calendar[$xmlName] = $row[$dbName];
458
-			}
459
-
460
-			$this->addOwnerPrincipal($calendar);
461
-
462
-			if (!isset($calendars[$calendar['id']])) {
463
-				$calendars[$calendar['id']] = $calendar;
464
-			}
465
-		}
466
-		$stmt->closeCursor();
467
-		return array_values($calendars);
468
-	}
469
-
470
-
471
-	/**
472
-	 * @param $uid
473
-	 * @return string
474
-	 */
475
-	private function getUserDisplayName($uid) {
476
-		if (!isset($this->userDisplayNames[$uid])) {
477
-			$user = $this->userManager->get($uid);
478
-
479
-			if ($user instanceof IUser) {
480
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
481
-			} else {
482
-				$this->userDisplayNames[$uid] = $uid;
483
-			}
484
-		}
485
-
486
-		return $this->userDisplayNames[$uid];
487
-	}
488
-
489
-	/**
490
-	 * @return array
491
-	 */
492
-	public function getPublicCalendars() {
493
-		$fields = array_values($this->propertyMap);
494
-		$fields[] = 'a.id';
495
-		$fields[] = 'a.uri';
496
-		$fields[] = 'a.synctoken';
497
-		$fields[] = 'a.components';
498
-		$fields[] = 'a.principaluri';
499
-		$fields[] = 'a.transparent';
500
-		$fields[] = 's.access';
501
-		$fields[] = 's.publicuri';
502
-		$calendars = [];
503
-		$query = $this->db->getQueryBuilder();
504
-		$result = $query->select($fields)
505
-			->from('dav_shares', 's')
506
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
-			->execute();
510
-
511
-		while ($row = $result->fetch()) {
512
-			$row['principaluri'] = (string) $row['principaluri'];
513
-			list(, $name) = Uri\split($row['principaluri']);
514
-			$row['displayname'] = $row['displayname'] . "($name)";
515
-			$components = [];
516
-			if ($row['components']) {
517
-				$components = explode(',',$row['components']);
518
-			}
519
-			$calendar = [
520
-				'id' => $row['id'],
521
-				'uri' => $row['publicuri'],
522
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
528
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
530
-			];
531
-
532
-			foreach ($this->propertyMap as $xmlName => $dbName) {
533
-				$calendar[$xmlName] = $row[$dbName];
534
-			}
535
-
536
-			$this->addOwnerPrincipal($calendar);
537
-
538
-			if (!isset($calendars[$calendar['id']])) {
539
-				$calendars[$calendar['id']] = $calendar;
540
-			}
541
-		}
542
-		$result->closeCursor();
543
-
544
-		return array_values($calendars);
545
-	}
546
-
547
-	/**
548
-	 * @param string $uri
549
-	 * @return array
550
-	 * @throws NotFound
551
-	 */
552
-	public function getPublicCalendar($uri) {
553
-		$fields = array_values($this->propertyMap);
554
-		$fields[] = 'a.id';
555
-		$fields[] = 'a.uri';
556
-		$fields[] = 'a.synctoken';
557
-		$fields[] = 'a.components';
558
-		$fields[] = 'a.principaluri';
559
-		$fields[] = 'a.transparent';
560
-		$fields[] = 's.access';
561
-		$fields[] = 's.publicuri';
562
-		$query = $this->db->getQueryBuilder();
563
-		$result = $query->select($fields)
564
-			->from('dav_shares', 's')
565
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
566
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
567
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
568
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
569
-			->execute();
570
-
571
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
572
-
573
-		$result->closeCursor();
574
-
575
-		if ($row === false) {
576
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
577
-		}
578
-
579
-		$row['principaluri'] = (string) $row['principaluri'];
580
-		list(, $name) = Uri\split($row['principaluri']);
581
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
582
-		$components = [];
583
-		if ($row['components']) {
584
-			$components = explode(',',$row['components']);
585
-		}
586
-		$calendar = [
587
-			'id' => $row['id'],
588
-			'uri' => $row['publicuri'],
589
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
590
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
591
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
592
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
593
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
594
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
595
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
596
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
597
-		];
598
-
599
-		foreach ($this->propertyMap as $xmlName => $dbName) {
600
-			$calendar[$xmlName] = $row[$dbName];
601
-		}
602
-
603
-		$this->addOwnerPrincipal($calendar);
604
-
605
-		return $calendar;
606
-	}
607
-
608
-	/**
609
-	 * @param string $principal
610
-	 * @param string $uri
611
-	 * @return array|null
612
-	 */
613
-	public function getCalendarByUri($principal, $uri) {
614
-		$fields = array_values($this->propertyMap);
615
-		$fields[] = 'id';
616
-		$fields[] = 'uri';
617
-		$fields[] = 'synctoken';
618
-		$fields[] = 'components';
619
-		$fields[] = 'principaluri';
620
-		$fields[] = 'transparent';
621
-
622
-		// Making fields a comma-delimited list
623
-		$query = $this->db->getQueryBuilder();
624
-		$query->select($fields)->from('calendars')
625
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
626
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
627
-			->setMaxResults(1);
628
-		$stmt = $query->execute();
629
-
630
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
631
-		$stmt->closeCursor();
632
-		if ($row === false) {
633
-			return null;
634
-		}
635
-
636
-		$row['principaluri'] = (string) $row['principaluri'];
637
-		$components = [];
638
-		if ($row['components']) {
639
-			$components = explode(',',$row['components']);
640
-		}
641
-
642
-		$calendar = [
643
-			'id' => $row['id'],
644
-			'uri' => $row['uri'],
645
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
646
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
647
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
648
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
649
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
650
-		];
651
-
652
-		foreach ($this->propertyMap as $xmlName => $dbName) {
653
-			$calendar[$xmlName] = $row[$dbName];
654
-		}
655
-
656
-		$this->addOwnerPrincipal($calendar);
657
-
658
-		return $calendar;
659
-	}
660
-
661
-	/**
662
-	 * @param $calendarId
663
-	 * @return array|null
664
-	 */
665
-	public function getCalendarById($calendarId) {
666
-		$fields = array_values($this->propertyMap);
667
-		$fields[] = 'id';
668
-		$fields[] = 'uri';
669
-		$fields[] = 'synctoken';
670
-		$fields[] = 'components';
671
-		$fields[] = 'principaluri';
672
-		$fields[] = 'transparent';
673
-
674
-		// Making fields a comma-delimited list
675
-		$query = $this->db->getQueryBuilder();
676
-		$query->select($fields)->from('calendars')
677
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
678
-			->setMaxResults(1);
679
-		$stmt = $query->execute();
680
-
681
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
682
-		$stmt->closeCursor();
683
-		if ($row === false) {
684
-			return null;
685
-		}
686
-
687
-		$row['principaluri'] = (string) $row['principaluri'];
688
-		$components = [];
689
-		if ($row['components']) {
690
-			$components = explode(',',$row['components']);
691
-		}
692
-
693
-		$calendar = [
694
-			'id' => $row['id'],
695
-			'uri' => $row['uri'],
696
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
697
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
698
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
699
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
700
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
701
-		];
702
-
703
-		foreach ($this->propertyMap as $xmlName => $dbName) {
704
-			$calendar[$xmlName] = $row[$dbName];
705
-		}
706
-
707
-		$this->addOwnerPrincipal($calendar);
708
-
709
-		return $calendar;
710
-	}
711
-
712
-	/**
713
-	 * @param $subscriptionId
714
-	 */
715
-	public function getSubscriptionById($subscriptionId) {
716
-		$fields = array_values($this->subscriptionPropertyMap);
717
-		$fields[] = 'id';
718
-		$fields[] = 'uri';
719
-		$fields[] = 'source';
720
-		$fields[] = 'synctoken';
721
-		$fields[] = 'principaluri';
722
-		$fields[] = 'lastmodified';
723
-
724
-		$query = $this->db->getQueryBuilder();
725
-		$query->select($fields)
726
-			->from('calendarsubscriptions')
727
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
728
-			->orderBy('calendarorder', 'asc');
729
-		$stmt = $query->execute();
730
-
731
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
732
-		$stmt->closeCursor();
733
-		if ($row === false) {
734
-			return null;
735
-		}
736
-
737
-		$row['principaluri'] = (string) $row['principaluri'];
738
-		$subscription = [
739
-			'id' => $row['id'],
740
-			'uri' => $row['uri'],
741
-			'principaluri' => $row['principaluri'],
742
-			'source' => $row['source'],
743
-			'lastmodified' => $row['lastmodified'],
744
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
745
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
746
-		];
747
-
748
-		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
749
-			if (!is_null($row[$dbName])) {
750
-				$subscription[$xmlName] = $row[$dbName];
751
-			}
752
-		}
753
-
754
-		return $subscription;
755
-	}
756
-
757
-	/**
758
-	 * Creates a new calendar for a principal.
759
-	 *
760
-	 * If the creation was a success, an id must be returned that can be used to reference
761
-	 * this calendar in other methods, such as updateCalendar.
762
-	 *
763
-	 * @param string $principalUri
764
-	 * @param string $calendarUri
765
-	 * @param array $properties
766
-	 * @return int
767
-	 */
768
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
769
-		$values = [
770
-			'principaluri' => $this->convertPrincipal($principalUri, true),
771
-			'uri' => $calendarUri,
772
-			'synctoken' => 1,
773
-			'transparent' => 0,
774
-			'components' => 'VEVENT,VTODO',
775
-			'displayname' => $calendarUri
776
-		];
777
-
778
-		// Default value
779
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
780
-		if (isset($properties[$sccs])) {
781
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
782
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
783
-			}
784
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
785
-		} elseif (isset($properties['components'])) {
786
-			// Allow to provide components internally without having
787
-			// to create a SupportedCalendarComponentSet object
788
-			$values['components'] = $properties['components'];
789
-		}
790
-
791
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
792
-		if (isset($properties[$transp])) {
793
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
794
-		}
795
-
796
-		foreach ($this->propertyMap as $xmlName => $dbName) {
797
-			if (isset($properties[$xmlName])) {
798
-				$values[$dbName] = $properties[$xmlName];
799
-			}
800
-		}
801
-
802
-		$query = $this->db->getQueryBuilder();
803
-		$query->insert('calendars');
804
-		foreach ($values as $column => $value) {
805
-			$query->setValue($column, $query->createNamedParameter($value));
806
-		}
807
-		$query->execute();
808
-		$calendarId = $query->getLastInsertId();
809
-
810
-		$calendarData = $this->getCalendarById($calendarId);
811
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
812
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
813
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
814
-			[
815
-				'calendarId' => $calendarId,
816
-				'calendarData' => $calendarData,
817
-			]));
818
-
819
-		return $calendarId;
820
-	}
821
-
822
-	/**
823
-	 * Updates properties for a calendar.
824
-	 *
825
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
826
-	 * To do the actual updates, you must tell this object which properties
827
-	 * you're going to process with the handle() method.
828
-	 *
829
-	 * Calling the handle method is like telling the PropPatch object "I
830
-	 * promise I can handle updating this property".
831
-	 *
832
-	 * Read the PropPatch documentation for more info and examples.
833
-	 *
834
-	 * @param mixed $calendarId
835
-	 * @param PropPatch $propPatch
836
-	 * @return void
837
-	 */
838
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
839
-		$supportedProperties = array_keys($this->propertyMap);
840
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
-
842
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
843
-			$newValues = [];
844
-			foreach ($mutations as $propertyName => $propertyValue) {
845
-				switch ($propertyName) {
846
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
847
-						$fieldName = 'transparent';
848
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
849
-						break;
850
-					default:
851
-						$fieldName = $this->propertyMap[$propertyName];
852
-						$newValues[$fieldName] = $propertyValue;
853
-						break;
854
-				}
855
-			}
856
-			$query = $this->db->getQueryBuilder();
857
-			$query->update('calendars');
858
-			foreach ($newValues as $fieldName => $value) {
859
-				$query->set($fieldName, $query->createNamedParameter($value));
860
-			}
861
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
862
-			$query->execute();
863
-
864
-			$this->addChange($calendarId, "", 2);
865
-
866
-			$calendarData = $this->getCalendarById($calendarId);
867
-			$shares = $this->getShares($calendarId);
868
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
869
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
870
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
871
-				[
872
-					'calendarId' => $calendarId,
873
-					'calendarData' => $calendarData,
874
-					'shares' => $shares,
875
-					'propertyMutations' => $mutations,
876
-				]));
877
-
878
-			return true;
879
-		});
880
-	}
881
-
882
-	/**
883
-	 * Delete a calendar and all it's objects
884
-	 *
885
-	 * @param mixed $calendarId
886
-	 * @return void
887
-	 */
888
-	public function deleteCalendar($calendarId) {
889
-		$calendarData = $this->getCalendarById($calendarId);
890
-		$shares = $this->getShares($calendarId);
891
-
892
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
893
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
894
-			[
895
-				'calendarId' => $calendarId,
896
-				'calendarData' => $calendarData,
897
-				'shares' => $shares,
898
-			]));
899
-
900
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
901
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
902
-
903
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
904
-		$stmt->execute([$calendarId]);
905
-
906
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
907
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
908
-
909
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
910
-
911
-		$query = $this->db->getQueryBuilder();
912
-		$query->delete($this->dbObjectPropertiesTable)
913
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
914
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
915
-			->execute();
916
-
917
-		if ($calendarData) {
918
-			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
919
-		}
920
-	}
921
-
922
-	/**
923
-	 * Delete all of an user's shares
924
-	 *
925
-	 * @param string $principaluri
926
-	 * @return void
927
-	 */
928
-	public function deleteAllSharesByUser($principaluri) {
929
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
930
-	}
931
-
932
-	/**
933
-	 * Returns all calendar objects within a calendar.
934
-	 *
935
-	 * Every item contains an array with the following keys:
936
-	 *   * calendardata - The iCalendar-compatible calendar data
937
-	 *   * uri - a unique key which will be used to construct the uri. This can
938
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
939
-	 *     good idea. This is only the basename, or filename, not the full
940
-	 *     path.
941
-	 *   * lastmodified - a timestamp of the last modification time
942
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
943
-	 *   '"abcdef"')
944
-	 *   * size - The size of the calendar objects, in bytes.
945
-	 *   * component - optional, a string containing the type of object, such
946
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
947
-	 *     the Content-Type header.
948
-	 *
949
-	 * Note that the etag is optional, but it's highly encouraged to return for
950
-	 * speed reasons.
951
-	 *
952
-	 * The calendardata is also optional. If it's not returned
953
-	 * 'getCalendarObject' will be called later, which *is* expected to return
954
-	 * calendardata.
955
-	 *
956
-	 * If neither etag or size are specified, the calendardata will be
957
-	 * used/fetched to determine these numbers. If both are specified the
958
-	 * amount of times this is needed is reduced by a great degree.
959
-	 *
960
-	 * @param mixed $calendarId
961
-	 * @param int $calendarType
962
-	 * @return array
963
-	 */
964
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
965
-		$query = $this->db->getQueryBuilder();
966
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
967
-			->from('calendarobjects')
968
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
969
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
970
-		$stmt = $query->execute();
971
-
972
-		$result = [];
973
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
974
-			$result[] = [
975
-				'id' => $row['id'],
976
-				'uri' => $row['uri'],
977
-				'lastmodified' => $row['lastmodified'],
978
-				'etag' => '"' . $row['etag'] . '"',
979
-				'calendarid' => $row['calendarid'],
980
-				'size' => (int)$row['size'],
981
-				'component' => strtolower($row['componenttype']),
982
-				'classification' => (int)$row['classification']
983
-			];
984
-		}
985
-		$stmt->closeCursor();
986
-
987
-		return $result;
988
-	}
989
-
990
-	/**
991
-	 * Returns information from a single calendar object, based on it's object
992
-	 * uri.
993
-	 *
994
-	 * The object uri is only the basename, or filename and not a full path.
995
-	 *
996
-	 * The returned array must have the same keys as getCalendarObjects. The
997
-	 * 'calendardata' object is required here though, while it's not required
998
-	 * for getCalendarObjects.
999
-	 *
1000
-	 * This method must return null if the object did not exist.
1001
-	 *
1002
-	 * @param mixed $calendarId
1003
-	 * @param string $objectUri
1004
-	 * @param int $calendarType
1005
-	 * @return array|null
1006
-	 */
1007
-	public function getCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1008
-		$query = $this->db->getQueryBuilder();
1009
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1010
-			->from('calendarobjects')
1011
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1012
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1013
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1014
-		$stmt = $query->execute();
1015
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1016
-		$stmt->closeCursor();
1017
-
1018
-		if (!$row) {
1019
-			return null;
1020
-		}
1021
-
1022
-		return [
1023
-			'id' => $row['id'],
1024
-			'uri' => $row['uri'],
1025
-			'lastmodified' => $row['lastmodified'],
1026
-			'etag' => '"' . $row['etag'] . '"',
1027
-			'calendarid' => $row['calendarid'],
1028
-			'size' => (int)$row['size'],
1029
-			'calendardata' => $this->readBlob($row['calendardata']),
1030
-			'component' => strtolower($row['componenttype']),
1031
-			'classification' => (int)$row['classification']
1032
-		];
1033
-	}
1034
-
1035
-	/**
1036
-	 * Returns a list of calendar objects.
1037
-	 *
1038
-	 * This method should work identical to getCalendarObject, but instead
1039
-	 * return all the calendar objects in the list as an array.
1040
-	 *
1041
-	 * If the backend supports this, it may allow for some speed-ups.
1042
-	 *
1043
-	 * @param mixed $calendarId
1044
-	 * @param string[] $uris
1045
-	 * @param int $calendarType
1046
-	 * @return array
1047
-	 */
1048
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1049
-		if (empty($uris)) {
1050
-			return [];
1051
-		}
1052
-
1053
-		$chunks = array_chunk($uris, 100);
1054
-		$objects = [];
1055
-
1056
-		$query = $this->db->getQueryBuilder();
1057
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1058
-			->from('calendarobjects')
1059
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1060
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1061
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1062
-
1063
-		foreach ($chunks as $uris) {
1064
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1065
-			$result = $query->execute();
1066
-
1067
-			while ($row = $result->fetch()) {
1068
-				$objects[] = [
1069
-					'id' => $row['id'],
1070
-					'uri' => $row['uri'],
1071
-					'lastmodified' => $row['lastmodified'],
1072
-					'etag' => '"' . $row['etag'] . '"',
1073
-					'calendarid' => $row['calendarid'],
1074
-					'size' => (int)$row['size'],
1075
-					'calendardata' => $this->readBlob($row['calendardata']),
1076
-					'component' => strtolower($row['componenttype']),
1077
-					'classification' => (int)$row['classification']
1078
-				];
1079
-			}
1080
-			$result->closeCursor();
1081
-		}
1082
-
1083
-		return $objects;
1084
-	}
1085
-
1086
-	/**
1087
-	 * Creates a new calendar object.
1088
-	 *
1089
-	 * The object uri is only the basename, or filename and not a full path.
1090
-	 *
1091
-	 * It is possible return an etag from this function, which will be used in
1092
-	 * the response to this PUT request. Note that the ETag must be surrounded
1093
-	 * by double-quotes.
1094
-	 *
1095
-	 * However, you should only really return this ETag if you don't mangle the
1096
-	 * calendar-data. If the result of a subsequent GET to this object is not
1097
-	 * the exact same as this request body, you should omit the ETag.
1098
-	 *
1099
-	 * @param mixed $calendarId
1100
-	 * @param string $objectUri
1101
-	 * @param string $calendarData
1102
-	 * @param int $calendarType
1103
-	 * @return string
1104
-	 */
1105
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1106
-		$extraData = $this->getDenormalizedData($calendarData);
1107
-
1108
-		$q = $this->db->getQueryBuilder();
1109
-		$q->select($q->func()->count('*'))
1110
-			->from('calendarobjects')
1111
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1112
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1113
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1114
-
1115
-		$result = $q->execute();
1116
-		$count = (int) $result->fetchColumn();
1117
-		$result->closeCursor();
1118
-
1119
-		if ($count !== 0) {
1120
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1121
-		}
1122
-
1123
-		$query = $this->db->getQueryBuilder();
1124
-		$query->insert('calendarobjects')
1125
-			->values([
1126
-				'calendarid' => $query->createNamedParameter($calendarId),
1127
-				'uri' => $query->createNamedParameter($objectUri),
1128
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1129
-				'lastmodified' => $query->createNamedParameter(time()),
1130
-				'etag' => $query->createNamedParameter($extraData['etag']),
1131
-				'size' => $query->createNamedParameter($extraData['size']),
1132
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1133
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1134
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1135
-				'classification' => $query->createNamedParameter($extraData['classification']),
1136
-				'uid' => $query->createNamedParameter($extraData['uid']),
1137
-				'calendartype' => $query->createNamedParameter($calendarType),
1138
-			])
1139
-			->execute();
1140
-
1141
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1142
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1143
-
1144
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1145
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1146
-			$calendarRow = $this->getCalendarById($calendarId);
1147
-			$shares = $this->getShares($calendarId);
1148
-
1149
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1150
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1151
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1152
-				[
1153
-					'calendarId' => $calendarId,
1154
-					'calendarData' => $calendarRow,
1155
-					'shares' => $shares,
1156
-					'objectData' => $objectRow,
1157
-				]
1158
-			));
1159
-		} else {
1160
-			$subscriptionRow = $this->getSubscriptionById($calendarId);
1161
-
1162
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1163
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1164
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1165
-				[
1166
-					'subscriptionId' => $calendarId,
1167
-					'calendarData' => $subscriptionRow,
1168
-					'shares' => [],
1169
-					'objectData' => $objectRow,
1170
-				]
1171
-			));
1172
-		}
1173
-
1174
-		return '"' . $extraData['etag'] . '"';
1175
-	}
1176
-
1177
-	/**
1178
-	 * Updates an existing calendarobject, based on it's uri.
1179
-	 *
1180
-	 * The object uri is only the basename, or filename and not a full path.
1181
-	 *
1182
-	 * It is possible return an etag from this function, which will be used in
1183
-	 * the response to this PUT request. Note that the ETag must be surrounded
1184
-	 * by double-quotes.
1185
-	 *
1186
-	 * However, you should only really return this ETag if you don't mangle the
1187
-	 * calendar-data. If the result of a subsequent GET to this object is not
1188
-	 * the exact same as this request body, you should omit the ETag.
1189
-	 *
1190
-	 * @param mixed $calendarId
1191
-	 * @param string $objectUri
1192
-	 * @param string $calendarData
1193
-	 * @param int $calendarType
1194
-	 * @return string
1195
-	 */
1196
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1197
-		$extraData = $this->getDenormalizedData($calendarData);
1198
-		$query = $this->db->getQueryBuilder();
1199
-		$query->update('calendarobjects')
1200
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1201
-				->set('lastmodified', $query->createNamedParameter(time()))
1202
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1203
-				->set('size', $query->createNamedParameter($extraData['size']))
1204
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1205
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1206
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1207
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1208
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1209
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1210
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1211
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1212
-			->execute();
1213
-
1214
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1215
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1216
-
1217
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1218
-		if (is_array($objectRow)) {
1219
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1220
-				$calendarRow = $this->getCalendarById($calendarId);
1221
-				$shares = $this->getShares($calendarId);
1222
-
1223
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1224
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1225
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1226
-					[
1227
-						'calendarId' => $calendarId,
1228
-						'calendarData' => $calendarRow,
1229
-						'shares' => $shares,
1230
-						'objectData' => $objectRow,
1231
-					]
1232
-				));
1233
-			} else {
1234
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1235
-
1236
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1237
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1238
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1239
-					[
1240
-						'subscriptionId' => $calendarId,
1241
-						'calendarData' => $subscriptionRow,
1242
-						'shares' => [],
1243
-						'objectData' => $objectRow,
1244
-					]
1245
-				));
1246
-			}
1247
-		}
1248
-
1249
-		return '"' . $extraData['etag'] . '"';
1250
-	}
1251
-
1252
-	/**
1253
-	 * @param int $calendarObjectId
1254
-	 * @param int $classification
1255
-	 */
1256
-	public function setClassification($calendarObjectId, $classification) {
1257
-		if (!in_array($classification, [
1258
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1259
-		])) {
1260
-			throw new \InvalidArgumentException();
1261
-		}
1262
-		$query = $this->db->getQueryBuilder();
1263
-		$query->update('calendarobjects')
1264
-			->set('classification', $query->createNamedParameter($classification))
1265
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1266
-			->execute();
1267
-	}
1268
-
1269
-	/**
1270
-	 * Deletes an existing calendar object.
1271
-	 *
1272
-	 * The object uri is only the basename, or filename and not a full path.
1273
-	 *
1274
-	 * @param mixed $calendarId
1275
-	 * @param string $objectUri
1276
-	 * @param int $calendarType
1277
-	 * @return void
1278
-	 */
1279
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1280
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1281
-		if (is_array($data)) {
1282
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1283
-				$calendarRow = $this->getCalendarById($calendarId);
1284
-				$shares = $this->getShares($calendarId);
1285
-
1286
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1287
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1288
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1289
-					[
1290
-						'calendarId' => $calendarId,
1291
-						'calendarData' => $calendarRow,
1292
-						'shares' => $shares,
1293
-						'objectData' => $data,
1294
-					]
1295
-				));
1296
-			} else {
1297
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1298
-
1299
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1300
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1301
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1302
-					[
1303
-						'subscriptionId' => $calendarId,
1304
-						'calendarData' => $subscriptionRow,
1305
-						'shares' => [],
1306
-						'objectData' => $data,
1307
-					]
1308
-				));
1309
-			}
1310
-		}
1311
-
1312
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1313
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1314
-
1315
-		if (is_array($data)) {
1316
-			$this->purgeProperties($calendarId, $data['id'], $calendarType);
1317
-		}
1318
-
1319
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1320
-	}
1321
-
1322
-	/**
1323
-	 * Performs a calendar-query on the contents of this calendar.
1324
-	 *
1325
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1326
-	 * calendar-query it is possible for a client to request a specific set of
1327
-	 * object, based on contents of iCalendar properties, date-ranges and
1328
-	 * iCalendar component types (VTODO, VEVENT).
1329
-	 *
1330
-	 * This method should just return a list of (relative) urls that match this
1331
-	 * query.
1332
-	 *
1333
-	 * The list of filters are specified as an array. The exact array is
1334
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1335
-	 *
1336
-	 * Note that it is extremely likely that getCalendarObject for every path
1337
-	 * returned from this method will be called almost immediately after. You
1338
-	 * may want to anticipate this to speed up these requests.
1339
-	 *
1340
-	 * This method provides a default implementation, which parses *all* the
1341
-	 * iCalendar objects in the specified calendar.
1342
-	 *
1343
-	 * This default may well be good enough for personal use, and calendars
1344
-	 * that aren't very large. But if you anticipate high usage, big calendars
1345
-	 * or high loads, you are strongly advised to optimize certain paths.
1346
-	 *
1347
-	 * The best way to do so is override this method and to optimize
1348
-	 * specifically for 'common filters'.
1349
-	 *
1350
-	 * Requests that are extremely common are:
1351
-	 *   * requests for just VEVENTS
1352
-	 *   * requests for just VTODO
1353
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1354
-	 *
1355
-	 * ..and combinations of these requests. It may not be worth it to try to
1356
-	 * handle every possible situation and just rely on the (relatively
1357
-	 * easy to use) CalendarQueryValidator to handle the rest.
1358
-	 *
1359
-	 * Note that especially time-range-filters may be difficult to parse. A
1360
-	 * time-range filter specified on a VEVENT must for instance also handle
1361
-	 * recurrence rules correctly.
1362
-	 * A good example of how to interprete all these filters can also simply
1363
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1364
-	 * as possible, so it gives you a good idea on what type of stuff you need
1365
-	 * to think of.
1366
-	 *
1367
-	 * @param mixed $calendarId
1368
-	 * @param array $filters
1369
-	 * @param int $calendarType
1370
-	 * @return array
1371
-	 */
1372
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1373
-		$componentType = null;
1374
-		$requirePostFilter = true;
1375
-		$timeRange = null;
1376
-
1377
-		// if no filters were specified, we don't need to filter after a query
1378
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1379
-			$requirePostFilter = false;
1380
-		}
1381
-
1382
-		// Figuring out if there's a component filter
1383
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1384
-			$componentType = $filters['comp-filters'][0]['name'];
1385
-
1386
-			// Checking if we need post-filters
1387
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1388
-				$requirePostFilter = false;
1389
-			}
1390
-			// There was a time-range filter
1391
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1392
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1393
-
1394
-				// If start time OR the end time is not specified, we can do a
1395
-				// 100% accurate mysql query.
1396
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1397
-					$requirePostFilter = false;
1398
-				}
1399
-			}
1400
-		}
1401
-		$columns = ['uri'];
1402
-		if ($requirePostFilter) {
1403
-			$columns = ['uri', 'calendardata'];
1404
-		}
1405
-		$query = $this->db->getQueryBuilder();
1406
-		$query->select($columns)
1407
-			->from('calendarobjects')
1408
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1409
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1410
-
1411
-		if ($componentType) {
1412
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1413
-		}
1414
-
1415
-		if ($timeRange && $timeRange['start']) {
1416
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1417
-		}
1418
-		if ($timeRange && $timeRange['end']) {
1419
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1420
-		}
1421
-
1422
-		$stmt = $query->execute();
1423
-
1424
-		$result = [];
1425
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1426
-			if ($requirePostFilter) {
1427
-				// validateFilterForObject will parse the calendar data
1428
-				// catch parsing errors
1429
-				try {
1430
-					$matches = $this->validateFilterForObject($row, $filters);
1431
-				} catch (ParseException $ex) {
1432
-					$this->logger->logException($ex, [
1433
-						'app' => 'dav',
1434
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1435
-					]);
1436
-					continue;
1437
-				} catch (InvalidDataException $ex) {
1438
-					$this->logger->logException($ex, [
1439
-						'app' => 'dav',
1440
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1441
-					]);
1442
-					continue;
1443
-				}
1444
-
1445
-				if (!$matches) {
1446
-					continue;
1447
-				}
1448
-			}
1449
-			$result[] = $row['uri'];
1450
-		}
1451
-
1452
-		return $result;
1453
-	}
1454
-
1455
-	/**
1456
-	 * custom Nextcloud search extension for CalDAV
1457
-	 *
1458
-	 * TODO - this should optionally cover cached calendar objects as well
1459
-	 *
1460
-	 * @param string $principalUri
1461
-	 * @param array $filters
1462
-	 * @param integer|null $limit
1463
-	 * @param integer|null $offset
1464
-	 * @return array
1465
-	 */
1466
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1467
-		$calendars = $this->getCalendarsForUser($principalUri);
1468
-		$ownCalendars = [];
1469
-		$sharedCalendars = [];
1470
-
1471
-		$uriMapper = [];
1472
-
1473
-		foreach ($calendars as $calendar) {
1474
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1475
-				$ownCalendars[] = $calendar['id'];
1476
-			} else {
1477
-				$sharedCalendars[] = $calendar['id'];
1478
-			}
1479
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1480
-		}
1481
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1482
-			return [];
1483
-		}
1484
-
1485
-		$query = $this->db->getQueryBuilder();
1486
-		// Calendar id expressions
1487
-		$calendarExpressions = [];
1488
-		foreach ($ownCalendars as $id) {
1489
-			$calendarExpressions[] = $query->expr()->andX(
1490
-				$query->expr()->eq('c.calendarid',
1491
-					$query->createNamedParameter($id)),
1492
-				$query->expr()->eq('c.calendartype',
1493
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1494
-		}
1495
-		foreach ($sharedCalendars as $id) {
1496
-			$calendarExpressions[] = $query->expr()->andX(
1497
-				$query->expr()->eq('c.calendarid',
1498
-					$query->createNamedParameter($id)),
1499
-				$query->expr()->eq('c.classification',
1500
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1501
-				$query->expr()->eq('c.calendartype',
1502
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1503
-		}
1504
-
1505
-		if (count($calendarExpressions) === 1) {
1506
-			$calExpr = $calendarExpressions[0];
1507
-		} else {
1508
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1509
-		}
1510
-
1511
-		// Component expressions
1512
-		$compExpressions = [];
1513
-		foreach ($filters['comps'] as $comp) {
1514
-			$compExpressions[] = $query->expr()
1515
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1516
-		}
1517
-
1518
-		if (count($compExpressions) === 1) {
1519
-			$compExpr = $compExpressions[0];
1520
-		} else {
1521
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1522
-		}
1523
-
1524
-		if (!isset($filters['props'])) {
1525
-			$filters['props'] = [];
1526
-		}
1527
-		if (!isset($filters['params'])) {
1528
-			$filters['params'] = [];
1529
-		}
1530
-
1531
-		$propParamExpressions = [];
1532
-		foreach ($filters['props'] as $prop) {
1533
-			$propParamExpressions[] = $query->expr()->andX(
1534
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1535
-				$query->expr()->isNull('i.parameter')
1536
-			);
1537
-		}
1538
-		foreach ($filters['params'] as $param) {
1539
-			$propParamExpressions[] = $query->expr()->andX(
1540
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1541
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1542
-			);
1543
-		}
1544
-
1545
-		if (count($propParamExpressions) === 1) {
1546
-			$propParamExpr = $propParamExpressions[0];
1547
-		} else {
1548
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1549
-		}
1550
-
1551
-		$query->select(['c.calendarid', 'c.uri'])
1552
-			->from($this->dbObjectPropertiesTable, 'i')
1553
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1554
-			->where($calExpr)
1555
-			->andWhere($compExpr)
1556
-			->andWhere($propParamExpr)
1557
-			->andWhere($query->expr()->iLike('i.value',
1558
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1559
-
1560
-		if ($offset) {
1561
-			$query->setFirstResult($offset);
1562
-		}
1563
-		if ($limit) {
1564
-			$query->setMaxResults($limit);
1565
-		}
1566
-
1567
-		$stmt = $query->execute();
1568
-
1569
-		$result = [];
1570
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1571
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1572
-			if (!in_array($path, $result)) {
1573
-				$result[] = $path;
1574
-			}
1575
-		}
1576
-
1577
-		return $result;
1578
-	}
1579
-
1580
-	/**
1581
-	 * used for Nextcloud's calendar API
1582
-	 *
1583
-	 * @param array $calendarInfo
1584
-	 * @param string $pattern
1585
-	 * @param array $searchProperties
1586
-	 * @param array $options
1587
-	 * @param integer|null $limit
1588
-	 * @param integer|null $offset
1589
-	 *
1590
-	 * @return array
1591
-	 */
1592
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1593
-						   array $options, $limit, $offset) {
1594
-		$outerQuery = $this->db->getQueryBuilder();
1595
-		$innerQuery = $this->db->getQueryBuilder();
1596
-
1597
-		$innerQuery->selectDistinct('op.objectid')
1598
-			->from($this->dbObjectPropertiesTable, 'op')
1599
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1600
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1601
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1602
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1603
-
1604
-		// only return public items for shared calendars for now
1605
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1606
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1607
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1608
-		}
1609
-
1610
-		$or = $innerQuery->expr()->orX();
1611
-		foreach ($searchProperties as $searchProperty) {
1612
-			$or->add($innerQuery->expr()->eq('op.name',
1613
-				$outerQuery->createNamedParameter($searchProperty)));
1614
-		}
1615
-		$innerQuery->andWhere($or);
1616
-
1617
-		if ($pattern !== '') {
1618
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1619
-				$outerQuery->createNamedParameter('%' .
1620
-					$this->db->escapeLikeParameter($pattern) . '%')));
1621
-		}
1622
-
1623
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1624
-			->from('calendarobjects', 'c');
1625
-
1626
-		if (isset($options['timerange'])) {
1627
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1628
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1629
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1630
-			}
1631
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1632
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1633
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1634
-			}
1635
-		}
1636
-
1637
-		if (isset($options['types'])) {
1638
-			$or = $outerQuery->expr()->orX();
1639
-			foreach ($options['types'] as $type) {
1640
-				$or->add($outerQuery->expr()->eq('componenttype',
1641
-					$outerQuery->createNamedParameter($type)));
1642
-			}
1643
-			$outerQuery->andWhere($or);
1644
-		}
1645
-
1646
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1647
-			$outerQuery->createFunction($innerQuery->getSQL())));
1648
-
1649
-		if ($offset) {
1650
-			$outerQuery->setFirstResult($offset);
1651
-		}
1652
-		if ($limit) {
1653
-			$outerQuery->setMaxResults($limit);
1654
-		}
1655
-
1656
-		$result = $outerQuery->execute();
1657
-		$calendarObjects = $result->fetchAll();
1658
-
1659
-		return array_map(function ($o) {
1660
-			$calendarData = Reader::read($o['calendardata']);
1661
-			$comps = $calendarData->getComponents();
1662
-			$objects = [];
1663
-			$timezones = [];
1664
-			foreach ($comps as $comp) {
1665
-				if ($comp instanceof VTimeZone) {
1666
-					$timezones[] = $comp;
1667
-				} else {
1668
-					$objects[] = $comp;
1669
-				}
1670
-			}
1671
-
1672
-			return [
1673
-				'id' => $o['id'],
1674
-				'type' => $o['componenttype'],
1675
-				'uid' => $o['uid'],
1676
-				'uri' => $o['uri'],
1677
-				'objects' => array_map(function ($c) {
1678
-					return $this->transformSearchData($c);
1679
-				}, $objects),
1680
-				'timezones' => array_map(function ($c) {
1681
-					return $this->transformSearchData($c);
1682
-				}, $timezones),
1683
-			];
1684
-		}, $calendarObjects);
1685
-	}
1686
-
1687
-	/**
1688
-	 * @param Component $comp
1689
-	 * @return array
1690
-	 */
1691
-	private function transformSearchData(Component $comp) {
1692
-		$data = [];
1693
-		/** @var Component[] $subComponents */
1694
-		$subComponents = $comp->getComponents();
1695
-		/** @var Property[] $properties */
1696
-		$properties = array_filter($comp->children(), function ($c) {
1697
-			return $c instanceof Property;
1698
-		});
1699
-		$validationRules = $comp->getValidationRules();
1700
-
1701
-		foreach ($subComponents as $subComponent) {
1702
-			$name = $subComponent->name;
1703
-			if (!isset($data[$name])) {
1704
-				$data[$name] = [];
1705
-			}
1706
-			$data[$name][] = $this->transformSearchData($subComponent);
1707
-		}
1708
-
1709
-		foreach ($properties as $property) {
1710
-			$name = $property->name;
1711
-			if (!isset($validationRules[$name])) {
1712
-				$validationRules[$name] = '*';
1713
-			}
1714
-
1715
-			$rule = $validationRules[$property->name];
1716
-			if ($rule === '+' || $rule === '*') { // multiple
1717
-				if (!isset($data[$name])) {
1718
-					$data[$name] = [];
1719
-				}
1720
-
1721
-				$data[$name][] = $this->transformSearchProperty($property);
1722
-			} else { // once
1723
-				$data[$name] = $this->transformSearchProperty($property);
1724
-			}
1725
-		}
1726
-
1727
-		return $data;
1728
-	}
1729
-
1730
-	/**
1731
-	 * @param Property $prop
1732
-	 * @return array
1733
-	 */
1734
-	private function transformSearchProperty(Property $prop) {
1735
-		// No need to check Date, as it extends DateTime
1736
-		if ($prop instanceof Property\ICalendar\DateTime) {
1737
-			$value = $prop->getDateTime();
1738
-		} else {
1739
-			$value = $prop->getValue();
1740
-		}
1741
-
1742
-		return [
1743
-			$value,
1744
-			$prop->parameters()
1745
-		];
1746
-	}
1747
-
1748
-	/**
1749
-	 * @param string $principalUri
1750
-	 * @param string $pattern
1751
-	 * @param array $componentTypes
1752
-	 * @param array $searchProperties
1753
-	 * @param array $searchParameters
1754
-	 * @param array $options
1755
-	 * @return array
1756
-	 */
1757
-	public function searchPrincipalUri(string $principalUri,
1758
-									   string $pattern,
1759
-									   array $componentTypes,
1760
-									   array $searchProperties,
1761
-									   array $searchParameters,
1762
-									   array $options = []): array {
1763
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1764
-
1765
-		$calendarObjectIdQuery = $this->db->getQueryBuilder();
1766
-		$calendarOr = $calendarObjectIdQuery->expr()->orX();
1767
-		$searchOr = $calendarObjectIdQuery->expr()->orX();
1768
-
1769
-		// Fetch calendars and subscription
1770
-		$calendars = $this->getCalendarsForUser($principalUri);
1771
-		$subscriptions = $this->getSubscriptionsForUser($principalUri);
1772
-		foreach ($calendars as $calendar) {
1773
-			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
1774
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1775
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1776
-
1777
-			// If it's shared, limit search to public events
1778
-			if ($calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1779
-				$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1780
-			}
1781
-
1782
-			$calendarOr->add($calendarAnd);
1783
-		}
1784
-		foreach ($subscriptions as $subscription) {
1785
-			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1786
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1787
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1788
-
1789
-			// If it's shared, limit search to public events
1790
-			if ($subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1791
-				$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1792
-			}
1793
-
1794
-			$calendarOr->add($subscriptionAnd);
1795
-		}
1796
-
1797
-		foreach ($searchProperties as $property) {
1798
-			$propertyAnd = $calendarObjectIdQuery->expr()->andX();
1799
-			$propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1800
-			$propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1801
-
1802
-			$searchOr->add($propertyAnd);
1803
-		}
1804
-		foreach ($searchParameters as $property => $parameter) {
1805
-			$parameterAnd = $calendarObjectIdQuery->expr()->andX();
1806
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1807
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
1808
-
1809
-			$searchOr->add($parameterAnd);
1810
-		}
1811
-
1812
-		if ($calendarOr->count() === 0) {
1813
-			return [];
1814
-		}
1815
-		if ($searchOr->count() === 0) {
1816
-			return [];
1817
-		}
1818
-
1819
-		$calendarObjectIdQuery->selectDistinct('cob.objectid')
1820
-			->from($this->dbObjectPropertiesTable, 'cob')
1821
-			->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1822
-			->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1823
-			->andWhere($calendarOr)
1824
-			->andWhere($searchOr);
1825
-
1826
-		if ('' !== $pattern) {
1827
-			if (!$escapePattern) {
1828
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1829
-			} else {
1830
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1831
-			}
1832
-		}
1833
-
1834
-		if (isset($options['limit'])) {
1835
-			$calendarObjectIdQuery->setMaxResults($options['limit']);
1836
-		}
1837
-		if (isset($options['offset'])) {
1838
-			$calendarObjectIdQuery->setFirstResult($options['offset']);
1839
-		}
1840
-
1841
-		$result = $calendarObjectIdQuery->execute();
1842
-		$matches = $result->fetchAll();
1843
-		$result->closeCursor();
1844
-		$matches = array_map(static function (array $match):int {
1845
-			return (int) $match['objectid'];
1846
-		}, $matches);
1847
-
1848
-		$query = $this->db->getQueryBuilder();
1849
-		$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1850
-			->from('calendarobjects')
1851
-			->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1852
-
1853
-		$result = $query->execute();
1854
-		$calendarObjects = $result->fetchAll();
1855
-		$result->closeCursor();
1856
-
1857
-		return array_map(function (array $array): array {
1858
-			$array['calendarid'] = (int)$array['calendarid'];
1859
-			$array['calendartype'] = (int)$array['calendartype'];
1860
-			$array['calendardata'] = $this->readBlob($array['calendardata']);
1861
-
1862
-			return $array;
1863
-		}, $calendarObjects);
1864
-	}
1865
-
1866
-	/**
1867
-	 * Searches through all of a users calendars and calendar objects to find
1868
-	 * an object with a specific UID.
1869
-	 *
1870
-	 * This method should return the path to this object, relative to the
1871
-	 * calendar home, so this path usually only contains two parts:
1872
-	 *
1873
-	 * calendarpath/objectpath.ics
1874
-	 *
1875
-	 * If the uid is not found, return null.
1876
-	 *
1877
-	 * This method should only consider * objects that the principal owns, so
1878
-	 * any calendars owned by other principals that also appear in this
1879
-	 * collection should be ignored.
1880
-	 *
1881
-	 * @param string $principalUri
1882
-	 * @param string $uid
1883
-	 * @return string|null
1884
-	 */
1885
-	public function getCalendarObjectByUID($principalUri, $uid) {
1886
-		$query = $this->db->getQueryBuilder();
1887
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1888
-			->from('calendarobjects', 'co')
1889
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1890
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1891
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1892
-
1893
-		$stmt = $query->execute();
1894
-
1895
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1896
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1897
-		}
1898
-
1899
-		return null;
1900
-	}
1901
-
1902
-	/**
1903
-	 * The getChanges method returns all the changes that have happened, since
1904
-	 * the specified syncToken in the specified calendar.
1905
-	 *
1906
-	 * This function should return an array, such as the following:
1907
-	 *
1908
-	 * [
1909
-	 *   'syncToken' => 'The current synctoken',
1910
-	 *   'added'   => [
1911
-	 *      'new.txt',
1912
-	 *   ],
1913
-	 *   'modified'   => [
1914
-	 *      'modified.txt',
1915
-	 *   ],
1916
-	 *   'deleted' => [
1917
-	 *      'foo.php.bak',
1918
-	 *      'old.txt'
1919
-	 *   ]
1920
-	 * );
1921
-	 *
1922
-	 * The returned syncToken property should reflect the *current* syncToken
1923
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1924
-	 * property This is * needed here too, to ensure the operation is atomic.
1925
-	 *
1926
-	 * If the $syncToken argument is specified as null, this is an initial
1927
-	 * sync, and all members should be reported.
1928
-	 *
1929
-	 * The modified property is an array of nodenames that have changed since
1930
-	 * the last token.
1931
-	 *
1932
-	 * The deleted property is an array with nodenames, that have been deleted
1933
-	 * from collection.
1934
-	 *
1935
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1936
-	 * 1, you only have to report changes that happened only directly in
1937
-	 * immediate descendants. If it's 2, it should also include changes from
1938
-	 * the nodes below the child collections. (grandchildren)
1939
-	 *
1940
-	 * The $limit argument allows a client to specify how many results should
1941
-	 * be returned at most. If the limit is not specified, it should be treated
1942
-	 * as infinite.
1943
-	 *
1944
-	 * If the limit (infinite or not) is higher than you're willing to return,
1945
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1946
-	 *
1947
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1948
-	 * return null.
1949
-	 *
1950
-	 * The limit is 'suggestive'. You are free to ignore it.
1951
-	 *
1952
-	 * @param string $calendarId
1953
-	 * @param string $syncToken
1954
-	 * @param int $syncLevel
1955
-	 * @param int $limit
1956
-	 * @param int $calendarType
1957
-	 * @return array
1958
-	 */
1959
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1960
-		// Current synctoken
1961
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1962
-		$stmt->execute([ $calendarId ]);
1963
-		$currentToken = $stmt->fetchColumn(0);
1964
-
1965
-		if (is_null($currentToken)) {
1966
-			return null;
1967
-		}
1968
-
1969
-		$result = [
1970
-			'syncToken' => $currentToken,
1971
-			'added' => [],
1972
-			'modified' => [],
1973
-			'deleted' => [],
1974
-		];
1975
-
1976
-		if ($syncToken) {
1977
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1978
-			if ($limit > 0) {
1979
-				$query .= " LIMIT " . (int)$limit;
1980
-			}
1981
-
1982
-			// Fetching all changes
1983
-			$stmt = $this->db->prepare($query);
1984
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1985
-
1986
-			$changes = [];
1987
-
1988
-			// This loop ensures that any duplicates are overwritten, only the
1989
-			// last change on a node is relevant.
1990
-			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1991
-				$changes[$row['uri']] = $row['operation'];
1992
-			}
1993
-
1994
-			foreach ($changes as $uri => $operation) {
1995
-				switch ($operation) {
1996
-					case 1:
1997
-						$result['added'][] = $uri;
1998
-						break;
1999
-					case 2:
2000
-						$result['modified'][] = $uri;
2001
-						break;
2002
-					case 3:
2003
-						$result['deleted'][] = $uri;
2004
-						break;
2005
-				}
2006
-			}
2007
-		} else {
2008
-			// No synctoken supplied, this is the initial sync.
2009
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
2010
-			$stmt = $this->db->prepare($query);
2011
-			$stmt->execute([$calendarId, $calendarType]);
2012
-
2013
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2014
-		}
2015
-		return $result;
2016
-	}
2017
-
2018
-	/**
2019
-	 * Returns a list of subscriptions for a principal.
2020
-	 *
2021
-	 * Every subscription is an array with the following keys:
2022
-	 *  * id, a unique id that will be used by other functions to modify the
2023
-	 *    subscription. This can be the same as the uri or a database key.
2024
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2025
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2026
-	 *    principalUri passed to this method.
2027
-	 *
2028
-	 * Furthermore, all the subscription info must be returned too:
2029
-	 *
2030
-	 * 1. {DAV:}displayname
2031
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2032
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2033
-	 *    should not be stripped).
2034
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2035
-	 *    should not be stripped).
2036
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2037
-	 *    attachments should not be stripped).
2038
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2039
-	 *     Sabre\DAV\Property\Href).
2040
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2041
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2042
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2043
-	 *    (should just be an instance of
2044
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2045
-	 *    default components).
2046
-	 *
2047
-	 * @param string $principalUri
2048
-	 * @return array
2049
-	 */
2050
-	public function getSubscriptionsForUser($principalUri) {
2051
-		$fields = array_values($this->subscriptionPropertyMap);
2052
-		$fields[] = 'id';
2053
-		$fields[] = 'uri';
2054
-		$fields[] = 'source';
2055
-		$fields[] = 'principaluri';
2056
-		$fields[] = 'lastmodified';
2057
-		$fields[] = 'synctoken';
2058
-
2059
-		$query = $this->db->getQueryBuilder();
2060
-		$query->select($fields)
2061
-			->from('calendarsubscriptions')
2062
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2063
-			->orderBy('calendarorder', 'asc');
2064
-		$stmt = $query->execute();
2065
-
2066
-		$subscriptions = [];
2067
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2068
-			$subscription = [
2069
-				'id' => $row['id'],
2070
-				'uri' => $row['uri'],
2071
-				'principaluri' => $row['principaluri'],
2072
-				'source' => $row['source'],
2073
-				'lastmodified' => $row['lastmodified'],
2074
-
2075
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2076
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2077
-			];
2078
-
2079
-			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2080
-				if (!is_null($row[$dbName])) {
2081
-					$subscription[$xmlName] = $row[$dbName];
2082
-				}
2083
-			}
2084
-
2085
-			$subscriptions[] = $subscription;
2086
-		}
2087
-
2088
-		return $subscriptions;
2089
-	}
2090
-
2091
-	/**
2092
-	 * Creates a new subscription for a principal.
2093
-	 *
2094
-	 * If the creation was a success, an id must be returned that can be used to reference
2095
-	 * this subscription in other methods, such as updateSubscription.
2096
-	 *
2097
-	 * @param string $principalUri
2098
-	 * @param string $uri
2099
-	 * @param array $properties
2100
-	 * @return mixed
2101
-	 */
2102
-	public function createSubscription($principalUri, $uri, array $properties) {
2103
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2104
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2105
-		}
2106
-
2107
-		$values = [
2108
-			'principaluri' => $principalUri,
2109
-			'uri' => $uri,
2110
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2111
-			'lastmodified' => time(),
2112
-		];
2113
-
2114
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2115
-
2116
-		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2117
-			if (array_key_exists($xmlName, $properties)) {
2118
-				$values[$dbName] = $properties[$xmlName];
2119
-				if (in_array($dbName, $propertiesBoolean)) {
2120
-					$values[$dbName] = true;
2121
-				}
2122
-			}
2123
-		}
2124
-
2125
-		$valuesToInsert = [];
2126
-
2127
-		$query = $this->db->getQueryBuilder();
2128
-
2129
-		foreach (array_keys($values) as $name) {
2130
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2131
-		}
2132
-
2133
-		$query->insert('calendarsubscriptions')
2134
-			->values($valuesToInsert)
2135
-			->execute();
2136
-
2137
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
2138
-
2139
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2140
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent((int)$subscriptionId, $subscriptionRow));
2141
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2142
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2143
-			[
2144
-				'subscriptionId' => $subscriptionId,
2145
-				'subscriptionData' => $subscriptionRow,
2146
-			]));
2147
-
2148
-		return $subscriptionId;
2149
-	}
2150
-
2151
-	/**
2152
-	 * Updates a subscription
2153
-	 *
2154
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2155
-	 * To do the actual updates, you must tell this object which properties
2156
-	 * you're going to process with the handle() method.
2157
-	 *
2158
-	 * Calling the handle method is like telling the PropPatch object "I
2159
-	 * promise I can handle updating this property".
2160
-	 *
2161
-	 * Read the PropPatch documentation for more info and examples.
2162
-	 *
2163
-	 * @param mixed $subscriptionId
2164
-	 * @param PropPatch $propPatch
2165
-	 * @return void
2166
-	 */
2167
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2168
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2169
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2170
-
2171
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2172
-			$newValues = [];
2173
-
2174
-			foreach ($mutations as $propertyName => $propertyValue) {
2175
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2176
-					$newValues['source'] = $propertyValue->getHref();
2177
-				} else {
2178
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2179
-					$newValues[$fieldName] = $propertyValue;
2180
-				}
2181
-			}
2182
-
2183
-			$query = $this->db->getQueryBuilder();
2184
-			$query->update('calendarsubscriptions')
2185
-				->set('lastmodified', $query->createNamedParameter(time()));
2186
-			foreach ($newValues as $fieldName => $value) {
2187
-				$query->set($fieldName, $query->createNamedParameter($value));
2188
-			}
2189
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2190
-				->execute();
2191
-
2192
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2193
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2194
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2195
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2196
-				[
2197
-					'subscriptionId' => $subscriptionId,
2198
-					'subscriptionData' => $subscriptionRow,
2199
-					'propertyMutations' => $mutations,
2200
-				]));
2201
-
2202
-			return true;
2203
-		});
2204
-	}
2205
-
2206
-	/**
2207
-	 * Deletes a subscription.
2208
-	 *
2209
-	 * @param mixed $subscriptionId
2210
-	 * @return void
2211
-	 */
2212
-	public function deleteSubscription($subscriptionId) {
2213
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2214
-
2215
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2216
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2217
-			[
2218
-				'subscriptionId' => $subscriptionId,
2219
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2220
-			]));
2221
-
2222
-		$query = $this->db->getQueryBuilder();
2223
-		$query->delete('calendarsubscriptions')
2224
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2225
-			->execute();
2226
-
2227
-		$query = $this->db->getQueryBuilder();
2228
-		$query->delete('calendarobjects')
2229
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2230
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2231
-			->execute();
2232
-
2233
-		$query->delete('calendarchanges')
2234
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2235
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2236
-			->execute();
2237
-
2238
-		$query->delete($this->dbObjectPropertiesTable)
2239
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2240
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2241
-			->execute();
2242
-
2243
-		if ($subscriptionRow) {
2244
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2245
-		}
2246
-	}
2247
-
2248
-	/**
2249
-	 * Returns a single scheduling object for the inbox collection.
2250
-	 *
2251
-	 * The returned array should contain the following elements:
2252
-	 *   * uri - A unique basename for the object. This will be used to
2253
-	 *           construct a full uri.
2254
-	 *   * calendardata - The iCalendar object
2255
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2256
-	 *                    timestamp, or a PHP DateTime object.
2257
-	 *   * etag - A unique token that must change if the object changed.
2258
-	 *   * size - The size of the object, in bytes.
2259
-	 *
2260
-	 * @param string $principalUri
2261
-	 * @param string $objectUri
2262
-	 * @return array
2263
-	 */
2264
-	public function getSchedulingObject($principalUri, $objectUri) {
2265
-		$query = $this->db->getQueryBuilder();
2266
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2267
-			->from('schedulingobjects')
2268
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2269
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2270
-			->execute();
2271
-
2272
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2273
-
2274
-		if (!$row) {
2275
-			return null;
2276
-		}
2277
-
2278
-		return [
2279
-			'uri' => $row['uri'],
2280
-			'calendardata' => $row['calendardata'],
2281
-			'lastmodified' => $row['lastmodified'],
2282
-			'etag' => '"' . $row['etag'] . '"',
2283
-			'size' => (int)$row['size'],
2284
-		];
2285
-	}
2286
-
2287
-	/**
2288
-	 * Returns all scheduling objects for the inbox collection.
2289
-	 *
2290
-	 * These objects should be returned as an array. Every item in the array
2291
-	 * should follow the same structure as returned from getSchedulingObject.
2292
-	 *
2293
-	 * The main difference is that 'calendardata' is optional.
2294
-	 *
2295
-	 * @param string $principalUri
2296
-	 * @return array
2297
-	 */
2298
-	public function getSchedulingObjects($principalUri) {
2299
-		$query = $this->db->getQueryBuilder();
2300
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2301
-				->from('schedulingobjects')
2302
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2303
-				->execute();
2304
-
2305
-		$result = [];
2306
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2307
-			$result[] = [
2308
-				'calendardata' => $row['calendardata'],
2309
-				'uri' => $row['uri'],
2310
-				'lastmodified' => $row['lastmodified'],
2311
-				'etag' => '"' . $row['etag'] . '"',
2312
-				'size' => (int)$row['size'],
2313
-			];
2314
-		}
2315
-
2316
-		return $result;
2317
-	}
2318
-
2319
-	/**
2320
-	 * Deletes a scheduling object from the inbox collection.
2321
-	 *
2322
-	 * @param string $principalUri
2323
-	 * @param string $objectUri
2324
-	 * @return void
2325
-	 */
2326
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2327
-		$query = $this->db->getQueryBuilder();
2328
-		$query->delete('schedulingobjects')
2329
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2330
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2331
-				->execute();
2332
-	}
2333
-
2334
-	/**
2335
-	 * Creates a new scheduling object. This should land in a users' inbox.
2336
-	 *
2337
-	 * @param string $principalUri
2338
-	 * @param string $objectUri
2339
-	 * @param string $objectData
2340
-	 * @return void
2341
-	 */
2342
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2343
-		$query = $this->db->getQueryBuilder();
2344
-		$query->insert('schedulingobjects')
2345
-			->values([
2346
-				'principaluri' => $query->createNamedParameter($principalUri),
2347
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2348
-				'uri' => $query->createNamedParameter($objectUri),
2349
-				'lastmodified' => $query->createNamedParameter(time()),
2350
-				'etag' => $query->createNamedParameter(md5($objectData)),
2351
-				'size' => $query->createNamedParameter(strlen($objectData))
2352
-			])
2353
-			->execute();
2354
-	}
2355
-
2356
-	/**
2357
-	 * Adds a change record to the calendarchanges table.
2358
-	 *
2359
-	 * @param mixed $calendarId
2360
-	 * @param string $objectUri
2361
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2362
-	 * @param int $calendarType
2363
-	 * @return void
2364
-	 */
2365
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2366
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2367
-
2368
-		$query = $this->db->getQueryBuilder();
2369
-		$query->select('synctoken')
2370
-			->from($table)
2371
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2372
-		$result = $query->execute();
2373
-		$syncToken = (int)$result->fetchColumn();
2374
-		$result->closeCursor();
2375
-
2376
-		$query = $this->db->getQueryBuilder();
2377
-		$query->insert('calendarchanges')
2378
-			->values([
2379
-				'uri' => $query->createNamedParameter($objectUri),
2380
-				'synctoken' => $query->createNamedParameter($syncToken),
2381
-				'calendarid' => $query->createNamedParameter($calendarId),
2382
-				'operation' => $query->createNamedParameter($operation),
2383
-				'calendartype' => $query->createNamedParameter($calendarType),
2384
-			])
2385
-			->execute();
2386
-
2387
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2388
-		$stmt->execute([
2389
-			$calendarId
2390
-		]);
2391
-	}
2392
-
2393
-	/**
2394
-	 * Parses some information from calendar objects, used for optimized
2395
-	 * calendar-queries.
2396
-	 *
2397
-	 * Returns an array with the following keys:
2398
-	 *   * etag - An md5 checksum of the object without the quotes.
2399
-	 *   * size - Size of the object in bytes
2400
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2401
-	 *   * firstOccurence
2402
-	 *   * lastOccurence
2403
-	 *   * uid - value of the UID property
2404
-	 *
2405
-	 * @param string $calendarData
2406
-	 * @return array
2407
-	 */
2408
-	public function getDenormalizedData($calendarData) {
2409
-		$vObject = Reader::read($calendarData);
2410
-		$vEvents = [];
2411
-		$componentType = null;
2412
-		$component = null;
2413
-		$firstOccurrence = null;
2414
-		$lastOccurrence = null;
2415
-		$uid = null;
2416
-		$classification = self::CLASSIFICATION_PUBLIC;
2417
-		$hasDTSTART = false;
2418
-		foreach ($vObject->getComponents() as $component) {
2419
-			if ($component->name !== 'VTIMEZONE') {
2420
-				// Finding all VEVENTs, and track them
2421
-				if ($component->name === 'VEVENT') {
2422
-					array_push($vEvents, $component);
2423
-					if ($component->DTSTART) {
2424
-						$hasDTSTART = true;
2425
-					}
2426
-				}
2427
-				// Track first component type and uid
2428
-				if ($uid === null) {
2429
-					$componentType = $component->name;
2430
-					$uid = (string)$component->UID;
2431
-				}
2432
-			}
2433
-		}
2434
-		if (!$componentType) {
2435
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2436
-		}
2437
-
2438
-		if ($hasDTSTART) {
2439
-			$component = $vEvents[0];
2440
-
2441
-			// Finding the last occurrence is a bit harder
2442
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
2443
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2444
-				if (isset($component->DTEND)) {
2445
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2446
-				} elseif (isset($component->DURATION)) {
2447
-					$endDate = clone $component->DTSTART->getDateTime();
2448
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2449
-					$lastOccurrence = $endDate->getTimeStamp();
2450
-				} elseif (!$component->DTSTART->hasTime()) {
2451
-					$endDate = clone $component->DTSTART->getDateTime();
2452
-					$endDate->modify('+1 day');
2453
-					$lastOccurrence = $endDate->getTimeStamp();
2454
-				} else {
2455
-					$lastOccurrence = $firstOccurrence;
2456
-				}
2457
-			} else {
2458
-				$it = new EventIterator($vEvents);
2459
-				$maxDate = new DateTime(self::MAX_DATE);
2460
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
2461
-				if ($it->isInfinite()) {
2462
-					$lastOccurrence = $maxDate->getTimestamp();
2463
-				} else {
2464
-					$end = $it->getDtEnd();
2465
-					while ($it->valid() && $end < $maxDate) {
2466
-						$end = $it->getDtEnd();
2467
-						$it->next();
2468
-					}
2469
-					$lastOccurrence = $end->getTimestamp();
2470
-				}
2471
-			}
2472
-		}
2473
-
2474
-		if ($component->CLASS) {
2475
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2476
-			switch ($component->CLASS->getValue()) {
2477
-				case 'PUBLIC':
2478
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2479
-					break;
2480
-				case 'CONFIDENTIAL':
2481
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2482
-					break;
2483
-			}
2484
-		}
2485
-		return [
2486
-			'etag' => md5($calendarData),
2487
-			'size' => strlen($calendarData),
2488
-			'componentType' => $componentType,
2489
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2490
-			'lastOccurence' => $lastOccurrence,
2491
-			'uid' => $uid,
2492
-			'classification' => $classification
2493
-		];
2494
-	}
2495
-
2496
-	/**
2497
-	 * @param $cardData
2498
-	 * @return bool|string
2499
-	 */
2500
-	private function readBlob($cardData) {
2501
-		if (is_resource($cardData)) {
2502
-			return stream_get_contents($cardData);
2503
-		}
2504
-
2505
-		return $cardData;
2506
-	}
2507
-
2508
-	/**
2509
-	 * @param IShareable $shareable
2510
-	 * @param array $add
2511
-	 * @param array $remove
2512
-	 */
2513
-	public function updateShares($shareable, $add, $remove) {
2514
-		$calendarId = $shareable->getResourceId();
2515
-		$calendarRow = $this->getCalendarById($calendarId);
2516
-		$oldShares = $this->getShares($calendarId);
2517
-
2518
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2519
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2520
-			[
2521
-				'calendarId' => $calendarId,
2522
-				'calendarData' => $calendarRow,
2523
-				'shares' => $oldShares,
2524
-				'add' => $add,
2525
-				'remove' => $remove,
2526
-			]));
2527
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2528
-
2529
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2530
-	}
2531
-
2532
-	/**
2533
-	 * @param int $resourceId
2534
-	 * @param int $calendarType
2535
-	 * @return array
2536
-	 */
2537
-	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2538
-		return $this->calendarSharingBackend->getShares($resourceId);
2539
-	}
2540
-
2541
-	/**
2542
-	 * @param boolean $value
2543
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2544
-	 * @return string|null
2545
-	 */
2546
-	public function setPublishStatus($value, $calendar) {
2547
-		$calendarId = $calendar->getResourceId();
2548
-		$calendarData = $this->getCalendarById($calendarId);
2549
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2550
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2551
-			[
2552
-				'calendarId' => $calendarId,
2553
-				'calendarData' => $calendarData,
2554
-				'public' => $value,
2555
-			]));
2556
-
2557
-		$query = $this->db->getQueryBuilder();
2558
-		if ($value) {
2559
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2560
-			$query->insert('dav_shares')
2561
-				->values([
2562
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2563
-					'type' => $query->createNamedParameter('calendar'),
2564
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2565
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2566
-					'publicuri' => $query->createNamedParameter($publicUri)
2567
-				]);
2568
-			$query->execute();
2569
-
2570
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2571
-			return $publicUri;
2572
-		}
2573
-		$query->delete('dav_shares')
2574
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2575
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2576
-		$query->execute();
2577
-
2578
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2579
-		return null;
2580
-	}
2581
-
2582
-	/**
2583
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2584
-	 * @return mixed
2585
-	 */
2586
-	public function getPublishStatus($calendar) {
2587
-		$query = $this->db->getQueryBuilder();
2588
-		$result = $query->select('publicuri')
2589
-			->from('dav_shares')
2590
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2591
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2592
-			->execute();
2593
-
2594
-		$row = $result->fetch();
2595
-		$result->closeCursor();
2596
-		return $row ? reset($row) : false;
2597
-	}
2598
-
2599
-	/**
2600
-	 * @param int $resourceId
2601
-	 * @param array $acl
2602
-	 * @return array
2603
-	 */
2604
-	public function applyShareAcl($resourceId, $acl) {
2605
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2606
-	}
2607
-
2608
-
2609
-
2610
-	/**
2611
-	 * update properties table
2612
-	 *
2613
-	 * @param int $calendarId
2614
-	 * @param string $objectUri
2615
-	 * @param string $calendarData
2616
-	 * @param int $calendarType
2617
-	 */
2618
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2619
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2620
-
2621
-		try {
2622
-			$vCalendar = $this->readCalendarData($calendarData);
2623
-		} catch (\Exception $ex) {
2624
-			return;
2625
-		}
2626
-
2627
-		$this->purgeProperties($calendarId, $objectId);
2628
-
2629
-		$query = $this->db->getQueryBuilder();
2630
-		$query->insert($this->dbObjectPropertiesTable)
2631
-			->values(
2632
-				[
2633
-					'calendarid' => $query->createNamedParameter($calendarId),
2634
-					'calendartype' => $query->createNamedParameter($calendarType),
2635
-					'objectid' => $query->createNamedParameter($objectId),
2636
-					'name' => $query->createParameter('name'),
2637
-					'parameter' => $query->createParameter('parameter'),
2638
-					'value' => $query->createParameter('value'),
2639
-				]
2640
-			);
2641
-
2642
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2643
-		foreach ($vCalendar->getComponents() as $component) {
2644
-			if (!in_array($component->name, $indexComponents)) {
2645
-				continue;
2646
-			}
2647
-
2648
-			foreach ($component->children() as $property) {
2649
-				if (in_array($property->name, self::$indexProperties)) {
2650
-					$value = $property->getValue();
2651
-					// is this a shitty db?
2652
-					if (!$this->db->supports4ByteText()) {
2653
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2654
-					}
2655
-					$value = mb_substr($value, 0, 254);
2656
-
2657
-					$query->setParameter('name', $property->name);
2658
-					$query->setParameter('parameter', null);
2659
-					$query->setParameter('value', $value);
2660
-					$query->execute();
2661
-				}
2662
-
2663
-				if (array_key_exists($property->name, self::$indexParameters)) {
2664
-					$parameters = $property->parameters();
2665
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2666
-
2667
-					foreach ($parameters as $key => $value) {
2668
-						if (in_array($key, $indexedParametersForProperty)) {
2669
-							// is this a shitty db?
2670
-							if ($this->db->supports4ByteText()) {
2671
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2672
-							}
2673
-
2674
-							$query->setParameter('name', $property->name);
2675
-							$query->setParameter('parameter', mb_substr($key, 0, 254));
2676
-							$query->setParameter('value', mb_substr($value, 0, 254));
2677
-							$query->execute();
2678
-						}
2679
-					}
2680
-				}
2681
-			}
2682
-		}
2683
-	}
2684
-
2685
-	/**
2686
-	 * deletes all birthday calendars
2687
-	 */
2688
-	public function deleteAllBirthdayCalendars() {
2689
-		$query = $this->db->getQueryBuilder();
2690
-		$result = $query->select(['id'])->from('calendars')
2691
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2692
-			->execute();
2693
-
2694
-		$ids = $result->fetchAll();
2695
-		foreach ($ids as $id) {
2696
-			$this->deleteCalendar($id['id']);
2697
-		}
2698
-	}
2699
-
2700
-	/**
2701
-	 * @param $subscriptionId
2702
-	 */
2703
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2704
-		$query = $this->db->getQueryBuilder();
2705
-		$query->select('uri')
2706
-			->from('calendarobjects')
2707
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2708
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2709
-		$stmt = $query->execute();
2710
-
2711
-		$uris = [];
2712
-		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2713
-			$uris[] = $row['uri'];
2714
-		}
2715
-		$stmt->closeCursor();
2716
-
2717
-		$query = $this->db->getQueryBuilder();
2718
-		$query->delete('calendarobjects')
2719
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2720
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2721
-			->execute();
2722
-
2723
-		$query->delete('calendarchanges')
2724
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2725
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2726
-			->execute();
2727
-
2728
-		$query->delete($this->dbObjectPropertiesTable)
2729
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2730
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2731
-			->execute();
2732
-
2733
-		foreach ($uris as $uri) {
2734
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2735
-		}
2736
-	}
2737
-
2738
-	/**
2739
-	 * Move a calendar from one user to another
2740
-	 *
2741
-	 * @param string $uriName
2742
-	 * @param string $uriOrigin
2743
-	 * @param string $uriDestination
2744
-	 */
2745
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination) {
2746
-		$query = $this->db->getQueryBuilder();
2747
-		$query->update('calendars')
2748
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2749
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2750
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2751
-			->execute();
2752
-	}
2753
-
2754
-	/**
2755
-	 * read VCalendar data into a VCalendar object
2756
-	 *
2757
-	 * @param string $objectData
2758
-	 * @return VCalendar
2759
-	 */
2760
-	protected function readCalendarData($objectData) {
2761
-		return Reader::read($objectData);
2762
-	}
2763
-
2764
-	/**
2765
-	 * delete all properties from a given calendar object
2766
-	 *
2767
-	 * @param int $calendarId
2768
-	 * @param int $objectId
2769
-	 */
2770
-	protected function purgeProperties($calendarId, $objectId) {
2771
-		$query = $this->db->getQueryBuilder();
2772
-		$query->delete($this->dbObjectPropertiesTable)
2773
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2774
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2775
-		$query->execute();
2776
-	}
2777
-
2778
-	/**
2779
-	 * get ID from a given calendar object
2780
-	 *
2781
-	 * @param int $calendarId
2782
-	 * @param string $uri
2783
-	 * @param int $calendarType
2784
-	 * @return int
2785
-	 */
2786
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2787
-		$query = $this->db->getQueryBuilder();
2788
-		$query->select('id')
2789
-			->from('calendarobjects')
2790
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2791
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2792
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2793
-
2794
-		$result = $query->execute();
2795
-		$objectIds = $result->fetch();
2796
-		$result->closeCursor();
2797
-
2798
-		if (!isset($objectIds['id'])) {
2799
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2800
-		}
2801
-
2802
-		return (int)$objectIds['id'];
2803
-	}
2804
-
2805
-	/**
2806
-	 * return legacy endpoint principal name to new principal name
2807
-	 *
2808
-	 * @param $principalUri
2809
-	 * @param $toV2
2810
-	 * @return string
2811
-	 */
2812
-	private function convertPrincipal($principalUri, $toV2) {
2813
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2814
-			list(, $name) = Uri\split($principalUri);
2815
-			if ($toV2 === true) {
2816
-				return "principals/users/$name";
2817
-			}
2818
-			return "principals/$name";
2819
-		}
2820
-		return $principalUri;
2821
-	}
2822
-
2823
-	/**
2824
-	 * adds information about an owner to the calendar data
2825
-	 *
2826
-	 * @param $calendarInfo
2827
-	 */
2828
-	private function addOwnerPrincipal(&$calendarInfo) {
2829
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2830
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2831
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2832
-			$uri = $calendarInfo[$ownerPrincipalKey];
2833
-		} else {
2834
-			$uri = $calendarInfo['principaluri'];
2835
-		}
2836
-
2837
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2838
-		if (isset($principalInformation['{DAV:}displayname'])) {
2839
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2840
-		}
2841
-	}
98
+    public const CALENDAR_TYPE_CALENDAR = 0;
99
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
100
+
101
+    public const PERSONAL_CALENDAR_URI = 'personal';
102
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
103
+
104
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
105
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
106
+
107
+    /**
108
+     * We need to specify a max date, because we need to stop *somewhere*
109
+     *
110
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
111
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
112
+     * in 2038-01-19 to avoid problems when the date is converted
113
+     * to a unix timestamp.
114
+     */
115
+    public const MAX_DATE = '2038-01-01';
116
+
117
+    public const ACCESS_PUBLIC = 4;
118
+    public const CLASSIFICATION_PUBLIC = 0;
119
+    public const CLASSIFICATION_PRIVATE = 1;
120
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
121
+
122
+    /**
123
+     * List of CalDAV properties, and how they map to database field names
124
+     * Add your own properties by simply adding on to this array.
125
+     *
126
+     * Note that only string-based properties are supported here.
127
+     *
128
+     * @var array
129
+     */
130
+    public $propertyMap = [
131
+        '{DAV:}displayname' => 'displayname',
132
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
133
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
134
+        '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
135
+        '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
136
+    ];
137
+
138
+    /**
139
+     * List of subscription properties, and how they map to database field names.
140
+     *
141
+     * @var array
142
+     */
143
+    public $subscriptionPropertyMap = [
144
+        '{DAV:}displayname' => 'displayname',
145
+        '{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
146
+        '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
147
+        '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
148
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
149
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
150
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
151
+    ];
152
+
153
+    /** @var array properties to index */
154
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
155
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
156
+        'ORGANIZER'];
157
+
158
+    /** @var array parameters to index */
159
+    public static $indexParameters = [
160
+        'ATTENDEE' => ['CN'],
161
+        'ORGANIZER' => ['CN'],
162
+    ];
163
+
164
+    /**
165
+     * @var string[] Map of uid => display name
166
+     */
167
+    protected $userDisplayNames;
168
+
169
+    /** @var IDBConnection */
170
+    private $db;
171
+
172
+    /** @var Backend */
173
+    private $calendarSharingBackend;
174
+
175
+    /** @var Principal */
176
+    private $principalBackend;
177
+
178
+    /** @var IUserManager */
179
+    private $userManager;
180
+
181
+    /** @var ISecureRandom */
182
+    private $random;
183
+
184
+    /** @var ILogger */
185
+    private $logger;
186
+
187
+    /** @var IEventDispatcher */
188
+    private $dispatcher;
189
+
190
+    /** @var EventDispatcherInterface */
191
+    private $legacyDispatcher;
192
+
193
+    /** @var bool */
194
+    private $legacyEndpoint;
195
+
196
+    /** @var string */
197
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
198
+
199
+    /**
200
+     * CalDavBackend constructor.
201
+     *
202
+     * @param IDBConnection $db
203
+     * @param Principal $principalBackend
204
+     * @param IUserManager $userManager
205
+     * @param IGroupManager $groupManager
206
+     * @param ISecureRandom $random
207
+     * @param ILogger $logger
208
+     * @param IEventDispatcher $dispatcher
209
+     * @param EventDispatcherInterface $legacyDispatcher
210
+     * @param bool $legacyEndpoint
211
+     */
212
+    public function __construct(IDBConnection $db,
213
+                                Principal $principalBackend,
214
+                                IUserManager $userManager,
215
+                                IGroupManager $groupManager,
216
+                                ISecureRandom $random,
217
+                                ILogger $logger,
218
+                                IEventDispatcher $dispatcher,
219
+                                EventDispatcherInterface $legacyDispatcher,
220
+                                bool $legacyEndpoint = false) {
221
+        $this->db = $db;
222
+        $this->principalBackend = $principalBackend;
223
+        $this->userManager = $userManager;
224
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
225
+        $this->random = $random;
226
+        $this->logger = $logger;
227
+        $this->dispatcher = $dispatcher;
228
+        $this->legacyDispatcher = $legacyDispatcher;
229
+        $this->legacyEndpoint = $legacyEndpoint;
230
+    }
231
+
232
+    /**
233
+     * Return the number of calendars for a principal
234
+     *
235
+     * By default this excludes the automatically generated birthday calendar
236
+     *
237
+     * @param $principalUri
238
+     * @param bool $excludeBirthday
239
+     * @return int
240
+     */
241
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
242
+        $principalUri = $this->convertPrincipal($principalUri, true);
243
+        $query = $this->db->getQueryBuilder();
244
+        $query->select($query->func()->count('*'))
245
+            ->from('calendars');
246
+
247
+        if ($principalUri === '') {
248
+            $query->where($query->expr()->emptyString('principaluri'));
249
+        } else {
250
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
251
+        }
252
+
253
+        if ($excludeBirthday) {
254
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
255
+        }
256
+
257
+        $result = $query->execute();
258
+        $column = (int)$result->fetchColumn();
259
+        $result->closeCursor();
260
+        return $column;
261
+    }
262
+
263
+    /**
264
+     * Returns a list of calendars for a principal.
265
+     *
266
+     * Every project is an array with the following keys:
267
+     *  * id, a unique id that will be used by other functions to modify the
268
+     *    calendar. This can be the same as the uri or a database key.
269
+     *  * uri, which the basename of the uri with which the calendar is
270
+     *    accessed.
271
+     *  * principaluri. The owner of the calendar. Almost always the same as
272
+     *    principalUri passed to this method.
273
+     *
274
+     * Furthermore it can contain webdav properties in clark notation. A very
275
+     * common one is '{DAV:}displayname'.
276
+     *
277
+     * Many clients also require:
278
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
279
+     * For this property, you can just return an instance of
280
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
281
+     *
282
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
283
+     * ACL will automatically be put in read-only mode.
284
+     *
285
+     * @param string $principalUri
286
+     * @return array
287
+     */
288
+    public function getCalendarsForUser($principalUri) {
289
+        $principalUriOriginal = $principalUri;
290
+        $principalUri = $this->convertPrincipal($principalUri, true);
291
+        $fields = array_values($this->propertyMap);
292
+        $fields[] = 'id';
293
+        $fields[] = 'uri';
294
+        $fields[] = 'synctoken';
295
+        $fields[] = 'components';
296
+        $fields[] = 'principaluri';
297
+        $fields[] = 'transparent';
298
+
299
+        // Making fields a comma-delimited list
300
+        $query = $this->db->getQueryBuilder();
301
+        $query->select($fields)
302
+            ->from('calendars')
303
+            ->orderBy('calendarorder', 'ASC');
304
+
305
+        if ($principalUri === '') {
306
+            $query->where($query->expr()->emptyString('principaluri'));
307
+        } else {
308
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
309
+        }
310
+
311
+        $result = $query->execute();
312
+
313
+        $calendars = [];
314
+        while ($row = $result->fetch()) {
315
+            $row['principaluri'] = (string) $row['principaluri'];
316
+            $components = [];
317
+            if ($row['components']) {
318
+                $components = explode(',',$row['components']);
319
+            }
320
+
321
+            $calendar = [
322
+                'id' => $row['id'],
323
+                'uri' => $row['uri'],
324
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
325
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
326
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
327
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
328
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
329
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
330
+            ];
331
+
332
+            foreach ($this->propertyMap as $xmlName => $dbName) {
333
+                $calendar[$xmlName] = $row[$dbName];
334
+            }
335
+
336
+            $this->addOwnerPrincipal($calendar);
337
+
338
+            if (!isset($calendars[$calendar['id']])) {
339
+                $calendars[$calendar['id']] = $calendar;
340
+            }
341
+        }
342
+        $result->closeCursor();
343
+
344
+        // query for shared calendars
345
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
346
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
347
+
348
+        $principals[] = $principalUri;
349
+
350
+        $fields = array_values($this->propertyMap);
351
+        $fields[] = 'a.id';
352
+        $fields[] = 'a.uri';
353
+        $fields[] = 'a.synctoken';
354
+        $fields[] = 'a.components';
355
+        $fields[] = 'a.principaluri';
356
+        $fields[] = 'a.transparent';
357
+        $fields[] = 's.access';
358
+        $query = $this->db->getQueryBuilder();
359
+        $query->select($fields)
360
+            ->from('dav_shares', 's')
361
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
362
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
363
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
364
+            ->setParameter('type', 'calendar')
365
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
366
+
367
+        $result	= $query->execute();
368
+
369
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
370
+        while ($row = $result->fetch()) {
371
+            $row['principaluri'] = (string) $row['principaluri'];
372
+            if ($row['principaluri'] === $principalUri) {
373
+                continue;
374
+            }
375
+
376
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
377
+            if (isset($calendars[$row['id']])) {
378
+                if ($readOnly) {
379
+                    // New share can not have more permissions then the old one.
380
+                    continue;
381
+                }
382
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
383
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
384
+                    // Old share is already read-write, no more permissions can be gained
385
+                    continue;
386
+                }
387
+            }
388
+
389
+            list(, $name) = Uri\split($row['principaluri']);
390
+            $uri = $row['uri'] . '_shared_by_' . $name;
391
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
392
+            $components = [];
393
+            if ($row['components']) {
394
+                $components = explode(',',$row['components']);
395
+            }
396
+            $calendar = [
397
+                'id' => $row['id'],
398
+                'uri' => $uri,
399
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
400
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
401
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
402
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
404
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
405
+                $readOnlyPropertyName => $readOnly,
406
+            ];
407
+
408
+            foreach ($this->propertyMap as $xmlName => $dbName) {
409
+                $calendar[$xmlName] = $row[$dbName];
410
+            }
411
+
412
+            $this->addOwnerPrincipal($calendar);
413
+
414
+            $calendars[$calendar['id']] = $calendar;
415
+        }
416
+        $result->closeCursor();
417
+
418
+        return array_values($calendars);
419
+    }
420
+
421
+    /**
422
+     * @param $principalUri
423
+     * @return array
424
+     */
425
+    public function getUsersOwnCalendars($principalUri) {
426
+        $principalUri = $this->convertPrincipal($principalUri, true);
427
+        $fields = array_values($this->propertyMap);
428
+        $fields[] = 'id';
429
+        $fields[] = 'uri';
430
+        $fields[] = 'synctoken';
431
+        $fields[] = 'components';
432
+        $fields[] = 'principaluri';
433
+        $fields[] = 'transparent';
434
+        // Making fields a comma-delimited list
435
+        $query = $this->db->getQueryBuilder();
436
+        $query->select($fields)->from('calendars')
437
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
438
+            ->orderBy('calendarorder', 'ASC');
439
+        $stmt = $query->execute();
440
+        $calendars = [];
441
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
442
+            $row['principaluri'] = (string) $row['principaluri'];
443
+            $components = [];
444
+            if ($row['components']) {
445
+                $components = explode(',',$row['components']);
446
+            }
447
+            $calendar = [
448
+                'id' => $row['id'],
449
+                'uri' => $row['uri'],
450
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
451
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
452
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
453
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
454
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
455
+            ];
456
+            foreach ($this->propertyMap as $xmlName => $dbName) {
457
+                $calendar[$xmlName] = $row[$dbName];
458
+            }
459
+
460
+            $this->addOwnerPrincipal($calendar);
461
+
462
+            if (!isset($calendars[$calendar['id']])) {
463
+                $calendars[$calendar['id']] = $calendar;
464
+            }
465
+        }
466
+        $stmt->closeCursor();
467
+        return array_values($calendars);
468
+    }
469
+
470
+
471
+    /**
472
+     * @param $uid
473
+     * @return string
474
+     */
475
+    private function getUserDisplayName($uid) {
476
+        if (!isset($this->userDisplayNames[$uid])) {
477
+            $user = $this->userManager->get($uid);
478
+
479
+            if ($user instanceof IUser) {
480
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
481
+            } else {
482
+                $this->userDisplayNames[$uid] = $uid;
483
+            }
484
+        }
485
+
486
+        return $this->userDisplayNames[$uid];
487
+    }
488
+
489
+    /**
490
+     * @return array
491
+     */
492
+    public function getPublicCalendars() {
493
+        $fields = array_values($this->propertyMap);
494
+        $fields[] = 'a.id';
495
+        $fields[] = 'a.uri';
496
+        $fields[] = 'a.synctoken';
497
+        $fields[] = 'a.components';
498
+        $fields[] = 'a.principaluri';
499
+        $fields[] = 'a.transparent';
500
+        $fields[] = 's.access';
501
+        $fields[] = 's.publicuri';
502
+        $calendars = [];
503
+        $query = $this->db->getQueryBuilder();
504
+        $result = $query->select($fields)
505
+            ->from('dav_shares', 's')
506
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
+            ->execute();
510
+
511
+        while ($row = $result->fetch()) {
512
+            $row['principaluri'] = (string) $row['principaluri'];
513
+            list(, $name) = Uri\split($row['principaluri']);
514
+            $row['displayname'] = $row['displayname'] . "($name)";
515
+            $components = [];
516
+            if ($row['components']) {
517
+                $components = explode(',',$row['components']);
518
+            }
519
+            $calendar = [
520
+                'id' => $row['id'],
521
+                'uri' => $row['publicuri'],
522
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
528
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
530
+            ];
531
+
532
+            foreach ($this->propertyMap as $xmlName => $dbName) {
533
+                $calendar[$xmlName] = $row[$dbName];
534
+            }
535
+
536
+            $this->addOwnerPrincipal($calendar);
537
+
538
+            if (!isset($calendars[$calendar['id']])) {
539
+                $calendars[$calendar['id']] = $calendar;
540
+            }
541
+        }
542
+        $result->closeCursor();
543
+
544
+        return array_values($calendars);
545
+    }
546
+
547
+    /**
548
+     * @param string $uri
549
+     * @return array
550
+     * @throws NotFound
551
+     */
552
+    public function getPublicCalendar($uri) {
553
+        $fields = array_values($this->propertyMap);
554
+        $fields[] = 'a.id';
555
+        $fields[] = 'a.uri';
556
+        $fields[] = 'a.synctoken';
557
+        $fields[] = 'a.components';
558
+        $fields[] = 'a.principaluri';
559
+        $fields[] = 'a.transparent';
560
+        $fields[] = 's.access';
561
+        $fields[] = 's.publicuri';
562
+        $query = $this->db->getQueryBuilder();
563
+        $result = $query->select($fields)
564
+            ->from('dav_shares', 's')
565
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
566
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
567
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
568
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
569
+            ->execute();
570
+
571
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
572
+
573
+        $result->closeCursor();
574
+
575
+        if ($row === false) {
576
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
577
+        }
578
+
579
+        $row['principaluri'] = (string) $row['principaluri'];
580
+        list(, $name) = Uri\split($row['principaluri']);
581
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
582
+        $components = [];
583
+        if ($row['components']) {
584
+            $components = explode(',',$row['components']);
585
+        }
586
+        $calendar = [
587
+            'id' => $row['id'],
588
+            'uri' => $row['publicuri'],
589
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
590
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
591
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
592
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
593
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
594
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
595
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
596
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
597
+        ];
598
+
599
+        foreach ($this->propertyMap as $xmlName => $dbName) {
600
+            $calendar[$xmlName] = $row[$dbName];
601
+        }
602
+
603
+        $this->addOwnerPrincipal($calendar);
604
+
605
+        return $calendar;
606
+    }
607
+
608
+    /**
609
+     * @param string $principal
610
+     * @param string $uri
611
+     * @return array|null
612
+     */
613
+    public function getCalendarByUri($principal, $uri) {
614
+        $fields = array_values($this->propertyMap);
615
+        $fields[] = 'id';
616
+        $fields[] = 'uri';
617
+        $fields[] = 'synctoken';
618
+        $fields[] = 'components';
619
+        $fields[] = 'principaluri';
620
+        $fields[] = 'transparent';
621
+
622
+        // Making fields a comma-delimited list
623
+        $query = $this->db->getQueryBuilder();
624
+        $query->select($fields)->from('calendars')
625
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
626
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
627
+            ->setMaxResults(1);
628
+        $stmt = $query->execute();
629
+
630
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
631
+        $stmt->closeCursor();
632
+        if ($row === false) {
633
+            return null;
634
+        }
635
+
636
+        $row['principaluri'] = (string) $row['principaluri'];
637
+        $components = [];
638
+        if ($row['components']) {
639
+            $components = explode(',',$row['components']);
640
+        }
641
+
642
+        $calendar = [
643
+            'id' => $row['id'],
644
+            'uri' => $row['uri'],
645
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
646
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
647
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
648
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
649
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
650
+        ];
651
+
652
+        foreach ($this->propertyMap as $xmlName => $dbName) {
653
+            $calendar[$xmlName] = $row[$dbName];
654
+        }
655
+
656
+        $this->addOwnerPrincipal($calendar);
657
+
658
+        return $calendar;
659
+    }
660
+
661
+    /**
662
+     * @param $calendarId
663
+     * @return array|null
664
+     */
665
+    public function getCalendarById($calendarId) {
666
+        $fields = array_values($this->propertyMap);
667
+        $fields[] = 'id';
668
+        $fields[] = 'uri';
669
+        $fields[] = 'synctoken';
670
+        $fields[] = 'components';
671
+        $fields[] = 'principaluri';
672
+        $fields[] = 'transparent';
673
+
674
+        // Making fields a comma-delimited list
675
+        $query = $this->db->getQueryBuilder();
676
+        $query->select($fields)->from('calendars')
677
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
678
+            ->setMaxResults(1);
679
+        $stmt = $query->execute();
680
+
681
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
682
+        $stmt->closeCursor();
683
+        if ($row === false) {
684
+            return null;
685
+        }
686
+
687
+        $row['principaluri'] = (string) $row['principaluri'];
688
+        $components = [];
689
+        if ($row['components']) {
690
+            $components = explode(',',$row['components']);
691
+        }
692
+
693
+        $calendar = [
694
+            'id' => $row['id'],
695
+            'uri' => $row['uri'],
696
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
697
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
698
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
699
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
700
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
701
+        ];
702
+
703
+        foreach ($this->propertyMap as $xmlName => $dbName) {
704
+            $calendar[$xmlName] = $row[$dbName];
705
+        }
706
+
707
+        $this->addOwnerPrincipal($calendar);
708
+
709
+        return $calendar;
710
+    }
711
+
712
+    /**
713
+     * @param $subscriptionId
714
+     */
715
+    public function getSubscriptionById($subscriptionId) {
716
+        $fields = array_values($this->subscriptionPropertyMap);
717
+        $fields[] = 'id';
718
+        $fields[] = 'uri';
719
+        $fields[] = 'source';
720
+        $fields[] = 'synctoken';
721
+        $fields[] = 'principaluri';
722
+        $fields[] = 'lastmodified';
723
+
724
+        $query = $this->db->getQueryBuilder();
725
+        $query->select($fields)
726
+            ->from('calendarsubscriptions')
727
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
728
+            ->orderBy('calendarorder', 'asc');
729
+        $stmt = $query->execute();
730
+
731
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
732
+        $stmt->closeCursor();
733
+        if ($row === false) {
734
+            return null;
735
+        }
736
+
737
+        $row['principaluri'] = (string) $row['principaluri'];
738
+        $subscription = [
739
+            'id' => $row['id'],
740
+            'uri' => $row['uri'],
741
+            'principaluri' => $row['principaluri'],
742
+            'source' => $row['source'],
743
+            'lastmodified' => $row['lastmodified'],
744
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
745
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
746
+        ];
747
+
748
+        foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
749
+            if (!is_null($row[$dbName])) {
750
+                $subscription[$xmlName] = $row[$dbName];
751
+            }
752
+        }
753
+
754
+        return $subscription;
755
+    }
756
+
757
+    /**
758
+     * Creates a new calendar for a principal.
759
+     *
760
+     * If the creation was a success, an id must be returned that can be used to reference
761
+     * this calendar in other methods, such as updateCalendar.
762
+     *
763
+     * @param string $principalUri
764
+     * @param string $calendarUri
765
+     * @param array $properties
766
+     * @return int
767
+     */
768
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
769
+        $values = [
770
+            'principaluri' => $this->convertPrincipal($principalUri, true),
771
+            'uri' => $calendarUri,
772
+            'synctoken' => 1,
773
+            'transparent' => 0,
774
+            'components' => 'VEVENT,VTODO',
775
+            'displayname' => $calendarUri
776
+        ];
777
+
778
+        // Default value
779
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
780
+        if (isset($properties[$sccs])) {
781
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
782
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
783
+            }
784
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
785
+        } elseif (isset($properties['components'])) {
786
+            // Allow to provide components internally without having
787
+            // to create a SupportedCalendarComponentSet object
788
+            $values['components'] = $properties['components'];
789
+        }
790
+
791
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
792
+        if (isset($properties[$transp])) {
793
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
794
+        }
795
+
796
+        foreach ($this->propertyMap as $xmlName => $dbName) {
797
+            if (isset($properties[$xmlName])) {
798
+                $values[$dbName] = $properties[$xmlName];
799
+            }
800
+        }
801
+
802
+        $query = $this->db->getQueryBuilder();
803
+        $query->insert('calendars');
804
+        foreach ($values as $column => $value) {
805
+            $query->setValue($column, $query->createNamedParameter($value));
806
+        }
807
+        $query->execute();
808
+        $calendarId = $query->getLastInsertId();
809
+
810
+        $calendarData = $this->getCalendarById($calendarId);
811
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
812
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
813
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
814
+            [
815
+                'calendarId' => $calendarId,
816
+                'calendarData' => $calendarData,
817
+            ]));
818
+
819
+        return $calendarId;
820
+    }
821
+
822
+    /**
823
+     * Updates properties for a calendar.
824
+     *
825
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
826
+     * To do the actual updates, you must tell this object which properties
827
+     * you're going to process with the handle() method.
828
+     *
829
+     * Calling the handle method is like telling the PropPatch object "I
830
+     * promise I can handle updating this property".
831
+     *
832
+     * Read the PropPatch documentation for more info and examples.
833
+     *
834
+     * @param mixed $calendarId
835
+     * @param PropPatch $propPatch
836
+     * @return void
837
+     */
838
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
839
+        $supportedProperties = array_keys($this->propertyMap);
840
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
+
842
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
843
+            $newValues = [];
844
+            foreach ($mutations as $propertyName => $propertyValue) {
845
+                switch ($propertyName) {
846
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
847
+                        $fieldName = 'transparent';
848
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
849
+                        break;
850
+                    default:
851
+                        $fieldName = $this->propertyMap[$propertyName];
852
+                        $newValues[$fieldName] = $propertyValue;
853
+                        break;
854
+                }
855
+            }
856
+            $query = $this->db->getQueryBuilder();
857
+            $query->update('calendars');
858
+            foreach ($newValues as $fieldName => $value) {
859
+                $query->set($fieldName, $query->createNamedParameter($value));
860
+            }
861
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
862
+            $query->execute();
863
+
864
+            $this->addChange($calendarId, "", 2);
865
+
866
+            $calendarData = $this->getCalendarById($calendarId);
867
+            $shares = $this->getShares($calendarId);
868
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
869
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
870
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
871
+                [
872
+                    'calendarId' => $calendarId,
873
+                    'calendarData' => $calendarData,
874
+                    'shares' => $shares,
875
+                    'propertyMutations' => $mutations,
876
+                ]));
877
+
878
+            return true;
879
+        });
880
+    }
881
+
882
+    /**
883
+     * Delete a calendar and all it's objects
884
+     *
885
+     * @param mixed $calendarId
886
+     * @return void
887
+     */
888
+    public function deleteCalendar($calendarId) {
889
+        $calendarData = $this->getCalendarById($calendarId);
890
+        $shares = $this->getShares($calendarId);
891
+
892
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
893
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
894
+            [
895
+                'calendarId' => $calendarId,
896
+                'calendarData' => $calendarData,
897
+                'shares' => $shares,
898
+            ]));
899
+
900
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
901
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
902
+
903
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
904
+        $stmt->execute([$calendarId]);
905
+
906
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
907
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
908
+
909
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
910
+
911
+        $query = $this->db->getQueryBuilder();
912
+        $query->delete($this->dbObjectPropertiesTable)
913
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
914
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
915
+            ->execute();
916
+
917
+        if ($calendarData) {
918
+            $this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
919
+        }
920
+    }
921
+
922
+    /**
923
+     * Delete all of an user's shares
924
+     *
925
+     * @param string $principaluri
926
+     * @return void
927
+     */
928
+    public function deleteAllSharesByUser($principaluri) {
929
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
930
+    }
931
+
932
+    /**
933
+     * Returns all calendar objects within a calendar.
934
+     *
935
+     * Every item contains an array with the following keys:
936
+     *   * calendardata - The iCalendar-compatible calendar data
937
+     *   * uri - a unique key which will be used to construct the uri. This can
938
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
939
+     *     good idea. This is only the basename, or filename, not the full
940
+     *     path.
941
+     *   * lastmodified - a timestamp of the last modification time
942
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
943
+     *   '"abcdef"')
944
+     *   * size - The size of the calendar objects, in bytes.
945
+     *   * component - optional, a string containing the type of object, such
946
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
947
+     *     the Content-Type header.
948
+     *
949
+     * Note that the etag is optional, but it's highly encouraged to return for
950
+     * speed reasons.
951
+     *
952
+     * The calendardata is also optional. If it's not returned
953
+     * 'getCalendarObject' will be called later, which *is* expected to return
954
+     * calendardata.
955
+     *
956
+     * If neither etag or size are specified, the calendardata will be
957
+     * used/fetched to determine these numbers. If both are specified the
958
+     * amount of times this is needed is reduced by a great degree.
959
+     *
960
+     * @param mixed $calendarId
961
+     * @param int $calendarType
962
+     * @return array
963
+     */
964
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
965
+        $query = $this->db->getQueryBuilder();
966
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
967
+            ->from('calendarobjects')
968
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
969
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
970
+        $stmt = $query->execute();
971
+
972
+        $result = [];
973
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
974
+            $result[] = [
975
+                'id' => $row['id'],
976
+                'uri' => $row['uri'],
977
+                'lastmodified' => $row['lastmodified'],
978
+                'etag' => '"' . $row['etag'] . '"',
979
+                'calendarid' => $row['calendarid'],
980
+                'size' => (int)$row['size'],
981
+                'component' => strtolower($row['componenttype']),
982
+                'classification' => (int)$row['classification']
983
+            ];
984
+        }
985
+        $stmt->closeCursor();
986
+
987
+        return $result;
988
+    }
989
+
990
+    /**
991
+     * Returns information from a single calendar object, based on it's object
992
+     * uri.
993
+     *
994
+     * The object uri is only the basename, or filename and not a full path.
995
+     *
996
+     * The returned array must have the same keys as getCalendarObjects. The
997
+     * 'calendardata' object is required here though, while it's not required
998
+     * for getCalendarObjects.
999
+     *
1000
+     * This method must return null if the object did not exist.
1001
+     *
1002
+     * @param mixed $calendarId
1003
+     * @param string $objectUri
1004
+     * @param int $calendarType
1005
+     * @return array|null
1006
+     */
1007
+    public function getCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1008
+        $query = $this->db->getQueryBuilder();
1009
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1010
+            ->from('calendarobjects')
1011
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1012
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1013
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1014
+        $stmt = $query->execute();
1015
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1016
+        $stmt->closeCursor();
1017
+
1018
+        if (!$row) {
1019
+            return null;
1020
+        }
1021
+
1022
+        return [
1023
+            'id' => $row['id'],
1024
+            'uri' => $row['uri'],
1025
+            'lastmodified' => $row['lastmodified'],
1026
+            'etag' => '"' . $row['etag'] . '"',
1027
+            'calendarid' => $row['calendarid'],
1028
+            'size' => (int)$row['size'],
1029
+            'calendardata' => $this->readBlob($row['calendardata']),
1030
+            'component' => strtolower($row['componenttype']),
1031
+            'classification' => (int)$row['classification']
1032
+        ];
1033
+    }
1034
+
1035
+    /**
1036
+     * Returns a list of calendar objects.
1037
+     *
1038
+     * This method should work identical to getCalendarObject, but instead
1039
+     * return all the calendar objects in the list as an array.
1040
+     *
1041
+     * If the backend supports this, it may allow for some speed-ups.
1042
+     *
1043
+     * @param mixed $calendarId
1044
+     * @param string[] $uris
1045
+     * @param int $calendarType
1046
+     * @return array
1047
+     */
1048
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1049
+        if (empty($uris)) {
1050
+            return [];
1051
+        }
1052
+
1053
+        $chunks = array_chunk($uris, 100);
1054
+        $objects = [];
1055
+
1056
+        $query = $this->db->getQueryBuilder();
1057
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1058
+            ->from('calendarobjects')
1059
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1060
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1061
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1062
+
1063
+        foreach ($chunks as $uris) {
1064
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1065
+            $result = $query->execute();
1066
+
1067
+            while ($row = $result->fetch()) {
1068
+                $objects[] = [
1069
+                    'id' => $row['id'],
1070
+                    'uri' => $row['uri'],
1071
+                    'lastmodified' => $row['lastmodified'],
1072
+                    'etag' => '"' . $row['etag'] . '"',
1073
+                    'calendarid' => $row['calendarid'],
1074
+                    'size' => (int)$row['size'],
1075
+                    'calendardata' => $this->readBlob($row['calendardata']),
1076
+                    'component' => strtolower($row['componenttype']),
1077
+                    'classification' => (int)$row['classification']
1078
+                ];
1079
+            }
1080
+            $result->closeCursor();
1081
+        }
1082
+
1083
+        return $objects;
1084
+    }
1085
+
1086
+    /**
1087
+     * Creates a new calendar object.
1088
+     *
1089
+     * The object uri is only the basename, or filename and not a full path.
1090
+     *
1091
+     * It is possible return an etag from this function, which will be used in
1092
+     * the response to this PUT request. Note that the ETag must be surrounded
1093
+     * by double-quotes.
1094
+     *
1095
+     * However, you should only really return this ETag if you don't mangle the
1096
+     * calendar-data. If the result of a subsequent GET to this object is not
1097
+     * the exact same as this request body, you should omit the ETag.
1098
+     *
1099
+     * @param mixed $calendarId
1100
+     * @param string $objectUri
1101
+     * @param string $calendarData
1102
+     * @param int $calendarType
1103
+     * @return string
1104
+     */
1105
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1106
+        $extraData = $this->getDenormalizedData($calendarData);
1107
+
1108
+        $q = $this->db->getQueryBuilder();
1109
+        $q->select($q->func()->count('*'))
1110
+            ->from('calendarobjects')
1111
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1112
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1113
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1114
+
1115
+        $result = $q->execute();
1116
+        $count = (int) $result->fetchColumn();
1117
+        $result->closeCursor();
1118
+
1119
+        if ($count !== 0) {
1120
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1121
+        }
1122
+
1123
+        $query = $this->db->getQueryBuilder();
1124
+        $query->insert('calendarobjects')
1125
+            ->values([
1126
+                'calendarid' => $query->createNamedParameter($calendarId),
1127
+                'uri' => $query->createNamedParameter($objectUri),
1128
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1129
+                'lastmodified' => $query->createNamedParameter(time()),
1130
+                'etag' => $query->createNamedParameter($extraData['etag']),
1131
+                'size' => $query->createNamedParameter($extraData['size']),
1132
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1133
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1134
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1135
+                'classification' => $query->createNamedParameter($extraData['classification']),
1136
+                'uid' => $query->createNamedParameter($extraData['uid']),
1137
+                'calendartype' => $query->createNamedParameter($calendarType),
1138
+            ])
1139
+            ->execute();
1140
+
1141
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1142
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1143
+
1144
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1145
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1146
+            $calendarRow = $this->getCalendarById($calendarId);
1147
+            $shares = $this->getShares($calendarId);
1148
+
1149
+            $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1150
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1151
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1152
+                [
1153
+                    'calendarId' => $calendarId,
1154
+                    'calendarData' => $calendarRow,
1155
+                    'shares' => $shares,
1156
+                    'objectData' => $objectRow,
1157
+                ]
1158
+            ));
1159
+        } else {
1160
+            $subscriptionRow = $this->getSubscriptionById($calendarId);
1161
+
1162
+            $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1163
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1164
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1165
+                [
1166
+                    'subscriptionId' => $calendarId,
1167
+                    'calendarData' => $subscriptionRow,
1168
+                    'shares' => [],
1169
+                    'objectData' => $objectRow,
1170
+                ]
1171
+            ));
1172
+        }
1173
+
1174
+        return '"' . $extraData['etag'] . '"';
1175
+    }
1176
+
1177
+    /**
1178
+     * Updates an existing calendarobject, based on it's uri.
1179
+     *
1180
+     * The object uri is only the basename, or filename and not a full path.
1181
+     *
1182
+     * It is possible return an etag from this function, which will be used in
1183
+     * the response to this PUT request. Note that the ETag must be surrounded
1184
+     * by double-quotes.
1185
+     *
1186
+     * However, you should only really return this ETag if you don't mangle the
1187
+     * calendar-data. If the result of a subsequent GET to this object is not
1188
+     * the exact same as this request body, you should omit the ETag.
1189
+     *
1190
+     * @param mixed $calendarId
1191
+     * @param string $objectUri
1192
+     * @param string $calendarData
1193
+     * @param int $calendarType
1194
+     * @return string
1195
+     */
1196
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1197
+        $extraData = $this->getDenormalizedData($calendarData);
1198
+        $query = $this->db->getQueryBuilder();
1199
+        $query->update('calendarobjects')
1200
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1201
+                ->set('lastmodified', $query->createNamedParameter(time()))
1202
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1203
+                ->set('size', $query->createNamedParameter($extraData['size']))
1204
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1205
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1206
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1207
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1208
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1209
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1210
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1211
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1212
+            ->execute();
1213
+
1214
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1215
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1216
+
1217
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1218
+        if (is_array($objectRow)) {
1219
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1220
+                $calendarRow = $this->getCalendarById($calendarId);
1221
+                $shares = $this->getShares($calendarId);
1222
+
1223
+                $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1224
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1225
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1226
+                    [
1227
+                        'calendarId' => $calendarId,
1228
+                        'calendarData' => $calendarRow,
1229
+                        'shares' => $shares,
1230
+                        'objectData' => $objectRow,
1231
+                    ]
1232
+                ));
1233
+            } else {
1234
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1235
+
1236
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1237
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1238
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1239
+                    [
1240
+                        'subscriptionId' => $calendarId,
1241
+                        'calendarData' => $subscriptionRow,
1242
+                        'shares' => [],
1243
+                        'objectData' => $objectRow,
1244
+                    ]
1245
+                ));
1246
+            }
1247
+        }
1248
+
1249
+        return '"' . $extraData['etag'] . '"';
1250
+    }
1251
+
1252
+    /**
1253
+     * @param int $calendarObjectId
1254
+     * @param int $classification
1255
+     */
1256
+    public function setClassification($calendarObjectId, $classification) {
1257
+        if (!in_array($classification, [
1258
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1259
+        ])) {
1260
+            throw new \InvalidArgumentException();
1261
+        }
1262
+        $query = $this->db->getQueryBuilder();
1263
+        $query->update('calendarobjects')
1264
+            ->set('classification', $query->createNamedParameter($classification))
1265
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1266
+            ->execute();
1267
+    }
1268
+
1269
+    /**
1270
+     * Deletes an existing calendar object.
1271
+     *
1272
+     * The object uri is only the basename, or filename and not a full path.
1273
+     *
1274
+     * @param mixed $calendarId
1275
+     * @param string $objectUri
1276
+     * @param int $calendarType
1277
+     * @return void
1278
+     */
1279
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1280
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1281
+        if (is_array($data)) {
1282
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1283
+                $calendarRow = $this->getCalendarById($calendarId);
1284
+                $shares = $this->getShares($calendarId);
1285
+
1286
+                $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1287
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1288
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1289
+                    [
1290
+                        'calendarId' => $calendarId,
1291
+                        'calendarData' => $calendarRow,
1292
+                        'shares' => $shares,
1293
+                        'objectData' => $data,
1294
+                    ]
1295
+                ));
1296
+            } else {
1297
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1298
+
1299
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1300
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1301
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1302
+                    [
1303
+                        'subscriptionId' => $calendarId,
1304
+                        'calendarData' => $subscriptionRow,
1305
+                        'shares' => [],
1306
+                        'objectData' => $data,
1307
+                    ]
1308
+                ));
1309
+            }
1310
+        }
1311
+
1312
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1313
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1314
+
1315
+        if (is_array($data)) {
1316
+            $this->purgeProperties($calendarId, $data['id'], $calendarType);
1317
+        }
1318
+
1319
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1320
+    }
1321
+
1322
+    /**
1323
+     * Performs a calendar-query on the contents of this calendar.
1324
+     *
1325
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1326
+     * calendar-query it is possible for a client to request a specific set of
1327
+     * object, based on contents of iCalendar properties, date-ranges and
1328
+     * iCalendar component types (VTODO, VEVENT).
1329
+     *
1330
+     * This method should just return a list of (relative) urls that match this
1331
+     * query.
1332
+     *
1333
+     * The list of filters are specified as an array. The exact array is
1334
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1335
+     *
1336
+     * Note that it is extremely likely that getCalendarObject for every path
1337
+     * returned from this method will be called almost immediately after. You
1338
+     * may want to anticipate this to speed up these requests.
1339
+     *
1340
+     * This method provides a default implementation, which parses *all* the
1341
+     * iCalendar objects in the specified calendar.
1342
+     *
1343
+     * This default may well be good enough for personal use, and calendars
1344
+     * that aren't very large. But if you anticipate high usage, big calendars
1345
+     * or high loads, you are strongly advised to optimize certain paths.
1346
+     *
1347
+     * The best way to do so is override this method and to optimize
1348
+     * specifically for 'common filters'.
1349
+     *
1350
+     * Requests that are extremely common are:
1351
+     *   * requests for just VEVENTS
1352
+     *   * requests for just VTODO
1353
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1354
+     *
1355
+     * ..and combinations of these requests. It may not be worth it to try to
1356
+     * handle every possible situation and just rely on the (relatively
1357
+     * easy to use) CalendarQueryValidator to handle the rest.
1358
+     *
1359
+     * Note that especially time-range-filters may be difficult to parse. A
1360
+     * time-range filter specified on a VEVENT must for instance also handle
1361
+     * recurrence rules correctly.
1362
+     * A good example of how to interprete all these filters can also simply
1363
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1364
+     * as possible, so it gives you a good idea on what type of stuff you need
1365
+     * to think of.
1366
+     *
1367
+     * @param mixed $calendarId
1368
+     * @param array $filters
1369
+     * @param int $calendarType
1370
+     * @return array
1371
+     */
1372
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1373
+        $componentType = null;
1374
+        $requirePostFilter = true;
1375
+        $timeRange = null;
1376
+
1377
+        // if no filters were specified, we don't need to filter after a query
1378
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1379
+            $requirePostFilter = false;
1380
+        }
1381
+
1382
+        // Figuring out if there's a component filter
1383
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1384
+            $componentType = $filters['comp-filters'][0]['name'];
1385
+
1386
+            // Checking if we need post-filters
1387
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1388
+                $requirePostFilter = false;
1389
+            }
1390
+            // There was a time-range filter
1391
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1392
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1393
+
1394
+                // If start time OR the end time is not specified, we can do a
1395
+                // 100% accurate mysql query.
1396
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1397
+                    $requirePostFilter = false;
1398
+                }
1399
+            }
1400
+        }
1401
+        $columns = ['uri'];
1402
+        if ($requirePostFilter) {
1403
+            $columns = ['uri', 'calendardata'];
1404
+        }
1405
+        $query = $this->db->getQueryBuilder();
1406
+        $query->select($columns)
1407
+            ->from('calendarobjects')
1408
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1409
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1410
+
1411
+        if ($componentType) {
1412
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1413
+        }
1414
+
1415
+        if ($timeRange && $timeRange['start']) {
1416
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1417
+        }
1418
+        if ($timeRange && $timeRange['end']) {
1419
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1420
+        }
1421
+
1422
+        $stmt = $query->execute();
1423
+
1424
+        $result = [];
1425
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1426
+            if ($requirePostFilter) {
1427
+                // validateFilterForObject will parse the calendar data
1428
+                // catch parsing errors
1429
+                try {
1430
+                    $matches = $this->validateFilterForObject($row, $filters);
1431
+                } catch (ParseException $ex) {
1432
+                    $this->logger->logException($ex, [
1433
+                        'app' => 'dav',
1434
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1435
+                    ]);
1436
+                    continue;
1437
+                } catch (InvalidDataException $ex) {
1438
+                    $this->logger->logException($ex, [
1439
+                        'app' => 'dav',
1440
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1441
+                    ]);
1442
+                    continue;
1443
+                }
1444
+
1445
+                if (!$matches) {
1446
+                    continue;
1447
+                }
1448
+            }
1449
+            $result[] = $row['uri'];
1450
+        }
1451
+
1452
+        return $result;
1453
+    }
1454
+
1455
+    /**
1456
+     * custom Nextcloud search extension for CalDAV
1457
+     *
1458
+     * TODO - this should optionally cover cached calendar objects as well
1459
+     *
1460
+     * @param string $principalUri
1461
+     * @param array $filters
1462
+     * @param integer|null $limit
1463
+     * @param integer|null $offset
1464
+     * @return array
1465
+     */
1466
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1467
+        $calendars = $this->getCalendarsForUser($principalUri);
1468
+        $ownCalendars = [];
1469
+        $sharedCalendars = [];
1470
+
1471
+        $uriMapper = [];
1472
+
1473
+        foreach ($calendars as $calendar) {
1474
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1475
+                $ownCalendars[] = $calendar['id'];
1476
+            } else {
1477
+                $sharedCalendars[] = $calendar['id'];
1478
+            }
1479
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1480
+        }
1481
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1482
+            return [];
1483
+        }
1484
+
1485
+        $query = $this->db->getQueryBuilder();
1486
+        // Calendar id expressions
1487
+        $calendarExpressions = [];
1488
+        foreach ($ownCalendars as $id) {
1489
+            $calendarExpressions[] = $query->expr()->andX(
1490
+                $query->expr()->eq('c.calendarid',
1491
+                    $query->createNamedParameter($id)),
1492
+                $query->expr()->eq('c.calendartype',
1493
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1494
+        }
1495
+        foreach ($sharedCalendars as $id) {
1496
+            $calendarExpressions[] = $query->expr()->andX(
1497
+                $query->expr()->eq('c.calendarid',
1498
+                    $query->createNamedParameter($id)),
1499
+                $query->expr()->eq('c.classification',
1500
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1501
+                $query->expr()->eq('c.calendartype',
1502
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1503
+        }
1504
+
1505
+        if (count($calendarExpressions) === 1) {
1506
+            $calExpr = $calendarExpressions[0];
1507
+        } else {
1508
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1509
+        }
1510
+
1511
+        // Component expressions
1512
+        $compExpressions = [];
1513
+        foreach ($filters['comps'] as $comp) {
1514
+            $compExpressions[] = $query->expr()
1515
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1516
+        }
1517
+
1518
+        if (count($compExpressions) === 1) {
1519
+            $compExpr = $compExpressions[0];
1520
+        } else {
1521
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1522
+        }
1523
+
1524
+        if (!isset($filters['props'])) {
1525
+            $filters['props'] = [];
1526
+        }
1527
+        if (!isset($filters['params'])) {
1528
+            $filters['params'] = [];
1529
+        }
1530
+
1531
+        $propParamExpressions = [];
1532
+        foreach ($filters['props'] as $prop) {
1533
+            $propParamExpressions[] = $query->expr()->andX(
1534
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1535
+                $query->expr()->isNull('i.parameter')
1536
+            );
1537
+        }
1538
+        foreach ($filters['params'] as $param) {
1539
+            $propParamExpressions[] = $query->expr()->andX(
1540
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1541
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1542
+            );
1543
+        }
1544
+
1545
+        if (count($propParamExpressions) === 1) {
1546
+            $propParamExpr = $propParamExpressions[0];
1547
+        } else {
1548
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1549
+        }
1550
+
1551
+        $query->select(['c.calendarid', 'c.uri'])
1552
+            ->from($this->dbObjectPropertiesTable, 'i')
1553
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1554
+            ->where($calExpr)
1555
+            ->andWhere($compExpr)
1556
+            ->andWhere($propParamExpr)
1557
+            ->andWhere($query->expr()->iLike('i.value',
1558
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1559
+
1560
+        if ($offset) {
1561
+            $query->setFirstResult($offset);
1562
+        }
1563
+        if ($limit) {
1564
+            $query->setMaxResults($limit);
1565
+        }
1566
+
1567
+        $stmt = $query->execute();
1568
+
1569
+        $result = [];
1570
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1571
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1572
+            if (!in_array($path, $result)) {
1573
+                $result[] = $path;
1574
+            }
1575
+        }
1576
+
1577
+        return $result;
1578
+    }
1579
+
1580
+    /**
1581
+     * used for Nextcloud's calendar API
1582
+     *
1583
+     * @param array $calendarInfo
1584
+     * @param string $pattern
1585
+     * @param array $searchProperties
1586
+     * @param array $options
1587
+     * @param integer|null $limit
1588
+     * @param integer|null $offset
1589
+     *
1590
+     * @return array
1591
+     */
1592
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1593
+                            array $options, $limit, $offset) {
1594
+        $outerQuery = $this->db->getQueryBuilder();
1595
+        $innerQuery = $this->db->getQueryBuilder();
1596
+
1597
+        $innerQuery->selectDistinct('op.objectid')
1598
+            ->from($this->dbObjectPropertiesTable, 'op')
1599
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1600
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1601
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1602
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1603
+
1604
+        // only return public items for shared calendars for now
1605
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1606
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1607
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1608
+        }
1609
+
1610
+        $or = $innerQuery->expr()->orX();
1611
+        foreach ($searchProperties as $searchProperty) {
1612
+            $or->add($innerQuery->expr()->eq('op.name',
1613
+                $outerQuery->createNamedParameter($searchProperty)));
1614
+        }
1615
+        $innerQuery->andWhere($or);
1616
+
1617
+        if ($pattern !== '') {
1618
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1619
+                $outerQuery->createNamedParameter('%' .
1620
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1621
+        }
1622
+
1623
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1624
+            ->from('calendarobjects', 'c');
1625
+
1626
+        if (isset($options['timerange'])) {
1627
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1628
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1629
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1630
+            }
1631
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1632
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1633
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1634
+            }
1635
+        }
1636
+
1637
+        if (isset($options['types'])) {
1638
+            $or = $outerQuery->expr()->orX();
1639
+            foreach ($options['types'] as $type) {
1640
+                $or->add($outerQuery->expr()->eq('componenttype',
1641
+                    $outerQuery->createNamedParameter($type)));
1642
+            }
1643
+            $outerQuery->andWhere($or);
1644
+        }
1645
+
1646
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1647
+            $outerQuery->createFunction($innerQuery->getSQL())));
1648
+
1649
+        if ($offset) {
1650
+            $outerQuery->setFirstResult($offset);
1651
+        }
1652
+        if ($limit) {
1653
+            $outerQuery->setMaxResults($limit);
1654
+        }
1655
+
1656
+        $result = $outerQuery->execute();
1657
+        $calendarObjects = $result->fetchAll();
1658
+
1659
+        return array_map(function ($o) {
1660
+            $calendarData = Reader::read($o['calendardata']);
1661
+            $comps = $calendarData->getComponents();
1662
+            $objects = [];
1663
+            $timezones = [];
1664
+            foreach ($comps as $comp) {
1665
+                if ($comp instanceof VTimeZone) {
1666
+                    $timezones[] = $comp;
1667
+                } else {
1668
+                    $objects[] = $comp;
1669
+                }
1670
+            }
1671
+
1672
+            return [
1673
+                'id' => $o['id'],
1674
+                'type' => $o['componenttype'],
1675
+                'uid' => $o['uid'],
1676
+                'uri' => $o['uri'],
1677
+                'objects' => array_map(function ($c) {
1678
+                    return $this->transformSearchData($c);
1679
+                }, $objects),
1680
+                'timezones' => array_map(function ($c) {
1681
+                    return $this->transformSearchData($c);
1682
+                }, $timezones),
1683
+            ];
1684
+        }, $calendarObjects);
1685
+    }
1686
+
1687
+    /**
1688
+     * @param Component $comp
1689
+     * @return array
1690
+     */
1691
+    private function transformSearchData(Component $comp) {
1692
+        $data = [];
1693
+        /** @var Component[] $subComponents */
1694
+        $subComponents = $comp->getComponents();
1695
+        /** @var Property[] $properties */
1696
+        $properties = array_filter($comp->children(), function ($c) {
1697
+            return $c instanceof Property;
1698
+        });
1699
+        $validationRules = $comp->getValidationRules();
1700
+
1701
+        foreach ($subComponents as $subComponent) {
1702
+            $name = $subComponent->name;
1703
+            if (!isset($data[$name])) {
1704
+                $data[$name] = [];
1705
+            }
1706
+            $data[$name][] = $this->transformSearchData($subComponent);
1707
+        }
1708
+
1709
+        foreach ($properties as $property) {
1710
+            $name = $property->name;
1711
+            if (!isset($validationRules[$name])) {
1712
+                $validationRules[$name] = '*';
1713
+            }
1714
+
1715
+            $rule = $validationRules[$property->name];
1716
+            if ($rule === '+' || $rule === '*') { // multiple
1717
+                if (!isset($data[$name])) {
1718
+                    $data[$name] = [];
1719
+                }
1720
+
1721
+                $data[$name][] = $this->transformSearchProperty($property);
1722
+            } else { // once
1723
+                $data[$name] = $this->transformSearchProperty($property);
1724
+            }
1725
+        }
1726
+
1727
+        return $data;
1728
+    }
1729
+
1730
+    /**
1731
+     * @param Property $prop
1732
+     * @return array
1733
+     */
1734
+    private function transformSearchProperty(Property $prop) {
1735
+        // No need to check Date, as it extends DateTime
1736
+        if ($prop instanceof Property\ICalendar\DateTime) {
1737
+            $value = $prop->getDateTime();
1738
+        } else {
1739
+            $value = $prop->getValue();
1740
+        }
1741
+
1742
+        return [
1743
+            $value,
1744
+            $prop->parameters()
1745
+        ];
1746
+    }
1747
+
1748
+    /**
1749
+     * @param string $principalUri
1750
+     * @param string $pattern
1751
+     * @param array $componentTypes
1752
+     * @param array $searchProperties
1753
+     * @param array $searchParameters
1754
+     * @param array $options
1755
+     * @return array
1756
+     */
1757
+    public function searchPrincipalUri(string $principalUri,
1758
+                                        string $pattern,
1759
+                                        array $componentTypes,
1760
+                                        array $searchProperties,
1761
+                                        array $searchParameters,
1762
+                                        array $options = []): array {
1763
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1764
+
1765
+        $calendarObjectIdQuery = $this->db->getQueryBuilder();
1766
+        $calendarOr = $calendarObjectIdQuery->expr()->orX();
1767
+        $searchOr = $calendarObjectIdQuery->expr()->orX();
1768
+
1769
+        // Fetch calendars and subscription
1770
+        $calendars = $this->getCalendarsForUser($principalUri);
1771
+        $subscriptions = $this->getSubscriptionsForUser($principalUri);
1772
+        foreach ($calendars as $calendar) {
1773
+            $calendarAnd = $calendarObjectIdQuery->expr()->andX();
1774
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1775
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1776
+
1777
+            // If it's shared, limit search to public events
1778
+            if ($calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
1779
+                $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1780
+            }
1781
+
1782
+            $calendarOr->add($calendarAnd);
1783
+        }
1784
+        foreach ($subscriptions as $subscription) {
1785
+            $subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1786
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1787
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1788
+
1789
+            // If it's shared, limit search to public events
1790
+            if ($subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
1791
+                $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1792
+            }
1793
+
1794
+            $calendarOr->add($subscriptionAnd);
1795
+        }
1796
+
1797
+        foreach ($searchProperties as $property) {
1798
+            $propertyAnd = $calendarObjectIdQuery->expr()->andX();
1799
+            $propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1800
+            $propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
1801
+
1802
+            $searchOr->add($propertyAnd);
1803
+        }
1804
+        foreach ($searchParameters as $property => $parameter) {
1805
+            $parameterAnd = $calendarObjectIdQuery->expr()->andX();
1806
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
1807
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
1808
+
1809
+            $searchOr->add($parameterAnd);
1810
+        }
1811
+
1812
+        if ($calendarOr->count() === 0) {
1813
+            return [];
1814
+        }
1815
+        if ($searchOr->count() === 0) {
1816
+            return [];
1817
+        }
1818
+
1819
+        $calendarObjectIdQuery->selectDistinct('cob.objectid')
1820
+            ->from($this->dbObjectPropertiesTable, 'cob')
1821
+            ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
1822
+            ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
1823
+            ->andWhere($calendarOr)
1824
+            ->andWhere($searchOr);
1825
+
1826
+        if ('' !== $pattern) {
1827
+            if (!$escapePattern) {
1828
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1829
+            } else {
1830
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1831
+            }
1832
+        }
1833
+
1834
+        if (isset($options['limit'])) {
1835
+            $calendarObjectIdQuery->setMaxResults($options['limit']);
1836
+        }
1837
+        if (isset($options['offset'])) {
1838
+            $calendarObjectIdQuery->setFirstResult($options['offset']);
1839
+        }
1840
+
1841
+        $result = $calendarObjectIdQuery->execute();
1842
+        $matches = $result->fetchAll();
1843
+        $result->closeCursor();
1844
+        $matches = array_map(static function (array $match):int {
1845
+            return (int) $match['objectid'];
1846
+        }, $matches);
1847
+
1848
+        $query = $this->db->getQueryBuilder();
1849
+        $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
1850
+            ->from('calendarobjects')
1851
+            ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
1852
+
1853
+        $result = $query->execute();
1854
+        $calendarObjects = $result->fetchAll();
1855
+        $result->closeCursor();
1856
+
1857
+        return array_map(function (array $array): array {
1858
+            $array['calendarid'] = (int)$array['calendarid'];
1859
+            $array['calendartype'] = (int)$array['calendartype'];
1860
+            $array['calendardata'] = $this->readBlob($array['calendardata']);
1861
+
1862
+            return $array;
1863
+        }, $calendarObjects);
1864
+    }
1865
+
1866
+    /**
1867
+     * Searches through all of a users calendars and calendar objects to find
1868
+     * an object with a specific UID.
1869
+     *
1870
+     * This method should return the path to this object, relative to the
1871
+     * calendar home, so this path usually only contains two parts:
1872
+     *
1873
+     * calendarpath/objectpath.ics
1874
+     *
1875
+     * If the uid is not found, return null.
1876
+     *
1877
+     * This method should only consider * objects that the principal owns, so
1878
+     * any calendars owned by other principals that also appear in this
1879
+     * collection should be ignored.
1880
+     *
1881
+     * @param string $principalUri
1882
+     * @param string $uid
1883
+     * @return string|null
1884
+     */
1885
+    public function getCalendarObjectByUID($principalUri, $uid) {
1886
+        $query = $this->db->getQueryBuilder();
1887
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1888
+            ->from('calendarobjects', 'co')
1889
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1890
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1891
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1892
+
1893
+        $stmt = $query->execute();
1894
+
1895
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1896
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1897
+        }
1898
+
1899
+        return null;
1900
+    }
1901
+
1902
+    /**
1903
+     * The getChanges method returns all the changes that have happened, since
1904
+     * the specified syncToken in the specified calendar.
1905
+     *
1906
+     * This function should return an array, such as the following:
1907
+     *
1908
+     * [
1909
+     *   'syncToken' => 'The current synctoken',
1910
+     *   'added'   => [
1911
+     *      'new.txt',
1912
+     *   ],
1913
+     *   'modified'   => [
1914
+     *      'modified.txt',
1915
+     *   ],
1916
+     *   'deleted' => [
1917
+     *      'foo.php.bak',
1918
+     *      'old.txt'
1919
+     *   ]
1920
+     * );
1921
+     *
1922
+     * The returned syncToken property should reflect the *current* syncToken
1923
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1924
+     * property This is * needed here too, to ensure the operation is atomic.
1925
+     *
1926
+     * If the $syncToken argument is specified as null, this is an initial
1927
+     * sync, and all members should be reported.
1928
+     *
1929
+     * The modified property is an array of nodenames that have changed since
1930
+     * the last token.
1931
+     *
1932
+     * The deleted property is an array with nodenames, that have been deleted
1933
+     * from collection.
1934
+     *
1935
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1936
+     * 1, you only have to report changes that happened only directly in
1937
+     * immediate descendants. If it's 2, it should also include changes from
1938
+     * the nodes below the child collections. (grandchildren)
1939
+     *
1940
+     * The $limit argument allows a client to specify how many results should
1941
+     * be returned at most. If the limit is not specified, it should be treated
1942
+     * as infinite.
1943
+     *
1944
+     * If the limit (infinite or not) is higher than you're willing to return,
1945
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1946
+     *
1947
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1948
+     * return null.
1949
+     *
1950
+     * The limit is 'suggestive'. You are free to ignore it.
1951
+     *
1952
+     * @param string $calendarId
1953
+     * @param string $syncToken
1954
+     * @param int $syncLevel
1955
+     * @param int $limit
1956
+     * @param int $calendarType
1957
+     * @return array
1958
+     */
1959
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1960
+        // Current synctoken
1961
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1962
+        $stmt->execute([ $calendarId ]);
1963
+        $currentToken = $stmt->fetchColumn(0);
1964
+
1965
+        if (is_null($currentToken)) {
1966
+            return null;
1967
+        }
1968
+
1969
+        $result = [
1970
+            'syncToken' => $currentToken,
1971
+            'added' => [],
1972
+            'modified' => [],
1973
+            'deleted' => [],
1974
+        ];
1975
+
1976
+        if ($syncToken) {
1977
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1978
+            if ($limit > 0) {
1979
+                $query .= " LIMIT " . (int)$limit;
1980
+            }
1981
+
1982
+            // Fetching all changes
1983
+            $stmt = $this->db->prepare($query);
1984
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1985
+
1986
+            $changes = [];
1987
+
1988
+            // This loop ensures that any duplicates are overwritten, only the
1989
+            // last change on a node is relevant.
1990
+            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1991
+                $changes[$row['uri']] = $row['operation'];
1992
+            }
1993
+
1994
+            foreach ($changes as $uri => $operation) {
1995
+                switch ($operation) {
1996
+                    case 1:
1997
+                        $result['added'][] = $uri;
1998
+                        break;
1999
+                    case 2:
2000
+                        $result['modified'][] = $uri;
2001
+                        break;
2002
+                    case 3:
2003
+                        $result['deleted'][] = $uri;
2004
+                        break;
2005
+                }
2006
+            }
2007
+        } else {
2008
+            // No synctoken supplied, this is the initial sync.
2009
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
2010
+            $stmt = $this->db->prepare($query);
2011
+            $stmt->execute([$calendarId, $calendarType]);
2012
+
2013
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2014
+        }
2015
+        return $result;
2016
+    }
2017
+
2018
+    /**
2019
+     * Returns a list of subscriptions for a principal.
2020
+     *
2021
+     * Every subscription is an array with the following keys:
2022
+     *  * id, a unique id that will be used by other functions to modify the
2023
+     *    subscription. This can be the same as the uri or a database key.
2024
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2025
+     *  * principaluri. The owner of the subscription. Almost always the same as
2026
+     *    principalUri passed to this method.
2027
+     *
2028
+     * Furthermore, all the subscription info must be returned too:
2029
+     *
2030
+     * 1. {DAV:}displayname
2031
+     * 2. {http://apple.com/ns/ical/}refreshrate
2032
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2033
+     *    should not be stripped).
2034
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2035
+     *    should not be stripped).
2036
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2037
+     *    attachments should not be stripped).
2038
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2039
+     *     Sabre\DAV\Property\Href).
2040
+     * 7. {http://apple.com/ns/ical/}calendar-color
2041
+     * 8. {http://apple.com/ns/ical/}calendar-order
2042
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2043
+     *    (should just be an instance of
2044
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2045
+     *    default components).
2046
+     *
2047
+     * @param string $principalUri
2048
+     * @return array
2049
+     */
2050
+    public function getSubscriptionsForUser($principalUri) {
2051
+        $fields = array_values($this->subscriptionPropertyMap);
2052
+        $fields[] = 'id';
2053
+        $fields[] = 'uri';
2054
+        $fields[] = 'source';
2055
+        $fields[] = 'principaluri';
2056
+        $fields[] = 'lastmodified';
2057
+        $fields[] = 'synctoken';
2058
+
2059
+        $query = $this->db->getQueryBuilder();
2060
+        $query->select($fields)
2061
+            ->from('calendarsubscriptions')
2062
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2063
+            ->orderBy('calendarorder', 'asc');
2064
+        $stmt = $query->execute();
2065
+
2066
+        $subscriptions = [];
2067
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
2068
+            $subscription = [
2069
+                'id' => $row['id'],
2070
+                'uri' => $row['uri'],
2071
+                'principaluri' => $row['principaluri'],
2072
+                'source' => $row['source'],
2073
+                'lastmodified' => $row['lastmodified'],
2074
+
2075
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2076
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2077
+            ];
2078
+
2079
+            foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2080
+                if (!is_null($row[$dbName])) {
2081
+                    $subscription[$xmlName] = $row[$dbName];
2082
+                }
2083
+            }
2084
+
2085
+            $subscriptions[] = $subscription;
2086
+        }
2087
+
2088
+        return $subscriptions;
2089
+    }
2090
+
2091
+    /**
2092
+     * Creates a new subscription for a principal.
2093
+     *
2094
+     * If the creation was a success, an id must be returned that can be used to reference
2095
+     * this subscription in other methods, such as updateSubscription.
2096
+     *
2097
+     * @param string $principalUri
2098
+     * @param string $uri
2099
+     * @param array $properties
2100
+     * @return mixed
2101
+     */
2102
+    public function createSubscription($principalUri, $uri, array $properties) {
2103
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2104
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2105
+        }
2106
+
2107
+        $values = [
2108
+            'principaluri' => $principalUri,
2109
+            'uri' => $uri,
2110
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2111
+            'lastmodified' => time(),
2112
+        ];
2113
+
2114
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2115
+
2116
+        foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2117
+            if (array_key_exists($xmlName, $properties)) {
2118
+                $values[$dbName] = $properties[$xmlName];
2119
+                if (in_array($dbName, $propertiesBoolean)) {
2120
+                    $values[$dbName] = true;
2121
+                }
2122
+            }
2123
+        }
2124
+
2125
+        $valuesToInsert = [];
2126
+
2127
+        $query = $this->db->getQueryBuilder();
2128
+
2129
+        foreach (array_keys($values) as $name) {
2130
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2131
+        }
2132
+
2133
+        $query->insert('calendarsubscriptions')
2134
+            ->values($valuesToInsert)
2135
+            ->execute();
2136
+
2137
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
2138
+
2139
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2140
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent((int)$subscriptionId, $subscriptionRow));
2141
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2142
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2143
+            [
2144
+                'subscriptionId' => $subscriptionId,
2145
+                'subscriptionData' => $subscriptionRow,
2146
+            ]));
2147
+
2148
+        return $subscriptionId;
2149
+    }
2150
+
2151
+    /**
2152
+     * Updates a subscription
2153
+     *
2154
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2155
+     * To do the actual updates, you must tell this object which properties
2156
+     * you're going to process with the handle() method.
2157
+     *
2158
+     * Calling the handle method is like telling the PropPatch object "I
2159
+     * promise I can handle updating this property".
2160
+     *
2161
+     * Read the PropPatch documentation for more info and examples.
2162
+     *
2163
+     * @param mixed $subscriptionId
2164
+     * @param PropPatch $propPatch
2165
+     * @return void
2166
+     */
2167
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2168
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2169
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2170
+
2171
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2172
+            $newValues = [];
2173
+
2174
+            foreach ($mutations as $propertyName => $propertyValue) {
2175
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2176
+                    $newValues['source'] = $propertyValue->getHref();
2177
+                } else {
2178
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2179
+                    $newValues[$fieldName] = $propertyValue;
2180
+                }
2181
+            }
2182
+
2183
+            $query = $this->db->getQueryBuilder();
2184
+            $query->update('calendarsubscriptions')
2185
+                ->set('lastmodified', $query->createNamedParameter(time()));
2186
+            foreach ($newValues as $fieldName => $value) {
2187
+                $query->set($fieldName, $query->createNamedParameter($value));
2188
+            }
2189
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2190
+                ->execute();
2191
+
2192
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2193
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2194
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2195
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2196
+                [
2197
+                    'subscriptionId' => $subscriptionId,
2198
+                    'subscriptionData' => $subscriptionRow,
2199
+                    'propertyMutations' => $mutations,
2200
+                ]));
2201
+
2202
+            return true;
2203
+        });
2204
+    }
2205
+
2206
+    /**
2207
+     * Deletes a subscription.
2208
+     *
2209
+     * @param mixed $subscriptionId
2210
+     * @return void
2211
+     */
2212
+    public function deleteSubscription($subscriptionId) {
2213
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2214
+
2215
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2216
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2217
+            [
2218
+                'subscriptionId' => $subscriptionId,
2219
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2220
+            ]));
2221
+
2222
+        $query = $this->db->getQueryBuilder();
2223
+        $query->delete('calendarsubscriptions')
2224
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2225
+            ->execute();
2226
+
2227
+        $query = $this->db->getQueryBuilder();
2228
+        $query->delete('calendarobjects')
2229
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2230
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2231
+            ->execute();
2232
+
2233
+        $query->delete('calendarchanges')
2234
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2235
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2236
+            ->execute();
2237
+
2238
+        $query->delete($this->dbObjectPropertiesTable)
2239
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2240
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2241
+            ->execute();
2242
+
2243
+        if ($subscriptionRow) {
2244
+            $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2245
+        }
2246
+    }
2247
+
2248
+    /**
2249
+     * Returns a single scheduling object for the inbox collection.
2250
+     *
2251
+     * The returned array should contain the following elements:
2252
+     *   * uri - A unique basename for the object. This will be used to
2253
+     *           construct a full uri.
2254
+     *   * calendardata - The iCalendar object
2255
+     *   * lastmodified - The last modification date. Can be an int for a unix
2256
+     *                    timestamp, or a PHP DateTime object.
2257
+     *   * etag - A unique token that must change if the object changed.
2258
+     *   * size - The size of the object, in bytes.
2259
+     *
2260
+     * @param string $principalUri
2261
+     * @param string $objectUri
2262
+     * @return array
2263
+     */
2264
+    public function getSchedulingObject($principalUri, $objectUri) {
2265
+        $query = $this->db->getQueryBuilder();
2266
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2267
+            ->from('schedulingobjects')
2268
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2269
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2270
+            ->execute();
2271
+
2272
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2273
+
2274
+        if (!$row) {
2275
+            return null;
2276
+        }
2277
+
2278
+        return [
2279
+            'uri' => $row['uri'],
2280
+            'calendardata' => $row['calendardata'],
2281
+            'lastmodified' => $row['lastmodified'],
2282
+            'etag' => '"' . $row['etag'] . '"',
2283
+            'size' => (int)$row['size'],
2284
+        ];
2285
+    }
2286
+
2287
+    /**
2288
+     * Returns all scheduling objects for the inbox collection.
2289
+     *
2290
+     * These objects should be returned as an array. Every item in the array
2291
+     * should follow the same structure as returned from getSchedulingObject.
2292
+     *
2293
+     * The main difference is that 'calendardata' is optional.
2294
+     *
2295
+     * @param string $principalUri
2296
+     * @return array
2297
+     */
2298
+    public function getSchedulingObjects($principalUri) {
2299
+        $query = $this->db->getQueryBuilder();
2300
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2301
+                ->from('schedulingobjects')
2302
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2303
+                ->execute();
2304
+
2305
+        $result = [];
2306
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2307
+            $result[] = [
2308
+                'calendardata' => $row['calendardata'],
2309
+                'uri' => $row['uri'],
2310
+                'lastmodified' => $row['lastmodified'],
2311
+                'etag' => '"' . $row['etag'] . '"',
2312
+                'size' => (int)$row['size'],
2313
+            ];
2314
+        }
2315
+
2316
+        return $result;
2317
+    }
2318
+
2319
+    /**
2320
+     * Deletes a scheduling object from the inbox collection.
2321
+     *
2322
+     * @param string $principalUri
2323
+     * @param string $objectUri
2324
+     * @return void
2325
+     */
2326
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2327
+        $query = $this->db->getQueryBuilder();
2328
+        $query->delete('schedulingobjects')
2329
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2330
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2331
+                ->execute();
2332
+    }
2333
+
2334
+    /**
2335
+     * Creates a new scheduling object. This should land in a users' inbox.
2336
+     *
2337
+     * @param string $principalUri
2338
+     * @param string $objectUri
2339
+     * @param string $objectData
2340
+     * @return void
2341
+     */
2342
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2343
+        $query = $this->db->getQueryBuilder();
2344
+        $query->insert('schedulingobjects')
2345
+            ->values([
2346
+                'principaluri' => $query->createNamedParameter($principalUri),
2347
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2348
+                'uri' => $query->createNamedParameter($objectUri),
2349
+                'lastmodified' => $query->createNamedParameter(time()),
2350
+                'etag' => $query->createNamedParameter(md5($objectData)),
2351
+                'size' => $query->createNamedParameter(strlen($objectData))
2352
+            ])
2353
+            ->execute();
2354
+    }
2355
+
2356
+    /**
2357
+     * Adds a change record to the calendarchanges table.
2358
+     *
2359
+     * @param mixed $calendarId
2360
+     * @param string $objectUri
2361
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2362
+     * @param int $calendarType
2363
+     * @return void
2364
+     */
2365
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2366
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2367
+
2368
+        $query = $this->db->getQueryBuilder();
2369
+        $query->select('synctoken')
2370
+            ->from($table)
2371
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2372
+        $result = $query->execute();
2373
+        $syncToken = (int)$result->fetchColumn();
2374
+        $result->closeCursor();
2375
+
2376
+        $query = $this->db->getQueryBuilder();
2377
+        $query->insert('calendarchanges')
2378
+            ->values([
2379
+                'uri' => $query->createNamedParameter($objectUri),
2380
+                'synctoken' => $query->createNamedParameter($syncToken),
2381
+                'calendarid' => $query->createNamedParameter($calendarId),
2382
+                'operation' => $query->createNamedParameter($operation),
2383
+                'calendartype' => $query->createNamedParameter($calendarType),
2384
+            ])
2385
+            ->execute();
2386
+
2387
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2388
+        $stmt->execute([
2389
+            $calendarId
2390
+        ]);
2391
+    }
2392
+
2393
+    /**
2394
+     * Parses some information from calendar objects, used for optimized
2395
+     * calendar-queries.
2396
+     *
2397
+     * Returns an array with the following keys:
2398
+     *   * etag - An md5 checksum of the object without the quotes.
2399
+     *   * size - Size of the object in bytes
2400
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2401
+     *   * firstOccurence
2402
+     *   * lastOccurence
2403
+     *   * uid - value of the UID property
2404
+     *
2405
+     * @param string $calendarData
2406
+     * @return array
2407
+     */
2408
+    public function getDenormalizedData($calendarData) {
2409
+        $vObject = Reader::read($calendarData);
2410
+        $vEvents = [];
2411
+        $componentType = null;
2412
+        $component = null;
2413
+        $firstOccurrence = null;
2414
+        $lastOccurrence = null;
2415
+        $uid = null;
2416
+        $classification = self::CLASSIFICATION_PUBLIC;
2417
+        $hasDTSTART = false;
2418
+        foreach ($vObject->getComponents() as $component) {
2419
+            if ($component->name !== 'VTIMEZONE') {
2420
+                // Finding all VEVENTs, and track them
2421
+                if ($component->name === 'VEVENT') {
2422
+                    array_push($vEvents, $component);
2423
+                    if ($component->DTSTART) {
2424
+                        $hasDTSTART = true;
2425
+                    }
2426
+                }
2427
+                // Track first component type and uid
2428
+                if ($uid === null) {
2429
+                    $componentType = $component->name;
2430
+                    $uid = (string)$component->UID;
2431
+                }
2432
+            }
2433
+        }
2434
+        if (!$componentType) {
2435
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2436
+        }
2437
+
2438
+        if ($hasDTSTART) {
2439
+            $component = $vEvents[0];
2440
+
2441
+            // Finding the last occurrence is a bit harder
2442
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
2443
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2444
+                if (isset($component->DTEND)) {
2445
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2446
+                } elseif (isset($component->DURATION)) {
2447
+                    $endDate = clone $component->DTSTART->getDateTime();
2448
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2449
+                    $lastOccurrence = $endDate->getTimeStamp();
2450
+                } elseif (!$component->DTSTART->hasTime()) {
2451
+                    $endDate = clone $component->DTSTART->getDateTime();
2452
+                    $endDate->modify('+1 day');
2453
+                    $lastOccurrence = $endDate->getTimeStamp();
2454
+                } else {
2455
+                    $lastOccurrence = $firstOccurrence;
2456
+                }
2457
+            } else {
2458
+                $it = new EventIterator($vEvents);
2459
+                $maxDate = new DateTime(self::MAX_DATE);
2460
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
2461
+                if ($it->isInfinite()) {
2462
+                    $lastOccurrence = $maxDate->getTimestamp();
2463
+                } else {
2464
+                    $end = $it->getDtEnd();
2465
+                    while ($it->valid() && $end < $maxDate) {
2466
+                        $end = $it->getDtEnd();
2467
+                        $it->next();
2468
+                    }
2469
+                    $lastOccurrence = $end->getTimestamp();
2470
+                }
2471
+            }
2472
+        }
2473
+
2474
+        if ($component->CLASS) {
2475
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2476
+            switch ($component->CLASS->getValue()) {
2477
+                case 'PUBLIC':
2478
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2479
+                    break;
2480
+                case 'CONFIDENTIAL':
2481
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2482
+                    break;
2483
+            }
2484
+        }
2485
+        return [
2486
+            'etag' => md5($calendarData),
2487
+            'size' => strlen($calendarData),
2488
+            'componentType' => $componentType,
2489
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2490
+            'lastOccurence' => $lastOccurrence,
2491
+            'uid' => $uid,
2492
+            'classification' => $classification
2493
+        ];
2494
+    }
2495
+
2496
+    /**
2497
+     * @param $cardData
2498
+     * @return bool|string
2499
+     */
2500
+    private function readBlob($cardData) {
2501
+        if (is_resource($cardData)) {
2502
+            return stream_get_contents($cardData);
2503
+        }
2504
+
2505
+        return $cardData;
2506
+    }
2507
+
2508
+    /**
2509
+     * @param IShareable $shareable
2510
+     * @param array $add
2511
+     * @param array $remove
2512
+     */
2513
+    public function updateShares($shareable, $add, $remove) {
2514
+        $calendarId = $shareable->getResourceId();
2515
+        $calendarRow = $this->getCalendarById($calendarId);
2516
+        $oldShares = $this->getShares($calendarId);
2517
+
2518
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2519
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2520
+            [
2521
+                'calendarId' => $calendarId,
2522
+                'calendarData' => $calendarRow,
2523
+                'shares' => $oldShares,
2524
+                'add' => $add,
2525
+                'remove' => $remove,
2526
+            ]));
2527
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2528
+
2529
+        $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2530
+    }
2531
+
2532
+    /**
2533
+     * @param int $resourceId
2534
+     * @param int $calendarType
2535
+     * @return array
2536
+     */
2537
+    public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2538
+        return $this->calendarSharingBackend->getShares($resourceId);
2539
+    }
2540
+
2541
+    /**
2542
+     * @param boolean $value
2543
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2544
+     * @return string|null
2545
+     */
2546
+    public function setPublishStatus($value, $calendar) {
2547
+        $calendarId = $calendar->getResourceId();
2548
+        $calendarData = $this->getCalendarById($calendarId);
2549
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2550
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2551
+            [
2552
+                'calendarId' => $calendarId,
2553
+                'calendarData' => $calendarData,
2554
+                'public' => $value,
2555
+            ]));
2556
+
2557
+        $query = $this->db->getQueryBuilder();
2558
+        if ($value) {
2559
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2560
+            $query->insert('dav_shares')
2561
+                ->values([
2562
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2563
+                    'type' => $query->createNamedParameter('calendar'),
2564
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2565
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2566
+                    'publicuri' => $query->createNamedParameter($publicUri)
2567
+                ]);
2568
+            $query->execute();
2569
+
2570
+            $this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2571
+            return $publicUri;
2572
+        }
2573
+        $query->delete('dav_shares')
2574
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2575
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2576
+        $query->execute();
2577
+
2578
+        $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2579
+        return null;
2580
+    }
2581
+
2582
+    /**
2583
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2584
+     * @return mixed
2585
+     */
2586
+    public function getPublishStatus($calendar) {
2587
+        $query = $this->db->getQueryBuilder();
2588
+        $result = $query->select('publicuri')
2589
+            ->from('dav_shares')
2590
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2591
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2592
+            ->execute();
2593
+
2594
+        $row = $result->fetch();
2595
+        $result->closeCursor();
2596
+        return $row ? reset($row) : false;
2597
+    }
2598
+
2599
+    /**
2600
+     * @param int $resourceId
2601
+     * @param array $acl
2602
+     * @return array
2603
+     */
2604
+    public function applyShareAcl($resourceId, $acl) {
2605
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2606
+    }
2607
+
2608
+
2609
+
2610
+    /**
2611
+     * update properties table
2612
+     *
2613
+     * @param int $calendarId
2614
+     * @param string $objectUri
2615
+     * @param string $calendarData
2616
+     * @param int $calendarType
2617
+     */
2618
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2619
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2620
+
2621
+        try {
2622
+            $vCalendar = $this->readCalendarData($calendarData);
2623
+        } catch (\Exception $ex) {
2624
+            return;
2625
+        }
2626
+
2627
+        $this->purgeProperties($calendarId, $objectId);
2628
+
2629
+        $query = $this->db->getQueryBuilder();
2630
+        $query->insert($this->dbObjectPropertiesTable)
2631
+            ->values(
2632
+                [
2633
+                    'calendarid' => $query->createNamedParameter($calendarId),
2634
+                    'calendartype' => $query->createNamedParameter($calendarType),
2635
+                    'objectid' => $query->createNamedParameter($objectId),
2636
+                    'name' => $query->createParameter('name'),
2637
+                    'parameter' => $query->createParameter('parameter'),
2638
+                    'value' => $query->createParameter('value'),
2639
+                ]
2640
+            );
2641
+
2642
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2643
+        foreach ($vCalendar->getComponents() as $component) {
2644
+            if (!in_array($component->name, $indexComponents)) {
2645
+                continue;
2646
+            }
2647
+
2648
+            foreach ($component->children() as $property) {
2649
+                if (in_array($property->name, self::$indexProperties)) {
2650
+                    $value = $property->getValue();
2651
+                    // is this a shitty db?
2652
+                    if (!$this->db->supports4ByteText()) {
2653
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2654
+                    }
2655
+                    $value = mb_substr($value, 0, 254);
2656
+
2657
+                    $query->setParameter('name', $property->name);
2658
+                    $query->setParameter('parameter', null);
2659
+                    $query->setParameter('value', $value);
2660
+                    $query->execute();
2661
+                }
2662
+
2663
+                if (array_key_exists($property->name, self::$indexParameters)) {
2664
+                    $parameters = $property->parameters();
2665
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2666
+
2667
+                    foreach ($parameters as $key => $value) {
2668
+                        if (in_array($key, $indexedParametersForProperty)) {
2669
+                            // is this a shitty db?
2670
+                            if ($this->db->supports4ByteText()) {
2671
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2672
+                            }
2673
+
2674
+                            $query->setParameter('name', $property->name);
2675
+                            $query->setParameter('parameter', mb_substr($key, 0, 254));
2676
+                            $query->setParameter('value', mb_substr($value, 0, 254));
2677
+                            $query->execute();
2678
+                        }
2679
+                    }
2680
+                }
2681
+            }
2682
+        }
2683
+    }
2684
+
2685
+    /**
2686
+     * deletes all birthday calendars
2687
+     */
2688
+    public function deleteAllBirthdayCalendars() {
2689
+        $query = $this->db->getQueryBuilder();
2690
+        $result = $query->select(['id'])->from('calendars')
2691
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2692
+            ->execute();
2693
+
2694
+        $ids = $result->fetchAll();
2695
+        foreach ($ids as $id) {
2696
+            $this->deleteCalendar($id['id']);
2697
+        }
2698
+    }
2699
+
2700
+    /**
2701
+     * @param $subscriptionId
2702
+     */
2703
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2704
+        $query = $this->db->getQueryBuilder();
2705
+        $query->select('uri')
2706
+            ->from('calendarobjects')
2707
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2708
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2709
+        $stmt = $query->execute();
2710
+
2711
+        $uris = [];
2712
+        foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2713
+            $uris[] = $row['uri'];
2714
+        }
2715
+        $stmt->closeCursor();
2716
+
2717
+        $query = $this->db->getQueryBuilder();
2718
+        $query->delete('calendarobjects')
2719
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2720
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2721
+            ->execute();
2722
+
2723
+        $query->delete('calendarchanges')
2724
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2725
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2726
+            ->execute();
2727
+
2728
+        $query->delete($this->dbObjectPropertiesTable)
2729
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2730
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2731
+            ->execute();
2732
+
2733
+        foreach ($uris as $uri) {
2734
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2735
+        }
2736
+    }
2737
+
2738
+    /**
2739
+     * Move a calendar from one user to another
2740
+     *
2741
+     * @param string $uriName
2742
+     * @param string $uriOrigin
2743
+     * @param string $uriDestination
2744
+     */
2745
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination) {
2746
+        $query = $this->db->getQueryBuilder();
2747
+        $query->update('calendars')
2748
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2749
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2750
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2751
+            ->execute();
2752
+    }
2753
+
2754
+    /**
2755
+     * read VCalendar data into a VCalendar object
2756
+     *
2757
+     * @param string $objectData
2758
+     * @return VCalendar
2759
+     */
2760
+    protected function readCalendarData($objectData) {
2761
+        return Reader::read($objectData);
2762
+    }
2763
+
2764
+    /**
2765
+     * delete all properties from a given calendar object
2766
+     *
2767
+     * @param int $calendarId
2768
+     * @param int $objectId
2769
+     */
2770
+    protected function purgeProperties($calendarId, $objectId) {
2771
+        $query = $this->db->getQueryBuilder();
2772
+        $query->delete($this->dbObjectPropertiesTable)
2773
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2774
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2775
+        $query->execute();
2776
+    }
2777
+
2778
+    /**
2779
+     * get ID from a given calendar object
2780
+     *
2781
+     * @param int $calendarId
2782
+     * @param string $uri
2783
+     * @param int $calendarType
2784
+     * @return int
2785
+     */
2786
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2787
+        $query = $this->db->getQueryBuilder();
2788
+        $query->select('id')
2789
+            ->from('calendarobjects')
2790
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2791
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2792
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2793
+
2794
+        $result = $query->execute();
2795
+        $objectIds = $result->fetch();
2796
+        $result->closeCursor();
2797
+
2798
+        if (!isset($objectIds['id'])) {
2799
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2800
+        }
2801
+
2802
+        return (int)$objectIds['id'];
2803
+    }
2804
+
2805
+    /**
2806
+     * return legacy endpoint principal name to new principal name
2807
+     *
2808
+     * @param $principalUri
2809
+     * @param $toV2
2810
+     * @return string
2811
+     */
2812
+    private function convertPrincipal($principalUri, $toV2) {
2813
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2814
+            list(, $name) = Uri\split($principalUri);
2815
+            if ($toV2 === true) {
2816
+                return "principals/users/$name";
2817
+            }
2818
+            return "principals/$name";
2819
+        }
2820
+        return $principalUri;
2821
+    }
2822
+
2823
+    /**
2824
+     * adds information about an owner to the calendar data
2825
+     *
2826
+     * @param $calendarInfo
2827
+     */
2828
+    private function addOwnerPrincipal(&$calendarInfo) {
2829
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2830
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2831
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2832
+            $uri = $calendarInfo[$ownerPrincipalKey];
2833
+        } else {
2834
+            $uri = $calendarInfo['principaluri'];
2835
+        }
2836
+
2837
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2838
+        if (isset($principalInformation['{DAV:}displayname'])) {
2839
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2840
+        }
2841
+    }
2842 2842
 }
Please login to merge, or discard this patch.
Spacing   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 		}
256 256
 
257 257
 		$result = $query->execute();
258
-		$column = (int)$result->fetchColumn();
258
+		$column = (int) $result->fetchColumn();
259 259
 		$result->closeCursor();
260 260
 		return $column;
261 261
 	}
@@ -315,18 +315,18 @@  discard block
 block discarded – undo
315 315
 			$row['principaluri'] = (string) $row['principaluri'];
316 316
 			$components = [];
317 317
 			if ($row['components']) {
318
-				$components = explode(',',$row['components']);
318
+				$components = explode(',', $row['components']);
319 319
 			}
320 320
 
321 321
 			$calendar = [
322 322
 				'id' => $row['id'],
323 323
 				'uri' => $row['uri'],
324 324
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
325
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
326
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
327
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
328
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
329
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
325
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
326
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
327
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
328
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
329
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
330 330
 			];
331 331
 
332 332
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
 			->setParameter('type', 'calendar')
365 365
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
366 366
 
367
-		$result	= $query->execute();
367
+		$result = $query->execute();
368 368
 
369
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
369
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
370 370
 		while ($row = $result->fetch()) {
371 371
 			$row['principaluri'] = (string) $row['principaluri'];
372 372
 			if ($row['principaluri'] === $principalUri) {
@@ -387,21 +387,21 @@  discard block
 block discarded – undo
387 387
 			}
388 388
 
389 389
 			list(, $name) = Uri\split($row['principaluri']);
390
-			$uri = $row['uri'] . '_shared_by_' . $name;
391
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
390
+			$uri = $row['uri'].'_shared_by_'.$name;
391
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
392 392
 			$components = [];
393 393
 			if ($row['components']) {
394
-				$components = explode(',',$row['components']);
394
+				$components = explode(',', $row['components']);
395 395
 			}
396 396
 			$calendar = [
397 397
 				'id' => $row['id'],
398 398
 				'uri' => $uri,
399 399
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
400
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
401
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
402
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
404
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
400
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
401
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
402
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
404
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
405 405
 				$readOnlyPropertyName => $readOnly,
406 406
 			];
407 407
 
@@ -442,16 +442,16 @@  discard block
 block discarded – undo
442 442
 			$row['principaluri'] = (string) $row['principaluri'];
443 443
 			$components = [];
444 444
 			if ($row['components']) {
445
-				$components = explode(',',$row['components']);
445
+				$components = explode(',', $row['components']);
446 446
 			}
447 447
 			$calendar = [
448 448
 				'id' => $row['id'],
449 449
 				'uri' => $row['uri'],
450 450
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
451
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
452
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
453
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
454
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
451
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
452
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
453
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
454
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
455 455
 			];
456 456
 			foreach ($this->propertyMap as $xmlName => $dbName) {
457 457
 				$calendar[$xmlName] = $row[$dbName];
@@ -511,22 +511,22 @@  discard block
 block discarded – undo
511 511
 		while ($row = $result->fetch()) {
512 512
 			$row['principaluri'] = (string) $row['principaluri'];
513 513
 			list(, $name) = Uri\split($row['principaluri']);
514
-			$row['displayname'] = $row['displayname'] . "($name)";
514
+			$row['displayname'] = $row['displayname']."($name)";
515 515
 			$components = [];
516 516
 			if ($row['components']) {
517
-				$components = explode(',',$row['components']);
517
+				$components = explode(',', $row['components']);
518 518
 			}
519 519
 			$calendar = [
520 520
 				'id' => $row['id'],
521 521
 				'uri' => $row['publicuri'],
522 522
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
523
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
524
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
525
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
527
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
528
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
529
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
523
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
524
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
525
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
526
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
527
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
528
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
529
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
530 530
 			];
531 531
 
532 532
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -573,27 +573,27 @@  discard block
 block discarded – undo
573 573
 		$result->closeCursor();
574 574
 
575 575
 		if ($row === false) {
576
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
576
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
577 577
 		}
578 578
 
579 579
 		$row['principaluri'] = (string) $row['principaluri'];
580 580
 		list(, $name) = Uri\split($row['principaluri']);
581
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
581
+		$row['displayname'] = $row['displayname'].' '."($name)";
582 582
 		$components = [];
583 583
 		if ($row['components']) {
584
-			$components = explode(',',$row['components']);
584
+			$components = explode(',', $row['components']);
585 585
 		}
586 586
 		$calendar = [
587 587
 			'id' => $row['id'],
588 588
 			'uri' => $row['publicuri'],
589 589
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
590
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
591
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
592
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
593
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
594
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
595
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
596
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
590
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
591
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
592
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
593
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
594
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
595
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
596
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
597 597
 		];
598 598
 
599 599
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -636,17 +636,17 @@  discard block
 block discarded – undo
636 636
 		$row['principaluri'] = (string) $row['principaluri'];
637 637
 		$components = [];
638 638
 		if ($row['components']) {
639
-			$components = explode(',',$row['components']);
639
+			$components = explode(',', $row['components']);
640 640
 		}
641 641
 
642 642
 		$calendar = [
643 643
 			'id' => $row['id'],
644 644
 			'uri' => $row['uri'],
645 645
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
646
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
647
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
648
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
649
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
646
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
647
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
648
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
649
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
650 650
 		];
651 651
 
652 652
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -687,17 +687,17 @@  discard block
 block discarded – undo
687 687
 		$row['principaluri'] = (string) $row['principaluri'];
688 688
 		$components = [];
689 689
 		if ($row['components']) {
690
-			$components = explode(',',$row['components']);
690
+			$components = explode(',', $row['components']);
691 691
 		}
692 692
 
693 693
 		$calendar = [
694 694
 			'id' => $row['id'],
695 695
 			'uri' => $row['uri'],
696 696
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
697
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
698
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
699
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
700
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
697
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
698
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
699
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
700
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
701 701
 		];
702 702
 
703 703
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -741,8 +741,8 @@  discard block
 block discarded – undo
741 741
 			'principaluri' => $row['principaluri'],
742 742
 			'source' => $row['source'],
743 743
 			'lastmodified' => $row['lastmodified'],
744
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
745
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
744
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
745
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
746 746
 		];
747 747
 
748 748
 		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -779,16 +779,16 @@  discard block
 block discarded – undo
779 779
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
780 780
 		if (isset($properties[$sccs])) {
781 781
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
782
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
782
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
783 783
 			}
784
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
784
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
785 785
 		} elseif (isset($properties['components'])) {
786 786
 			// Allow to provide components internally without having
787 787
 			// to create a SupportedCalendarComponentSet object
788 788
 			$values['components'] = $properties['components'];
789 789
 		}
790 790
 
791
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
791
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
792 792
 		if (isset($properties[$transp])) {
793 793
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
794 794
 		}
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
 		$calendarId = $query->getLastInsertId();
809 809
 
810 810
 		$calendarData = $this->getCalendarById($calendarId);
811
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
811
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
812 812
 		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
813 813
 			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
814 814
 			[
@@ -837,13 +837,13 @@  discard block
 block discarded – undo
837 837
 	 */
838 838
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
839 839
 		$supportedProperties = array_keys($this->propertyMap);
840
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
840
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
841 841
 
842
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
842
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
843 843
 			$newValues = [];
844 844
 			foreach ($mutations as $propertyName => $propertyValue) {
845 845
 				switch ($propertyName) {
846
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
846
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
847 847
 						$fieldName = 'transparent';
848 848
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
849 849
 						break;
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
 
866 866
 			$calendarData = $this->getCalendarById($calendarId);
867 867
 			$shares = $this->getShares($calendarId);
868
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
868
+			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int) $calendarId, $calendarData, $shares, $mutations));
869 869
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
870 870
 				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
871 871
 				[
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
 			->execute();
916 916
 
917 917
 		if ($calendarData) {
918
-			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
918
+			$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int) $calendarId, $calendarData, $shares));
919 919
 		}
920 920
 	}
921 921
 
@@ -975,11 +975,11 @@  discard block
 block discarded – undo
975 975
 				'id' => $row['id'],
976 976
 				'uri' => $row['uri'],
977 977
 				'lastmodified' => $row['lastmodified'],
978
-				'etag' => '"' . $row['etag'] . '"',
978
+				'etag' => '"'.$row['etag'].'"',
979 979
 				'calendarid' => $row['calendarid'],
980
-				'size' => (int)$row['size'],
980
+				'size' => (int) $row['size'],
981 981
 				'component' => strtolower($row['componenttype']),
982
-				'classification' => (int)$row['classification']
982
+				'classification' => (int) $row['classification']
983 983
 			];
984 984
 		}
985 985
 		$stmt->closeCursor();
@@ -1023,12 +1023,12 @@  discard block
 block discarded – undo
1023 1023
 			'id' => $row['id'],
1024 1024
 			'uri' => $row['uri'],
1025 1025
 			'lastmodified' => $row['lastmodified'],
1026
-			'etag' => '"' . $row['etag'] . '"',
1026
+			'etag' => '"'.$row['etag'].'"',
1027 1027
 			'calendarid' => $row['calendarid'],
1028
-			'size' => (int)$row['size'],
1028
+			'size' => (int) $row['size'],
1029 1029
 			'calendardata' => $this->readBlob($row['calendardata']),
1030 1030
 			'component' => strtolower($row['componenttype']),
1031
-			'classification' => (int)$row['classification']
1031
+			'classification' => (int) $row['classification']
1032 1032
 		];
1033 1033
 	}
1034 1034
 
@@ -1069,12 +1069,12 @@  discard block
 block discarded – undo
1069 1069
 					'id' => $row['id'],
1070 1070
 					'uri' => $row['uri'],
1071 1071
 					'lastmodified' => $row['lastmodified'],
1072
-					'etag' => '"' . $row['etag'] . '"',
1072
+					'etag' => '"'.$row['etag'].'"',
1073 1073
 					'calendarid' => $row['calendarid'],
1074
-					'size' => (int)$row['size'],
1074
+					'size' => (int) $row['size'],
1075 1075
 					'calendardata' => $this->readBlob($row['calendardata']),
1076 1076
 					'component' => strtolower($row['componenttype']),
1077
-					'classification' => (int)$row['classification']
1077
+					'classification' => (int) $row['classification']
1078 1078
 				];
1079 1079
 			}
1080 1080
 			$result->closeCursor();
@@ -1146,7 +1146,7 @@  discard block
 block discarded – undo
1146 1146
 			$calendarRow = $this->getCalendarById($calendarId);
1147 1147
 			$shares = $this->getShares($calendarId);
1148 1148
 
1149
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1149
+			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1150 1150
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1151 1151
 				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1152 1152
 				[
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
 		} else {
1160 1160
 			$subscriptionRow = $this->getSubscriptionById($calendarId);
1161 1161
 
1162
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1162
+			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1163 1163
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1164 1164
 				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1165 1165
 				[
@@ -1171,7 +1171,7 @@  discard block
 block discarded – undo
1171 1171
 			));
1172 1172
 		}
1173 1173
 
1174
-		return '"' . $extraData['etag'] . '"';
1174
+		return '"'.$extraData['etag'].'"';
1175 1175
 	}
1176 1176
 
1177 1177
 	/**
@@ -1220,7 +1220,7 @@  discard block
 block discarded – undo
1220 1220
 				$calendarRow = $this->getCalendarById($calendarId);
1221 1221
 				$shares = $this->getShares($calendarId);
1222 1222
 
1223
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1223
+				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1224 1224
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1225 1225
 					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1226 1226
 					[
@@ -1233,7 +1233,7 @@  discard block
 block discarded – undo
1233 1233
 			} else {
1234 1234
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1235 1235
 
1236
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1236
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1237 1237
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1238 1238
 					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1239 1239
 					[
@@ -1246,7 +1246,7 @@  discard block
 block discarded – undo
1246 1246
 			}
1247 1247
 		}
1248 1248
 
1249
-		return '"' . $extraData['etag'] . '"';
1249
+		return '"'.$extraData['etag'].'"';
1250 1250
 	}
1251 1251
 
1252 1252
 	/**
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
 				$calendarRow = $this->getCalendarById($calendarId);
1284 1284
 				$shares = $this->getShares($calendarId);
1285 1285
 
1286
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1286
+				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int) $calendarId, $calendarRow, $shares, $data));
1287 1287
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1288 1288
 					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1289 1289
 					[
@@ -1296,7 +1296,7 @@  discard block
 block discarded – undo
1296 1296
 			} else {
1297 1297
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1298 1298
 
1299
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1299
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int) $calendarId, $subscriptionRow, [], $data));
1300 1300
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1301 1301
 					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1302 1302
 					[
@@ -1568,7 +1568,7 @@  discard block
 block discarded – undo
1568 1568
 
1569 1569
 		$result = [];
1570 1570
 		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1571
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1571
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1572 1572
 			if (!in_array($path, $result)) {
1573 1573
 				$result[] = $path;
1574 1574
 			}
@@ -1616,8 +1616,8 @@  discard block
 block discarded – undo
1616 1616
 
1617 1617
 		if ($pattern !== '') {
1618 1618
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1619
-				$outerQuery->createNamedParameter('%' .
1620
-					$this->db->escapeLikeParameter($pattern) . '%')));
1619
+				$outerQuery->createNamedParameter('%'.
1620
+					$this->db->escapeLikeParameter($pattern).'%')));
1621 1621
 		}
1622 1622
 
1623 1623
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1656,7 +1656,7 @@  discard block
 block discarded – undo
1656 1656
 		$result = $outerQuery->execute();
1657 1657
 		$calendarObjects = $result->fetchAll();
1658 1658
 
1659
-		return array_map(function ($o) {
1659
+		return array_map(function($o) {
1660 1660
 			$calendarData = Reader::read($o['calendardata']);
1661 1661
 			$comps = $calendarData->getComponents();
1662 1662
 			$objects = [];
@@ -1674,10 +1674,10 @@  discard block
 block discarded – undo
1674 1674
 				'type' => $o['componenttype'],
1675 1675
 				'uid' => $o['uid'],
1676 1676
 				'uri' => $o['uri'],
1677
-				'objects' => array_map(function ($c) {
1677
+				'objects' => array_map(function($c) {
1678 1678
 					return $this->transformSearchData($c);
1679 1679
 				}, $objects),
1680
-				'timezones' => array_map(function ($c) {
1680
+				'timezones' => array_map(function($c) {
1681 1681
 					return $this->transformSearchData($c);
1682 1682
 				}, $timezones),
1683 1683
 			];
@@ -1693,7 +1693,7 @@  discard block
 block discarded – undo
1693 1693
 		/** @var Component[] $subComponents */
1694 1694
 		$subComponents = $comp->getComponents();
1695 1695
 		/** @var Property[] $properties */
1696
-		$properties = array_filter($comp->children(), function ($c) {
1696
+		$properties = array_filter($comp->children(), function($c) {
1697 1697
 			return $c instanceof Property;
1698 1698
 		});
1699 1699
 		$validationRules = $comp->getValidationRules();
@@ -1771,7 +1771,7 @@  discard block
 block discarded – undo
1771 1771
 		$subscriptions = $this->getSubscriptionsForUser($principalUri);
1772 1772
 		foreach ($calendars as $calendar) {
1773 1773
 			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
1774
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
1774
+			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])));
1775 1775
 			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1776 1776
 
1777 1777
 			// If it's shared, limit search to public events
@@ -1783,7 +1783,7 @@  discard block
 block discarded – undo
1783 1783
 		}
1784 1784
 		foreach ($subscriptions as $subscription) {
1785 1785
 			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
1786
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
1786
+			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])));
1787 1787
 			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
1788 1788
 
1789 1789
 			// If it's shared, limit search to public events
@@ -1827,7 +1827,7 @@  discard block
 block discarded – undo
1827 1827
 			if (!$escapePattern) {
1828 1828
 				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
1829 1829
 			} else {
1830
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1830
+				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
1831 1831
 			}
1832 1832
 		}
1833 1833
 
@@ -1841,7 +1841,7 @@  discard block
 block discarded – undo
1841 1841
 		$result = $calendarObjectIdQuery->execute();
1842 1842
 		$matches = $result->fetchAll();
1843 1843
 		$result->closeCursor();
1844
-		$matches = array_map(static function (array $match):int {
1844
+		$matches = array_map(static function(array $match):int {
1845 1845
 			return (int) $match['objectid'];
1846 1846
 		}, $matches);
1847 1847
 
@@ -1854,9 +1854,9 @@  discard block
 block discarded – undo
1854 1854
 		$calendarObjects = $result->fetchAll();
1855 1855
 		$result->closeCursor();
1856 1856
 
1857
-		return array_map(function (array $array): array {
1858
-			$array['calendarid'] = (int)$array['calendarid'];
1859
-			$array['calendartype'] = (int)$array['calendartype'];
1857
+		return array_map(function(array $array): array {
1858
+			$array['calendarid'] = (int) $array['calendarid'];
1859
+			$array['calendartype'] = (int) $array['calendartype'];
1860 1860
 			$array['calendardata'] = $this->readBlob($array['calendardata']);
1861 1861
 
1862 1862
 			return $array;
@@ -1893,7 +1893,7 @@  discard block
 block discarded – undo
1893 1893
 		$stmt = $query->execute();
1894 1894
 
1895 1895
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1896
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1896
+			return $row['calendaruri'].'/'.$row['objecturi'];
1897 1897
 		}
1898 1898
 
1899 1899
 		return null;
@@ -1959,7 +1959,7 @@  discard block
 block discarded – undo
1959 1959
 	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1960 1960
 		// Current synctoken
1961 1961
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1962
-		$stmt->execute([ $calendarId ]);
1962
+		$stmt->execute([$calendarId]);
1963 1963
 		$currentToken = $stmt->fetchColumn(0);
1964 1964
 
1965 1965
 		if (is_null($currentToken)) {
@@ -1976,7 +1976,7 @@  discard block
 block discarded – undo
1976 1976
 		if ($syncToken) {
1977 1977
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1978 1978
 			if ($limit > 0) {
1979
-				$query .= " LIMIT " . (int)$limit;
1979
+				$query .= " LIMIT ".(int) $limit;
1980 1980
 			}
1981 1981
 
1982 1982
 			// Fetching all changes
@@ -2072,8 +2072,8 @@  discard block
 block discarded – undo
2072 2072
 				'source' => $row['source'],
2073 2073
 				'lastmodified' => $row['lastmodified'],
2074 2074
 
2075
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2076
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2075
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2076
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
2077 2077
 			];
2078 2078
 
2079 2079
 			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -2137,7 +2137,7 @@  discard block
 block discarded – undo
2137 2137
 		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
2138 2138
 
2139 2139
 		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2140
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent((int)$subscriptionId, $subscriptionRow));
2140
+		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent((int) $subscriptionId, $subscriptionRow));
2141 2141
 		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2142 2142
 			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2143 2143
 			[
@@ -2168,7 +2168,7 @@  discard block
 block discarded – undo
2168 2168
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2169 2169
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2170 2170
 
2171
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2171
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2172 2172
 			$newValues = [];
2173 2173
 
2174 2174
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
 				->execute();
2191 2191
 
2192 2192
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2193
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2193
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2194 2194
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2195 2195
 				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2196 2196
 				[
@@ -2241,7 +2241,7 @@  discard block
 block discarded – undo
2241 2241
 			->execute();
2242 2242
 
2243 2243
 		if ($subscriptionRow) {
2244
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2244
+			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2245 2245
 		}
2246 2246
 	}
2247 2247
 
@@ -2279,8 +2279,8 @@  discard block
 block discarded – undo
2279 2279
 			'uri' => $row['uri'],
2280 2280
 			'calendardata' => $row['calendardata'],
2281 2281
 			'lastmodified' => $row['lastmodified'],
2282
-			'etag' => '"' . $row['etag'] . '"',
2283
-			'size' => (int)$row['size'],
2282
+			'etag' => '"'.$row['etag'].'"',
2283
+			'size' => (int) $row['size'],
2284 2284
 		];
2285 2285
 	}
2286 2286
 
@@ -2308,8 +2308,8 @@  discard block
 block discarded – undo
2308 2308
 				'calendardata' => $row['calendardata'],
2309 2309
 				'uri' => $row['uri'],
2310 2310
 				'lastmodified' => $row['lastmodified'],
2311
-				'etag' => '"' . $row['etag'] . '"',
2312
-				'size' => (int)$row['size'],
2311
+				'etag' => '"'.$row['etag'].'"',
2312
+				'size' => (int) $row['size'],
2313 2313
 			];
2314 2314
 		}
2315 2315
 
@@ -2363,14 +2363,14 @@  discard block
 block discarded – undo
2363 2363
 	 * @return void
2364 2364
 	 */
2365 2365
 	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2366
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2366
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2367 2367
 
2368 2368
 		$query = $this->db->getQueryBuilder();
2369 2369
 		$query->select('synctoken')
2370 2370
 			->from($table)
2371 2371
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2372 2372
 		$result = $query->execute();
2373
-		$syncToken = (int)$result->fetchColumn();
2373
+		$syncToken = (int) $result->fetchColumn();
2374 2374
 		$result->closeCursor();
2375 2375
 
2376 2376
 		$query = $this->db->getQueryBuilder();
@@ -2427,7 +2427,7 @@  discard block
 block discarded – undo
2427 2427
 				// Track first component type and uid
2428 2428
 				if ($uid === null) {
2429 2429
 					$componentType = $component->name;
2430
-					$uid = (string)$component->UID;
2430
+					$uid = (string) $component->UID;
2431 2431
 				}
2432 2432
 			}
2433 2433
 		}
@@ -2526,7 +2526,7 @@  discard block
 block discarded – undo
2526 2526
 			]));
2527 2527
 		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2528 2528
 
2529
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2529
+		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int) $calendarId, $calendarRow, $oldShares, $add, $remove));
2530 2530
 	}
2531 2531
 
2532 2532
 	/**
@@ -2567,7 +2567,7 @@  discard block
 block discarded – undo
2567 2567
 				]);
2568 2568
 			$query->execute();
2569 2569
 
2570
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2570
+			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int) $calendarId, $calendarData, $publicUri));
2571 2571
 			return $publicUri;
2572 2572
 		}
2573 2573
 		$query->delete('dav_shares')
@@ -2575,7 +2575,7 @@  discard block
 block discarded – undo
2575 2575
 			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2576 2576
 		$query->execute();
2577 2577
 
2578
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2578
+		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int) $calendarId, $calendarData));
2579 2579
 		return null;
2580 2580
 	}
2581 2581
 
@@ -2796,10 +2796,10 @@  discard block
 block discarded – undo
2796 2796
 		$result->closeCursor();
2797 2797
 
2798 2798
 		if (!isset($objectIds['id'])) {
2799
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2799
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2800 2800
 		}
2801 2801
 
2802
-		return (int)$objectIds['id'];
2802
+		return (int) $objectIds['id'];
2803 2803
 	}
2804 2804
 
2805 2805
 	/**
@@ -2826,8 +2826,8 @@  discard block
 block discarded – undo
2826 2826
 	 * @param $calendarInfo
2827 2827
 	 */
2828 2828
 	private function addOwnerPrincipal(&$calendarInfo) {
2829
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2830
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2829
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2830
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2831 2831
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2832 2832
 			$uri = $calendarInfo[$ownerPrincipalKey];
2833 2833
 		} else {
Please login to merge, or discard this patch.