CloudFederationProviderFiles.php 26 KB

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