AppConfig.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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> [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 = array_filter(
  200. (($this->fastCache[$app] ?? []) + ($this->lazyCache[$app] ?? [])),
  201. function (string $key) use ($prefix): bool {
  202. return str_starts_with($key, $prefix); // filter values based on $prefix
  203. }, ARRAY_FILTER_USE_KEY
  204. );
  205. if (!$filtered) {
  206. return $values;
  207. }
  208. /**
  209. * Using the old (deprecated) list of sensitive values.
  210. */
  211. foreach ($this->getSensitiveKeys($app) as $sensitiveKeyExp) {
  212. $sensitiveKeys = preg_grep($sensitiveKeyExp, array_keys($values));
  213. foreach ($sensitiveKeys as $sensitiveKey) {
  214. $this->valueTypes[$app][$sensitiveKey] = ($this->valueTypes[$app][$sensitiveKey] ?? 0) | self::VALUE_SENSITIVE;
  215. }
  216. }
  217. $result = [];
  218. foreach ($values as $key => $value) {
  219. $result[$key] = $this->isTyped(self::VALUE_SENSITIVE, $this->valueTypes[$app][$key] ?? 0) ? IConfig::SENSITIVE_VALUE : $value;
  220. }
  221. return $result;
  222. }
  223. /**
  224. * @inheritDoc
  225. *
  226. * @param string $key config key
  227. * @param bool $lazy search within lazy loaded config
  228. *
  229. * @return array<string, string> [appId => configValue]
  230. * @since 29.0.0
  231. */
  232. public function searchValues(string $key, bool $lazy = false): array {
  233. $this->assertParams('', $key, true);
  234. $this->loadConfig($lazy);
  235. $values = [];
  236. /** @var array<array-key, array<array-key, mixed>> $cache */
  237. if ($lazy) {
  238. $cache = $this->lazyCache;
  239. } else {
  240. $cache = $this->fastCache;
  241. }
  242. foreach (array_keys($cache) as $app) {
  243. if (isset($cache[$app][$key])) {
  244. $values[$app] = $cache[$app][$key];
  245. }
  246. }
  247. return $values;
  248. }
  249. /**
  250. * Get the config value as string.
  251. * If the value does not exist the given default will be returned.
  252. *
  253. * Set lazy to `null` to ignore it and get the value from either source.
  254. *
  255. * **WARNING:** Method is internal and **SHOULD** not be used, as it is better to get the value with a type.
  256. *
  257. * @param string $app id of the app
  258. * @param string $key config key
  259. * @param string $default config value
  260. * @param null|bool $lazy get config as lazy loaded or not. can be NULL
  261. *
  262. * @return string the value or $default
  263. * @internal
  264. * @since 29.0.0
  265. * @see IAppConfig for explanation about lazy loading
  266. * @see getValueString()
  267. * @see getValueInt()
  268. * @see getValueFloat()
  269. * @see getValueBool()
  270. * @see getValueArray()
  271. */
  272. public function getValueMixed(
  273. string $app,
  274. string $key,
  275. string $default = '',
  276. ?bool $lazy = false
  277. ): string {
  278. try {
  279. $lazy = ($lazy === null) ? $this->isLazy($app, $key) : $lazy;
  280. } catch (AppConfigUnknownKeyException $e) {
  281. return $default;
  282. }
  283. return $this->getTypedValue(
  284. $app,
  285. $key,
  286. $default,
  287. $lazy,
  288. self::VALUE_MIXED
  289. );
  290. }
  291. /**
  292. * @inheritDoc
  293. *
  294. * @param string $app id of the app
  295. * @param string $key config key
  296. * @param string $default default value
  297. * @param bool $lazy search within lazy loaded config
  298. *
  299. * @return string stored config value or $default if not set in database
  300. * @throws InvalidArgumentException if one of the argument format is invalid
  301. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  302. * @since 29.0.0
  303. * @see IAppConfig for explanation about lazy loading
  304. */
  305. public function getValueString(
  306. string $app,
  307. string $key,
  308. string $default = '',
  309. bool $lazy = false
  310. ): string {
  311. return $this->getTypedValue($app, $key, $default, $lazy, self::VALUE_STRING);
  312. }
  313. /**
  314. * @inheritDoc
  315. *
  316. * @param string $app id of the app
  317. * @param string $key config key
  318. * @param int $default default value
  319. * @param bool $lazy search within lazy loaded config
  320. *
  321. * @return int stored config value or $default if not set in database
  322. * @throws InvalidArgumentException if one of the argument format is invalid
  323. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  324. * @since 29.0.0
  325. * @see IAppConfig for explanation about lazy loading
  326. */
  327. public function getValueInt(
  328. string $app,
  329. string $key,
  330. int $default = 0,
  331. bool $lazy = false
  332. ): int {
  333. return (int)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_INT);
  334. }
  335. /**
  336. * @inheritDoc
  337. *
  338. * @param string $app id of the app
  339. * @param string $key config key
  340. * @param float $default default value
  341. * @param bool $lazy search within lazy loaded config
  342. *
  343. * @return float stored config value or $default if not set in database
  344. * @throws InvalidArgumentException if one of the argument format is invalid
  345. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  346. * @since 29.0.0
  347. * @see IAppConfig for explanation about lazy loading
  348. */
  349. public function getValueFloat(string $app, string $key, float $default = 0, bool $lazy = false): float {
  350. return (float)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_FLOAT);
  351. }
  352. /**
  353. * @inheritDoc
  354. *
  355. * @param string $app id of the app
  356. * @param string $key config key
  357. * @param bool $default default value
  358. * @param bool $lazy search within lazy loaded config
  359. *
  360. * @return bool stored config value or $default if not set in database
  361. * @throws InvalidArgumentException if one of the argument format is invalid
  362. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  363. * @since 29.0.0
  364. * @see IAppConfig for explanation about lazy loading
  365. */
  366. public function getValueBool(string $app, string $key, bool $default = false, bool $lazy = false): bool {
  367. $b = strtolower($this->getTypedValue($app, $key, $default ? 'true' : 'false', $lazy, self::VALUE_BOOL));
  368. return in_array($b, ['1', 'true', 'yes', 'on']);
  369. }
  370. /**
  371. * @inheritDoc
  372. *
  373. * @param string $app id of the app
  374. * @param string $key config key
  375. * @param array $default default value
  376. * @param bool $lazy search within lazy loaded config
  377. *
  378. * @return array stored config value or $default if not set in database
  379. * @throws InvalidArgumentException if one of the argument format is invalid
  380. * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
  381. * @since 29.0.0
  382. * @see IAppConfig for explanation about lazy loading
  383. */
  384. public function getValueArray(
  385. string $app,
  386. string $key,
  387. array $default = [],
  388. bool $lazy = false
  389. ): array {
  390. try {
  391. $defaultJson = json_encode($default, JSON_THROW_ON_ERROR);
  392. $value = json_decode($this->getTypedValue($app, $key, $defaultJson, $lazy, self::VALUE_ARRAY), true, flags: JSON_THROW_ON_ERROR);
  393. return is_array($value) ? $value : [];
  394. } catch (JsonException) {
  395. return [];
  396. }
  397. }
  398. /**
  399. * @param string $app id of the app
  400. * @param string $key config key
  401. * @param string $default default value
  402. * @param bool $lazy search within lazy loaded config
  403. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT}{@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  404. *
  405. * @return string
  406. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  407. * @throws InvalidArgumentException
  408. */
  409. private function getTypedValue(
  410. string $app,
  411. string $key,
  412. string $default,
  413. bool $lazy,
  414. int $type
  415. ): string {
  416. $this->assertParams($app, $key, valueType: $type);
  417. $this->loadConfig($lazy);
  418. /**
  419. * We ignore check if mixed type is requested.
  420. * If type of stored value is set as mixed, we don't filter.
  421. * If type of stored value is defined, we compare with the one requested.
  422. */
  423. $knownType = $this->valueTypes[$app][$key] ?? 0;
  424. if (!$this->isTyped(self::VALUE_MIXED, $type)
  425. && $knownType > 0
  426. && !$this->isTyped(self::VALUE_MIXED, $knownType)
  427. && !$this->isTyped($type, $knownType)) {
  428. $this->logger->warning('conflict with value type from database', ['app' => $app, 'key' => $key, 'type' => $type, 'knownType' => $knownType]);
  429. throw new AppConfigTypeConflictException('conflict with value type from database');
  430. }
  431. /**
  432. * - the pair $app/$key cannot exist in both array,
  433. * - we should still return an existing non-lazy value even if current method
  434. * is called with $lazy is true
  435. *
  436. * This way, lazyCache will be empty until the load for lazy config value is requested.
  437. */
  438. if (isset($this->lazyCache[$app][$key])) {
  439. $value = $this->lazyCache[$app][$key];
  440. } elseif (isset($this->fastCache[$app][$key])) {
  441. $value = $this->fastCache[$app][$key];
  442. } else {
  443. return $default;
  444. }
  445. $sensitive = $this->isTyped(self::VALUE_SENSITIVE, $knownType);
  446. if ($sensitive && str_starts_with($value, self::ENCRYPTION_PREFIX)) {
  447. // Only decrypt values that are stored encrypted
  448. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  449. }
  450. return $value;
  451. }
  452. /**
  453. * @inheritDoc
  454. *
  455. * @param string $app id of the app
  456. * @param string $key config key
  457. *
  458. * @return int type of the value
  459. * @throws AppConfigUnknownKeyException if config key is not known
  460. * @since 29.0.0
  461. * @see VALUE_STRING
  462. * @see VALUE_INT
  463. * @see VALUE_FLOAT
  464. * @see VALUE_BOOL
  465. * @see VALUE_ARRAY
  466. */
  467. public function getValueType(string $app, string $key): int {
  468. $this->assertParams($app, $key);
  469. $this->loadConfigAll();
  470. if (!isset($this->valueTypes[$app][$key])) {
  471. throw new AppConfigUnknownKeyException('unknown config key');
  472. }
  473. $type = $this->valueTypes[$app][$key];
  474. $type &= ~self::VALUE_SENSITIVE;
  475. return $type;
  476. }
  477. /**
  478. * Store a config key and its value in database as VALUE_MIXED
  479. *
  480. * **WARNING:** Method is internal and **MUST** not be used as it is best to set a real value type
  481. *
  482. * @param string $app id of the app
  483. * @param string $key config key
  484. * @param string $value config value
  485. * @param bool $lazy set config as lazy loaded
  486. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  487. *
  488. * @return bool TRUE if value was different, therefor updated in database
  489. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED
  490. * @internal
  491. * @since 29.0.0
  492. * @see IAppConfig for explanation about lazy loading
  493. * @see setValueString()
  494. * @see setValueInt()
  495. * @see setValueFloat()
  496. * @see setValueBool()
  497. * @see setValueArray()
  498. */
  499. public function setValueMixed(
  500. string $app,
  501. string $key,
  502. string $value,
  503. bool $lazy = false,
  504. bool $sensitive = false
  505. ): bool {
  506. return $this->setTypedValue(
  507. $app,
  508. $key,
  509. $value,
  510. $lazy,
  511. self::VALUE_MIXED | ($sensitive ? self::VALUE_SENSITIVE : 0)
  512. );
  513. }
  514. /**
  515. * @inheritDoc
  516. *
  517. * @param string $app id of the app
  518. * @param string $key config key
  519. * @param string $value config value
  520. * @param bool $lazy set config as lazy loaded
  521. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  522. *
  523. * @return bool TRUE if value was different, therefor updated in database
  524. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  525. * @since 29.0.0
  526. * @see IAppConfig for explanation about lazy loading
  527. */
  528. public function setValueString(
  529. string $app,
  530. string $key,
  531. string $value,
  532. bool $lazy = false,
  533. bool $sensitive = false
  534. ): bool {
  535. return $this->setTypedValue(
  536. $app,
  537. $key,
  538. $value,
  539. $lazy,
  540. self::VALUE_STRING | ($sensitive ? self::VALUE_SENSITIVE : 0)
  541. );
  542. }
  543. /**
  544. * @inheritDoc
  545. *
  546. * @param string $app id of the app
  547. * @param string $key config key
  548. * @param int $value config value
  549. * @param bool $lazy set config as lazy loaded
  550. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  551. *
  552. * @return bool TRUE if value was different, therefor updated in database
  553. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  554. * @since 29.0.0
  555. * @see IAppConfig for explanation about lazy loading
  556. */
  557. public function setValueInt(
  558. string $app,
  559. string $key,
  560. int $value,
  561. bool $lazy = false,
  562. bool $sensitive = false
  563. ): bool {
  564. if ($value > 2000000000) {
  565. $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.');
  566. }
  567. return $this->setTypedValue(
  568. $app,
  569. $key,
  570. (string)$value,
  571. $lazy,
  572. self::VALUE_INT | ($sensitive ? self::VALUE_SENSITIVE : 0)
  573. );
  574. }
  575. /**
  576. * @inheritDoc
  577. *
  578. * @param string $app id of the app
  579. * @param string $key config key
  580. * @param float $value config value
  581. * @param bool $lazy set config as lazy loaded
  582. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  583. *
  584. * @return bool TRUE if value was different, therefor updated in database
  585. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  586. * @since 29.0.0
  587. * @see IAppConfig for explanation about lazy loading
  588. */
  589. public function setValueFloat(
  590. string $app,
  591. string $key,
  592. float $value,
  593. bool $lazy = false,
  594. bool $sensitive = false
  595. ): bool {
  596. return $this->setTypedValue(
  597. $app,
  598. $key,
  599. (string)$value,
  600. $lazy,
  601. self::VALUE_FLOAT | ($sensitive ? self::VALUE_SENSITIVE : 0)
  602. );
  603. }
  604. /**
  605. * @inheritDoc
  606. *
  607. * @param string $app id of the app
  608. * @param string $key config key
  609. * @param bool $value config value
  610. * @param bool $lazy set config as lazy loaded
  611. *
  612. * @return bool TRUE if value was different, therefor updated in database
  613. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  614. * @since 29.0.0
  615. * @see IAppConfig for explanation about lazy loading
  616. */
  617. public function setValueBool(
  618. string $app,
  619. string $key,
  620. bool $value,
  621. bool $lazy = false
  622. ): bool {
  623. return $this->setTypedValue(
  624. $app,
  625. $key,
  626. ($value) ? '1' : '0',
  627. $lazy,
  628. self::VALUE_BOOL
  629. );
  630. }
  631. /**
  632. * @inheritDoc
  633. *
  634. * @param string $app id of the app
  635. * @param string $key config key
  636. * @param array $value config value
  637. * @param bool $lazy set config as lazy loaded
  638. * @param bool $sensitive if TRUE value will be hidden when listing config values.
  639. *
  640. * @return bool TRUE if value was different, therefor updated in database
  641. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  642. * @throws JsonException
  643. * @since 29.0.0
  644. * @see IAppConfig for explanation about lazy loading
  645. */
  646. public function setValueArray(
  647. string $app,
  648. string $key,
  649. array $value,
  650. bool $lazy = false,
  651. bool $sensitive = false
  652. ): bool {
  653. try {
  654. return $this->setTypedValue(
  655. $app,
  656. $key,
  657. json_encode($value, JSON_THROW_ON_ERROR),
  658. $lazy,
  659. self::VALUE_ARRAY | ($sensitive ? self::VALUE_SENSITIVE : 0)
  660. );
  661. } catch (JsonException $e) {
  662. $this->logger->warning('could not setValueArray', ['app' => $app, 'key' => $key, 'exception' => $e]);
  663. throw $e;
  664. }
  665. }
  666. /**
  667. * Store a config key and its value in database
  668. *
  669. * If config key is already known with the exact same config value and same sensitive/lazy status, the
  670. * database is not updated. If config value was previously stored as sensitive, status will not be
  671. * altered.
  672. *
  673. * @param string $app id of the app
  674. * @param string $key config key
  675. * @param string $value config value
  676. * @param bool $lazy config set as lazy loaded
  677. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  678. *
  679. * @return bool TRUE if value was updated in database
  680. * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
  681. * @see IAppConfig for explanation about lazy loading
  682. */
  683. private function setTypedValue(
  684. string $app,
  685. string $key,
  686. string $value,
  687. bool $lazy,
  688. int $type
  689. ): bool {
  690. $this->assertParams($app, $key);
  691. $this->loadConfig($lazy);
  692. $sensitive = $this->isTyped(self::VALUE_SENSITIVE, $type);
  693. $inserted = $refreshCache = false;
  694. $origValue = $value;
  695. if ($sensitive || ($this->hasKey($app, $key, $lazy) && $this->isSensitive($app, $key, $lazy))) {
  696. $value = self::ENCRYPTION_PREFIX . $this->crypto->encrypt($value);
  697. }
  698. if ($this->hasKey($app, $key, $lazy)) {
  699. /**
  700. * no update if key is already known with set lazy status and value is
  701. * not different, unless sensitivity is switched from false to true.
  702. */
  703. if ($origValue === $this->getTypedValue($app, $key, $value, $lazy, $type)
  704. && (!$sensitive || $this->isSensitive($app, $key, $lazy))) {
  705. return false;
  706. }
  707. } else {
  708. /**
  709. * if key is not known yet, we try to insert.
  710. * It might fail if the key exists with a different lazy flag.
  711. */
  712. try {
  713. $insert = $this->connection->getQueryBuilder();
  714. $insert->insert('appconfig')
  715. ->setValue('appid', $insert->createNamedParameter($app))
  716. ->setValue('lazy', $insert->createNamedParameter(($lazy) ? 1 : 0, IQueryBuilder::PARAM_INT))
  717. ->setValue('type', $insert->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  718. ->setValue('configkey', $insert->createNamedParameter($key))
  719. ->setValue('configvalue', $insert->createNamedParameter($value));
  720. $insert->executeStatement();
  721. $inserted = true;
  722. } catch (DBException $e) {
  723. if ($e->getReason() !== DBException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  724. throw $e; // TODO: throw exception or just log and returns false !?
  725. }
  726. }
  727. }
  728. /**
  729. * We cannot insert a new row, meaning we need to update an already existing one
  730. */
  731. if (!$inserted) {
  732. $currType = $this->valueTypes[$app][$key] ?? 0;
  733. if ($currType === 0) { // this might happen when switching lazy loading status
  734. $this->loadConfigAll();
  735. $currType = $this->valueTypes[$app][$key] ?? 0;
  736. }
  737. /**
  738. * This should only happen during the upgrade process from 28 to 29.
  739. * We only log a warning and set it to VALUE_MIXED.
  740. */
  741. if ($currType === 0) {
  742. $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]);
  743. $currType = self::VALUE_MIXED;
  744. }
  745. /**
  746. * we only accept a different type from the one stored in database
  747. * if the one stored in database is not-defined (VALUE_MIXED)
  748. */
  749. if (!$this->isTyped(self::VALUE_MIXED, $currType) &&
  750. ($type | self::VALUE_SENSITIVE) !== ($currType | self::VALUE_SENSITIVE)) {
  751. try {
  752. $currType = $this->convertTypeToString($currType);
  753. $type = $this->convertTypeToString($type);
  754. } catch (AppConfigIncorrectTypeException) {
  755. // can be ignored, this was just needed for a better exception message.
  756. }
  757. throw new AppConfigTypeConflictException('conflict between new type (' . $type . ') and old type (' . $currType . ')');
  758. }
  759. // we fix $type if the stored value, or the new value as it might be changed, is set as sensitive
  760. if ($sensitive || $this->isTyped(self::VALUE_SENSITIVE, $currType)) {
  761. $type |= self::VALUE_SENSITIVE;
  762. }
  763. if ($lazy !== $this->isLazy($app, $key)) {
  764. $refreshCache = true;
  765. }
  766. $update = $this->connection->getQueryBuilder();
  767. $update->update('appconfig')
  768. ->set('configvalue', $update->createNamedParameter($value))
  769. ->set('lazy', $update->createNamedParameter(($lazy) ? 1 : 0, IQueryBuilder::PARAM_INT))
  770. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  771. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  772. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  773. $update->executeStatement();
  774. }
  775. if ($refreshCache) {
  776. $this->clearCache();
  777. return true;
  778. }
  779. // update local cache
  780. if ($lazy) {
  781. $cache = &$this->lazyCache;
  782. } else {
  783. $cache = &$this->fastCache;
  784. }
  785. $cache[$app][$key] = $value;
  786. $this->valueTypes[$app][$key] = $type;
  787. return true;
  788. }
  789. /**
  790. * Change the type of config value.
  791. *
  792. * **WARNING:** Method is internal and **MUST** not be used as it may break things.
  793. *
  794. * @param string $app id of the app
  795. * @param string $key config key
  796. * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
  797. *
  798. * @return bool TRUE if database update were necessary
  799. * @throws AppConfigUnknownKeyException if $key is now known in database
  800. * @throws AppConfigIncorrectTypeException if $type is not valid
  801. * @internal
  802. * @since 29.0.0
  803. */
  804. public function updateType(string $app, string $key, int $type = self::VALUE_MIXED): bool {
  805. $this->assertParams($app, $key);
  806. $this->loadConfigAll();
  807. $lazy = $this->isLazy($app, $key);
  808. // type can only be one type
  809. if (!in_array($type, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
  810. throw new AppConfigIncorrectTypeException('Unknown value type');
  811. }
  812. $currType = $this->valueTypes[$app][$key];
  813. if (($type | self::VALUE_SENSITIVE) === ($currType | self::VALUE_SENSITIVE)) {
  814. return false;
  815. }
  816. // we complete with sensitive flag if the stored value is set as sensitive
  817. if ($this->isTyped(self::VALUE_SENSITIVE, $currType)) {
  818. $type = $type | self::VALUE_SENSITIVE;
  819. }
  820. $update = $this->connection->getQueryBuilder();
  821. $update->update('appconfig')
  822. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  823. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  824. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  825. $update->executeStatement();
  826. $this->valueTypes[$app][$key] = $type;
  827. return true;
  828. }
  829. /**
  830. * @inheritDoc
  831. *
  832. * @param string $app id of the app
  833. * @param string $key config key
  834. * @param bool $sensitive TRUE to set as sensitive, FALSE to unset
  835. *
  836. * @return bool TRUE if entry was found in database and an update was necessary
  837. * @since 29.0.0
  838. */
  839. public function updateSensitive(string $app, string $key, bool $sensitive): bool {
  840. $this->assertParams($app, $key);
  841. $this->loadConfigAll();
  842. try {
  843. if ($sensitive === $this->isSensitive($app, $key, null)) {
  844. return false;
  845. }
  846. } catch (AppConfigUnknownKeyException $e) {
  847. return false;
  848. }
  849. $lazy = $this->isLazy($app, $key);
  850. if ($lazy) {
  851. $cache = $this->lazyCache;
  852. } else {
  853. $cache = $this->fastCache;
  854. }
  855. if (!isset($cache[$app][$key])) {
  856. throw new AppConfigUnknownKeyException('unknown config key');
  857. }
  858. /**
  859. * type returned by getValueType() is already cleaned from sensitive flag
  860. * we just need to update it based on $sensitive and store it in database
  861. */
  862. $type = $this->getValueType($app, $key);
  863. $value = $cache[$app][$key];
  864. if ($sensitive) {
  865. $type |= self::VALUE_SENSITIVE;
  866. $value = self::ENCRYPTION_PREFIX . $this->crypto->encrypt($value);
  867. } else {
  868. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  869. }
  870. $update = $this->connection->getQueryBuilder();
  871. $update->update('appconfig')
  872. ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
  873. ->set('configvalue', $update->createNamedParameter($value))
  874. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  875. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  876. $update->executeStatement();
  877. $this->valueTypes[$app][$key] = $type;
  878. return true;
  879. }
  880. /**
  881. * @inheritDoc
  882. *
  883. * @param string $app id of the app
  884. * @param string $key config key
  885. * @param bool $lazy TRUE to set as lazy loaded, FALSE to unset
  886. *
  887. * @return bool TRUE if entry was found in database and an update was necessary
  888. * @since 29.0.0
  889. */
  890. public function updateLazy(string $app, string $key, bool $lazy): bool {
  891. $this->assertParams($app, $key);
  892. $this->loadConfigAll();
  893. try {
  894. if ($lazy === $this->isLazy($app, $key)) {
  895. return false;
  896. }
  897. } catch (AppConfigUnknownKeyException $e) {
  898. return false;
  899. }
  900. $update = $this->connection->getQueryBuilder();
  901. $update->update('appconfig')
  902. ->set('lazy', $update->createNamedParameter($lazy ? 1 : 0, IQueryBuilder::PARAM_INT))
  903. ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
  904. ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
  905. $update->executeStatement();
  906. // At this point, it is a lot safer to clean cache
  907. $this->clearCache();
  908. return true;
  909. }
  910. /**
  911. * @inheritDoc
  912. *
  913. * @param string $app id of the app
  914. * @param string $key config key
  915. *
  916. * @return array
  917. * @throws AppConfigUnknownKeyException if config key is not known in database
  918. * @since 29.0.0
  919. */
  920. public function getDetails(string $app, string $key): array {
  921. $this->assertParams($app, $key);
  922. $this->loadConfigAll();
  923. $lazy = $this->isLazy($app, $key);
  924. if ($lazy) {
  925. $cache = $this->lazyCache;
  926. } else {
  927. $cache = $this->fastCache;
  928. }
  929. $type = $this->getValueType($app, $key);
  930. try {
  931. $typeString = $this->convertTypeToString($type);
  932. } catch (AppConfigIncorrectTypeException $e) {
  933. $this->logger->warning('type stored in database is not correct', ['exception' => $e, 'type' => $type]);
  934. $typeString = (string)$type;
  935. }
  936. if (!isset($cache[$app][$key])) {
  937. throw new AppConfigUnknownKeyException('unknown config key');
  938. }
  939. $value = $cache[$app][$key];
  940. $sensitive = $this->isSensitive($app, $key, null);
  941. if ($sensitive && str_starts_with($value, self::ENCRYPTION_PREFIX)) {
  942. $value = $this->crypto->decrypt(substr($value, self::ENCRYPTION_PREFIX_LENGTH));
  943. }
  944. return [
  945. 'app' => $app,
  946. 'key' => $key,
  947. 'value' => $value,
  948. 'type' => $type,
  949. 'lazy' => $lazy,
  950. 'typeString' => $typeString,
  951. 'sensitive' => $sensitive
  952. ];
  953. }
  954. /**
  955. * @param string $type
  956. *
  957. * @return int
  958. * @throws AppConfigIncorrectTypeException
  959. * @since 29.0.0
  960. */
  961. public function convertTypeToInt(string $type): int {
  962. return match (strtolower($type)) {
  963. 'mixed' => IAppConfig::VALUE_MIXED,
  964. 'string' => IAppConfig::VALUE_STRING,
  965. 'integer' => IAppConfig::VALUE_INT,
  966. 'float' => IAppConfig::VALUE_FLOAT,
  967. 'boolean' => IAppConfig::VALUE_BOOL,
  968. 'array' => IAppConfig::VALUE_ARRAY,
  969. default => throw new AppConfigIncorrectTypeException('Unknown type ' . $type)
  970. };
  971. }
  972. /**
  973. * @param int $type
  974. *
  975. * @return string
  976. * @throws AppConfigIncorrectTypeException
  977. * @since 29.0.0
  978. */
  979. public function convertTypeToString(int $type): string {
  980. $type &= ~self::VALUE_SENSITIVE;
  981. return match ($type) {
  982. IAppConfig::VALUE_MIXED => 'mixed',
  983. IAppConfig::VALUE_STRING => 'string',
  984. IAppConfig::VALUE_INT => 'integer',
  985. IAppConfig::VALUE_FLOAT => 'float',
  986. IAppConfig::VALUE_BOOL => 'boolean',
  987. IAppConfig::VALUE_ARRAY => 'array',
  988. default => throw new AppConfigIncorrectTypeException('Unknown numeric type ' . $type)
  989. };
  990. }
  991. /**
  992. * @inheritDoc
  993. *
  994. * @param string $app id of the app
  995. * @param string $key config key
  996. *
  997. * @since 29.0.0
  998. */
  999. public function deleteKey(string $app, string $key): void {
  1000. $this->assertParams($app, $key);
  1001. $qb = $this->connection->getQueryBuilder();
  1002. $qb->delete('appconfig')
  1003. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)))
  1004. ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
  1005. $qb->executeStatement();
  1006. unset($this->lazyCache[$app][$key]);
  1007. unset($this->fastCache[$app][$key]);
  1008. }
  1009. /**
  1010. * @inheritDoc
  1011. *
  1012. * @param string $app id of the app
  1013. *
  1014. * @since 29.0.0
  1015. */
  1016. public function deleteApp(string $app): void {
  1017. $this->assertParams($app);
  1018. $qb = $this->connection->getQueryBuilder();
  1019. $qb->delete('appconfig')
  1020. ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)));
  1021. $qb->executeStatement();
  1022. $this->clearCache();
  1023. }
  1024. /**
  1025. * @inheritDoc
  1026. *
  1027. * @param bool $reload set to TRUE to refill cache instantly after clearing it
  1028. *
  1029. * @since 29.0.0
  1030. */
  1031. public function clearCache(bool $reload = false): void {
  1032. $this->lazyLoaded = $this->fastLoaded = false;
  1033. $this->lazyCache = $this->fastCache = $this->valueTypes = [];
  1034. if (!$reload) {
  1035. return;
  1036. }
  1037. $this->loadConfigAll();
  1038. }
  1039. /**
  1040. * For debug purpose.
  1041. * Returns the cached data.
  1042. *
  1043. * @return array
  1044. * @since 29.0.0
  1045. * @internal
  1046. */
  1047. public function statusCache(): array {
  1048. return [
  1049. 'fastLoaded' => $this->fastLoaded,
  1050. 'fastCache' => $this->fastCache,
  1051. 'lazyLoaded' => $this->lazyLoaded,
  1052. 'lazyCache' => $this->lazyCache,
  1053. ];
  1054. }
  1055. /**
  1056. * @param int $needle bitflag to search
  1057. * @param int $type known value
  1058. *
  1059. * @return bool TRUE if bitflag $needle is set in $type
  1060. */
  1061. private function isTyped(int $needle, int $type): bool {
  1062. return (($needle & $type) !== 0);
  1063. }
  1064. /**
  1065. * Confirm the string set for app and key fit the database description
  1066. *
  1067. * @param string $app assert $app fit in database
  1068. * @param string $configKey assert config key fit in database
  1069. * @param bool $allowEmptyApp $app can be empty string
  1070. * @param int $valueType assert value type is only one type
  1071. *
  1072. * @throws InvalidArgumentException
  1073. */
  1074. private function assertParams(string $app = '', string $configKey = '', bool $allowEmptyApp = false, int $valueType = -1): void {
  1075. if (!$allowEmptyApp && $app === '') {
  1076. throw new InvalidArgumentException('app cannot be an empty string');
  1077. }
  1078. if (strlen($app) > self::APP_MAX_LENGTH) {
  1079. throw new InvalidArgumentException(
  1080. 'Value (' . $app . ') for app is too long (' . self::APP_MAX_LENGTH . ')'
  1081. );
  1082. }
  1083. if (strlen($configKey) > self::KEY_MAX_LENGTH) {
  1084. throw new InvalidArgumentException('Value (' . $configKey . ') for key is too long (' . self::KEY_MAX_LENGTH . ')');
  1085. }
  1086. if ($valueType > -1) {
  1087. $valueType &= ~self::VALUE_SENSITIVE;
  1088. if (!in_array($valueType, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
  1089. throw new InvalidArgumentException('Unknown value type');
  1090. }
  1091. }
  1092. }
  1093. private function loadConfigAll(): void {
  1094. $this->loadConfig(null);
  1095. }
  1096. /**
  1097. * Load normal config or config set as lazy loaded
  1098. *
  1099. * @param bool|null $lazy set to TRUE to load config set as lazy loaded, set to NULL to load all config
  1100. */
  1101. private function loadConfig(?bool $lazy = false): void {
  1102. if ($this->isLoaded($lazy)) {
  1103. return;
  1104. }
  1105. if (($lazy ?? true) !== false) { // if lazy is null or true, we debug log
  1106. $this->logger->debug('The loading of lazy AppConfig values have been requested', ['exception' => new \RuntimeException('ignorable exception')]);
  1107. }
  1108. $qb = $this->connection->getQueryBuilder();
  1109. $qb->from('appconfig');
  1110. /**
  1111. * The use of $this->>migrationCompleted is only needed to manage the
  1112. * database during the upgrading process to nc29.
  1113. */
  1114. if (!$this->migrationCompleted) {
  1115. $qb->select('appid', 'configkey', 'configvalue');
  1116. } else {
  1117. // we only need value from lazy when loadConfig does not specify it
  1118. $qb->select('appid', 'configkey', 'configvalue', 'type');
  1119. if ($lazy !== null) {
  1120. $qb->where($qb->expr()->eq('lazy', $qb->createNamedParameter($lazy ? 1 : 0, IQueryBuilder::PARAM_INT)));
  1121. } else {
  1122. $qb->addSelect('lazy');
  1123. }
  1124. }
  1125. try {
  1126. $result = $qb->executeQuery();
  1127. } catch (DBException $e) {
  1128. /**
  1129. * in case of issue with field name, it means that migration is not completed.
  1130. * Falling back to a request without select on lazy.
  1131. * This whole try/catch and the migrationCompleted variable can be removed in NC30.
  1132. */
  1133. if ($e->getReason() !== DBException::REASON_INVALID_FIELD_NAME) {
  1134. throw $e;
  1135. }
  1136. $this->migrationCompleted = false;
  1137. $this->loadConfig($lazy);
  1138. return;
  1139. }
  1140. $rows = $result->fetchAll();
  1141. foreach ($rows as $row) {
  1142. // most of the time, 'lazy' is not in the select because its value is already known
  1143. if (($row['lazy'] ?? ($lazy ?? 0) ? 1 : 0) === 1) {
  1144. $cache = &$this->lazyCache;
  1145. } else {
  1146. $cache = &$this->fastCache;
  1147. }
  1148. $cache[$row['appid']][$row['configkey']] = $row['configvalue'] ?? '';
  1149. $this->valueTypes[$row['appid']][$row['configkey']] = (int)($row['type'] ?? 0);
  1150. }
  1151. $result->closeCursor();
  1152. $this->setAsLoaded($lazy);
  1153. }
  1154. /**
  1155. * if $lazy is:
  1156. * - false: will returns true if fast config is loaded
  1157. * - true : will returns true if lazy config is loaded
  1158. * - null : will returns true if both config are loaded
  1159. *
  1160. * @param bool $lazy
  1161. *
  1162. * @return bool
  1163. */
  1164. private function isLoaded(?bool $lazy): bool {
  1165. if ($lazy === null) {
  1166. return $this->lazyLoaded && $this->fastLoaded;
  1167. }
  1168. return $lazy ? $this->lazyLoaded : $this->fastLoaded;
  1169. }
  1170. /**
  1171. * if $lazy is:
  1172. * - false: set fast config as loaded
  1173. * - true : set lazy config as loaded
  1174. * - null : set both config as loaded
  1175. *
  1176. * @param bool $lazy
  1177. */
  1178. private function setAsLoaded(?bool $lazy): void {
  1179. if ($lazy === null) {
  1180. $this->fastLoaded = true;
  1181. $this->lazyLoaded = true;
  1182. return;
  1183. }
  1184. if ($lazy) {
  1185. $this->lazyLoaded = true;
  1186. } else {
  1187. $this->fastLoaded = true;
  1188. }
  1189. }
  1190. /**
  1191. * Gets the config value
  1192. *
  1193. * @param string $app app
  1194. * @param string $key key
  1195. * @param string $default = null, default value if the key does not exist
  1196. *
  1197. * @return string the value or $default
  1198. * @deprecated - use getValue*()
  1199. *
  1200. * This function gets a value from the appconfig table. If the key does
  1201. * not exist the default value will be returned
  1202. */
  1203. public function getValue($app, $key, $default = null) {
  1204. $this->loadConfig();
  1205. return $this->fastCache[$app][$key] ?? $default;
  1206. }
  1207. /**
  1208. * Sets a value. If the key did not exist before it will be created.
  1209. *
  1210. * @param string $app app
  1211. * @param string $key key
  1212. * @param string|float|int $value value
  1213. *
  1214. * @return bool True if the value was inserted or updated, false if the value was the same
  1215. * @throws AppConfigTypeConflictException
  1216. * @throws AppConfigUnknownKeyException
  1217. * @deprecated
  1218. */
  1219. public function setValue($app, $key, $value) {
  1220. /**
  1221. * TODO: would it be overkill, or decently improve performance, to catch
  1222. * call to this method with $key='enabled' and 'hide' config value related
  1223. * to $app when the app is disabled (by modifying entry in database: lazy=lazy+2)
  1224. * or enabled (lazy=lazy-2)
  1225. *
  1226. * this solution would remove the loading of config values from disabled app
  1227. * unless calling the method {@see loadConfigAll()}
  1228. */
  1229. return $this->setTypedValue($app, $key, (string)$value, false, self::VALUE_MIXED);
  1230. }
  1231. /**
  1232. * get multiple values, either the app or key can be used as wildcard by setting it to false
  1233. *
  1234. * @param string|false $app
  1235. * @param string|false $key
  1236. *
  1237. * @return array|false
  1238. * @deprecated 29.0.0 use {@see getAllValues()}
  1239. */
  1240. public function getValues($app, $key) {
  1241. if (($app !== false) === ($key !== false)) {
  1242. return false;
  1243. }
  1244. $key = ($key === false) ? '' : $key;
  1245. if (!$app) {
  1246. return $this->searchValues($key);
  1247. } else {
  1248. return $this->getAllValues($app, $key);
  1249. }
  1250. }
  1251. /**
  1252. * get all values of the app or and filters out sensitive data
  1253. *
  1254. * @param string $app
  1255. *
  1256. * @return array
  1257. * @deprecated 29.0.0 use {@see getAllValues()}
  1258. */
  1259. public function getFilteredValues($app) {
  1260. return $this->getAllValues($app, filtered: true);
  1261. }
  1262. /**
  1263. * @param string $app
  1264. *
  1265. * @return string[]
  1266. * @deprecated data sensitivity should be set when calling setValue*()
  1267. */
  1268. private function getSensitiveKeys(string $app): array {
  1269. $sensitiveValues = [
  1270. 'circles' => [
  1271. '/^key_pairs$/',
  1272. '/^local_gskey$/',
  1273. ],
  1274. 'external' => [
  1275. '/^sites$/',
  1276. ],
  1277. 'integration_discourse' => [
  1278. '/^private_key$/',
  1279. '/^public_key$/',
  1280. ],
  1281. 'integration_dropbox' => [
  1282. '/^client_id$/',
  1283. '/^client_secret$/',
  1284. ],
  1285. 'integration_github' => [
  1286. '/^client_id$/',
  1287. '/^client_secret$/',
  1288. ],
  1289. 'integration_gitlab' => [
  1290. '/^client_id$/',
  1291. '/^client_secret$/',
  1292. '/^oauth_instance_url$/',
  1293. ],
  1294. 'integration_google' => [
  1295. '/^client_id$/',
  1296. '/^client_secret$/',
  1297. ],
  1298. 'integration_jira' => [
  1299. '/^client_id$/',
  1300. '/^client_secret$/',
  1301. '/^forced_instance_url$/',
  1302. ],
  1303. 'integration_onedrive' => [
  1304. '/^client_id$/',
  1305. '/^client_secret$/',
  1306. ],
  1307. 'integration_openproject' => [
  1308. '/^client_id$/',
  1309. '/^client_secret$/',
  1310. '/^oauth_instance_url$/',
  1311. ],
  1312. 'integration_reddit' => [
  1313. '/^client_id$/',
  1314. '/^client_secret$/',
  1315. ],
  1316. 'integration_suitecrm' => [
  1317. '/^client_id$/',
  1318. '/^client_secret$/',
  1319. '/^oauth_instance_url$/',
  1320. ],
  1321. 'integration_twitter' => [
  1322. '/^consumer_key$/',
  1323. '/^consumer_secret$/',
  1324. '/^followed_user$/',
  1325. ],
  1326. 'integration_zammad' => [
  1327. '/^client_id$/',
  1328. '/^client_secret$/',
  1329. '/^oauth_instance_url$/',
  1330. ],
  1331. 'notify_push' => [
  1332. '/^cookie$/',
  1333. ],
  1334. 'serverinfo' => [
  1335. '/^token$/',
  1336. ],
  1337. 'spreed' => [
  1338. '/^bridge_bot_password$/',
  1339. '/^hosted-signaling-server-(.*)$/',
  1340. '/^recording_servers$/',
  1341. '/^signaling_servers$/',
  1342. '/^signaling_ticket_secret$/',
  1343. '/^signaling_token_privkey_(.*)$/',
  1344. '/^signaling_token_pubkey_(.*)$/',
  1345. '/^sip_bridge_dialin_info$/',
  1346. '/^sip_bridge_shared_secret$/',
  1347. '/^stun_servers$/',
  1348. '/^turn_servers$/',
  1349. '/^turn_server_secret$/',
  1350. ],
  1351. 'support' => [
  1352. '/^last_response$/',
  1353. '/^potential_subscription_key$/',
  1354. '/^subscription_key$/',
  1355. ],
  1356. 'theming' => [
  1357. '/^imprintUrl$/',
  1358. '/^privacyUrl$/',
  1359. '/^slogan$/',
  1360. '/^url$/',
  1361. ],
  1362. 'user_ldap' => [
  1363. '/^(s..)?ldap_agent_password$/',
  1364. ],
  1365. 'user_saml' => [
  1366. '/^idp-x509cert$/',
  1367. ],
  1368. ];
  1369. return $sensitiveValues[$app] ?? [];
  1370. }
  1371. /**
  1372. * Clear all the cached app config values
  1373. * New cache will be generated next time a config value is retrieved
  1374. *
  1375. * @deprecated use {@see clearCache()}
  1376. */
  1377. public function clearCachedConfig(): void {
  1378. $this->clearCache();
  1379. }
  1380. }