Passed
Push — master ( 03e345...83711e )
by Christoph
14:25 queued 15s
created
apps/dav/lib/Connector/Sabre/FilesPlugin.php 2 patches
Indentation   +543 added lines, -543 removed lines patch added patch discarded remove patch
@@ -57,547 +57,547 @@
 block discarded – undo
57 57
 
58 58
 class FilesPlugin extends ServerPlugin {
59 59
 
60
-	// namespace
61
-	public const NS_OWNCLOUD = 'http://owncloud.org/ns';
62
-	public const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
63
-	public const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
64
-	public const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
65
-	public const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
66
-	public const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
67
-	public const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
68
-	public const SHARE_ATTRIBUTES_PROPERTYNAME = '{http://nextcloud.org/ns}share-attributes';
69
-	public const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
70
-	public const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
71
-	public const GETETAG_PROPERTYNAME = '{DAV:}getetag';
72
-	public const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
73
-	public const CREATIONDATE_PROPERTYNAME = '{DAV:}creationdate';
74
-	public const DISPLAYNAME_PROPERTYNAME = '{DAV:}displayname';
75
-	public const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
76
-	public const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
77
-	public const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
78
-	public const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
79
-	public const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
80
-	public const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
81
-	public const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
82
-	public const METADATA_ETAG_PROPERTYNAME = '{http://nextcloud.org/ns}metadata_etag';
83
-	public const UPLOAD_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}upload_time';
84
-	public const CREATION_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}creation_time';
85
-	public const SHARE_NOTE = '{http://nextcloud.org/ns}note';
86
-	public const SUBFOLDER_COUNT_PROPERTYNAME = '{http://nextcloud.org/ns}contained-folder-count';
87
-	public const SUBFILE_COUNT_PROPERTYNAME = '{http://nextcloud.org/ns}contained-file-count';
88
-	public const FILE_METADATA_SIZE = '{http://nextcloud.org/ns}file-metadata-size';
89
-
90
-	/** Reference to main server object */
91
-	private ?Server $server = null;
92
-	private Tree $tree;
93
-	private IUserSession $userSession;
94
-
95
-	/**
96
-	 * Whether this is public webdav.
97
-	 * If true, some returned information will be stripped off.
98
-	 */
99
-	private bool $isPublic;
100
-	private bool $downloadAttachment;
101
-	private IConfig $config;
102
-	private IRequest $request;
103
-	private IPreview $previewManager;
104
-
105
-	public function __construct(Tree $tree,
106
-								IConfig $config,
107
-								IRequest $request,
108
-								IPreview $previewManager,
109
-								IUserSession $userSession,
110
-								bool $isPublic = false,
111
-								bool $downloadAttachment = true) {
112
-		$this->tree = $tree;
113
-		$this->config = $config;
114
-		$this->request = $request;
115
-		$this->userSession = $userSession;
116
-		$this->isPublic = $isPublic;
117
-		$this->downloadAttachment = $downloadAttachment;
118
-		$this->previewManager = $previewManager;
119
-	}
120
-
121
-	/**
122
-	 * This initializes the plugin.
123
-	 *
124
-	 * This function is called by \Sabre\DAV\Server, after
125
-	 * addPlugin is called.
126
-	 *
127
-	 * This method should set up the required event subscriptions.
128
-	 *
129
-	 * @return void
130
-	 */
131
-	public function initialize(Server $server) {
132
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
133
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
134
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
135
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
136
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
137
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
138
-		$server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
139
-		$server->protectedProperties[] = self::SHARE_ATTRIBUTES_PROPERTYNAME;
140
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
141
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
142
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
143
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
144
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
145
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
146
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
147
-		$server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
148
-		$server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
149
-		$server->protectedProperties[] = self::SHARE_NOTE;
150
-
151
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
152
-		$allowedProperties = ['{DAV:}getetag'];
153
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
154
-
155
-		$this->server = $server;
156
-		$this->server->on('propFind', [$this, 'handleGetProperties']);
157
-		$this->server->on('propPatch', [$this, 'handleUpdateProperties']);
158
-		$this->server->on('afterBind', [$this, 'sendFileIdHeader']);
159
-		$this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
160
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
161
-		$this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
162
-		$this->server->on('afterResponse', function ($request, ResponseInterface $response) {
163
-			$body = $response->getBody();
164
-			if (is_resource($body)) {
165
-				fclose($body);
166
-			}
167
-		});
168
-		$this->server->on('beforeMove', [$this, 'checkMove']);
169
-	}
170
-
171
-	/**
172
-	 * Plugin that checks if a move can actually be performed.
173
-	 *
174
-	 * @param string $source source path
175
-	 * @param string $destination destination path
176
-	 * @throws Forbidden
177
-	 * @throws NotFound
178
-	 */
179
-	public function checkMove($source, $destination) {
180
-		$sourceNode = $this->tree->getNodeForPath($source);
181
-		if (!$sourceNode instanceof Node) {
182
-			return;
183
-		}
184
-		[$sourceDir,] = \Sabre\Uri\split($source);
185
-		[$destinationDir,] = \Sabre\Uri\split($destination);
186
-
187
-		if ($sourceDir !== $destinationDir) {
188
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
189
-			if ($sourceNodeFileInfo === null) {
190
-				throw new NotFound($source . ' does not exist');
191
-			}
192
-
193
-			if (!$sourceNodeFileInfo->isDeletable()) {
194
-				throw new Forbidden($source . " cannot be deleted");
195
-			}
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * This sets a cookie to be able to recognize the start of the download
201
-	 * the content must not be longer than 32 characters and must only contain
202
-	 * alphanumeric characters
203
-	 *
204
-	 * @param RequestInterface $request
205
-	 * @param ResponseInterface $response
206
-	 */
207
-	public function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
208
-		$queryParams = $request->getQueryParameters();
209
-
210
-		/**
211
-		 * this sets a cookie to be able to recognize the start of the download
212
-		 * the content must not be longer than 32 characters and must only contain
213
-		 * alphanumeric characters
214
-		 */
215
-		if (isset($queryParams['downloadStartSecret'])) {
216
-			$token = $queryParams['downloadStartSecret'];
217
-			if (!isset($token[32])
218
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
219
-				// FIXME: use $response->setHeader() instead
220
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
221
-			}
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * Add headers to file download
227
-	 *
228
-	 * @param RequestInterface $request
229
-	 * @param ResponseInterface $response
230
-	 */
231
-	public function httpGet(RequestInterface $request, ResponseInterface $response) {
232
-		// Only handle valid files
233
-		$node = $this->tree->getNodeForPath($request->getPath());
234
-		if (!($node instanceof IFile)) {
235
-			return;
236
-		}
237
-
238
-		// adds a 'Content-Disposition: attachment' header in case no disposition
239
-		// header has been set before
240
-		if ($this->downloadAttachment &&
241
-			$response->getHeader('Content-Disposition') === null) {
242
-			$filename = $node->getName();
243
-			if ($this->request->isUserAgent(
244
-				[
245
-					Request::USER_AGENT_IE,
246
-					Request::USER_AGENT_ANDROID_MOBILE_CHROME,
247
-					Request::USER_AGENT_FREEBOX,
248
-				])) {
249
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
250
-			} else {
251
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
252
-													 . '; filename="' . rawurlencode($filename) . '"');
253
-			}
254
-		}
255
-
256
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
257
-			//Add OC-Checksum header
258
-			$checksum = $node->getChecksum();
259
-			if ($checksum !== null && $checksum !== '') {
260
-				$response->addHeader('OC-Checksum', $checksum);
261
-			}
262
-		}
263
-		$response->addHeader('X-Accel-Buffering', 'no');
264
-	}
265
-
266
-	/**
267
-	 * Adds all ownCloud-specific properties
268
-	 *
269
-	 * @param PropFind $propFind
270
-	 * @param \Sabre\DAV\INode $node
271
-	 * @return void
272
-	 */
273
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
274
-		$httpRequest = $this->server->httpRequest;
275
-
276
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
277
-			/**
278
-			 * This was disabled, because it made dir listing throw an exception,
279
-			 * so users were unable to navigate into folders where one subitem
280
-			 * is blocked by the files_accesscontrol app, see:
281
-			 * https://github.com/nextcloud/files_accesscontrol/issues/65
282
-			 * if (!$node->getFileInfo()->isReadable()) {
283
-			 *     // avoid detecting files through this means
284
-			 *     throw new NotFound();
285
-			 * }
286
-			 */
287
-
288
-			$propFind->handle(self::FILEID_PROPERTYNAME, function () use ($node) {
289
-				return $node->getFileId();
290
-			});
291
-
292
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function () use ($node) {
293
-				return $node->getInternalFileId();
294
-			});
295
-
296
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function () use ($node) {
297
-				$perms = $node->getDavPermissions();
298
-				if ($this->isPublic) {
299
-					// remove mount information
300
-					$perms = str_replace(['S', 'M'], '', $perms);
301
-				}
302
-				return $perms;
303
-			});
304
-
305
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest) {
306
-				$user = $this->userSession->getUser();
307
-				if ($user === null) {
308
-					return null;
309
-				}
310
-				return $node->getSharePermissions(
311
-					$user->getUID()
312
-				);
313
-			});
314
-
315
-			$propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest): ?string {
316
-				$user = $this->userSession->getUser();
317
-				if ($user === null) {
318
-					return null;
319
-				}
320
-				$ncPermissions = $node->getSharePermissions(
321
-					$user->getUID()
322
-				);
323
-				$ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
324
-				return json_encode($ocmPermissions, JSON_THROW_ON_ERROR);
325
-			});
326
-
327
-			$propFind->handle(self::SHARE_ATTRIBUTES_PROPERTYNAME, function () use ($node, $httpRequest) {
328
-				return json_encode($node->getShareAttributes(), JSON_THROW_ON_ERROR);
329
-			});
330
-
331
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function () use ($node): string {
332
-				return $node->getETag();
333
-			});
334
-
335
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function () use ($node): ?string {
336
-				$owner = $node->getOwner();
337
-				if (!$owner) {
338
-					return null;
339
-				} else {
340
-					return $owner->getUID();
341
-				}
342
-			});
343
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function () use ($node): ?string {
344
-				$owner = $node->getOwner();
345
-				if (!$owner) {
346
-					return null;
347
-				} else {
348
-					return $owner->getDisplayName();
349
-				}
350
-			});
351
-
352
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
353
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()), JSON_THROW_ON_ERROR);
354
-			});
355
-			$propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node): ?int {
356
-				return $node->getSize();
357
-			});
358
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
359
-				return $node->getFileInfo()->getMountPoint()->getMountType();
360
-			});
361
-
362
-			$propFind->handle(self::SHARE_NOTE, function () use ($node, $httpRequest): ?string {
363
-				$user = $this->userSession->getUser();
364
-				if ($user === null) {
365
-					return null;
366
-				}
367
-				return $node->getNoteFromShare(
368
-					$user->getUID()
369
-				);
370
-			});
371
-
372
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function () use ($node) {
373
-				return $this->config->getSystemValue('data-fingerprint', '');
374
-			});
375
-			$propFind->handle(self::CREATIONDATE_PROPERTYNAME, function () use ($node) {
376
-				return (new \DateTimeImmutable())
377
-					->setTimestamp($node->getFileInfo()->getCreationTime())
378
-					->format(\DateTimeInterface::ATOM);
379
-			});
380
-			$propFind->handle(self::CREATION_TIME_PROPERTYNAME, function () use ($node) {
381
-				return $node->getFileInfo()->getCreationTime();
382
-			});
383
-			/**
384
-			 * Return file/folder name as displayname. The primary reason to
385
-			 * implement it this way is to avoid costly fallback to 
386
-			 * CustomPropertiesBackend (esp. visible when querying all files
387
-			 * in a folder).
388
-			 */
389
-			$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
390
-				return $node->getName();
391
-			});
392
-		}
393
-
394
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
395
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function () use ($node) {
396
-				try {
397
-					$directDownloadUrl = $node->getDirectDownload();
398
-					if (isset($directDownloadUrl['url'])) {
399
-						return $directDownloadUrl['url'];
400
-					}
401
-				} catch (StorageNotAvailableException $e) {
402
-					return false;
403
-				} catch (ForbiddenException $e) {
404
-					return false;
405
-				}
406
-				return false;
407
-			});
408
-
409
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function () use ($node) {
410
-				$checksum = $node->getChecksum();
411
-				if ($checksum === null || $checksum === '') {
412
-					return null;
413
-				}
414
-
415
-				return new ChecksumList($checksum);
416
-			});
417
-
418
-			$propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function () use ($node) {
419
-				return $node->getFileInfo()->getUploadTime();
420
-			});
421
-
422
-			if ($this->config->getSystemValueBool('enable_file_metadata', true)) {
423
-				$propFind->handle(self::FILE_METADATA_SIZE, function () use ($node) {
424
-					if (!str_starts_with($node->getFileInfo()->getMimetype(), 'image')) {
425
-						return json_encode((object)[], JSON_THROW_ON_ERROR);
426
-					}
427
-
428
-					if ($node->hasMetadata('size')) {
429
-						$sizeMetadata = $node->getMetadata('size');
430
-					} else {
431
-						// This code path should not be called since we try to preload
432
-						// the metadata when loading the folder or the search results
433
-						// in one go
434
-						$metadataManager = \OC::$server->get(IMetadataManager::class);
435
-						$sizeMetadata = $metadataManager->fetchMetadataFor('size', [$node->getId()])[$node->getId()];
436
-
437
-						// TODO would be nice to display this in the profiler...
438
-						\OC::$server->get(LoggerInterface::class)->debug('Inefficient fetching of metadata');
439
-					}
440
-
441
-					return json_encode((object)$sizeMetadata->getMetadata(), JSON_THROW_ON_ERROR);
442
-				});
443
-			}
444
-		}
445
-
446
-		if ($node instanceof Directory) {
447
-			$propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node) {
448
-				return $node->getSize();
449
-			});
450
-
451
-			$propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function () use ($node) {
452
-				return $node->getFileInfo()->isEncrypted() ? '1' : '0';
453
-			});
454
-
455
-			$requestProperties = $propFind->getRequestedProperties();
456
-
457
-			// TODO detect dynamically which metadata groups are requested and
458
-			// preload all of them and not just size
459
-			if ($this->config->getSystemValueBool('enable_file_metadata', true)
460
-				&& in_array(self::FILE_METADATA_SIZE, $requestProperties, true)) {
461
-				// Preloading of the metadata
462
-				$fileIds = [];
463
-				foreach ($node->getChildren() as $child) {
464
-					/** @var \OCP\Files\Node|Node $child */
465
-					if (str_starts_with($child->getFileInfo()->getMimeType(), 'image/')) {
466
-						/** @var File $child */
467
-						$fileIds[] = $child->getFileInfo()->getId();
468
-					}
469
-				}
470
-				/** @var IMetaDataManager $metadataManager */
471
-				$metadataManager = \OC::$server->get(IMetadataManager::class);
472
-				$preloadedMetadata = $metadataManager->fetchMetadataFor('size', $fileIds);
473
-				foreach ($node->getChildren() as $child) {
474
-					/** @var \OCP\Files\Node|Node $child */
475
-					if (str_starts_with($child->getFileInfo()->getMimeType(), 'image')) {
476
-						/** @var File $child */
477
-						$child->setMetadata('size', $preloadedMetadata[$child->getFileInfo()->getId()]);
478
-					}
479
-				}
480
-			}
481
-
482
-			if (in_array(self::SUBFILE_COUNT_PROPERTYNAME, $requestProperties, true)
483
-				|| in_array(self::SUBFOLDER_COUNT_PROPERTYNAME, $requestProperties, true)) {
484
-				$nbFiles = 0;
485
-				$nbFolders = 0;
486
-				foreach ($node->getChildren() as $child) {
487
-					if ($child instanceof File) {
488
-						$nbFiles++;
489
-					} elseif ($child instanceof Directory) {
490
-						$nbFolders++;
491
-					}
492
-				}
493
-
494
-				$propFind->handle(self::SUBFILE_COUNT_PROPERTYNAME, $nbFiles);
495
-				$propFind->handle(self::SUBFOLDER_COUNT_PROPERTYNAME, $nbFolders);
496
-			}
497
-		}
498
-	}
499
-
500
-	/**
501
-	 * translate Nextcloud permissions to OCM Permissions
502
-	 *
503
-	 * @param $ncPermissions
504
-	 * @return array
505
-	 */
506
-	protected function ncPermissions2ocmPermissions($ncPermissions) {
507
-		$ocmPermissions = [];
508
-
509
-		if ($ncPermissions & Constants::PERMISSION_SHARE) {
510
-			$ocmPermissions[] = 'share';
511
-		}
512
-
513
-		if ($ncPermissions & Constants::PERMISSION_READ) {
514
-			$ocmPermissions[] = 'read';
515
-		}
516
-
517
-		if (($ncPermissions & Constants::PERMISSION_CREATE) ||
518
-			($ncPermissions & Constants::PERMISSION_UPDATE)) {
519
-			$ocmPermissions[] = 'write';
520
-		}
521
-
522
-		return $ocmPermissions;
523
-	}
524
-
525
-	/**
526
-	 * Update ownCloud-specific properties
527
-	 *
528
-	 * @param string $path
529
-	 * @param PropPatch $propPatch
530
-	 *
531
-	 * @return void
532
-	 */
533
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
534
-		$node = $this->tree->getNodeForPath($path);
535
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
536
-			return;
537
-		}
538
-
539
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function ($time) use ($node) {
540
-			if (empty($time)) {
541
-				return false;
542
-			}
543
-			$node->touch($time);
544
-			return true;
545
-		});
546
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function ($etag) use ($node) {
547
-			if (empty($etag)) {
548
-				return false;
549
-			}
550
-			return $node->setEtag($etag) !== -1;
551
-		});
552
-		$propPatch->handle(self::CREATIONDATE_PROPERTYNAME, function ($time) use ($node) {
553
-			if (empty($time)) {
554
-				return false;
555
-			}
556
-			$dateTime = new \DateTimeImmutable($time);
557
-			$node->setCreationTime($dateTime->getTimestamp());
558
-			return true;
559
-		});
560
-		$propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function ($time) use ($node) {
561
-			if (empty($time)) {
562
-				return false;
563
-			}
564
-			$node->setCreationTime((int) $time);
565
-			return true;
566
-		});
567
-		/**
568
-		 * Disable modification of the displayname property for files and
569
-		 * folders via PROPPATCH. See PROPFIND for more information.
570
-		 */
571
-		$propPatch->handle(self::DISPLAYNAME_PROPERTYNAME, function ($displayName) {
572
-			return 403;
573
-		});
574
-	}
575
-
576
-	/**
577
-	 * @param string $filePath
578
-	 * @param \Sabre\DAV\INode $node
579
-	 * @throws \Sabre\DAV\Exception\BadRequest
580
-	 */
581
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
582
-		// chunked upload handling
583
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
584
-			[$path, $name] = \Sabre\Uri\split($filePath);
585
-			$info = \OC_FileChunking::decodeName($name);
586
-			if (!empty($info)) {
587
-				$filePath = $path . '/' . $info['name'];
588
-			}
589
-		}
590
-
591
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
592
-		if (!$this->server->tree->nodeExists($filePath)) {
593
-			return;
594
-		}
595
-		$node = $this->server->tree->getNodeForPath($filePath);
596
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
597
-			$fileId = $node->getFileId();
598
-			if (!is_null($fileId)) {
599
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
600
-			}
601
-		}
602
-	}
60
+    // namespace
61
+    public const NS_OWNCLOUD = 'http://owncloud.org/ns';
62
+    public const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
63
+    public const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
64
+    public const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
65
+    public const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
66
+    public const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
67
+    public const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
68
+    public const SHARE_ATTRIBUTES_PROPERTYNAME = '{http://nextcloud.org/ns}share-attributes';
69
+    public const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
70
+    public const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
71
+    public const GETETAG_PROPERTYNAME = '{DAV:}getetag';
72
+    public const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
73
+    public const CREATIONDATE_PROPERTYNAME = '{DAV:}creationdate';
74
+    public const DISPLAYNAME_PROPERTYNAME = '{DAV:}displayname';
75
+    public const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
76
+    public const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
77
+    public const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
78
+    public const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
79
+    public const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
80
+    public const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
81
+    public const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
82
+    public const METADATA_ETAG_PROPERTYNAME = '{http://nextcloud.org/ns}metadata_etag';
83
+    public const UPLOAD_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}upload_time';
84
+    public const CREATION_TIME_PROPERTYNAME = '{http://nextcloud.org/ns}creation_time';
85
+    public const SHARE_NOTE = '{http://nextcloud.org/ns}note';
86
+    public const SUBFOLDER_COUNT_PROPERTYNAME = '{http://nextcloud.org/ns}contained-folder-count';
87
+    public const SUBFILE_COUNT_PROPERTYNAME = '{http://nextcloud.org/ns}contained-file-count';
88
+    public const FILE_METADATA_SIZE = '{http://nextcloud.org/ns}file-metadata-size';
89
+
90
+    /** Reference to main server object */
91
+    private ?Server $server = null;
92
+    private Tree $tree;
93
+    private IUserSession $userSession;
94
+
95
+    /**
96
+     * Whether this is public webdav.
97
+     * If true, some returned information will be stripped off.
98
+     */
99
+    private bool $isPublic;
100
+    private bool $downloadAttachment;
101
+    private IConfig $config;
102
+    private IRequest $request;
103
+    private IPreview $previewManager;
104
+
105
+    public function __construct(Tree $tree,
106
+                                IConfig $config,
107
+                                IRequest $request,
108
+                                IPreview $previewManager,
109
+                                IUserSession $userSession,
110
+                                bool $isPublic = false,
111
+                                bool $downloadAttachment = true) {
112
+        $this->tree = $tree;
113
+        $this->config = $config;
114
+        $this->request = $request;
115
+        $this->userSession = $userSession;
116
+        $this->isPublic = $isPublic;
117
+        $this->downloadAttachment = $downloadAttachment;
118
+        $this->previewManager = $previewManager;
119
+    }
120
+
121
+    /**
122
+     * This initializes the plugin.
123
+     *
124
+     * This function is called by \Sabre\DAV\Server, after
125
+     * addPlugin is called.
126
+     *
127
+     * This method should set up the required event subscriptions.
128
+     *
129
+     * @return void
130
+     */
131
+    public function initialize(Server $server) {
132
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
133
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
134
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
135
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
136
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
137
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
138
+        $server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
139
+        $server->protectedProperties[] = self::SHARE_ATTRIBUTES_PROPERTYNAME;
140
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
141
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
142
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
143
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
144
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
145
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
146
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
147
+        $server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
148
+        $server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
149
+        $server->protectedProperties[] = self::SHARE_NOTE;
150
+
151
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
152
+        $allowedProperties = ['{DAV:}getetag'];
153
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
154
+
155
+        $this->server = $server;
156
+        $this->server->on('propFind', [$this, 'handleGetProperties']);
157
+        $this->server->on('propPatch', [$this, 'handleUpdateProperties']);
158
+        $this->server->on('afterBind', [$this, 'sendFileIdHeader']);
159
+        $this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
160
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
161
+        $this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
162
+        $this->server->on('afterResponse', function ($request, ResponseInterface $response) {
163
+            $body = $response->getBody();
164
+            if (is_resource($body)) {
165
+                fclose($body);
166
+            }
167
+        });
168
+        $this->server->on('beforeMove', [$this, 'checkMove']);
169
+    }
170
+
171
+    /**
172
+     * Plugin that checks if a move can actually be performed.
173
+     *
174
+     * @param string $source source path
175
+     * @param string $destination destination path
176
+     * @throws Forbidden
177
+     * @throws NotFound
178
+     */
179
+    public function checkMove($source, $destination) {
180
+        $sourceNode = $this->tree->getNodeForPath($source);
181
+        if (!$sourceNode instanceof Node) {
182
+            return;
183
+        }
184
+        [$sourceDir,] = \Sabre\Uri\split($source);
185
+        [$destinationDir,] = \Sabre\Uri\split($destination);
186
+
187
+        if ($sourceDir !== $destinationDir) {
188
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
189
+            if ($sourceNodeFileInfo === null) {
190
+                throw new NotFound($source . ' does not exist');
191
+            }
192
+
193
+            if (!$sourceNodeFileInfo->isDeletable()) {
194
+                throw new Forbidden($source . " cannot be deleted");
195
+            }
196
+        }
197
+    }
198
+
199
+    /**
200
+     * This sets a cookie to be able to recognize the start of the download
201
+     * the content must not be longer than 32 characters and must only contain
202
+     * alphanumeric characters
203
+     *
204
+     * @param RequestInterface $request
205
+     * @param ResponseInterface $response
206
+     */
207
+    public function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
208
+        $queryParams = $request->getQueryParameters();
209
+
210
+        /**
211
+         * this sets a cookie to be able to recognize the start of the download
212
+         * the content must not be longer than 32 characters and must only contain
213
+         * alphanumeric characters
214
+         */
215
+        if (isset($queryParams['downloadStartSecret'])) {
216
+            $token = $queryParams['downloadStartSecret'];
217
+            if (!isset($token[32])
218
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
219
+                // FIXME: use $response->setHeader() instead
220
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
221
+            }
222
+        }
223
+    }
224
+
225
+    /**
226
+     * Add headers to file download
227
+     *
228
+     * @param RequestInterface $request
229
+     * @param ResponseInterface $response
230
+     */
231
+    public function httpGet(RequestInterface $request, ResponseInterface $response) {
232
+        // Only handle valid files
233
+        $node = $this->tree->getNodeForPath($request->getPath());
234
+        if (!($node instanceof IFile)) {
235
+            return;
236
+        }
237
+
238
+        // adds a 'Content-Disposition: attachment' header in case no disposition
239
+        // header has been set before
240
+        if ($this->downloadAttachment &&
241
+            $response->getHeader('Content-Disposition') === null) {
242
+            $filename = $node->getName();
243
+            if ($this->request->isUserAgent(
244
+                [
245
+                    Request::USER_AGENT_IE,
246
+                    Request::USER_AGENT_ANDROID_MOBILE_CHROME,
247
+                    Request::USER_AGENT_FREEBOX,
248
+                ])) {
249
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
250
+            } else {
251
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
252
+                                                        . '; filename="' . rawurlencode($filename) . '"');
253
+            }
254
+        }
255
+
256
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
257
+            //Add OC-Checksum header
258
+            $checksum = $node->getChecksum();
259
+            if ($checksum !== null && $checksum !== '') {
260
+                $response->addHeader('OC-Checksum', $checksum);
261
+            }
262
+        }
263
+        $response->addHeader('X-Accel-Buffering', 'no');
264
+    }
265
+
266
+    /**
267
+     * Adds all ownCloud-specific properties
268
+     *
269
+     * @param PropFind $propFind
270
+     * @param \Sabre\DAV\INode $node
271
+     * @return void
272
+     */
273
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
274
+        $httpRequest = $this->server->httpRequest;
275
+
276
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
277
+            /**
278
+             * This was disabled, because it made dir listing throw an exception,
279
+             * so users were unable to navigate into folders where one subitem
280
+             * is blocked by the files_accesscontrol app, see:
281
+             * https://github.com/nextcloud/files_accesscontrol/issues/65
282
+             * if (!$node->getFileInfo()->isReadable()) {
283
+             *     // avoid detecting files through this means
284
+             *     throw new NotFound();
285
+             * }
286
+             */
287
+
288
+            $propFind->handle(self::FILEID_PROPERTYNAME, function () use ($node) {
289
+                return $node->getFileId();
290
+            });
291
+
292
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function () use ($node) {
293
+                return $node->getInternalFileId();
294
+            });
295
+
296
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function () use ($node) {
297
+                $perms = $node->getDavPermissions();
298
+                if ($this->isPublic) {
299
+                    // remove mount information
300
+                    $perms = str_replace(['S', 'M'], '', $perms);
301
+                }
302
+                return $perms;
303
+            });
304
+
305
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest) {
306
+                $user = $this->userSession->getUser();
307
+                if ($user === null) {
308
+                    return null;
309
+                }
310
+                return $node->getSharePermissions(
311
+                    $user->getUID()
312
+                );
313
+            });
314
+
315
+            $propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest): ?string {
316
+                $user = $this->userSession->getUser();
317
+                if ($user === null) {
318
+                    return null;
319
+                }
320
+                $ncPermissions = $node->getSharePermissions(
321
+                    $user->getUID()
322
+                );
323
+                $ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
324
+                return json_encode($ocmPermissions, JSON_THROW_ON_ERROR);
325
+            });
326
+
327
+            $propFind->handle(self::SHARE_ATTRIBUTES_PROPERTYNAME, function () use ($node, $httpRequest) {
328
+                return json_encode($node->getShareAttributes(), JSON_THROW_ON_ERROR);
329
+            });
330
+
331
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function () use ($node): string {
332
+                return $node->getETag();
333
+            });
334
+
335
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function () use ($node): ?string {
336
+                $owner = $node->getOwner();
337
+                if (!$owner) {
338
+                    return null;
339
+                } else {
340
+                    return $owner->getUID();
341
+                }
342
+            });
343
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function () use ($node): ?string {
344
+                $owner = $node->getOwner();
345
+                if (!$owner) {
346
+                    return null;
347
+                } else {
348
+                    return $owner->getDisplayName();
349
+                }
350
+            });
351
+
352
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
353
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()), JSON_THROW_ON_ERROR);
354
+            });
355
+            $propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node): ?int {
356
+                return $node->getSize();
357
+            });
358
+            $propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
359
+                return $node->getFileInfo()->getMountPoint()->getMountType();
360
+            });
361
+
362
+            $propFind->handle(self::SHARE_NOTE, function () use ($node, $httpRequest): ?string {
363
+                $user = $this->userSession->getUser();
364
+                if ($user === null) {
365
+                    return null;
366
+                }
367
+                return $node->getNoteFromShare(
368
+                    $user->getUID()
369
+                );
370
+            });
371
+
372
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function () use ($node) {
373
+                return $this->config->getSystemValue('data-fingerprint', '');
374
+            });
375
+            $propFind->handle(self::CREATIONDATE_PROPERTYNAME, function () use ($node) {
376
+                return (new \DateTimeImmutable())
377
+                    ->setTimestamp($node->getFileInfo()->getCreationTime())
378
+                    ->format(\DateTimeInterface::ATOM);
379
+            });
380
+            $propFind->handle(self::CREATION_TIME_PROPERTYNAME, function () use ($node) {
381
+                return $node->getFileInfo()->getCreationTime();
382
+            });
383
+            /**
384
+             * Return file/folder name as displayname. The primary reason to
385
+             * implement it this way is to avoid costly fallback to 
386
+             * CustomPropertiesBackend (esp. visible when querying all files
387
+             * in a folder).
388
+             */
389
+            $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
390
+                return $node->getName();
391
+            });
392
+        }
393
+
394
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
395
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function () use ($node) {
396
+                try {
397
+                    $directDownloadUrl = $node->getDirectDownload();
398
+                    if (isset($directDownloadUrl['url'])) {
399
+                        return $directDownloadUrl['url'];
400
+                    }
401
+                } catch (StorageNotAvailableException $e) {
402
+                    return false;
403
+                } catch (ForbiddenException $e) {
404
+                    return false;
405
+                }
406
+                return false;
407
+            });
408
+
409
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function () use ($node) {
410
+                $checksum = $node->getChecksum();
411
+                if ($checksum === null || $checksum === '') {
412
+                    return null;
413
+                }
414
+
415
+                return new ChecksumList($checksum);
416
+            });
417
+
418
+            $propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function () use ($node) {
419
+                return $node->getFileInfo()->getUploadTime();
420
+            });
421
+
422
+            if ($this->config->getSystemValueBool('enable_file_metadata', true)) {
423
+                $propFind->handle(self::FILE_METADATA_SIZE, function () use ($node) {
424
+                    if (!str_starts_with($node->getFileInfo()->getMimetype(), 'image')) {
425
+                        return json_encode((object)[], JSON_THROW_ON_ERROR);
426
+                    }
427
+
428
+                    if ($node->hasMetadata('size')) {
429
+                        $sizeMetadata = $node->getMetadata('size');
430
+                    } else {
431
+                        // This code path should not be called since we try to preload
432
+                        // the metadata when loading the folder or the search results
433
+                        // in one go
434
+                        $metadataManager = \OC::$server->get(IMetadataManager::class);
435
+                        $sizeMetadata = $metadataManager->fetchMetadataFor('size', [$node->getId()])[$node->getId()];
436
+
437
+                        // TODO would be nice to display this in the profiler...
438
+                        \OC::$server->get(LoggerInterface::class)->debug('Inefficient fetching of metadata');
439
+                    }
440
+
441
+                    return json_encode((object)$sizeMetadata->getMetadata(), JSON_THROW_ON_ERROR);
442
+                });
443
+            }
444
+        }
445
+
446
+        if ($node instanceof Directory) {
447
+            $propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node) {
448
+                return $node->getSize();
449
+            });
450
+
451
+            $propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function () use ($node) {
452
+                return $node->getFileInfo()->isEncrypted() ? '1' : '0';
453
+            });
454
+
455
+            $requestProperties = $propFind->getRequestedProperties();
456
+
457
+            // TODO detect dynamically which metadata groups are requested and
458
+            // preload all of them and not just size
459
+            if ($this->config->getSystemValueBool('enable_file_metadata', true)
460
+                && in_array(self::FILE_METADATA_SIZE, $requestProperties, true)) {
461
+                // Preloading of the metadata
462
+                $fileIds = [];
463
+                foreach ($node->getChildren() as $child) {
464
+                    /** @var \OCP\Files\Node|Node $child */
465
+                    if (str_starts_with($child->getFileInfo()->getMimeType(), 'image/')) {
466
+                        /** @var File $child */
467
+                        $fileIds[] = $child->getFileInfo()->getId();
468
+                    }
469
+                }
470
+                /** @var IMetaDataManager $metadataManager */
471
+                $metadataManager = \OC::$server->get(IMetadataManager::class);
472
+                $preloadedMetadata = $metadataManager->fetchMetadataFor('size', $fileIds);
473
+                foreach ($node->getChildren() as $child) {
474
+                    /** @var \OCP\Files\Node|Node $child */
475
+                    if (str_starts_with($child->getFileInfo()->getMimeType(), 'image')) {
476
+                        /** @var File $child */
477
+                        $child->setMetadata('size', $preloadedMetadata[$child->getFileInfo()->getId()]);
478
+                    }
479
+                }
480
+            }
481
+
482
+            if (in_array(self::SUBFILE_COUNT_PROPERTYNAME, $requestProperties, true)
483
+                || in_array(self::SUBFOLDER_COUNT_PROPERTYNAME, $requestProperties, true)) {
484
+                $nbFiles = 0;
485
+                $nbFolders = 0;
486
+                foreach ($node->getChildren() as $child) {
487
+                    if ($child instanceof File) {
488
+                        $nbFiles++;
489
+                    } elseif ($child instanceof Directory) {
490
+                        $nbFolders++;
491
+                    }
492
+                }
493
+
494
+                $propFind->handle(self::SUBFILE_COUNT_PROPERTYNAME, $nbFiles);
495
+                $propFind->handle(self::SUBFOLDER_COUNT_PROPERTYNAME, $nbFolders);
496
+            }
497
+        }
498
+    }
499
+
500
+    /**
501
+     * translate Nextcloud permissions to OCM Permissions
502
+     *
503
+     * @param $ncPermissions
504
+     * @return array
505
+     */
506
+    protected function ncPermissions2ocmPermissions($ncPermissions) {
507
+        $ocmPermissions = [];
508
+
509
+        if ($ncPermissions & Constants::PERMISSION_SHARE) {
510
+            $ocmPermissions[] = 'share';
511
+        }
512
+
513
+        if ($ncPermissions & Constants::PERMISSION_READ) {
514
+            $ocmPermissions[] = 'read';
515
+        }
516
+
517
+        if (($ncPermissions & Constants::PERMISSION_CREATE) ||
518
+            ($ncPermissions & Constants::PERMISSION_UPDATE)) {
519
+            $ocmPermissions[] = 'write';
520
+        }
521
+
522
+        return $ocmPermissions;
523
+    }
524
+
525
+    /**
526
+     * Update ownCloud-specific properties
527
+     *
528
+     * @param string $path
529
+     * @param PropPatch $propPatch
530
+     *
531
+     * @return void
532
+     */
533
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
534
+        $node = $this->tree->getNodeForPath($path);
535
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
536
+            return;
537
+        }
538
+
539
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function ($time) use ($node) {
540
+            if (empty($time)) {
541
+                return false;
542
+            }
543
+            $node->touch($time);
544
+            return true;
545
+        });
546
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function ($etag) use ($node) {
547
+            if (empty($etag)) {
548
+                return false;
549
+            }
550
+            return $node->setEtag($etag) !== -1;
551
+        });
552
+        $propPatch->handle(self::CREATIONDATE_PROPERTYNAME, function ($time) use ($node) {
553
+            if (empty($time)) {
554
+                return false;
555
+            }
556
+            $dateTime = new \DateTimeImmutable($time);
557
+            $node->setCreationTime($dateTime->getTimestamp());
558
+            return true;
559
+        });
560
+        $propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function ($time) use ($node) {
561
+            if (empty($time)) {
562
+                return false;
563
+            }
564
+            $node->setCreationTime((int) $time);
565
+            return true;
566
+        });
567
+        /**
568
+         * Disable modification of the displayname property for files and
569
+         * folders via PROPPATCH. See PROPFIND for more information.
570
+         */
571
+        $propPatch->handle(self::DISPLAYNAME_PROPERTYNAME, function ($displayName) {
572
+            return 403;
573
+        });
574
+    }
575
+
576
+    /**
577
+     * @param string $filePath
578
+     * @param \Sabre\DAV\INode $node
579
+     * @throws \Sabre\DAV\Exception\BadRequest
580
+     */
581
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
582
+        // chunked upload handling
583
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
584
+            [$path, $name] = \Sabre\Uri\split($filePath);
585
+            $info = \OC_FileChunking::decodeName($name);
586
+            if (!empty($info)) {
587
+                $filePath = $path . '/' . $info['name'];
588
+            }
589
+        }
590
+
591
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
592
+        if (!$this->server->tree->nodeExists($filePath)) {
593
+            return;
594
+        }
595
+        $node = $this->server->tree->getNodeForPath($filePath);
596
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
597
+            $fileId = $node->getFileId();
598
+            if (!is_null($fileId)) {
599
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
600
+            }
601
+        }
602
+    }
603 603
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
 		$this->server->on('propPatch', [$this, 'handleUpdateProperties']);
