Files
xamxam/app/public/admin/actions/settings.php
Pontoporeia d588ae004d Reintroduce TFE duration metadata: DB columns, form fields, controllers, views, and migration
Add 'unsafe-eval' to CSP script-src directives (htmx requires Function())
2026-06-15 15:56:52 +02:00

175 lines
7.0 KiB
PHP

<?php
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();
if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
|| !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
App::flash('error', "Erreur de sécurité : token invalide.");
header('Location: /admin/parametres.php');
exit;
}
require_once APP_ROOT . '/src/Database.php';
require_once APP_ROOT . '/src/SmtpRelay.php';
require_once APP_ROOT . '/src/PeerTubeService.php';
require_once APP_ROOT . '/src/AdminLogger.php';
$db = new Database();
$logger = AdminLogger::make();
$isHxRequest = (isset($_SERVER['HTTP_HX_REQUEST']) && $_SERVER['HTTP_HX_REQUEST'] === 'true');
$section = $_POST['section'] ?? '';
/**
* Return an HTML toast fragment for HTMX responses and exit.
* The fragment auto-dismisses after 3 seconds via a script at the end.
*/
function hxToastSuccess(string $message): never {
$id = 'toast-' . bin2hex(random_bytes(4));
http_response_code(200);
echo '<div class="toast toast--success" role="status" id="' . $id . '">' .
'<span class="toast__icon" aria-hidden="true">✓</span> ' .
htmlspecialchars($message) . '</div>' .
'<script>' .
'(function(){console.log("[settings-toast] success: ' . htmlspecialchars(addslashes($message), ENT_QUOTES) . '");' .
'var el=document.getElementById("' . $id . '");' .
'if(el){setTimeout(function(){el.remove();console.log("[settings-toast] removed ' . $id . '")},3000)}' .
'})()</script>';
exit;
}
function hxToastError(string $message): never {
$id = 'toast-' . bin2hex(random_bytes(4));
http_response_code(200);
echo '<div class="toast toast--error" role="alert" id="' . $id . '">' .
'<span class="toast__icon" aria-hidden="true">⚠</span> ' .
htmlspecialchars($message) . '</div>' .
'<script>' .
'(function(){console.warn("[settings-toast] error: ' . htmlspecialchars(addslashes($message), ENT_QUOTES) . '");' .
'var el=document.getElementById("' . $id . '");' .
'if(el){setTimeout(function(){el.remove();console.log("[settings-toast] removed ' . $id . '")},3000)}' .
'})()</script>';
exit;
}
if ($section === 'formulaire_restrictions') {
// HTMX may not send unchecked checkboxes even with hidden 0-value inputs;
// missing key means unchecked → treat as '0'.
$newValue = empty($_POST['restricted_files_enabled']) ? '0' : '1';
$db->setSetting('restricted_files_enabled', $newValue);
$logger->logFormSettingsUpdate(['restricted_files_enabled' => $newValue]);
if ($isHxRequest) {
hxToastSuccess('Restrictions d\'accès aux fichiers mises à jour.');
} else {
App::flash('success', "Paramètres mis à jour.");
}
} elseif ($section === 'formulaire_acces') {
$allowed = [
'access_type_libre_enabled',
'access_type_interne_enabled',
'access_type_interdit_enabled',
];
$newValues = [];
foreach ($allowed as $key) {
$value = empty($_POST[$key]) ? '0' : '1';
$db->setSetting($key, $value);
$newValues[$key] = $value;
}
$logger->logFormSettingsUpdate($newValues);
if ($isHxRequest) {
hxToastSuccess("Degrés d'ouverture mis à jour.");
} else {
App::flash('success', "Degrés d'ouverture mis à jour.");
}
} elseif ($section === 'objet_types') {
$newValues = [
'objet_these_enabled' => empty($_POST['objet_these_enabled']) ? '0' : '1',
'objet_frart_enabled' => empty($_POST['objet_frart_enabled']) ? '0' : '1',
];
$db->setSetting('objet_these_enabled', $newValues['objet_these_enabled']);
$db->setSetting('objet_frart_enabled', $newValues['objet_frart_enabled']);
$logger->logObjetTypesUpdate($newValues);
if ($isHxRequest) {
hxToastSuccess('Types de travaux mis à jour.');
} else {
App::flash('success', "Types de travaux mis à jour.");
}
} elseif ($section === 'smtp') {
$smtpData = [
'host' => $_POST['smtp_host'] ?? '',
'port' => $_POST['smtp_port'] ?? 587,
'encryption' => $_POST['smtp_encryption'] ?? 'tls',
'username' => $_POST['smtp_username'] ?? '',
'from_email' => $_POST['smtp_username'] ?? '', // same as username
'from_name' => $_POST['smtp_from_name'] ?? 'XAMXAM',
'notify_email' => $_POST['smtp_notify_email'] ?? '',
];
// Only update password when user actually typed something.
$pwd = $_POST['smtp_password'] ?? '';
if ($pwd !== '') {
$smtpData['password'] = $pwd;
}
SmtpRelay::updateSettings($db, $smtpData);
// Immediately probe the server to validate credentials
$test = SmtpRelay::test($db);
$logger->logSmtpUpdate($test['ok']);
if ($test['ok']) {
App::flash('success', "Paramètres SMTP mis à jour — connexion validée ✓");
} else {
App::flash('error', "Paramètres sauvegardés, mais le test de connexion a échoué : " . $test['error']);
if ($test['field'] !== null) {
$_SESSION['_flash_smtp_field'] = $test['field'];
}
}
} elseif ($section === 'peertube') {
// Feature flag
$enabled = isset($_POST['peertube_upload_enabled']) ? '1' : '0';
$db->setSetting('peertube_upload_enabled', $enabled);
// PeerTube-specific settings (auth uses SMTP credentials)
$data = [
'instance_url' => $_POST['peertube_instance_url'] ?? '',
'channel_name' => $_POST['peertube_channel_name'] ?? '',
'privacy' => $_POST['peertube_privacy'] ?? 1,
];
PeerTubeService::updateSettings($db, $data);
$logger->logPeerTubeUpdate($enabled === '1');
App::flash('success', 'Paramètres PeerTube mis à jour.');
} elseif ($section === 'tfe_messages') {
if (isset($_POST['tfe_restricted_message'])) {
$db->setSetting('tfe_restricted_message', $_POST['tfe_restricted_message']);
}
if (isset($_POST['tfe_forbidden_message'])) {
$db->setSetting('tfe_forbidden_message', $_POST['tfe_forbidden_message']);
}
if ($isHxRequest) {
hxToastSuccess('Messages TFE mis à jour.');
} else {
App::flash('success', "Messages TFE mis à jour.");
}
} else {
App::flash('error', "Section inconnue.");
}
// Centralised HTMX response — each section above already called hxToast* and exited.
// If we get here as an HTMX request from an unhandled section, return empty 200.
if ($isHxRequest) {
http_response_code(200);
exit;
}
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// Redirect back to wherever the form came from, defaulting to parametres
$redirect = '/admin/parametres.php';
if (in_array($section, ['formulaire_acces', 'objet_types'], true)) {
$redirect = '/admin/contenus.php';
} elseif ($section === 'formulaire_restrictions') {
$redirect = '/admin/acces.php';
} elseif ($section === 'tfe_messages') {
$redirect = '/admin/acces.php';
}
header('Location: ' . $redirect);
exit;