Browse Source

Merge pull request #47658 from nextcloud/enh/noid/user-preferences

pull/49361/head
John Molakvoæ 1 year ago
committed by GitHub
parent
commit
899b65111d
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 3
      build/psalm-baseline.xml
  2. 54
      core/Migrations/Version31000Date20240814184402.php
  3. 7
      lib/composer/composer/autoload_classmap.php
  4. 7
      lib/composer/composer/autoload_static.php
  5. 261
      lib/private/AllConfig.php
  6. 1806
      lib/private/Config/UserConfig.php
  7. 2
      lib/private/Server.php
  8. 18
      lib/unstable/Config/Exceptions/IncorrectTypeException.php
  9. 18
      lib/unstable/Config/Exceptions/TypeConflictException.php
  10. 18
      lib/unstable/Config/Exceptions/UnknownKeyException.php
  11. 694
      lib/unstable/Config/IUserConfig.php
  12. 79
      lib/unstable/Config/ValueType.php
  13. 6
      tests/lib/AllConfigTest.php
  14. 1836
      tests/lib/Config/UserConfigTest.php

3
build/psalm-baseline.xml

@ -1328,9 +1328,6 @@
<MoreSpecificImplementedParamType> <MoreSpecificImplementedParamType>
<code><![CDATA[$key]]></code> <code><![CDATA[$key]]></code>
</MoreSpecificImplementedParamType> </MoreSpecificImplementedParamType>
<TypeDoesNotContainType>
<code><![CDATA[!is_array($userIds)]]></code>
</TypeDoesNotContainType>
</file> </file>
<file src="lib/private/App/AppStore/Fetcher/Fetcher.php"> <file src="lib/private/App/AppStore/Fetcher/Fetcher.php">
<TooManyArguments> <TooManyArguments>

54
core/Migrations/Version31000Date20240814184402.php

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\Core\Migrations;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\Attributes\AddColumn;
use OCP\Migration\Attributes\AddIndex;
use OCP\Migration\Attributes\ColumnType;
use OCP\Migration\Attributes\DropIndex;
use OCP\Migration\Attributes\IndexType;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
/**
* Create new column and index for lazy loading in preferences for the new IUserPreferences API.
*/
#[AddColumn(table: 'preferences', name: 'lazy', type: ColumnType::SMALLINT, description: 'lazy loading to user preferences')]
#[AddColumn(table: 'preferences', name: 'type', type: ColumnType::SMALLINT, description: 'typed values to user preferences')]
#[AddColumn(table: 'preferences', name: 'flag', type: ColumnType::INTEGER, description: 'bitflag about the value')]
#[AddColumn(table: 'preferences', name: 'indexed', type: ColumnType::INTEGER, description: 'non-array value can be set as indexed')]
#[DropIndex(table: 'preferences', type: IndexType::INDEX, description: 'remove previous app/key index', notes: ['will be re-created to include \'indexed\' field'])]
#[AddIndex(table: 'preferences', type: IndexType::INDEX, description: 'new index including user+lazy')]
#[AddIndex(table: 'preferences', type: IndexType::INDEX, description: 'new index including app/key and indexed')]
class Version31000Date20240814184402 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
$table = $schema->getTable('preferences');
$table->addColumn('lazy', Types::SMALLINT, ['notnull' => true, 'default' => 0, 'length' => 1, 'unsigned' => true]);
$table->addColumn('type', Types::SMALLINT, ['notnull' => true, 'default' => 0, 'unsigned' => true]);
$table->addColumn('flags', Types::INTEGER, ['notnull' => true, 'default' => 0, 'unsigned' => true]);
$table->addColumn('indexed', Types::STRING, ['notnull' => false, 'default' => '', 'length' => 64]);
// removing this index from Version13000Date20170718121200
// $table->addIndex(['appid', 'configkey'], 'preferences_app_key');
if ($table->hasIndex('preferences_app_key')) {
$table->dropIndex('preferences_app_key');
}
$table->addIndex(['userid', 'lazy'], 'prefs_uid_lazy_i');
$table->addIndex(['appid', 'configkey', 'indexed', 'flags'], 'prefs_app_key_ind_fl_i');
return $schema;
}
}

7
lib/composer/composer/autoload_classmap.php

