Files
fitme3070.pt/config/env.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

69 lines
3.1 KiB
PHP

<?php
// ─── .env loader + env() helper ──────────────────────────────────────────────
//
// Lightweight, dependency-free reader for KEY=value files. Loaded by
// config/db.php BEFORE any other include so credentials and APP_ENV are
// available everywhere. Real environment variables (PHP-FPM pool, Apache
// SetEnv, shell exports) win over .env values — never overwritten.
//
// Format: one KEY=value per line, # for comments, optional surrounding quotes.
function env_load(string $path): void {
if (!is_file($path)) return;
// No is_readable() pre-check: it returns false negatives on Windows
// network mounts. Attempt the read and report only a real failure.
$lines = @file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
error_log("env_load: .env file exists at {$path} but could not be read by the PHP process. Fix with: chmod 640 {$path}");
return;
}
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') continue;
if (strpos($line, '=') === false) continue;
[$k, $v] = array_pad(explode('=', $line, 2), 2, '');
$k = trim($k);
if ($k === '') continue;
// Strip inline comments only when value isn't quoted.
$v = trim($v);
if ($v !== '' && $v[0] !== '"' && $v[0] !== "'") {
$hash = strpos($v, ' #');
if ($hash !== false) $v = rtrim(substr($v, 0, $hash));
}
$v = trim($v, " \"'");
// Don't overwrite real environment variables — they take precedence.
if (getenv($k) === false) {
putenv("$k=$v");
$_ENV[$k] = $v;
}
}
}
function env(string $key, $default = null) {
$v = getenv($key);
return $v === false ? $default : $v;
}
// IP do visitante — a regra vive no platform-tools (platform_client_ip():
// X-Real-IP, senão o último X-Forwarded-For, e só vindo do proxy com
// TRUSTED_PROXY). Em produção o Apache só vê o Nginx Proxy Manager
// (REMOTE_ADDR = 172.18.0.2 para toda a gente); o throttle do login contava
// tudo contra esse IP. A correção nasceu aqui e foi promovida ao partilhado
// (platform-tools 12f26fd), para throttle, audit e IP ban usarem a mesma.
require_once __DIR__ . '/../shared/platform-tools/functions_client_ip.php';
function client_ip(): string {
return platform_client_ip() ?? '0.0.0.0';
}
// True when the current request is HTTPS — including when TLS terminates at a
// reverse proxy. Behind a proxy you MUST set TRUSTED_PROXY=true in .env or the
// X-Forwarded-Proto header is ignored (otherwise any client could spoof it).
function request_is_https(): bool {
if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') return true;
if (($_SERVER['SERVER_PORT'] ?? '') === '443') return true;
$trusted = filter_var(env('TRUSTED_PROXY', 'false'), FILTER_VALIDATE_BOOLEAN);
if ($trusted && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') return true;
return false;
}