158 158
 		$this->server->on('afterBind', [$this, 'sendFileIdHeader']);
159 159
 		$this->server->on('afterWriteContent', [$this, 'sendFileIdHeader']);
160
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
160
+		$this->server->on('afterMethod:GET', [$this, 'httpGet']);
161 161
 		$this->server->on('afterMethod:GET', [$this, 'handleDownloadToken']);
162
-		$this->server->on('afterResponse', function ($request, ResponseInterface $response) {
162
+		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
163 163
 			$body = $response->getBody();
164 164
 			if (is_resource($body)) {
165 165
 				fclose($body);
@@ -181,17 +181,17 @@  discard block
 block discarded – undo
181 181
 		if (!$sourceNode instanceof Node) {
182 182
 			return;
183 183
 		}
184
-		[$sourceDir,] = \Sabre\Uri\split($source);
185
-		[$destinationDir,] = \Sabre\Uri\split($destination);
184
+		[$sourceDir, ] = \Sabre\Uri\split($source);
185
+		[$destinationDir, ] = \Sabre\Uri\split($destination);
186 186
 
187 187
 		if ($sourceDir !== $destinationDir) {
188 188
 			$sourceNodeFileInfo = $sourceNode->getFileInfo();
189 189
 			if ($sourceNodeFileInfo === null) {
190
-				throw new NotFound($source . ' does not exist');
190
+				throw new NotFound($source.' does not exist');
191 191
 			}
192 192
 
193 193
 			if (!$sourceNodeFileInfo->isDeletable()) {
194
-				throw new Forbidden($source . " cannot be deleted");
194
+				throw new Forbidden($source." cannot be deleted");
195 195
 			}
196 196
 		}
197 197
 	}
@@ -246,10 +246,10 @@  discard block
 block discarded – undo
246 246
 					Request::USER_AGENT_ANDROID_MOBILE_CHROME,
247 247
 					Request::USER_AGENT_FREEBOX,
248 248
 				])) {
249
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
249
+				$response->addHeader('Content-Disposition', 'attachment; filename="'.rawurlencode($filename).'"');
250 250
 			} else {
251
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
252
-													 . '; filename="' . rawurlencode($filename) . '"');
251
+				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($filename)
252
+													 . '; filename="'.rawurlencode($filename).'"');
253 253
 			}
254 254
 		}
255 255
 
@@ -285,15 +285,15 @@  discard block
 block discarded – undo
285 285
 			 * }
286 286
 			 */
287 287
 
288
-			$propFind->handle(self::FILEID_PROPERTYNAME, function () use ($node) {
288
+			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
289 289
 				return $node->getFileId();
290 290
 			});
291 291
 
292
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function () use ($node) {
292
+			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
293 293
 				return $node->getInternalFileId();
294 294
 			});
295 295
 
296
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function () use ($node) {
296
+			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
297 297
 				$perms = $node->getDavPermissions();
298 298
 				if ($this->isPublic) {
299 299
 					// remove mount information
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 				return $perms;
303 303
 			});
304 304
 
305
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest) {
305
+			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
306 306
 				$user = $this->userSession->getUser();
307 307
 				if ($user === null) {
308 308
 					return null;
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 				);
313 313
 			});
314 314
 
315
-			$propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest): ?string {
315
+			$propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest): ?string {
316 316
 				$user = $this->userSession->getUser();
317 317
 				if ($user === null) {
318 318
 					return null;
@@ -324,15 +324,15 @@  discard block
 block discarded – undo
324 324
 				return json_encode($ocmPermissions, JSON_THROW_ON_ERROR);
325 325
 			});
326 326
 
327
-			$propFind->handle(self::SHARE_ATTRIBUTES_PROPERTYNAME, function () use ($node, $httpRequest) {
327
+			$propFind->handle(self::SHARE_ATTRIBUTES_PROPERTYNAME, function() use ($node, $httpRequest) {
328 328
 				return json_encode($node->getShareAttributes(), JSON_THROW_ON_ERROR);
329 329
 			});
330 330
 
331
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function () use ($node): string {
331
+			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node): string {
332 332
 				return $node->getETag();
333 333
 			});
334 334
 
335
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function () use ($node): ?string {
335
+			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node): ?string {
336 336
 				$owner = $node->getOwner();
337 337
 				if (!$owner) {
338 338
 					return null;
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 					return $owner->getUID();
341 341
 				}
342 342
 			});
343
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function () use ($node): ?string {
343
+			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node): ?string {
344 344
 				$owner = $node->getOwner();
345 345
 				if (!$owner) {
346 346
 					return null;
@@ -349,17 +349,17 @@  discard block
 block discarded – undo
349 349
 				}
350 350
 			});
351 351
 
352
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
352
+			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function() use ($node) {
353 353
 				return json_encode($this->previewManager->isAvailable($node->getFileInfo()), JSON_THROW_ON_ERROR);
354 354
 			});
355
-			$propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node): ?int {
355
+			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node): ?int {
356 356
 				return $node->getSize();
357 357
 			});
358
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
358
+			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function() use ($node) {
359 359
 				return $node->getFileInfo()->getMountPoint()->getMountType();
360 360
 			});
361 361
 