@ -7,6 +7,11 @@ $baseDir = dirname(dirname($vendorDir));
return array( return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'NCU\\Config\\Exceptions\\IncorrectTypeException' => $baseDir . '/lib/unstable/Config/Exceptions/IncorrectTypeException.php',
'NCU\\Config\\Exceptions\\TypeConflictException' => $baseDir . '/lib/unstable/Config/Exceptions/TypeConflictException.php',
'NCU\\Config\\Exceptions\\UnknownKeyException' => $baseDir . '/lib/unstable/Config/Exceptions/UnknownKeyException.php',
'NCU\\Config\\IUserConfig' => $baseDir . '/lib/unstable/Config/IUserConfig.php',
'NCU\\Config\\ValueType' => $baseDir . '/lib/unstable/Config/ValueType.php',
'OCP\\Accounts\\IAccount' => $baseDir . '/lib/public/Accounts/IAccount.php', 'OCP\\Accounts\\IAccount' => $baseDir . '/lib/public/Accounts/IAccount.php',
'OCP\\Accounts\\IAccountManager' => $baseDir . '/lib/public/Accounts/IAccountManager.php', 'OCP\\Accounts\\IAccountManager' => $baseDir . '/lib/public/Accounts/IAccountManager.php',
'OCP\\Accounts\\IAccountProperty' => $baseDir . '/lib/public/Accounts/IAccountProperty.php', 'OCP\\Accounts\\IAccountProperty' => $baseDir . '/lib/public/Accounts/IAccountProperty.php',
@ -1118,6 +1123,7 @@ return array(
'OC\\Comments\\Manager' => $baseDir . '/lib/private/Comments/Manager.php', 'OC\\Comments\\Manager' => $baseDir . '/lib/private/Comments/Manager.php',
'OC\\Comments\\ManagerFactory' => $baseDir . '/lib/private/Comments/ManagerFactory.php', 'OC\\Comments\\ManagerFactory' => $baseDir . '/lib/private/Comments/ManagerFactory.php',
'OC\\Config' => $baseDir . '/lib/private/Config.php', 'OC\\Config' => $baseDir . '/lib/private/Config.php',
'OC\\Config\\UserConfig' => $baseDir . '/lib/private/Config/UserConfig.php',
'OC\\Console\\Application' => $baseDir . '/lib/private/Console/Application.php', 'OC\\Console\\Application' => $baseDir . '/lib/private/Console/Application.php',
'OC\\Console\\TimestampFormatter' => $baseDir . '/lib/private/Console/TimestampFormatter.php', 'OC\\Console\\TimestampFormatter' => $baseDir . '/lib/private/Console/TimestampFormatter.php',
'OC\\ContactsManager' => $baseDir . '/lib/private/ContactsManager.php', 'OC\\ContactsManager' => $baseDir . '/lib/private/ContactsManager.php',
@ -1386,6 +1392,7 @@ return array(
'OC\\Core\\Migrations\\Version30000Date20240814180800' => $baseDir . '/core/Migrations/Version30000Date20240814180800.php', 'OC\\Core\\Migrations\\Version30000Date20240814180800' => $baseDir . '/core/Migrations/Version30000Date20240814180800.php',
'OC\\Core\\Migrations\\Version30000Date20240815080800' => $baseDir . '/core/Migrations/Version30000Date20240815080800.php', 'OC\\Core\\Migrations\\Version30000Date20240815080800' => $baseDir . '/core/Migrations/Version30000Date20240815080800.php',
'OC\\Core\\Migrations\\Version30000Date20240906095113' => $baseDir . '/core/Migrations/Version30000Date20240906095113.php', 'OC\\Core\\Migrations\\Version30000Date20240906095113' => $baseDir . '/core/Migrations/Version30000Date20240906095113.php',
'OC\\Core\\Migrations\\Version31000Date20240814184402' => $baseDir . '/core/Migrations/Version31000Date20240814184402.php',
'OC\\Core\\Migrations\\Version31000Date20241018063111' => $baseDir . '/core/Migrations/Version31000Date20241018063111.php', 'OC\\Core\\Migrations\\Version31000Date20241018063111' => $baseDir . '/core/Migrations/Version31000Date20241018063111.php',
'OC\\Core\\Notification\\CoreNotifier' => $baseDir . '/core/Notification/CoreNotifier.php', 'OC\\Core\\Notification\\CoreNotifier' => $baseDir . '/core/Notification/CoreNotifier.php',
'OC\\Core\\ResponseDefinitions' => $baseDir . '/core/ResponseDefinitions.php', 'OC\\Core\\ResponseDefinitions' => $baseDir . '/core/ResponseDefinitions.php',

7
lib/composer/composer/autoload_static.php

@ -48,6 +48,11 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
public static $classMap = array ( public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'NCU\\Config\\Exceptions\\IncorrectTypeException' => __DIR__ . '/../../..' . '/lib/unstable/Config/Exceptions/IncorrectTypeException.php',
'NCU\\Config\\Exceptions\\TypeConflictException' => __DIR__ . '/../../..' . '/lib/unstable/Config/Exceptions/TypeConflictException.php',
'NCU\\Config\\Exceptions\\UnknownKeyException' => __DIR__ . '/../../..' . '/lib/unstable/Config/Exceptions/UnknownKeyException.php',
'NCU\\Config\\IUserConfig' => __DIR__ . '/../../..' . '/lib/unstable/Config/IUserConfig.php',
'NCU\\Config\\ValueType' => __DIR__ . '/../../..' . '/lib/unstable/Config/ValueType.php',
'OCP\\Accounts\\IAccount' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccount.php', 'OCP\\Accounts\\IAccount' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccount.php',
'OCP\\Accounts\\IAccountManager' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccountManager.php', 'OCP\\Accounts\\IAccountManager' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccountManager.php',
'OCP\\Accounts\\IAccountProperty' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccountProperty.php', 'OCP\\Accounts\\IAccountProperty' => __DIR__ . '/../../..' . '/lib/public/Accounts/IAccountProperty.php',
@ -1159,6 +1164,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Comments\\Manager' => __DIR__ . '/../../..' . '/lib/private/Comments/Manager.php', 'OC\\Comments\\Manager' => __DIR__ . '/../../..' . '/lib/private/Comments/Manager.php',
'OC\\Comments\\ManagerFactory' => __DIR__ . '/../../..' . '/lib/private/Comments/ManagerFactory.php', 'OC\\Comments\\ManagerFactory' => __DIR__ . '/../../..' . '/lib/private/Comments/ManagerFactory.php',
'OC\\Config' => __DIR__ . '/../../..' . '/lib/private/Config.php', 'OC\\Config' => __DIR__ . '/../../..' . '/lib/private/Config.php',
'OC\\Config\\UserConfig' => __DIR__ . '/../../..' . '/lib/private/Config/UserConfig.php',
'OC\\Console\\Application' => __DIR__ . '/../../..' . '/lib/private/Console/Application.php', 'OC\\Console\\Application' => __DIR__ . '/../../..' . '/lib/private/Console/Application.php',
'OC\\Console\\TimestampFormatter' => __DIR__ . '/../../..' . '/lib/private/Console/TimestampFormatter.php', 'OC\\Console\\TimestampFormatter' => __DIR__ . '/../../..' . '/lib/private/Console/TimestampFormatter.php',
'OC\\ContactsManager' => __DIR__ . '/../../..' . '/lib/private/ContactsManager.php', 'OC\\ContactsManager' => __DIR__ . '/../../..' . '/lib/private/ContactsManager.php',
@ -1427,6 +1433,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Core\\Migrations\\Version30000Date20240814180800' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240814180800.php', 'OC\\Core\\Migrations\\Version30000Date20240814180800' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240814180800.php',
'OC\\Core\\Migrations\\Version30000Date20240815080800' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240815080800.php', 'OC\\Core\\Migrations\\Version30000Date20240815080800' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240815080800.php',
'OC\\Core\\Migrations\\Version30000Date20240906095113' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240906095113.php', 'OC\\Core\\Migrations\\Version30000Date20240906095113' => __DIR__ . '/../../..' . '/core/Migrations/Version30000Date20240906095113.php',
'OC\\Core\\Migrations\\Version31000Date20240814184402' => __DIR__ . '/../../..' . '/core/Migrations/Version31000Date20240814184402.php',
'OC\\Core\\Migrations\\Version31000Date20241018063111' => __DIR__ . '/../../..' . '/core/Migrations/Version31000Date20241018063111.php', 'OC\\Core\\Migrations\\Version31000Date20241018063111' => __DIR__ . '/../../..' . '/core/Migrations/Version31000Date20241018063111.php',
'OC\\Core\\Notification\\CoreNotifier' => __DIR__ . '/../../..' . '/core/Notification/CoreNotifier.php', 'OC\\Core\\Notification\\CoreNotifier' => __DIR__ . '/../../..' . '/core/Notification/CoreNotifier.php',
'OC\\Core\\ResponseDefinitions' => __DIR__ . '/../../..' . '/core/ResponseDefinitions.php', 'OC\\Core\\ResponseDefinitions' => __DIR__ . '/../../..' . '/core/ResponseDefinitions.php',

261
lib/private/AllConfig.php

@ -6,8 +6,11 @@
*/ */
namespace OC; namespace OC;
use NCU\Config\Exceptions\TypeConflictException;
use NCU\Config\IUserConfig;
use NCU\Config\ValueType;
use OC\Config\UserConfig;
use OCP\Cache\CappedMemoryCache; use OCP\Cache\CappedMemoryCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IConfig; use OCP\IConfig;
use OCP\IDBConnection; use OCP\IDBConnection;
use OCP\PreConditionNotMetException; use OCP\PreConditionNotMetException;
@ -224,64 +227,33 @@ class AllConfig implements IConfig {
* @param string $key the key under which the value is being stored * @param string $key the key under which the value is being stored
* @param string|float|int $value the value that you want to store * @param string|float|int $value the value that you want to store
* @param string $preCondition only update if the config value was previously the value passed as $preCondition * @param string $preCondition only update if the config value was previously the value passed as $preCondition
*
* @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
* @throws \UnexpectedValueException when trying to store an unexpected value * @throws \UnexpectedValueException when trying to store an unexpected value
* @deprecated 31.0.0 - use {@see IUserConfig} directly
* @see IUserConfig::getValueString
* @see IUserConfig::getValueInt
* @see IUserConfig::getValueFloat
* @see IUserConfig::getValueArray
* @see IUserConfig::getValueBool
*/ */
public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
if (!is_int($value) && !is_float($value) && !is_string($value)) { if (!is_int($value) && !is_float($value) && !is_string($value)) {
throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
} }
// TODO - FIXME
$this->fixDIInit();
if ($appName === 'settings' && $key === 'email') {
$value = strtolower((string)$value);
}
$prevValue = $this->getUserValue($userId, $appName, $key, null);
if ($prevValue !== null) {
if ($preCondition !== null && $prevValue !== (string)$preCondition) {
throw new PreConditionNotMetException();
} elseif ($prevValue === (string)$value) {
return;
} else {
$qb = $this->connection->getQueryBuilder();
$qb->update('preferences')
->set('configvalue', $qb->createNamedParameter($value))
->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
$qb->executeStatement();
$this->userCache[$userId][$appName][$key] = (string)$value;
return;
/** @var UserConfig $userPreferences */
$userPreferences = \OCP\Server::get(IUserConfig::class);
if ($preCondition !== null) {
try {
if ($userPreferences->getValueMixed($userId, $appName, $key) !== (string)$preCondition) {
throw new PreConditionNotMetException();
}
} catch (TypeConflictException) {
} }
} }
$preconditionArray = [];
if (isset($preCondition)) {
$preconditionArray = [
'configvalue' => $preCondition,
];
}
$this->connection->setValues('preferences', [
'userid' => $userId,
'appid' => $appName,
'configkey' => $key,
], [
'configvalue' => $value,
], $preconditionArray);
// only add to the cache if we already loaded data for the user
if (isset($this->userCache[$userId])) {
if (!isset($this->userCache[$userId][$appName])) {
$this->userCache[$userId][$appName] = [];
}
$this->userCache[$userId][$appName][$key] = (string)$value;
}
$userPreferences->setValueMixed($userId, $appName, $key, (string)$value);
} }
/** /**
@ -291,15 +263,26 @@ class AllConfig implements IConfig {
* @param string $appName the appName that we stored the value under * @param string $appName the appName that we stored the value under
* @param string $key the key under which the value is being stored * @param string $key the key under which the value is being stored
* @param mixed $default the default value to be returned if the value isn't set * @param mixed $default the default value to be returned if the value isn't set
*
* @return string * @return string
* @deprecated 31.0.0 - use {@see IUserConfig} directly
* @see IUserConfig::getValueString
* @see IUserConfig::getValueInt
* @see IUserConfig::getValueFloat
* @see IUserConfig::getValueArray
* @see IUserConfig::getValueBool
*/ */
public function getUserValue($userId, $appName, $key, $default = '') { public function getUserValue($userId, $appName, $key, $default = '') {
$data = $this->getAllUserValues($userId);
if (isset($data[$appName][$key])) {
return $data[$appName][$key];
} else {
if ($userId === null || $userId === '') {
return $default;
}
/** @var UserConfig $userPreferences */
$userPreferences = \OCP\Server::get(IUserConfig::class);
// because $default can be null ...
if (!$userPreferences->hasKey($userId, $appName, $key)) {
return $default; return $default;
} }
return $userPreferences->getValueMixed($userId, $appName, $key, $default ?? '');
} }
/** /**
@ -307,15 +290,12 @@ class AllConfig implements IConfig {
* *
* @param string $userId the userId of the user that we want to store the value under * @param string $userId the userId of the user that we want to store the value under
* @param string $appName the appName that we stored the value under * @param string $appName the appName that we stored the value under
*
* @return string[] * @return string[]
* @deprecated 31.0.0 - use {@see IUserConfig::getKeys} directly
*/ */
public function getUserKeys($userId, $appName) { public function getUserKeys($userId, $appName) {
$data = $this->getAllUserValues($userId);
if (isset($data[$appName])) {
return array_map('strval', array_keys($data[$appName]));
} else {
return [];
}
return \OCP\Server::get(IUserConfig::class)->getKeys($userId, $appName);
} }
/** /**
@ -324,96 +304,63 @@ class AllConfig implements IConfig {
* @param string $userId the userId of the user that we want to store the value under * @param string $userId the userId of the user that we want to store the value under
* @param string $appName the appName that we stored the value under * @param string $appName the appName that we stored the value under
* @param string $key the key under which the value is being stored * @param string $key the key under which the value is being stored
*
* @deprecated 31.0.0 - use {@see IUserConfig::deleteUserConfig} directly
*/ */
public function deleteUserValue($userId, $appName, $key) { public function deleteUserValue($userId, $appName, $key) {
// TODO - FIXME
$this->fixDIInit();
$qb = $this->connection->getQueryBuilder();
$qb->delete('preferences')
->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key, IQueryBuilder::PARAM_STR)))
->executeStatement();
if (isset($this->userCache[$userId][$appName])) {
unset($this->userCache[$userId][$appName][$key]);
}
\OCP\Server::get(IUserConfig::class)->deleteUserConfig($userId, $appName, $key);
} }
/** /**
* Delete all user values * Delete all user values
* *
* @param string $userId the userId of the user that we want to remove all values from * @param string $userId the userId of the user that we want to remove all values from
*
* @deprecated 31.0.0 - use {@see IUserConfig::deleteAllUserConfig} directly
*/ */
public function deleteAllUserValues($userId) { public function deleteAllUserValues($userId) {
// TODO - FIXME
$this->fixDIInit();
$qb = $this->connection->getQueryBuilder();
$qb->delete('preferences')
->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR)))
->executeStatement();
unset($this->userCache[$userId]);
if ($userId === null) {
return;
}
\OCP\Server::get(IUserConfig::class)->deleteAllUserConfig($userId);
} }
/** /**
* Delete all user related values of one app * Delete all user related values of one app
* *
* @param string $appName the appName of the app that we want to remove all values from * @param string $appName the appName of the app that we want to remove all values from
*
* @deprecated 31.0.0 - use {@see IUserConfig::deleteApp} directly
*/ */
public function deleteAppFromAllUsers($appName) { public function deleteAppFromAllUsers($appName) {
// TODO - FIXME
$this->fixDIInit();
$qb = $this->connection->getQueryBuilder();
$qb->delete('preferences')
->where($qb->expr()->eq('appid', $qb->createNamedParameter($appName, IQueryBuilder::PARAM_STR)))
->executeStatement();
foreach ($this->userCache as &$userCache) {
unset($userCache[$appName]);
}
\OCP\Server::get(IUserConfig::class)->deleteApp($appName);
} }
/** /**
* Returns all user configs sorted by app of one user * Returns all user configs sorted by app of one user
* *
* @param ?string $userId the user ID to get the app configs from * @param ?string $userId the user ID to get the app configs from
*
* @psalm-return array<string, array<string, string>> * @psalm-return array<string, array<string, string>>
* @return array[] - 2 dimensional array with the following structure: * @return array[] - 2 dimensional array with the following structure:
* [ $appId => * [ $appId =>
* [ $key => $value ] * [ $key => $value ]
* ] * ]
* @deprecated 31.0.0 - use {@see IUserConfig::getAllValues} directly
*/ */
public function getAllUserValues(?string $userId): array { public function getAllUserValues(?string $userId): array {
if (isset($this->userCache[$userId])) {
return $this->userCache[$userId];
}
if ($userId === null || $userId === '') { if ($userId === null || $userId === '') {
$this->userCache[''] = [];
return $this->userCache[''];
return [];
} }
// TODO - FIXME
$this->fixDIInit();
$data = [];
$qb = $this->connection->getQueryBuilder();
$result = $qb->select('appid', 'configkey', 'configvalue')
->from('preferences')
->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR)))
->executeQuery();
while ($row = $result->fetch()) {
$appId = $row['appid'];
if (!isset($data[$appId])) {
$data[$appId] = [];
$values = \OCP\Server::get(IUserConfig::class)->getAllValues($userId);
$result = [];
foreach ($values as $app => $list) {
foreach ($list as $key => $value) {
$result[$app][$key] = (string)$value;
} }
$data[$appId][$row['configkey']] = $row['configvalue'];
} }
$this->userCache[$userId] = $data;
return $data;
return $result;
} }
/** /**
@ -422,38 +369,12 @@ class AllConfig implements IConfig {
* @param string $appName app to get the value for * @param string $appName app to get the value for
* @param string $key the key to get the value for * @param string $key the key to get the value for
* @param array $userIds the user IDs to fetch the values for * @param array $userIds the user IDs to fetch the values for
*
* @return array Mapped values: userId => value * @return array Mapped values: userId => value
* @deprecated 31.0.0 - use {@see IUserConfig::getValuesByUsers} directly
*/ */
public function getUserValueForUsers($appName, $key, $userIds) { public function getUserValueForUsers($appName, $key, $userIds) {
// TODO - FIXME
$this->fixDIInit();
if (empty($userIds) || !is_array($userIds)) {
return [];
}
$chunkedUsers = array_chunk($userIds, 50, true);
$qb = $this->connection->getQueryBuilder();
$qb->select('userid', 'configvalue')
->from('preferences')
->where($qb->expr()->eq('appid', $qb->createParameter('appName')))
->andWhere($qb->expr()->eq('configkey', $qb->createParameter('configKey')))
->andWhere($qb->expr()->in('userid', $qb->createParameter('userIds')));
$userValues = [];
foreach ($chunkedUsers as $chunk) {
$qb->setParameter('appName', $appName, IQueryBuilder::PARAM_STR);
$qb->setParameter('configKey', $key, IQueryBuilder::PARAM_STR);
$qb->setParameter('userIds', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
$result = $qb->executeQuery();
while ($row = $result->fetch()) {
$userValues[$row['userid']] = $row['configvalue'];
}
}
return $userValues;
return \OCP\Server::get(IUserConfig::class)->getValuesByUsers($appName, $key, ValueType::MIXED, $userIds);
} }
/** /**
@ -462,32 +383,14 @@ class AllConfig implements IConfig {
* @param string $appName the app to get the user for * @param string $appName the app to get the user for
* @param string $key the key to get the user for * @param string $key the key to get the user for
* @param string $value the value to get the user for * @param string $value the value to get the user for
*
* @return list<string> of user IDs * @return list<string> of user IDs
* @deprecated 31.0.0 - use {@see IUserConfig::searchUsersByValueString} directly
*/ */
public function getUsersForUserValue($appName, $key, $value) { public function getUsersForUserValue($appName, $key, $value) {
// TODO - FIXME
$this->fixDIInit();
$qb = $this->connection->getQueryBuilder();
$configValueColumn = ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE)
? $qb->expr()->castColumn('configvalue', IQueryBuilder::PARAM_STR)
: 'configvalue';
$result = $qb->select('userid')
->from('preferences')
->where($qb->expr()->eq('appid', $qb->createNamedParameter($appName, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq(
$configValueColumn,
$qb->createNamedParameter($value, IQueryBuilder::PARAM_STR))
)->orderBy('userid')
->executeQuery();
$userIDs = [];
while ($row = $result->fetch()) {
$userIDs[] = $row['userid'];
}
return $userIDs;
/** @var list<string> $result */
$result = iterator_to_array(\OCP\Server::get(IUserConfig::class)->searchUsersByValueString($appName, $key, $value));
return $result;
} }
/** /**
@ -496,38 +399,18 @@ class AllConfig implements IConfig {
* @param string $appName the app to get the user for * @param string $appName the app to get the user for
* @param string $key the key to get the user for * @param string $key the key to get the user for
* @param string $value the value to get the user for * @param string $value the value to get the user for
*
* @return list<string> of user IDs * @return list<string> of user IDs
* @deprecated 31.0.0 - use {@see IUserConfig::searchUsersByValueString} directly
*/ */
public function getUsersForUserValueCaseInsensitive($appName, $key, $value) { public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
// TODO - FIXME
$this->fixDIInit();
if ($appName === 'settings' && $key === 'email') { if ($appName === 'settings' && $key === 'email') {
// Email address is always stored lowercase in the database
return $this->getUsersForUserValue($appName, $key, strtolower($value)); return $this->getUsersForUserValue($appName, $key, strtolower($value));
} }
$qb = $this->connection->getQueryBuilder();
$configValueColumn = ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE)
? $qb->expr()->castColumn('configvalue', IQueryBuilder::PARAM_STR)
: 'configvalue';
$result = $qb->select('userid')
->from('preferences')
->where($qb->expr()->eq('appid', $qb->createNamedParameter($appName, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->eq(
$qb->func()->lower($configValueColumn),
$qb->createNamedParameter(strtolower($value), IQueryBuilder::PARAM_STR))
)->orderBy('userid')
->executeQuery();
$userIDs = [];
while ($row = $result->fetch()) {
$userIDs[] = $row['userid'];
}
return $userIDs;
/** @var list<string> $result */
$result = iterator_to_array(\OCP\Server::get(IUserConfig::class)->searchUsersByValueString($appName, $key, $value, true));
return $result;
} }
public function getSystemConfig() { public function getSystemConfig() {

1806
lib/private/Config/UserConfig.php
File diff suppressed because it is too large
View File

2
lib/private/Server.php

@ -7,6 +7,7 @@
namespace OC; namespace OC;
use bantu\IniGetWrapper\IniGetWrapper; use bantu\IniGetWrapper\IniGetWrapper;
use NCU\Config\IUserConfig;
use OC\Accounts\AccountManager; use OC\Accounts\AccountManager;
use OC\App\AppManager; use OC\App\AppManager;
use OC\App\AppStore\Bundles\BundleFetcher; use OC\App\AppStore\Bundles\BundleFetcher;
@ -567,6 +568,7 @@ class Server extends ServerContainer implements IServerContainer {
}); });
$this->registerAlias(IAppConfig::class, \OC\AppConfig::class); $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
$this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
$this->registerService(IFactory::class, function (Server $c) { $this->registerService(IFactory::class, function (Server $c) {
return new \OC\L10N\Factory( return new \OC\L10N\Factory(

18
lib/unstable/Config/Exceptions/IncorrectTypeException.php

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace NCU\Config\Exceptions;
use Exception;
/**
* @experimental 31.0.0
* @since 31.0.0
*/
class IncorrectTypeException extends Exception {
}

18
lib/unstable/Config/Exceptions/TypeConflictException.php

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace NCU\Config\Exceptions;
use Exception;
/**
* @experimental 31.0.0
* @since 31.0.0
*/
class TypeConflictException extends Exception {
}

18
lib/unstable/Config/Exceptions/UnknownKeyException.php

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace NCU\Config\Exceptions;
use Exception;
/**
* @experimental 31.0.0
* @since 31.0.0
*/
class UnknownKeyException extends Exception {
}

694
lib/unstable/Config/IUserConfig.php

@ -0,0 +1,694 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace NCU\Config;
use Generator;
use NCU\Config\Exceptions\IncorrectTypeException;
use NCU\Config\Exceptions\UnknownKeyException;
/**
* This class provides an easy way for apps to store user config in the
* database.
* Supports **lazy loading**
*
* ### What is lazy loading ?
* In order to avoid loading useless user config 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.
*
* @experimental 31.0.0
* @since 31.0.0
*/
interface IUserConfig {
/** @since 31.0.0 */
public const FLAG_SENSITIVE = 1; // value is sensitive
/** @since 31.0.0 */
public const FLAG_INDEXED = 2; // value should be indexed
/**
* Get list of all userIds with config stored in database.
* If $appId is specified, will only limit the search to this value
*
* **WARNING:** ignore any cache and get data directly from database.
*
* @param string $appId optional id of app
*
* @return list<string> list of userIds
* @since 31.0.0
*/
public function getUserIds(string $appId = ''): array;
/**
* Get list of all apps that have at least one config
* value related to $userId stored in database
*
* **WARNING:** ignore lazy filtering, all user config are loaded from database
*
* @param string $userId id of the user
*
* @return list<string> list of app ids
* @since 31.0.0
*/
public function getApps(string $userId): array;
/**
* Returns all keys stored in database, related to user+app.
* Please note that the values are not returned.
*
* **WARNING:** ignore lazy filtering, all user config are loaded from database
*
* @param string $userId id of the user
* @param string $app id of the app
*
* @return list<string> list of stored config keys
* @since 31.0.0
*/
public function getKeys(string $userId, string $app): array;
/**
* Check if a key exists in the list of stored config values.
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool $lazy search within lazy loaded config
*
* @return bool TRUE if key exists
* @since 31.0.0
*/
public function hasKey(string $userId, string $app, string $key, ?bool $lazy = false): bool;
/**
* best way to see if a value is set as sensitive (not displayed in report)
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy search within lazy loaded config
*
* @return bool TRUE if value is sensitive
* @throws UnknownKeyException if config key is not known
* @since 31.0.0
*/
public function isSensitive(string $userId, string $app, string $key, ?bool $lazy = false): bool;
/**
* best way to see if a value is set as indexed (so it can be search)
*
* @see self::searchUsersByValueString()
* @see self::searchUsersByValueInt()
* @see self::searchUsersByValueBool()
* @see self::searchUsersByValues()
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy search within lazy loaded config
*
* @return bool TRUE if value is sensitive
* @throws UnknownKeyException if config key is not known
* @since 31.0.0
*/
public function isIndexed(string $userId, string $app, string $key, ?bool $lazy = false): bool;
/**
* Returns if the config key stored in database is lazy loaded
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
*
* @return bool TRUE if config is lazy loaded
* @throws UnknownKeyException if config key is not known
* @see IUserConfig for details about lazy loading
* @since 31.0.0
*/
public function isLazy(string $userId, string $app, string $key): bool;
/**
* List all config values from an app with config key starting with $key.
* Returns an array with config key as key, stored value as value.
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $prefix config keys prefix to search, can be empty.
* @param bool $filtered filter sensitive config values
*
* @return array<string, string|int|float|bool|array> [key => value]
* @since 31.0.0
*/
public function getValues(string $userId, string $app, string $prefix = '', bool $filtered = false): array;
/**
* List all config values of a user.
* Returns an array with config key as key, stored value as value.
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
*
* @param string $userId id of the user
* @param bool $filtered filter sensitive config values
*
* @return array<string, string|int|float|bool|array> [key => value]
* @since 31.0.0
*/
public function getAllValues(string $userId, bool $filtered = false): array;
/**
* List all apps storing a specific config key and its stored value.
* Returns an array with appId as key, stored value as value.
*
* @param string $userId id of the user
* @param string $key config key
* @param bool $lazy search within lazy loaded config
* @param ValueType|null $typedAs enforce type for the returned values
*
* @return array<string, string|int|float|bool|array> [appId => value]
* @since 31.0.0
*/
public function getValuesByApps(string $userId, string $key, bool $lazy = false, ?ValueType $typedAs = null): array;
/**
* List all users storing a specific config key and its stored value.
* Returns an array with userId as key, stored value as value.
*
* **WARNING:** no caching, generate a fresh request
*
* @param string $app id of the app
* @param string $key config key
* @param ValueType|null $typedAs enforce type for the returned values
* @param array|null $userIds limit the search to a list of user ids
*
* @return array<string, string|int|float|bool|array> [userId => value]
* @since 31.0.0
*/
public function getValuesByUsers(string $app, string $key, ?ValueType $typedAs = null, ?array $userIds = null): array;
/**
* List all users storing a specific config key/value pair.
* Returns a list of user ids.
*
* **WARNING:** no caching, generate a fresh request
*
* @param string $app id of the app
* @param string $key config key
* @param string $value config value
* @param bool $caseInsensitive non-case-sensitive search, only works if $value is a string
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueString(string $app, string $key, string $value, bool $caseInsensitive = false): Generator;
/**
* List all users storing a specific config key/value pair.
* Returns a list of user ids.
*
* **WARNING:** no caching, generate a fresh request
*
* @param string $app id of the app
* @param string $key config key
* @param int $value config value
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueInt(string $app, string $key, int $value): Generator;
/**
* List all users storing a specific config key/value pair.
* Returns a list of user ids.
*
* **WARNING:** no caching, generate a fresh request
*
* @param string $app id of the app
* @param string $key config key
* @param array $values list of possible config values
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValues(string $app, string $key, array $values): Generator;
/**
* List all users storing a specific config key/value pair.
* Returns a list of user ids.
*
* **WARNING:** no caching, generate a fresh request
*
* @param string $app id of the app
* @param string $key config key
* @param bool $value config value
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueBool(string $app, string $key, bool $value): Generator;
/**
* Get user config assigned to a config key.
* If config key is not found in database, default value is returned.
* If config key is set as lazy loaded, the $lazy argument needs to be set to TRUE.
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see getValueInt()
* @see getValueFloat()
* @see getValueBool()
* @see getValueArray()
*/
public function getValueString(string $userId, string $app, string $key, string $default = '', bool $lazy = false): string;
/**
* Get config value assigned to a config key.
* If config key is not found in database, default value is returned.
* If config key is set as lazy loaded, the $lazy argument needs to be set to TRUE.
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see getValueString()
* @see getValueFloat()
* @see getValueBool()
* @see getValueArray()
*/
public function getValueInt(string $userId, string $app, string $key, int $default = 0, bool $lazy = false): int;
/**
* Get config value assigned to a config key.
* If config key is not found in database, default value is returned.
* If config key is set as lazy loaded, the $lazy argument needs to be set to TRUE.
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see getValueString()
* @see getValueInt()
* @see getValueBool()
* @see getValueArray()
*/
public function getValueFloat(string $userId, string $app, string $key, float $default = 0, bool $lazy = false): float;
/**
* Get config value assigned to a config key.
* If config key is not found in database, default value is returned.
* If config key is set as lazy loaded, the $lazy argument needs to be set to TRUE.
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserPrefences for explanation about lazy loading
* @see getValueString()
* @see getValueInt()
* @see getValueFloat()
* @see getValueArray()
*/
public function getValueBool(string $userId, string $app, string $key, bool $default = false, bool $lazy = false): bool;
/**
* Get config value assigned to a config key.
* If config key is not found in database, default value is returned.
* If config key is set as lazy loaded, the $lazy argument needs to be set to TRUE.
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see getValueString()
* @see getValueInt()
* @see getValueFloat()
* @see getValueBool()
*/
public function getValueArray(string $userId, string $app, string $key, array $default = [], bool $lazy = false): array;
/**
* returns the type of config value
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
* unless lazy is set to false
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy
*
* @return ValueType type of the value
* @throws UnknownKeyException if config key is not known
* @throws IncorrectTypeException if config value type is not known
* @since 31.0.0
*/
public function getValueType(string $userId, string $app, string $key, ?bool $lazy = null): ValueType;
/**
* returns a bitflag related to config value
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
* unless lazy is set to false
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool $lazy lazy loading
*
* @return int a bitflag in relation to the config value
* @throws UnknownKeyException if config key is not known
* @throws IncorrectTypeException if config value type is not known
* @since 31.0.0
*/
public function getValueFlags(string $userId, string $app, string $key, bool $lazy = false): int;
/**
* Store a config key and its value in database
*
* If config key is already known with the exact same config value, the database is not updated.
* If config key is not supposed to be read during the boot of the cloud, it is advised to set it as lazy loaded.
*
* If config value was previously stored as sensitive or lazy loaded, status cannot be altered without using {@see deleteKey()} first
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param string $value config value
* @param bool $sensitive if TRUE value will be hidden when listing config values.
* @param bool $lazy set config as lazy loaded
*
* @return bool TRUE if value was different, therefor updated in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueInt()
* @see setValueFloat()
* @see setValueBool()
* @see setValueArray()
*/
public function setValueString(string $userId, string $app, string $key, string $value, bool $lazy = false, int $flags = 0): bool;
/**
* Store a config key and its value in database
*
* When handling huge value around and/or above 2,147,483,647, a debug log will be generated
* on 64bits system, as php int type reach its limit (and throw an exception) on 32bits when using huge numbers.
*
* When using huge numbers, it is advised to use {@see \OCP\Util::numericToNumber()} and {@see setValueString()}
*
* If config key is already known with the exact same config value, the database is not updated.
* If config key is not supposed to be read during the boot of the cloud, it is advised to set it as lazy loaded.
*
* If config value was previously stored as sensitive or lazy loaded, status cannot be altered without using {@see deleteKey()} first
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param int $value config value
* @param bool $sensitive if TRUE value will be hidden when listing config values.
* @param bool $lazy set config as lazy loaded
*
* @return bool TRUE if value was different, therefor updated in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueString()
* @see setValueFloat()
* @see setValueBool()
* @see setValueArray()
*/
public function setValueInt(string $userId, string $app, string $key, int $value, bool $lazy = false, int $flags = 0): bool;
/**
* Store a config key and its value in database.
*
* If config key is already known with the exact same config value, the database is not updated.
* If config key is not supposed to be read during the boot of the cloud, it is advised to set it as lazy loaded.
*
* If config value was previously stored as sensitive or lazy loaded, status cannot be altered without using {@see deleteKey()} first
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param float $value config value
* @param bool $sensitive if TRUE value will be hidden when listing config values.
* @param bool $lazy set config as lazy loaded
*
* @return bool TRUE if value was different, therefor updated in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueString()
* @see setValueInt()
* @see setValueBool()
* @see setValueArray()
*/
public function setValueFloat(string $userId, string $app, string $key, float $value, bool $lazy = false, int $flags = 0): bool;
/**
* Store a config key and its value in database
*
* If config key is already known with the exact same config value, the database is not updated.
* If config key is not supposed to be read during the boot of the cloud, it is advised to set it as lazy loaded.
*
* If config value was previously stored as lazy loaded, status cannot be altered without using {@see deleteKey()} first
*
* @param string $userId id of the user
* @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
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueString()
* @see setValueInt()
* @see setValueFloat()
* @see setValueArray()
*/
public function setValueBool(string $userId, string $app, string $key, bool $value, bool $lazy = false): bool;
/**
* Store a config key and its value in database
*
* If config key is already known with the exact same config value, the database is not updated.
* If config key is not supposed to be read during the boot of the cloud, it is advised to set it as lazy loaded.
*
* If config value was previously stored as sensitive or lazy loaded, status cannot be altered without using {@see deleteKey()} first
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param array $value config value
* @param bool $sensitive if TRUE value will be hidden when listing config values.
* @param bool $lazy set config as lazy loaded
*
* @return bool TRUE if value was different, therefor updated in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueString()
* @see setValueInt()
* @see setValueFloat()
* @see setValueBool()
*/
public function setValueArray(string $userId, string $app, string $key, array $value, bool $lazy = false, int $flags = 0): bool;
/**
* switch sensitive status of a config value
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
*
* @param string $userId id of the user
* @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
* @since 31.0.0
*/
public function updateSensitive(string $userId, string $app, string $key, bool $sensitive): bool;
/**
* switch sensitive loading status of a config key for all users
*
* **Warning:** heavy on resources, MUST only be used on occ command or migrations
*
* @param string $app id of the app
* @param string $key config key
* @param bool $sensitive TRUE to set as sensitive, FALSE to unset
*
* @since 31.0.0
*/
public function updateGlobalSensitive(string $app, string $key, bool $sensitive): void;
/**
* switch indexed status of a config value
*
* **WARNING:** ignore lazy filtering, all config values are loaded from database
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool $indexed TRUE to set as indexed, FALSE to unset
*
* @return bool TRUE if database update were necessary
* @since 31.0.0
*/
public function updateIndexed(string $userId, string $app, string $key, bool $indexed): bool;
/**
* switch sensitive loading status of a config key for all users
*
* **Warning:** heavy on resources, MUST only be used on occ command or migrations
*
* @param string $app id of the app
* @param string $key config key
* @param bool $indexed TRUE to set as indexed, FALSE to unset
* @since 31.0.0
*/
public function updateGlobalIndexed(string $app, string $key, bool $indexed): void;
/**
* switch lazy loading status of a config value
*
* @param string $userId id of the user
* @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
* @since 31.0.0
*/
public function updateLazy(string $userId, string $app, string $key, bool $lazy): bool;
/**
* switch lazy loading status of a config key for all users
*
* **Warning:** heavy on resources, MUST only be used on occ command or migrations
*
* @param string $app id of the app
* @param string $key config key
* @param bool $lazy TRUE to set as lazy loaded, FALSE to unset
* @since 31.0.0
*/
public function updateGlobalLazy(string $app, string $key, bool $lazy): void;
/**
* returns an array contains details about a config value
*
* ```
* [
* "app" => "myapp",
* "key" => "mykey",
* "value" => "its_value",
* "lazy" => false,
* "type" => 4,
* "typeString" => "string",
* 'sensitive' => true
* ]
* ```
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
*
* @return array
* @throws UnknownKeyException if config key is not known in database
* @since 31.0.0
*/
public function getDetails(string $userId, string $app, string $key): array;
/**
* Delete single config key from database.
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
*
* @since 31.0.0
*/
public function deleteUserConfig(string $userId, string $app, string $key): void;
/**
* Delete config values from all users linked to a specific config keys
*
* @param string $app id of the app
* @param string $key config key
*
* @since 31.0.0
*/
public function deleteKey(string $app, string $key): void;
/**
* delete all config keys linked to an app
*
* @param string $app id of the app
* @since 31.0.0
*/
public function deleteApp(string $app): void;
/**
* delete all config keys linked to a user
*
* @param string $userId id of the user
* @since 31.0.0
*/
public function deleteAllUserConfig(string $userId): void;
/**
* Clear the cache for a single user
*
* The cache will be rebuilt only the next time a user config is requested.
*
* @param string $userId id of the user
* @param bool $reload set to TRUE to refill cache instantly after clearing it
*
* @since 31.0.0
*/
public function clearCache(string $userId, bool $reload = false): void;
/**
* Clear the cache for all users.
* The cache will be rebuilt only the next time a user config is requested.
*
* @since 31.0.0
*/
public function clearCacheAll(): void;
}

79
lib/unstable/Config/ValueType.php

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace NCU\Config;
use NCU\Config\Exceptions\IncorrectTypeException;
use UnhandledMatchError;
/**
* Listing of available value type for typed config value
*
* @experimental 31.0.0
* @since 31.0.0
*/
enum ValueType: int {
/** @since 31.0.0 */
case MIXED = 0;
/** @since 31.0.0 */
case STRING = 1;
/** @since 31.0.0 */
case INT = 2;
/** @since 31.0.0 */
case FLOAT = 3;
/** @since 31.0.0 */
case BOOL = 4;
/** @since 31.0.0 */
case ARRAY = 5;
/**
* get ValueType from string
*
* @param string $definition
*
* @return self
* @throws IncorrectTypeException
* @since 31.0.0
*/
public static function fromStringDefinition(string $definition): self {
try {
return match ($definition) {
'mixed' => self::MIXED,
'string' => self::STRING,
'int' => self::INT,
'float' => self::FLOAT,
'bool' => self::BOOL,
'array' => self::ARRAY
};
} catch (\UnhandledMatchError) {
throw new IncorrectTypeException('unknown string definition');
}
}
/**
* get string definition for current enum value
*
* @return string
* @throws IncorrectTypeException
* @since 31.0.0
*/
public function getDefinition(): string {
try {
return match ($this) {
self::MIXED => 'mixed',
self::STRING => 'string',
self::INT => 'int',
self::FLOAT => 'float',
self::BOOL => 'bool',
self::ARRAY => 'array',
};
} catch (UnhandledMatchError) {
throw new IncorrectTypeException('unknown type definition ' . $this->value);
}
}
}

6
tests/lib/AllConfigTest.php

@ -317,8 +317,8 @@ class AllConfigTest extends \Test\TestCase {
// preparation - add something to the database // preparation - add something to the database
$data = [ $data = [
['userFetch', 'appFetch1', '123', 'value'],
['userFetch', 'appFetch1', '456', 'value'],
['userFetch8', 'appFetch1', '123', 'value'],
['userFetch8', 'appFetch1', '456', 'value'],
]; ];
foreach ($data as $entry) { foreach ($data as $entry) {
$this->connection->executeUpdate( $this->connection->executeUpdate(
@ -328,7 +328,7 @@ class AllConfigTest extends \Test\TestCase {
); );
} }
$value = $config->getUserKeys('userFetch', 'appFetch1');
$value = $config->getUserKeys('userFetch8', 'appFetch1');
$this->assertEquals(['123', '456'], $value); $this->assertEquals(['123', '456'], $value);
$this->assertIsString($value[0]); $this->assertIsString($value[0]);
$this->assertIsString($value[1]); $this->assertIsString($value[1]);

1836
tests/lib/Config/UserConfigTest.php
File diff suppressed because it is too large
View File

Loading…
Cancel
Save