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