362
-			$propFind->handle(self::SHARE_NOTE, function () use ($node, $httpRequest): ?string {
362
+			$propFind->handle(self::SHARE_NOTE, function() use ($node, $httpRequest): ?string {
363 363
 				$user = $this->userSession->getUser();
364 364
 				if ($user === null) {
365 365
 					return null;
@@ -369,15 +369,15 @@  discard block
 block discarded – undo
369 369
 				);
370 370
 			});
371 371
 
372
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function () use ($node) {
372
+			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
373 373
 				return $this->config->getSystemValue('data-fingerprint', '');
374 374
 			});
375
-			$propFind->handle(self::CREATIONDATE_PROPERTYNAME, function () use ($node) {
375
+			$propFind->handle(self::CREATIONDATE_PROPERTYNAME, function() use ($node) {
376 376
 				return (new \DateTimeImmutable())
377 377
 					->setTimestamp($node->getFileInfo()->getCreationTime())
378 378
 					->format(\DateTimeInterface::ATOM);
379 379
 			});
380
-			$propFind->handle(self::CREATION_TIME_PROPERTYNAME, function () use ($node) {
380
+			$propFind->handle(self::CREATION_TIME_PROPERTYNAME, function() use ($node) {
381 381
 				return $node->getFileInfo()->getCreationTime();
382 382
 			});
383 383
 			/**
@@ -386,13 +386,13 @@  discard block
 block discarded – undo
386 386
 			 * CustomPropertiesBackend (esp. visible when querying all files
387 387
 			 * in a folder).
388 388
 			 */
389
-			$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
389
+			$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function() use ($node) {
390 390
 				return $node->getName();
391 391
 			});
392 392
 		}
393 393
 
394 394
 		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
395
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function () use ($node) {
395
+			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
396 396
 				try {
397 397
 					$directDownloadUrl = $node->getDirectDownload();
398 398
 					if (isset($directDownloadUrl['url'])) {
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 				return false;
407 407
 			});
408 408
 
409
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function () use ($node) {
409
+			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
410 410
 				$checksum = $node->getChecksum();
411 411
 				if ($checksum === null || $checksum === '') {
412 412
 					return null;
@@ -415,14 +415,14 @@  discard block
 block discarded – undo
415 415
 				return new ChecksumList($checksum);
416 416
 			});
417 417
 
418
-			$propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function () use ($node) {
418
+			$propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function() use ($node) {
419 419
 				return $node->getFileInfo()->getUploadTime();
420 420
 			});
421 421
 
422 422
 			if ($this->config->getSystemValueBool('enable_file_metadata', true)) {
423
-				$propFind->handle(self::FILE_METADATA_SIZE, function () use ($node) {
423
+				$propFind->handle(self::FILE_METADATA_SIZE, function() use ($node) {
424 424
 					if (!str_starts_with($node->getFileInfo()->getMimetype(), 'image')) {
425
-						return json_encode((object)[], JSON_THROW_ON_ERROR);
425
+						return json_encode((object) [], JSON_THROW_ON_ERROR);
426 426
 					}
427 427
 
428 428
 					if ($node->hasMetadata('size')) {
@@ -438,17 +438,17 @@  discard block
 block discarded – undo
438 438
 						\OC::$server->get(LoggerInterface::class)->debug('Inefficient fetching of metadata');
439 439
 					}
440 440
 
441
-					return json_encode((object)$sizeMetadata->getMetadata(), JSON_THROW_ON_ERROR);
441
+					return json_encode((object) $sizeMetadata->getMetadata(), JSON_THROW_ON_ERROR);
442 442
 				});
443 443
 			}
444 444
 		}
445 445
 
446 446
 		if ($node instanceof Directory) {
447
-			$propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node) {
447
+			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
448 448
 				return $node->getSize();
449 449
 			});
450 450
 
451
-			$propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function () use ($node) {
451
+			$propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function() use ($node) {
452 452
 				return $node->getFileInfo()->isEncrypted() ? '1' : '0';
453 453
 			});
454 454
 
@@ -536,20 +536,20 @@  discard block
 block discarded – undo
536 536
 			return;
537 537
 		}
538 538
 
539
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function ($time) use ($node) {
539
+		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
540 540
 			if (empty($time)) {
541 541
 				return false;
542 542
 			}
543 543
 			$node->touch($time);
544 544
 			return true;
545 545
 		});
546
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function ($etag) use ($node) {
546
+		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
547 547
 			if (empty($etag)) {
548 548
 				return false;
549 549
 			}
550 550
 			return $node->setEtag($etag) !== -1;
551 551
 		});
552
-		$propPatch->handle(self::CREATIONDATE_PROPERTYNAME, function ($time) use ($node) {
552
+		$propPatch->handle(self::CREATIONDATE_PROPERTYNAME, function($time) use ($node) {
553 553
 			if (empty($time)) {
554 554
 				return false;
555 555
 			}
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 			$node->setCreationTime($dateTime->getTimestamp());
558 558
 			return true;
559 559
 		});
560
-		$propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function ($time) use ($node) {
560
+		$propPatch->handle(self::CREATION_TIME_PROPERTYNAME, function($time) use ($node) {
561 561
 			if (empty($time)) {
562 562
 				return false;
563 563
 			}
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 		 * Disable modification of the displayname property for files and
569 569
 		 * folders via PROPPATCH. See PROPFIND for more information.
570 570
 		 */
571
-		$propPatch->handle(self::DISPLAYNAME_PROPERTYNAME, function ($displayName) {
571
+		$propPatch->handle(self::DISPLAYNAME_PROPERTYNAME, function($displayName) {
572 572
 			return 403;
573 573
 		});
574 574
 	}
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 			[$path, $name] = \Sabre\Uri\split($filePath);
585 585
 			$info = \OC_FileChunking::decodeName($name);
586 586
 			if (!empty($info)) {
587
-				$filePath = $path . '/' . $info['name'];
587
+				$filePath = $path.'/'.$info['name'];
588 588
 			}
589 589
 		}
590 590
 
Please login to merge, or discard this patch.
apps/dav/lib/Comments/CommentsPlugin.php 1 patch
Indentation   +206 added lines, -206 removed lines patch added patch discarded remove patch
@@ -44,210 +44,210 @@
 block discarded – undo
44 44
  * Sabre plugin to handle comments:
45 45
  */
46 46
 class CommentsPlugin extends ServerPlugin {
47
-	// namespace
48
-	public const NS_OWNCLOUD = 'http://owncloud.org/ns';
49
-
50
-	public const REPORT_NAME = '{http://owncloud.org/ns}filter-comments';
51
-	public const REPORT_PARAM_LIMIT = '{http://owncloud.org/ns}limit';
52
-	public const REPORT_PARAM_OFFSET = '{http://owncloud.org/ns}offset';
53
-	public const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
54
-
55
-	/** @var ICommentsManager  */
56
-	protected $commentsManager;
57
-
58
-	/** @var \Sabre\DAV\Server $server */
59
-	private $server;
60
-
61
-	/** @var  \OCP\IUserSession */
62
-	protected $userSession;
63
-
64
-	/**
65
-	 * Comments plugin
66
-	 *
67
-	 * @param ICommentsManager $commentsManager
68
-	 * @param IUserSession $userSession
69
-	 */
70
-	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
71
-		$this->commentsManager = $commentsManager;
72
-		$this->userSession = $userSession;
73
-	}
74
-
75
-	/**
76
-	 * This initializes the plugin.
77
-	 *
78
-	 * This function is called by Sabre\DAV\Server, after
79
-	 * addPlugin is called.
80
-	 *
81
-	 * This method should set up the required event subscriptions.
82
-	 *
83
-	 * @param Server $server
84
-	 * @return void
85
-	 */
86
-	public function initialize(Server $server) {
87
-		$this->server = $server;
88
-		if (strpos($this->server->getRequestUri(), 'comments/') !== 0) {
89
-			return;
90
-		}
91
-
92
-		$this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
93
-
94
-		$this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
95
-			$writer->write(\Sabre\HTTP\toDate($value));
96
-		};
97
-
98
-		$this->server->on('report', [$this, 'onReport']);
99
-		$this->server->on('method:POST', [$this, 'httpPost']);
100
-	}
101
-
102
-	/**
103
-	 * POST operation on Comments collections
104
-	 *
105
-	 * @param RequestInterface $request request object
106
-	 * @param ResponseInterface $response response object
107
-	 * @return null|false
108
-	 */
109
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
110
-		$path = $request->getPath();
111
-		$node = $this->server->tree->getNodeForPath($path);
112
-		if (!$node instanceof EntityCollection) {
113
-			return null;
114
-		}
115
-
116
-		$data = $request->getBodyAsString();
117
-		$comment = $this->createComment(
118
-			$node->getName(),
119
-			$node->getId(),
120
-			$data,
121
-			$request->getHeader('Content-Type')
122
-		);
123
-
124
-		// update read marker for the current user/poster to avoid
125
-		// having their own comments marked as unread
126
-		$node->setReadMarker(null);
127
-
128
-		$url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
129
-
130
-		$response->setHeader('Content-Location', $url);
131
-
132
-		// created
133
-		$response->setStatus(201);
134
-		return false;
135
-	}
136
-
137
-	/**
138
-	 * Returns a list of reports this plugin supports.
139
-	 *
140
-	 * This will be used in the {DAV:}supported-report-set property.
141
-	 *
142
-	 * @param string $uri
143
-	 * @return array
144
-	 */
145
-	public function getSupportedReportSet($uri) {
146
-		return [self::REPORT_NAME];
147
-	}
148
-
149
-	/**
150
-	 * REPORT operations to look for comments
151
-	 *
152
-	 * @param string $reportName
153
-	 * @param array $report
154
-	 * @param string $uri
155
-	 * @return bool
156
-	 * @throws NotFound
157
-	 * @throws ReportNotSupported
158
-	 */
159
-	public function onReport($reportName, $report, $uri) {
160
-		$node = $this->server->tree->getNodeForPath($uri);
161
-		if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
162
-			throw new ReportNotSupported();
163
-		}
164
-		$args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
165
-		$acceptableParameters = [
166
-			$this::REPORT_PARAM_LIMIT,
167
-			$this::REPORT_PARAM_OFFSET,
168
-			$this::REPORT_PARAM_TIMESTAMP
169
-		];
170
-		$ns = '{' . $this::NS_OWNCLOUD . '}';
171
-		foreach ($report as $parameter) {
172
-			if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
173
-				continue;
174
-			}
175
-			$args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
176
-		}
177
-
178
-		if (!is_null($args['datetime'])) {
179
-			$args['datetime'] = new \DateTime($args['datetime']);
180
-		}
181
-
182
-		$results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
183
-
184
-		$responses = [];
185
-		foreach ($results as $node) {
186
-			$nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
187
-			$resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
188
-			if (isset($resultSet[0]) && isset($resultSet[0][200])) {
189
-				$responses[] = new Response(
190
-					$this->server->getBaseUri() . $nodePath,
191
-					[200 => $resultSet[0][200]],
192
-					200
193
-				);
194
-			}
195
-		}
196
-
197
-		$xml = $this->server->xml->write(
198
-			'{DAV:}multistatus',
199
-			new MultiStatus($responses)
200
-		);
201
-
202
-		$this->server->httpResponse->setStatus(207);
203
-		$this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
204
-		$this->server->httpResponse->setBody($xml);
205
-
206
-		return false;
207
-	}
208
-
209
-	/**
210
-	 * Creates a new comment
211
-	 *
212
-	 * @param string $objectType e.g. "files"
213
-	 * @param string $objectId e.g. the file id
214
-	 * @param string $data JSON encoded string containing the properties of the tag to create
215
-	 * @param string $contentType content type of the data
216
-	 * @return IComment newly created comment
217
-	 *
218
-	 * @throws BadRequest if a field was missing
219
-	 * @throws UnsupportedMediaType if the content type is not supported
220
-	 */
221
-	private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
222
-		if (explode(';', $contentType)[0] === 'application/json') {
223
-			$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
224
-		} else {
225
-			throw new UnsupportedMediaType();
226
-		}
227
-
228
-		$actorType = $data['actorType'];
229
-		$actorId = null;
230
-		if ($actorType === 'users') {
231
-			$user = $this->userSession->getUser();
232
-			if (!is_null($user)) {
233
-				$actorId = $user->getUID();
234
-			}
235
-		}
236
-		if (is_null($actorId)) {
237
-			throw new BadRequest('Invalid actor "' .  $actorType .'"');
238
-		}
239
-
240
-		try {
241
-			$comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
242
-			$comment->setMessage($data['message']);
243
-			$comment->setVerb($data['verb']);
244
-			$this->commentsManager->save($comment);
245
-			return $comment;
246
-		} catch (\InvalidArgumentException $e) {
247
-			throw new BadRequest('Invalid input values', 0, $e);
248
-		} catch (\OCP\Comments\MessageTooLongException $e) {
249
-			$msg = 'Message exceeds allowed character limit of ';
250
-			throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
251
-		}
252
-	}
47
+    // namespace
48
+    public const NS_OWNCLOUD = 'http://owncloud.org/ns';
49
+
50
+    public const REPORT_NAME = '{http://owncloud.org/ns}filter-comments';
51
+    public const REPORT_PARAM_LIMIT = '{http://owncloud.org/ns}limit';
52
+    public const REPORT_PARAM_OFFSET = '{http://owncloud.org/ns}offset';
53
+    public const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
54
+
55
+    /** @var ICommentsManager  */
56
+    protected $commentsManager;
57
+
58
+    /** @var \Sabre\DAV\Server $server */
59
+    private $server;
60
+
61
+    /** @var  \OCP\IUserSession */
62
+    protected $userSession;
63
+
64
+    /**
65
+     * Comments plugin
66
+     *
67
+     * @param ICommentsManager $commentsManager
68
+     * @param IUserSession $userSession
69
+     */
70
+    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
71
+        $this->commentsManager = $commentsManager;
72
+        $this->userSession = $userSession;
73
+    }
74
+
75
+    /**
76
+     * This initializes the plugin.
77
+     *
78
+     * This function is called by Sabre\DAV\Server, after
79
+     * addPlugin is called.
80
+     *
81
+     * This method should set up the required event subscriptions.
82
+     *
83
+     * @param Server $server
84
+     * @return void
85
+     */
86
+    public function initialize(Server $server) {
87
+        $this->server = $server;
88
+        if (strpos($this->server->getRequestUri(), 'comments/') !== 0) {
89
+            return;
90
+        }
91
+
92
+        $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
93
+
94
+        $this->server->xml->classMap['DateTime'] = function (Writer $writer, \DateTime $value) {
95
+            $writer->write(\Sabre\HTTP\toDate($value));
96
+        };
97
+
98
+        $this->server->on('report', [$this, 'onReport']);
99
+        $this->server->on('method:POST', [$this, 'httpPost']);
100
+    }
101
+
102
+    /**
103
+     * POST operation on Comments collections
104
+     *
105
+     * @param RequestInterface $request request object
106
+     * @param ResponseInterface $response response object
107
+     * @return null|false
108
+     */
109
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
110
+        $path = $request->getPath();
111
+        $node = $this->server->tree->getNodeForPath($path);
112
+        if (!$node instanceof EntityCollection) {
113
+            return null;
114
+        }
115
+
116
+        $data = $request->getBodyAsString();
117
+        $comment = $this->createComment(
118
+            $node->getName(),
119
+            $node->getId(),
120
+            $data,
121
+            $request->getHeader('Content-Type')
122
+        );
123
+
124
+        // update read marker for the current user/poster to avoid
125
+        // having their own comments marked as unread
126
+        $node->setReadMarker(null);
127
+
128
+        $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
129
+
130
+        $response->setHeader('Content-Location', $url);
131
+
132
+        // created
133
+        $response->setStatus(201);
134
+        return false;
135
+    }
136
+
137
+    /**
138
+     * Returns a list of reports this plugin supports.
139
+     *
140
+     * This will be used in the {DAV:}supported-report-set property.
141
+     *
142
+     * @param string $uri
143
+     * @return array
144
+     */
145
+    public function getSupportedReportSet($uri) {
146
+        return [self::REPORT_NAME];
147
+    }
148
+
149
+    /**
150
+     * REPORT operations to look for comments
151
+     *
152
+     * @param string $reportName
153
+     * @param array $report
154
+     * @param string $uri
155
+     * @return bool
156
+     * @throws NotFound
157
+     * @throws ReportNotSupported
158
+     */
159
+    public function onReport($reportName, $report, $uri) {
160
+        $node = $this->server->tree->getNodeForPath($uri);
161
+        if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
162
+            throw new ReportNotSupported();
163
+        }
164
+        $args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
165
+        $acceptableParameters = [
166
+            $this::REPORT_PARAM_LIMIT,
167
+            $this::REPORT_PARAM_OFFSET,
168
+            $this::REPORT_PARAM_TIMESTAMP
169
+        ];
170
+        $ns = '{' . $this::NS_OWNCLOUD . '}';
171
+        foreach ($report as $parameter) {
172
+            if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
173
+                continue;
174
+            }
175
+            $args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
176
+        }
177
+
178
+        if (!is_null($args['datetime'])) {
179
+            $args['datetime'] = new \DateTime($args['datetime']);
180
+        }
181
+
182
+        $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
183
+
184
+        $responses = [];
185
+        foreach ($results as $node) {
186
+            $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
187
+            $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
188
+            if (isset($resultSet[0]) && isset($resultSet[0][200])) {
189
+                $responses[] = new Response(
190
+                    $this->server->getBaseUri() . $nodePath,
191
+                    [200 => $resultSet[0][200]],
192
+                    200
193
+                );
194
+            }
195
+        }
196
+
197
+        $xml = $this->server->xml->write(
198
+            '{DAV:}multistatus',
199
+            new MultiStatus($responses)
200
+        );
201
+
202
+        $this->server->httpResponse->setStatus(207);
203
+        $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
204
+        $this->server->httpResponse->setBody($xml);
205
+
206
+        return false;
207
+    }
208
+
209
+    /**
210
+     * Creates a new comment
211
+     *
212
+     * @param string $objectType e.g. "files"
213
+     * @param string $objectId e.g. the file id
214
+     * @param string $data JSON encoded string containing the properties of the tag to create
215
+     * @param string $contentType content type of the data
216
+     * @return IComment newly created comment
217
+     *
218
+     * @throws BadRequest if a field was missing
219
+     * @throws UnsupportedMediaType if the content type is not supported
220
+     */
221
+    private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
222
+        if (explode(';', $contentType)[0] === 'application/json') {
223
+            $data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
224
+        } else {
225
+            throw new UnsupportedMediaType();
226
+        }
227
+
228
+        $actorType = $data['actorType'];
229
+        $actorId = null;
230
+        if ($actorType === 'users') {
231
+            $user = $this->userSession->getUser();
232
+            if (!is_null($user)) {
233
+                $actorId = $user->getUID();
234
+            }
235
+        }
236
+        if (is_null($actorId)) {
237
+            throw new BadRequest('Invalid actor "' .  $actorType .'"');
238
+        }
239
+
240
+        try {
241
+            $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
242
+            $comment->setMessage($data['message']);
243
+            $comment->setVerb($data['verb']);
244
+            $this->commentsManager->save($comment);
245
+            return $comment;
246
+        } catch (\InvalidArgumentException $e) {
247
+            throw new BadRequest('Invalid input values', 0, $e);
248
+        } catch (\OCP\Comments\MessageTooLongException $e) {
249
+            $msg = 'Message exceeds allowed character limit of ';
250
+            throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
251
+        }
252
+    }
253 253
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php 1 patch
Indentation   +409 added lines, -409 removed lines patch added patch discarded remove patch
@@ -42,413 +42,413 @@
 block discarded – undo
42 42
 
