Files
fitme3070.pt/config/functions_settings.php
T
andreandClaude Opus 4.8 e68d357177 Initial import of fitme3070.pt platform
Plain-PHP fleet platform with id.andmore.pt SSO. Wires shared/platform-tools
as a submodule (platform_update, backups, git/migration tools) like the other
platforms.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-12 10:44:58 +01:00

92 lines
2.9 KiB
PHP

<?php
// ─── DB-backed system settings with file-based cache ─────────────────────────
//
// Settings live in the `system_settings` table (key→value). To avoid a query
// on every page load, the full set is cached as a PHP array literal under
// config/cache/settings.cache.php — read via require, served from opcache
// in memory. The cache is invalidated (file deleted) on every db_update_setting().
//
// Public API:
// setting($key, $default = null) — cached read
// settings_all() — cached array
// db_get_all_settings($pdo) — bypasses cache
// db_update_setting($pdo, $key, $value, $userId = null) — UPSERT + invalidate
//
// $pdo is read from the global scope only by db_*() helpers; setting() and
// settings_all() never touch the DB once the cache exists.
function _settings_cache_path(): string {
return __DIR__ . '/cache/settings.cache.php';
}
function settings_cache_clear(): void {
$path = _settings_cache_path();
if (is_file($path)) {
@unlink($path);
}
}
function settings_cache_write(array $data): void {
$path = _settings_cache_path();
$dir = dirname($path);
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$tmp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp';
$code = "<?php\nreturn " . var_export($data, true) . ";\n";
if (@file_put_contents($tmp, $code, LOCK_EX) === false) {
return;
}
@rename($tmp, $path);
if (function_exists('opcache_invalidate')) {
@opcache_invalidate($path, true);
}
}
function db_get_all_settings(PDO $pdo): array {
$rows = $pdo->query("SELECT setting_key, setting_value FROM system_settings")
->fetchAll(PDO::FETCH_KEY_PAIR);
return $rows ?: [];
}
function settings_cache_load(): array {
static $loaded = null;
if ($loaded !== null) {
return $loaded;
}
$path = _settings_cache_path();
if (is_file($path)) {
$data = @include $path;
if (is_array($data)) {
return $loaded = $data;
}
}
global $pdo;
if (!($pdo instanceof PDO)) {
return $loaded = [];
}
$data = db_get_all_settings($pdo);
settings_cache_write($data);
return $loaded = $data;
}
function settings_all(): array {
return settings_cache_load();
}
function setting(string $key, $default = null) {
$data = settings_cache_load();
return array_key_exists($key, $data) ? $data[$key] : $default;
}
function db_update_setting(PDO $pdo, string $key, string $value, ?int $userId = null): void {
$s = $pdo->prepare(
"INSERT INTO system_settings (setting_key, setting_value, updated_by)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value),
updated_by = VALUES(updated_by)"
);
$s->execute([$key, $value, $userId]);
settings_cache_clear();
}