Files
fitme3070.pt/config/functions_settings.php
T
andreandClaude Opus 5.5 0e8b53f620 feat(audit): platform-tools atualizado (12f26fd) e registo de auditoria ligado
- shared/platform-tools: ea3616a → 12f26fd (27 commits). Traz o módulo de
  audit (f761d99, o pin da frota), «manter sessão iniciada», o registo de
  segurança da frota (o gancho que o login já tinha passa a funcionar) e a
  correção do IP do cliente encontrada nesta auditoria (último X-Forwarded-For
  / X-Real-IP), promovida ao partilhado. client_ip() da app delega nele.
- config/functions_audit.php: audit() sobre platform_audit(); tabela
  audit_log criada no primeiro uso, segredos ocultados, nunca parte a ação.
- Registado: login, falha de login, bloqueio por excesso de tentativas,
  logout, pedidos de recuperação, mudança/definição de palavra-passe,
  registo e criação de utilizadores, convites, perfil (antes/depois), todas
  as definições (db_update_setting, com valor anterior), cada passo da
  lixeira (apagar, restaurar, eliminar de vez) e ações nas mensagens.
- Sistema → Auditoria (views/sysadmin/audit.php), só sysadmin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 07:28:13 +01:00

108 lines
3.6 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 {
// Valor anterior para o audit (os segredos são ocultados pelo módulo, pelo
// nome da chave: *password*, *token*, *key*, *secret*).
$old = null;
try {
$o = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
$o->execute([$key]);
$old = $o->fetchColumn();
$old = $old === false ? null : (string) $old;
} catch (Throwable $e) {}
$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();
if ($old !== $value && function_exists('platform_audit')) {
platform_audit($pdo, 'settings.update', [
'target_type' => 'setting', 'target_id' => $key, 'target_label' => $key,
'changes' => [$key => ['antes' => $old, 'depois' => $value]],
]);
}
}