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

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 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\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. use Psr\Log\LoggerInterface;
  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 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. [$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. \OC::$server->get(LoggerInterface::class)
  224. );
  225. try {
  226. $externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
  227. $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
  228. if ($shareType === IShare::TYPE_USER) {
  229. $event = $this->activityManager->generateEvent();
  230. $event->setApp('files_sharing')
  231. ->setType('remote_share')
  232. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
  233. ->setAffectedUser($shareWith)
  234. ->setObject('remote_share', $shareId, $name);
  235. \OC::$server->getActivityManager()->publish($event);
  236. $this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
  237. } else {
  238. $groupMembers = $this->groupManager->get($shareWith)->getUsers();
  239. foreach ($groupMembers as $user) {
  240. $event = $this->activityManager->generateEvent();
  241. $event->setApp('files_sharing')
  242. ->setType('remote_share')
  243. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
  244. ->setAffectedUser($user->getUID())
  245. ->setObject('remote_share', $shareId, $name);
  246. \OC::$server->getActivityManager()->publish($event);
  247. $this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
  248. }
  249. }
  250. return $shareId;
  251. } catch (\Exception $e) {
  252. $this->logger->logException($e, [
  253. 'message' => 'Server can not add remote share.',
  254. 'level' => ILogger::ERROR,
  255. 'app' => 'files_sharing'
  256. ]);
  257. throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
  258. }
  259. }
  260. throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
  261. }
  262. /**
  263. * notification received from another server
  264. *
  265. * @param string $notificationType (e.g. SHARE_ACCEPTED)
  266. * @param string $providerId id of the share
  267. * @param array $notification payload of the notification
  268. * @return array data send back to the sender
  269. *
  270. * @throws ActionNotSupportedException
  271. * @throws AuthenticationFailedException
  272. * @throws BadRequestException
  273. * @throws HintException
  274. * @since 14.0.0
  275. */
  276. public function notificationReceived($notificationType, $providerId, array $notification) {
  277. switch ($notificationType) {
  278. case 'SHARE_ACCEPTED':
  279. return $this->shareAccepted($providerId, $notification);
  280. case 'SHARE_DECLINED':
  281. return $this->shareDeclined($providerId, $notification);
  282. case 'SHARE_UNSHARED':
  283. return $this->unshare($providerId, $notification);
  284. case 'REQUEST_RESHARE':
  285. return $this->reshareRequested($providerId, $notification);
  286. case 'RESHARE_UNDO':
  287. return $this->undoReshare($providerId, $notification);
  288. case 'RESHARE_CHANGE_PERMISSION':
  289. return $this->updateResharePermissions($providerId, $notification);
  290. }
  291. throw new BadRequestException([$notificationType]);
  292. }
  293. /**
  294. * map OCM share type (strings) to Nextcloud internal share types (integer)
  295. *
  296. * @param string $shareType
  297. * @return int
  298. */
  299. private function mapShareTypeToNextcloud($shareType) {
  300. $result = IShare::TYPE_USER;
  301. if ($shareType === 'group') {
  302. $result = IShare::TYPE_GROUP;
  303. }
  304. return $result;
  305. }
  306. private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name): void {
  307. $notification = $this->notificationManager->createNotification();
  308. $notification->setApp('files_sharing')
  309. ->setUser($shareWith)
  310. ->setDateTime(new \DateTime())
  311. ->setObject('remote_share', $shareId)
  312. ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
  313. $declineAction = $notification->createAction();
  314. $declineAction->setLabel('decline')
  315. ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
  316. $notification->addAction($declineAction);
  317. $acceptAction = $notification->createAction();
  318. $acceptAction->setLabel('accept')
  319. ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
  320. $notification->addAction($acceptAction);
  321. $this->notificationManager->notify($notification);
  322. }
  323. /**
  324. * process notification that the recipient accepted a share
  325. *
  326. * @param string $id
  327. * @param array $notification
  328. * @return array
  329. * @throws ActionNotSupportedException
  330. * @throws AuthenticationFailedException
  331. * @throws BadRequestException
  332. * @throws HintException
  333. */
  334. private function shareAccepted($id, array $notification) {
  335. if (!$this->isS2SEnabled()) {
  336. throw new ActionNotSupportedException('Server does not support federated cloud sharing');
  337. }
  338. if (!isset($notification['sharedSecret'])) {
  339. throw new BadRequestException(['sharedSecret']);
  340. }
  341. $token = $notification['sharedSecret'];
  342. $share = $this->federatedShareProvider->getShareById($id);
  343. $this->verifyShare($share, $token);
  344. $this->executeAcceptShare($share);
  345. if ($share->getShareOwner() !== $share->getSharedBy()) {
  346. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  347. $remoteId = $this->federatedShareProvider->getRemoteId($share);
  348. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  349. $notification->setMessage(
  350. 'SHARE_ACCEPTED',
  351. 'file',
  352. $remoteId,
  353. [
  354. 'sharedSecret' => $token,
  355. 'message' => 'Recipient accepted the re-share'
  356. ]
  357. );
  358. $this->cloudFederationProviderManager->sendNotification($remote, $notification);
  359. }
  360. return [];
  361. }
  362. /**
  363. * @param IShare $share
  364. * @throws ShareNotFound
  365. */
  366. protected function executeAcceptShare(IShare $share) {
  367. try {
  368. $fileId = (int)$share->getNode()->getId();
  369. [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
  370. } catch (\Exception $e) {
  371. throw new ShareNotFound();
  372. }
  373. $event = $this->activityManager->generateEvent();
  374. $event->setApp('files_sharing')
  375. ->setType('remote_share')
  376. ->setAffectedUser($this->getCorrectUid($share))
  377. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
  378. ->setObject('files', $fileId, $file)
  379. ->setLink($link);
  380. $this->activityManager->publish($event);
  381. }
  382. /**
  383. * process notification that the recipient declined a share
  384. *
  385. * @param string $id
  386. * @param array $notification
  387. * @return array
  388. * @throws ActionNotSupportedException
  389. * @throws AuthenticationFailedException
  390. * @throws BadRequestException
  391. * @throws ShareNotFound
  392. * @throws HintException
  393. *
  394. */
  395. protected function shareDeclined($id, array $notification) {
  396. if (!$this->isS2SEnabled()) {
  397. throw new ActionNotSupportedException('Server does not support federated cloud sharing');
  398. }
  399. if (!isset($notification['sharedSecret'])) {
  400. throw new BadRequestException(['sharedSecret']);
  401. }
  402. $token = $notification['sharedSecret'];
  403. $share = $this->federatedShareProvider->getShareById($id);
  404. $this->verifyShare($share, $token);
  405. if ($share->getShareOwner() !== $share->getSharedBy()) {
  406. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  407. $remoteId = $this->federatedShareProvider->getRemoteId($share);
  408. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  409. $notification->setMessage(
  410. 'SHARE_DECLINED',
  411. 'file',
  412. $remoteId,
  413. [
  414. 'sharedSecret' => $token,
  415. 'message' => 'Recipient declined the re-share'
  416. ]
  417. );
  418. $this->cloudFederationProviderManager->sendNotification($remote, $notification);
  419. }
  420. $this->executeDeclineShare($share);
  421. return [];
  422. }
  423. /**
  424. * delete declined share and create a activity
  425. *
  426. * @param IShare $share
  427. * @throws ShareNotFound
  428. */
  429. protected function executeDeclineShare(IShare $share) {
  430. $this->federatedShareProvider->removeShareFromTable($share);
  431. try {
  432. $fileId = (int)$share->getNode()->getId();
  433. [$file, $link] = $this->getFile($this->getCorrectUid($share), $fileId);
  434. } catch (\Exception $e) {
  435. throw new ShareNotFound();
  436. }
  437. $event = $this->activityManager->generateEvent();
  438. $event->setApp('files_sharing')
  439. ->setType('remote_share')
  440. ->setAffectedUser($this->getCorrectUid($share))
  441. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
  442. ->setObject('files', $fileId, $file)
  443. ->setLink($link);
  444. $this->activityManager->publish($event);
  445. }
  446. /**
  447. * received the notification that the owner unshared a file from you
  448. *
  449. * @param string $id
  450. * @param array $notification
  451. * @return array
  452. * @throws AuthenticationFailedException
  453. * @throws BadRequestException
  454. */
  455. private function undoReshare($id, array $notification) {
  456. if (!isset($notification['sharedSecret'])) {
  457. throw new BadRequestException(['sharedSecret']);
  458. }
  459. $token = $notification['sharedSecret'];
  460. $share = $this->federatedShareProvider->getShareById($id);
  461. $this->verifyShare($share, $token);
  462. $this->federatedShareProvider->removeShareFromTable($share);
  463. return [];
  464. }
  465. /**
  466. * unshare file from self
  467. *
  468. * @param string $id
  469. * @param array $notification
  470. * @return array
  471. * @throws ActionNotSupportedException
  472. * @throws BadRequestException
  473. */
  474. private function unshare($id, array $notification) {
  475. if (!$this->isS2SEnabled(true)) {
  476. throw new ActionNotSupportedException("incoming shares disabled!");
  477. }
  478. if (!isset($notification['sharedSecret'])) {
  479. throw new BadRequestException(['sharedSecret']);
  480. }
  481. $token = $notification['sharedSecret'];
  482. $qb = $this->connection->getQueryBuilder();
  483. $qb->select('*')
  484. ->from('share_external')
  485. ->where(
  486. $qb->expr()->andX(
  487. $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
  488. $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
  489. )
  490. );
  491. $result = $qb->execute();
  492. $share = $result->fetch();
  493. $result->closeCursor();
  494. if ($token && $id && !empty($share)) {
  495. $remote = $this->cleanupRemote($share['remote']);
  496. $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
  497. $mountpoint = $share['mountpoint'];
  498. $user = $share['user'];
  499. $qb = $this->connection->getQueryBuilder();
  500. $qb->delete('share_external')
  501. ->where(
  502. $qb->expr()->andX(
  503. $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
  504. $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
  505. )
  506. );
  507. $qb->execute();
  508. // delete all child in case of a group share
  509. $qb = $this->connection->getQueryBuilder();
  510. $qb->delete('share_external')
  511. ->where($qb->expr()->eq('parent', $qb->createNamedParameter((int)$share['id'])));
  512. $qb->execute();
  513. if ((int)$share['share_type'] === IShare::TYPE_USER) {
  514. if ($share['accepted']) {
  515. $path = trim($mountpoint, '/');
  516. } else {
  517. $path = trim($share['name'], '/');
  518. }
  519. $notification = $this->notificationManager->createNotification();
  520. $notification->setApp('files_sharing')
  521. ->setUser($share['user'])
  522. ->setObject('remote_share', (int)$share['id']);
  523. $this->notificationManager->markProcessed($notification);
  524. $event = $this->activityManager->generateEvent();
  525. $event->setApp('files_sharing')
  526. ->setType('remote_share')
  527. ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
  528. ->setAffectedUser($user)
  529. ->setObject('remote_share', (int)$share['id'], $path);
  530. \OC::$server->getActivityManager()->publish($event);
  531. }
  532. }
  533. return [];
  534. }
  535. private function cleanupRemote($remote) {
  536. $remote = substr($remote, strpos($remote, '://') + 3);
  537. return rtrim($remote, '/');
  538. }
  539. /**
  540. * recipient of a share request to re-share the file with another user
  541. *
  542. * @param string $id
  543. * @param array $notification
  544. * @return array
  545. * @throws AuthenticationFailedException
  546. * @throws BadRequestException
  547. * @throws ProviderCouldNotAddShareException
  548. * @throws ShareNotFound
  549. */
  550. protected function reshareRequested($id, array $notification) {
  551. if (!isset($notification['sharedSecret'])) {
  552. throw new BadRequestException(['sharedSecret']);
  553. }
  554. $token = $notification['sharedSecret'];
  555. if (!isset($notification['shareWith'])) {
  556. throw new BadRequestException(['shareWith']);
  557. }
  558. $shareWith = $notification['shareWith'];
  559. if (!isset($notification['senderId'])) {
  560. throw new BadRequestException(['senderId']);
  561. }
  562. $senderId = $notification['senderId'];
  563. $share = $this->federatedShareProvider->getShareById($id);
  564. // We have to respect the default share permissions
  565. $permissions = $share->getPermissions() & (int)$this->config->getAppValue('core', 'shareapi_default_permissions', (string)Constants::PERMISSION_ALL);
  566. $share->setPermissions($permissions);
  567. // don't allow to share a file back to the owner
  568. try {
  569. [$user, $remote] = $this->addressHandler->splitUserRemote($shareWith);
  570. $owner = $share->getShareOwner();
  571. $currentServer = $this->addressHandler->generateRemoteURL();
  572. if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
  573. throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
  574. }
  575. } catch (\Exception $e) {
  576. throw new ProviderCouldNotAddShareException($e->getMessage());
  577. }
  578. $this->verifyShare($share, $token);
  579. // check if re-sharing is allowed
  580. if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
  581. // the recipient of the initial share is now the initiator for the re-share
  582. $share->setSharedBy($share->getSharedWith());
  583. $share->setSharedWith($shareWith);
  584. $result = $this->federatedShareProvider->create($share);
  585. $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
  586. return ['token' => $result->getToken(), 'providerId' => $result->getId()];
  587. } else {
  588. throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
  589. }
  590. }
  591. /**
  592. * update permission of a re-share so that the share dialog shows the right
  593. * permission if the owner or the sender changes the permission
  594. *
  595. * @param string $id
  596. * @param array $notification
  597. * @return array
  598. * @throws AuthenticationFailedException
  599. * @throws BadRequestException
  600. */
  601. protected function updateResharePermissions($id, array $notification) {
  602. throw new HintException('Updating reshares not allowed');
  603. }
  604. /**
  605. * translate OCM Permissions to Nextcloud permissions
  606. *
  607. * @param array $ocmPermissions
  608. * @return int
  609. * @throws BadRequestException
  610. */
  611. protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
  612. $ncPermissions = 0;
  613. foreach ($ocmPermissions as $permission) {
  614. switch (strtolower($permission)) {
  615. case 'read':
  616. $ncPermissions += Constants::PERMISSION_READ;
  617. break;
  618. case 'write':
  619. $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
  620. break;
  621. case 'share':
  622. $ncPermissions += Constants::PERMISSION_SHARE;
  623. break;
  624. default:
  625. throw new BadRequestException(['permission']);
  626. }
  627. }
  628. return $ncPermissions;
  629. }
  630. /**
  631. * update permissions in database
  632. *
  633. * @param IShare $share
  634. * @param int $permissions
  635. */
  636. protected function updatePermissionsInDatabase(IShare $share, $permissions) {
  637. $query = $this->connection->getQueryBuilder();
  638. $query->update('share')
  639. ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
  640. ->set('permissions', $query->createNamedParameter($permissions))
  641. ->execute();
  642. }
  643. /**
  644. * get file
  645. *
  646. * @param string $user
  647. * @param int $fileSource
  648. * @return array with internal path of the file and a absolute link to it
  649. */
  650. private function getFile($user, $fileSource) {
  651. \OC_Util::setupFS($user);
  652. try {
  653. $file = Filesystem::getPath($fileSource);
  654. } catch (NotFoundException $e) {
  655. $file = null;
  656. }
  657. $args = Filesystem::is_dir($file) ? ['dir' => $file] : ['dir' => dirname($file), 'scrollto' => $file];
  658. $link = Util::linkToAbsolute('files', 'index.php', $args);
  659. return [$file, $link];
  660. }
  661. /**
  662. * check if we are the initiator or the owner of a re-share and return the correct UID
  663. *
  664. * @param IShare $share
  665. * @return string
  666. */
  667. protected function getCorrectUid(IShare $share) {
  668. if ($this->userManager->userExists($share->getShareOwner())) {
  669. return $share->getShareOwner();
  670. }
  671. return $share->getSharedBy();
  672. }
  673. /**
  674. * check if we got the right share
  675. *
  676. * @param IShare $share
  677. * @param string $token
  678. * @return bool
  679. * @throws AuthenticationFailedException
  680. */
  681. protected function verifyShare(IShare $share, $token) {
  682. if (
  683. $share->getShareType() === IShare::TYPE_REMOTE &&
  684. $share->getToken() === $token
  685. ) {
  686. return true;
  687. }
  688. if ($share->getShareType() === IShare::TYPE_CIRCLE) {
  689. try {
  690. $knownShare = $this->shareManager->getShareByToken($token);
  691. if ($knownShare->getId() === $share->getId()) {
  692. return true;
  693. }
  694. } catch (ShareNotFound $e) {
  695. }
  696. }
  697. throw new AuthenticationFailedException();
  698. }
  699. /**
  700. * check if server-to-server sharing is enabled
  701. *
  702. * @param bool $incoming
  703. * @return bool
  704. */
  705. private function isS2SEnabled($incoming = false) {
  706. $result = $this->appManager->isEnabledForUser('files_sharing');
  707. if ($incoming) {
  708. $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
  709. } else {
  710. $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
  711. }
  712. return $result;
  713. }
  714. /**
  715. * get the supported share types, e.g. "user", "group", etc.
  716. *
  717. * @return array
  718. *
  719. * @since 14.0.0
  720. */
  721. public function getSupportedShareTypes() {
  722. return ['user', 'group'];
  723. }
  724. }