DBConfigService.php 18 KB

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