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