Files
fitme3070.pt/config/functions_settings.php
andreandClaude Opus 5.5 04c8c83e66 feat: aulas experimentais guardadas, anti-spam partilhado nos formulários, audit das escritas
- Pedido de aula experimental passa a ficar em trial_leads (por ginásio)
  ANTES do email: sem SMTP o visitante já não vê «erro» e o pedido não se
  perde. Gestão → Aulas experimentais: estados, notas, CSV (auditado),
  apagar para a lixeira; aviso «sem email» quando o aviso não saiu.
- Aula experimental, inscrição e eventos usam o anti-spam do platform-tools
  (honeypot, carimbo assinado com tempo mínimo, prova de JS, limite por IP,
  pontuação de conteúdo) e o bloqueio de IP, em vez de honeypots locais.
  Recusas ficam em blocked_submissions; resposta igual à de sucesso.
  Falha aberto se o módulo rebentar.
- Checkbox de consentimento da aula experimental passa a ser guardada.
- Audit das escritas de conteúdo: criar/editar equipa, modalidades,
  eventos, mensalidades, pedidos de inscrição, galerias, horário (incl.
  arrastar no calendário), horas, contactos e ginásios, com antes/depois
  campo a campo (audit_row/audit_change). Exportação CSV de inscrições
  auditada.
- .table-responsive em todas as tabelas do backoffice.
- Migração: database/migration_20260926_trial_leads.sql (só cria tabelas).

Testado numa cópia da BD de produção: 63/63 verificações HTTP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:33:24 +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 => ['from' => $old, 'to' => $value]],
]);
}
}