Manager.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_Sharing\External;
  8. use Doctrine\DBAL\Driver\Exception;
  9. use OC\Files\Filesystem;
  10. use OCA\FederatedFileSharing\Events\FederatedShareAddedEvent;
  11. use OCA\Files_Sharing\Helper;
  12. use OCA\Files_Sharing\ResponseDefinitions;
  13. use OCP\DB\QueryBuilder\IQueryBuilder;
  14. use OCP\EventDispatcher\IEventDispatcher;
  15. use OCP\Federation\ICloudFederationFactory;
  16. use OCP\Federation\ICloudFederationProviderManager;
  17. use OCP\Files;
  18. use OCP\Files\Events\InvalidateMountCacheEvent;
  19. use OCP\Files\NotFoundException;
  20. use OCP\Files\Storage\IStorageFactory;
  21. use OCP\Http\Client\IClientService;
  22. use OCP\IDBConnection;
  23. use OCP\IGroupManager;
  24. use OCP\IUserManager;
  25. use OCP\IUserSession;
  26. use OCP\Notification\IManager;
  27. use OCP\OCS\IDiscoveryService;
  28. use OCP\Share;
  29. use OCP\Share\IShare;
  30. use Psr\Log\LoggerInterface;
  31. /**
  32. * @psalm-import-type Files_SharingRemoteShare from ResponseDefinitions
  33. */
  34. class Manager {
  35. public const STORAGE = '\OCA\Files_Sharing\External\Storage';
  36. /** @var string|null */
  37. private $uid;
  38. /** @var \OC\Files\Mount\Manager */
  39. private $mountManager;
  40. public function __construct(
  41. private IDBConnection $connection,
  42. \OC\Files\Mount\Manager $mountManager,
  43. private IStorageFactory $storageLoader,
  44. private IClientService $clientService,
  45. private IManager $notificationManager,
  46. private IDiscoveryService $discoveryService,
  47. private ICloudFederationProviderManager $cloudFederationProviderManager,
  48. private ICloudFederationFactory $cloudFederationFactory,
  49. private IGroupManager $groupManager,
  50. private IUserManager $userManager,
  51. IUserSession $userSession,
  52. private IEventDispatcher $eventDispatcher,
  53. private LoggerInterface $logger,
  54. ) {
  55. $user = $userSession->getUser();
  56. $this->mountManager = $mountManager;
  57. $this->uid = $user ? $user->getUID() : null;
  58. }
  59. /**
  60. * add new server-to-server share
  61. *
  62. * @param string $remote
  63. * @param string $token
  64. * @param string $password
  65. * @param string $name
  66. * @param string $owner
  67. * @param int $shareType
  68. * @param boolean $accepted
  69. * @param string $user
  70. * @param string $remoteId
  71. * @param int $parent
  72. * @return Mount|null
  73. * @throws \Doctrine\DBAL\Exception
  74. */
  75. public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
  76. $user = $user ?? $this->uid;
  77. $accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
  78. $name = Filesystem::normalizePath('/' . $name);
  79. if ($accepted !== IShare::STATUS_ACCEPTED) {
  80. // To avoid conflicts with the mount point generation later,
  81. // we only use a temporary mount point name here. The real
  82. // mount point name will be generated when accepting the share,
  83. // using the original share item name.
  84. $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
  85. $mountPoint = $tmpMountPointName;
  86. $hash = md5($tmpMountPointName);
  87. $data = [
  88. 'remote' => $remote,
  89. 'share_token' => $token,
  90. 'password' => $password,
  91. 'name' => $name,
  92. 'owner' => $owner,
  93. 'user' => $user,
  94. 'mountpoint' => $mountPoint,
  95. 'mountpoint_hash' => $hash,
  96. 'accepted' => $accepted,
  97. 'remote_id' => $remoteId,
  98. 'share_type' => $shareType,
  99. ];
  100. $i = 1;
  101. while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
  102. // The external share already exists for the user
  103. $data['mountpoint'] = $tmpMountPointName . '-' . $i;
  104. $data['mountpoint_hash'] = md5($data['mountpoint']);
  105. $i++;
  106. }
  107. return null;
  108. }
  109. $mountPoint = Files::buildNotExistingFileName('/', $name);
  110. $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
  111. $hash = md5($mountPoint);
  112. $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
  113. $options = [
  114. 'remote' => $remote,
  115. 'token' => $token,
  116. 'password' => $password,
  117. 'mountpoint' => $mountPoint,
  118. 'owner' => $owner
  119. ];
  120. return $this->mountShare($options);
  121. }
  122. /**
  123. * write remote share to the database
  124. *
  125. * @param $remote
  126. * @param $token
  127. * @param $password
  128. * @param $name
  129. * @param $owner
  130. * @param $user
  131. * @param $mountPoint
  132. * @param $hash
  133. * @param $accepted
  134. * @param $remoteId
  135. * @param $parent
  136. * @param $shareType
  137. *
  138. * @return void
  139. * @throws \Doctrine\DBAL\Driver\Exception
  140. */
  141. private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {
  142. $query = $this->connection->prepare('
  143. INSERT INTO `*PREFIX*share_external`
  144. (`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
  145. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  146. ');
  147. $query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
  148. }
  149. /**
  150. * get share
  151. *
  152. * @param int $id share id
  153. * @return mixed share of false
  154. */
  155. private function fetchShare($id) {
  156. $getShare = $this->connection->prepare('
  157. SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
  158. FROM `*PREFIX*share_external`
  159. WHERE `id` = ?');
  160. $result = $getShare->execute([$id]);
  161. $share = $result->fetch();
  162. $result->closeCursor();
  163. return $share;
  164. }
  165. private function fetchUserShare($parentId, $uid) {
  166. $getShare = $this->connection->prepare('
  167. SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
  168. FROM `*PREFIX*share_external`
  169. WHERE `parent` = ? AND `user` = ?');
  170. $result = $getShare->execute([$parentId, $uid]);
  171. $share = $result->fetch();
  172. $result->closeCursor();
  173. if ($share !== false) {
  174. return $share;
  175. }
  176. return null;
  177. }
  178. /**
  179. * get share
  180. *
  181. * @param int $id share id
  182. * @return mixed share of false
  183. */
  184. public function getShare($id) {
  185. $share = $this->fetchShare($id);
  186. $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
  187. // check if the user is allowed to access it
  188. if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
  189. return $share;
  190. } elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
  191. $parentId = (int)$share['parent'];
  192. if ($parentId !== -1) {
  193. // we just retrieved a sub-share, switch to the parent entry for verification
  194. $groupShare = $this->fetchShare($parentId);
  195. } else {
  196. $groupShare = $share;
  197. }
  198. $user = $this->userManager->get($this->uid);
  199. if ($this->groupManager->get($groupShare['user'])->inGroup($user)) {
  200. return $share;
  201. }
  202. }
  203. return false;
  204. }
  205. /**
  206. * Updates accepted flag in the database
  207. *
  208. * @param int $id
  209. */
  210. private function updateAccepted(int $shareId, bool $accepted) : void {
  211. $query = $this->connection->prepare('
  212. UPDATE `*PREFIX*share_external`
  213. SET `accepted` = ?
  214. WHERE `id` = ?');
  215. $updateResult = $query->execute([$accepted ? 1 : 0, $shareId]);
  216. $updateResult->closeCursor();
  217. }
  218. /**
  219. * accept server-to-server share
  220. *
  221. * @param int $id
  222. * @return bool True if the share could be accepted, false otherwise
  223. */
  224. public function acceptShare($id) {
  225. $share = $this->getShare($id);
  226. $result = false;
  227. if ($share) {
  228. \OC_Util::setupFS($this->uid);
  229. $shareFolder = Helper::getShareFolder(null, $this->uid);
  230. $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
  231. $mountPoint = Filesystem::normalizePath($mountPoint);
  232. $hash = md5($mountPoint);
  233. $userShareAccepted = false;
  234. if ((int)$share['share_type'] === IShare::TYPE_USER) {
  235. $acceptShare = $this->connection->prepare('
  236. UPDATE `*PREFIX*share_external`
  237. SET `accepted` = ?,
  238. `mountpoint` = ?,
  239. `mountpoint_hash` = ?
  240. WHERE `id` = ? AND `user` = ?');
  241. $userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
  242. } else {
  243. $parentId = (int)$share['parent'];
  244. if ($parentId !== -1) {
  245. // this is the sub-share
  246. $subshare = $share;
  247. } else {
  248. $subshare = $this->fetchUserShare($id, $this->uid);
  249. }
  250. if ($subshare !== null) {
  251. try {
  252. $acceptShare = $this->connection->prepare('
  253. UPDATE `*PREFIX*share_external`
  254. SET `accepted` = ?,
  255. `mountpoint` = ?,
  256. `mountpoint_hash` = ?
  257. WHERE `id` = ? AND `user` = ?');
  258. $acceptShare->execute([1, $mountPoint, $hash, $subshare['id'], $this->uid]);
  259. $result = true;
  260. } catch (Exception $e) {
  261. $this->logger->emergency('Could not update share', ['exception' => $e]);
  262. $result = false;
  263. }
  264. } else {
  265. try {
  266. $this->writeShareToDb(
  267. $share['remote'],
  268. $share['share_token'],
  269. $share['password'],
  270. $share['name'],
  271. $share['owner'],
  272. $this->uid,
  273. $mountPoint, $hash, 1,
  274. $share['remote_id'],
  275. $id,
  276. $share['share_type']);
  277. $result = true;
  278. } catch (Exception $e) {
  279. $this->logger->emergency('Could not create share', ['exception' => $e]);
  280. $result = false;
  281. }
  282. }
  283. }
  284. if ($userShareAccepted !== false) {
  285. $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
  286. $event = new FederatedShareAddedEvent($share['remote']);
  287. $this->eventDispatcher->dispatchTyped($event);
  288. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent($this->userManager->get($this->uid)));
  289. $result = true;
  290. }
  291. }
  292. // Make sure the user has no notification for something that does not exist anymore.
  293. $this->processNotification($id);
  294. return $result;
  295. }
  296. /**
  297. * decline server-to-server share
  298. *
  299. * @param int $id
  300. * @return bool True if the share could be declined, false otherwise
  301. */
  302. public function declineShare($id) {
  303. $share = $this->getShare($id);
  304. $result = false;
  305. if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
  306. $removeShare = $this->connection->prepare('
  307. DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
  308. $removeShare->execute([$id, $this->uid]);
  309. $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
  310. $this->processNotification($id);
  311. $result = true;
  312. } elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
  313. $parentId = (int)$share['parent'];
  314. if ($parentId !== -1) {
  315. // this is the sub-share
  316. $subshare = $share;
  317. } else {
  318. $subshare = $this->fetchUserShare($id, $this->uid);
  319. }
  320. if ($subshare !== null) {
  321. try {
  322. $this->updateAccepted((int)$subshare['id'], false);
  323. $result = true;
  324. } catch (Exception $e) {
  325. $this->logger->emergency('Could not update share', ['exception' => $e]);
  326. $result = false;
  327. }
  328. } else {
  329. try {
  330. $this->writeShareToDb(
  331. $share['remote'],
  332. $share['share_token'],
  333. $share['password'],
  334. $share['name'],
  335. $share['owner'],
  336. $this->uid,
  337. $share['mountpoint'],
  338. $share['mountpoint_hash'],
  339. 0,
  340. $share['remote_id'],
  341. $id,
  342. $share['share_type']);
  343. $result = true;
  344. } catch (Exception $e) {
  345. $this->logger->emergency('Could not create share', ['exception' => $e]);
  346. $result = false;
  347. }
  348. }
  349. $this->processNotification($id);
  350. }
  351. return $result;
  352. }
  353. public function processNotification(int $remoteShare): void {
  354. $filter = $this->notificationManager->createNotification();
  355. $filter->setApp('files_sharing')
  356. ->setUser($this->uid)
  357. ->setObject('remote_share', (string)$remoteShare);
  358. $this->notificationManager->markProcessed($filter);
  359. }
  360. /**
  361. * inform remote server whether server-to-server share was accepted/declined
  362. *
  363. * @param string $remote
  364. * @param string $token
  365. * @param string $remoteId Share id on the remote host
  366. * @param string $feedback
  367. * @return boolean
  368. */
  369. private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
  370. $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
  371. if (is_array($result)) {
  372. return true;
  373. }
  374. $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
  375. $endpoint = $federationEndpoints['share'] ?? '/ocs/v2.php/cloud/shares';
  376. $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
  377. $fields = ['token' => $token];
  378. $client = $this->clientService->newClient();
  379. try {
  380. $response = $client->post(
  381. $url,
  382. [
  383. 'body' => $fields,
  384. 'connect_timeout' => 10,
  385. ]
  386. );
  387. } catch (\Exception $e) {
  388. return false;
  389. }
  390. $status = json_decode($response->getBody(), true);
  391. return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
  392. }
  393. /**
  394. * try send accept message to ocm end-point
  395. *
  396. * @param string $remoteDomain
  397. * @param string $token
  398. * @param string $remoteId id of the share
  399. * @param string $feedback
  400. * @return array|false
  401. */
  402. protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
  403. switch ($feedback) {
  404. case 'accept':
  405. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  406. $notification->setMessage(
  407. 'SHARE_ACCEPTED',
  408. 'file',
  409. $remoteId,
  410. [
  411. 'sharedSecret' => $token,
  412. 'message' => 'Recipient accept the share'
  413. ]
  414. );
  415. return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
  416. case 'decline':
  417. $notification = $this->cloudFederationFactory->getCloudFederationNotification();
  418. $notification->setMessage(
  419. 'SHARE_DECLINED',
  420. 'file',
  421. $remoteId,
  422. [
  423. 'sharedSecret' => $token,
  424. 'message' => 'Recipient declined the share'
  425. ]
  426. );
  427. return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
  428. }
  429. return false;
  430. }
  431. /**
  432. * remove '/user/files' from the path and trailing slashes
  433. *
  434. * @param string $path
  435. * @return string
  436. */
  437. protected function stripPath($path) {
  438. $prefix = '/' . $this->uid . '/files';
  439. return rtrim(substr($path, strlen($prefix)), '/');
  440. }
  441. public function getMount($data) {
  442. $data['manager'] = $this;
  443. $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
  444. $data['mountpoint'] = $mountPoint;
  445. $data['certificateManager'] = \OC::$server->getCertificateManager();
  446. return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
  447. }
  448. /**
  449. * @param array $data
  450. * @return Mount
  451. */
  452. protected function mountShare($data) {
  453. $mount = $this->getMount($data);
  454. $this->mountManager->addMount($mount);
  455. return $mount;
  456. }
  457. /**
  458. * @return \OC\Files\Mount\Manager
  459. */
  460. public function getMountManager() {
  461. return $this->mountManager;
  462. }
  463. /**
  464. * @param string $source
  465. * @param string $target
  466. * @return bool
  467. */
  468. public function setMountPoint($source, $target) {
  469. $source = $this->stripPath($source);
  470. $target = $this->stripPath($target);
  471. $sourceHash = md5($source);
  472. $targetHash = md5($target);
  473. $query = $this->connection->prepare('
  474. UPDATE `*PREFIX*share_external`
  475. SET `mountpoint` = ?, `mountpoint_hash` = ?
  476. WHERE `mountpoint_hash` = ?
  477. AND `user` = ?
  478. ');
  479. $result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
  480. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent($this->userManager->get($this->uid)));
  481. return $result;
  482. }
  483. public function removeShare($mountPoint): bool {
  484. try {
  485. $mountPointObj = $this->mountManager->find($mountPoint);
  486. } catch (NotFoundException $e) {
  487. $this->logger->error('Mount point to remove share not found', ['mountPoint' => $mountPoint]);
  488. return false;
  489. }
  490. if (!$mountPointObj instanceof Mount) {
  491. $this->logger->error('Mount point to remove share is not an external share, share probably doesn\'t exist', ['mountPoint' => $mountPoint]);
  492. return false;
  493. }
  494. $id = $mountPointObj->getStorage()->getCache()->getId('');
  495. $mountPoint = $this->stripPath($mountPoint);
  496. $hash = md5($mountPoint);
  497. try {
  498. $getShare = $this->connection->prepare('
  499. SELECT `remote`, `share_token`, `remote_id`, `share_type`, `id`
  500. FROM `*PREFIX*share_external`
  501. WHERE `mountpoint_hash` = ? AND `user` = ?');
  502. $result = $getShare->execute([$hash, $this->uid]);
  503. $share = $result->fetch();
  504. $result->closeCursor();
  505. if ($share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
  506. try {
  507. $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
  508. } catch (\Throwable $e) {
  509. // if we fail to notify the remote (probably cause the remote is down)
  510. // we still want the share to be gone to prevent undeletable remotes
  511. }
  512. $query = $this->connection->prepare('
  513. DELETE FROM `*PREFIX*share_external`
  514. WHERE `id` = ?
  515. ');
  516. $deleteResult = $query->execute([(int)$share['id']]);
  517. $deleteResult->closeCursor();
  518. } elseif ($share !== false && (int)$share['share_type'] === IShare::TYPE_GROUP) {
  519. $this->updateAccepted((int)$share['id'], false);
  520. }
  521. $this->removeReShares($id);
  522. } catch (\Doctrine\DBAL\Exception $ex) {
  523. $this->logger->emergency('Could not update share', ['exception' => $ex]);
  524. return false;
  525. }
  526. return true;
  527. }
  528. /**
  529. * remove re-shares from share table and mapping in the federated_reshares table
  530. *
  531. * @param $mountPointId
  532. */
  533. protected function removeReShares($mountPointId) {
  534. $selectQuery = $this->connection->getQueryBuilder();
  535. $query = $this->connection->getQueryBuilder();
  536. $selectQuery->select('id')->from('share')
  537. ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
  538. $select = $selectQuery->getSQL();
  539. $query->delete('federated_reshares')
  540. ->where($query->expr()->in('share_id', $query->createFunction($select)));
  541. $query->execute();
  542. $deleteReShares = $this->connection->getQueryBuilder();
  543. $deleteReShares->delete('share')
  544. ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
  545. $deleteReShares->execute();
  546. }
  547. /**
  548. * remove all shares for user $uid if the user was deleted
  549. *
  550. * @param string $uid
  551. */
  552. public function removeUserShares($uid): bool {
  553. try {
  554. // TODO: use query builder
  555. $getShare = $this->connection->prepare('
  556. SELECT `id`, `remote`, `share_type`, `share_token`, `remote_id`
  557. FROM `*PREFIX*share_external`
  558. WHERE `user` = ?
  559. AND `share_type` = ?');
  560. $result = $getShare->execute([$uid, IShare::TYPE_USER]);
  561. $shares = $result->fetchAll();
  562. $result->closeCursor();
  563. foreach ($shares as $share) {
  564. $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
  565. }
  566. $qb = $this->connection->getQueryBuilder();
  567. $qb->delete('share_external')
  568. // user field can specify a user or a group
  569. ->where($qb->expr()->eq('user', $qb->createNamedParameter($uid)))
  570. ->andWhere(
  571. $qb->expr()->orX(
  572. // delete direct shares
  573. $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_USER)),
  574. // delete sub-shares of group shares for that user
  575. $qb->expr()->andX(
  576. $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_GROUP)),
  577. $qb->expr()->neq('parent', $qb->expr()->literal(-1)),
  578. )
  579. )
  580. );
  581. $qb->execute();
  582. } catch (\Doctrine\DBAL\Exception $ex) {
  583. $this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
  584. return false;
  585. }
  586. return true;
  587. }
  588. public function removeGroupShares($gid): bool {
  589. try {
  590. $getShare = $this->connection->prepare('
  591. SELECT `id`, `remote`, `share_type`, `share_token`, `remote_id`
  592. FROM `*PREFIX*share_external`
  593. WHERE `user` = ?
  594. AND `share_type` = ?');
  595. $result = $getShare->execute([$gid, IShare::TYPE_GROUP]);
  596. $shares = $result->fetchAll();
  597. $result->closeCursor();
  598. $deletedGroupShares = [];
  599. $qb = $this->connection->getQueryBuilder();
  600. // delete group share entry and matching sub-entries
  601. $qb->delete('share_external')
  602. ->where(
  603. $qb->expr()->orX(
  604. $qb->expr()->eq('id', $qb->createParameter('share_id')),
  605. $qb->expr()->eq('parent', $qb->createParameter('share_parent_id'))
  606. )
  607. );
  608. foreach ($shares as $share) {
  609. $qb->setParameter('share_id', $share['id']);
  610. $qb->setParameter('share_parent_id', $share['id']);
  611. $qb->execute();
  612. }
  613. } catch (\Doctrine\DBAL\Exception $ex) {
  614. $this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
  615. return false;
  616. }
  617. return true;
  618. }
  619. /**
  620. * return a list of shares which are not yet accepted by the user
  621. *
  622. * @return list<Files_SharingRemoteShare> list of open server-to-server shares
  623. */
  624. public function getOpenShares() {
  625. return $this->getShares(false);
  626. }
  627. /**
  628. * return a list of shares which are accepted by the user
  629. *
  630. * @return list<Files_SharingRemoteShare> list of accepted server-to-server shares
  631. */
  632. public function getAcceptedShares() {
  633. return $this->getShares(true);
  634. }
  635. /**
  636. * return a list of shares for the user
  637. *
  638. * @param bool|null $accepted True for accepted only,
  639. * false for not accepted,
  640. * null for all shares of the user
  641. * @return list<Files_SharingRemoteShare> list of open server-to-server shares
  642. */
  643. private function getShares($accepted) {
  644. $user = $this->userManager->get($this->uid);
  645. $groups = $this->groupManager->getUserGroups($user);
  646. $userGroups = [];
  647. foreach ($groups as $group) {
  648. $userGroups[] = $group->getGID();
  649. }
  650. $qb = $this->connection->getQueryBuilder();
  651. $qb->select('id', 'share_type', 'parent', 'remote', 'remote_id', 'share_token', 'name', 'owner', 'user', 'mountpoint', 'accepted')
  652. ->from('share_external')
  653. ->where(
  654. $qb->expr()->orX(
  655. $qb->expr()->eq('user', $qb->createNamedParameter($this->uid)),
  656. $qb->expr()->in(
  657. 'user',
  658. $qb->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)
  659. )
  660. )
  661. )
  662. ->orderBy('id', 'ASC');
  663. try {
  664. $result = $qb->execute();
  665. $shares = $result->fetchAll();
  666. $result->closeCursor();
  667. // remove parent group share entry if we have a specific user share entry for the user
  668. $toRemove = [];
  669. foreach ($shares as $share) {
  670. if ((int)$share['share_type'] === IShare::TYPE_GROUP && (int)$share['parent'] > 0) {
  671. $toRemove[] = $share['parent'];
  672. }
  673. }
  674. $shares = array_filter($shares, function ($share) use ($toRemove) {
  675. return !in_array($share['id'], $toRemove, true);
  676. });
  677. if (!is_null($accepted)) {
  678. $shares = array_filter($shares, function ($share) use ($accepted) {
  679. return (bool)$share['accepted'] === $accepted;
  680. });
  681. }
  682. return array_values($shares);
  683. } catch (\Doctrine\DBAL\Exception $e) {
  684. $this->logger->emergency('Error when retrieving shares', ['exception' => $e]);
  685. return [];
  686. }
  687. }
  688. }