AppConfig.php 45 KB

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