43 43
 class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob {
44 44
 
45
-	/** @var IResourceManager */
46
-	private $resourceManager;
47
-
48
-	/** @var IRoomManager */
49
-	private $roomManager;
50
-
51
-	/** @var IDBConnection */
52
-	private $dbConnection;
53
-
54
-	/** @var CalDavBackend */
55
-	private $calDavBackend;
56
-
57
-	public function __construct(ITimeFactory $time,
58
-								IResourceManager $resourceManager,
59
-								IRoomManager $roomManager,
60
-								IDBConnection $dbConnection,
61
-								CalDavBackend $calDavBackend) {
62
-		parent::__construct($time);
63
-		$this->resourceManager = $resourceManager;
64
-		$this->roomManager = $roomManager;
65
-		$this->dbConnection = $dbConnection;
66
-		$this->calDavBackend = $calDavBackend;
67
-
68
-		// Run once an hour
69
-		$this->setInterval(60 * 60);
70
-		$this->setTimeSensitivity(self::TIME_SENSITIVE);
71
-	}
72
-
73
-	/**
74
-	 * @param $argument
75
-	 */
76
-	public function run($argument): void {
77
-		$this->runForBackend(
78
-			$this->resourceManager,
79
-			'calendar_resources',
80
-			'calendar_resources_md',
81
-			'resource_id',
82
-			'principals/calendar-resources'
83
-		);
84
-		$this->runForBackend(
85
-			$this->roomManager,
86
-			'calendar_rooms',
87
-			'calendar_rooms_md',
88
-			'room_id',
89
-			'principals/calendar-rooms'
90
-		);
91
-	}
92
-
93
-	/**
94
-	 * Run background-job for one specific backendManager
95
-	 * either ResourceManager or RoomManager
96
-	 *
97
-	 * @param IResourceManager|IRoomManager $backendManager
98
-	 * @param string $dbTable
99
-	 * @param string $dbTableMetadata
100
-	 * @param string $foreignKey
101
-	 * @param string $principalPrefix
102
-	 */
103
-	private function runForBackend($backendManager,
104
-								   string $dbTable,
105
-								   string $dbTableMetadata,
106
-								   string $foreignKey,
107
-								   string $principalPrefix): void {
108
-		$backends = $backendManager->getBackends();
109
-
110
-		foreach ($backends as $backend) {
111
-			$backendId = $backend->getBackendIdentifier();
112
-
113
-			try {
114
-				if ($backend instanceof IResourceBackend) {
115
-					$list = $backend->listAllResources();
116
-				} else {
117
-					$list = $backend->listAllRooms();
118
-				}
119
-			} catch (BackendTemporarilyUnavailableException $ex) {
120
-				continue;
121
-			}
122
-
123
-			$cachedList = $this->getAllCachedByBackend($dbTable, $backendId);
124
-			$newIds = array_diff($list, $cachedList);
125
-			$deletedIds = array_diff($cachedList, $list);
126
-			$editedIds = array_intersect($list, $cachedList);
127
-
128
-			foreach ($newIds as $newId) {
129
-				try {
130
-					if ($backend instanceof IResourceBackend) {
131
-						$resource = $backend->getResource($newId);
132
-					} else {
133
-						$resource = $backend->getRoom($newId);
134
-					}
135
-
136
-					$metadata = [];
137
-					if ($resource instanceof IMetadataProvider) {
138
-						$metadata = $this->getAllMetadataOfBackend($resource);
139
-					}
140
-				} catch (BackendTemporarilyUnavailableException $ex) {
141
-					continue;
142
-				}
143
-
144
-				$id = $this->addToCache($dbTable, $backendId, $resource);
145
-				$this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata);
146
-				// we don't create the calendar here, it is created lazily
147
-				// when an event is actually scheduled with this resource / room
148
-			}
149
-
150
-			foreach ($deletedIds as $deletedId) {
151
-				$id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId);
152
-				$this->deleteFromCache($dbTable, $id);
153
-				$this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id);
154
-
155
-				$principalName = implode('-', [$backendId, $deletedId]);
156
-				$this->deleteCalendarDataForResource($principalPrefix, $principalName);
157
-			}
158
-
159
-			foreach ($editedIds as $editedId) {
160
-				$id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId);
161
-
162
-				try {
163
-					if ($backend instanceof IResourceBackend) {
164
-						$resource = $backend->getResource($editedId);
165
-					} else {
166
-						$resource = $backend->getRoom($editedId);
167
-					}
168
-
169
-					$metadata = [];
170
-					if ($resource instanceof IMetadataProvider) {
171
-						$metadata = $this->getAllMetadataOfBackend($resource);
172
-					}
173
-				} catch (BackendTemporarilyUnavailableException $ex) {
174
-					continue;
175
-				}
176
-
177
-				$this->updateCache($dbTable, $id, $resource);
178
-
179
-				if ($resource instanceof IMetadataProvider) {
180
-					$cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id);
181
-					$this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata);
182
-				}
183
-			}
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * add entry to cache that exists remotely but not yet in cache
189
-	 *
190
-	 * @param string $table
191
-	 * @param string $backendId
192
-	 * @param IResource|IRoom $remote
193
-	 *
194
-	 * @return int Insert id
195
-	 */
196
-	private function addToCache(string $table,
197
-								string $backendId,
198
-								$remote): int {
199
-		$query = $this->dbConnection->getQueryBuilder();
200
-		$query->insert($table)
201
-			->values([
202
-				'backend_id' => $query->createNamedParameter($backendId),
203
-				'resource_id' => $query->createNamedParameter($remote->getId()),
204
-				'email' => $query->createNamedParameter($remote->getEMail()),
205
-				'displayname' => $query->createNamedParameter($remote->getDisplayName()),
206
-				'group_restrictions' => $query->createNamedParameter(
207
-					$this->serializeGroupRestrictions(
208
-						$remote->getGroupRestrictions()
209
-					))
210
-			])
211
-			->executeStatement();
212
-		return $query->getLastInsertId();
213
-	}
214
-
215
-	/**
216
-	 * @param string $table
217
-	 * @param string $foreignKey
218
-	 * @param int $foreignId
219
-	 * @param array $metadata
220
-	 */
221
-	private function addMetadataToCache(string $table,
222
-										string $foreignKey,
223
-										int $foreignId,
224
-										array $metadata): void {
225
-		foreach ($metadata as $key => $value) {
226
-			$query = $this->dbConnection->getQueryBuilder();
227
-			$query->insert($table)
228
-				->values([
229
-					$foreignKey => $query->createNamedParameter($foreignId),
230
-					'key' => $query->createNamedParameter($key),
231
-					'value' => $query->createNamedParameter($value),
232
-				])
233
-				->executeStatement();
234
-		}
235
-	}
236
-
237
-	/**
238
-	 * delete entry from cache that does not exist anymore remotely
239
-	 *
240
-	 * @param string $table
241
-	 * @param int $id
242
-	 */
243
-	private function deleteFromCache(string $table,
244
-									 int $id): void {
245
-		$query = $this->dbConnection->getQueryBuilder();
246
-		$query->delete($table)
247
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)))
248
-			->executeStatement();
249
-	}
250
-
251
-	/**
252
-	 * @param string $table
253
-	 * @param string $foreignKey
254
-	 * @param int $id
255
-	 */
256
-	private function deleteMetadataFromCache(string $table,
257
-											 string $foreignKey,
258
-											 int $id): void {
259
-		$query = $this->dbConnection->getQueryBuilder();
260
-		$query->delete($table)
261
-			->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
262
-			->executeStatement();
263
-	}
264
-
265
-	/**
266
-	 * update an existing entry in cache
267
-	 *
268
-	 * @param string $table
269
-	 * @param int $id
270
-	 * @param IResource|IRoom $remote
271
-	 */
272
-	private function updateCache(string $table,
273
-								 int $id,
274
-								 $remote): void {
275
-		$query = $this->dbConnection->getQueryBuilder();
276
-		$query->update($table)
277
-			->set('email', $query->createNamedParameter($remote->getEMail()))
278
-			->set('displayname', $query->createNamedParameter($remote->getDisplayName()))
279
-			->set('group_restrictions', $query->createNamedParameter(
280
-				$this->serializeGroupRestrictions(
281
-					$remote->getGroupRestrictions()
282
-				)))
283
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)))
284
-			->executeStatement();
285
-	}
286
-
287
-	/**
288
-	 * @param string $dbTable
289
-	 * @param string $foreignKey
290
-	 * @param int $id
291
-	 * @param array $metadata
292
-	 * @param array $cachedMetadata
293
-	 */
294
-	private function updateMetadataCache(string $dbTable,
295
-										 string $foreignKey,
296
-										 int $id,
297
-										 array $metadata,
298
-										 array $cachedMetadata): void {
299
-		$newMetadata = array_diff_key($metadata, $cachedMetadata);
300
-		$deletedMetadata = array_diff_key($cachedMetadata, $metadata);
301
-
302
-		foreach ($newMetadata as $key => $value) {
303
-			$query = $this->dbConnection->getQueryBuilder();
304
-			$query->insert($dbTable)
305
-				->values([
306
-					$foreignKey => $query->createNamedParameter($id),
307
-					'key' => $query->createNamedParameter($key),
308
-					'value' => $query->createNamedParameter($value),
309
-				])
310
-				->executeStatement();
311
-		}
312
-
313
-		foreach ($deletedMetadata as $key => $value) {
314
-			$query = $this->dbConnection->getQueryBuilder();
315
-			$query->delete($dbTable)
316
-				->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
317
-				->andWhere($query->expr()->eq('key', $query->createNamedParameter($key)))
318
-				->executeStatement();
319
-		}
320
-
321
-		$existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata));
322
-		foreach ($existingKeys as $existingKey) {
323
-			if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) {
324
-				$query = $this->dbConnection->getQueryBuilder();
325
-				$query->update($dbTable)
326
-					->set('value', $query->createNamedParameter($metadata[$existingKey]))
327
-					->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
328
-					->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey)))
329
-					->executeStatement();
330
-			}
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * serialize array of group restrictions to store them in database
336
-	 *
337
-	 * @param array $groups
338
-	 *
339
-	 * @return string
340
-	 */
341
-	private function serializeGroupRestrictions(array $groups): string {
342
-		return \json_encode($groups, JSON_THROW_ON_ERROR);
343
-	}
344
-
345
-	/**
346
-	 * Gets all metadata of a backend
347
-	 *
348
-	 * @param IResource|IRoom $resource
349
-	 *
350
-	 * @return array
351
-	 */
352
-	private function getAllMetadataOfBackend($resource): array {
353
-		if (!($resource instanceof IMetadataProvider)) {
354
-			return [];
355
-		}
356
-
357
-		$keys = $resource->getAllAvailableMetadataKeys();
358
-		$metadata = [];
359
-		foreach ($keys as $key) {
360
-			$metadata[$key] = $resource->getMetadataForKey($key);
361
-		}
362
-
363
-		return $metadata;
364
-	}
365
-
366
-	/**
367
-	 * @param string $table
368
-	 * @param string $foreignKey
369
-	 * @param int $id
370
-	 *
371
-	 * @return array
372
-	 */
373
-	private function getAllMetadataOfCache(string $table,
374
-										   string $foreignKey,
375
-										   int $id): array {
376
-		$query = $this->dbConnection->getQueryBuilder();
377
-		$query->select(['key', 'value'])
378
-			->from($table)
379
-			->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)));
380
-		$result = $query->executeQuery();
381
-		$rows = $result->fetchAll();
382
-		$result->closeCursor();
383
-
384
-		$metadata = [];
385
-		foreach ($rows as $row) {
386
-			$metadata[$row['key']] = $row['value'];
387
-		}
388
-
389
-		return $metadata;
390
-	}
391
-
392
-	/**
393
-	 * Gets all cached rooms / resources by backend
394
-	 *
395
-	 * @param $tableName
396
-	 * @param $backendId
397
-	 *
398
-	 * @return array
399
-	 */
400
-	private function getAllCachedByBackend(string $tableName,
401
-										   string $backendId): array {
402
-		$query = $this->dbConnection->getQueryBuilder();
403
-		$query->select('resource_id')
404
-			->from($tableName)
405
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)));
406
-		$result = $query->executeQuery();
407
-		$rows = $result->fetchAll();
408
-		$result->closeCursor();
409
-
410
-		return array_map(function ($row): string {
411
-			return $row['resource_id'];
412
-		}, $rows);
413
-	}
414
-
415
-	/**
416
-	 * @param $principalPrefix
417
-	 * @param $principalUri
418
-	 */
419
-	private function deleteCalendarDataForResource(string $principalPrefix,
420
-												   string $principalUri): void {
421
-		$calendar = $this->calDavBackend->getCalendarByUri(
422
-			implode('/', [$principalPrefix, $principalUri]),
423
-			CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI);
424
-
425
-		if ($calendar !== null) {
426
-			$this->calDavBackend->deleteCalendar(
427
-				$calendar['id'],
428
-				true // Because this wasn't deleted by a user
429
-			);
430
-		}
431
-	}
432
-
433
-	/**
434
-	 * @param $table
435
-	 * @param $backendId
436
-	 * @param $resourceId
437
-	 *
438
-	 * @return int
439
-	 */
440
-	private function getIdForBackendAndResource(string $table,
441
-												string $backendId,
442
-												string $resourceId): int {
443
-		$query = $this->dbConnection->getQueryBuilder();
444
-		$query->select('id')
445
-			->from($table)
446
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
447
-			->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
448
-		$result = $query->executeQuery();
449
-
450
-		$id = (int) $result->fetchOne();
451
-		$result->closeCursor();
452
-		return $id;
453
-	}
45
+    /** @var IResourceManager */
46
+    private $resourceManager;
47
+
48
+    /** @var IRoomManager */
49
+    private $roomManager;
50
+
51
+    /** @var IDBConnection */
52
+    private $dbConnection;
53
+
54
+    /** @var CalDavBackend */
55
+    private $calDavBackend;
56
+
57
+    public function __construct(ITimeFactory $time,
58
+                                IResourceManager $resourceManager,
59
+                                IRoomManager $roomManager,
60
+                                IDBConnection $dbConnection,
61
+                                CalDavBackend $calDavBackend) {
62
+        parent::__construct($time);
63
+        $this->resourceManager = $resourceManager;
64
+        $this->roomManager = $roomManager;
65
+        $this->dbConnection = $dbConnection;
66
+        $this->calDavBackend = $calDavBackend;
67
+
68
+        // Run once an hour
69
+        $this->setInterval(60 * 60);
70
+        $this->setTimeSensitivity(self::TIME_SENSITIVE);
71
+    }
72
+
73
+    /**
74
+     * @param $argument
75
+     */
76
+    public function run($argument): void {
77
+        $this->runForBackend(
78
+            $this->resourceManager,
79
+            'calendar_resources',
80
+            'calendar_resources_md',
81
+            'resource_id',
82
+            'principals/calendar-resources'
83
+        );
84
+        $this->runForBackend(
85
+            $this->roomManager,
86
+            'calendar_rooms',
87
+            'calendar_rooms_md',
88
+            'room_id',
89
+            'principals/calendar-rooms'
90
+        );
91
+    }
92
+
93
+    /**
94
+     * Run background-job for one specific backendManager
95
+     * either ResourceManager or RoomManager
96
+     *
97
+     * @param IResourceManager|IRoomManager $backendManager
98
+     * @param string $dbTable
99
+     * @param string $dbTableMetadata
100
+     * @param string $foreignKey
101
+     * @param string $principalPrefix
102
+     */
103
+    private function runForBackend($backendManager,
104
+                                    string $dbTable,
105
+                                    string $dbTableMetadata,
106
+                                    string $foreignKey,
107
+                                    string $principalPrefix): void {
108
+        $backends = $backendManager->getBackends();
109
+
110
+        foreach ($backends as $backend) {
111
+            $backendId = $backend->getBackendIdentifier();
112
+
113
+            try {
114
+                if ($backend instanceof IResourceBackend) {
115
+                    $list = $backend->listAllResources();
116
+                } else {
117
+                    $list = $backend->listAllRooms();
118
+                }
119
+            } catch (BackendTemporarilyUnavailableException $ex) {
120
+                continue;
121
+            }
122
+
123
+            $cachedList = $this->getAllCachedByBackend($dbTable, $backendId);
124
+            $newIds = array_diff($list, $cachedList);
125
+            $deletedIds = array_diff($cachedList, $list);
126
+            $editedIds = array_intersect($list, $cachedList);
127
+
128
+            foreach ($newIds as $newId) {
129
+                try {
130
+                    if ($backend instanceof IResourceBackend) {
131
+                        $resource = $backend->getResource($newId);
132
+                    } else {
133
+                        $resource = $backend->getRoom($newId);
134
+                    }
135
+
136
+                    $metadata = [];
137
+                    if ($resource instanceof IMetadataProvider) {
138
+                        $metadata = $this->getAllMetadataOfBackend($resource);
139
+                    }
140
+                } catch (BackendTemporarilyUnavailableException $ex) {
141
+                    continue;
142
+                }
143
+
144
+                $id = $this->addToCache($dbTable, $backendId, $resource);
145
+                $this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata);
146
+                // we don't create the calendar here, it is created lazily
147
+                // when an event is actually scheduled with this resource / room
148
+            }
149
+
150
+            foreach ($deletedIds as $deletedId) {
151
+                $id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId);
152
+                $this->deleteFromCache($dbTable, $id);
153
+                $this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id);
154
+
155
+                $principalName = implode('-', [$backendId, $deletedId]);
156
+                $this->deleteCalendarDataForResource($principalPrefix, $principalName);
157
+            }
158
+
159
+            foreach ($editedIds as $editedId) {
160
+                $id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId);
161
+
162
+                try {
163
+                    if ($backend instanceof IResourceBackend) {
164
+                        $resource = $backend->getResource($editedId);
165
+                    } else {
166
+                        $resource = $backend->getRoom($editedId);
167
+                    }
168
+
169
+                    $metadata = [];
170
+                    if ($resource instanceof IMetadataProvider) {
171
+                        $metadata = $this->getAllMetadataOfBackend($resource);
172
+                    }
173
+                } catch (BackendTemporarilyUnavailableException $ex) {
174
+                    continue;
175
+                }
176
+
177
+                $this->updateCache($dbTable, $id, $resource);
178
+
179
+                if ($resource instanceof IMetadataProvider) {
180
+                    $cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id);
181
+                    $this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata);
182
+                }
183
+            }
184
+        }
185
+    }
186
+
187
+    /**
188
+     * add entry to cache that exists remotely but not yet in cache
189
+     *
190
+     * @param string $table
191
+     * @param string $backendId
192
+     * @param IResource|IRoom $remote
193
+     *
194
+     * @return int Insert id
195
+     */
196
+    private function addToCache(string $table,
197
+                                string $backendId,
198
+                                $remote): int {
199
+        $query = $this->dbConnection->getQueryBuilder();
200
+        $query->insert($table)
201
+            ->values([
202
+                'backend_id' => $query->createNamedParameter($backendId),
203
+                'resource_id' => $query->createNamedParameter($remote->getId()),
204
+                'email' => $query->createNamedParameter($remote->getEMail()),
205
+                'displayname' => $query->createNamedParameter($remote->getDisplayName()),
206
+                'group_restrictions' => $query->createNamedParameter(
207
+                    $this->serializeGroupRestrictions(
208
+                        $remote->getGroupRestrictions()
209
+                    ))
210
+            ])
211
+            ->executeStatement();
212
+        return $query->getLastInsertId();
213
+    }
214
+
215
+    /**
216
+     * @param string $table
217
+     * @param string $foreignKey
218
+     * @param int $foreignId
219
+     * @param array $metadata
220
+     */
221
+    private function addMetadataToCache(string $table,
222
+                                        string $foreignKey,
223
+                                        int $foreignId,
224
+                                        array $metadata): void {
225
+        foreach ($metadata as $key => $value) {
226
+            $query = $this->dbConnection->getQueryBuilder();
227
+            $query->insert($table)
228
+                ->values([
229
+                    $foreignKey => $query->createNamedParameter($foreignId),
230
+                    'key' => $query->createNamedParameter($key),
231
+                    'value' => $query->createNamedParameter($value),
232
+                ])
233
+                ->executeStatement();
234
+        }
235
+    }
236
+
237
+    /**
238
+     * delete entry from cache that does not exist anymore remotely
239
+     *
240
+     * @param string $table
241
+     * @param int $id
242
+     */
243
+    private function deleteFromCache(string $table,
244
+                                        int $id): void {
245
+        $query = $this->dbConnection->getQueryBuilder();
246
+        $query->delete($table)
247
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
248
+            ->executeStatement();
249
+    }
250
+
251
+    /**
252
+     * @param string $table
253
+     * @param string $foreignKey
254
+     * @param int $id
255
+     */
256
+    private function deleteMetadataFromCache(string $table,
257
+                                                string $foreignKey,
258
+                                                int $id): void {
259
+        $query = $this->dbConnection->getQueryBuilder();
260
+        $query->delete($table)
261
+            ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
262
+            ->executeStatement();
263
+    }
264
+
265
+    /**
266
+     * update an existing entry in cache
267
+     *
268
+     * @param string $table
269
+     * @param int $id
270
+     * @param IResource|IRoom $remote
271
+     */
272
+    private function updateCache(string $table,
273
+                                    int $id,
274
+                                    $remote): void {
275
+        $query = $this->dbConnection->getQueryBuilder();
276
+        $query->update($table)
277
+            ->set('email', $query->createNamedParameter($remote->getEMail()))
278
+            ->set('displayname', $query->createNamedParameter($remote->getDisplayName()))
279
+            ->set('group_restrictions', $query->createNamedParameter(
280
+                $this->serializeGroupRestrictions(
281
+                    $remote->getGroupRestrictions()
282
+                )))
283
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
284
+            ->executeStatement();
285
+    }
286
+
287
+    /**
288
+     * @param string $dbTable
289
+     * @param string $foreignKey
290
+     * @param int $id
291
+     * @param array $metadata
292
+     * @param array $cachedMetadata
293
+     */
294
+    private function updateMetadataCache(string $dbTable,
295
+                                            string $foreignKey,
296
+                                            int $id,
297
+                                            array $metadata,
298
+                                            array $cachedMetadata): void {
299
+        $newMetadata = array_diff_key($metadata, $cachedMetadata);
300
+        $deletedMetadata = array_diff_key($cachedMetadata, $metadata);
301
+
302
+        foreach ($newMetadata as $key => $value) {
303
+            $query = $this->dbConnection->getQueryBuilder();
304
+            $query->insert($dbTable)
305
+                ->values([
306
+                    $foreignKey => $query->createNamedParameter($id),
307
+                    'key' => $query->createNamedParameter($key),
308
+                    'value' => $query->createNamedParameter($value),
309
+                ])
310
+                ->executeStatement();
311
+        }
312
+
313
+        foreach ($deletedMetadata as $key => $value) {
314
+            $query = $this->dbConnection->getQueryBuilder();
315
+            $query->delete($dbTable)
316
+                ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
317
+                ->andWhere($query->expr()->eq('key', $query->createNamedParameter($key)))
318
+                ->executeStatement();
319
+        }
320
+
321
+        $existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata));
322
+        foreach ($existingKeys as $existingKey) {
323
+            if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) {
324
+                $query = $this->dbConnection->getQueryBuilder();
325
+                $query->update($dbTable)
326
+                    ->set('value', $query->createNamedParameter($metadata[$existingKey]))
327
+                    ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
328
+                    ->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey)))
329
+                    ->executeStatement();
330
+            }
331
+        }
332
+    }
333
+
334
+    /**
335
+     * serialize array of group restrictions to store them in database
336
+     *
337
+     * @param array $groups
338
+     *
339
+     * @return string
340
+     */
341
+    private function serializeGroupRestrictions(array $groups): string {
342
+        return \json_encode($groups, JSON_THROW_ON_ERROR);
343
+    }
344
+
345
+    /**
346
+     * Gets all metadata of a backend
347
+     *
348
+     * @param IResource|IRoom $resource
349
+     *
350
+     * @return array
351
+     */
352
+    private function getAllMetadataOfBackend($resource): array {
353
+        if (!($resource instanceof IMetadataProvider)) {
354
+            return [];
355
+        }
356
+
357
+        $keys = $resource->getAllAvailableMetadataKeys();
358
+        $metadata = [];
359
+        foreach ($keys as $key) {
360
+            $metadata[$key] = $resource->getMetadataForKey($key);
361
+        }
362
+
363
+        return $metadata;
364
+    }
365
+
366
+    /**
367
+     * @param string $table
368
+     * @param string $foreignKey
369
+     * @param int $id
370
+     *
371
+     * @return array
372
+     */
373
+    private function getAllMetadataOfCache(string $table,
374
+                                            string $foreignKey,
375
+                                            int $id): array {
376
+        $query = $this->dbConnection->getQueryBuilder();
377
+        $query->select(['key', 'value'])
378
+            ->from($table)
379
+            ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)));
380
+        $result = $query->executeQuery();
381
+        $rows = $result->fetchAll();
382
+        $result->closeCursor();
383
+
384
+        $metadata = [];
385
+        foreach ($rows as $row) {
386
+            $metadata[$row['key']] = $row['value'];
387
+        }
388
+
389
+        return $metadata;
390
+    }
391
+
392
+    /**
393
+     * Gets all cached rooms / resources by backend
394
+     *
395
+     * @param $tableName
396
+     * @param $backendId
397
+     *
398
+     * @return array
399
+     */
400
+    private function getAllCachedByBackend(string $tableName,
401
+                                            string $backendId): array {
402
+        $query = $this->dbConnection->getQueryBuilder();
403
+        $query->select('resource_id')
404
+            ->from($tableName)
405
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)));
406
+        $result = $query->executeQuery();
407
+        $rows = $result->fetchAll();
408
+        $result->closeCursor();
409
+
410
+        return array_map(function ($row): string {
411
+            return $row['resource_id'];
412
+        }, $rows);
413
+    }
414
+
415
+    /**
416
+     * @param $principalPrefix
417
+     * @param $principalUri
418
+     */
419
+    private function deleteCalendarDataForResource(string $principalPrefix,
420
+                                                    string $principalUri): void {
421
+        $calendar = $this->calDavBackend->getCalendarByUri(
422
+            implode('/', [$principalPrefix, $principalUri]),
423
+            CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI);
424
+
425
+        if ($calendar !== null) {
426
+            $this->calDavBackend->deleteCalendar(
427
+                $calendar['id'],
428
+                true // Because this wasn't deleted by a user
429
+            );
430
+        }
431
+    }
432
+
433
+    /**
434
+     * @param $table
435
+     * @param $backendId
436
+     * @param $resourceId
437
+     *
438
+     * @return int
439
+     */
440
+    private function getIdForBackendAndResource(string $table,
441
+                                                string $backendId,
442
+                                                string $resourceId): int {
443
+        $query = $this->dbConnection->getQueryBuilder();
444
+        $query->select('id')
445
+            ->from($table)
446
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
447
+            ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
448
+        $result = $query->executeQuery();
449
+
450
+        $id = (int) $result->fetchOne();
451
+        $result->closeCursor();
452
+        return $id;
453
+    }
454 454
 }
