You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CloudFederationProviderFiles.php 26KB

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