CloudFederationProviderFiles.php 26 KB

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