fix #29 : envoyer le lien magique par email (envoyer_mail_smtp)
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
Options -Indexes
|
||||
DirectoryIndex index.php
|
||||
|
||||
RewriteEngine On
|
||||
|
||||
# Fichiers et répertoires réels servis directement
|
||||
RewriteCond %{REQUEST_FILENAME} -f [OR]
|
||||
RewriteCond %{REQUEST_FILENAME} -d
|
||||
RewriteRule ^ - [L]
|
||||
|
||||
# URL propre pour les articles : /post/<slug>
|
||||
RewriteRule ^post/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=view&slug=$1 [L,QSA]
|
||||
|
||||
# Filtre par catégorie : /categorie/<nom>
|
||||
RewriteRule ^categorie/(.+?)/?$ /index.php?cat=$1 [L,QSA,B]
|
||||
|
||||
# Pagination par curseur : /page/<uuid>
|
||||
RewriteRule ^page/([0-9a-f-]{36})/?$ /index.php?cursor=$1 [L,QSA]
|
||||
|
||||
# Édition / création
|
||||
RewriteRule ^edit/([0-9a-f-]{36})/tags/(.+?)/?$ /index.php?action=edit_tags&uuid=$1&tag_type=$2 [L,QSA,B]
|
||||
RewriteRule ^edit/([0-9a-f-]{36})/?$ /index.php?action=edit&uuid=$1 [L,QSA]
|
||||
RewriteRule ^new/?$ /index.php?action=create [L,QSA]
|
||||
RewriteRule ^delete/([0-9a-f-]{36})/?$ /index.php?action=delete&uuid=$1 [L,QSA]
|
||||
|
||||
# Sources et diff
|
||||
RewriteRule ^sources/([0-9a-f-]{36})/?$ /index.php?action=sources&uuid=$1 [L,QSA]
|
||||
RewriteRule ^diff/([0-9a-f-]{36})/(\d+)/?$ /index.php?action=diff&uuid=$1&rev=$2 [L,QSA]
|
||||
|
||||
# Fichiers / import
|
||||
RewriteRule ^files/([0-9a-f-]{36})/add/?$ /index.php?action=add_files&uuid=$1 [L,QSA]
|
||||
RewriteRule ^import/([0-9a-f-]{36})/?$ /index.php?action=import_image&uuid=$1 [L,QSA]
|
||||
|
||||
# Admin (regen-thumbs et role/<email> avant la règle générique admin/<tab>)
|
||||
RewriteRule ^admin/regen-thumbs/?$ /index.php?action=regen_thumbs [L,QSA]
|
||||
RewriteRule ^admin/role/([a-z0-9_-]+)/?$ /index.php?action=admin_role_edit&role_name=$1 [L,QSA]
|
||||
RewriteRule ^admin/([a-z0-9-]+)/?$ /index.php?action=admin&tab=$1 [L,QSA]
|
||||
RewriteRule ^admin/?$ /index.php?action=admin [L,QSA]
|
||||
|
||||
# Réactions et commentaires
|
||||
RewriteRule ^react/?$ /index.php?action=react [L,QSA]
|
||||
RewriteRule ^comment/?$ /index.php?action=comment [L,QSA]
|
||||
RewriteRule ^comment-moderate/?$ /index.php?action=comment_moderate [L,QSA]
|
||||
RewriteRule ^verify-comment/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/?$ /index.php?action=verify_comment&token=$1 [L,QSA]
|
||||
|
||||
# Pages de gestion
|
||||
RewriteRule ^categories/?$ /index.php?action=categories [L,QSA]
|
||||
RewriteRule ^profile/?$ /index.php?action=profile [L,QSA]
|
||||
RewriteRule ^search/?$ /index.php?action=search [L,QSA]
|
||||
RewriteRule ^flux/?$ /index.php?action=flux [L,QSA]
|
||||
RewriteRule ^feed/add/?$ /index.php?action=add_feed [L,QSA]
|
||||
RewriteRule ^feed/delete/?$ /index.php?action=delete_feed [L,QSA]
|
||||
|
||||
# Profil public auteur + page liens
|
||||
RewriteRule ^profil/([a-z0-9][a-z0-9-]*)/article/cursor/([0-9a-f-]{36})/?$ /index.php?action=author_articles&slug=$1&cursor=$2 [L,QSA]
|
||||
RewriteRule ^profil/([a-z0-9][a-z0-9-]*)/article/?$ /index.php?action=author_articles&slug=$1 [L,QSA]
|
||||
RewriteRule ^profil/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=author&slug=$1 [L,QSA]
|
||||
RewriteRule ^liens/([a-z0-9][a-z0-9-]*)/?$ /index.php?action=liens&slug=$1 [L,QSA]
|
||||
RewriteRule ^link/add/?$ /index.php?action=add_link [L,QSA]
|
||||
RewriteRule ^link/delete/?$ /index.php?action=delete_link [L,QSA]
|
||||
RewriteRule ^link/reorder/?$ /index.php?action=reorder_links [L,QSA]
|
||||
|
||||
# Pages statiques
|
||||
RewriteRule ^about/?$ /index.php?action=about [L,QSA]
|
||||
RewriteRule ^legal/?$ /index.php?action=legal [L,QSA]
|
||||
RewriteRule ^licenses/?$ /index.php?action=licenses [L,QSA]
|
||||
RewriteRule ^contact/?$ /index.php?action=contact [L,QSA]
|
||||
|
||||
# Flux RSS — /feed est canonique, /rss et /rss.xml redirigent en 301
|
||||
RewriteRule ^rss/?$ /feed [R=301,L]
|
||||
RewriteRule ^rss\.xml$ /feed [R=301,L]
|
||||
RewriteRule ^feed/([0-9a-f-]{36})/?$ /feed.php?after=$1 [L,QSA]
|
||||
RewriteRule ^feed/?$ /feed.php [L,QSA]
|
||||
|
||||
# Sitemap
|
||||
RewriteRule ^sitemap\.xml$ /sitemap.php [L]
|
||||
|
||||
# Ajoute .php si le fichier correspondant existe
|
||||
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
|
||||
RewriteRule ^(.+?)/?$ /$1.php [L,QSA]
|
||||
|
||||
# 404 intelligent : redirige vers l'article le plus proche
|
||||
ErrorDocument 404 /index.php?action=not_found
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024–2026 Cédric Abonnel
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011-2024 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+6
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" rx="7" fill="#4f46e5"/>
|
||||
<text x="16" y="23" text-anchor="middle" font-family="system-ui,sans-serif" font-weight="700" font-size="20" fill="white">v</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 256 B |
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,118 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var panel = document.getElementById('sf-panel');
|
||||
if (!panel) return;
|
||||
|
||||
var input = document.getElementById('sf-input');
|
||||
var btn = document.getElementById('sf-btn');
|
||||
var box = document.getElementById('sf-results');
|
||||
var toUuid = panel.dataset.uuid;
|
||||
|
||||
function fileIcon(mime) {
|
||||
if (mime.startsWith('video/')) return '🎬';
|
||||
if (mime.startsWith('audio/')) return '🎵';
|
||||
if (mime === 'application/pdf') return '📑';
|
||||
return '📄';
|
||||
}
|
||||
|
||||
async function doSearch() {
|
||||
var q = input.value.trim();
|
||||
if (!q) return;
|
||||
btn.disabled = true;
|
||||
box.innerHTML = '<p class="text-muted small">Recherche…</p>';
|
||||
try {
|
||||
var res = await fetch('/?action=search_files&q=' + encodeURIComponent(q) + '&exclude=' + encodeURIComponent(toUuid));
|
||||
var data = await res.json();
|
||||
box.innerHTML = '';
|
||||
if (!data.length) {
|
||||
box.innerHTML = '<p class="text-muted small">Aucun fichier trouvé.</p>';
|
||||
return;
|
||||
}
|
||||
data.forEach(function (group) {
|
||||
var section = document.createElement('div');
|
||||
section.className = 'mb-4';
|
||||
|
||||
var header = document.createElement('p');
|
||||
header.className = 'fw-semibold small mb-2';
|
||||
header.textContent = group.article.title;
|
||||
section.appendChild(header);
|
||||
|
||||
var grid = document.createElement('div');
|
||||
grid.className = 'd-flex flex-wrap gap-2';
|
||||
|
||||
group.files.forEach(function (f) {
|
||||
var wrap = document.createElement('div');
|
||||
wrap.style.cssText = 'position:relative;cursor:pointer';
|
||||
wrap.title = f.name + ' (' + (f.size / 1024).toFixed(1) + ' Ko)';
|
||||
|
||||
if (f.is_image) {
|
||||
var img = document.createElement('img');
|
||||
img.src = f.url;
|
||||
img.alt = f.name;
|
||||
img.style.cssText = 'width:72px;height:72px;object-fit:cover;border-radius:6px;border:2px solid transparent;transition:border-color .15s,opacity .15s;display:block';
|
||||
wrap.appendChild(img);
|
||||
} else {
|
||||
var icon = document.createElement('div');
|
||||
icon.style.cssText = 'width:72px;height:72px;border-radius:6px;border:2px solid #dee2e6;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:1.6rem;background:#f8f9fa;transition:border-color .15s';
|
||||
icon.innerHTML = fileIcon(f.mime) + '<span style="font-size:.6rem;margin-top:2px;color:#6c757d;max-width:68px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + f.name.split('.').pop().toUpperCase() + '</span>';
|
||||
wrap.appendChild(icon);
|
||||
}
|
||||
|
||||
var overlay = document.createElement('div');
|
||||
overlay.style.cssText = 'position:absolute;inset:0;border-radius:6px;display:none;align-items:center;justify-content:center;background:rgba(25,135,84,.8);color:#fff;font-size:1.4rem';
|
||||
overlay.textContent = '✓';
|
||||
wrap.appendChild(overlay);
|
||||
|
||||
wrap.addEventListener('mouseenter', function () {
|
||||
if (!wrap._copied) wrap.firstChild.style.borderColor = '#0d6efd';
|
||||
});
|
||||
wrap.addEventListener('mouseleave', function () {
|
||||
if (!wrap._copied) wrap.firstChild.style.borderColor = 'transparent';
|
||||
});
|
||||
|
||||
wrap.addEventListener('click', async function () {
|
||||
if (wrap._copying || wrap._copied) return;
|
||||
wrap._copying = true;
|
||||
wrap.firstChild.style.opacity = '.5';
|
||||
try {
|
||||
var fd = new FormData();
|
||||
fd.append('from_uuid', group.article.uuid);
|
||||
fd.append('name', f.name);
|
||||
fd.append('to_uuid', toUuid);
|
||||
var r = await fetch('/?action=copy_file&uuid=' + encodeURIComponent(toUuid), {method: 'POST', body: fd});
|
||||
var d = await r.json();
|
||||
if (d.ok) {
|
||||
wrap._copied = true;
|
||||
wrap.firstChild.style.opacity = '1';
|
||||
wrap.firstChild.style.borderColor = '#198754';
|
||||
overlay.style.display = 'flex';
|
||||
} else {
|
||||
wrap.firstChild.style.opacity = '1';
|
||||
wrap.firstChild.style.borderColor = '#dc3545';
|
||||
wrap.title = d.error || 'Erreur';
|
||||
}
|
||||
} catch (e) {
|
||||
wrap.firstChild.style.opacity = '1';
|
||||
} finally {
|
||||
wrap._copying = false;
|
||||
}
|
||||
});
|
||||
|
||||
grid.appendChild(wrap);
|
||||
});
|
||||
|
||||
section.appendChild(grid);
|
||||
box.appendChild(section);
|
||||
});
|
||||
} catch (e) {
|
||||
box.innerHTML = '<p class="text-danger small">Erreur de recherche.</p>';
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
btn.addEventListener('click', doSearch);
|
||||
input.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
|
||||
});
|
||||
doSearch();
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// Confirmation data-confirm sur les formulaires (evite confirm() inline bloqué par CSP)
|
||||
document.querySelectorAll('form[data-confirm]').forEach(function (form) {
|
||||
form.addEventListener('submit', function (e) {
|
||||
var msg = form.getAttribute('data-confirm') || 'Confirmer ?';
|
||||
if (!window.confirm(msg)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Sélection globale articles
|
||||
var checkAll = document.getElementById('check-all');
|
||||
if (checkAll) {
|
||||
checkAll.addEventListener('change', function () {
|
||||
document.querySelectorAll('.bulk-check').forEach(function (cb) {
|
||||
cb.checked = checkAll.checked;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Indicateurs de traitement formulaire SMTP (config + tester connexion)
|
||||
var smtpForm = document.getElementById('smtp-config-form');
|
||||
if (smtpForm) {
|
||||
smtpForm.addEventListener('submit', function (e) {
|
||||
var clicked = e.submitter;
|
||||
if (!clicked) return;
|
||||
smtpForm.querySelectorAll('button[type="submit"]').forEach(function (btn) {
|
||||
btn.disabled = true;
|
||||
});
|
||||
var isSave = clicked.id === 'smtp-save-btn';
|
||||
clicked.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>'
|
||||
+ (isSave ? 'Enregistrement…' : 'En cours…');
|
||||
});
|
||||
}
|
||||
|
||||
// Indicateur de traitement envoi email de test
|
||||
var smtpTestForm = document.getElementById('smtp-test-form');
|
||||
if (smtpTestForm) {
|
||||
smtpTestForm.addEventListener('submit', function () {
|
||||
var btn = document.getElementById('smtp-send-btn');
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>En cours…';
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,462 @@
|
||||
// varlog — app.js
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
|
||||
// ─── Auto-resize textareas ───────────────────────────────────────────────
|
||||
document.querySelectorAll('textarea.form-control').forEach(function (ta) {
|
||||
function resize() {
|
||||
ta.style.height = 'auto';
|
||||
ta.style.height = ta.scrollHeight + 'px';
|
||||
}
|
||||
ta.addEventListener('input', resize);
|
||||
resize();
|
||||
});
|
||||
|
||||
// ─── Ctrl+Enter : soumettre le formulaire ────────────────────────────────
|
||||
var form = document.querySelector('form[method="POST"]');
|
||||
if (form) {
|
||||
form.addEventListener('keydown', function (e) {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
|
||||
form.submit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Slug auto-génération ────────────────────────────────────────────────
|
||||
const titleInput = document.getElementById('title');
|
||||
const slugField = document.getElementById('slug');
|
||||
const slugPreview = document.getElementById('slug-preview');
|
||||
|
||||
if (titleInput && slugField) {
|
||||
if (slugField.value !== '') slugField._auto = false;
|
||||
|
||||
titleInput.addEventListener('input', function () {
|
||||
if (slugField._auto !== false) {
|
||||
const generated = slugify(this.value);
|
||||
slugField.value = generated;
|
||||
if (slugPreview) slugPreview.textContent = generated;
|
||||
}
|
||||
});
|
||||
|
||||
slugField.addEventListener('input', function () {
|
||||
this._auto = (this.value === '');
|
||||
if (slugPreview) slugPreview.textContent = this.value;
|
||||
});
|
||||
}
|
||||
|
||||
function slugify(s) {
|
||||
const map = {'à':'a','â':'a','ä':'a','é':'e','è':'e','ê':'e','ë':'e','î':'i','ï':'i','ô':'o','ö':'o','ù':'u','û':'u','ü':'u','ç':'c','æ':'ae','œ':'oe'};
|
||||
return s.toLowerCase().replace(/[àâäéèêëîïôöùûüçæœ]/g, c => map[c] || c)
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
// ─── Rôle : nom technique auto depuis le label ───────────────────────────
|
||||
var roleLabelInput = document.getElementById('role-label');
|
||||
var roleNameInput = document.getElementById('role-name');
|
||||
if (roleLabelInput && roleNameInput) {
|
||||
roleLabelInput.addEventListener('input', function () {
|
||||
if (roleNameInput._manual) return;
|
||||
roleNameInput.value = slugify(this.value);
|
||||
});
|
||||
roleNameInput.addEventListener('input', function () {
|
||||
this._manual = (this.value !== '');
|
||||
});
|
||||
roleNameInput.addEventListener('blur', function () {
|
||||
if (this.value === '') {
|
||||
this._manual = false;
|
||||
this.value = slugify(roleLabelInput.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Aperçu couleur catégorie ────────────────────────────────────────────
|
||||
const KNOWN_CATS = {
|
||||
'actualité': 10, 'travaux': 35, 'scolaire': 55,
|
||||
'linux': 120, 'domotique': 160, 'télécom': 190,
|
||||
'blog': 220, 'informatique': 255, 'réflexion': 285,
|
||||
'loisirs': 320, 'perso': 345,
|
||||
};
|
||||
const FREE_HUES = [87, 140, 205, 237, 302];
|
||||
|
||||
function gradient(hue) {
|
||||
return `linear-gradient(135deg,hsl(${hue},70%,88%) 0%,hsl(${hue},60%,28%) 100%)`;
|
||||
}
|
||||
|
||||
function hashHue(str) {
|
||||
let h = 5381;
|
||||
for (let i = 0; i < str.length; i++) h = (((h << 5) + h) + str.charCodeAt(i)) | 0;
|
||||
return ((Math.abs(h) * 0.6180339887) * 360 | 0) % 360;
|
||||
}
|
||||
|
||||
function nearestKnown(hue) {
|
||||
let best = null, bestDist = Infinity;
|
||||
for (const [name, h] of Object.entries(KNOWN_CATS)) {
|
||||
const d = Math.min(Math.abs(hue - h), 360 - Math.abs(hue - h));
|
||||
if (d < bestDist) { bestDist = d; best = name; }
|
||||
}
|
||||
return { name: best, dist: bestDist };
|
||||
}
|
||||
|
||||
function updateCatPreview(val) {
|
||||
const key = val.trim().toLowerCase();
|
||||
const swatch = document.getElementById('cat-swatch');
|
||||
const hint = document.getElementById('cat-hint');
|
||||
const freeEl = document.getElementById('cat-free-swatches');
|
||||
if (!swatch) return;
|
||||
freeEl.innerHTML = '';
|
||||
|
||||
if (!key) {
|
||||
swatch.style.background = '#e5e7eb';
|
||||
swatch.title = '';
|
||||
hint.textContent = '';
|
||||
return;
|
||||
}
|
||||
|
||||
if (KNOWN_CATS[key] !== undefined) {
|
||||
const hue = KNOWN_CATS[key];
|
||||
swatch.style.background = gradient(hue);
|
||||
swatch.title = `${hue}°`;
|
||||
hint.textContent = `Catégorie existante · teinte fixe (${hue}°)`;
|
||||
hint.className = 'text-muted d-block mt-1';
|
||||
return;
|
||||
}
|
||||
|
||||
const hue = hashHue(key);
|
||||
const { name, dist } = nearestKnown(hue);
|
||||
|
||||
swatch.style.background = gradient(hue);
|
||||
swatch.title = `${hue}°`;
|
||||
|
||||
if (dist < 20) {
|
||||
hint.innerHTML = `⚠ Teinte proche de <strong>${name}</strong> (${dist}° d'écart) · couleurs disponibles :`;
|
||||
hint.className = 'text-warning d-block mt-1';
|
||||
FREE_HUES.forEach(h => {
|
||||
const el = document.createElement('span');
|
||||
el.title = `${h}°`;
|
||||
el.style.cssText = `display:inline-block;width:28px;height:20px;border-radius:4px;cursor:help;background:${gradient(h)}`;
|
||||
freeEl.appendChild(el);
|
||||
});
|
||||
} else {
|
||||
hint.textContent = `Nouvelle catégorie · teinte libre (${hue}°)`;
|
||||
hint.className = 'text-muted d-block mt-1';
|
||||
}
|
||||
}
|
||||
|
||||
const catInput = document.getElementById('category');
|
||||
if (catInput) {
|
||||
catInput.addEventListener('input', function () { updateCatPreview(this.value); });
|
||||
updateCatPreview(catInput.value);
|
||||
}
|
||||
|
||||
// ─── Copier la référence Markdown ────────────────────────────────────────
|
||||
document.querySelectorAll('[data-copy-md-name]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
const name = this.dataset.copyMdName;
|
||||
const isImage = this.dataset.copyMdIsImage === '1';
|
||||
const ref = isImage ? `` : `[${name}](${name})`;
|
||||
navigator.clipboard.writeText(ref).then(() => {
|
||||
const orig = this.textContent;
|
||||
this.textContent = 'Copié !';
|
||||
setTimeout(() => { this.textContent = orig; }, 1500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Boîtes de confirmation (suppression) ───────────────────────────────
|
||||
document.querySelectorAll('button[data-confirm], a[data-confirm]').forEach(function (el) {
|
||||
el.addEventListener('click', function (e) {
|
||||
if (!confirm(this.dataset.confirm)) e.preventDefault();
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('form[data-confirm]').forEach(function (form) {
|
||||
form.addEventListener('submit', function (e) {
|
||||
if (!confirm(this.dataset.confirm)) e.preventDefault();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Insérer une référence Markdown au curseur ───────────────────────────
|
||||
const ta = document.getElementById('content');
|
||||
if (ta) {
|
||||
ta._savedStart = null;
|
||||
ta._savedEnd = null;
|
||||
|
||||
function saveCursor() {
|
||||
if (document.activeElement === ta) {
|
||||
ta._savedStart = ta.selectionStart;
|
||||
ta._savedEnd = ta.selectionEnd;
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', saveCursor);
|
||||
ta.addEventListener('keyup', saveCursor);
|
||||
ta.addEventListener('mouseup', saveCursor);
|
||||
|
||||
document.querySelectorAll('[data-insert-ref]').forEach(function (el) {
|
||||
el.addEventListener('click', function () {
|
||||
insertRef(this.dataset.insertRef);
|
||||
});
|
||||
if (el.tagName === 'IMG') {
|
||||
el.addEventListener('mouseenter', function () { this.style.borderColor = '#0d6efd'; });
|
||||
el.addEventListener('mouseleave', function () { this.style.borderColor = 'transparent'; });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function insertRef(url) {
|
||||
if (!ta) return;
|
||||
const isImage = /\.(jpe?g|png|gif|webp|svg|avif)(\?.*)?$/i.test(url);
|
||||
const label = url.startsWith('http')
|
||||
? (decodeURIComponent(url.split('/').pop().split('?')[0]) || url)
|
||||
: url;
|
||||
const ref = isImage ? `` : `[${label}](${url})`;
|
||||
const len = ta.value.length;
|
||||
const start = ta._savedStart !== null ? ta._savedStart : len;
|
||||
const end = ta._savedEnd !== null ? ta._savedEnd : len;
|
||||
ta.focus();
|
||||
ta.setRangeText(ref, start, end, 'end');
|
||||
ta._savedStart = ta._savedEnd = start + ref.length;
|
||||
ta.dispatchEvent(new Event('input'));
|
||||
}
|
||||
|
||||
// ─── Compteurs SEO ───────────────────────────────────────────────────────
|
||||
function initCounter(inputId, counterId, max) {
|
||||
const input = document.getElementById(inputId);
|
||||
const counter = document.getElementById(counterId);
|
||||
if (!input || !counter) return;
|
||||
function update() {
|
||||
const len = input.value.length;
|
||||
counter.textContent = `${len} / ${max}`;
|
||||
counter.className = len > max ? 'text-danger' : 'text-muted';
|
||||
}
|
||||
input.addEventListener('input', update);
|
||||
update();
|
||||
}
|
||||
initCounter('seo_title', 'seo_title_counter', 60);
|
||||
initCounter('seo_description', 'seo_desc_counter', 155);
|
||||
|
||||
// ─── Page catégories ─────────────────────────────────────────────────────
|
||||
function catComputeGradient(val) {
|
||||
const key = val.trim().toLowerCase();
|
||||
if (!key) return null;
|
||||
if (KNOWN_CATS[key] !== undefined) return { hue: KNOWN_CATS[key], known: true };
|
||||
const hue = hashHue(key);
|
||||
const { name, dist } = nearestKnown(hue);
|
||||
return { hue, known: false, conflict: dist < 20 ? name : null };
|
||||
}
|
||||
|
||||
document.querySelectorAll('form[action="/?action=rename_category"] input[name="new"]').forEach(function (input) {
|
||||
input.addEventListener('input', function () {
|
||||
const swatch = input.closest('form').querySelector('.rename-swatch');
|
||||
const result = catComputeGradient(input.value);
|
||||
if (swatch) swatch.style.background = result ? gradient(result.hue) : '#e5e7eb';
|
||||
});
|
||||
});
|
||||
|
||||
const newCatInput = document.getElementById('new-cat-input');
|
||||
if (newCatInput) {
|
||||
newCatInput.addEventListener('input', function () {
|
||||
const swatch = document.getElementById('new-cat-swatch');
|
||||
const hint = document.getElementById('new-cat-hint');
|
||||
const result = catComputeGradient(this.value);
|
||||
|
||||
if (!result) {
|
||||
swatch.style.background = '#e5e7eb';
|
||||
hint.textContent = '';
|
||||
return;
|
||||
}
|
||||
|
||||
swatch.style.background = gradient(result.hue);
|
||||
|
||||
if (result.known) {
|
||||
hint.textContent = `Catégorie existante · teinte fixe (${result.hue}°)`;
|
||||
hint.className = 'text-muted d-block mb-3';
|
||||
} else if (result.conflict) {
|
||||
hint.textContent = `⚠ Teinte proche de « ${result.conflict} » — choisissez un autre nom ou une couleur disponible ci-dessous`;
|
||||
hint.className = 'text-warning d-block mb-3';
|
||||
} else {
|
||||
hint.textContent = `Couleur libre · teinte ${result.hue}°`;
|
||||
hint.className = 'text-success d-block mb-3';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Import image : récupérer les métadonnées ────────────────────────────
|
||||
const fetchMetaBtn = document.getElementById('fetch-meta-btn');
|
||||
if (fetchMetaBtn) {
|
||||
fetchMetaBtn.addEventListener('click', async function () {
|
||||
const urlInput = document.getElementById('import-url');
|
||||
const resultDiv = document.getElementById('meta-result');
|
||||
const url = urlInput ? urlInput.value.trim() : '';
|
||||
|
||||
if (!url) {
|
||||
resultDiv.innerHTML = '<small class="text-danger">Saisissez une URL d\'abord.</small>';
|
||||
return;
|
||||
}
|
||||
|
||||
fetchMetaBtn.disabled = true;
|
||||
fetchMetaBtn.textContent = 'Chargement…';
|
||||
resultDiv.innerHTML = '';
|
||||
|
||||
try {
|
||||
const res = await fetch(`/?action=fetch_file_meta&url=${encodeURIComponent(url)}`);
|
||||
const data = await res.json();
|
||||
|
||||
if (!data.ok) {
|
||||
resultDiv.innerHTML = `<small class="text-danger">${data.error || 'Erreur lors de la récupération.'}</small>`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-remplissage dynamique des champs (si vides)
|
||||
const AUTOFILL = {
|
||||
img_author: { keys: ['author', 'credit'], label: 'Auteur / crédit' },
|
||||
img_source: { keys: ['canonical', 'source'], label: 'URL source' },
|
||||
};
|
||||
const autofillKeys = new Set();
|
||||
const autofillNotice = [];
|
||||
for (const [fieldName, cfg] of Object.entries(AUTOFILL)) {
|
||||
const f = document.querySelector(`input[name="${fieldName}"]`);
|
||||
if (!f || f.value) continue;
|
||||
for (const key of cfg.keys) {
|
||||
if (data[key]) {
|
||||
f.value = data[key];
|
||||
autofillKeys.add(key);
|
||||
autofillNotice.push(`<strong>${cfg.label}</strong> : ${data[key]}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Affichage dynamique de tous les champs retournés
|
||||
const isPdf = (data.mime === 'application/pdf');
|
||||
const isHtml = (data.mime || '').startsWith('text/html');
|
||||
|
||||
const META_ORDER = ['mime','size','pages','page_size','pdf_version',
|
||||
'width','site_name','og_type','language',
|
||||
'title','description','author','subject','keywords',
|
||||
'credit','source','creator','producer','date','camera','copyright',
|
||||
'canonical','og_image'];
|
||||
const META_LABELS = {
|
||||
mime: 'Type', size: 'Taille', width: 'Dimensions',
|
||||
pages: 'Pages', page_size: 'Format', pdf_version: 'Version PDF',
|
||||
site_name: 'Site', og_type: 'Type OG', language: 'Langue',
|
||||
title: isPdf || isHtml ? 'Titre' : 'Titre EXIF/IPTC',
|
||||
author: isPdf || isHtml ? 'Auteur' : 'Auteur EXIF/IPTC',
|
||||
date: isPdf ? 'Créé le' : isHtml ? 'Publié le' : 'Prise de vue',
|
||||
description: 'Description', subject: 'Sujet', keywords: 'Mots-clés',
|
||||
credit: 'Crédit', source: 'Source IPTC',
|
||||
creator: 'Créé avec', producer: 'Produit par',
|
||||
camera: 'Appareil', copyright: 'Copyright',
|
||||
canonical: 'URL canonique', og_image: 'Image OG',
|
||||
};
|
||||
|
||||
function fmtVal(key, val) {
|
||||
if (key === 'size') return (val/1024).toFixed(0) + ' Ko' + (val >= 1048576 ? ` (${(val/1048576).toFixed(1)} Mo)` : '');
|
||||
if (key === 'width') return `${data.width} × ${data.height} px`;
|
||||
if (key === 'og_image') return `<img src="${val}" style="max-width:120px;max-height:80px;border-radius:4px" alt="">`;
|
||||
if (key === 'canonical') return `<a href="${val}" target="_blank" rel="noopener">${val}</a>`;
|
||||
return String(val);
|
||||
}
|
||||
|
||||
const SKIP = new Set(['ok', 'height']);
|
||||
const seen = new Set();
|
||||
const rows = [];
|
||||
|
||||
for (const key of META_ORDER) {
|
||||
const val = data[key];
|
||||
if (val == null || val === '' || key === 'height') continue;
|
||||
seen.add(key);
|
||||
const badge = autofillKeys.has(key)
|
||||
? ' <span class="badge text-bg-primary ms-1" title="Pré-rempli dans le formulaire">↓ pré-rempli</span>'
|
||||
: '';
|
||||
rows.push([META_LABELS[key] ?? key, fmtVal(key, val) + badge]);
|
||||
}
|
||||
for (const [key, val] of Object.entries(data)) {
|
||||
if (seen.has(key) || SKIP.has(key) || val == null || val === '') continue;
|
||||
rows.push([key, fmtVal(key, val)]);
|
||||
}
|
||||
|
||||
let html = '';
|
||||
if (rows.length > 0) {
|
||||
const trs = rows.map(([k, v]) =>
|
||||
`<tr><th class="text-muted fw-normal pe-3 text-nowrap">${k}</th><td>${v}</td></tr>`
|
||||
).join('');
|
||||
html = `<table class="table table-sm table-borderless mb-0 small"><tbody>${trs}</tbody></table>`;
|
||||
} else {
|
||||
html = '<small class="text-muted">Aucune métadonnée disponible pour ce fichier.</small>';
|
||||
}
|
||||
if (autofillNotice.length > 0) {
|
||||
html += `<div class="small text-primary mt-1">✓ Pré-rempli — ${autofillNotice.join(' · ')}</div>`;
|
||||
}
|
||||
resultDiv.innerHTML = html;
|
||||
} catch {
|
||||
resultDiv.innerHTML = '<small class="text-danger">Erreur de connexion.</small>';
|
||||
} finally {
|
||||
fetchMetaBtn.disabled = false;
|
||||
fetchMetaBtn.textContent = 'Métadonnées';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Import image : toggle mode download ────────────────────────────────
|
||||
document.querySelectorAll('input[name="mode"]').forEach(function (r) {
|
||||
r.addEventListener('change', function () {
|
||||
const dl = this.value === 'download';
|
||||
const ss = this.value === 'screenshot';
|
||||
const warn = document.getElementById('copyright-warning');
|
||||
const fields = document.getElementById('download-fields');
|
||||
if (warn) warn.style.display = dl ? 'block' : 'none';
|
||||
if (fields) fields.style.display = (dl || ss) ? 'block' : 'none';
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Données page (mode édition uniquement) ──────────────────────────────
|
||||
const pageEl = document.getElementById('vl-page');
|
||||
if (!pageEl) return;
|
||||
|
||||
const uuid = pageEl.dataset.uuid;
|
||||
const insertUrl = pageEl.dataset.insertUrl;
|
||||
|
||||
// Auto-insertion après import d'image
|
||||
if (insertUrl && ta) {
|
||||
const isImage = /\.(jpe?g|png|gif|webp|svg|avif)(\?.*)?$/i.test(insertUrl);
|
||||
const name = decodeURIComponent(insertUrl.split('/').pop().split('?')[0]) || 'fichier';
|
||||
const ref = isImage ? `` : `[${name}](${insertUrl})`;
|
||||
const sep = ta.value.length > 0 && !ta.value.endsWith('\n') ? '\n' : '';
|
||||
ta.value += sep + ref;
|
||||
ta.focus();
|
||||
ta.selectionStart = ta.selectionEnd = ta.value.length;
|
||||
ta.dispatchEvent(new Event('input'));
|
||||
}
|
||||
|
||||
// ─── Autosave ────────────────────────────────────────────────────────────
|
||||
const indicator = document.getElementById('autosave-indicator');
|
||||
if (!indicator || !uuid) return;
|
||||
|
||||
let timer = null;
|
||||
|
||||
function scheduleAutosave() {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(doAutosave, 3000);
|
||||
}
|
||||
|
||||
async function doAutosave() {
|
||||
const title = document.getElementById('title').value;
|
||||
const slug = document.getElementById('slug').value;
|
||||
const content = document.getElementById('content').value;
|
||||
indicator.textContent = 'Sauvegarde…';
|
||||
try {
|
||||
const res = await fetch(`/?action=autosave&uuid=${encodeURIComponent(uuid)}`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: new URLSearchParams({title, slug, content}),
|
||||
});
|
||||
const data = await res.json();
|
||||
indicator.textContent = data.ok ? `Brouillon sauvegardé à ${data.time}` : 'Erreur de sauvegarde';
|
||||
} catch {
|
||||
indicator.textContent = 'Erreur de sauvegarde';
|
||||
}
|
||||
}
|
||||
|
||||
['title', 'slug', 'content'].forEach(id => {
|
||||
document.getElementById(id)?.addEventListener('input', scheduleAutosave);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
(function(){
|
||||
var bio = document.getElementById('author-bio');
|
||||
var btn = document.getElementById('bio-toggle');
|
||||
if (!bio || !btn) return;
|
||||
requestAnimationFrame(function() {
|
||||
if (bio.scrollHeight > bio.clientHeight + 2) { btn.hidden = false; }
|
||||
});
|
||||
btn.addEventListener('click', function() {
|
||||
var exp = btn.getAttribute('aria-expanded') === 'true';
|
||||
bio.classList.toggle('bio-clamped', exp);
|
||||
btn.textContent = exp ? 'plus' : 'moins';
|
||||
btn.setAttribute('aria-expanded', exp ? 'false' : 'true');
|
||||
});
|
||||
})();
|
||||
+6
File diff suppressed because one or more lines are too long
@@ -0,0 +1,29 @@
|
||||
(function() {
|
||||
const list = document.getElementById('links-sortable');
|
||||
if (!list) return;
|
||||
let dragged = null;
|
||||
list.querySelectorAll('li').forEach(li => {
|
||||
li.setAttribute('draggable', true);
|
||||
li.addEventListener('dragstart', () => { dragged = li; li.style.opacity = '.4'; });
|
||||
li.addEventListener('dragend', () => { dragged = null; li.style.opacity = ''; saveOrder(); });
|
||||
li.addEventListener('dragover', e => { e.preventDefault(); const after = getDragAfter(list, e.clientY); after ? list.insertBefore(dragged, after) : list.appendChild(dragged); });
|
||||
});
|
||||
function getDragAfter(container, y) {
|
||||
return [...container.querySelectorAll('li:not([style*="opacity"])')].reduce((closest, el) => {
|
||||
const box = el.getBoundingClientRect();
|
||||
const offset = y - box.top - box.height / 2;
|
||||
return offset < 0 && offset > closest.offset ? { offset, element: el } : closest;
|
||||
}, { offset: Number.NEGATIVE_INFINITY }).element;
|
||||
}
|
||||
function saveOrder() {
|
||||
const form = document.getElementById('reorder-form');
|
||||
if (!form) return;
|
||||
form.querySelectorAll('input').forEach(i => i.remove());
|
||||
list.querySelectorAll('li[data-id]').forEach(li => {
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'hidden'; inp.name = 'order[]'; inp.value = li.dataset.id;
|
||||
form.appendChild(inp);
|
||||
});
|
||||
form.submit();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,62 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var data = document.getElementById('pc-data');
|
||||
if (!data) return;
|
||||
|
||||
var defaultTitle = data.dataset.defaultTitle;
|
||||
var defaultDesc = data.dataset.defaultDesc;
|
||||
var baseUrl = data.dataset.baseUrl;
|
||||
|
||||
function initCounter(inputId, counterId, max) {
|
||||
var el = document.getElementById(inputId);
|
||||
var ct = document.getElementById(counterId);
|
||||
if (!el || !ct) return;
|
||||
function upd() {
|
||||
var n = el.value.length;
|
||||
ct.textContent = n + ' / ' + max;
|
||||
ct.className = n > max ? 'text-danger' : 'text-muted';
|
||||
}
|
||||
el.addEventListener('input', upd);
|
||||
upd();
|
||||
}
|
||||
initCounter('seo_title', 'seo_title_counter', 60);
|
||||
initCounter('seo_description', 'seo_desc_counter', 155);
|
||||
|
||||
function updatePreview() {
|
||||
var seoTitle = document.getElementById('seo_title').value.trim();
|
||||
var seoDesc = document.getElementById('seo_description').value.trim();
|
||||
var slug = document.getElementById('confirm-slug').value.trim();
|
||||
document.getElementById('preview-title').textContent = seoTitle || defaultTitle;
|
||||
document.getElementById('preview-desc').textContent = seoDesc || defaultDesc;
|
||||
document.getElementById('preview-url').textContent = baseUrl + slug;
|
||||
}
|
||||
|
||||
['seo_title', 'seo_description', 'confirm-slug'].forEach(function (id) {
|
||||
var el = document.getElementById(id);
|
||||
if (el) el.addEventListener('input', updatePreview);
|
||||
});
|
||||
|
||||
var slugInput = document.getElementById('confirm-slug');
|
||||
var slugDisplay = document.getElementById('slug-display');
|
||||
|
||||
var btnSuggest = document.getElementById('slug-btn-suggest');
|
||||
if (btnSuggest) {
|
||||
btnSuggest.addEventListener('click', function () {
|
||||
var val = btnSuggest.dataset.slugSuggest;
|
||||
slugInput.value = val;
|
||||
slugDisplay.textContent = val;
|
||||
updatePreview();
|
||||
});
|
||||
}
|
||||
|
||||
var btnKeep = document.getElementById('slug-btn-keep');
|
||||
if (btnKeep) {
|
||||
btnKeep.addEventListener('click', function () {
|
||||
var val = btnKeep.dataset.slugKeep;
|
||||
slugInput.value = val;
|
||||
slugDisplay.textContent = val;
|
||||
updatePreview();
|
||||
});
|
||||
}
|
||||
|
||||
updatePreview();
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// reactions.js — toggle réactions via fetch, fallback formulaire natif
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.querySelectorAll('.reaction-form').forEach(function (form) {
|
||||
form.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
var btn = form.querySelector('.reaction-btn');
|
||||
var type = form.querySelector('[name="type"]').value;
|
||||
var uuid = form.querySelector('[name="uuid"]').value;
|
||||
var badge = form.querySelector('.reaction-count');
|
||||
var active = btn.classList.contains('btn-primary');
|
||||
|
||||
var data = new URLSearchParams();
|
||||
data.append('uuid', uuid);
|
||||
data.append('type', type);
|
||||
data.append('_ajax', '1');
|
||||
|
||||
fetch('/react', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: data.toString(),
|
||||
})
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (json) {
|
||||
if (!json.ok) { form.submit(); return; }
|
||||
|
||||
var nowActive = json.active;
|
||||
if (btn.classList.contains('hero-reaction-btn')) {
|
||||
btn.classList.toggle('hero-reaction-btn--active', nowActive);
|
||||
} else {
|
||||
btn.classList.toggle('btn-primary', nowActive);
|
||||
btn.classList.toggle('btn-outline-secondary', !nowActive);
|
||||
if (badge) {
|
||||
badge.classList.toggle('bg-light', nowActive);
|
||||
badge.classList.toggle('text-primary', nowActive);
|
||||
badge.classList.toggle('bg-secondary', !nowActive);
|
||||
}
|
||||
}
|
||||
if (badge) { badge.textContent = json.count; }
|
||||
})
|
||||
.catch(function () { form.submit(); });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
(function () {
|
||||
var headings = document.querySelectorAll('.post-content h2, .post-content h3');
|
||||
var links = document.querySelectorAll('.toc-list a');
|
||||
|
||||
if (headings.length && links.length) {
|
||||
var map = {};
|
||||
links.forEach(function (a) {
|
||||
map[decodeURIComponent(a.getAttribute('href').slice(1))] = a;
|
||||
});
|
||||
|
||||
var active = null;
|
||||
var observer = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (entry) {
|
||||
if (entry.isIntersecting) {
|
||||
if (active) active.classList.remove('toc-active');
|
||||
active = map[entry.target.id] || null;
|
||||
if (active) active.classList.add('toc-active');
|
||||
}
|
||||
});
|
||||
}, { rootMargin: '-8% 0px -82% 0px', threshold: 0 });
|
||||
|
||||
headings.forEach(function (h) { observer.observe(h); });
|
||||
}
|
||||
|
||||
var btnTop = document.getElementById('toc-go-top');
|
||||
var btnBot = document.getElementById('toc-go-bottom');
|
||||
if (btnTop) {
|
||||
btnTop.addEventListener('click', function () {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
if (btnBot) {
|
||||
btnBot.addEventListener('click', function () {
|
||||
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
})();
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
define('BASE_PATH', realpath(__DIR__ . '/../'));
|
||||
|
||||
require_once BASE_PATH . '/src/auth.php';
|
||||
require_once BASE_PATH . '/src/SiteSettings.php';
|
||||
require_once BASE_PATH . '/config/config.php';
|
||||
require_once BASE_PATH . '/src/ArticleManager.php';
|
||||
require_once BASE_PATH . '/src/Parsedown.php';
|
||||
|
||||
const FEED_PAGE_SIZE = 20;
|
||||
|
||||
$articles = new ArticleManager(BASE_PATH . '/data');
|
||||
$privateCats = $articles->getPrivateCategories();
|
||||
$Parsedown = new Parsedown();
|
||||
|
||||
$now = time();
|
||||
$base = rtrim(APP_URL, '/');
|
||||
|
||||
$all = array_values(array_filter(
|
||||
$articles->getAll(publishedOnly: true),
|
||||
static function (array $a) use ($now, $privateCats): bool {
|
||||
if (strtotime((string)($a['published_at'] ?? '')) > $now) {
|
||||
return false;
|
||||
}
|
||||
$cat = trim($a['category'] ?? '');
|
||||
return $cat === '' || !in_array($cat, $privateCats, true);
|
||||
}
|
||||
));
|
||||
|
||||
// ─── Pagination curseur ──────────────────────────────────────────────────────
|
||||
$after = trim($_GET['after'] ?? '');
|
||||
$offset = 0;
|
||||
if ($after !== '') {
|
||||
foreach ($all as $i => $a) {
|
||||
if ($a['uuid'] === $after) {
|
||||
$offset = $i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$items = array_slice($all, $offset, FEED_PAGE_SIZE);
|
||||
$nextCursor = (count($all) > $offset + FEED_PAGE_SIZE)
|
||||
? ($all[$offset + FEED_PAGE_SIZE - 1]['uuid'] ?? null)
|
||||
: null;
|
||||
|
||||
$feedUrl = $base . '/feed';
|
||||
$feedNextUrl = $nextCursor !== null ? $base . '/feed/' . $nextCursor : null;
|
||||
|
||||
// ─── lastBuildDate ───────────────────────────────────────────────────────────
|
||||
$lastBuild = '';
|
||||
foreach ($all as $a) {
|
||||
$ts = (int)strtotime((string)($a['updated_at'] ?? $a['published_at'] ?? ''));
|
||||
if ($ts > (int)strtotime($lastBuild ?: '1970-01-01')) {
|
||||
$lastBuild = date(DATE_RSS, $ts);
|
||||
}
|
||||
}
|
||||
if ($lastBuild === '') {
|
||||
$lastBuild = date(DATE_RSS);
|
||||
}
|
||||
|
||||
header('Content-Type: application/rss+xml; charset=UTF-8');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
|
||||
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
|
||||
?>
|
||||
<rss version="2.0"
|
||||
xmlns:atom="http://www.w3.org/2005/Atom"
|
||||
xmlns:fh="http://purl.org/syndication/history/1.0">
|
||||
<channel>
|
||||
<title><?= htmlspecialchars(siteTitle()) ?></title>
|
||||
<link><?= htmlspecialchars($base) ?></link>
|
||||
<description><?= htmlspecialchars(siteClaim()) ?></description>
|
||||
<language><?= htmlspecialchars(siteLang()) ?></language>
|
||||
<lastBuildDate><?= htmlspecialchars($lastBuild) ?></lastBuildDate>
|
||||
|
||||
<atom:link href="<?= htmlspecialchars($feedUrl) ?>" rel="self" type="application/rss+xml"/>
|
||||
|
||||
<?php if ($offset > 0): ?>
|
||||
<atom:link href="<?= htmlspecialchars($feedUrl) ?>" rel="first" type="application/rss+xml"/>
|
||||
<?php endif; ?>
|
||||
<?php if ($feedNextUrl !== null): ?>
|
||||
<atom:link href="<?= htmlspecialchars($feedNextUrl) ?>" rel="next" type="application/rss+xml"/>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($feedNextUrl !== null || $offset > 0): ?>
|
||||
<fh:archive/>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php foreach ($items as $article):
|
||||
$pubDate = date(DATE_RSS, (int)strtotime((string)($article['published_at'] ?? $article['created_at'] ?? '')));
|
||||
$link = $base . '/post/' . rawurlencode($article['slug'] ?? '');
|
||||
$title = htmlspecialchars($article['title'] ?? '', ENT_XML1);
|
||||
$plain = preg_replace('/\s+/', ' ', strip_tags($Parsedown->text($article['content'] ?? '')));
|
||||
$desc = htmlspecialchars(mb_strimwidth(trim((string)$plain), 0, 300, '…'), ENT_XML1);
|
||||
$guid = htmlspecialchars($base . '/post/' . rawurlencode($article['slug'] ?? ''), ENT_XML1);
|
||||
?>
|
||||
<item>
|
||||
<title><?= $title ?></title>
|
||||
<link><?= htmlspecialchars($link) ?></link>
|
||||
<description><?= $desc ?></description>
|
||||
<pubDate><?= htmlspecialchars($pubDate) ?></pubDate>
|
||||
<guid isPermaLink="true"><?= $guid ?></guid>
|
||||
</item>
|
||||
<?php endforeach; ?>
|
||||
</channel>
|
||||
</rss>
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
define('BASE_PATH', realpath(__DIR__ . '/../'));
|
||||
|
||||
$uuid = $_GET['uuid'] ?? '';
|
||||
$name = $_GET['name'] ?? '';
|
||||
|
||||
// Valide le format UUID v4
|
||||
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $uuid)) {
|
||||
http_response_code(400);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Sécurise le nom de fichier (pas de traversal)
|
||||
$name = basename($name);
|
||||
if ($name === '' || $name[0] === '.') {
|
||||
http_response_code(400);
|
||||
exit;
|
||||
}
|
||||
|
||||
$path = BASE_PATH . '/data/' . $uuid . '/files/' . $name;
|
||||
|
||||
if (!is_file($path)) {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
$mime = mime_content_type($path) ?: 'application/octet-stream';
|
||||
header('Content-Type: ' . $mime);
|
||||
header('Content-Length: ' . filesize($path));
|
||||
header('Cache-Control: public, max-age=31536000, immutable');
|
||||
readfile($path);
|
||||
exit;
|
||||
+3140
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
// public/login/config.php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/app/bootstrap.php';
|
||||
if (!defined('BASE_PATH')) {
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
}
|
||||
require_once BASE_PATH . '/includes/db.php';
|
||||
require_once BASE_PATH . '/includes/csrf.php';
|
||||
require_once BASE_PATH . '/src/ConfigRepo.php';
|
||||
|
||||
Session::startSecure(getenv('SESSION_NAME') ?: 'SID_IDENT');
|
||||
ensure_admin();
|
||||
csrf_start();
|
||||
|
||||
$cfg = config_repo_get();
|
||||
$msg = null;
|
||||
$err = null;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if (!csrf_check($_POST['csrf'] ?? '')) {
|
||||
http_response_code(403);
|
||||
exit('CSRF');
|
||||
}
|
||||
|
||||
$in = [
|
||||
'oidc_issuer' => trim((string)($_POST['oidc_issuer'] ?? '')),
|
||||
'oidc_name' => trim((string)($_POST['oidc_name'] ?? '')),
|
||||
'oidc_client_id' => trim((string)($_POST['oidc_client_id'] ?? '')),
|
||||
'oidc_client_secret' => trim((string)($_POST['oidc_client_secret'] ?? '')),
|
||||
'oidc_redirect_uri' => trim((string)($_POST['oidc_redirect_uri'] ?? '')),
|
||||
];
|
||||
|
||||
// validations simples
|
||||
if ($in['allow_oidc']) {
|
||||
if ($in['oidc_issuer'] === '' || $in['oidc_client_id'] === '' || $in['oidc_client_secret'] === '' || $in['oidc_redirect_uri'] === '') {
|
||||
$err = 'OIDC activé mais champs incomplets.';
|
||||
}
|
||||
}
|
||||
|
||||
if (!$err) {
|
||||
config_repo_save($in);
|
||||
|
||||
// Mise à jour du .env
|
||||
$envPairs = [
|
||||
'OIDC_ISSUER' => $in['oidc_issuer'] !== '' ? $in['oidc_issuer'] : null,
|
||||
'OIDC_NAME' => $in['oidc_name'] !== '' ? $in['oidc_name'] : null,
|
||||
'OIDC_CLIENT_ID' => $in['oidc_client_id'] !== '' ? $in['oidc_client_id'] : null,
|
||||
'OIDC_CLIENT_SECRET' => $in['oidc_client_secret'] !== '' ? $in['oidc_client_secret'] : null,
|
||||
'OIDC_REDIRECT_URI' => $in['oidc_redirect_uri'] !== '' ? $in['oidc_redirect_uri'] : null,
|
||||
];
|
||||
env_set_pairs(BASE_PATH.'/.env', $envPairs);
|
||||
|
||||
$cfg = config_repo_get();
|
||||
$msg = 'Configuration enregistrée.';
|
||||
}
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Configuration authentification</title>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<link href="/assets/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<div class="container py-4">
|
||||
<h1 class="h3 mb-3">Configuration authentification</h1>
|
||||
|
||||
<?php if ($msg): ?><div class="alert alert-success"><?=htmlspecialchars($msg)?></div><?php endif; ?>
|
||||
<?php if ($err): ?><div class="alert alert-danger"><?=htmlspecialchars($err)?></div><?php endif; ?>
|
||||
|
||||
<form method="post" class="card p-3">
|
||||
<input type="hidden" name="csrf" value="<?=htmlspecialchars(csrf_token())?>">
|
||||
<fieldset class="mb-3">
|
||||
<legend class="h5">Modes de connexion</legend>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="allow_password" name="allow_password" <?= $cfg['allow_password'] ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="allow_password">Login + mot de passe autorisé</label>
|
||||
</div>
|
||||
<div class="form-check mt-2">
|
||||
<input class="form-check-input" type="checkbox" id="allow_oidc" name="allow_oidc" <?= $cfg['allow_oidc'] ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="allow_oidc">Connexion OIDC autorisée</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="mb-3">
|
||||
<legend class="h5">Inscriptions</legend>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="radio" id="reg_open" name="registrations_open" value="open" <?= $cfg['registrations_open'] ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="reg_open">Ouvertes à tous</label>
|
||||
</div>
|
||||
<div class="form-check mt-2">
|
||||
<input class="form-check-input" type="radio" id="reg_closed" name="registrations_open" value="closed" <?= !$cfg['registrations_open'] ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="reg_closed">Fermées</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="mb-3">
|
||||
<legend class="h5">Paramètres OIDC</legend>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Issuer URL</label>
|
||||
<input type="url" name="oidc_issuer" class="form-control" value="<?=htmlspecialchars((string)$cfg['oidc_issuer'])?>" placeholder="https://idp.example.com/realms/xxx">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Nom affiché</label>
|
||||
<input type="text" name="oidc_name" class="form-control" value="<?=htmlspecialchars((string)$cfg['oidc_name'])?>" placeholder="Keycloak, Azure AD…">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Client ID</label>
|
||||
<input type="text" name="oidc_client_id" class="form-control" value="<?=htmlspecialchars((string)$cfg['oidc_client_id'])?>">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Client Secret</label>
|
||||
<input type="password" name="oidc_client_secret" class="form-control" value="<?=htmlspecialchars((string)$cfg['oidc_client_secret'])?>">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Redirect URI</label>
|
||||
<input type="url" name="oidc_redirect_uri" class="form-control" value="<?=htmlspecialchars((string)$cfg['oidc_redirect_uri'])?>" placeholder="<?=htmlspecialchars(rtrim(getenv('APP_URL') ?: '', '/').'/oidc/callback')?>">
|
||||
</div>
|
||||
</div>
|
||||
<p class="form-text mt-2">Ces champs alimentent le fichier <code>.env</code>.</p>
|
||||
</fieldset>
|
||||
|
||||
<div class="mt-3">
|
||||
<button class="btn btn-primary" type="submit">Enregistrer</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
// projet : mug.a5l.fr
|
||||
// fichier : pages/login/index.php
|
||||
// version : 20251011
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Http\Csrf;
|
||||
|
||||
// --- Helpers AVANT tout usage ---
|
||||
if (!function_exists('env')) {
|
||||
function env(string $key, ?string $default = null): ?string
|
||||
{
|
||||
if (array_key_exists($key, $_ENV) && $_ENV[$key] !== '') {
|
||||
return (string)$_ENV[$key];
|
||||
}
|
||||
$v = getenv($key);
|
||||
if ($v !== false && $v !== '') {
|
||||
return (string)$v;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
if (!function_exists('db')) {
|
||||
function db(): \PDO
|
||||
{
|
||||
return \App\Infrastructure\Database::get();
|
||||
}
|
||||
}
|
||||
if (!function_exists('url')) {
|
||||
function url(string $path = '/'): string
|
||||
{
|
||||
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
|
||||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
|
||||
return $scheme . '://' . $host . $path;
|
||||
}
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
require_once dirname(__DIR__, 2) . '/src/SiteSettings.php';
|
||||
require_once dirname(__DIR__, 2) . '/src/mailer.php';
|
||||
|
||||
// Paramètres (env)
|
||||
$ttlMin = (int) env('MAGIC_LINK_TTL_MINUTES', '30');
|
||||
$coolMin = (int) env('MAGIC_COOLDOWN_MINUTES', '5');
|
||||
$winHours = (int) env('MAGIC_WINDOW_HOURS', '12');
|
||||
$maxPerWin = (int) env('MAGIC_MAX_PER_WINDOW', '5');
|
||||
|
||||
// --- return_to ---
|
||||
$defaultReturn = '/';
|
||||
$sanitize = static function (string $url) use ($defaultReturn): string {
|
||||
$url = trim($url);
|
||||
if ($url === '' || !str_starts_with($url, '/')) {
|
||||
return $defaultReturn;
|
||||
}
|
||||
return $url;
|
||||
};
|
||||
$returnTo = $sanitize((string)($_GET['return_to'] ?? ($_SERVER['HTTP_REFERER'] ?? $defaultReturn)));
|
||||
|
||||
// --- OIDC ---
|
||||
$oidcEnabled = (bool) (env('OIDC_ISSUER') && env('OIDC_CLIENT_ID'));
|
||||
$oidcLoginUrl = '/login/oidc' . ($returnTo ? ('?return_to=' . urlencode($returnTo)) : '');
|
||||
$oidcAuto = (isset($_GET['sso']) && $_GET['sso'] === '1') || (env('OIDC_AUTO', '0') === '1');
|
||||
if ($oidcEnabled && $oidcAuto) {
|
||||
header('Location: ' . $oidcLoginUrl, true, 302);
|
||||
exit;
|
||||
}
|
||||
|
||||
// --- form: demande de lien magique ---
|
||||
$errors = [];
|
||||
$okMsg = '';
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
|
||||
if (!Csrf::validate($_POST['_csrf'] ?? null)) {
|
||||
http_response_code(400);
|
||||
$errors[] = 'Jeton CSRF invalide.';
|
||||
} else {
|
||||
$email = strtolower(trim((string)($_POST['email'] ?? '')));
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = 'Adresse email invalide.';
|
||||
} else {
|
||||
// rate limit simple par email et IP
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
|
||||
if (strpos($ip, ',') !== false) {
|
||||
$ip = trim(explode(',', $ip, 2)[0]);
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
// purge expirés / consommés
|
||||
$pdo->prepare('DELETE FROM auth_magic_links WHERE email = :e AND (expires_at < NOW() OR consumed_at IS NOT NULL)')
|
||||
->execute([':e' => $email]);
|
||||
|
||||
// 1) cooldown: refuser si un envoi récent < coolMin
|
||||
$sql = sprintf(
|
||||
"SELECT 1 FROM auth_magic_links
|
||||
WHERE email = :e AND created_at >= NOW() - INTERVAL '%d minutes'
|
||||
LIMIT 1",
|
||||
max(0, $coolMin)
|
||||
);
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute([':e' => $email]);
|
||||
if ($stmt->fetchColumn()) {
|
||||
throw new RuntimeException(sprintf('Un lien vient d’être envoyé. Réessayez dans %d min.
|
||||
Si vous ne recevez toujours rien, envisagez d\'utiliser un fournisseur de messagerie respectueux de la vie privée,
|
||||
comme Proton Mail, Tuta, Posteo, Mailfence ou Infomaniak, qui garantissent un hébergement européen
|
||||
et ne revendent pas vos données. -- Cédrix, le 11/10/2025', $coolMin));
|
||||
}
|
||||
|
||||
// 2) plafond: maxPerWin liens sur winHours
|
||||
$sql = sprintf(
|
||||
"SELECT COUNT(*) FROM auth_magic_links
|
||||
WHERE email = :e AND created_at >= NOW() - INTERVAL '%d hours'",
|
||||
max(0, $winHours)
|
||||
);
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute([':e' => $email]);
|
||||
if ((int)$stmt->fetchColumn() >= $maxPerWin) {
|
||||
throw new RuntimeException('Quota atteint. Réessayez plus tard.');
|
||||
}
|
||||
|
||||
// Génère et enregistre le lien avec TTL ttlMin
|
||||
$raw = random_bytes(32);
|
||||
$token = rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
|
||||
|
||||
$sql = sprintf(
|
||||
"INSERT INTO auth_magic_links (id,email,token,created_at,expires_at,ip,user_agent,return_to)
|
||||
VALUES (gen_random_uuid(), :email, :token, NOW(), NOW() + INTERVAL '%d minutes', :ip, :ua, :rt)
|
||||
RETURNING token",
|
||||
max(1, $ttlMin)
|
||||
);
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute([
|
||||
':email' => $email,
|
||||
':token' => $token,
|
||||
':ip' => $ip,
|
||||
':ua' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 512),
|
||||
':rt' => ($returnTo !== '/' ? $returnTo : null),
|
||||
]);
|
||||
$pdo->commit();
|
||||
|
||||
// construit l'URL et envoie le mail
|
||||
$magicUrl = url('/login/magic.php') . '?token=' . urlencode($token);
|
||||
$siteName = htmlspecialchars(env('SMTP_FROM_NAME', 'varlog'), ENT_QUOTES);
|
||||
$html = <<<HTML
|
||||
<p>Bonjour,</p>
|
||||
<p>Cliquez sur le lien ci-dessous pour vous connecter à <strong>{$siteName}</strong> :</p>
|
||||
<p><a href="{$magicUrl}">{$magicUrl}</a></p>
|
||||
<p>Ce lien est valable {$ttlMin} minutes et ne peut être utilisé qu'une seule fois.</p>
|
||||
<p>Si vous n'avez pas demandé ce lien, ignorez cet email.</p>
|
||||
HTML;
|
||||
envoyer_mail_smtp(
|
||||
$email,
|
||||
"Votre lien de connexion — {$siteName}",
|
||||
$html,
|
||||
null,
|
||||
['bypass_rate_limit' => true]
|
||||
);
|
||||
|
||||
// message utilisateur
|
||||
$okMsg = 'Un lien vient d’être envoyé. Vérifiez votre boîte de réception et le dossier spam/indésirables.';
|
||||
|
||||
} catch (\Throwable $ex) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
$errors[] = $ex->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$csrf = Csrf::token();
|
||||
|
||||
ob_start();
|
||||
?>
|
||||
<style>.or-sep{display:flex;align-items:center;gap:.75rem;margin:1.25rem 0}.or-sep::before,.or-sep::after{content:"";flex:1;height:1px;background:#ddd}</style>
|
||||
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-12 col-sm-10 col-md-7 col-lg-5">
|
||||
<h1 class="mb-1">Connexion</h1>
|
||||
<p class="text-muted mb-4">Vous n'êtes pas connecté.</p>
|
||||
|
||||
<?php foreach ($errors as $e): ?>
|
||||
<div class="alert alert-danger"><?= htmlspecialchars($e, ENT_QUOTES) ?></div>
|
||||
<?php endforeach; ?>
|
||||
<?php if ($okMsg): ?>
|
||||
<div class="alert alert-success"><?= htmlspecialchars($okMsg, ENT_QUOTES) ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($oidcEnabled): ?>
|
||||
<div class="mb-3">
|
||||
<a class="btn btn-primary w-100" href="<?= htmlspecialchars($oidcLoginUrl, ENT_QUOTES) ?>">Se connecter avec A5L</a>
|
||||
</div>
|
||||
<div class="or-sep"><span>ou</span></div>
|
||||
<?php else: ?>
|
||||
<div class="alert alert-warning">A5L indisponible : configurez <code>OIDC_ISSUER</code> et <code>OIDC_CLIENT_ID</code> dans <code>.env</code>.</div>
|
||||
<div class="or-sep"><span>ou</span></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" action="/login<?= $returnTo ? ('?return_to=' . urlencode($returnTo)) : '' ?>" novalidate>
|
||||
<input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES) ?>">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="email">Adresse email</label>
|
||||
<input class="form-control" id="email" type="email" name="email" required autocomplete="email" inputmode="email" placeholder="vous@domaine.tld">
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">Recevoir un lien magique</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
$content = ob_get_clean();
|
||||
$title = 'Connexion';
|
||||
include BASE_PATH . '/templates/layout.php';
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
// projet : mug.a5l.fr
|
||||
// fichier : pages/login/magic.php
|
||||
// version : 20251011
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
|
||||
// si tu as un service pour ouvrir une session
|
||||
|
||||
if (!function_exists('db')) {
|
||||
function db(): PDO
|
||||
{
|
||||
return \App\Infrastructure\Database::get();
|
||||
}
|
||||
}
|
||||
if (!function_exists('url')) {
|
||||
function url(string $path = '/'): string
|
||||
{
|
||||
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
|
||||
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
|
||||
return $scheme . '://' . $host . $path;
|
||||
}
|
||||
}
|
||||
|
||||
$token = (string)($_GET['token'] ?? '');
|
||||
if ($token === '' || preg_match('/[^A-Za-z0-9\-\_]/', $token)) {
|
||||
http_response_code(400);
|
||||
exit('Lien invalide.');
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
// récupère lien non consommé et non expiré
|
||||
$sql = 'SELECT id, email, token, created_at, expires_at, consumed_at, return_to
|
||||
FROM auth_magic_links
|
||||
WHERE token = :t
|
||||
FOR UPDATE';
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute([':t' => $token]);
|
||||
$row = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$row) {
|
||||
throw new RuntimeException('Lien inconnu.');
|
||||
}
|
||||
if ($row['consumed_at'] !== null) {
|
||||
throw new RuntimeException('Lien déjà utilisé.');
|
||||
}
|
||||
if (strtotime((string)$row['expires_at']) < time()) {
|
||||
throw new RuntimeException('Lien expiré.');
|
||||
}
|
||||
|
||||
// consomme le lien
|
||||
$pdo->prepare('UPDATE auth_magic_links SET consumed_at = NOW() WHERE id = :id')->execute([':id' => $row['id']]);
|
||||
$pdo->commit();
|
||||
|
||||
if (session_status() !== PHP_SESSION_ACTIVE) {
|
||||
session_start();
|
||||
}
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['user_email'] = strtolower(trim((string)$row['email']));
|
||||
|
||||
$dest = $row['return_to'] ?? '/';
|
||||
// sécurité: ne renvoyer que des chemins relatifs
|
||||
if (!is_string($dest) || !str_starts_with($dest, '/')) {
|
||||
$dest = '/';
|
||||
}
|
||||
header('Location: ' . $dest, true, 303);
|
||||
exit;
|
||||
} catch (\Throwable $e) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
http_response_code(400);
|
||||
echo htmlspecialchars($e->getMessage(), ENT_QUOTES);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
// proxy vers pages/oidc/start.php avec flow=login
|
||||
$_GET['flow'] = 'login';
|
||||
require_once dirname(__DIR__) . '/oidc/start.php';
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
define('BASE_PATH', realpath(__DIR__ . '/../'));
|
||||
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
require_once BASE_PATH . '/src/auth.php';
|
||||
require_once BASE_PATH . '/config/config.php';
|
||||
|
||||
$logoutUrl = ssoLogoutUrl();
|
||||
|
||||
$_SESSION = [];
|
||||
if (ini_get('session.use_cookies')) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(
|
||||
session_name(),
|
||||
'',
|
||||
time() - 42000,
|
||||
$params['path'],
|
||||
$params['domain'],
|
||||
$params['secure'],
|
||||
$params['httponly']
|
||||
);
|
||||
}
|
||||
session_destroy();
|
||||
|
||||
header('Location: ' . $logoutUrl, true, 303);
|
||||
exit;
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
|
||||
if (!function_exists('env')) {
|
||||
function env(string $key, ?string $default = null): ?string
|
||||
{
|
||||
if (array_key_exists($key, $_ENV) && $_ENV[$key] !== '') {
|
||||
return (string)$_ENV[$key];
|
||||
}
|
||||
$v = getenv($key);
|
||||
if ($v !== false && $v !== '') {
|
||||
return (string)$v;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
$debug = (env('APP_DEBUG', '0') === '1');
|
||||
|
||||
$OIDC_ISSUER = rtrim((string)(env('OIDC_ISSUER') ?? ''), '/');
|
||||
$OIDC_CLIENT_ID = (string)(env('OIDC_CLIENT_ID') ?? '');
|
||||
$OIDC_CLIENT_SECRET = (string)(env('OIDC_CLIENT_SECRET') ?? '');
|
||||
$OIDC_REDIRECT_URI = (string)(env('OIDC_REDIRECT_URI') ?: url('oidc/callback'));
|
||||
|
||||
if (!$OIDC_ISSUER || !$OIDC_CLIENT_ID || !$OIDC_REDIRECT_URI) {
|
||||
http_response_code(500);
|
||||
echo $debug ? 'OIDC config manquante.' : 'Erreur.';
|
||||
exit;
|
||||
}
|
||||
|
||||
$tokenEndpoint = $OIDC_ISSUER . '/protocol/openid-connect/token';
|
||||
$userInfoEndpoint = $OIDC_ISSUER . '/protocol/openid-connect/userinfo';
|
||||
|
||||
if (!isset($_GET['state'], $_SESSION['oidc_state']) || !hash_equals((string)$_SESSION['oidc_state'], (string)$_GET['state'])) {
|
||||
http_response_code(400);
|
||||
echo $debug ? 'State invalide.' : 'Requête invalide.';
|
||||
exit;
|
||||
}
|
||||
unset($_SESSION['oidc_state']);
|
||||
|
||||
if (empty($_GET['code'])) {
|
||||
http_response_code(400);
|
||||
echo $debug ? 'Code manquant.' : 'Requête invalide.';
|
||||
exit;
|
||||
}
|
||||
$code = (string)$_GET['code'];
|
||||
|
||||
$codeVerifier = $_SESSION['oidc_code_verifier'] ?? null;
|
||||
unset($_SESSION['oidc_code_verifier'], $_SESSION['oidc_nonce']);
|
||||
|
||||
if (!$codeVerifier) {
|
||||
http_response_code(400);
|
||||
echo $debug ? 'PKCE code_verifier manquant.' : 'Requête invalide.';
|
||||
exit;
|
||||
}
|
||||
|
||||
// Échange code → tokens
|
||||
$post = [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $code,
|
||||
'redirect_uri' => $OIDC_REDIRECT_URI,
|
||||
'client_id' => $OIDC_CLIENT_ID,
|
||||
'code_verifier' => $codeVerifier,
|
||||
];
|
||||
if ($OIDC_CLIENT_SECRET !== '') {
|
||||
$post['client_secret'] = $OIDC_CLIENT_SECRET;
|
||||
}
|
||||
|
||||
$ch = curl_init($tokenEndpoint);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => http_build_query($post, '', '&', PHP_QUERY_RFC3986),
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => true,
|
||||
CURLOPT_SSL_VERIFYHOST => 2,
|
||||
]);
|
||||
$tokenResponse = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlErr = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($tokenResponse === false || $httpCode !== 200) {
|
||||
http_response_code(500);
|
||||
echo $debug ? 'Échec échange token : ' . htmlspecialchars($curlErr ?: (string)$tokenResponse) : 'Erreur d\'authentification.';
|
||||
exit;
|
||||
}
|
||||
|
||||
$tokens = json_decode((string)$tokenResponse, true) ?: [];
|
||||
$accessToken = $tokens['access_token'] ?? null;
|
||||
$idToken = $tokens['id_token'] ?? null;
|
||||
|
||||
if (!$accessToken) {
|
||||
http_response_code(500);
|
||||
echo $debug ? 'Access token manquant.' : 'Erreur d\'authentification.';
|
||||
exit;
|
||||
}
|
||||
|
||||
// UserInfo
|
||||
$ch = curl_init($userInfoEndpoint);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $accessToken],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_SSL_VERIFYPEER => true,
|
||||
CURLOPT_SSL_VERIFYHOST => 2,
|
||||
]);
|
||||
$userInfoResponse = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($userInfoResponse === false || $httpCode !== 200) {
|
||||
http_response_code(500);
|
||||
echo $debug ? 'Échec UserInfo.' : 'Erreur d\'authentification.';
|
||||
exit;
|
||||
}
|
||||
|
||||
$claims = json_decode((string)$userInfoResponse, true) ?: [];
|
||||
$email = $claims['email'] ?? null;
|
||||
|
||||
// Fallback : lire l'email depuis le payload du id_token
|
||||
if (!$email && $idToken && substr_count($idToken, '.') === 2) {
|
||||
[, $p, ] = explode('.', $idToken, 3);
|
||||
$payload = json_decode((string)base64_decode(strtr($p, '-_', '+/'), true), true);
|
||||
if (is_array($payload) && !empty($payload['email'])) {
|
||||
$email = $payload['email'];
|
||||
}
|
||||
}
|
||||
|
||||
if (!$email) {
|
||||
http_response_code(400);
|
||||
echo $debug ? 'Email non fourni par l\'IdP.' : 'Impossible de récupérer votre email.';
|
||||
exit;
|
||||
}
|
||||
|
||||
// Nom d'affichage depuis les claims SSO
|
||||
$ssoName = '';
|
||||
if (!empty($claims['given_name']) || !empty($claims['family_name'])) {
|
||||
$ssoName = trim(($claims['given_name'] ?? '') . ' ' . ($claims['family_name'] ?? ''));
|
||||
} elseif (!empty($claims['name'])) {
|
||||
$ssoName = trim($claims['name']);
|
||||
} elseif (!empty($claims['preferred_username'])) {
|
||||
$ssoName = trim($claims['preferred_username']);
|
||||
}
|
||||
|
||||
// Charge le nom personnalisé depuis la base (prioritaire sur le SSO)
|
||||
require_once dirname(__DIR__, 2) . '/src/auth.php';
|
||||
$pdo = dbPdo();
|
||||
$dbName = '';
|
||||
if ($pdo) {
|
||||
try {
|
||||
$st = $pdo->prepare('SELECT display_name FROM user_profiles WHERE email = :e');
|
||||
$st->execute([':e' => strtolower(trim($email))]);
|
||||
$dbName = (string)($st->fetchColumn() ?: '');
|
||||
} catch (\Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
if ($dbName !== '') {
|
||||
// Nom personnalisé existant → on le conserve, le SSO ne l'écrase pas
|
||||
$sessionName = $dbName;
|
||||
} else {
|
||||
// Première connexion → on persiste le nom SSO
|
||||
$sessionName = $ssoName;
|
||||
if ($ssoName !== '' && $pdo) {
|
||||
try {
|
||||
$pdo->prepare(
|
||||
'INSERT INTO user_profiles (email, display_name, updated_at)
|
||||
VALUES (:e, :n, now())
|
||||
ON CONFLICT (email) DO NOTHING'
|
||||
)->execute([':e' => strtolower(trim($email)), ':n' => $ssoName]);
|
||||
} catch (\Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ouvre la session authentifiée
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['user_email'] = strtolower(trim($email));
|
||||
$_SESSION['user_display_name'] = $sessionName;
|
||||
$_SESSION['oidc'] = [
|
||||
'issuer' => $OIDC_ISSUER,
|
||||
'sub' => $claims['sub'] ?? null,
|
||||
'access_token' => $accessToken,
|
||||
'id_token' => $idToken,
|
||||
'expires_at' => time() + (int)($tokens['expires_in'] ?? 3600),
|
||||
];
|
||||
|
||||
$target = $_SESSION['oidc_return_to'] ?? '/';
|
||||
unset($_SESSION['oidc_return_to'], $_SESSION['oidc_flow']);
|
||||
if (!is_string($target) || $target === '' || $target[0] !== '/') {
|
||||
$target = '/';
|
||||
}
|
||||
header('Location: ' . $target, true, 303);
|
||||
exit;
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
// projet : mug.a5l.fr
|
||||
// fichier : pages/oidc/me.php
|
||||
// version : 20251005
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
|
||||
function maskToken(?string $t): string
|
||||
{
|
||||
if (!$t) {
|
||||
return '';
|
||||
}
|
||||
$len = strlen($t);
|
||||
if ($len <= 12) {
|
||||
return str_repeat('•', $len);
|
||||
}
|
||||
return substr($t, 0, 6) . str_repeat('•', max(0, $len - 12)) . substr($t, -6);
|
||||
}
|
||||
function b64url_decode_str(string $s): string|false
|
||||
{
|
||||
$s = strtr($s, '-_', '+/');
|
||||
$pad = strlen($s) % 4;
|
||||
if ($pad) {
|
||||
$s .= str_repeat('=', 4 - $pad);
|
||||
}
|
||||
return base64_decode($s, true);
|
||||
}
|
||||
function decode_jwt(string $jwt): array
|
||||
{
|
||||
if (substr_count($jwt, '.') !== 2) {
|
||||
return [];
|
||||
}
|
||||
[, $payload, ] = explode('.', $jwt, 3);
|
||||
$json = b64url_decode_str($payload);
|
||||
if ($json === false) {
|
||||
return [];
|
||||
}
|
||||
$arr = json_decode($json, true);
|
||||
return is_array($arr) ? $arr : [];
|
||||
}
|
||||
|
||||
$env = static function (string $k, ?string $d = null): ?string {
|
||||
if (array_key_exists($k, $_ENV) && $_ENV[$k] !== '') {
|
||||
return (string)$_ENV[$k];
|
||||
}
|
||||
$v = getenv($k);
|
||||
if ($v !== false && $v !== '') {
|
||||
return (string)$v;
|
||||
}
|
||||
return $d;
|
||||
};
|
||||
|
||||
$debugEnabled = ($env('DEBUG_OIDC') === 'true') || (isset($_GET['debug']) && $_GET['debug'] === '1');
|
||||
|
||||
$oidc = $_SESSION['oidc'] ?? [];
|
||||
$claims = $_SESSION['oidc_userinfo'] ?? [];
|
||||
$issuer = (string)($oidc['issuer'] ?? '');
|
||||
$sub = (string)($oidc['sub'] ?? '');
|
||||
$idToken = (string)($oidc['id_token'] ?? '');
|
||||
$accTok = (string)($oidc['access_token'] ?? '');
|
||||
$expAt = (int) ($oidc['expires_at'] ?? 0);
|
||||
|
||||
$now = time();
|
||||
$left = $expAt ? max(0, $expAt - $now) : null;
|
||||
|
||||
// Fallback 1 : si pas de claims userinfo, essayer de les lire dans l'id_token
|
||||
if (!$claims && $idToken) {
|
||||
$claims = decode_jwt($idToken);
|
||||
}
|
||||
|
||||
// Fallback 2 (debug) : tenter un appel live au UserInfo si access_token présent
|
||||
if ($debugEnabled && $claims === [] && $accTok && $issuer) {
|
||||
$userinfoEndpoint = rtrim($issuer, '/') . '/protocol/openid-connect/userinfo';
|
||||
$ch = curl_init($userinfoEndpoint);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $accTok],
|
||||
CURLOPT_TIMEOUT => 6,
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
if ($resp !== false && $code === 200) {
|
||||
$tmp = json_decode((string)$resp, true);
|
||||
if (is_array($tmp)) {
|
||||
$claims = $tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extraire rôles groupés (Keycloak)
|
||||
$roles = [];
|
||||
if (isset($claims['realm_access']['roles']) && is_array($claims['realm_access']['roles'])) {
|
||||
$roles = array_merge($roles, $claims['realm_access']['roles']);
|
||||
}
|
||||
if (isset($claims['resource_access']) && is_array($claims['resource_access'])) {
|
||||
foreach ($claims['resource_access'] as $clientId => $data) {
|
||||
if (!empty($data['roles']) && is_array($data['roles'])) {
|
||||
foreach ($data['roles'] as $r) {
|
||||
$roles[] = $clientId . ':' . $r;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$roles = array_values(array_unique($roles));
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>OIDC • Profil</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="/assets/bootstrap/bootstrap.min.css" rel="stylesheet">
|
||||
<style>
|
||||
.kv { display:grid; grid-template-columns: 220px 1fr; gap:.5rem 1rem; }
|
||||
.kv dt { font-weight: 600; color: #555; }
|
||||
pre { background: #f8f9fa; padding: .75rem; border-radius: .5rem; overflow:auto; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="container py-4">
|
||||
<h1 class="mb-4">Profil A5L</h1>
|
||||
|
||||
<?php if (!$oidc): ?>
|
||||
<div class="alert alert-warning">Aucune session A5L. Connecte-toi via A5L d'abord.</div>
|
||||
<?php else: ?>
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">Session / Jetons</div>
|
||||
<div class="card-body">
|
||||
<dl class="kv">
|
||||
<dt>Issuer</dt><dd><?= htmlspecialchars($issuer) ?></dd>
|
||||
<dt>Subject (sub)</dt><dd><?= htmlspecialchars($sub) ?></dd>
|
||||
<dt>ID Token</dt><dd><code><?= htmlspecialchars(maskToken($idToken)) ?></code></dd>
|
||||
<dt>Access Token</dt><dd><code><?= htmlspecialchars(maskToken($accTok)) ?></code></dd>
|
||||
<dt>Expire à</dt><dd><?= $expAt ? date('Y-m-d H:i:s', $expAt) : '—' ?></dd>
|
||||
<dt>Temps restant</dt><dd><?= $left !== null ? ($left . ' s') : '—' ?></dd>
|
||||
</dl>
|
||||
<?php if ($debugEnabled): ?>
|
||||
<details class="mt-3">
|
||||
<summary>Voir jetons non masqués (danger)</summary>
|
||||
<div class="mt-2">
|
||||
<div><strong>ID Token</strong></div>
|
||||
<pre><?= htmlspecialchars($idToken) ?></pre>
|
||||
<div><strong>Access Token</strong></div>
|
||||
<pre><?= htmlspecialchars($accTok) ?></pre>
|
||||
</div>
|
||||
</details>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">Claims</div>
|
||||
<div class="card-body">
|
||||
<dl class="kv">
|
||||
<dt>Email</dt><dd><?= htmlspecialchars((string)($claims['email'] ?? '')) ?></dd>
|
||||
<dt>Preferred username</dt><dd><?= htmlspecialchars((string)($claims['preferred_username'] ?? '')) ?></dd>
|
||||
<dt>Given name</dt><dd><?= htmlspecialchars((string)($claims['given_name'] ?? '')) ?></dd>
|
||||
<dt>Family name</dt><dd><?= htmlspecialchars((string)($claims['family_name'] ?? '')) ?></dd>
|
||||
<dt>Name</dt><dd><?= htmlspecialchars((string)($claims['name'] ?? '')) ?></dd>
|
||||
<dt>Locale</dt><dd><?= htmlspecialchars((string)($claims['locale'] ?? '')) ?></dd>
|
||||
<dt>Rôles</dt>
|
||||
<dd>
|
||||
<?php if ($roles): ?>
|
||||
<ul class="mb-0">
|
||||
<?php foreach ($roles as $r): ?>
|
||||
<li><?= htmlspecialchars((string)$r) ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php else: ?>
|
||||
—
|
||||
<?php endif; ?>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<?php if ($debugEnabled): ?>
|
||||
<h6 class="mt-3">Claims (JSON complet)</h6>
|
||||
<pre><?= htmlspecialchars(json_encode($claims, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!$claims): ?>
|
||||
<div class="alert alert-info mt-3">
|
||||
Aucun claim reçu. Vérifie que ton <code>callback</code> remplit bien <code>$_SESSION['oidc_userinfo']</code> ou que l’<code>ID Token</code> contient les champs.
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<a class="btn btn-secondary" href="<?= htmlspecialchars(url('')) ?>">Retour</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
|
||||
require_once dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
require_once dirname(__DIR__, 2) . '/config/config.php';
|
||||
|
||||
if (!function_exists('env')) {
|
||||
function env(string $key, ?string $default = null): ?string
|
||||
{
|
||||
if (array_key_exists($key, $_ENV) && $_ENV[$key] !== '') {
|
||||
return (string)$_ENV[$key];
|
||||
}
|
||||
$v = getenv($key);
|
||||
if ($v !== false && $v !== '') {
|
||||
return (string)$v;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
$flow = $_GET['flow'] ?? 'login'; // 'login' ou 'register'
|
||||
if (!in_array($flow, ['login','register'], true)) {
|
||||
$flow = 'login';
|
||||
}
|
||||
|
||||
// return_to (URL relative uniquement)
|
||||
$defaultReturn = '/';
|
||||
$rawReturn = $_GET['return_to'] ?? ($_SERVER['HTTP_REFERER'] ?? $defaultReturn);
|
||||
$returnTo = (is_string($rawReturn) && str_starts_with($rawReturn, '/')) ? $rawReturn : $defaultReturn;
|
||||
|
||||
// Mémorise flow + cible
|
||||
$_SESSION['oidc_flow'] = $flow;
|
||||
$_SESSION['oidc_return_to'] = $returnTo;
|
||||
|
||||
// --- OIDC conf ---
|
||||
$issuer = rtrim((string)env('OIDC_ISSUER', ''), '/');
|
||||
$clientId = (string)env('OIDC_CLIENT_ID', '');
|
||||
$redirectUri = (string)(env('OIDC_REDIRECT_URI') ?: url('oidc/callback'));
|
||||
if (!$issuer || !$clientId || !$redirectUri) {
|
||||
http_response_code(500);
|
||||
echo 'OIDC non configuré (OIDC_ISSUER / OIDC_CLIENT_ID / OIDC_REDIRECT_URI).';
|
||||
exit;
|
||||
}
|
||||
|
||||
// --- Endpoints & PKCE ---
|
||||
$authEndpoint = $issuer . '/protocol/openid-connect/auth';
|
||||
$state = bin2hex(random_bytes(16));
|
||||
$nonce = bin2hex(random_bytes(16));
|
||||
$codeVerifier = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
|
||||
|
||||
$_SESSION['oidc_state'] = $state;
|
||||
$_SESSION['oidc_nonce'] = $nonce;
|
||||
$_SESSION['oidc_code_verifier'] = $codeVerifier;
|
||||
|
||||
// --- URL d’auth ---
|
||||
$params = [
|
||||
'response_type' => 'code',
|
||||
'client_id' => $clientId,
|
||||
'redirect_uri' => $redirectUri,
|
||||
'scope' => 'openid email profile',
|
||||
'state' => $state,
|
||||
'nonce' => $nonce,
|
||||
'code_challenge' => $codeChallenge,
|
||||
'code_challenge_method' => 'S256',
|
||||
'ui_locales' => 'fr',
|
||||
];
|
||||
|
||||
header('Location: ' . $authEndpoint . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986), true, 302);
|
||||
exit;
|
||||
@@ -0,0 +1,16 @@
|
||||
User-agent: *
|
||||
Disallow: /?action=edit
|
||||
Disallow: /?action=create
|
||||
Disallow: /?action=admin
|
||||
Disallow: /?action=delete
|
||||
Disallow: /?action=diff
|
||||
Disallow: /?action=categories
|
||||
Disallow: /?action=add_files
|
||||
Disallow: /?action=import_image
|
||||
Disallow: /?action=sources
|
||||
Disallow: /?action=profile
|
||||
Disallow: /login
|
||||
Disallow: /logout.php
|
||||
Disallow: /oidc/
|
||||
|
||||
Sitemap: https://varlog.a5l.fr/sitemap.xml
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
// Ce fichier est conservé pour compatibilité ascendante.
|
||||
// Toute la logique est désormais dans index.php.
|
||||
header('Location: /' . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : ''), true, 301);
|
||||
exit;
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
define('BASE_PATH', realpath(__DIR__ . '/../'));
|
||||
|
||||
require_once BASE_PATH . '/src/helpers.php';
|
||||
require_once BASE_PATH . '/config/config.php';
|
||||
require_once BASE_PATH . '/src/ArticleManager.php';
|
||||
|
||||
$articles = new ArticleManager(BASE_PATH . '/data');
|
||||
$privateCats = $articles->getPrivateCategories();
|
||||
|
||||
$published = array_filter($articles->getAll(true), static function (array $a) use ($privateCats): bool {
|
||||
$cat = trim($a['category'] ?? '');
|
||||
if ($cat !== '' && in_array($cat, $privateCats, true)) {
|
||||
return false;
|
||||
}
|
||||
if (strtotime((string)($a['published_at'] ?? '')) > time()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
header('Content-Type: application/xml; charset=UTF-8');
|
||||
header('X-Robots-Tag: noindex');
|
||||
|
||||
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
|
||||
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
|
||||
|
||||
// Homepage
|
||||
echo ' <url>' . "\n";
|
||||
echo ' <loc>' . htmlspecialchars(rtrim(APP_URL, '/') . '/') . '</loc>' . "\n";
|
||||
echo ' <changefreq>daily</changefreq>' . "\n";
|
||||
echo ' <priority>1.0</priority>' . "\n";
|
||||
echo ' </url>' . "\n";
|
||||
|
||||
foreach ($published as $article) {
|
||||
$loc = htmlspecialchars(rtrim(APP_URL, '/') . '/post/' . rawurlencode($article['slug'] ?? ''));
|
||||
$lastmod = date('Y-m-d', strtotime((string)($article['updated_at'] ?? $article['published_at'] ?? 'now')));
|
||||
echo ' <url>' . "\n";
|
||||
echo ' <loc>' . $loc . '</loc>' . "\n";
|
||||
echo ' <lastmod>' . $lastmod . '</lastmod>' . "\n";
|
||||
echo ' <changefreq>monthly</changefreq>' . "\n";
|
||||
echo ' <priority>0.8</priority>' . "\n";
|
||||
echo ' </url>' . "\n";
|
||||
}
|
||||
|
||||
echo '</urlset>' . "\n";
|
||||
Reference in New Issue
Block a user