Manager.php 25 KB

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