DBConfigService.php 19 KB

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