Please login to merge, or discard this patch.
apps/dav/lib/BulkUpload/BulkUploadPlugin.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -34,83 +34,83 @@
 block discarded – undo
34 34
 use OCA\DAV\Connector\Sabre\MtimeSanitizer;
35 35
 
36 36
 class BulkUploadPlugin extends ServerPlugin {
37
-	private Folder $userFolder;
38
-	private LoggerInterface $logger;
37
+    private Folder $userFolder;
38
+    private LoggerInterface $logger;
39 39
 
40
-	public function __construct(
41
-		Folder $userFolder,
42
-		LoggerInterface $logger
43
-	) {
44
-		$this->userFolder = $userFolder;
45
-		$this->logger = $logger;
46
-	}
40
+    public function __construct(
41
+        Folder $userFolder,
42
+        LoggerInterface $logger
43
+    ) {
44
+        $this->userFolder = $userFolder;
45
+        $this->logger = $logger;
46
+    }
47 47
 
48
-	/**
49
-	 * Register listener on POST requests with the httpPost method.
50
-	 */
51
-	public function initialize(Server $server): void {
52
-		$server->on('method:POST', [$this, 'httpPost'], 10);
53
-	}
48
+    /**
49
+     * Register listener on POST requests with the httpPost method.
50
+     */
51
+    public function initialize(Server $server): void {
52
+        $server->on('method:POST', [$this, 'httpPost'], 10);
53
+    }
54 54
 
55
-	/**
56
-	 * Handle POST requests on /dav/bulk
57
-	 * - parsing is done with a MultipartContentsParser object
58
-	 * - writing is done with the userFolder service
59
-	 *
60
-	 * Will respond with an object containing an ETag for every written files.
61
-	 */
62
-	public function httpPost(RequestInterface $request, ResponseInterface $response): bool {
63
-		// Limit bulk upload to the /dav/bulk endpoint
64
-		if ($request->getPath() !== "bulk") {
65
-			return true;
66
-		}
55
+    /**
56
+     * Handle POST requests on /dav/bulk
57
+     * - parsing is done with a MultipartContentsParser object
58
+     * - writing is done with the userFolder service
59
+     *
60
+     * Will respond with an object containing an ETag for every written files.
61
+     */
62
+    public function httpPost(RequestInterface $request, ResponseInterface $response): bool {
63
+        // Limit bulk upload to the /dav/bulk endpoint
64
+        if ($request->getPath() !== "bulk") {
65
+            return true;
66
+        }
67 67
 
68
-		$multiPartParser = new MultipartRequestParser($request);
69
-		$writtenFiles = [];
68
+        $multiPartParser = new MultipartRequestParser($request);
69
+        $writtenFiles = [];
70 70
 
71
-		while (!$multiPartParser->isAtLastBoundary()) {
72
-			try {
73
-				[$headers, $content] = $multiPartParser->parseNextPart();
74
-			} catch (\Exception $e) {
75
-				// Return early if an error occurs during parsing.
76
-				$this->logger->error($e->getMessage());
77
-				$response->setStatus(Http::STATUS_BAD_REQUEST);
78
-				$response->setBody(json_encode($writtenFiles, JSON_THROW_ON_ERROR));
79
-				return false;
80
-			}
71
+        while (!$multiPartParser->isAtLastBoundary()) {
72
+            try {
73
+                [$headers, $content] = $multiPartParser->parseNextPart();
74
+            } catch (\Exception $e) {
75
+                // Return early if an error occurs during parsing.
76
+                $this->logger->error($e->getMessage());
77
+                $response->setStatus(Http::STATUS_BAD_REQUEST);
78
+                $response->setBody(json_encode($writtenFiles, JSON_THROW_ON_ERROR));
79
+                return false;
80
+            }
81 81
 
82
-			try {
83
-				// TODO: Remove 'x-file-mtime' when the desktop client no longer use it.
84
-				if (isset($headers['x-file-mtime'])) {
85
-					$mtime = MtimeSanitizer::sanitizeMtime($headers['x-file-mtime']);
86
-				} elseif (isset($headers['x-oc-mtime'])) {
87
-					$mtime = MtimeSanitizer::sanitizeMtime($headers['x-oc-mtime']);
88
-				} else {
89
-					$mtime = null;
90
-				}
82
+            try {
83
+                // TODO: Remove 'x-file-mtime' when the desktop client no longer use it.
84
+                if (isset($headers['x-file-mtime'])) {
85
+                    $mtime = MtimeSanitizer::sanitizeMtime($headers['x-file-mtime']);
86
+                } elseif (isset($headers['x-oc-mtime'])) {
87
+                    $mtime = MtimeSanitizer::sanitizeMtime($headers['x-oc-mtime']);
88
+                } else {
89
+                    $mtime = null;
90
+                }
91 91
 
92
-				$node = $this->userFolder->newFile($headers['x-file-path'], $content);
93
-				$node->touch($mtime);
94
-				$node = $this->userFolder->getById($node->getId())[0];
92
+                $node = $this->userFolder->newFile($headers['x-file-path'], $content);
93
+                $node->touch($mtime);
94
+                $node = $this->userFolder->getById($node->getId())[0];
95 95
 
96
-				$writtenFiles[$headers['x-file-path']] = [
97
-					"error" => false,
98
-					"etag" => $node->getETag(),
99
-					"fileid" => DavUtil::getDavFileId($node->getId()),
100
-					"permissions" => DavUtil::getDavPermissions($node),
101
-				];
102
-			} catch (\Exception $e) {
103
-				$this->logger->error($e->getMessage(), ['path' => $headers['x-file-path']]);
104
-				$writtenFiles[$headers['x-file-path']] = [
105
-					"error" => true,
106
-					"message" => $e->getMessage(),
107
-				];
108
-			}
109
-		}
96
+                $writtenFiles[$headers['x-file-path']] = [
97
+                    "error" => false,
98
+                    "etag" => $node->getETag(),
99
+                    "fileid" => DavUtil::getDavFileId($node->getId()),
100
+                    "permissions" => DavUtil::getDavPermissions($node),
101
+                ];
102
+            } catch (\Exception $e) {
103
+                $this->logger->error($e->getMessage(), ['path' => $headers['x-file-path']]);
104
+                $writtenFiles[$headers['x-file-path']] = [
105
+                    "error" => true,
106
+                    "message" => $e->getMessage(),
107
+                ];
108
+            }
109
+        }
110 110
 
111
-		$response->setStatus(Http::STATUS_OK);
112
-		$response->setBody(json_encode($writtenFiles, JSON_THROW_ON_ERROR));
111
+        $response->setStatus(Http::STATUS_OK);
112
+        $response->setBody(json_encode($writtenFiles, JSON_THROW_ON_ERROR));
113 113
 
114
-		return false;
115
-	}
114
+        return false;
115
+    }
116 116
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagPlugin.php 1 patch
Indentation   +274 added lines, -274 removed lines patch added patch discarded remove patch
@@ -48,278 +48,278 @@
 block discarded – undo
48 48
  */
49 49
 class SystemTagPlugin extends \Sabre\DAV\ServerPlugin {
50 50
 
51
-	// namespace
52
-	public const NS_OWNCLOUD = 'http://owncloud.org/ns';
53
-	public const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
54
-	public const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
55
-	public const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
56
-	public const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
57
-	public const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
58
-	public const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
59
-
60
-	/**
61
-	 * @var \Sabre\DAV\Server $server
62
-	 */
63
-	private $server;
64
-
65
-	/**
66
-	 * @var ISystemTagManager
67
-	 */
68
-	protected $tagManager;
69
-
70
-	/**
71
-	 * @var IUserSession
72
-	 */
73
-	protected $userSession;
74
-
75
-	/**
76
-	 * @var IGroupManager
77
-	 */
78
-	protected $groupManager;
79
-
80
-	/**
81
-	 * @param ISystemTagManager $tagManager tag manager
82
-	 * @param IGroupManager $groupManager
83
-	 * @param IUserSession $userSession
84
-	 */
85
-	public function __construct(ISystemTagManager $tagManager,
86
-								IGroupManager $groupManager,
87
-								IUserSession $userSession) {
88
-		$this->tagManager = $tagManager;
89
-		$this->userSession = $userSession;
90
-		$this->groupManager = $groupManager;
91
-	}
92
-
93
-	/**
94
-	 * This initializes the plugin.
95
-	 *
96
-	 * This function is called by \Sabre\DAV\Server, after
97
-	 * addPlugin is called.
98
-	 *
99
-	 * This method should set up the required event subscriptions.
100
-	 *
101
-	 * @param \Sabre\DAV\Server $server
102
-	 * @return void
103
-	 */
104
-	public function initialize(\Sabre\DAV\Server $server) {
105
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
106
-
107
-		$server->protectedProperties[] = self::ID_PROPERTYNAME;
108
-
109
-		$server->on('propFind', [$this, 'handleGetProperties']);
110
-		$server->on('propPatch', [$this, 'handleUpdateProperties']);
111
-		$server->on('method:POST', [$this, 'httpPost']);
112
-
113
-		$this->server = $server;
114
-	}
115
-
116
-	/**
117
-	 * POST operation on system tag collections
118
-	 *
119
-	 * @param RequestInterface $request request object
120
-	 * @param ResponseInterface $response response object
121
-	 * @return null|false
122
-	 */
123
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
124
-		$path = $request->getPath();
125
-
126
-		// Making sure the node exists
127
-		$node = $this->server->tree->getNodeForPath($path);
128
-		if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
129
-			$data = $request->getBodyAsString();
130
-
131
-			$tag = $this->createTag($data, $request->getHeader('Content-Type'));
132
-
133
-			if ($node instanceof SystemTagsObjectMappingCollection) {
134
-				// also add to collection
135
-				$node->createFile($tag->getId());
136
-				$url = $request->getBaseUrl() . 'systemtags/';
137
-			} else {
138
-				$url = $request->getUrl();
139
-			}
140
-
141
-			if ($url[strlen($url) - 1] !== '/') {
142
-				$url .= '/';
143
-			}
144
-
145
-			$response->setHeader('Content-Location', $url . $tag->getId());
146
-
147
-			// created
148
-			$response->setStatus(201);
149
-			return false;
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * Creates a new tag
155
-	 *
156
-	 * @param string $data JSON encoded string containing the properties of the tag to create
157
-	 * @param string $contentType content type of the data
158
-	 * @return ISystemTag newly created system tag
159
-	 *
160
-	 * @throws BadRequest if a field was missing
161
-	 * @throws Conflict if a tag with the same properties already exists
162
-	 * @throws UnsupportedMediaType if the content type is not supported
163
-	 */
164
-	private function createTag($data, $contentType = 'application/json') {
165
-		if (explode(';', $contentType)[0] === 'application/json') {
166
-			$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
167
-		} else {
168
-			throw new UnsupportedMediaType();
169
-		}
170
-
171
-		if (!isset($data['name'])) {
172
-			throw new BadRequest('Missing "name" attribute');
173
-		}
174
-
175
-		$tagName = $data['name'];
176
-		$userVisible = true;
177
-		$userAssignable = true;
178
-
179
-		if (isset($data['userVisible'])) {
180
-			$userVisible = (bool)$data['userVisible'];
181
-		}
182
-
183
-		if (isset($data['userAssignable'])) {
184
-			$userAssignable = (bool)$data['userAssignable'];
185
-		}
186
-
187
-		$groups = [];
188
-		if (isset($data['groups'])) {
189
-			$groups = $data['groups'];
190
-			if (is_string($groups)) {
191
-				$groups = explode('|', $groups);
192
-			}
193
-		}
194
-
195
-		if ($userVisible === false || $userAssignable === false || !empty($groups)) {
196
-			if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
197
-				throw new BadRequest('Not sufficient permissions');
198
-			}
199
-		}
200
-
201
-		try {
202
-			$tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
203
-			if (!empty($groups)) {
204
-				$this->tagManager->setTagGroups($tag, $groups);
205
-			}
206
-			return $tag;
207
-		} catch (TagAlreadyExistsException $e) {
208
-			throw new Conflict('Tag already exists', 0, $e);
209
-		}
210
-	}
211
-
212
-
213
-	/**
214
-	 * Retrieves system tag properties
215
-	 *
216
-	 * @param PropFind $propFind
217
-	 * @param \Sabre\DAV\INode $node
218
-	 */
219
-	public function handleGetProperties(
220
-		PropFind $propFind,
221
-		\Sabre\DAV\INode $node
222
-	) {
223
-		if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
224
-			return;
225
-		}
226
-
227
-		$propFind->handle(self::ID_PROPERTYNAME, function () use ($node) {
228
-			return $node->getSystemTag()->getId();
229
-		});
230
-
231
-		$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
232
-			return $node->getSystemTag()->getName();
233
-		});
234
-
235
-		$propFind->handle(self::USERVISIBLE_PROPERTYNAME, function () use ($node) {
236
-			return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
237
-		});
238
-
239
-		$propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function () use ($node) {
240
-			// this is the tag's inherent property "is user assignable"
241
-			return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
242
-		});
243
-
244
-		$propFind->handle(self::CANASSIGN_PROPERTYNAME, function () use ($node) {
245
-			// this is the effective permission for the current user
246
-			return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
247
-		});
248
-
249
-		$propFind->handle(self::GROUPS_PROPERTYNAME, function () use ($node) {
250
-			if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
251
-				// property only available for admins
252
-				throw new Forbidden();
253
-			}
254
-			$groups = [];
255
-			// no need to retrieve groups for namespaces that don't qualify
256
-			if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
257
-				$groups = $this->tagManager->getTagGroups($node->getSystemTag());
258
-			}
259
-			return implode('|', $groups);
260
-		});
261
-	}
262
-
263
-	/**
264
-	 * Updates tag attributes
265
-	 *
266
-	 * @param string $path
267
-	 * @param PropPatch $propPatch
268
-	 *
269
-	 * @return void
270
-	 */
271
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
272
-		$node = $this->server->tree->getNodeForPath($path);
273
-		if (!($node instanceof SystemTagNode)) {
274
-			return;
275
-		}
276
-
277
-		$propPatch->handle([
278
-			self::DISPLAYNAME_PROPERTYNAME,
279
-			self::USERVISIBLE_PROPERTYNAME,
280
-			self::USERASSIGNABLE_PROPERTYNAME,
281
-			self::GROUPS_PROPERTYNAME,
282
-		], function ($props) use ($node) {
283
-			$tag = $node->getSystemTag();
284
-			$name = $tag->getName();
285
-			$userVisible = $tag->isUserVisible();
286
-			$userAssignable = $tag->isUserAssignable();
287
-
288
-			$updateTag = false;
289
-
290
-			if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
291
-				$name = $props[self::DISPLAYNAME_PROPERTYNAME];
292
-				$updateTag = true;
293
-			}
294
-
295
-			if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
296
-				$propValue = $props[self::USERVISIBLE_PROPERTYNAME];
297
-				$userVisible = ($propValue !== 'false' && $propValue !== '0');
298
-				$updateTag = true;
299
-			}
300
-
301
-			if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
302
-				$propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
303
-				$userAssignable = ($propValue !== 'false' && $propValue !== '0');
304
-				$updateTag = true;
305
-			}
306
-
307
-			if (isset($props[self::GROUPS_PROPERTYNAME])) {
308
-				if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
309
-					// property only available for admins
310
-					throw new Forbidden();
311
-				}
312
-
313
-				$propValue = $props[self::GROUPS_PROPERTYNAME];
314
-				$groupIds = explode('|', $propValue);
315
-				$this->tagManager->setTagGroups($tag, $groupIds);
316
-			}
317
-
318
-			if ($updateTag) {
319
-				$node->update($name, $userVisible, $userAssignable);
320
-			}
321
-
322
-			return true;
323
-		});
324
-	}
51
+    // namespace
52
+    public const NS_OWNCLOUD = 'http://owncloud.org/ns';
53
+    public const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
54
+    public const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
55
+    public const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
56
+    public const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
57
+    public const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
58
+    public const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
59
+
60
+    /**
61
+     * @var \Sabre\DAV\Server $server
62
+     */
63
+    private $server;
64
+
65
+    /**
66
+     * @var ISystemTagManager
67
+     */
68
+    protected $tagManager;
69
+
70
+    /**
71
+     * @var IUserSession
72
+     */
73
+    protected $userSession;
74
+
75
+    /**
76
+     * @var IGroupManager
77
+     */
78
+    protected $groupManager;
79
+
80
+    /**
81
+     * @param ISystemTagManager $tagManager tag manager
82
+     * @param IGroupManager $groupManager
83
+     * @param IUserSession $userSession
84
+     */
85
+    public function __construct(ISystemTagManager $tagManager,
86
+                                IGroupManager $groupManager,
87
+                                IUserSession $userSession) {
88
+        $this->tagManager = $tagManager;
89
+        $this->userSession = $userSession;
90
+        $this->groupManager = $groupManager;
91
+    }
92
+
93
+    /**
94
+     * This initializes the plugin.
95
+     *
96
+     * This function is called by \Sabre\DAV\Server, after
97
+     * addPlugin is called.
98
+     *
99
+     * This method should set up the required event subscriptions.
100
+     *
101
+     * @param \Sabre\DAV\Server $server
102
+     * @return void
103
+     */
104
+    public function initialize(\Sabre\DAV\Server $server) {
105
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
106
+
107
+        $server->protectedProperties[] = self::ID_PROPERTYNAME;
108
+
109
+        $server->on('propFind', [$this, 'handleGetProperties']);
110
+        $server->on('propPatch', [$this, 'handleUpdateProperties']);
111
+        $server->on('method:POST', [$this, 'httpPost']);
112
+
113
+        $this->server = $server;
114
+    }
115
+
116
+    /**
117
+     * POST operation on system tag collections
118
+     *
119
+     * @param RequestInterface $request request object
120
+     * @param ResponseInterface $response response object
121
+     * @return null|false
122
+     */
123
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
124
+        $path = $request->getPath();
125
+
126
+        // Making sure the node exists
127
+        $node = $this->server->tree->getNodeForPath($path);
128
+        if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
129
+            $data = $request->getBodyAsString();
130
+
131
+            $tag = $this->createTag($data, $request->getHeader('Content-Type'));
132
+
133
+            if ($node instanceof SystemTagsObjectMappingCollection) {
134
+                // also add to collection
135
+                $node->createFile($tag->getId());
136
+                $url = $request->getBaseUrl() . 'systemtags/';
137
+            } else {
138
+                $url = $request->getUrl();
139
+            }
140
+
141
+            if ($url[strlen($url) - 1] !== '/') {
142
+                $url .= '/';
143
+            }
144
+
145
+            $response->setHeader('Content-Location', $url . $tag->getId());
146
+
147
+            // created
148
+            $response->setStatus(201);
149
+            return false;
150
+        }
151
+    }
152
+
153
+    /**
154
+     * Creates a new tag
155
+     *
156
+     * @param string $data JSON encoded string containing the properties of the tag to create
157
+     * @param string $contentType content type of the data
158
+     * @return ISystemTag newly created system tag
159
+     *
160
+     * @throws BadRequest if a field was missing
161
+     * @throws Conflict if a tag with the same properties already exists
162
+     * @throws UnsupportedMediaType if the content type is not supported
163
+     */
164
+    private function createTag($data, $contentType = 'application/json') {
165
+        if (explode(';', $contentType)[0] === 'application/json') {
166
+            $data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
167
+        } else {
168
+            throw new UnsupportedMediaType();
169
+        }
170
+
171
+        if (!isset($data['name'])) {
172
+            throw new BadRequest('Missing "name" attribute');
173
+        }
174
+
175
+        $tagName = $data['name'];
176
+        $userVisible = true;
177
+        $userAssignable = true;
178
+
179
+        if (isset($data['userVisible'])) {
180
+            $userVisible = (bool)$data['userVisible'];
181
+        }
182
+
183
+        if (isset($data['userAssignable'])) {
184
+            $userAssignable = (bool)$data['userAssignable'];
185
+        }
186
+
187
+        $groups = [];
188
+        if (isset($data['groups'])) {
189
+            $groups = $data['groups'];
190
+            if (is_string($groups)) {
191
+                $groups = explode('|', $groups);
192
+            }
193
+        }
194
+
195
+        if ($userVisible === false || $userAssignable === false || !empty($groups)) {
196
+            if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
197
+                throw new BadRequest('Not sufficient permissions');
198
+            }
199
+        }
200
+
201
+        try {
202
+            $tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
203
+            if (!empty($groups)) {
204
+                $this->tagManager->setTagGroups($tag, $groups);
205
+            }
206
+            return $tag;
207
+        } catch (TagAlreadyExistsException $e) {
208
+            throw new Conflict('Tag already exists', 0, $e);
209
+        }
210
+    }
211
+
212
+
213
+    /**
214
+     * Retrieves system tag properties
215
+     *
216
+     * @param PropFind $propFind
217
+     * @param \Sabre\DAV\INode $node
218
+     */
219
+    public function handleGetProperties(
220
+        PropFind $propFind,
221
+        \Sabre\DAV\INode $node
222
+    ) {
223
+        if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
224
+            return;
225
+        }
226
+
227
+        $propFind->handle(self::ID_PROPERTYNAME, function () use ($node) {
228
+            return $node->getSystemTag()->getId();
229
+        });
230
+
231
+        $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) {
232
+            return $node->getSystemTag()->getName();
233
+        });
234
+
235
+        $propFind->handle(self::USERVISIBLE_PROPERTYNAME, function () use ($node) {
236
+            return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
237
+        });
238
+
239
+        $propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function () use ($node) {
240
+            // this is the tag's inherent property "is user assignable"
241
+            return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
242
+        });
243
+
244
+        $propFind->handle(self::CANASSIGN_PROPERTYNAME, function () use ($node) {
245
+            // this is the effective permission for the current user
246
+            return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
247
+        });
248
+
249
+        $propFind->handle(self::GROUPS_PROPERTYNAME, function () use ($node) {
250
+            if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
251
+                // property only available for admins
252
+                throw new Forbidden();
253
+            }
254
+            $groups = [];
255
+            // no need to retrieve groups for namespaces that don't qualify
256
+            if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
257
+                $groups = $this->tagManager->getTagGroups($node->getSystemTag());
258
+            }
259
+            return implode('|', $groups);
260
+        });
261
+    }
262
+
263
+    /**
264
+     * Updates tag attributes
265
+     *
266
+     * @param string $path
267
+     * @param PropPatch $propPatch
268
+     *
269
+     * @return void
270
+     */
271
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
272
+        $node = $this->server->tree->getNodeForPath($path);
273
+        if (!($node instanceof SystemTagNode)) {
274
+            return;
275
+        }
276
+
277
+        $propPatch->handle([
278
+            self::DISPLAYNAME_PROPERTYNAME,
279
+            self::USERVISIBLE_PROPERTYNAME,
280
+            self::USERASSIGNABLE_PROPERTYNAME,
281
+            self::GROUPS_PROPERTYNAME,
282
+        ], function ($props) use ($node) {
283
+            $tag = $node->getSystemTag();
284
+            $name = $tag->getName();
285
+            $userVisible = $tag->isUserVisible();
286
+            $userAssignable = $tag->isUserAssignable();
287
+
288
+            $updateTag = false;
289
+
290
+            if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
291
+                $name = $props[self::DISPLAYNAME_PROPERTYNAME];
292
+                $updateTag = true;
293
+            }
294
+
295
+            if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
296
+                $propValue = $props[self::USERVISIBLE_PROPERTYNAME];
297
+                $userVisible = ($propValue !== 'false' && $propValue !== '0');
298
+                $updateTag = true;
299
+            }
300
+
301
+            if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
302
+                $propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
303
+                $userAssignable = ($propValue !== 'false' && $propValue !== '0');
304
+                $updateTag = true;
305
+            }
306
+
307
+            if (isset($props[self::GROUPS_PROPERTYNAME])) {
308
+                if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
309
+                    // property only available for admins
310
+                    throw new Forbidden();
311
+                }
312
+
313
+                $propValue = $props[self::GROUPS_PROPERTYNAME];
314
+                $groupIds = explode('|', $propValue);
315
+                $this->tagManager->setTagGroups($tag, $groupIds);
316
+            }
317
+
318
+            if ($updateTag) {
319
+                $node->update($name, $userVisible, $userAssignable);
320
+            }
321
+
322
+            return true;
323
+        });
324
+    }
325 325
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php 2 patches
Indentation   +490 added lines, -490 removed lines patch added patch discarded remove patch
@@ -45,494 +45,494 @@
 block discarded – undo
