CloudFederationProviderFiles.php 24 KB

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