AppConfig.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2017, Joas Schilling <coding@schilljs.com>
  5. * @copyright Copyright (c) 2016, ownCloud, Inc.
  6. *
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Jakob Sack <mail@jakobsack.de>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Maxence Lange <maxence@artificial-owl.com>
  14. * @author michaelletzgus <michaelletzgus@users.noreply.github.com>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC;
  36. use InvalidArgumentException;
  37. use JsonException;
  38. use OCP\DB\Exception as DBException;
  39. use OCP\DB\QueryBuilder\IQueryBuilder;
  40. use OCP\Exceptions\AppConfigIncorrectTypeException;
  41. use OCP\Exceptions\AppConfigTypeConflictException;
  42. use OCP\Exceptions\AppConfigUnknownKeyException;
  43. use OCP\IAppConfig;
  44. use OCP\IConfig;
  45. use OCP\IDBConnection;
  46. use OCP\Security\ICrypto;
  47. use Psr\Log\LoggerInterface;
  48. /**
  49. * This class provides an easy way for apps to store config values in the
  50. * database.
  51. *
  52. * **Note:** since 29.0.0, it supports **lazy loading**
  53. *
  54. * ### What is lazy loading ?
  55. * In order to avoid loading useless config values into memory for each request,
  56. * only non-lazy values are now loaded.
  57. *
  58. * Once a value that is lazy is requested, all lazy values will be loaded.
  59. *
  60. * Similarly, some methods from this class are marked with a warning about ignoring
  61. * lazy loading. Use them wisely and only on parts of the code that are called
  62. * during specific requests or actions to avoid loading the lazy values all the time.
  63. *
  64. * @since 7.0.0
  65. * @since 29.0.0 - Supporting types and lazy loading
  66. */
  67. class AppConfig implements IAppConfig {
  68. private const APP_MAX_LENGTH = 32;
  69. private const KEY_MAX_LENGTH = 64;
  70. private const ENCRYPTION_PREFIX = '$AppConfigEncryption$';
  71. private const ENCRYPTION_PREFIX_LENGTH = 21; // strlen(self::ENCRYPTION_PREFIX)
  72. /** @var array<string, array<string, mixed>> ['app_id' => ['config_key' => 'config_value']] */
  73. private array $fastCache = []; // cache for normal config keys
  74. /** @var array<string, array<string, mixed>> ['app_id' => ['config_key' => 'config_value']] */
  75. private array $lazyCache = []; // cache for lazy config keys
  76. /** @var array<string, array<string, int>> ['app_id' => ['config_key' => bitflag]] */
  77. private array $valueTypes = []; // type for all config values
  78. private bool $fastLoaded = false;
  79. private bool $lazyLoaded = false;
  80. /**
  81. * $migrationCompleted is only needed to manage the previous structure
  82. * of the database during the upgrading process to nc29.
  83. *
  84. * only when upgrading from a version prior 28.0.2
  85. *
  86. * @TODO: remove this value in Nextcloud 30+
  87. */
  88. private bool $migrationCompleted = true;
  89. public function __construct(
  90. protected IDBConnection $connection,
  91. protected LoggerInterface $logger,
  92. protected ICrypto $crypto,
  93. ) {
  94. }
  95. /**
  96. * @inheritDoc
  97. *
  98. * @return string[] list of app ids
  99. * @since 7.0.0
  100. */
  101. public function getApps(): array {
  102. $this->loadConfigAll();
  103. $apps = array_merge(array_keys($this->fastCache), array_keys($this->lazyCache));
  104. sort($apps);
  105. return array_values(array_unique($apps));
  106. }
  107. /**
  108. * @inheritDoc
  109. *
  110. * @param string $app id of the app
  111. *
  112. * @return string[] list of stored config keys
  113. * @since 29.0.0
  114. */
  115. public function getKeys(string $app): array {
  116. $this->assertParams($app);
  117. $this->loadConfigAll();
  118. $keys = array_merge(array_keys($this->fastCache[$app] ?? []), array_keys($this->lazyCache[$app] ?? []));
  119. sort($keys);
  120. return array_values(array_unique($keys));
  121. }
  122. /**
  123. * @inheritDoc
  124. *
  125. * @param string $app id of the app
  126. * @param string $key config key
  127. * @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
  128. *
  129. * @return bool TRUE if key exists
  130. * @since 7.0.0
  131. * @since 29.0.0 Added the $lazy argument
  132. */
  133. public function hasKey(string $app, string $key, ?bool $lazy = false): bool {
  134. $this->assertParams($app, $key);
  135. $this->loadConfig($lazy);
  136. if ($lazy === null) {
  137. $appCache = $this->getAllValues($app);
  138. return isset($appCache[$key]);
  139. }
  140. if ($lazy) {
  141. return isset($this->lazyCache[$app][$key]);
  142. }
  143. return isset($this->fastCache[$app][$key]);
  144. }
  145. /**
  146. * @param string $app id of the app
  147. * @param string $key config key
  148. * @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
  149. *
  150. * @return bool
  151. * @throws AppConfigUnknownKeyException if config key is not known
  152. * @since 29.0.0
  153. */
  154. public function isSensitive(string $app, string $key, ?bool $lazy = false): bool {
  155. $this->assertParams($app, $key);
  156. $this->loadConfig($lazy);
  157. if (!isset($this->valueTypes[$app][$key])) {
  158. throw new AppConfigUnknownKeyException('unknown config key');
  159. }
  160. return $this->isTyped(self::VALUE_SENSITIVE, $this->valueTypes[$app][$key]);
  161. }
  162. /**
  163. * @inheritDoc
  164. *
  165. * @param string $app if of the app
  166. * @param string $key config key
  167. *
  168. * @return bool TRUE if config is lazy loaded
  169. * @throws AppConfigUnknownKeyException if config key is not known
  170. * @see IAppConfig for details about lazy loading
  171. * @since 29.0.0
  172. */
  173. public function isLazy(string $app, string $key): bool {
  174. // there is a huge probability the non-lazy config are already loaded
  175. if ($this->hasKey($app, $key, false)) {
  176. return false;
  177. }
  178. // key not found, we search in the lazy config
  179. if ($this->hasKey($app, $key, true)) {
  180. return true;
  181. }
  182. throw new AppConfigUnknownKeyException('unknown config key');
  183. }
  184. /**
  185. * @inheritDoc
  186. *
  187. * @param string $app id of the app
  188. * @param string $prefix config keys prefix to search
  189. * @param bool $filtered TRUE to hide sensitive config values. Value are replaced by {@see IConfig::SENSITIVE_VALUE}
  190. *
  191. * @return array<string, string|int|float|bool|array> [configKey => configValue]
  192. * @since 29.0.0
  193. */
  194. public function getAllValues(string $app, string $prefix = '', bool $filtered = false): array {
  195. $this->assertParams($app, $prefix);
  196. // if we want to filter values, we need to get sensitivity
  197. $this->loadConfigAll();
  198. // array_merge() will remove numeric keys (here config keys), so addition arrays instead
  199. $values = $this->formatAppValues($app, ($this->fastCache[$app] ?? []) + ($this->lazyCache[$app] ?? []));
  200. $values = array_filter(
  201. $values,
  202. function (string $key) use ($prefix): bool {
  203. return str_starts_with($key, $prefix); // filter values based on $prefix
  204. }, ARRAY_FILTER_USE_KEY
  205. );
  206. if (!$filtered) {
  207. return $values;
  208. }
  209. /**
  210. * Using the old (deprecated) list of sensitive values.
  211. */
  212. foreach ($this->getSensitiveKeys($app) as $sensitiveKeyExp) {
  213. $sensitiveKeys = preg_grep($sensitiveKeyExp, array_keys($values));
  214. foreach ($sensitiveKeys as $sensitiveKey) {
  215. $this->valueTypes[$app][$sensitiveKey] = ($this->valueTypes[$app][$sensitiveKey] ?? 0) | self::VALUE_SENSITIVE;
  216. }
  217. }
  218. $result = [];
  219. foreach ($values as $key => $value) {
  220. $result[$key] = $this->isTyped(self::VALUE_SENSITIVE, $this->valueTypes[$app][$key] ?? 0) ? IConfig::SENSITIVE_VALUE : $value;
  221. }
  222. return $result;
  223. }
  224. /**
  225. * @inheritDoc
  226. *
  227. * @param string $key config key
  228. * @param bool $lazy search within lazy loaded config
  229. * @param int|null $typedAs enforce type for the returned values ({@see self::VALUE_STRING} and others)
  230. *
  231. * @return array<string, string|int|float|bool|array> [appId => configValue]
  232. * @since 29.0.0
  233. */
  234. public function searchValues(string $key, bool $lazy = false, ?int $typedAs = null): array {
  235. $this->assertParams('', $key, true);
  236. $this->loadConfig($lazy);
  237. /** @var array<array-key, array<array-key, mixed>> $cache */
  238. if ($lazy) {
  239. $cache = $this->lazyCache;
  240. } else {
  241. $cache = $this->fastCache;
  242. }
  243. $values = [];
  244. foreach (array_keys($cache) as $app) {
  245. if (isset($cache[$app][$key])) {
  246. $values[$app] = $this->convertTypedValue($cache[$app][$key], $typedAs ?? $this->getValueType((string)$app, $key, $lazy));
  247. }
  248. }
  249. return $values;
  250. }
  251. /**
  252. * Get the config value as string.
  253. * If the value does not exist the given default will be returned.
  254. *
  255. * Set lazy to `null` to ignore it and get the value from either source.
  256. *
  257. * **WARNING:** Method is internal and **SHOULD** not be used, as it is better to get the value with a type.
  258. *
  259. * @param string $app id of the app
  260. * @param string $key config key
  261. * @param string $default config value
  262. * @param null|bool $lazy get config as lazy loaded or not. can be NULL
  263. *
  264. * @return string the value or $default
  265. * @internal
  266. * @since 29.0.0
  267. * @see IAppConfig for explanation about lazy loading
  268. * @see getValueString()
  269. * @see getValueInt()
  270. * @see getValueFloat()
  271. * @see getValueBool()
  272. * @see getValueArray()
  273. */
  274. public function getValueMixed(
  275. string $app,
  276. string $key,
  277. string $default = '',
  278. ?bool $lazy = false
  279. ): string {
  280. try {
  281. $lazy = ($lazy === null) ? $this->isLazy($app, $key) : $lazy;
  282. } catch (AppConfigUnknownKeyException $e) {
  283. return $default;
  284. }
  285. return $this->getTypedValue(
  286. $app,
  287. $key,
  288. $default,
  289. $lazy,
  290. self::VALUE_MIXED
  291. );
  292. }
  293. /**
  294. * @inheritDoc
  295. *
  296. * @param string $app id of the app
  297. * @param string $key config key
  298. * @param string $default default value
  299. * @param bool $lazy search within lazy loaded config
  300. *
  301. * @return string stored config value or $default if not set in database
  302. * @throws InvalidArgumentException if one of the argument format is invalid
  303. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  304. * @since 29.0.0
  305. * @see IAppConfig for explanation about lazy loading
  306. */
  307. public function getValueString(
  308. string $app,
  309. string $key,
  310. string $default = '',
  311. bool $lazy = false
  312. ): string {
  313. return $this->getTypedValue($app, $key, $default, $lazy, self::VALUE_STRING);
  314. }
  315. /**
  316. * @inheritDoc
  317. *
  318. * @param string $app id of the app
  319. * @param string $key config key
  320. * @param int $default default value
  321. * @param bool $lazy search within lazy loaded config
  322. *
  323. * @return int stored config value or $default if not set in database
  324. * @throws InvalidArgumentException if one of the argument format is invalid
  325. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  326. * @since 29.0.0
  327. * @see IAppConfig for explanation about lazy loading
  328. */
  329. public function getValueInt(
  330. string $app,
  331. string $key,
  332. int $default = 0,
  333. bool $lazy = false
  334. ): int {
  335. return (int)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_INT);
  336. }
  337. /**
  338. * @inheritDoc
  339. *
  340. * @param string $app id of the app
  341. * @param string $key config key
  342. * @param float $default default value
  343. * @param bool $lazy search within lazy loaded config
  344. *
  345. * @return float stored config value or $default if not set in database
  346. * @throws InvalidArgumentException if one of the argument format is invalid
  347. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  348. * @since 29.0.0
  349. * @see IAppConfig for explanation about lazy loading
  350. */
  351. public function getValueFloat(string $app, string $key, float $default = 0, bool $lazy = false): float {
  352. return (float)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_FLOAT);
  353. }
  354. /**
  355. * @inheritDoc
  356. *
  357. * @param string $app id of the app
  358. * @param string $key config key
  359. * @param bool $default default value
  360. * @param bool $lazy search within lazy loaded config
  361. *
  362. * @return bool stored config value or $default if not set in database
  363. * @throws InvalidArgumentException if one of the argument format is invalid
  364. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  365. * @since 29.0.0
  366. * @see IAppConfig for explanation about lazy loading
  367. */
  368. public function getValueBool(string $app, string $key, bool $default = false, bool $lazy = false): bool {
  369. $b = strtolower($this->getTypedValue($app, $key, $default ? 'true' : 'false', $lazy, self::VALUE_BOOL));
  370. return in_array($b, ['1', 'true', 'yes', 'on']);
  371. }
  372. /**
  373. * @inheritDoc
  374. *
  375. * @param string $app id of the app
  376. * @param string $key config key
  377. * @param array $default default value
  378. * @param bool $lazy search within lazy loaded config
  379. *
  380. * @return array stored config value or $default if not set in database
  381. * @throws InvalidArgumentException if one of the argument format is invalid
  382. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  383. * @since 29.0.0
  384. * @see IAppConfig for explanation about lazy loading
  385. */
  386. public function getValueArray(
  387. string $app,
  388. string $key,
  389. array $default = [],
  390. bool $lazy = false
  391. ): array {
  392. try {
  393. $defaultJson = json_encode($default, JSON_THROW_ON_ERROR);
  394. $value = json_decode($this->getTypedValue($app, $key, $defaultJson, $lazy, self::VALUE_ARRAY), true, flags: JSON_THROW_ON_ERROR);
  395. return is_array($value) ? $value : [];
  396. } catch (JsonException) {
  397. return [];
  398. }
  399. }
  400. /**
  401. * @param string $app id of the app
  402. * @param string $key config key
  403. * @param string $default default value
  404. * @param bool $lazy search within lazy loaded config
  405. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT}{@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  406. *
  407. * @return string
  408. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  409. * @throws InvalidArgumentException
  410. */
  411. private function getTypedValue(
  412. string $app,
  413. string $key,
  414. string $default,
  415. bool $lazy,
  416. int $type
  417. ): string {
  418. $this->assertParams($app, $key, valueType: $type);
  419. $this->loadConfig($lazy);
  420. /**
  421. * We ignore check if mixed type is requested.
  422. * If type of stored value is set as mixed, we don't filter.
  423. * If type of stored value is defined, we compare with the one requested.
  424. */
  425. $knownType = $this->valueTypes[$app][$key] ?? 0;
  426. if (!$this->isTyped(self::VALUE_MIXED, $type)
  427. && $knownType > 0
  428. && !$this->isTyped(self::VALUE_MIXED, $knownType)
  429. && !$this->isTyped($type, $knownType)) {
  430. $this->logger->warning('conflict with value type from database', ['app' => $app, 'key' => $key, 'type' => $type, 'knownType' => $knownType]);
  431. throw new AppConfigTypeConflictException('conflict with value type from database');
  432. }
  433. /**
  434. * - the pair $app/$key cannot exist in both array,
  435. * - we should still return an existing non-lazy value even if current method
  436. * is called with $lazy is true
  437. *
  438. * This way, lazyCache will be empty until the load for lazy config value is requested.
  439. */
  440. if (isset($this->lazyCache[$app][$key])) {
  441. $value = $this->lazyCache[$app][$key];
  442. } elseif (isset($this->fastCache[$app][$key])) {
  443. $value = $this->fastCache[$app][$key];
  444. } else {
  445. return $default;
  446. }
  447. $sensitive = $this->isTyped(self::VALUE_SENSITIVE, $knownType);
  448. if ($sensitive && str_starts_with($value, self::ENCRYPTION_PREFIX)) {
  449. // Only decrypt values that are stored encrypted
  450. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  451. }
  452. return $value;
  453. }
  454. /**
  455. * @inheritDoc
  456. *
  457. * @param string $app id of the app
  458. * @param string $key config key
  459. *
  460. * @return int type of the value
  461. * @throws AppConfigUnknownKeyException if config key is not known
  462. * @since 29.0.0
  463. * @see VALUE_STRING
  464. * @see VALUE_INT
  465. * @see VALUE_FLOAT
  466. * @see VALUE_BOOL
  467. * @see VALUE_ARRAY
  468. */
  469. public function getValueType(string $app, string $key, ?bool $lazy = null): int {
  470. $this->assertParams($app, $key);
  471. $this->loadConfig($lazy);
  472. if (!isset($this->valueTypes[$app][$key])) {
  473. throw new AppConfigUnknownKeyException('unknown config key');
  474. }
  475. $type = $this->valueTypes[$app][$key];
  476. $type &= ~self::VALUE_SENSITIVE;
  477. return $type;
  478. }
  479. /**
  480. * Store a config key and its value in database as VALUE_MIXED
  481. *
  482. * **WARNING:** Method is internal and **MUST** not be used as it is best to set a real value type
  483. *
  484. * @param string $app id of the app
  485. * @param string $key config key
  486. * @param string $value config value
  487. * @param bool $lazy set config as lazy loaded
  488. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  489. *
  490. * @return bool TRUE if value was different, therefor updated in database
  491. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED
  492. * @internal
  493. * @since 29.0.0
  494. * @see IAppConfig for explanation about lazy loading
  495. * @see setValueString()
  496. * @see setValueInt()
  497. * @see setValueFloat()
  498. * @see setValueBool()
  499. * @see setValueArray()
  500. */
  501. public function setValueMixed(
  502. string $app,
  503. string $key,
  504. string $value,
  505. bool $lazy = false,
  506. bool $sensitive = false
  507. ): bool {
  508. return $this->setTypedValue(
  509. $app,
  510. $key,
  511. $value,
  512. $lazy,
  513. self::VALUE_MIXED | ($sensitive ? self::VALUE_SENSITIVE : 0)
  514. );
  515. }
  516. /**
  517. * @inheritDoc
  518. *
  519. * @param string $app id of the app
  520. * @param string $key config key
  521. * @param string $value config value
  522. * @param bool $lazy set config as lazy loaded
  523. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  524. *
  525. * @return bool TRUE if value was different, therefor updated in database
  526. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  527. * @since 29.0.0
  528. * @see IAppConfig for explanation about lazy loading
  529. */
  530. public function setValueString(
  531. string $app,
  532. string $key,
  533. string $value,
  534. bool $lazy = false,
  535. bool $sensitive = false
  536. ): bool {
  537. return $this->setTypedValue(
  538. $app,
  539. $key,
  540. $value,
  541. $lazy,
  542. self::VALUE_STRING | ($sensitive ? self::VALUE_SENSITIVE : 0)
  543. );
  544. }
  545. /**
  546. * @inheritDoc
  547. *
  548. * @param string $app id of the app
  549. * @param string $key config key
  550. * @param int $value config value
  551. * @param bool $lazy set config as lazy loaded
  552. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  553. *
  554. * @return bool TRUE if value was different, therefor updated in database
  555. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  556. * @since 29.0.0
  557. * @see IAppConfig for explanation about lazy loading
  558. */
  559. public function setValueInt(
  560. string $app,
  561. string $key,
  562. int $value,
  563. bool $lazy = false,
  564. bool $sensitive = false
  565. ): bool {
  566. if ($value > 2000000000) {
  567. $this->logger->debug('You are trying to store an integer value around/above 2,147,483,647. This is a reminder that reaching this theoretical limit on 32 bits system will throw an exception.');
  568. }
  569. return $this->setTypedValue(
  570. $app,
  571. $key,
  572. (string)$value,
  573. $lazy,
  574. self::VALUE_INT | ($sensitive ? self::VALUE_SENSITIVE : 0)
  575. );
  576. }
  577. /**
  578. * @inheritDoc
  579. *
  580. * @param string $app id of the app
  581. * @param string $key config key
  582. * @param float $value config value
  583. * @param bool $lazy set config as lazy loaded
  584. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  585. *
  586. * @return bool TRUE if value was different, therefor updated in database
  587. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  588. * @since 29.0.0
  589. * @see IAppConfig for explanation about lazy loading
  590. */
  591. public function setValueFloat(
  592. string $app,
  593. string $key,
  594. float $value,
  595. bool $lazy = false,
  596. bool $sensitive = false
  597. ): bool {
  598. return $this->setTypedValue(
  599. $app,
  600. $key,
  601. (string)$value,
  602. $lazy,
  603. self::VALUE_FLOAT | ($sensitive ? self::VALUE_SENSITIVE : 0)
  604. );
  605. }
  606. /**
  607. * @inheritDoc
  608. *
  609. * @param string $app id of the app
  610. * @param string $key config key
  611. * @param bool $value config value
  612. * @param bool $lazy set config as lazy loaded
  613. *
  614. * @return bool TRUE if value was different, therefor updated in database
  615. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  616. * @since 29.0.0
  617. * @see IAppConfig for explanation about lazy loading
  618. */
  619. public function setValueBool(
  620. string $app,
  621. string $key,
  622. bool $value,
  623. bool $lazy = false
  624. ): bool {
  625. return $this->setTypedValue(
  626. $app,
  627. $key,
  628. ($value) ? '1' : '0',
  629. $lazy,
  630. self::VALUE_BOOL
  631. );
  632. }
  633. /**
  634. * @inheritDoc
  635. *
  636. * @param string $app id of the app
  637. * @param string $key config key
  638. * @param array $value config value
  639. * @param bool $lazy set config as lazy loaded
  640. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  641. *
  642. * @return bool TRUE if value was different, therefor updated in database
  643. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  644. * @throws JsonException
  645. * @since 29.0.0
  646. * @see IAppConfig for explanation about lazy loading
  647. */
  648. public function setValueArray(
  649. string $app,
  650. string $key,
  651. array $value,
  652. bool $lazy = false,
  653. bool $sensitive = false
  654. ): bool {
  655. try {
  656. return $this->setTypedValue(
  657. $app,
  658. $key,
  659. json_encode($value, JSON_THROW_ON_ERROR),
  660. $lazy,
  661. self::VALUE_ARRAY | ($sensitive ? self::VALUE_SENSITIVE : 0)
  662. );
  663. } catch (JsonException $e) {
  664. $this->logger->warning('could not setValueArray', ['app' => $app, 'key' => $key, 'exception' => $e]);
  665. throw $e;
  666. }
  667. }
  668. /**
  669. * Store a config key and its value in database
  670. *
  671. * If config key is already known with the exact same config value and same sensitive/lazy status, the
  672. * database is not updated. If config value was previously stored as sensitive, status will not be
  673. * altered.
  674. *
  675. * @param string $app id of the app
  676. * @param string $key config key
  677. * @param string $value config value
  678. * @param bool $lazy config set as lazy loaded
  679. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  680. *
  681. * @return bool TRUE if value was updated in database
  682. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  683. * @see IAppConfig for explanation about lazy loading
  684. */
  685. private function setTypedValue(
  686. string $app,
  687. string $key,
  688. string $value,
  689. bool $lazy,
  690. int $type
  691. ): bool {
  692. $this->assertParams($app, $key);
  693. $this->loadConfig($lazy);
  694. $sensitive = $this->isTyped(self::VALUE_SENSITIVE, $type);
  695. $inserted = $refreshCache = false;
  696. $origValue = $value;
  697. if ($sensitive || ($this->hasKey($app, $key, $lazy) && $this->isSensitive($app, $key, $lazy))) {
  698. $value = self::ENCRYPTION_PREFIX . $this->crypto->encrypt($value);
  699. }
  700. if ($this->hasKey($app, $key, $lazy)) {
  701. /**
  702. * no update if key is already known with set lazy status and value is
  703. * not different, unless sensitivity is switched from false to true.
  704. */
  705. if ($origValue === $this->getTypedValue($app, $key, $value, $lazy, $type)
  706. && (!$sensitive || $this->isSensitive($app, $key, $lazy))) {
  707. return false;
  708. }
  709. } else {
  710. /**
  711. * if key is not known yet, we try to insert.
  712. * It might fail if the key exists with a different lazy flag.
  713. */
  714. try {
  715. $insert = $this->connection->getQueryBuilder();
  716. $insert->insert('appconfig')
  717. ->setValue('appid', $insert->createNamedParameter($app))
  718. ->setValue('lazy', $insert->createNamedParameter(($lazy) ? 1 : 0, IQueryBuilder::PARAM_INT))
  719. ->setValue('type', $insert->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  720. ->setValue('configkey', $insert->createNamedParameter($key))
  721. ->setValue('configvalue', $insert->createNamedParameter($value));
  722. $insert->executeStatement();
  723. $inserted = true;
  724. } catch (DBException $e) {
  725. if ($e->getReason() !== DBException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  726. throw $e; // TODO: throw exception or just log and returns false !?
  727. }
  728. }
  729. }
  730. /**
  731. * We cannot insert a new row, meaning we need to update an already existing one
  732. */
  733. if (!$inserted) {
  734. $currType = $this->valueTypes[$app][$key] ?? 0;
  735. if ($currType === 0) { // this might happen when switching lazy loading status
  736. $this->loadConfigAll();
  737. $currType = $this->valueTypes[$app][$key] ?? 0;
  738. }
  739. /**
  740. * This should only happen during the upgrade process from 28 to 29.
  741. * We only log a warning and set it to VALUE_MIXED.
  742. */
  743. if ($currType === 0) {
  744. $this->logger->warning('Value type is set to zero (0) in database. This is fine only during the upgrade process from 28 to 29.', ['app' => $app, 'key' => $key]);
  745. $currType = self::VALUE_MIXED;
  746. }
  747. /**
  748. * we only accept a different type from the one stored in database
  749. * if the one stored in database is not-defined (VALUE_MIXED)
  750. */
  751. if (!$this->isTyped(self::VALUE_MIXED, $currType) &&
  752. ($type | self::VALUE_SENSITIVE) !== ($currType | self::VALUE_SENSITIVE)) {
  753. try {
  754. $currType = $this->convertTypeToString($currType);
  755. $type = $this->convertTypeToString($type);
  756. } catch (AppConfigIncorrectTypeException) {
  757. // can be ignored, this was just needed for a better exception message.
  758. }
  759. throw new AppConfigTypeConflictException('conflict between new type (' . $type . ') and old type (' . $currType . ')');
  760. }
  761. // we fix $type if the stored value, or the new value as it might be changed, is set as sensitive
  762. if ($sensitive || $this->isTyped(self::VALUE_SENSITIVE, $currType)) {
  763. $type |= self::VALUE_SENSITIVE;
  764. }
  765. if ($lazy !== $this->isLazy($app, $key)) {
  766. $refreshCache = true;
  767. }
  768. $update = $this->connection->getQueryBuilder();
  769. $update->update('appconfig')
  770. ->set('configvalue', $update->createNamedParameter($value))
  771. ->set('lazy', $update->createNamedParameter(($lazy) ? 1 : 0, IQueryBuilder::PARAM_INT))
  772. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  773. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  774. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  775. $update->executeStatement();
  776. }
  777. if ($refreshCache) {
  778. $this->clearCache();
  779. return true;
  780. }
  781. // update local cache
  782. if ($lazy) {
  783. $cache = &$this->lazyCache;
  784. } else {
  785. $cache = &$this->fastCache;
  786. }
  787. $cache[$app][$key] = $value;
  788. $this->valueTypes[$app][$key] = $type;
  789. return true;
  790. }
  791. /**
  792. * Change the type of config value.
  793. *
  794. * **WARNING:** Method is internal and **MUST** not be used as it may break things.
  795. *
  796. * @param string $app id of the app
  797. * @param string $key config key
  798. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  799. *
  800. * @return bool TRUE if database update were necessary
  801. * @throws AppConfigUnknownKeyException if $key is now known in database
  802. * @throws AppConfigIncorrectTypeException if $type is not valid
  803. * @internal
  804. * @since 29.0.0
  805. */
  806. public function updateType(string $app, string $key, int $type = self::VALUE_MIXED): bool {
  807. $this->assertParams($app, $key);
  808. $this->loadConfigAll();
  809. $lazy = $this->isLazy($app, $key);
  810. // type can only be one type
  811. if (!in_array($type, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
  812. throw new AppConfigIncorrectTypeException('Unknown value type');
  813. }
  814. $currType = $this->valueTypes[$app][$key];
  815. if (($type | self::VALUE_SENSITIVE) === ($currType | self::VALUE_SENSITIVE)) {
  816. return false;
  817. }
  818. // we complete with sensitive flag if the stored value is set as sensitive
  819. if ($this->isTyped(self::VALUE_SENSITIVE, $currType)) {
  820. $type = $type | self::VALUE_SENSITIVE;
  821. }
  822. $update = $this->connection->getQueryBuilder();
  823. $update->update('appconfig')
  824. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  825. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  826. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  827. $update->executeStatement();
  828. $this->valueTypes[$app][$key] = $type;
  829. return true;
  830. }
  831. /**
  832. * @inheritDoc
  833. *
  834. * @param string $app id of the app
  835. * @param string $key config key
  836. * @param bool $sensitive TRUE to set as sensitive, FALSE to unset
  837. *
  838. * @return bool TRUE if entry was found in database and an update was necessary
  839. * @since 29.0.0
  840. */
  841. public function updateSensitive(string $app, string $key, bool $sensitive): bool {
  842. $this->assertParams($app, $key);
  843. $this->loadConfigAll();
  844. try {
  845. if ($sensitive === $this->isSensitive($app, $key, null)) {
  846. return false;
  847. }
  848. } catch (AppConfigUnknownKeyException $e) {
  849. return false;
  850. }
  851. $lazy = $this->isLazy($app, $key);
  852. if ($lazy) {
  853. $cache = $this->lazyCache;
  854. } else {
  855. $cache = $this->fastCache;
  856. }
  857. if (!isset($cache[$app][$key])) {
  858. throw new AppConfigUnknownKeyException('unknown config key');
  859. }
  860. /**
  861. * type returned by getValueType() is already cleaned from sensitive flag
  862. * we just need to update it based on $sensitive and store it in database
  863. */
  864. $type = $this->getValueType($app, $key);
  865. $value = $cache[$app][$key];
  866. if ($sensitive) {
  867. $type |= self::VALUE_SENSITIVE;
  868. $value = self::ENCRYPTION_PREFIX . $this->crypto->encrypt($value);
  869. } else {
  870. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  871. }
  872. $update = $this->connection->getQueryBuilder();
  873. $update->update('appconfig')
  874. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  875. ->set('configvalue', $update->createNamedParameter($value))
  876. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  877. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  878. $update->executeStatement();
  879. $this->valueTypes[$app][$key] = $type;
  880. return true;
  881. }
  882. /**
  883. * @inheritDoc
  884. *
  885. * @param string $app id of the app
  886. * @param string $key config key
  887. * @param bool $lazy TRUE to set as lazy loaded, FALSE to unset
  888. *
  889. * @return bool TRUE if entry was found in database and an update was necessary
  890. * @since 29.0.0
  891. */
  892. public function updateLazy(string $app, string $key, bool $lazy): bool {
  893. $this->assertParams($app, $key);
  894. $this->loadConfigAll();
  895. try {
  896. if ($lazy === $this->isLazy($app, $key)) {
  897. return false;
  898. }
  899. } catch (AppConfigUnknownKeyException $e) {
  900. return false;
  901. }
  902. $update = $this->connection->getQueryBuilder();
  903. $update->update('appconfig')
  904. ->set('lazy', $update->createNamedParameter($lazy ? 1 : 0, IQueryBuilder::PARAM_INT))
  905. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  906. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  907. $update->executeStatement();
  908. // At this point, it is a lot safer to clean cache
  909. $this->clearCache();
  910. return true;
  911. }
  912. /**
  913. * @inheritDoc
  914. *
  915. * @param string $app id of the app
  916. * @param string $key config key
  917. *
  918. * @return array
  919. * @throws AppConfigUnknownKeyException if config key is not known in database
  920. * @since 29.0.0
  921. */
  922. public function getDetails(string $app, string $key): array {
  923. $this->assertParams($app, $key);
  924. $this->loadConfigAll();
  925. $lazy = $this->isLazy($app, $key);
  926. if ($lazy) {
  927. $cache = $this->lazyCache;
  928. } else {
  929. $cache = $this->fastCache;
  930. }
  931. $type = $this->getValueType($app, $key);
  932. try {
  933. $typeString = $this->convertTypeToString($type);
  934. } catch (AppConfigIncorrectTypeException $e) {
  935. $this->logger->warning('type stored in database is not correct', ['exception' => $e, 'type' => $type]);
  936. $typeString = (string)$type;
  937. }
  938. if (!isset($cache[$app][$key])) {
  939. throw new AppConfigUnknownKeyException('unknown config key');
  940. }
  941. $value = $cache[$app][$key];
  942. $sensitive = $this->isSensitive($app, $key, null);
  943. if ($sensitive && str_starts_with($value, self::ENCRYPTION_PREFIX)) {
  944. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  945. }
  946. return [
  947. 'app' => $app,
  948. 'key' => $key,
  949. 'value' => $value,
  950. 'type' => $type,
  951. 'lazy' => $lazy,
  952. 'typeString' => $typeString,
  953. 'sensitive' => $sensitive
  954. ];
  955. }
  956. /**
  957. * @param string $type
  958. *
  959. * @return int
  960. * @throws AppConfigIncorrectTypeException
  961. * @since 29.0.0
  962. */
  963. public function convertTypeToInt(string $type): int {
  964. return match (strtolower($type)) {
  965. 'mixed' => IAppConfig::VALUE_MIXED,
  966. 'string' => IAppConfig::VALUE_STRING,
  967. 'integer' => IAppConfig::VALUE_INT,
  968. 'float' => IAppConfig::VALUE_FLOAT,
  969. 'boolean' => IAppConfig::VALUE_BOOL,
  970. 'array' => IAppConfig::VALUE_ARRAY,
  971. default => throw new AppConfigIncorrectTypeException('Unknown type ' . $type)
  972. };
  973. }
  974. /**
  975. * @param int $type
  976. *
  977. * @return string
  978. * @throws AppConfigIncorrectTypeException
  979. * @since 29.0.0
  980. */
  981. public function convertTypeToString(int $type): string {
  982. $type &= ~self::VALUE_SENSITIVE;
  983. return match ($type) {
  984. IAppConfig::VALUE_MIXED => 'mixed',
  985. IAppConfig::VALUE_STRING => 'string',
  986. IAppConfig::VALUE_INT => 'integer',
  987. IAppConfig::VALUE_FLOAT => 'float',
  988. IAppConfig::VALUE_BOOL => 'boolean',
  989. IAppConfig::VALUE_ARRAY => 'array',
  990. default => throw new AppConfigIncorrectTypeException('Unknown numeric type ' . $type)
  991. };
  992. }
  993. /**
  994. * @inheritDoc
  995. *
  996. * @param string $app id of the app
  997. * @param string $key config key
  998. *
  999. * @since 29.0.0
  1000. */
  1001. public function deleteKey(string $app, string $key): void {
  1002. $this->assertParams($app, $key);
  1003. $qb = $this->connection->getQueryBuilder();
  1004. $qb->delete('appconfig')
  1005. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)))
  1006. ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
  1007. $qb->executeStatement();
  1008. unset($this->lazyCache[$app][$key]);
  1009. unset($this->fastCache[$app][$key]);
  1010. }
  1011. /**
  1012. * @inheritDoc
  1013. *
  1014. * @param string $app id of the app
  1015. *
  1016. * @since 29.0.0
  1017. */
  1018. public function deleteApp(string $app): void {
  1019. $this->assertParams($app);
  1020. $qb = $this->connection->getQueryBuilder();
  1021. $qb->delete('appconfig')
  1022. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)));
  1023. $qb->executeStatement();
  1024. $this->clearCache();
  1025. }
  1026. /**
  1027. * @inheritDoc
  1028. *
  1029. * @param bool $reload set to TRUE to refill cache instantly after clearing it
  1030. *
  1031. * @since 29.0.0
  1032. */
  1033. public function clearCache(bool $reload = false): void {
  1034. $this->lazyLoaded = $this->fastLoaded = false;
  1035. $this->lazyCache = $this->fastCache = $this->valueTypes = [];
  1036. if (!$reload) {
  1037. return;
  1038. }
  1039. $this->loadConfigAll();
  1040. }
  1041. /**
  1042. * For debug purpose.
  1043. * Returns the cached data.
  1044. *
  1045. * @return array
  1046. * @since 29.0.0
  1047. * @internal
  1048. */
  1049. public function statusCache(): array {
  1050. return [
  1051. 'fastLoaded' => $this->fastLoaded,
  1052. 'fastCache' => $this->fastCache,
  1053. 'lazyLoaded' => $this->lazyLoaded,
  1054. 'lazyCache' => $this->lazyCache,
  1055. ];
  1056. }
  1057. /**
  1058. * @param int $needle bitflag to search
  1059. * @param int $type known value
  1060. *
  1061. * @return bool TRUE if bitflag $needle is set in $type
  1062. */
  1063. private function isTyped(int $needle, int $type): bool {
  1064. return (($needle & $type) !== 0);
  1065. }
  1066. /**
  1067. * Confirm the string set for app and key fit the database description
  1068. *
  1069. * @param string $app assert $app fit in database
  1070. * @param string $configKey assert config key fit in database
  1071. * @param bool $allowEmptyApp $app can be empty string
  1072. * @param int $valueType assert value type is only one type
  1073. *
  1074. * @throws InvalidArgumentException
  1075. */
  1076. private function assertParams(string $app = '', string $configKey = '', bool $allowEmptyApp = false, int $valueType = -1): void {
  1077. if (!$allowEmptyApp && $app === '') {
  1078. throw new InvalidArgumentException('app cannot be an empty string');
  1079. }
  1080. if (strlen($app) > self::APP_MAX_LENGTH) {
  1081. throw new InvalidArgumentException(
  1082. 'Value (' . $app . ') for app is too long (' . self::APP_MAX_LENGTH . ')'
  1083. );
  1084. }
  1085. if (strlen($configKey) > self::KEY_MAX_LENGTH) {
  1086. throw new InvalidArgumentException('Value (' . $configKey . ') for key is too long (' . self::KEY_MAX_LENGTH . ')');
  1087. }
  1088. if ($valueType > -1) {
  1089. $valueType &= ~self::VALUE_SENSITIVE;
  1090. if (!in_array($valueType, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
  1091. throw new InvalidArgumentException('Unknown value type');
  1092. }
  1093. }
  1094. }
  1095. private function loadConfigAll(): void {
  1096. $this->loadConfig(null);
  1097. }
  1098. /**
  1099. * Load normal config or config set as lazy loaded
  1100. *
  1101. * @param bool|null $lazy set to TRUE to load config set as lazy loaded, set to NULL to load all config
  1102. */
  1103. private function loadConfig(?bool $lazy = false): void {
  1104. if ($this->isLoaded($lazy)) {
  1105. return;
  1106. }
  1107. if (($lazy ?? true) !== false) { // if lazy is null or true, we debug log
  1108. $this->logger->debug('The loading of lazy AppConfig values have been requested', ['exception' => new \RuntimeException('ignorable exception')]);
  1109. }
  1110. $qb = $this->connection->getQueryBuilder();
  1111. $qb->from('appconfig');
  1112. /**
  1113. * The use of $this->>migrationCompleted is only needed to manage the
  1114. * database during the upgrading process to nc29.
  1115. */
  1116. if (!$this->migrationCompleted) {
  1117. $qb->select('appid', 'configkey', 'configvalue');
  1118. } else {
  1119. // we only need value from lazy when loadConfig does not specify it
  1120. $qb->select('appid', 'configkey', 'configvalue', 'type');
  1121. if ($lazy !== null) {
  1122. $qb->where($qb->expr()->eq('lazy', $qb->createNamedParameter($lazy ? 1 : 0, IQueryBuilder::PARAM_INT)));
  1123. } else {
  1124. $qb->addSelect('lazy');
  1125. }
  1126. }
  1127. try {
  1128. $result = $qb->executeQuery();
  1129. } catch (DBException $e) {
  1130. /**
  1131. * in case of issue with field name, it means that migration is not completed.
  1132. * Falling back to a request without select on lazy.
  1133. * This whole try/catch and the migrationCompleted variable can be removed in NC30.
  1134. */
  1135. if ($e->getReason() !== DBException::REASON_INVALID_FIELD_NAME) {
  1136. throw $e;
  1137. }
  1138. $this->migrationCompleted = false;
  1139. $this->loadConfig($lazy);
  1140. return;
  1141. }
  1142. $rows = $result->fetchAll();
  1143. foreach ($rows as $row) {
  1144. // most of the time, 'lazy' is not in the select because its value is already known
  1145. if (($row['lazy'] ?? ($lazy ?? 0) ? 1 : 0) === 1) {
  1146. $cache = &$this->lazyCache;
  1147. } else {
  1148. $cache = &$this->fastCache;
  1149. }
  1150. $cache[$row['appid']][$row['configkey']] = $row['configvalue'] ?? '';
  1151. $this->valueTypes[$row['appid']][$row['configkey']] = (int)($row['type'] ?? 0);
  1152. }
  1153. $result->closeCursor();
  1154. $this->setAsLoaded($lazy);
  1155. }
  1156. /**
  1157. * if $lazy is:
  1158. * - false: will returns true if fast config is loaded
  1159. * - true : will returns true if lazy config is loaded
  1160. * - null : will returns true if both config are loaded
  1161. *
  1162. * @param bool $lazy
  1163. *
  1164. * @return bool
  1165. */
  1166. private function isLoaded(?bool $lazy): bool {
  1167. if ($lazy === null) {
  1168. return $this->lazyLoaded && $this->fastLoaded;
  1169. }
  1170. return $lazy ? $this->lazyLoaded : $this->fastLoaded;
  1171. }
  1172. /**
  1173. * if $lazy is:
  1174. * - false: set fast config as loaded
  1175. * - true : set lazy config as loaded
  1176. * - null : set both config as loaded
  1177. *
  1178. * @param bool $lazy
  1179. */
  1180. private function setAsLoaded(?bool $lazy): void {
  1181. if ($lazy === null) {
  1182. $this->fastLoaded = true;
  1183. $this->lazyLoaded = true;
  1184. return;
  1185. }
  1186. if ($lazy) {
  1187. $this->lazyLoaded = true;
  1188. } else {
  1189. $this->fastLoaded = true;
  1190. }
  1191. }
  1192. /**
  1193. * Gets the config value
  1194. *
  1195. * @param string $app app
  1196. * @param string $key key
  1197. * @param string $default = null, default value if the key does not exist
  1198. *
  1199. * @return string the value or $default
  1200. * @deprecated - use getValue*()
  1201. *
  1202. * This function gets a value from the appconfig table. If the key does
  1203. * not exist the default value will be returned
  1204. */
  1205. public function getValue($app, $key, $default = null) {
  1206. $this->loadConfig();
  1207. return $this->fastCache[$app][$key] ?? $default;
  1208. }
  1209. /**
  1210. * Sets a value. If the key did not exist before it will be created.
  1211. *
  1212. * @param string $app app
  1213. * @param string $key key
  1214. * @param string|float|int $value value
  1215. *
  1216. * @return bool True if the value was inserted or updated, false if the value was the same
  1217. * @throws AppConfigTypeConflictException
  1218. * @throws AppConfigUnknownKeyException
  1219. * @deprecated
  1220. */
  1221. public function setValue($app, $key, $value) {
  1222. /**
  1223. * TODO: would it be overkill, or decently improve performance, to catch
  1224. * call to this method with $key='enabled' and 'hide' config value related
  1225. * to $app when the app is disabled (by modifying entry in database: lazy=lazy+2)
  1226. * or enabled (lazy=lazy-2)
  1227. *
  1228. * this solution would remove the loading of config values from disabled app
  1229. * unless calling the method {@see loadConfigAll()}
  1230. */
  1231. return $this->setTypedValue($app, $key, (string)$value, false, self::VALUE_MIXED);
  1232. }
  1233. /**
  1234. * get multiple values, either the app or key can be used as wildcard by setting it to false
  1235. *
  1236. * @param string|false $app
  1237. * @param string|false $key
  1238. *
  1239. * @return array|false
  1240. * @deprecated 29.0.0 use {@see getAllValues()}
  1241. */
  1242. public function getValues($app, $key) {
  1243. if (($app !== false) === ($key !== false)) {
  1244. return false;
  1245. }
  1246. $key = ($key === false) ? '' : $key;
  1247. if (!$app) {
  1248. return $this->searchValues($key, false, self::VALUE_MIXED);
  1249. } else {
  1250. return $this->getAllValues($app, $key);
  1251. }
  1252. }
  1253. /**
  1254. * get all values of the app or and filters out sensitive data
  1255. *
  1256. * @param string $app
  1257. *
  1258. * @return array
  1259. * @deprecated 29.0.0 use {@see getAllValues()}
  1260. */
  1261. public function getFilteredValues($app) {
  1262. return $this->getAllValues($app, filtered: true);
  1263. }
  1264. /**
  1265. * **Warning:** avoid default NULL value for $lazy as this will
  1266. * load all lazy values from the database
  1267. *
  1268. * @param string $app
  1269. * @param array<string, string> $values ['key' => 'value']
  1270. * @param bool|null $lazy
  1271. *
  1272. * @return array<string, string|int|float|bool|array>
  1273. */
  1274. private function formatAppValues(string $app, array $values, ?bool $lazy = null): array {
  1275. foreach($values as $key => $value) {
  1276. try {
  1277. $type = $this->getValueType($app, $key, $lazy);
  1278. } catch (AppConfigUnknownKeyException $e) {
  1279. continue;
  1280. }
  1281. $values[$key] = $this->convertTypedValue($value, $type);
  1282. }
  1283. return $values;
  1284. }
  1285. /**
  1286. * convert string value to the expected type
  1287. *
  1288. * @param string $value
  1289. * @param int $type
  1290. *
  1291. * @return string|int|float|bool|array
  1292. */
  1293. private function convertTypedValue(string $value, int $type): string|int|float|bool|array {
  1294. switch ($type) {
  1295. case self::VALUE_INT:
  1296. return (int)$value;
  1297. case self::VALUE_FLOAT:
  1298. return (float)$value;
  1299. case self::VALUE_BOOL:
  1300. return in_array(strtolower($value), ['1', 'true', 'yes', 'on']);
  1301. case self::VALUE_ARRAY:
  1302. try {
  1303. return json_decode($value, true, flags: JSON_THROW_ON_ERROR);
  1304. } catch (JsonException $e) {
  1305. // ignoreable
  1306. }
  1307. break;
  1308. }
  1309. return $value;
  1310. }
  1311. /**
  1312. * @param string $app
  1313. *
  1314. * @return string[]
  1315. * @deprecated data sensitivity should be set when calling setValue*()
  1316. */
  1317. private function getSensitiveKeys(string $app): array {
  1318. $sensitiveValues = [
  1319. 'circles' => [
  1320. '/^key_pairs$/',
  1321. '/^local_gskey$/',
  1322. ],
  1323. 'external' => [
  1324. '/^sites$/',
  1325. ],
  1326. 'integration_discourse' => [
  1327. '/^private_key$/',
  1328. '/^public_key$/',
  1329. ],
  1330. 'integration_dropbox' => [
  1331. '/^client_id$/',
  1332. '/^client_secret$/',
  1333. ],
  1334. 'integration_github' => [
  1335. '/^client_id$/',
  1336. '/^client_secret$/',
  1337. ],
  1338. 'integration_gitlab' => [
  1339. '/^client_id$/',
  1340. '/^client_secret$/',
  1341. '/^oauth_instance_url$/',
  1342. ],
  1343. 'integration_google' => [
  1344. '/^client_id$/',
  1345. '/^client_secret$/',
  1346. ],
  1347. 'integration_jira' => [
  1348. '/^client_id$/',
  1349. '/^client_secret$/',
  1350. '/^forced_instance_url$/',
  1351. ],
  1352. 'integration_onedrive' => [
  1353. '/^client_id$/',
  1354. '/^client_secret$/',
  1355. ],
  1356. 'integration_openproject' => [
  1357. '/^client_id$/',
  1358. '/^client_secret$/',
  1359. '/^oauth_instance_url$/',
  1360. ],
  1361. 'integration_reddit' => [
  1362. '/^client_id$/',
  1363. '/^client_secret$/',
  1364. ],
  1365. 'integration_suitecrm' => [
  1366. '/^client_id$/',
  1367. '/^client_secret$/',
  1368. '/^oauth_instance_url$/',
  1369. ],
  1370. 'integration_twitter' => [
  1371. '/^consumer_key$/',
  1372. '/^consumer_secret$/',
  1373. '/^followed_user$/',
  1374. ],
  1375. 'integration_zammad' => [
  1376. '/^client_id$/',
  1377. '/^client_secret$/',
  1378. '/^oauth_instance_url$/',
  1379. ],
  1380. 'notify_push' => [
  1381. '/^cookie$/',
  1382. ],
  1383. 'serverinfo' => [
  1384. '/^token$/',
  1385. ],
  1386. 'spreed' => [
  1387. '/^bridge_bot_password$/',
  1388. '/^hosted-signaling-server-(.*)$/',
  1389. '/^recording_servers$/',
  1390. '/^signaling_servers$/',
  1391. '/^signaling_ticket_secret$/',
  1392. '/^signaling_token_privkey_(.*)$/',
  1393. '/^signaling_token_pubkey_(.*)$/',
  1394. '/^sip_bridge_dialin_info$/',
  1395. '/^sip_bridge_shared_secret$/',
  1396. '/^stun_servers$/',
  1397. '/^turn_servers$/',
  1398. '/^turn_server_secret$/',
  1399. ],
  1400. 'support' => [
  1401. '/^last_response$/',
  1402. '/^potential_subscription_key$/',
  1403. '/^subscription_key$/',
  1404. ],
  1405. 'theming' => [
  1406. '/^imprintUrl$/',
  1407. '/^privacyUrl$/',
  1408. '/^slogan$/',
  1409. '/^url$/',
  1410. ],
  1411. 'user_ldap' => [
  1412. '/^(s..)?ldap_agent_password$/',
  1413. ],
  1414. 'user_saml' => [
  1415. '/^idp-x509cert$/',
  1416. ],
  1417. ];
  1418. return $sensitiveValues[$app] ?? [];
  1419. }
  1420. /**
  1421. * Clear all the cached app config values
  1422. * New cache will be generated next time a config value is retrieved
  1423. *
  1424. * @deprecated use {@see clearCache()}
  1425. */
  1426. public function clearCachedConfig(): void {
  1427. $this->clearCache();
  1428. }
  1429. }