123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443 |
- <?php
- declare(strict_types=1);
- /**
- * @copyright Copyright (c) 2017, Joas Schilling <coding@schilljs.com>
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bart Visscher <bartv@thisnet.nl>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Jakob Sack <mail@jakobsack.de>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Maxence Lange <maxence@artificial-owl.com>
- * @author michaelletzgus <michaelletzgus@users.noreply.github.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Robin McCorkell <robin@mccorkell.me.uk>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
- */
- namespace OC;
- use InvalidArgumentException;
- use JsonException;
- use OCP\DB\Exception as DBException;
- use OCP\DB\QueryBuilder\IQueryBuilder;
- use OCP\Exceptions\AppConfigIncorrectTypeException;
- use OCP\Exceptions\AppConfigTypeConflictException;
- use OCP\Exceptions\AppConfigUnknownKeyException;
- use OCP\IAppConfig;
- use OCP\IConfig;
- use OCP\IDBConnection;
- use Psr\Log\LoggerInterface;
- /**
- * This class provides an easy way for apps to store config values in the
- * database.
- *
- * **Note:** since 29.0.0, it supports **lazy loading**
- *
- * ### What is lazy loading ?
- * In order to avoid loading useless config values into memory for each request,
- * only non-lazy values are now loaded.
- *
- * Once a value that is lazy is requested, all lazy values will be loaded.
- *
- * Similarly, some methods from this class are marked with a warning about ignoring
- * lazy loading. Use them wisely and only on parts of the code that are called
- * during specific requests or actions to avoid loading the lazy values all the time.
- *
- * @since 7.0.0
- * @since 29.0.0 - Supporting types and lazy loading
- */
- class AppConfig implements IAppConfig {
- private const APP_MAX_LENGTH = 32;
- private const KEY_MAX_LENGTH = 64;
- /** @var array<string, array<string, mixed>> ['app_id' => ['config_key' => 'config_value']] */
- private array $fastCache = []; // cache for normal config keys
- /** @var array<string, array<string, mixed>> ['app_id' => ['config_key' => 'config_value']] */
- private array $lazyCache = []; // cache for lazy config keys
- /** @var array<string, array<string, int>> ['app_id' => ['config_key' => bitflag]] */
- private array $valueTypes = []; // type for all config values
- private bool $fastLoaded = false;
- private bool $lazyLoaded = false;
- /**
- * $migrationCompleted is only needed to manage the previous structure
- * of the database during the upgrading process to nc29.
- * @TODO: remove this value in Nextcloud 30+
- */
- private bool $migrationCompleted = true;
- public function __construct(
- protected IDBConnection $connection,
- private LoggerInterface $logger,
- ) {
- }
- /**
- * @inheritDoc
- *
- * @return string[] list of app ids
- * @since 7.0.0
- */
- public function getApps(): array {
- $this->loadConfigAll();
- $apps = array_merge(array_keys($this->fastCache), array_keys($this->lazyCache));
- sort($apps);
- return array_values(array_unique($apps));
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- *
- * @return string[] list of stored config keys
- * @since 29.0.0
- */
- public function getKeys(string $app): array {
- $this->assertParams($app);
- $this->loadConfigAll();
- $keys = array_merge(array_keys($this->fastCache[$app] ?? []), array_keys($this->lazyCache[$app] ?? []));
- sort($keys);
- return array_values(array_unique($keys));
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
- *
- * @return bool TRUE if key exists
- * @since 7.0.0
- * @since 29.0.0 Added the $lazy argument
- */
- public function hasKey(string $app, string $key, ?bool $lazy = false): bool {
- $this->assertParams($app, $key);
- $this->loadConfig($lazy);
- if ($lazy === null) {
- $appCache = $this->getAllValues($app);
- return isset($appCache[$key]);
- }
- if ($lazy) {
- return isset($this->lazyCache[$app][$key]);
- }
- return isset($this->fastCache[$app][$key]);
- }
- /**
- * @param string $app id of the app
- * @param string $key config key
- * @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
- *
- * @return bool
- * @throws AppConfigUnknownKeyException if config key is not known
- * @since 29.0.0
- */
- public function isSensitive(string $app, string $key, ?bool $lazy = false): bool {
- $this->assertParams($app, $key);
- $this->loadConfig($lazy);
- if (!isset($this->valueTypes[$app][$key])) {
- throw new AppConfigUnknownKeyException('unknown config key');
- }
- return $this->isTyped(self::VALUE_SENSITIVE, $this->valueTypes[$app][$key]);
- }
- /**
- * @inheritDoc
- *
- * @param string $app if of the app
- * @param string $key config key
- *
- * @return bool TRUE if config is lazy loaded
- * @throws AppConfigUnknownKeyException if config key is not known
- * @see IAppConfig for details about lazy loading
- * @since 29.0.0
- */
- public function isLazy(string $app, string $key): bool {
- // there is a huge probability the non-lazy config are already loaded
- if ($this->hasKey($app, $key, false)) {
- return false;
- }
- // key not found, we search in the lazy config
- if ($this->hasKey($app, $key, true)) {
- return true;
- }
- throw new AppConfigUnknownKeyException('unknown config key');
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config keys prefix to search
- * @param bool $filtered TRUE to hide sensitive config values. Value are replaced by {@see IConfig::SENSITIVE_VALUE}
- *
- * @return array<string, string> [configKey => configValue]
- * @since 29.0.0
- */
- public function getAllValues(string $app, string $key = '', bool $filtered = false): array {
- $this->assertParams($app, $key);
- // if we want to filter values, we need to get sensitivity
- $this->loadConfigAll();
- // array_merge() will remove numeric keys (here config keys), so addition arrays instead
- $values = ($this->fastCache[$app] ?? []) + ($this->lazyCache[$app] ?? []);
- if (!$filtered) {
- return $values;
- }
- /**
- * Using the old (deprecated) list of sensitive values.
- */
- foreach ($this->getSensitiveKeys($app) as $sensitiveKeyExp) {
- $sensitiveKeys = preg_grep($sensitiveKeyExp, array_keys($values));
- foreach ($sensitiveKeys as $sensitiveKey) {
- $this->valueTypes[$app][$sensitiveKey] = ($this->valueTypes[$app][$sensitiveKey] ?? 0) | self::VALUE_SENSITIVE;
- }
- }
- $result = [];
- foreach ($values as $key => $value) {
- $result[$key] = $this->isTyped(self::VALUE_SENSITIVE, $this->valueTypes[$app][$key] ?? 0) ? IConfig::SENSITIVE_VALUE : $value;
- }
- return $result;
- }
- /**
- * @inheritDoc
- *
- * @param string $key config key
- * @param bool $lazy search within lazy loaded config
- *
- * @return array<string, string> [appId => configValue]
- * @since 29.0.0
- */
- public function searchValues(string $key, bool $lazy = false): array {
- $this->assertParams('', $key, true);
- $this->loadConfig($lazy);
- $values = [];
- /** @var array<array-key, array<array-key, mixed>> $cache */
- if ($lazy) {
- $cache = $this->lazyCache;
- } else {
- $cache = $this->fastCache;
- }
- foreach (array_keys($cache) as $app) {
- if (isset($cache[$app][$key])) {
- $values[$app] = $cache[$app][$key];
- }
- }
- return $values;
- }
- /**
- * Get the config value as string.
- * If the value does not exist the given default will be returned.
- *
- * Set lazy to `null` to ignore it and get the value from either source.
- *
- * **WARNING:** Method is internal and **SHOULD** not be used, as it is better to get the value with a type.
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param string $default config value
- * @param null|bool $lazy get config as lazy loaded or not. can be NULL
- *
- * @return string the value or $default
- * @internal
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- * @see getValueString()
- * @see getValueInt()
- * @see getValueFloat()
- * @see getValueBool()
- * @see getValueArray()
- */
- public function getValueMixed(
- string $app,
- string $key,
- string $default = '',
- ?bool $lazy = false
- ): string {
- try {
- $lazy = ($lazy === null) ? $this->isLazy($app, $key) : $lazy;
- } catch (AppConfigUnknownKeyException $e) {
- return $default;
- }
- return $this->getTypedValue(
- $app,
- $key,
- $default,
- $lazy,
- self::VALUE_MIXED
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param string $default default value
- * @param bool $lazy search within lazy loaded config
- *
- * @return string stored config value or $default if not set in database
- * @throws InvalidArgumentException if one of the argument format is invalid
- * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function getValueString(
- string $app,
- string $key,
- string $default = '',
- bool $lazy = false
- ): string {
- return $this->getTypedValue($app, $key, $default, $lazy, self::VALUE_STRING);
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param int $default default value
- * @param bool $lazy search within lazy loaded config
- *
- * @return int stored config value or $default if not set in database
- * @throws InvalidArgumentException if one of the argument format is invalid
- * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function getValueInt(
- string $app,
- string $key,
- int $default = 0,
- bool $lazy = false
- ): int {
- return (int)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_INT);
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param float $default default value
- * @param bool $lazy search within lazy loaded config
- *
- * @return float stored config value or $default if not set in database
- * @throws InvalidArgumentException if one of the argument format is invalid
- * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function getValueFloat(string $app, string $key, float $default = 0, bool $lazy = false): float {
- return (float)$this->getTypedValue($app, $key, (string)$default, $lazy, self::VALUE_FLOAT);
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param bool $default default value
- * @param bool $lazy search within lazy loaded config
- *
- * @return bool stored config value or $default if not set in database
- * @throws InvalidArgumentException if one of the argument format is invalid
- * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function getValueBool(string $app, string $key, bool $default = false, bool $lazy = false): bool {
- $b = strtolower($this->getTypedValue($app, $key, $default ? 'true' : 'false', $lazy, self::VALUE_BOOL));
- return in_array($b, ['1', 'true', 'yes', 'on']);
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param array $default default value
- * @param bool $lazy search within lazy loaded config
- *
- * @return array stored config value or $default if not set in database
- * @throws InvalidArgumentException if one of the argument format is invalid
- * @throws AppConfigTypeConflictException in case of conflict with the value type set in database
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function getValueArray(
- string $app,
- string $key,
- array $default = [],
- bool $lazy = false
- ): array {
- try {
- $defaultJson = json_encode($default, JSON_THROW_ON_ERROR);
- $value = json_decode($this->getTypedValue($app, $key, $defaultJson, $lazy, self::VALUE_ARRAY), true, flags: JSON_THROW_ON_ERROR);
- return is_array($value) ? $value : [];
- } catch (JsonException) {
- return [];
- }
- }
- /**
- * @param string $app id of the app
- * @param string $key config key
- * @param string $default default value
- * @param bool $lazy search within lazy loaded config
- * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT}{@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
- *
- * @return string
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @throws InvalidArgumentException
- */
- private function getTypedValue(
- string $app,
- string $key,
- string $default,
- bool $lazy,
- int $type
- ): string {
- $this->assertParams($app, $key, valueType: $type);
- $this->loadConfig($lazy);
- /**
- * We ignore check if mixed type is requested.
- * If type of stored value is set as mixed, we don't filter.
- * If type of stored value is defined, we compare with the one requested.
- */
- $knownType = $this->valueTypes[$app][$key] ?? 0;
- if (!$this->isTyped(self::VALUE_MIXED, $type)
- && $knownType > 0
- && !$this->isTyped(self::VALUE_MIXED, $knownType)
- && !$this->isTyped($type, $knownType)) {
- $this->logger->warning('conflict with value type from database', ['app' => $app, 'key' => $key, 'type' => $type, 'knownType' => $knownType]);
- throw new AppConfigTypeConflictException('conflict with value type from database');
- }
- if ($lazy) {
- return $this->lazyCache[$app][$key] ?? $default;
- }
- return $this->fastCache[$app][$key] ?? $default;
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- *
- * @return int type of the value
- * @throws AppConfigUnknownKeyException if config key is not known
- * @since 29.0.0
- * @see VALUE_STRING
- * @see VALUE_INT
- * @see VALUE_FLOAT
- * @see VALUE_BOOL
- * @see VALUE_ARRAY
- */
- public function getValueType(string $app, string $key): int {
- $this->assertParams($app, $key);
- $this->loadConfigAll();
- if (!isset($this->valueTypes[$app][$key])) {
- throw new AppConfigUnknownKeyException('unknown config key');
- }
- $type = $this->valueTypes[$app][$key];
- $type &= ~self::VALUE_SENSITIVE;
- return $type;
- }
- /**
- * Store a config key and its value in database as VALUE_MIXED
- *
- * **WARNING:** Method is internal and **MUST** not be used as it is best to set a real value type
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param string $value config value
- * @param bool $lazy set config as lazy loaded
- * @param bool $sensitive if TRUE value will be hidden when listing config values.
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED
- * @internal
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- * @see setValueString()
- * @see setValueInt()
- * @see setValueFloat()
- * @see setValueBool()
- * @see setValueArray()
- */
- public function setValueMixed(
- string $app,
- string $key,
- string $value,
- bool $lazy = false,
- bool $sensitive = false
- ): bool {
- return $this->setTypedValue(
- $app,
- $key,
- $value,
- $lazy,
- self::VALUE_MIXED | ($sensitive ? self::VALUE_SENSITIVE : 0)
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param string $value config value
- * @param bool $lazy set config as lazy loaded
- * @param bool $sensitive if TRUE value will be hidden when listing config values.
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function setValueString(
- string $app,
- string $key,
- string $value,
- bool $lazy = false,
- bool $sensitive = false
- ): bool {
- return $this->setTypedValue(
- $app,
- $key,
- $value,
- $lazy,
- self::VALUE_STRING | ($sensitive ? self::VALUE_SENSITIVE : 0)
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param int $value config value
- * @param bool $lazy set config as lazy loaded
- * @param bool $sensitive if TRUE value will be hidden when listing config values.
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function setValueInt(
- string $app,
- string $key,
- int $value,
- bool $lazy = false,
- bool $sensitive = false
- ): bool {
- if ($value > 2000000000) {
- $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.');
- }
- return $this->setTypedValue(
- $app,
- $key,
- (string)$value,
- $lazy,
- self::VALUE_INT | ($sensitive ? self::VALUE_SENSITIVE : 0)
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param float $value config value
- * @param bool $lazy set config as lazy loaded
- * @param bool $sensitive if TRUE value will be hidden when listing config values.
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function setValueFloat(
- string $app,
- string $key,
- float $value,
- bool $lazy = false,
- bool $sensitive = false
- ): bool {
- return $this->setTypedValue(
- $app,
- $key,
- (string)$value,
- $lazy,
- self::VALUE_FLOAT | ($sensitive ? self::VALUE_SENSITIVE : 0)
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param bool $value config value
- * @param bool $lazy set config as lazy loaded
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function setValueBool(
- string $app,
- string $key,
- bool $value,
- bool $lazy = false
- ): bool {
- return $this->setTypedValue(
- $app,
- $key,
- ($value) ? '1' : '0',
- $lazy,
- self::VALUE_BOOL
- );
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param array $value config value
- * @param bool $lazy set config as lazy loaded
- * @param bool $sensitive if TRUE value will be hidden when listing config values.
- *
- * @return bool TRUE if value was different, therefor updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @throws JsonException
- * @since 29.0.0
- * @see IAppConfig for explanation about lazy loading
- */
- public function setValueArray(
- string $app,
- string $key,
- array $value,
- bool $lazy = false,
- bool $sensitive = false
- ): bool {
- try {
- return $this->setTypedValue(
- $app,
- $key,
- json_encode($value, JSON_THROW_ON_ERROR),
- $lazy,
- self::VALUE_ARRAY | ($sensitive ? self::VALUE_SENSITIVE : 0)
- );
- } catch (JsonException $e) {
- $this->logger->warning('could not setValueArray', ['app' => $app, 'key' => $key, 'exception' => $e]);
- throw $e;
- }
- }
- /**
- * Store a config key and its value in database
- *
- * If config key is already known with the exact same config value and same sensitive/lazy status, the
- * database is not updated. If config value was previously stored as sensitive, status will not be
- * altered.
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param string $value config value
- * @param bool $lazy config set as lazy loaded
- * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
- *
- * @return bool TRUE if value was updated in database
- * @throws AppConfigTypeConflictException if type from database is not VALUE_MIXED and different from the requested one
- * @see IAppConfig for explanation about lazy loading
- */
- private function setTypedValue(
- string $app,
- string $key,
- string $value,
- bool $lazy,
- int $type
- ): bool {
- $this->assertParams($app, $key);
- $this->loadConfig($lazy);
- $sensitive = $this->isTyped(self::VALUE_SENSITIVE, $type);
- /*
- * no update if key is already known with set lazy status, or value is
- * different, or sensitivity switched from false to true.
- */
- if ($this->hasKey($app, $key, $lazy)
- && $value === $this->getTypedValue($app, $key, $value, $lazy, $type)
- && (!$sensitive || $this->isSensitive($app, $key, $lazy))) {
- return false;
- }
- $refreshCache = false;
- $insert = $this->connection->getQueryBuilder();
- $insert->insert('appconfig')
- ->setValue('appid', $insert->createNamedParameter($app))
- ->setValue('lazy', $insert->createNamedParameter($lazy, IQueryBuilder::PARAM_BOOL))
- ->setValue('type', $insert->createNamedParameter($type, IQueryBuilder::PARAM_INT))
- ->setValue('configkey', $insert->createNamedParameter($key))
- ->setValue('configvalue', $insert->createNamedParameter($value));
- try {
- $insert->executeStatement();
- } catch (DBException $e) {
- if ($e->getReason() !== DBException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
- throw $e; // TODO: throw exception or just log and returns false !?
- }
- $currType = $this->valueTypes[$app][$key] ?? 0;
- if ($currType === 0) { // this might happen when switching lazy loading status
- $this->loadConfigAll();
- $currType = $this->valueTypes[$app][$key] ?? 0;
- }
- /**
- * This should only happen during the upgrade process from 28 to 29.
- * We only log a warning and set it to VALUE_MIXED.
- */
- if ($currType === 0) {
- $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]);
- $currType = self::VALUE_MIXED;
- }
- /**
- * we only accept a different type from the one stored in database
- * if the one stored in database is not-defined (VALUE_MIXED)
- */
- if (!$this->isTyped(self::VALUE_MIXED, $currType) &&
- ($type | self::VALUE_SENSITIVE) !== ($currType | self::VALUE_SENSITIVE)) {
- try {
- $currType = $this->convertTypeToString($currType);
- $type = $this->convertTypeToString($type);
- } catch (AppConfigIncorrectTypeException) {
- // can be ignored, this was just needed for a better exception message.
- }
- throw new AppConfigTypeConflictException('conflict between new type (' . $type . ') and old type (' . $currType . ')');
- }
- // we fix $type if the stored value, or the new value as it might be changed, is set as sensitive
- if ($sensitive || $this->isTyped(self::VALUE_SENSITIVE, $currType)) {
- $type = $type | self::VALUE_SENSITIVE;
- }
- if ($lazy !== $this->isLazy($app, $key)) {
- $refreshCache = true;
- }
- $update = $this->connection->getQueryBuilder();
- $update->update('appconfig')
- ->set('configvalue', $update->createNamedParameter($value))
- ->set('lazy', $update->createNamedParameter($lazy, IQueryBuilder::PARAM_BOOL))
- ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
- ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
- ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
- $update->executeStatement();
- }
- if ($refreshCache) {
- $this->clearCache();
- return true;
- }
- // update local cache
- if ($lazy) {
- $cache = &$this->lazyCache;
- } else {
- $cache = &$this->fastCache;
- }
- $cache[$app][$key] = $value;
- $this->valueTypes[$app][$key] = $type;
- return true;
- }
- /**
- * Change the type of config value.
- *
- * **WARNING:** Method is internal and **MUST** not be used as it may break things.
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param int $type value type {@see VALUE_STRING} {@see VALUE_INT} {@see VALUE_FLOAT} {@see VALUE_BOOL} {@see VALUE_ARRAY}
- *
- * @return bool TRUE if database update were necessary
- * @throws AppConfigUnknownKeyException if $key is now known in database
- * @throws AppConfigIncorrectTypeException if $type is not valid
- * @internal
- * @since 29.0.0
- */
- public function updateType(string $app, string $key, int $type = self::VALUE_MIXED): bool {
- $this->assertParams($app, $key);
- $this->loadConfigAll();
- $lazy = $this->isLazy($app, $key);
- if (!$this->hasKey($app, $key, $lazy)) {
- throw new AppConfigUnknownKeyException('Unknown config key');
- }
- // type can only be one type
- if (!in_array($type, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
- throw new AppConfigIncorrectTypeException('Unknown value type');
- }
- $currType = $this->valueTypes[$app][$key];
- if (($type | self::VALUE_SENSITIVE) === ($currType | self::VALUE_SENSITIVE)) {
- return false;
- }
- // we complete with sensitive flag if the stored value is set as sensitive
- if ($this->isTyped(self::VALUE_SENSITIVE, $currType)) {
- $type = $type | self::VALUE_SENSITIVE;
- }
- $update = $this->connection->getQueryBuilder();
- $update->update('appconfig')
- ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
- ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
- ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
- $update->executeStatement();
- $this->valueTypes[$app][$key] = $type;
- return true;
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param bool $sensitive TRUE to set as sensitive, FALSE to unset
- *
- * @return bool TRUE if database update were necessary
- * @throws AppConfigUnknownKeyException if config key is not known
- * @since 29.0.0
- */
- public function updateSensitive(string $app, string $key, bool $sensitive): bool {
- $this->assertParams($app, $key);
- $this->loadConfigAll();
- if ($sensitive === $this->isSensitive($app, $key, null)) {
- return false;
- }
- /**
- * type returned by getValueType() is already cleaned from sensitive flag
- * we just need to update it based on $sensitive and store it in database
- */
- $type = $this->getValueType($app, $key);
- if ($sensitive) {
- $type = $type | self::VALUE_SENSITIVE;
- }
- $update = $this->connection->getQueryBuilder();
- $update->update('appconfig')
- ->set('type', $update->createNamedParameter($type, IQueryBuilder::PARAM_INT))
- ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
- ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
- $update->executeStatement();
- $this->valueTypes[$app][$key] = $type;
- return true;
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- * @param bool $lazy TRUE to set as lazy loaded, FALSE to unset
- *
- * @return bool TRUE if database update was necessary
- * @throws AppConfigUnknownKeyException if config key is not known
- * @since 29.0.0
- */
- public function updateLazy(string $app, string $key, bool $lazy): bool {
- $this->assertParams($app, $key);
- $this->loadConfigAll();
- if ($lazy === $this->isLazy($app, $key)) {
- return false;
- }
- $update = $this->connection->getQueryBuilder();
- $update->update('appconfig')
- ->set('lazy', $update->createNamedParameter($lazy, IQueryBuilder::PARAM_BOOL))
- ->where($update->expr()->eq('appid', $update->createNamedParameter($app)))
- ->andWhere($update->expr()->eq('configkey', $update->createNamedParameter($key)));
- $update->executeStatement();
- // At this point, it is a lot safer to clean cache
- $this->clearCache();
- return true;
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- *
- * @return array
- * @throws AppConfigUnknownKeyException if config key is not known in database
- * @since 29.0.0
- */
- public function getDetails(string $app, string $key): array {
- $this->assertParams($app, $key);
- $this->loadConfigAll();
- $lazy = $this->isLazy($app, $key);
- if ($lazy) {
- $cache = $this->lazyCache;
- } else {
- $cache = $this->fastCache;
- }
- $type = $this->getValueType($app, $key);
- try {
- $typeString = $this->convertTypeToString($type);
- } catch (AppConfigIncorrectTypeException $e) {
- $this->logger->warning('type stored in database is not correct', ['exception' => $e, 'type' => $type]);
- $typeString = (string)$type;
- }
- if (!isset($cache[$app][$key])) {
- throw new AppConfigUnknownKeyException('unknown config key');
- }
- return [
- 'app' => $app,
- 'key' => $key,
- 'value' => $cache[$app][$key],
- 'type' => $type,
- 'lazy' => $lazy,
- 'typeString' => $typeString,
- 'sensitive' => $this->isSensitive($app, $key, null)
- ];
- }
- /**
- * @param string $type
- *
- * @return int
- * @throws AppConfigIncorrectTypeException
- * @since 29.0.0
- */
- public function convertTypeToInt(string $type): int {
- return match (strtolower($type)) {
- 'mixed' => IAppConfig::VALUE_MIXED,
- 'string' => IAppConfig::VALUE_STRING,
- 'integer' => IAppConfig::VALUE_INT,
- 'float' => IAppConfig::VALUE_FLOAT,
- 'boolean' => IAppConfig::VALUE_BOOL,
- 'array' => IAppConfig::VALUE_ARRAY,
- default => throw new AppConfigIncorrectTypeException('Unknown type ' . $type)
- };
- }
- /**
- * @param int $type
- *
- * @return string
- * @throws AppConfigIncorrectTypeException
- * @since 29.0.0
- */
- public function convertTypeToString(int $type): string {
- $type &= ~self::VALUE_SENSITIVE;
- return match ($type) {
- IAppConfig::VALUE_MIXED => 'mixed',
- IAppConfig::VALUE_STRING => 'string',
- IAppConfig::VALUE_INT => 'integer',
- IAppConfig::VALUE_FLOAT => 'float',
- IAppConfig::VALUE_BOOL => 'boolean',
- IAppConfig::VALUE_ARRAY => 'array',
- default => throw new AppConfigIncorrectTypeException('Unknown numeric type ' . $type)
- };
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- * @param string $key config key
- *
- * @since 29.0.0
- */
- public function deleteKey(string $app, string $key): void {
- $this->assertParams($app, $key);
- $qb = $this->connection->getQueryBuilder();
- $qb->delete('appconfig')
- ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)))
- ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
- $qb->executeStatement();
- unset($this->lazyCache[$app][$key]);
- unset($this->fastCache[$app][$key]);
- }
- /**
- * @inheritDoc
- *
- * @param string $app id of the app
- *
- * @since 29.0.0
- */
- public function deleteApp(string $app): void {
- $this->assertParams($app);
- $qb = $this->connection->getQueryBuilder();
- $qb->delete('appconfig')
- ->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)));
- $qb->executeStatement();
- $this->clearCache();
- }
- /**
- * @inheritDoc
- *
- * @param bool $reload set to TRUE to refill cache instantly after clearing it
- *
- * @since 29.0.0
- */
- public function clearCache(bool $reload = false): void {
- $this->lazyLoaded = $this->fastLoaded = false;
- $this->lazyCache = $this->fastCache = $this->valueTypes = [];
- if (!$reload) {
- return;
- }
- $this->loadConfigAll();
- }
- /**
- * For debug purpose.
- * Returns the cached data.
- *
- * @return array
- * @since 29.0.0
- * @internal
- */
- public function statusCache(): array {
- return [
- 'fastLoaded' => $this->fastLoaded,
- 'fastCache' => $this->fastCache,
- 'lazyLoaded' => $this->lazyLoaded,
- 'lazyCache' => $this->lazyCache,
- ];
- }
- /**
- * @param int $needle bitflag to search
- * @param int $type known value
- *
- * @return bool TRUE if bitflag $needle is set in $type
- */
- private function isTyped(int $needle, int $type): bool {
- return (($needle & $type) !== 0);
- }
- /**
- * Confirm the string set for app and key fit the database description
- *
- * @param string $app assert $app fit in database
- * @param string $configKey assert config key fit in database
- * @param bool $allowEmptyApp $app can be empty string
- * @param int $valueType assert value type is only one type
- *
- * @throws InvalidArgumentException
- */
- private function assertParams(string $app = '', string $configKey = '', bool $allowEmptyApp = false, int $valueType = -1): void {
- if (!$allowEmptyApp && $app === '') {
- throw new InvalidArgumentException('app cannot be an empty string');
- }
- if (strlen($app) > self::APP_MAX_LENGTH) {
- throw new InvalidArgumentException(
- 'Value (' . $app . ') for app is too long (' . self::APP_MAX_LENGTH . ')'
- );
- }
- if (strlen($configKey) > self::KEY_MAX_LENGTH) {
- throw new InvalidArgumentException('Value (' . $configKey . ') for key is too long (' . self::KEY_MAX_LENGTH . ')');
- }
- if ($valueType > -1) {
- $valueType &= ~self::VALUE_SENSITIVE;
- if (!in_array($valueType, [self::VALUE_MIXED, self::VALUE_STRING, self::VALUE_INT, self::VALUE_FLOAT, self::VALUE_BOOL, self::VALUE_ARRAY])) {
- throw new InvalidArgumentException('Unknown value type');
- }
- }
- }
- private function loadConfigAll(): void {
- $this->loadConfig(null);
- }
- /**
- * Load normal config or config set as lazy loaded
- *
- * @param bool|null $lazy set to TRUE to load config set as lazy loaded, set to NULL to load all config
- */
- private function loadConfig(?bool $lazy = false): void {
- if ($this->isLoaded($lazy)) {
- return;
- }
- $qb = $this->connection->getQueryBuilder();
- $qb->from('appconfig');
- /**
- * The use of $this->>migrationCompleted is only needed to manage the
- * database during the upgrading process to nc29.
- */
- if (!$this->migrationCompleted) {
- $qb->select('appid', 'configkey', 'configvalue');
- } else {
- $qb->select('appid', 'configkey', 'configvalue', 'type', 'lazy');
- if ($lazy !== null) {
- if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) {
- // Oracle does not like empty string nor false boolean !?
- if ($lazy) {
- $qb->where($qb->expr()->eq('lazy', $qb->createNamedParameter('1', IQueryBuilder::PARAM_INT)));
- } else {
- $qb->where($qb->expr()->orX(
- $qb->expr()->isNull('lazy'),
- $qb->expr()->eq('lazy', $qb->createNamedParameter('0', IQueryBuilder::PARAM_INT))
- ));
- }
- } else {
- $qb->where($qb->expr()->eq('lazy', $qb->createNamedParameter($lazy, IQueryBuilder::PARAM_BOOL)));
- }
- }
- }
- try {
- $result = $qb->executeQuery();
- } catch (DBException $e) {
- /**
- * in case of issue with field name, it means that migration is not completed.
- * Falling back to a request without select on lazy.
- * This whole try/catch and the migrationCompleted variable can be removed in NC30.
- */
- if ($e->getReason() !== DBException::REASON_INVALID_FIELD_NAME) {
- throw $e;
- }
- $this->migrationCompleted = false;
- $this->loadConfig($lazy);
- return;
- }
- $rows = $result->fetchAll();
- foreach ($rows as $row) {
- // if migration is not completed, 'lazy' and 'type' does not exist in $row
- // also on oracle, lazy can be null ...
- if ($row['lazy'] ?? false) {
- $cache = &$this->lazyCache;
- } else {
- $cache = &$this->fastCache;
- }
- $cache[$row['appid']][$row['configkey']] = $row['configvalue'] ?? '';
- $this->valueTypes[$row['appid']][$row['configkey']] = (int)($row['type'] ?? 0);
- }
- $result->closeCursor();
- $this->setAsLoaded($lazy);
- }
- /**
- * if $lazy is:
- * - false: will returns true if fast config is loaded
- * - true : will returns true if lazy config is loaded
- * - null : will returns true if both config are loaded
- *
- * @param bool $lazy
- *
- * @return bool
- */
- private function isLoaded(?bool $lazy): bool {
- if ($lazy === null) {
- return $this->lazyLoaded && $this->fastLoaded;
- }
- return $lazy ? $this->lazyLoaded : $this->fastLoaded;
- }
- /**
- * if $lazy is:
- * - false: set fast config as loaded
- * - true : set lazy config as loaded
- * - null : set both config as loaded
- *
- * @param bool $lazy
- */
- private function setAsLoaded(?bool $lazy): void {
- if ($lazy === null) {
- $this->fastLoaded = true;
- $this->lazyLoaded = true;
- return;
- }
- if ($lazy) {
- $this->lazyLoaded = true;
- } else {
- $this->fastLoaded = true;
- }
- }
- /**
- * Gets the config value
- *
- * @param string $app app
- * @param string $key key
- * @param string $default = null, default value if the key does not exist
- *
- * @return string the value or $default
- * @deprecated - use getValue*()
- *
- * This function gets a value from the appconfig table. If the key does
- * not exist the default value will be returned
- */
- public function getValue($app, $key, $default = null) {
- $this->loadConfig();
- return $this->fastCache[$app][$key] ?? $default;
- }
- /**
- * Sets a value. If the key did not exist before it will be created.
- *
- * @param string $app app
- * @param string $key key
- * @param string|float|int $value value
- *
- * @return bool True if the value was inserted or updated, false if the value was the same
- * @throws AppConfigTypeConflictException
- * @throws AppConfigUnknownKeyException
- * @deprecated
- */
- public function setValue($app, $key, $value) {
- return $this->setTypedValue($app, $key, (string)$value, false, self::VALUE_MIXED);
- }
- /**
- * get multiple values, either the app or key can be used as wildcard by setting it to false
- *
- * @param string|false $app
- * @param string|false $key
- *
- * @return array|false
- * @deprecated 29.0.0 use getAllValues()
- */
- public function getValues($app, $key) {
- if (($app !== false) === ($key !== false)) {
- return false;
- }
- $key = ($key === false) ? '' : $key;
- if (!$app) {
- return $this->searchValues($key);
- } else {
- return $this->getAllValues($app, $key);
- }
- }
- /**
- * get all values of the app or and filters out sensitive data
- *
- * @param string $app
- *
- * @return array
- * @deprecated 29.0.0 use getAllValues()
- */
- public function getFilteredValues($app) {
- return $this->getAllValues($app, filtered: true);
- }
- /**
- * @param string $app
- *
- * @return string[]
- * @deprecated data sensitivity should be set when calling setValue*()
- */
- private function getSensitiveKeys(string $app): array {
- $sensitiveValues = [
- 'circles' => [
- '/^key_pairs$/',
- '/^local_gskey$/',
- ],
- 'external' => [
- '/^sites$/',
- ],
- 'integration_discourse' => [
- '/^private_key$/',
- '/^public_key$/',
- ],
- 'integration_dropbox' => [
- '/^client_id$/',
- '/^client_secret$/',
- ],
- 'integration_github' => [
- '/^client_id$/',
- '/^client_secret$/',
- ],
- 'integration_gitlab' => [
- '/^client_id$/',
- '/^client_secret$/',
- '/^oauth_instance_url$/',
- ],
- 'integration_google' => [
- '/^client_id$/',
- '/^client_secret$/',
- ],
- 'integration_jira' => [
- '/^client_id$/',
- '/^client_secret$/',
- '/^forced_instance_url$/',
- ],
- 'integration_onedrive' => [
- '/^client_id$/',
- '/^client_secret$/',
- ],
- 'integration_openproject' => [
- '/^client_id$/',
- '/^client_secret$/',
- '/^oauth_instance_url$/',
- ],
- 'integration_reddit' => [
- '/^client_id$/',
- '/^client_secret$/',
- ],
- 'integration_suitecrm' => [
- '/^client_id$/',
- '/^client_secret$/',
- '/^oauth_instance_url$/',
- ],
- 'integration_twitter' => [
- '/^consumer_key$/',
- '/^consumer_secret$/',
- '/^followed_user$/',
- ],
- 'integration_zammad' => [
- '/^client_id$/',
- '/^client_secret$/',
- '/^oauth_instance_url$/',
- ],
- 'notify_push' => [
- '/^cookie$/',
- ],
- 'serverinfo' => [
- '/^token$/',
- ],
- 'spreed' => [
- '/^bridge_bot_password$/',
- '/^hosted-signaling-server-(.*)$/',
- '/^recording_servers$/',
- '/^signaling_servers$/',
- '/^signaling_ticket_secret$/',
- '/^signaling_token_privkey_(.*)$/',
- '/^signaling_token_pubkey_(.*)$/',
- '/^sip_bridge_dialin_info$/',
- '/^sip_bridge_shared_secret$/',
- '/^stun_servers$/',
- '/^turn_servers$/',
- '/^turn_server_secret$/',
- ],
- 'support' => [
- '/^last_response$/',
- '/^potential_subscription_key$/',
- '/^subscription_key$/',
- ],
- 'theming' => [
- '/^imprintUrl$/',
- '/^privacyUrl$/',
- '/^slogan$/',
- '/^url$/',
- ],
- 'user_ldap' => [
- '/^(s..)?ldap_agent_password$/',
- ],
- 'user_saml' => [
- '/^idp-x509cert$/',
- ],
- ];
- return $sensitiveValues[$app] ?? [];
- }
- /**
- * Clear all the cached app config values
- * New cache will be generated next time a config value is retrieved
- *
- * @deprecated use {@see clearCache()}
- */
- public function clearCachedConfig(): void {
- $this->clearCache();
- }
- }
|