Change setting base
This commit is contained in:
189
src/App/DesktopUserPreferenceRepository.php
Normal file
189
src/App/DesktopUserPreferenceRepository.php
Normal file
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
final class DesktopUserPreferenceRepository
|
||||
{
|
||||
private const TABLE_NAME = 'desktop_preferences_user_data';
|
||||
|
||||
private ?\PDO $pdo = null;
|
||||
private bool $schemaEnsured = false;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config
|
||||
*/
|
||||
public function __construct(private readonly array $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return $this->pdo() instanceof \PDO;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function read(string $userScope): ?array
|
||||
{
|
||||
$pdo = $this->pdo();
|
||||
if (!$pdo instanceof \PDO || $userScope === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->ensureSchema($pdo);
|
||||
|
||||
$statement = $pdo->prepare(
|
||||
'SELECT settings_json
|
||||
FROM ' . self::TABLE_NAME . '
|
||||
WHERE user_scope = :user_scope
|
||||
LIMIT 1'
|
||||
);
|
||||
$statement->execute(['user_scope' => $userScope]);
|
||||
$raw = $statement->fetchColumn();
|
||||
|
||||
if (!is_string($raw) || trim($raw) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode($raw, true);
|
||||
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
* @param array<string, mixed> $authUser
|
||||
*/
|
||||
public function write(string $userScope, array $settings, array $authUser): void
|
||||
{
|
||||
$pdo = $this->pdo();
|
||||
if (!$pdo instanceof \PDO || $userScope === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->ensureSchema($pdo);
|
||||
|
||||
$payload = [
|
||||
'user_scope' => $userScope,
|
||||
'username' => $this->limit((string) ($authUser['username'] ?? ''), 191),
|
||||
'subject_id' => $this->limit((string) ($authUser['sub'] ?? ''), 191),
|
||||
'settings_json' => json_encode($settings, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
|
||||
];
|
||||
|
||||
$driver = strtolower((string) $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME));
|
||||
if ($driver === 'mysql') {
|
||||
$statement = $pdo->prepare(
|
||||
'INSERT INTO ' . self::TABLE_NAME . ' (user_scope, username, subject_id, settings_json)
|
||||
VALUES (:user_scope, :username, :subject_id, :settings_json)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
username = VALUES(username),
|
||||
subject_id = VALUES(subject_id),
|
||||
settings_json = VALUES(settings_json),
|
||||
updated_at = CURRENT_TIMESTAMP'
|
||||
);
|
||||
$statement->execute($payload);
|
||||
return;
|
||||
}
|
||||
|
||||
$updated = $pdo->prepare(
|
||||
'UPDATE ' . self::TABLE_NAME . '
|
||||
SET username = :username,
|
||||
subject_id = :subject_id,
|
||||
settings_json = :settings_json,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE user_scope = :user_scope'
|
||||
);
|
||||
$updated->execute($payload);
|
||||
|
||||
if ($updated->rowCount() > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$insert = $pdo->prepare(
|
||||
'INSERT INTO ' . self::TABLE_NAME . ' (user_scope, username, subject_id, settings_json, created_at, updated_at)
|
||||
VALUES (:user_scope, :username, :subject_id, :settings_json, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)'
|
||||
);
|
||||
$insert->execute($payload);
|
||||
}
|
||||
|
||||
private function pdo(): ?\PDO
|
||||
{
|
||||
if ($this->pdo instanceof \PDO) {
|
||||
return $this->pdo;
|
||||
}
|
||||
|
||||
if (empty($this->config['enabled']) || !is_array($this->config['db'] ?? null) || $this->config['db'] === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->pdo = PdoFactory::createFromArray($this->config['db']);
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('[desktop-user-preferences] DB unavailable: ' . $exception->getMessage());
|
||||
$this->pdo = null;
|
||||
}
|
||||
|
||||
return $this->pdo;
|
||||
}
|
||||
|
||||
private function ensureSchema(\PDO $pdo): void
|
||||
{
|
||||
if ($this->schemaEnsured) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = strtolower((string) $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME));
|
||||
$sql = match ($driver) {
|
||||
'pgsql' => <<<SQL
|
||||
CREATE TABLE IF NOT EXISTS desktop_preferences_user_data (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_scope TEXT NOT NULL UNIQUE,
|
||||
username TEXT NULL,
|
||||
subject_id TEXT NULL,
|
||||
settings_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
SQL,
|
||||
'sqlite' => <<<SQL
|
||||
CREATE TABLE IF NOT EXISTS desktop_preferences_user_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_scope TEXT NOT NULL UNIQUE,
|
||||
username TEXT NULL,
|
||||
subject_id TEXT NULL,
|
||||
settings_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
SQL,
|
||||
default => <<<SQL
|
||||
CREATE TABLE IF NOT EXISTS desktop_preferences_user_data (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
user_scope VARCHAR(191) NOT NULL UNIQUE,
|
||||
username VARCHAR(191) NULL,
|
||||
subject_id VARCHAR(191) NULL,
|
||||
settings_json LONGTEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
SQL,
|
||||
};
|
||||
|
||||
$pdo->exec($sql);
|
||||
$this->schemaEnsured = true;
|
||||
}
|
||||
|
||||
private function limit(string $value, int $maxLength): string
|
||||
{
|
||||
$trimmed = trim($value);
|
||||
|
||||
if (function_exists('mb_substr')) {
|
||||
return mb_substr($trimmed, 0, $maxLength);
|
||||
}
|
||||
|
||||
return substr($trimmed, 0, $maxLength);
|
||||
}
|
||||
}
|
||||
107
src/App/PdoFactory.php
Normal file
107
src/App/PdoFactory.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
final class PdoFactory
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $db
|
||||
*/
|
||||
public static function createFromArray(array $db): \PDO
|
||||
{
|
||||
$driver = (string) ($db['driver'] ?? '');
|
||||
if ($driver === '') {
|
||||
throw new \RuntimeException('DB config missing "driver".');
|
||||
}
|
||||
|
||||
$dsn = match ($driver) {
|
||||
'mysql' => self::buildMysqlDsn($db),
|
||||
'pgsql' => self::buildPgsqlDsn($db),
|
||||
'sqlite' => self::buildSqliteDsn($db),
|
||||
default => throw new \RuntimeException('Unsupported PDO driver: ' . $driver),
|
||||
};
|
||||
|
||||
$pdo = new \PDO(
|
||||
$dsn,
|
||||
(string) ($db['user'] ?? ''),
|
||||
(string) ($db['password'] ?? ''),
|
||||
(array) ($db['options'] ?? [])
|
||||
);
|
||||
|
||||
if ($driver === 'pgsql' && !empty($db['schema'])) {
|
||||
$schema = preg_replace('/[^a-zA-Z0-9_]/', '', (string) $db['schema']);
|
||||
if ($schema !== null && $schema !== '') {
|
||||
$pdo->exec('SET search_path TO ' . $schema);
|
||||
}
|
||||
}
|
||||
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $db
|
||||
*/
|
||||
private static function buildMysqlDsn(array $db): string
|
||||
{
|
||||
if (empty($db['dbname'])) {
|
||||
throw new \RuntimeException('MySQL config missing "dbname".');
|
||||
}
|
||||
|
||||
$charset = (string) ($db['charset'] ?? 'utf8mb4');
|
||||
|
||||
if (!empty($db['unix_socket'])) {
|
||||
return sprintf(
|
||||
'mysql:unix_socket=%s;dbname=%s;charset=%s',
|
||||
(string) $db['unix_socket'],
|
||||
(string) $db['dbname'],
|
||||
$charset
|
||||
);
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
||||
(string) ($db['host'] ?? 'localhost'),
|
||||
(int) ($db['port'] ?? 3306),
|
||||
(string) $db['dbname'],
|
||||
$charset
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $db
|
||||
*/
|
||||
private static function buildPgsqlDsn(array $db): string
|
||||
{
|
||||
if (empty($db['dbname'])) {
|
||||
throw new \RuntimeException('PostgreSQL config missing "dbname".');
|
||||
}
|
||||
|
||||
$dsn = sprintf(
|
||||
'pgsql:host=%s;port=%d;dbname=%s',
|
||||
(string) ($db['host'] ?? 'localhost'),
|
||||
(int) ($db['port'] ?? 5432),
|
||||
(string) $db['dbname']
|
||||
);
|
||||
|
||||
if (isset($db['connect_timeout'])) {
|
||||
$dsn .= ';connect_timeout=' . max(1, (int) $db['connect_timeout']);
|
||||
}
|
||||
|
||||
return $dsn;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $db
|
||||
*/
|
||||
private static function buildSqliteDsn(array $db): string
|
||||
{
|
||||
$path = (string) ($db['path'] ?? '');
|
||||
if ($path === '') {
|
||||
throw new \RuntimeException('SQLite config missing "path".');
|
||||
}
|
||||
|
||||
return 'sqlite:' . $path;
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ final class UserSelfManagementService
|
||||
public function load(array $authUser, array $visibleApps, array $widgets, array $availableSkins): array
|
||||
{
|
||||
return $this->normalizeSettings(
|
||||
$this->store($this->storageScope($authUser))->read(),
|
||||
$this->readRawSettings($authUser),
|
||||
$authUser,
|
||||
$visibleApps,
|
||||
$widgets,
|
||||
@@ -60,7 +60,7 @@ final class UserSelfManagementService
|
||||
$normalized = $this->normalizeSettings($merged, $authUser, $visibleApps, $widgets, $availableSkins);
|
||||
$normalized['updated_at'] = gmdate(DATE_ATOM);
|
||||
|
||||
$this->store($this->storageScope($authUser))->write($normalized);
|
||||
$this->writeRawSettings($normalized, $authUser);
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
@@ -142,7 +142,7 @@ final class UserSelfManagementService
|
||||
'meta' => [
|
||||
'storage_scope' => $this->storageScope($authUser),
|
||||
'authenticated' => ($authUser['sub'] ?? '') !== '' || ($authUser['username'] ?? '') !== '',
|
||||
'sync_mode' => 'local-profile',
|
||||
'sync_mode' => $this->repository()->available() ? 'base-db-user-data' : 'local-fallback',
|
||||
'sync_targets' => [
|
||||
'ldap' => 'planned',
|
||||
'keycloak' => 'planned',
|
||||
@@ -162,11 +162,26 @@ final class UserSelfManagementService
|
||||
return $sanitized !== null && $sanitized !== '' ? $sanitized : 'guest';
|
||||
}
|
||||
|
||||
private function store(string $scope): JsonStore
|
||||
private function fileStore(string $scope): JsonStore
|
||||
{
|
||||
return new JsonStore($this->projectRoot . '/data/user-self-management/users/' . $scope . '.json');
|
||||
}
|
||||
|
||||
private function repository(): DesktopUserPreferenceRepository
|
||||
{
|
||||
static $repository = null;
|
||||
|
||||
if ($repository instanceof DesktopUserPreferenceRepository) {
|
||||
return $repository;
|
||||
}
|
||||
|
||||
$repository = new DesktopUserPreferenceRepository(
|
||||
ConfigLoader::load($this->projectRoot, 'base_db')
|
||||
);
|
||||
|
||||
return $repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
* @param array<string, mixed> $authUser
|
||||
@@ -236,6 +251,49 @@ final class UserSelfManagementService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $authUser
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function readRawSettings(array $authUser): array
|
||||
{
|
||||
$scope = $this->storageScope($authUser);
|
||||
$repository = $this->repository();
|
||||
|
||||
if ($repository->available()) {
|
||||
$stored = $repository->read($scope);
|
||||
if (is_array($stored)) {
|
||||
return $stored;
|
||||
}
|
||||
|
||||
$legacy = $this->fileStore($scope)->read();
|
||||
if ($legacy !== []) {
|
||||
$repository->write($scope, $legacy, $authUser);
|
||||
}
|
||||
|
||||
return $legacy;
|
||||
}
|
||||
|
||||
return $this->fileStore($scope)->read();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
* @param array<string, mixed> $authUser
|
||||
*/
|
||||
private function writeRawSettings(array $settings, array $authUser): void
|
||||
{
|
||||
$scope = $this->storageScope($authUser);
|
||||
$repository = $this->repository();
|
||||
|
||||
if ($repository->available()) {
|
||||
$repository->write($scope, $settings, $authUser);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->fileStore($scope)->write($settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $selected
|
||||
* @param array<int, string> $allowedIds
|
||||
|
||||
Reference in New Issue
Block a user