CloudFederationProviderFiles.php 23 KB

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