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