Files
fitme3070.pt/views/admin/events/edit.php
T
andreandClaude Opus 5.5 895b3d58d7 fix(segurança): lixeira de 30 dias, CSRF em todas as ações, IP real, sessão e uploads
Correções da auditoria de 24/09 (audits/fitme3070-auditoria-2026-09-24.html).

Lixeira
- Tudo o que é importante passa a soft delete (deleted_at + deleted_by):
  equipa, modalidades, eventos, mensalidades, galerias, imagens, horário,
  horas de funcionamento, inscrições em eventos e pedidos de inscrição.
- config/functions_trash.php: um registo por tipo; apagar, restaurar, listar
  e eliminar leem todos dele. Eliminar de vez só com 30 dias na lixeira —
  a condição está no WHERE do DELETE, um POST forjado não apaga nada.
- Gestão → Lixeira (views/admin/trash/index.php): lista única com quem e
  quando, restauro a qualquer momento.
- Imagens de galeria: o site lista a pasta, por isso o ficheiro passa para
  .trash/ (negado pelo .htaccess) e volta no restauro.
- As listagens e o site público filtram deleted_at (horário também filtra
  modalidades apagadas). Migração: database/migration_20260925_trash.sql
  (só acrescenta colunas; tem de ser aplicada antes deste código).

CSRF
- csrf_check() recusa qualquer pedido que não seja POST (405). Antes saía
  sem verificar nada em GET, e dez ações de apagar/restaurar eram GET.
- Os dez handlers passaram a POST com token; links viraram formulários.

Autenticação e sessão
- client_ip(): X-Real-IP / último X-Forwarded-For, só vindo de proxy privado
  com TRUSTED_PROXY. O throttle contava o IP do proxy (limite global).
- Throttle também por conta (hash do email), além do IP.
- Sem oráculo de tempo: login verifica contra um hash de referência quando
  a conta não existe; a recuperação deixa o email na fila.
- Cookie de sessão Secure/HttpOnly/SameSite=Lax e use_strict_mode.
- Definições de sistema só para sysadmin; autocomplete=username.

Servidor e uploads
- .htaccess: nosniff, Referrer-Policy, X-Frame-Options, Permissions-Policy,
  CSP (frame-ancestors, base-uri, object-src, form-action); nega parciais
  _*.php, PHP soltos do platform-tools e *.md; 404 própria.
- Uploads validados pelo conteúdo (finfo/getimagesize); SVG só sem scripts,
  handlers on*=, foreignObject ou hrefs externos.

Testado numa cópia da BD de produção (fitme_audit_test) com um contentor
temporário: 34/34 verificações HTTP ponta-a-ponta.

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

169 lines
8.4 KiB
PHP

