Fix/404 tux pattes #3

Merged
BlackAngelTV merged 66 commits from fix/404-tux-pattes into main 2026-10-02 21:00:06 +02:00
3 changed files with 351 additions and 25 deletions
Showing only changes of commit 8a7e83cd01 - Show all commits

No files matched your search

+3
View File
@@ -18,5 +18,8 @@ api/bugs/data/*.db-shm
*.sqlite-wal
*.sqlite-shm
# Images des paquets envoyées via l'admin (données hébergées, pas du code)
p/assets/img/packages/
# Cache HTTP local du site (releases Gitea/GitHub, généré par inc/site.php)
cache/
+346 -24
View File
@@ -141,6 +141,84 @@ function screens_from_lines(string $raw): array
return $out;
}
/* ── Paquets : images (max 5, stockées sous p/assets/img/packages/) ── */
define('FWS_PKG_IMG_MAX', 5);
function fws_admin_packages_img_dir(): string
{
/* __DIR__ = admin/bugs → racine du site = deux niveaux au-dessus. */
return dirname(__DIR__, 2) . '/p/assets/img/packages';
}
/** Src web « /p/assets/img/packages/… » si l'image est dans le dossier géré, sinon null. */
function fws_admin_managed_img_web(string $src): ?string
{
$prefix = '/p/assets/img/packages/';
if (strncmp($src, $prefix, strlen($prefix)) !== 0) {
return null;
}
$name = basename($src);
if ($name === '' || str_contains($name, '..')) {
return null;
}
return $prefix . $name;
}
/** Supprime une image gérée si plus aucun paquet ne la référence. */
function fws_admin_delete_img_if_unused(PDO $pdo, string $src): void
{
$web = fws_admin_managed_img_web($src);
if ($web === null) {
return; /* image hors du dossier géré (chemin manuel) : on n'y touche pas */
}
$st = $pdo->prepare('SELECT COUNT(*) FROM packages WHERE screens LIKE :pat');
$st->execute([':pat' => '%' . $web . '%']);
if ((int) $st->fetchColumn() > 0) {
return; /* encore utilisée par un autre paquet */
}
$abs = dirname(__DIR__, 2) . $web;
if (is_file($abs)) {
@unlink($abs);
}
}
/** Valide et stocke un upload d'image de paquet. Renvoie le src web.
* Lance RuntimeException avec un message clair si le fichier est refusé. */
function fws_admin_store_screen_upload(array $file, string $slug): string
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('Envoi impossible (code ' . (string) ($file['error'] ?? '?') . ').');
}
if (($file['size'] ?? 0) <= 0 || ($file['size'] ?? 0) > 2 * 1024 * 1024) {
throw new RuntimeException('« ' . (string) ($file['name'] ?? '?') . ' » dépasse 2 Mo.');
}
$ext = strtolower(pathinfo((string) ($file['name'] ?? ''), PATHINFO_EXTENSION));
$allowed = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp', 'gif' => 'image/gif'];
if (!isset($allowed[$ext])) {
throw new RuntimeException('« ' . (string) ($file['name'] ?? '?') . ' » : format non supporté (jpg, png, webp, gif).');
}
$info = @getimagesize((string) ($file['tmp_name'] ?? ''));
if ($info === false || ($info['mime'] ?? '') !== $allowed[$ext]) {
throw new RuntimeException('« ' . (string) ($file['name'] ?? '?') . ' » n\'est pas une image valide.');
}
$dir = fws_admin_packages_img_dir();
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
throw new RuntimeException('Impossible de créer le dossier des images.');
}
@chmod($dir, 0777); /* bind-mount Docker : tout appartient à root */
$base = trim(preg_replace('/[^a-zA-Z0-9-]+/', '-', $slug) ?? '', '-');
if ($base === '') {
$base = 'paquet';
}
$name = $base . '-' . bin2hex(random_bytes(8)) . '.' . $ext;
if (!@move_uploaded_file((string) ($file['tmp_name'] ?? ''), $dir . '/' . $name)) {
throw new RuntimeException('Échec de l\'enregistrement de « ' . (string) ($file['name'] ?? '?') . ' ».');
}
@chmod($dir . '/' . $name, 0644);
return '/p/assets/img/packages/' . $name;
}
function lines_from_links(array $links): string
{
$lines = [];
@@ -293,31 +371,139 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$error = 'Le nom du paquet est obligatoire.';
} else {
$pdo = fws_bugs_db();
$savedId = fws_packages_save($pdo, [
'id' => (int) ($_POST['pkg_id'] ?? 0),
'slug' => (string) ($_POST['slug'] ?? ''),
'name' => $name,
'tagline' => (string) ($_POST['tagline'] ?? ''),
'description' => (string) ($_POST['description'] ?? ''),
'since' => (string) ($_POST['since'] ?? ''),
'since_label' => (string) ($_POST['since_label'] ?? ''),
'latest_name' => (string) ($_POST['latest_name'] ?? ''),
'latest_date' => (string) ($_POST['latest_date'] ?? ''),
'links' => links_from_lines((string) ($_POST['links'] ?? '')),
'screens' => screens_from_lines((string) ($_POST['screens'] ?? '')),
'changelog' => changelog_from_lines((string) ($_POST['changelog'] ?? '')),
]);
$wasEdit = (int) ($_POST['pkg_id'] ?? 0) > 0;
$_SESSION['flash'] = ['ok' => $wasEdit
? "Paquet « $name » mis à jour."
: "Paquet « $name » créé."];
header('Location: index.php?view=packages');
exit;
/* Captures d'écran : existantes conservées (avec légendes
éditées) + nouveaux envois, 5 maximum par paquet. */
$pkgIdPost = (int) ($_POST['pkg_id'] ?? 0);
$oldRow = null;
if ($pkgIdPost > 0) {
$stOld = $pdo->prepare('SELECT screens FROM packages WHERE id = :id');
$stOld->execute([':id' => $pkgIdPost]);
$oldRow = $stOld->fetch() ?: null;
}
$oldScreens = $oldRow !== null
? (array) (json_decode((string) $oldRow['screens'], true) ?: [])
: [];
$keep = array_fill_keys((array) ($_POST['keep_screens'] ?? []), true);
$captions = (array) ($_POST['captions'] ?? []);
$screens = [];
$removedSrcs = [];
foreach ($oldScreens as $os) {
$src = (string) ($os['src'] ?? '');
if ($src === '' || !isset($keep[$src])) {
/* Décochée : le fichier sera supprimé APRÈS la mise à
jour en base (sinon elle le compte encore en usage). */
if ($src !== '') {
$removedSrcs[] = $src;
}
continue;
}
$cap = isset($captions[$src]) ? trim((string) $captions[$src]) : '';
$screens[] = [
'src' => $src,
'alt' => ($os['alt'] ?? '') !== '' ? (string) $os['alt'] : $name,
'caption' => $cap !== '' ? $cap : null,
];
}
$newFiles = (array) ($_FILES['new_screens'] ?? []);
$countNew = is_array($newFiles['name'] ?? null) ? count($newFiles['name']) : 0;
/* Indices des fichiers réellement envoyés (pas les slots vides). */
$uploadIdx = [];
for ($i = 0; $i < $countNew; $i++) {
if ((int) ($newFiles['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE
|| (string) ($newFiles['name'][$i] ?? '') !== '') {
$uploadIdx[] = $i;
}
}
/* Limite vérifiée AVANT tout stockage : refus clair, rien n'est
écrit (ni base ni fichiers) si le total dépasse la limite. */
if (count($screens) + count($uploadIdx) > FWS_PKG_IMG_MAX) {
$error = 'Maximum ' . FWS_PKG_IMG_MAX . ' images par paquet : '
. count($screens) . ' conservée(s) + ' . count($uploadIdx)
. ' envoyée(s). Retirez-en d\'abord.';
} else {
$slugPost = trim((string) ($_POST['slug'] ?? ''));
if ($slugPost === '') {
$slugPost = trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $name) ?? '', '-');
}
$storedThisRequest = [];
foreach ($uploadIdx as $i) {
try {
$src = fws_admin_store_screen_upload([
'name' => (string) $newFiles['name'][$i],
'type' => (string) ($newFiles['type'][$i] ?? ''),
'tmp_name' => (string) ($newFiles['tmp_name'][$i] ?? ''),
'error' => (int) ($newFiles['error'][$i] ?? UPLOAD_ERR_NO_FILE),
'size' => (int) ($newFiles['size'][$i] ?? 0),
], $slugPost);
$storedThisRequest[] = $src;
$screens[] = ['src' => $src, 'alt' => $name, 'caption' => null];
} catch (RuntimeException $ex) {
/* Un fichier invalide annule tout : on ne garde pas
des images déjà stockées mais non enregistrées. */
foreach ($storedThisRequest as $tmpSrc) {
@unlink(dirname(__DIR__, 2) . $tmpSrc);
}
$error = $ex->getMessage();
break;
}
}
}
if ($error === null) {
fws_packages_save($pdo, [
'id' => $pkgIdPost,
'slug' => (string) ($_POST['slug'] ?? ''),
'name' => $name,
'tagline' => (string) ($_POST['tagline'] ?? ''),
'description' => (string) ($_POST['description'] ?? ''),
'since' => (string) ($_POST['since'] ?? ''),
'since_label' => (string) ($_POST['since_label'] ?? ''),
'latest_name' => (string) ($_POST['latest_name'] ?? ''),
'latest_date' => (string) ($_POST['latest_date'] ?? ''),
'links' => links_from_lines((string) ($_POST['links'] ?? '')),
'screens' => $screens,
'changelog' => changelog_from_lines((string) ($_POST['changelog'] ?? '')),
]);
/* La base est à jour : on peut maintenant supprimer les
fichiers décochés devenus orphelins. */
foreach ($removedSrcs as $rsrc) {
fws_admin_delete_img_if_unused($pdo, $rsrc);
}
$wasEdit = $pkgIdPost > 0;
$_SESSION['flash'] = ['ok' => $wasEdit
? "Paquet « $name » mis à jour."
: "Paquet « $name » créé."];
header('Location: index.php?view=packages');
exit;
}
}
} elseif ($action === 'pkg_delete') {
$pkgId = (int) ($_POST['pkg_id'] ?? 0);
$pdo = fws_bugs_db();
/* On note les images du paquet, on supprime la ligne, puis on
nettoie les fichiers devenus orphelins (la base ne doit plus
les référencer au moment de la vérification). */
$stDel = $pdo->prepare('SELECT screens FROM packages WHERE id = :id');
$stDel->execute([':id' => $pkgId]);
$rowDel = $stDel->fetch();
$orphanSrcs = [];
if ($rowDel !== false) {
foreach ((array) (json_decode((string) $rowDel['screens'], true) ?: []) as $os) {
$s = (string) ($os['src'] ?? '');
if ($s !== '') {
$orphanSrcs[] = $s;
}
}
}
fws_packages_delete($pdo, $pkgId);
foreach ($orphanSrcs as $osrc) {
fws_admin_delete_img_if_unused($pdo, $osrc);
}
$_SESSION['flash'] = ['ok' => "Paquet #$pkgId supprimé."];
header('Location: index.php?view=packages');
exit;
@@ -499,6 +685,63 @@ input[type=text], input[type=password], input[type=date], textarea {
}
textarea { resize: vertical; min-height: 70px; }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
/* ── Picker d'images des paquets ── */
.pkg-screens-picker {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 10px;
margin: 4px 0 6px;
}
.pkg-shot {
margin: 0;
border: 1px solid #1e293b;
border-radius: 10px;
overflow: hidden;
background: #0f172a;
display: grid;
gap: 4px;
padding: 6px;
}
.pkg-shot img {
width: 100%;
height: 70px;
object-fit: cover;
border-radius: 6px;
display: block;
}
.pkg-shot-keep {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: .72rem;
color: #94a3b8;
cursor: pointer;
}
.pkg-shot-keep input { accent-color: #0284c7; }
.pkg-shot input[type="text"] {
font-size: .75rem;
padding: 3px 6px;
}
.pkg-shot-add {
display: grid;
place-content: center;
justify-items: center;
gap: 2px;
min-height: 118px;
border-style: dashed;
cursor: pointer;
}
.pkg-shot-add:hover { border-color: #0284c7; }
.pkg-shot-plus { font-size: 1.6rem; color: #38bdf8; cursor: pointer; }
.pkg-shot-label {
font-size: .75rem;
color: #94a3b8;
text-align: center;
cursor: pointer;
}
.pkg-shot-label small { color: #64748b; }
.pkg-shot label { color: inherit; }
label { font-size: .85rem; color: #cbd5e1; }
.back { margin-bottom: 12px; display: inline-block; }
.pager { display: flex; gap: 8px; margin-top: 16px; }
@@ -773,7 +1016,13 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
'links' => '[]', 'screens' => '[]', 'changelog' => '[]',
];
$fLinks = lines_from_links((array) (json_decode((string) $form['links'], true) ?: []));
$fScreens = lines_from_screens((array) (json_decode((string) $form['screens'], true) ?: []));
/* Captures actuelles du paquet (picker d'images). */
$formScreensData = [];
foreach ((array) (json_decode((string) $form['screens'], true) ?: []) as $fsd) {
if (is_array($fsd) && (string) ($fsd['src'] ?? '') !== '') {
$formScreensData[] = $fsd;
}
}
$fChangelog = lines_from_changelog((array) (json_decode((string) $form['changelog'], true) ?: []));
?>
@@ -782,7 +1031,7 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
<?php if ($editing !== null): ?><p style="font-size:.85rem;color:#94a3b8"><a href="index.php?view=packages">← Annuler la modification</a></p><?php endif; ?>
<p style="font-size:.85rem;color:#94a3b8">Les champs « une ligne par entrée » utilisent le format <code>Label | URL</code> (liens),
<code>Version | Date | Notes</code> (historique) et <code>src | alt | légende</code> (captures).</p>
<form method="post" style="display:grid;gap:2px;max-width:680px">
<form method="post" enctype="multipart/form-data" style="display:grid;gap:2px;max-width:680px">
<input type="hidden" name="action" value="pkg_save">
<input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
<input type="hidden" name="pkg_id" value="<?= (int) $form['id'] ?>">
@@ -822,8 +1071,24 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
<textarea id="pkg_links" name="links" rows="3" placeholder="Gitea | https://gitea.nocode-var.tech/FWS/FWS-PacManage"><?= h($fLinks) ?></textarea>
<label for="pkg_changelog">Historique — une ligne par version : <code>Version | Date | Notes</code></label>
<textarea id="pkg_changelog" name="changelog" rows="5" placeholder="V1.2.1 | 2026-08-29 | Correction de bugs"><?= h($fChangelog) ?></textarea>
<label for="pkg_screens">Captures d'écran — une ligne : <code>src | alt | légende</code></label>
<textarea id="pkg_screens" name="screens" rows="2" placeholder="/p/assets/img/… | Alt | Légende"><?= h($fScreens) ?></textarea>
<label>Captures d'écran (<?= count($formScreensData) ?>/<?= FWS_PKG_IMG_MAX ?>) — décochez pour retirer</label>
<div class="pkg-screens-picker">
<?php $remaining = FWS_PKG_IMG_MAX - count($formScreensData); foreach ($formScreensData as $fs): $src = (string) ($fs['src'] ?? ''); if ($src === '') continue; ?>
<figure class="pkg-shot">
<img src="<?= h($src) ?>" alt="">
<label class="pkg-shot-keep"><input type="checkbox" name="keep_screens[]" value="<?= h($src) ?>" checked> garder</label>
<input type="text" name="captions[<?= h($src) ?>]" value="<?= h((string) ($fs['caption'] ?? '')) ?>" placeholder="Légende (optionnelle)">
</figure>
<?php endforeach; ?>
<?php if ($remaining > 0): ?>
<figure class="pkg-shot pkg-shot-add">
<label for="pkg_new_screens" class="pkg-shot-plus" title="Ajouter des images">+</label>
<input type="file" id="pkg_new_screens" name="new_screens[]" accept="image/png,image/jpeg,image/webp,image/gif" multiple style="display:none">
<label for="pkg_new_screens" class="pkg-shot-label">Ajouter…<br><small><?= $remaining ?> restante(s)</small></label>
</figure>
<?php endif; ?>
</div>
<small id="pkg-new-hint" style="color:#94a3b8;font-size:.78rem">JPG / PNG / WebP / GIF — 2 Mo max par image, <?= FWS_PKG_IMG_MAX ?> images max par paquet. Elles sont servies sur tout le site (cartes, page détail, menu).</small>
<button class="btn primary" type="submit" style="justify-self:start;margin-top:4px">💾 Enregistrer</button>
</form>
</div>
@@ -940,5 +1205,62 @@ table.list th { color: #94a3b8; font-size: .72rem; text-transform: uppercase; le
<?php endif; /* fin espace admin */ ?>
</div>
<script>
/* Picker d'images des paquets : aperçu immédiat des fichiers choisis,
limite dure au nombre maximum autorisé. */
(function () {
var picker = document.querySelector('.pkg-screens-picker');
var input = document.getElementById('pkg_new_screens');
if (!picker || !input) return;
var addFigure = input.closest('.pkg-shot-add');
var existing = picker.querySelectorAll('.pkg-shot:not(.pkg-shot-add)').length;
var max = <?= (int) FWS_PKG_IMG_MAX ?>;
var hint = document.getElementById('pkg-new-hint');
var hintText = hint ? hint.textContent : '';
input.addEventListener('change', function () {
var room = max - existing;
var files = Array.prototype.slice.call(input.files || []);
if (files.length > room) {
alert('Maximum ' + max + ' images par paquet (' + room + ' restante(s)).');
input.value = '';
return;
}
/* Retire l'ancien aperçu puis montre les nouveaux. */
picker.querySelectorAll('.pkg-shot-preview').forEach(function (n) { n.remove(); });
files.forEach(function (f) {
var fig = document.createElement('figure');
fig.className = 'pkg-shot pkg-shot-preview';
var img = document.createElement('img');
img.alt = f.name;
img.style.opacity = '0.85';
var cap = document.createElement('div');
cap.style.cssText = 'font-size:.7rem;color:#64748b;overflow:hidden;text-overflow:ellipsis;white-space:nowrap';
cap.textContent = f.name;
fig.appendChild(img);
fig.appendChild(cap);
picker.insertBefore(fig, addFigure);
if (URL && URL.createObjectURL) {
var url = URL.createObjectURL(f);
img.src = url;
fig.addEventListener('remove', function () { URL.revokeObjectURL(url); });
}
});
});
/* On désactive proprement le champ si l'utilisateur décoche des images
existantes (le nombre maximal est vérifié côté serveur de toute façon). */
if (hint) {
picker.addEventListener('change', function (ev) {
var cb = ev.target.closest('input[type=checkbox]');
if (!cb) return;
var fig = cb.closest('.pkg-shot');
if (fig) fig.style.opacity = cb.checked ? '1' : '0.35';
});
}
})();
</script>
</body>
</html>
+2 -1
View File
@@ -326,7 +326,8 @@ function fws_packages_save(PDO $pdo, array $d): int
':latest_name' => fws_utf8_str(trim((string) ($d['latest_name'] ?? ''))),
':latest_date' => ($d['latest_date'] ?? '') !== '' ? (string) $d['latest_date'] : null,
':links' => (string) json_encode(fws_utf8_arr((array) ($d['links'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
':screens' => (string) json_encode(fws_utf8_arr((array) ($d['screens'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
/* 5 captures maximum par paquet (gardée de force côté serveur). */
':screens' => (string) json_encode(array_slice(fws_utf8_arr((array) ($d['screens'] ?? [])), 0, 5), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
':changelog' => (string) json_encode(fws_utf8_arr((array) ($d['changelog'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
];