1
0

Manager.php 24 KB

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