Passed
Push — master ( 21b7e5...813bdc )
by Christoph
12:53 queued 10s
created
apps/dav/lib/Connector/Sabre/FilesPlugin.php 2 patches
Indentation   +466 added lines, -466 removed lines patch added patch discarded remove patch
@@ -53,470 +53,470 @@
 block discarded – undo
53 53
 
54 54
 class FilesPlugin extends ServerPlugin {
55 55
 
56
-	// namespace
57
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
58
-	const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
59
-	const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
60
-	const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
61
-	const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
62
-	const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
63
-	const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
64
-	const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
65
-	const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
66
-	const GETETAG_PROPERTYNAME = '{DAV:}getetag';
67
-	const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
68
-	const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
69
-	const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
70
-	const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
71
-	const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
72
-	const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
73
-	const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
74
-	const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
75
-	const METADATA_ETAG_PROPERTYNAME = '{http://nextcloud.org/ns}metadata_etag';
76
-	const UPLOAD_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}upload_time';
77
-	const CREATION_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}creation_time';
78
-	const SHARE_NOTE = '{http://nextcloud.org/ns}note';
79
-
80
-	/**
81
-	 * Reference to main server object
82
-	 *
83
-	 * @var \Sabre\DAV\Server
84
-	 */
85
-	private $server;
86
-
87
-	/**
88
-	 * @var Tree
89
-	 */
90
-	private $tree;
91
-
92
-	/**
93
-	 * Whether this is public webdav.
94
-	 * If true, some returned information will be stripped off.
95
-	 *
96
-	 * @var bool
97
-	 */
98
-	private $isPublic;
99
-
100
-	/**
101
-	 * @var bool
102
-	 */
103
-	private $downloadAttachment;
104
-
105
-	/**
106
-	 * @var IConfig
107
-	 */
108
-	private $config;
109
-
110
-	/**
111
-	 * @var IRequest
112
-	 */
113
-	private $request;
114
-
115
-	/**
116
-	 * @var IPreview
117
-	 */
118
-	private $previewManager;
119
-
120
-	/**
121
-	 * @param Tree $tree
122
-	 * @param IConfig $config
123
-	 * @param IRequest $request
124
-	 * @param IPreview $previewManager
125
-	 * @param bool $isPublic
126
-	 * @param bool $downloadAttachment
127
-	 */
128
-	public function __construct(Tree $tree,
129
-								IConfig $config,
130
-								IRequest $request,
131
-								IPreview $previewManager,
132
-								$isPublic = false,
133
-								$downloadAttachment = true) {
134
-		$this->tree = $tree;
135
-		$this->config = $config;
136
-		$this->request = $request;
137
-		$this->isPublic = $isPublic;
138
-		$this->downloadAttachment = $downloadAttachment;
139
-		$this->previewManager = $previewManager;
140
-	}
141
-
142
-	/**
143
-	 * This initializes the plugin.
144
-	 *
145
-	 * This function is called by \Sabre\DAV\Server, after
146
-	 * addPlugin is called.
147
-	 *
148
-	 * This method should set up the required event subscriptions.
149
-	 *
150
-	 * @param \Sabre\DAV\Server $server
151
-	 * @return void
152
-	 */
153
-	public function initialize(\Sabre\DAV\Server $server) {
154
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
155
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
156
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
162
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
163
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
164
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
165
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
166
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
167
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
168
-		$server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
169
-		$server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
170
-		$server->protectedProperties[] = self::SHARE_NOTE;
171
-
172
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
173
-		$allowedProperties = ['{DAV:}getetag'];
174
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
175
-
176
-		$this->server = $server;
177
-		$this->server->on('propFind', [$this, 'handleGetProperties']);
178
-		$this->server->on('propPatch', [$this, 'handleUpdateProperties']);
179
-		$this->server->on('afterBind', [$this, 'sendFileIdHeader']);
180
-		$this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
181
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
182
-		$this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
183
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
184
-			$body = $response->getBody();
185
-			if (is_resource($body)) {
186
-				fclose($body);
187
-			}
188
-		});
189
-		$this->server->on('beforeMove', [$this, 'checkMove']);
190
-	}
191
-
192
-	/**
193
-	 * Plugin that checks if a move can actually be performed.
194
-	 *
195
-	 * @param string $source source path
196
-	 * @param string $destination destination path
197
-	 * @throws Forbidden
198
-	 * @throws NotFound
199
-	 */
200
-	function checkMove($source, $destination) {
201
-		$sourceNode = $this->tree->getNodeForPath($source);
202
-		if (!$sourceNode instanceof Node) {
203
-			return;
204
-		}
205
-		list($sourceDir,) = \Sabre\Uri\split($source);
206
-		list($destinationDir,) = \Sabre\Uri\split($destination);
207
-
208
-		if ($sourceDir !== $destinationDir) {
209
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
210
-			if ($sourceNodeFileInfo === null) {
211
-				throw new NotFound($source . ' does not exist');
212
-			}
213
-
214
-			if (!$sourceNodeFileInfo->isDeletable()) {
215
-				throw new Forbidden($source . " cannot be deleted");
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * This sets a cookie to be able to recognize the start of the download
222
-	 * the content must not be longer than 32 characters and must only contain
223
-	 * alphanumeric characters
224
-	 *
225
-	 * @param RequestInterface $request
226
-	 * @param ResponseInterface $response
227
-	 */
228
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
229
-		$queryParams = $request->getQueryParameters();
230
-
231
-		/**
232
-		 * this sets a cookie to be able to recognize the start of the download
233
-		 * the content must not be longer than 32 characters and must only contain
234
-		 * alphanumeric characters
235
-		 */
236
-		if (isset($queryParams['downloadStartSecret'])) {
237
-			$token = $queryParams['downloadStartSecret'];
238
-			if (!isset($token[32])
239
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
240
-				// FIXME: use $response->setHeader() instead
241
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
242
-			}
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Add headers to file download
248
-	 *
249
-	 * @param RequestInterface $request
250
-	 * @param ResponseInterface $response
251
-	 */
252
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
253
-		// Only handle valid files
254
-		$node = $this->tree->getNodeForPath($request->getPath());
255
-		if (!($node instanceof IFile)) return;
256
-
257
-		// adds a 'Content-Disposition: attachment' header in case no disposition
258
-		// header has been set before
259
-		if ($this->downloadAttachment &&
260
-			$response->getHeader('Content-Disposition') === null) {
261
-			$filename = $node->getName();
262
-			if ($this->request->isUserAgent(
263
-				[
264
-					Request::USER_AGENT_IE,
265
-					Request::USER_AGENT_ANDROID_MOBILE_CHROME,
266
-					Request::USER_AGENT_FREEBOX,
267
-				])) {
268
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
269
-			} else {
270
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
271
-													 . '; filename="' . rawurlencode($filename) . '"');
272
-			}
273
-		}
274
-
275
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
276
-			//Add OC-Checksum header
277
-			/** @var $node File */
278
-			$checksum = $node->getChecksum();
279
-			if ($checksum !== null && $checksum !== '') {
280
-				$response->addHeader('OC-Checksum', $checksum);
281
-			}
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * Adds all ownCloud-specific properties
287
-	 *
288
-	 * @param PropFind $propFind
289
-	 * @param \Sabre\DAV\INode $node
290
-	 * @return void
291
-	 */
292
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
293
-
294
-		$httpRequest = $this->server->httpRequest;
295
-
296
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
297
-			/**
298
-			 * This was disabled, because it made dir listing throw an exception,
299
-			 * so users were unable to navigate into folders where one subitem
300
-			 * is blocked by the files_accesscontrol app, see:
301
-			 * https://github.com/nextcloud/files_accesscontrol/issues/65
302
-			 * if (!$node->getFileInfo()->isReadable()) {
303
-			 *     // avoid detecting files through this means
304
-			 *     throw new NotFound();
305
-			 * }
306
-			 */
307
-
308
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
309
-				return $node->getFileId();
310
-			});
311
-
312
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
313
-				return $node->getInternalFileId();
314
-			});
315
-
316
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
317
-				$perms = $node->getDavPermissions();
318
-				if ($this->isPublic) {
319
-					// remove mount information
320
-					$perms = str_replace(['S', 'M'], '', $perms);
321
-				}
322
-				return $perms;
323
-			});
324
-
325
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
326
-				return $node->getSharePermissions(
327
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
328
-				);
329
-			});
330
-
331
-			$propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
332
-				$ncPermissions = $node->getSharePermissions(
333
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
334
-				);
335
-				$ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
336
-				return json_encode($ocmPermissions);
337
-			});
338
-
339
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
340
-				return $node->getETag();
341
-			});
342
-
343
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
344
-				$owner = $node->getOwner();
345
-				if (!$owner) {
346
-					return null;
347
-				} else {
348
-					return $owner->getUID();
349
-				}
350
-			});
351
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
352
-				$owner = $node->getOwner();
353
-				if (!$owner) {
354
-					return null;
355
-				} else {
356
-					return $owner->getDisplayName();
357
-				}
358
-			});
359
-
360
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
361
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
362
-			});
363
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
364
-				return $node->getSize();
365
-			});
366
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
367
-				return $node->getFileInfo()->getMountPoint()->getMountType();
368
-			});
369
-
370
-			$propFind->handle(self::SHARE_NOTE, function() use ($node, $httpRequest) {
371
-				return $node->getNoteFromShare(
372
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
373
-				);
374
-			});
375
-		}
376
-
377
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
378
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
379
-				return $this->config->getSystemValue('data-fingerprint', '');
380
-			});
381
-		}
382
-
383
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
384
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
385
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
386
-				try {
387
-					$directDownloadUrl = $node->getDirectDownload();
388
-					if (isset($directDownloadUrl['url'])) {
389
-						return $directDownloadUrl['url'];
390
-					}
391
-				} catch (StorageNotAvailableException $e) {
392
-					return false;
393
-				} catch (ForbiddenException $e) {
394
-					return false;
395
-				}
396
-				return false;
397
-			});
398
-
399
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
400
-				$checksum = $node->getChecksum();
401
-				if ($checksum === null || $checksum === '') {
402
-					return null;
403
-				}
404
-
405
-				return new ChecksumList($checksum);
406
-			});
407
-
408
-			$propFind->handle(self::CREATION_TIME_PROPERTYNAME, function() use ($node) {
409
-				return $node->getFileInfo()->getCreationTime();
410
-			});
411
-
412
-			$propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function() use ($node) {
413
-				return $node->getFileInfo()->getUploadTime();
414
-			});
415
-
416
-		}
417
-
418
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
419
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
420
-				return $node->getSize();
421
-			});
422
-
423
-			$propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function() use ($node) {
424
-				return $node->getFileInfo()->isEncrypted() ? '1' : '0';
425
-			});
426
-		}
427
-	}
428
-
429
-	/**
430
-	 * translate Nextcloud permissions to OCM Permissions
431
-	 *
432
-	 * @param $ncPermissions
433
-	 * @return array
434
-	 */
435
-	protected function ncPermissions2ocmPermissions($ncPermissions) {
436
-
437
-		$ocmPermissions = [];
438
-
439
-		if ($ncPermissions & Constants::PERMISSION_SHARE) {
440
-			$ocmPermissions[] = 'share';
441
-		}
442
-
443
-		if ($ncPermissions & Constants::PERMISSION_READ) {
444
-			$ocmPermissions[] = 'read';
445
-		}
446
-
447
-		if (($ncPermissions & Constants::PERMISSION_CREATE) ||
448
-			($ncPermissions & Constants::PERMISSION_UPDATE)) {
449
-			$ocmPermissions[] = 'write';
450
-		}
451
-
452
-		return $ocmPermissions;
453
-
454
-	}
455
-
456
-	/**
457
-	 * Update ownCloud-specific properties
458
-	 *
459
-	 * @param string $path
460
-	 * @param PropPatch $propPatch
461
-	 *
462
-	 * @return void
463
-	 */
464
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
465
-		$node = $this->tree->getNodeForPath($path);
466
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
467
-			return;
468
-		}
469
-
470
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
471
-			if (empty($time)) {
472
-				return false;
473
-			}
474
-			$node->touch($time);
475
-			return true;
476
-		});
477
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
478
-			if (empty($etag)) {
479
-				return false;
480
-			}
481
-			if ($node->setEtag($etag) !== -1) {
482
-				return true;
483
-			}
484
-			return false;
485
-		});
486
-		$propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function($time) use ($node) {
487
-			if (empty($time)) {
488
-				return false;
489
-			}
490
-			$node->setCreationTime((int) $time);
491
-			return true;
492
-		});
493
-	}
494
-
495
-	/**
496
-	 * @param string $filePath
497
-	 * @param \Sabre\DAV\INode $node
498
-	 * @throws \Sabre\DAV\Exception\BadRequest
499
-	 */
500
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
501
-		// chunked upload handling
502
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
503
-			list($path, $name) = \Sabre\Uri\split($filePath);
504
-			$info = \OC_FileChunking::decodeName($name);
505
-			if (!empty($info)) {
506
-				$filePath = $path . '/' . $info['name'];
507
-			}
508
-		}
509
-
510
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
511
-		if (!$this->server->tree->nodeExists($filePath)) {
512
-			return;
513
-		}
514
-		$node = $this->server->tree->getNodeForPath($filePath);
515
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
516
-			$fileId = $node->getFileId();
517
-			if (!is_null($fileId)) {
518
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
519
-			}
520
-		}
521
-	}
56
+    // namespace
57
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
58
+    const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
59
+    const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
60
+    const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
61
+    const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
62
+    const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
63
+    const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
64
+    const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
65
+    const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
66
+    const GETETAG_PROPERTYNAME = '{DAV:}getetag';
67
+    const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
68
+    const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
69
+    const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
70
+    const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
71
+    const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
72
+    const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
73
+    const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
74
+    const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
75
+    const METADATA_ETAG_PROPERTYNAME = '{http://nextcloud.org/ns}metadata_etag';
76
+    const UPLOAD_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}upload_time';
77
+    const CREATION_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}creation_time';
78
+    const SHARE_NOTE = '{http://nextcloud.org/ns}note';
79
+
80
+    /**
81
+     * Reference to main server object
82
+     *
83
+     * @var \Sabre\DAV\Server
84
+     */
85
+    private $server;
86
+
87
+    /**
88
+     * @var Tree
89
+     */
90
+    private $tree;
91
+
92
+    /**
93
+     * Whether this is public webdav.
94
+     * If true, some returned information will be stripped off.
95
+     *
96
+     * @var bool
97
+     */
98
+    private $isPublic;
99
+
100
+    /**
101
+     * @var bool
102
+     */
103
+    private $downloadAttachment;
104
+
105
+    /**
106
+     * @var IConfig
107
+     */
108
+    private $config;
109
+
110
+    /**
111
+     * @var IRequest
112
+     */
113
+    private $request;
114
+
115
+    /**
116
+     * @var IPreview
117
+     */
118
+    private $previewManager;
119
+
120
+    /**
121
+     * @param Tree $tree
122
+     * @param IConfig $config
123
+     * @param IRequest $request
124
+     * @param IPreview $previewManager
125
+     * @param bool $isPublic
126
+     * @param bool $downloadAttachment
127
+     */
128
+    public function __construct(Tree $tree,
129
+                                IConfig $config,
130
+                                IRequest $request,
131
+                                IPreview $previewManager,
132
+                                $isPublic = false,
133
+                                $downloadAttachment = true) {
134
+        $this->tree = $tree;
135
+        $this->config = $config;
136
+        $this->request = $request;
137
+        $this->isPublic = $isPublic;
138
+        $this->downloadAttachment = $downloadAttachment;
139
+        $this->previewManager = $previewManager;
140
+    }
141
+
142
+    /**
143
+     * This initializes the plugin.
144
+     *
145
+     * This function is called by \Sabre\DAV\Server, after
146
+     * addPlugin is called.
147
+     *
148
+     * This method should set up the required event subscriptions.
149
+     *
150
+     * @param \Sabre\DAV\Server $server
151
+     * @return void
152
+     */
153
+    public function initialize(\Sabre\DAV\Server $server) {
154
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
155
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
156
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
162
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
163
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
164
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
165
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
166
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
167
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
168
+        $server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
169
+        $server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
170
+        $server->protectedProperties[] = self::SHARE_NOTE;
171
+
172
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
173
+        $allowedProperties = ['{DAV:}getetag'];
174
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
175
+
176
+        $this->server = $server;
177
+        $this->server->on('propFind', [$this, 'handleGetProperties']);
178
+        $this->server->on('propPatch', [$this, 'handleUpdateProperties']);
179
+        $this->server->on('afterBind', [$this, 'sendFileIdHeader']);
180
+        $this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
181
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
182
+        $this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
183
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
184
+            $body = $response->getBody();
185
+            if (is_resource($body)) {
186
+                fclose($body);
187
+            }
188
+        });
189
+        $this->server->on('beforeMove', [$this, 'checkMove']);
190
+    }
191
+
192
+    /**
193
+     * Plugin that checks if a move can actually be performed.
194
+     *
195
+     * @param string $source source path
196
+     * @param string $destination destination path
197
+     * @throws Forbidden
198
+     * @throws NotFound
199
+     */
200
+    function checkMove($source, $destination) {
201
+        $sourceNode = $this->tree->getNodeForPath($source);
202
+        if (!$sourceNode instanceof Node) {
203
+            return;
204
+        }
205
+        list($sourceDir,) = \Sabre\Uri\split($source);
206
+        list($destinationDir,) = \Sabre\Uri\split($destination);
207
+
208
+        if ($sourceDir !== $destinationDir) {
209
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
210
+            if ($sourceNodeFileInfo === null) {
211
+                throw new NotFound($source . ' does not exist');
212
+            }
213
+
214
+            if (!$sourceNodeFileInfo->isDeletable()) {
215
+                throw new Forbidden($source . " cannot be deleted");
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * This sets a cookie to be able to recognize the start of the download
222
+     * the content must not be longer than 32 characters and must only contain
223
+     * alphanumeric characters
224
+     *
225
+     * @param RequestInterface $request
226
+     * @param ResponseInterface $response
227
+     */
228
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
229
+        $queryParams = $request->getQueryParameters();
230
+
231
+        /**
232
+         * this sets a cookie to be able to recognize the start of the download
233
+         * the content must not be longer than 32 characters and must only contain
234
+         * alphanumeric characters
235
+         */
236
+        if (isset($queryParams['downloadStartSecret'])) {
237
+            $token = $queryParams['downloadStartSecret'];
238
+            if (!isset($token[32])
239
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
240
+                // FIXME: use $response->setHeader() instead
241
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
242
+            }
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Add headers to file download
248
+     *
249
+     * @param RequestInterface $request
250
+     * @param ResponseInterface $response
251
+     */
252
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
253
+        // Only handle valid files
254
+        $node = $this->tree->getNodeForPath($request->getPath());
255
+        if (!($node instanceof IFile)) return;
256
+
257
+        // adds a 'Content-Disposition: attachment' header in case no disposition
258
+        // header has been set before
259
+        if ($this->downloadAttachment &&
260
+            $response->getHeader('Content-Disposition') === null) {
261
+            $filename = $node->getName();
262
+            if ($this->request->isUserAgent(
263
+                [
264
+                    Request::USER_AGENT_IE,
265
+                    Request::USER_AGENT_ANDROID_MOBILE_CHROME,
266
+                    Request::USER_AGENT_FREEBOX,
267
+                ])) {
268
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
269
+            } else {
270
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
271
+                                                        . '; filename="' . rawurlencode($filename) . '"');
272
+            }
273
+        }
274
+
275
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
276
+            //Add OC-Checksum header
277
+            /** @var $node File */
278
+            $checksum = $node->getChecksum();
279
+            if ($checksum !== null && $checksum !== '') {
280
+                $response->addHeader('OC-Checksum', $checksum);
281
+            }
282
+        }
283
+    }
284
+
285
+    /**
286
+     * Adds all ownCloud-specific properties
287
+     *
288
+     * @param PropFind $propFind
289
+     * @param \Sabre\DAV\INode $node
290
+     * @return void
291
+     */
292
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
293
+
294
+        $httpRequest = $this->server->httpRequest;
295
+
296
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
297
+            /**
298
+             * This was disabled, because it made dir listing throw an exception,
299
+             * so users were unable to navigate into folders where one subitem
300
+             * is blocked by the files_accesscontrol app, see:
301
+             * https://github.com/nextcloud/files_accesscontrol/issues/65
302
+             * if (!$node->getFileInfo()->isReadable()) {
303
+             *     // avoid detecting files through this means
304
+             *     throw new NotFound();
305
+             * }
306
+             */
307
+
308
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
309
+                return $node->getFileId();
310
+            });
311
+
312
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
313
+                return $node->getInternalFileId();
314
+            });
315
+
316
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
317
+                $perms = $node->getDavPermissions();
318
+                if ($this->isPublic) {
319
+                    // remove mount information
320
+                    $perms = str_replace(['S', 'M'], '', $perms);
321
+                }
322
+                return $perms;
323
+            });
324
+
325
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
326
+                return $node->getSharePermissions(
327
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
328
+                );
329
+            });
330
+
331
+            $propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
332
+                $ncPermissions = $node->getSharePermissions(
333
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
334
+                );
335
+                $ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
336
+                return json_encode($ocmPermissions);
337
+            });
338
+
339
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
340
+                return $node->getETag();
341
+            });
342
+
343
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
344
+                $owner = $node->getOwner();
345
+                if (!$owner) {
346
+                    return null;
347
+                } else {
348
+                    return $owner->getUID();
349
+                }
350
+            });
351
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
352
+                $owner = $node->getOwner();
353
+                if (!$owner) {
354
+                    return null;
355
+                } else {
356
+                    return $owner->getDisplayName();
357
+                }
358
+            });
359
+
360
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
361
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
362
+            });
363
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
364
+                return $node->getSize();
365
+            });
366
+            $propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
367
+                return $node->getFileInfo()->getMountPoint()->getMountType();
368
+            });
369
+
370
+            $propFind->handle(self::SHARE_NOTE, function() use ($node, $httpRequest) {
371
+                return $node->getNoteFromShare(
372
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
373
+                );
374
+            });
375
+        }
376
+
377
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
378
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
379
+                return $this->config->getSystemValue('data-fingerprint', '');
380
+            });
381
+        }
382
+
383
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
384
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
385
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
386
+                try {
387
+                    $directDownloadUrl = $node->getDirectDownload();
388
+                    if (isset($directDownloadUrl['url'])) {
389
+                        return $directDownloadUrl['url'];
390
+                    }
391
+                } catch (StorageNotAvailableException $e) {
392
+                    return false;
393
+                } catch (ForbiddenException $e) {
394
+                    return false;
395
+                }
396
+                return false;
397
+            });
398
+
399
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
400
+                $checksum = $node->getChecksum();
401
+                if ($checksum === null || $checksum === '') {
402
+                    return null;
403
+                }
404
+
405
+                return new ChecksumList($checksum);
406
+            });
407
+
408
+            $propFind->handle(self::CREATION_TIME_PROPERTYNAME, function() use ($node) {
409
+                return $node->getFileInfo()->getCreationTime();
410
+            });
411
+
412
+            $propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function() use ($node) {
413
+                return $node->getFileInfo()->getUploadTime();
414
+            });
415
+
416
+        }
417
+
418
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
419
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
420
+                return $node->getSize();
421
+            });
422
+
423
+            $propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function() use ($node) {
424
+                return $node->getFileInfo()->isEncrypted() ? '1' : '0';
425
+            });
426
+        }
427
+    }
428
+
429
+    /**
430
+     * translate Nextcloud permissions to OCM Permissions
431
+     *
432
+     * @param $ncPermissions
433
+     * @return array
434
+     */
435
+    protected function ncPermissions2ocmPermissions($ncPermissions) {
436
+
437
+        $ocmPermissions = [];
438
+
439
+        if ($ncPermissions & Constants::PERMISSION_SHARE) {
440
+            $ocmPermissions[] = 'share';
441
+        }
442
+
443
+        if ($ncPermissions & Constants::PERMISSION_READ) {
444
+            $ocmPermissions[] = 'read';
445
+        }
446
+
447
+        if (($ncPermissions & Constants::PERMISSION_CREATE) ||
448
+            ($ncPermissions & Constants::PERMISSION_UPDATE)) {
449
+            $ocmPermissions[] = 'write';
450
+        }
451
+
452
+        return $ocmPermissions;
453
+
454
+    }
455
+
456
+    /**
457
+     * Update ownCloud-specific properties
458
+     *
459
+     * @param string $path
460
+     * @param PropPatch $propPatch
461
+     *
462
+     * @return void
463
+     */
464
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
465
+        $node = $this->tree->getNodeForPath($path);
466
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
467
+            return;
468
+        }
469
+
470
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
471
+            if (empty($time)) {
472
+                return false;
473
+            }
474
+            $node->touch($time);
475
+            return true;
476
+        });
477
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
478
+            if (empty($etag)) {
479
+                return false;
480
+            }
481
+            if ($node->setEtag($etag) !== -1) {
482
+                return true;
483
+            }
484
+            return false;
485
+        });
486
+        $propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function($time) use ($node) {
487
+            if (empty($time)) {
488
+                return false;
489
+            }
490
+            $node->setCreationTime((int) $time);
491
+            return true;
492
+        });
493
+    }
494
+
495
+    /**
496
+     * @param string $filePath
497
+     * @param \Sabre\DAV\INode $node
498
+     * @throws \Sabre\DAV\Exception\BadRequest
499
+     */
500
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
501
+        // chunked upload handling
502
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
503
+            list($path, $name) = \Sabre\Uri\split($filePath);
504
+            $info = \OC_FileChunking::decodeName($name);
505
+            if (!empty($info)) {
506
+                $filePath = $path . '/' . $info['name'];
507
+            }
508
+        }
509
+
510
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
511
+        if (!$this->server->tree->nodeExists($filePath)) {
512
+            return;
513
+        }
514
+        $node = $this->server->tree->getNodeForPath($filePath);
515
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
516
+            $fileId = $node->getFileId();
517
+            if (!is_null($fileId)) {
518
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
519
+            }
520
+        }
521
+    }
522 522
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		$this->server->on('propPatch', [$this, 'handleUpdateProperties']);
179 179
 		$this->server->on('afterBind', [$this, 'sendFileIdHeader']);
180 180
 		$this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
181
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
181
+		$this->server->on('afterMethod:GET', [$this, 'httpGet']);
182 182
 		$this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
183 183
 		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
184 184
 			$body = $response->getBody();
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 		if ($sourceDir !== $destinationDir) {
209 209
 			$sourceNodeFileInfo = $sourceNode->getFileInfo();
210 210
 			if ($sourceNodeFileInfo === null) {
211
-				throw new NotFound($source . ' does not exist');
211
+				throw new NotFound($source.' does not exist');
212 212
 			}
213 213
 
214 214
 			if (!$sourceNodeFileInfo->isDeletable()) {
215
-				throw new Forbidden($source . " cannot be deleted");
215
+				throw new Forbidden($source." cannot be deleted");
216 216
 			}
217 217
 		}
218 218
 	}
@@ -265,10 +265,10 @@  discard block
 block discarded – undo
265 265
 					Request::USER_AGENT_ANDROID_MOBILE_CHROME,
266 266
 					Request::USER_AGENT_FREEBOX,
267 267
 				])) {
268
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
268
+				$response->addHeader('Content-Disposition', 'attachment; filename="'.rawurlencode($filename).'"');
269 269
 			} else {
270
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
271
-													 . '; filename="' . rawurlencode($filename) . '"');
270
+				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($filename)
271
+													 . '; filename="'.rawurlencode($filename).'"');
272 272
 			}
273 273
 		}
274 274
 
@@ -357,13 +357,13 @@  discard block
 block discarded – undo
357 357
 				}
358 358
 			});
359 359
 
360
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
360
+			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function() use ($node) {
361 361
 				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
362 362
 			});
363 363
 			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
364 364
 				return $node->getSize();
365 365
 			});
366
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
366
+			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function() use ($node) {
367 367
 				return $node->getFileInfo()->getMountPoint()->getMountType();
368 368
 			});
369 369
 
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 			list($path, $name) = \Sabre\Uri\split($filePath);
504 504
 			$info = \OC_FileChunking::decodeName($name);
505 505
 			if (!empty($info)) {
506
-				$filePath = $path . '/' . $info['name'];
506
+				$filePath = $path.'/'.$info['name'];
507 507
 			}
508 508
 		}
509 509
 
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -47,114 +47,114 @@
 block discarded – undo
47 47
  * @package OCA\DAV\Connector\Sabre
48 48
  */
49 49
 class FakeLockerPlugin extends ServerPlugin {
50
-	/** @var \Sabre\DAV\Server */
51
-	private $server;
50
+    /** @var \Sabre\DAV\Server */
51
+    private $server;
52 52
 
53
-	/** {@inheritDoc} */
54
-	public function initialize(\Sabre\DAV\Server $server) {
55
-		$this->server = $server;
56
-		$this->server->on('method:LOCK', [$this, 'fakeLockProvider'], 1);
57
-		$this->server->on('method:UNLOCK', [$this, 'fakeUnlockProvider'], 1);
58
-		$server->on('propFind', [$this, 'propFind']);
59
-		$server->on('validateTokens', [$this, 'validateTokens']);
60
-	}
53
+    /** {@inheritDoc} */
54
+    public function initialize(\Sabre\DAV\Server $server) {
55
+        $this->server = $server;
56
+        $this->server->on('method:LOCK', [$this, 'fakeLockProvider'], 1);
57
+        $this->server->on('method:UNLOCK', [$this, 'fakeUnlockProvider'], 1);
58
+        $server->on('propFind', [$this, 'propFind']);
59
+        $server->on('validateTokens', [$this, 'validateTokens']);
60
+    }
61 61
 
62
-	/**
63
-	 * Indicate that we support LOCK and UNLOCK
64
-	 *
65
-	 * @param string $path
66
-	 * @return string[]
67
-	 */
68
-	public function getHTTPMethods($path) {
69
-		return [
70
-			'LOCK',
71
-			'UNLOCK',
72
-		];
73
-	}
62
+    /**
63
+     * Indicate that we support LOCK and UNLOCK
64
+     *
65
+     * @param string $path
66
+     * @return string[]
67
+     */
68
+    public function getHTTPMethods($path) {
69
+        return [
70
+            'LOCK',
71
+            'UNLOCK',
72
+        ];
73
+    }
74 74
 
75
-	/**
76
-	 * Indicate that we support locking
77
-	 *
78
-	 * @return integer[]
79
-	 */
80
-	function getFeatures() {
81
-		return [2];
82
-	}
75
+    /**
76
+     * Indicate that we support locking
77
+     *
78
+     * @return integer[]
79
+     */
80
+    function getFeatures() {
81
+        return [2];
82
+    }
83 83
 
84
-	/**
85
-	 * Return some dummy response for PROPFIND requests with regard to locking
86
-	 *
87
-	 * @param PropFind $propFind
88
-	 * @param INode $node
89
-	 * @return void
90
-	 */
91
-	function propFind(PropFind $propFind, INode $node) {
92
-		$propFind->handle('{DAV:}supportedlock', function() {
93
-			return new SupportedLock(true);
94
-		});
95
-		$propFind->handle('{DAV:}lockdiscovery', function() use ($propFind) {
96
-			return new LockDiscovery([]);
97
-		});
98
-	}
84
+    /**
85
+     * Return some dummy response for PROPFIND requests with regard to locking
86
+     *
87
+     * @param PropFind $propFind
88
+     * @param INode $node
89
+     * @return void
90
+     */
91
+    function propFind(PropFind $propFind, INode $node) {
92
+        $propFind->handle('{DAV:}supportedlock', function() {
93
+            return new SupportedLock(true);
94
+        });
95
+        $propFind->handle('{DAV:}lockdiscovery', function() use ($propFind) {
96
+            return new LockDiscovery([]);
97
+        });
98
+    }
99 99
 
100
-	/**
101
-	 * Mark a locking token always as valid
102
-	 *
103
-	 * @param RequestInterface $request
104
-	 * @param array $conditions
105
-	 */
106
-	public function validateTokens(RequestInterface $request, &$conditions) {
107
-		foreach($conditions as &$fileCondition) {
108
-			if(isset($fileCondition['tokens'])) {
109
-				foreach($fileCondition['tokens'] as &$token) {
110
-					if(isset($token['token'])) {
111
-						if(substr($token['token'], 0, 16) === 'opaquelocktoken:') {
112
-							$token['validToken'] = true;
113
-						}
114
-					}
115
-				}
116
-			}
117
-		}
118
-	}
100
+    /**
101
+     * Mark a locking token always as valid
102
+     *
103
+     * @param RequestInterface $request
104
+     * @param array $conditions
105
+     */
106
+    public function validateTokens(RequestInterface $request, &$conditions) {
107
+        foreach($conditions as &$fileCondition) {
108
+            if(isset($fileCondition['tokens'])) {
109
+                foreach($fileCondition['tokens'] as &$token) {
110
+                    if(isset($token['token'])) {
111
+                        if(substr($token['token'], 0, 16) === 'opaquelocktoken:') {
112
+                            $token['validToken'] = true;
113
+                        }
114
+                    }
115
+                }
116
+            }
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Fakes a successful LOCK
122
-	 *
123
-	 * @param RequestInterface $request
124
-	 * @param ResponseInterface $response
125
-	 * @return bool
126
-	 */
127
-	public function fakeLockProvider(RequestInterface $request,
128
-									 ResponseInterface $response) {
120
+    /**
121
+     * Fakes a successful LOCK
122
+     *
123
+     * @param RequestInterface $request
124
+     * @param ResponseInterface $response
125
+     * @return bool
126
+     */
127
+    public function fakeLockProvider(RequestInterface $request,
128
+                                        ResponseInterface $response) {
129 129
 
130
-		$lockInfo = new LockInfo();
131
-		$lockInfo->token = md5($request->getPath());
132
-		$lockInfo->uri = $request->getPath();
133
-		$lockInfo->depth = \Sabre\DAV\Server::DEPTH_INFINITY;
134
-		$lockInfo->timeout = 1800;
130
+        $lockInfo = new LockInfo();
131
+        $lockInfo->token = md5($request->getPath());
132
+        $lockInfo->uri = $request->getPath();
133
+        $lockInfo->depth = \Sabre\DAV\Server::DEPTH_INFINITY;
134
+        $lockInfo->timeout = 1800;
135 135
 
136
-		$body = $this->server->xml->write('{DAV:}prop', [
137
-			'{DAV:}lockdiscovery' =>
138
-					new LockDiscovery([$lockInfo])
139
-		]);
136
+        $body = $this->server->xml->write('{DAV:}prop', [
137
+            '{DAV:}lockdiscovery' =>
138
+                    new LockDiscovery([$lockInfo])
139
+        ]);
140 140
 
141
-		$response->setStatus(200);
142
-		$response->setBody($body);
141
+        $response->setStatus(200);
142
+        $response->setBody($body);
143 143
 
144
-		return false;
145
-	}
144
+        return false;
145
+    }
146 146
 
147
-	/**
148
-	 * Fakes a successful LOCK
149
-	 *
150
-	 * @param RequestInterface $request
151
-	 * @param ResponseInterface $response
152
-	 * @return bool
153
-	 */
154
-	public function fakeUnlockProvider(RequestInterface $request,
155
-									 ResponseInterface $response) {
156
-		$response->setStatus(204);
157
-		$response->setHeader('Content-Length', '0');
158
-		return false;
159
-	}
147
+    /**
148
+     * Fakes a successful LOCK
149
+     *
150
+     * @param RequestInterface $request
151
+     * @param ResponseInterface $response
152
+     * @return bool
153
+     */
154
+    public function fakeUnlockProvider(RequestInterface $request,
155
+                                        ResponseInterface $response) {
156
+        $response->setStatus(204);
157
+        $response->setHeader('Content-Length', '0');
158
+        return false;
159
+    }
160 160
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ServerFactory.php 2 patches
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -48,176 +48,176 @@
 block discarded – undo
48 48
 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
49 49
 
50 50
 class ServerFactory {
51
-	/** @var IConfig */
52
-	private $config;
53
-	/** @var ILogger */
54
-	private $logger;
55
-	/** @var IDBConnection */
56
-	private $databaseConnection;
57
-	/** @var IUserSession */
58
-	private $userSession;
59
-	/** @var IMountManager */
60
-	private $mountManager;
61
-	/** @var ITagManager */
62
-	private $tagManager;
63
-	/** @var IRequest */
64
-	private $request;
65
-	/** @var IPreview  */
66
-	private $previewManager;
67
-	/** @var EventDispatcherInterface */
68
-	private $eventDispatcher;
51
+    /** @var IConfig */
52
+    private $config;
53
+    /** @var ILogger */
54
+    private $logger;
55
+    /** @var IDBConnection */
56
+    private $databaseConnection;
57
+    /** @var IUserSession */
58
+    private $userSession;
59
+    /** @var IMountManager */
60
+    private $mountManager;
61
+    /** @var ITagManager */
62
+    private $tagManager;
63
+    /** @var IRequest */
64
+    private $request;
65
+    /** @var IPreview  */
66
+    private $previewManager;
67
+    /** @var EventDispatcherInterface */
68
+    private $eventDispatcher;
69 69
 
70
-	/**
71
-	 * @param IConfig $config
72
-	 * @param ILogger $logger
73
-	 * @param IDBConnection $databaseConnection
74
-	 * @param IUserSession $userSession
75
-	 * @param IMountManager $mountManager
76
-	 * @param ITagManager $tagManager
77
-	 * @param IRequest $request
78
-	 * @param IPreview $previewManager
79
-	 */
80
-	public function __construct(
81
-		IConfig $config,
82
-		ILogger $logger,
83
-		IDBConnection $databaseConnection,
84
-		IUserSession $userSession,
85
-		IMountManager $mountManager,
86
-		ITagManager $tagManager,
87
-		IRequest $request,
88
-		IPreview $previewManager,
89
-		EventDispatcherInterface $eventDispatcher
90
-	) {
91
-		$this->config = $config;
92
-		$this->logger = $logger;
93
-		$this->databaseConnection = $databaseConnection;
94
-		$this->userSession = $userSession;
95
-		$this->mountManager = $mountManager;
96
-		$this->tagManager = $tagManager;
97
-		$this->request = $request;
98
-		$this->previewManager = $previewManager;
99
-		$this->eventDispatcher = $eventDispatcher;
100
-	}
70
+    /**
71
+     * @param IConfig $config
72
+     * @param ILogger $logger
73
+     * @param IDBConnection $databaseConnection
74
+     * @param IUserSession $userSession
75
+     * @param IMountManager $mountManager
76
+     * @param ITagManager $tagManager
77
+     * @param IRequest $request
78
+     * @param IPreview $previewManager
79
+     */
80
+    public function __construct(
81
+        IConfig $config,
82
+        ILogger $logger,
83
+        IDBConnection $databaseConnection,
84
+        IUserSession $userSession,
85
+        IMountManager $mountManager,
86
+        ITagManager $tagManager,
87
+        IRequest $request,
88
+        IPreview $previewManager,
89
+        EventDispatcherInterface $eventDispatcher
90
+    ) {
91
+        $this->config = $config;
92
+        $this->logger = $logger;
93
+        $this->databaseConnection = $databaseConnection;
94
+        $this->userSession = $userSession;
95
+        $this->mountManager = $mountManager;
96
+        $this->tagManager = $tagManager;
97
+        $this->request = $request;
98
+        $this->previewManager = $previewManager;
99
+        $this->eventDispatcher = $eventDispatcher;
100
+    }
101 101
 
102
-	/**
103
-	 * @param string $baseUri
104
-	 * @param string $requestUri
105
-	 * @param Plugin $authPlugin
106
-	 * @param callable $viewCallBack callback that should return the view for the dav endpoint
107
-	 * @return Server
108
-	 */
109
-	public function createServer($baseUri,
110
-								 $requestUri,
111
-								 Plugin $authPlugin,
112
-								 callable $viewCallBack) {
113
-		// Fire up server
114
-		$objectTree = new \OCA\DAV\Connector\Sabre\ObjectTree();
115
-		$server = new \OCA\DAV\Connector\Sabre\Server($objectTree);
116
-		// Set URL explicitly due to reverse-proxy situations
117
-		$server->httpRequest->setUrl($requestUri);
118
-		$server->setBaseUri($baseUri);
102
+    /**
103
+     * @param string $baseUri
104
+     * @param string $requestUri
105
+     * @param Plugin $authPlugin
106
+     * @param callable $viewCallBack callback that should return the view for the dav endpoint
107
+     * @return Server
108
+     */
109
+    public function createServer($baseUri,
110
+                                    $requestUri,
111
+                                    Plugin $authPlugin,
112
+                                    callable $viewCallBack) {
113
+        // Fire up server
114
+        $objectTree = new \OCA\DAV\Connector\Sabre\ObjectTree();
115
+        $server = new \OCA\DAV\Connector\Sabre\Server($objectTree);
116
+        // Set URL explicitly due to reverse-proxy situations
117
+        $server->httpRequest->setUrl($requestUri);
118
+        $server->setBaseUri($baseUri);
119 119
 
120
-		// Load plugins
121
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config));
122
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin($this->config));
123
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\AnonymousOptionsPlugin());
124
-		$server->addPlugin($authPlugin);
125
-		// FIXME: The following line is a workaround for legacy components relying on being able to send a GET to /
126
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin());
127
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $this->logger));
128
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
129
-		// Some WebDAV clients do require Class 2 WebDAV support (locking), since
130
-		// we do not provide locking we emulate it using a fake locking plugin.
131
-		if($this->request->isUserAgent([
132
-			'/WebDAVFS/',
133
-			'/OneNote/',
134
-			'/Microsoft-WebDAV-MiniRedir/',
135
-		])) {
136
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\FakeLockerPlugin());
137
-		}
120
+        // Load plugins
121
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config));
122
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin($this->config));
123
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\AnonymousOptionsPlugin());
124
+        $server->addPlugin($authPlugin);
125
+        // FIXME: The following line is a workaround for legacy components relying on being able to send a GET to /
126
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin());
127
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $this->logger));
128
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
129
+        // Some WebDAV clients do require Class 2 WebDAV support (locking), since
130
+        // we do not provide locking we emulate it using a fake locking plugin.
131
+        if($this->request->isUserAgent([
132
+            '/WebDAVFS/',
133
+            '/OneNote/',
134
+            '/Microsoft-WebDAV-MiniRedir/',
135
+        ])) {
136
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\FakeLockerPlugin());
137
+        }
138 138
 
139
-		if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) {
140
-			$server->addPlugin(new BrowserErrorPagePlugin());
141
-		}
139
+        if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) {
140
+            $server->addPlugin(new BrowserErrorPagePlugin());
141
+        }
142 142
 
143
-		// wait with registering these until auth is handled and the filesystem is setup
144
-		$server->on('beforeMethod:*', function () use ($server, $objectTree, $viewCallBack) {
145
-			// ensure the skeleton is copied
146
-			$userFolder = \OC::$server->getUserFolder();
143
+        // wait with registering these until auth is handled and the filesystem is setup
144
+        $server->on('beforeMethod:*', function () use ($server, $objectTree, $viewCallBack) {
145
+            // ensure the skeleton is copied
146
+            $userFolder = \OC::$server->getUserFolder();
147 147
 
148
-			/** @var \OC\Files\View $view */
149
-			$view = $viewCallBack($server);
150
-			if ($userFolder instanceof Folder && $userFolder->getPath() === $view->getRoot()) {
151
-				$rootInfo = $userFolder;
152
-			} else {
153
-				$rootInfo = $view->getFileInfo('');
154
-			}
148
+            /** @var \OC\Files\View $view */
149
+            $view = $viewCallBack($server);
150
+            if ($userFolder instanceof Folder && $userFolder->getPath() === $view->getRoot()) {
151
+                $rootInfo = $userFolder;
152
+            } else {
153
+                $rootInfo = $view->getFileInfo('');
154
+            }
155 155
 
156
-			// Create Nextcloud Dir
157
-			if ($rootInfo->getType() === 'dir') {
158
-				$root = new \OCA\DAV\Connector\Sabre\Directory($view, $rootInfo, $objectTree);
159
-			} else {
160
-				$root = new \OCA\DAV\Connector\Sabre\File($view, $rootInfo);
161
-			}
162
-			$objectTree->init($root, $view, $this->mountManager);
156
+            // Create Nextcloud Dir
157
+            if ($rootInfo->getType() === 'dir') {
158
+                $root = new \OCA\DAV\Connector\Sabre\Directory($view, $rootInfo, $objectTree);
159
+            } else {
160
+                $root = new \OCA\DAV\Connector\Sabre\File($view, $rootInfo);
161
+            }
162
+            $objectTree->init($root, $view, $this->mountManager);
163 163
 
164
-			$server->addPlugin(
165
-				new \OCA\DAV\Connector\Sabre\FilesPlugin(
166
-					$objectTree,
167
-					$this->config,
168
-					$this->request,
169
-					$this->previewManager,
170
-					false,
171
-					!$this->config->getSystemValue('debug', false)
172
-				)
173
-			);
174
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view, true));
164
+            $server->addPlugin(
165
+                new \OCA\DAV\Connector\Sabre\FilesPlugin(
166
+                    $objectTree,
167
+                    $this->config,
168
+                    $this->request,
169
+                    $this->previewManager,
170
+                    false,
171
+                    !$this->config->getSystemValue('debug', false)
172
+                )
173
+            );
174
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view, true));
175 175
 
176
-			if($this->userSession->isLoggedIn()) {
177
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager));
178
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin(
179
-					$objectTree,
180
-					$this->userSession,
181
-					$userFolder,
182
-					\OC::$server->getShareManager()
183
-				));
184
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->getCommentsManager(), $this->userSession));
185
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin(
186
-					$objectTree,
187
-					$view,
188
-					\OC::$server->getSystemTagManager(),
189
-					\OC::$server->getSystemTagObjectMapper(),
190
-					\OC::$server->getTagManager(),
191
-					$this->userSession,
192
-					\OC::$server->getGroupManager(),
193
-					$userFolder,
194
-					\OC::$server->getAppManager()
195
-				));
196
-				// custom properties plugin must be the last one
197
-				$server->addPlugin(
198
-					new \Sabre\DAV\PropertyStorage\Plugin(
199
-						new \OCA\DAV\DAV\CustomPropertiesBackend(
200
-							$objectTree,
201
-							$this->databaseConnection,
202
-							$this->userSession->getUser()
203
-						)
204
-					)
205
-				);
206
-			}
207
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin());
176
+            if($this->userSession->isLoggedIn()) {
177
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager));
178
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin(
179
+                    $objectTree,
180
+                    $this->userSession,
181
+                    $userFolder,
182
+                    \OC::$server->getShareManager()
183
+                ));
184
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->getCommentsManager(), $this->userSession));
185
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin(
186
+                    $objectTree,
187
+                    $view,
188
+                    \OC::$server->getSystemTagManager(),
189
+                    \OC::$server->getSystemTagObjectMapper(),
190
+                    \OC::$server->getTagManager(),
191
+                    $this->userSession,
192
+                    \OC::$server->getGroupManager(),
193
+                    $userFolder,
194
+                    \OC::$server->getAppManager()
195
+                ));
196
+                // custom properties plugin must be the last one
197
+                $server->addPlugin(
198
+                    new \Sabre\DAV\PropertyStorage\Plugin(
199
+                        new \OCA\DAV\DAV\CustomPropertiesBackend(
200
+                            $objectTree,
201
+                            $this->databaseConnection,
202
+                            $this->userSession->getUser()
203
+                        )
204
+                    )
205
+                );
206
+            }
207
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin());
208 208
 
209
-			// Load dav plugins from apps
210
-			$event = new SabrePluginEvent($server);
211
-			$this->eventDispatcher->dispatch($event);
212
-			$pluginManager = new PluginManager(
213
-				\OC::$server,
214
-				\OC::$server->getAppManager()
215
-			);
216
-			foreach ($pluginManager->getAppPlugins() as $appPlugin) {
217
-				$server->addPlugin($appPlugin);
218
-			}
209
+            // Load dav plugins from apps
210
+            $event = new SabrePluginEvent($server);
211
+            $this->eventDispatcher->dispatch($event);
212
+            $pluginManager = new PluginManager(
213
+                \OC::$server,
214
+                \OC::$server->getAppManager()
215
+            );
216
+            foreach ($pluginManager->getAppPlugins() as $appPlugin) {
217
+                $server->addPlugin($appPlugin);
218
+            }
219 219
 
220
-		}, 30); // priority 30: after auth (10) and acl(20), before lock(50) and handling the request
221
-		return $server;
222
-	}
220
+        }, 30); // priority 30: after auth (10) and acl(20), before lock(50) and handling the request
221
+        return $server;
222
+    }
223 223
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		$server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
129 129
 		// Some WebDAV clients do require Class 2 WebDAV support (locking), since
130 130
 		// we do not provide locking we emulate it using a fake locking plugin.
131
-		if($this->request->isUserAgent([
131
+		if ($this->request->isUserAgent([
132 132
 			'/WebDAVFS/',
133 133
 			'/OneNote/',
134 134
 			'/Microsoft-WebDAV-MiniRedir/',
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 		}
142 142
 
143 143
 		// wait with registering these until auth is handled and the filesystem is setup
144
-		$server->on('beforeMethod:*', function () use ($server, $objectTree, $viewCallBack) {
144
+		$server->on('beforeMethod:*', function() use ($server, $objectTree, $viewCallBack) {
145 145
 			// ensure the skeleton is copied
146 146
 			$userFolder = \OC::$server->getUserFolder();
147 147
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 			);
174 174
 			$server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view, true));
175 175
 
176
-			if($this->userSession->isLoggedIn()) {
176
+			if ($this->userSession->isLoggedIn()) {
177 177
 				$server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager));
178 178
 				$server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin(
179 179
 					$objectTree,
Please login to merge, or discard this patch.
apps/dav/lib/RootCollection.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -49,132 +49,132 @@
 block discarded – undo
49 49
 
50 50
 class RootCollection extends SimpleCollection {
51 51
 
52
-	public function __construct() {
53
-		$config = \OC::$server->getConfig();
54
-		$l10n = \OC::$server->getL10N('dav');
55
-		$random = \OC::$server->getSecureRandom();
56
-		$logger = \OC::$server->getLogger();
57
-		$userManager = \OC::$server->getUserManager();
58
-		$userSession = \OC::$server->getUserSession();
59
-		$groupManager = \OC::$server->getGroupManager();
60
-		$shareManager = \OC::$server->getShareManager();
61
-		$db = \OC::$server->getDatabaseConnection();
62
-		$dispatcher = \OC::$server->getEventDispatcher();
63
-		$proxyMapper = \OC::$server->query(ProxyMapper::class);
64
-
65
-		$userPrincipalBackend = new Principal(
66
-			$userManager,
67
-			$groupManager,
68
-			$shareManager,
69
-			\OC::$server->getUserSession(),
70
-			\OC::$server->getAppManager(),
71
-			$proxyMapper,
72
-			\OC::$server->getConfig()
73
-		);
74
-		$groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager);
75
-		$calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
76
-		$calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
77
-		// as soon as debug mode is enabled we allow listing of principals
78
-		$disableListing = !$config->getSystemValue('debug', false);
79
-
80
-		// setup the first level of the dav tree
81
-		$userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
82
-		$userPrincipals->disableListing = $disableListing;
83
-		$groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
84
-		$groupPrincipals->disableListing = $disableListing;
85
-		$systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
86
-		$systemPrincipals->disableListing = $disableListing;
87
-		$calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
88
-		$calendarResourcePrincipals->disableListing = $disableListing;
89
-		$calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
90
-		$calendarRoomPrincipals->disableListing = $disableListing;
91
-
92
-
93
-		$filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
94
-		$filesCollection->disableListing = $disableListing;
95
-		$caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
96
-		$userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
97
-		$userCalendarRoot->disableListing = $disableListing;
98
-
99
-		$resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
100
-		$resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
101
-		$resourceCalendarRoot->disableListing = $disableListing;
102
-		$roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
103
-		$roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
104
-		$roomCalendarRoot->disableListing = $disableListing;
105
-
106
-		$publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
107
-		$publicCalendarRoot->disableListing = $disableListing;
108
-
109
-		$systemTagCollection = new SystemTag\SystemTagsByIdCollection(
110
-			\OC::$server->getSystemTagManager(),
111
-			\OC::$server->getUserSession(),
112
-			$groupManager
113
-		);
114
-		$systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
115
-			\OC::$server->getSystemTagManager(),
116
-			\OC::$server->getSystemTagObjectMapper(),
117
-			\OC::$server->getUserSession(),
118
-			$groupManager,
119
-			\OC::$server->getEventDispatcher()
120
-		);
121
-		$commentsCollection = new Comments\RootCollection(
122
-			\OC::$server->getCommentsManager(),
123
-			$userManager,
124
-			\OC::$server->getUserSession(),
125
-			\OC::$server->getEventDispatcher(),
126
-			\OC::$server->getLogger()
127
-		);
128
-
129
-		$pluginManager = new PluginManager(\OC::$server, \OC::$server->query(IAppManager::class));
130
-		$usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
131
-		$usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, 'principals/users');
132
-		$usersAddressBookRoot->disableListing = $disableListing;
133
-
134
-		$systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
135
-		$systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, $pluginManager, 'principals/system');
136
-		$systemAddressBookRoot->disableListing = $disableListing;
137
-
138
-		$uploadCollection = new Upload\RootCollection(
139
-			$userPrincipalBackend,
140
-			'principals/users',
141
-			\OC::$server->query(CleanupService::class));
142
-		$uploadCollection->disableListing = $disableListing;
143
-
144
-		$avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
145
-		$avatarCollection->disableListing = $disableListing;
146
-
147
-		$appleProvisioning = new AppleProvisioningNode(
148
-			\OC::$server->query(ITimeFactory::class));
149
-
150
-		$children = [
151
-			new SimpleCollection('principals', [
152
-				$userPrincipals,
153
-				$groupPrincipals,
154
-				$systemPrincipals,
155
-				$calendarResourcePrincipals,
156
-				$calendarRoomPrincipals]),
157
-			$filesCollection,
158
-			$userCalendarRoot,
159
-			new SimpleCollection('system-calendars', [
160
-				$resourceCalendarRoot,
161
-				$roomCalendarRoot,
162
-			]),
163
-			$publicCalendarRoot,
164
-			new SimpleCollection('addressbooks', [
165
-				$usersAddressBookRoot,
166
-				$systemAddressBookRoot]),
167
-			$systemTagCollection,
168
-			$systemTagRelationsCollection,
169
-			$commentsCollection,
170
-			$uploadCollection,
171
-			$avatarCollection,
172
-			new SimpleCollection('provisioning', [
173
-				$appleProvisioning
174
-			])
175
-		];
176
-
177
-		parent::__construct('root', $children);
178
-	}
52
+    public function __construct() {
53
+        $config = \OC::$server->getConfig();
54
+        $l10n = \OC::$server->getL10N('dav');
55
+        $random = \OC::$server->getSecureRandom();
56
+        $logger = \OC::$server->getLogger();
57
+        $userManager = \OC::$server->getUserManager();
58
+        $userSession = \OC::$server->getUserSession();
59
+        $groupManager = \OC::$server->getGroupManager();
60
+        $shareManager = \OC::$server->getShareManager();
61
+        $db = \OC::$server->getDatabaseConnection();
62
+        $dispatcher = \OC::$server->getEventDispatcher();
63
+        $proxyMapper = \OC::$server->query(ProxyMapper::class);
64
+
65
+        $userPrincipalBackend = new Principal(
66
+            $userManager,
67
+            $groupManager,
68
+            $shareManager,
69
+            \OC::$server->getUserSession(),
70
+            \OC::$server->getAppManager(),
71
+            $proxyMapper,
72
+            \OC::$server->getConfig()
73
+        );
74
+        $groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager);
75
+        $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
76
+        $calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
77
+        // as soon as debug mode is enabled we allow listing of principals
78
+        $disableListing = !$config->getSystemValue('debug', false);
79
+
80
+        // setup the first level of the dav tree
81
+        $userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
82
+        $userPrincipals->disableListing = $disableListing;
83
+        $groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
84
+        $groupPrincipals->disableListing = $disableListing;
85
+        $systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
86
+        $systemPrincipals->disableListing = $disableListing;
87
+        $calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
88
+        $calendarResourcePrincipals->disableListing = $disableListing;
89
+        $calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
90
+        $calendarRoomPrincipals->disableListing = $disableListing;
91
+
92
+
93
+        $filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
94
+        $filesCollection->disableListing = $disableListing;
95
+        $caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
96
+        $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
97
+        $userCalendarRoot->disableListing = $disableListing;
98
+
99
+        $resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
100
+        $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
101
+        $resourceCalendarRoot->disableListing = $disableListing;
102
+        $roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
103
+        $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
104
+        $roomCalendarRoot->disableListing = $disableListing;
105
+
106
+        $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
107
+        $publicCalendarRoot->disableListing = $disableListing;
108
+
109
+        $systemTagCollection = new SystemTag\SystemTagsByIdCollection(
110
+            \OC::$server->getSystemTagManager(),
111
+            \OC::$server->getUserSession(),
112
+            $groupManager
113
+        );
114
+        $systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
115
+            \OC::$server->getSystemTagManager(),
116
+            \OC::$server->getSystemTagObjectMapper(),
117
+            \OC::$server->getUserSession(),
118
+            $groupManager,
119
+            \OC::$server->getEventDispatcher()
120
+        );
121
+        $commentsCollection = new Comments\RootCollection(
122
+            \OC::$server->getCommentsManager(),
123
+            $userManager,
124
+            \OC::$server->getUserSession(),
125
+            \OC::$server->getEventDispatcher(),
126
+            \OC::$server->getLogger()
127
+        );
128
+
129
+        $pluginManager = new PluginManager(\OC::$server, \OC::$server->query(IAppManager::class));
130
+        $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
131
+        $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, 'principals/users');
132
+        $usersAddressBookRoot->disableListing = $disableListing;
133
+
134
+        $systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
135
+        $systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, $pluginManager, 'principals/system');
136
+        $systemAddressBookRoot->disableListing = $disableListing;
137
+
138
+        $uploadCollection = new Upload\RootCollection(
139
+            $userPrincipalBackend,
140
+            'principals/users',
141
+            \OC::$server->query(CleanupService::class));
142
+        $uploadCollection->disableListing = $disableListing;
143
+
144
+        $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
145
+        $avatarCollection->disableListing = $disableListing;
146
+
147
+        $appleProvisioning = new AppleProvisioningNode(
148
+            \OC::$server->query(ITimeFactory::class));
149
+
150
+        $children = [
151
+            new SimpleCollection('principals', [
152
+                $userPrincipals,
153
+                $groupPrincipals,
154
+                $systemPrincipals,
155
+                $calendarResourcePrincipals,
156
+                $calendarRoomPrincipals]),
157
+            $filesCollection,
158
+            $userCalendarRoot,
159
+            new SimpleCollection('system-calendars', [
160
+                $resourceCalendarRoot,
161
+                $roomCalendarRoot,
162
+            ]),
163
+            $publicCalendarRoot,
164
+            new SimpleCollection('addressbooks', [
165
+                $usersAddressBookRoot,
166
+                $systemAddressBookRoot]),
167
+            $systemTagCollection,
168
+            $systemTagRelationsCollection,
169
+            $commentsCollection,
170
+            $uploadCollection,
171
+            $avatarCollection,
172
+            new SimpleCollection('provisioning', [
173
+                $appleProvisioning
174
+            ])
175
+        ];
176
+
177
+        parent::__construct('root', $children);
178
+    }
179 179
 
180 180
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Calendar.php 2 patches
Indentation   +360 added lines, -360 removed lines patch added patch discarded remove patch
@@ -45,364 +45,364 @@
 block discarded – undo
45 45
  */
46 46
 class Calendar extends \Sabre\CalDAV\Calendar implements IShareable {
47 47
 
48
-	/** @var IConfig */
49
-	private $config;
50
-
51
-	/** @var IL10N */
52
-	protected $l10n;
53
-
54
-	/**
55
-	 * Calendar constructor.
56
-	 *
57
-	 * @param BackendInterface $caldavBackend
58
-	 * @param $calendarInfo
59
-	 * @param IL10N $l10n
60
-	 * @param IConfig $config
61
-	 */
62
-	public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n, IConfig $config) {
63
-		parent::__construct($caldavBackend, $calendarInfo);
64
-
65
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
66
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
67
-		}
68
-		if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
69
-			$this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
70
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
71
-		}
72
-
73
-		$this->config = $config;
74
-		$this->l10n = $l10n;
75
-	}
76
-
77
-	/**
78
-	 * Updates the list of shares.
79
-	 *
80
-	 * The first array is a list of people that are to be added to the
81
-	 * resource.
82
-	 *
83
-	 * Every element in the add array has the following properties:
84
-	 *   * href - A url. Usually a mailto: address
85
-	 *   * commonName - Usually a first and last name, or false
86
-	 *   * summary - A description of the share, can also be false
87
-	 *   * readOnly - A boolean value
88
-	 *
89
-	 * Every element in the remove array is just the address string.
90
-	 *
91
-	 * @param array $add
92
-	 * @param array $remove
93
-	 * @return void
94
-	 * @throws Forbidden
95
-	 */
96
-	public function updateShares(array $add, array $remove) {
97
-		if ($this->isShared()) {
98
-			throw new Forbidden();
99
-		}
100
-		$this->caldavBackend->updateShares($this, $add, $remove);
101
-	}
102
-
103
-	/**
104
-	 * Returns the list of people whom this resource is shared with.
105
-	 *
106
-	 * Every element in this array should have the following properties:
107
-	 *   * href - Often a mailto: address
108
-	 *   * commonName - Optional, for example a first + last name
109
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
110
-	 *   * readOnly - boolean
111
-	 *   * summary - Optional, a description for the share
112
-	 *
113
-	 * @return array
114
-	 */
115
-	public function getShares() {
116
-		if ($this->isShared()) {
117
-			return [];
118
-		}
119
-		return $this->caldavBackend->getShares($this->getResourceId());
120
-	}
121
-
122
-	/**
123
-	 * @return int
124
-	 */
125
-	public function getResourceId() {
126
-		return $this->calendarInfo['id'];
127
-	}
128
-
129
-	/**
130
-	 * @return string
131
-	 */
132
-	public function getPrincipalURI() {
133
-		return $this->calendarInfo['principaluri'];
134
-	}
135
-
136
-	/**
137
-	 * @return array
138
-	 */
139
-	public function getACL() {
140
-		$acl =  [
141
-			[
142
-				'privilege' => '{DAV:}read',
143
-				'principal' => $this->getOwner(),
144
-				'protected' => true,
145
-			],
146
-			[
147
-				'privilege' => '{DAV:}read',
148
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
149
-				'protected' => true,
150
-			],
151
-			[
152
-				'privilege' => '{DAV:}read',
153
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
154
-				'protected' => true,
155
-			],
156
-		];
157
-
158
-		if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
159
-			$acl[] = [
160
-				'privilege' => '{DAV:}write',
161
-				'principal' => $this->getOwner(),
162
-				'protected' => true,
163
-			];
164
-			$acl[] = [
165
-				'privilege' => '{DAV:}write',
166
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
167
-				'protected' => true,
168
-			];
169
-		} else {
170
-			$acl[] = [
171
-				'privilege' => '{DAV:}write-properties',
172
-				'principal' => $this->getOwner(),
173
-				'protected' => true,
174
-			];
175
-			$acl[] = [
176
-				'privilege' => '{DAV:}write-properties',
177
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
178
-				'protected' => true,
179
-			];
180
-		}
181
-
182
-		$acl[] = [
183
-			'privilege' => '{DAV:}write-properties',
184
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
185
-			'protected' => true,
186
-		];
187
-
188
-		if (!$this->isShared()) {
189
-			return $acl;
190
-		}
191
-
192
-		if ($this->getOwner() !== parent::getOwner()) {
193
-			$acl[] =  [
194
-				'privilege' => '{DAV:}read',
195
-				'principal' => parent::getOwner(),
196
-				'protected' => true,
197
-			];
198
-			if ($this->canWrite()) {
199
-				$acl[] = [
200
-					'privilege' => '{DAV:}write',
201
-					'principal' => parent::getOwner(),
202
-					'protected' => true,
203
-				];
204
-			} else {
205
-				$acl[] = [
206
-					'privilege' => '{DAV:}write-properties',
207
-					'principal' => parent::getOwner(),
208
-					'protected' => true,
209
-				];
210
-			}
211
-		}
212
-		if ($this->isPublic()) {
213
-			$acl[] = [
214
-				'privilege' => '{DAV:}read',
215
-				'principal' => 'principals/system/public',
216
-				'protected' => true,
217
-			];
218
-		}
219
-
220
-		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221
-		$allowedPrincipals = [
222
-			$this->getOwner(),
223
-			$this->getOwner(). '/calendar-proxy-read',
224
-			$this->getOwner(). '/calendar-proxy-write',
225
-			parent::getOwner(),
226
-			'principals/system/public'
227
-		];
228
-		return array_filter($acl, function($rule) use ($allowedPrincipals) {
229
-			return \in_array($rule['principal'], $allowedPrincipals, true);
230
-		});
231
-	}
232
-
233
-	public function getChildACL() {
234
-		return $this->getACL();
235
-	}
236
-
237
-	public function getOwner() {
238
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
239
-			return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
240
-		}
241
-		return parent::getOwner();
242
-	}
243
-
244
-	public function delete() {
245
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246
-			$this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
-			$principal = 'principal:' . parent::getOwner();
248
-			$shares = $this->caldavBackend->getShares($this->getResourceId());
249
-			$shares = array_filter($shares, function($share) use ($principal){
250
-				return $share['href'] === $principal;
251
-			});
252
-			if (empty($shares)) {
253
-				throw new Forbidden();
254
-			}
255
-
256
-			$this->caldavBackend->updateShares($this, [], [
257
-				$principal
258
-			]);
259
-			return;
260
-		}
261
-
262
-		// Remember when a user deleted their birthday calendar
263
-		// in order to not regenerate it on the next contacts change
264
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
265
-			$principalURI = $this->getPrincipalURI();
266
-			$userId = substr($principalURI, 17);
267
-
268
-			$this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
269
-		}
270
-
271
-		parent::delete();
272
-	}
273
-
274
-	public function propPatch(PropPatch $propPatch) {
275
-		// parent::propPatch will only update calendars table
276
-		// if calendar is shared, changes have to be made to the properties table
277
-		if (!$this->isShared()) {
278
-			parent::propPatch($propPatch);
279
-		}
280
-	}
281
-
282
-	public function getChild($name) {
283
-
284
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
285
-
286
-		if (!$obj) {
287
-			throw new NotFound('Calendar object not found');
288
-		}
289
-
290
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
291
-			throw new NotFound('Calendar object not found');
292
-		}
293
-
294
-		$obj['acl'] = $this->getChildACL();
295
-
296
-		return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
297
-
298
-	}
299
-
300
-	public function getChildren() {
301
-
302
-		$objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
303
-		$children = [];
304
-		foreach ($objs as $obj) {
305
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
306
-				continue;
307
-			}
308
-			$obj['acl'] = $this->getChildACL();
309
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
310
-		}
311
-		return $children;
312
-
313
-	}
314
-
315
-	public function getMultipleChildren(array $paths) {
316
-
317
-		$objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
318
-		$children = [];
319
-		foreach ($objs as $obj) {
320
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
321
-				continue;
322
-			}
323
-			$obj['acl'] = $this->getChildACL();
324
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
325
-		}
326
-		return $children;
327
-
328
-	}
329
-
330
-	public function childExists($name) {
331
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
332
-		if (!$obj) {
333
-			return false;
334
-		}
335
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
336
-			return false;
337
-		}
338
-
339
-		return true;
340
-	}
341
-
342
-	public function calendarQuery(array $filters) {
343
-
344
-		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345
-		if ($this->isShared()) {
346
-			return array_filter($uris, function ($uri) {
347
-				return $this->childExists($uri);
348
-			});
349
-		}
350
-
351
-		return $uris;
352
-	}
353
-
354
-	/**
355
-	 * @param boolean $value
356
-	 * @return string|null
357
-	 */
358
-	public function setPublishStatus($value) {
359
-		$publicUri = $this->caldavBackend->setPublishStatus($value, $this);
360
-		$this->calendarInfo['publicuri'] = $publicUri;
361
-		return $publicUri;
362
-	}
363
-
364
-	/**
365
-	 * @return mixed $value
366
-	 */
367
-	public function getPublishStatus() {
368
-		return $this->caldavBackend->getPublishStatus($this);
369
-	}
370
-
371
-	public function canWrite() {
372
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
373
-			return false;
374
-		}
375
-
376
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
377
-			return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
378
-		}
379
-		return true;
380
-	}
381
-
382
-	private function isPublic() {
383
-		return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
384
-	}
385
-
386
-	protected function isShared() {
387
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
388
-			return false;
389
-		}
390
-
391
-		return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
392
-	}
393
-
394
-	public function isSubscription() {
395
-		return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
396
-	}
397
-
398
-	/**
399
-	 * @inheritDoc
400
-	 */
401
-	public function getChanges($syncToken, $syncLevel, $limit = null) {
402
-		if (!$syncToken && $limit) {
403
-			throw new UnsupportedLimitOnInitialSyncException();
404
-		}
405
-
406
-		return parent::getChanges($syncToken, $syncLevel, $limit);
407
-	}
48
+    /** @var IConfig */
49
+    private $config;
50
+
51
+    /** @var IL10N */
52
+    protected $l10n;
53
+
54
+    /**
55
+     * Calendar constructor.
56
+     *
57
+     * @param BackendInterface $caldavBackend
58
+     * @param $calendarInfo
59
+     * @param IL10N $l10n
60
+     * @param IConfig $config
61
+     */
62
+    public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n, IConfig $config) {
63
+        parent::__construct($caldavBackend, $calendarInfo);
64
+
65
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
66
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
67
+        }
68
+        if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
69
+            $this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
70
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
71
+        }
72
+
73
+        $this->config = $config;
74
+        $this->l10n = $l10n;
75
+    }
76
+
77
+    /**
78
+     * Updates the list of shares.
79
+     *
80
+     * The first array is a list of people that are to be added to the
81
+     * resource.
82
+     *
83
+     * Every element in the add array has the following properties:
84
+     *   * href - A url. Usually a mailto: address
85
+     *   * commonName - Usually a first and last name, or false
86
+     *   * summary - A description of the share, can also be false
87
+     *   * readOnly - A boolean value
88
+     *
89
+     * Every element in the remove array is just the address string.
90
+     *
91
+     * @param array $add
92
+     * @param array $remove
93
+     * @return void
94
+     * @throws Forbidden
95
+     */
96
+    public function updateShares(array $add, array $remove) {
97
+        if ($this->isShared()) {
98
+            throw new Forbidden();
99
+        }
100
+        $this->caldavBackend->updateShares($this, $add, $remove);
101
+    }
102
+
103
+    /**
104
+     * Returns the list of people whom this resource is shared with.
105
+     *
106
+     * Every element in this array should have the following properties:
107
+     *   * href - Often a mailto: address
108
+     *   * commonName - Optional, for example a first + last name
109
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
110
+     *   * readOnly - boolean
111
+     *   * summary - Optional, a description for the share
112
+     *
113
+     * @return array
114
+     */
115
+    public function getShares() {
116
+        if ($this->isShared()) {
117
+            return [];
118
+        }
119
+        return $this->caldavBackend->getShares($this->getResourceId());
120
+    }
121
+
122
+    /**
123
+     * @return int
124
+     */
125
+    public function getResourceId() {
126
+        return $this->calendarInfo['id'];
127
+    }
128
+
129
+    /**
130
+     * @return string
131
+     */
132
+    public function getPrincipalURI() {
133
+        return $this->calendarInfo['principaluri'];
134
+    }
135
+
136
+    /**
137
+     * @return array
138
+     */
139
+    public function getACL() {
140
+        $acl =  [
141
+            [
142
+                'privilege' => '{DAV:}read',
143
+                'principal' => $this->getOwner(),
144
+                'protected' => true,
145
+            ],
146
+            [
147
+                'privilege' => '{DAV:}read',
148
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
149
+                'protected' => true,
150
+            ],
151
+            [
152
+                'privilege' => '{DAV:}read',
153
+                'principal' => $this->getOwner() . '/calendar-proxy-read',
154
+                'protected' => true,
155
+            ],
156
+        ];
157
+
158
+        if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
159
+            $acl[] = [
160
+                'privilege' => '{DAV:}write',
161
+                'principal' => $this->getOwner(),
162
+                'protected' => true,
163
+            ];
164
+            $acl[] = [
165
+                'privilege' => '{DAV:}write',
166
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
167
+                'protected' => true,
168
+            ];
169
+        } else {
170
+            $acl[] = [
171
+                'privilege' => '{DAV:}write-properties',
172
+                'principal' => $this->getOwner(),
173
+                'protected' => true,
174
+            ];
175
+            $acl[] = [
176
+                'privilege' => '{DAV:}write-properties',
177
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
178
+                'protected' => true,
179
+            ];
180
+        }
181
+
182
+        $acl[] = [
183
+            'privilege' => '{DAV:}write-properties',
184
+            'principal' => $this->getOwner() . '/calendar-proxy-read',
185
+            'protected' => true,
186
+        ];
187
+
188
+        if (!$this->isShared()) {
189
+            return $acl;
190
+        }
191
+
192
+        if ($this->getOwner() !== parent::getOwner()) {
193
+            $acl[] =  [
194
+                'privilege' => '{DAV:}read',
195
+                'principal' => parent::getOwner(),
196
+                'protected' => true,
197
+            ];
198
+            if ($this->canWrite()) {
199
+                $acl[] = [
200
+                    'privilege' => '{DAV:}write',
201
+                    'principal' => parent::getOwner(),
202
+                    'protected' => true,
203
+                ];
204
+            } else {
205
+                $acl[] = [
206
+                    'privilege' => '{DAV:}write-properties',
207
+                    'principal' => parent::getOwner(),
208
+                    'protected' => true,
209
+                ];
210
+            }
211
+        }
212
+        if ($this->isPublic()) {
213
+            $acl[] = [
214
+                'privilege' => '{DAV:}read',
215
+                'principal' => 'principals/system/public',
216
+                'protected' => true,
217
+            ];
218
+        }
219
+
220
+        $acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221
+        $allowedPrincipals = [
222
+            $this->getOwner(),
223
+            $this->getOwner(). '/calendar-proxy-read',
224
+            $this->getOwner(). '/calendar-proxy-write',
225
+            parent::getOwner(),
226
+            'principals/system/public'
227
+        ];
228
+        return array_filter($acl, function($rule) use ($allowedPrincipals) {
229
+            return \in_array($rule['principal'], $allowedPrincipals, true);
230
+        });
231
+    }
232
+
233
+    public function getChildACL() {
234
+        return $this->getACL();
235
+    }
236
+
237
+    public function getOwner() {
238
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
239
+            return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
240
+        }
241
+        return parent::getOwner();
242
+    }
243
+
244
+    public function delete() {
245
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246
+            $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
+            $principal = 'principal:' . parent::getOwner();
248
+            $shares = $this->caldavBackend->getShares($this->getResourceId());
249
+            $shares = array_filter($shares, function($share) use ($principal){
250
+                return $share['href'] === $principal;
251
+            });
252
+            if (empty($shares)) {
253
+                throw new Forbidden();
254
+            }
255
+
256
+            $this->caldavBackend->updateShares($this, [], [
257
+                $principal
258
+            ]);
259
+            return;
260
+        }
261
+
262
+        // Remember when a user deleted their birthday calendar
263
+        // in order to not regenerate it on the next contacts change
264
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
265
+            $principalURI = $this->getPrincipalURI();
266
+            $userId = substr($principalURI, 17);
267
+
268
+            $this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
269
+        }
270
+
271
+        parent::delete();
272
+    }
273
+
274
+    public function propPatch(PropPatch $propPatch) {
275
+        // parent::propPatch will only update calendars table
276
+        // if calendar is shared, changes have to be made to the properties table
277
+        if (!$this->isShared()) {
278
+            parent::propPatch($propPatch);
279
+        }
280
+    }
281
+
282
+    public function getChild($name) {
283
+
284
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
285
+
286
+        if (!$obj) {
287
+            throw new NotFound('Calendar object not found');
288
+        }
289
+
290
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
291
+            throw new NotFound('Calendar object not found');
292
+        }
293
+
294
+        $obj['acl'] = $this->getChildACL();
295
+
296
+        return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
297
+
298
+    }
299
+
300
+    public function getChildren() {
301
+
302
+        $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
303
+        $children = [];
304
+        foreach ($objs as $obj) {
305
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
306
+                continue;
307
+            }
308
+            $obj['acl'] = $this->getChildACL();
309
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
310
+        }
311
+        return $children;
312
+
313
+    }
314
+
315
+    public function getMultipleChildren(array $paths) {
316
+
317
+        $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
318
+        $children = [];
319
+        foreach ($objs as $obj) {
320
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
321
+                continue;
322
+            }
323
+            $obj['acl'] = $this->getChildACL();
324
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
325
+        }
326
+        return $children;
327
+
328
+    }
329
+
330
+    public function childExists($name) {
331
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
332
+        if (!$obj) {
333
+            return false;
334
+        }
335
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
336
+            return false;
337
+        }
338
+
339
+        return true;
340
+    }
341
+
342
+    public function calendarQuery(array $filters) {
343
+
344
+        $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345
+        if ($this->isShared()) {
346
+            return array_filter($uris, function ($uri) {
347
+                return $this->childExists($uri);
348
+            });
349
+        }
350
+
351
+        return $uris;
352
+    }
353
+
354
+    /**
355
+     * @param boolean $value
356
+     * @return string|null
357
+     */
358
+    public function setPublishStatus($value) {
359
+        $publicUri = $this->caldavBackend->setPublishStatus($value, $this);
360
+        $this->calendarInfo['publicuri'] = $publicUri;
361
+        return $publicUri;
362
+    }
363
+
364
+    /**
365
+     * @return mixed $value
366
+     */
367
+    public function getPublishStatus() {
368
+        return $this->caldavBackend->getPublishStatus($this);
369
+    }
370
+
371
+    public function canWrite() {
372
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
373
+            return false;
374
+        }
375
+
376
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
377
+            return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
378
+        }
379
+        return true;
380
+    }
381
+
382
+    private function isPublic() {
383
+        return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
384
+    }
385
+
386
+    protected function isShared() {
387
+        if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
388
+            return false;
389
+        }
390
+
391
+        return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
392
+    }
393
+
394
+    public function isSubscription() {
395
+        return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
396
+    }
397
+
398
+    /**
399
+     * @inheritDoc
400
+     */
401
+    public function getChanges($syncToken, $syncLevel, $limit = null) {
402
+        if (!$syncToken && $limit) {
403
+            throw new UnsupportedLimitOnInitialSyncException();
404
+        }
405
+
406
+        return parent::getChanges($syncToken, $syncLevel, $limit);
407
+    }
408 408
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return array
138 138
 	 */
139 139
 	public function getACL() {
140
-		$acl =  [
140
+		$acl = [
141 141
 			[
142 142
 				'privilege' => '{DAV:}read',
143 143
 				'principal' => $this->getOwner(),
@@ -145,12 +145,12 @@  discard block
 block discarded – undo
145 145
 			],
146 146
 			[
147 147
 				'privilege' => '{DAV:}read',
148
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
148
+				'principal' => $this->getOwner().'/calendar-proxy-write',
149 149
 				'protected' => true,
150 150
 			],
151 151
 			[
152 152
 				'privilege' => '{DAV:}read',
153
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
153
+				'principal' => $this->getOwner().'/calendar-proxy-read',
154 154
 				'protected' => true,
155 155
 			],
156 156
 		];
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			];
164 164
 			$acl[] = [
165 165
 				'privilege' => '{DAV:}write',
166
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
166
+				'principal' => $this->getOwner().'/calendar-proxy-write',
167 167
 				'protected' => true,
168 168
 			];
169 169
 		} else {
@@ -174,14 +174,14 @@  discard block
 block discarded – undo
174 174
 			];
175 175
 			$acl[] = [
176 176
 				'privilege' => '{DAV:}write-properties',
177
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
177
+				'principal' => $this->getOwner().'/calendar-proxy-write',
178 178
 				'protected' => true,
179 179
 			];
180 180
 		}
181 181
 
182 182
 		$acl[] = [
183 183
 			'privilege' => '{DAV:}write-properties',
184
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
184
+			'principal' => $this->getOwner().'/calendar-proxy-read',
185 185
 			'protected' => true,
186 186
 		];
187 187
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 
192 192
 		if ($this->getOwner() !== parent::getOwner()) {
193
-			$acl[] =  [
193
+			$acl[] = [
194 194
 				'privilege' => '{DAV:}read',
195 195
 				'principal' => parent::getOwner(),
196 196
 				'protected' => true,
@@ -220,8 +220,8 @@  discard block
 block discarded – undo
220 220
 		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
221 221
 		$allowedPrincipals = [
222 222
 			$this->getOwner(),
223
-			$this->getOwner(). '/calendar-proxy-read',
224
-			$this->getOwner(). '/calendar-proxy-write',
223
+			$this->getOwner().'/calendar-proxy-read',
224
+			$this->getOwner().'/calendar-proxy-write',
225 225
 			parent::getOwner(),
226 226
 			'principals/system/public'
227 227
 		];
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 	public function delete() {
245 245
 		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
246 246
 			$this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
247
-			$principal = 'principal:' . parent::getOwner();
247
+			$principal = 'principal:'.parent::getOwner();
248 248
 			$shares = $this->caldavBackend->getShares($this->getResourceId());
249 249
 			$shares = array_filter($shares, function($share) use ($principal){
250 250
 				return $share['href'] === $principal;
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 
344 344
 		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
345 345
 		if ($this->isShared()) {
346
-			return array_filter($uris, function ($uri) {
346
+			return array_filter($uris, function($uri) {
347 347
 				return $this->childExists($uri);
348 348
 			});
349 349
 		}
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2560 added lines, -2560 removed lines patch added patch discarded remove patch
@@ -78,2564 +78,2564 @@
 block discarded – undo
78 78
  */
79 79
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
80 80
 
81
-	const CALENDAR_TYPE_CALENDAR = 0;
82
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
83
-
84
-	const PERSONAL_CALENDAR_URI = 'personal';
85
-	const PERSONAL_CALENDAR_NAME = 'Personal';
86
-
87
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
88
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
89
-
90
-	/**
91
-	 * We need to specify a max date, because we need to stop *somewhere*
92
-	 *
93
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
94
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
95
-	 * in 2038-01-19 to avoid problems when the date is converted
96
-	 * to a unix timestamp.
97
-	 */
98
-	const MAX_DATE = '2038-01-01';
99
-
100
-	const ACCESS_PUBLIC = 4;
101
-	const CLASSIFICATION_PUBLIC = 0;
102
-	const CLASSIFICATION_PRIVATE = 1;
103
-	const CLASSIFICATION_CONFIDENTIAL = 2;
104
-
105
-	/**
106
-	 * List of CalDAV properties, and how they map to database field names
107
-	 * Add your own properties by simply adding on to this array.
108
-	 *
109
-	 * Note that only string-based properties are supported here.
110
-	 *
111
-	 * @var array
112
-	 */
113
-	public $propertyMap = [
114
-		'{DAV:}displayname'                          => 'displayname',
115
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
116
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
117
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
118
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
119
-	];
120
-
121
-	/**
122
-	 * List of subscription properties, and how they map to database field names.
123
-	 *
124
-	 * @var array
125
-	 */
126
-	public $subscriptionPropertyMap = [
127
-		'{DAV:}displayname'                                           => 'displayname',
128
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
129
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
130
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
131
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
132
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
133
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
134
-	];
135
-
136
-	/** @var array properties to index */
137
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
138
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
139
-		'ORGANIZER'];
140
-
141
-	/** @var array parameters to index */
142
-	public static $indexParameters = [
143
-		'ATTENDEE' => ['CN'],
144
-		'ORGANIZER' => ['CN'],
145
-	];
146
-
147
-	/**
148
-	 * @var string[] Map of uid => display name
149
-	 */
150
-	protected $userDisplayNames;
151
-
152
-	/** @var IDBConnection */
153
-	private $db;
154
-
155
-	/** @var Backend */
156
-	private $calendarSharingBackend;
157
-
158
-	/** @var Principal */
159
-	private $principalBackend;
160
-
161
-	/** @var IUserManager */
162
-	private $userManager;
163
-
164
-	/** @var ISecureRandom */
165
-	private $random;
166
-
167
-	/** @var ILogger */
168
-	private $logger;
169
-
170
-	/** @var EventDispatcherInterface */
171
-	private $dispatcher;
172
-
173
-	/** @var bool */
174
-	private $legacyEndpoint;
175
-
176
-	/** @var string */
177
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
178
-
179
-	/**
180
-	 * CalDavBackend constructor.
181
-	 *
182
-	 * @param IDBConnection $db
183
-	 * @param Principal $principalBackend
184
-	 * @param IUserManager $userManager
185
-	 * @param IGroupManager $groupManager
186
-	 * @param ISecureRandom $random
187
-	 * @param ILogger $logger
188
-	 * @param EventDispatcherInterface $dispatcher
189
-	 * @param bool $legacyEndpoint
190
-	 */
191
-	public function __construct(IDBConnection $db,
192
-								Principal $principalBackend,
193
-								IUserManager $userManager,
194
-								IGroupManager $groupManager,
195
-								ISecureRandom $random,
196
-								ILogger $logger,
197
-								EventDispatcherInterface $dispatcher,
198
-								bool $legacyEndpoint = false) {
199
-		$this->db = $db;
200
-		$this->principalBackend = $principalBackend;
201
-		$this->userManager = $userManager;
202
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
203
-		$this->random = $random;
204
-		$this->logger = $logger;
205
-		$this->dispatcher = $dispatcher;
206
-		$this->legacyEndpoint = $legacyEndpoint;
207
-	}
208
-
209
-	/**
210
-	 * Return the number of calendars for a principal
211
-	 *
212
-	 * By default this excludes the automatically generated birthday calendar
213
-	 *
214
-	 * @param $principalUri
215
-	 * @param bool $excludeBirthday
216
-	 * @return int
217
-	 */
218
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
219
-		$principalUri = $this->convertPrincipal($principalUri, true);
220
-		$query = $this->db->getQueryBuilder();
221
-		$query->select($query->func()->count('*'))
222
-			->from('calendars')
223
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
224
-
225
-		if ($excludeBirthday) {
226
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227
-		}
228
-
229
-		return (int)$query->execute()->fetchColumn();
230
-	}
231
-
232
-	/**
233
-	 * Returns a list of calendars for a principal.
234
-	 *
235
-	 * Every project is an array with the following keys:
236
-	 *  * id, a unique id that will be used by other functions to modify the
237
-	 *    calendar. This can be the same as the uri or a database key.
238
-	 *  * uri, which the basename of the uri with which the calendar is
239
-	 *    accessed.
240
-	 *  * principaluri. The owner of the calendar. Almost always the same as
241
-	 *    principalUri passed to this method.
242
-	 *
243
-	 * Furthermore it can contain webdav properties in clark notation. A very
244
-	 * common one is '{DAV:}displayname'.
245
-	 *
246
-	 * Many clients also require:
247
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
248
-	 * For this property, you can just return an instance of
249
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
250
-	 *
251
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
252
-	 * ACL will automatically be put in read-only mode.
253
-	 *
254
-	 * @param string $principalUri
255
-	 * @return array
256
-	 */
257
-	function getCalendarsForUser($principalUri) {
258
-		$principalUriOriginal = $principalUri;
259
-		$principalUri = $this->convertPrincipal($principalUri, true);
260
-		$fields = array_values($this->propertyMap);
261
-		$fields[] = 'id';
262
-		$fields[] = 'uri';
263
-		$fields[] = 'synctoken';
264
-		$fields[] = 'components';
265
-		$fields[] = 'principaluri';
266
-		$fields[] = 'transparent';
267
-
268
-		// Making fields a comma-delimited list
269
-		$query = $this->db->getQueryBuilder();
270
-		$query->select($fields)->from('calendars')
271
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
272
-				->orderBy('calendarorder', 'ASC');
273
-		$stmt = $query->execute();
274
-
275
-		$calendars = [];
276
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277
-
278
-			$components = [];
279
-			if ($row['components']) {
280
-				$components = explode(',',$row['components']);
281
-			}
282
-
283
-			$calendar = [
284
-				'id' => $row['id'],
285
-				'uri' => $row['uri'],
286
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
-			];
293
-
294
-			foreach($this->propertyMap as $xmlName=>$dbName) {
295
-				$calendar[$xmlName] = $row[$dbName];
296
-			}
297
-
298
-			$this->addOwnerPrincipal($calendar);
299
-
300
-			if (!isset($calendars[$calendar['id']])) {
301
-				$calendars[$calendar['id']] = $calendar;
302
-			}
303
-		}
304
-
305
-		$stmt->closeCursor();
306
-
307
-		// query for shared calendars
308
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
309
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
310
-
311
-		$principals = array_map(function($principal) {
312
-			return urldecode($principal);
313
-		}, $principals);
314
-		$principals[]= $principalUri;
315
-
316
-		$fields = array_values($this->propertyMap);
317
-		$fields[] = 'a.id';
318
-		$fields[] = 'a.uri';
319
-		$fields[] = 'a.synctoken';
320
-		$fields[] = 'a.components';
321
-		$fields[] = 'a.principaluri';
322
-		$fields[] = 'a.transparent';
323
-		$fields[] = 's.access';
324
-		$query = $this->db->getQueryBuilder();
325
-		$result = $query->select($fields)
326
-			->from('dav_shares', 's')
327
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
328
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
329
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
330
-			->setParameter('type', 'calendar')
331
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332
-			->execute();
333
-
334
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
-		while($row = $result->fetch()) {
336
-			if ($row['principaluri'] === $principalUri) {
337
-				continue;
338
-			}
339
-
340
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
341
-			if (isset($calendars[$row['id']])) {
342
-				if ($readOnly) {
343
-					// New share can not have more permissions then the old one.
344
-					continue;
345
-				}
346
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
347
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
348
-					// Old share is already read-write, no more permissions can be gained
349
-					continue;
350
-				}
351
-			}
352
-
353
-			list(, $name) = Uri\split($row['principaluri']);
354
-			$uri = $row['uri'] . '_shared_by_' . $name;
355
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
356
-			$components = [];
357
-			if ($row['components']) {
358
-				$components = explode(',',$row['components']);
359
-			}
360
-			$calendar = [
361
-				'id' => $row['id'],
362
-				'uri' => $uri,
363
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369
-				$readOnlyPropertyName => $readOnly,
370
-			];
371
-
372
-			foreach($this->propertyMap as $xmlName=>$dbName) {
373
-				$calendar[$xmlName] = $row[$dbName];
374
-			}
375
-
376
-			$this->addOwnerPrincipal($calendar);
377
-
378
-			$calendars[$calendar['id']] = $calendar;
379
-		}
380
-		$result->closeCursor();
381
-
382
-		return array_values($calendars);
383
-	}
384
-
385
-	/**
386
-	 * @param $principalUri
387
-	 * @return array
388
-	 */
389
-	public function getUsersOwnCalendars($principalUri) {
390
-		$principalUri = $this->convertPrincipal($principalUri, true);
391
-		$fields = array_values($this->propertyMap);
392
-		$fields[] = 'id';
393
-		$fields[] = 'uri';
394
-		$fields[] = 'synctoken';
395
-		$fields[] = 'components';
396
-		$fields[] = 'principaluri';
397
-		$fields[] = 'transparent';
398
-		// Making fields a comma-delimited list
399
-		$query = $this->db->getQueryBuilder();
400
-		$query->select($fields)->from('calendars')
401
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
402
-			->orderBy('calendarorder', 'ASC');
403
-		$stmt = $query->execute();
404
-		$calendars = [];
405
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406
-			$components = [];
407
-			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
409
-			}
410
-			$calendar = [
411
-				'id' => $row['id'],
412
-				'uri' => $row['uri'],
413
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
-			];
419
-			foreach($this->propertyMap as $xmlName=>$dbName) {
420
-				$calendar[$xmlName] = $row[$dbName];
421
-			}
422
-
423
-			$this->addOwnerPrincipal($calendar);
424
-
425
-			if (!isset($calendars[$calendar['id']])) {
426
-				$calendars[$calendar['id']] = $calendar;
427
-			}
428
-		}
429
-		$stmt->closeCursor();
430
-		return array_values($calendars);
431
-	}
432
-
433
-
434
-	/**
435
-	 * @param $uid
436
-	 * @return string
437
-	 */
438
-	private function getUserDisplayName($uid) {
439
-		if (!isset($this->userDisplayNames[$uid])) {
440
-			$user = $this->userManager->get($uid);
441
-
442
-			if ($user instanceof IUser) {
443
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
444
-			} else {
445
-				$this->userDisplayNames[$uid] = $uid;
446
-			}
447
-		}
448
-
449
-		return $this->userDisplayNames[$uid];
450
-	}
451
-
452
-	/**
453
-	 * @return array
454
-	 */
455
-	public function getPublicCalendars() {
456
-		$fields = array_values($this->propertyMap);
457
-		$fields[] = 'a.id';
458
-		$fields[] = 'a.uri';
459
-		$fields[] = 'a.synctoken';
460
-		$fields[] = 'a.components';
461
-		$fields[] = 'a.principaluri';
462
-		$fields[] = 'a.transparent';
463
-		$fields[] = 's.access';
464
-		$fields[] = 's.publicuri';
465
-		$calendars = [];
466
-		$query = $this->db->getQueryBuilder();
467
-		$result = $query->select($fields)
468
-			->from('dav_shares', 's')
469
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
470
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
471
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472
-			->execute();
473
-
474
-		while($row = $result->fetch()) {
475
-			list(, $name) = Uri\split($row['principaluri']);
476
-			$row['displayname'] = $row['displayname'] . "($name)";
477
-			$components = [];
478
-			if ($row['components']) {
479
-				$components = explode(',',$row['components']);
480
-			}
481
-			$calendar = [
482
-				'id' => $row['id'],
483
-				'uri' => $row['publicuri'],
484
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
492
-			];
493
-
494
-			foreach($this->propertyMap as $xmlName=>$dbName) {
495
-				$calendar[$xmlName] = $row[$dbName];
496
-			}
497
-
498
-			$this->addOwnerPrincipal($calendar);
499
-
500
-			if (!isset($calendars[$calendar['id']])) {
501
-				$calendars[$calendar['id']] = $calendar;
502
-			}
503
-		}
504
-		$result->closeCursor();
505
-
506
-		return array_values($calendars);
507
-	}
508
-
509
-	/**
510
-	 * @param string $uri
511
-	 * @return array
512
-	 * @throws NotFound
513
-	 */
514
-	public function getPublicCalendar($uri) {
515
-		$fields = array_values($this->propertyMap);
516
-		$fields[] = 'a.id';
517
-		$fields[] = 'a.uri';
518
-		$fields[] = 'a.synctoken';
519
-		$fields[] = 'a.components';
520
-		$fields[] = 'a.principaluri';
521
-		$fields[] = 'a.transparent';
522
-		$fields[] = 's.access';
523
-		$fields[] = 's.publicuri';
524
-		$query = $this->db->getQueryBuilder();
525
-		$result = $query->select($fields)
526
-			->from('dav_shares', 's')
527
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
528
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
529
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
530
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
531
-			->execute();
532
-
533
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
534
-
535
-		$result->closeCursor();
536
-
537
-		if ($row === false) {
538
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
539
-		}
540
-
541
-		list(, $name) = Uri\split($row['principaluri']);
542
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
543
-		$components = [];
544
-		if ($row['components']) {
545
-			$components = explode(',',$row['components']);
546
-		}
547
-		$calendar = [
548
-			'id' => $row['id'],
549
-			'uri' => $row['publicuri'],
550
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
558
-		];
559
-
560
-		foreach($this->propertyMap as $xmlName=>$dbName) {
561
-			$calendar[$xmlName] = $row[$dbName];
562
-		}
563
-
564
-		$this->addOwnerPrincipal($calendar);
565
-
566
-		return $calendar;
567
-
568
-	}
569
-
570
-	/**
571
-	 * @param string $principal
572
-	 * @param string $uri
573
-	 * @return array|null
574
-	 */
575
-	public function getCalendarByUri($principal, $uri) {
576
-		$fields = array_values($this->propertyMap);
577
-		$fields[] = 'id';
578
-		$fields[] = 'uri';
579
-		$fields[] = 'synctoken';
580
-		$fields[] = 'components';
581
-		$fields[] = 'principaluri';
582
-		$fields[] = 'transparent';
583
-
584
-		// Making fields a comma-delimited list
585
-		$query = $this->db->getQueryBuilder();
586
-		$query->select($fields)->from('calendars')
587
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
588
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
589
-			->setMaxResults(1);
590
-		$stmt = $query->execute();
591
-
592
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
593
-		$stmt->closeCursor();
594
-		if ($row === false) {
595
-			return null;
596
-		}
597
-
598
-		$components = [];
599
-		if ($row['components']) {
600
-			$components = explode(',',$row['components']);
601
-		}
602
-
603
-		$calendar = [
604
-			'id' => $row['id'],
605
-			'uri' => $row['uri'],
606
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
611
-		];
612
-
613
-		foreach($this->propertyMap as $xmlName=>$dbName) {
614
-			$calendar[$xmlName] = $row[$dbName];
615
-		}
616
-
617
-		$this->addOwnerPrincipal($calendar);
618
-
619
-		return $calendar;
620
-	}
621
-
622
-	/**
623
-	 * @param $calendarId
624
-	 * @return array|null
625
-	 */
626
-	public function getCalendarById($calendarId) {
627
-		$fields = array_values($this->propertyMap);
628
-		$fields[] = 'id';
629
-		$fields[] = 'uri';
630
-		$fields[] = 'synctoken';
631
-		$fields[] = 'components';
632
-		$fields[] = 'principaluri';
633
-		$fields[] = 'transparent';
634
-
635
-		// Making fields a comma-delimited list
636
-		$query = $this->db->getQueryBuilder();
637
-		$query->select($fields)->from('calendars')
638
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
639
-			->setMaxResults(1);
640
-		$stmt = $query->execute();
641
-
642
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
643
-		$stmt->closeCursor();
644
-		if ($row === false) {
645
-			return null;
646
-		}
647
-
648
-		$components = [];
649
-		if ($row['components']) {
650
-			$components = explode(',',$row['components']);
651
-		}
652
-
653
-		$calendar = [
654
-			'id' => $row['id'],
655
-			'uri' => $row['uri'],
656
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
661
-		];
662
-
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
664
-			$calendar[$xmlName] = $row[$dbName];
665
-		}
666
-
667
-		$this->addOwnerPrincipal($calendar);
668
-
669
-		return $calendar;
670
-	}
671
-
672
-	/**
673
-	 * @param $subscriptionId
674
-	 */
675
-	public function getSubscriptionById($subscriptionId) {
676
-		$fields = array_values($this->subscriptionPropertyMap);
677
-		$fields[] = 'id';
678
-		$fields[] = 'uri';
679
-		$fields[] = 'source';
680
-		$fields[] = 'synctoken';
681
-		$fields[] = 'principaluri';
682
-		$fields[] = 'lastmodified';
683
-
684
-		$query = $this->db->getQueryBuilder();
685
-		$query->select($fields)
686
-			->from('calendarsubscriptions')
687
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688
-			->orderBy('calendarorder', 'asc');
689
-		$stmt =$query->execute();
690
-
691
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
692
-		$stmt->closeCursor();
693
-		if ($row === false) {
694
-			return null;
695
-		}
696
-
697
-		$subscription = [
698
-			'id'           => $row['id'],
699
-			'uri'          => $row['uri'],
700
-			'principaluri' => $row['principaluri'],
701
-			'source'       => $row['source'],
702
-			'lastmodified' => $row['lastmodified'],
703
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
705
-		];
706
-
707
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708
-			if (!is_null($row[$dbName])) {
709
-				$subscription[$xmlName] = $row[$dbName];
710
-			}
711
-		}
712
-
713
-		return $subscription;
714
-	}
715
-
716
-	/**
717
-	 * Creates a new calendar for a principal.
718
-	 *
719
-	 * If the creation was a success, an id must be returned that can be used to reference
720
-	 * this calendar in other methods, such as updateCalendar.
721
-	 *
722
-	 * @param string $principalUri
723
-	 * @param string $calendarUri
724
-	 * @param array $properties
725
-	 * @return int
726
-	 * @suppress SqlInjectionChecker
727
-	 */
728
-	function createCalendar($principalUri, $calendarUri, array $properties) {
729
-		$values = [
730
-			'principaluri' => $this->convertPrincipal($principalUri, true),
731
-			'uri'          => $calendarUri,
732
-			'synctoken'    => 1,
733
-			'transparent'  => 0,
734
-			'components'   => 'VEVENT,VTODO',
735
-			'displayname'  => $calendarUri
736
-		];
737
-
738
-		// Default value
739
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740
-		if (isset($properties[$sccs])) {
741
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743
-			}
744
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
745
-		} else if (isset($properties['components'])) {
746
-			// Allow to provide components internally without having
747
-			// to create a SupportedCalendarComponentSet object
748
-			$values['components'] = $properties['components'];
749
-		}
750
-
751
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
752
-		if (isset($properties[$transp])) {
753
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754
-		}
755
-
756
-		foreach($this->propertyMap as $xmlName=>$dbName) {
757
-			if (isset($properties[$xmlName])) {
758
-				$values[$dbName] = $properties[$xmlName];
759
-			}
760
-		}
761
-
762
-		$query = $this->db->getQueryBuilder();
763
-		$query->insert('calendars');
764
-		foreach($values as $column => $value) {
765
-			$query->setValue($column, $query->createNamedParameter($value));
766
-		}
767
-		$query->execute();
768
-		$calendarId = $query->getLastInsertId();
769
-
770
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
771
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
772
-			[
773
-				'calendarId' => $calendarId,
774
-				'calendarData' => $this->getCalendarById($calendarId),
775
-			]));
776
-
777
-		return $calendarId;
778
-	}
779
-
780
-	/**
781
-	 * Updates properties for a calendar.
782
-	 *
783
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
784
-	 * To do the actual updates, you must tell this object which properties
785
-	 * you're going to process with the handle() method.
786
-	 *
787
-	 * Calling the handle method is like telling the PropPatch object "I
788
-	 * promise I can handle updating this property".
789
-	 *
790
-	 * Read the PropPatch documentation for more info and examples.
791
-	 *
792
-	 * @param mixed $calendarId
793
-	 * @param PropPatch $propPatch
794
-	 * @return void
795
-	 */
796
-	function updateCalendar($calendarId, PropPatch $propPatch) {
797
-		$supportedProperties = array_keys($this->propertyMap);
798
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
799
-
800
-		/**
801
-		 * @suppress SqlInjectionChecker
802
-		 */
803
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
804
-			$newValues = [];
805
-			foreach ($mutations as $propertyName => $propertyValue) {
806
-
807
-				switch ($propertyName) {
808
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
809
-						$fieldName = 'transparent';
810
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811
-						break;
812
-					default :
813
-						$fieldName = $this->propertyMap[$propertyName];
814
-						$newValues[$fieldName] = $propertyValue;
815
-						break;
816
-				}
817
-
818
-			}
819
-			$query = $this->db->getQueryBuilder();
820
-			$query->update('calendars');
821
-			foreach ($newValues as $fieldName => $value) {
822
-				$query->set($fieldName, $query->createNamedParameter($value));
823
-			}
824
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
825
-			$query->execute();
826
-
827
-			$this->addChange($calendarId, "", 2);
828
-
829
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
830
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
831
-				[
832
-					'calendarId' => $calendarId,
833
-					'calendarData' => $this->getCalendarById($calendarId),
834
-					'shares' => $this->getShares($calendarId),
835
-					'propertyMutations' => $mutations,
836
-				]));
837
-
838
-			return true;
839
-		});
840
-	}
841
-
842
-	/**
843
-	 * Delete a calendar and all it's objects
844
-	 *
845
-	 * @param mixed $calendarId
846
-	 * @return void
847
-	 */
848
-	function deleteCalendar($calendarId) {
849
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
850
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
851
-			[
852
-				'calendarId' => $calendarId,
853
-				'calendarData' => $this->getCalendarById($calendarId),
854
-				'shares' => $this->getShares($calendarId),
855
-			]));
856
-
857
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
858
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
859
-
860
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
861
-		$stmt->execute([$calendarId]);
862
-
863
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
864
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
865
-
866
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
867
-
868
-		$query = $this->db->getQueryBuilder();
869
-		$query->delete($this->dbObjectPropertiesTable)
870
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
871
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
872
-			->execute();
873
-	}
874
-
875
-	/**
876
-	 * Delete all of an user's shares
877
-	 *
878
-	 * @param string $principaluri
879
-	 * @return void
880
-	 */
881
-	function deleteAllSharesByUser($principaluri) {
882
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
883
-	}
884
-
885
-	/**
886
-	 * Returns all calendar objects within a calendar.
887
-	 *
888
-	 * Every item contains an array with the following keys:
889
-	 *   * calendardata - The iCalendar-compatible calendar data
890
-	 *   * uri - a unique key which will be used to construct the uri. This can
891
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
892
-	 *     good idea. This is only the basename, or filename, not the full
893
-	 *     path.
894
-	 *   * lastmodified - a timestamp of the last modification time
895
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
896
-	 *   '"abcdef"')
897
-	 *   * size - The size of the calendar objects, in bytes.
898
-	 *   * component - optional, a string containing the type of object, such
899
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
900
-	 *     the Content-Type header.
901
-	 *
902
-	 * Note that the etag is optional, but it's highly encouraged to return for
903
-	 * speed reasons.
904
-	 *
905
-	 * The calendardata is also optional. If it's not returned
906
-	 * 'getCalendarObject' will be called later, which *is* expected to return
907
-	 * calendardata.
908
-	 *
909
-	 * If neither etag or size are specified, the calendardata will be
910
-	 * used/fetched to determine these numbers. If both are specified the
911
-	 * amount of times this is needed is reduced by a great degree.
912
-	 *
913
-	 * @param mixed $id
914
-	 * @param int $calendarType
915
-	 * @return array
916
-	 */
917
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
918
-		$query = $this->db->getQueryBuilder();
919
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920
-			->from('calendarobjects')
921
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
922
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
923
-		$stmt = $query->execute();
924
-
925
-		$result = [];
926
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927
-			$result[] = [
928
-				'id'           => $row['id'],
929
-				'uri'          => $row['uri'],
930
-				'lastmodified' => $row['lastmodified'],
931
-				'etag'         => '"' . $row['etag'] . '"',
932
-				'calendarid'   => $row['calendarid'],
933
-				'size'         => (int)$row['size'],
934
-				'component'    => strtolower($row['componenttype']),
935
-				'classification'=> (int)$row['classification']
936
-			];
937
-		}
938
-
939
-		return $result;
940
-	}
941
-
942
-	/**
943
-	 * Returns information from a single calendar object, based on it's object
944
-	 * uri.
945
-	 *
946
-	 * The object uri is only the basename, or filename and not a full path.
947
-	 *
948
-	 * The returned array must have the same keys as getCalendarObjects. The
949
-	 * 'calendardata' object is required here though, while it's not required
950
-	 * for getCalendarObjects.
951
-	 *
952
-	 * This method must return null if the object did not exist.
953
-	 *
954
-	 * @param mixed $id
955
-	 * @param string $objectUri
956
-	 * @param int $calendarType
957
-	 * @return array|null
958
-	 */
959
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
960
-		$query = $this->db->getQueryBuilder();
961
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962
-			->from('calendarobjects')
963
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
964
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
965
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
966
-		$stmt = $query->execute();
967
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
968
-
969
-		if(!$row) {
970
-			return null;
971
-		}
972
-
973
-		return [
974
-			'id'            => $row['id'],
975
-			'uri'           => $row['uri'],
976
-			'lastmodified'  => $row['lastmodified'],
977
-			'etag'          => '"' . $row['etag'] . '"',
978
-			'calendarid'    => $row['calendarid'],
979
-			'size'          => (int)$row['size'],
980
-			'calendardata'  => $this->readBlob($row['calendardata']),
981
-			'component'     => strtolower($row['componenttype']),
982
-			'classification'=> (int)$row['classification']
983
-		];
984
-	}
985
-
986
-	/**
987
-	 * Returns a list of calendar objects.
988
-	 *
989
-	 * This method should work identical to getCalendarObject, but instead
990
-	 * return all the calendar objects in the list as an array.
991
-	 *
992
-	 * If the backend supports this, it may allow for some speed-ups.
993
-	 *
994
-	 * @param mixed $calendarId
995
-	 * @param string[] $uris
996
-	 * @param int $calendarType
997
-	 * @return array
998
-	 */
999
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1000
-		if (empty($uris)) {
1001
-			return [];
1002
-		}
1003
-
1004
-		$chunks = array_chunk($uris, 100);
1005
-		$objects = [];
1006
-
1007
-		$query = $this->db->getQueryBuilder();
1008
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1009
-			->from('calendarobjects')
1010
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1011
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1012
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1013
-
1014
-		foreach ($chunks as $uris) {
1015
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1016
-			$result = $query->execute();
1017
-
1018
-			while ($row = $result->fetch()) {
1019
-				$objects[] = [
1020
-					'id'           => $row['id'],
1021
-					'uri'          => $row['uri'],
1022
-					'lastmodified' => $row['lastmodified'],
1023
-					'etag'         => '"' . $row['etag'] . '"',
1024
-					'calendarid'   => $row['calendarid'],
1025
-					'size'         => (int)$row['size'],
1026
-					'calendardata' => $this->readBlob($row['calendardata']),
1027
-					'component'    => strtolower($row['componenttype']),
1028
-					'classification' => (int)$row['classification']
1029
-				];
1030
-			}
1031
-			$result->closeCursor();
1032
-		}
1033
-
1034
-		return $objects;
1035
-	}
1036
-
1037
-	/**
1038
-	 * Creates a new calendar object.
1039
-	 *
1040
-	 * The object uri is only the basename, or filename and not a full path.
1041
-	 *
1042
-	 * It is possible return an etag from this function, which will be used in
1043
-	 * the response to this PUT request. Note that the ETag must be surrounded
1044
-	 * by double-quotes.
1045
-	 *
1046
-	 * However, you should only really return this ETag if you don't mangle the
1047
-	 * calendar-data. If the result of a subsequent GET to this object is not
1048
-	 * the exact same as this request body, you should omit the ETag.
1049
-	 *
1050
-	 * @param mixed $calendarId
1051
-	 * @param string $objectUri
1052
-	 * @param string $calendarData
1053
-	 * @param int $calendarType
1054
-	 * @return string
1055
-	 */
1056
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1057
-		$extraData = $this->getDenormalizedData($calendarData);
1058
-
1059
-		$q = $this->db->getQueryBuilder();
1060
-		$q->select($q->func()->count('*'))
1061
-			->from('calendarobjects')
1062
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1063
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1064
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1065
-
1066
-		$result = $q->execute();
1067
-		$count = (int) $result->fetchColumn();
1068
-		$result->closeCursor();
1069
-
1070
-		if ($count !== 0) {
1071
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1072
-		}
1073
-
1074
-		$query = $this->db->getQueryBuilder();
1075
-		$query->insert('calendarobjects')
1076
-			->values([
1077
-				'calendarid' => $query->createNamedParameter($calendarId),
1078
-				'uri' => $query->createNamedParameter($objectUri),
1079
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1080
-				'lastmodified' => $query->createNamedParameter(time()),
1081
-				'etag' => $query->createNamedParameter($extraData['etag']),
1082
-				'size' => $query->createNamedParameter($extraData['size']),
1083
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1084
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1085
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1086
-				'classification' => $query->createNamedParameter($extraData['classification']),
1087
-				'uid' => $query->createNamedParameter($extraData['uid']),
1088
-				'calendartype' => $query->createNamedParameter($calendarType),
1089
-			])
1090
-			->execute();
1091
-
1092
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1093
-
1094
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1095
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1096
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1097
-				[
1098
-					'calendarId' => $calendarId,
1099
-					'calendarData' => $this->getCalendarById($calendarId),
1100
-					'shares' => $this->getShares($calendarId),
1101
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1102
-				]
1103
-			));
1104
-		} else {
1105
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1106
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1107
-				[
1108
-					'subscriptionId' => $calendarId,
1109
-					'calendarData' => $this->getCalendarById($calendarId),
1110
-					'shares' => $this->getShares($calendarId),
1111
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1112
-				]
1113
-			));
1114
-		}
1115
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1116
-
1117
-		return '"' . $extraData['etag'] . '"';
1118
-	}
1119
-
1120
-	/**
1121
-	 * Updates an existing calendarobject, based on it's uri.
1122
-	 *
1123
-	 * The object uri is only the basename, or filename and not a full path.
1124
-	 *
1125
-	 * It is possible return an etag from this function, which will be used in
1126
-	 * the response to this PUT request. Note that the ETag must be surrounded
1127
-	 * by double-quotes.
1128
-	 *
1129
-	 * However, you should only really return this ETag if you don't mangle the
1130
-	 * calendar-data. If the result of a subsequent GET to this object is not
1131
-	 * the exact same as this request body, you should omit the ETag.
1132
-	 *
1133
-	 * @param mixed $calendarId
1134
-	 * @param string $objectUri
1135
-	 * @param string $calendarData
1136
-	 * @param int $calendarType
1137
-	 * @return string
1138
-	 */
1139
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1140
-		$extraData = $this->getDenormalizedData($calendarData);
1141
-		$query = $this->db->getQueryBuilder();
1142
-		$query->update('calendarobjects')
1143
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1144
-				->set('lastmodified', $query->createNamedParameter(time()))
1145
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1146
-				->set('size', $query->createNamedParameter($extraData['size']))
1147
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1148
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1149
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1150
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1151
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1152
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1155
-			->execute();
1156
-
1157
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1158
-
1159
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1160
-		if (is_array($data)) {
1161
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1162
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1163
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1164
-					[
1165
-						'calendarId' => $calendarId,
1166
-						'calendarData' => $this->getCalendarById($calendarId),
1167
-						'shares' => $this->getShares($calendarId),
1168
-						'objectData' => $data,
1169
-					]
1170
-				));
1171
-			} else {
1172
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1173
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1174
-					[
1175
-						'subscriptionId' => $calendarId,
1176
-						'calendarData' => $this->getCalendarById($calendarId),
1177
-						'shares' => $this->getShares($calendarId),
1178
-						'objectData' => $data,
1179
-					]
1180
-				));
1181
-			}
1182
-		}
1183
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1184
-
1185
-		return '"' . $extraData['etag'] . '"';
1186
-	}
1187
-
1188
-	/**
1189
-	 * @param int $calendarObjectId
1190
-	 * @param int $classification
1191
-	 */
1192
-	public function setClassification($calendarObjectId, $classification) {
1193
-		if (!in_array($classification, [
1194
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1195
-		])) {
1196
-			throw new \InvalidArgumentException();
1197
-		}
1198
-		$query = $this->db->getQueryBuilder();
1199
-		$query->update('calendarobjects')
1200
-			->set('classification', $query->createNamedParameter($classification))
1201
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1202
-			->execute();
1203
-	}
1204
-
1205
-	/**
1206
-	 * Deletes an existing calendar object.
1207
-	 *
1208
-	 * The object uri is only the basename, or filename and not a full path.
1209
-	 *
1210
-	 * @param mixed $calendarId
1211
-	 * @param string $objectUri
1212
-	 * @param int $calendarType
1213
-	 * @return void
1214
-	 */
1215
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1216
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217
-		if (is_array($data)) {
1218
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1219
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1220
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1221
-					[
1222
-						'calendarId' => $calendarId,
1223
-						'calendarData' => $this->getCalendarById($calendarId),
1224
-						'shares' => $this->getShares($calendarId),
1225
-						'objectData' => $data,
1226
-					]
1227
-				));
1228
-			} else {
1229
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1230
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1231
-					[
1232
-						'subscriptionId' => $calendarId,
1233
-						'calendarData' => $this->getCalendarById($calendarId),
1234
-						'shares' => $this->getShares($calendarId),
1235
-						'objectData' => $data,
1236
-					]
1237
-				));
1238
-			}
1239
-		}
1240
-
1241
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1242
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1243
-
1244
-		if (is_array($data)) {
1245
-			$this->purgeProperties($calendarId, $data['id'], $calendarType);
1246
-		}
1247
-
1248
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1249
-	}
1250
-
1251
-	/**
1252
-	 * Performs a calendar-query on the contents of this calendar.
1253
-	 *
1254
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1255
-	 * calendar-query it is possible for a client to request a specific set of
1256
-	 * object, based on contents of iCalendar properties, date-ranges and
1257
-	 * iCalendar component types (VTODO, VEVENT).
1258
-	 *
1259
-	 * This method should just return a list of (relative) urls that match this
1260
-	 * query.
1261
-	 *
1262
-	 * The list of filters are specified as an array. The exact array is
1263
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1264
-	 *
1265
-	 * Note that it is extremely likely that getCalendarObject for every path
1266
-	 * returned from this method will be called almost immediately after. You
1267
-	 * may want to anticipate this to speed up these requests.
1268
-	 *
1269
-	 * This method provides a default implementation, which parses *all* the
1270
-	 * iCalendar objects in the specified calendar.
1271
-	 *
1272
-	 * This default may well be good enough for personal use, and calendars
1273
-	 * that aren't very large. But if you anticipate high usage, big calendars
1274
-	 * or high loads, you are strongly advised to optimize certain paths.
1275
-	 *
1276
-	 * The best way to do so is override this method and to optimize
1277
-	 * specifically for 'common filters'.
1278
-	 *
1279
-	 * Requests that are extremely common are:
1280
-	 *   * requests for just VEVENTS
1281
-	 *   * requests for just VTODO
1282
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1283
-	 *
1284
-	 * ..and combinations of these requests. It may not be worth it to try to
1285
-	 * handle every possible situation and just rely on the (relatively
1286
-	 * easy to use) CalendarQueryValidator to handle the rest.
1287
-	 *
1288
-	 * Note that especially time-range-filters may be difficult to parse. A
1289
-	 * time-range filter specified on a VEVENT must for instance also handle
1290
-	 * recurrence rules correctly.
1291
-	 * A good example of how to interprete all these filters can also simply
1292
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1293
-	 * as possible, so it gives you a good idea on what type of stuff you need
1294
-	 * to think of.
1295
-	 *
1296
-	 * @param mixed $id
1297
-	 * @param array $filters
1298
-	 * @param int $calendarType
1299
-	 * @return array
1300
-	 */
1301
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1302
-		$componentType = null;
1303
-		$requirePostFilter = true;
1304
-		$timeRange = null;
1305
-
1306
-		// if no filters were specified, we don't need to filter after a query
1307
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1308
-			$requirePostFilter = false;
1309
-		}
1310
-
1311
-		// Figuring out if there's a component filter
1312
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1313
-			$componentType = $filters['comp-filters'][0]['name'];
1314
-
1315
-			// Checking if we need post-filters
1316
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1317
-				$requirePostFilter = false;
1318
-			}
1319
-			// There was a time-range filter
1320
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1321
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1322
-
1323
-				// If start time OR the end time is not specified, we can do a
1324
-				// 100% accurate mysql query.
1325
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1326
-					$requirePostFilter = false;
1327
-				}
1328
-			}
1329
-
1330
-		}
1331
-		$columns = ['uri'];
1332
-		if ($requirePostFilter) {
1333
-			$columns = ['uri', 'calendardata'];
1334
-		}
1335
-		$query = $this->db->getQueryBuilder();
1336
-		$query->select($columns)
1337
-			->from('calendarobjects')
1338
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1339
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1340
-
1341
-		if ($componentType) {
1342
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1343
-		}
1344
-
1345
-		if ($timeRange && $timeRange['start']) {
1346
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1347
-		}
1348
-		if ($timeRange && $timeRange['end']) {
1349
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1350
-		}
1351
-
1352
-		$stmt = $query->execute();
1353
-
1354
-		$result = [];
1355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
-			if ($requirePostFilter) {
1357
-				// validateFilterForObject will parse the calendar data
1358
-				// catch parsing errors
1359
-				try {
1360
-					$matches = $this->validateFilterForObject($row, $filters);
1361
-				} catch(ParseException $ex) {
1362
-					$this->logger->logException($ex, [
1363
-						'app' => 'dav',
1364
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1365
-					]);
1366
-					continue;
1367
-				} catch (InvalidDataException $ex) {
1368
-					$this->logger->logException($ex, [
1369
-						'app' => 'dav',
1370
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1371
-					]);
1372
-					continue;
1373
-				}
1374
-
1375
-				if (!$matches) {
1376
-					continue;
1377
-				}
1378
-			}
1379
-			$result[] = $row['uri'];
1380
-		}
1381
-
1382
-		return $result;
1383
-	}
1384
-
1385
-	/**
1386
-	 * custom Nextcloud search extension for CalDAV
1387
-	 *
1388
-	 * TODO - this should optionally cover cached calendar objects as well
1389
-	 *
1390
-	 * @param string $principalUri
1391
-	 * @param array $filters
1392
-	 * @param integer|null $limit
1393
-	 * @param integer|null $offset
1394
-	 * @return array
1395
-	 */
1396
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1397
-		$calendars = $this->getCalendarsForUser($principalUri);
1398
-		$ownCalendars = [];
1399
-		$sharedCalendars = [];
1400
-
1401
-		$uriMapper = [];
1402
-
1403
-		foreach($calendars as $calendar) {
1404
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405
-				$ownCalendars[] = $calendar['id'];
1406
-			} else {
1407
-				$sharedCalendars[] = $calendar['id'];
1408
-			}
1409
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1410
-		}
1411
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1412
-			return [];
1413
-		}
1414
-
1415
-		$query = $this->db->getQueryBuilder();
1416
-		// Calendar id expressions
1417
-		$calendarExpressions = [];
1418
-		foreach($ownCalendars as $id) {
1419
-			$calendarExpressions[] = $query->expr()->andX(
1420
-				$query->expr()->eq('c.calendarid',
1421
-					$query->createNamedParameter($id)),
1422
-				$query->expr()->eq('c.calendartype',
1423
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
-		}
1425
-		foreach($sharedCalendars as $id) {
1426
-			$calendarExpressions[] = $query->expr()->andX(
1427
-				$query->expr()->eq('c.calendarid',
1428
-					$query->createNamedParameter($id)),
1429
-				$query->expr()->eq('c.classification',
1430
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1431
-				$query->expr()->eq('c.calendartype',
1432
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1433
-		}
1434
-
1435
-		if (count($calendarExpressions) === 1) {
1436
-			$calExpr = $calendarExpressions[0];
1437
-		} else {
1438
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1439
-		}
1440
-
1441
-		// Component expressions
1442
-		$compExpressions = [];
1443
-		foreach($filters['comps'] as $comp) {
1444
-			$compExpressions[] = $query->expr()
1445
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1446
-		}
1447
-
1448
-		if (count($compExpressions) === 1) {
1449
-			$compExpr = $compExpressions[0];
1450
-		} else {
1451
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1452
-		}
1453
-
1454
-		if (!isset($filters['props'])) {
1455
-			$filters['props'] = [];
1456
-		}
1457
-		if (!isset($filters['params'])) {
1458
-			$filters['params'] = [];
1459
-		}
1460
-
1461
-		$propParamExpressions = [];
1462
-		foreach($filters['props'] as $prop) {
1463
-			$propParamExpressions[] = $query->expr()->andX(
1464
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465
-				$query->expr()->isNull('i.parameter')
1466
-			);
1467
-		}
1468
-		foreach($filters['params'] as $param) {
1469
-			$propParamExpressions[] = $query->expr()->andX(
1470
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1472
-			);
1473
-		}
1474
-
1475
-		if (count($propParamExpressions) === 1) {
1476
-			$propParamExpr = $propParamExpressions[0];
1477
-		} else {
1478
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1479
-		}
1480
-
1481
-		$query->select(['c.calendarid', 'c.uri'])
1482
-			->from($this->dbObjectPropertiesTable, 'i')
1483
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1484
-			->where($calExpr)
1485
-			->andWhere($compExpr)
1486
-			->andWhere($propParamExpr)
1487
-			->andWhere($query->expr()->iLike('i.value',
1488
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1489
-
1490
-		if ($offset) {
1491
-			$query->setFirstResult($offset);
1492
-		}
1493
-		if ($limit) {
1494
-			$query->setMaxResults($limit);
1495
-		}
1496
-
1497
-		$stmt = $query->execute();
1498
-
1499
-		$result = [];
1500
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1502
-			if (!in_array($path, $result)) {
1503
-				$result[] = $path;
1504
-			}
1505
-		}
1506
-
1507
-		return $result;
1508
-	}
1509
-
1510
-	/**
1511
-	 * used for Nextcloud's calendar API
1512
-	 *
1513
-	 * @param array $calendarInfo
1514
-	 * @param string $pattern
1515
-	 * @param array $searchProperties
1516
-	 * @param array $options
1517
-	 * @param integer|null $limit
1518
-	 * @param integer|null $offset
1519
-	 *
1520
-	 * @return array
1521
-	 */
1522
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1523
-						   array $options, $limit, $offset) {
1524
-		$outerQuery = $this->db->getQueryBuilder();
1525
-		$innerQuery = $this->db->getQueryBuilder();
1526
-
1527
-		$innerQuery->selectDistinct('op.objectid')
1528
-			->from($this->dbObjectPropertiesTable, 'op')
1529
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1530
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1531
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1532
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1533
-
1534
-		// only return public items for shared calendars for now
1535
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1536
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1537
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1538
-		}
1539
-
1540
-		$or = $innerQuery->expr()->orX();
1541
-		foreach($searchProperties as $searchProperty) {
1542
-			$or->add($innerQuery->expr()->eq('op.name',
1543
-				$outerQuery->createNamedParameter($searchProperty)));
1544
-		}
1545
-		$innerQuery->andWhere($or);
1546
-
1547
-		if ($pattern !== '') {
1548
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
-				$outerQuery->createNamedParameter('%' .
1550
-					$this->db->escapeLikeParameter($pattern) . '%')));
1551
-		}
1552
-
1553
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1554
-			->from('calendarobjects', 'c');
1555
-
1556
-		if (isset($options['timerange'])) {
1557
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1558
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1559
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1560
-
1561
-			}
1562
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1563
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1564
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1565
-			}
1566
-		}
1567
-
1568
-		if (isset($options['types'])) {
1569
-			$or = $outerQuery->expr()->orX();
1570
-			foreach($options['types'] as $type) {
1571
-				$or->add($outerQuery->expr()->eq('componenttype',
1572
-					$outerQuery->createNamedParameter($type)));
1573
-			}
1574
-			$outerQuery->andWhere($or);
1575
-		}
1576
-
1577
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1578
-			$outerQuery->createFunction($innerQuery->getSQL())));
1579
-
1580
-		if ($offset) {
1581
-			$outerQuery->setFirstResult($offset);
1582
-		}
1583
-		if ($limit) {
1584
-			$outerQuery->setMaxResults($limit);
1585
-		}
1586
-
1587
-		$result = $outerQuery->execute();
1588
-		$calendarObjects = $result->fetchAll();
1589
-
1590
-		return array_map(function($o) {
1591
-			$calendarData = Reader::read($o['calendardata']);
1592
-			$comps = $calendarData->getComponents();
1593
-			$objects = [];
1594
-			$timezones = [];
1595
-			foreach($comps as $comp) {
1596
-				if ($comp instanceof VTimeZone) {
1597
-					$timezones[] = $comp;
1598
-				} else {
1599
-					$objects[] = $comp;
1600
-				}
1601
-			}
1602
-
1603
-			return [
1604
-				'id' => $o['id'],
1605
-				'type' => $o['componenttype'],
1606
-				'uid' => $o['uid'],
1607
-				'uri' => $o['uri'],
1608
-				'objects' => array_map(function($c) {
1609
-					return $this->transformSearchData($c);
1610
-				}, $objects),
1611
-				'timezones' => array_map(function($c) {
1612
-					return $this->transformSearchData($c);
1613
-				}, $timezones),
1614
-			];
1615
-		}, $calendarObjects);
1616
-	}
1617
-
1618
-	/**
1619
-	 * @param Component $comp
1620
-	 * @return array
1621
-	 */
1622
-	private function transformSearchData(Component $comp) {
1623
-		$data = [];
1624
-		/** @var Component[] $subComponents */
1625
-		$subComponents = $comp->getComponents();
1626
-		/** @var Property[] $properties */
1627
-		$properties = array_filter($comp->children(), function($c) {
1628
-			return $c instanceof Property;
1629
-		});
1630
-		$validationRules = $comp->getValidationRules();
1631
-
1632
-		foreach($subComponents as $subComponent) {
1633
-			$name = $subComponent->name;
1634
-			if (!isset($data[$name])) {
1635
-				$data[$name] = [];
1636
-			}
1637
-			$data[$name][] = $this->transformSearchData($subComponent);
1638
-		}
1639
-
1640
-		foreach($properties as $property) {
1641
-			$name = $property->name;
1642
-			if (!isset($validationRules[$name])) {
1643
-				$validationRules[$name] = '*';
1644
-			}
1645
-
1646
-			$rule = $validationRules[$property->name];
1647
-			if ($rule === '+' || $rule === '*') { // multiple
1648
-				if (!isset($data[$name])) {
1649
-					$data[$name] = [];
1650
-				}
1651
-
1652
-				$data[$name][] = $this->transformSearchProperty($property);
1653
-			} else { // once
1654
-				$data[$name] = $this->transformSearchProperty($property);
1655
-			}
1656
-		}
1657
-
1658
-		return $data;
1659
-	}
1660
-
1661
-	/**
1662
-	 * @param Property $prop
1663
-	 * @return array
1664
-	 */
1665
-	private function transformSearchProperty(Property $prop) {
1666
-		// No need to check Date, as it extends DateTime
1667
-		if ($prop instanceof Property\ICalendar\DateTime) {
1668
-			$value = $prop->getDateTime();
1669
-		} else {
1670
-			$value = $prop->getValue();
1671
-		}
1672
-
1673
-		return [
1674
-			$value,
1675
-			$prop->parameters()
1676
-		];
1677
-	}
1678
-
1679
-	/**
1680
-	 * Searches through all of a users calendars and calendar objects to find
1681
-	 * an object with a specific UID.
1682
-	 *
1683
-	 * This method should return the path to this object, relative to the
1684
-	 * calendar home, so this path usually only contains two parts:
1685
-	 *
1686
-	 * calendarpath/objectpath.ics
1687
-	 *
1688
-	 * If the uid is not found, return null.
1689
-	 *
1690
-	 * This method should only consider * objects that the principal owns, so
1691
-	 * any calendars owned by other principals that also appear in this
1692
-	 * collection should be ignored.
1693
-	 *
1694
-	 * @param string $principalUri
1695
-	 * @param string $uid
1696
-	 * @return string|null
1697
-	 */
1698
-	function getCalendarObjectByUID($principalUri, $uid) {
1699
-
1700
-		$query = $this->db->getQueryBuilder();
1701
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1702
-			->from('calendarobjects', 'co')
1703
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1704
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1705
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1706
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1707
-
1708
-		$stmt = $query->execute();
1709
-
1710
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1712
-		}
1713
-
1714
-		return null;
1715
-	}
1716
-
1717
-	/**
1718
-	 * The getChanges method returns all the changes that have happened, since
1719
-	 * the specified syncToken in the specified calendar.
1720
-	 *
1721
-	 * This function should return an array, such as the following:
1722
-	 *
1723
-	 * [
1724
-	 *   'syncToken' => 'The current synctoken',
1725
-	 *   'added'   => [
1726
-	 *      'new.txt',
1727
-	 *   ],
1728
-	 *   'modified'   => [
1729
-	 *      'modified.txt',
1730
-	 *   ],
1731
-	 *   'deleted' => [
1732
-	 *      'foo.php.bak',
1733
-	 *      'old.txt'
1734
-	 *   ]
1735
-	 * );
1736
-	 *
1737
-	 * The returned syncToken property should reflect the *current* syncToken
1738
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1739
-	 * property This is * needed here too, to ensure the operation is atomic.
1740
-	 *
1741
-	 * If the $syncToken argument is specified as null, this is an initial
1742
-	 * sync, and all members should be reported.
1743
-	 *
1744
-	 * The modified property is an array of nodenames that have changed since
1745
-	 * the last token.
1746
-	 *
1747
-	 * The deleted property is an array with nodenames, that have been deleted
1748
-	 * from collection.
1749
-	 *
1750
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1751
-	 * 1, you only have to report changes that happened only directly in
1752
-	 * immediate descendants. If it's 2, it should also include changes from
1753
-	 * the nodes below the child collections. (grandchildren)
1754
-	 *
1755
-	 * The $limit argument allows a client to specify how many results should
1756
-	 * be returned at most. If the limit is not specified, it should be treated
1757
-	 * as infinite.
1758
-	 *
1759
-	 * If the limit (infinite or not) is higher than you're willing to return,
1760
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1761
-	 *
1762
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1763
-	 * return null.
1764
-	 *
1765
-	 * The limit is 'suggestive'. You are free to ignore it.
1766
-	 *
1767
-	 * @param string $calendarId
1768
-	 * @param string $syncToken
1769
-	 * @param int $syncLevel
1770
-	 * @param int $limit
1771
-	 * @param int $calendarType
1772
-	 * @return array
1773
-	 */
1774
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1775
-		// Current synctoken
1776
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
-		$stmt->execute([ $calendarId ]);
1778
-		$currentToken = $stmt->fetchColumn(0);
1779
-
1780
-		if (is_null($currentToken)) {
1781
-			return null;
1782
-		}
1783
-
1784
-		$result = [
1785
-			'syncToken' => $currentToken,
1786
-			'added'     => [],
1787
-			'modified'  => [],
1788
-			'deleted'   => [],
1789
-		];
1790
-
1791
-		if ($syncToken) {
1792
-
1793
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
-			if ($limit>0) {
1795
-				$query.= " LIMIT " . (int)$limit;
1796
-			}
1797
-
1798
-			// Fetching all changes
1799
-			$stmt = $this->db->prepare($query);
1800
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1801
-
1802
-			$changes = [];
1803
-
1804
-			// This loop ensures that any duplicates are overwritten, only the
1805
-			// last change on a node is relevant.
1806
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807
-
1808
-				$changes[$row['uri']] = $row['operation'];
1809
-
1810
-			}
1811
-
1812
-			foreach($changes as $uri => $operation) {
1813
-
1814
-				switch($operation) {
1815
-					case 1 :
1816
-						$result['added'][] = $uri;
1817
-						break;
1818
-					case 2 :
1819
-						$result['modified'][] = $uri;
1820
-						break;
1821
-					case 3 :
1822
-						$result['deleted'][] = $uri;
1823
-						break;
1824
-				}
1825
-
1826
-			}
1827
-		} else {
1828
-			// No synctoken supplied, this is the initial sync.
1829
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1830
-			$stmt = $this->db->prepare($query);
1831
-			$stmt->execute([$calendarId, $calendarType]);
1832
-
1833
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1834
-		}
1835
-		return $result;
1836
-
1837
-	}
1838
-
1839
-	/**
1840
-	 * Returns a list of subscriptions for a principal.
1841
-	 *
1842
-	 * Every subscription is an array with the following keys:
1843
-	 *  * id, a unique id that will be used by other functions to modify the
1844
-	 *    subscription. This can be the same as the uri or a database key.
1845
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1846
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1847
-	 *    principalUri passed to this method.
1848
-	 *
1849
-	 * Furthermore, all the subscription info must be returned too:
1850
-	 *
1851
-	 * 1. {DAV:}displayname
1852
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1853
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1854
-	 *    should not be stripped).
1855
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1856
-	 *    should not be stripped).
1857
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1858
-	 *    attachments should not be stripped).
1859
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1860
-	 *     Sabre\DAV\Property\Href).
1861
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1862
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1863
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1864
-	 *    (should just be an instance of
1865
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1866
-	 *    default components).
1867
-	 *
1868
-	 * @param string $principalUri
1869
-	 * @return array
1870
-	 */
1871
-	function getSubscriptionsForUser($principalUri) {
1872
-		$fields = array_values($this->subscriptionPropertyMap);
1873
-		$fields[] = 'id';
1874
-		$fields[] = 'uri';
1875
-		$fields[] = 'source';
1876
-		$fields[] = 'principaluri';
1877
-		$fields[] = 'lastmodified';
1878
-		$fields[] = 'synctoken';
1879
-
1880
-		$query = $this->db->getQueryBuilder();
1881
-		$query->select($fields)
1882
-			->from('calendarsubscriptions')
1883
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884
-			->orderBy('calendarorder', 'asc');
1885
-		$stmt =$query->execute();
1886
-
1887
-		$subscriptions = [];
1888
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889
-
1890
-			$subscription = [
1891
-				'id'           => $row['id'],
1892
-				'uri'          => $row['uri'],
1893
-				'principaluri' => $row['principaluri'],
1894
-				'source'       => $row['source'],
1895
-				'lastmodified' => $row['lastmodified'],
1896
-
1897
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1899
-			];
1900
-
1901
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902
-				if (!is_null($row[$dbName])) {
1903
-					$subscription[$xmlName] = $row[$dbName];
1904
-				}
1905
-			}
1906
-
1907
-			$subscriptions[] = $subscription;
1908
-
1909
-		}
1910
-
1911
-		return $subscriptions;
1912
-	}
1913
-
1914
-	/**
1915
-	 * Creates a new subscription for a principal.
1916
-	 *
1917
-	 * If the creation was a success, an id must be returned that can be used to reference
1918
-	 * this subscription in other methods, such as updateSubscription.
1919
-	 *
1920
-	 * @param string $principalUri
1921
-	 * @param string $uri
1922
-	 * @param array $properties
1923
-	 * @return mixed
1924
-	 */
1925
-	function createSubscription($principalUri, $uri, array $properties) {
1926
-
1927
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1928
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1929
-		}
1930
-
1931
-		$values = [
1932
-			'principaluri' => $principalUri,
1933
-			'uri'          => $uri,
1934
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1935
-			'lastmodified' => time(),
1936
-		];
1937
-
1938
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939
-
1940
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941
-			if (array_key_exists($xmlName, $properties)) {
1942
-					$values[$dbName] = $properties[$xmlName];
1943
-					if (in_array($dbName, $propertiesBoolean)) {
1944
-						$values[$dbName] = true;
1945
-				}
1946
-			}
1947
-		}
1948
-
1949
-		$valuesToInsert = [];
1950
-
1951
-		$query = $this->db->getQueryBuilder();
1952
-
1953
-		foreach (array_keys($values) as $name) {
1954
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1955
-		}
1956
-
1957
-		$query->insert('calendarsubscriptions')
1958
-			->values($valuesToInsert)
1959
-			->execute();
1960
-
1961
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1962
-
1963
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1964
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1965
-			[
1966
-				'subscriptionId' => $subscriptionId,
1967
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1968
-			]));
1969
-
1970
-		return $subscriptionId;
1971
-	}
1972
-
1973
-	/**
1974
-	 * Updates a subscription
1975
-	 *
1976
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1977
-	 * To do the actual updates, you must tell this object which properties
1978
-	 * you're going to process with the handle() method.
1979
-	 *
1980
-	 * Calling the handle method is like telling the PropPatch object "I
1981
-	 * promise I can handle updating this property".
1982
-	 *
1983
-	 * Read the PropPatch documentation for more info and examples.
1984
-	 *
1985
-	 * @param mixed $subscriptionId
1986
-	 * @param PropPatch $propPatch
1987
-	 * @return void
1988
-	 */
1989
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1990
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1991
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1992
-
1993
-		/**
1994
-		 * @suppress SqlInjectionChecker
1995
-		 */
1996
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1997
-
1998
-			$newValues = [];
1999
-
2000
-			foreach($mutations as $propertyName=>$propertyValue) {
2001
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002
-					$newValues['source'] = $propertyValue->getHref();
2003
-				} else {
2004
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2005
-					$newValues[$fieldName] = $propertyValue;
2006
-				}
2007
-			}
2008
-
2009
-			$query = $this->db->getQueryBuilder();
2010
-			$query->update('calendarsubscriptions')
2011
-				->set('lastmodified', $query->createNamedParameter(time()));
2012
-			foreach($newValues as $fieldName=>$value) {
2013
-				$query->set($fieldName, $query->createNamedParameter($value));
2014
-			}
2015
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2016
-				->execute();
2017
-
2018
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2019
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2020
-				[
2021
-					'subscriptionId' => $subscriptionId,
2022
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2023
-					'propertyMutations' => $mutations,
2024
-				]));
2025
-
2026
-			return true;
2027
-
2028
-		});
2029
-	}
2030
-
2031
-	/**
2032
-	 * Deletes a subscription.
2033
-	 *
2034
-	 * @param mixed $subscriptionId
2035
-	 * @return void
2036
-	 */
2037
-	function deleteSubscription($subscriptionId) {
2038
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2039
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2040
-			[
2041
-				'subscriptionId' => $subscriptionId,
2042
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2043
-			]));
2044
-
2045
-		$query = $this->db->getQueryBuilder();
2046
-		$query->delete('calendarsubscriptions')
2047
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2048
-			->execute();
2049
-
2050
-		$query = $this->db->getQueryBuilder();
2051
-		$query->delete('calendarobjects')
2052
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2053
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2054
-			->execute();
2055
-
2056
-		$query->delete('calendarchanges')
2057
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2058
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2059
-			->execute();
2060
-
2061
-		$query->delete($this->dbObjectPropertiesTable)
2062
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2063
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2064
-			->execute();
2065
-	}
2066
-
2067
-	/**
2068
-	 * Returns a single scheduling object for the inbox collection.
2069
-	 *
2070
-	 * The returned array should contain the following elements:
2071
-	 *   * uri - A unique basename for the object. This will be used to
2072
-	 *           construct a full uri.
2073
-	 *   * calendardata - The iCalendar object
2074
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2075
-	 *                    timestamp, or a PHP DateTime object.
2076
-	 *   * etag - A unique token that must change if the object changed.
2077
-	 *   * size - The size of the object, in bytes.
2078
-	 *
2079
-	 * @param string $principalUri
2080
-	 * @param string $objectUri
2081
-	 * @return array
2082
-	 */
2083
-	function getSchedulingObject($principalUri, $objectUri) {
2084
-		$query = $this->db->getQueryBuilder();
2085
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2086
-			->from('schedulingobjects')
2087
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2088
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2089
-			->execute();
2090
-
2091
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092
-
2093
-		if(!$row) {
2094
-			return null;
2095
-		}
2096
-
2097
-		return [
2098
-			'uri'          => $row['uri'],
2099
-			'calendardata' => $row['calendardata'],
2100
-			'lastmodified' => $row['lastmodified'],
2101
-			'etag'         => '"' . $row['etag'] . '"',
2102
-			'size'         => (int)$row['size'],
2103
-		];
2104
-	}
2105
-
2106
-	/**
2107
-	 * Returns all scheduling objects for the inbox collection.
2108
-	 *
2109
-	 * These objects should be returned as an array. Every item in the array
2110
-	 * should follow the same structure as returned from getSchedulingObject.
2111
-	 *
2112
-	 * The main difference is that 'calendardata' is optional.
2113
-	 *
2114
-	 * @param string $principalUri
2115
-	 * @return array
2116
-	 */
2117
-	function getSchedulingObjects($principalUri) {
2118
-		$query = $this->db->getQueryBuilder();
2119
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2120
-				->from('schedulingobjects')
2121
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2122
-				->execute();
2123
-
2124
-		$result = [];
2125
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126
-			$result[] = [
2127
-				'calendardata' => $row['calendardata'],
2128
-				'uri'          => $row['uri'],
2129
-				'lastmodified' => $row['lastmodified'],
2130
-				'etag'         => '"' . $row['etag'] . '"',
2131
-				'size'         => (int)$row['size'],
2132
-			];
2133
-		}
2134
-
2135
-		return $result;
2136
-	}
2137
-
2138
-	/**
2139
-	 * Deletes a scheduling object from the inbox collection.
2140
-	 *
2141
-	 * @param string $principalUri
2142
-	 * @param string $objectUri
2143
-	 * @return void
2144
-	 */
2145
-	function deleteSchedulingObject($principalUri, $objectUri) {
2146
-		$query = $this->db->getQueryBuilder();
2147
-		$query->delete('schedulingobjects')
2148
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2149
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2150
-				->execute();
2151
-	}
2152
-
2153
-	/**
2154
-	 * Creates a new scheduling object. This should land in a users' inbox.
2155
-	 *
2156
-	 * @param string $principalUri
2157
-	 * @param string $objectUri
2158
-	 * @param string $objectData
2159
-	 * @return void
2160
-	 */
2161
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2162
-		$query = $this->db->getQueryBuilder();
2163
-		$query->insert('schedulingobjects')
2164
-			->values([
2165
-				'principaluri' => $query->createNamedParameter($principalUri),
2166
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2167
-				'uri' => $query->createNamedParameter($objectUri),
2168
-				'lastmodified' => $query->createNamedParameter(time()),
2169
-				'etag' => $query->createNamedParameter(md5($objectData)),
2170
-				'size' => $query->createNamedParameter(strlen($objectData))
2171
-			])
2172
-			->execute();
2173
-	}
2174
-
2175
-	/**
2176
-	 * Adds a change record to the calendarchanges table.
2177
-	 *
2178
-	 * @param mixed $calendarId
2179
-	 * @param string $objectUri
2180
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2181
-	 * @param int $calendarType
2182
-	 * @return void
2183
-	 */
2184
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2186
-
2187
-		$query = $this->db->getQueryBuilder();
2188
-		$query->select('synctoken')
2189
-			->from($table)
2190
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
-		$syncToken = (int)$query->execute()->fetchColumn();
2192
-
2193
-		$query = $this->db->getQueryBuilder();
2194
-		$query->insert('calendarchanges')
2195
-			->values([
2196
-				'uri' => $query->createNamedParameter($objectUri),
2197
-				'synctoken' => $query->createNamedParameter($syncToken),
2198
-				'calendarid' => $query->createNamedParameter($calendarId),
2199
-				'operation' => $query->createNamedParameter($operation),
2200
-				'calendartype' => $query->createNamedParameter($calendarType),
2201
-			])
2202
-			->execute();
2203
-
2204
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2205
-		$stmt->execute([
2206
-			$calendarId
2207
-		]);
2208
-
2209
-	}
2210
-
2211
-	/**
2212
-	 * Parses some information from calendar objects, used for optimized
2213
-	 * calendar-queries.
2214
-	 *
2215
-	 * Returns an array with the following keys:
2216
-	 *   * etag - An md5 checksum of the object without the quotes.
2217
-	 *   * size - Size of the object in bytes
2218
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2219
-	 *   * firstOccurence
2220
-	 *   * lastOccurence
2221
-	 *   * uid - value of the UID property
2222
-	 *
2223
-	 * @param string $calendarData
2224
-	 * @return array
2225
-	 */
2226
-	public function getDenormalizedData($calendarData) {
2227
-
2228
-		$vObject = Reader::read($calendarData);
2229
-		$componentType = null;
2230
-		$component = null;
2231
-		$firstOccurrence = null;
2232
-		$lastOccurrence = null;
2233
-		$uid = null;
2234
-		$classification = self::CLASSIFICATION_PUBLIC;
2235
-		foreach($vObject->getComponents() as $component) {
2236
-			if ($component->name!=='VTIMEZONE') {
2237
-				$componentType = $component->name;
2238
-				$uid = (string)$component->UID;
2239
-				break;
2240
-			}
2241
-		}
2242
-		if (!$componentType) {
2243
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2244
-		}
2245
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2246
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2247
-			// Finding the last occurrence is a bit harder
2248
-			if (!isset($component->RRULE)) {
2249
-				if (isset($component->DTEND)) {
2250
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2251
-				} elseif (isset($component->DURATION)) {
2252
-					$endDate = clone $component->DTSTART->getDateTime();
2253
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2254
-					$lastOccurrence = $endDate->getTimeStamp();
2255
-				} elseif (!$component->DTSTART->hasTime()) {
2256
-					$endDate = clone $component->DTSTART->getDateTime();
2257
-					$endDate->modify('+1 day');
2258
-					$lastOccurrence = $endDate->getTimeStamp();
2259
-				} else {
2260
-					$lastOccurrence = $firstOccurrence;
2261
-				}
2262
-			} else {
2263
-				$it = new EventIterator($vObject, (string)$component->UID);
2264
-				$maxDate = new DateTime(self::MAX_DATE);
2265
-				if ($it->isInfinite()) {
2266
-					$lastOccurrence = $maxDate->getTimestamp();
2267
-				} else {
2268
-					$end = $it->getDtEnd();
2269
-					while($it->valid() && $end < $maxDate) {
2270
-						$end = $it->getDtEnd();
2271
-						$it->next();
2272
-
2273
-					}
2274
-					$lastOccurrence = $end->getTimestamp();
2275
-				}
2276
-
2277
-			}
2278
-		}
2279
-
2280
-		if ($component->CLASS) {
2281
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2282
-			switch ($component->CLASS->getValue()) {
2283
-				case 'PUBLIC':
2284
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2285
-					break;
2286
-				case 'CONFIDENTIAL':
2287
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2288
-					break;
2289
-			}
2290
-		}
2291
-		return [
2292
-			'etag' => md5($calendarData),
2293
-			'size' => strlen($calendarData),
2294
-			'componentType' => $componentType,
2295
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2296
-			'lastOccurence'  => $lastOccurrence,
2297
-			'uid' => $uid,
2298
-			'classification' => $classification
2299
-		];
2300
-
2301
-	}
2302
-
2303
-	/**
2304
-	 * @param $cardData
2305
-	 * @return bool|string
2306
-	 */
2307
-	private function readBlob($cardData) {
2308
-		if (is_resource($cardData)) {
2309
-			return stream_get_contents($cardData);
2310
-		}
2311
-
2312
-		return $cardData;
2313
-	}
2314
-
2315
-	/**
2316
-	 * @param IShareable $shareable
2317
-	 * @param array $add
2318
-	 * @param array $remove
2319
-	 */
2320
-	public function updateShares($shareable, $add, $remove) {
2321
-		$calendarId = $shareable->getResourceId();
2322
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2323
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2324
-			[
2325
-				'calendarId' => $calendarId,
2326
-				'calendarData' => $this->getCalendarById($calendarId),
2327
-				'shares' => $this->getShares($calendarId),
2328
-				'add' => $add,
2329
-				'remove' => $remove,
2330
-			]));
2331
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2332
-	}
2333
-
2334
-	/**
2335
-	 * @param int $resourceId
2336
-	 * @param int $calendarType
2337
-	 * @return array
2338
-	 */
2339
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2340
-		return $this->calendarSharingBackend->getShares($resourceId);
2341
-	}
2342
-
2343
-	/**
2344
-	 * @param boolean $value
2345
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2346
-	 * @return string|null
2347
-	 */
2348
-	public function setPublishStatus($value, $calendar) {
2349
-
2350
-		$calendarId = $calendar->getResourceId();
2351
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2352
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2353
-			[
2354
-				'calendarId' => $calendarId,
2355
-				'calendarData' => $this->getCalendarById($calendarId),
2356
-				'public' => $value,
2357
-			]));
2358
-
2359
-		$query = $this->db->getQueryBuilder();
2360
-		if ($value) {
2361
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2362
-			$query->insert('dav_shares')
2363
-				->values([
2364
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2365
-					'type' => $query->createNamedParameter('calendar'),
2366
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2367
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2368
-					'publicuri' => $query->createNamedParameter($publicUri)
2369
-				]);
2370
-			$query->execute();
2371
-			return $publicUri;
2372
-		}
2373
-		$query->delete('dav_shares')
2374
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2375
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2376
-		$query->execute();
2377
-		return null;
2378
-	}
2379
-
2380
-	/**
2381
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2382
-	 * @return mixed
2383
-	 */
2384
-	public function getPublishStatus($calendar) {
2385
-		$query = $this->db->getQueryBuilder();
2386
-		$result = $query->select('publicuri')
2387
-			->from('dav_shares')
2388
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2389
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2390
-			->execute();
2391
-
2392
-		$row = $result->fetch();
2393
-		$result->closeCursor();
2394
-		return $row ? reset($row) : false;
2395
-	}
2396
-
2397
-	/**
2398
-	 * @param int $resourceId
2399
-	 * @param array $acl
2400
-	 * @return array
2401
-	 */
2402
-	public function applyShareAcl($resourceId, $acl) {
2403
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2404
-	}
2405
-
2406
-
2407
-
2408
-	/**
2409
-	 * update properties table
2410
-	 *
2411
-	 * @param int $calendarId
2412
-	 * @param string $objectUri
2413
-	 * @param string $calendarData
2414
-	 * @param int $calendarType
2415
-	 */
2416
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2417
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418
-
2419
-		try {
2420
-			$vCalendar = $this->readCalendarData($calendarData);
2421
-		} catch (\Exception $ex) {
2422
-			return;
2423
-		}
2424
-
2425
-		$this->purgeProperties($calendarId, $objectId);
2426
-
2427
-		$query = $this->db->getQueryBuilder();
2428
-		$query->insert($this->dbObjectPropertiesTable)
2429
-			->values(
2430
-				[
2431
-					'calendarid' => $query->createNamedParameter($calendarId),
2432
-					'calendartype' => $query->createNamedParameter($calendarType),
2433
-					'objectid' => $query->createNamedParameter($objectId),
2434
-					'name' => $query->createParameter('name'),
2435
-					'parameter' => $query->createParameter('parameter'),
2436
-					'value' => $query->createParameter('value'),
2437
-				]
2438
-			);
2439
-
2440
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2441
-		foreach ($vCalendar->getComponents() as $component) {
2442
-			if (!in_array($component->name, $indexComponents)) {
2443
-				continue;
2444
-			}
2445
-
2446
-			foreach ($component->children() as $property) {
2447
-				if (in_array($property->name, self::$indexProperties)) {
2448
-					$value = $property->getValue();
2449
-					// is this a shitty db?
2450
-					if (!$this->db->supports4ByteText()) {
2451
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2452
-					}
2453
-					$value = mb_substr($value, 0, 254);
2454
-
2455
-					$query->setParameter('name', $property->name);
2456
-					$query->setParameter('parameter', null);
2457
-					$query->setParameter('value', $value);
2458
-					$query->execute();
2459
-				}
2460
-
2461
-				if (array_key_exists($property->name, self::$indexParameters)) {
2462
-					$parameters = $property->parameters();
2463
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2464
-
2465
-					foreach ($parameters as $key => $value) {
2466
-						if (in_array($key, $indexedParametersForProperty)) {
2467
-							// is this a shitty db?
2468
-							if ($this->db->supports4ByteText()) {
2469
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2470
-							}
2471
-
2472
-							$query->setParameter('name', $property->name);
2473
-							$query->setParameter('parameter', mb_substr($key, 0, 254));
2474
-							$query->setParameter('value', mb_substr($value, 0, 254));
2475
-							$query->execute();
2476
-						}
2477
-					}
2478
-				}
2479
-			}
2480
-		}
2481
-	}
2482
-
2483
-	/**
2484
-	 * deletes all birthday calendars
2485
-	 */
2486
-	public function deleteAllBirthdayCalendars() {
2487
-		$query = $this->db->getQueryBuilder();
2488
-		$result = $query->select(['id'])->from('calendars')
2489
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2490
-			->execute();
2491
-
2492
-		$ids = $result->fetchAll();
2493
-		foreach($ids as $id) {
2494
-			$this->deleteCalendar($id['id']);
2495
-		}
2496
-	}
2497
-
2498
-	/**
2499
-	 * @param $subscriptionId
2500
-	 */
2501
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2502
-		$query = $this->db->getQueryBuilder();
2503
-		$query->select('uri')
2504
-			->from('calendarobjects')
2505
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2507
-		$stmt = $query->execute();
2508
-
2509
-		$uris = [];
2510
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511
-			$uris[] = $row['uri'];
2512
-		}
2513
-		$stmt->closeCursor();
2514
-
2515
-		$query = $this->db->getQueryBuilder();
2516
-		$query->delete('calendarobjects')
2517
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2518
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2519
-			->execute();
2520
-
2521
-		$query->delete('calendarchanges')
2522
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2523
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2524
-			->execute();
2525
-
2526
-		$query->delete($this->dbObjectPropertiesTable)
2527
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2528
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529
-			->execute();
2530
-
2531
-		foreach($uris as $uri) {
2532
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533
-		}
2534
-	}
2535
-
2536
-	/**
2537
-	 * Move a calendar from one user to another
2538
-	 *
2539
-	 * @param string $uriName
2540
-	 * @param string $uriOrigin
2541
-	 * @param string $uriDestination
2542
-	 */
2543
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2544
-	{
2545
-		$query = $this->db->getQueryBuilder();
2546
-		$query->update('calendars')
2547
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2548
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2549
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2550
-			->execute();
2551
-	}
2552
-
2553
-	/**
2554
-	 * read VCalendar data into a VCalendar object
2555
-	 *
2556
-	 * @param string $objectData
2557
-	 * @return VCalendar
2558
-	 */
2559
-	protected function readCalendarData($objectData) {
2560
-		return Reader::read($objectData);
2561
-	}
2562
-
2563
-	/**
2564
-	 * delete all properties from a given calendar object
2565
-	 *
2566
-	 * @param int $calendarId
2567
-	 * @param int $objectId
2568
-	 */
2569
-	protected function purgeProperties($calendarId, $objectId) {
2570
-		$query = $this->db->getQueryBuilder();
2571
-		$query->delete($this->dbObjectPropertiesTable)
2572
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2573
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2574
-		$query->execute();
2575
-	}
2576
-
2577
-	/**
2578
-	 * get ID from a given calendar object
2579
-	 *
2580
-	 * @param int $calendarId
2581
-	 * @param string $uri
2582
-	 * @param int $calendarType
2583
-	 * @return int
2584
-	 */
2585
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2586
-		$query = $this->db->getQueryBuilder();
2587
-		$query->select('id')
2588
-			->from('calendarobjects')
2589
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2590
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2591
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2592
-
2593
-		$result = $query->execute();
2594
-		$objectIds = $result->fetch();
2595
-		$result->closeCursor();
2596
-
2597
-		if (!isset($objectIds['id'])) {
2598
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2599
-		}
2600
-
2601
-		return (int)$objectIds['id'];
2602
-	}
2603
-
2604
-	/**
2605
-	 * return legacy endpoint principal name to new principal name
2606
-	 *
2607
-	 * @param $principalUri
2608
-	 * @param $toV2
2609
-	 * @return string
2610
-	 */
2611
-	private function convertPrincipal($principalUri, $toV2) {
2612
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2613
-			list(, $name) = Uri\split($principalUri);
2614
-			if ($toV2 === true) {
2615
-				return "principals/users/$name";
2616
-			}
2617
-			return "principals/$name";
2618
-		}
2619
-		return $principalUri;
2620
-	}
2621
-
2622
-	/**
2623
-	 * adds information about an owner to the calendar data
2624
-	 *
2625
-	 * @param $calendarInfo
2626
-	 */
2627
-	private function addOwnerPrincipal(&$calendarInfo) {
2628
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2630
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2631
-			$uri = $calendarInfo[$ownerPrincipalKey];
2632
-		} else {
2633
-			$uri = $calendarInfo['principaluri'];
2634
-		}
2635
-
2636
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2637
-		if (isset($principalInformation['{DAV:}displayname'])) {
2638
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2639
-		}
2640
-	}
81
+    const CALENDAR_TYPE_CALENDAR = 0;
82
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
83
+
84
+    const PERSONAL_CALENDAR_URI = 'personal';
85
+    const PERSONAL_CALENDAR_NAME = 'Personal';
86
+
87
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
88
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
89
+
90
+    /**
91
+     * We need to specify a max date, because we need to stop *somewhere*
92
+     *
93
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
94
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
95
+     * in 2038-01-19 to avoid problems when the date is converted
96
+     * to a unix timestamp.
97
+     */
98
+    const MAX_DATE = '2038-01-01';
99
+
100
+    const ACCESS_PUBLIC = 4;
101
+    const CLASSIFICATION_PUBLIC = 0;
102
+    const CLASSIFICATION_PRIVATE = 1;
103
+    const CLASSIFICATION_CONFIDENTIAL = 2;
104
+
105
+    /**
106
+     * List of CalDAV properties, and how they map to database field names
107
+     * Add your own properties by simply adding on to this array.
108
+     *
109
+     * Note that only string-based properties are supported here.
110
+     *
111
+     * @var array
112
+     */
113
+    public $propertyMap = [
114
+        '{DAV:}displayname'                          => 'displayname',
115
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
116
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
117
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
118
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
119
+    ];
120
+
121
+    /**
122
+     * List of subscription properties, and how they map to database field names.
123
+     *
124
+     * @var array
125
+     */
126
+    public $subscriptionPropertyMap = [
127
+        '{DAV:}displayname'                                           => 'displayname',
128
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
129
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
130
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
131
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
132
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
133
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
134
+    ];
135
+
136
+    /** @var array properties to index */
137
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
138
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
139
+        'ORGANIZER'];
140
+
141
+    /** @var array parameters to index */
142
+    public static $indexParameters = [
143
+        'ATTENDEE' => ['CN'],
144
+        'ORGANIZER' => ['CN'],
145
+    ];
146
+
147
+    /**
148
+     * @var string[] Map of uid => display name
149
+     */
150
+    protected $userDisplayNames;
151
+
152
+    /** @var IDBConnection */
153
+    private $db;
154
+
155
+    /** @var Backend */
156
+    private $calendarSharingBackend;
157
+
158
+    /** @var Principal */
159
+    private $principalBackend;
160
+
161
+    /** @var IUserManager */
162
+    private $userManager;
163
+
164
+    /** @var ISecureRandom */
165
+    private $random;
166
+
167
+    /** @var ILogger */
168
+    private $logger;
169
+
170
+    /** @var EventDispatcherInterface */
171
+    private $dispatcher;
172
+
173
+    /** @var bool */
174
+    private $legacyEndpoint;
175
+
176
+    /** @var string */
177
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
178
+
179
+    /**
180
+     * CalDavBackend constructor.
181
+     *
182
+     * @param IDBConnection $db
183
+     * @param Principal $principalBackend
184
+     * @param IUserManager $userManager
185
+     * @param IGroupManager $groupManager
186
+     * @param ISecureRandom $random
187
+     * @param ILogger $logger
188
+     * @param EventDispatcherInterface $dispatcher
189
+     * @param bool $legacyEndpoint
190
+     */
191
+    public function __construct(IDBConnection $db,
192
+                                Principal $principalBackend,
193
+                                IUserManager $userManager,
194
+                                IGroupManager $groupManager,
195
+                                ISecureRandom $random,
196
+                                ILogger $logger,
197
+                                EventDispatcherInterface $dispatcher,
198
+                                bool $legacyEndpoint = false) {
199
+        $this->db = $db;
200
+        $this->principalBackend = $principalBackend;
201
+        $this->userManager = $userManager;
202
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
203
+        $this->random = $random;
204
+        $this->logger = $logger;
205
+        $this->dispatcher = $dispatcher;
206
+        $this->legacyEndpoint = $legacyEndpoint;
207
+    }
208
+
209
+    /**
210
+     * Return the number of calendars for a principal
211
+     *
212
+     * By default this excludes the automatically generated birthday calendar
213
+     *
214
+     * @param $principalUri
215
+     * @param bool $excludeBirthday
216
+     * @return int
217
+     */
218
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
219
+        $principalUri = $this->convertPrincipal($principalUri, true);
220
+        $query = $this->db->getQueryBuilder();
221
+        $query->select($query->func()->count('*'))
222
+            ->from('calendars')
223
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
224
+
225
+        if ($excludeBirthday) {
226
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227
+        }
228
+
229
+        return (int)$query->execute()->fetchColumn();
230
+    }
231
+
232
+    /**
233
+     * Returns a list of calendars for a principal.
234
+     *
235
+     * Every project is an array with the following keys:
236
+     *  * id, a unique id that will be used by other functions to modify the
237
+     *    calendar. This can be the same as the uri or a database key.
238
+     *  * uri, which the basename of the uri with which the calendar is
239
+     *    accessed.
240
+     *  * principaluri. The owner of the calendar. Almost always the same as
241
+     *    principalUri passed to this method.
242
+     *
243
+     * Furthermore it can contain webdav properties in clark notation. A very
244
+     * common one is '{DAV:}displayname'.
245
+     *
246
+     * Many clients also require:
247
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
248
+     * For this property, you can just return an instance of
249
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
250
+     *
251
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
252
+     * ACL will automatically be put in read-only mode.
253
+     *
254
+     * @param string $principalUri
255
+     * @return array
256
+     */
257
+    function getCalendarsForUser($principalUri) {
258
+        $principalUriOriginal = $principalUri;
259
+        $principalUri = $this->convertPrincipal($principalUri, true);
260
+        $fields = array_values($this->propertyMap);
261
+        $fields[] = 'id';
262
+        $fields[] = 'uri';
263
+        $fields[] = 'synctoken';
264
+        $fields[] = 'components';
265
+        $fields[] = 'principaluri';
266
+        $fields[] = 'transparent';
267
+
268
+        // Making fields a comma-delimited list
269
+        $query = $this->db->getQueryBuilder();
270
+        $query->select($fields)->from('calendars')
271
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
272
+                ->orderBy('calendarorder', 'ASC');
273
+        $stmt = $query->execute();
274
+
275
+        $calendars = [];
276
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277
+
278
+            $components = [];
279
+            if ($row['components']) {
280
+                $components = explode(',',$row['components']);
281
+            }
282
+
283
+            $calendar = [
284
+                'id' => $row['id'],
285
+                'uri' => $row['uri'],
286
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
+            ];
293
+
294
+            foreach($this->propertyMap as $xmlName=>$dbName) {
295
+                $calendar[$xmlName] = $row[$dbName];
296
+            }
297
+
298
+            $this->addOwnerPrincipal($calendar);
299
+
300
+            if (!isset($calendars[$calendar['id']])) {
301
+                $calendars[$calendar['id']] = $calendar;
302
+            }
303
+        }
304
+
305
+        $stmt->closeCursor();
306
+
307
+        // query for shared calendars
308
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
309
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
310
+
311
+        $principals = array_map(function($principal) {
312
+            return urldecode($principal);
313
+        }, $principals);
314
+        $principals[]= $principalUri;
315
+
316
+        $fields = array_values($this->propertyMap);
317
+        $fields[] = 'a.id';
318
+        $fields[] = 'a.uri';
319
+        $fields[] = 'a.synctoken';
320
+        $fields[] = 'a.components';
321
+        $fields[] = 'a.principaluri';
322
+        $fields[] = 'a.transparent';
323
+        $fields[] = 's.access';
324
+        $query = $this->db->getQueryBuilder();
325
+        $result = $query->select($fields)
326
+            ->from('dav_shares', 's')
327
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
328
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
329
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
330
+            ->setParameter('type', 'calendar')
331
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332
+            ->execute();
333
+
334
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
+        while($row = $result->fetch()) {
336
+            if ($row['principaluri'] === $principalUri) {
337
+                continue;
338
+            }
339
+
340
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
341
+            if (isset($calendars[$row['id']])) {
342
+                if ($readOnly) {
343
+                    // New share can not have more permissions then the old one.
344
+                    continue;
345
+                }
346
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
347
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
348
+                    // Old share is already read-write, no more permissions can be gained
349
+                    continue;
350
+                }
351
+            }
352
+
353
+            list(, $name) = Uri\split($row['principaluri']);
354
+            $uri = $row['uri'] . '_shared_by_' . $name;
355
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
356
+            $components = [];
357
+            if ($row['components']) {
358
+                $components = explode(',',$row['components']);
359
+            }
360
+            $calendar = [
361
+                'id' => $row['id'],
362
+                'uri' => $uri,
363
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369
+                $readOnlyPropertyName => $readOnly,
370
+            ];
371
+
372
+            foreach($this->propertyMap as $xmlName=>$dbName) {
373
+                $calendar[$xmlName] = $row[$dbName];
374
+            }
375
+
376
+            $this->addOwnerPrincipal($calendar);
377
+
378
+            $calendars[$calendar['id']] = $calendar;
379
+        }
380
+        $result->closeCursor();
381
+
382
+        return array_values($calendars);
383
+    }
384
+
385
+    /**
386
+     * @param $principalUri
387
+     * @return array
388
+     */
389
+    public function getUsersOwnCalendars($principalUri) {
390
+        $principalUri = $this->convertPrincipal($principalUri, true);
391
+        $fields = array_values($this->propertyMap);
392
+        $fields[] = 'id';
393
+        $fields[] = 'uri';
394
+        $fields[] = 'synctoken';
395
+        $fields[] = 'components';
396
+        $fields[] = 'principaluri';
397
+        $fields[] = 'transparent';
398
+        // Making fields a comma-delimited list
399
+        $query = $this->db->getQueryBuilder();
400
+        $query->select($fields)->from('calendars')
401
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
402
+            ->orderBy('calendarorder', 'ASC');
403
+        $stmt = $query->execute();
404
+        $calendars = [];
405
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406
+            $components = [];
407
+            if ($row['components']) {
408
+                $components = explode(',',$row['components']);
409
+            }
410
+            $calendar = [
411
+                'id' => $row['id'],
412
+                'uri' => $row['uri'],
413
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
418
+            ];
419
+            foreach($this->propertyMap as $xmlName=>$dbName) {
420
+                $calendar[$xmlName] = $row[$dbName];
421
+            }
422
+
423
+            $this->addOwnerPrincipal($calendar);
424
+
425
+            if (!isset($calendars[$calendar['id']])) {
426
+                $calendars[$calendar['id']] = $calendar;
427
+            }
428
+        }
429
+        $stmt->closeCursor();
430
+        return array_values($calendars);
431
+    }
432
+
433
+
434
+    /**
435
+     * @param $uid
436
+     * @return string
437
+     */
438
+    private function getUserDisplayName($uid) {
439
+        if (!isset($this->userDisplayNames[$uid])) {
440
+            $user = $this->userManager->get($uid);
441
+
442
+            if ($user instanceof IUser) {
443
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
444
+            } else {
445
+                $this->userDisplayNames[$uid] = $uid;
446
+            }
447
+        }
448
+
449
+        return $this->userDisplayNames[$uid];
450
+    }
451
+
452
+    /**
453
+     * @return array
454
+     */
455
+    public function getPublicCalendars() {
456
+        $fields = array_values($this->propertyMap);
457
+        $fields[] = 'a.id';
458
+        $fields[] = 'a.uri';
459
+        $fields[] = 'a.synctoken';
460
+        $fields[] = 'a.components';
461
+        $fields[] = 'a.principaluri';
462
+        $fields[] = 'a.transparent';
463
+        $fields[] = 's.access';
464
+        $fields[] = 's.publicuri';
465
+        $calendars = [];
466
+        $query = $this->db->getQueryBuilder();
467
+        $result = $query->select($fields)
468
+            ->from('dav_shares', 's')
469
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
470
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
471
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472
+            ->execute();
473
+
474
+        while($row = $result->fetch()) {
475
+            list(, $name) = Uri\split($row['principaluri']);
476
+            $row['displayname'] = $row['displayname'] . "($name)";
477
+            $components = [];
478
+            if ($row['components']) {
479
+                $components = explode(',',$row['components']);
480
+            }
481
+            $calendar = [
482
+                'id' => $row['id'],
483
+                'uri' => $row['publicuri'],
484
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
492
+            ];
493
+
494
+            foreach($this->propertyMap as $xmlName=>$dbName) {
495
+                $calendar[$xmlName] = $row[$dbName];
496
+            }
497
+
498
+            $this->addOwnerPrincipal($calendar);
499
+
500
+            if (!isset($calendars[$calendar['id']])) {
501
+                $calendars[$calendar['id']] = $calendar;
502
+            }
503
+        }
504
+        $result->closeCursor();
505
+
506
+        return array_values($calendars);
507
+    }
508
+
509
+    /**
510
+     * @param string $uri
511
+     * @return array
512
+     * @throws NotFound
513
+     */
514
+    public function getPublicCalendar($uri) {
515
+        $fields = array_values($this->propertyMap);
516
+        $fields[] = 'a.id';
517
+        $fields[] = 'a.uri';
518
+        $fields[] = 'a.synctoken';
519
+        $fields[] = 'a.components';
520
+        $fields[] = 'a.principaluri';
521
+        $fields[] = 'a.transparent';
522
+        $fields[] = 's.access';
523
+        $fields[] = 's.publicuri';
524
+        $query = $this->db->getQueryBuilder();
525
+        $result = $query->select($fields)
526
+            ->from('dav_shares', 's')
527
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
528
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
529
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
530
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
531
+            ->execute();
532
+
533
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
534
+
535
+        $result->closeCursor();
536
+
537
+        if ($row === false) {
538
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
539
+        }
540
+
541
+        list(, $name) = Uri\split($row['principaluri']);
542
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
543
+        $components = [];
544
+        if ($row['components']) {
545
+            $components = explode(',',$row['components']);
546
+        }
547
+        $calendar = [
548
+            'id' => $row['id'],
549
+            'uri' => $row['publicuri'],
550
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
558
+        ];
559
+
560
+        foreach($this->propertyMap as $xmlName=>$dbName) {
561
+            $calendar[$xmlName] = $row[$dbName];
562
+        }
563
+
564
+        $this->addOwnerPrincipal($calendar);
565
+
566
+        return $calendar;
567
+
568
+    }
569
+
570
+    /**
571
+     * @param string $principal
572
+     * @param string $uri
573
+     * @return array|null
574
+     */
575
+    public function getCalendarByUri($principal, $uri) {
576
+        $fields = array_values($this->propertyMap);
577
+        $fields[] = 'id';
578
+        $fields[] = 'uri';
579
+        $fields[] = 'synctoken';
580
+        $fields[] = 'components';
581
+        $fields[] = 'principaluri';
582
+        $fields[] = 'transparent';
583
+
584
+        // Making fields a comma-delimited list
585
+        $query = $this->db->getQueryBuilder();
586
+        $query->select($fields)->from('calendars')
587
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
588
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
589
+            ->setMaxResults(1);
590
+        $stmt = $query->execute();
591
+
592
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
593
+        $stmt->closeCursor();
594
+        if ($row === false) {
595
+            return null;
596
+        }
597
+
598
+        $components = [];
599
+        if ($row['components']) {
600
+            $components = explode(',',$row['components']);
601
+        }
602
+
603
+        $calendar = [
604
+            'id' => $row['id'],
605
+            'uri' => $row['uri'],
606
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
611
+        ];
612
+
613
+        foreach($this->propertyMap as $xmlName=>$dbName) {
614
+            $calendar[$xmlName] = $row[$dbName];
615
+        }
616
+
617
+        $this->addOwnerPrincipal($calendar);
618
+
619
+        return $calendar;
620
+    }
621
+
622
+    /**
623
+     * @param $calendarId
624
+     * @return array|null
625
+     */
626
+    public function getCalendarById($calendarId) {
627
+        $fields = array_values($this->propertyMap);
628
+        $fields[] = 'id';
629
+        $fields[] = 'uri';
630
+        $fields[] = 'synctoken';
631
+        $fields[] = 'components';
632
+        $fields[] = 'principaluri';
633
+        $fields[] = 'transparent';
634
+
635
+        // Making fields a comma-delimited list
636
+        $query = $this->db->getQueryBuilder();
637
+        $query->select($fields)->from('calendars')
638
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
639
+            ->setMaxResults(1);
640
+        $stmt = $query->execute();
641
+
642
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
643
+        $stmt->closeCursor();
644
+        if ($row === false) {
645
+            return null;
646
+        }
647
+
648
+        $components = [];
649
+        if ($row['components']) {
650
+            $components = explode(',',$row['components']);
651
+        }
652
+
653
+        $calendar = [
654
+            'id' => $row['id'],
655
+            'uri' => $row['uri'],
656
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
661
+        ];
662
+
663
+        foreach($this->propertyMap as $xmlName=>$dbName) {
664
+            $calendar[$xmlName] = $row[$dbName];
665
+        }
666
+
667
+        $this->addOwnerPrincipal($calendar);
668
+
669
+        return $calendar;
670
+    }
671
+
672
+    /**
673
+     * @param $subscriptionId
674
+     */
675
+    public function getSubscriptionById($subscriptionId) {
676
+        $fields = array_values($this->subscriptionPropertyMap);
677
+        $fields[] = 'id';
678
+        $fields[] = 'uri';
679
+        $fields[] = 'source';
680
+        $fields[] = 'synctoken';
681
+        $fields[] = 'principaluri';
682
+        $fields[] = 'lastmodified';
683
+
684
+        $query = $this->db->getQueryBuilder();
685
+        $query->select($fields)
686
+            ->from('calendarsubscriptions')
687
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688
+            ->orderBy('calendarorder', 'asc');
689
+        $stmt =$query->execute();
690
+
691
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
692
+        $stmt->closeCursor();
693
+        if ($row === false) {
694
+            return null;
695
+        }
696
+
697
+        $subscription = [
698
+            'id'           => $row['id'],
699
+            'uri'          => $row['uri'],
700
+            'principaluri' => $row['principaluri'],
701
+            'source'       => $row['source'],
702
+            'lastmodified' => $row['lastmodified'],
703
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
705
+        ];
706
+
707
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708
+            if (!is_null($row[$dbName])) {
709
+                $subscription[$xmlName] = $row[$dbName];
710
+            }
711
+        }
712
+
713
+        return $subscription;
714
+    }
715
+
716
+    /**
717
+     * Creates a new calendar for a principal.
718
+     *
719
+     * If the creation was a success, an id must be returned that can be used to reference
720
+     * this calendar in other methods, such as updateCalendar.
721
+     *
722
+     * @param string $principalUri
723
+     * @param string $calendarUri
724
+     * @param array $properties
725
+     * @return int
726
+     * @suppress SqlInjectionChecker
727
+     */
728
+    function createCalendar($principalUri, $calendarUri, array $properties) {
729
+        $values = [
730
+            'principaluri' => $this->convertPrincipal($principalUri, true),
731
+            'uri'          => $calendarUri,
732
+            'synctoken'    => 1,
733
+            'transparent'  => 0,
734
+            'components'   => 'VEVENT,VTODO',
735
+            'displayname'  => $calendarUri
736
+        ];
737
+
738
+        // Default value
739
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740
+        if (isset($properties[$sccs])) {
741
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743
+            }
744
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
745
+        } else if (isset($properties['components'])) {
746
+            // Allow to provide components internally without having
747
+            // to create a SupportedCalendarComponentSet object
748
+            $values['components'] = $properties['components'];
749
+        }
750
+
751
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
752
+        if (isset($properties[$transp])) {
753
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754
+        }
755
+
756
+        foreach($this->propertyMap as $xmlName=>$dbName) {
757
+            if (isset($properties[$xmlName])) {
758
+                $values[$dbName] = $properties[$xmlName];
759
+            }
760
+        }
761
+
762
+        $query = $this->db->getQueryBuilder();
763
+        $query->insert('calendars');
764
+        foreach($values as $column => $value) {
765
+            $query->setValue($column, $query->createNamedParameter($value));
766
+        }
767
+        $query->execute();
768
+        $calendarId = $query->getLastInsertId();
769
+
770
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
771
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
772
+            [
773
+                'calendarId' => $calendarId,
774
+                'calendarData' => $this->getCalendarById($calendarId),
775
+            ]));
776
+
777
+        return $calendarId;
778
+    }
779
+
780
+    /**
781
+     * Updates properties for a calendar.
782
+     *
783
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
784
+     * To do the actual updates, you must tell this object which properties
785
+     * you're going to process with the handle() method.
786
+     *
787
+     * Calling the handle method is like telling the PropPatch object "I
788
+     * promise I can handle updating this property".
789
+     *
790
+     * Read the PropPatch documentation for more info and examples.
791
+     *
792
+     * @param mixed $calendarId
793
+     * @param PropPatch $propPatch
794
+     * @return void
795
+     */
796
+    function updateCalendar($calendarId, PropPatch $propPatch) {
797
+        $supportedProperties = array_keys($this->propertyMap);
798
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
799
+
800
+        /**
801
+         * @suppress SqlInjectionChecker
802
+         */
803
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
804
+            $newValues = [];
805
+            foreach ($mutations as $propertyName => $propertyValue) {
806
+
807
+                switch ($propertyName) {
808
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
809
+                        $fieldName = 'transparent';
810
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811
+                        break;
812
+                    default :
813
+                        $fieldName = $this->propertyMap[$propertyName];
814
+                        $newValues[$fieldName] = $propertyValue;
815
+                        break;
816
+                }
817
+
818
+            }
819
+            $query = $this->db->getQueryBuilder();
820
+            $query->update('calendars');
821
+            foreach ($newValues as $fieldName => $value) {
822
+                $query->set($fieldName, $query->createNamedParameter($value));
823
+            }
824
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
825
+            $query->execute();
826
+
827
+            $this->addChange($calendarId, "", 2);
828
+
829
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
830
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
831
+                [
832
+                    'calendarId' => $calendarId,
833
+                    'calendarData' => $this->getCalendarById($calendarId),
834
+                    'shares' => $this->getShares($calendarId),
835
+                    'propertyMutations' => $mutations,
836
+                ]));
837
+
838
+            return true;
839
+        });
840
+    }
841
+
842
+    /**
843
+     * Delete a calendar and all it's objects
844
+     *
845
+     * @param mixed $calendarId
846
+     * @return void
847
+     */
848
+    function deleteCalendar($calendarId) {
849
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
850
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
851
+            [
852
+                'calendarId' => $calendarId,
853
+                'calendarData' => $this->getCalendarById($calendarId),
854
+                'shares' => $this->getShares($calendarId),
855
+            ]));
856
+
857
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
858
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
859
+
860
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
861
+        $stmt->execute([$calendarId]);
862
+
863
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
864
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
865
+
866
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
867
+
868
+        $query = $this->db->getQueryBuilder();
869
+        $query->delete($this->dbObjectPropertiesTable)
870
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
871
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
872
+            ->execute();
873
+    }
874
+
875
+    /**
876
+     * Delete all of an user's shares
877
+     *
878
+     * @param string $principaluri
879
+     * @return void
880
+     */
881
+    function deleteAllSharesByUser($principaluri) {
882
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
883
+    }
884
+
885
+    /**
886
+     * Returns all calendar objects within a calendar.
887
+     *
888
+     * Every item contains an array with the following keys:
889
+     *   * calendardata - The iCalendar-compatible calendar data
890
+     *   * uri - a unique key which will be used to construct the uri. This can
891
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
892
+     *     good idea. This is only the basename, or filename, not the full
893
+     *     path.
894
+     *   * lastmodified - a timestamp of the last modification time
895
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
896
+     *   '"abcdef"')
897
+     *   * size - The size of the calendar objects, in bytes.
898
+     *   * component - optional, a string containing the type of object, such
899
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
900
+     *     the Content-Type header.
901
+     *
902
+     * Note that the etag is optional, but it's highly encouraged to return for
903
+     * speed reasons.
904
+     *
905
+     * The calendardata is also optional. If it's not returned
906
+     * 'getCalendarObject' will be called later, which *is* expected to return
907
+     * calendardata.
908
+     *
909
+     * If neither etag or size are specified, the calendardata will be
910
+     * used/fetched to determine these numbers. If both are specified the
911
+     * amount of times this is needed is reduced by a great degree.
912
+     *
913
+     * @param mixed $id
914
+     * @param int $calendarType
915
+     * @return array
916
+     */
917
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
918
+        $query = $this->db->getQueryBuilder();
919
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920
+            ->from('calendarobjects')
921
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
922
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
923
+        $stmt = $query->execute();
924
+
925
+        $result = [];
926
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927
+            $result[] = [
928
+                'id'           => $row['id'],
929
+                'uri'          => $row['uri'],
930
+                'lastmodified' => $row['lastmodified'],
931
+                'etag'         => '"' . $row['etag'] . '"',
932
+                'calendarid'   => $row['calendarid'],
933
+                'size'         => (int)$row['size'],
934
+                'component'    => strtolower($row['componenttype']),
935
+                'classification'=> (int)$row['classification']
936
+            ];
937
+        }
938
+
939
+        return $result;
940
+    }
941
+
942
+    /**
943
+     * Returns information from a single calendar object, based on it's object
944
+     * uri.
945
+     *
946
+     * The object uri is only the basename, or filename and not a full path.
947
+     *
948
+     * The returned array must have the same keys as getCalendarObjects. The
949
+     * 'calendardata' object is required here though, while it's not required
950
+     * for getCalendarObjects.
951
+     *
952
+     * This method must return null if the object did not exist.
953
+     *
954
+     * @param mixed $id
955
+     * @param string $objectUri
956
+     * @param int $calendarType
957
+     * @return array|null
958
+     */
959
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
960
+        $query = $this->db->getQueryBuilder();
961
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962
+            ->from('calendarobjects')
963
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
964
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
965
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
966
+        $stmt = $query->execute();
967
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
968
+
969
+        if(!$row) {
970
+            return null;
971
+        }
972
+
973
+        return [
974
+            'id'            => $row['id'],
975
+            'uri'           => $row['uri'],
976
+            'lastmodified'  => $row['lastmodified'],
977
+            'etag'          => '"' . $row['etag'] . '"',
978
+            'calendarid'    => $row['calendarid'],
979
+            'size'          => (int)$row['size'],
980
+            'calendardata'  => $this->readBlob($row['calendardata']),
981
+            'component'     => strtolower($row['componenttype']),
982
+            'classification'=> (int)$row['classification']
983
+        ];
984
+    }
985
+
986
+    /**
987
+     * Returns a list of calendar objects.
988
+     *
989
+     * This method should work identical to getCalendarObject, but instead
990
+     * return all the calendar objects in the list as an array.
991
+     *
992
+     * If the backend supports this, it may allow for some speed-ups.
993
+     *
994
+     * @param mixed $calendarId
995
+     * @param string[] $uris
996
+     * @param int $calendarType
997
+     * @return array
998
+     */
999
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1000
+        if (empty($uris)) {
1001
+            return [];
1002
+        }
1003
+
1004
+        $chunks = array_chunk($uris, 100);
1005
+        $objects = [];
1006
+
1007
+        $query = $this->db->getQueryBuilder();
1008
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1009
+            ->from('calendarobjects')
1010
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1011
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1012
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1013
+
1014
+        foreach ($chunks as $uris) {
1015
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1016
+            $result = $query->execute();
1017
+
1018
+            while ($row = $result->fetch()) {
1019
+                $objects[] = [
1020
+                    'id'           => $row['id'],
1021
+                    'uri'          => $row['uri'],
1022
+                    'lastmodified' => $row['lastmodified'],
1023
+                    'etag'         => '"' . $row['etag'] . '"',
1024
+                    'calendarid'   => $row['calendarid'],
1025
+                    'size'         => (int)$row['size'],
1026
+                    'calendardata' => $this->readBlob($row['calendardata']),
1027
+                    'component'    => strtolower($row['componenttype']),
1028
+                    'classification' => (int)$row['classification']
1029
+                ];
1030
+            }
1031
+            $result->closeCursor();
1032
+        }
1033
+
1034
+        return $objects;
1035
+    }
1036
+
1037
+    /**
1038
+     * Creates a new calendar object.
1039
+     *
1040
+     * The object uri is only the basename, or filename and not a full path.
1041
+     *
1042
+     * It is possible return an etag from this function, which will be used in
1043
+     * the response to this PUT request. Note that the ETag must be surrounded
1044
+     * by double-quotes.
1045
+     *
1046
+     * However, you should only really return this ETag if you don't mangle the
1047
+     * calendar-data. If the result of a subsequent GET to this object is not
1048
+     * the exact same as this request body, you should omit the ETag.
1049
+     *
1050
+     * @param mixed $calendarId
1051
+     * @param string $objectUri
1052
+     * @param string $calendarData
1053
+     * @param int $calendarType
1054
+     * @return string
1055
+     */
1056
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1057
+        $extraData = $this->getDenormalizedData($calendarData);
1058
+
1059
+        $q = $this->db->getQueryBuilder();
1060
+        $q->select($q->func()->count('*'))
1061
+            ->from('calendarobjects')
1062
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1063
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1064
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1065
+
1066
+        $result = $q->execute();
1067
+        $count = (int) $result->fetchColumn();
1068
+        $result->closeCursor();
1069
+
1070
+        if ($count !== 0) {
1071
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1072
+        }
1073
+
1074
+        $query = $this->db->getQueryBuilder();
1075
+        $query->insert('calendarobjects')
1076
+            ->values([
1077
+                'calendarid' => $query->createNamedParameter($calendarId),
1078
+                'uri' => $query->createNamedParameter($objectUri),
1079
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1080
+                'lastmodified' => $query->createNamedParameter(time()),
1081
+                'etag' => $query->createNamedParameter($extraData['etag']),
1082
+                'size' => $query->createNamedParameter($extraData['size']),
1083
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1084
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1085
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1086
+                'classification' => $query->createNamedParameter($extraData['classification']),
1087
+                'uid' => $query->createNamedParameter($extraData['uid']),
1088
+                'calendartype' => $query->createNamedParameter($calendarType),
1089
+            ])
1090
+            ->execute();
1091
+
1092
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1093
+
1094
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1095
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1096
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1097
+                [
1098
+                    'calendarId' => $calendarId,
1099
+                    'calendarData' => $this->getCalendarById($calendarId),
1100
+                    'shares' => $this->getShares($calendarId),
1101
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1102
+                ]
1103
+            ));
1104
+        } else {
1105
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1106
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1107
+                [
1108
+                    'subscriptionId' => $calendarId,
1109
+                    'calendarData' => $this->getCalendarById($calendarId),
1110
+                    'shares' => $this->getShares($calendarId),
1111
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1112
+                ]
1113
+            ));
1114
+        }
1115
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1116
+
1117
+        return '"' . $extraData['etag'] . '"';
1118
+    }
1119
+
1120
+    /**
1121
+     * Updates an existing calendarobject, based on it's uri.
1122
+     *
1123
+     * The object uri is only the basename, or filename and not a full path.
1124
+     *
1125
+     * It is possible return an etag from this function, which will be used in
1126
+     * the response to this PUT request. Note that the ETag must be surrounded
1127
+     * by double-quotes.
1128
+     *
1129
+     * However, you should only really return this ETag if you don't mangle the
1130
+     * calendar-data. If the result of a subsequent GET to this object is not
1131
+     * the exact same as this request body, you should omit the ETag.
1132
+     *
1133
+     * @param mixed $calendarId
1134
+     * @param string $objectUri
1135
+     * @param string $calendarData
1136
+     * @param int $calendarType
1137
+     * @return string
1138
+     */
1139
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1140
+        $extraData = $this->getDenormalizedData($calendarData);
1141
+        $query = $this->db->getQueryBuilder();
1142
+        $query->update('calendarobjects')
1143
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1144
+                ->set('lastmodified', $query->createNamedParameter(time()))
1145
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1146
+                ->set('size', $query->createNamedParameter($extraData['size']))
1147
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1148
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1149
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1150
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1151
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1152
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1155
+            ->execute();
1156
+
1157
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1158
+
1159
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1160
+        if (is_array($data)) {
1161
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1162
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1163
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1164
+                    [
1165
+                        'calendarId' => $calendarId,
1166
+                        'calendarData' => $this->getCalendarById($calendarId),
1167
+                        'shares' => $this->getShares($calendarId),
1168
+                        'objectData' => $data,
1169
+                    ]
1170
+                ));
1171
+            } else {
1172
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1173
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1174
+                    [
1175
+                        'subscriptionId' => $calendarId,
1176
+                        'calendarData' => $this->getCalendarById($calendarId),
1177
+                        'shares' => $this->getShares($calendarId),
1178
+                        'objectData' => $data,
1179
+                    ]
1180
+                ));
1181
+            }
1182
+        }
1183
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1184
+
1185
+        return '"' . $extraData['etag'] . '"';
1186
+    }
1187
+
1188
+    /**
1189
+     * @param int $calendarObjectId
1190
+     * @param int $classification
1191
+     */
1192
+    public function setClassification($calendarObjectId, $classification) {
1193
+        if (!in_array($classification, [
1194
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1195
+        ])) {
1196
+            throw new \InvalidArgumentException();
1197
+        }
1198
+        $query = $this->db->getQueryBuilder();
1199
+        $query->update('calendarobjects')
1200
+            ->set('classification', $query->createNamedParameter($classification))
1201
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1202
+            ->execute();
1203
+    }
1204
+
1205
+    /**
1206
+     * Deletes an existing calendar object.
1207
+     *
1208
+     * The object uri is only the basename, or filename and not a full path.
1209
+     *
1210
+     * @param mixed $calendarId
1211
+     * @param string $objectUri
1212
+     * @param int $calendarType
1213
+     * @return void
1214
+     */
1215
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1216
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217
+        if (is_array($data)) {
1218
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1219
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1220
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1221
+                    [
1222
+                        'calendarId' => $calendarId,
1223
+                        'calendarData' => $this->getCalendarById($calendarId),
1224
+                        'shares' => $this->getShares($calendarId),
1225
+                        'objectData' => $data,
1226
+                    ]
1227
+                ));
1228
+            } else {
1229
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1230
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1231
+                    [
1232
+                        'subscriptionId' => $calendarId,
1233
+                        'calendarData' => $this->getCalendarById($calendarId),
1234
+                        'shares' => $this->getShares($calendarId),
1235
+                        'objectData' => $data,
1236
+                    ]
1237
+                ));
1238
+            }
1239
+        }
1240
+
1241
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1242
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1243
+
1244
+        if (is_array($data)) {
1245
+            $this->purgeProperties($calendarId, $data['id'], $calendarType);
1246
+        }
1247
+
1248
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1249
+    }
1250
+
1251
+    /**
1252
+     * Performs a calendar-query on the contents of this calendar.
1253
+     *
1254
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1255
+     * calendar-query it is possible for a client to request a specific set of
1256
+     * object, based on contents of iCalendar properties, date-ranges and
1257
+     * iCalendar component types (VTODO, VEVENT).
1258
+     *
1259
+     * This method should just return a list of (relative) urls that match this
1260
+     * query.
1261
+     *
1262
+     * The list of filters are specified as an array. The exact array is
1263
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1264
+     *
1265
+     * Note that it is extremely likely that getCalendarObject for every path
1266
+     * returned from this method will be called almost immediately after. You
1267
+     * may want to anticipate this to speed up these requests.
1268
+     *
1269
+     * This method provides a default implementation, which parses *all* the
1270
+     * iCalendar objects in the specified calendar.
1271
+     *
1272
+     * This default may well be good enough for personal use, and calendars
1273
+     * that aren't very large. But if you anticipate high usage, big calendars
1274
+     * or high loads, you are strongly advised to optimize certain paths.
1275
+     *
1276
+     * The best way to do so is override this method and to optimize
1277
+     * specifically for 'common filters'.
1278
+     *
1279
+     * Requests that are extremely common are:
1280
+     *   * requests for just VEVENTS
1281
+     *   * requests for just VTODO
1282
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1283
+     *
1284
+     * ..and combinations of these requests. It may not be worth it to try to
1285
+     * handle every possible situation and just rely on the (relatively
1286
+     * easy to use) CalendarQueryValidator to handle the rest.
1287
+     *
1288
+     * Note that especially time-range-filters may be difficult to parse. A
1289
+     * time-range filter specified on a VEVENT must for instance also handle
1290
+     * recurrence rules correctly.
1291
+     * A good example of how to interprete all these filters can also simply
1292
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1293
+     * as possible, so it gives you a good idea on what type of stuff you need
1294
+     * to think of.
1295
+     *
1296
+     * @param mixed $id
1297
+     * @param array $filters
1298
+     * @param int $calendarType
1299
+     * @return array
1300
+     */
1301
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1302
+        $componentType = null;
1303
+        $requirePostFilter = true;
1304
+        $timeRange = null;
1305
+
1306
+        // if no filters were specified, we don't need to filter after a query
1307
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1308
+            $requirePostFilter = false;
1309
+        }
1310
+
1311
+        // Figuring out if there's a component filter
1312
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1313
+            $componentType = $filters['comp-filters'][0]['name'];
1314
+
1315
+            // Checking if we need post-filters
1316
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1317
+                $requirePostFilter = false;
1318
+            }
1319
+            // There was a time-range filter
1320
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1321
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1322
+
1323
+                // If start time OR the end time is not specified, we can do a
1324
+                // 100% accurate mysql query.
1325
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1326
+                    $requirePostFilter = false;
1327
+                }
1328
+            }
1329
+
1330
+        }
1331
+        $columns = ['uri'];
1332
+        if ($requirePostFilter) {
1333
+            $columns = ['uri', 'calendardata'];
1334
+        }
1335
+        $query = $this->db->getQueryBuilder();
1336
+        $query->select($columns)
1337
+            ->from('calendarobjects')
1338
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1339
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1340
+
1341
+        if ($componentType) {
1342
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1343
+        }
1344
+
1345
+        if ($timeRange && $timeRange['start']) {
1346
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1347
+        }
1348
+        if ($timeRange && $timeRange['end']) {
1349
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1350
+        }
1351
+
1352
+        $stmt = $query->execute();
1353
+
1354
+        $result = [];
1355
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356
+            if ($requirePostFilter) {
1357
+                // validateFilterForObject will parse the calendar data
1358
+                // catch parsing errors
1359
+                try {
1360
+                    $matches = $this->validateFilterForObject($row, $filters);
1361
+                } catch(ParseException $ex) {
1362
+                    $this->logger->logException($ex, [
1363
+                        'app' => 'dav',
1364
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1365
+                    ]);
1366
+                    continue;
1367
+                } catch (InvalidDataException $ex) {
1368
+                    $this->logger->logException($ex, [
1369
+                        'app' => 'dav',
1370
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1371
+                    ]);
1372
+                    continue;
1373
+                }
1374
+
1375
+                if (!$matches) {
1376
+                    continue;
1377
+                }
1378
+            }
1379
+            $result[] = $row['uri'];
1380
+        }
1381
+
1382
+        return $result;
1383
+    }
1384
+
1385
+    /**
1386
+     * custom Nextcloud search extension for CalDAV
1387
+     *
1388
+     * TODO - this should optionally cover cached calendar objects as well
1389
+     *
1390
+     * @param string $principalUri
1391
+     * @param array $filters
1392
+     * @param integer|null $limit
1393
+     * @param integer|null $offset
1394
+     * @return array
1395
+     */
1396
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1397
+        $calendars = $this->getCalendarsForUser($principalUri);
1398
+        $ownCalendars = [];
1399
+        $sharedCalendars = [];
1400
+
1401
+        $uriMapper = [];
1402
+
1403
+        foreach($calendars as $calendar) {
1404
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405
+                $ownCalendars[] = $calendar['id'];
1406
+            } else {
1407
+                $sharedCalendars[] = $calendar['id'];
1408
+            }
1409
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1410
+        }
1411
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1412
+            return [];
1413
+        }
1414
+
1415
+        $query = $this->db->getQueryBuilder();
1416
+        // Calendar id expressions
1417
+        $calendarExpressions = [];
1418
+        foreach($ownCalendars as $id) {
1419
+            $calendarExpressions[] = $query->expr()->andX(
1420
+                $query->expr()->eq('c.calendarid',
1421
+                    $query->createNamedParameter($id)),
1422
+                $query->expr()->eq('c.calendartype',
1423
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424
+        }
1425
+        foreach($sharedCalendars as $id) {
1426
+            $calendarExpressions[] = $query->expr()->andX(
1427
+                $query->expr()->eq('c.calendarid',
1428
+                    $query->createNamedParameter($id)),
1429
+                $query->expr()->eq('c.classification',
1430
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1431
+                $query->expr()->eq('c.calendartype',
1432
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1433
+        }
1434
+
1435
+        if (count($calendarExpressions) === 1) {
1436
+            $calExpr = $calendarExpressions[0];
1437
+        } else {
1438
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1439
+        }
1440
+
1441
+        // Component expressions
1442
+        $compExpressions = [];
1443
+        foreach($filters['comps'] as $comp) {
1444
+            $compExpressions[] = $query->expr()
1445
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1446
+        }
1447
+
1448
+        if (count($compExpressions) === 1) {
1449
+            $compExpr = $compExpressions[0];
1450
+        } else {
1451
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1452
+        }
1453
+
1454
+        if (!isset($filters['props'])) {
1455
+            $filters['props'] = [];
1456
+        }
1457
+        if (!isset($filters['params'])) {
1458
+            $filters['params'] = [];
1459
+        }
1460
+
1461
+        $propParamExpressions = [];
1462
+        foreach($filters['props'] as $prop) {
1463
+            $propParamExpressions[] = $query->expr()->andX(
1464
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465
+                $query->expr()->isNull('i.parameter')
1466
+            );
1467
+        }
1468
+        foreach($filters['params'] as $param) {
1469
+            $propParamExpressions[] = $query->expr()->andX(
1470
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1472
+            );
1473
+        }
1474
+
1475
+        if (count($propParamExpressions) === 1) {
1476
+            $propParamExpr = $propParamExpressions[0];
1477
+        } else {
1478
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1479
+        }
1480
+
1481
+        $query->select(['c.calendarid', 'c.uri'])
1482
+            ->from($this->dbObjectPropertiesTable, 'i')
1483
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1484
+            ->where($calExpr)
1485
+            ->andWhere($compExpr)
1486
+            ->andWhere($propParamExpr)
1487
+            ->andWhere($query->expr()->iLike('i.value',
1488
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1489
+
1490
+        if ($offset) {
1491
+            $query->setFirstResult($offset);
1492
+        }
1493
+        if ($limit) {
1494
+            $query->setMaxResults($limit);
1495
+        }
1496
+
1497
+        $stmt = $query->execute();
1498
+
1499
+        $result = [];
1500
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1502
+            if (!in_array($path, $result)) {
1503
+                $result[] = $path;
1504
+            }
1505
+        }
1506
+
1507
+        return $result;
1508
+    }
1509
+
1510
+    /**
1511
+     * used for Nextcloud's calendar API
1512
+     *
1513
+     * @param array $calendarInfo
1514
+     * @param string $pattern
1515
+     * @param array $searchProperties
1516
+     * @param array $options
1517
+     * @param integer|null $limit
1518
+     * @param integer|null $offset
1519
+     *
1520
+     * @return array
1521
+     */
1522
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1523
+                            array $options, $limit, $offset) {
1524
+        $outerQuery = $this->db->getQueryBuilder();
1525
+        $innerQuery = $this->db->getQueryBuilder();
1526
+
1527
+        $innerQuery->selectDistinct('op.objectid')
1528
+            ->from($this->dbObjectPropertiesTable, 'op')
1529
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1530
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1531
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1532
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1533
+
1534
+        // only return public items for shared calendars for now
1535
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1536
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1537
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1538
+        }
1539
+
1540
+        $or = $innerQuery->expr()->orX();
1541
+        foreach($searchProperties as $searchProperty) {
1542
+            $or->add($innerQuery->expr()->eq('op.name',
1543
+                $outerQuery->createNamedParameter($searchProperty)));
1544
+        }
1545
+        $innerQuery->andWhere($or);
1546
+
1547
+        if ($pattern !== '') {
1548
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
+                $outerQuery->createNamedParameter('%' .
1550
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1551
+        }
1552
+
1553
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1554
+            ->from('calendarobjects', 'c');
1555
+
1556
+        if (isset($options['timerange'])) {
1557
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1558
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1559
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1560
+
1561
+            }
1562
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1563
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1564
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1565
+            }
1566
+        }
1567
+
1568
+        if (isset($options['types'])) {
1569
+            $or = $outerQuery->expr()->orX();
1570
+            foreach($options['types'] as $type) {
1571
+                $or->add($outerQuery->expr()->eq('componenttype',
1572
+                    $outerQuery->createNamedParameter($type)));
1573
+            }
1574
+            $outerQuery->andWhere($or);
1575
+        }
1576
+
1577
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1578
+            $outerQuery->createFunction($innerQuery->getSQL())));
1579
+
1580
+        if ($offset) {
1581
+            $outerQuery->setFirstResult($offset);
1582
+        }
1583
+        if ($limit) {
1584
+            $outerQuery->setMaxResults($limit);
1585
+        }
1586
+
1587
+        $result = $outerQuery->execute();
1588
+        $calendarObjects = $result->fetchAll();
1589
+
1590
+        return array_map(function($o) {
1591
+            $calendarData = Reader::read($o['calendardata']);
1592
+            $comps = $calendarData->getComponents();
1593
+            $objects = [];
1594
+            $timezones = [];
1595
+            foreach($comps as $comp) {
1596
+                if ($comp instanceof VTimeZone) {
1597
+                    $timezones[] = $comp;
1598
+                } else {
1599
+                    $objects[] = $comp;
1600
+                }
1601
+            }
1602
+
1603
+            return [
1604
+                'id' => $o['id'],
1605
+                'type' => $o['componenttype'],
1606
+                'uid' => $o['uid'],
1607
+                'uri' => $o['uri'],
1608
+                'objects' => array_map(function($c) {
1609
+                    return $this->transformSearchData($c);
1610
+                }, $objects),
1611
+                'timezones' => array_map(function($c) {
1612
+                    return $this->transformSearchData($c);
1613
+                }, $timezones),
1614
+            ];
1615
+        }, $calendarObjects);
1616
+    }
1617
+
1618
+    /**
1619
+     * @param Component $comp
1620
+     * @return array
1621
+     */
1622
+    private function transformSearchData(Component $comp) {
1623
+        $data = [];
1624
+        /** @var Component[] $subComponents */
1625
+        $subComponents = $comp->getComponents();
1626
+        /** @var Property[] $properties */
1627
+        $properties = array_filter($comp->children(), function($c) {
1628
+            return $c instanceof Property;
1629
+        });
1630
+        $validationRules = $comp->getValidationRules();
1631
+
1632
+        foreach($subComponents as $subComponent) {
1633
+            $name = $subComponent->name;
1634
+            if (!isset($data[$name])) {
1635
+                $data[$name] = [];
1636
+            }
1637
+            $data[$name][] = $this->transformSearchData($subComponent);
1638
+        }
1639
+
1640
+        foreach($properties as $property) {
1641
+            $name = $property->name;
1642
+            if (!isset($validationRules[$name])) {
1643
+                $validationRules[$name] = '*';
1644
+            }
1645
+
1646
+            $rule = $validationRules[$property->name];
1647
+            if ($rule === '+' || $rule === '*') { // multiple
1648
+                if (!isset($data[$name])) {
1649
+                    $data[$name] = [];
1650
+                }
1651
+
1652
+                $data[$name][] = $this->transformSearchProperty($property);
1653
+            } else { // once
1654
+                $data[$name] = $this->transformSearchProperty($property);
1655
+            }
1656
+        }
1657
+
1658
+        return $data;
1659
+    }
1660
+
1661
+    /**
1662
+     * @param Property $prop
1663
+     * @return array
1664
+     */
1665
+    private function transformSearchProperty(Property $prop) {
1666
+        // No need to check Date, as it extends DateTime
1667
+        if ($prop instanceof Property\ICalendar\DateTime) {
1668
+            $value = $prop->getDateTime();
1669
+        } else {
1670
+            $value = $prop->getValue();
1671
+        }
1672
+
1673
+        return [
1674
+            $value,
1675
+            $prop->parameters()
1676
+        ];
1677
+    }
1678
+
1679
+    /**
1680
+     * Searches through all of a users calendars and calendar objects to find
1681
+     * an object with a specific UID.
1682
+     *
1683
+     * This method should return the path to this object, relative to the
1684
+     * calendar home, so this path usually only contains two parts:
1685
+     *
1686
+     * calendarpath/objectpath.ics
1687
+     *
1688
+     * If the uid is not found, return null.
1689
+     *
1690
+     * This method should only consider * objects that the principal owns, so
1691
+     * any calendars owned by other principals that also appear in this
1692
+     * collection should be ignored.
1693
+     *
1694
+     * @param string $principalUri
1695
+     * @param string $uid
1696
+     * @return string|null
1697
+     */
1698
+    function getCalendarObjectByUID($principalUri, $uid) {
1699
+
1700
+        $query = $this->db->getQueryBuilder();
1701
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1702
+            ->from('calendarobjects', 'co')
1703
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1704
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1705
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1706
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1707
+
1708
+        $stmt = $query->execute();
1709
+
1710
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1712
+        }
1713
+
1714
+        return null;
1715
+    }
1716
+
1717
+    /**
1718
+     * The getChanges method returns all the changes that have happened, since
1719
+     * the specified syncToken in the specified calendar.
1720
+     *
1721
+     * This function should return an array, such as the following:
1722
+     *
1723
+     * [
1724
+     *   'syncToken' => 'The current synctoken',
1725
+     *   'added'   => [
1726
+     *      'new.txt',
1727
+     *   ],
1728
+     *   'modified'   => [
1729
+     *      'modified.txt',
1730
+     *   ],
1731
+     *   'deleted' => [
1732
+     *      'foo.php.bak',
1733
+     *      'old.txt'
1734
+     *   ]
1735
+     * );
1736
+     *
1737
+     * The returned syncToken property should reflect the *current* syncToken
1738
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1739
+     * property This is * needed here too, to ensure the operation is atomic.
1740
+     *
1741
+     * If the $syncToken argument is specified as null, this is an initial
1742
+     * sync, and all members should be reported.
1743
+     *
1744
+     * The modified property is an array of nodenames that have changed since
1745
+     * the last token.
1746
+     *
1747
+     * The deleted property is an array with nodenames, that have been deleted
1748
+     * from collection.
1749
+     *
1750
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1751
+     * 1, you only have to report changes that happened only directly in
1752
+     * immediate descendants. If it's 2, it should also include changes from
1753
+     * the nodes below the child collections. (grandchildren)
1754
+     *
1755
+     * The $limit argument allows a client to specify how many results should
1756
+     * be returned at most. If the limit is not specified, it should be treated
1757
+     * as infinite.
1758
+     *
1759
+     * If the limit (infinite or not) is higher than you're willing to return,
1760
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1761
+     *
1762
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1763
+     * return null.
1764
+     *
1765
+     * The limit is 'suggestive'. You are free to ignore it.
1766
+     *
1767
+     * @param string $calendarId
1768
+     * @param string $syncToken
1769
+     * @param int $syncLevel
1770
+     * @param int $limit
1771
+     * @param int $calendarType
1772
+     * @return array
1773
+     */
1774
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1775
+        // Current synctoken
1776
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
+        $stmt->execute([ $calendarId ]);
1778
+        $currentToken = $stmt->fetchColumn(0);
1779
+
1780
+        if (is_null($currentToken)) {
1781
+            return null;
1782
+        }
1783
+
1784
+        $result = [
1785
+            'syncToken' => $currentToken,
1786
+            'added'     => [],
1787
+            'modified'  => [],
1788
+            'deleted'   => [],
1789
+        ];
1790
+
1791
+        if ($syncToken) {
1792
+
1793
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
+            if ($limit>0) {
1795
+                $query.= " LIMIT " . (int)$limit;
1796
+            }
1797
+
1798
+            // Fetching all changes
1799
+            $stmt = $this->db->prepare($query);
1800
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1801
+
1802
+            $changes = [];
1803
+
1804
+            // This loop ensures that any duplicates are overwritten, only the
1805
+            // last change on a node is relevant.
1806
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807
+
1808
+                $changes[$row['uri']] = $row['operation'];
1809
+
1810
+            }
1811
+
1812
+            foreach($changes as $uri => $operation) {
1813
+
1814
+                switch($operation) {
1815
+                    case 1 :
1816
+                        $result['added'][] = $uri;
1817
+                        break;
1818
+                    case 2 :
1819
+                        $result['modified'][] = $uri;
1820
+                        break;
1821
+                    case 3 :
1822
+                        $result['deleted'][] = $uri;
1823
+                        break;
1824
+                }
1825
+
1826
+            }
1827
+        } else {
1828
+            // No synctoken supplied, this is the initial sync.
1829
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1830
+            $stmt = $this->db->prepare($query);
1831
+            $stmt->execute([$calendarId, $calendarType]);
1832
+
1833
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1834
+        }
1835
+        return $result;
1836
+
1837
+    }
1838
+
1839
+    /**
1840
+     * Returns a list of subscriptions for a principal.
1841
+     *
1842
+     * Every subscription is an array with the following keys:
1843
+     *  * id, a unique id that will be used by other functions to modify the
1844
+     *    subscription. This can be the same as the uri or a database key.
1845
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1846
+     *  * principaluri. The owner of the subscription. Almost always the same as
1847
+     *    principalUri passed to this method.
1848
+     *
1849
+     * Furthermore, all the subscription info must be returned too:
1850
+     *
1851
+     * 1. {DAV:}displayname
1852
+     * 2. {http://apple.com/ns/ical/}refreshrate
1853
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1854
+     *    should not be stripped).
1855
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1856
+     *    should not be stripped).
1857
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1858
+     *    attachments should not be stripped).
1859
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1860
+     *     Sabre\DAV\Property\Href).
1861
+     * 7. {http://apple.com/ns/ical/}calendar-color
1862
+     * 8. {http://apple.com/ns/ical/}calendar-order
1863
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1864
+     *    (should just be an instance of
1865
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1866
+     *    default components).
1867
+     *
1868
+     * @param string $principalUri
1869
+     * @return array
1870
+     */
1871
+    function getSubscriptionsForUser($principalUri) {
1872
+        $fields = array_values($this->subscriptionPropertyMap);
1873
+        $fields[] = 'id';
1874
+        $fields[] = 'uri';
1875
+        $fields[] = 'source';
1876
+        $fields[] = 'principaluri';
1877
+        $fields[] = 'lastmodified';
1878
+        $fields[] = 'synctoken';
1879
+
1880
+        $query = $this->db->getQueryBuilder();
1881
+        $query->select($fields)
1882
+            ->from('calendarsubscriptions')
1883
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884
+            ->orderBy('calendarorder', 'asc');
1885
+        $stmt =$query->execute();
1886
+
1887
+        $subscriptions = [];
1888
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889
+
1890
+            $subscription = [
1891
+                'id'           => $row['id'],
1892
+                'uri'          => $row['uri'],
1893
+                'principaluri' => $row['principaluri'],
1894
+                'source'       => $row['source'],
1895
+                'lastmodified' => $row['lastmodified'],
1896
+
1897
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1899
+            ];
1900
+
1901
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902
+                if (!is_null($row[$dbName])) {
1903
+                    $subscription[$xmlName] = $row[$dbName];
1904
+                }
1905
+            }
1906
+
1907
+            $subscriptions[] = $subscription;
1908
+
1909
+        }
1910
+
1911
+        return $subscriptions;
1912
+    }
1913
+
1914
+    /**
1915
+     * Creates a new subscription for a principal.
1916
+     *
1917
+     * If the creation was a success, an id must be returned that can be used to reference
1918
+     * this subscription in other methods, such as updateSubscription.
1919
+     *
1920
+     * @param string $principalUri
1921
+     * @param string $uri
1922
+     * @param array $properties
1923
+     * @return mixed
1924
+     */
1925
+    function createSubscription($principalUri, $uri, array $properties) {
1926
+
1927
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1928
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1929
+        }
1930
+
1931
+        $values = [
1932
+            'principaluri' => $principalUri,
1933
+            'uri'          => $uri,
1934
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1935
+            'lastmodified' => time(),
1936
+        ];
1937
+
1938
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939
+
1940
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941
+            if (array_key_exists($xmlName, $properties)) {
1942
+                    $values[$dbName] = $properties[$xmlName];
1943
+                    if (in_array($dbName, $propertiesBoolean)) {
1944
+                        $values[$dbName] = true;
1945
+                }
1946
+            }
1947
+        }
1948
+
1949
+        $valuesToInsert = [];
1950
+
1951
+        $query = $this->db->getQueryBuilder();
1952
+
1953
+        foreach (array_keys($values) as $name) {
1954
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1955
+        }
1956
+
1957
+        $query->insert('calendarsubscriptions')
1958
+            ->values($valuesToInsert)
1959
+            ->execute();
1960
+
1961
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1962
+
1963
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1964
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1965
+            [
1966
+                'subscriptionId' => $subscriptionId,
1967
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1968
+            ]));
1969
+
1970
+        return $subscriptionId;
1971
+    }
1972
+
1973
+    /**
1974
+     * Updates a subscription
1975
+     *
1976
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1977
+     * To do the actual updates, you must tell this object which properties
1978
+     * you're going to process with the handle() method.
1979
+     *
1980
+     * Calling the handle method is like telling the PropPatch object "I
1981
+     * promise I can handle updating this property".
1982
+     *
1983
+     * Read the PropPatch documentation for more info and examples.
1984
+     *
1985
+     * @param mixed $subscriptionId
1986
+     * @param PropPatch $propPatch
1987
+     * @return void
1988
+     */
1989
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1990
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1991
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1992
+
1993
+        /**
1994
+         * @suppress SqlInjectionChecker
1995
+         */
1996
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1997
+
1998
+            $newValues = [];
1999
+
2000
+            foreach($mutations as $propertyName=>$propertyValue) {
2001
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002
+                    $newValues['source'] = $propertyValue->getHref();
2003
+                } else {
2004
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2005
+                    $newValues[$fieldName] = $propertyValue;
2006
+                }
2007
+            }
2008
+
2009
+            $query = $this->db->getQueryBuilder();
2010
+            $query->update('calendarsubscriptions')
2011
+                ->set('lastmodified', $query->createNamedParameter(time()));
2012
+            foreach($newValues as $fieldName=>$value) {
2013
+                $query->set($fieldName, $query->createNamedParameter($value));
2014
+            }
2015
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2016
+                ->execute();
2017
+
2018
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2019
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2020
+                [
2021
+                    'subscriptionId' => $subscriptionId,
2022
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2023
+                    'propertyMutations' => $mutations,
2024
+                ]));
2025
+
2026
+            return true;
2027
+
2028
+        });
2029
+    }
2030
+
2031
+    /**
2032
+     * Deletes a subscription.
2033
+     *
2034
+     * @param mixed $subscriptionId
2035
+     * @return void
2036
+     */
2037
+    function deleteSubscription($subscriptionId) {
2038
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2039
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2040
+            [
2041
+                'subscriptionId' => $subscriptionId,
2042
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2043
+            ]));
2044
+
2045
+        $query = $this->db->getQueryBuilder();
2046
+        $query->delete('calendarsubscriptions')
2047
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2048
+            ->execute();
2049
+
2050
+        $query = $this->db->getQueryBuilder();
2051
+        $query->delete('calendarobjects')
2052
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2053
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2054
+            ->execute();
2055
+
2056
+        $query->delete('calendarchanges')
2057
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2058
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2059
+            ->execute();
2060
+
2061
+        $query->delete($this->dbObjectPropertiesTable)
2062
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2063
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2064
+            ->execute();
2065
+    }
2066
+
2067
+    /**
2068
+     * Returns a single scheduling object for the inbox collection.
2069
+     *
2070
+     * The returned array should contain the following elements:
2071
+     *   * uri - A unique basename for the object. This will be used to
2072
+     *           construct a full uri.
2073
+     *   * calendardata - The iCalendar object
2074
+     *   * lastmodified - The last modification date. Can be an int for a unix
2075
+     *                    timestamp, or a PHP DateTime object.
2076
+     *   * etag - A unique token that must change if the object changed.
2077
+     *   * size - The size of the object, in bytes.
2078
+     *
2079
+     * @param string $principalUri
2080
+     * @param string $objectUri
2081
+     * @return array
2082
+     */
2083
+    function getSchedulingObject($principalUri, $objectUri) {
2084
+        $query = $this->db->getQueryBuilder();
2085
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2086
+            ->from('schedulingobjects')
2087
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2088
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2089
+            ->execute();
2090
+
2091
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092
+
2093
+        if(!$row) {
2094
+            return null;
2095
+        }
2096
+
2097
+        return [
2098
+            'uri'          => $row['uri'],
2099
+            'calendardata' => $row['calendardata'],
2100
+            'lastmodified' => $row['lastmodified'],
2101
+            'etag'         => '"' . $row['etag'] . '"',
2102
+            'size'         => (int)$row['size'],
2103
+        ];
2104
+    }
2105
+
2106
+    /**
2107
+     * Returns all scheduling objects for the inbox collection.
2108
+     *
2109
+     * These objects should be returned as an array. Every item in the array
2110
+     * should follow the same structure as returned from getSchedulingObject.
2111
+     *
2112
+     * The main difference is that 'calendardata' is optional.
2113
+     *
2114
+     * @param string $principalUri
2115
+     * @return array
2116
+     */
2117
+    function getSchedulingObjects($principalUri) {
2118
+        $query = $this->db->getQueryBuilder();
2119
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2120
+                ->from('schedulingobjects')
2121
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2122
+                ->execute();
2123
+
2124
+        $result = [];
2125
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126
+            $result[] = [
2127
+                'calendardata' => $row['calendardata'],
2128
+                'uri'          => $row['uri'],
2129
+                'lastmodified' => $row['lastmodified'],
2130
+                'etag'         => '"' . $row['etag'] . '"',
2131
+                'size'         => (int)$row['size'],
2132
+            ];
2133
+        }
2134
+
2135
+        return $result;
2136
+    }
2137
+
2138
+    /**
2139
+     * Deletes a scheduling object from the inbox collection.
2140
+     *
2141
+     * @param string $principalUri
2142
+     * @param string $objectUri
2143
+     * @return void
2144
+     */
2145
+    function deleteSchedulingObject($principalUri, $objectUri) {
2146
+        $query = $this->db->getQueryBuilder();
2147
+        $query->delete('schedulingobjects')
2148
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2149
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2150
+                ->execute();
2151
+    }
2152
+
2153
+    /**
2154
+     * Creates a new scheduling object. This should land in a users' inbox.
2155
+     *
2156
+     * @param string $principalUri
2157
+     * @param string $objectUri
2158
+     * @param string $objectData
2159
+     * @return void
2160
+     */
2161
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2162
+        $query = $this->db->getQueryBuilder();
2163
+        $query->insert('schedulingobjects')
2164
+            ->values([
2165
+                'principaluri' => $query->createNamedParameter($principalUri),
2166
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2167
+                'uri' => $query->createNamedParameter($objectUri),
2168
+                'lastmodified' => $query->createNamedParameter(time()),
2169
+                'etag' => $query->createNamedParameter(md5($objectData)),
2170
+                'size' => $query->createNamedParameter(strlen($objectData))
2171
+            ])
2172
+            ->execute();
2173
+    }
2174
+
2175
+    /**
2176
+     * Adds a change record to the calendarchanges table.
2177
+     *
2178
+     * @param mixed $calendarId
2179
+     * @param string $objectUri
2180
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2181
+     * @param int $calendarType
2182
+     * @return void
2183
+     */
2184
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2186
+
2187
+        $query = $this->db->getQueryBuilder();
2188
+        $query->select('synctoken')
2189
+            ->from($table)
2190
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
+        $syncToken = (int)$query->execute()->fetchColumn();
2192
+
2193
+        $query = $this->db->getQueryBuilder();
2194
+        $query->insert('calendarchanges')
2195
+            ->values([
2196
+                'uri' => $query->createNamedParameter($objectUri),
2197
+                'synctoken' => $query->createNamedParameter($syncToken),
2198
+                'calendarid' => $query->createNamedParameter($calendarId),
2199
+                'operation' => $query->createNamedParameter($operation),
2200
+                'calendartype' => $query->createNamedParameter($calendarType),
2201
+            ])
2202
+            ->execute();
2203
+
2204
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2205
+        $stmt->execute([
2206
+            $calendarId
2207
+        ]);
2208
+
2209
+    }
2210
+
2211
+    /**
2212
+     * Parses some information from calendar objects, used for optimized
2213
+     * calendar-queries.
2214
+     *
2215
+     * Returns an array with the following keys:
2216
+     *   * etag - An md5 checksum of the object without the quotes.
2217
+     *   * size - Size of the object in bytes
2218
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2219
+     *   * firstOccurence
2220
+     *   * lastOccurence
2221
+     *   * uid - value of the UID property
2222
+     *
2223
+     * @param string $calendarData
2224
+     * @return array
2225
+     */
2226
+    public function getDenormalizedData($calendarData) {
2227
+
2228
+        $vObject = Reader::read($calendarData);
2229
+        $componentType = null;
2230
+        $component = null;
2231
+        $firstOccurrence = null;
2232
+        $lastOccurrence = null;
2233
+        $uid = null;
2234
+        $classification = self::CLASSIFICATION_PUBLIC;
2235
+        foreach($vObject->getComponents() as $component) {
2236
+            if ($component->name!=='VTIMEZONE') {
2237
+                $componentType = $component->name;
2238
+                $uid = (string)$component->UID;
2239
+                break;
2240
+            }
2241
+        }
2242
+        if (!$componentType) {
2243
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2244
+        }
2245
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2246
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2247
+            // Finding the last occurrence is a bit harder
2248
+            if (!isset($component->RRULE)) {
2249
+                if (isset($component->DTEND)) {
2250
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2251
+                } elseif (isset($component->DURATION)) {
2252
+                    $endDate = clone $component->DTSTART->getDateTime();
2253
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2254
+                    $lastOccurrence = $endDate->getTimeStamp();
2255
+                } elseif (!$component->DTSTART->hasTime()) {
2256
+                    $endDate = clone $component->DTSTART->getDateTime();
2257
+                    $endDate->modify('+1 day');
2258
+                    $lastOccurrence = $endDate->getTimeStamp();
2259
+                } else {
2260
+                    $lastOccurrence = $firstOccurrence;
2261
+                }
2262
+            } else {
2263
+                $it = new EventIterator($vObject, (string)$component->UID);
2264
+                $maxDate = new DateTime(self::MAX_DATE);
2265
+                if ($it->isInfinite()) {
2266
+                    $lastOccurrence = $maxDate->getTimestamp();
2267
+                } else {
2268
+                    $end = $it->getDtEnd();
2269
+                    while($it->valid() && $end < $maxDate) {
2270
+                        $end = $it->getDtEnd();
2271
+                        $it->next();
2272
+
2273
+                    }
2274
+                    $lastOccurrence = $end->getTimestamp();
2275
+                }
2276
+
2277
+            }
2278
+        }
2279
+
2280
+        if ($component->CLASS) {
2281
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2282
+            switch ($component->CLASS->getValue()) {
2283
+                case 'PUBLIC':
2284
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2285
+                    break;
2286
+                case 'CONFIDENTIAL':
2287
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2288
+                    break;
2289
+            }
2290
+        }
2291
+        return [
2292
+            'etag' => md5($calendarData),
2293
+            'size' => strlen($calendarData),
2294
+            'componentType' => $componentType,
2295
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2296
+            'lastOccurence'  => $lastOccurrence,
2297
+            'uid' => $uid,
2298
+            'classification' => $classification
2299
+        ];
2300
+
2301
+    }
2302
+
2303
+    /**
2304
+     * @param $cardData
2305
+     * @return bool|string
2306
+     */
2307
+    private function readBlob($cardData) {
2308
+        if (is_resource($cardData)) {
2309
+            return stream_get_contents($cardData);
2310
+        }
2311
+
2312
+        return $cardData;
2313
+    }
2314
+
2315
+    /**
2316
+     * @param IShareable $shareable
2317
+     * @param array $add
2318
+     * @param array $remove
2319
+     */
2320
+    public function updateShares($shareable, $add, $remove) {
2321
+        $calendarId = $shareable->getResourceId();
2322
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2323
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2324
+            [
2325
+                'calendarId' => $calendarId,
2326
+                'calendarData' => $this->getCalendarById($calendarId),
2327
+                'shares' => $this->getShares($calendarId),
2328
+                'add' => $add,
2329
+                'remove' => $remove,
2330
+            ]));
2331
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2332
+    }
2333
+
2334
+    /**
2335
+     * @param int $resourceId
2336
+     * @param int $calendarType
2337
+     * @return array
2338
+     */
2339
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2340
+        return $this->calendarSharingBackend->getShares($resourceId);
2341
+    }
2342
+
2343
+    /**
2344
+     * @param boolean $value
2345
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2346
+     * @return string|null
2347
+     */
2348
+    public function setPublishStatus($value, $calendar) {
2349
+
2350
+        $calendarId = $calendar->getResourceId();
2351
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2352
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2353
+            [
2354
+                'calendarId' => $calendarId,
2355
+                'calendarData' => $this->getCalendarById($calendarId),
2356
+                'public' => $value,
2357
+            ]));
2358
+
2359
+        $query = $this->db->getQueryBuilder();
2360
+        if ($value) {
2361
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2362
+            $query->insert('dav_shares')
2363
+                ->values([
2364
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2365
+                    'type' => $query->createNamedParameter('calendar'),
2366
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2367
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2368
+                    'publicuri' => $query->createNamedParameter($publicUri)
2369
+                ]);
2370
+            $query->execute();
2371
+            return $publicUri;
2372
+        }
2373
+        $query->delete('dav_shares')
2374
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2375
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2376
+        $query->execute();
2377
+        return null;
2378
+    }
2379
+
2380
+    /**
2381
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2382
+     * @return mixed
2383
+     */
2384
+    public function getPublishStatus($calendar) {
2385
+        $query = $this->db->getQueryBuilder();
2386
+        $result = $query->select('publicuri')
2387
+            ->from('dav_shares')
2388
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2389
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2390
+            ->execute();
2391
+
2392
+        $row = $result->fetch();
2393
+        $result->closeCursor();
2394
+        return $row ? reset($row) : false;
2395
+    }
2396
+
2397
+    /**
2398
+     * @param int $resourceId
2399
+     * @param array $acl
2400
+     * @return array
2401
+     */
2402
+    public function applyShareAcl($resourceId, $acl) {
2403
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2404
+    }
2405
+
2406
+
2407
+
2408
+    /**
2409
+     * update properties table
2410
+     *
2411
+     * @param int $calendarId
2412
+     * @param string $objectUri
2413
+     * @param string $calendarData
2414
+     * @param int $calendarType
2415
+     */
2416
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2417
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418
+
2419
+        try {
2420
+            $vCalendar = $this->readCalendarData($calendarData);
2421
+        } catch (\Exception $ex) {
2422
+            return;
2423
+        }
2424
+
2425
+        $this->purgeProperties($calendarId, $objectId);
2426
+
2427
+        $query = $this->db->getQueryBuilder();
2428
+        $query->insert($this->dbObjectPropertiesTable)
2429
+            ->values(
2430
+                [
2431
+                    'calendarid' => $query->createNamedParameter($calendarId),
2432
+                    'calendartype' => $query->createNamedParameter($calendarType),
2433
+                    'objectid' => $query->createNamedParameter($objectId),
2434
+                    'name' => $query->createParameter('name'),
2435
+                    'parameter' => $query->createParameter('parameter'),
2436
+                    'value' => $query->createParameter('value'),
2437
+                ]
2438
+            );
2439
+
2440
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2441
+        foreach ($vCalendar->getComponents() as $component) {
2442
+            if (!in_array($component->name, $indexComponents)) {
2443
+                continue;
2444
+            }
2445
+
2446
+            foreach ($component->children() as $property) {
2447
+                if (in_array($property->name, self::$indexProperties)) {
2448
+                    $value = $property->getValue();
2449
+                    // is this a shitty db?
2450
+                    if (!$this->db->supports4ByteText()) {
2451
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2452
+                    }
2453
+                    $value = mb_substr($value, 0, 254);
2454
+
2455
+                    $query->setParameter('name', $property->name);
2456
+                    $query->setParameter('parameter', null);
2457
+                    $query->setParameter('value', $value);
2458
+                    $query->execute();
2459
+                }
2460
+
2461
+                if (array_key_exists($property->name, self::$indexParameters)) {
2462
+                    $parameters = $property->parameters();
2463
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2464
+
2465
+                    foreach ($parameters as $key => $value) {
2466
+                        if (in_array($key, $indexedParametersForProperty)) {
2467
+                            // is this a shitty db?
2468
+                            if ($this->db->supports4ByteText()) {
2469
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2470
+                            }
2471
+
2472
+                            $query->setParameter('name', $property->name);
2473
+                            $query->setParameter('parameter', mb_substr($key, 0, 254));
2474
+                            $query->setParameter('value', mb_substr($value, 0, 254));
2475
+                            $query->execute();
2476
+                        }
2477
+                    }
2478
+                }
2479
+            }
2480
+        }
2481
+    }
2482
+
2483
+    /**
2484
+     * deletes all birthday calendars
2485
+     */
2486
+    public function deleteAllBirthdayCalendars() {
2487
+        $query = $this->db->getQueryBuilder();
2488
+        $result = $query->select(['id'])->from('calendars')
2489
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2490
+            ->execute();
2491
+
2492
+        $ids = $result->fetchAll();
2493
+        foreach($ids as $id) {
2494
+            $this->deleteCalendar($id['id']);
2495
+        }
2496
+    }
2497
+
2498
+    /**
2499
+     * @param $subscriptionId
2500
+     */
2501
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2502
+        $query = $this->db->getQueryBuilder();
2503
+        $query->select('uri')
2504
+            ->from('calendarobjects')
2505
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2507
+        $stmt = $query->execute();
2508
+
2509
+        $uris = [];
2510
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511
+            $uris[] = $row['uri'];
2512
+        }
2513
+        $stmt->closeCursor();
2514
+
2515
+        $query = $this->db->getQueryBuilder();
2516
+        $query->delete('calendarobjects')
2517
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2518
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2519
+            ->execute();
2520
+
2521
+        $query->delete('calendarchanges')
2522
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2523
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2524
+            ->execute();
2525
+
2526
+        $query->delete($this->dbObjectPropertiesTable)
2527
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2528
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529
+            ->execute();
2530
+
2531
+        foreach($uris as $uri) {
2532
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533
+        }
2534
+    }
2535
+
2536
+    /**
2537
+     * Move a calendar from one user to another
2538
+     *
2539
+     * @param string $uriName
2540
+     * @param string $uriOrigin
2541
+     * @param string $uriDestination
2542
+     */
2543
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2544
+    {
2545
+        $query = $this->db->getQueryBuilder();
2546
+        $query->update('calendars')
2547
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2548
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2549
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2550
+            ->execute();
2551
+    }
2552
+
2553
+    /**
2554
+     * read VCalendar data into a VCalendar object
2555
+     *
2556
+     * @param string $objectData
2557
+     * @return VCalendar
2558
+     */
2559
+    protected function readCalendarData($objectData) {
2560
+        return Reader::read($objectData);
2561
+    }
2562
+
2563
+    /**
2564
+     * delete all properties from a given calendar object
2565
+     *
2566
+     * @param int $calendarId
2567
+     * @param int $objectId
2568
+     */
2569
+    protected function purgeProperties($calendarId, $objectId) {
2570
+        $query = $this->db->getQueryBuilder();
2571
+        $query->delete($this->dbObjectPropertiesTable)
2572
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2573
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2574
+        $query->execute();
2575
+    }
2576
+
2577
+    /**
2578
+     * get ID from a given calendar object
2579
+     *
2580
+     * @param int $calendarId
2581
+     * @param string $uri
2582
+     * @param int $calendarType
2583
+     * @return int
2584
+     */
2585
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2586
+        $query = $this->db->getQueryBuilder();
2587
+        $query->select('id')
2588
+            ->from('calendarobjects')
2589
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2590
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2591
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2592
+
2593
+        $result = $query->execute();
2594
+        $objectIds = $result->fetch();
2595
+        $result->closeCursor();
2596
+
2597
+        if (!isset($objectIds['id'])) {
2598
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2599
+        }
2600
+
2601
+        return (int)$objectIds['id'];
2602
+    }
2603
+
2604
+    /**
2605
+     * return legacy endpoint principal name to new principal name
2606
+     *
2607
+     * @param $principalUri
2608
+     * @param $toV2
2609
+     * @return string
2610
+     */
2611
+    private function convertPrincipal($principalUri, $toV2) {
2612
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2613
+            list(, $name) = Uri\split($principalUri);
2614
+            if ($toV2 === true) {
2615
+                return "principals/users/$name";
2616
+            }
2617
+            return "principals/$name";
2618
+        }
2619
+        return $principalUri;
2620
+    }
2621
+
2622
+    /**
2623
+     * adds information about an owner to the calendar data
2624
+     *
2625
+     * @param $calendarInfo
2626
+     */
2627
+    private function addOwnerPrincipal(&$calendarInfo) {
2628
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2630
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2631
+            $uri = $calendarInfo[$ownerPrincipalKey];
2632
+        } else {
2633
+            $uri = $calendarInfo['principaluri'];
2634
+        }
2635
+
2636
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2637
+        if (isset($principalInformation['{DAV:}displayname'])) {
2638
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2639
+        }
2640
+    }
2641 2641
 }
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
227 227
 		}
228 228
 
229
-		return (int)$query->execute()->fetchColumn();
229
+		return (int) $query->execute()->fetchColumn();
230 230
 	}
231 231
 
232 232
 	/**
@@ -273,25 +273,25 @@  discard block
 block discarded – undo
273 273
 		$stmt = $query->execute();
274 274
 
275 275
 		$calendars = [];
276
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
276
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
277 277
 
278 278
 			$components = [];
279 279
 			if ($row['components']) {
280
-				$components = explode(',',$row['components']);
280
+				$components = explode(',', $row['components']);
281 281
 			}
282 282
 
283 283
 			$calendar = [
284 284
 				'id' => $row['id'],
285 285
 				'uri' => $row['uri'],
286 286
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
287
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
288
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
289
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
291
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292 292
 			];
293 293
 
294
-			foreach($this->propertyMap as $xmlName=>$dbName) {
294
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
295 295
 				$calendar[$xmlName] = $row[$dbName];
296 296
 			}
297 297
 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 		$principals = array_map(function($principal) {
312 312
 			return urldecode($principal);
313 313
 		}, $principals);
314
-		$principals[]= $principalUri;
314
+		$principals[] = $principalUri;
315 315
 
316 316
 		$fields = array_values($this->propertyMap);
317 317
 		$fields[] = 'a.id';
@@ -331,8 +331,8 @@  discard block
 block discarded – undo
331 331
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
332 332
 			->execute();
333 333
 
334
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
335
-		while($row = $result->fetch()) {
334
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
335
+		while ($row = $result->fetch()) {
336 336
 			if ($row['principaluri'] === $principalUri) {
337 337
 				continue;
338 338
 			}
@@ -351,25 +351,25 @@  discard block
 block discarded – undo
351 351
 			}
352 352
 
353 353
 			list(, $name) = Uri\split($row['principaluri']);
354
-			$uri = $row['uri'] . '_shared_by_' . $name;
355
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
354
+			$uri = $row['uri'].'_shared_by_'.$name;
355
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
356 356
 			$components = [];
357 357
 			if ($row['components']) {
358
-				$components = explode(',',$row['components']);
358
+				$components = explode(',', $row['components']);
359 359
 			}
360 360
 			$calendar = [
361 361
 				'id' => $row['id'],
362 362
 				'uri' => $uri,
363 363
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
365
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
366
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
364
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
365
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
366
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
367
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
368
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
369 369
 				$readOnlyPropertyName => $readOnly,
370 370
 			];
371 371
 
372
-			foreach($this->propertyMap as $xmlName=>$dbName) {
372
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
373 373
 				$calendar[$xmlName] = $row[$dbName];
374 374
 			}
375 375
 
@@ -402,21 +402,21 @@  discard block
 block discarded – undo
402 402
 			->orderBy('calendarorder', 'ASC');
403 403
 		$stmt = $query->execute();
404 404
 		$calendars = [];
405
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
405
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
406 406
 			$components = [];
407 407
 			if ($row['components']) {
408
-				$components = explode(',',$row['components']);
408
+				$components = explode(',', $row['components']);
409 409
 			}
410 410
 			$calendar = [
411 411
 				'id' => $row['id'],
412 412
 				'uri' => $row['uri'],
413 413
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
414
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
415
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
416
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
414
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
415
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
416
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
417
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
418 418
 			];
419
-			foreach($this->propertyMap as $xmlName=>$dbName) {
419
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
420 420
 				$calendar[$xmlName] = $row[$dbName];
421 421
 			}
422 422
 
@@ -471,27 +471,27 @@  discard block
 block discarded – undo
471 471
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
472 472
 			->execute();
473 473
 
474
-		while($row = $result->fetch()) {
474
+		while ($row = $result->fetch()) {
475 475
 			list(, $name) = Uri\split($row['principaluri']);
476
-			$row['displayname'] = $row['displayname'] . "($name)";
476
+			$row['displayname'] = $row['displayname']."($name)";
477 477
 			$components = [];
478 478
 			if ($row['components']) {
479
-				$components = explode(',',$row['components']);
479
+				$components = explode(',', $row['components']);
480 480
 			}
481 481
 			$calendar = [
482 482
 				'id' => $row['id'],
483 483
 				'uri' => $row['publicuri'],
484 484
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
486
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
491
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
486
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
487
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
489
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
490
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
491
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
492 492
 			];
493 493
 
494
-			foreach($this->propertyMap as $xmlName=>$dbName) {
494
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
495 495
 				$calendar[$xmlName] = $row[$dbName];
496 496
 			}
497 497
 
@@ -535,29 +535,29 @@  discard block
 block discarded – undo
535 535
 		$result->closeCursor();
536 536
 
537 537
 		if ($row === false) {
538
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
538
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
539 539
 		}
540 540
 
541 541
 		list(, $name) = Uri\split($row['principaluri']);
542
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
542
+		$row['displayname'] = $row['displayname'].' '."($name)";
543 543
 		$components = [];
544 544
 		if ($row['components']) {
545
-			$components = explode(',',$row['components']);
545
+			$components = explode(',', $row['components']);
546 546
 		}
547 547
 		$calendar = [
548 548
 			'id' => $row['id'],
549 549
 			'uri' => $row['publicuri'],
550 550
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
551
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
552
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
553
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
555
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
557
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
552
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
553
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
554
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
555
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
556
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
557
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
558 558
 		];
559 559
 
560
-		foreach($this->propertyMap as $xmlName=>$dbName) {
560
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
561 561
 			$calendar[$xmlName] = $row[$dbName];
562 562
 		}
563 563
 
@@ -597,20 +597,20 @@  discard block
 block discarded – undo
597 597
 
598 598
 		$components = [];
599 599
 		if ($row['components']) {
600
-			$components = explode(',',$row['components']);
600
+			$components = explode(',', $row['components']);
601 601
 		}
602 602
 
603 603
 		$calendar = [
604 604
 			'id' => $row['id'],
605 605
 			'uri' => $row['uri'],
606 606
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
608
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
609
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
607
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
608
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
609
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
610
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
611 611
 		];
612 612
 
613
-		foreach($this->propertyMap as $xmlName=>$dbName) {
613
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
614 614
 			$calendar[$xmlName] = $row[$dbName];
615 615
 		}
616 616
 
@@ -647,20 +647,20 @@  discard block
 block discarded – undo
647 647
 
648 648
 		$components = [];
649 649
 		if ($row['components']) {
650
-			$components = explode(',',$row['components']);
650
+			$components = explode(',', $row['components']);
651 651
 		}
652 652
 
653 653
 		$calendar = [
654 654
 			'id' => $row['id'],
655 655
 			'uri' => $row['uri'],
656 656
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
657
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
658
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
659
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
657
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
658
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
659
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
660
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
661 661
 		];
662 662
 
663
-		foreach($this->propertyMap as $xmlName=>$dbName) {
663
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
664 664
 			$calendar[$xmlName] = $row[$dbName];
665 665
 		}
666 666
 
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 			->from('calendarsubscriptions')
687 687
 			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
688 688
 			->orderBy('calendarorder', 'asc');
689
-		$stmt =$query->execute();
689
+		$stmt = $query->execute();
690 690
 
691 691
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
692 692
 		$stmt->closeCursor();
@@ -700,11 +700,11 @@  discard block
 block discarded – undo
700 700
 			'principaluri' => $row['principaluri'],
701 701
 			'source'       => $row['source'],
702 702
 			'lastmodified' => $row['lastmodified'],
703
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
703
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
704
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
705 705
 		];
706 706
 
707
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
707
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
708 708
 			if (!is_null($row[$dbName])) {
709 709
 				$subscription[$xmlName] = $row[$dbName];
710 710
 			}
@@ -739,21 +739,21 @@  discard block
 block discarded – undo
739 739
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
740 740
 		if (isset($properties[$sccs])) {
741 741
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
742
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
742
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
743 743
 			}
744
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
744
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
745 745
 		} else if (isset($properties['components'])) {
746 746
 			// Allow to provide components internally without having
747 747
 			// to create a SupportedCalendarComponentSet object
748 748
 			$values['components'] = $properties['components'];
749 749
 		}
750 750
 
751
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
751
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
752 752
 		if (isset($properties[$transp])) {
753 753
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
754 754
 		}
755 755
 
756
-		foreach($this->propertyMap as $xmlName=>$dbName) {
756
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
757 757
 			if (isset($properties[$xmlName])) {
758 758
 				$values[$dbName] = $properties[$xmlName];
759 759
 			}
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 
762 762
 		$query = $this->db->getQueryBuilder();
763 763
 		$query->insert('calendars');
764
-		foreach($values as $column => $value) {
764
+		foreach ($values as $column => $value) {
765 765
 			$query->setValue($column, $query->createNamedParameter($value));
766 766
 		}
767 767
 		$query->execute();
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
 	 */
796 796
 	function updateCalendar($calendarId, PropPatch $propPatch) {
797 797
 		$supportedProperties = array_keys($this->propertyMap);
798
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
798
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
799 799
 
800 800
 		/**
801 801
 		 * @suppress SqlInjectionChecker
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
 			foreach ($mutations as $propertyName => $propertyValue) {
806 806
 
807 807
 				switch ($propertyName) {
808
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
808
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
809 809
 						$fieldName = 'transparent';
810 810
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
811 811
 						break;
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 	 * @param int $calendarType
915 915
 	 * @return array
916 916
 	 */
917
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
917
+	public function getCalendarObjects($id, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
918 918
 		$query = $this->db->getQueryBuilder();
919 919
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
920 920
 			->from('calendarobjects')
@@ -923,16 +923,16 @@  discard block
 block discarded – undo
923 923
 		$stmt = $query->execute();
924 924
 
925 925
 		$result = [];
926
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
926
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
927 927
 			$result[] = [
928 928
 				'id'           => $row['id'],
929 929
 				'uri'          => $row['uri'],
930 930
 				'lastmodified' => $row['lastmodified'],
931
-				'etag'         => '"' . $row['etag'] . '"',
931
+				'etag'         => '"'.$row['etag'].'"',
932 932
 				'calendarid'   => $row['calendarid'],
933
-				'size'         => (int)$row['size'],
933
+				'size'         => (int) $row['size'],
934 934
 				'component'    => strtolower($row['componenttype']),
935
-				'classification'=> (int)$row['classification']
935
+				'classification'=> (int) $row['classification']
936 936
 			];
937 937
 		}
938 938
 
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 	 * @param int $calendarType
957 957
 	 * @return array|null
958 958
 	 */
959
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
959
+	public function getCalendarObject($id, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
960 960
 		$query = $this->db->getQueryBuilder();
961 961
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
962 962
 			->from('calendarobjects')
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
 		$stmt = $query->execute();
967 967
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
968 968
 
969
-		if(!$row) {
969
+		if (!$row) {
970 970
 			return null;
971 971
 		}
972 972
 
@@ -974,12 +974,12 @@  discard block
 block discarded – undo
974 974
 			'id'            => $row['id'],
975 975
 			'uri'           => $row['uri'],
976 976
 			'lastmodified'  => $row['lastmodified'],
977
-			'etag'          => '"' . $row['etag'] . '"',
977
+			'etag'          => '"'.$row['etag'].'"',
978 978
 			'calendarid'    => $row['calendarid'],
979
-			'size'          => (int)$row['size'],
979
+			'size'          => (int) $row['size'],
980 980
 			'calendardata'  => $this->readBlob($row['calendardata']),
981 981
 			'component'     => strtolower($row['componenttype']),
982
-			'classification'=> (int)$row['classification']
982
+			'classification'=> (int) $row['classification']
983 983
 		];
984 984
 	}
985 985
 
@@ -996,7 +996,7 @@  discard block
 block discarded – undo
996 996
 	 * @param int $calendarType
997 997
 	 * @return array
998 998
 	 */
999
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
999
+	public function getMultipleCalendarObjects($id, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1000 1000
 		if (empty($uris)) {
1001 1001
 			return [];
1002 1002
 		}
@@ -1020,12 +1020,12 @@  discard block
 block discarded – undo
1020 1020
 					'id'           => $row['id'],
1021 1021
 					'uri'          => $row['uri'],
1022 1022
 					'lastmodified' => $row['lastmodified'],
1023
-					'etag'         => '"' . $row['etag'] . '"',
1023
+					'etag'         => '"'.$row['etag'].'"',
1024 1024
 					'calendarid'   => $row['calendarid'],
1025
-					'size'         => (int)$row['size'],
1025
+					'size'         => (int) $row['size'],
1026 1026
 					'calendardata' => $this->readBlob($row['calendardata']),
1027 1027
 					'component'    => strtolower($row['componenttype']),
1028
-					'classification' => (int)$row['classification']
1028
+					'classification' => (int) $row['classification']
1029 1029
 				];
1030 1030
 			}
1031 1031
 			$result->closeCursor();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
 	 * @param int $calendarType
1054 1054
 	 * @return string
1055 1055
 	 */
1056
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1056
+	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1057 1057
 		$extraData = $this->getDenormalizedData($calendarData);
1058 1058
 
1059 1059
 		$q = $this->db->getQueryBuilder();
@@ -1114,7 +1114,7 @@  discard block
 block discarded – undo
1114 1114
 		}
1115 1115
 		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1116 1116
 
1117
-		return '"' . $extraData['etag'] . '"';
1117
+		return '"'.$extraData['etag'].'"';
1118 1118
 	}
1119 1119
 
1120 1120
 	/**
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 	 * @param int $calendarType
1137 1137
 	 * @return string
1138 1138
 	 */
1139
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1139
+	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1140 1140
 		$extraData = $this->getDenormalizedData($calendarData);
1141 1141
 		$query = $this->db->getQueryBuilder();
1142 1142
 		$query->update('calendarobjects')
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
 		}
1183 1183
 		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1184 1184
 
1185
-		return '"' . $extraData['etag'] . '"';
1185
+		return '"'.$extraData['etag'].'"';
1186 1186
 	}
1187 1187
 
1188 1188
 	/**
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
 	 * @param int $calendarType
1213 1213
 	 * @return void
1214 1214
 	 */
1215
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1215
+	function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1216 1216
 		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1217 1217
 		if (is_array($data)) {
1218 1218
 			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
@@ -1298,7 +1298,7 @@  discard block
 block discarded – undo
1298 1298
 	 * @param int $calendarType
1299 1299
 	 * @return array
1300 1300
 	 */
1301
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1301
+	public function calendarQuery($id, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1302 1302
 		$componentType = null;
1303 1303
 		$requirePostFilter = true;
1304 1304
 		$timeRange = null;
@@ -1352,13 +1352,13 @@  discard block
 block discarded – undo
1352 1352
 		$stmt = $query->execute();
1353 1353
 
1354 1354
 		$result = [];
1355
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1355
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1356 1356
 			if ($requirePostFilter) {
1357 1357
 				// validateFilterForObject will parse the calendar data
1358 1358
 				// catch parsing errors
1359 1359
 				try {
1360 1360
 					$matches = $this->validateFilterForObject($row, $filters);
1361
-				} catch(ParseException $ex) {
1361
+				} catch (ParseException $ex) {
1362 1362
 					$this->logger->logException($ex, [
1363 1363
 						'app' => 'dav',
1364 1364
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
@@ -1393,14 +1393,14 @@  discard block
 block discarded – undo
1393 1393
 	 * @param integer|null $offset
1394 1394
 	 * @return array
1395 1395
 	 */
1396
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1396
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1397 1397
 		$calendars = $this->getCalendarsForUser($principalUri);
1398 1398
 		$ownCalendars = [];
1399 1399
 		$sharedCalendars = [];
1400 1400
 
1401 1401
 		$uriMapper = [];
1402 1402
 
1403
-		foreach($calendars as $calendar) {
1403
+		foreach ($calendars as $calendar) {
1404 1404
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1405 1405
 				$ownCalendars[] = $calendar['id'];
1406 1406
 			} else {
@@ -1415,14 +1415,14 @@  discard block
 block discarded – undo
1415 1415
 		$query = $this->db->getQueryBuilder();
1416 1416
 		// Calendar id expressions
1417 1417
 		$calendarExpressions = [];
1418
-		foreach($ownCalendars as $id) {
1418
+		foreach ($ownCalendars as $id) {
1419 1419
 			$calendarExpressions[] = $query->expr()->andX(
1420 1420
 				$query->expr()->eq('c.calendarid',
1421 1421
 					$query->createNamedParameter($id)),
1422 1422
 				$query->expr()->eq('c.calendartype',
1423 1423
 						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1424 1424
 		}
1425
-		foreach($sharedCalendars as $id) {
1425
+		foreach ($sharedCalendars as $id) {
1426 1426
 			$calendarExpressions[] = $query->expr()->andX(
1427 1427
 				$query->expr()->eq('c.calendarid',
1428 1428
 					$query->createNamedParameter($id)),
@@ -1440,7 +1440,7 @@  discard block
 block discarded – undo
1440 1440
 
1441 1441
 		// Component expressions
1442 1442
 		$compExpressions = [];
1443
-		foreach($filters['comps'] as $comp) {
1443
+		foreach ($filters['comps'] as $comp) {
1444 1444
 			$compExpressions[] = $query->expr()
1445 1445
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1446 1446
 		}
@@ -1459,13 +1459,13 @@  discard block
 block discarded – undo
1459 1459
 		}
1460 1460
 
1461 1461
 		$propParamExpressions = [];
1462
-		foreach($filters['props'] as $prop) {
1462
+		foreach ($filters['props'] as $prop) {
1463 1463
 			$propParamExpressions[] = $query->expr()->andX(
1464 1464
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1465 1465
 				$query->expr()->isNull('i.parameter')
1466 1466
 			);
1467 1467
 		}
1468
-		foreach($filters['params'] as $param) {
1468
+		foreach ($filters['params'] as $param) {
1469 1469
 			$propParamExpressions[] = $query->expr()->andX(
1470 1470
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1471 1471
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1497,8 +1497,8 @@  discard block
 block discarded – undo
1497 1497
 		$stmt = $query->execute();
1498 1498
 
1499 1499
 		$result = [];
1500
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1500
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1501
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1502 1502
 			if (!in_array($path, $result)) {
1503 1503
 				$result[] = $path;
1504 1504
 			}
@@ -1538,7 +1538,7 @@  discard block
 block discarded – undo
1538 1538
 		}
1539 1539
 
1540 1540
 		$or = $innerQuery->expr()->orX();
1541
-		foreach($searchProperties as $searchProperty) {
1541
+		foreach ($searchProperties as $searchProperty) {
1542 1542
 			$or->add($innerQuery->expr()->eq('op.name',
1543 1543
 				$outerQuery->createNamedParameter($searchProperty)));
1544 1544
 		}
@@ -1546,8 +1546,8 @@  discard block
 block discarded – undo
1546 1546
 
1547 1547
 		if ($pattern !== '') {
1548 1548
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1549
-				$outerQuery->createNamedParameter('%' .
1550
-					$this->db->escapeLikeParameter($pattern) . '%')));
1549
+				$outerQuery->createNamedParameter('%'.
1550
+					$this->db->escapeLikeParameter($pattern).'%')));
1551 1551
 		}
1552 1552
 
1553 1553
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1567,7 +1567,7 @@  discard block
 block discarded – undo
1567 1567
 
1568 1568
 		if (isset($options['types'])) {
1569 1569
 			$or = $outerQuery->expr()->orX();
1570
-			foreach($options['types'] as $type) {
1570
+			foreach ($options['types'] as $type) {
1571 1571
 				$or->add($outerQuery->expr()->eq('componenttype',
1572 1572
 					$outerQuery->createNamedParameter($type)));
1573 1573
 			}
@@ -1592,7 +1592,7 @@  discard block
 block discarded – undo
1592 1592
 			$comps = $calendarData->getComponents();
1593 1593
 			$objects = [];
1594 1594
 			$timezones = [];
1595
-			foreach($comps as $comp) {
1595
+			foreach ($comps as $comp) {
1596 1596
 				if ($comp instanceof VTimeZone) {
1597 1597
 					$timezones[] = $comp;
1598 1598
 				} else {
@@ -1629,7 +1629,7 @@  discard block
 block discarded – undo
1629 1629
 		});
1630 1630
 		$validationRules = $comp->getValidationRules();
1631 1631
 
1632
-		foreach($subComponents as $subComponent) {
1632
+		foreach ($subComponents as $subComponent) {
1633 1633
 			$name = $subComponent->name;
1634 1634
 			if (!isset($data[$name])) {
1635 1635
 				$data[$name] = [];
@@ -1637,7 +1637,7 @@  discard block
 block discarded – undo
1637 1637
 			$data[$name][] = $this->transformSearchData($subComponent);
1638 1638
 		}
1639 1639
 
1640
-		foreach($properties as $property) {
1640
+		foreach ($properties as $property) {
1641 1641
 			$name = $property->name;
1642 1642
 			if (!isset($validationRules[$name])) {
1643 1643
 				$validationRules[$name] = '*';
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
 		$stmt = $query->execute();
1709 1709
 
1710 1710
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1711
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1711
+			return $row['calendaruri'].'/'.$row['objecturi'];
1712 1712
 		}
1713 1713
 
1714 1714
 		return null;
@@ -1771,10 +1771,10 @@  discard block
 block discarded – undo
1771 1771
 	 * @param int $calendarType
1772 1772
 	 * @return array
1773 1773
 	 */
1774
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1774
+	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1775 1775
 		// Current synctoken
1776 1776
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1777
-		$stmt->execute([ $calendarId ]);
1777
+		$stmt->execute([$calendarId]);
1778 1778
 		$currentToken = $stmt->fetchColumn(0);
1779 1779
 
1780 1780
 		if (is_null($currentToken)) {
@@ -1791,8 +1791,8 @@  discard block
 block discarded – undo
1791 1791
 		if ($syncToken) {
1792 1792
 
1793 1793
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1794
-			if ($limit>0) {
1795
-				$query.= " LIMIT " . (int)$limit;
1794
+			if ($limit > 0) {
1795
+				$query .= " LIMIT ".(int) $limit;
1796 1796
 			}
1797 1797
 
1798 1798
 			// Fetching all changes
@@ -1803,15 +1803,15 @@  discard block
 block discarded – undo
1803 1803
 
1804 1804
 			// This loop ensures that any duplicates are overwritten, only the
1805 1805
 			// last change on a node is relevant.
1806
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1806
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1807 1807
 
1808 1808
 				$changes[$row['uri']] = $row['operation'];
1809 1809
 
1810 1810
 			}
1811 1811
 
1812
-			foreach($changes as $uri => $operation) {
1812
+			foreach ($changes as $uri => $operation) {
1813 1813
 
1814
-				switch($operation) {
1814
+				switch ($operation) {
1815 1815
 					case 1 :
1816 1816
 						$result['added'][] = $uri;
1817 1817
 						break;
@@ -1882,10 +1882,10 @@  discard block
 block discarded – undo
1882 1882
 			->from('calendarsubscriptions')
1883 1883
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1884 1884
 			->orderBy('calendarorder', 'asc');
1885
-		$stmt =$query->execute();
1885
+		$stmt = $query->execute();
1886 1886
 
1887 1887
 		$subscriptions = [];
1888
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1888
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1889 1889
 
1890 1890
 			$subscription = [
1891 1891
 				'id'           => $row['id'],
@@ -1894,11 +1894,11 @@  discard block
 block discarded – undo
1894 1894
 				'source'       => $row['source'],
1895 1895
 				'lastmodified' => $row['lastmodified'],
1896 1896
 
1897
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1897
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1898
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
1899 1899
 			];
1900 1900
 
1901
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1901
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1902 1902
 				if (!is_null($row[$dbName])) {
1903 1903
 					$subscription[$xmlName] = $row[$dbName];
1904 1904
 				}
@@ -1937,7 +1937,7 @@  discard block
 block discarded – undo
1937 1937
 
1938 1938
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1939 1939
 
1940
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1940
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1941 1941
 			if (array_key_exists($xmlName, $properties)) {
1942 1942
 					$values[$dbName] = $properties[$xmlName];
1943 1943
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1997,7 +1997,7 @@  discard block
 block discarded – undo
1997 1997
 
1998 1998
 			$newValues = [];
1999 1999
 
2000
-			foreach($mutations as $propertyName=>$propertyValue) {
2000
+			foreach ($mutations as $propertyName=>$propertyValue) {
2001 2001
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2002 2002
 					$newValues['source'] = $propertyValue->getHref();
2003 2003
 				} else {
@@ -2009,7 +2009,7 @@  discard block
 block discarded – undo
2009 2009
 			$query = $this->db->getQueryBuilder();
2010 2010
 			$query->update('calendarsubscriptions')
2011 2011
 				->set('lastmodified', $query->createNamedParameter(time()));
2012
-			foreach($newValues as $fieldName=>$value) {
2012
+			foreach ($newValues as $fieldName=>$value) {
2013 2013
 				$query->set($fieldName, $query->createNamedParameter($value));
2014 2014
 			}
2015 2015
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -2090,7 +2090,7 @@  discard block
 block discarded – undo
2090 2090
 
2091 2091
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2092 2092
 
2093
-		if(!$row) {
2093
+		if (!$row) {
2094 2094
 			return null;
2095 2095
 		}
2096 2096
 
@@ -2098,8 +2098,8 @@  discard block
 block discarded – undo
2098 2098
 			'uri'          => $row['uri'],
2099 2099
 			'calendardata' => $row['calendardata'],
2100 2100
 			'lastmodified' => $row['lastmodified'],
2101
-			'etag'         => '"' . $row['etag'] . '"',
2102
-			'size'         => (int)$row['size'],
2101
+			'etag'         => '"'.$row['etag'].'"',
2102
+			'size'         => (int) $row['size'],
2103 2103
 		];
2104 2104
 	}
2105 2105
 
@@ -2122,13 +2122,13 @@  discard block
 block discarded – undo
2122 2122
 				->execute();
2123 2123
 
2124 2124
 		$result = [];
2125
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2125
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2126 2126
 			$result[] = [
2127 2127
 				'calendardata' => $row['calendardata'],
2128 2128
 				'uri'          => $row['uri'],
2129 2129
 				'lastmodified' => $row['lastmodified'],
2130
-				'etag'         => '"' . $row['etag'] . '"',
2131
-				'size'         => (int)$row['size'],
2130
+				'etag'         => '"'.$row['etag'].'"',
2131
+				'size'         => (int) $row['size'],
2132 2132
 			];
2133 2133
 		}
2134 2134
 
@@ -2181,14 +2181,14 @@  discard block
 block discarded – undo
2181 2181
 	 * @param int $calendarType
2182 2182
 	 * @return void
2183 2183
 	 */
2184
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2185
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2184
+	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2185
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2186 2186
 
2187 2187
 		$query = $this->db->getQueryBuilder();
2188 2188
 		$query->select('synctoken')
2189 2189
 			->from($table)
2190 2190
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2191
-		$syncToken = (int)$query->execute()->fetchColumn();
2191
+		$syncToken = (int) $query->execute()->fetchColumn();
2192 2192
 
2193 2193
 		$query = $this->db->getQueryBuilder();
2194 2194
 		$query->insert('calendarchanges')
@@ -2232,10 +2232,10 @@  discard block
 block discarded – undo
2232 2232
 		$lastOccurrence = null;
2233 2233
 		$uid = null;
2234 2234
 		$classification = self::CLASSIFICATION_PUBLIC;
2235
-		foreach($vObject->getComponents() as $component) {
2236
-			if ($component->name!=='VTIMEZONE') {
2235
+		foreach ($vObject->getComponents() as $component) {
2236
+			if ($component->name !== 'VTIMEZONE') {
2237 2237
 				$componentType = $component->name;
2238
-				$uid = (string)$component->UID;
2238
+				$uid = (string) $component->UID;
2239 2239
 				break;
2240 2240
 			}
2241 2241
 		}
@@ -2260,13 +2260,13 @@  discard block
 block discarded – undo
2260 2260
 					$lastOccurrence = $firstOccurrence;
2261 2261
 				}
2262 2262
 			} else {
2263
-				$it = new EventIterator($vObject, (string)$component->UID);
2263
+				$it = new EventIterator($vObject, (string) $component->UID);
2264 2264
 				$maxDate = new DateTime(self::MAX_DATE);
2265 2265
 				if ($it->isInfinite()) {
2266 2266
 					$lastOccurrence = $maxDate->getTimestamp();
2267 2267
 				} else {
2268 2268
 					$end = $it->getDtEnd();
2269
-					while($it->valid() && $end < $maxDate) {
2269
+					while ($it->valid() && $end < $maxDate) {
2270 2270
 						$end = $it->getDtEnd();
2271 2271
 						$it->next();
2272 2272
 
@@ -2336,7 +2336,7 @@  discard block
 block discarded – undo
2336 2336
 	 * @param int $calendarType
2337 2337
 	 * @return array
2338 2338
 	 */
2339
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2339
+	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2340 2340
 		return $this->calendarSharingBackend->getShares($resourceId);
2341 2341
 	}
2342 2342
 
@@ -2413,7 +2413,7 @@  discard block
 block discarded – undo
2413 2413
 	 * @param string $calendarData
2414 2414
 	 * @param int $calendarType
2415 2415
 	 */
2416
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2416
+	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2417 2417
 		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2418 2418
 
2419 2419
 		try {
@@ -2490,7 +2490,7 @@  discard block
 block discarded – undo
2490 2490
 			->execute();
2491 2491
 
2492 2492
 		$ids = $result->fetchAll();
2493
-		foreach($ids as $id) {
2493
+		foreach ($ids as $id) {
2494 2494
 			$this->deleteCalendar($id['id']);
2495 2495
 		}
2496 2496
 	}
@@ -2507,7 +2507,7 @@  discard block
 block discarded – undo
2507 2507
 		$stmt = $query->execute();
2508 2508
 
2509 2509
 		$uris = [];
2510
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2510
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2511 2511
 			$uris[] = $row['uri'];
2512 2512
 		}
2513 2513
 		$stmt->closeCursor();
@@ -2528,7 +2528,7 @@  discard block
 block discarded – undo
2528 2528
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2529 2529
 			->execute();
2530 2530
 
2531
-		foreach($uris as $uri) {
2531
+		foreach ($uris as $uri) {
2532 2532
 			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2533 2533
 		}
2534 2534
 	}
@@ -2595,10 +2595,10 @@  discard block
 block discarded – undo
2595 2595
 		$result->closeCursor();
2596 2596
 
2597 2597
 		if (!isset($objectIds['id'])) {
2598
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2598
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2599 2599
 		}
2600 2600
 
2601
-		return (int)$objectIds['id'];
2601
+		return (int) $objectIds['id'];
2602 2602
 	}
2603 2603
 
2604 2604
 	/**
@@ -2625,8 +2625,8 @@  discard block
 block discarded – undo
2625 2625
 	 * @param $calendarInfo
2626 2626
 	 */
2627 2627
 	private function addOwnerPrincipal(&$calendarInfo) {
2628
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2629
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2628
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2629
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2630 2630
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2631 2631
 			$uri = $calendarInfo[$ownerPrincipalKey];
2632 2632
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/SyncService.php 1 patch
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -42,304 +42,304 @@
 block discarded – undo
42 42
 
43 43
 class SyncService {
44 44
 
45
-	/** @var CardDavBackend */
46
-	private $backend;
47
-
48
-	/** @var IUserManager */
49
-	private $userManager;
50
-
51
-	/** @var ILogger */
52
-	private $logger;
53
-
54
-	/** @var array */
55
-	private $localSystemAddressBook;
56
-
57
-	/** @var AccountManager */
58
-	private $accountManager;
59
-
60
-	/** @var string */
61
-	protected $certPath;
62
-
63
-	/**
64
-	 * SyncService constructor.
65
-	 *
66
-	 * @param CardDavBackend $backend
67
-	 * @param IUserManager $userManager
68
-	 * @param ILogger $logger
69
-	 * @param AccountManager $accountManager
70
-	 */
71
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
72
-		$this->backend = $backend;
73
-		$this->userManager = $userManager;
74
-		$this->logger = $logger;
75
-		$this->accountManager = $accountManager;
76
-		$this->certPath = '';
77
-	}
78
-
79
-	/**
80
-	 * @param string $url
81
-	 * @param string $userName
82
-	 * @param string $addressBookUrl
83
-	 * @param string $sharedSecret
84
-	 * @param string $syncToken
85
-	 * @param int $targetBookId
86
-	 * @param string $targetPrincipal
87
-	 * @param array $targetProperties
88
-	 * @return string
89
-	 * @throws \Exception
90
-	 */
91
-	public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
92
-		// 1. create addressbook
93
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
94
-		$addressBookId = $book['id'];
95
-
96
-		// 2. query changes
97
-		try {
98
-			$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
99
-		} catch (ClientHttpException $ex) {
100
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
101
-				// remote server revoked access to the address book, remove it
102
-				$this->backend->deleteAddressBook($addressBookId);
103
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
104
-				throw $ex;
105
-			}
106
-		}
107
-
108
-		// 3. apply changes
109
-		// TODO: use multi-get for download
110
-		foreach ($response['response'] as $resource => $status) {
111
-			$cardUri = basename($resource);
112
-			if (isset($status[200])) {
113
-				$vCard = $this->download($url, $userName, $sharedSecret, $resource);
114
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
115
-				if ($existingCard === false) {
116
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
117
-				} else {
118
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
119
-				}
120
-			} else {
121
-				$this->backend->deleteCard($addressBookId, $cardUri);
122
-			}
123
-		}
124
-
125
-		return $response['token'];
126
-	}
127
-
128
-	/**
129
-	 * @param string $principal
130
-	 * @param string $id
131
-	 * @param array $properties
132
-	 * @return array|null
133
-	 * @throws \Sabre\DAV\Exception\BadRequest
134
-	 */
135
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
136
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
137
-		if (!is_null($book)) {
138
-			return $book;
139
-		}
140
-		$this->backend->createAddressBook($principal, $id, $properties);
141
-
142
-		return $this->backend->getAddressBooksByUri($principal, $id);
143
-	}
144
-
145
-	/**
146
-	 * Check if there is a valid certPath we should use
147
-	 *
148
-	 * @return string
149
-	 */
150
-	protected function getCertPath() {
151
-
152
-		// we already have a valid certPath
153
-		if ($this->certPath !== '') {
154
-			return $this->certPath;
155
-		}
156
-
157
-		/** @var ICertificateManager $certManager */
158
-		$certManager = \OC::$server->getCertificateManager(null);
159
-		$certPath = $certManager->getAbsoluteBundlePath();
160
-		if (file_exists($certPath)) {
161
-			$this->certPath = $certPath;
162
-		}
163
-
164
-		return $this->certPath;
165
-	}
166
-
167
-	/**
168
-	 * @param string $url
169
-	 * @param string $userName
170
-	 * @param string $addressBookUrl
171
-	 * @param string $sharedSecret
172
-	 * @return Client
173
-	 */
174
-	protected function getClient($url, $userName, $sharedSecret) {
175
-		$settings = [
176
-			'baseUri' => $url . '/',
177
-			'userName' => $userName,
178
-			'password' => $sharedSecret,
179
-		];
180
-		$client = new Client($settings);
181
-		$certPath = $this->getCertPath();
182
-		$client->setThrowExceptions(true);
183
-
184
-		if ($certPath !== '' && strpos($url, 'http://') !== 0) {
185
-			$client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
186
-		}
187
-
188
-		return $client;
189
-	}
190
-
191
-	/**
192
-	 * @param string $url
193
-	 * @param string $userName
194
-	 * @param string $addressBookUrl
195
-	 * @param string $sharedSecret
196
-	 * @param string $syncToken
197
-	 * @return array
198
-	 */
199
-	 protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
200
-		 $client = $this->getClient($url, $userName, $sharedSecret);
201
-
202
-		 $body = $this->buildSyncCollectionRequestBody($syncToken);
203
-
204
-		 $response = $client->request('REPORT', $addressBookUrl, $body, [
205
-			'Content-Type' => 'application/xml'
206
-		 ]);
207
-
208
-		 return $this->parseMultiStatus($response['body']);
209
-	 }
210
-
211
-	/**
212
-	 * @param string $url
213
-	 * @param string $userName
214
-	 * @param string $sharedSecret
215
-	 * @param string $resourcePath
216
-	 * @return array
217
-	 */
218
-	protected function download($url, $userName, $sharedSecret, $resourcePath) {
219
-		$client = $this->getClient($url, $userName, $sharedSecret);
220
-		return $client->request('GET', $resourcePath);
221
-	}
222
-
223
-	/**
224
-	 * @param string|null $syncToken
225
-	 * @return string
226
-	 */
227
-	private function buildSyncCollectionRequestBody($syncToken) {
228
-
229
-		$dom = new \DOMDocument('1.0', 'UTF-8');
230
-		$dom->formatOutput = true;
231
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
232
-		$sync = $dom->createElement('d:sync-token', $syncToken);
233
-		$prop = $dom->createElement('d:prop');
234
-		$cont = $dom->createElement('d:getcontenttype');
235
-		$etag = $dom->createElement('d:getetag');
236
-
237
-		$prop->appendChild($cont);
238
-		$prop->appendChild($etag);
239
-		$root->appendChild($sync);
240
-		$root->appendChild($prop);
241
-		$dom->appendChild($root);
242
-		return $dom->saveXML();
243
-	}
244
-
245
-	/**
246
-	 * @param string $body
247
-	 * @return array
248
-	 * @throws \Sabre\Xml\ParseException
249
-	 */
250
-	private function parseMultiStatus($body) {
251
-		$xml = new Service();
252
-
253
-		/** @var MultiStatus $multiStatus */
254
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
255
-
256
-		$result = [];
257
-		foreach ($multiStatus->getResponses() as $response) {
258
-			$result[$response->getHref()] = $response->getResponseProperties();
259
-		}
260
-
261
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
262
-	}
263
-
264
-	/**
265
-	 * @param IUser $user
266
-	 */
267
-	public function updateUser(IUser $user) {
268
-		$systemAddressBook = $this->getLocalSystemAddressBook();
269
-		$addressBookId = $systemAddressBook['id'];
270
-		$converter = new Converter($this->accountManager);
271
-		$name = $user->getBackendClassName();
272
-		$userId = $user->getUID();
273
-
274
-		$cardId = "$name:$userId.vcf";
275
-		$card = $this->backend->getCard($addressBookId, $cardId);
276
-		if ($user->isEnabled()) {
277
-			if ($card === false) {
278
-				$vCard = $converter->createCardFromUser($user);
279
-				if ($vCard !== null) {
280
-					$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
281
-				}
282
-			} else {
283
-				$vCard = $converter->createCardFromUser($user);
284
-				if (is_null($vCard)) {
285
-					$this->backend->deleteCard($addressBookId, $cardId);
286
-				} else {
287
-					$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
288
-				}
289
-			}
290
-		} else {
291
-			$this->backend->deleteCard($addressBookId, $cardId);
292
-		}
293
-	}
294
-
295
-	/**
296
-	 * @param IUser|string $userOrCardId
297
-	 */
298
-	public function deleteUser($userOrCardId) {
299
-		$systemAddressBook = $this->getLocalSystemAddressBook();
300
-		if ($userOrCardId instanceof IUser){
301
-			$name = $userOrCardId->getBackendClassName();
302
-			$userId = $userOrCardId->getUID();
303
-
304
-			$userOrCardId = "$name:$userId.vcf";
305
-		}
306
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
307
-	}
308
-
309
-	/**
310
-	 * @return array|null
311
-	 */
312
-	public function getLocalSystemAddressBook() {
313
-		if (is_null($this->localSystemAddressBook)) {
314
-			$systemPrincipal = "principals/system/system";
315
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
316
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
317
-			]);
318
-		}
319
-
320
-		return $this->localSystemAddressBook;
321
-	}
322
-
323
-	public function syncInstance(\Closure $progressCallback = null) {
324
-		$systemAddressBook = $this->getLocalSystemAddressBook();
325
-		$this->userManager->callForSeenUsers(function($user) use ($systemAddressBook, $progressCallback) {
326
-			$this->updateUser($user);
327
-			if (!is_null($progressCallback)) {
328
-				$progressCallback();
329
-			}
330
-		});
331
-
332
-		// remove no longer existing
333
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
334
-		foreach($allCards as $card) {
335
-			$vCard = Reader::read($card['carddata']);
336
-			$uid = $vCard->UID->getValue();
337
-			// load backend and see if user exists
338
-			if (!$this->userManager->userExists($uid)) {
339
-				$this->deleteUser($card['uri']);
340
-			}
341
-		}
342
-	}
45
+    /** @var CardDavBackend */
46
+    private $backend;
47
+
48
+    /** @var IUserManager */
49
+    private $userManager;
50
+
51
+    /** @var ILogger */
52
+    private $logger;
53
+
54
+    /** @var array */
55
+    private $localSystemAddressBook;
56
+
57
+    /** @var AccountManager */
58
+    private $accountManager;
59
+
60
+    /** @var string */
61
+    protected $certPath;
62
+
63
+    /**
64
+     * SyncService constructor.
65
+     *
66
+     * @param CardDavBackend $backend
67
+     * @param IUserManager $userManager
68
+     * @param ILogger $logger
69
+     * @param AccountManager $accountManager
70
+     */
71
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
72
+        $this->backend = $backend;
73
+        $this->userManager = $userManager;
74
+        $this->logger = $logger;
75
+        $this->accountManager = $accountManager;
76
+        $this->certPath = '';
77
+    }
78
+
79
+    /**
80
+     * @param string $url
81
+     * @param string $userName
82
+     * @param string $addressBookUrl
83
+     * @param string $sharedSecret
84
+     * @param string $syncToken
85
+     * @param int $targetBookId
86
+     * @param string $targetPrincipal
87
+     * @param array $targetProperties
88
+     * @return string
89
+     * @throws \Exception
90
+     */
91
+    public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
92
+        // 1. create addressbook
93
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
94
+        $addressBookId = $book['id'];
95
+
96
+        // 2. query changes
97
+        try {
98
+            $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
99
+        } catch (ClientHttpException $ex) {
100
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
101
+                // remote server revoked access to the address book, remove it
102
+                $this->backend->deleteAddressBook($addressBookId);
103
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
104
+                throw $ex;
105
+            }
106
+        }
107
+
108
+        // 3. apply changes
109
+        // TODO: use multi-get for download
110
+        foreach ($response['response'] as $resource => $status) {
111
+            $cardUri = basename($resource);
112
+            if (isset($status[200])) {
113
+                $vCard = $this->download($url, $userName, $sharedSecret, $resource);
114
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
115
+                if ($existingCard === false) {
116
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
117
+                } else {
118
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
119
+                }
120
+            } else {
121
+                $this->backend->deleteCard($addressBookId, $cardUri);
122
+            }
123
+        }
124
+
125
+        return $response['token'];
126
+    }
127
+
128
+    /**
129
+     * @param string $principal
130
+     * @param string $id
131
+     * @param array $properties
132
+     * @return array|null
133
+     * @throws \Sabre\DAV\Exception\BadRequest
134
+     */
135
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
136
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
137
+        if (!is_null($book)) {
138
+            return $book;
139
+        }
140
+        $this->backend->createAddressBook($principal, $id, $properties);
141
+
142
+        return $this->backend->getAddressBooksByUri($principal, $id);
143
+    }
144
+
145
+    /**
146
+     * Check if there is a valid certPath we should use
147
+     *
148
+     * @return string
149
+     */
150
+    protected function getCertPath() {
151
+
152
+        // we already have a valid certPath
153
+        if ($this->certPath !== '') {
154
+            return $this->certPath;
155
+        }
156
+
157
+        /** @var ICertificateManager $certManager */
158
+        $certManager = \OC::$server->getCertificateManager(null);
159
+        $certPath = $certManager->getAbsoluteBundlePath();
160
+        if (file_exists($certPath)) {
161
+            $this->certPath = $certPath;
162
+        }
163
+
164
+        return $this->certPath;
165
+    }
166
+
167
+    /**
168
+     * @param string $url
169
+     * @param string $userName
170
+     * @param string $addressBookUrl
171
+     * @param string $sharedSecret
172
+     * @return Client
173
+     */
174
+    protected function getClient($url, $userName, $sharedSecret) {
175
+        $settings = [
176
+            'baseUri' => $url . '/',
177
+            'userName' => $userName,
178
+            'password' => $sharedSecret,
179
+        ];
180
+        $client = new Client($settings);
181
+        $certPath = $this->getCertPath();
182
+        $client->setThrowExceptions(true);
183
+
184
+        if ($certPath !== '' && strpos($url, 'http://') !== 0) {
185
+            $client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
186
+        }
187
+
188
+        return $client;
189
+    }
190
+
191
+    /**
192
+     * @param string $url
193
+     * @param string $userName
194
+     * @param string $addressBookUrl
195
+     * @param string $sharedSecret
196
+     * @param string $syncToken
197
+     * @return array
198
+     */
199
+        protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
200
+            $client = $this->getClient($url, $userName, $sharedSecret);
201
+
202
+            $body = $this->buildSyncCollectionRequestBody($syncToken);
203
+
204
+            $response = $client->request('REPORT', $addressBookUrl, $body, [
205
+            'Content-Type' => 'application/xml'
206
+            ]);
207
+
208
+            return $this->parseMultiStatus($response['body']);
209
+        }
210
+
211
+    /**
212
+     * @param string $url
213
+     * @param string $userName
214
+     * @param string $sharedSecret
215
+     * @param string $resourcePath
216
+     * @return array
217
+     */
218
+    protected function download($url, $userName, $sharedSecret, $resourcePath) {
219
+        $client = $this->getClient($url, $userName, $sharedSecret);
220
+        return $client->request('GET', $resourcePath);
221
+    }
222
+
223
+    /**
224
+     * @param string|null $syncToken
225
+     * @return string
226
+     */
227
+    private function buildSyncCollectionRequestBody($syncToken) {
228
+
229
+        $dom = new \DOMDocument('1.0', 'UTF-8');
230
+        $dom->formatOutput = true;
231
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
232
+        $sync = $dom->createElement('d:sync-token', $syncToken);
233
+        $prop = $dom->createElement('d:prop');
234
+        $cont = $dom->createElement('d:getcontenttype');
235
+        $etag = $dom->createElement('d:getetag');
236
+
237
+        $prop->appendChild($cont);
238
+        $prop->appendChild($etag);
239
+        $root->appendChild($sync);
240
+        $root->appendChild($prop);
241
+        $dom->appendChild($root);
242
+        return $dom->saveXML();
243
+    }
244
+
245
+    /**
246
+     * @param string $body
247
+     * @return array
248
+     * @throws \Sabre\Xml\ParseException
249
+     */
250
+    private function parseMultiStatus($body) {
251
+        $xml = new Service();
252
+
253
+        /** @var MultiStatus $multiStatus */
254
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
255
+
256
+        $result = [];
257
+        foreach ($multiStatus->getResponses() as $response) {
258
+            $result[$response->getHref()] = $response->getResponseProperties();
259
+        }
260
+
261
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
262
+    }
263
+
264
+    /**
265
+     * @param IUser $user
266
+     */
267
+    public function updateUser(IUser $user) {
268
+        $systemAddressBook = $this->getLocalSystemAddressBook();
269
+        $addressBookId = $systemAddressBook['id'];
270
+        $converter = new Converter($this->accountManager);
271
+        $name = $user->getBackendClassName();
272
+        $userId = $user->getUID();
273
+
274
+        $cardId = "$name:$userId.vcf";
275
+        $card = $this->backend->getCard($addressBookId, $cardId);
276
+        if ($user->isEnabled()) {
277
+            if ($card === false) {
278
+                $vCard = $converter->createCardFromUser($user);
279
+                if ($vCard !== null) {
280
+                    $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
281
+                }
282
+            } else {
283
+                $vCard = $converter->createCardFromUser($user);
284
+                if (is_null($vCard)) {
285
+                    $this->backend->deleteCard($addressBookId, $cardId);
286
+                } else {
287
+                    $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
288
+                }
289
+            }
290
+        } else {
291
+            $this->backend->deleteCard($addressBookId, $cardId);
292
+        }
293
+    }
294
+
295
+    /**
296
+     * @param IUser|string $userOrCardId
297
+     */
298
+    public function deleteUser($userOrCardId) {
299
+        $systemAddressBook = $this->getLocalSystemAddressBook();
300
+        if ($userOrCardId instanceof IUser){
301
+            $name = $userOrCardId->getBackendClassName();
302
+            $userId = $userOrCardId->getUID();
303
+
304
+            $userOrCardId = "$name:$userId.vcf";
305
+        }
306
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
307
+    }
308
+
309
+    /**
310
+     * @return array|null
311
+     */
312
+    public function getLocalSystemAddressBook() {
313
+        if (is_null($this->localSystemAddressBook)) {
314
+            $systemPrincipal = "principals/system/system";
315
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
316
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
317
+            ]);
318
+        }
319
+
320
+        return $this->localSystemAddressBook;
321
+    }
322
+
323
+    public function syncInstance(\Closure $progressCallback = null) {
324
+        $systemAddressBook = $this->getLocalSystemAddressBook();
325
+        $this->userManager->callForSeenUsers(function($user) use ($systemAddressBook, $progressCallback) {
326
+            $this->updateUser($user);
327
+            if (!is_null($progressCallback)) {
328
+                $progressCallback();
329
+            }
330
+        });
331
+
332
+        // remove no longer existing
333
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
334
+        foreach($allCards as $card) {
335
+            $vCard = Reader::read($card['carddata']);
336
+            $uid = $vCard->UID->getValue();
337
+            // load backend and see if user exists
338
+            if (!$this->userManager->userExists($uid)) {
339
+                $this->deleteUser($card['uri']);
340
+            }
341
+        }
342
+    }
343 343
 
344 344
 
345 345
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookImpl.php 1 patch
Indentation   +283 added lines, -283 removed lines patch added patch discarded remove patch
@@ -40,287 +40,287 @@
 block discarded – undo
40 40
 
41 41
 class AddressBookImpl implements IAddressBook {
42 42
 
43
-	/** @var CardDavBackend */
44
-	private $backend;
45
-
46
-	/** @var array */
47
-	private $addressBookInfo;
48
-
49
-	/** @var AddressBook */
50
-	private $addressBook;
51
-
52
-	/** @var IURLGenerator */
53
-	private $urlGenerator;
54
-
55
-	/**
56
-	 * AddressBookImpl constructor.
57
-	 *
58
-	 * @param AddressBook $addressBook
59
-	 * @param array $addressBookInfo
60
-	 * @param CardDavBackend $backend
61
-	 * @param IUrlGenerator $urlGenerator
62
-	 */
63
-	public function __construct(
64
-			AddressBook $addressBook,
65
-			array $addressBookInfo,
66
-			CardDavBackend $backend,
67
-			IURLGenerator $urlGenerator) {
68
-
69
-		$this->addressBook = $addressBook;
70
-		$this->addressBookInfo = $addressBookInfo;
71
-		$this->backend = $backend;
72
-		$this->urlGenerator = $urlGenerator;
73
-	}
74
-
75
-	/**
76
-	 * @return string defining the technical unique key
77
-	 * @since 5.0.0
78
-	 */
79
-	public function getKey() {
80
-		return $this->addressBookInfo['id'];
81
-	}
82
-
83
-	/**
84
-	 * @return string defining the unique uri
85
-	 * @since 16.0.0
86
-	 * @return string
87
-	 */
88
-	public function getUri(): string {
89
-		return $this->addressBookInfo['uri'];
90
-	}
91
-
92
-	/**
93
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
94
-	 *
95
-	 * @return mixed
96
-	 * @since 5.0.0
97
-	 */
98
-	public function getDisplayName() {
99
-		return $this->addressBookInfo['{DAV:}displayname'];
100
-	}
101
-
102
-	/**
103
-	 * @param string $pattern which should match within the $searchProperties
104
-	 * @param array $searchProperties defines the properties within the query pattern should match
105
-	 * @param array $options Options to define the output format and search behavior
106
-	 * 	- 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
107
-	 *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
108
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
109
-	 * @return array an array of contacts which are arrays of key-value-pairs
110
-	 *  example result:
111
-	 *  [
112
-	 *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
113
-	 *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
114
-	 *	]
115
-	 * @since 5.0.0
116
-	 */
117
-	public function search($pattern, $searchProperties, $options) {
118
-		$results = $this->backend->search($this->getKey(), $pattern, $searchProperties, $options);
119
-
120
-		$withTypes = \array_key_exists('types', $options) && $options['types'] === true;
121
-
122
-		$vCards = [];
123
-		foreach ($results as $result) {
124
-			$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
125
-		}
126
-
127
-		return $vCards;
128
-	}
129
-
130
-	/**
131
-	 * @param array $properties this array if key-value-pairs defines a contact
132
-	 * @return array an array representing the contact just created or updated
133
-	 * @since 5.0.0
134
-	 */
135
-	public function createOrUpdate($properties) {
136
-		$update = false;
137
-		if (!isset($properties['URI'])) { // create a new contact
138
-			$uid = $this->createUid();
139
-			$uri = $uid . '.vcf';
140
-			$vCard = $this->createEmptyVCard($uid);
141
-		} else { // update existing contact
142
-			$uri = $properties['URI'];
143
-			$vCardData = $this->backend->getCard($this->getKey(), $uri);
144
-			$vCard = $this->readCard($vCardData['carddata']);
145
-			$update = true;
146
-		}
147
-
148
-		foreach ($properties as $key => $value) {
149
-			$vCard->$key = $vCard->createProperty($key, $value);
150
-		}
151
-
152
-		if ($update) {
153
-			$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
154
-		} else {
155
-			$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
156
-		}
157
-
158
-		return $this->vCard2Array($uri, $vCard);
159
-
160
-	}
161
-
162
-	/**
163
-	 * @return mixed
164
-	 * @since 5.0.0
165
-	 */
166
-	public function getPermissions() {
167
-		$permissions = $this->addressBook->getACL();
168
-		$result = 0;
169
-		foreach ($permissions as $permission) {
170
-			switch($permission['privilege']) {
171
-				case '{DAV:}read':
172
-					$result |= Constants::PERMISSION_READ;
173
-					break;
174
-				case '{DAV:}write':
175
-					$result |= Constants::PERMISSION_CREATE;
176
-					$result |= Constants::PERMISSION_UPDATE;
177
-					break;
178
-				case '{DAV:}all':
179
-					$result |= Constants::PERMISSION_ALL;
180
-					break;
181
-			}
182
-		}
183
-
184
-		return $result;
185
-	}
186
-
187
-	/**
188
-	 * @param object $id the unique identifier to a contact
189
-	 * @return bool successful or not
190
-	 * @since 5.0.0
191
-	 */
192
-	public function delete($id) {
193
-		$uri = $this->backend->getCardUri($id);
194
-		return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
195
-	}
196
-
197
-	/**
198
-	 * read vCard data into a vCard object
199
-	 *
200
-	 * @param string $cardData
201
-	 * @return VCard
202
-	 */
203
-	protected function readCard($cardData) {
204
-		return  Reader::read($cardData);
205
-	}
206
-
207
-	/**
208
-	 * create UID for contact
209
-	 *
210
-	 * @return string
211
-	 */
212
-	protected function createUid() {
213
-		do {
214
-			$uid = $this->getUid();
215
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
216
-		} while (!empty($contact));
217
-
218
-		return $uid;
219
-	}
220
-
221
-	/**
222
-	 * getUid is only there for testing, use createUid instead
223
-	 */
224
-	protected function getUid() {
225
-		return UUIDUtil::getUUID();
226
-	}
227
-
228
-	/**
229
-	 * create empty vcard
230
-	 *
231
-	 * @param string $uid
232
-	 * @return VCard
233
-	 */
234
-	protected function createEmptyVCard($uid) {
235
-		$vCard = new VCard();
236
-		$vCard->UID = $uid;
237
-		return $vCard;
238
-	}
239
-
240
-	/**
241
-	 * create array with all vCard properties
242
-	 *
243
-	 * @param string $uri
244
-	 * @param VCard $vCard
245
-	 * @return array
246
-	 */
247
-	protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
248
-		$result = [
249
-			'URI' => $uri,
250
-		];
251
-
252
-		foreach ($vCard->children() as $property) {
253
-			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
254
-				$url = $this->urlGenerator->getAbsoluteURL(
255
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
256
-				$url .= implode('/', [
257
-					'addressbooks',
258
-					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
259
-					$this->addressBookInfo['uri'],
260
-					$uri
261
-				]) . '?photo';
262
-
263
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
264
-
265
-			} else if ($property->name === 'X-SOCIALPROFILE') {
266
-				$type = $this->getTypeFromProperty($property);
267
-
268
-				// Type is the social network, when it's empty we don't need this.
269
-				if ($type !== null) {
270
-					if (!isset($result[$property->name])) {
271
-						$result[$property->name] = [];
272
-					}
273
-					$result[$property->name][$type] = $property->getValue();
274
-				}
275
-
276
-			// The following properties can be set multiple times
277
-			} else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL', 'X-ADDRESSBOOKSERVER-MEMBER'])) {
278
-				if (!isset($result[$property->name])) {
279
-					$result[$property->name] = [];
280
-				}
281
-
282
-				$type = $this->getTypeFromProperty($property);
283
-				if ($withTypes) {
284
-					$result[$property->name][] = [
285
-						'type' => $type,
286
-						'value' => $property->getValue()
287
-					];
288
-				} else {
289
-					$result[$property->name][] = $property->getValue();
290
-				}
291
-
292
-
293
-			} else {
294
-				$result[$property->name] = $property->getValue();
295
-			}
296
-		}
297
-
298
-		if (
299
-			$this->addressBookInfo['principaluri'] === 'principals/system/system' && (
300
-				$this->addressBookInfo['uri'] === 'system' ||
301
-				$this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
302
-			)
303
-		) {
304
-			$result['isLocalSystemBook'] = true;
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * Get the type of the current property
311
-	 *
312
-	 * @param Property $property
313
-	 * @return null|string
314
-	 */
315
-	protected function getTypeFromProperty(Property $property) {
316
-		$parameters = $property->parameters();
317
-		// Type is the social network, when it's empty we don't need this.
318
-		if (isset($parameters['TYPE'])) {
319
-			/** @var \Sabre\VObject\Parameter $type */
320
-			$type = $parameters['TYPE'];
321
-			return $type->getValue();
322
-		}
323
-
324
-		return null;
325
-	}
43
+    /** @var CardDavBackend */
44
+    private $backend;
45
+
46
+    /** @var array */
47
+    private $addressBookInfo;
48
+
49
+    /** @var AddressBook */
50
+    private $addressBook;
51
+
52
+    /** @var IURLGenerator */
53
+    private $urlGenerator;
54
+
55
+    /**
56
+     * AddressBookImpl constructor.
57
+     *
58
+     * @param AddressBook $addressBook
59
+     * @param array $addressBookInfo
60
+     * @param CardDavBackend $backend
61
+     * @param IUrlGenerator $urlGenerator
62
+     */
63
+    public function __construct(
64
+            AddressBook $addressBook,
65
+            array $addressBookInfo,
66
+            CardDavBackend $backend,
67
+            IURLGenerator $urlGenerator) {
68
+
69
+        $this->addressBook = $addressBook;
70
+        $this->addressBookInfo = $addressBookInfo;
71
+        $this->backend = $backend;
72
+        $this->urlGenerator = $urlGenerator;
73
+    }
74
+
75
+    /**
76
+     * @return string defining the technical unique key
77
+     * @since 5.0.0
78
+     */
79
+    public function getKey() {
80
+        return $this->addressBookInfo['id'];
81
+    }
82
+
83
+    /**
84
+     * @return string defining the unique uri
85
+     * @since 16.0.0
86
+     * @return string
87
+     */
88
+    public function getUri(): string {
89
+        return $this->addressBookInfo['uri'];
90
+    }
91
+
92
+    /**
93
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
94
+     *
95
+     * @return mixed
96
+     * @since 5.0.0
97
+     */
98
+    public function getDisplayName() {
99
+        return $this->addressBookInfo['{DAV:}displayname'];
100
+    }
101
+
102
+    /**
103
+     * @param string $pattern which should match within the $searchProperties
104
+     * @param array $searchProperties defines the properties within the query pattern should match
105
+     * @param array $options Options to define the output format and search behavior
106
+     * 	- 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
107
+     *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
108
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
109
+     * @return array an array of contacts which are arrays of key-value-pairs
110
+     *  example result:
111
+     *  [
112
+     *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
113
+     *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
114
+     *	]
115
+     * @since 5.0.0
116
+     */
117
+    public function search($pattern, $searchProperties, $options) {
118
+        $results = $this->backend->search($this->getKey(), $pattern, $searchProperties, $options);
119
+
120
+        $withTypes = \array_key_exists('types', $options) && $options['types'] === true;
121
+
122
+        $vCards = [];
123
+        foreach ($results as $result) {
124
+            $vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
125
+        }
126
+
127
+        return $vCards;
128
+    }
129
+
130
+    /**
131
+     * @param array $properties this array if key-value-pairs defines a contact
132
+     * @return array an array representing the contact just created or updated
133
+     * @since 5.0.0
134
+     */
135
+    public function createOrUpdate($properties) {
136
+        $update = false;
137
+        if (!isset($properties['URI'])) { // create a new contact
138
+            $uid = $this->createUid();
139
+            $uri = $uid . '.vcf';
140
+            $vCard = $this->createEmptyVCard($uid);
141
+        } else { // update existing contact
142
+            $uri = $properties['URI'];
143
+            $vCardData = $this->backend->getCard($this->getKey(), $uri);
144
+            $vCard = $this->readCard($vCardData['carddata']);
145
+            $update = true;
146
+        }
147
+
148
+        foreach ($properties as $key => $value) {
149
+            $vCard->$key = $vCard->createProperty($key, $value);
150
+        }
151
+
152
+        if ($update) {
153
+            $this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
154
+        } else {
155
+            $this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
156
+        }
157
+
158
+        return $this->vCard2Array($uri, $vCard);
159
+
160
+    }
161
+
162
+    /**
163
+     * @return mixed
164
+     * @since 5.0.0
165
+     */
166
+    public function getPermissions() {
167
+        $permissions = $this->addressBook->getACL();
168
+        $result = 0;
169
+        foreach ($permissions as $permission) {
170
+            switch($permission['privilege']) {
171
+                case '{DAV:}read':
172
+                    $result |= Constants::PERMISSION_READ;
173
+                    break;
174
+                case '{DAV:}write':
175
+                    $result |= Constants::PERMISSION_CREATE;
176
+                    $result |= Constants::PERMISSION_UPDATE;
177
+                    break;
178
+                case '{DAV:}all':
179
+                    $result |= Constants::PERMISSION_ALL;
180
+                    break;
181
+            }
182
+        }
183
+
184
+        return $result;
185
+    }
186
+
187
+    /**
188
+     * @param object $id the unique identifier to a contact
189
+     * @return bool successful or not
190
+     * @since 5.0.0
191
+     */
192
+    public function delete($id) {
193
+        $uri = $this->backend->getCardUri($id);
194
+        return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
195
+    }
196
+
197
+    /**
198
+     * read vCard data into a vCard object
199
+     *
200
+     * @param string $cardData
201
+     * @return VCard
202
+     */
203
+    protected function readCard($cardData) {
204
+        return  Reader::read($cardData);
205
+    }
206
+
207
+    /**
208
+     * create UID for contact
209
+     *
210
+     * @return string
211
+     */
212
+    protected function createUid() {
213
+        do {
214
+            $uid = $this->getUid();
215
+            $contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
216
+        } while (!empty($contact));
217
+
218
+        return $uid;
219
+    }
220
+
221
+    /**
222
+     * getUid is only there for testing, use createUid instead
223
+     */
224
+    protected function getUid() {
225
+        return UUIDUtil::getUUID();
226
+    }
227
+
228
+    /**
229
+     * create empty vcard
230
+     *
231
+     * @param string $uid
232
+     * @return VCard
233
+     */
234
+    protected function createEmptyVCard($uid) {
235
+        $vCard = new VCard();
236
+        $vCard->UID = $uid;
237
+        return $vCard;
238
+    }
239
+
240
+    /**
241
+     * create array with all vCard properties
242
+     *
243
+     * @param string $uri
244
+     * @param VCard $vCard
245
+     * @return array
246
+     */
247
+    protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
248
+        $result = [
249
+            'URI' => $uri,
250
+        ];
251
+
252
+        foreach ($vCard->children() as $property) {
253
+            if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
254
+                $url = $this->urlGenerator->getAbsoluteURL(
255
+                    $this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
256
+                $url .= implode('/', [
257
+                    'addressbooks',
258
+                    substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
259
+                    $this->addressBookInfo['uri'],
260
+                    $uri
261
+                ]) . '?photo';
262
+
263
+                $result['PHOTO'] = 'VALUE=uri:' . $url;
264
+
265
+            } else if ($property->name === 'X-SOCIALPROFILE') {
266
+                $type = $this->getTypeFromProperty($property);
267
+
268
+                // Type is the social network, when it's empty we don't need this.
269
+                if ($type !== null) {
270
+                    if (!isset($result[$property->name])) {
271
+                        $result[$property->name] = [];
272
+                    }
273
+                    $result[$property->name][$type] = $property->getValue();
274
+                }
275
+
276
+            // The following properties can be set multiple times
277
+            } else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL', 'X-ADDRESSBOOKSERVER-MEMBER'])) {
278
+                if (!isset($result[$property->name])) {
279
+                    $result[$property->name] = [];
280
+                }
281
+
282
+                $type = $this->getTypeFromProperty($property);
283
+                if ($withTypes) {
284
+                    $result[$property->name][] = [
285
+                        'type' => $type,
286
+                        'value' => $property->getValue()
287
+                    ];
288
+                } else {
289
+                    $result[$property->name][] = $property->getValue();
290
+                }
291
+
292
+
293
+            } else {
294
+                $result[$property->name] = $property->getValue();
295
+            }
296
+        }
297
+
298
+        if (
299
+            $this->addressBookInfo['principaluri'] === 'principals/system/system' && (
300
+                $this->addressBookInfo['uri'] === 'system' ||
301
+                $this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
302
+            )
303
+        ) {
304
+            $result['isLocalSystemBook'] = true;
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * Get the type of the current property
311
+     *
312
+     * @param Property $property
313
+     * @return null|string
314
+     */
315
+    protected function getTypeFromProperty(Property $property) {
316
+        $parameters = $property->parameters();
317
+        // Type is the social network, when it's empty we don't need this.
318
+        if (isset($parameters['TYPE'])) {
319
+            /** @var \Sabre\VObject\Parameter $type */
320
+            $type = $parameters['TYPE'];
321
+            return $type->getValue();
322
+        }
323
+
324
+        return null;
325
+    }
326 326
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 1 patch
Indentation   +1118 added lines, -1118 removed lines patch added patch discarded remove patch
@@ -56,1122 +56,1122 @@
 block discarded – undo
56 56
 
57 57
 class CardDavBackend implements BackendInterface, SyncSupport {
58 58
 
59
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
60
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
61
-
62
-	/** @var Principal */
63
-	private $principalBackend;
64
-
65
-	/** @var string */
66
-	private $dbCardsTable = 'cards';
67
-
68
-	/** @var string */
69
-	private $dbCardsPropertiesTable = 'cards_properties';
70
-
71
-	/** @var IDBConnection */
72
-	private $db;
73
-
74
-	/** @var Backend */
75
-	private $sharingBackend;
76
-
77
-	/** @var array properties to index */
78
-	public static $indexProperties = [
79
-		'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
80
-		'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
81
-
82
-	/**
83
-	 * @var string[] Map of uid => display name
84
-	 */
85
-	protected $userDisplayNames;
86
-
87
-	/** @var IUserManager */
88
-	private $userManager;
89
-
90
-	/** @var EventDispatcherInterface */
91
-	private $dispatcher;
92
-
93
-	/**
94
-	 * CardDavBackend constructor.
95
-	 *
96
-	 * @param IDBConnection $db
97
-	 * @param Principal $principalBackend
98
-	 * @param IUserManager $userManager
99
-	 * @param IGroupManager $groupManager
100
-	 * @param EventDispatcherInterface $dispatcher
101
-	 */
102
-	public function __construct(IDBConnection $db,
103
-								Principal $principalBackend,
104
-								IUserManager $userManager,
105
-								IGroupManager $groupManager,
106
-								EventDispatcherInterface $dispatcher) {
107
-		$this->db = $db;
108
-		$this->principalBackend = $principalBackend;
109
-		$this->userManager = $userManager;
110
-		$this->dispatcher = $dispatcher;
111
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
112
-	}
113
-
114
-	/**
115
-	 * Return the number of address books for a principal
116
-	 *
117
-	 * @param $principalUri
118
-	 * @return int
119
-	 */
120
-	public function getAddressBooksForUserCount($principalUri) {
121
-		$principalUri = $this->convertPrincipal($principalUri, true);
122
-		$query = $this->db->getQueryBuilder();
123
-		$query->select($query->func()->count('*'))
124
-			->from('addressbooks')
125
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
126
-
127
-		return (int)$query->execute()->fetchColumn();
128
-	}
129
-
130
-	/**
131
-	 * Returns the list of address books for a specific user.
132
-	 *
133
-	 * Every addressbook should have the following properties:
134
-	 *   id - an arbitrary unique id
135
-	 *   uri - the 'basename' part of the url
136
-	 *   principaluri - Same as the passed parameter
137
-	 *
138
-	 * Any additional clark-notation property may be passed besides this. Some
139
-	 * common ones are :
140
-	 *   {DAV:}displayname
141
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
142
-	 *   {http://calendarserver.org/ns/}getctag
143
-	 *
144
-	 * @param string $principalUri
145
-	 * @return array
146
-	 */
147
-	function getAddressBooksForUser($principalUri) {
148
-		$principalUriOriginal = $principalUri;
149
-		$principalUri = $this->convertPrincipal($principalUri, true);
150
-		$query = $this->db->getQueryBuilder();
151
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
152
-			->from('addressbooks')
153
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
154
-
155
-		$addressBooks = [];
156
-
157
-		$result = $query->execute();
158
-		while($row = $result->fetch()) {
159
-			$addressBooks[$row['id']] = [
160
-				'id'  => $row['id'],
161
-				'uri' => $row['uri'],
162
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
163
-				'{DAV:}displayname' => $row['displayname'],
164
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
165
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
166
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
167
-			];
168
-
169
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
170
-		}
171
-		$result->closeCursor();
172
-
173
-		// query for shared addressbooks
174
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
175
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
176
-
177
-		$principals = array_map(function($principal) {
178
-			return urldecode($principal);
179
-		}, $principals);
180
-		$principals[]= $principalUri;
181
-
182
-		$query = $this->db->getQueryBuilder();
183
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
184
-			->from('dav_shares', 's')
185
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
186
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
187
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
188
-			->setParameter('type', 'addressbook')
189
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
190
-			->execute();
191
-
192
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
193
-		while($row = $result->fetch()) {
194
-			if ($row['principaluri'] === $principalUri) {
195
-				continue;
196
-			}
197
-
198
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
199
-			if (isset($addressBooks[$row['id']])) {
200
-				if ($readOnly) {
201
-					// New share can not have more permissions then the old one.
202
-					continue;
203
-				}
204
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
205
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
206
-					// Old share is already read-write, no more permissions can be gained
207
-					continue;
208
-				}
209
-			}
210
-
211
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
212
-			$uri = $row['uri'] . '_shared_by_' . $name;
213
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
214
-
215
-			$addressBooks[$row['id']] = [
216
-				'id'  => $row['id'],
217
-				'uri' => $uri,
218
-				'principaluri' => $principalUriOriginal,
219
-				'{DAV:}displayname' => $displayName,
220
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
221
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
222
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
223
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
224
-				$readOnlyPropertyName => $readOnly,
225
-			];
226
-
227
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
228
-		}
229
-		$result->closeCursor();
230
-
231
-		return array_values($addressBooks);
232
-	}
233
-
234
-	public function getUsersOwnAddressBooks($principalUri) {
235
-		$principalUri = $this->convertPrincipal($principalUri, true);
236
-		$query = $this->db->getQueryBuilder();
237
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
238
-			  ->from('addressbooks')
239
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
240
-
241
-		$addressBooks = [];
242
-
243
-		$result = $query->execute();
244
-		while($row = $result->fetch()) {
245
-			$addressBooks[$row['id']] = [
246
-				'id'  => $row['id'],
247
-				'uri' => $row['uri'],
248
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
249
-				'{DAV:}displayname' => $row['displayname'],
250
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
251
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
252
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
253
-			];
254
-
255
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
256
-		}
257
-		$result->closeCursor();
258
-
259
-		return array_values($addressBooks);
260
-	}
261
-
262
-	private function getUserDisplayName($uid) {
263
-		if (!isset($this->userDisplayNames[$uid])) {
264
-			$user = $this->userManager->get($uid);
265
-
266
-			if ($user instanceof IUser) {
267
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
268
-			} else {
269
-				$this->userDisplayNames[$uid] = $uid;
270
-			}
271
-		}
272
-
273
-		return $this->userDisplayNames[$uid];
274
-	}
275
-
276
-	/**
277
-	 * @param int $addressBookId
278
-	 */
279
-	public function getAddressBookById($addressBookId) {
280
-		$query = $this->db->getQueryBuilder();
281
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
282
-			->from('addressbooks')
283
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
284
-			->execute();
285
-
286
-		$row = $result->fetch();
287
-		$result->closeCursor();
288
-		if ($row === false) {
289
-			return null;
290
-		}
291
-
292
-		$addressBook = [
293
-			'id'  => $row['id'],
294
-			'uri' => $row['uri'],
295
-			'principaluri' => $row['principaluri'],
296
-			'{DAV:}displayname' => $row['displayname'],
297
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
298
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
299
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
300
-		];
301
-
302
-		$this->addOwnerPrincipal($addressBook);
303
-
304
-		return $addressBook;
305
-	}
306
-
307
-	/**
308
-	 * @param $addressBookUri
309
-	 * @return array|null
310
-	 */
311
-	public function getAddressBooksByUri($principal, $addressBookUri) {
312
-		$query = $this->db->getQueryBuilder();
313
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
314
-			->from('addressbooks')
315
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
316
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
317
-			->setMaxResults(1)
318
-			->execute();
319
-
320
-		$row = $result->fetch();
321
-		$result->closeCursor();
322
-		if ($row === false) {
323
-			return null;
324
-		}
325
-
326
-		$addressBook = [
327
-			'id'  => $row['id'],
328
-			'uri' => $row['uri'],
329
-			'principaluri' => $row['principaluri'],
330
-			'{DAV:}displayname' => $row['displayname'],
331
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
332
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
333
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
-		];
335
-
336
-		$this->addOwnerPrincipal($addressBook);
337
-
338
-		return $addressBook;
339
-	}
340
-
341
-	/**
342
-	 * Updates properties for an address book.
343
-	 *
344
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
345
-	 * To do the actual updates, you must tell this object which properties
346
-	 * you're going to process with the handle() method.
347
-	 *
348
-	 * Calling the handle method is like telling the PropPatch object "I
349
-	 * promise I can handle updating this property".
350
-	 *
351
-	 * Read the PropPatch documentation for more info and examples.
352
-	 *
353
-	 * @param string $addressBookId
354
-	 * @param \Sabre\DAV\PropPatch $propPatch
355
-	 * @return void
356
-	 */
357
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
358
-		$supportedProperties = [
359
-			'{DAV:}displayname',
360
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
361
-		];
362
-
363
-		/**
364
-		 * @suppress SqlInjectionChecker
365
-		 */
366
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
367
-
368
-			$updates = [];
369
-			foreach($mutations as $property=>$newValue) {
370
-
371
-				switch($property) {
372
-					case '{DAV:}displayname' :
373
-						$updates['displayname'] = $newValue;
374
-						break;
375
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
376
-						$updates['description'] = $newValue;
377
-						break;
378
-				}
379
-			}
380
-			$query = $this->db->getQueryBuilder();
381
-			$query->update('addressbooks');
382
-
383
-			foreach($updates as $key=>$value) {
384
-				$query->set($key, $query->createNamedParameter($value));
385
-			}
386
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
387
-			->execute();
388
-
389
-			$this->addChange($addressBookId, "", 2);
390
-
391
-			return true;
392
-
393
-		});
394
-	}
395
-
396
-	/**
397
-	 * Creates a new address book
398
-	 *
399
-	 * @param string $principalUri
400
-	 * @param string $url Just the 'basename' of the url.
401
-	 * @param array $properties
402
-	 * @return int
403
-	 * @throws BadRequest
404
-	 */
405
-	function createAddressBook($principalUri, $url, array $properties) {
406
-		$values = [
407
-			'displayname' => null,
408
-			'description' => null,
409
-			'principaluri' => $principalUri,
410
-			'uri' => $url,
411
-			'synctoken' => 1
412
-		];
413
-
414
-		foreach($properties as $property=>$newValue) {
415
-
416
-			switch($property) {
417
-				case '{DAV:}displayname' :
418
-					$values['displayname'] = $newValue;
419
-					break;
420
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
421
-					$values['description'] = $newValue;
422
-					break;
423
-				default :
424
-					throw new BadRequest('Unknown property: ' . $property);
425
-			}
426
-
427
-		}
428
-
429
-		// Fallback to make sure the displayname is set. Some clients may refuse
430
-		// to work with addressbooks not having a displayname.
431
-		if(is_null($values['displayname'])) {
432
-			$values['displayname'] = $url;
433
-		}
434
-
435
-		$query = $this->db->getQueryBuilder();
436
-		$query->insert('addressbooks')
437
-			->values([
438
-				'uri' => $query->createParameter('uri'),
439
-				'displayname' => $query->createParameter('displayname'),
440
-				'description' => $query->createParameter('description'),
441
-				'principaluri' => $query->createParameter('principaluri'),
442
-				'synctoken' => $query->createParameter('synctoken'),
443
-			])
444
-			->setParameters($values)
445
-			->execute();
446
-
447
-		return $query->getLastInsertId();
448
-	}
449
-
450
-	/**
451
-	 * Deletes an entire addressbook and all its contents
452
-	 *
453
-	 * @param mixed $addressBookId
454
-	 * @return void
455
-	 */
456
-	function deleteAddressBook($addressBookId) {
457
-		$query = $this->db->getQueryBuilder();
458
-		$query->delete('cards')
459
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
460
-			->setParameter('addressbookid', $addressBookId)
461
-			->execute();
462
-
463
-		$query->delete('addressbookchanges')
464
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
465
-			->setParameter('addressbookid', $addressBookId)
466
-			->execute();
467
-
468
-		$query->delete('addressbooks')
469
-			->where($query->expr()->eq('id', $query->createParameter('id')))
470
-			->setParameter('id', $addressBookId)
471
-			->execute();
472
-
473
-		$this->sharingBackend->deleteAllShares($addressBookId);
474
-
475
-		$query->delete($this->dbCardsPropertiesTable)
476
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
477
-			->execute();
478
-
479
-	}
480
-
481
-	/**
482
-	 * Returns all cards for a specific addressbook id.
483
-	 *
484
-	 * This method should return the following properties for each card:
485
-	 *   * carddata - raw vcard data
486
-	 *   * uri - Some unique url
487
-	 *   * lastmodified - A unix timestamp
488
-	 *
489
-	 * It's recommended to also return the following properties:
490
-	 *   * etag - A unique etag. This must change every time the card changes.
491
-	 *   * size - The size of the card in bytes.
492
-	 *
493
-	 * If these last two properties are provided, less time will be spent
494
-	 * calculating them. If they are specified, you can also ommit carddata.
495
-	 * This may speed up certain requests, especially with large cards.
496
-	 *
497
-	 * @param mixed $addressBookId
498
-	 * @return array
499
-	 */
500
-	function getCards($addressBookId) {
501
-		$query = $this->db->getQueryBuilder();
502
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
503
-			->from('cards')
504
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
505
-
506
-		$cards = [];
507
-
508
-		$result = $query->execute();
509
-		while($row = $result->fetch()) {
510
-			$row['etag'] = '"' . $row['etag'] . '"';
511
-			$row['carddata'] = $this->readBlob($row['carddata']);
512
-			$cards[] = $row;
513
-		}
514
-		$result->closeCursor();
515
-
516
-		return $cards;
517
-	}
518
-
519
-	/**
520
-	 * Returns a specific card.
521
-	 *
522
-	 * The same set of properties must be returned as with getCards. The only
523
-	 * exception is that 'carddata' is absolutely required.
524
-	 *
525
-	 * If the card does not exist, you must return false.
526
-	 *
527
-	 * @param mixed $addressBookId
528
-	 * @param string $cardUri
529
-	 * @return array
530
-	 */
531
-	function getCard($addressBookId, $cardUri) {
532
-		$query = $this->db->getQueryBuilder();
533
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
534
-			->from('cards')
535
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
536
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
537
-			->setMaxResults(1);
538
-
539
-		$result = $query->execute();
540
-		$row = $result->fetch();
541
-		if (!$row) {
542
-			return false;
543
-		}
544
-		$row['etag'] = '"' . $row['etag'] . '"';
545
-		$row['carddata'] = $this->readBlob($row['carddata']);
546
-
547
-		return $row;
548
-	}
549
-
550
-	/**
551
-	 * Returns a list of cards.
552
-	 *
553
-	 * This method should work identical to getCard, but instead return all the
554
-	 * cards in the list as an array.
555
-	 *
556
-	 * If the backend supports this, it may allow for some speed-ups.
557
-	 *
558
-	 * @param mixed $addressBookId
559
-	 * @param string[] $uris
560
-	 * @return array
561
-	 */
562
-	function getMultipleCards($addressBookId, array $uris) {
563
-		if (empty($uris)) {
564
-			return [];
565
-		}
566
-
567
-		$chunks = array_chunk($uris, 100);
568
-		$cards = [];
569
-
570
-		$query = $this->db->getQueryBuilder();
571
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
572
-			->from('cards')
573
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
574
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
575
-
576
-		foreach ($chunks as $uris) {
577
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
578
-			$result = $query->execute();
579
-
580
-			while ($row = $result->fetch()) {
581
-				$row['etag'] = '"' . $row['etag'] . '"';
582
-				$row['carddata'] = $this->readBlob($row['carddata']);
583
-				$cards[] = $row;
584
-			}
585
-			$result->closeCursor();
586
-		}
587
-		return $cards;
588
-	}
589
-
590
-	/**
591
-	 * Creates a new card.
592
-	 *
593
-	 * The addressbook id will be passed as the first argument. This is the
594
-	 * same id as it is returned from the getAddressBooksForUser method.
595
-	 *
596
-	 * The cardUri is a base uri, and doesn't include the full path. The
597
-	 * cardData argument is the vcard body, and is passed as a string.
598
-	 *
599
-	 * It is possible to return an ETag from this method. This ETag is for the
600
-	 * newly created resource, and must be enclosed with double quotes (that
601
-	 * is, the string itself must contain the double quotes).
602
-	 *
603
-	 * You should only return the ETag if you store the carddata as-is. If a
604
-	 * subsequent GET request on the same card does not have the same body,
605
-	 * byte-by-byte and you did return an ETag here, clients tend to get
606
-	 * confused.
607
-	 *
608
-	 * If you don't return an ETag, you can just return null.
609
-	 *
610
-	 * @param mixed $addressBookId
611
-	 * @param string $cardUri
612
-	 * @param string $cardData
613
-	 * @return string
614
-	 */
615
-	function createCard($addressBookId, $cardUri, $cardData) {
616
-		$etag = md5($cardData);
617
-		$uid = $this->getUID($cardData);
618
-
619
-		$q = $this->db->getQueryBuilder();
620
-		$q->select('uid')
621
-			->from('cards')
622
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
623
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
624
-			->setMaxResults(1);
625
-		$result = $q->execute();
626
-		$count = (bool) $result->fetchColumn();
627
-		$result->closeCursor();
628
-		if ($count) {
629
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
630
-		}
631
-
632
-		$query = $this->db->getQueryBuilder();
633
-		$query->insert('cards')
634
-			->values([
635
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
636
-				'uri' => $query->createNamedParameter($cardUri),
637
-				'lastmodified' => $query->createNamedParameter(time()),
638
-				'addressbookid' => $query->createNamedParameter($addressBookId),
639
-				'size' => $query->createNamedParameter(strlen($cardData)),
640
-				'etag' => $query->createNamedParameter($etag),
641
-				'uid' => $query->createNamedParameter($uid),
642
-			])
643
-			->execute();
644
-
645
-		$this->addChange($addressBookId, $cardUri, 1);
646
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
647
-
648
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
649
-			new GenericEvent(null, [
650
-				'addressBookId' => $addressBookId,
651
-				'cardUri' => $cardUri,
652
-				'cardData' => $cardData]));
653
-
654
-		return '"' . $etag . '"';
655
-	}
656
-
657
-	/**
658
-	 * Updates a card.
659
-	 *
660
-	 * The addressbook id will be passed as the first argument. This is the
661
-	 * same id as it is returned from the getAddressBooksForUser method.
662
-	 *
663
-	 * The cardUri is a base uri, and doesn't include the full path. The
664
-	 * cardData argument is the vcard body, and is passed as a string.
665
-	 *
666
-	 * It is possible to return an ETag from this method. This ETag should
667
-	 * match that of the updated resource, and must be enclosed with double
668
-	 * quotes (that is: the string itself must contain the actual quotes).
669
-	 *
670
-	 * You should only return the ETag if you store the carddata as-is. If a
671
-	 * subsequent GET request on the same card does not have the same body,
672
-	 * byte-by-byte and you did return an ETag here, clients tend to get
673
-	 * confused.
674
-	 *
675
-	 * If you don't return an ETag, you can just return null.
676
-	 *
677
-	 * @param mixed $addressBookId
678
-	 * @param string $cardUri
679
-	 * @param string $cardData
680
-	 * @return string
681
-	 */
682
-	function updateCard($addressBookId, $cardUri, $cardData) {
683
-
684
-		$uid = $this->getUID($cardData);
685
-		$etag = md5($cardData);
686
-		$query = $this->db->getQueryBuilder();
687
-		$query->update('cards')
688
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
689
-			->set('lastmodified', $query->createNamedParameter(time()))
690
-			->set('size', $query->createNamedParameter(strlen($cardData)))
691
-			->set('etag', $query->createNamedParameter($etag))
692
-			->set('uid', $query->createNamedParameter($uid))
693
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
694
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
695
-			->execute();
696
-
697
-		$this->addChange($addressBookId, $cardUri, 2);
698
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
699
-
700
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
701
-			new GenericEvent(null, [
702
-				'addressBookId' => $addressBookId,
703
-				'cardUri' => $cardUri,
704
-				'cardData' => $cardData]));
705
-
706
-		return '"' . $etag . '"';
707
-	}
708
-
709
-	/**
710
-	 * Deletes a card
711
-	 *
712
-	 * @param mixed $addressBookId
713
-	 * @param string $cardUri
714
-	 * @return bool
715
-	 */
716
-	function deleteCard($addressBookId, $cardUri) {
717
-		try {
718
-			$cardId = $this->getCardId($addressBookId, $cardUri);
719
-		} catch (\InvalidArgumentException $e) {
720
-			$cardId = null;
721
-		}
722
-		$query = $this->db->getQueryBuilder();
723
-		$ret = $query->delete('cards')
724
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
725
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
726
-			->execute();
727
-
728
-		$this->addChange($addressBookId, $cardUri, 3);
729
-
730
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
731
-			new GenericEvent(null, [
732
-				'addressBookId' => $addressBookId,
733
-				'cardUri' => $cardUri]));
734
-
735
-		if ($ret === 1) {
736
-			if ($cardId !== null) {
737
-				$this->purgeProperties($addressBookId, $cardId);
738
-			}
739
-			return true;
740
-		}
741
-
742
-		return false;
743
-	}
744
-
745
-	/**
746
-	 * The getChanges method returns all the changes that have happened, since
747
-	 * the specified syncToken in the specified address book.
748
-	 *
749
-	 * This function should return an array, such as the following:
750
-	 *
751
-	 * [
752
-	 *   'syncToken' => 'The current synctoken',
753
-	 *   'added'   => [
754
-	 *      'new.txt',
755
-	 *   ],
756
-	 *   'modified'   => [
757
-	 *      'modified.txt',
758
-	 *   ],
759
-	 *   'deleted' => [
760
-	 *      'foo.php.bak',
761
-	 *      'old.txt'
762
-	 *   ]
763
-	 * ];
764
-	 *
765
-	 * The returned syncToken property should reflect the *current* syncToken
766
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
767
-	 * property. This is needed here too, to ensure the operation is atomic.
768
-	 *
769
-	 * If the $syncToken argument is specified as null, this is an initial
770
-	 * sync, and all members should be reported.
771
-	 *
772
-	 * The modified property is an array of nodenames that have changed since
773
-	 * the last token.
774
-	 *
775
-	 * The deleted property is an array with nodenames, that have been deleted
776
-	 * from collection.
777
-	 *
778
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
779
-	 * 1, you only have to report changes that happened only directly in
780
-	 * immediate descendants. If it's 2, it should also include changes from
781
-	 * the nodes below the child collections. (grandchildren)
782
-	 *
783
-	 * The $limit argument allows a client to specify how many results should
784
-	 * be returned at most. If the limit is not specified, it should be treated
785
-	 * as infinite.
786
-	 *
787
-	 * If the limit (infinite or not) is higher than you're willing to return,
788
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
789
-	 *
790
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
791
-	 * return null.
792
-	 *
793
-	 * The limit is 'suggestive'. You are free to ignore it.
794
-	 *
795
-	 * @param string $addressBookId
796
-	 * @param string $syncToken
797
-	 * @param int $syncLevel
798
-	 * @param int $limit
799
-	 * @return array
800
-	 */
801
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
802
-		// Current synctoken
803
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
804
-		$stmt->execute([ $addressBookId ]);
805
-		$currentToken = $stmt->fetchColumn(0);
806
-
807
-		if (is_null($currentToken)) return null;
808
-
809
-		$result = [
810
-			'syncToken' => $currentToken,
811
-			'added'     => [],
812
-			'modified'  => [],
813
-			'deleted'   => [],
814
-		];
815
-
816
-		if ($syncToken) {
817
-
818
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
819
-			if ($limit>0) {
820
-				$query .= " LIMIT " . (int)$limit;
821
-			}
822
-
823
-			// Fetching all changes
824
-			$stmt = $this->db->prepare($query);
825
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
826
-
827
-			$changes = [];
828
-
829
-			// This loop ensures that any duplicates are overwritten, only the
830
-			// last change on a node is relevant.
831
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
832
-
833
-				$changes[$row['uri']] = $row['operation'];
834
-
835
-			}
836
-
837
-			foreach($changes as $uri => $operation) {
838
-
839
-				switch($operation) {
840
-					case 1:
841
-						$result['added'][] = $uri;
842
-						break;
843
-					case 2:
844
-						$result['modified'][] = $uri;
845
-						break;
846
-					case 3:
847
-						$result['deleted'][] = $uri;
848
-						break;
849
-				}
850
-
851
-			}
852
-		} else {
853
-			// No synctoken supplied, this is the initial sync.
854
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
855
-			$stmt = $this->db->prepare($query);
856
-			$stmt->execute([$addressBookId]);
857
-
858
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
859
-		}
860
-		return $result;
861
-	}
862
-
863
-	/**
864
-	 * Adds a change record to the addressbookchanges table.
865
-	 *
866
-	 * @param mixed $addressBookId
867
-	 * @param string $objectUri
868
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
869
-	 * @return void
870
-	 */
871
-	protected function addChange($addressBookId, $objectUri, $operation) {
872
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
873
-		$stmt = $this->db->prepare($sql);
874
-		$stmt->execute([
875
-			$objectUri,
876
-			$addressBookId,
877
-			$operation,
878
-			$addressBookId
879
-		]);
880
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
881
-		$stmt->execute([
882
-			$addressBookId
883
-		]);
884
-	}
885
-
886
-	private function readBlob($cardData) {
887
-		if (is_resource($cardData)) {
888
-			return stream_get_contents($cardData);
889
-		}
890
-
891
-		return $cardData;
892
-	}
893
-
894
-	/**
895
-	 * @param IShareable $shareable
896
-	 * @param string[] $add
897
-	 * @param string[] $remove
898
-	 */
899
-	public function updateShares(IShareable $shareable, $add, $remove) {
900
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
901
-	}
902
-
903
-	/**
904
-	 * search contact
905
-	 *
906
-	 * @param int $addressBookId
907
-	 * @param string $pattern which should match within the $searchProperties
908
-	 * @param array $searchProperties defines the properties within the query pattern should match
909
-	 * @param array $options = array() to define the search behavior
910
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
911
-	 * @return array an array of contacts which are arrays of key-value-pairs
912
-	 */
913
-	public function search($addressBookId, $pattern, $searchProperties, $options = []) {
914
-		$query = $this->db->getQueryBuilder();
915
-		$query2 = $this->db->getQueryBuilder();
916
-
917
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
918
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
919
-		$or = $query2->expr()->orX();
920
-		foreach ($searchProperties as $property) {
921
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
922
-		}
923
-		$query2->andWhere($or);
924
-
925
-		// No need for like when the pattern is empty
926
-		if ('' !== $pattern) {
927
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
928
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
929
-			} else {
930
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
931
-			}
932
-		}
933
-
934
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
935
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
936
-
937
-		$result = $query->execute();
938
-		$cards = $result->fetchAll();
939
-
940
-		$result->closeCursor();
941
-
942
-		return array_map(function($array) {
943
-			$array['carddata'] = $this->readBlob($array['carddata']);
944
-			return $array;
945
-		}, $cards);
946
-	}
947
-
948
-	/**
949
-	 * @param int $bookId
950
-	 * @param string $name
951
-	 * @return array
952
-	 */
953
-	public function collectCardProperties($bookId, $name) {
954
-		$query = $this->db->getQueryBuilder();
955
-		$result = $query->selectDistinct('value')
956
-			->from($this->dbCardsPropertiesTable)
957
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
958
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
959
-			->execute();
960
-
961
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
962
-		$result->closeCursor();
963
-
964
-		return $all;
965
-	}
966
-
967
-	/**
968
-	 * get URI from a given contact
969
-	 *
970
-	 * @param int $id
971
-	 * @return string
972
-	 */
973
-	public function getCardUri($id) {
974
-		$query = $this->db->getQueryBuilder();
975
-		$query->select('uri')->from($this->dbCardsTable)
976
-				->where($query->expr()->eq('id', $query->createParameter('id')))
977
-				->setParameter('id', $id);
978
-
979
-		$result = $query->execute();
980
-		$uri = $result->fetch();
981
-		$result->closeCursor();
982
-
983
-		if (!isset($uri['uri'])) {
984
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
985
-		}
986
-
987
-		return $uri['uri'];
988
-	}
989
-
990
-	/**
991
-	 * return contact with the given URI
992
-	 *
993
-	 * @param int $addressBookId
994
-	 * @param string $uri
995
-	 * @returns array
996
-	 */
997
-	public function getContact($addressBookId, $uri) {
998
-		$result = [];
999
-		$query = $this->db->getQueryBuilder();
1000
-		$query->select('*')->from($this->dbCardsTable)
1001
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1002
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1003
-		$queryResult = $query->execute();
1004
-		$contact = $queryResult->fetch();
1005
-		$queryResult->closeCursor();
1006
-
1007
-		if (is_array($contact)) {
1008
-			$result = $contact;
1009
-		}
1010
-
1011
-		return $result;
1012
-	}
1013
-
1014
-	/**
1015
-	 * Returns the list of people whom this address book is shared with.
1016
-	 *
1017
-	 * Every element in this array should have the following properties:
1018
-	 *   * href - Often a mailto: address
1019
-	 *   * commonName - Optional, for example a first + last name
1020
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1021
-	 *   * readOnly - boolean
1022
-	 *   * summary - Optional, a description for the share
1023
-	 *
1024
-	 * @return array
1025
-	 */
1026
-	public function getShares($addressBookId) {
1027
-		return $this->sharingBackend->getShares($addressBookId);
1028
-	}
1029
-
1030
-	/**
1031
-	 * update properties table
1032
-	 *
1033
-	 * @param int $addressBookId
1034
-	 * @param string $cardUri
1035
-	 * @param string $vCardSerialized
1036
-	 */
1037
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1038
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1039
-		$vCard = $this->readCard($vCardSerialized);
1040
-
1041
-		$this->purgeProperties($addressBookId, $cardId);
1042
-
1043
-		$query = $this->db->getQueryBuilder();
1044
-		$query->insert($this->dbCardsPropertiesTable)
1045
-			->values(
1046
-				[
1047
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1048
-					'cardid' => $query->createNamedParameter($cardId),
1049
-					'name' => $query->createParameter('name'),
1050
-					'value' => $query->createParameter('value'),
1051
-					'preferred' => $query->createParameter('preferred')
1052
-				]
1053
-			);
1054
-
1055
-		foreach ($vCard->children() as $property) {
1056
-			if(!in_array($property->name, self::$indexProperties)) {
1057
-				continue;
1058
-			}
1059
-			$preferred = 0;
1060
-			foreach($property->parameters as $parameter) {
1061
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1062
-					$preferred = 1;
1063
-					break;
1064
-				}
1065
-			}
1066
-			$query->setParameter('name', $property->name);
1067
-			$query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1068
-			$query->setParameter('preferred', $preferred);
1069
-			$query->execute();
1070
-		}
1071
-	}
1072
-
1073
-	/**
1074
-	 * read vCard data into a vCard object
1075
-	 *
1076
-	 * @param string $cardData
1077
-	 * @return VCard
1078
-	 */
1079
-	protected function readCard($cardData) {
1080
-		return  Reader::read($cardData);
1081
-	}
1082
-
1083
-	/**
1084
-	 * delete all properties from a given card
1085
-	 *
1086
-	 * @param int $addressBookId
1087
-	 * @param int $cardId
1088
-	 */
1089
-	protected function purgeProperties($addressBookId, $cardId) {
1090
-		$query = $this->db->getQueryBuilder();
1091
-		$query->delete($this->dbCardsPropertiesTable)
1092
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1093
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1094
-		$query->execute();
1095
-	}
1096
-
1097
-	/**
1098
-	 * get ID from a given contact
1099
-	 *
1100
-	 * @param int $addressBookId
1101
-	 * @param string $uri
1102
-	 * @return int
1103
-	 */
1104
-	protected function getCardId($addressBookId, $uri) {
1105
-		$query = $this->db->getQueryBuilder();
1106
-		$query->select('id')->from($this->dbCardsTable)
1107
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1108
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1109
-
1110
-		$result = $query->execute();
1111
-		$cardIds = $result->fetch();
1112
-		$result->closeCursor();
1113
-
1114
-		if (!isset($cardIds['id'])) {
1115
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1116
-		}
1117
-
1118
-		return (int)$cardIds['id'];
1119
-	}
1120
-
1121
-	/**
1122
-	 * For shared address books the sharee is set in the ACL of the address book
1123
-	 * @param $addressBookId
1124
-	 * @param $acl
1125
-	 * @return array
1126
-	 */
1127
-	public function applyShareAcl($addressBookId, $acl) {
1128
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1129
-	}
1130
-
1131
-	private function convertPrincipal($principalUri, $toV2) {
1132
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1133
-			list(, $name) = \Sabre\Uri\split($principalUri);
1134
-			if ($toV2 === true) {
1135
-				return "principals/users/$name";
1136
-			}
1137
-			return "principals/$name";
1138
-		}
1139
-		return $principalUri;
1140
-	}
1141
-
1142
-	private function addOwnerPrincipal(&$addressbookInfo) {
1143
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1144
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1145
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1146
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1147
-		} else {
1148
-			$uri = $addressbookInfo['principaluri'];
1149
-		}
1150
-
1151
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1152
-		if (isset($principalInformation['{DAV:}displayname'])) {
1153
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1154
-		}
1155
-	}
1156
-
1157
-	/**
1158
-	 * Extract UID from vcard
1159
-	 *
1160
-	 * @param string $cardData the vcard raw data
1161
-	 * @return string the uid
1162
-	 * @throws BadRequest if no UID is available
1163
-	 */
1164
-	private function getUID($cardData) {
1165
-		if ($cardData != '') {
1166
-			$vCard = Reader::read($cardData);
1167
-			if ($vCard->UID) {
1168
-				$uid = $vCard->UID->getValue();
1169
-				return $uid;
1170
-			}
1171
-			// should already be handled, but just in case
1172
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1173
-		}
1174
-		// should already be handled, but just in case
1175
-		throw new BadRequest('vCard can not be empty');
1176
-	}
59
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
60
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
61
+
62
+    /** @var Principal */
63
+    private $principalBackend;
64
+
65
+    /** @var string */
66
+    private $dbCardsTable = 'cards';
67
+
68
+    /** @var string */
69
+    private $dbCardsPropertiesTable = 'cards_properties';
70
+
71
+    /** @var IDBConnection */
72
+    private $db;
73
+
74
+    /** @var Backend */
75
+    private $sharingBackend;
76
+
77
+    /** @var array properties to index */
78
+    public static $indexProperties = [
79
+        'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
80
+        'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
81
+
82
+    /**
83
+     * @var string[] Map of uid => display name
84
+     */
85
+    protected $userDisplayNames;
86
+
87
+    /** @var IUserManager */
88
+    private $userManager;
89
+
90
+    /** @var EventDispatcherInterface */
91
+    private $dispatcher;
92
+
93
+    /**
94
+     * CardDavBackend constructor.
95
+     *
96
+     * @param IDBConnection $db
97
+     * @param Principal $principalBackend
98
+     * @param IUserManager $userManager
99
+     * @param IGroupManager $groupManager
100
+     * @param EventDispatcherInterface $dispatcher
101
+     */
102
+    public function __construct(IDBConnection $db,
103
+                                Principal $principalBackend,
104
+                                IUserManager $userManager,
105
+                                IGroupManager $groupManager,
106
+                                EventDispatcherInterface $dispatcher) {
107
+        $this->db = $db;
108
+        $this->principalBackend = $principalBackend;
109
+        $this->userManager = $userManager;
110
+        $this->dispatcher = $dispatcher;
111
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
112
+    }
113
+
114
+    /**
115
+     * Return the number of address books for a principal
116
+     *
117
+     * @param $principalUri
118
+     * @return int
119
+     */
120
+    public function getAddressBooksForUserCount($principalUri) {
121
+        $principalUri = $this->convertPrincipal($principalUri, true);
122
+        $query = $this->db->getQueryBuilder();
123
+        $query->select($query->func()->count('*'))
124
+            ->from('addressbooks')
125
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
126
+
127
+        return (int)$query->execute()->fetchColumn();
128
+    }
129
+
130
+    /**
131
+     * Returns the list of address books for a specific user.
132
+     *
133
+     * Every addressbook should have the following properties:
134
+     *   id - an arbitrary unique id
135
+     *   uri - the 'basename' part of the url
136
+     *   principaluri - Same as the passed parameter
137
+     *
138
+     * Any additional clark-notation property may be passed besides this. Some
139
+     * common ones are :
140
+     *   {DAV:}displayname
141
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
142
+     *   {http://calendarserver.org/ns/}getctag
143
+     *
144
+     * @param string $principalUri
145
+     * @return array
146
+     */
147
+    function getAddressBooksForUser($principalUri) {
148
+        $principalUriOriginal = $principalUri;
149
+        $principalUri = $this->convertPrincipal($principalUri, true);
150
+        $query = $this->db->getQueryBuilder();
151
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
152
+            ->from('addressbooks')
153
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
154
+
155
+        $addressBooks = [];
156
+
157
+        $result = $query->execute();
158
+        while($row = $result->fetch()) {
159
+            $addressBooks[$row['id']] = [
160
+                'id'  => $row['id'],
161
+                'uri' => $row['uri'],
162
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
163
+                '{DAV:}displayname' => $row['displayname'],
164
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
165
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
166
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
167
+            ];
168
+
169
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
170
+        }
171
+        $result->closeCursor();
172
+
173
+        // query for shared addressbooks
174
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
175
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
176
+
177
+        $principals = array_map(function($principal) {
178
+            return urldecode($principal);
179
+        }, $principals);
180
+        $principals[]= $principalUri;
181
+
182
+        $query = $this->db->getQueryBuilder();
183
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
184
+            ->from('dav_shares', 's')
185
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
186
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
187
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
188
+            ->setParameter('type', 'addressbook')
189
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
190
+            ->execute();
191
+
192
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
193
+        while($row = $result->fetch()) {
194
+            if ($row['principaluri'] === $principalUri) {
195
+                continue;
196
+            }
197
+
198
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
199
+            if (isset($addressBooks[$row['id']])) {
200
+                if ($readOnly) {
201
+                    // New share can not have more permissions then the old one.
202
+                    continue;
203
+                }
204
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
205
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
206
+                    // Old share is already read-write, no more permissions can be gained
207
+                    continue;
208
+                }
209
+            }
210
+
211
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
212
+            $uri = $row['uri'] . '_shared_by_' . $name;
213
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
214
+
215
+            $addressBooks[$row['id']] = [
216
+                'id'  => $row['id'],
217
+                'uri' => $uri,
218
+                'principaluri' => $principalUriOriginal,
219
+                '{DAV:}displayname' => $displayName,
220
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
221
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
222
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
223
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
224
+                $readOnlyPropertyName => $readOnly,
225
+            ];
226
+
227
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
228
+        }
229
+        $result->closeCursor();
230
+
231
+        return array_values($addressBooks);
232
+    }
233
+
234
+    public function getUsersOwnAddressBooks($principalUri) {
235
+        $principalUri = $this->convertPrincipal($principalUri, true);
236
+        $query = $this->db->getQueryBuilder();
237
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
238
+                ->from('addressbooks')
239
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
240
+
241
+        $addressBooks = [];
242
+
243
+        $result = $query->execute();
244
+        while($row = $result->fetch()) {
245
+            $addressBooks[$row['id']] = [
246
+                'id'  => $row['id'],
247
+                'uri' => $row['uri'],
248
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
249
+                '{DAV:}displayname' => $row['displayname'],
250
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
251
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
252
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
253
+            ];
254
+
255
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
256
+        }
257
+        $result->closeCursor();
258
+
259
+        return array_values($addressBooks);
260
+    }
261
+
262
+    private function getUserDisplayName($uid) {
263
+        if (!isset($this->userDisplayNames[$uid])) {
264
+            $user = $this->userManager->get($uid);
265
+
266
+            if ($user instanceof IUser) {
267
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
268
+            } else {
269
+                $this->userDisplayNames[$uid] = $uid;
270
+            }
271
+        }
272
+
273
+        return $this->userDisplayNames[$uid];
274
+    }
275
+
276
+    /**
277
+     * @param int $addressBookId
278
+     */
279
+    public function getAddressBookById($addressBookId) {
280
+        $query = $this->db->getQueryBuilder();
281
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
282
+            ->from('addressbooks')
283
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
284
+            ->execute();
285
+
286
+        $row = $result->fetch();
287
+        $result->closeCursor();
288
+        if ($row === false) {
289
+            return null;
290
+        }
291
+
292
+        $addressBook = [
293
+            'id'  => $row['id'],
294
+            'uri' => $row['uri'],
295
+            'principaluri' => $row['principaluri'],
296
+            '{DAV:}displayname' => $row['displayname'],
297
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
298
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
299
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
300
+        ];
301
+
302
+        $this->addOwnerPrincipal($addressBook);
303
+
304
+        return $addressBook;
305
+    }
306
+
307
+    /**
308
+     * @param $addressBookUri
309
+     * @return array|null
310
+     */
311
+    public function getAddressBooksByUri($principal, $addressBookUri) {
312
+        $query = $this->db->getQueryBuilder();
313
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
314
+            ->from('addressbooks')
315
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
316
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
317
+            ->setMaxResults(1)
318
+            ->execute();
319
+
320
+        $row = $result->fetch();
321
+        $result->closeCursor();
322
+        if ($row === false) {
323
+            return null;
324
+        }
325
+
326
+        $addressBook = [
327
+            'id'  => $row['id'],
328
+            'uri' => $row['uri'],
329
+            'principaluri' => $row['principaluri'],
330
+            '{DAV:}displayname' => $row['displayname'],
331
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
332
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
333
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
+        ];
335
+
336
+        $this->addOwnerPrincipal($addressBook);
337
+
338
+        return $addressBook;
339
+    }
340
+
341
+    /**
342
+     * Updates properties for an address book.
343
+     *
344
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
345
+     * To do the actual updates, you must tell this object which properties
346
+     * you're going to process with the handle() method.
347
+     *
348
+     * Calling the handle method is like telling the PropPatch object "I
349
+     * promise I can handle updating this property".
350
+     *
351
+     * Read the PropPatch documentation for more info and examples.
352
+     *
353
+     * @param string $addressBookId
354
+     * @param \Sabre\DAV\PropPatch $propPatch
355
+     * @return void
356
+     */
357
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
358
+        $supportedProperties = [
359
+            '{DAV:}displayname',
360
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
361
+        ];
362
+
363
+        /**
364
+         * @suppress SqlInjectionChecker
365
+         */
366
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
367
+
368
+            $updates = [];
369
+            foreach($mutations as $property=>$newValue) {
370
+
371
+                switch($property) {
372
+                    case '{DAV:}displayname' :
373
+                        $updates['displayname'] = $newValue;
374
+                        break;
375
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
376
+                        $updates['description'] = $newValue;
377
+                        break;
378
+                }
379
+            }
380
+            $query = $this->db->getQueryBuilder();
381
+            $query->update('addressbooks');
382
+
383
+            foreach($updates as $key=>$value) {
384
+                $query->set($key, $query->createNamedParameter($value));
385
+            }
386
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
387
+            ->execute();
388
+
389
+            $this->addChange($addressBookId, "", 2);
390
+
391
+            return true;
392
+
393
+        });
394
+    }
395
+
396
+    /**
397
+     * Creates a new address book
398
+     *
399
+     * @param string $principalUri
400
+     * @param string $url Just the 'basename' of the url.
401
+     * @param array $properties
402
+     * @return int
403
+     * @throws BadRequest
404
+     */
405
+    function createAddressBook($principalUri, $url, array $properties) {
406
+        $values = [
407
+            'displayname' => null,
408
+            'description' => null,
409
+            'principaluri' => $principalUri,
410
+            'uri' => $url,
411
+            'synctoken' => 1
412
+        ];
413
+
414
+        foreach($properties as $property=>$newValue) {
415
+
416
+            switch($property) {
417
+                case '{DAV:}displayname' :
418
+                    $values['displayname'] = $newValue;
419
+                    break;
420
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
421
+                    $values['description'] = $newValue;
422
+                    break;
423
+                default :
424
+                    throw new BadRequest('Unknown property: ' . $property);
425
+            }
426
+
427
+        }
428
+
429
+        // Fallback to make sure the displayname is set. Some clients may refuse
430
+        // to work with addressbooks not having a displayname.
431
+        if(is_null($values['displayname'])) {
432
+            $values['displayname'] = $url;
433
+        }
434
+
435
+        $query = $this->db->getQueryBuilder();
436
+        $query->insert('addressbooks')
437
+            ->values([
438
+                'uri' => $query->createParameter('uri'),
439
+                'displayname' => $query->createParameter('displayname'),
440
+                'description' => $query->createParameter('description'),
441
+                'principaluri' => $query->createParameter('principaluri'),
442
+                'synctoken' => $query->createParameter('synctoken'),
443
+            ])
444
+            ->setParameters($values)
445
+            ->execute();
446
+
447
+        return $query->getLastInsertId();
448
+    }
449
+
450
+    /**
451
+     * Deletes an entire addressbook and all its contents
452
+     *
453
+     * @param mixed $addressBookId
454
+     * @return void
455
+     */
456
+    function deleteAddressBook($addressBookId) {
457
+        $query = $this->db->getQueryBuilder();
458
+        $query->delete('cards')
459
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
460
+            ->setParameter('addressbookid', $addressBookId)
461
+            ->execute();
462
+
463
+        $query->delete('addressbookchanges')
464
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
465
+            ->setParameter('addressbookid', $addressBookId)
466
+            ->execute();
467
+
468
+        $query->delete('addressbooks')
469
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
470
+            ->setParameter('id', $addressBookId)
471
+            ->execute();
472
+
473
+        $this->sharingBackend->deleteAllShares($addressBookId);
474
+
475
+        $query->delete($this->dbCardsPropertiesTable)
476
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
477
+            ->execute();
478
+
479
+    }
480
+
481
+    /**
482
+     * Returns all cards for a specific addressbook id.
483
+     *
484
+     * This method should return the following properties for each card:
485
+     *   * carddata - raw vcard data
486
+     *   * uri - Some unique url
487
+     *   * lastmodified - A unix timestamp
488
+     *
489
+     * It's recommended to also return the following properties:
490
+     *   * etag - A unique etag. This must change every time the card changes.
491
+     *   * size - The size of the card in bytes.
492
+     *
493
+     * If these last two properties are provided, less time will be spent
494
+     * calculating them. If they are specified, you can also ommit carddata.
495
+     * This may speed up certain requests, especially with large cards.
496
+     *
497
+     * @param mixed $addressBookId
498
+     * @return array
499
+     */
500
+    function getCards($addressBookId) {
501
+        $query = $this->db->getQueryBuilder();
502
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
503
+            ->from('cards')
504
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
505
+
506
+        $cards = [];
507
+
508
+        $result = $query->execute();
509
+        while($row = $result->fetch()) {
510
+            $row['etag'] = '"' . $row['etag'] . '"';
511
+            $row['carddata'] = $this->readBlob($row['carddata']);
512
+            $cards[] = $row;
513
+        }
514
+        $result->closeCursor();
515
+
516
+        return $cards;
517
+    }
518
+
519
+    /**
520
+     * Returns a specific card.
521
+     *
522
+     * The same set of properties must be returned as with getCards. The only
523
+     * exception is that 'carddata' is absolutely required.
524
+     *
525
+     * If the card does not exist, you must return false.
526
+     *
527
+     * @param mixed $addressBookId
528
+     * @param string $cardUri
529
+     * @return array
530
+     */
531
+    function getCard($addressBookId, $cardUri) {
532
+        $query = $this->db->getQueryBuilder();
533
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
534
+            ->from('cards')
535
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
536
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
537
+            ->setMaxResults(1);
538
+
539
+        $result = $query->execute();
540
+        $row = $result->fetch();
541
+        if (!$row) {
542
+            return false;
543
+        }
544
+        $row['etag'] = '"' . $row['etag'] . '"';
545
+        $row['carddata'] = $this->readBlob($row['carddata']);
546
+
547
+        return $row;
548
+    }
549
+
550
+    /**
551
+     * Returns a list of cards.
552
+     *
553
+     * This method should work identical to getCard, but instead return all the
554
+     * cards in the list as an array.
555
+     *
556
+     * If the backend supports this, it may allow for some speed-ups.
557
+     *
558
+     * @param mixed $addressBookId
559
+     * @param string[] $uris
560
+     * @return array
561
+     */
562
+    function getMultipleCards($addressBookId, array $uris) {
563
+        if (empty($uris)) {
564
+            return [];
565
+        }
566
+
567
+        $chunks = array_chunk($uris, 100);
568
+        $cards = [];
569
+
570
+        $query = $this->db->getQueryBuilder();
571
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
572
+            ->from('cards')
573
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
574
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
575
+
576
+        foreach ($chunks as $uris) {
577
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
578
+            $result = $query->execute();
579
+
580
+            while ($row = $result->fetch()) {
581
+                $row['etag'] = '"' . $row['etag'] . '"';
582
+                $row['carddata'] = $this->readBlob($row['carddata']);
583
+                $cards[] = $row;
584
+            }
585
+            $result->closeCursor();
586
+        }
587
+        return $cards;
588
+    }
589
+
590
+    /**
591
+     * Creates a new card.
592
+     *
593
+     * The addressbook id will be passed as the first argument. This is the
594
+     * same id as it is returned from the getAddressBooksForUser method.
595
+     *
596
+     * The cardUri is a base uri, and doesn't include the full path. The
597
+     * cardData argument is the vcard body, and is passed as a string.
598
+     *
599
+     * It is possible to return an ETag from this method. This ETag is for the
600
+     * newly created resource, and must be enclosed with double quotes (that
601
+     * is, the string itself must contain the double quotes).
602
+     *
603
+     * You should only return the ETag if you store the carddata as-is. If a
604
+     * subsequent GET request on the same card does not have the same body,
605
+     * byte-by-byte and you did return an ETag here, clients tend to get
606
+     * confused.
607
+     *
608
+     * If you don't return an ETag, you can just return null.
609
+     *
610
+     * @param mixed $addressBookId
611
+     * @param string $cardUri
612
+     * @param string $cardData
613
+     * @return string
614
+     */
615
+    function createCard($addressBookId, $cardUri, $cardData) {
616
+        $etag = md5($cardData);
617
+        $uid = $this->getUID($cardData);
618
+
619
+        $q = $this->db->getQueryBuilder();
620
+        $q->select('uid')
621
+            ->from('cards')
622
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
623
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
624
+            ->setMaxResults(1);
625
+        $result = $q->execute();
626
+        $count = (bool) $result->fetchColumn();
627
+        $result->closeCursor();
628
+        if ($count) {
629
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
630
+        }
631
+
632
+        $query = $this->db->getQueryBuilder();
633
+        $query->insert('cards')
634
+            ->values([
635
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
636
+                'uri' => $query->createNamedParameter($cardUri),
637
+                'lastmodified' => $query->createNamedParameter(time()),
638
+                'addressbookid' => $query->createNamedParameter($addressBookId),
639
+                'size' => $query->createNamedParameter(strlen($cardData)),
640
+                'etag' => $query->createNamedParameter($etag),
641
+                'uid' => $query->createNamedParameter($uid),
642
+            ])
643
+            ->execute();
644
+
645
+        $this->addChange($addressBookId, $cardUri, 1);
646
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
647
+
648
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
649
+            new GenericEvent(null, [
650
+                'addressBookId' => $addressBookId,
651
+                'cardUri' => $cardUri,
652
+                'cardData' => $cardData]));
653
+
654
+        return '"' . $etag . '"';
655
+    }
656
+
657
+    /**
658
+     * Updates a card.
659
+     *
660
+     * The addressbook id will be passed as the first argument. This is the
661
+     * same id as it is returned from the getAddressBooksForUser method.
662
+     *
663
+     * The cardUri is a base uri, and doesn't include the full path. The
664
+     * cardData argument is the vcard body, and is passed as a string.
665
+     *
666
+     * It is possible to return an ETag from this method. This ETag should
667
+     * match that of the updated resource, and must be enclosed with double
668
+     * quotes (that is: the string itself must contain the actual quotes).
669
+     *
670
+     * You should only return the ETag if you store the carddata as-is. If a
671
+     * subsequent GET request on the same card does not have the same body,
672
+     * byte-by-byte and you did return an ETag here, clients tend to get
673
+     * confused.
674
+     *
675
+     * If you don't return an ETag, you can just return null.
676
+     *
677
+     * @param mixed $addressBookId
678
+     * @param string $cardUri
679
+     * @param string $cardData
680
+     * @return string
681
+     */
682
+    function updateCard($addressBookId, $cardUri, $cardData) {
683
+
684
+        $uid = $this->getUID($cardData);
685
+        $etag = md5($cardData);
686
+        $query = $this->db->getQueryBuilder();
687
+        $query->update('cards')
688
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
689
+            ->set('lastmodified', $query->createNamedParameter(time()))
690
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
691
+            ->set('etag', $query->createNamedParameter($etag))
692
+            ->set('uid', $query->createNamedParameter($uid))
693
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
694
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
695
+            ->execute();
696
+
697
+        $this->addChange($addressBookId, $cardUri, 2);
698
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
699
+
700
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
701
+            new GenericEvent(null, [
702
+                'addressBookId' => $addressBookId,
703
+                'cardUri' => $cardUri,
704
+                'cardData' => $cardData]));
705
+
706
+        return '"' . $etag . '"';
707
+    }
708
+
709
+    /**
710
+     * Deletes a card
711
+     *
712
+     * @param mixed $addressBookId
713
+     * @param string $cardUri
714
+     * @return bool
715
+     */
716
+    function deleteCard($addressBookId, $cardUri) {
717
+        try {
718
+            $cardId = $this->getCardId($addressBookId, $cardUri);
719
+        } catch (\InvalidArgumentException $e) {
720
+            $cardId = null;
721
+        }
722
+        $query = $this->db->getQueryBuilder();
723
+        $ret = $query->delete('cards')
724
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
725
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
726
+            ->execute();
727
+
728
+        $this->addChange($addressBookId, $cardUri, 3);
729
+
730
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
731
+            new GenericEvent(null, [
732
+                'addressBookId' => $addressBookId,
733
+                'cardUri' => $cardUri]));
734
+
735
+        if ($ret === 1) {
736
+            if ($cardId !== null) {
737
+                $this->purgeProperties($addressBookId, $cardId);
738
+            }
739
+            return true;
740
+        }
741
+
742
+        return false;
743
+    }
744
+
745
+    /**
746
+     * The getChanges method returns all the changes that have happened, since
747
+     * the specified syncToken in the specified address book.
748
+     *
749
+     * This function should return an array, such as the following:
750
+     *
751
+     * [
752
+     *   'syncToken' => 'The current synctoken',
753
+     *   'added'   => [
754
+     *      'new.txt',
755
+     *   ],
756
+     *   'modified'   => [
757
+     *      'modified.txt',
758
+     *   ],
759
+     *   'deleted' => [
760
+     *      'foo.php.bak',
761
+     *      'old.txt'
762
+     *   ]
763
+     * ];
764
+     *
765
+     * The returned syncToken property should reflect the *current* syncToken
766
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
767
+     * property. This is needed here too, to ensure the operation is atomic.
768
+     *
769
+     * If the $syncToken argument is specified as null, this is an initial
770
+     * sync, and all members should be reported.
771
+     *
772
+     * The modified property is an array of nodenames that have changed since
773
+     * the last token.
774
+     *
775
+     * The deleted property is an array with nodenames, that have been deleted
776
+     * from collection.
777
+     *
778
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
779
+     * 1, you only have to report changes that happened only directly in
780
+     * immediate descendants. If it's 2, it should also include changes from
781
+     * the nodes below the child collections. (grandchildren)
782
+     *
783
+     * The $limit argument allows a client to specify how many results should
784
+     * be returned at most. If the limit is not specified, it should be treated
785
+     * as infinite.
786
+     *
787
+     * If the limit (infinite or not) is higher than you're willing to return,
788
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
789
+     *
790
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
791
+     * return null.
792
+     *
793
+     * The limit is 'suggestive'. You are free to ignore it.
794
+     *
795
+     * @param string $addressBookId
796
+     * @param string $syncToken
797
+     * @param int $syncLevel
798
+     * @param int $limit
799
+     * @return array
800
+     */
801
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
802
+        // Current synctoken
803
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
804
+        $stmt->execute([ $addressBookId ]);
805
+        $currentToken = $stmt->fetchColumn(0);
806
+
807
+        if (is_null($currentToken)) return null;
808
+
809
+        $result = [
810
+            'syncToken' => $currentToken,
811
+            'added'     => [],
812
+            'modified'  => [],
813
+            'deleted'   => [],
814
+        ];
815
+
816
+        if ($syncToken) {
817
+
818
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
819
+            if ($limit>0) {
820
+                $query .= " LIMIT " . (int)$limit;
821
+            }
822
+
823
+            // Fetching all changes
824
+            $stmt = $this->db->prepare($query);
825
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
826
+
827
+            $changes = [];
828
+
829
+            // This loop ensures that any duplicates are overwritten, only the
830
+            // last change on a node is relevant.
831
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
832
+
833
+                $changes[$row['uri']] = $row['operation'];
834
+
835
+            }
836
+
837
+            foreach($changes as $uri => $operation) {
838
+
839
+                switch($operation) {
840
+                    case 1:
841
+                        $result['added'][] = $uri;
842
+                        break;
843
+                    case 2:
844
+                        $result['modified'][] = $uri;
845
+                        break;
846
+                    case 3:
847
+                        $result['deleted'][] = $uri;
848
+                        break;
849
+                }
850
+
851
+            }
852
+        } else {
853
+            // No synctoken supplied, this is the initial sync.
854
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
855
+            $stmt = $this->db->prepare($query);
856
+            $stmt->execute([$addressBookId]);
857
+
858
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
859
+        }
860
+        return $result;
861
+    }
862
+
863
+    /**
864
+     * Adds a change record to the addressbookchanges table.
865
+     *
866
+     * @param mixed $addressBookId
867
+     * @param string $objectUri
868
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
869
+     * @return void
870
+     */
871
+    protected function addChange($addressBookId, $objectUri, $operation) {
872
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
873
+        $stmt = $this->db->prepare($sql);
874
+        $stmt->execute([
875
+            $objectUri,
876
+            $addressBookId,
877
+            $operation,
878
+            $addressBookId
879
+        ]);
880
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
881
+        $stmt->execute([
882
+            $addressBookId
883
+        ]);
884
+    }
885
+
886
+    private function readBlob($cardData) {
887
+        if (is_resource($cardData)) {
888
+            return stream_get_contents($cardData);
889
+        }
890
+
891
+        return $cardData;
892
+    }
893
+
894
+    /**
895
+     * @param IShareable $shareable
896
+     * @param string[] $add
897
+     * @param string[] $remove
898
+     */
899
+    public function updateShares(IShareable $shareable, $add, $remove) {
900
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
901
+    }
902
+
903
+    /**
904
+     * search contact
905
+     *
906
+     * @param int $addressBookId
907
+     * @param string $pattern which should match within the $searchProperties
908
+     * @param array $searchProperties defines the properties within the query pattern should match
909
+     * @param array $options = array() to define the search behavior
910
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
911
+     * @return array an array of contacts which are arrays of key-value-pairs
912
+     */
913
+    public function search($addressBookId, $pattern, $searchProperties, $options = []) {
914
+        $query = $this->db->getQueryBuilder();
915
+        $query2 = $this->db->getQueryBuilder();
916
+
917
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
918
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
919
+        $or = $query2->expr()->orX();
920
+        foreach ($searchProperties as $property) {
921
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
922
+        }
923
+        $query2->andWhere($or);
924
+
925
+        // No need for like when the pattern is empty
926
+        if ('' !== $pattern) {
927
+            if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
928
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
929
+            } else {
930
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
931
+            }
932
+        }
933
+
934
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
935
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
936
+
937
+        $result = $query->execute();
938
+        $cards = $result->fetchAll();
939
+
940
+        $result->closeCursor();
941
+
942
+        return array_map(function($array) {
943
+            $array['carddata'] = $this->readBlob($array['carddata']);
944
+            return $array;
945
+        }, $cards);
946
+    }
947
+
948
+    /**
949
+     * @param int $bookId
950
+     * @param string $name
951
+     * @return array
952
+     */
953
+    public function collectCardProperties($bookId, $name) {
954
+        $query = $this->db->getQueryBuilder();
955
+        $result = $query->selectDistinct('value')
956
+            ->from($this->dbCardsPropertiesTable)
957
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
958
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
959
+            ->execute();
960
+
961
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
962
+        $result->closeCursor();
963
+
964
+        return $all;
965
+    }
966
+
967
+    /**
968
+     * get URI from a given contact
969
+     *
970
+     * @param int $id
971
+     * @return string
972
+     */
973
+    public function getCardUri($id) {
974
+        $query = $this->db->getQueryBuilder();
975
+        $query->select('uri')->from($this->dbCardsTable)
976
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
977
+                ->setParameter('id', $id);
978
+
979
+        $result = $query->execute();
980
+        $uri = $result->fetch();
981
+        $result->closeCursor();
982
+
983
+        if (!isset($uri['uri'])) {
984
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
985
+        }
986
+
987
+        return $uri['uri'];
988
+    }
989
+
990
+    /**
991
+     * return contact with the given URI
992
+     *
993
+     * @param int $addressBookId
994
+     * @param string $uri
995
+     * @returns array
996
+     */
997
+    public function getContact($addressBookId, $uri) {
998
+        $result = [];
999
+        $query = $this->db->getQueryBuilder();
1000
+        $query->select('*')->from($this->dbCardsTable)
1001
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1002
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1003
+        $queryResult = $query->execute();
1004
+        $contact = $queryResult->fetch();
1005
+        $queryResult->closeCursor();
1006
+
1007
+        if (is_array($contact)) {
1008
+            $result = $contact;
1009
+        }
1010
+
1011
+        return $result;
1012
+    }
1013
+
1014
+    /**
1015
+     * Returns the list of people whom this address book is shared with.
1016
+     *
1017
+     * Every element in this array should have the following properties:
1018
+     *   * href - Often a mailto: address
1019
+     *   * commonName - Optional, for example a first + last name
1020
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1021
+     *   * readOnly - boolean
1022
+     *   * summary - Optional, a description for the share
1023
+     *
1024
+     * @return array
1025
+     */
1026
+    public function getShares($addressBookId) {
1027
+        return $this->sharingBackend->getShares($addressBookId);
1028
+    }
1029
+
1030
+    /**
1031
+     * update properties table
1032
+     *
1033
+     * @param int $addressBookId
1034
+     * @param string $cardUri
1035
+     * @param string $vCardSerialized
1036
+     */
1037
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1038
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1039
+        $vCard = $this->readCard($vCardSerialized);
1040
+
1041
+        $this->purgeProperties($addressBookId, $cardId);
1042
+
1043
+        $query = $this->db->getQueryBuilder();
1044
+        $query->insert($this->dbCardsPropertiesTable)
1045
+            ->values(
1046
+                [
1047
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1048
+                    'cardid' => $query->createNamedParameter($cardId),
1049
+                    'name' => $query->createParameter('name'),
1050
+                    'value' => $query->createParameter('value'),
1051
+                    'preferred' => $query->createParameter('preferred')
1052
+                ]
1053
+            );
1054
+
1055
+        foreach ($vCard->children() as $property) {
1056
+            if(!in_array($property->name, self::$indexProperties)) {
1057
+                continue;
1058
+            }
1059
+            $preferred = 0;
1060
+            foreach($property->parameters as $parameter) {
1061
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1062
+                    $preferred = 1;
1063
+                    break;
1064
+                }
1065
+            }
1066
+            $query->setParameter('name', $property->name);
1067
+            $query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1068
+            $query->setParameter('preferred', $preferred);
1069
+            $query->execute();
1070
+        }
1071
+    }
1072
+
1073
+    /**
1074
+     * read vCard data into a vCard object
1075
+     *
1076
+     * @param string $cardData
1077
+     * @return VCard
1078
+     */
1079
+    protected function readCard($cardData) {
1080
+        return  Reader::read($cardData);
1081
+    }
1082
+
1083
+    /**
1084
+     * delete all properties from a given card
1085
+     *
1086
+     * @param int $addressBookId
1087
+     * @param int $cardId
1088
+     */
1089
+    protected function purgeProperties($addressBookId, $cardId) {
1090
+        $query = $this->db->getQueryBuilder();
1091
+        $query->delete($this->dbCardsPropertiesTable)
1092
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1093
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1094
+        $query->execute();
1095
+    }
1096
+
1097
+    /**
1098
+     * get ID from a given contact
1099
+     *
1100
+     * @param int $addressBookId
1101
+     * @param string $uri
1102
+     * @return int
1103
+     */
1104
+    protected function getCardId($addressBookId, $uri) {
1105
+        $query = $this->db->getQueryBuilder();
1106
+        $query->select('id')->from($this->dbCardsTable)
1107
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1108
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1109
+
1110
+        $result = $query->execute();
1111
+        $cardIds = $result->fetch();
1112
+        $result->closeCursor();
1113
+
1114
+        if (!isset($cardIds['id'])) {
1115
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1116
+        }
1117
+
1118
+        return (int)$cardIds['id'];
1119
+    }
1120
+
1121
+    /**
1122
+     * For shared address books the sharee is set in the ACL of the address book
1123
+     * @param $addressBookId
1124
+     * @param $acl
1125
+     * @return array
1126
+     */
1127
+    public function applyShareAcl($addressBookId, $acl) {
1128
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1129
+    }
1130
+
1131
+    private function convertPrincipal($principalUri, $toV2) {
1132
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1133
+            list(, $name) = \Sabre\Uri\split($principalUri);
1134
+            if ($toV2 === true) {
1135
+                return "principals/users/$name";
1136
+            }
1137
+            return "principals/$name";
1138
+        }
1139
+        return $principalUri;
1140
+    }
1141
+
1142
+    private function addOwnerPrincipal(&$addressbookInfo) {
1143
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1144
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1145
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1146
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1147
+        } else {
1148
+            $uri = $addressbookInfo['principaluri'];
1149
+        }
1150
+
1151
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1152
+        if (isset($principalInformation['{DAV:}displayname'])) {
1153
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1154
+        }
1155
+    }
1156
+
1157
+    /**
1158
+     * Extract UID from vcard
1159
+     *
1160
+     * @param string $cardData the vcard raw data
1161
+     * @return string the uid
1162
+     * @throws BadRequest if no UID is available
1163
+     */
1164
+    private function getUID($cardData) {
1165
+        if ($cardData != '') {
1166
+            $vCard = Reader::read($cardData);
1167
+            if ($vCard->UID) {
1168
+                $uid = $vCard->UID->getValue();
1169
+                return $uid;
1170
+            }
1171
+            // should already be handled, but just in case
1172
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1173
+        }
1174
+        // should already be handled, but just in case
1175
+        throw new BadRequest('vCard can not be empty');
1176
+    }
1177 1177
 }
Please login to merge, or discard this patch.