Passed
Push — master ( 0c33fc...bf5d5c )
by Roeland
18:37 queued 04:24
created
apps/files_sharing/lib/Controller/ShareAPIController.php 1 patch
Indentation   +1692 added lines, -1692 removed lines patch added patch discarded remove patch
@@ -84,1699 +84,1699 @@
 block discarded – undo
84 84
  */
85 85
 class ShareAPIController extends OCSController {
86 86
 
87
-	/** @var IManager */
88
-	private $shareManager;
89
-	/** @var IGroupManager */
90
-	private $groupManager;
91
-	/** @var IUserManager */
92
-	private $userManager;
93
-	/** @var IRootFolder */
94
-	private $rootFolder;
95
-	/** @var IURLGenerator */
96
-	private $urlGenerator;
97
-	/** @var string */
98
-	private $currentUser;
99
-	/** @var IL10N */
100
-	private $l;
101
-	/** @var \OCP\Files\Node */
102
-	private $lockedNode;
103
-	/** @var IConfig */
104
-	private $config;
105
-	/** @var IAppManager */
106
-	private $appManager;
107
-	/** @var IServerContainer */
108
-	private $serverContainer;
109
-	/** @var IUserStatusManager */
110
-	private $userStatusManager;
111
-	/** @var IPreview */
112
-	private $previewManager;
113
-
114
-	/**
115
-	 * Share20OCS constructor.
116
-	 *
117
-	 * @param string $appName
118
-	 * @param IRequest $request
119
-	 * @param IManager $shareManager
120
-	 * @param IGroupManager $groupManager
121
-	 * @param IUserManager $userManager
122
-	 * @param IRootFolder $rootFolder
123
-	 * @param IURLGenerator $urlGenerator
124
-	 * @param string $userId
125
-	 * @param IL10N $l10n
126
-	 * @param IConfig $config
127
-	 * @param IAppManager $appManager
128
-	 * @param IServerContainer $serverContainer
129
-	 * @param IUserStatusManager $userStatusManager
130
-	 */
131
-	public function __construct(
132
-		string $appName,
133
-		IRequest $request,
134
-		IManager $shareManager,
135
-		IGroupManager $groupManager,
136
-		IUserManager $userManager,
137
-		IRootFolder $rootFolder,
138
-		IURLGenerator $urlGenerator,
139
-		string $userId = null,
140
-		IL10N $l10n,
141
-		IConfig $config,
142
-		IAppManager $appManager,
143
-		IServerContainer $serverContainer,
144
-		IUserStatusManager $userStatusManager,
145
-		IPreview $previewManager
146
-	) {
147
-		parent::__construct($appName, $request);
148
-
149
-		$this->shareManager = $shareManager;
150
-		$this->userManager = $userManager;
151
-		$this->groupManager = $groupManager;
152
-		$this->request = $request;
153
-		$this->rootFolder = $rootFolder;
154
-		$this->urlGenerator = $urlGenerator;
155
-		$this->currentUser = $userId;
156
-		$this->l = $l10n;
157
-		$this->config = $config;
158
-		$this->appManager = $appManager;
159
-		$this->serverContainer = $serverContainer;
160
-		$this->userStatusManager = $userStatusManager;
161
-		$this->previewManager = $previewManager;
162
-	}
163
-
164
-	/**
165
-	 * Convert an IShare to an array for OCS output
166
-	 *
167
-	 * @param \OCP\Share\IShare $share
168
-	 * @param Node|null $recipientNode
169
-	 * @return array
170
-	 * @throws NotFoundException In case the node can't be resolved.
171
-	 *
172
-	 * @suppress PhanUndeclaredClassMethod
173
-	 */
174
-	protected function formatShare(IShare $share, Node $recipientNode = null): array {
175
-		$sharedBy = $this->userManager->get($share->getSharedBy());
176
-		$shareOwner = $this->userManager->get($share->getShareOwner());
177
-
178
-		$result = [
179
-			'id' => $share->getId(),
180
-			'share_type' => $share->getShareType(),
181
-			'uid_owner' => $share->getSharedBy(),
182
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
183
-			// recipient permissions
184
-			'permissions' => $share->getPermissions(),
185
-			// current user permissions on this share
186
-			'can_edit' => $this->canEditShare($share),
187
-			'can_delete' => $this->canDeleteShare($share),
188
-			'stime' => $share->getShareTime()->getTimestamp(),
189
-			'parent' => null,
190
-			'expiration' => null,
191
-			'token' => null,
192
-			'uid_file_owner' => $share->getShareOwner(),
193
-			'note' => $share->getNote(),
194
-			'label' => $share->getLabel(),
195
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
196
-		];
197
-
198
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
199
-		if ($recipientNode) {
200
-			$node = $recipientNode;
201
-		} else {
202
-			$nodes = $userFolder->getById($share->getNodeId());
203
-			if (empty($nodes)) {
204
-				// fallback to guessing the path
205
-				$node = $userFolder->get($share->getTarget());
206
-				if ($node === null || $share->getTarget() === '') {
207
-					throw new NotFoundException();
208
-				}
209
-			} else {
210
-				$node = reset($nodes);
211
-			}
212
-		}
213
-
214
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
215
-		if ($node instanceof Folder) {
216
-			$result['item_type'] = 'folder';
217
-		} else {
218
-			$result['item_type'] = 'file';
219
-		}
220
-
221
-		$result['mimetype'] = $node->getMimetype();
222
-		$result['has_preview'] = $this->previewManager->isAvailable($node);
223
-		$result['storage_id'] = $node->getStorage()->getId();
224
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
225
-		$result['item_source'] = $node->getId();
226
-		$result['file_source'] = $node->getId();
227
-		$result['file_parent'] = $node->getParent()->getId();
228
-		$result['file_target'] = $share->getTarget();
229
-
230
-		$expiration = $share->getExpirationDate();
231
-		if ($expiration !== null) {
232
-			$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
233
-		}
234
-
235
-		if ($share->getShareType() === IShare::TYPE_USER) {
236
-			$sharedWith = $this->userManager->get($share->getSharedWith());
237
-			$result['share_with'] = $share->getSharedWith();
238
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
239
-			$result['share_with_displayname_unique'] = $sharedWith !== null ? (
240
-				 $sharedWith->getEMailAddress() !== '' ? $sharedWith->getEMailAddress() : $sharedWith->getUID()
241
-			) : $share->getSharedWith();
242
-			$result['status'] = [];
243
-
244
-			$userStatuses = $this->userStatusManager->getUserStatuses([$share->getSharedWith()]);
245
-			$userStatus = array_shift($userStatuses);
246
-			if ($userStatus) {
247
-				$result['status'] = [
248
-					'status' => $userStatus->getStatus(),
249
-					'message' => $userStatus->getMessage(),
250
-					'icon' => $userStatus->getIcon(),
251
-					'clearAt' => $userStatus->getClearAt()
252
-						? (int)$userStatus->getClearAt()->format('U')
253
-						: null,
254
-				];
255
-			}
256
-		} elseif ($share->getShareType() === IShare::TYPE_GROUP) {
257
-			$group = $this->groupManager->get($share->getSharedWith());
258
-			$result['share_with'] = $share->getSharedWith();
259
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
260
-		} elseif ($share->getShareType() === IShare::TYPE_LINK) {
261
-
262
-			// "share_with" and "share_with_displayname" for passwords of link
263
-			// shares was deprecated in Nextcloud 15, use "password" instead.
264
-			$result['share_with'] = $share->getPassword();
265
-			$result['share_with_displayname'] = '(' . $this->l->t('Shared link') . ')';
266
-
267
-			$result['password'] = $share->getPassword();
268
-
269
-			$result['send_password_by_talk'] = $share->getSendPasswordByTalk();
270
-
271
-			$result['token'] = $share->getToken();
272
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
273
-		} elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
274
-			$result['share_with'] = $share->getSharedWith();
275
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
276
-			$result['token'] = $share->getToken();
277
-		} elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
278
-			$result['share_with'] = $share->getSharedWith();
279
-			$result['password'] = $share->getPassword();
280
-			$result['send_password_by_talk'] = $share->getSendPasswordByTalk();
281
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
282
-			$result['token'] = $share->getToken();
283
-		} elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
284
-			// getSharedWith() returns either "name (type, owner)" or
285
-			// "name (type, owner) [id]", depending on the Circles app version.
286
-			$hasCircleId = (substr($share->getSharedWith(), -1) === ']');
287
-
288
-			$result['share_with_displayname'] = $share->getSharedWithDisplayName();
289
-			if (empty($result['share_with_displayname'])) {
290
-				$displayNameLength = ($hasCircleId ? strrpos($share->getSharedWith(), ' ') : strlen($share->getSharedWith()));
291
-				$result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
292
-			}
293
-
294
-			$result['share_with_avatar'] = $share->getSharedWithAvatar();
295
-
296
-			$shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
297
-			$shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
298
-			if (is_bool($shareWithLength)) {
299
-				$shareWithLength = -1;
300
-			}
301
-			$result['share_with'] = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
302
-		} elseif ($share->getShareType() === IShare::TYPE_ROOM) {
303
-			$result['share_with'] = $share->getSharedWith();
304
-			$result['share_with_displayname'] = '';
305
-
306
-			try {
307
-				$result = array_merge($result, $this->getRoomShareHelper()->formatShare($share));
308
-			} catch (QueryException $e) {
309
-			}
310
-		} elseif ($share->getShareType() === IShare::TYPE_DECK) {
311
-			$result['share_with'] = $share->getSharedWith();
312
-			$result['share_with_displayname'] = '';
313
-
314
-			try {
315
-				$result = array_merge($result, $this->getDeckShareHelper()->formatShare($share));
316
-			} catch (QueryException $e) {
317
-			}
318
-		}
319
-
320
-
321
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
322
-		$result['hide_download'] = $share->getHideDownload() ? 1 : 0;
323
-
324
-		return $result;
325
-	}
326
-
327
-	/**
328
-	 * Check if one of the users address books knows the exact property, if
329
-	 * yes we return the full name.
330
-	 *
331
-	 * @param string $query
332
-	 * @param string $property
333
-	 * @return string
334
-	 */
335
-	private function getDisplayNameFromAddressBook(string $query, string $property): string {
336
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
337
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
338
-		foreach ($result as $r) {
339
-			foreach ($r[$property] as $value) {
340
-				if ($value === $query && $r['FN']) {
341
-					return $r['FN'];
342
-				}
343
-			}
344
-		}
345
-
346
-		return $query;
347
-	}
348
-
349
-	/**
350
-	 * Get a specific share by id
351
-	 *
352
-	 * @NoAdminRequired
353
-	 *
354
-	 * @param string $id
355
-	 * @return DataResponse
356
-	 * @throws OCSNotFoundException
357
-	 */
358
-	public function getShare(string $id): DataResponse {
359
-		try {
360
-			$share = $this->getShareById($id);
361
-		} catch (ShareNotFound $e) {
362
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
363
-		}
364
-
365
-		try {
366
-			if ($this->canAccessShare($share)) {
367
-				$share = $this->formatShare($share);
368
-				return new DataResponse([$share]);
369
-			}
370
-		} catch (NotFoundException $e) {
371
-			// Fall trough
372
-		}
373
-
374
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
375
-	}
376
-
377
-	/**
378
-	 * Delete a share
379
-	 *
380
-	 * @NoAdminRequired
381
-	 *
382
-	 * @param string $id
383
-	 * @return DataResponse
384
-	 * @throws OCSNotFoundException
385
-	 */
386
-	public function deleteShare(string $id): DataResponse {
387
-		try {
388
-			$share = $this->getShareById($id);
389
-		} catch (ShareNotFound $e) {
390
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
391
-		}
392
-
393
-		try {
394
-			$this->lock($share->getNode());
395
-		} catch (LockedException $e) {
396
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
397
-		}
398
-
399
-		if (!$this->canAccessShare($share)) {
400
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
401
-		}
402
-
403
-		// if it's a group share or a room share
404
-		// we don't delete the share, but only the
405
-		// mount point. Allowing it to be restored
406
-		// from the deleted shares
407
-		if ($this->canDeleteShareFromSelf($share)) {
408
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
409
-		} else {
410
-			if (!$this->canDeleteShare($share)) {
411
-				throw new OCSForbiddenException($this->l->t('Could not delete share'));
412
-			}
413
-
414
-			$this->shareManager->deleteShare($share);
415
-		}
416
-
417
-		return new DataResponse();
418
-	}
419
-
420
-	/**
421
-	 * @NoAdminRequired
422
-	 *
423
-	 * @param string $path
424
-	 * @param int $permissions
425
-	 * @param int $shareType
426
-	 * @param string $shareWith
427
-	 * @param string $publicUpload
428
-	 * @param string $password
429
-	 * @param string $sendPasswordByTalk
430
-	 * @param string $expireDate
431
-	 * @param string $label
432
-	 *
433
-	 * @return DataResponse
434
-	 * @throws NotFoundException
435
-	 * @throws OCSBadRequestException
436
-	 * @throws OCSException
437
-	 * @throws OCSForbiddenException
438
-	 * @throws OCSNotFoundException
439
-	 * @throws InvalidPathException
440
-	 * @suppress PhanUndeclaredClassMethod
441
-	 */
442
-	public function createShare(
443
-		string $path = null,
444
-		int $permissions = null,
445
-		int $shareType = -1,
446
-		string $shareWith = null,
447
-		string $publicUpload = 'false',
448
-		string $password = '',
449
-		string $sendPasswordByTalk = null,
450
-		string $expireDate = '',
451
-		string $label = ''
452
-	): DataResponse {
453
-		$share = $this->shareManager->newShare();
454
-
455
-		if ($permissions === null) {
456
-			$permissions = $this->config->getAppValue('core', 'shareapi_default_permissions', Constants::PERMISSION_ALL);
457
-		}
458
-
459
-		// Verify path
460
-		if ($path === null) {
461
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
462
-		}
463
-
464
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
465
-		try {
466
-			$path = $userFolder->get($path);
467
-		} catch (NotFoundException $e) {
468
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
469
-		}
470
-
471
-		$share->setNode($path);
472
-
473
-		try {
474
-			$this->lock($share->getNode());
475
-		} catch (LockedException $e) {
476
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
477
-		}
478
-
479
-		if ($permissions < 0 || $permissions > Constants::PERMISSION_ALL) {
480
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
481
-		}
482
-
483
-		// Shares always require read permissions
484
-		$permissions |= Constants::PERMISSION_READ;
485
-
486
-		if ($path instanceof \OCP\Files\File) {
487
-			// Single file shares should never have delete or create permissions
488
-			$permissions &= ~Constants::PERMISSION_DELETE;
489
-			$permissions &= ~Constants::PERMISSION_CREATE;
490
-		}
491
-
492
-		/**
493
-		 * Hack for https://github.com/owncloud/core/issues/22587
494
-		 * We check the permissions via webdav. But the permissions of the mount point
495
-		 * do not equal the share permissions. Here we fix that for federated mounts.
496
-		 */
497
-		if ($path->getStorage()->instanceOfStorage(Storage::class)) {
498
-			$permissions &= ~($permissions & ~$path->getPermissions());
499
-		}
500
-
501
-		if ($shareType === IShare::TYPE_USER) {
502
-			// Valid user is required to share
503
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
504
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
505
-			}
506
-			$share->setSharedWith($shareWith);
507
-			$share->setPermissions($permissions);
508
-		} elseif ($shareType === IShare::TYPE_GROUP) {
509
-			if (!$this->shareManager->allowGroupSharing()) {
510
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
511
-			}
512
-
513
-			// Valid group is required to share
514
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
515
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
516
-			}
517
-			$share->setSharedWith($shareWith);
518
-			$share->setPermissions($permissions);
519
-		} elseif ($shareType === IShare::TYPE_LINK
520
-			|| $shareType === IShare::TYPE_EMAIL) {
521
-
522
-			// Can we even share links?
523
-			if (!$this->shareManager->shareApiAllowLinks()) {
524
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
525
-			}
526
-
527
-			if ($publicUpload === 'true') {
528
-				// Check if public upload is allowed
529
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
530
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
531
-				}
532
-
533
-				// Public upload can only be set for folders
534
-				if ($path instanceof \OCP\Files\File) {
535
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
536
-				}
537
-
538
-				$permissions = Constants::PERMISSION_READ |
539
-					Constants::PERMISSION_CREATE |
540
-					Constants::PERMISSION_UPDATE |
541
-					Constants::PERMISSION_DELETE;
542
-			} else {
543
-				$permissions = Constants::PERMISSION_READ;
544
-			}
545
-
546
-			// TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
547
-			if (($permissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {
548
-				$permissions |= Constants::PERMISSION_SHARE;
549
-			}
550
-
551
-			$share->setPermissions($permissions);
552
-
553
-			// Set password
554
-			if ($password !== '') {
555
-				$share->setPassword($password);
556
-			}
557
-
558
-			// Only share by mail have a recipient
559
-			if ($shareType === IShare::TYPE_EMAIL) {
560
-				$share->setSharedWith($shareWith);
561
-			} else {
562
-				// Only link share have a label
563
-				if (!empty($label)) {
564
-					$share->setLabel($label);
565
-				}
566
-			}
567
-
568
-			if ($sendPasswordByTalk === 'true') {
569
-				if (!$this->appManager->isEnabledForUser('spreed')) {
570
-					throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
571
-				}
572
-
573
-				$share->setSendPasswordByTalk(true);
574
-			}
575
-
576
-			//Expire date
577
-			if ($expireDate !== '') {
578
-				try {
579
-					$expireDate = $this->parseDate($expireDate);
580
-					$share->setExpirationDate($expireDate);
581
-				} catch (\Exception $e) {
582
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
583
-				}
584
-			}
585
-		} elseif ($shareType === IShare::TYPE_REMOTE) {
586
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
587
-				throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
588
-			}
589
-
590
-			$share->setSharedWith($shareWith);
591
-			$share->setPermissions($permissions);
592
-		} elseif ($shareType === IShare::TYPE_REMOTE_GROUP) {
593
-			if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
594
-				throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
595
-			}
596
-
597
-			$share->setSharedWith($shareWith);
598
-			$share->setPermissions($permissions);
599
-		} elseif ($shareType === IShare::TYPE_CIRCLE) {
600
-			if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
601
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
602
-			}
603
-
604
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
605
-
606
-			// Valid circle is required to share
607
-			if ($circle === null) {
608
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
609
-			}
610
-			$share->setSharedWith($shareWith);
611
-			$share->setPermissions($permissions);
612
-		} elseif ($shareType === IShare::TYPE_ROOM) {
613
-			try {
614
-				$this->getRoomShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
615
-			} catch (QueryException $e) {
616
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
617
-			}
618
-		} elseif ($shareType === IShare::TYPE_DECK) {
619
-			try {
620
-				$this->getDeckShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
621
-			} catch (QueryException $e) {
622
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
623
-			}
624
-		} else {
625
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
626
-		}
627
-
628
-		$share->setShareType($shareType);
629
-		$share->setSharedBy($this->currentUser);
630
-
631
-		try {
632
-			$share = $this->shareManager->createShare($share);
633
-		} catch (GenericShareException $e) {
634
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
635
-			throw new OCSException($e->getHint(), $code);
636
-		} catch (\Exception $e) {
637
-			throw new OCSForbiddenException($e->getMessage(), $e);
638
-		}
639
-
640
-		$output = $this->formatShare($share);
641
-
642
-		return new DataResponse($output);
643
-	}
644
-
645
-	/**
646
-	 * @param null|Node $node
647
-	 * @param boolean $includeTags
648
-	 *
649
-	 * @return array
650
-	 */
651
-	private function getSharedWithMe($node, bool $includeTags): array {
652
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_USER, $node, -1, 0);
653
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_GROUP, $node, -1, 0);
654
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_CIRCLE, $node, -1, 0);
655
-		$roomShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_ROOM, $node, -1, 0);
656
-		$deckShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_DECK, $node, -1, 0);
657
-
658
-		$shares = array_merge($userShares, $groupShares, $circleShares, $roomShares, $deckShares);
659
-
660
-		$filteredShares = array_filter($shares, function (IShare $share) {
661
-			return $share->getShareOwner() !== $this->currentUser;
662
-		});
663
-
664
-		$formatted = [];
665
-		foreach ($filteredShares as $share) {
666
-			if ($this->canAccessShare($share)) {
667
-				try {
668
-					$formatted[] = $this->formatShare($share);
669
-				} catch (NotFoundException $e) {
670
-					// Ignore this share
671
-				}
672
-			}
673
-		}
674
-
675
-		if ($includeTags) {
676
-			$formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
677
-		}
678
-
679
-		return $formatted;
680
-	}
681
-
682
-	/**
683
-	 * @param \OCP\Files\Node $folder
684
-	 *
685
-	 * @return array
686
-	 * @throws OCSBadRequestException
687
-	 * @throws NotFoundException
688
-	 */
689
-	private function getSharesInDir(Node $folder): array {
690
-		if (!($folder instanceof \OCP\Files\Folder)) {
691
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
692
-		}
693
-
694
-		$nodes = $folder->getDirectoryListing();
695
-
696
-		/** @var \OCP\Share\IShare[] $shares */
697
-		$shares = array_reduce($nodes, function ($carry, $node) {
698
-			$carry = array_merge($carry, $this->getAllShares($node, true));
699
-			return $carry;
700
-		}, []);
701
-
702
-		// filter out duplicate shares
703
-		$known = [];
704
-
705
-
706
-		$formatted = $miniFormatted = [];
707
-		$resharingRight = false;
708
-		$known = [];
709
-		foreach ($shares as $share) {
710
-			if (in_array($share->getId(), $known) || $share->getSharedWith() === $this->currentUser) {
711
-				continue;
712
-			}
713
-
714
-			try {
715
-				$format = $this->formatShare($share);
716
-
717
-				$known[] = $share->getId();
718
-				$formatted[] = $format;
719
-				if ($share->getSharedBy() === $this->currentUser) {
720
-					$miniFormatted[] = $format;
721
-				}
722
-				if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $folder)) {
723
-					$resharingRight = true;
724
-				}
725
-			} catch (\Exception $e) {
726
-				//Ignore this share
727
-			}
728
-		}
729
-
730
-		if (!$resharingRight) {
731
-			$formatted = $miniFormatted;
732
-		}
733
-
734
-		return $formatted;
735
-	}
736
-
737
-	/**
738
-	 * The getShares function.
739
-	 *
740
-	 * @NoAdminRequired
741
-	 *
742
-	 * @param string $shared_with_me
743
-	 * @param string $reshares
744
-	 * @param string $subfiles
745
-	 * @param string $path
746
-	 *
747
-	 * - Get shares by the current user
748
-	 * - Get shares by the current user and reshares (?reshares=true)
749
-	 * - Get shares with the current user (?shared_with_me=true)
750
-	 * - Get shares for a specific path (?path=...)
751
-	 * - Get all shares in a folder (?subfiles=true&path=..)
752
-	 *
753
-	 * @param string $include_tags
754
-	 *
755
-	 * @return DataResponse
756
-	 * @throws NotFoundException
757
-	 * @throws OCSBadRequestException
758
-	 * @throws OCSNotFoundException
759
-	 */
760
-	public function getShares(
761
-		string $shared_with_me = 'false',
762
-		string $reshares = 'false',
763
-		string $subfiles = 'false',
764
-		string $path = '',
765
-		string $include_tags = 'false'
766
-	): DataResponse {
767
-		$node = null;
768
-		if ($path !== '') {
769
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
770
-			try {
771
-				$node = $userFolder->get($path);
772
-				$this->lock($node);
773
-			} catch (NotFoundException $e) {
774
-				throw new OCSNotFoundException(
775
-					$this->l->t('Wrong path, file/folder doesn\'t exist')
776
-				);
777
-			} catch (LockedException $e) {
778
-				throw new OCSNotFoundException($this->l->t('Could not lock node'));
779
-			}
780
-		}
781
-
782
-		$shares = $this->getFormattedShares(
783
-			$this->currentUser,
784
-			$node,
785
-			($shared_with_me === 'true'),
786
-			($reshares === 'true'),
787
-			($subfiles === 'true'),
788
-			($include_tags === 'true')
789
-		);
790
-
791
-		return new DataResponse($shares);
792
-	}
793
-
794
-
795
-	/**
796
-	 * @param string $viewer
797
-	 * @param Node $node
798
-	 * @param bool $sharedWithMe
799
-	 * @param bool $reShares
800
-	 * @param bool $subFiles
801
-	 * @param bool $includeTags
802
-	 *
803
-	 * @return array
804
-	 * @throws NotFoundException
805
-	 * @throws OCSBadRequestException
806
-	 */
807
-	private function getFormattedShares(
808
-		string $viewer,
809
-		$node = null,
810
-		bool $sharedWithMe = false,
811
-		bool $reShares = false,
812
-		bool $subFiles = false,
813
-		bool $includeTags = false
814
-	): array {
815
-		if ($sharedWithMe) {
816
-			return $this->getSharedWithMe($node, $includeTags);
817
-		}
818
-
819
-		if ($subFiles) {
820
-			return $this->getSharesInDir($node);
821
-		}
822
-
823
-		$shares = $this->getSharesFromNode($viewer, $node, $reShares);
824
-
825
-		$known = $formatted = $miniFormatted = [];
826
-		$resharingRight = false;
827
-		foreach ($shares as $share) {
828
-			try {
829
-				$share->getNode();
830
-			} catch (NotFoundException $e) {
831
-				/*
87
+    /** @var IManager */
88
+    private $shareManager;
89
+    /** @var IGroupManager */
90
+    private $groupManager;
91
+    /** @var IUserManager */
92
+    private $userManager;
93
+    /** @var IRootFolder */
94
+    private $rootFolder;
95
+    /** @var IURLGenerator */
96
+    private $urlGenerator;
97
+    /** @var string */
98
+    private $currentUser;
99
+    /** @var IL10N */
100
+    private $l;
101
+    /** @var \OCP\Files\Node */
102
+    private $lockedNode;
103
+    /** @var IConfig */
104
+    private $config;
105
+    /** @var IAppManager */
106
+    private $appManager;
107
+    /** @var IServerContainer */
108
+    private $serverContainer;
109
+    /** @var IUserStatusManager */
110
+    private $userStatusManager;
111
+    /** @var IPreview */
112
+    private $previewManager;
113
+
114
+    /**
115
+     * Share20OCS constructor.
116
+     *
117
+     * @param string $appName
118
+     * @param IRequest $request
119
+     * @param IManager $shareManager
120
+     * @param IGroupManager $groupManager
121
+     * @param IUserManager $userManager
122
+     * @param IRootFolder $rootFolder
123
+     * @param IURLGenerator $urlGenerator
124
+     * @param string $userId
125
+     * @param IL10N $l10n
126
+     * @param IConfig $config
127
+     * @param IAppManager $appManager
128
+     * @param IServerContainer $serverContainer
129
+     * @param IUserStatusManager $userStatusManager
130
+     */
131
+    public function __construct(
132
+        string $appName,
133
+        IRequest $request,
134
+        IManager $shareManager,
135
+        IGroupManager $groupManager,
136
+        IUserManager $userManager,
137
+        IRootFolder $rootFolder,
138
+        IURLGenerator $urlGenerator,
139
+        string $userId = null,
140
+        IL10N $l10n,
141
+        IConfig $config,
142
+        IAppManager $appManager,
143
+        IServerContainer $serverContainer,
144
+        IUserStatusManager $userStatusManager,
145
+        IPreview $previewManager
146
+    ) {
147
+        parent::__construct($appName, $request);
148
+
149
+        $this->shareManager = $shareManager;
150
+        $this->userManager = $userManager;
151
+        $this->groupManager = $groupManager;
152
+        $this->request = $request;
153
+        $this->rootFolder = $rootFolder;
154
+        $this->urlGenerator = $urlGenerator;
155
+        $this->currentUser = $userId;
156
+        $this->l = $l10n;
157
+        $this->config = $config;
158
+        $this->appManager = $appManager;
159
+        $this->serverContainer = $serverContainer;
160
+        $this->userStatusManager = $userStatusManager;
161
+        $this->previewManager = $previewManager;
162
+    }
163
+
164
+    /**
165
+     * Convert an IShare to an array for OCS output
166
+     *
167
+     * @param \OCP\Share\IShare $share
168
+     * @param Node|null $recipientNode
169
+     * @return array
170
+     * @throws NotFoundException In case the node can't be resolved.
171
+     *
172
+     * @suppress PhanUndeclaredClassMethod
173
+     */
174
+    protected function formatShare(IShare $share, Node $recipientNode = null): array {
175
+        $sharedBy = $this->userManager->get($share->getSharedBy());
176
+        $shareOwner = $this->userManager->get($share->getShareOwner());
177
+
178
+        $result = [
179
+            'id' => $share->getId(),
180
+            'share_type' => $share->getShareType(),
181
+            'uid_owner' => $share->getSharedBy(),
182
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
183
+            // recipient permissions
184
+            'permissions' => $share->getPermissions(),
185
+            // current user permissions on this share
186
+            'can_edit' => $this->canEditShare($share),
187
+            'can_delete' => $this->canDeleteShare($share),
188
+            'stime' => $share->getShareTime()->getTimestamp(),
189
+            'parent' => null,
190
+            'expiration' => null,
191
+            'token' => null,
192
+            'uid_file_owner' => $share->getShareOwner(),
193
+            'note' => $share->getNote(),
194
+            'label' => $share->getLabel(),
195
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
196
+        ];
197
+
198
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
199
+        if ($recipientNode) {
200
+            $node = $recipientNode;
201
+        } else {
202
+            $nodes = $userFolder->getById($share->getNodeId());
203
+            if (empty($nodes)) {
204
+                // fallback to guessing the path
205
+                $node = $userFolder->get($share->getTarget());
206
+                if ($node === null || $share->getTarget() === '') {
207
+                    throw new NotFoundException();
208
+                }
209
+            } else {
210
+                $node = reset($nodes);
211
+            }
212
+        }
213
+
214
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
215
+        if ($node instanceof Folder) {
216
+            $result['item_type'] = 'folder';
217
+        } else {
218
+            $result['item_type'] = 'file';
219
+        }
220
+
221
+        $result['mimetype'] = $node->getMimetype();
222
+        $result['has_preview'] = $this->previewManager->isAvailable($node);
223
+        $result['storage_id'] = $node->getStorage()->getId();
224
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
225
+        $result['item_source'] = $node->getId();
226
+        $result['file_source'] = $node->getId();
227
+        $result['file_parent'] = $node->getParent()->getId();
228
+        $result['file_target'] = $share->getTarget();
229
+
230
+        $expiration = $share->getExpirationDate();
231
+        if ($expiration !== null) {
232
+            $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
233
+        }
234
+
235
+        if ($share->getShareType() === IShare::TYPE_USER) {
236
+            $sharedWith = $this->userManager->get($share->getSharedWith());
237
+            $result['share_with'] = $share->getSharedWith();
238
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
239
+            $result['share_with_displayname_unique'] = $sharedWith !== null ? (
240
+                    $sharedWith->getEMailAddress() !== '' ? $sharedWith->getEMailAddress() : $sharedWith->getUID()
241
+            ) : $share->getSharedWith();
242
+            $result['status'] = [];
243
+
244
+            $userStatuses = $this->userStatusManager->getUserStatuses([$share->getSharedWith()]);
245
+            $userStatus = array_shift($userStatuses);
246
+            if ($userStatus) {
247
+                $result['status'] = [
248
+                    'status' => $userStatus->getStatus(),
249
+                    'message' => $userStatus->getMessage(),
250
+                    'icon' => $userStatus->getIcon(),
251
+                    'clearAt' => $userStatus->getClearAt()
252
+                        ? (int)$userStatus->getClearAt()->format('U')
253
+                        : null,
254
+                ];
255
+            }
256
+        } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
257
+            $group = $this->groupManager->get($share->getSharedWith());
258
+            $result['share_with'] = $share->getSharedWith();
259
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
260
+        } elseif ($share->getShareType() === IShare::TYPE_LINK) {
261
+
262
+            // "share_with" and "share_with_displayname" for passwords of link
263
+            // shares was deprecated in Nextcloud 15, use "password" instead.
264
+            $result['share_with'] = $share->getPassword();
265
+            $result['share_with_displayname'] = '(' . $this->l->t('Shared link') . ')';
266
+
267
+            $result['password'] = $share->getPassword();
268
+
269
+            $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
270
+
271
+            $result['token'] = $share->getToken();
272
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
273
+        } elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
274
+            $result['share_with'] = $share->getSharedWith();
275
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
276
+            $result['token'] = $share->getToken();
277
+        } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
278
+            $result['share_with'] = $share->getSharedWith();
279
+            $result['password'] = $share->getPassword();
280
+            $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
281
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
282
+            $result['token'] = $share->getToken();
283
+        } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
284
+            // getSharedWith() returns either "name (type, owner)" or
285
+            // "name (type, owner) [id]", depending on the Circles app version.
286
+            $hasCircleId = (substr($share->getSharedWith(), -1) === ']');
287
+
288
+            $result['share_with_displayname'] = $share->getSharedWithDisplayName();
289
+            if (empty($result['share_with_displayname'])) {
290
+                $displayNameLength = ($hasCircleId ? strrpos($share->getSharedWith(), ' ') : strlen($share->getSharedWith()));
291
+                $result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
292
+            }
293
+
294
+            $result['share_with_avatar'] = $share->getSharedWithAvatar();
295
+
296
+            $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
297
+            $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
298
+            if (is_bool($shareWithLength)) {
299
+                $shareWithLength = -1;
300
+            }
301
+            $result['share_with'] = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
302
+        } elseif ($share->getShareType() === IShare::TYPE_ROOM) {
303
+            $result['share_with'] = $share->getSharedWith();
304
+            $result['share_with_displayname'] = '';
305
+
306
+            try {
307
+                $result = array_merge($result, $this->getRoomShareHelper()->formatShare($share));
308
+            } catch (QueryException $e) {
309
+            }
310
+        } elseif ($share->getShareType() === IShare::TYPE_DECK) {
311
+            $result['share_with'] = $share->getSharedWith();
312
+            $result['share_with_displayname'] = '';
313
+
314
+            try {
315
+                $result = array_merge($result, $this->getDeckShareHelper()->formatShare($share));
316
+            } catch (QueryException $e) {
317
+            }
318
+        }
319
+
320
+
321
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
322
+        $result['hide_download'] = $share->getHideDownload() ? 1 : 0;
323
+
324
+        return $result;
325
+    }
326
+
327
+    /**
328
+     * Check if one of the users address books knows the exact property, if
329
+     * yes we return the full name.
330
+     *
331
+     * @param string $query
332
+     * @param string $property
333
+     * @return string
334
+     */
335
+    private function getDisplayNameFromAddressBook(string $query, string $property): string {
336
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
337
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
338
+        foreach ($result as $r) {
339
+            foreach ($r[$property] as $value) {
340
+                if ($value === $query && $r['FN']) {
341
+                    return $r['FN'];
342
+                }
343
+            }
344
+        }
345
+
346
+        return $query;
347
+    }
348
+
349
+    /**
350
+     * Get a specific share by id
351
+     *
352
+     * @NoAdminRequired
353
+     *
354
+     * @param string $id
355
+     * @return DataResponse
356
+     * @throws OCSNotFoundException
357
+     */
358
+    public function getShare(string $id): DataResponse {
359
+        try {
360
+            $share = $this->getShareById($id);
361
+        } catch (ShareNotFound $e) {
362
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
363
+        }
364
+
365
+        try {
366
+            if ($this->canAccessShare($share)) {
367
+                $share = $this->formatShare($share);
368
+                return new DataResponse([$share]);
369
+            }
370
+        } catch (NotFoundException $e) {
371
+            // Fall trough
372
+        }
373
+
374
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
375
+    }
376
+
377
+    /**
378
+     * Delete a share
379
+     *
380
+     * @NoAdminRequired
381
+     *
382
+     * @param string $id
383
+     * @return DataResponse
384
+     * @throws OCSNotFoundException
385
+     */
386
+    public function deleteShare(string $id): DataResponse {
387
+        try {
388
+            $share = $this->getShareById($id);
389
+        } catch (ShareNotFound $e) {
390
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
391
+        }
392
+
393
+        try {
394
+            $this->lock($share->getNode());
395
+        } catch (LockedException $e) {
396
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
397
+        }
398
+
399
+        if (!$this->canAccessShare($share)) {
400
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
401
+        }
402
+
403
+        // if it's a group share or a room share
404
+        // we don't delete the share, but only the
405
+        // mount point. Allowing it to be restored
406
+        // from the deleted shares
407
+        if ($this->canDeleteShareFromSelf($share)) {
408
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
409
+        } else {
410
+            if (!$this->canDeleteShare($share)) {
411
+                throw new OCSForbiddenException($this->l->t('Could not delete share'));
412
+            }
413
+
414
+            $this->shareManager->deleteShare($share);
415
+        }
416
+
417
+        return new DataResponse();
418
+    }
419
+
420
+    /**
421
+     * @NoAdminRequired
422
+     *
423
+     * @param string $path
424
+     * @param int $permissions
425
+     * @param int $shareType
426
+     * @param string $shareWith
427
+     * @param string $publicUpload
428
+     * @param string $password
429
+     * @param string $sendPasswordByTalk
430
+     * @param string $expireDate
431
+     * @param string $label
432
+     *
433
+     * @return DataResponse
434
+     * @throws NotFoundException
435
+     * @throws OCSBadRequestException
436
+     * @throws OCSException
437
+     * @throws OCSForbiddenException
438
+     * @throws OCSNotFoundException
439
+     * @throws InvalidPathException
440
+     * @suppress PhanUndeclaredClassMethod
441
+     */
442
+    public function createShare(
443
+        string $path = null,
444
+        int $permissions = null,
445
+        int $shareType = -1,
446
+        string $shareWith = null,
447
+        string $publicUpload = 'false',
448
+        string $password = '',
449
+        string $sendPasswordByTalk = null,
450
+        string $expireDate = '',
451
+        string $label = ''
452
+    ): DataResponse {
453
+        $share = $this->shareManager->newShare();
454
+
455
+        if ($permissions === null) {
456
+            $permissions = $this->config->getAppValue('core', 'shareapi_default_permissions', Constants::PERMISSION_ALL);
457
+        }
458
+
459
+        // Verify path
460
+        if ($path === null) {
461
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
462
+        }
463
+
464
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
465
+        try {
466
+            $path = $userFolder->get($path);
467
+        } catch (NotFoundException $e) {
468
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
469
+        }
470
+
471
+        $share->setNode($path);
472
+
473
+        try {
474
+            $this->lock($share->getNode());
475
+        } catch (LockedException $e) {
476
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
477
+        }
478
+
479
+        if ($permissions < 0 || $permissions > Constants::PERMISSION_ALL) {
480
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
481
+        }
482
+
483
+        // Shares always require read permissions
484
+        $permissions |= Constants::PERMISSION_READ;
485
+
486
+        if ($path instanceof \OCP\Files\File) {
487
+            // Single file shares should never have delete or create permissions
488
+            $permissions &= ~Constants::PERMISSION_DELETE;
489
+            $permissions &= ~Constants::PERMISSION_CREATE;
490
+        }
491
+
492
+        /**
493
+         * Hack for https://github.com/owncloud/core/issues/22587
494
+         * We check the permissions via webdav. But the permissions of the mount point
495
+         * do not equal the share permissions. Here we fix that for federated mounts.
496
+         */
497
+        if ($path->getStorage()->instanceOfStorage(Storage::class)) {
498
+            $permissions &= ~($permissions & ~$path->getPermissions());
499
+        }
500
+
501
+        if ($shareType === IShare::TYPE_USER) {
502
+            // Valid user is required to share
503
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
504
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
505
+            }
506
+            $share->setSharedWith($shareWith);
507
+            $share->setPermissions($permissions);
508
+        } elseif ($shareType === IShare::TYPE_GROUP) {
509
+            if (!$this->shareManager->allowGroupSharing()) {
510
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
511
+            }
512
+
513
+            // Valid group is required to share
514
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
515
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
516
+            }
517
+            $share->setSharedWith($shareWith);
518
+            $share->setPermissions($permissions);
519
+        } elseif ($shareType === IShare::TYPE_LINK
520
+            || $shareType === IShare::TYPE_EMAIL) {
521
+
522
+            // Can we even share links?
523
+            if (!$this->shareManager->shareApiAllowLinks()) {
524
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
525
+            }
526
+
527
+            if ($publicUpload === 'true') {
528
+                // Check if public upload is allowed
529
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
530
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
531
+                }
532
+
533
+                // Public upload can only be set for folders
534
+                if ($path instanceof \OCP\Files\File) {
535
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
536
+                }
537
+
538
+                $permissions = Constants::PERMISSION_READ |
539
+                    Constants::PERMISSION_CREATE |
540
+                    Constants::PERMISSION_UPDATE |
541
+                    Constants::PERMISSION_DELETE;
542
+            } else {
543
+                $permissions = Constants::PERMISSION_READ;
544
+            }
545
+
546
+            // TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
547
+            if (($permissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {
548
+                $permissions |= Constants::PERMISSION_SHARE;
549
+            }
550
+
551
+            $share->setPermissions($permissions);
552
+
553
+            // Set password
554
+            if ($password !== '') {
555
+                $share->setPassword($password);
556
+            }
557
+
558
+            // Only share by mail have a recipient
559
+            if ($shareType === IShare::TYPE_EMAIL) {
560
+                $share->setSharedWith($shareWith);
561
+            } else {
562
+                // Only link share have a label
563
+                if (!empty($label)) {
564
+                    $share->setLabel($label);
565
+                }
566
+            }
567
+
568
+            if ($sendPasswordByTalk === 'true') {
569
+                if (!$this->appManager->isEnabledForUser('spreed')) {
570
+                    throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
571
+                }
572
+
573
+                $share->setSendPasswordByTalk(true);
574
+            }
575
+
576
+            //Expire date
577
+            if ($expireDate !== '') {
578
+                try {
579
+                    $expireDate = $this->parseDate($expireDate);
580
+                    $share->setExpirationDate($expireDate);
581
+                } catch (\Exception $e) {
582
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
583
+                }
584
+            }
585
+        } elseif ($shareType === IShare::TYPE_REMOTE) {
586
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
587
+                throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
588
+            }
589
+
590
+            $share->setSharedWith($shareWith);
591
+            $share->setPermissions($permissions);
592
+        } elseif ($shareType === IShare::TYPE_REMOTE_GROUP) {
593
+            if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
594
+                throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
595
+            }
596
+
597
+            $share->setSharedWith($shareWith);
598
+            $share->setPermissions($permissions);
599
+        } elseif ($shareType === IShare::TYPE_CIRCLE) {
600
+            if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
601
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
602
+            }
603
+
604
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
605
+
606
+            // Valid circle is required to share
607
+            if ($circle === null) {
608
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
609
+            }
610
+            $share->setSharedWith($shareWith);
611
+            $share->setPermissions($permissions);
612
+        } elseif ($shareType === IShare::TYPE_ROOM) {
613
+            try {
614
+                $this->getRoomShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
615
+            } catch (QueryException $e) {
616
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
617
+            }
618
+        } elseif ($shareType === IShare::TYPE_DECK) {
619
+            try {
620
+                $this->getDeckShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
621
+            } catch (QueryException $e) {
622
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
623
+            }
624
+        } else {
625
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
626
+        }
627
+
628
+        $share->setShareType($shareType);
629
+        $share->setSharedBy($this->currentUser);
630
+
631
+        try {
632
+            $share = $this->shareManager->createShare($share);
633
+        } catch (GenericShareException $e) {
634
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
635
+            throw new OCSException($e->getHint(), $code);
636
+        } catch (\Exception $e) {
637
+            throw new OCSForbiddenException($e->getMessage(), $e);
638
+        }
639
+
640
+        $output = $this->formatShare($share);
641
+
642
+        return new DataResponse($output);
643
+    }
644
+
645
+    /**
646
+     * @param null|Node $node
647
+     * @param boolean $includeTags
648
+     *
649
+     * @return array
650
+     */
651
+    private function getSharedWithMe($node, bool $includeTags): array {
652
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_USER, $node, -1, 0);
653
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_GROUP, $node, -1, 0);
654
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_CIRCLE, $node, -1, 0);
655
+        $roomShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_ROOM, $node, -1, 0);
656
+        $deckShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_DECK, $node, -1, 0);
657
+
658
+        $shares = array_merge($userShares, $groupShares, $circleShares, $roomShares, $deckShares);
659
+
660
+        $filteredShares = array_filter($shares, function (IShare $share) {
661
+            return $share->getShareOwner() !== $this->currentUser;
662
+        });
663
+
664
+        $formatted = [];
665
+        foreach ($filteredShares as $share) {
666
+            if ($this->canAccessShare($share)) {
667
+                try {
668
+                    $formatted[] = $this->formatShare($share);
669
+                } catch (NotFoundException $e) {
670
+                    // Ignore this share
671
+                }
672
+            }
673
+        }
674
+
675
+        if ($includeTags) {
676
+            $formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
677
+        }
678
+
679
+        return $formatted;
680
+    }
681
+
682
+    /**
683
+     * @param \OCP\Files\Node $folder
684
+     *
685
+     * @return array
686
+     * @throws OCSBadRequestException
687
+     * @throws NotFoundException
688
+     */
689
+    private function getSharesInDir(Node $folder): array {
690
+        if (!($folder instanceof \OCP\Files\Folder)) {
691
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
692
+        }
693
+
694
+        $nodes = $folder->getDirectoryListing();
695
+
696
+        /** @var \OCP\Share\IShare[] $shares */
697
+        $shares = array_reduce($nodes, function ($carry, $node) {
698
+            $carry = array_merge($carry, $this->getAllShares($node, true));
699
+            return $carry;
700
+        }, []);
701
+
702
+        // filter out duplicate shares
703
+        $known = [];
704
+
705
+
706
+        $formatted = $miniFormatted = [];
707
+        $resharingRight = false;
708
+        $known = [];
709
+        foreach ($shares as $share) {
710
+            if (in_array($share->getId(), $known) || $share->getSharedWith() === $this->currentUser) {
711
+                continue;
712
+            }
713
+
714
+            try {
715
+                $format = $this->formatShare($share);
716
+
717
+                $known[] = $share->getId();
718
+                $formatted[] = $format;
719
+                if ($share->getSharedBy() === $this->currentUser) {
720
+                    $miniFormatted[] = $format;
721
+                }
722
+                if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $folder)) {
723
+                    $resharingRight = true;
724
+                }
725
+            } catch (\Exception $e) {
726
+                //Ignore this share
727
+            }
728
+        }
729
+
730
+        if (!$resharingRight) {
731
+            $formatted = $miniFormatted;
732
+        }
733
+
734
+        return $formatted;
735
+    }
736
+
737
+    /**
738
+     * The getShares function.
739
+     *
740
+     * @NoAdminRequired
741
+     *
742
+     * @param string $shared_with_me
743
+     * @param string $reshares
744
+     * @param string $subfiles
745
+     * @param string $path
746
+     *
747
+     * - Get shares by the current user
748
+     * - Get shares by the current user and reshares (?reshares=true)
749
+     * - Get shares with the current user (?shared_with_me=true)
750
+     * - Get shares for a specific path (?path=...)
751
+     * - Get all shares in a folder (?subfiles=true&path=..)
752
+     *
753
+     * @param string $include_tags
754
+     *
755
+     * @return DataResponse
756
+     * @throws NotFoundException
757
+     * @throws OCSBadRequestException
758
+     * @throws OCSNotFoundException
759
+     */
760
+    public function getShares(
761
+        string $shared_with_me = 'false',
762
+        string $reshares = 'false',
763
+        string $subfiles = 'false',
764
+        string $path = '',
765
+        string $include_tags = 'false'
766
+    ): DataResponse {
767
+        $node = null;
768
+        if ($path !== '') {
769
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
770
+            try {
771
+                $node = $userFolder->get($path);
772
+                $this->lock($node);
773
+            } catch (NotFoundException $e) {
774
+                throw new OCSNotFoundException(
775
+                    $this->l->t('Wrong path, file/folder doesn\'t exist')
776
+                );
777
+            } catch (LockedException $e) {
778
+                throw new OCSNotFoundException($this->l->t('Could not lock node'));
779
+            }
780
+        }
781
+
782
+        $shares = $this->getFormattedShares(
783
+            $this->currentUser,
784
+            $node,
785
+            ($shared_with_me === 'true'),
786
+            ($reshares === 'true'),
787
+            ($subfiles === 'true'),
788
+            ($include_tags === 'true')
789
+        );
790
+
791
+        return new DataResponse($shares);
792
+    }
793
+
794
+
795
+    /**
796
+     * @param string $viewer
797
+     * @param Node $node
798
+     * @param bool $sharedWithMe
799
+     * @param bool $reShares
800
+     * @param bool $subFiles
801
+     * @param bool $includeTags
802
+     *
803
+     * @return array
804
+     * @throws NotFoundException
805
+     * @throws OCSBadRequestException
806
+     */
807
+    private function getFormattedShares(
808
+        string $viewer,
809
+        $node = null,
810
+        bool $sharedWithMe = false,
811
+        bool $reShares = false,
812
+        bool $subFiles = false,
813
+        bool $includeTags = false
814
+    ): array {
815
+        if ($sharedWithMe) {
816
+            return $this->getSharedWithMe($node, $includeTags);
817
+        }
818
+
819
+        if ($subFiles) {
820
+            return $this->getSharesInDir($node);
821
+        }
822
+
823
+        $shares = $this->getSharesFromNode($viewer, $node, $reShares);
824
+
825
+        $known = $formatted = $miniFormatted = [];
826
+        $resharingRight = false;
827
+        foreach ($shares as $share) {
828
+            try {
829
+                $share->getNode();
830
+            } catch (NotFoundException $e) {
831
+                /*
832 832
 				 * Ignore shares where we can't get the node
833 833
 				 * For example deleted shares
834 834
 				 */
835
-				continue;
836
-			}
837
-
838
-			if (in_array($share->getId(), $known)
839
-				|| ($share->getSharedWith() === $this->currentUser && $share->getShareType() === IShare::TYPE_USER)) {
840
-				continue;
841
-			}
842
-
843
-			$known[] = $share->getId();
844
-			try {
845
-				/** @var IShare $share */
846
-				$format = $this->formatShare($share, $node);
847
-				$formatted[] = $format;
848
-
849
-				// let's also build a list of shares created
850
-				// by the current user only, in case
851
-				// there is no resharing rights
852
-				if ($share->getSharedBy() === $this->currentUser) {
853
-					$miniFormatted[] = $format;
854
-				}
855
-
856
-				// check if one of those share is shared with me
857
-				// and if I have resharing rights on it
858
-				if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $node)) {
859
-					$resharingRight = true;
860
-				}
861
-			} catch (InvalidPathException | NotFoundException $e) {
862
-			}
863
-		}
864
-
865
-		if (!$resharingRight) {
866
-			$formatted = $miniFormatted;
867
-		}
868
-
869
-		if ($includeTags) {
870
-			$formatted =
871
-				Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
872
-		}
873
-
874
-		return $formatted;
875
-	}
876
-
877
-
878
-	/**
879
-	 * The getInheritedShares function.
880
-	 * returns all shares relative to a file, including parent folders shares rights.
881
-	 *
882
-	 * @NoAdminRequired
883
-	 *
884
-	 * @param string $path
885
-	 *
886
-	 * - Get shares by the current user
887
-	 * - Get shares by the current user and reshares (?reshares=true)
888
-	 * - Get shares with the current user (?shared_with_me=true)
889
-	 * - Get shares for a specific path (?path=...)
890
-	 * - Get all shares in a folder (?subfiles=true&path=..)
891
-	 *
892
-	 * @return DataResponse
893
-	 * @throws InvalidPathException
894
-	 * @throws NotFoundException
895
-	 * @throws OCSNotFoundException
896
-	 * @throws OCSBadRequestException
897
-	 * @throws SharingRightsException
898
-	 */
899
-	public function getInheritedShares(string $path): DataResponse {
900
-
901
-		// get Node from (string) path.
902
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
903
-		try {
904
-			$node = $userFolder->get($path);
905
-			$this->lock($node);
906
-		} catch (\OCP\Files\NotFoundException $e) {
907
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
908
-		} catch (LockedException $e) {
909
-			throw new OCSNotFoundException($this->l->t('Could not lock path'));
910
-		}
911
-
912
-		if (!($node->getPermissions() & Constants::PERMISSION_SHARE)) {
913
-			throw new SharingRightsException('no sharing rights on this item');
914
-		}
915
-
916
-		// The current top parent we have access to
917
-		$parent = $node;
918
-
919
-		// initiate real owner.
920
-		$owner = $node->getOwner()
921
-					  ->getUID();
922
-		if (!$this->userManager->userExists($owner)) {
923
-			return new DataResponse([]);
924
-		}
925
-
926
-		// get node based on the owner, fix owner in case of external storage
927
-		$userFolder = $this->rootFolder->getUserFolder($owner);
928
-		if ($node->getId() !== $userFolder->getId() && !$userFolder->isSubNode($node)) {
929
-			$owner = $node->getOwner()
930
-						  ->getUID();
931
-			$userFolder = $this->rootFolder->getUserFolder($owner);
932
-			$nodes = $userFolder->getById($node->getId());
933
-			$node = array_shift($nodes);
934
-		}
935
-		$basePath = $userFolder->getPath();
936
-
937
-		// generate node list for each parent folders
938
-		/** @var Node[] $nodes */
939
-		$nodes = [];
940
-		while ($node->getPath() !== $basePath) {
941
-			$node = $node->getParent();
942
-			$nodes[] = $node;
943
-		}
944
-
945
-		// The user that is requesting this list
946
-		$currentUserFolder = $this->rootFolder->getUserFolder($this->currentUser);
947
-
948
-		// for each nodes, retrieve shares.
949
-		$shares = [];
950
-
951
-		foreach ($nodes as $node) {
952
-			$getShares = $this->getFormattedShares($owner, $node, false, true);
953
-
954
-			$currentUserNodes = $currentUserFolder->getById($node->getId());
955
-			if (!empty($currentUserNodes)) {
956
-				$parent = array_pop($currentUserNodes);
957
-			}
958
-
959
-			$subPath = $currentUserFolder->getRelativePath($parent->getPath());
960
-			foreach ($getShares as &$share) {
961
-				$share['via_fileid'] = $parent->getId();
962
-				$share['via_path'] = $subPath;
963
-			}
964
-			$this->mergeFormattedShares($shares, $getShares);
965
-		}
966
-
967
-		return new DataResponse(array_values($shares));
968
-	}
969
-
970
-
971
-	/**
972
-	 * @NoAdminRequired
973
-	 *
974
-	 * @param string $id
975
-	 * @param int $permissions
976
-	 * @param string $password
977
-	 * @param string $sendPasswordByTalk
978
-	 * @param string $publicUpload
979
-	 * @param string $expireDate
980
-	 * @param string $note
981
-	 * @param string $label
982
-	 * @param string $hideDownload
983
-	 * @return DataResponse
984
-	 * @throws LockedException
985
-	 * @throws NotFoundException
986
-	 * @throws OCSBadRequestException
987
-	 * @throws OCSForbiddenException
988
-	 * @throws OCSNotFoundException
989
-	 */
990
-	public function updateShare(
991
-		string $id,
992
-		int $permissions = null,
993
-		string $password = null,
994
-		string $sendPasswordByTalk = null,
995
-		string $publicUpload = null,
996
-		string $expireDate = null,
997
-		string $note = null,
998
-		string $label = null,
999
-		string $hideDownload = null
1000
-	): DataResponse {
1001
-		try {
1002
-			$share = $this->getShareById($id);
1003
-		} catch (ShareNotFound $e) {
1004
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1005
-		}
1006
-
1007
-		$this->lock($share->getNode());
1008
-
1009
-		if (!$this->canAccessShare($share, false)) {
1010
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1011
-		}
1012
-
1013
-		if (!$this->canEditShare($share)) {
1014
-			throw new OCSForbiddenException('You are not allowed to edit incoming shares');
1015
-		}
1016
-
1017
-		if (
1018
-			$permissions === null &&
1019
-			$password === null &&
1020
-			$sendPasswordByTalk === null &&
1021
-			$publicUpload === null &&
1022
-			$expireDate === null &&
1023
-			$note === null &&
1024
-			$label === null &&
1025
-			$hideDownload === null
1026
-		) {
1027
-			throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
1028
-		}
1029
-
1030
-		if ($note !== null) {
1031
-			$share->setNote($note);
1032
-		}
1033
-
1034
-		/**
1035
-		 * expirationdate, password and publicUpload only make sense for link shares
1036
-		 */
1037
-		if ($share->getShareType() === IShare::TYPE_LINK
1038
-			|| $share->getShareType() === IShare::TYPE_EMAIL) {
1039
-
1040
-			/**
1041
-			 * We do not allow editing link shares that the current user
1042
-			 * doesn't own. This is confusing and lead to errors when
1043
-			 * someone else edit a password or expiration date without
1044
-			 * the share owner knowing about it.
1045
-			 * We only allow deletion
1046
-			 */
1047
-
1048
-			if ($share->getSharedBy() !== $this->currentUser) {
1049
-				throw new OCSForbiddenException('You are not allowed to edit link shares that you don\'t own');
1050
-			}
1051
-
1052
-			// Update hide download state
1053
-			if ($hideDownload === 'true') {
1054
-				$share->setHideDownload(true);
1055
-			} elseif ($hideDownload === 'false') {
1056
-				$share->setHideDownload(false);
1057
-			}
1058
-
1059
-			$newPermissions = null;
1060
-			if ($publicUpload === 'true') {
1061
-				$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
1062
-			} elseif ($publicUpload === 'false') {
1063
-				$newPermissions = Constants::PERMISSION_READ;
1064
-			}
1065
-
1066
-			if ($permissions !== null) {
1067
-				$newPermissions = $permissions;
1068
-				$newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
1069
-			}
1070
-
1071
-			if ($newPermissions !== null &&
1072
-				!in_array($newPermissions, [
1073
-					Constants::PERMISSION_READ,
1074
-					Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE, // legacy
1075
-					Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE, // correct
1076
-					Constants::PERMISSION_CREATE, // hidden file list
1077
-					Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, // allow to edit single files
1078
-				], true)
1079
-			) {
1080
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
1081
-			}
1082
-
1083
-			if (
1084
-				// legacy
1085
-				$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||
1086
-				// correct
1087
-				$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
1088
-			) {
1089
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
1090
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
1091
-				}
1092
-
1093
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
1094
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
1095
-				}
1096
-
1097
-				// normalize to correct public upload permissions
1098
-				$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
1099
-			}
1100
-
1101
-			if ($newPermissions !== null) {
1102
-				// TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
1103
-				if (($newPermissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {
1104
-					$newPermissions |= Constants::PERMISSION_SHARE;
1105
-				}
1106
-
1107
-				$share->setPermissions($newPermissions);
1108
-				$permissions = $newPermissions;
1109
-			}
1110
-
1111
-			if ($expireDate === '') {
1112
-				$share->setExpirationDate(null);
1113
-			} elseif ($expireDate !== null) {
1114
-				try {
1115
-					$expireDate = $this->parseDate($expireDate);
1116
-				} catch (\Exception $e) {
1117
-					throw new OCSBadRequestException($e->getMessage(), $e);
1118
-				}
1119
-				$share->setExpirationDate($expireDate);
1120
-			}
1121
-
1122
-			if ($password === '') {
1123
-				$share->setPassword(null);
1124
-			} elseif ($password !== null) {
1125
-				$share->setPassword($password);
1126
-			}
1127
-
1128
-			// only link shares have labels
1129
-			if ($share->getShareType() === IShare::TYPE_LINK && $label !== null) {
1130
-				if (strlen($label) > 255) {
1131
-					throw new OCSBadRequestException("Maxmimum label length is 255");
1132
-				}
1133
-				$share->setLabel($label);
1134
-			}
1135
-
1136
-			if ($sendPasswordByTalk === 'true') {
1137
-				if (!$this->appManager->isEnabledForUser('spreed')) {
1138
-					throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
1139
-				}
1140
-
1141
-				$share->setSendPasswordByTalk(true);
1142
-			} elseif ($sendPasswordByTalk !== null) {
1143
-				$share->setSendPasswordByTalk(false);
1144
-			}
1145
-		}
1146
-
1147
-		// NOT A LINK SHARE
1148
-		else {
1149
-			if ($permissions !== null) {
1150
-				$share->setPermissions($permissions);
1151
-			}
1152
-
1153
-			if ($expireDate === '') {
1154
-				$share->setExpirationDate(null);
1155
-			} elseif ($expireDate !== null) {
1156
-				try {
1157
-					$expireDate = $this->parseDate($expireDate);
1158
-				} catch (\Exception $e) {
1159
-					throw new OCSBadRequestException($e->getMessage(), $e);
1160
-				}
1161
-				$share->setExpirationDate($expireDate);
1162
-			}
1163
-		}
1164
-
1165
-		try {
1166
-			$share = $this->shareManager->updateShare($share);
1167
-		} catch (GenericShareException $e) {
1168
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
1169
-			throw new OCSException($e->getHint(), $code);
1170
-		} catch (\Exception $e) {
1171
-			throw new OCSBadRequestException($e->getMessage(), $e);
1172
-		}
1173
-
1174
-		return new DataResponse($this->formatShare($share));
1175
-	}
1176
-
1177
-	/**
1178
-	 * @NoAdminRequired
1179
-	 */
1180
-	public function pendingShares(): DataResponse {
1181
-		$pendingShares = [];
1182
-
1183
-		$shareTypes = [
1184
-			IShare::TYPE_USER,
1185
-			IShare::TYPE_GROUP
1186
-		];
1187
-
1188
-		foreach ($shareTypes as $shareType) {
1189
-			$shares = $this->shareManager->getSharedWith($this->currentUser, $shareType, null, -1, 0);
1190
-
1191
-			foreach ($shares as $share) {
1192
-				if ($share->getStatus() === IShare::STATUS_PENDING || $share->getStatus() === IShare::STATUS_REJECTED) {
1193
-					$pendingShares[] = $share;
1194
-				}
1195
-			}
1196
-		}
1197
-
1198
-		$result = array_filter(array_map(function (IShare $share) {
1199
-			$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1200
-			$nodes = $userFolder->getById($share->getNodeId());
1201
-			if (empty($nodes)) {
1202
-				// fallback to guessing the path
1203
-				$node = $userFolder->get($share->getTarget());
1204
-				if ($node === null || $share->getTarget() === '') {
1205
-					return null;
1206
-				}
1207
-			} else {
1208
-				$node = $nodes[0];
1209
-			}
1210
-
1211
-			try {
1212
-				$formattedShare = $this->formatShare($share, $node);
1213
-				$formattedShare['status'] = $share->getStatus();
1214
-				$formattedShare['path'] = $share->getNode()->getName();
1215
-				$formattedShare['permissions'] = 0;
1216
-				return $formattedShare;
1217
-			} catch (NotFoundException $e) {
1218
-				return null;
1219
-			}
1220
-		}, $pendingShares), function ($entry) {
1221
-			return $entry !== null;
1222
-		});
1223
-
1224
-		return new DataResponse($result);
1225
-	}
1226
-
1227
-	/**
1228
-	 * @NoAdminRequired
1229
-	 *
1230
-	 * @param string $id
1231
-	 * @return DataResponse
1232
-	 * @throws OCSNotFoundException
1233
-	 * @throws OCSException
1234
-	 * @throws OCSBadRequestException
1235
-	 */
1236
-	public function acceptShare(string $id): DataResponse {
1237
-		try {
1238
-			$share = $this->getShareById($id);
1239
-		} catch (ShareNotFound $e) {
1240
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1241
-		}
1242
-
1243
-		if (!$this->canAccessShare($share)) {
1244
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1245
-		}
1246
-
1247
-		try {
1248
-			$this->shareManager->acceptShare($share, $this->currentUser);
1249
-		} catch (GenericShareException $e) {
1250
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
1251
-			throw new OCSException($e->getHint(), $code);
1252
-		} catch (\Exception $e) {
1253
-			throw new OCSBadRequestException($e->getMessage(), $e);
1254
-		}
1255
-
1256
-		return new DataResponse();
1257
-	}
1258
-
1259
-	/**
1260
-	 * Does the user have read permission on the share
1261
-	 *
1262
-	 * @param \OCP\Share\IShare $share the share to check
1263
-	 * @param boolean $checkGroups check groups as well?
1264
-	 * @return boolean
1265
-	 * @throws NotFoundException
1266
-	 *
1267
-	 * @suppress PhanUndeclaredClassMethod
1268
-	 */
1269
-	protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
1270
-		// A file with permissions 0 can't be accessed by us. So Don't show it
1271
-		if ($share->getPermissions() === 0) {
1272
-			return false;
1273
-		}
1274
-
1275
-		// Owner of the file and the sharer of the file can always get share
1276
-		if ($share->getShareOwner() === $this->currentUser
1277
-			|| $share->getSharedBy() === $this->currentUser) {
1278
-			return true;
1279
-		}
1280
-
1281
-		// If the share is shared with you, you can access it!
1282
-		if ($share->getShareType() === IShare::TYPE_USER
1283
-			&& $share->getSharedWith() === $this->currentUser) {
1284
-			return true;
1285
-		}
1286
-
1287
-		// Have reshare rights on the shared file/folder ?
1288
-		// Does the currentUser have access to the shared file?
1289
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
1290
-		$files = $userFolder->getById($share->getNodeId());
1291
-		if (!empty($files) && $this->shareProviderResharingRights($this->currentUser, $share, $files[0])) {
1292
-			return true;
1293
-		}
1294
-
1295
-		// If in the recipient group, you can see the share
1296
-		if ($checkGroups && $share->getShareType() === IShare::TYPE_GROUP) {
1297
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1298
-			$user = $this->userManager->get($this->currentUser);
1299
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1300
-				return true;
1301
-			}
1302
-		}
1303
-
1304
-		if ($share->getShareType() === IShare::TYPE_CIRCLE) {
1305
-			// TODO: have a sanity check like above?
1306
-			return true;
1307
-		}
1308
-
1309
-		if ($share->getShareType() === IShare::TYPE_ROOM) {
1310
-			try {
1311
-				return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1312
-			} catch (QueryException $e) {
1313
-				return false;
1314
-			}
1315
-		}
1316
-
1317
-		if ($share->getShareType() === IShare::TYPE_DECK) {
1318
-			try {
1319
-				return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
1320
-			} catch (QueryException $e) {
1321
-				return false;
1322
-			}
1323
-		}
1324
-
1325
-		return false;
1326
-	}
1327
-
1328
-	/**
1329
-	 * Does the user have edit permission on the share
1330
-	 *
1331
-	 * @param \OCP\Share\IShare $share the share to check
1332
-	 * @return boolean
1333
-	 */
1334
-	protected function canEditShare(\OCP\Share\IShare $share): bool {
1335
-		// A file with permissions 0 can't be accessed by us. So Don't show it
1336
-		if ($share->getPermissions() === 0) {
1337
-			return false;
1338
-		}
1339
-
1340
-		// The owner of the file and the creator of the share
1341
-		// can always edit the share
1342
-		if ($share->getShareOwner() === $this->currentUser ||
1343
-			$share->getSharedBy() === $this->currentUser
1344
-		) {
1345
-			return true;
1346
-		}
1347
-
1348
-		//! we do NOT support some kind of `admin` in groups.
1349
-		//! You cannot edit shares shared to a group you're
1350
-		//! a member of if you're not the share owner or the file owner!
1351
-
1352
-		return false;
1353
-	}
1354
-
1355
-	/**
1356
-	 * Does the user have delete permission on the share
1357
-	 *
1358
-	 * @param \OCP\Share\IShare $share the share to check
1359
-	 * @return boolean
1360
-	 */
1361
-	protected function canDeleteShare(\OCP\Share\IShare $share): bool {
1362
-		// A file with permissions 0 can't be accessed by us. So Don't show it
1363
-		if ($share->getPermissions() === 0) {
1364
-			return false;
1365
-		}
1366
-
1367
-		// if the user is the recipient, i can unshare
1368
-		// the share with self
1369
-		if ($share->getShareType() === IShare::TYPE_USER &&
1370
-			$share->getSharedWith() === $this->currentUser
1371
-		) {
1372
-			return true;
1373
-		}
1374
-
1375
-		// The owner of the file and the creator of the share
1376
-		// can always delete the share
1377
-		if ($share->getShareOwner() === $this->currentUser ||
1378
-			$share->getSharedBy() === $this->currentUser
1379
-		) {
1380
-			return true;
1381
-		}
1382
-
1383
-		return false;
1384
-	}
1385
-
1386
-	/**
1387
-	 * Does the user have delete permission on the share
1388
-	 * This differs from the canDeleteShare function as it only
1389
-	 * remove the share for the current user. It does NOT
1390
-	 * completely delete the share but only the mount point.
1391
-	 * It can then be restored from the deleted shares section.
1392
-	 *
1393
-	 * @param \OCP\Share\IShare $share the share to check
1394
-	 * @return boolean
1395
-	 *
1396
-	 * @suppress PhanUndeclaredClassMethod
1397
-	 */
1398
-	protected function canDeleteShareFromSelf(\OCP\Share\IShare $share): bool {
1399
-		if ($share->getShareType() !== IShare::TYPE_GROUP &&
1400
-			$share->getShareType() !== IShare::TYPE_ROOM &&
1401
-			$share->getShareType() !== IShare::TYPE_DECK
1402
-		) {
1403
-			return false;
1404
-		}
1405
-
1406
-		if ($share->getShareOwner() === $this->currentUser ||
1407
-			$share->getSharedBy() === $this->currentUser
1408
-		) {
1409
-			// Delete the whole share, not just for self
1410
-			return false;
1411
-		}
1412
-
1413
-		// If in the recipient group, you can delete the share from self
1414
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
1415
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1416
-			$user = $this->userManager->get($this->currentUser);
1417
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1418
-				return true;
1419
-			}
1420
-		}
1421
-
1422
-		if ($share->getShareType() === IShare::TYPE_ROOM) {
1423
-			try {
1424
-				return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1425
-			} catch (QueryException $e) {
1426
-				return false;
1427
-			}
1428
-		}
1429
-
1430
-		if ($share->getShareType() === IShare::TYPE_DECK) {
1431
-			try {
1432
-				return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
1433
-			} catch (QueryException $e) {
1434
-				return false;
1435
-			}
1436
-		}
1437
-
1438
-		return false;
1439
-	}
1440
-
1441
-	/**
1442
-	 * Make sure that the passed date is valid ISO 8601
1443
-	 * So YYYY-MM-DD
1444
-	 * If not throw an exception
1445
-	 *
1446
-	 * @param string $expireDate
1447
-	 *
1448
-	 * @throws \Exception
1449
-	 * @return \DateTime
1450
-	 */
1451
-	private function parseDate(string $expireDate): \DateTime {
1452
-		try {
1453
-			$date = new \DateTime($expireDate);
1454
-		} catch (\Exception $e) {
1455
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1456
-		}
1457
-
1458
-		$date->setTime(0, 0, 0);
1459
-
1460
-		return $date;
1461
-	}
1462
-
1463
-	/**
1464
-	 * Since we have multiple providers but the OCS Share API v1 does
1465
-	 * not support this we need to check all backends.
1466
-	 *
1467
-	 * @param string $id
1468
-	 * @return \OCP\Share\IShare
1469
-	 * @throws ShareNotFound
1470
-	 */
1471
-	private function getShareById(string $id): IShare {
1472
-		$share = null;
1473
-
1474
-		// First check if it is an internal share.
1475
-		try {
1476
-			$share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
1477
-			return $share;
1478
-		} catch (ShareNotFound $e) {
1479
-			// Do nothing, just try the other share type
1480
-		}
1481
-
1482
-
1483
-		try {
1484
-			if ($this->shareManager->shareProviderExists(IShare::TYPE_CIRCLE)) {
1485
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
1486
-				return $share;
1487
-			}
1488
-		} catch (ShareNotFound $e) {
1489
-			// Do nothing, just try the other share type
1490
-		}
1491
-
1492
-		try {
1493
-			if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
1494
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
1495
-				return $share;
1496
-			}
1497
-		} catch (ShareNotFound $e) {
1498
-			// Do nothing, just try the other share type
1499
-		}
1500
-
1501
-		try {
1502
-			$share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
1503
-			return $share;
1504
-		} catch (ShareNotFound $e) {
1505
-			// Do nothing, just try the other share type
1506
-		}
1507
-
1508
-		try {
1509
-			if ($this->shareManager->shareProviderExists(IShare::TYPE_DECK)) {
1510
-				$share = $this->shareManager->getShareById('deck:' . $id, $this->currentUser);
1511
-				return $share;
1512
-			}
1513
-		} catch (ShareNotFound $e) {
1514
-			// Do nothing, just try the other share type
1515
-		}
1516
-
1517
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
1518
-			throw new ShareNotFound();
1519
-		}
1520
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
1521
-
1522
-		return $share;
1523
-	}
1524
-
1525
-	/**
1526
-	 * Lock a Node
1527
-	 *
1528
-	 * @param \OCP\Files\Node $node
1529
-	 * @throws LockedException
1530
-	 */
1531
-	private function lock(\OCP\Files\Node $node) {
1532
-		$node->lock(ILockingProvider::LOCK_SHARED);
1533
-		$this->lockedNode = $node;
1534
-	}
1535
-
1536
-	/**
1537
-	 * Cleanup the remaining locks
1538
-	 * @throws LockedException
1539
-	 */
1540
-	public function cleanup() {
1541
-		if ($this->lockedNode !== null) {
1542
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
1543
-		}
1544
-	}
1545
-
1546
-	/**
1547
-	 * Returns the helper of ShareAPIController for room shares.
1548
-	 *
1549
-	 * If the Talk application is not enabled or the helper is not available
1550
-	 * a QueryException is thrown instead.
1551
-	 *
1552
-	 * @return \OCA\Talk\Share\Helper\ShareAPIController
1553
-	 * @throws QueryException
1554
-	 */
1555
-	private function getRoomShareHelper() {
1556
-		if (!$this->appManager->isEnabledForUser('spreed')) {
1557
-			throw new QueryException();
1558
-		}
1559
-
1560
-		return $this->serverContainer->get('\OCA\Talk\Share\Helper\ShareAPIController');
1561
-	}
1562
-
1563
-	/**
1564
-	 * Returns the helper of ShareAPIHelper for deck shares.
1565
-	 *
1566
-	 * If the Deck application is not enabled or the helper is not available
1567
-	 * a QueryException is thrown instead.
1568
-	 *
1569
-	 * @return \OCA\Deck\Sharing\ShareAPIHelper
1570
-	 * @throws QueryException
1571
-	 */
1572
-	private function getDeckShareHelper() {
1573
-		if (!$this->appManager->isEnabledForUser('deck')) {
1574
-			throw new QueryException();
1575
-		}
1576
-
1577
-		return $this->serverContainer->get('\OCA\Deck\Sharing\ShareAPIHelper');
1578
-	}
1579
-
1580
-	/**
1581
-	 * @param string $viewer
1582
-	 * @param Node $node
1583
-	 * @param bool $reShares
1584
-	 *
1585
-	 * @return IShare[]
1586
-	 */
1587
-	private function getSharesFromNode(string $viewer, $node, bool $reShares): array {
1588
-		$providers = [
1589
-			IShare::TYPE_USER,
1590
-			IShare::TYPE_GROUP,
1591
-			IShare::TYPE_LINK,
1592
-			IShare::TYPE_EMAIL,
1593
-			IShare::TYPE_EMAIL,
1594
-			IShare::TYPE_CIRCLE,
1595
-			IShare::TYPE_ROOM,
1596
-			IShare::TYPE_DECK
1597
-		];
1598
-
1599
-		// Should we assume that the (currentUser) viewer is the owner of the node !?
1600
-		$shares = [];
1601
-		foreach ($providers as $provider) {
1602
-			if (!$this->shareManager->shareProviderExists($provider)) {
1603
-				continue;
1604
-			}
1605
-
1606
-			$providerShares =
1607
-				$this->shareManager->getSharesBy($viewer, $provider, $node, $reShares, -1, 0);
1608
-			$shares = array_merge($shares, $providerShares);
1609
-		}
1610
-
1611
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
1612
-			$federatedShares = $this->shareManager->getSharesBy(
1613
-				$this->currentUser, IShare::TYPE_REMOTE, $node, $reShares, -1, 0
1614
-			);
1615
-			$shares = array_merge($shares, $federatedShares);
1616
-		}
1617
-
1618
-		if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
1619
-			$federatedShares = $this->shareManager->getSharesBy(
1620
-				$this->currentUser, IShare::TYPE_REMOTE_GROUP, $node, $reShares, -1, 0
1621
-			);
1622
-			$shares = array_merge($shares, $federatedShares);
1623
-		}
1624
-
1625
-		return $shares;
1626
-	}
1627
-
1628
-
1629
-	/**
1630
-	 * @param Node $node
1631
-	 *
1632
-	 * @throws SharingRightsException
1633
-	 */
1634
-	private function confirmSharingRights(Node $node): void {
1635
-		if (!$this->hasResharingRights($this->currentUser, $node)) {
1636
-			throw new SharingRightsException('no sharing rights on this item');
1637
-		}
1638
-	}
1639
-
1640
-
1641
-	/**
1642
-	 * @param string $viewer
1643
-	 * @param Node $node
1644
-	 *
1645
-	 * @return bool
1646
-	 */
1647
-	private function hasResharingRights($viewer, $node): bool {
1648
-		if ($viewer === $node->getOwner()->getUID()) {
1649
-			return true;
1650
-		}
1651
-
1652
-		foreach ([$node, $node->getParent()] as $node) {
1653
-			$shares = $this->getSharesFromNode($viewer, $node, true);
1654
-			foreach ($shares as $share) {
1655
-				try {
1656
-					if ($this->shareProviderResharingRights($viewer, $share, $node)) {
1657
-						return true;
1658
-					}
1659
-				} catch (InvalidPathException | NotFoundException $e) {
1660
-				}
1661
-			}
1662
-		}
1663
-
1664
-		return false;
1665
-	}
1666
-
1667
-
1668
-	/**
1669
-	 * Returns if we can find resharing rights in an IShare object for a specific user.
1670
-	 *
1671
-	 * @suppress PhanUndeclaredClassMethod
1672
-	 *
1673
-	 * @param string $userId
1674
-	 * @param IShare $share
1675
-	 * @param Node $node
1676
-	 *
1677
-	 * @return bool
1678
-	 * @throws NotFoundException
1679
-	 * @throws InvalidPathException
1680
-	 */
1681
-	private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
1682
-		if ($share->getShareOwner() === $userId) {
1683
-			return true;
1684
-		}
1685
-
1686
-		// we check that current user have parent resharing rights on the current file
1687
-		if ($node !== null && ($node->getPermissions() & Constants::PERMISSION_SHARE) !== 0) {
1688
-			return true;
1689
-		}
1690
-
1691
-		if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
1692
-			return false;
1693
-		}
1694
-
1695
-		if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() === $userId) {
1696
-			return true;
1697
-		}
1698
-
1699
-		if ($share->getShareType() === IShare::TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
1700
-			return true;
1701
-		}
1702
-
1703
-		if ($share->getShareType() === IShare::TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles')
1704
-			&& class_exists('\OCA\Circles\Api\v1\Circles')) {
1705
-			$hasCircleId = (substr($share->getSharedWith(), -1) === ']');
1706
-			$shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
1707
-			$shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
1708
-			if ($shareWithLength === false) {
1709
-				$sharedWith = substr($share->getSharedWith(), $shareWithStart);
1710
-			} else {
1711
-				$sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
1712
-			}
1713
-			try {
1714
-				$member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
1715
-				if ($member->getLevel() >= 4) {
1716
-					return true;
1717
-				}
1718
-				return false;
1719
-			} catch (QueryException $e) {
1720
-				return false;
1721
-			}
1722
-		}
1723
-
1724
-		return false;
1725
-	}
1726
-
1727
-	/**
1728
-	 * Get all the shares for the current user
1729
-	 *
1730
-	 * @param Node|null $path
1731
-	 * @param boolean $reshares
1732
-	 * @return IShare[]
1733
-	 */
1734
-	private function getAllShares(?Node $path = null, bool $reshares = false) {
1735
-		// Get all shares
1736
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_USER, $path, $reshares, -1, 0);
1737
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_GROUP, $path, $reshares, -1, 0);
1738
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_LINK, $path, $reshares, -1, 0);
1739
-
1740
-		// EMAIL SHARES
1741
-		$mailShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_EMAIL, $path, $reshares, -1, 0);
1742
-
1743
-		// CIRCLE SHARES
1744
-		$circleShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_CIRCLE, $path, $reshares, -1, 0);
1745
-
1746
-		// TALK SHARES
1747
-		$roomShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_ROOM, $path, $reshares, -1, 0);
1748
-
1749
-		$deckShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_DECK, $path, $reshares, -1, 0);
1750
-
1751
-		// FEDERATION
1752
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
1753
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE, $path, $reshares, -1, 0);
1754
-		} else {
1755
-			$federatedShares = [];
1756
-		}
1757
-		if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
1758
-			$federatedGroupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
1759
-		} else {
1760
-			$federatedGroupShares = [];
1761
-		}
1762
-
1763
-		return array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares, $deckShares, $federatedShares, $federatedGroupShares);
1764
-	}
1765
-
1766
-
1767
-	/**
1768
-	 * merging already formatted shares.
1769
-	 * We'll make an associative array to easily detect duplicate Ids.
1770
-	 * Keys _needs_ to be removed after all shares are retrieved and merged.
1771
-	 *
1772
-	 * @param array $shares
1773
-	 * @param array $newShares
1774
-	 */
1775
-	private function mergeFormattedShares(array &$shares, array $newShares) {
1776
-		foreach ($newShares as $newShare) {
1777
-			if (!array_key_exists($newShare['id'], $shares)) {
1778
-				$shares[$newShare['id']] = $newShare;
1779
-			}
1780
-		}
1781
-	}
835
+                continue;
836
+            }
837
+
838
+            if (in_array($share->getId(), $known)
839
+                || ($share->getSharedWith() === $this->currentUser && $share->getShareType() === IShare::TYPE_USER)) {
840
+                continue;
841
+            }
842
+
843
+            $known[] = $share->getId();
844
+            try {
845
+                /** @var IShare $share */
846
+                $format = $this->formatShare($share, $node);
847
+                $formatted[] = $format;
848
+
849
+                // let's also build a list of shares created
850
+                // by the current user only, in case
851
+                // there is no resharing rights
852
+                if ($share->getSharedBy() === $this->currentUser) {
853
+                    $miniFormatted[] = $format;
854
+                }
855
+
856
+                // check if one of those share is shared with me
857
+                // and if I have resharing rights on it
858
+                if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $node)) {
859
+                    $resharingRight = true;
860
+                }
861
+            } catch (InvalidPathException | NotFoundException $e) {
862
+            }
863
+        }
864
+
865
+        if (!$resharingRight) {
866
+            $formatted = $miniFormatted;
867
+        }
868
+
869
+        if ($includeTags) {
870
+            $formatted =
871
+                Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
872
+        }
873
+
874
+        return $formatted;
875
+    }
876
+
877
+
878
+    /**
879
+     * The getInheritedShares function.
880
+     * returns all shares relative to a file, including parent folders shares rights.
881
+     *
882
+     * @NoAdminRequired
883
+     *
884
+     * @param string $path
885
+     *
886
+     * - Get shares by the current user
887
+     * - Get shares by the current user and reshares (?reshares=true)
888
+     * - Get shares with the current user (?shared_with_me=true)
889
+     * - Get shares for a specific path (?path=...)
890
+     * - Get all shares in a folder (?subfiles=true&path=..)
891
+     *
892
+     * @return DataResponse
893
+     * @throws InvalidPathException
894
+     * @throws NotFoundException
895
+     * @throws OCSNotFoundException
896
+     * @throws OCSBadRequestException
897
+     * @throws SharingRightsException
898
+     */
899
+    public function getInheritedShares(string $path): DataResponse {
900
+
901
+        // get Node from (string) path.
902
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
903
+        try {
904
+            $node = $userFolder->get($path);
905
+            $this->lock($node);
906
+        } catch (\OCP\Files\NotFoundException $e) {
907
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
908
+        } catch (LockedException $e) {
909
+            throw new OCSNotFoundException($this->l->t('Could not lock path'));
910
+        }
911
+
912
+        if (!($node->getPermissions() & Constants::PERMISSION_SHARE)) {
913
+            throw new SharingRightsException('no sharing rights on this item');
914
+        }
915
+
916
+        // The current top parent we have access to
917
+        $parent = $node;
918
+
919
+        // initiate real owner.
920
+        $owner = $node->getOwner()
921
+                        ->getUID();
922
+        if (!$this->userManager->userExists($owner)) {
923
+            return new DataResponse([]);
924
+        }
925
+
926
+        // get node based on the owner, fix owner in case of external storage
927
+        $userFolder = $this->rootFolder->getUserFolder($owner);
928
+        if ($node->getId() !== $userFolder->getId() && !$userFolder->isSubNode($node)) {
929
+            $owner = $node->getOwner()
930
+                            ->getUID();
931
+            $userFolder = $this->rootFolder->getUserFolder($owner);
932
+            $nodes = $userFolder->getById($node->getId());
933
+            $node = array_shift($nodes);
934
+        }
935
+        $basePath = $userFolder->getPath();
936
+
937
+        // generate node list for each parent folders
938
+        /** @var Node[] $nodes */
939
+        $nodes = [];
940
+        while ($node->getPath() !== $basePath) {
941
+            $node = $node->getParent();
942
+            $nodes[] = $node;
943
+        }
944
+
945
+        // The user that is requesting this list
946
+        $currentUserFolder = $this->rootFolder->getUserFolder($this->currentUser);
947
+
948
+        // for each nodes, retrieve shares.
949
+        $shares = [];
950
+
951
+        foreach ($nodes as $node) {
952
+            $getShares = $this->getFormattedShares($owner, $node, false, true);
953
+
954
+            $currentUserNodes = $currentUserFolder->getById($node->getId());
955
+            if (!empty($currentUserNodes)) {
956
+                $parent = array_pop($currentUserNodes);
957
+            }
958
+
959
+            $subPath = $currentUserFolder->getRelativePath($parent->getPath());
960
+            foreach ($getShares as &$share) {
961
+                $share['via_fileid'] = $parent->getId();
962
+                $share['via_path'] = $subPath;
963
+            }
964
+            $this->mergeFormattedShares($shares, $getShares);
965
+        }
966
+
967
+        return new DataResponse(array_values($shares));
968
+    }
969
+
970
+
971
+    /**
972
+     * @NoAdminRequired
973
+     *
974
+     * @param string $id
975
+     * @param int $permissions
976
+     * @param string $password
977
+     * @param string $sendPasswordByTalk
978
+     * @param string $publicUpload
979
+     * @param string $expireDate
980
+     * @param string $note
981
+     * @param string $label
982
+     * @param string $hideDownload
983
+     * @return DataResponse
984
+     * @throws LockedException
985
+     * @throws NotFoundException
986
+     * @throws OCSBadRequestException
987
+     * @throws OCSForbiddenException
988
+     * @throws OCSNotFoundException
989
+     */
990
+    public function updateShare(
991
+        string $id,
992
+        int $permissions = null,
993
+        string $password = null,
994
+        string $sendPasswordByTalk = null,
995
+        string $publicUpload = null,
996
+        string $expireDate = null,
997
+        string $note = null,
998
+        string $label = null,
999
+        string $hideDownload = null
1000
+    ): DataResponse {
1001
+        try {
1002
+            $share = $this->getShareById($id);
1003
+        } catch (ShareNotFound $e) {
1004
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1005
+        }
1006
+
1007
+        $this->lock($share->getNode());
1008
+
1009
+        if (!$this->canAccessShare($share, false)) {
1010
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1011
+        }
1012
+
1013
+        if (!$this->canEditShare($share)) {
1014
+            throw new OCSForbiddenException('You are not allowed to edit incoming shares');
1015
+        }
1016
+
1017
+        if (
1018
+            $permissions === null &&
1019
+            $password === null &&
1020
+            $sendPasswordByTalk === null &&
1021
+            $publicUpload === null &&
1022
+            $expireDate === null &&
1023
+            $note === null &&
1024
+            $label === null &&
1025
+            $hideDownload === null
1026
+        ) {
1027
+            throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
1028
+        }
1029
+
1030
+        if ($note !== null) {
1031
+            $share->setNote($note);
1032
+        }
1033
+
1034
+        /**
1035
+         * expirationdate, password and publicUpload only make sense for link shares
1036
+         */
1037
+        if ($share->getShareType() === IShare::TYPE_LINK
1038
+            || $share->getShareType() === IShare::TYPE_EMAIL) {
1039
+
1040
+            /**
1041
+             * We do not allow editing link shares that the current user
1042
+             * doesn't own. This is confusing and lead to errors when
1043
+             * someone else edit a password or expiration date without
1044
+             * the share owner knowing about it.
1045
+             * We only allow deletion
1046
+             */
1047
+
1048
+            if ($share->getSharedBy() !== $this->currentUser) {
1049
+                throw new OCSForbiddenException('You are not allowed to edit link shares that you don\'t own');
1050
+            }
1051
+
1052
+            // Update hide download state
1053
+            if ($hideDownload === 'true') {
1054
+                $share->setHideDownload(true);
1055
+            } elseif ($hideDownload === 'false') {
1056
+                $share->setHideDownload(false);
1057
+            }
1058
+
1059
+            $newPermissions = null;
1060
+            if ($publicUpload === 'true') {
1061
+                $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
1062
+            } elseif ($publicUpload === 'false') {
1063
+                $newPermissions = Constants::PERMISSION_READ;
1064
+            }
1065
+
1066
+            if ($permissions !== null) {
1067
+                $newPermissions = $permissions;
1068
+                $newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
1069
+            }
1070
+
1071
+            if ($newPermissions !== null &&
1072
+                !in_array($newPermissions, [
1073
+                    Constants::PERMISSION_READ,
1074
+                    Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE, // legacy
1075
+                    Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE, // correct
1076
+                    Constants::PERMISSION_CREATE, // hidden file list
1077
+                    Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, // allow to edit single files
1078
+                ], true)
1079
+            ) {
1080
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
1081
+            }
1082
+
1083
+            if (
1084
+                // legacy
1085
+                $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||
1086
+                // correct
1087
+                $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
1088
+            ) {
1089
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
1090
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
1091
+                }
1092
+
1093
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
1094
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
1095
+                }
1096
+
1097
+                // normalize to correct public upload permissions
1098
+                $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
1099
+            }
1100
+
1101
+            if ($newPermissions !== null) {
1102
+                // TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
1103
+                if (($newPermissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {
1104
+                    $newPermissions |= Constants::PERMISSION_SHARE;
1105
+                }
1106
+
1107
+                $share->setPermissions($newPermissions);
1108
+                $permissions = $newPermissions;
1109
+            }
1110
+
1111
+            if ($expireDate === '') {
1112
+                $share->setExpirationDate(null);
1113
+            } elseif ($expireDate !== null) {
1114
+                try {
1115
+                    $expireDate = $this->parseDate($expireDate);
1116
+                } catch (\Exception $e) {
1117
+                    throw new OCSBadRequestException($e->getMessage(), $e);
1118
+                }
1119
+                $share->setExpirationDate($expireDate);
1120
+            }
1121
+
1122
+            if ($password === '') {
1123
+                $share->setPassword(null);
1124
+            } elseif ($password !== null) {
1125
+                $share->setPassword($password);
1126
+            }
1127
+
1128
+            // only link shares have labels
1129
+            if ($share->getShareType() === IShare::TYPE_LINK && $label !== null) {
1130
+                if (strlen($label) > 255) {
1131
+                    throw new OCSBadRequestException("Maxmimum label length is 255");
1132
+                }
1133
+                $share->setLabel($label);
1134
+            }
1135
+
1136
+            if ($sendPasswordByTalk === 'true') {
1137
+                if (!$this->appManager->isEnabledForUser('spreed')) {
1138
+                    throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
1139
+                }
1140
+
1141
+                $share->setSendPasswordByTalk(true);
1142
+            } elseif ($sendPasswordByTalk !== null) {
1143
+                $share->setSendPasswordByTalk(false);
1144
+            }
1145
+        }
1146
+
1147
+        // NOT A LINK SHARE
1148
+        else {
1149
+            if ($permissions !== null) {
1150
+                $share->setPermissions($permissions);
1151
+            }
1152
+
1153
+            if ($expireDate === '') {
1154
+                $share->setExpirationDate(null);
1155
+            } elseif ($expireDate !== null) {
1156
+                try {
1157
+                    $expireDate = $this->parseDate($expireDate);
1158
+                } catch (\Exception $e) {
1159
+                    throw new OCSBadRequestException($e->getMessage(), $e);
1160
+                }
1161
+                $share->setExpirationDate($expireDate);
1162
+            }
1163
+        }
1164
+
1165
+        try {
1166
+            $share = $this->shareManager->updateShare($share);
1167
+        } catch (GenericShareException $e) {
1168
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
1169
+            throw new OCSException($e->getHint(), $code);
1170
+        } catch (\Exception $e) {
1171
+            throw new OCSBadRequestException($e->getMessage(), $e);
1172
+        }
1173
+
1174
+        return new DataResponse($this->formatShare($share));
1175
+    }
1176
+
1177
+    /**
1178
+     * @NoAdminRequired
1179
+     */
1180
+    public function pendingShares(): DataResponse {
1181
+        $pendingShares = [];
1182
+
1183
+        $shareTypes = [
1184
+            IShare::TYPE_USER,
1185
+            IShare::TYPE_GROUP
1186
+        ];
1187
+
1188
+        foreach ($shareTypes as $shareType) {
1189
+            $shares = $this->shareManager->getSharedWith($this->currentUser, $shareType, null, -1, 0);
1190
+
1191
+            foreach ($shares as $share) {
1192
+                if ($share->getStatus() === IShare::STATUS_PENDING || $share->getStatus() === IShare::STATUS_REJECTED) {
1193
+                    $pendingShares[] = $share;
1194
+                }
1195
+            }
1196
+        }
1197
+
1198
+        $result = array_filter(array_map(function (IShare $share) {
1199
+            $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1200
+            $nodes = $userFolder->getById($share->getNodeId());
1201
+            if (empty($nodes)) {
1202
+                // fallback to guessing the path
1203
+                $node = $userFolder->get($share->getTarget());
1204
+                if ($node === null || $share->getTarget() === '') {
1205
+                    return null;
1206
+                }
1207
+            } else {
1208
+                $node = $nodes[0];
1209
+            }
1210
+
1211
+            try {
1212
+                $formattedShare = $this->formatShare($share, $node);
1213
+                $formattedShare['status'] = $share->getStatus();
1214
+                $formattedShare['path'] = $share->getNode()->getName();
1215
+                $formattedShare['permissions'] = 0;
1216
+                return $formattedShare;
1217
+            } catch (NotFoundException $e) {
1218
+                return null;
1219
+            }
1220
+        }, $pendingShares), function ($entry) {
1221
+            return $entry !== null;
1222
+        });
1223
+
1224
+        return new DataResponse($result);
1225
+    }
1226
+
1227
+    /**
1228
+     * @NoAdminRequired
1229
+     *
1230
+     * @param string $id
1231
+     * @return DataResponse
1232
+     * @throws OCSNotFoundException
1233
+     * @throws OCSException
1234
+     * @throws OCSBadRequestException
1235
+     */
1236
+    public function acceptShare(string $id): DataResponse {
1237
+        try {
1238
+            $share = $this->getShareById($id);
1239
+        } catch (ShareNotFound $e) {
1240
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1241
+        }
1242
+
1243
+        if (!$this->canAccessShare($share)) {
1244
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
1245
+        }
1246
+
1247
+        try {
1248
+            $this->shareManager->acceptShare($share, $this->currentUser);
1249
+        } catch (GenericShareException $e) {
1250
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
1251
+            throw new OCSException($e->getHint(), $code);
1252
+        } catch (\Exception $e) {
1253
+            throw new OCSBadRequestException($e->getMessage(), $e);
1254
+        }
1255
+
1256
+        return new DataResponse();
1257
+    }
1258
+
1259
+    /**
1260
+     * Does the user have read permission on the share
1261
+     *
1262
+     * @param \OCP\Share\IShare $share the share to check
1263
+     * @param boolean $checkGroups check groups as well?
1264
+     * @return boolean
1265
+     * @throws NotFoundException
1266
+     *
1267
+     * @suppress PhanUndeclaredClassMethod
1268
+     */
1269
+    protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
1270
+        // A file with permissions 0 can't be accessed by us. So Don't show it
1271
+        if ($share->getPermissions() === 0) {
1272
+            return false;
1273
+        }
1274
+
1275
+        // Owner of the file and the sharer of the file can always get share
1276
+        if ($share->getShareOwner() === $this->currentUser
1277
+            || $share->getSharedBy() === $this->currentUser) {
1278
+            return true;
1279
+        }
1280
+
1281
+        // If the share is shared with you, you can access it!
1282
+        if ($share->getShareType() === IShare::TYPE_USER
1283
+            && $share->getSharedWith() === $this->currentUser) {
1284
+            return true;
1285
+        }
1286
+
1287
+        // Have reshare rights on the shared file/folder ?
1288
+        // Does the currentUser have access to the shared file?
1289
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
1290
+        $files = $userFolder->getById($share->getNodeId());
1291
+        if (!empty($files) && $this->shareProviderResharingRights($this->currentUser, $share, $files[0])) {
1292
+            return true;
1293
+        }
1294
+
1295
+        // If in the recipient group, you can see the share
1296
+        if ($checkGroups && $share->getShareType() === IShare::TYPE_GROUP) {
1297
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1298
+            $user = $this->userManager->get($this->currentUser);
1299
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1300
+                return true;
1301
+            }
1302
+        }
1303
+
1304
+        if ($share->getShareType() === IShare::TYPE_CIRCLE) {
1305
+            // TODO: have a sanity check like above?
1306
+            return true;
1307
+        }
1308
+
1309
+        if ($share->getShareType() === IShare::TYPE_ROOM) {
1310
+            try {
1311
+                return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1312
+            } catch (QueryException $e) {
1313
+                return false;
1314
+            }
1315
+        }
1316
+
1317
+        if ($share->getShareType() === IShare::TYPE_DECK) {
1318
+            try {
1319
+                return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
1320
+            } catch (QueryException $e) {
1321
+                return false;
1322
+            }
1323
+        }
1324
+
1325
+        return false;
1326
+    }
1327
+
1328
+    /**
1329
+     * Does the user have edit permission on the share
1330
+     *
1331
+     * @param \OCP\Share\IShare $share the share to check
1332
+     * @return boolean
1333
+     */
1334
+    protected function canEditShare(\OCP\Share\IShare $share): bool {
1335
+        // A file with permissions 0 can't be accessed by us. So Don't show it
1336
+        if ($share->getPermissions() === 0) {
1337
+            return false;
1338
+        }
1339
+
1340
+        // The owner of the file and the creator of the share
1341
+        // can always edit the share
1342
+        if ($share->getShareOwner() === $this->currentUser ||
1343
+            $share->getSharedBy() === $this->currentUser
1344
+        ) {
1345
+            return true;
1346
+        }
1347
+
1348
+        //! we do NOT support some kind of `admin` in groups.
1349
+        //! You cannot edit shares shared to a group you're
1350
+        //! a member of if you're not the share owner or the file owner!
1351
+
1352
+        return false;
1353
+    }
1354
+
1355
+    /**
1356
+     * Does the user have delete permission on the share
1357
+     *
1358
+     * @param \OCP\Share\IShare $share the share to check
1359
+     * @return boolean
1360
+     */
1361
+    protected function canDeleteShare(\OCP\Share\IShare $share): bool {
1362
+        // A file with permissions 0 can't be accessed by us. So Don't show it
1363
+        if ($share->getPermissions() === 0) {
1364
+            return false;
1365
+        }
1366
+
1367
+        // if the user is the recipient, i can unshare
1368
+        // the share with self
1369
+        if ($share->getShareType() === IShare::TYPE_USER &&
1370
+            $share->getSharedWith() === $this->currentUser
1371
+        ) {
1372
+            return true;
1373
+        }
1374
+
1375
+        // The owner of the file and the creator of the share
1376
+        // can always delete the share
1377
+        if ($share->getShareOwner() === $this->currentUser ||
1378
+            $share->getSharedBy() === $this->currentUser
1379
+        ) {
1380
+            return true;
1381
+        }
1382
+
1383
+        return false;
1384
+    }
1385
+
1386
+    /**
1387
+     * Does the user have delete permission on the share
1388
+     * This differs from the canDeleteShare function as it only
1389
+     * remove the share for the current user. It does NOT
1390
+     * completely delete the share but only the mount point.
1391
+     * It can then be restored from the deleted shares section.
1392
+     *
1393
+     * @param \OCP\Share\IShare $share the share to check
1394
+     * @return boolean
1395
+     *
1396
+     * @suppress PhanUndeclaredClassMethod
1397
+     */
1398
+    protected function canDeleteShareFromSelf(\OCP\Share\IShare $share): bool {
1399
+        if ($share->getShareType() !== IShare::TYPE_GROUP &&
1400
+            $share->getShareType() !== IShare::TYPE_ROOM &&
1401
+            $share->getShareType() !== IShare::TYPE_DECK
1402
+        ) {
1403
+            return false;
1404
+        }
1405
+
1406
+        if ($share->getShareOwner() === $this->currentUser ||
1407
+            $share->getSharedBy() === $this->currentUser
1408
+        ) {
1409
+            // Delete the whole share, not just for self
1410
+            return false;
1411
+        }
1412
+
1413
+        // If in the recipient group, you can delete the share from self
1414
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
1415
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1416
+            $user = $this->userManager->get($this->currentUser);
1417
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1418
+                return true;
1419
+            }
1420
+        }
1421
+
1422
+        if ($share->getShareType() === IShare::TYPE_ROOM) {
1423
+            try {
1424
+                return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1425
+            } catch (QueryException $e) {
1426
+                return false;
1427
+            }
1428
+        }
1429
+
1430
+        if ($share->getShareType() === IShare::TYPE_DECK) {
1431
+            try {
1432
+                return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
1433
+            } catch (QueryException $e) {
1434
+                return false;
1435
+            }
1436
+        }
1437
+
1438
+        return false;
1439
+    }
1440
+
1441
+    /**
1442
+     * Make sure that the passed date is valid ISO 8601
1443
+     * So YYYY-MM-DD
1444
+     * If not throw an exception
1445
+     *
1446
+     * @param string $expireDate
1447
+     *
1448
+     * @throws \Exception
1449
+     * @return \DateTime
1450
+     */
1451
+    private function parseDate(string $expireDate): \DateTime {
1452
+        try {
1453
+            $date = new \DateTime($expireDate);
1454
+        } catch (\Exception $e) {
1455
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1456
+        }
1457
+
1458
+        $date->setTime(0, 0, 0);
1459
+
1460
+        return $date;
1461
+    }
1462
+
1463
+    /**
1464
+     * Since we have multiple providers but the OCS Share API v1 does
1465
+     * not support this we need to check all backends.
1466
+     *
1467
+     * @param string $id
1468
+     * @return \OCP\Share\IShare
1469
+     * @throws ShareNotFound
1470
+     */
1471
+    private function getShareById(string $id): IShare {
1472
+        $share = null;
1473
+
1474
+        // First check if it is an internal share.
1475
+        try {
1476
+            $share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
1477
+            return $share;
1478
+        } catch (ShareNotFound $e) {
1479
+            // Do nothing, just try the other share type
1480
+        }
1481
+
1482
+
1483
+        try {
1484
+            if ($this->shareManager->shareProviderExists(IShare::TYPE_CIRCLE)) {
1485
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
1486
+                return $share;
1487
+            }
1488
+        } catch (ShareNotFound $e) {
1489
+            // Do nothing, just try the other share type
1490
+        }
1491
+
1492
+        try {
1493
+            if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
1494
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
1495
+                return $share;
1496
+            }
1497
+        } catch (ShareNotFound $e) {
1498
+            // Do nothing, just try the other share type
1499
+        }
1500
+
1501
+        try {
1502
+            $share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
1503
+            return $share;
1504
+        } catch (ShareNotFound $e) {
1505
+            // Do nothing, just try the other share type
1506
+        }
1507
+
1508
+        try {
1509
+            if ($this->shareManager->shareProviderExists(IShare::TYPE_DECK)) {
1510
+                $share = $this->shareManager->getShareById('deck:' . $id, $this->currentUser);
1511
+                return $share;
1512
+            }
1513
+        } catch (ShareNotFound $e) {
1514
+            // Do nothing, just try the other share type
1515
+        }
1516
+
1517
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
1518
+            throw new ShareNotFound();
1519
+        }
1520
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
1521
+
1522
+        return $share;
1523
+    }
1524
+
1525
+    /**
1526
+     * Lock a Node
1527
+     *
1528
+     * @param \OCP\Files\Node $node
1529
+     * @throws LockedException
1530
+     */
1531
+    private function lock(\OCP\Files\Node $node) {
1532
+        $node->lock(ILockingProvider::LOCK_SHARED);
1533
+        $this->lockedNode = $node;
1534
+    }
1535
+
1536
+    /**
1537
+     * Cleanup the remaining locks
1538
+     * @throws LockedException
1539
+     */
1540
+    public function cleanup() {
1541
+        if ($this->lockedNode !== null) {
1542
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
1543
+        }
1544
+    }
1545
+
1546
+    /**
1547
+     * Returns the helper of ShareAPIController for room shares.
1548
+     *
1549
+     * If the Talk application is not enabled or the helper is not available
1550
+     * a QueryException is thrown instead.
1551
+     *
1552
+     * @return \OCA\Talk\Share\Helper\ShareAPIController
1553
+     * @throws QueryException
1554
+     */
1555
+    private function getRoomShareHelper() {
1556
+        if (!$this->appManager->isEnabledForUser('spreed')) {
1557
+            throw new QueryException();
1558
+        }
1559
+
1560
+        return $this->serverContainer->get('\OCA\Talk\Share\Helper\ShareAPIController');
1561
+    }
1562
+
1563
+    /**
1564
+     * Returns the helper of ShareAPIHelper for deck shares.
1565
+     *
1566
+     * If the Deck application is not enabled or the helper is not available
1567
+     * a QueryException is thrown instead.
1568
+     *
1569
+     * @return \OCA\Deck\Sharing\ShareAPIHelper
1570
+     * @throws QueryException
1571
+     */
1572
+    private function getDeckShareHelper() {
1573
+        if (!$this->appManager->isEnabledForUser('deck')) {
1574
+            throw new QueryException();
1575
+        }
1576
+
1577
+        return $this->serverContainer->get('\OCA\Deck\Sharing\ShareAPIHelper');
1578
+    }
1579
+
1580
+    /**
1581
+     * @param string $viewer
1582
+     * @param Node $node
1583
+     * @param bool $reShares
1584
+     *
1585
+     * @return IShare[]
1586
+     */
1587
+    private function getSharesFromNode(string $viewer, $node, bool $reShares): array {
1588
+        $providers = [
1589
+            IShare::TYPE_USER,
1590
+            IShare::TYPE_GROUP,
1591
+            IShare::TYPE_LINK,
1592
+            IShare::TYPE_EMAIL,
1593
+            IShare::TYPE_EMAIL,
1594
+            IShare::TYPE_CIRCLE,
1595
+            IShare::TYPE_ROOM,
1596
+            IShare::TYPE_DECK
1597
+        ];
1598
+
1599
+        // Should we assume that the (currentUser) viewer is the owner of the node !?
1600
+        $shares = [];
1601
+        foreach ($providers as $provider) {
1602
+            if (!$this->shareManager->shareProviderExists($provider)) {
1603
+                continue;
1604
+            }
1605
+
1606
+            $providerShares =
1607
+                $this->shareManager->getSharesBy($viewer, $provider, $node, $reShares, -1, 0);
1608
+            $shares = array_merge($shares, $providerShares);
1609
+        }
1610
+
1611
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
1612
+            $federatedShares = $this->shareManager->getSharesBy(
1613
+                $this->currentUser, IShare::TYPE_REMOTE, $node, $reShares, -1, 0
1614
+            );
1615
+            $shares = array_merge($shares, $federatedShares);
1616
+        }
1617
+
1618
+        if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
1619
+            $federatedShares = $this->shareManager->getSharesBy(
1620
+                $this->currentUser, IShare::TYPE_REMOTE_GROUP, $node, $reShares, -1, 0
1621
+            );
1622
+            $shares = array_merge($shares, $federatedShares);
1623
+        }
1624
+
1625
+        return $shares;
1626
+    }
1627
+
1628
+
1629
+    /**
1630
+     * @param Node $node
1631
+     *
1632
+     * @throws SharingRightsException
1633
+     */
1634
+    private function confirmSharingRights(Node $node): void {
1635
+        if (!$this->hasResharingRights($this->currentUser, $node)) {
1636
+            throw new SharingRightsException('no sharing rights on this item');
1637
+        }
1638
+    }
1639
+
1640
+
1641
+    /**
1642
+     * @param string $viewer
1643
+     * @param Node $node
1644
+     *
1645
+     * @return bool
1646
+     */
1647
+    private function hasResharingRights($viewer, $node): bool {
1648
+        if ($viewer === $node->getOwner()->getUID()) {
1649
+            return true;
1650
+        }
1651
+
1652
+        foreach ([$node, $node->getParent()] as $node) {
1653
+            $shares = $this->getSharesFromNode($viewer, $node, true);
1654
+            foreach ($shares as $share) {
1655
+                try {
1656
+                    if ($this->shareProviderResharingRights($viewer, $share, $node)) {
1657
+                        return true;
1658
+                    }
1659
+                } catch (InvalidPathException | NotFoundException $e) {
1660
+                }
1661
+            }
1662
+        }
1663
+
1664
+        return false;
1665
+    }
1666
+
1667
+
1668
+    /**
1669
+     * Returns if we can find resharing rights in an IShare object for a specific user.
1670
+     *
1671
+     * @suppress PhanUndeclaredClassMethod
1672
+     *
1673
+     * @param string $userId
1674
+     * @param IShare $share
1675
+     * @param Node $node
1676
+     *
1677
+     * @return bool
1678
+     * @throws NotFoundException
1679
+     * @throws InvalidPathException
1680
+     */
1681
+    private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
1682
+        if ($share->getShareOwner() === $userId) {
1683
+            return true;
1684
+        }
1685
+
1686
+        // we check that current user have parent resharing rights on the current file
1687
+        if ($node !== null && ($node->getPermissions() & Constants::PERMISSION_SHARE) !== 0) {
1688
+            return true;
1689
+        }
1690
+
1691
+        if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
1692
+            return false;
1693
+        }
1694
+
1695
+        if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() === $userId) {
1696
+            return true;
1697
+        }
1698
+
1699
+        if ($share->getShareType() === IShare::TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
1700
+            return true;
1701
+        }
1702
+
1703
+        if ($share->getShareType() === IShare::TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles')
1704
+            && class_exists('\OCA\Circles\Api\v1\Circles')) {
1705
+            $hasCircleId = (substr($share->getSharedWith(), -1) === ']');
1706
+            $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
1707
+            $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
1708
+            if ($shareWithLength === false) {
1709
+                $sharedWith = substr($share->getSharedWith(), $shareWithStart);
1710
+            } else {
1711
+                $sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
1712
+            }
1713
+            try {
1714
+                $member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
1715
+                if ($member->getLevel() >= 4) {
1716
+                    return true;
1717
+                }
1718
+                return false;
1719
+            } catch (QueryException $e) {
1720
+                return false;
1721
+            }
1722
+        }
1723
+
1724
+        return false;
1725
+    }
1726
+
1727
+    /**
1728
+     * Get all the shares for the current user
1729
+     *
1730
+     * @param Node|null $path
1731
+     * @param boolean $reshares
1732
+     * @return IShare[]
1733
+     */
1734
+    private function getAllShares(?Node $path = null, bool $reshares = false) {
1735
+        // Get all shares
1736
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_USER, $path, $reshares, -1, 0);
1737
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_GROUP, $path, $reshares, -1, 0);
1738
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_LINK, $path, $reshares, -1, 0);
1739
+
1740
+        // EMAIL SHARES
1741
+        $mailShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_EMAIL, $path, $reshares, -1, 0);
1742
+
1743
+        // CIRCLE SHARES
1744
+        $circleShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_CIRCLE, $path, $reshares, -1, 0);
1745
+
1746
+        // TALK SHARES
1747
+        $roomShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_ROOM, $path, $reshares, -1, 0);
1748
+
1749
+        $deckShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_DECK, $path, $reshares, -1, 0);
1750
+
1751
+        // FEDERATION
1752
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
1753
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE, $path, $reshares, -1, 0);
1754
+        } else {
1755
+            $federatedShares = [];
1756
+        }
1757
+        if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
1758
+            $federatedGroupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
1759
+        } else {
1760
+            $federatedGroupShares = [];
1761
+        }
1762
+
1763
+        return array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares, $deckShares, $federatedShares, $federatedGroupShares);
1764
+    }
1765
+
1766
+
1767
+    /**
1768
+     * merging already formatted shares.
1769
+     * We'll make an associative array to easily detect duplicate Ids.
1770
+     * Keys _needs_ to be removed after all shares are retrieved and merged.
1771
+     *
1772
+     * @param array $shares
1773
+     * @param array $newShares
1774
+     */
1775
+    private function mergeFormattedShares(array &$shares, array $newShares) {
1776
+        foreach ($newShares as $newShare) {
1777
+            if (!array_key_exists($newShare['id'], $shares)) {
1778
+                $shares[$newShare['id']] = $newShare;
1779
+            }
1780
+        }
1781
+    }
1782 1782
 }
Please login to merge, or discard this patch.