45 45
 
46 46
 abstract class AbstractPrincipalBackend implements BackendInterface {
47 47
 
48
-	/** @var IDBConnection */
49
-	private $db;
50
-
51
-	/** @var IUserSession */
52
-	private $userSession;
53
-
54
-	/** @var IGroupManager */
55
-	private $groupManager;
56
-
57
-	private LoggerInterface $logger;
58
-
59
-	/** @var ProxyMapper */
60
-	private $proxyMapper;
61
-
62
-	/** @var string */
63
-	private $principalPrefix;
64
-
65
-	/** @var string */
66
-	private $dbTableName;
67
-
68
-	/** @var string */
69
-	private $dbMetaDataTableName;
70
-
71
-	/** @var string */
72
-	private $dbForeignKeyName;
73
-
74
-	/** @var string */
75
-	private $cuType;
76
-
77
-	public function __construct(IDBConnection $dbConnection,
78
-								IUserSession $userSession,
79
-								IGroupManager $groupManager,
80
-								LoggerInterface $logger,
81
-								ProxyMapper $proxyMapper,
82
-								string $principalPrefix,
83
-								string $dbPrefix,
84
-								string $cuType) {
85
-		$this->db = $dbConnection;
86
-		$this->userSession = $userSession;
87
-		$this->groupManager = $groupManager;
88
-		$this->logger = $logger;
89
-		$this->proxyMapper = $proxyMapper;
90
-		$this->principalPrefix = $principalPrefix;
91
-		$this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
-		$this->dbMetaDataTableName = $this->dbTableName . '_md';
93
-		$this->dbForeignKeyName = $dbPrefix . '_id';
94
-		$this->cuType = $cuType;
95
-	}
96
-
97
-	use PrincipalProxyTrait;
98
-
99
-	/**
100
-	 * Returns a list of principals based on a prefix.
101
-	 *
102
-	 * This prefix will often contain something like 'principals'. You are only
103
-	 * expected to return principals that are in this base path.
104
-	 *
105
-	 * You are expected to return at least a 'uri' for every user, you can
106
-	 * return any additional properties if you wish so. Common properties are:
107
-	 *   {DAV:}displayname
108
-	 *
109
-	 * @param string $prefixPath
110
-	 * @return string[]
111
-	 */
112
-	public function getPrincipalsByPrefix($prefixPath): array {
113
-		$principals = [];
114
-
115
-		if ($prefixPath === $this->principalPrefix) {
116
-			$query = $this->db->getQueryBuilder();
117
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
118
-				->from($this->dbTableName);
119
-			$stmt = $query->execute();
120
-
121
-			$metaDataQuery = $this->db->getQueryBuilder();
122
-			$metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value'])
123
-				->from($this->dbMetaDataTableName);
124
-			$metaDataStmt = $metaDataQuery->execute();
125
-			$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
126
-
127
-			$metaDataById = [];
128
-			foreach ($metaDataRows as $metaDataRow) {
129
-				if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
130
-					$metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
131
-				}
132
-
133
-				$metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
134
-					$metaDataRow['value'];
135
-			}
136
-
137
-			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
138
-				$id = $row['id'];
139
-
140
-				if (isset($metaDataById[$id])) {
141
-					$principals[] = $this->rowToPrincipal($row, $metaDataById[$id]);
142
-				} else {
143
-					$principals[] = $this->rowToPrincipal($row);
144
-				}
145
-			}
146
-
147
-			$stmt->closeCursor();
148
-		}
149
-
150
-		return $principals;
151
-	}
152
-
153
-	/**
154
-	 * Returns a specific principal, specified by its path.
155
-	 * The returned structure should be the exact same as from
156
-	 * getPrincipalsByPrefix.
157
-	 *
158
-	 * @param string $prefixPath
159
-	 *
160
-	 * @return array
161
-	 */
162
-	public function getPrincipalByPath($path) {
163
-		if (strpos($path, $this->principalPrefix) !== 0) {
164
-			return null;
165
-		}
166
-		[, $name] = \Sabre\Uri\split($path);
167
-
168
-		[$backendId, $resourceId] = explode('-',  $name, 2);
169
-
170
-		$query = $this->db->getQueryBuilder();
171
-		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
172
-			->from($this->dbTableName)
173
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
174
-			->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
175
-		$stmt = $query->execute();
176
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
177
-
178
-		if (!$row) {
179
-			return null;
180
-		}
181
-
182
-		$metaDataQuery = $this->db->getQueryBuilder();
183
-		$metaDataQuery->select(['key', 'value'])
184
-			->from($this->dbMetaDataTableName)
185
-			->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
186
-		$metaDataStmt = $metaDataQuery->execute();
187
-		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
188
-		$metadata = [];
189
-
190
-		foreach ($metaDataRows as $metaDataRow) {
191
-			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
192
-		}
193
-
194
-		return $this->rowToPrincipal($row, $metadata);
195
-	}
196
-
197
-	/**
198
-	 * @param int $id
199
-	 * @return string[]|null
200
-	 */
201
-	public function getPrincipalById($id): ?array {
202
-		$query = $this->db->getQueryBuilder();
203
-		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
204
-			->from($this->dbTableName)
205
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
206
-		$stmt = $query->execute();
207
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
208
-
209
-		if (!$row) {
210
-			return null;
211
-		}
212
-
213
-		$metaDataQuery = $this->db->getQueryBuilder();
214
-		$metaDataQuery->select(['key', 'value'])
215
-			->from($this->dbMetaDataTableName)
216
-			->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
217
-		$metaDataStmt = $metaDataQuery->execute();
218
-		$metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
219
-		$metadata = [];
220
-
221
-		foreach ($metaDataRows as $metaDataRow) {
222
-			$metadata[$metaDataRow['key']] = $metaDataRow['value'];
223
-		}
224
-
225
-		return $this->rowToPrincipal($row, $metadata);
226
-	}
227
-
228
-	/**
229
-	 * @param string $path
230
-	 * @param PropPatch $propPatch
231
-	 * @return int
232
-	 */
233
-	public function updatePrincipal($path, PropPatch $propPatch): int {
234
-		return 0;
235
-	}
236
-
237
-	/**
238
-	 * @param string $prefixPath
239
-	 * @param string $test
240
-	 *
241
-	 * @return array
242
-	 */
243
-	public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
244
-		$results = [];
245
-		if (\count($searchProperties) === 0) {
246
-			return [];
247
-		}
248
-		if ($prefixPath !== $this->principalPrefix) {
249
-			return [];
250
-		}
251
-
252
-		$user = $this->userSession->getUser();
253
-		if (!$user) {
254
-			return [];
255
-		}
256
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
257
-
258
-		foreach ($searchProperties as $prop => $value) {
259
-			switch ($prop) {
260
-				case '{http://sabredav.org/ns}email-address':
261
-					$query = $this->db->getQueryBuilder();
262
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263
-						->from($this->dbTableName)
264
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
265
-
266
-					$stmt = $query->execute();
267
-					$principals = [];
268
-					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
270
-							continue;
271
-						}
272
-						$principals[] = $this->rowToPrincipal($row)['uri'];
273
-					}
274
-					$results[] = $principals;
275
-
276
-					$stmt->closeCursor();
277
-					break;
278
-
279
-				case '{DAV:}displayname':
280
-					$query = $this->db->getQueryBuilder();
281
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282
-						->from($this->dbTableName)
283
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
284
-
285
-					$stmt = $query->execute();
286
-					$principals = [];
287
-					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
288
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
289
-							continue;
290
-						}
291
-						$principals[] = $this->rowToPrincipal($row)['uri'];
292
-					}
293
-					$results[] = $principals;
294
-
295
-					$stmt->closeCursor();
296
-					break;
297
-
298
-				case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
299
-					// If you add support for more search properties that qualify as a user-address,
300
-					// please also add them to the array below
301
-					$results[] = $this->searchPrincipals($this->principalPrefix, [
302
-						'{http://sabredav.org/ns}email-address' => $value,
303
-					], 'anyof');
304
-					break;
305
-
306
-				case IRoomMetadata::FEATURES:
307
-					$results[] = $this->searchPrincipalsByRoomFeature($prop, $value);
308
-					break;
309
-
310
-				case IRoomMetadata::CAPACITY:
311
-				case IResourceMetadata::VEHICLE_SEATING_CAPACITY:
312
-					$results[] = $this->searchPrincipalsByCapacity($prop,$value);
313
-					break;
314
-
315
-				default:
316
-					$results[] = $this->searchPrincipalsByMetadataKey($prop, $value, $usersGroups);
317
-					break;
318
-			}
319
-		}
320
-
321
-		// results is an array of arrays, so this is not the first search result
322
-		// but the results of the first searchProperty
323
-		if (count($results) === 1) {
324
-			return $results[0];
325
-		}
326
-
327
-		switch ($test) {
328
-			case 'anyof':
329
-				return array_values(array_unique(array_merge(...$results)));
330
-
331
-			case 'allof':
332
-			default:
333
-				return array_values(array_intersect(...$results));
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $key
339
-	 * @return IQueryBuilder
340
-	 */
341
-	private function getMetadataQuery(string $key): IQueryBuilder {
342
-		$query = $this->db->getQueryBuilder();
343
-		$query->select([$this->dbForeignKeyName])
344
-			->from($this->dbMetaDataTableName)
345
-			->where($query->expr()->eq('key', $query->createNamedParameter($key)));
346
-		return $query;
347
-	}
348
-
349
-	/**
350
-	 * Searches principals based on their metadata keys.
351
-	 * This allows to search for all principals with a specific key.
352
-	 * e.g.:
353
-	 * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...'
354
-	 *
355
-	 * @param string $key
356
-	 * @param string $value
357
-	 * @param string[] $usersGroups
358
-	 * @return string[]
359
-	 */
360
-	private function searchPrincipalsByMetadataKey(string $key, string $value, array $usersGroups = []): array {
361
-		$query = $this->getMetadataQuery($key);
362
-		$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
363
-		return $this->getRows($query, $usersGroups);
364
-	}
365
-
366
-	/**
367
-	 * Searches principals based on room features
368
-	 * e.g.:
369
-	 * '{http://nextcloud.com/ns}room-features' => 'TV,PROJECTOR'
370
-	 *
371
-	 * @param string $key
372
-	 * @param string $value
373
-	 * @param string[] $usersGroups
374
-	 * @return string[]
375
-	 */
376
-	private function searchPrincipalsByRoomFeature(string $key, string $value, array $usersGroups = []): array {
377
-		$query = $this->getMetadataQuery($key);
378
-		foreach (explode(',', $value) as $v) {
379
-			$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($v) . '%')));
380
-		}
381
-		return $this->getRows($query, $usersGroups);
382
-	}
383
-
384
-	/**
385
-	 * Searches principals based on room seating capacity or vehicle capacity
386
-	 * e.g.:
387
-	 * '{http://nextcloud.com/ns}room-seating-capacity' => '100'
388
-	 *
389
-	 * @param string $key
390
-	 * @param string $value
391
-	 * @param string[] $usersGroups
392
-	 * @return string[]
393
-	 */
394
-	private function searchPrincipalsByCapacity(string $key, string $value, array $usersGroups = []): array {
395
-		$query = $this->getMetadataQuery($key);
396
-		$query->andWhere($query->expr()->gte('value', $query->createNamedParameter($value)));
397
-		return $this->getRows($query, $usersGroups);
398
-	}
399
-
400
-	/**
401
-	 * @param IQueryBuilder $query
402
-	 * @param string[] $usersGroups
403
-	 * @return string[]
404
-	 */
405
-	private function getRows(IQueryBuilder $query, array $usersGroups): array {
406
-		try {
407
-			$stmt = $query->executeQuery();
408
-		} catch (Exception $e) {
409
-			$this->logger->error("Could not search resources: " . $e->getMessage(), ['exception' => $e]);
410
-		}
411
-
412
-		$rows = [];
413
-		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
414
-			$principalRow = $this->getPrincipalById($row[$this->dbForeignKeyName]);
415
-			if (!$principalRow) {
416
-				continue;
417
-			}
418
-
419
-			$rows[] = $principalRow;
420
-		}
421
-
422
-		$stmt->closeCursor();
423
-
424
-		$filteredRows = array_filter($rows, function ($row) use ($usersGroups) {
425
-			return $this->isAllowedToAccessResource($row, $usersGroups);
426
-		});
427
-
428
-		return array_map(static function ($row): string {
429
-			return $row['uri'];
430
-		}, $filteredRows);
431
-	}
432
-
433
-	/**
434
-	 * @param string $uri
435
-	 * @param string $principalPrefix
436
-	 * @return null|string
437
-	 * @throws Exception
438
-	 */
439
-	public function findByUri($uri, $principalPrefix): ?string {
440
-		$user = $this->userSession->getUser();
441
-		if (!$user) {
442
-			return null;
443
-		}
444
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
445
-
446
-		if (strpos($uri, 'mailto:') === 0) {
447
-			$email = substr($uri, 7);
448
-			$query = $this->db->getQueryBuilder();
449
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
450
-				->from($this->dbTableName)
451
-				->where($query->expr()->eq('email', $query->createNamedParameter($email)));
452
-
453
-			$stmt = $query->execute();
454
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
455
-
456
-			if (!$row) {
457
-				return null;
458
-			}
459
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
460
-				return null;
461
-			}
462
-
463
-			return $this->rowToPrincipal($row)['uri'];
464
-		}
465
-
466
-		if (strpos($uri, 'principal:') === 0) {
467
-			$path = substr($uri, 10);
468
-			if (strpos($path, $this->principalPrefix) !== 0) {
469
-				return null;
470
-			}
471
-
472
-			[, $name] = \Sabre\Uri\split($path);
473
-			[$backendId, $resourceId] = explode('-',  $name, 2);
474
-
475
-			$query = $this->db->getQueryBuilder();
476
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
477
-				->from($this->dbTableName)
478
-				->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
479
-				->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
480
-			$stmt = $query->execute();
481
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
482
-
483
-			if (!$row) {
484
-				return null;
485
-			}
486
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
487
-				return null;
488
-			}
489
-
490
-			return $this->rowToPrincipal($row)['uri'];
491
-		}
492
-
493
-		return null;
494
-	}
495
-
496
-	/**
497
-	 * convert database row to principal
498
-	 *
499
-	 * @param string[] $row
500
-	 * @param string[] $metadata
501
-	 * @return string[]
502
-	 */
503
-	private function rowToPrincipal(array $row, array $metadata = []): array {
504
-		return array_merge([
505
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
506
-			'{DAV:}displayname' => $row['displayname'],
507
-			'{http://sabredav.org/ns}email-address' => $row['email'],
508
-			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
509
-		], $metadata);
510
-	}
511
-
512
-	/**
513
-	 * @param array $row
514
-	 * @param array $userGroups
515
-	 * @return bool
516
-	 */
517
-	private function isAllowedToAccessResource(array $row, array $userGroups): bool {
518
-		if (!isset($row['group_restrictions']) ||
519
-			$row['group_restrictions'] === null ||
520
-			$row['group_restrictions'] === '') {
521
-			return true;
522
-		}
523
-
524
-		// group restrictions contains something, but not parsable, deny access and log warning
525
-		$json = json_decode($row['group_restrictions'], null, 512, JSON_THROW_ON_ERROR);
526
-		if (!\is_array($json)) {
527
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
528
-			return false;
529
-		}
530
-
531
-		// empty array => no group restrictions
532
-		if (empty($json)) {
533
-			return true;
534
-		}
535
-
536
-		return !empty(array_intersect($json, $userGroups));
537
-	}
48
+    /** @var IDBConnection */
49
+    private $db;
50
+
51
+    /** @var IUserSession */
52
+    private $userSession;
53
+
54
+    /** @var IGroupManager */
55
+    private $groupManager;
56
+
57
+    private LoggerInterface $logger;
58
+
59
+    /** @var ProxyMapper */
60
+    private $proxyMapper;
61
+
62
+    /** @var string */
63
+    private $principalPrefix;
64
+
65
+    /** @var string */
66
+    private $dbTableName;
67
+
68
+    /** @var string */
69
+    private $dbMetaDataTableName;
70
+
71
+    /** @var string */
72
+    private $dbForeignKeyName;
73
+
74
+    /** @var string */
75
+    private $cuType;
76
+
77
+    public function __construct(IDBConnection $dbConnection,
78
+                                IUserSession $userSession,
79
+                                IGroupManager $groupManager,
80
+                                LoggerInterface $logger,
81
+                                ProxyMapper $proxyMapper,
82
+                                string $principalPrefix,
83
+                                string $dbPrefix,
84
+                                string $cuType) {
85
+        $this->db = $dbConnection;
86
+        $this->userSession = $userSession;
87
+        $this->groupManager = $groupManager;
88
+        $this->logger = $logger;
89
+        $this->proxyMapper = $proxyMapper;
90
+        $this->principalPrefix = $principalPrefix;
91
+        $this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
+        $this->dbMetaDataTableName = $this->dbTableName . '_md';
93
+        $this->dbForeignKeyName = $dbPrefix . '_id';
94
+        $this->cuType = $cuType;
95
+    }
96
+
97
+    use PrincipalProxyTrait;
98
+
99
+    /**
100
+     * Returns a list of principals based on a prefix.
101
+     *
102
+     * This prefix will often contain something like 'principals'. You are only
103
+     * expected to return principals that are in this base path.
104
+     *
105
+     * You are expected to return at least a 'uri' for every user, you can
106
+     * return any additional properties if you wish so. Common properties are:
107
+     *   {DAV:}displayname
108
+     *
109
+     * @param string $prefixPath
110
+     * @return string[]
111
+     */
112
+    public function getPrincipalsByPrefix($prefixPath): array {
113
+        $principals = [];
114
+
115
+        if ($prefixPath === $this->principalPrefix) {
116
+            $query = $this->db->getQueryBuilder();
117
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
118
+                ->from($this->dbTableName);
119
+            $stmt = $query->execute();
120
+
121
+            $metaDataQuery = $this->db->getQueryBuilder();
122
+            $metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value'])
123
+                ->from($this->dbMetaDataTableName);
124
+            $metaDataStmt = $metaDataQuery->execute();
125
+            $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
126
+
127
+            $metaDataById = [];
128
+            foreach ($metaDataRows as $metaDataRow) {
129
+                if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
130
+                    $metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
131
+                }
132
+
133
+                $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
134
+                    $metaDataRow['value'];
135
+            }
136
+
137
+            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
138
+                $id = $row['id'];
139
+
140
+                if (isset($metaDataById[$id])) {
141
+                    $principals[] = $this->rowToPrincipal($row, $metaDataById[$id]);
142
+                } else {
143
+                    $principals[] = $this->rowToPrincipal($row);
144
+                }
145
+            }
146
+
147
+            $stmt->closeCursor();
148
+        }
149
+
150
+        return $principals;
151
+    }
152
+
153
+    /**
154
+     * Returns a specific principal, specified by its path.
155
+     * The returned structure should be the exact same as from
156
+     * getPrincipalsByPrefix.
157
+     *
158
+     * @param string $prefixPath
159
+     *
160
+     * @return array
161
+     */
162
+    public function getPrincipalByPath($path) {
163
+        if (strpos($path, $this->principalPrefix) !== 0) {
164
+            return null;
165
+        }
166
+        [, $name] = \Sabre\Uri\split($path);
167
+
168
+        [$backendId, $resourceId] = explode('-',  $name, 2);
169
+
170
+        $query = $this->db->getQueryBuilder();
171
+        $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
172
+            ->from($this->dbTableName)
173
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
174
+            ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
175
+        $stmt = $query->execute();
176
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
177
+
178
+        if (!$row) {
179
+            return null;
180
+        }
181
+
182
+        $metaDataQuery = $this->db->getQueryBuilder();
183
+        $metaDataQuery->select(['key', 'value'])
184
+            ->from($this->dbMetaDataTableName)
185
+            ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
186
+        $metaDataStmt = $metaDataQuery->execute();
187
+        $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
188
+        $metadata = [];
189
+
190
+        foreach ($metaDataRows as $metaDataRow) {
191
+            $metadata[$metaDataRow['key']] = $metaDataRow['value'];
192
+        }
193
+
194
+        return $this->rowToPrincipal($row, $metadata);
195
+    }
196
+
197
+    /**
198
+     * @param int $id
199
+     * @return string[]|null
200
+     */
201
+    public function getPrincipalById($id): ?array {
202
+        $query = $this->db->getQueryBuilder();
203
+        $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
204
+            ->from($this->dbTableName)
205
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
206
+        $stmt = $query->execute();
207
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
208
+
209
+        if (!$row) {
210
+            return null;
211
+        }
212
+
213
+        $metaDataQuery = $this->db->getQueryBuilder();
214
+        $metaDataQuery->select(['key', 'value'])
215
+            ->from($this->dbMetaDataTableName)
216
+            ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
217
+        $metaDataStmt = $metaDataQuery->execute();
218
+        $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
219
+        $metadata = [];
220
+
221
+        foreach ($metaDataRows as $metaDataRow) {
222
+            $metadata[$metaDataRow['key']] = $metaDataRow['value'];
223
+        }
224
+
225
+        return $this->rowToPrincipal($row, $metadata);
226
+    }
227
+
228
+    /**
229
+     * @param string $path
230
+     * @param PropPatch $propPatch
231
+     * @return int
232
+     */
233
+    public function updatePrincipal($path, PropPatch $propPatch): int {
234
+        return 0;
235
+    }
236
+
237
+    /**
238
+     * @param string $prefixPath
239
+     * @param string $test
240
+     *
241
+     * @return array
242
+     */
243
+    public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
244
+        $results = [];
245
+        if (\count($searchProperties) === 0) {
246
+            return [];
247
+        }
248
+        if ($prefixPath !== $this->principalPrefix) {
249
+            return [];
250
+        }
251
+
252
+        $user = $this->userSession->getUser();
253
+        if (!$user) {
254
+            return [];
255
+        }
256
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
257
+
258
+        foreach ($searchProperties as $prop => $value) {
259
+            switch ($prop) {
260
+                case '{http://sabredav.org/ns}email-address':
261
+                    $query = $this->db->getQueryBuilder();
262
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263
+                        ->from($this->dbTableName)
264
+                        ->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
265
+
266
+                    $stmt = $query->execute();
267
+                    $principals = [];
268
+                    while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
270
+                            continue;
271
+                        }
272
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
273
+                    }
274
+                    $results[] = $principals;
275
+
276
+                    $stmt->closeCursor();
277
+                    break;
278
+
279
+                case '{DAV:}displayname':
280
+                    $query = $this->db->getQueryBuilder();
281
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282
+                        ->from($this->dbTableName)
283
+                        ->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
284
+
285
+                    $stmt = $query->execute();
286
+                    $principals = [];
287
+                    while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
288
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
289
+                            continue;
290
+                        }
291
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
292
+                    }
293
+                    $results[] = $principals;
294
+
295
+                    $stmt->closeCursor();
296
+                    break;
297
+
298
+                case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
299
+                    // If you add support for more search properties that qualify as a user-address,
300
+                    // please also add them to the array below
301
+                    $results[] = $this->searchPrincipals($this->principalPrefix, [
302
+                        '{http://sabredav.org/ns}email-address' => $value,
303
+                    ], 'anyof');
304
+                    break;
305
+
306
+                case IRoomMetadata::FEATURES:
307
+                    $results[] = $this->searchPrincipalsByRoomFeature($prop, $value);
308
+                    break;
309
+
310
+                case IRoomMetadata::CAPACITY:
311
+                case IResourceMetadata::VEHICLE_SEATING_CAPACITY:
312
+                    $results[] = $this->searchPrincipalsByCapacity($prop,$value);
313
+                    break;
314
+
315
+                default:
316
+                    $results[] = $this->searchPrincipalsByMetadataKey($prop, $value, $usersGroups);
317
+                    break;
318
+            }
319
+        }
320
+
321
+        // results is an array of arrays, so this is not the first search result
322
+        // but the results of the first searchProperty
323
+        if (count($results) === 1) {
324
+            return $results[0];
325
+        }
326
+
327
+        switch ($test) {
328
+            case 'anyof':
329
+                return array_values(array_unique(array_merge(...$results)));
330
+
331
+            case 'allof':
332
+            default:
333
+                return array_values(array_intersect(...$results));
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $key
339
+     * @return IQueryBuilder
340
+     */
341
+    private function getMetadataQuery(string $key): IQueryBuilder {
342
+        $query = $this->db->getQueryBuilder();
343
+        $query->select([$this->dbForeignKeyName])
344
+            ->from($this->dbMetaDataTableName)
345
+            ->where($query->expr()->eq('key', $query->createNamedParameter($key)));
346
+        return $query;
347
+    }
348
+
349
+    /**
350
+     * Searches principals based on their metadata keys.
351
+     * This allows to search for all principals with a specific key.
352
+     * e.g.:
353
+     * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...'
354
+     *
355
+     * @param string $key
356
+     * @param string $value
357
+     * @param string[] $usersGroups
358
+     * @return string[]
359
+     */
360
+    private function searchPrincipalsByMetadataKey(string $key, string $value, array $usersGroups = []): array {
361
+        $query = $this->getMetadataQuery($key);
362
+        $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
363
+        return $this->getRows($query, $usersGroups);
364
+    }
365
+
366
+    /**
367
+     * Searches principals based on room features
368
+     * e.g.:
369
+     * '{http://nextcloud.com/ns}room-features' => 'TV,PROJECTOR'
370
+     *
371
+     * @param string $key
372
+     * @param string $value
373
+     * @param string[] $usersGroups
374
+     * @return string[]
375
+     */
376
+    private function searchPrincipalsByRoomFeature(string $key, string $value, array $usersGroups = []): array {
377
+        $query = $this->getMetadataQuery($key);
378
+        foreach (explode(',', $value) as $v) {
379
+            $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($v) . '%')));
380
+        }
381
+        return $this->getRows($query, $usersGroups);
382
+    }
383
+
384
+    /**
385
+     * Searches principals based on room seating capacity or vehicle capacity
386
+     * e.g.:
387
+     * '{http://nextcloud.com/ns}room-seating-capacity' => '100'
388
+     *
389
+     * @param string $key
390
+     * @param string $value
391
+     * @param string[] $usersGroups
392
+     * @return string[]
393
+     */
394
+    private function searchPrincipalsByCapacity(string $key, string $value, array $usersGroups = []): array {
395
+        $query = $this->getMetadataQuery($key);
396
+        $query->andWhere($query->expr()->gte('value', $query->createNamedParameter($value)));
397
+        return $this->getRows($query, $usersGroups);
398
+    }
399
+
400
+    /**
401
+     * @param IQueryBuilder $query
402
+     * @param string[] $usersGroups
403
+     * @return string[]
404
+     */
405
+    private function getRows(IQueryBuilder $query, array $usersGroups): array {
406
+        try {
407
+            $stmt = $query->executeQuery();
408
+        } catch (Exception $e) {
409
+            $this->logger->error("Could not search resources: " . $e->getMessage(), ['exception' => $e]);
410
+        }
411
+
412
+        $rows = [];
413
+        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
414
+            $principalRow = $this->getPrincipalById($row[$this->dbForeignKeyName]);
415
+            if (!$principalRow) {
416
+                continue;
417
+            }
418
+
419
+            $rows[] = $principalRow;
420
+        }
421
+
422
+        $stmt->closeCursor();
423
+
424
+        $filteredRows = array_filter($rows, function ($row) use ($usersGroups) {
425
+            return $this->isAllowedToAccessResource($row, $usersGroups);
426
+        });
427
+
428
+        return array_map(static function ($row): string {
429
+            return $row['uri'];
430
+        }, $filteredRows);
431
+    }
432
+
433
+    /**
434
+     * @param string $uri
435
+     * @param string $principalPrefix
436
+     * @return null|string
437
+     * @throws Exception
438
+     */
439
+    public function findByUri($uri, $principalPrefix): ?string {
440
+        $user = $this->userSession->getUser();
441
+        if (!$user) {
442
+            return null;
443
+        }
444
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
445
+
446
+        if (strpos($uri, 'mailto:') === 0) {
447
+            $email = substr($uri, 7);
448
+            $query = $this->db->getQueryBuilder();
449
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
450
+                ->from($this->dbTableName)
451
+                ->where($query->expr()->eq('email', $query->createNamedParameter($email)));
452
+
453
+            $stmt = $query->execute();
454
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
455
+
456
+            if (!$row) {
457
+                return null;
458
+            }
459
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
460
+                return null;
461
+            }
462
+
463
+            return $this->rowToPrincipal($row)['uri'];
464
+        }
465
+
466
+        if (strpos($uri, 'principal:') === 0) {
467
+            $path = substr($uri, 10);
468
+            if (strpos($path, $this->principalPrefix) !== 0) {
469
+                return null;
470
+            }
471
+
472
+            [, $name] = \Sabre\Uri\split($path);
473
+            [$backendId, $resourceId] = explode('-',  $name, 2);
474
+
475
+            $query = $this->db->getQueryBuilder();
476
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
477
+                ->from($this->dbTableName)
478
+                ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
479
+                ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
480
+            $stmt = $query->execute();
481
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
482
+
483
+            if (!$row) {
484
+                return null;
485
+            }
486
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
487
+                return null;
488
+            }
489
+
490
+            return $this->rowToPrincipal($row)['uri'];
491
+        }
492
+
493
+        return null;
494
+    }
495
+
496
+    /**
497
+     * convert database row to principal
498
+     *
499
+     * @param string[] $row
500
+     * @param string[] $metadata
501
+     * @return string[]
502
+     */
503
+    private function rowToPrincipal(array $row, array $metadata = []): array {
504
+        return array_merge([
505
+            'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
506
+            '{DAV:}displayname' => $row['displayname'],
507
+            '{http://sabredav.org/ns}email-address' => $row['email'],
508
+            '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
509
+        ], $metadata);
510
+    }
511
+
512
+    /**
513
+     * @param array $row
514
+     * @param array $userGroups
515
+     * @return bool
516
+     */
517
+    private function isAllowedToAccessResource(array $row, array $userGroups): bool {
518
+        if (!isset($row['group_restrictions']) ||
519
+            $row['group_restrictions'] === null ||
520
+            $row['group_restrictions'] === '') {
521
+            return true;
522
+        }
523
+
524
+        // group restrictions contains something, but not parsable, deny access and log warning
525
+        $json = json_decode($row['group_restrictions'], null, 512, JSON_THROW_ON_ERROR);
526
+        if (!\is_array($json)) {
527
+            $this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
528
+            return false;
529
+        }
530
+
531
+        // empty array => no group restrictions
532
+        if (empty($json)) {
533
+            return true;
534
+        }
535
+
536
+        return !empty(array_intersect($json, $userGroups));
537
+    }
538 538
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -88,9 +88,9 @@  discard block
 block discarded – undo
