You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppConfig.php 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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. return [
  942. 'app' => $app,
  943. 'key' => $key,
  944. 'value' => $cache[$app][$key],
  945. 'type' => $type,
  946. 'lazy' => $lazy,
  947. 'typeString' => $typeString,
  948. 'sensitive' => $this->isSensitive($app, $key, null)
  949. ];
  950. }
  951. /**
  952. * @param string $type
  953. *
  954. * @return int
  955. * @throws AppConfigIncorrectTypeException
  956. * @since 29.0.0
  957. */
  958. public function convertTypeToInt(string $type): int {
  959. return match (strtolower($type)) {
  960. 'mixed' => IAppConfig::VALUE_MIXED,
  961. 'string' => IAppConfig::VALUE_STRING,
  962. 'integer' => IAppConfig::VALUE_INT,
  963. 'float' => IAppConfig::VALUE_FLOAT,
  964. 'boolean' => IAppConfig::VALUE_BOOL,
  965. 'array' => IAppConfig::VALUE_ARRAY,
  966. default => throw new AppConfigIncorrectTypeException('Unknown type ' . $type)
  967. };
  968. }
  969. /**
  970. * @param int $type
  971. *
  972. * @return string
  973. * @throws AppConfigIncorrectTypeException
  974. * @since 29.0.0
  975. */
  976. public function convertTypeToString(int $type): string {
  977. $type &= ~self::VALUE_SENSITIVE;
  978. return match ($type) {
  979. IAppConfig::VALUE_MIXED => 'mixed',
  980. IAppConfig::VALUE_STRING => 'string',
  981. IAppConfig::VALUE_INT => 'integer',
  982. IAppConfig::VALUE_FLOAT => 'float',
  983. IAppConfig::VALUE_BOOL => 'boolean',
  984. IAppConfig::VALUE_ARRAY => 'array',
  985. default => throw new AppConfigIncorrectTypeException('Unknown numeric type ' . $type)
  986. };
  987. }
  988. /**
  989. * @inheritDoc
  990. *
  991. * @param string $app id of the app
  992. * @param string $key config key
  993. *
  994. * @since 29.0.0
  995. */
  996. public function deleteKey(string $app, string $key): void {
  997. $this->assertParams($app, $key);
  998. $qb = $this->connection->getQueryBuilder();
  999. $qb->delete('appconfig')
  1000. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)))
  1001. ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
  1002. $qb->executeStatement();
  1003. unset($this->lazyCache[$app][$key]);
  1004. unset($this->fastCache[$app][$key]);
  1005. }
  1006. /**
  1007. * @inheritDoc
  1008. *
  1009. * @param string $app id of the app
  1010. *
  1011. * @since 29.0.0
  1012. */
  1013. public function deleteApp(string $app): void {
  1014. $this->assertParams($app);
  1015. $qb = $this->connection->getQueryBuilder();
  1016. $qb->delete('appconfig')
  1017. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)));
  1018. $qb->executeStatement();
  1019. $this->clearCache();
  1020. }
  1021. /**
  1022. * @inheritDoc
  1023. *
  1024. * @param bool $reload set to TRUE to refill cache instantly after clearing it
  1025. *
  1026. * @since 29.0.0
  1027. */
  1028. public function clearCache(bool $reload = false): void {
  1029. $this->lazyLoaded = $this->fastLoaded = false;
  1030. $this->lazyCache = $this->fastCache = $this->valueTypes = [];
  1031. if (!$reload) {
  1032. return;
  1033. }
  1034. $this->loadConfigAll();
  1035. }
  1036. /**
  1037. * For debug purpose.
  1038. * Returns the cached data.
  1039. *
  1040. * @return array
  1041. * @since 29.0.0
  1042. * @internal
  1043. */
  1044. public function statusCache(): array {
  1045. return [
  1046. 'fastLoaded' => $this->fastLoaded,
  1047. 'fastCache' => $this->fastCache,
  1048. 'lazyLoaded' => $this->lazyLoaded,
  1049. 'lazyCache' => $this->lazyCache,
  1050. ];
  1051. }
  1052. /**
  1053. * @param int $needle bitflag to search
  1054. * @param int $type known value
  1055. *
  1056. * @return bool TRUE if bitflag $needle is set in $type
  1057. */
  1058. private function isTyped(int $needle, int $type): bool {
  1059. return (($needle & $type) !== 0);
  1060. }
  1061. /**
  1062. * Confirm the string set for app and key fit the database description
  1063. *
  1064. * @param string $app assert $app fit in database
  1065. * @param string $configKey assert config key fit in database
  1066. * @param bool $allowEmptyApp $app can be empty string
  1067. * @param int $valueType assert value type is only one type
  1068. *
  1069. * @throws InvalidArgumentException
  1070. */
  1071. private function assertParams(string $app = '', string $configKey = '', bool $allowEmptyApp = false, int $valueType = -1): void {
  1072. if (!$allowEmptyApp && $app === '') {
  1073. throw new InvalidArgumentException('app cannot be an empty string');
  1074. }
  1075. if (strlen($app) > self::APP_MAX_LENGTH) {
  1076. throw new InvalidArgumentException(
  1077. 'Value (' . $app . ') for app is too long (' . self::APP_MAX_LENGTH . ')'
  1078. );
  1079. }
  1080. if (strlen($configKey) > self::KEY_MAX_LENGTH) {
  1081. throw new InvalidArgumentException('Value (' . $configKey . ') for key is too long (' . self::KEY_MAX_LENGTH . ')');
  1082. }
  1083. if ($valueType > -1) {
  1084. $valueType &= ~self::VALUE_SENSITIVE;
  1085. if (!in_array($valueType, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
  1086. throw new InvalidArgumentException('Unknown value type');
  1087. }
  1088. }
  1089. }
  1090. private function loadConfigAll(): void {
  1091. $this->loadConfig(null);
  1092. }
  1093. /**
  1094. * Load normal config or config set as lazy loaded
  1095. *
  1096. * @param bool|null $lazy set to TRUE to load config set as lazy loaded, set to NULL to load all config
  1097. */
  1098. private function loadConfig(?bool $lazy = false): void {
  1099. if ($this->isLoaded($lazy)) {
  1100. return;
  1101. }
  1102. if (($lazy ?? true) !== false) { // if lazy is null or true, we debug log
  1103. $this->logger->debug('The loading of lazy AppConfig values have been requested', ['exception' => new \RuntimeException('ignorable exception')]);
  1104. }
  1105. $qb = $this->connection->getQueryBuilder();
  1106. $qb->from('appconfig');
  1107. /**
  1108. * The use of $this->>migrationCompleted is only needed to manage the
  1109. * database during the upgrading process to nc29.
  1110. */
  1111. if (!$this->migrationCompleted) {
  1112. $qb->select('appid', 'configkey', 'configvalue');
  1113. } else {
  1114. // we only need value from lazy when loadConfig does not specify it
  1115. $qb->select('appid', 'configkey', 'configvalue', 'type');
  1116. if ($lazy !== null) {
  1117. $qb->where($qb->expr()->eq('lazy', $qb->createNamedParameter($lazy ? 1 : 0, IQueryBuilder::PARAM_INT)));
  1118. } else {
  1119. $qb->addSelect('lazy');
  1120. }
  1121. }
  1122. try {
  1123. $result = $qb->executeQuery();
  1124. } catch (DBException $e) {
  1125. /**
  1126. * in case of issue with field name, it means that migration is not completed.
  1127. * Falling back to a request without select on lazy.
  1128. * This whole try/catch and the migrationCompleted variable can be removed in NC30.
  1129. */
  1130. if ($e->getReason() !== DBException::REASON_INVALID_FIELD_NAME) {
  1131. throw $e;
  1132. }
  1133. $this->migrationCompleted = false;
  1134. $this->loadConfig($lazy);
  1135. return;
  1136. }
  1137. $rows = $result->fetchAll();
  1138. foreach ($rows as $row) {
  1139. // most of the time, 'lazy' is not in the select because its value is already known
  1140. if (($row['lazy'] ?? ($lazy ?? 0) ? 1 : 0) === 1) {
  1141. $cache = &$this->lazyCache;
  1142. } else {
  1143. $cache = &$this->fastCache;
  1144. }
  1145. $cache[$row['appid']][$row['configkey']] = $row['configvalue'] ?? '';
  1146. $this->valueTypes[$row['appid']][$row['configkey']] = (int)($row['type'] ?? 0);
  1147. }
  1148. $result->closeCursor();
  1149. $this->setAsLoaded($lazy);
  1150. }
  1151. /**
  1152. * if $lazy is:
  1153. * - false: will returns true if fast config is loaded
  1154. * - true : will returns true if lazy config is loaded
  1155. * - null : will returns true if both config are loaded
  1156. *
  1157. * @param bool $lazy
  1158. *
  1159. * @return bool
  1160. */
  1161. private function isLoaded(?bool $lazy): bool {
  1162. if ($lazy === null) {
  1163. return $this->lazyLoaded && $this->fastLoaded;
  1164. }
  1165. return $lazy ? $this->lazyLoaded : $this->fastLoaded;
  1166. }
  1167. /**
  1168. * if $lazy is:
  1169. * - false: set fast config as loaded
  1170. * - true : set lazy config as loaded
  1171. * - null : set both config as loaded
  1172. *
  1173. * @param bool $lazy
  1174. */
  1175. private function setAsLoaded(?bool $lazy): void {
  1176. if ($lazy === null) {
  1177. $this->fastLoaded = true;
  1178. $this->lazyLoaded = true;
  1179. return;
  1180. }
  1181. if ($lazy) {
  1182. $this->lazyLoaded = true;
  1183. } else {
  1184. $this->fastLoaded = true;
  1185. }
  1186. }
  1187. /**
  1188. * Gets the config value
  1189. *
  1190. * @param string $app app
  1191. * @param string $key key
  1192. * @param string $default = null, default value if the key does not exist
  1193. *
  1194. * @return string the value or $default
  1195. * @deprecated - use getValue*()
  1196. *
  1197. * This function gets a value from the appconfig table. If the key does
  1198. * not exist the default value will be returned
  1199. */
  1200. public function getValue($app, $key, $default = null) {
  1201. $this->loadConfig();
  1202. return $this->fastCache[$app][$key] ?? $default;
  1203. }
  1204. /**
  1205. * Sets a value. If the key did not exist before it will be created.
  1206. *
  1207. * @param string $app app
  1208. * @param string $key key
  1209. * @param string|float|int $value value
  1210. *
  1211. * @return bool True if the value was inserted or updated, false if the value was the same
  1212. * @throws AppConfigTypeConflictException
  1213. * @throws AppConfigUnknownKeyException
  1214. * @deprecated
  1215. */
  1216. public function setValue($app, $key, $value) {
  1217. /**
  1218. * TODO: would it be overkill, or decently improve performance, to catch
  1219. * call to this method with $key='enabled' and 'hide' config value related
  1220. * to $app when the app is disabled (by modifying entry in database: lazy=lazy+2)
  1221. * or enabled (lazy=lazy-2)
  1222. *
  1223. * this solution would remove the loading of config values from disabled app
  1224. * unless calling the method {@see loadConfigAll()}
  1225. */
  1226. return $this->setTypedValue($app, $key, (string)$value, false, self::VALUE_MIXED);
  1227. }
  1228. /**
  1229. * get multiple values, either the app or key can be used as wildcard by setting it to false
  1230. *
  1231. * @param string|false $app
  1232. * @param string|false $key
  1233. *
  1234. * @return array|false
  1235. * @deprecated 29.0.0 use {@see getAllValues()}
  1236. */
  1237. public function getValues($app, $key) {
  1238. if (($app !== false) === ($key !== false)) {
  1239. return false;
  1240. }
  1241. $key = ($key === false) ? '' : $key;
  1242. if (!$app) {
  1243. return $this->searchValues($key, false, self::VALUE_MIXED);
  1244. } else {
  1245. return $this->getAllValues($app, $key);
  1246. }
  1247. }
  1248. /**
  1249. * get all values of the app or and filters out sensitive data
  1250. *
  1251. * @param string $app
  1252. *
  1253. * @return array
  1254. * @deprecated 29.0.0 use {@see getAllValues()}
  1255. */
  1256. public function getFilteredValues($app) {
  1257. return $this->getAllValues($app, filtered: true);
  1258. }
  1259. /**
  1260. * **Warning:** avoid default NULL value for $lazy as this will
  1261. * load all lazy values from the database
  1262. *
  1263. * @param string $app
  1264. * @param array<string, string> $values ['key' => 'value']
  1265. * @param bool|null $lazy
  1266. *
  1267. * @return array<string, string|int|float|bool|array>
  1268. */
  1269. private function formatAppValues(string $app, array $values, ?bool $lazy = null): array {
  1270. foreach($values as $key => $value) {
  1271. try {
  1272. $type = $this->getValueType($app, $key, $lazy);
  1273. } catch (AppConfigUnknownKeyException $e) {
  1274. continue;
  1275. }
  1276. $values[$key] = $this->convertTypedValue($value, $type);
  1277. }
  1278. return $values;
  1279. }
  1280. /**
  1281. * convert string value to the expected type
  1282. *
  1283. * @param string $value
  1284. * @param int $type
  1285. *
  1286. * @return string|int|float|bool|array
  1287. */
  1288. private function convertTypedValue(string $value, int $type): string|int|float|bool|array {
  1289. switch ($type) {
  1290. case self::VALUE_INT:
  1291. return (int)$value;
  1292. case self::VALUE_FLOAT:
  1293. return (float)$value;
  1294. case self::VALUE_BOOL:
  1295. return in_array(strtolower($value), ['1', 'true', 'yes', 'on']);
  1296. case self::VALUE_ARRAY:
  1297. try {
  1298. return json_decode($value, true, flags: JSON_THROW_ON_ERROR);
  1299. } catch (JsonException $e) {
  1300. // ignoreable
  1301. }
  1302. break;
  1303. }
  1304. return $value;
  1305. }
  1306. /**
  1307. * @param string $app
  1308. *
  1309. * @return string[]
  1310. * @deprecated data sensitivity should be set when calling setValue*()
  1311. */
  1312. private function getSensitiveKeys(string $app): array {
  1313. $sensitiveValues = [
  1314. 'circles' => [
  1315. '/^key_pairs$/',
  1316. '/^local_gskey$/',
  1317. ],
  1318. 'external' => [
  1319. '/^sites$/',
  1320. ],
  1321. 'integration_discourse' => [
  1322. '/^private_key$/',
  1323. '/^public_key$/',
  1324. ],
  1325. 'integration_dropbox' => [
  1326. '/^client_id$/',
  1327. '/^client_secret$/',
  1328. ],
  1329. 'integration_github' => [
  1330. '/^client_id$/',
  1331. '/^client_secret$/',
  1332. ],
  1333. 'integration_gitlab' => [
  1334. '/^client_id$/',
  1335. '/^client_secret$/',
  1336. '/^oauth_instance_url$/',
  1337. ],
  1338. 'integration_google' => [
  1339. '/^client_id$/',
  1340. '/^client_secret$/',
  1341. ],
  1342. 'integration_jira' => [
  1343. '/^client_id$/',
  1344. '/^client_secret$/',
  1345. '/^forced_instance_url$/',
  1346. ],
  1347. 'integration_onedrive' => [
  1348. '/^client_id$/',
  1349. '/^client_secret$/',
  1350. ],
  1351. 'integration_openproject' => [
  1352. '/^client_id$/',
  1353. '/^client_secret$/',
  1354. '/^oauth_instance_url$/',
  1355. ],
  1356. 'integration_reddit' => [
  1357. '/^client_id$/',
  1358. '/^client_secret$/',
  1359. ],
  1360. 'integration_suitecrm' => [
  1361. '/^client_id$/',
  1362. '/^client_secret$/',
  1363. '/^oauth_instance_url$/',
  1364. ],
  1365. 'integration_twitter' => [
  1366. '/^consumer_key$/',
  1367. '/^consumer_secret$/',
  1368. '/^followed_user$/',
  1369. ],
  1370. 'integration_zammad' => [
  1371. '/^client_id$/',
  1372. '/^client_secret$/',
  1373. '/^oauth_instance_url$/',
  1374. ],
  1375. 'notify_push' => [
  1376. '/^cookie$/',
  1377. ],
  1378. 'serverinfo' => [
  1379. '/^token$/',
  1380. ],
  1381. 'spreed' => [
  1382. '/^bridge_bot_password$/',
  1383. '/^hosted-signaling-server-(.*)$/',
  1384. '/^recording_servers$/',
  1385. '/^signaling_servers$/',
  1386. '/^signaling_ticket_secret$/',
  1387. '/^signaling_token_privkey_(.*)$/',
  1388. '/^signaling_token_pubkey_(.*)$/',
  1389. '/^sip_bridge_dialin_info$/',
  1390. '/^sip_bridge_shared_secret$/',
  1391. '/^stun_servers$/',
  1392. '/^turn_servers$/',
  1393. '/^turn_server_secret$/',
  1394. ],
  1395. 'support' => [
  1396. '/^last_response$/',
  1397. '/^potential_subscription_key$/',
  1398. '/^subscription_key$/',
  1399. ],
  1400. 'theming' => [
  1401. '/^imprintUrl$/',
  1402. '/^privacyUrl$/',
  1403. '/^slogan$/',
  1404. '/^url$/',
  1405. ],
  1406. 'user_ldap' => [
  1407. '/^(s..)?ldap_agent_password$/',
  1408. ],
  1409. 'user_saml' => [
  1410. '/^idp-x509cert$/',
  1411. ],
  1412. ];
  1413. return $sensitiveValues[$app] ?? [];
  1414. }
  1415. /**
  1416. * Clear all the cached app config values
  1417. * New cache will be generated next time a config value is retrieved
  1418. *
  1419. * @deprecated use {@see clearCache()}
  1420. */
  1421. public function clearCachedConfig(): void {
  1422. $this->clearCache();
  1423. }
  1424. }