AllConfig.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. $prevValue = $this->getUserValue($userId, $appName, $key, null);
  241. if ($prevValue !== null) {
  242. if ($prevValue === (string)$value) {
  243. return;
  244. } elseif ($preCondition !== null && $prevValue !== (string)$preCondition) {
  245. throw new PreConditionNotMetException();
  246. } else {
  247. $qb = $this->connection->getQueryBuilder();
  248. $qb->update('preferences')
  249. ->set('configvalue', $qb->createNamedParameter($value))
  250. ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
  251. ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
  252. ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
  253. $qb->execute();
  254. $this->userCache[$userId][$appName][$key] = (string)$value;
  255. return;
  256. }
  257. }
  258. $preconditionArray = [];
  259. if (isset($preCondition)) {
  260. $preconditionArray = [
  261. 'configvalue' => $preCondition,
  262. ];
  263. }
  264. $this->connection->setValues('preferences', [
  265. 'userid' => $userId,
  266. 'appid' => $appName,
  267. 'configkey' => $key,
  268. ], [
  269. 'configvalue' => $value,
  270. ], $preconditionArray);
  271. // only add to the cache if we already loaded data for the user
  272. if (isset($this->userCache[$userId])) {
  273. if (!isset($this->userCache[$userId][$appName])) {
  274. $this->userCache[$userId][$appName] = [];
  275. }
  276. $this->userCache[$userId][$appName][$key] = (string)$value;
  277. }
  278. }
  279. /**
  280. * Getting a user defined value
  281. *
  282. * @param string $userId the userId of the user that we want to store the value under
  283. * @param string $appName the appName that we stored the value under
  284. * @param string $key the key under which the value is being stored
  285. * @param mixed $default the default value to be returned if the value isn't set
  286. * @return string
  287. */
  288. public function getUserValue($userId, $appName, $key, $default = '') {
  289. $data = $this->getUserValues($userId);
  290. if (isset($data[$appName][$key])) {
  291. return $data[$appName][$key];
  292. } else {
  293. return $default;
  294. }
  295. }
  296. /**
  297. * Get the keys of all stored by an app for the user
  298. *
  299. * @param string $userId the userId of the user that we want to store the value under
  300. * @param string $appName the appName that we stored the value under
  301. * @return string[]
  302. */
  303. public function getUserKeys($userId, $appName) {
  304. $data = $this->getUserValues($userId);
  305. if (isset($data[$appName])) {
  306. return array_keys($data[$appName]);
  307. } else {
  308. return [];
  309. }
  310. }
  311. /**
  312. * Delete a user value
  313. *
  314. * @param string $userId the userId of the user that we want to store the value under
  315. * @param string $appName the appName that we stored the value under
  316. * @param string $key the key under which the value is being stored
  317. */
  318. public function deleteUserValue($userId, $appName, $key) {
  319. // TODO - FIXME
  320. $this->fixDIInit();
  321. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  322. 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
  323. $this->connection->executeUpdate($sql, [$userId, $appName, $key]);
  324. if (isset($this->userCache[$userId][$appName])) {
  325. unset($this->userCache[$userId][$appName][$key]);
  326. }
  327. }
  328. /**
  329. * Delete all user values
  330. *
  331. * @param string $userId the userId of the user that we want to remove all values from
  332. */
  333. public function deleteAllUserValues($userId) {
  334. // TODO - FIXME
  335. $this->fixDIInit();
  336. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  337. 'WHERE `userid` = ?';
  338. $this->connection->executeUpdate($sql, [$userId]);
  339. unset($this->userCache[$userId]);
  340. }
  341. /**
  342. * Delete all user related values of one app
  343. *
  344. * @param string $appName the appName of the app that we want to remove all values from
  345. */
  346. public function deleteAppFromAllUsers($appName) {
  347. // TODO - FIXME
  348. $this->fixDIInit();
  349. $sql = 'DELETE FROM `*PREFIX*preferences` '.
  350. 'WHERE `appid` = ?';
  351. $this->connection->executeUpdate($sql, [$appName]);
  352. foreach ($this->userCache as &$userCache) {
  353. unset($userCache[$appName]);
  354. }
  355. }
  356. /**
  357. * Returns all user configs sorted by app of one user
  358. *
  359. * @param string $userId the user ID to get the app configs from
  360. * @return array[] - 2 dimensional array with the following structure:
  361. * [ $appId =>
  362. * [ $key => $value ]
  363. * ]
  364. */
  365. private function getUserValues($userId) {
  366. if (isset($this->userCache[$userId])) {
  367. return $this->userCache[$userId];
  368. }
  369. if ($userId === null || $userId === '') {
  370. $this->userCache[$userId] = [];
  371. return $this->userCache[$userId];
  372. }
  373. // TODO - FIXME
  374. $this->fixDIInit();
  375. $data = [];
  376. $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
  377. $result = $this->connection->executeQuery($query, [$userId]);
  378. while ($row = $result->fetch()) {
  379. $appId = $row['appid'];
  380. if (!isset($data[$appId])) {
  381. $data[$appId] = [];
  382. }
  383. $data[$appId][$row['configkey']] = $row['configvalue'];
  384. }
  385. $this->userCache[$userId] = $data;
  386. return $data;
  387. }
  388. /**
  389. * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
  390. *
  391. * @param string $appName app to get the value for
  392. * @param string $key the key to get the value for
  393. * @param array $userIds the user IDs to fetch the values for
  394. * @return array Mapped values: userId => value
  395. */
  396. public function getUserValueForUsers($appName, $key, $userIds) {
  397. // TODO - FIXME
  398. $this->fixDIInit();
  399. if (empty($userIds) || !is_array($userIds)) {
  400. return [];
  401. }
  402. $chunkedUsers = array_chunk($userIds, 50, true);
  403. $placeholders50 = implode(',', array_fill(0, 50, '?'));
  404. $userValues = [];
  405. foreach ($chunkedUsers as $chunk) {
  406. $queryParams = $chunk;
  407. // create [$app, $key, $chunkedUsers]
  408. array_unshift($queryParams, $key);
  409. array_unshift($queryParams, $appName);
  410. $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?'));
  411. $query = 'SELECT `userid`, `configvalue` ' .
  412. 'FROM `*PREFIX*preferences` ' .
  413. 'WHERE `appid` = ? AND `configkey` = ? ' .
  414. 'AND `userid` IN (' . $placeholders . ')';
  415. $result = $this->connection->executeQuery($query, $queryParams);
  416. while ($row = $result->fetch()) {
  417. $userValues[$row['userid']] = $row['configvalue'];
  418. }
  419. }
  420. return $userValues;
  421. }
  422. /**
  423. * Determines the users that have the given value set for a specific app-key-pair
  424. *
  425. * @param string $appName the app to get the user for
  426. * @param string $key the key to get the user for
  427. * @param string $value the value to get the user for
  428. * @return array of user IDs
  429. */
  430. public function getUsersForUserValue($appName, $key, $value) {
  431. // TODO - FIXME
  432. $this->fixDIInit();
  433. $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
  434. 'WHERE `appid` = ? AND `configkey` = ? ';
  435. if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
  436. //oracle hack: need to explicitly cast CLOB to CHAR for comparison
  437. $sql .= 'AND to_char(`configvalue`) = ?';
  438. } else {
  439. $sql .= 'AND `configvalue` = ?';
  440. }
  441. $result = $this->connection->executeQuery($sql, [$appName, $key, $value]);
  442. $userIDs = [];
  443. while ($row = $result->fetch()) {
  444. $userIDs[] = $row['userid'];
  445. }
  446. return $userIDs;
  447. }
  448. /**
  449. * Determines the users that have the given value set for a specific app-key-pair
  450. *
  451. * @param string $appName the app to get the user for
  452. * @param string $key the key to get the user for
  453. * @param string $value the value to get the user for
  454. * @return array of user IDs
  455. */
  456. public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
  457. // TODO - FIXME
  458. $this->fixDIInit();
  459. $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
  460. 'WHERE `appid` = ? AND `configkey` = ? ';
  461. if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
  462. //oracle hack: need to explicitly cast CLOB to CHAR for comparison
  463. $sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)';
  464. } else {
  465. $sql .= 'AND LOWER(`configvalue`) = LOWER(?)';
  466. }
  467. $result = $this->connection->executeQuery($sql, [$appName, $key, $value]);
  468. $userIDs = [];
  469. while ($row = $result->fetch()) {
  470. $userIDs[] = $row['userid'];
  471. }
  472. return $userIDs;
  473. }
  474. public function getSystemConfig() {
  475. return $this->systemConfig;
  476. }
  477. }