88 88
 		$this->logger = $logger;
89 89
 		$this->proxyMapper = $proxyMapper;
90 90
 		$this->principalPrefix = $principalPrefix;
91
-		$this->dbTableName = 'calendar_' . $dbPrefix . 's';
92
-		$this->dbMetaDataTableName = $this->dbTableName . '_md';
93
-		$this->dbForeignKeyName = $dbPrefix . '_id';
91
+		$this->dbTableName = 'calendar_'.$dbPrefix.'s';
92
+		$this->dbMetaDataTableName = $this->dbTableName.'_md';
93
+		$this->dbForeignKeyName = $dbPrefix.'_id';
94 94
 		$this->cuType = $cuType;
95 95
 	}
96 96
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		}
166 166
 		[, $name] = \Sabre\Uri\split($path);
167 167
 
168
-		[$backendId, $resourceId] = explode('-',  $name, 2);
168
+		[$backendId, $resourceId] = explode('-', $name, 2);
169 169
 
170 170
 		$query = $this->db->getQueryBuilder();
171 171
 		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 					$query = $this->db->getQueryBuilder();
262 262
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
263 263
 						->from($this->dbTableName)
264
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
264
+						->where($query->expr()->iLike('email', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
265 265
 
266 266
 					$stmt = $query->execute();
267 267
 					$principals = [];
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 					$query = $this->db->getQueryBuilder();
281 281
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
282 282
 						->from($this->dbTableName)
283
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
283
+						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
284 284
 
285 285
 					$stmt = $query->execute();
286 286
 					$principals = [];
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 
310 310
 				case IRoomMetadata::CAPACITY:
311 311
 				case IResourceMetadata::VEHICLE_SEATING_CAPACITY:
312
-					$results[] = $this->searchPrincipalsByCapacity($prop,$value);
312
+					$results[] = $this->searchPrincipalsByCapacity($prop, $value);
313 313
 					break;
314 314
 
315 315
 				default:
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 	 */
360 360
 	private function searchPrincipalsByMetadataKey(string $key, string $value, array $usersGroups = []): array {
361 361
 		$query = $this->getMetadataQuery($key);
362
-		$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
362
+		$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
363 363
 		return $this->getRows($query, $usersGroups);
364 364
 	}
365 365
 
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 	private function searchPrincipalsByRoomFeature(string $key, string $value, array $usersGroups = []): array {
377 377
 		$query = $this->getMetadataQuery($key);
378 378
 		foreach (explode(',', $value) as $v) {
379
-			$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($v) . '%')));
379
+			$query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($v).'%')));
380 380
 		}
381 381
 		return $this->getRows($query, $usersGroups);
382 382
 	}
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 		try {
407 407
 			$stmt = $query->executeQuery();
408 408
 		} catch (Exception $e) {
409
-			$this->logger->error("Could not search resources: " . $e->getMessage(), ['exception' => $e]);
409
+			$this->logger->error("Could not search resources: ".$e->getMessage(), ['exception' => $e]);
410 410
 		}
411 411
 
412 412
 		$rows = [];
@@ -421,11 +421,11 @@  discard block
 block discarded – undo
421 421
 
422 422
 		$stmt->closeCursor();
423 423
 
