AllConfig.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Loki3000 <github@labcms.ru>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author MichaIng <micha@dietpi.com>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Robin McCorkell <robin@mccorkell.me.uk>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OC;
  34. use OC\Cache\CappedMemoryCache;
  35. use OCP\IDBConnection;
  36. use OCP\PreConditionNotMetException;
  37. /**
  38. * Class to combine all the configuration options ownCloud offers
  39. */
  40. class AllConfig implements \OCP\IConfig {
  41. /** @var SystemConfig */
  42. private $systemConfig;
  43. /** @var IDBConnection */
  44. private $connection;
  45. /**
  46. * 3 dimensional array with the following structure:
  47. * [ $userId =>
  48. * [ $appId =>
  49. * [ $key => $value ]
  50. * ]
  51. * ]
  52. *
  53. * database table: preferences
  54. *
  55. * methods that use this:
  56. * - setUserValue
  57. * - getUserValue
  58. * - getUserKeys
  59. * - deleteUserValue
  60. * - deleteAllUserValues
  61. * - deleteAppFromAllUsers
  62. *
  63. * @var CappedMemoryCache $userCache
  64. */
  65. private $userCache;
  66. /**
  67. * @param SystemConfig $systemConfig
  68. */
  69. public function __construct(SystemConfig $systemConfig) {
  70. $this->userCache = new CappedMemoryCache();
  71. $this->systemConfig = $systemConfig;
  72. }
  73. /**
  74. * TODO - FIXME This fixes an issue with base.php that cause cyclic
  75. * dependencies, especially with autoconfig setup
  76. *
  77. * Replace this by properly injected database connection. Currently the
  78. * base.php triggers the getDatabaseConnection too early which causes in
  79. * autoconfig setup case a too early distributed database connection and
  80. * the autoconfig then needs to reinit all already initialized dependencies
  81. * that use the database connection.
  82. *
  83. * otherwise a SQLite database is created in the wrong directory
  84. * because the database connection was created with an uninitialized config
  85. */
  86. private function fixDIInit() {
  87. if ($this->connection === null) {
  88. $this->connection = \OC::$server->getDatabaseConnection();
  89. }
  90. }
  91. /**
  92. * Sets and deletes system wide values
  93. *
  94. * @param array $configs Associative array with `key => value` pairs
  95. * If value is null, the config key will be deleted
  96. */
  97. public function setSystemValues(array $configs) {
  98. $this->systemConfig->setValues($configs);
  99. }
  100. /**
  101. * Sets a new system wide value
  102. *
  103. * @param string $key the key of the value, under which will be saved
  104. * @param mixed $value the value that should be stored
  105. */
  106. public function setSystemValue($key, $value) {
  107. $this->systemConfig->setValue($key, $value);
  108. }
  109. /**
  110. * Looks up a system wide defined value
  111. *
  112. * @param string $key the key of the value, under which it was saved
  113. * @param mixed $default the default value to be returned if the value isn't set
  114. * @return mixed the value or $default
  115. */
  116. public function getSystemValue($key, $default = '') {
  117. return $this->systemConfig->getValue($key, $default);
  118. }
  119. /**
  120. * Looks up a boolean system wide defined value
  121. *
  122. * @param string $key the key of the value, under which it was saved
  123. * @param bool $default the default value to be returned if the value isn't set
  124. *
  125. * @return bool
  126. *
  127. * @since 16.0.0
  128. */
  129. public function getSystemValueBool(string $key, bool $default = false): bool {
  130. return (bool) $this->getSystemValue($key, $default);
  131. }
  132. /**
  133. * Looks up an integer system wide defined value
  134. *
  135. * @param string $key the key of the value, under which it was saved
  136. * @param int $default the default value to be returned if the value isn't set
  137. *
  138. * @return int
  139. *
  140. * @since 16.0.0
  141. */
  142. public function getSystemValueInt(string $key, int $default = 0): int {
  143. return (int) $this->getSystemValue($key, $default);
  144. }
  145. /**
  146. * Looks up a string system wide defined value
  147. *
  148. * @param string $key the key of the value, under which it was saved
  149. * @param string $default the default value to be returned if the value isn't set
  150. *
  151. * @return string
  152. *
  153. * @since 16.0.0
  154. */
  155. public function getSystemValueString(string $key, string $default = ''): string {
  156. return (string) $this->getSystemValue($key, $default);
  157. }
  158. /**
  159. * Looks up a system wide defined value and filters out sensitive data
  160. *
  161. * @param string $key the key of the value, under which it was saved
  162. * @param mixed $default the default value to be returned if the value isn't set
  163. * @return mixed the value or $default
  164. */
  165. public function getFilteredSystemValue($key, $default = '') {
  166. return $this->systemConfig->getFilteredValue($key, $default);
  167. }
  168. /**
  169. * Delete a system wide defined value
  170. *
  171. * @param string $key the key of the value, under which it was saved
  172. */
  173. public function deleteSystemValue($key) {
  174. $this->systemConfig->deleteValue($key);
  175. }
  176. /**
  177. * Get all keys stored for an app
  178. *
  179. * @param string $appName the appName that we stored the value under
  180. * @return string[] the keys stored for the app
  181. */
  182. public function getAppKeys($appName) {
  183. return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
  184. }
  185. /**
  186. * Writes a new app wide value
  187. *
  188. * @param string $appName the appName that we want to store the value under
  189. * @param string $key the key of the value, under which will be saved
  190. * @param string|float|int $value the value that should be stored
  191. */
  192. public function setAppValue($appName, $key, $value) {
  193. \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
  194. }
  195. /**
  196. * Looks up an app wide defined value
  197. *
  198. * @param string $appName the appName that we stored the value under
  199. * @param string $key the key of the value, under which it was saved
  200. * @param string $default the default value to be returned if the value isn't set
  201. * @return string the saved value
  202. */
  203. public function getAppValue($appName, $key, $default = '') {
  204. return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
  205. }
  206. /**
  207. * Delete an app wide defined value
  208. *
  209. * @param string $appName the appName that we stored the value under
  210. * @param string $key the key of the value, under which it was saved
  211. */
  212. public function deleteAppValue($appName, $key) {
  213. \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
  214. }
  215. /**
  216. * Removes all keys in appconfig belonging to the app
  217. *
  218. * @param string $appName the appName the configs are stored under
  219. */
  220. public function deleteAppValues($appName) {
  221. \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
  222. }
  223. /**
  224. * Set a user defined value
  225. *
  226. * @param string $userId the userId of the user that we want to store the value under
  227. * @param string $appName the appName that we want to store the value under
  228. * @param string $key the key under which the value is being stored
  229. * @param string|float|int $value the value that you want to store
  230. * @param string $preCondition only update if the config value was previously the value passed as $preCondition
  231. * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
  232. * @throws \UnexpectedValueException when trying to store an unexpected value
  233. */
  234. public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
  235. if (!is_int($value) && !is_float($value) && !is_string($value)) {
  236. throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
  237. }
  238. // TODO - FIXME
  239. $this->fixDIInit();
  240. if ($appName === 'settings' && $key === 'email') {
  241. $value = strtolower((string) $value);
  242. }
  243. $prevValue = $this->getUserValue($userId, $appName, $key, null);
  244. if ($prevValue !== null) {
  245. if ($prevValue === (string)$value) {
  246. return;
  247. } elseif ($preCondition !== null && $prevValue !== (string)$preCondition) {
  248. throw new PreConditionNotMetException();
  249. } else {
  250. $qb = $this->connection->getQueryBuilder();
  251. $qb->update('preferences')
  252. ->set('configvalue', $qb->createNamedParameter($value))
  253. ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
  254. ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
  255. ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
  256. $qb->execute();
  257. $this->userCache[$userId][$appName][$key] = (string)$value;
  258. return;
  259. }
  260. }
  261. $preconditionArray = [];
  262. if (isset($preCondition)) {
  263. $preconditionArray = [
  264. 'configvalue' => $preCondition,
  265. ];
  266. }
  267. $this->connection->setValues('preferences', [
  268. 'userid' => $userId,
  269. 'appid' => $appName,
  270. 'configkey' => $key,
  271. ], [
  272. 'configvalue' => $value,
  273. ], $preconditionArray);
  274. // only add to the cache if we already loaded data for the user
  275. if (isset($this->userCache[$userId])) {
  276. if (!isset($this->userCache[$userId][$appName])) {
  277. $this->userCache[$userId][$appName] = [];
  278. }
  279. $this->userCache[$userId][$appName][$key] = (string)$value;
  280. }
  281. }
  282. /**
  283. * Getting a user defined value
  284. *
  285. * @param ?string $userId the userId of the user that we want to store the value under
  286. * @param string $appName the appName that we stored the value under
  287. * @param string $key the key under which the value is being stored
  288. * @param mixed $default the default value to be returned if the value isn't set
  289. * @return string
  290. */
  291. public function getUserValue($userId, $appName, $key, $default = '') {
  292. $data = $this->getAllUserValues($userId);
  293. if (isset($data[$appName][$key])) {
  294. return $data[$appName][$key];
  295. } else {
  296. return $default;
  297. }
  298. }
  299. /**
  300. * Get the keys of all stored by an app for the user
  301. *
  302. * @param string $userId the userId of the user that we want to store the value under
  303. * @param string $appName the appName that we stored the value under
  304. * @return string[]
  305. */
  306. public function getUserKeys($userId, $appName) {
  307. $data = $this->getAllUserValues($userId);
  308. if (isset($data[$appName])) {
  309. return array_keys($data[$appName]);
  310. } else {
  311. return [];
  312. }
  313. }
  314. /**
  315. * Delete a user value
  316. *
  317. * @param string $userId the userId of the user that we want to store the value under
  318. * @param string $appName the appName that we stored the value under
  319. * @param string $key the key under which the value is being stored
  320. */
  321. public function deleteUserValue($userId, $appName, $key) {
  322. // TODO - FIXME
  323. $this->fixDIInit();
  324. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  325. 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
  326. $this->connection->executeUpdate($sql, [$userId, $appName, $key]);
  327. if (isset($this->userCache[$userId][$appName])) {
  328. unset($this->userCache[$userId][$appName][$key]);
  329. }
  330. }
  331. /**
  332. * Delete all user values
  333. *
  334. * @param string $userId the userId of the user that we want to remove all values from
  335. */
  336. public function deleteAllUserValues($userId) {
  337. // TODO - FIXME
  338. $this->fixDIInit();
  339. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  340. 'WHERE `userid` = ?';
  341. $this->connection->executeUpdate($sql, [$userId]);
  342. unset($this->userCache[$userId]);
  343. }
  344. /**
  345. * Delete all user related values of one app
  346. *
  347. * @param string $appName the appName of the app that we want to remove all values from
  348. */
  349. public function deleteAppFromAllUsers($appName) {
  350. // TODO - FIXME
  351. $this->fixDIInit();
  352. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  353. 'WHERE `appid` = ?';
  354. $this->connection->executeUpdate($sql, [$appName]);
  355. foreach ($this->userCache as &$userCache) {
  356. unset($userCache[$appName]);
  357. }
  358. }
  359. /**
  360. * Returns all user configs sorted by app of one user
  361. *
  362. * @param ?string $userId the user ID to get the app configs from
  363. * @psalm-return array<string, array<string, string>>
  364. * @return array[] - 2 dimensional array with the following structure:
  365. * [ $appId =>
  366. * [ $key => $value ]
  367. * ]
  368. */
  369. public function getAllUserValues(?string $userId): array {
  370. if (isset($this->userCache[$userId])) {
  371. return $this->userCache[$userId];
  372. }
  373. if ($userId === null || $userId === '') {
  374. $this->userCache[''] = [];
  375. return $this->userCache[''];
  376. }
  377. // TODO - FIXME
  378. $this->fixDIInit();
  379. $data = [];
  380. $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
  381. $result = $this->connection->executeQuery($query, [$userId]);
  382. while ($row = $result->fetch()) {
  383. $appId = $row['appid'];
  384. if (!isset($data[$appId])) {
  385. $data[$appId] = [];
  386. }
  387. $data[$appId][$row['configkey']] = $row['configvalue'];
  388. }
  389. $this->userCache[$userId] = $data;
  390. return $data;
  391. }
  392. /**
  393. * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
  394. *
  395. * @param string $appName app to get the value for
  396. * @param string $key the key to get the value for
  397. * @param array $userIds the user IDs to fetch the values for
  398. * @return array Mapped values: userId => value
  399. */
  400. public function getUserValueForUsers($appName, $key, $userIds) {
  401. // TODO - FIXME
  402. $this->fixDIInit();
  403. if (empty($userIds) || !is_array($userIds)) {
  404. return [];
  405. }
  406. $chunkedUsers = array_chunk($userIds, 50, true);
  407. $placeholders50 = implode(',', array_fill(0, 50, '?'));
  408. $userValues = [];
  409. foreach ($chunkedUsers as $chunk) {
  410. $queryParams = $chunk;
  411. // create [$app, $key, $chunkedUsers]
  412. array_unshift($queryParams, $key);
  413. array_unshift($queryParams, $appName);
  414. $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?'));
  415. $query = 'SELECT `userid`, `configvalue` ' .
  416. 'FROM `*PREFIX*preferences` ' .
  417. 'WHERE `appid` = ? AND `configkey` = ? ' .
  418. 'AND `userid` IN (' . $placeholders . ')';
  419. $result = $this->connection->executeQuery($query, $queryParams);
  420. while ($row = $result->fetch()) {
  421. $userValues[$row['userid']] = $row['configvalue'];
  422. }
  423. }
  424. return $userValues;
  425. }
  426. /**
  427. * Determines the users that have the given value set for a specific app-key-pair
  428. *
  429. * @param string $appName the app to get the user for
  430. * @param string $key the key to get the user for
  431. * @param string $value the value to get the user for
  432. * @return array of user IDs
  433. */
  434. public function getUsersForUserValue($appName, $key, $value) {
  435. // TODO - FIXME
  436. $this->fixDIInit();
  437. $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
  438. 'WHERE `appid` = ? AND `configkey` = ? ';
  439. if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
  440. //oracle hack: need to explicitly cast CLOB to CHAR for comparison
  441. $sql .= 'AND to_char(`configvalue`) = ?';
  442. } else {
  443. $sql .= 'AND `configvalue` = ?';
  444. }
  445. $result = $this->connection->executeQuery($sql, [$appName, $key, $value]);
  446. $userIDs = [];
  447. while ($row = $result->fetch()) {
  448. $userIDs[] = $row['userid'];
  449. }
  450. return $userIDs;
  451. }
  452. /**
  453. * Determines the users that have the given value set for a specific app-key-pair
  454. *
  455. * @param string $appName the app to get the user for
  456. * @param string $key the key to get the user for
  457. * @param string $value the value to get the user for
  458. * @return array of user IDs
  459. */
  460. public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
  461. // TODO - FIXME
  462. $this->fixDIInit();
  463. if ($appName === 'settings' && $key === 'email') {
  464. // Email address is always stored lowercase in the database
  465. return $this->getUsersForUserValue($appName, $key, strtolower($value));
  466. }
  467. $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
  468. 'WHERE `appid` = ? AND `configkey` = ? ';
  469. if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
  470. //oracle hack: need to explicitly cast CLOB to CHAR for comparison
  471. $sql .= 'AND LOWER(to_char(`configvalue`)) = ?';
  472. } else {
  473. $sql .= 'AND LOWER(`configvalue`) = ?';
  474. }
  475. $result = $this->connection->executeQuery($sql, [$appName, $key, strtolower($value)]);
  476. $userIDs = [];
  477. while ($row = $result->fetch()) {
  478. $userIDs[] = $row['userid'];
  479. }
  480. return $userIDs;
  481. }
  482. public function getSystemConfig() {
  483. return $this->systemConfig;
  484. }
  485. }