FederatedShareProvider.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Georg Ehrke <oc.list@georgehrke.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Maxence Lange <maxence@artificial-owl.com>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Sergej Pupykin <pupykin.s@gmail.com>
  18. * @author Stefan Weil <sw@weilnetz.de>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
  21. * @author Vincent Petry <vincent@nextcloud.com>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OCA\FederatedFileSharing;
  39. use OC\Share20\Exception\InvalidShare;
  40. use OC\Share20\Share;
  41. use OCP\Constants;
  42. use OCP\DB\QueryBuilder\IQueryBuilder;
  43. use OCP\Federation\ICloudFederationProviderManager;
  44. use OCP\Federation\ICloudIdManager;
  45. use OCP\Files\Folder;
  46. use OCP\Files\IRootFolder;
  47. use OCP\Files\Node;
  48. use OCP\Files\NotFoundException;
  49. use OCP\IConfig;
  50. use OCP\IDBConnection;
  51. use OCP\IL10N;
  52. use OCP\IUserManager;
  53. use OCP\Share\Exceptions\GenericShareException;
  54. use OCP\Share\Exceptions\ShareNotFound;
  55. use OCP\Share\IShare;
  56. use OCP\Share\IShareProvider;
  57. use Psr\Log\LoggerInterface;
  58. /**
  59. * Class FederatedShareProvider
  60. *
  61. * @package OCA\FederatedFileSharing
  62. */
  63. class FederatedShareProvider implements IShareProvider {
  64. public const SHARE_TYPE_REMOTE = 6;
  65. /** @var string */
  66. private $externalShareTable = 'share_external';
  67. /** @var array list of supported share types */
  68. private $supportedShareType = [IShare::TYPE_REMOTE_GROUP, IShare::TYPE_REMOTE, IShare::TYPE_CIRCLE];
  69. /**
  70. * DefaultShareProvider constructor.
  71. */
  72. public function __construct(
  73. private IDBConnection $dbConnection,
  74. private AddressHandler $addressHandler,
  75. private Notifications $notifications,
  76. private TokenHandler $tokenHandler,
  77. private IL10N $l,
  78. private IRootFolder $rootFolder,
  79. private IConfig $config,
  80. private IUserManager $userManager,
  81. private ICloudIdManager $cloudIdManager,
  82. private \OCP\GlobalScale\IConfig $gsConfig,
  83. private ICloudFederationProviderManager $cloudFederationProviderManager,
  84. private LoggerInterface $logger,
  85. ) {
  86. }
  87. /**
  88. * Return the identifier of this provider.
  89. *
  90. * @return string Containing only [a-zA-Z0-9]
  91. */
  92. public function identifier() {
  93. return 'ocFederatedSharing';
  94. }
  95. /**
  96. * Share a path
  97. *
  98. * @param IShare $share
  99. * @return IShare The share object
  100. * @throws ShareNotFound
  101. * @throws \Exception
  102. */
  103. public function create(IShare $share) {
  104. $shareWith = $share->getSharedWith();
  105. $itemSource = $share->getNodeId();
  106. $itemType = $share->getNodeType();
  107. $permissions = $share->getPermissions();
  108. $sharedBy = $share->getSharedBy();
  109. $shareType = $share->getShareType();
  110. $expirationDate = $share->getExpirationDate();
  111. if ($shareType === IShare::TYPE_REMOTE_GROUP &&
  112. !$this->isOutgoingServer2serverGroupShareEnabled()
  113. ) {
  114. $message = 'It is not allowed to send federated group shares from this server.';
  115. $message_t = $this->l->t('It is not allowed to send federated group shares from this server.');
  116. $this->logger->debug($message, ['app' => 'Federated File Sharing']);
  117. throw new \Exception($message_t);
  118. }
  119. /*
  120. * Check if file is not already shared with the remote user
  121. */
  122. $alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE, $share->getNode(), 1, 0);
  123. $alreadySharedGroup = $this->getSharedWith($shareWith, IShare::TYPE_REMOTE_GROUP, $share->getNode(), 1, 0);
  124. if (!empty($alreadyShared) || !empty($alreadySharedGroup)) {
  125. $message = 'Sharing %1$s failed, because this item is already shared with %2$s';
  126. $message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with user %2$s', [$share->getNode()->getName(), $shareWith]);
  127. $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
  128. throw new \Exception($message_t);
  129. }
  130. // don't allow federated shares if source and target server are the same
  131. $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
  132. $currentServer = $this->addressHandler->generateRemoteURL();
  133. $currentUser = $sharedBy;
  134. if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
  135. $message = 'Not allowed to create a federated share with the same user.';
  136. $message_t = $this->l->t('Not allowed to create a federated share with the same user');
  137. $this->logger->debug($message, ['app' => 'Federated File Sharing']);
  138. throw new \Exception($message_t);
  139. }
  140. // Federated shares always have read permissions
  141. if (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {
  142. $message = 'Federated shares require read permissions';
  143. $message_t = $this->l->t('Federated shares require read permissions');
  144. $this->logger->debug($message, ['app' => 'Federated File Sharing']);
  145. throw new \Exception($message_t);
  146. }
  147. $share->setSharedWith($cloudId->getId());
  148. try {
  149. $remoteShare = $this->getShareFromExternalShareTable($share);
  150. } catch (ShareNotFound $e) {
  151. $remoteShare = null;
  152. }
  153. if ($remoteShare) {
  154. try {
  155. $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
  156. $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time(), $shareType, $expirationDate);
  157. $share->setId($shareId);
  158. [$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId);
  159. // remote share was create successfully if we get a valid token as return
  160. $send = is_string($token) && $token !== '';
  161. } catch (\Exception $e) {
  162. // fall back to old re-share behavior if the remote server
  163. // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
  164. $this->removeShareFromTable($share);
  165. $shareId = $this->createFederatedShare($share);
  166. }
  167. if ($send) {
  168. $this->updateSuccessfulReshare($shareId, $token);
  169. $this->storeRemoteId($shareId, $remoteId);
  170. } else {
  171. $this->removeShareFromTable($share);
  172. $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
  173. throw new \Exception($message_t);
  174. }
  175. } else {
  176. $shareId = $this->createFederatedShare($share);
  177. }
  178. $data = $this->getRawShare($shareId);
  179. return $this->createShareObject($data);
  180. }
  181. /**
  182. * create federated share and inform the recipient
  183. *
  184. * @param IShare $share
  185. * @return int
  186. * @throws ShareNotFound
  187. * @throws \Exception
  188. */
  189. protected function createFederatedShare(IShare $share) {
  190. $token = $this->tokenHandler->generateToken();
  191. $shareId = $this->addShareToDB(
  192. $share->getNodeId(),
  193. $share->getNodeType(),
  194. $share->getSharedWith(),
  195. $share->getSharedBy(),
  196. $share->getShareOwner(),
  197. $share->getPermissions(),
  198. $token,
  199. $share->getShareType(),
  200. $share->getExpirationDate()
  201. );
  202. $failure = false;
  203. try {
  204. $sharedByFederatedId = $share->getSharedBy();
  205. if ($this->userManager->userExists($sharedByFederatedId)) {
  206. $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
  207. $sharedByFederatedId = $cloudId->getId();
  208. }
  209. $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
  210. $send = $this->notifications->sendRemoteShare(
  211. $token,
  212. $share->getSharedWith(),
  213. $share->getNode()->getName(),
  214. $shareId,
  215. $share->getShareOwner(),
  216. $ownerCloudId->getId(),
  217. $share->getSharedBy(),
  218. $sharedByFederatedId,
  219. $share->getShareType()
  220. );
  221. if ($send === false) {
  222. $failure = true;
  223. }
  224. } catch (\Exception $e) {
  225. $this->logger->error('Failed to notify remote server of federated share, removing share.', [
  226. 'app' => 'federatedfilesharing',
  227. 'exception' => $e,
  228. ]);
  229. $failure = true;
  230. }
  231. if ($failure) {
  232. $this->removeShareFromTableById($shareId);
  233. $message_t = $this->l->t('Sharing %1$s failed, could not find %2$s, maybe the server is currently unreachable or uses a self-signed certificate.',
  234. [$share->getNode()->getName(), $share->getSharedWith()]);
  235. throw new \Exception($message_t);
  236. }
  237. return $shareId;
  238. }
  239. /**
  240. * @param string $shareWith
  241. * @param IShare $share
  242. * @param string $shareId internal share Id
  243. * @return array
  244. * @throws \Exception
  245. */
  246. protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
  247. $remoteShare = $this->getShareFromExternalShareTable($share);
  248. $token = $remoteShare['share_token'];
  249. $remoteId = $remoteShare['remote_id'];
  250. $remote = $remoteShare['remote'];
  251. [$token, $remoteId] = $this->notifications->requestReShare(
  252. $token,
  253. $remoteId,
  254. $shareId,
  255. $remote,
  256. $shareWith,
  257. $share->getPermissions(),
  258. $share->getNode()->getName()
  259. );
  260. return [$token, $remoteId];
  261. }
  262. /**
  263. * get federated share from the share_external table but exclude mounted link shares
  264. *
  265. * @param IShare $share
  266. * @return array
  267. * @throws ShareNotFound
  268. */
  269. protected function getShareFromExternalShareTable(IShare $share) {
  270. $query = $this->dbConnection->getQueryBuilder();
  271. $query->select('*')->from($this->externalShareTable)
  272. ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
  273. ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
  274. $qResult = $query->execute();
  275. $result = $qResult->fetchAll();
  276. $qResult->closeCursor();
  277. if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
  278. return $result[0];
  279. }
  280. throw new ShareNotFound('share not found in share_external table');
  281. }
  282. /**
  283. * add share to the database and return the ID
  284. *
  285. * @param int $itemSource
  286. * @param string $itemType
  287. * @param string $shareWith
  288. * @param string $sharedBy
  289. * @param string $uidOwner
  290. * @param int $permissions
  291. * @param string $token
  292. * @param int $shareType
  293. * @param \DateTime $expirationDate
  294. * @return int
  295. */
  296. private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $shareType, $expirationDate) {
  297. $qb = $this->dbConnection->getQueryBuilder();
  298. $qb->insert('share')
  299. ->setValue('share_type', $qb->createNamedParameter($shareType))
  300. ->setValue('item_type', $qb->createNamedParameter($itemType))
  301. ->setValue('item_source', $qb->createNamedParameter($itemSource))
  302. ->setValue('file_source', $qb->createNamedParameter($itemSource))
  303. ->setValue('share_with', $qb->createNamedParameter($shareWith))
  304. ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
  305. ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
  306. ->setValue('permissions', $qb->createNamedParameter($permissions))
  307. ->setValue('expiration', $qb->createNamedParameter($expirationDate, IQueryBuilder::PARAM_DATE))
  308. ->setValue('token', $qb->createNamedParameter($token))
  309. ->setValue('stime', $qb->createNamedParameter(time()));
  310. /*
  311. * Added to fix https://github.com/owncloud/core/issues/22215
  312. * Can be removed once we get rid of ajax/share.php
  313. */
  314. $qb->setValue('file_target', $qb->createNamedParameter(''));
  315. $qb->execute();
  316. return $qb->getLastInsertId();
  317. }
  318. /**
  319. * Update a share
  320. *
  321. * @param IShare $share
  322. * @return IShare The share object
  323. */
  324. public function update(IShare $share) {
  325. /*
  326. * We allow updating the permissions of federated shares
  327. */
  328. $qb = $this->dbConnection->getQueryBuilder();
  329. $qb->update('share')
  330. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  331. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  332. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  333. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  334. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  335. ->execute();
  336. // send the updated permission to the owner/initiator, if they are not the same
  337. if ($share->getShareOwner() !== $share->getSharedBy()) {
  338. $this->sendPermissionUpdate($share);
  339. }
  340. return $share;
  341. }
  342. /**
  343. * send the updated permission to the owner/initiator, if they are not the same
  344. *
  345. * @param IShare $share
  346. * @throws ShareNotFound
  347. * @throws \OCP\HintException
  348. */
  349. protected function sendPermissionUpdate(IShare $share) {
  350. $remoteId = $this->getRemoteId($share);
  351. // if the local user is the owner we send the permission change to the initiator
  352. if ($this->userManager->userExists($share->getShareOwner())) {
  353. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  354. } else { // ... if not we send the permission change to the owner
  355. [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
  356. }
  357. $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
  358. }
  359. /**
  360. * update successful reShare with the correct token
  361. *
  362. * @param int $shareId
  363. * @param string $token
  364. */
  365. protected function updateSuccessfulReShare($shareId, $token) {
  366. $query = $this->dbConnection->getQueryBuilder();
  367. $query->update('share')
  368. ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
  369. ->set('token', $query->createNamedParameter($token))
  370. ->execute();
  371. }
  372. /**
  373. * store remote ID in federated reShare table
  374. *
  375. * @param $shareId
  376. * @param $remoteId
  377. */
  378. public function storeRemoteId(int $shareId, string $remoteId): void {
  379. $query = $this->dbConnection->getQueryBuilder();
  380. $query->insert('federated_reshares')
  381. ->values(
  382. [
  383. 'share_id' => $query->createNamedParameter($shareId),
  384. 'remote_id' => $query->createNamedParameter($remoteId),
  385. ]
  386. );
  387. $query->execute();
  388. }
  389. /**
  390. * get share ID on remote server for federated re-shares
  391. *
  392. * @param IShare $share
  393. * @return string
  394. * @throws ShareNotFound
  395. */
  396. public function getRemoteId(IShare $share): string {
  397. $query = $this->dbConnection->getQueryBuilder();
  398. $query->select('remote_id')->from('federated_reshares')
  399. ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
  400. $result = $query->execute();
  401. $data = $result->fetch();
  402. $result->closeCursor();
  403. if (!is_array($data) || !isset($data['remote_id'])) {
  404. throw new ShareNotFound();
  405. }
  406. return (string)$data['remote_id'];
  407. }
  408. /**
  409. * @inheritdoc
  410. */
  411. public function move(IShare $share, $recipient) {
  412. /*
  413. * This function does nothing yet as it is just for outgoing
  414. * federated shares.
  415. */
  416. return $share;
  417. }
  418. /**
  419. * Get all children of this share
  420. *
  421. * @param IShare $parent
  422. * @return IShare[]
  423. */
  424. public function getChildren(IShare $parent) {
  425. $children = [];
  426. $qb = $this->dbConnection->getQueryBuilder();
  427. $qb->select('*')
  428. ->from('share')
  429. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
  430. ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
  431. ->orderBy('id');
  432. $cursor = $qb->execute();
  433. while ($data = $cursor->fetch()) {
  434. $children[] = $this->createShareObject($data);
  435. }
  436. $cursor->closeCursor();
  437. return $children;
  438. }
  439. /**
  440. * Delete a share (owner unShares the file)
  441. *
  442. * @param IShare $share
  443. * @throws ShareNotFound
  444. * @throws \OCP\HintException
  445. */
  446. public function delete(IShare $share) {
  447. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedWith());
  448. // if the local user is the owner we can send the unShare request directly...
  449. if ($this->userManager->userExists($share->getShareOwner())) {
  450. $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
  451. $this->revokeShare($share, true);
  452. } else { // ... if not we need to correct ID for the unShare request
  453. $remoteId = $this->getRemoteId($share);
  454. $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
  455. $this->revokeShare($share, false);
  456. }
  457. // only remove the share when all messages are send to not lose information
  458. // about the share to early
  459. $this->removeShareFromTable($share);
  460. }
  461. /**
  462. * in case of a re-share we need to send the other use (initiator or owner)
  463. * a message that the file was unshared
  464. *
  465. * @param IShare $share
  466. * @param bool $isOwner the user can either be the owner or the user who re-sahred it
  467. * @throws ShareNotFound
  468. * @throws \OCP\HintException
  469. */
  470. protected function revokeShare($share, $isOwner) {
  471. if ($this->userManager->userExists($share->getShareOwner()) && $this->userManager->userExists($share->getSharedBy())) {
  472. // If both the owner and the initiator of the share are local users we don't have to notify anybody else
  473. return;
  474. }
  475. // also send a unShare request to the initiator, if this is a different user than the owner
  476. if ($share->getShareOwner() !== $share->getSharedBy()) {
  477. if ($isOwner) {
  478. [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy());
  479. } else {
  480. [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner());
  481. }
  482. $remoteId = $this->getRemoteId($share);
  483. $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
  484. }
  485. }
  486. /**
  487. * remove share from table
  488. *
  489. * @param IShare $share
  490. */
  491. public function removeShareFromTable(IShare $share) {
  492. $this->removeShareFromTableById($share->getId());
  493. }
  494. /**
  495. * remove share from table
  496. *
  497. * @param string $shareId
  498. */
  499. private function removeShareFromTableById($shareId) {
  500. $qb = $this->dbConnection->getQueryBuilder();
  501. $qb->delete('share')
  502. ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)))
  503. ->andWhere($qb->expr()->neq('share_type', $qb->createNamedParameter(IShare::TYPE_CIRCLE)));
  504. $qb->execute();
  505. $qb = $this->dbConnection->getQueryBuilder();
  506. $qb->delete('federated_reshares')
  507. ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
  508. $qb->execute();
  509. }
  510. /**
  511. * @inheritdoc
  512. */
  513. public function deleteFromSelf(IShare $share, $recipient) {
  514. // nothing to do here. Technically deleteFromSelf in the context of federated
  515. // shares is a umount of an external storage. This is handled here
  516. // apps/files_sharing/lib/external/manager.php
  517. // TODO move this code over to this app
  518. }
  519. public function restore(IShare $share, string $recipient): IShare {
  520. throw new GenericShareException('not implemented');
  521. }
  522. public function getSharesInFolder($userId, Folder $node, $reshares, $shallow = true) {
  523. $qb = $this->dbConnection->getQueryBuilder();
  524. $qb->select('*')
  525. ->from('share', 's')
  526. ->andWhere($qb->expr()->orX(
  527. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  528. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  529. ))
  530. ->andWhere(
  531. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE))
  532. );
  533. /**
  534. * Reshares for this user are shares where they are the owner.
  535. */
  536. if ($reshares === false) {
  537. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  538. } else {
  539. $qb->andWhere(
  540. $qb->expr()->orX(
  541. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  542. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  543. )
  544. );
  545. }
  546. $qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
  547. if ($shallow) {
  548. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  549. } else {
  550. $qb->andWhere($qb->expr()->like('f.path', $qb->createNamedParameter($this->dbConnection->escapeLikeParameter($node->getInternalPath()) . '/%')));
  551. }
  552. $qb->orderBy('id');
  553. $cursor = $qb->execute();
  554. $shares = [];
  555. while ($data = $cursor->fetch()) {
  556. $shares[$data['fileid']][] = $this->createShareObject($data);
  557. }
  558. $cursor->closeCursor();
  559. return $shares;
  560. }
  561. /**
  562. * @inheritdoc
  563. */
  564. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
  565. $qb = $this->dbConnection->getQueryBuilder();
  566. $qb->select('*')
  567. ->from('share');
  568. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
  569. /**
  570. * Reshares for this user are shares where they are the owner.
  571. */
  572. if ($reshares === false) {
  573. //Special case for old shares created via the web UI
  574. $or1 = $qb->expr()->andX(
  575. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  576. $qb->expr()->isNull('uid_initiator')
  577. );
  578. $qb->andWhere(
  579. $qb->expr()->orX(
  580. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
  581. $or1
  582. )
  583. );
  584. } else {
  585. $qb->andWhere(
  586. $qb->expr()->orX(
  587. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  588. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  589. )
  590. );
  591. }
  592. if ($node !== null) {
  593. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  594. }
  595. if ($limit !== -1) {
  596. $qb->setMaxResults($limit);
  597. }
  598. $qb->setFirstResult($offset);
  599. $qb->orderBy('id');
  600. $cursor = $qb->execute();
  601. $shares = [];
  602. while ($data = $cursor->fetch()) {
  603. $shares[] = $this->createShareObject($data);
  604. }
  605. $cursor->closeCursor();
  606. return $shares;
  607. }
  608. /**
  609. * @inheritdoc
  610. */
  611. public function getShareById($id, $recipientId = null) {
  612. $qb = $this->dbConnection->getQueryBuilder();
  613. $qb->select('*')
  614. ->from('share')
  615. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  616. ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
  617. $cursor = $qb->execute();
  618. $data = $cursor->fetch();
  619. $cursor->closeCursor();
  620. if ($data === false) {
  621. throw new ShareNotFound('Can not find share with ID: ' . $id);
  622. }
  623. try {
  624. $share = $this->createShareObject($data);
  625. } catch (InvalidShare $e) {
  626. throw new ShareNotFound();
  627. }
  628. return $share;
  629. }
  630. /**
  631. * Get shares for a given path
  632. *
  633. * @param \OCP\Files\Node $path
  634. * @return IShare[]
  635. */
  636. public function getSharesByPath(Node $path) {
  637. $qb = $this->dbConnection->getQueryBuilder();
  638. // get federated user shares
  639. $cursor = $qb->select('*')
  640. ->from('share')
  641. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  642. ->andWhere($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
  643. ->execute();
  644. $shares = [];
  645. while ($data = $cursor->fetch()) {
  646. $shares[] = $this->createShareObject($data);
  647. }
  648. $cursor->closeCursor();
  649. return $shares;
  650. }
  651. /**
  652. * @inheritdoc
  653. */
  654. public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
  655. /** @var IShare[] $shares */
  656. $shares = [];
  657. //Get shares directly with this user
  658. $qb = $this->dbConnection->getQueryBuilder();
  659. $qb->select('*')
  660. ->from('share');
  661. // Order by id
  662. $qb->orderBy('id');
  663. // Set limit and offset
  664. if ($limit !== -1) {
  665. $qb->setMaxResults($limit);
  666. }
  667. $qb->setFirstResult($offset);
  668. $qb->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)));
  669. $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
  670. // Filter by node if provided
  671. if ($node !== null) {
  672. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  673. }
  674. $cursor = $qb->execute();
  675. while ($data = $cursor->fetch()) {
  676. $shares[] = $this->createShareObject($data);
  677. }
  678. $cursor->closeCursor();
  679. return $shares;
  680. }
  681. /**
  682. * Get a share by token
  683. *
  684. * @param string $token
  685. * @return IShare
  686. * @throws ShareNotFound
  687. */
  688. public function getShareByToken($token) {
  689. $qb = $this->dbConnection->getQueryBuilder();
  690. $cursor = $qb->select('*')
  691. ->from('share')
  692. ->where($qb->expr()->in('share_type', $qb->createNamedParameter($this->supportedShareType, IQueryBuilder::PARAM_INT_ARRAY)))
  693. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  694. ->execute();
  695. $data = $cursor->fetch();
  696. if ($data === false) {
  697. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  698. }
  699. try {
  700. $share = $this->createShareObject($data);
  701. } catch (InvalidShare $e) {
  702. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  703. }
  704. return $share;
  705. }
  706. /**
  707. * get database row of a give share
  708. *
  709. * @param $id
  710. * @return array
  711. * @throws ShareNotFound
  712. */
  713. private function getRawShare($id) {
  714. // Now fetch the inserted share and create a complete share object
  715. $qb = $this->dbConnection->getQueryBuilder();
  716. $qb->select('*')
  717. ->from('share')
  718. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
  719. $cursor = $qb->execute();
  720. $data = $cursor->fetch();
  721. $cursor->closeCursor();
  722. if ($data === false) {
  723. throw new ShareNotFound;
  724. }
  725. return $data;
  726. }
  727. /**
  728. * Create a share object from an database row
  729. *
  730. * @param array $data
  731. * @return IShare
  732. * @throws InvalidShare
  733. * @throws ShareNotFound
  734. */
  735. private function createShareObject($data) {
  736. $share = new Share($this->rootFolder, $this->userManager);
  737. $share->setId((int)$data['id'])
  738. ->setShareType((int)$data['share_type'])
  739. ->setPermissions((int)$data['permissions'])
  740. ->setTarget($data['file_target'])
  741. ->setMailSend((bool)$data['mail_send'])
  742. ->setToken($data['token']);
  743. $shareTime = new \DateTime();
  744. $shareTime->setTimestamp((int)$data['stime']);
  745. $share->setShareTime($shareTime);
  746. $share->setSharedWith($data['share_with']);
  747. if ($data['uid_initiator'] !== null) {
  748. $share->setShareOwner($data['uid_owner']);
  749. $share->setSharedBy($data['uid_initiator']);
  750. } else {
  751. //OLD SHARE
  752. $share->setSharedBy($data['uid_owner']);
  753. $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
  754. $owner = $path->getOwner();
  755. $share->setShareOwner($owner->getUID());
  756. }
  757. $share->setNodeId((int)$data['file_source']);
  758. $share->setNodeType($data['item_type']);
  759. $share->setProviderId($this->identifier());
  760. if ($data['expiration'] !== null) {
  761. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  762. $share->setExpirationDate($expiration);
  763. }
  764. return $share;
  765. }
  766. /**
  767. * Get the node with file $id for $user
  768. *
  769. * @param string $userId
  770. * @param int $id
  771. * @return \OCP\Files\File|\OCP\Files\Folder
  772. * @throws InvalidShare
  773. */
  774. private function getNode($userId, $id) {
  775. try {
  776. $userFolder = $this->rootFolder->getUserFolder($userId);
  777. } catch (NotFoundException $e) {
  778. throw new InvalidShare();
  779. }
  780. $nodes = $userFolder->getById($id);
  781. if (empty($nodes)) {
  782. throw new InvalidShare();
  783. }
  784. return $nodes[0];
  785. }
  786. /**
  787. * A user is deleted from the system
  788. * So clean up the relevant shares.
  789. *
  790. * @param string $uid
  791. * @param int $shareType
  792. */
  793. public function userDeleted($uid, $shareType) {
  794. //TODO: probably a good idea to send unshare info to remote servers
  795. $qb = $this->dbConnection->getQueryBuilder();
  796. $qb->delete('share')
  797. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
  798. ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
  799. ->execute();
  800. }
  801. /**
  802. * This provider does not handle groups
  803. *
  804. * @param string $gid
  805. */
  806. public function groupDeleted($gid) {
  807. // We don't handle groups here
  808. }
  809. /**
  810. * This provider does not handle groups
  811. *
  812. * @param string $uid
  813. * @param string $gid
  814. */
  815. public function userDeletedFromGroup($uid, $gid) {
  816. // We don't handle groups here
  817. }
  818. /**
  819. * check if users from other Nextcloud instances are allowed to mount public links share by this instance
  820. *
  821. * @return bool
  822. */
  823. public function isOutgoingServer2serverShareEnabled() {
  824. if ($this->gsConfig->onlyInternalFederation()) {
  825. return false;
  826. }
  827. $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
  828. return ($result === 'yes');
  829. }
  830. /**
  831. * check if users are allowed to mount public links from other Nextclouds
  832. *
  833. * @return bool
  834. */
  835. public function isIncomingServer2serverShareEnabled() {
  836. if ($this->gsConfig->onlyInternalFederation()) {
  837. return false;
  838. }
  839. $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
  840. return ($result === 'yes');
  841. }
  842. /**
  843. * check if users from other Nextcloud instances are allowed to send federated group shares
  844. *
  845. * @return bool
  846. */
  847. public function isOutgoingServer2serverGroupShareEnabled() {
  848. if ($this->gsConfig->onlyInternalFederation()) {
  849. return false;
  850. }
  851. $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no');
  852. return ($result === 'yes');
  853. }
  854. /**
  855. * check if users are allowed to receive federated group shares
  856. *
  857. * @return bool
  858. */
  859. public function isIncomingServer2serverGroupShareEnabled() {
  860. if ($this->gsConfig->onlyInternalFederation()) {
  861. return false;
  862. }
  863. $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_group_share_enabled', 'no');
  864. return ($result === 'yes');
  865. }
  866. /**
  867. * check if federated group sharing is supported, therefore the OCM API need to be enabled
  868. *
  869. * @return bool
  870. */
  871. public function isFederatedGroupSharingSupported() {
  872. return $this->cloudFederationProviderManager->isReady();
  873. }
  874. /**
  875. * Check if querying sharees on the lookup server is enabled
  876. *
  877. * @return bool
  878. */
  879. public function isLookupServerQueriesEnabled() {
  880. // in a global scale setup we should always query the lookup server
  881. if ($this->gsConfig->isGlobalScaleEnabled()) {
  882. return true;
  883. }
  884. $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes');
  885. return ($result === 'yes');
  886. }
  887. /**
  888. * Check if it is allowed to publish user specific data to the lookup server
  889. *
  890. * @return bool
  891. */
  892. public function isLookupServerUploadEnabled() {
  893. // in a global scale setup the admin is responsible to keep the lookup server up-to-date
  894. if ($this->gsConfig->isGlobalScaleEnabled()) {
  895. return false;
  896. }
  897. $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
  898. return ($result === 'yes');
  899. }
  900. /**
  901. * @inheritdoc
  902. */
  903. public function getAccessList($nodes, $currentAccess) {
  904. $ids = [];
  905. foreach ($nodes as $node) {
  906. $ids[] = $node->getId();
  907. }
  908. $qb = $this->dbConnection->getQueryBuilder();
  909. $qb->select('share_with', 'token', 'file_source')
  910. ->from('share')
  911. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)))
  912. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  913. ->andWhere($qb->expr()->orX(
  914. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  915. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  916. ));
  917. $cursor = $qb->execute();
  918. if ($currentAccess === false) {
  919. $remote = $cursor->fetch() !== false;
  920. $cursor->closeCursor();
  921. return ['remote' => $remote];
  922. }
  923. $remote = [];
  924. while ($row = $cursor->fetch()) {
  925. $remote[$row['share_with']] = [
  926. 'node_id' => $row['file_source'],
  927. 'token' => $row['token'],
  928. ];
  929. }
  930. $cursor->closeCursor();
  931. return ['remote' => $remote];
  932. }
  933. public function getAllShares(): iterable {
  934. $qb = $this->dbConnection->getQueryBuilder();
  935. $qb->select('*')
  936. ->from('share')
  937. ->where(
  938. $qb->expr()->orX(
  939. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE)),
  940. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_REMOTE_GROUP))
  941. )
  942. );
  943. $cursor = $qb->execute();
  944. while ($data = $cursor->fetch()) {
  945. try {
  946. $share = $this->createShareObject($data);
  947. } catch (InvalidShare $e) {
  948. continue;
  949. } catch (ShareNotFound $e) {
  950. continue;
  951. }
  952. yield $share;
  953. }
  954. $cursor->closeCursor();
  955. }
  956. }