CloudFederationProviderFiles.php 24 KB

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