CloudFederationProviderFiles.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\FederatedFileSharing\OCM;
  7. use OC\AppFramework\Http;
  8. use OC\Files\Filesystem;
  9. use OCA\FederatedFileSharing\AddressHandler;
  10. use OCA\FederatedFileSharing\FederatedShareProvider;
  11. use OCA\Files_Sharing\Activity\Providers\RemoteShares;
  12. use OCA\Files_Sharing\External\Manager;
  13. use OCP\Activity\IManager as IActivityManager;
  14. use OCP\App\IAppManager;
  15. use OCP\Constants;
  16. use OCP\Federation\Exceptions\ActionNotSupportedException;
  17. use OCP\Federation\Exceptions\AuthenticationFailedException;
  18. use OCP\Federation\Exceptions\BadRequestException;
  19. use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
  20. use OCP\Federation\ICloudFederationFactory;
  21. use OCP\Federation\ICloudFederationProvider;
  22. use OCP\Federation\ICloudFederationProviderManager;
  23. use OCP\Federation\ICloudFederationShare;
  24. use OCP\Federation\ICloudIdManager;
  25. use OCP\Files\IFilenameValidator;
  26. use OCP\Files\NotFoundException;
  27. use OCP\HintException;
  28. use OCP\IConfig;
  29. use OCP\IDBConnection;
  30. use OCP\IGroupManager;
  31. use OCP\IURLGenerator;
  32. use OCP\IUserManager;
  33. use OCP\Notification\IManager as INotificationManager;
  34. use OCP\Server;
  35. use OCP\Share\Exceptions\ShareNotFound;
  36. use OCP\Share\IManager;
  37. use OCP\Share\IShare;
  38. use OCP\Util;
  39. use Psr\Log\LoggerInterface;
  40. class CloudFederationProviderFiles implements ICloudFederationProvider {
  41. /**
  42. * CloudFederationProvider constructor.
  43. */
  44. public function __construct(
  45. private IAppManager $appManager,
  46. private FederatedShareProvider $federatedShareProvider,
  47. private AddressHandler $addressHandler,
  48. private IUserManager $userManager,
  49. private IManager $shareManager,
  50. private ICloudIdManager $cloudIdManager,
  51. private IActivityManager $activityManager,
  52. private INotificationManager $notificationManager,
  53. private IURLGenerator $urlGenerator,
  54. private ICloudFederationFactory $cloudFederationFactory,
  55. private ICloudFederationProviderManager $cloudFederationProviderManager,
  56. private IDBConnection $connection,
  57. private IGroupManager $groupManager,
  58. private IConfig $config,
  59. private Manager $externalShareManager,
  60. private LoggerInterface $logger,
  61. private IFilenameValidator $filenameValidator,
  62. ) {
  63. }
  64. /**
  65. * @return string
  66. */
  67. public function getShareType() {
  68. return 'file';
  69. }
  70. /**
  71. * share received from another server
  72. *
  73. * @param ICloudFederationShare $share
  74. * @return string provider specific unique ID of the share
  75. *
  76. * @throws ProviderCouldNotAddShareException
  77. * @throws \OCP\AppFramework\QueryException
  78. * @throws HintException
  79. * @since 14.0.0
  80. */
  81. public function shareReceived(ICloudFederationShare $share) {
  82. if (!$this->isS2SEnabled(true)) {
  83. throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
  84. }
  85. $protocol = $share->getProtocol();
  86. if ($protocol['name'] !== 'webdav') {
  87. throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
  88. }
  89. [$ownerUid, $remote] = $this->addressHandler->splitUserRemote($share->getOwner());
  90. // for backward compatibility make sure that the remote url stored in the
  91. // database ends with a trailing slash
  92. if (!str_ends_with($remote, '/')) {
  93. $remote = $remote . '/';
  94. }
  95. $token = $share->getShareSecret();
  96. $name = $share->getResourceName();
  97. $owner = $share->getOwnerDisplayName();
  98. $sharedBy = $share->getSharedByDisplayName();
  99. $shareWith = $share->getShareWith();
  100. $remoteId = $share->getProviderId();
  101. $sharedByFederatedId = $share->getSharedBy();
  102. $ownerFederatedId = $share->getOwner();
  103. $shareType = $this->mapShareTypeToNextcloud($share->getShareType());
  104. // if no explicit information about the person who created the share was send
  105. // we assume that the share comes from the owner
  106. if ($sharedByFederatedId === null) {
  107. $sharedBy = $owner;
  108. $sharedByFederatedId = $ownerFederatedId;
  109. }
  110. if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
  111. if (!$this->filenameValidator->isFilenameValid($name)) {
  112. throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
  113. }
  114. // FIXME this should be a method in the user management instead
  115. if ($shareType === IShare::TYPE_USER) {
  116. $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
  117. Util::emitHook(
  118. '\OCA\Files_Sharing\API\Server2Server',
  119. 'preLoginNameUsedAsUserName',
  120. ['uid' => &$shareWith]
  121. );
  122. $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
  123. if (!$this->userManager->userExists($shareWith)) {
  124. throw new ProviderCouldNotAddShareException('User does not exists', '', Http::STATUS_BAD_REQUEST);
  125. }
  126. \OC_Util::setupFS($shareWith);
  127. }
  128. if ($shareType === IShare::TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
  129. throw new ProviderCouldNotAddShareException('Group does not exists', '', Http::STATUS_BAD_REQUEST);
  130. }
  131. try {
  132. $this->externalShareManager->addShare($remote, $token, '', $name, $owner, $shareType, false, $shareWith, $remoteId);
  133. $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
  134. // get DisplayName about the owner of the share
  135. $ownerDisplayName = $this->getUserDisplayName($ownerFederatedId);
  136. if ($shareType === IShare::TYPE_USER) {
  137. $event = $this->activityManager->generateEvent();
  138. $event->setApp('files_sharing')
  139. ->setType('remote_share')
  140. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/'), $ownerDisplayName])
  141. ->setAffectedUser($shareWith)
  142. ->setObject('remote_share', $shareId, $name);
  143. \OC::$server->getActivityManager()->publish($event);
  144. $this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name, $ownerDisplayName);
  145. } else {
  146. $groupMembers = $this->groupManager->get($shareWith)->getUsers();
  147. foreach ($groupMembers as $user) {
  148. $event = $this->activityManager->generateEvent();
  149. $event->setApp('files_sharing')
  150. ->setType('remote_share')
  151. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/'), $ownerDisplayName])
  152. ->setAffectedUser($user->getUID())
  153. ->setObject('remote_share', $shareId, $name);
  154. \OC::$server->getActivityManager()->publish($event);
  155. $this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name, $ownerDisplayName);
  156. }
  157. }
  158. return $shareId;
  159. } catch (\Exception $e) {
  160. $this->logger->error('Server can not add remote share.', [
  161. 'app' => 'files_sharing',
  162. 'exception' => $e,
  163. ]);
  164. throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
  165. }
  166. }
  167. throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
  168. }
  169. /**
  170. * notification received from another server
  171. *
  172. * @param string $notificationType (e.g. SHARE_ACCEPTED)
  173. * @param string $providerId id of the share
  174. * @param array $notification payload of the notification
  175. * @return array<string> data send back to the sender
  176. *
  177. * @throws ActionNotSupportedException
  178. * @throws AuthenticationFailedException
  179. * @throws BadRequestException
  180. * @throws HintException
  181. * @since 14.0.0
  182. */
  183. public function notificationReceived($notificationType, $providerId, array $notification) {
  184. switch ($notificationType) {
  185. case 'SHARE_ACCEPTED':
  186. return $this->shareAccepted($providerId, $notification);
  187. case 'SHARE_DECLINED':
  188. return $this->shareDeclined($providerId, $notification);
  189. case 'SHARE_UNSHARED':
  190. return $this->unshare($providerId, $notification);
  191. case 'REQUEST_RESHARE':
  192. return $this->reshareRequested($providerId, $notification);
  193. case 'RESHARE_UNDO':
  194. return $this->undoReshare($providerId, $notification);
  195. case 'RESHARE_CHANGE_PERMISSION':
  196. return $this->updateResharePermissions($providerId, $notification);
  197. }
  198. throw new BadRequestException([$notificationType]);
  199. }
  200. /**
  201. * map OCM share type (strings) to Nextcloud internal share types (integer)
  202. *
  203. * @param string $shareType
  204. * @return int
  205. */
  206. private function mapShareTypeToNextcloud($shareType) {
  207. $result = IShare::TYPE_USER;
  208. if ($shareType === 'group') {
  209. $result = IShare::TYPE_GROUP;
  210. }
  211. return $result;
  212. }
  213. private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name, $displayName): void {
  214. $notification = $this->notificationManager->createNotification();
  215. $notification->setApp('files_sharing')
  216. ->setUser($shareWith)
  217. ->setDateTime(new \DateTime())
  218. ->setObject('remote_share', $shareId)
  219. ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/'), $displayName]);
  220. $declineAction = $notification->createAction();
  221. $declineAction->setLabel('decline')
  222. ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
  223. $notification->addAction($declineAction);
  224. $acceptAction = $notification->createAction();
  225. $acceptAction->setLabel('accept')
  226. ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
  227. $notification->addAction($acceptAction);
  228. $this->notificationManager->notify($notification);
  229. }
  230. /**
  231. * process notification that the recipient accepted a share
  232. *
  233. * @param string $id
  234. * @param array $notification
  235. * @return array<string>
  236. * @throws ActionNotSupportedException
  237. * @throws AuthenticationFailedException
  238. * @throws BadRequestException
  239. * @throws HintException
  240. */
  241. private function shareAccepted($id, array $notification) {
  242. if (!$this->isS2SEnabled()) {
  243. throw new ActionNotSupportedException('Server does not support federated cloud sharing');
  244. }
  245. if (!isset($notification['sharedSecret'])) {
  246. throw new BadRequestException(['sharedSecret']);
  247. }
  248. $token = $notification['sharedSecret'];
  249. $share = $this->federatedShareProvider->getShareById($id);
  250. $this->verifyShare($share, $token);
  251. $this->executeAcceptShare($share);
  252. if ($share->getShareOwner() !== $share->getSharedBy()) {
  253. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  254. $remoteId = $this->federatedShareProvider->getRemoteId($share);
  255. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  256. $notification->setMessage(
  257. 'SHARE_ACCEPTED',
  258. 'file',
  259. $remoteId,
  260. [
  261. 'sharedSecret' => $token,
  262. 'message' => 'Recipient accepted the re-share'
  263. ]
  264. );
  265. $this->cloudFederationProviderManager->sendNotification($remote, $notification);
  266. }
  267. return [];
  268. }
  269. /**
  270. * @param IShare $share
  271. * @throws ShareNotFound
  272. */
  273. protected function executeAcceptShare(IShare $share) {
  274. try {
  275. $fileId = (int)$share->getNode()->getId();
  276. [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
  277. } catch (\Exception $e) {
  278. throw new ShareNotFound();
  279. }
  280. $event = $this->activityManager->generateEvent();
  281. $event->setApp('files_sharing')
  282. ->setType('remote_share')
  283. ->setAffectedUser($this->getCorrectUid($share))
  284. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
  285. ->setObject('files', $fileId, $file)
  286. ->setLink($link);
  287. $this->activityManager->publish($event);
  288. }
  289. /**
  290. * process notification that the recipient declined a share
  291. *
  292. * @param string $id
  293. * @param array $notification
  294. * @return array<string>
  295. * @throws ActionNotSupportedException
  296. * @throws AuthenticationFailedException
  297. * @throws BadRequestException
  298. * @throws ShareNotFound
  299. * @throws HintException
  300. *
  301. */
  302. protected function shareDeclined($id, array $notification) {
  303. if (!$this->isS2SEnabled()) {
  304. throw new ActionNotSupportedException('Server does not support federated cloud sharing');
  305. }
  306. if (!isset($notification['sharedSecret'])) {
  307. throw new BadRequestException(['sharedSecret']);
  308. }
  309. $token = $notification['sharedSecret'];
  310. $share = $this->federatedShareProvider->getShareById($id);
  311. $this->verifyShare($share, $token);
  312. if ($share->getShareOwner() !== $share->getSharedBy()) {
  313. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  314. $remoteId = $this->federatedShareProvider->getRemoteId($share);
  315. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  316. $notification->setMessage(
  317. 'SHARE_DECLINED',
  318. 'file',
  319. $remoteId,
  320. [
  321. 'sharedSecret' => $token,
  322. 'message' => 'Recipient declined the re-share'
  323. ]
  324. );
  325. $this->cloudFederationProviderManager->sendNotification($remote, $notification);
  326. }
  327. $this->executeDeclineShare($share);
  328. return [];
  329. }
  330. /**
  331. * delete declined share and create a activity
  332. *
  333. * @param IShare $share
  334. * @throws ShareNotFound
  335. */
  336. protected function executeDeclineShare(IShare $share) {
  337. $this->federatedShareProvider->removeShareFromTable($share);
  338. try {
  339. $fileId = (int)$share->getNode()->getId();
  340. [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
  341. } catch (\Exception $e) {
  342. throw new ShareNotFound();
  343. }
  344. $event = $this->activityManager->generateEvent();
  345. $event->setApp('files_sharing')
  346. ->setType('remote_share')
  347. ->setAffectedUser($this->getCorrectUid($share))
  348. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
  349. ->setObject('files', $fileId, $file)
  350. ->setLink($link);
  351. $this->activityManager->publish($event);
  352. }
  353. /**
  354. * received the notification that the owner unshared a file from you
  355. *
  356. * @param string $id
  357. * @param array $notification
  358. * @return array<string>
  359. * @throws AuthenticationFailedException
  360. * @throws BadRequestException
  361. */
  362. private function undoReshare($id, array $notification) {
  363. if (!isset($notification['sharedSecret'])) {
  364. throw new BadRequestException(['sharedSecret']);
  365. }
  366. $token = $notification['sharedSecret'];
  367. $share = $this->federatedShareProvider->getShareById($id);
  368. $this->verifyShare($share, $token);
  369. $this->federatedShareProvider->removeShareFromTable($share);
  370. return [];
  371. }
  372. /**
  373. * unshare file from self
  374. *
  375. * @param string $id
  376. * @param array $notification
  377. * @return array<string>
  378. * @throws ActionNotSupportedException
  379. * @throws BadRequestException
  380. */
  381. private function unshare($id, array $notification) {
  382. if (!$this->isS2SEnabled(true)) {
  383. throw new ActionNotSupportedException("incoming shares disabled!");
  384. }
  385. if (!isset($notification['sharedSecret'])) {
  386. throw new BadRequestException(['sharedSecret']);
  387. }
  388. $token = $notification['sharedSecret'];
  389. $qb = $this->connection->getQueryBuilder();
  390. $qb->select('*')
  391. ->from('share_external')
  392. ->where(
  393. $qb->expr()->andX(
  394. $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
  395. $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
  396. )
  397. );
  398. $result = $qb->execute();
  399. $share = $result->fetch();
  400. $result->closeCursor();
  401. if ($token && $id && !empty($share)) {
  402. $remote = $this->cleanupRemote($share['remote']);
  403. $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
  404. $mountpoint = $share['mountpoint'];
  405. $user = $share['user'];
  406. $qb = $this->connection->getQueryBuilder();
  407. $qb->delete('share_external')
  408. ->where(
  409. $qb->expr()->andX(
  410. $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
  411. $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
  412. )
  413. );
  414. $qb->execute();
  415. // delete all child in case of a group share
  416. $qb = $this->connection->getQueryBuilder();
  417. $qb->delete('share_external')
  418. ->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id'])));
  419. $qb->execute();
  420. $ownerDisplayName = $this->getUserDisplayName($owner->getId());
  421. if ((int)$share['share_type'] === IShare::TYPE_USER) {
  422. if ($share['accepted']) {
  423. $path = trim($mountpoint, '/');
  424. } else {
  425. $path = trim($share['name'], '/');
  426. }
  427. $notification = $this->notificationManager->createNotification();
  428. $notification->setApp('files_sharing')
  429. ->setUser($share['user'])
  430. ->setObject('remote_share', (int)$share['id']);
  431. $this->notificationManager->markProcessed($notification);
  432. $event = $this->activityManager->generateEvent();
  433. $event->setApp('files_sharing')
  434. ->setType('remote_share')
  435. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path, $ownerDisplayName])
  436. ->setAffectedUser($user)
  437. ->setObject('remote_share', (int)$share['id'], $path);
  438. \OC::$server->getActivityManager()->publish($event);
  439. }
  440. }
  441. return [];
  442. }
  443. private function cleanupRemote($remote) {
  444. $remote = substr($remote, strpos($remote, '://') + 3);
  445. return rtrim($remote, '/');
  446. }
  447. /**
  448. * recipient of a share request to re-share the file with another user
  449. *
  450. * @param string $id
  451. * @param array $notification
  452. * @return array<string>
  453. * @throws AuthenticationFailedException
  454. * @throws BadRequestException
  455. * @throws ProviderCouldNotAddShareException
  456. * @throws ShareNotFound
  457. */
  458. protected function reshareRequested($id, array $notification) {
  459. if (!isset($notification['sharedSecret'])) {
  460. throw new BadRequestException(['sharedSecret']);
  461. }
  462. $token = $notification['sharedSecret'];
  463. if (!isset($notification['shareWith'])) {
  464. throw new BadRequestException(['shareWith']);
  465. }
  466. $shareWith = $notification['shareWith'];
  467. if (!isset($notification['senderId'])) {
  468. throw new BadRequestException(['senderId']);
  469. }
  470. $senderId = $notification['senderId'];
  471. $share = $this->federatedShareProvider->getShareById($id);
  472. // We have to respect the default share permissions
  473. $permissions = $share->getPermissions() & (int)$this->config->getAppValue('core', 'shareapi_default_permissions', (string)Constants::PERMISSION_ALL);
  474. $share->setPermissions($permissions);
  475. // don't allow to share a file back to the owner
  476. try {
  477. [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
  478. $owner = $share->getShareOwner();
  479. $currentServer = $this->addressHandler->generateRemoteURL();
  480. if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
  481. throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
  482. }
  483. } catch (\Exception $e) {
  484. throw new ProviderCouldNotAddShareException($e->getMessage());
  485. }
  486. $this->verifyShare($share, $token);
  487. // check if re-sharing is allowed
  488. if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
  489. // the recipient of the initial share is now the initiator for the re-share
  490. $share->setSharedBy($share->getSharedWith());
  491. $share->setSharedWith($shareWith);
  492. $result = $this->federatedShareProvider->create($share);
  493. $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
  494. return ['token' => $result->getToken(), 'providerId' => $result->getId()];
  495. } else {
  496. throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
  497. }
  498. }
  499. /**
  500. * update permission of a re-share so that the share dialog shows the right
  501. * permission if the owner or the sender changes the permission
  502. *
  503. * @param string $id
  504. * @param array $notification
  505. * @return array<string>
  506. * @throws AuthenticationFailedException
  507. * @throws BadRequestException
  508. */
  509. protected function updateResharePermissions($id, array $notification) {
  510. throw new HintException('Updating reshares not allowed');
  511. }
  512. /**
  513. * translate OCM Permissions to Nextcloud permissions
  514. *
  515. * @param array $ocmPermissions
  516. * @return int
  517. * @throws BadRequestException
  518. */
  519. protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
  520. $ncPermissions = 0;
  521. foreach ($ocmPermissions as $permission) {
  522. switch (strtolower($permission)) {
  523. case 'read':
  524. $ncPermissions += Constants::PERMISSION_READ;
  525. break;
  526. case 'write':
  527. $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
  528. break;
  529. case 'share':
  530. $ncPermissions += Constants::PERMISSION_SHARE;
  531. break;
  532. default:
  533. throw new BadRequestException(['permission']);
  534. }
  535. }
  536. return $ncPermissions;
  537. }
  538. /**
  539. * update permissions in database
  540. *
  541. * @param IShare $share
  542. * @param int $permissions
  543. */
  544. protected function updatePermissionsInDatabase(IShare $share, $permissions) {
  545. $query = $this->connection->getQueryBuilder();
  546. $query->update('share')
  547. ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
  548. ->set('permissions', $query->createNamedParameter($permissions))
  549. ->execute();
  550. }
  551. /**
  552. * get file
  553. *
  554. * @param string $user
  555. * @param int $fileSource
  556. * @return array with internal path of the file and a absolute link to it
  557. */
  558. private function getFile($user, $fileSource) {
  559. \OC_Util::setupFS($user);
  560. try {
  561. $file = Filesystem::getPath($fileSource);
  562. } catch (NotFoundException $e) {
  563. $file = null;
  564. }
  565. $args = Filesystem::is_dir($file) ? ['dir' => $file] : ['dir' => dirname($file), 'scrollto' => $file];
  566. $link = Util::linkToAbsolute('files', 'index.php', $args);
  567. return [$file, $link];
  568. }
  569. /**
  570. * check if we are the initiator or the owner of a re-share and return the correct UID
  571. *
  572. * @param IShare $share
  573. * @return string
  574. */
  575. protected function getCorrectUid(IShare $share) {
  576. if ($this->userManager->userExists($share->getShareOwner())) {
  577. return $share->getShareOwner();
  578. }
  579. return $share->getSharedBy();
  580. }
  581. /**
  582. * check if we got the right share
  583. *
  584. * @param IShare $share
  585. * @param string $token
  586. * @return bool
  587. * @throws AuthenticationFailedException
  588. */
  589. protected function verifyShare(IShare $share, $token) {
  590. if (
  591. $share->getShareType() === IShare::TYPE_REMOTE &&
  592. $share->getToken() === $token
  593. ) {
  594. return true;
  595. }
  596. if ($share->getShareType() === IShare::TYPE_CIRCLE) {
  597. try {
  598. $knownShare = $this->shareManager->getShareByToken($token);
  599. if ($knownShare->getId() === $share->getId()) {
  600. return true;
  601. }
  602. } catch (ShareNotFound $e) {
  603. }
  604. }
  605. throw new AuthenticationFailedException();
  606. }
  607. /**
  608. * check if server-to-server sharing is enabled
  609. *
  610. * @param bool $incoming
  611. * @return bool
  612. */
  613. private function isS2SEnabled($incoming = false) {
  614. $result = $this->appManager->isEnabledForUser('files_sharing');
  615. if ($incoming) {
  616. $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
  617. } else {
  618. $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
  619. }
  620. return $result;
  621. }
  622. /**
  623. * get the supported share types, e.g. "user", "group", etc.
  624. *
  625. * @return array
  626. *
  627. * @since 14.0.0
  628. */
  629. public function getSupportedShareTypes() {
  630. return ['user', 'group'];
  631. }
  632. public function getUserDisplayName(string $userId): string {
  633. // check if gss is enabled and available
  634. if (!$this->appManager->isInstalled('globalsiteselector')
  635. || !class_exists('\OCA\GlobalSiteSelector\Service\SlaveService')) {
  636. return '';
  637. }
  638. try {
  639. $slaveService = Server::get(\OCA\GlobalSiteSelector\Service\SlaveService::class);
  640. } catch (\Throwable $e) {
  641. Server::get(LoggerInterface::class)->error(
  642. $e->getMessage(),
  643. ['exception' => $e]
  644. );
  645. return '';
  646. }
  647. return $slaveService->getUserDisplayName($this->cloudIdManager->removeProtocolFromUrl($userId), false);
  648. }
  649. }