CloudFederationProviderFiles.php 25 KB

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