DBConfigService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018-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_External\Service;
  8. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  9. use OCP\DB\QueryBuilder\IQueryBuilder;
  10. use OCP\IDBConnection;
  11. use OCP\Security\ICrypto;
  12. /**
  13. * Stores the mount config in the database
  14. */
  15. class DBConfigService {
  16. public const MOUNT_TYPE_ADMIN = 1;
  17. public const MOUNT_TYPE_PERSONAL = 2;
  18. /** @deprecated use MOUNT_TYPE_PERSONAL (full uppercase) instead */
  19. public const MOUNT_TYPE_PERSONAl = 2;
  20. public const APPLICABLE_TYPE_GLOBAL = 1;
  21. public const APPLICABLE_TYPE_GROUP = 2;
  22. public const APPLICABLE_TYPE_USER = 3;
  23. /**
  24. * @var IDBConnection
  25. */
  26. private $connection;
  27. /**
  28. * @var ICrypto
  29. */
  30. private $crypto;
  31. /**
  32. * DBConfigService constructor.
  33. *
  34. * @param IDBConnection $connection
  35. * @param ICrypto $crypto
  36. */
  37. public function __construct(IDBConnection $connection, ICrypto $crypto) {
  38. $this->connection = $connection;
  39. $this->crypto = $crypto;
  40. }
  41. public function getMountById(int $mountId): ?array {
  42. $builder = $this->connection->getQueryBuilder();
  43. $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
  44. ->from('external_mounts', 'm')
  45. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  46. $mounts = $this->getMountsFromQuery($query);
  47. if (count($mounts) > 0) {
  48. return $mounts[0];
  49. } else {
  50. return null;
  51. }
  52. }
  53. /**
  54. * Get all configured mounts
  55. *
  56. * @return array
  57. */
  58. public function getAllMounts() {
  59. $builder = $this->connection->getQueryBuilder();
  60. $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
  61. ->from('external_mounts');
  62. return $this->getMountsFromQuery($query);
  63. }
  64. public function getMountsForUser($userId, $groupIds) {
  65. $builder = $this->connection->getQueryBuilder();
  66. $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
  67. ->from('external_mounts', 'm')
  68. ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
  69. ->where($builder->expr()->orX(
  70. $builder->expr()->andX( // global mounts
  71. $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
  72. $builder->expr()->isNull('a.value')
  73. ),
  74. $builder->expr()->andX( // mounts for user
  75. $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
  76. $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
  77. ),
  78. $builder->expr()->andX( // mounts for group
  79. $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
  80. $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
  81. )
  82. ));
  83. return $this->getMountsFromQuery($query);
  84. }
  85. public function modifyMountsOnUserDelete(string $uid): void {
  86. $this->modifyMountsOnDelete($uid, self::APPLICABLE_TYPE_USER);
  87. }
  88. public function modifyMountsOnGroupDelete(string $gid): void {
  89. $this->modifyMountsOnDelete($gid, self::APPLICABLE_TYPE_GROUP);
  90. }
  91. protected function modifyMountsOnDelete(string $applicableId, int $applicableType): void {
  92. $builder = $this->connection->getQueryBuilder();
  93. $query = $builder->select(['a.mount_id', $builder->func()->count('a.mount_id', 'count')])
  94. ->from('external_applicable', 'a')
  95. ->leftJoin('a', 'external_applicable', 'b', $builder->expr()->eq('a.mount_id', 'b.mount_id'))
  96. ->where($builder->expr()->andX(
  97. $builder->expr()->eq('b.type', $builder->createNamedParameter($applicableType, IQueryBuilder::PARAM_INT)),
  98. $builder->expr()->eq('b.value', $builder->createNamedParameter($applicableId))
  99. )
  100. )
  101. ->groupBy(['a.mount_id']);
  102. $stmt = $query->execute();
  103. $result = $stmt->fetchAll();
  104. $stmt->closeCursor();
  105. foreach ($result as $row) {
  106. if ((int)$row['count'] > 1) {
  107. $this->removeApplicable($row['mount_id'], $applicableType, $applicableId);
  108. } else {
  109. $this->removeMount($row['mount_id']);
  110. }
  111. }
  112. }
  113. /**
  114. * Get admin defined mounts
  115. *
  116. * @return array
  117. */
  118. public function getAdminMounts() {
  119. $builder = $this->connection->getQueryBuilder();
  120. $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
  121. ->from('external_mounts')
  122. ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
  123. return $this->getMountsFromQuery($query);
  124. }
  125. protected function getForQuery(IQueryBuilder $builder, $type, $value) {
  126. $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
  127. ->from('external_mounts', 'm')
  128. ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
  129. ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
  130. if (is_null($value)) {
  131. $query = $query->andWhere($builder->expr()->isNull('a.value'));
  132. } else {
  133. $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
  134. }
  135. return $query;
  136. }
  137. /**
  138. * Get mounts by applicable
  139. *
  140. * @param int $type any of the self::APPLICABLE_TYPE_ constants
  141. * @param string|null $value user_id, group_id or null for global mounts
  142. * @return array
  143. */
  144. public function getMountsFor($type, $value) {
  145. $builder = $this->connection->getQueryBuilder();
  146. $query = $this->getForQuery($builder, $type, $value);
  147. return $this->getMountsFromQuery($query);
  148. }
  149. /**
  150. * Get admin defined mounts by applicable
  151. *
  152. * @param int $type any of the self::APPLICABLE_TYPE_ constants
  153. * @param string|null $value user_id, group_id or null for global mounts
  154. * @return array
  155. */
  156. public function getAdminMountsFor($type, $value) {
  157. $builder = $this->connection->getQueryBuilder();
  158. $query = $this->getForQuery($builder, $type, $value);
  159. $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
  160. return $this->getMountsFromQuery($query);
  161. }
  162. /**
  163. * Get admin defined mounts for multiple applicable
  164. *
  165. * @param int $type any of the self::APPLICABLE_TYPE_ constants
  166. * @param string[] $values user_ids or group_ids
  167. * @return array
  168. */
  169. public function getAdminMountsForMultiple($type, array $values) {
  170. $builder = $this->connection->getQueryBuilder();
  171. $params = array_map(function ($value) use ($builder) {
  172. return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
  173. }, $values);
  174. $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
  175. ->from('external_mounts', 'm')
  176. ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
  177. ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
  178. ->andWhere($builder->expr()->in('a.value', $params));
  179. $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
  180. return $this->getMountsFromQuery($query);
  181. }
  182. /**
  183. * Get user defined mounts by applicable
  184. *
  185. * @param int $type any of the self::APPLICABLE_TYPE_ constants
  186. * @param string|null $value user_id, group_id or null for global mounts
  187. * @return array
  188. */
  189. public function getUserMountsFor($type, $value) {
  190. $builder = $this->connection->getQueryBuilder();
  191. $query = $this->getForQuery($builder, $type, $value);
  192. $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAL, IQueryBuilder::PARAM_INT)));
  193. return $this->getMountsFromQuery($query);
  194. }
  195. /**
  196. * Add a mount to the database
  197. *
  198. * @param string $mountPoint
  199. * @param string $storageBackend
  200. * @param string $authBackend
  201. * @param int $priority
  202. * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
  203. * @return int the id of the new mount
  204. */
  205. public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
  206. if (!$priority) {
  207. $priority = 100;
  208. }
  209. $builder = $this->connection->getQueryBuilder();
  210. $query = $builder->insert('external_mounts')
  211. ->values([
  212. 'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
  213. 'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
  214. 'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
  215. 'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
  216. 'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
  217. ]);
  218. $query->execute();
  219. return $query->getLastInsertId();
  220. }
  221. /**
  222. * Remove a mount from the database
  223. *
  224. * @param int $mountId
  225. */
  226. public function removeMount($mountId) {
  227. $builder = $this->connection->getQueryBuilder();
  228. $query = $builder->delete('external_mounts')
  229. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  230. $query->execute();
  231. $builder = $this->connection->getQueryBuilder();
  232. $query = $builder->delete('external_applicable')
  233. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  234. $query->execute();
  235. $builder = $this->connection->getQueryBuilder();
  236. $query = $builder->delete('external_config')
  237. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  238. $query->execute();
  239. $builder = $this->connection->getQueryBuilder();
  240. $query = $builder->delete('external_options')
  241. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  242. $query->execute();
  243. }
  244. /**
  245. * @param int $mountId
  246. * @param string $newMountPoint
  247. */
  248. public function setMountPoint($mountId, $newMountPoint) {
  249. $builder = $this->connection->getQueryBuilder();
  250. $query = $builder->update('external_mounts')
  251. ->set('mount_point', $builder->createNamedParameter($newMountPoint))
  252. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  253. $query->execute();
  254. }
  255. /**
  256. * @param int $mountId
  257. * @param string $newAuthBackend
  258. */
  259. public function setAuthBackend($mountId, $newAuthBackend) {
  260. $builder = $this->connection->getQueryBuilder();
  261. $query = $builder->update('external_mounts')
  262. ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
  263. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
  264. $query->execute();
  265. }
  266. /**
  267. * @param int $mountId
  268. * @param string $key
  269. * @param string $value
  270. */
  271. public function setConfig($mountId, $key, $value) {
  272. if ($key === 'password') {
  273. $value = $this->encryptValue($value);
  274. }
  275. try {
  276. $builder = $this->connection->getQueryBuilder();
  277. $builder->insert('external_config')
  278. ->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
  279. ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
  280. ->setValue('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
  281. ->execute();
  282. } catch (UniqueConstraintViolationException $e) {
  283. $builder = $this->connection->getQueryBuilder();
  284. $query = $builder->update('external_config')
  285. ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
  286. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
  287. ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
  288. $query->execute();
  289. }
  290. }
  291. /**
  292. * @param int $mountId
  293. * @param string $key
  294. * @param string $value
  295. */
  296. public function setOption($mountId, $key, $value) {
  297. try {
  298. $builder = $this->connection->getQueryBuilder();
  299. $builder->insert('external_options')
  300. ->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
  301. ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
  302. ->setValue('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
  303. ->execute();
  304. } catch (UniqueConstraintViolationException $e) {
  305. $builder = $this->connection->getQueryBuilder();
  306. $query = $builder->update('external_options')
  307. ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
  308. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
  309. ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
  310. $query->execute();
  311. }
  312. }
  313. public function addApplicable($mountId, $type, $value) {
  314. try {
  315. $builder = $this->connection->getQueryBuilder();
  316. $builder->insert('external_applicable')
  317. ->setValue('mount_id', $builder->createNamedParameter($mountId))
  318. ->setValue('type', $builder->createNamedParameter($type))
  319. ->setValue('value', $builder->createNamedParameter($value))
  320. ->execute();
  321. } catch (UniqueConstraintViolationException $e) {
  322. // applicable exists already
  323. }
  324. }
  325. public function removeApplicable($mountId, $type, $value) {
  326. $builder = $this->connection->getQueryBuilder();
  327. $query = $builder->delete('external_applicable')
  328. ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
  329. ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
  330. if (is_null($value)) {
  331. $query = $query->andWhere($builder->expr()->isNull('value'));
  332. } else {
  333. $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
  334. }
  335. $query->execute();
  336. }
  337. private function getMountsFromQuery(IQueryBuilder $query) {
  338. $result = $query->execute();
  339. $mounts = $result->fetchAll();
  340. $uniqueMounts = [];
  341. foreach ($mounts as $mount) {
  342. $id = $mount['mount_id'];
  343. if (!isset($uniqueMounts[$id])) {
  344. $uniqueMounts[$id] = $mount;
  345. }
  346. }
  347. $uniqueMounts = array_values($uniqueMounts);
  348. $mountIds = array_map(function ($mount) {
  349. return $mount['mount_id'];
  350. }, $uniqueMounts);
  351. $mountIds = array_values(array_unique($mountIds));
  352. $applicable = $this->getApplicableForMounts($mountIds);
  353. $config = $this->getConfigForMounts($mountIds);
  354. $options = $this->getOptionsForMounts($mountIds);
  355. return array_map(function ($mount, $applicable, $config, $options) {
  356. $mount['type'] = (int)$mount['type'];
  357. $mount['priority'] = (int)$mount['priority'];
  358. $mount['applicable'] = $applicable;
  359. $mount['config'] = $config;
  360. $mount['options'] = $options;
  361. return $mount;
  362. }, $uniqueMounts, $applicable, $config, $options);
  363. }
  364. /**
  365. * Get mount options from a table grouped by mount id
  366. *
  367. * @param string $table
  368. * @param string[] $fields
  369. * @param int[] $mountIds
  370. * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
  371. */
  372. private function selectForMounts($table, array $fields, array $mountIds) {
  373. if (count($mountIds) === 0) {
  374. return [];
  375. }
  376. $builder = $this->connection->getQueryBuilder();
  377. $fields[] = 'mount_id';
  378. $placeHolders = array_map(function ($id) use ($builder) {
  379. return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
  380. }, $mountIds);
  381. $query = $builder->select($fields)
  382. ->from($table)
  383. ->where($builder->expr()->in('mount_id', $placeHolders));
  384. $result = $query->execute();
  385. $rows = $result->fetchAll();
  386. $result->closeCursor();
  387. $result = [];
  388. foreach ($mountIds as $mountId) {
  389. $result[$mountId] = [];
  390. }
  391. foreach ($rows as $row) {
  392. if (isset($row['type'])) {
  393. $row['type'] = (int)$row['type'];
  394. }
  395. $result[$row['mount_id']][] = $row;
  396. }
  397. return $result;
  398. }
  399. /**
  400. * @param int[] $mountIds
  401. * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
  402. */
  403. public function getApplicableForMounts($mountIds) {
  404. return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
  405. }
  406. /**
  407. * @param int[] $mountIds
  408. * @return array [$id => ['key1' => $value1, ...], ...]
  409. */
  410. public function getConfigForMounts($mountIds) {
  411. $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
  412. return array_map([$this, 'createKeyValueMap'], $mountConfigs);
  413. }
  414. /**
  415. * @param int[] $mountIds
  416. * @return array [$id => ['key1' => $value1, ...], ...]
  417. */
  418. public function getOptionsForMounts($mountIds) {
  419. $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
  420. $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
  421. return array_map(function (array $options) {
  422. return array_map(function ($option) {
  423. return json_decode($option);
  424. }, $options);
  425. }, $optionsMap);
  426. }
  427. /**
  428. * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
  429. * @return array ['key1' => $value1, ...]
  430. */
  431. private function createKeyValueMap(array $keyValuePairs) {
  432. $decryptedPairts = array_map(function ($pair) {
  433. if ($pair['key'] === 'password') {
  434. $pair['value'] = $this->decryptValue($pair['value']);
  435. }
  436. return $pair;
  437. }, $keyValuePairs);
  438. $keys = array_map(function ($pair) {
  439. return $pair['key'];
  440. }, $decryptedPairts);
  441. $values = array_map(function ($pair) {
  442. return $pair['value'];
  443. }, $decryptedPairts);
  444. return array_combine($keys, $values);
  445. }
  446. private function encryptValue($value) {
  447. return $this->crypto->encrypt($value);
  448. }
  449. private function decryptValue($value) {
  450. try {
  451. return $this->crypto->decrypt($value);
  452. } catch (\Exception $e) {
  453. return $value;
  454. }
  455. }
  456. }