1
0

DBConfigService.php 18 KB

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