<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$id = (int) ($_GET['id'] ?? 0);
if (!$id) { header('Location: index.php'); exit; }
// Restaurar só por POST + CSRF (o formulário aponta para ?restore=1).
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['restore']) || isset($_GET['restore']))) {
csrf_check();
db_events_restore($pdo, $id);
session()->setFlashdata('success', 'Evento restaurado.');
header('Location: ' . base_url('views/admin/events/edit.php?id=' . $id));
exit;
}
$item = db_events_get($pdo, $id);
if (!$item) { header('Location: index.php'); exit; }
// Delete a single lead.
if (isset($_POST['delete_lead'])) {
csrf_check();
db_event_lead_delete($pdo, (int) $_POST['delete_lead'], $id);
session()->setFlashdata('success', 'Inscrição removida — fica na lixeira 30 dias.');
header('Location: ' . base_url('views/admin/events/edit.php?id=' . $id . '#leads'));
exit;
}
$errors = [];
$data = $item;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_event'])) {
csrf_check();
$data = [
'title' => trim($_POST['title'] ?? ''),
'slug' => trim($_POST['slug'] ?? ''),
'subtitle' => trim($_POST['subtitle'] ?? ''),
'summary' => trim($_POST['summary'] ?? ''),
'description' => trim($_POST['description'] ?? ''),
'cor' => trim($_POST['cor'] ?? '#C2D500'),
'location' => trim($_POST['location'] ?? ''),
'event_starts_at' => trim($_POST['event_starts_at'] ?? ''),
'event_ends_at' => trim($_POST['event_ends_at'] ?? ''),
'publish_from' => trim($_POST['publish_from'] ?? ''),
'publish_until' => trim($_POST['publish_until'] ?? ''),
'is_active' => isset($_POST['is_active']) ? 1 : 0,
'cta_label' => trim($_POST['cta_label'] ?? ''),
'cta_url' => trim($_POST['cta_url'] ?? ''),
'show_lead_form' => isset($_POST['show_lead_form']) ? 1 : 0,
'hero_image' => $item['hero_image'],
];
if ($data['title'] === '') $errors[] = 'O título é obrigatório.';
if ($data['publish_from'] === '') $errors[] = 'A data de início da publicação é obrigatória.';
if ($data['publish_until'] === '') $errors[] = 'A data de fim da publicação é obrigatória.';
if ($data['publish_from'] !== '' && $data['publish_until'] !== ''
&& strtotime($data['publish_until']) < strtotime($data['publish_from'])) {
$errors[] = 'A data de fim da publicação não pode ser anterior à de início.';
}
// Hero: a new upload replaces the current image; an explicit "remover" clears it.
$uploaded = null;
if (!$errors) {
$hero_err = null;
$uploaded = events_image_upload($_FILES['hero_file'] ?? [], $hero_err);
if ($hero_err) $errors[] = $hero_err;
}
if (!$errors) {
if ($uploaded) {
events_image_remove($item['hero_image']);
$data['hero_image'] = $uploaded;
} elseif (!empty($_POST['remove_hero'])) {
events_image_remove($item['hero_image']);
$data['hero_image'] = '';
}
// Slug: keep the field's value (auto-regenerate from title only if emptied).
$data['slug'] = events_make_slug($pdo, $data['slug'] !== '' ? $data['slug'] : $data['title'], $id);
db_events_update($pdo, $id, $data);
session()->setFlashdata('success', 'Evento atualizado.');
header('Location: ' . base_url('views/admin/events/edit.php?id=' . $id));
exit;
}
// On error keep the existing slug for the form.
$data['slug'] = $item['slug'];
}
$leads = db_event_leads_list($pdo, $id);
$status = events_status($item);
$page_title = 'Editar Evento';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container" style="max-width:820px;">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Editar Evento</h1>
<div class="small text-muted">/evento/<?= htmlspecialchars($item['slug']) ?></div>
</div>
<div class="d-flex gap-2">
<?php if (events_is_live($item)): ?>
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('evento/' . rawurlencode($item['slug'])) ?>" target="_blank" rel="noopener"><i class="bi bi-box-arrow-up-right me-1"></i>Ver página</a>
<?php endif; ?>
<a class="btn btn-outline-secondary btn-sm" href="index.php"><i class="bi bi-arrow-left me-1"></i>Voltar</a>
</div>
</div>
<?php if ($item['deleted_at']): ?>
<div class="alert alert-warning d-flex justify-content-between align-items-center">
<span>Este evento está apagado.</span>
<form method="POST" action="<?= base_url('views/admin/events/edit.php?id=' . $id . '&restore=1') ?>" class="mb-0">
<?= csrf_field() ?><button class="btn btn-sm btn-info">Restaurar</button>
</form>
</div>
<?php endif; ?>
<?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
<form method="POST" enctype="multipart/form-data" class="card shadow-sm mb-4"><div class="card-body">
<?= csrf_field() ?>
<input type="hidden" name="save_event" value="1">
<div class="mb-3">
<label class="form-label">Slug (URL)</label>
<input class="form-control" name="slug" value="<?= htmlspecialchars($data['slug'] ?? '') ?>">
<div class="form-text">Deixe em branco para gerar a partir do título.</div>
</div>
<?php include __DIR__ . '/_form.php'; ?>
<div class="mt-4 d-flex gap-2">
<button type="submit" class="btn btn-primary">Atualizar</button>
<a class="btn btn-outline-secondary" href="index.php">Cancelar</a>
</div>
</div></form>
<!-- ── Inscrições (leads) ─────────────────────────────────────────────── -->
<div class="card shadow-sm" id="leads"><div class="card-body">
<h2 class="h5 mb-3">Inscrições <span class="badge bg-secondary"><?= count($leads) ?></span></h2>
<?php if (!$leads): ?>
<p class="text-muted mb-0">Ainda não há inscrições para este evento.</p>
<?php else: ?>
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="table-light"><tr>
<th>Data</th><th>Nome</th><th>Email</th><th>Telefone</th><th>Mensagem</th><th class="text-center">Consent.</th><th></th>
</tr></thead>
<tbody>
<?php foreach ($leads as $lead): ?>
<tr>
<td class="small text-nowrap"><?= htmlspecialchars(format_date_pt((string) $lead['created_at'])) ?></td>
<td><?= htmlspecialchars($lead['name']) ?></td>
<td class="small"><?php if ($lead['email']): ?><a href="mailto:<?= htmlspecialchars($lead['email']) ?>"><?= htmlspecialchars($lead['email']) ?></a><?php else: ?><span class="text-muted">—</span><?php endif; ?></td>
<td class="small"><?= $lead['phone'] !== '' ? htmlspecialchars($lead['phone']) : '<span class="text-muted">—</span>' ?></td>
<td class="small" style="max-width:240px;"><?= $lead['message'] !== '' ? nl2br(htmlspecialchars($lead['message'])) : '<span class="text-muted">—</span>' ?></td>
<td class="text-center"><?php if (!empty($lead['consent'])): ?><span class="badge bg-success" title="<?= htmlspecialchars($lead['ip'] ?? '') ?>"><i class="bi bi-check-lg"></i></span><?php else: ?><span class="badge bg-secondary">—</span><?php endif; ?></td>
<td>
<form method="POST" class="mb-0" onsubmit="return confirm('Remover esta inscrição?')">
<?= csrf_field() ?>
<button class="btn btn-sm btn-outline-danger" name="delete_lead" value="<?= (int) $lead['lead_id'] ?>"><i class="bi bi-trash"></i></button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div></div>
</div>
<?php include __DIR__ . '/../../../includes/footer.php'; ?>