424
-		$filteredRows = array_filter($rows, function ($row) use ($usersGroups) {
424
+		$filteredRows = array_filter($rows, function($row) use ($usersGroups) {
425 425
 			return $this->isAllowedToAccessResource($row, $usersGroups);
426 426
 		});
427 427
 
428
-		return array_map(static function ($row): string {
428
+		return array_map(static function($row): string {
429 429
 			return $row['uri'];
430 430
 		}, $filteredRows);
431 431
 	}
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 			}
471 471
 
472 472
 			[, $name] = \Sabre\Uri\split($path);
473
-			[$backendId, $resourceId] = explode('-',  $name, 2);
473
+			[$backendId, $resourceId] = explode('-', $name, 2);
474 474
 
475 475
 			$query = $this->db->getQueryBuilder();
476 476
 			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	private function rowToPrincipal(array $row, array $metadata = []): array {
504 504
 		return array_merge([
505
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
505
+			'uri' => $this->principalPrefix.'/'.$row['backend_id'].'-'.$row['resource_id'],
506 506
 			'{DAV:}displayname' => $row['displayname'],
507 507
 			'{http://sabredav.org/ns}email-address' => $row['email'],
508 508
 			'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 		// group restrictions contains something, but not parsable, deny access and log warning
525 525
 		$json = json_decode($row['group_restrictions'], null, 512, JSON_THROW_ON_ERROR);
526 526
 		if (!\is_array($json)) {
527
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
527
+			$this->logger->info('group_restrictions field could not be parsed for '.$this->dbTableName.'::'.$row['id'].', denying access to resource');
528 528
 			return false;
529 529
 		}
530 530
 
Please login to merge, or discard this patch.
apps/dav/lib/UserMigration/ContactsMigrator.php 1 patch
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -54,361 +54,361 @@
 block discarded – undo
54 54
 
55 55
 class ContactsMigrator implements IMigrator, ISizeEstimationMigrator {
56 56
 
57
-	use TMigratorBasicVersionHandling;
58
-
59
-	private CardDavBackend $cardDavBackend;
60
-
61
-	private IL10N $l10n;
62
-
63
-	private SabreDavServer $sabreDavServer;
64
-
65
-	private const USERS_URI_ROOT = 'principals/users/';
66
-
67
-	private const FILENAME_EXT = 'vcf';
68
-
69
-	private const METADATA_EXT = 'json';
70
-
71
-	private const MIGRATED_URI_PREFIX = 'migrated-';
72
-
73
-	private const PATH_ROOT = Application::APP_ID . '/address_books/';
74
-
75
-	public function __construct(
76
-		CardDavBackend $cardDavBackend,
77
-		IL10N $l10n
78
-	) {
79
-		$this->cardDavBackend = $cardDavBackend;
80
-		$this->l10n = $l10n;
81
-
82
-		$root = new RootCollection();
83
-		$this->sabreDavServer = new SabreDavServer(new CachingTree($root));
84
-		$this->sabreDavServer->addPlugin(new CardDAVPlugin());
85
-	}
86
-
87
-	private function getPrincipalUri(IUser $user): string {
88
-		return ContactsMigrator::USERS_URI_ROOT . $user->getUID();
89
-	}
90
-
91
-	/**
92
-	 * @return array{name: string, displayName: string, description: ?string, vCards: VCard[]}
93
-	 *
94
-	 * @throws InvalidAddressBookException
95
-	 */
96
-	private function getAddressBookExportData(IUser $user, array $addressBookInfo, OutputInterface $output): array {
97
-		$userId = $user->getUID();
98
-
99
-		if (!isset($addressBookInfo['uri'])) {
100
-			throw new InvalidAddressBookException();
101
-		}
102
-
103
-		$uri = $addressBookInfo['uri'];
104
-
105
-		$path = CardDAVPlugin::ADDRESSBOOK_ROOT . "/users/$userId/$uri";
106
-
107
-		/**
108
-		 * @see \Sabre\CardDAV\VCFExportPlugin::httpGet() implementation reference
109
-		 */
110
-
111
-		$addressBookDataProp = '{' . CardDAVPlugin::NS_CARDDAV . '}address-data';
112
-		$addressBookNode = $this->sabreDavServer->tree->getNodeForPath($path);
113
-		$nodes = $this->sabreDavServer->getPropertiesIteratorForPath($path, [$addressBookDataProp], 1);
114
-
115
-		/**
116
-		 * @see \Sabre\CardDAV\VCFExportPlugin::generateVCF() implementation reference
117
-		 */
118
-
119
-		/** @var VCard[] $vCards */
120
-		$vCards = [];
121
-		foreach ($nodes as $node) {
122
-			if (isset($node[200][$addressBookDataProp])) {
123
-				$vCard = VObjectReader::read($node[200][$addressBookDataProp]);
124
-
125
-				$problems = $vCard->validate();
126
-				if (!empty($problems)) {
127
-					$output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
128
-					continue;
129
-				}
130
-				$vCards[] = $vCard;
131
-			}
132
-		}
133
-
134
-		if (count($vCards) === 0) {
135
-			throw new InvalidAddressBookException();
136
-		}
137
-
138
-		return [
139
-			'name' => $addressBookNode->getName(),
140
-			'displayName' => $addressBookInfo['{DAV:}displayname'],
141
-			'description' => $addressBookInfo['{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description'],
142
-			'vCards' => $vCards,
143
-		];
144
-	}
145
-
146
-	/**
147
-	 * @return array<int, array{name: string, displayName: string, description: ?string, vCards: VCard[]}>
148
-	 */
149
-	private function getAddressBookExports(IUser $user, OutputInterface $output): array {
150
-		$principalUri = $this->getPrincipalUri($user);
151
-
152
-		return array_values(array_filter(array_map(
153
-			function (array $addressBookInfo) use ($user, $output) {
154
-				try {
155
-					return $this->getAddressBookExportData($user, $addressBookInfo, $output);
156
-				} catch (InvalidAddressBookException $e) {
157
-					// Allow this exception as invalid address books are not to be exported
158
-					return null;
159
-				}
160
-			},
161
-			$this->cardDavBackend->getAddressBooksForUser($principalUri),
162
-		)));
163
-	}
164
-
165
-	private function getUniqueAddressBookUri(IUser $user, string $initialAddressBookUri): string {
166
-		$principalUri = $this->getPrincipalUri($user);
167
-
168
-		try {
169
-			$initialAddressBookUri = substr($initialAddressBookUri, 0, strlen(ContactsMigrator::MIGRATED_URI_PREFIX)) === ContactsMigrator::MIGRATED_URI_PREFIX
170
-				? $initialAddressBookUri
171
-				: ContactsMigrator::MIGRATED_URI_PREFIX . $initialAddressBookUri;
172
-		} catch (StringsException $e) {
173
-			throw new ContactsMigratorException('Failed to get unique address book URI', 0, $e);
174
-		}
175
-
176
-		$existingAddressBookUris = array_map(
177
-			fn (array $addressBookInfo): string => $addressBookInfo['uri'],
178
-			$this->cardDavBackend->getAddressBooksForUser($principalUri),
179
-		);
180
-
181
-		$addressBookUri = $initialAddressBookUri;
182
-		$acc = 1;
183
-		while (in_array($addressBookUri, $existingAddressBookUris, true)) {
184
-			$addressBookUri = $initialAddressBookUri . "-$acc";
185
-			++$acc;
186
-		}
187
-
188
-		return $addressBookUri;
189
-	}
190
-
191
-	/**
192
-	 * @param VCard[] $vCards
193
-	 */
194
-	private function serializeCards(array $vCards): string {
195
-		return array_reduce(
196
-			$vCards,
197
-			fn (string $addressBookBlob, VCard $vCard) => $addressBookBlob . $vCard->serialize(),
198
-			'',
199
-		);
200
-	}
201
-
202
-	/**
203
-	 * {@inheritDoc}
204
-	 */
205
-	public function getEstimatedExportSize(IUser $user): int {
206
-		$addressBookExports = $this->getAddressBookExports($user, new NullOutput());
207
-		$addressBookCount = count($addressBookExports);
208
-
209
-		// 50B for each metadata JSON
210
-		$size = ($addressBookCount * 50) / 1024;
211
-
212
-		$contactsCount = array_sum(array_map(
213
-			fn (array $data): int => count($data['vCards']),
214
-			$addressBookExports,
215
-		));
216
-
217
-		// 350B for each contact
218
-		$size += ($contactsCount * 350) / 1024;
219
-
220
-		return (int)ceil($size);
221
-	}
222
-
223
-	/**
224
-	 * {@inheritDoc}
225
-	 */
226
-	public function export(IUser $user, IExportDestination $exportDestination, OutputInterface $output): void {
227
-		$output->writeln('Exporting contacts into ' . ContactsMigrator::PATH_ROOT . '…');
228
-
229
-		$addressBookExports = $this->getAddressBookExports($user, $output);
230
-
231
-		if (empty($addressBookExports)) {
232
-			$output->writeln('No contacts to export…');
233
-		}
234
-
235
-		try {
236
-			/**
237
-			 * @var string $name
238
-			 * @var string $displayName
239
-			 * @var ?string $description
240
-			 * @var VCard[] $vCards
241
-			 */
242
-			foreach ($addressBookExports as ['name' => $name, 'displayName' => $displayName, 'description' => $description, 'vCards' => $vCards]) {
243
-				// Set filename to sanitized address book name
244
-				$basename = preg_replace('/[^a-z0-9-_]/iu', '', $name);
245
-				$exportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::FILENAME_EXT;
246
-				$metadataExportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::METADATA_EXT;
247
-
248
-				$exportDestination->addFileContents($exportPath, $this->serializeCards($vCards));
249
-
250
-				$metadata = array_filter(['displayName' => $displayName, 'description' => $description]);
251
-				$exportDestination->addFileContents($metadataExportPath, json_encode($metadata, JSON_THROW_ON_ERROR));
252
-			}
253
-		} catch (Throwable $e) {
254
-			throw new CalendarMigratorException('Could not export address book', 0, $e);
255
-		}
256
-	}
257
-
258
-	private function importContact(int $addressBookId, VCard $vCard, string $filename, OutputInterface $output): void {
259
-		// Operate on clone to prevent mutation of the original
260
-		$vCard = clone $vCard;
261
-		$vCard->PRODID = '-//IDN nextcloud.com//Migrated contact//EN';
262
-
263
-		try {
264
-			$this->cardDavBackend->createCard(
265
-				$addressBookId,
266
-				UUIDUtil::getUUID() . '.' . ContactsMigrator::FILENAME_EXT,
267
-				$vCard->serialize(),
268
-			);
269
-		} catch (Throwable $e) {
270
-			$output->writeln("Error creating contact \"" . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…");
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * @param array{displayName: string, description?: string} $metadata
276
-	 * @param VCard[] $vCards
277
-	 */
278
-	private function importAddressBook(IUser $user, string $filename, string $initialAddressBookUri, array $metadata, array $vCards, OutputInterface $output): void {
279
-		$principalUri = $this->getPrincipalUri($user);
280
-		$addressBookUri = $this->getUniqueAddressBookUri($user, $initialAddressBookUri);
281
-
282
-		$addressBookId = $this->cardDavBackend->createAddressBook($principalUri, $addressBookUri, array_filter([
283
-			'{DAV:}displayname' => $metadata['displayName'],
284
-			'{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description' => $metadata['description'] ?? null,
285
-		]));
286
-
287
-		foreach ($vCards as $vCard) {
288
-			$this->importContact($addressBookId, $vCard, $filename, $output);
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * @return array<int, array{addressBook: string, metadata: string}>
294
-	 */
295
-	private function getAddressBookImports(array $importFiles): array {
296
-		$addressBookImports = array_filter(
297
-			$importFiles,
298
-			fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::FILENAME_EXT,
299
-		);
300
-
301
-		$metadataImports = array_filter(
302
-			$importFiles,
303
-			fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::METADATA_EXT,
304
-		);
305
-
306
-		try {
307
-			sort($addressBookImports);
308
-			sort($metadataImports);
309
-		} catch (ArrayException $e) {
310
-			throw new ContactsMigratorException('Failed to sort address book files in ' . ContactsMigrator::PATH_ROOT, 0, $e);
311
-		}
312
-
313
-		if (count($addressBookImports) !== count($metadataImports)) {
314
-			throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
315
-		}
316
-
317
-		for ($i = 0; $i < count($addressBookImports); ++$i) {
318
-			if (pathinfo($addressBookImports[$i], PATHINFO_FILENAME) !== pathinfo($metadataImports[$i], PATHINFO_FILENAME)) {
319
-				throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
320
-			}
321
-		}
322
-
323
-		return array_map(
324
-			fn (string $addressBookFilename, string $metadataFilename) => ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename],
325
-			$addressBookImports,
326
-			$metadataImports,
327
-		);
328
-	}
329
-
330
-	/**
331
-	 * {@inheritDoc}
332
-	 *
333
-	 * @throws ContactsMigratorException
334
-	 */
335
-	public function import(IUser $user, IImportSource $importSource, OutputInterface $output): void {
336
-		if ($importSource->getMigratorVersion($this->getId()) === null) {
337
-			$output->writeln('No version for ' . static::class . ', skipping import…');
338
-			return;
339
-		}
340
-
341
-		$output->writeln('Importing contacts from ' . ContactsMigrator::PATH_ROOT . '…');
342
-
343
-		$importFiles = $importSource->getFolderListing(ContactsMigrator::PATH_ROOT);
344
-
345
-		if (empty($importFiles)) {
346
-			$output->writeln('No contacts to import…');
347
-		}
348
-
349
-		foreach ($this->getAddressBookImports($importFiles) as ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename]) {
350
-			$addressBookImportPath = ContactsMigrator::PATH_ROOT . $addressBookFilename;
351
-			$metadataImportPath = ContactsMigrator::PATH_ROOT . $metadataFilename;
352
-
353
-			$vCardSplitter = new VCardSplitter(
354
-				$importSource->getFileAsStream($addressBookImportPath),
355
-				VObjectParser::OPTION_FORGIVING,
356
-			);
357
-
358
-			/** @var VCard[] $vCards */
359
-			$vCards = [];
360
-			/** @var ?VCard $vCard */
361
-			while ($vCard = $vCardSplitter->getNext()) {
362
-				$problems = $vCard->validate();
363
-				if (!empty($problems)) {
364
-					$output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
365
-					continue;
366
-				}
367
-				$vCards[] = $vCard;
368
-			}
369
-
370
-			$splitFilename = explode('.', $addressBookFilename, 2);
371
-			if (count($splitFilename) !== 2) {
372
-				throw new ContactsMigratorException("Invalid filename \"$addressBookFilename\", expected filename of the format \"<address_book_name>." . ContactsMigrator::FILENAME_EXT . '"');
373
-			}
374
-			[$initialAddressBookUri, $ext] = $splitFilename;
375
-
376
-			/** @var array{displayName: string, description?: string} $metadata */
377
-			$metadata = json_decode($importSource->getFileContents($metadataImportPath), true, 512, JSON_THROW_ON_ERROR);
378
-
379
-			$this->importAddressBook(
380
-				$user,
381
-				$addressBookFilename,
382
-				$initialAddressBookUri,
383
-				$metadata,
384
-				$vCards,
385
-				$output,
386
-			);
387
-
388
-			foreach ($vCards as $vCard) {
389
-				$vCard->destroy();
390
-			}
391
-		}
392
-	}
393
-
394
-	/**
395
-	 * {@inheritDoc}
396
-	 */
397
-	public function getId(): string {
398
-		return 'contacts';
399
-	}
400
-
401
-	/**
402
-	 * {@inheritDoc}
403
-	 */
404
-	public function getDisplayName(): string {
405
-		return $this->l10n->t('Contacts');
406
-	}
407
-
408
-	/**
409
-	 * {@inheritDoc}
410
-	 */
411
-	public function getDescription(): string {
412
-		return $this->l10n->t('Contacts and groups');
413
-	}
57
+    use TMigratorBasicVersionHandling;
58
+
59
+    private CardDavBackend $cardDavBackend;
60
+
61
+    private IL10N $l10n;
62
+
63
+    private SabreDavServer $sabreDavServer;
64
+
65
+    private const USERS_URI_ROOT = 'principals/users/';
66
+
67
+    private const FILENAME_EXT = 'vcf';
68
+
69
+    private const METADATA_EXT = 'json';
70
+
71
+    private const MIGRATED_URI_PREFIX = 'migrated-';
72
+
73
+    private const PATH_ROOT = Application::APP_ID . '/address_books/';
74
+
75
+    public function __construct(
76
+        CardDavBackend $cardDavBackend,
77
+        IL10N $l10n
78
+    ) {
79
+        $this->cardDavBackend = $cardDavBackend;
80
+        $this->l10n = $l10n;
81
+
82
+        $root = new RootCollection();
83
+        $this->sabreDavServer = new SabreDavServer(new CachingTree($root));
84
+        $this->sabreDavServer->addPlugin(new CardDAVPlugin());
85
+    }
86
+
87
+    private function getPrincipalUri(IUser $user): string {
88
+        return ContactsMigrator::USERS_URI_ROOT . $user->getUID();
89
+    }
90
+
91
+    /**
92
+     * @return array{name: string, displayName: string, description: ?string, vCards: VCard[]}
93
+     *
94
+     * @throws InvalidAddressBookException
95
+     */
96
+    private function getAddressBookExportData(IUser $user, array $addressBookInfo, OutputInterface $output): array {
97
+        $userId = $user->getUID();
98
+
99
+        if (!isset($addressBookInfo['uri'])) {
100
+            throw new InvalidAddressBookException();
101
+        }
102
+
103
+        $uri = $addressBookInfo['uri'];
104
+
105
+        $path = CardDAVPlugin::ADDRESSBOOK_ROOT . "/users/$userId/$uri";
106
+
107
+        /**
108
+         * @see \Sabre\CardDAV\VCFExportPlugin::httpGet() implementation reference
109
+         */
110
+
111
+        $addressBookDataProp = '{' . CardDAVPlugin::NS_CARDDAV . '}address-data';
112
+        $addressBookNode = $this->sabreDavServer->tree->getNodeForPath($path);
113
+        $nodes = $this->sabreDavServer->getPropertiesIteratorForPath($path, [$addressBookDataProp], 1);
114
+
115
+        /**
116
+         * @see \Sabre\CardDAV\VCFExportPlugin::generateVCF() implementation reference
117
+         */
118
+
119
+        /** @var VCard[] $vCards */
120
+        $vCards = [];
121
+        foreach ($nodes as $node) {
122
+            if (isset($node[200][$addressBookDataProp])) {
123
+                $vCard = VObjectReader::read($node[200][$addressBookDataProp]);
124
+
125
+                $problems = $vCard->validate();
126
+                if (!empty($problems)) {
127
+                    $output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
128
+                    continue;
129
+                }
130
+                $vCards[] = $vCard;
131
+            }
132
+        }
133
+
134
+        if (count($vCards) === 0) {
135
+            throw new InvalidAddressBookException();
136
+        }
137
+
138
+        return [
139
+            'name' => $addressBookNode->getName(),
140
+            'displayName' => $addressBookInfo['{DAV:}displayname'],
141
+            'description' => $addressBookInfo['{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description'],
142
+            'vCards' => $vCards,
143
+        ];
144
+    }
145
+
146
+    /**
147
+     * @return array<int, array{name: string, displayName: string, description: ?string, vCards: VCard[]}>
148
+     */
149
+    private function getAddressBookExports(IUser $user, OutputInterface $output): array {
150
+        $principalUri = $this->getPrincipalUri($user);
151
+
152
+        return array_values(array_filter(array_map(
153
+            function (array $addressBookInfo) use ($user, $output) {
154
+                try {
155
+                    return $this->getAddressBookExportData($user, $addressBookInfo, $output);
156
+                } catch (InvalidAddressBookException $e) {
157
+                    // Allow this exception as invalid address books are not to be exported
158
+                    return null;
159
+                }
160
+            },
161
+            $this->cardDavBackend->getAddressBooksForUser($principalUri),
162
+        )));
163
+    }
164
+
165
+    private function getUniqueAddressBookUri(IUser $user, string $initialAddressBookUri): string {
166
+        $principalUri = $this->getPrincipalUri($user);
167
+
168
+        try {
169
+            $initialAddressBookUri = substr($initialAddressBookUri, 0, strlen(ContactsMigrator::MIGRATED_URI_PREFIX)) === ContactsMigrator::MIGRATED_URI_PREFIX
170
+                ? $initialAddressBookUri
171
+                : ContactsMigrator::MIGRATED_URI_PREFIX . $initialAddressBookUri;
172
+        } catch (StringsException $e) {
173
+            throw new ContactsMigratorException('Failed to get unique address book URI', 0, $e);
174
+        }
175
+
176
+        $existingAddressBookUris = array_map(
177
+            fn (array $addressBookInfo): string => $addressBookInfo['uri'],
178
+            $this->cardDavBackend->getAddressBooksForUser($principalUri),
179
+        );
180
+
181
+        $addressBookUri = $initialAddressBookUri;
182
+        $acc = 1;
183
+        while (in_array($addressBookUri, $existingAddressBookUris, true)) {
184
+            $addressBookUri = $initialAddressBookUri . "-$acc";
185
+            ++$acc;
186
+        }
187
+
188
+        return $addressBookUri;
189
+    }
190
+
191
+    /**
192
+     * @param VCard[] $vCards
193
+     */
194
+    private function serializeCards(array $vCards): string {
195
+        return array_reduce(
196
+            $vCards,
197
+            fn (string $addressBookBlob, VCard $vCard) => $addressBookBlob . $vCard->serialize(),
198
+            '',
199
+        );
200
+    }
201
+
202
+    /**
203
+     * {@inheritDoc}
204
+     */
205
+    public function getEstimatedExportSize(IUser $user): int {
206
+        $addressBookExports = $this->getAddressBookExports($user, new NullOutput());
207
+        $addressBookCount = count($addressBookExports);
208
+
209
+        // 50B for each metadata JSON
210
+        $size = ($addressBookCount * 50) / 1024;
211
+
212
+        $contactsCount = array_sum(array_map(
213
+            fn (array $data): int => count($data['vCards']),
214
+            $addressBookExports,
215
+        ));
216
+
217
+        // 350B for each contact
218
+        $size += ($contactsCount * 350) / 1024;
219
+
220
+        return (int)ceil($size);
221
+    }
222
+
223
+    /**
224
+     * {@inheritDoc}
225
+     */
226
+    public function export(IUser $user, IExportDestination $exportDestination, OutputInterface $output): void {
227
+        $output->writeln('Exporting contacts into ' . ContactsMigrator::PATH_ROOT . '…');
228
+
229
+        $addressBookExports = $this->getAddressBookExports($user, $output);
230
+
231
+        if (empty($addressBookExports)) {
232
+            $output->writeln('No contacts to export…');
233
+        }
234
+
235
+        try {
236
+            /**
237
+             * @var string $name
238
+             * @var string $displayName
239
+             * @var ?string $description
240
+             * @var VCard[] $vCards
241
+             */
242
+            foreach ($addressBookExports as ['name' => $name, 'displayName' => $displayName, 'description' => $description, 'vCards' => $vCards]) {
243
+                // Set filename to sanitized address book name
244
+                $basename = preg_replace('/[^a-z0-9-_]/iu', '', $name);
245
+                $exportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::FILENAME_EXT;
246
+                $metadataExportPath = ContactsMigrator::PATH_ROOT . $basename . '.' . ContactsMigrator::METADATA_EXT;
247
+
248
+                $exportDestination->addFileContents($exportPath, $this->serializeCards($vCards));
249
+
250
+                $metadata = array_filter(['displayName' => $displayName, 'description' => $description]);
251
+                $exportDestination->addFileContents($metadataExportPath, json_encode($metadata, JSON_THROW_ON_ERROR));
252
+            }
253
+        } catch (Throwable $e) {
254
+            throw new CalendarMigratorException('Could not export address book', 0, $e);
255
+        }
256
+    }
257
+
258
+    private function importContact(int $addressBookId, VCard $vCard, string $filename, OutputInterface $output): void {
259
+        // Operate on clone to prevent mutation of the original
260
+        $vCard = clone $vCard;
261
+        $vCard->PRODID = '-//IDN nextcloud.com//Migrated contact//EN';
262
+
263
+        try {
264
+            $this->cardDavBackend->createCard(
265
+                $addressBookId,
266
+                UUIDUtil::getUUID() . '.' . ContactsMigrator::FILENAME_EXT,
267
+                $vCard->serialize(),
268
+            );
269
+        } catch (Throwable $e) {
270
+            $output->writeln("Error creating contact \"" . ($vCard->FN ?? 'null') . "\" from \"$filename\", skipping…");
271
+        }
272
+    }
273
+
274
+    /**
275
+     * @param array{displayName: string, description?: string} $metadata
276
+     * @param VCard[] $vCards
277
+     */
278
+    private function importAddressBook(IUser $user, string $filename, string $initialAddressBookUri, array $metadata, array $vCards, OutputInterface $output): void {
279
+        $principalUri = $this->getPrincipalUri($user);
280
+        $addressBookUri = $this->getUniqueAddressBookUri($user, $initialAddressBookUri);
281
+
282
+        $addressBookId = $this->cardDavBackend->createAddressBook($principalUri, $addressBookUri, array_filter([
283
+            '{DAV:}displayname' => $metadata['displayName'],
284
+            '{' . CardDAVPlugin::NS_CARDDAV . '}addressbook-description' => $metadata['description'] ?? null,
285
+        ]));
286
+
287
+        foreach ($vCards as $vCard) {
288
+            $this->importContact($addressBookId, $vCard, $filename, $output);
289
+        }
290
+    }
291
+
292
+    /**
293
+     * @return array<int, array{addressBook: string, metadata: string}>
294
+     */
295
+    private function getAddressBookImports(array $importFiles): array {
296
+        $addressBookImports = array_filter(
297
+            $importFiles,
298
+            fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::FILENAME_EXT,
299
+        );
300
+
301
+        $metadataImports = array_filter(
302
+            $importFiles,
303
+            fn (string $filename) => pathinfo($filename, PATHINFO_EXTENSION) === ContactsMigrator::METADATA_EXT,
304
+        );
305
+
306
+        try {
307
+            sort($addressBookImports);
308
+            sort($metadataImports);
309
+        } catch (ArrayException $e) {
310
+            throw new ContactsMigratorException('Failed to sort address book files in ' . ContactsMigrator::PATH_ROOT, 0, $e);
311
+        }
312
+
313
+        if (count($addressBookImports) !== count($metadataImports)) {
314
+            throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
315
+        }
316
+
317
+        for ($i = 0; $i < count($addressBookImports); ++$i) {
318
+            if (pathinfo($addressBookImports[$i], PATHINFO_FILENAME) !== pathinfo($metadataImports[$i], PATHINFO_FILENAME)) {
319
+                throw new ContactsMigratorException('Each ' . ContactsMigrator::FILENAME_EXT . ' file must have a corresponding ' . ContactsMigrator::METADATA_EXT . ' file');
320
+            }
321
+        }
322
+
323
+        return array_map(
324
+            fn (string $addressBookFilename, string $metadataFilename) => ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename],
325
+            $addressBookImports,
326
+            $metadataImports,
327
+        );
328
+    }
329
+
330
+    /**
331
+     * {@inheritDoc}
332
+     *
333
+     * @throws ContactsMigratorException
334
+     */
335
+    public function import(IUser $user, IImportSource $importSource, OutputInterface $output): void {
336
+        if ($importSource->getMigratorVersion($this->getId()) === null) {
337
+            $output->writeln('No version for ' . static::class . ', skipping import…');
338
+            return;
339
+        }
340
+
341
+        $output->writeln('Importing contacts from ' . ContactsMigrator::PATH_ROOT . '…');
342
+
343
+        $importFiles = $importSource->getFolderListing(ContactsMigrator::PATH_ROOT);
344
+
345
+        if (empty($importFiles)) {
346
+            $output->writeln('No contacts to import…');
347
+        }
348
+
349
+        foreach ($this->getAddressBookImports($importFiles) as ['addressBook' => $addressBookFilename, 'metadata' => $metadataFilename]) {
350
+            $addressBookImportPath = ContactsMigrator::PATH_ROOT . $addressBookFilename;
351
+            $metadataImportPath = ContactsMigrator::PATH_ROOT . $metadataFilename;
352
+
353
+            $vCardSplitter = new VCardSplitter(
354
+                $importSource->getFileAsStream($addressBookImportPath),
355
+                VObjectParser::OPTION_FORGIVING,
356
+            );
357
+
358
+            /** @var VCard[] $vCards */
359
+            $vCards = [];
360
+            /** @var ?VCard $vCard */
361
+            while ($vCard = $vCardSplitter->getNext()) {
362
+                $problems = $vCard->validate();
363
+                if (!empty($problems)) {
364
+                    $output->writeln('Skipping contact "' . ($vCard->FN ?? 'null') . '" containing invalid contact data');
365
+                    continue;
366
+                }
367
+                $vCards[] = $vCard;
368
+            }
369
+
370
+            $splitFilename = explode('.', $addressBookFilename, 2);
371
+            if (count($splitFilename) !== 2) {
372
+                throw new ContactsMigratorException("Invalid filename \"$addressBookFilename\", expected filename of the format \"<address_book_name>." . ContactsMigrator::FILENAME_EXT . '"');
373
+            }
374
+            [$initialAddressBookUri, $ext] = $splitFilename;
375
+
376
+            /** @var array{displayName: string, description?: string} $metadata */
377
+            $metadata = json_decode($importSource->getFileContents($metadataImportPath), true, 512, JSON_THROW_ON_ERROR);
378
+
379
+            $this->importAddressBook(
380
+                $user,
381
+                $addressBookFilename,
382
+                $initialAddressBookUri,
383
+                $metadata,
384
+                $vCards,
385
+                $output,
386
+            );
387
+
388
+            foreach ($vCards as $vCard) {
389
+                $vCard->destroy();
390
+            }
391
+        }
392
+    }
393
+
394
+    /**
395
+     * {@inheritDoc}
396
+     */
397
+    public function getId(): string {
398
+        return 'contacts';
399
+    }
400
+
401
+    /**
402
+     * {@inheritDoc}
403
+     */
404
+    public function getDisplayName(): string {
405
+        return $this->l10n->t('Contacts');
406
+    }
407
+
408
+    /**
409
+     * {@inheritDoc}
410
+     */
411
+    public function getDescription(): string {
412
+        return $this->l10n->t('Contacts and groups');
413
+    }
414 414
 }
Please login to merge, or discard this patch.