FederatedShareProvider.php 34 KB

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