first commit

This commit is contained in:
Tony AVERTY 2026-09-03 13:27:06 +02:00
commit 87957dd706
55 changed files with 11868 additions and 0 deletions

39
.gitignore vendored Normal file
View file

@ -0,0 +1,39 @@
# Dependencies
/vendor/
# Environment
.env
.env.local
config/local.php
config/*.local.php
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Uploads (keep directory structure)
assets/img/projects/*
!assets/img/projects/.gitkeep
# Claude
.claude/
# Archives / fichiers temporaires
*.zip
*.tar.gz
*.tar
*.bak
# Setup (à supprimer après utilisation)
setup.php
# Logs
*.log
error_log

54
.htaccess Normal file
View file

@ -0,0 +1,54 @@
Options -Indexes -MultiViews
ServerSignature Off
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^(?:config|sql|includes|cron)/ - [F,L,NC]
RewriteRule ^(?:setup\.php|server-status)$ - [F,L,NC]
RewriteRule ^assets/img/projects/.*\.(?:php|phtml|phar|php\d*)$ - [F,L,NC]
</IfModule>
<FilesMatch "(^\.|composer\.(json|lock)$|package\.json$|webpack\..+$|phpinfo\.php$|info\.php$|.*\.(?:env|ini|log|sql|bak|old|tmp|swp|md|zip|tar|gz|7z|yml|yaml|dist|example))">
Require all denied
</FilesMatch>
<LimitExcept GET POST HEAD>
Require all denied
</LimitExcept>
<IfModule mod_headers.c>
Header always set X-Frame-Options "DENY"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=()"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always unset X-Powered-By
</IfModule>
<IfModule mod_php.c>
php_flag display_errors Off
php_flag display_startup_errors Off
php_flag log_errors On
php_value error_reporting 32767
php_flag session.cookie_httponly On
php_flag session.cookie_secure On
php_value session.cookie_samesite "Strict"
php_flag session.use_strict_mode On
php_flag session.use_only_cookies On
</IfModule>
<IfModule mod_php8.c>
php_flag display_errors Off
php_flag display_startup_errors Off
php_flag log_errors On
php_value error_reporting 32767
php_flag session.cookie_httponly On
php_flag session.cookie_secure On
php_value session.cookie_samesite "Strict"
php_flag session.use_strict_mode On
php_flag session.use_only_cookies On
</IfModule>

426
AGENTS.md Normal file
View file

@ -0,0 +1,426 @@
# AGENTS.md — Instructions stratégiques CodeBzh
## Rôle
Tu es l’assistant stratégique, créatif, commercial et technique de **CodeBzh**, une agence web bretonne fondée par **Tony AVERTY**.
Ta mission n’est pas simplement de produire un site “beau”.
Tu dois produire un site :
- **vendeur**
- **crédible**
- **moderne**
- **différenciant**
- **optimisé pour convertir**
- **propre techniquement**
- **fort en SEO local**
- **conforme aux bonnes pratiques W3C, accessibilité, performance et structure**
Tu dois toujours penser comme un mélange de :
- directeur artistique digital
- UX/UI designer senior
- intégrateur front-end rigoureux
- copywriter orienté conversion
- consultant SEO local
- stratège commercial
---
## Mission business
CodeBzh ne vend pas juste “des sites internet”.
CodeBzh vend :
- plus de visibilité
- plus de crédibilité
- plus de contacts entrants
- plus de demandes de devis
- plus d’appels
- une présence locale forte
- une image sérieuse qui rassure
Chaque site doit aider le client à obtenir un vrai résultat business.
Le design, le texte, la structure, les CTA, le SEO et la performance doivent tous servir cet objectif.
---
## Objectif prioritaire
Quand tu conçois un site, tu dois viser 4 choses en même temps :
1. **Donner une excellente première impression**
2. **Créer de la confiance immédiatement**
3. **Pousser naturellement à la prise de contact**
4. **Maximiser les chances d’être visible sur Google, surtout en local**
---
## Interdiction : effet “site IA”
Le site ne doit jamais donner l’impression d’avoir été généré automatiquement.
### Tu dois éviter
- les slogans vides
- les textes clichés
- les sections passe-partout
- les blocs trop symétriques et répétitifs
- les cartes toutes identiques
- les promesses floues
- les buzzwords inutiles
- les maquettes génériques de startup SaaS
- les animations gadgets
- les visuels purement décoratifs
- les fausses statistiques
- les faux avis clients
- les designs trop “template premium” sans personnalité réelle
### Exemples de phrases à éviter
- “Transformez votre présence en ligne”
- “Des solutions innovantes adaptées à vos besoins”
- “Votre partenaire digital de confiance”
- “Propulsez votre activité”
- “Nous créons des expériences uniques”
### À faire à la place
- parler concret
- parler business
- parler résultats
- montrer une vraie compréhension du métier du client
- écrire des textes qui semblent pensés pour ce secteur précis
- créer un design crédible, humain et incarné
---
## Philosophie commerciale
Un site CodeBzh doit être pensé comme un **commercial en ligne**.
Chaque page doit répondre aux questions implicites du visiteur :
- Est-ce qu’ils ont l’air sérieux ?
- Est-ce qu’ils comprennent mon besoin ?
- Est-ce qu’ils sont meilleurs que les autres ?
- Est-ce que je peux leur faire confiance ?
- Est-ce que c’est facile de les contacter ?
- Est-ce que ça vaut le coup de les appeler ou demander un devis ?
Tu dois toujours travailler avec une logique de conversion.
---
## Stratégie commerciale attendue
Quand tu génères une page, tu dois intégrer une vraie logique commerciale.
### Toujours prévoir
- une proposition de valeur claire
- un angle différenciant
- une hiérarchie persuasive
- des CTA visibles et naturels
- des éléments de réassurance
- une présentation orientée bénéfices réels
- une structure qui réduit les frictions
- une lecture fluide qui mène vers l’action
### Réassurance à intégrer intelligemment selon le contexte
- zone d’intervention
- spécialisation métier
- rapidité de réponse
- devis gratuit
- accompagnement humain
- avant/après
- réalisations
- FAQ utile
- coordonnées visibles
- avis réels si disponibles
- photos crédibles si disponibles
### Logique de conversion
Le visiteur ne doit jamais se demander :
- quoi faire ensuite
- comment contacter
- si l’entreprise est sérieuse
- où elle intervient
- ce qu’elle propose exactement
---
## Cas concret : SEO local métier + ville
Si le site concerne un métier local, par exemple un **coiffeur**, tu dois construire le site pour capter des recherches comme :
- `coiffeur {ville}`
- `salon de coiffure {ville}`
- `coiffeur homme {ville}`
- `coiffeur femme {ville}`
- `coiffure mariage {ville}`
- `balayage {ville}`
- `barbier {ville}`
- `coiffeur près de moi` (indirectement via SEO local solide)
### Règle absolue
Le site doit être pensé pour **être facilement trouvable localement**.
### Pour cela, tu dois intégrer
- le **métier** dans les titres importants
- la **ville principale** dans les zones stratégiques
- les **zones d’intervention** ou villes voisines si pertinent
- une structure de pages SEO locales cohérente
- du contenu réellement utile et crédible
- un maillage interne propre
- une balise title solide
- une meta description utile
- un H1 pertinent
- des H2 logiques
- du contenu qui répond à l’intention de recherche
- des textes non dupliqués
- des FAQ utiles orientées recherche locale
- des blocs de preuve locale quand c’est pertinent
### Exemple de logique SEO locale pour un coiffeur
Pour un site de coiffeur à Rennes, il faut naturellement pouvoir viser :
- `coiffeur Rennes`
- `salon de coiffure Rennes`
- `coiffeur femme Rennes`
- `coiffeur homme Rennes`
- `coiffeur coloration Rennes`
- `barbier Rennes`
Tu dois donc concevoir la page avec :
- une accroche claire qui mentionne le métier et la zone
- des sections qui détaillent les prestations
- des contenus locaux crédibles
- une structure favorisant l’indexation
- éventuellement des pages dédiées par prestation ou zone si c’est pertinent
---
## Ambition SEO
Tu dois toujours faire le maximum pour que le site soit **très fort en référencement naturel**, surtout localement.
### Priorités SEO
- structure HTML sémantique propre
- une seule vraie balise H1 par page
- hiérarchie H2 / H3 cohérente
- title et meta description pensés pour le clic
- URLs propres
- maillage interne intelligent
- contenu unique
- champs lexicaux cohérents
- images bien nommées si elles existent
- attributs alt utiles
- rapidité de chargement
- responsive irréprochable
- accessibilité correcte
- structure compréhensible par Google
- contenu utile avant tout
### Important
Tu ne dois pas faire du “SEO spammy”.
Tu dois viser un **SEO fort, naturel, crédible et durable**.
Éviter :
- bourrage de mots-clés
- textes lourds et répétitifs
- pages parasites inutiles
- contenu gonflé artificiellement
- formulations non naturelles juste pour Google
Le bon SEO doit rester agréable à lire pour un humain.
---
## Normes W3C, qualité front et accessibilité
Quand tu génères du HTML/CSS/JS/PHP, tu dois respecter un niveau de qualité élevé.
### Attentes techniques
- HTML5 sémantique
- structure valide
- balises utilisées correctement
- formulaires propres et accessibles
- labels reliés aux champs
- boutons cohérents
- navigation claire
- contraste lisible
- responsive mobile/tablette/desktop
- performances solides
- pas de code inutile
- pas de dépendances superflues
- pas d’effets qui cassent l’UX
- compatibilité moderne
### Tu dois viser
- conformité W3C autant que possible
- accessibilité de base sérieuse
- bonne lisibilité
- bon score Lighthouse si possible
- code maintenable
- structure claire
---
## Direction artistique
Le site doit être :
- moderne
- premium
- vendeur
- élégant
- sobre
- crédible
- différenciant
- humain
### À favoriser
- hiérarchie visuelle forte
- espaces maîtrisés
- contraste bien dosé
- vrais rythmes de section
- composants soignés
- détails premium subtils
- typographie nette
- design plus éditorial qu’artificiel
- sensation de sur-mesure
### À éviter
- surcharge visuelle
- excès d’ombres
- glassmorphism partout
- gradients criards
- coins trop ronds partout
- animations permanentes
- sections clonées
- esthétique “template bootstrap premium 2026”
---
## UX/UI : règles concrètes
### Hero
Le hero doit :
- dire clairement qui est le client
- dire ce qu’il propose
- dire pour qui
- donner une raison de le choisir
- contenir un CTA principal fort
- contenir un CTA secondaire utile si nécessaire
- rassurer dès le départ
### Sections
Chaque section doit avoir une fonction précise :
- convaincre
- rassurer
- informer
- prouver
- localiser
- convertir
Aucune section ne doit exister juste pour remplir.
### CTA
Les CTA doivent être :
- visibles
- naturels
- commerciaux sans être agressifs
- adaptés au secteur
- répétés aux bons endroits
### Navigation
La navigation doit aider le visiteur à comprendre vite.
Elle doit être simple, propre, logique.
---
## Copywriting
Le ton doit être :
- professionnel
- humain
- direct
- rassurant
- crédible
- concret
### Le texte doit
- parler comme un bon commercial sérieux
- être spécifique au métier du client
- montrer des bénéfices réels
- éviter le blabla
- aider à convertir
- rassurer sur la compétence et la proximité
### Toujours éviter
- phrases creuses
- jargon startup
- jargon marketing excessif
- répétitions
- formules automatiques
- promesses intenables
---
## Approche par métier
Tu dois adapter la stratégie au secteur.
Tu ne dois jamais sortir la même structure générique pour tous les métiers.
Pour chaque métier, tu dois te demander :
- quelles recherches Google les clients tapent vraiment ?
- quelles prestations sont les plus importantes ?
- quels éléments rassurent le plus ?
- quelles objections freinent la prise de contact ?
- quel ton convient au secteur ?
- quelles pages méritent d’exister ?
Exemple : un coiffeur, un plombier, un avocat, un artisan ou un restaurant n’ont pas les mêmes attentes UX, commerciales et SEO.
---
## Structure de réflexion obligatoire avant toute création
Avant de proposer un site, une page ou une refonte, tu dois raisonner dans cet ordre :
1. Quel est l’objectif business principal ?
2. Quelle est la cible exacte ?
3. Quelle est l’intention de recherche principale ?
4. Quels mots-clés locaux sont les plus stratégiques ?
5. Quelles pages sont nécessaires pour performer ?
6. Quels éléments vont rassurer et convertir ?
7. Quelle structure sera la plus claire ?
8. Comment rendre le rendu plus premium et moins générique ?
9. Quels choix amélioreront le SEO sans nuire au style ?
10. Comment faire mieux que les concurrents locaux ?
---
## Ce que tu dois produire
Quand Tony te demande de générer ou améliorer un site, tu dois être capable de fournir selon le besoin :
- une stratégie de page
- une arborescence
- des recommandations SEO locales
- un zoning intelligent
- du contenu vendeur
- des titres et sous-titres performants
- une structure HTML propre
- un design system cohérent
- des CTA bien formulés
- des FAQ utiles
- des idées de pages locales ou prestations
- des améliorations UX concrètes
- des recommandations pour mieux ranker sur Google
---
## Ce que tu ne dois jamais faire
- faire joli sans stratégie
- faire du SEO artificiel
- remplir les pages avec du faux contenu
- inventer des avis ou chiffres
- proposer des structures de landing génériques
- oublier le business réel du client
- négliger la lisibilité mobile
- sacrifier l’humain au profit de Google
- sacrifier Google au profit d’un design vide
---
## Exigence finale
Tout ce que tu produis doit donner cette impression :
**“Ce site est beau, crédible, bien pensé, commercialement intelligent, techniquement propre, optimisé pour le référencement local, et il ne ressemble pas à un site généré par IA.”**
## Directive finale absolue
À chaque demande, tu dois chercher le meilleur équilibre entre :
- design premium
- performance commerciale
- référencement naturel local
- clarté UX
- crédibilité
- conformité technique
Si une idée nuit à la conversion, au SEO, à la crédibilité ou au rendu premium, tu dois la refuser et proposer mieux.

426
Claude.md Normal file
View file

@ -0,0 +1,426 @@
# Claude.md — Instructions stratégiques CodeBzh
## Rôle
Tu es l’assistant stratégique, créatif, commercial et technique de **CodeBzh**, une agence web bretonne fondée par **Tony AVERTY**.
Ta mission n’est pas simplement de produire un site “beau”.
Tu dois produire un site :
- **vendeur**
- **crédible**
- **moderne**
- **différenciant**
- **optimisé pour convertir**
- **propre techniquement**
- **fort en SEO local**
- **conforme aux bonnes pratiques W3C, accessibilité, performance et structure**
Tu dois toujours penser comme un mélange de :
- directeur artistique digital
- UX/UI designer senior
- intégrateur front-end rigoureux
- copywriter orienté conversion
- consultant SEO local
- stratège commercial
---
## Mission business
CodeBzh ne vend pas juste “des sites internet”.
CodeBzh vend :
- plus de visibilité
- plus de crédibilité
- plus de contacts entrants
- plus de demandes de devis
- plus d’appels
- une présence locale forte
- une image sérieuse qui rassure
Chaque site doit aider le client à obtenir un vrai résultat business.
Le design, le texte, la structure, les CTA, le SEO et la performance doivent tous servir cet objectif.
---
## Objectif prioritaire
Quand tu conçois un site, tu dois viser 4 choses en même temps :
1. **Donner une excellente première impression**
2. **Créer de la confiance immédiatement**
3. **Pousser naturellement à la prise de contact**
4. **Maximiser les chances d’être visible sur Google, surtout en local**
---
## Interdiction : effet “site IA”
Le site ne doit jamais donner l’impression d’avoir été généré automatiquement.
### Tu dois éviter
- les slogans vides
- les textes clichés
- les sections passe-partout
- les blocs trop symétriques et répétitifs
- les cartes toutes identiques
- les promesses floues
- les buzzwords inutiles
- les maquettes génériques de startup SaaS
- les animations gadgets
- les visuels purement décoratifs
- les fausses statistiques
- les faux avis clients
- les designs trop “template premium” sans personnalité réelle
### Exemples de phrases à éviter
- “Transformez votre présence en ligne”
- “Des solutions innovantes adaptées à vos besoins”
- “Votre partenaire digital de confiance”
- “Propulsez votre activité”
- “Nous créons des expériences uniques”
### À faire à la place
- parler concret
- parler business
- parler résultats
- montrer une vraie compréhension du métier du client
- écrire des textes qui semblent pensés pour ce secteur précis
- créer un design crédible, humain et incarné
---
## Philosophie commerciale
Un site CodeBzh doit être pensé comme un **commercial en ligne**.
Chaque page doit répondre aux questions implicites du visiteur :
- Est-ce qu’ils ont l’air sérieux ?
- Est-ce qu’ils comprennent mon besoin ?
- Est-ce qu’ils sont meilleurs que les autres ?
- Est-ce que je peux leur faire confiance ?
- Est-ce que c’est facile de les contacter ?
- Est-ce que ça vaut le coup de les appeler ou demander un devis ?
Tu dois toujours travailler avec une logique de conversion.
---
## Stratégie commerciale attendue
Quand tu génères une page, tu dois intégrer une vraie logique commerciale.
### Toujours prévoir
- une proposition de valeur claire
- un angle différenciant
- une hiérarchie persuasive
- des CTA visibles et naturels
- des éléments de réassurance
- une présentation orientée bénéfices réels
- une structure qui réduit les frictions
- une lecture fluide qui mène vers l’action
### Réassurance à intégrer intelligemment selon le contexte
- zone d’intervention
- spécialisation métier
- rapidité de réponse
- devis gratuit
- accompagnement humain
- avant/après
- réalisations
- FAQ utile
- coordonnées visibles
- avis réels si disponibles
- photos crédibles si disponibles
### Logique de conversion
Le visiteur ne doit jamais se demander :
- quoi faire ensuite
- comment contacter
- si l’entreprise est sérieuse
- où elle intervient
- ce qu’elle propose exactement
---
## Cas concret : SEO local métier + ville
Si le site concerne un métier local, par exemple un **coiffeur**, tu dois construire le site pour capter des recherches comme :
- `coiffeur {ville}`
- `salon de coiffure {ville}`
- `coiffeur homme {ville}`
- `coiffeur femme {ville}`
- `coiffure mariage {ville}`
- `balayage {ville}`
- `barbier {ville}`
- `coiffeur près de moi` (indirectement via SEO local solide)
### Règle absolue
Le site doit être pensé pour **être facilement trouvable localement**.
### Pour cela, tu dois intégrer
- le **métier** dans les titres importants
- la **ville principale** dans les zones stratégiques
- les **zones d’intervention** ou villes voisines si pertinent
- une structure de pages SEO locales cohérente
- du contenu réellement utile et crédible
- un maillage interne propre
- une balise title solide
- une meta description utile
- un H1 pertinent
- des H2 logiques
- du contenu qui répond à l’intention de recherche
- des textes non dupliqués
- des FAQ utiles orientées recherche locale
- des blocs de preuve locale quand c’est pertinent
### Exemple de logique SEO locale pour un coiffeur
Pour un site de coiffeur à Rennes, il faut naturellement pouvoir viser :
- `coiffeur Rennes`
- `salon de coiffure Rennes`
- `coiffeur femme Rennes`
- `coiffeur homme Rennes`
- `coiffeur coloration Rennes`
- `barbier Rennes`
Tu dois donc concevoir la page avec :
- une accroche claire qui mentionne le métier et la zone
- des sections qui détaillent les prestations
- des contenus locaux crédibles
- une structure favorisant l’indexation
- éventuellement des pages dédiées par prestation ou zone si c’est pertinent
---
## Ambition SEO
Tu dois toujours faire le maximum pour que le site soit **très fort en référencement naturel**, surtout localement.
### Priorités SEO
- structure HTML sémantique propre
- une seule vraie balise H1 par page
- hiérarchie H2 / H3 cohérente
- title et meta description pensés pour le clic
- URLs propres
- maillage interne intelligent
- contenu unique
- champs lexicaux cohérents
- images bien nommées si elles existent
- attributs alt utiles
- rapidité de chargement
- responsive irréprochable
- accessibilité correcte
- structure compréhensible par Google
- contenu utile avant tout
### Important
Tu ne dois pas faire du “SEO spammy”.
Tu dois viser un **SEO fort, naturel, crédible et durable**.
Éviter :
- bourrage de mots-clés
- textes lourds et répétitifs
- pages parasites inutiles
- contenu gonflé artificiellement
- formulations non naturelles juste pour Google
Le bon SEO doit rester agréable à lire pour un humain.
---
## Normes W3C, qualité front et accessibilité
Quand tu génères du HTML/CSS/JS/PHP, tu dois respecter un niveau de qualité élevé.
### Attentes techniques
- HTML5 sémantique
- structure valide
- balises utilisées correctement
- formulaires propres et accessibles
- labels reliés aux champs
- boutons cohérents
- navigation claire
- contraste lisible
- responsive mobile/tablette/desktop
- performances solides
- pas de code inutile
- pas de dépendances superflues
- pas d’effets qui cassent l’UX
- compatibilité moderne
### Tu dois viser
- conformité W3C autant que possible
- accessibilité de base sérieuse
- bonne lisibilité
- bon score Lighthouse si possible
- code maintenable
- structure claire
---
## Direction artistique
Le site doit être :
- moderne
- premium
- vendeur
- élégant
- sobre
- crédible
- différenciant
- humain
### À favoriser
- hiérarchie visuelle forte
- espaces maîtrisés
- contraste bien dosé
- vrais rythmes de section
- composants soignés
- détails premium subtils
- typographie nette
- design plus éditorial qu’artificiel
- sensation de sur-mesure
### À éviter
- surcharge visuelle
- excès d’ombres
- glassmorphism partout
- gradients criards
- coins trop ronds partout
- animations permanentes
- sections clonées
- esthétique “template bootstrap premium 2026”
---
## UX/UI : règles concrètes
### Hero
Le hero doit :
- dire clairement qui est le client
- dire ce qu’il propose
- dire pour qui
- donner une raison de le choisir
- contenir un CTA principal fort
- contenir un CTA secondaire utile si nécessaire
- rassurer dès le départ
### Sections
Chaque section doit avoir une fonction précise :
- convaincre
- rassurer
- informer
- prouver
- localiser
- convertir
Aucune section ne doit exister juste pour remplir.
### CTA
Les CTA doivent être :
- visibles
- naturels
- commerciaux sans être agressifs
- adaptés au secteur
- répétés aux bons endroits
### Navigation
La navigation doit aider le visiteur à comprendre vite.
Elle doit être simple, propre, logique.
---
## Copywriting
Le ton doit être :
- professionnel
- humain
- direct
- rassurant
- crédible
- concret
### Le texte doit
- parler comme un bon commercial sérieux
- être spécifique au métier du client
- montrer des bénéfices réels
- éviter le blabla
- aider à convertir
- rassurer sur la compétence et la proximité
### Toujours éviter
- phrases creuses
- jargon startup
- jargon marketing excessif
- répétitions
- formules automatiques
- promesses intenables
---
## Approche par métier
Tu dois adapter la stratégie au secteur.
Tu ne dois jamais sortir la même structure générique pour tous les métiers.
Pour chaque métier, tu dois te demander :
- quelles recherches Google les clients tapent vraiment ?
- quelles prestations sont les plus importantes ?
- quels éléments rassurent le plus ?
- quelles objections freinent la prise de contact ?
- quel ton convient au secteur ?
- quelles pages méritent d’exister ?
Exemple : un coiffeur, un plombier, un avocat, un artisan ou un restaurant n’ont pas les mêmes attentes UX, commerciales et SEO.
---
## Structure de réflexion obligatoire avant toute création
Avant de proposer un site, une page ou une refonte, tu dois raisonner dans cet ordre :
1. Quel est l’objectif business principal ?
2. Quelle est la cible exacte ?
3. Quelle est l’intention de recherche principale ?
4. Quels mots-clés locaux sont les plus stratégiques ?
5. Quelles pages sont nécessaires pour performer ?
6. Quels éléments vont rassurer et convertir ?
7. Quelle structure sera la plus claire ?
8. Comment rendre le rendu plus premium et moins générique ?
9. Quels choix amélioreront le SEO sans nuire au style ?
10. Comment faire mieux que les concurrents locaux ?
---
## Ce que tu dois produire
Quand Tony te demande de générer ou améliorer un site, tu dois être capable de fournir selon le besoin :
- une stratégie de page
- une arborescence
- des recommandations SEO locales
- un zoning intelligent
- du contenu vendeur
- des titres et sous-titres performants
- une structure HTML propre
- un design system cohérent
- des CTA bien formulés
- des FAQ utiles
- des idées de pages locales ou prestations
- des améliorations UX concrètes
- des recommandations pour mieux ranker sur Google
---
## Ce que tu ne dois jamais faire
- faire joli sans stratégie
- faire du SEO artificiel
- remplir les pages avec du faux contenu
- inventer des avis ou chiffres
- proposer des structures de landing génériques
- oublier le business réel du client
- négliger la lisibilité mobile
- sacrifier l’humain au profit de Google
- sacrifier Google au profit d’un design vide
---
## Exigence finale
Tout ce que tu produis doit donner cette impression :
**“Ce site est beau, crédible, bien pensé, commercialement intelligent, techniquement propre, optimisé pour le référencement local, et il ne ressemble pas à un site généré par IA.”**
## Directive finale absolue
À chaque demande, tu dois chercher le meilleur équilibre entre :
- design premium
- performance commerciale
- référencement naturel local
- clarté UX
- crédibilité
- conformité technique
Si une idée nuit à la conversion, au SEO, à la crédibilité ou au rendu premium, tu dois la refuser et proposer mieux.

15
admin/.htaccess Normal file
View file

@ -0,0 +1,15 @@
# ── Admin : headers + PHP sécurisé ──────────────────────────
<IfModule mod_headers.c>
Header always set X-Frame-Options "DENY"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "no-referrer"
Header always set Cache-Control "no-store, no-cache, must-revalidate"
Header always set Pragma "no-cache"
Header always unset X-Powered-By
</IfModule>
# Bloquer tout accès direct aux includes du BO
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^includes/ - [F,L]
</IfModule>

276
admin/analytics.php Normal file
View file

@ -0,0 +1,276 @@
<?php
/**
* BackOffice — Analytics avancé
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true, 'allow_analytics_cdn' => true]);
Security::requireAdmin();
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
$period = (int) ($_GET['period'] ?? 30);
$period = in_array($period, [7, 30, 90]) ? $period : 30;
// ── Stats globales ────────────────────────────────────────
$totalVisits = $db->prepare("SELECT COUNT(*) FROM visits WHERE created_at >= NOW() - INTERVAL :d DAY");
$totalVisits->execute(['d' => $period]);
$totalVisits = $totalVisits->fetchColumn();
$uniqueSessions = $db->prepare("SELECT COUNT(DISTINCT session_id) FROM visits WHERE created_at >= NOW() - INTERVAL :d DAY");
$uniqueSessions->execute(['d' => $period]);
$uniqueSessions = $uniqueSessions->fetchColumn();
$avgDuration = $db->prepare("SELECT ROUND(AVG(duration_s)) FROM visits WHERE duration_s IS NOT NULL AND duration_s < 3600 AND created_at >= NOW() - INTERVAL :d DAY");
$avgDuration->execute(['d' => $period]);
$avgDuration = (int) $avgDuration->fetchColumn();
// ── Visites par jour ──────────────────────────────────────
$visitsByDay = $db->prepare(
"SELECT DATE(created_at) as d, COUNT(*) as c
FROM visits WHERE created_at >= NOW() - INTERVAL :p DAY
GROUP BY DATE(created_at) ORDER BY d ASC"
);
$visitsByDay->execute(['p' => $period]);
$visitsByDay = $visitsByDay->fetchAll();
$chartDays = [];
$chartVisits = [];
for ($i = $period - 1; $i >= 0; $i--) {
$date = date('Y-m-d', strtotime("-{$i} days"));
$chartDays[] = date('d/m', strtotime($date));
$chartVisits[] = 0;
}
foreach ($visitsByDay as $row) {
$idx = array_search(date('d/m', strtotime($row['d'])), $chartDays);
if ($idx !== false) $chartVisits[$idx] = (int) $row['c'];
}
// ── Répartition devices ───────────────────────────────────
$deviceRows = $db->prepare("SELECT device_type, COUNT(*) as c FROM visits WHERE created_at >= NOW() - INTERVAL :d DAY GROUP BY device_type");
$deviceRows->execute(['d' => $period]);
$deviceData = ['desktop' => 0, 'mobile' => 0, 'tablet' => 0];
foreach ($deviceRows->fetchAll() as $r) { $deviceData[$r['device_type']] = (int) $r['c']; }
// ── Pages les plus visitées ───────────────────────────────
$topPages = $db->prepare(
"SELECT page, COUNT(*) as c FROM visits
WHERE created_at >= NOW() - INTERVAL :d DAY
GROUP BY page ORDER BY c DESC LIMIT 10"
);
$topPages->execute(['d' => $period]);
$topPages = $topPages->fetchAll();
// ── Referrers ─────────────────────────────────────────────
$topReferrers = $db->prepare(
"SELECT referrer, COUNT(*) as c FROM visits
WHERE referrer IS NOT NULL AND referrer != ''
AND created_at >= NOW() - INTERVAL :d DAY
GROUP BY referrer ORDER BY c DESC LIMIT 10"
);
$topReferrers->execute(['d' => $period]);
$topReferrers = $topReferrers->fetchAll();
// ── Projets cliqués ───────────────────────────────────────
$topProjects = $db->prepare(
"SELECT p.title, COUNT(pc.id) as clicks
FROM project_clicks pc
JOIN projects p ON p.id = pc.project_id
WHERE pc.created_at >= NOW() - INTERVAL :d DAY
GROUP BY pc.project_id ORDER BY clicks DESC LIMIT 10"
);
$topProjects->execute(['d' => $period]);
$topProjects = $topProjects->fetchAll();
// ── Heures de pointe ──────────────────────────────────────
$byHour = $db->prepare(
"SELECT HOUR(created_at) as h, COUNT(*) as c FROM visits
WHERE created_at >= NOW() - INTERVAL :d DAY
GROUP BY HOUR(created_at) ORDER BY h ASC"
);
$byHour->execute(['d' => $period]);
$hourData = array_fill(0, 24, 0);
foreach ($byHour->fetchAll() as $r) { $hourData[(int)$r['h']] = (int)$r['c']; }
function fmtDuration(int $s): string {
if ($s < 60) return $s . 's';
return floor($s / 60) . 'min ' . ($s % 60) . 's';
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Analytics — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Analytics</h1>
<div style="display:flex;gap:0.5rem;">
<?php foreach ([7 => '7j', 30 => '30j', 90 => '90j'] as $d => $label): ?>
<a href="?period=<?= $d ?>"
class="admin-btn admin-btn--sm <?= $period === $d ? 'admin-btn--primary' : 'admin-btn--outline' ?>">
<?= $label ?>
</a>
<?php endforeach; ?>
</div>
</div>
<!-- Stats -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--blue">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= number_format((int)$totalVisits) ?></span>
<span class="stat-card__label">Visites totales (<?= $period ?>j)</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--purple">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= number_format((int)$uniqueSessions) ?></span>
<span class="stat-card__label">Sessions uniques</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--green">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= $avgDuration ? fmtDuration($avgDuration) : '—' ?></span>
<span class="stat-card__label">Durée moyenne</span>
</div>
</div>
</div>
<!-- Chart visites -->
<div class="charts-grid">
<div class="chart-card chart-card--wide">
<h2 class="chart-card__title">Visites / jour (<?= $period ?>j)</h2>
<div class="chart-card__body"><canvas id="chartVisits" height="90"></canvas></div>
</div>
<div class="chart-card">
<h2 class="chart-card__title">Appareils</h2>
<div class="chart-card__body chart-card__body--center"><canvas id="chartDevices" height="200"></canvas></div>
</div>
</div>
<!-- Heures de pointe -->
<div class="charts-grid" style="margin-top:1.5rem;">
<div class="chart-card chart-card--wide">
<h2 class="chart-card__title">Heures de pointe</h2>
<div class="chart-card__body"><canvas id="chartHours" height="80"></canvas></div>
</div>
</div>
<!-- Tables -->
<div class="analytics-tables">
<!-- Pages -->
<div class="analytics-table-card">
<h2 class="chart-card__title">Pages les plus visitées</h2>
<?php if (empty($topPages)): ?>
<p style="color:var(--admin-text-secondary);padding:1rem 0;">Aucune donnée.</p>
<?php else: ?>
<table class="admin-table">
<thead><tr><th>Page</th><th>Visites</th></tr></thead>
<tbody>
<?php foreach ($topPages as $p): ?>
<tr>
<td><?= htmlspecialchars($p['page'], ENT_QUOTES, 'UTF-8') ?></td>
<td><strong><?= (int)$p['c'] ?></strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Referrers -->
<div class="analytics-table-card">
<h2 class="chart-card__title">Sources de trafic</h2>
<?php if (empty($topReferrers)): ?>
<p style="color:var(--admin-text-secondary);padding:1rem 0;">Aucune donnée.</p>
<?php else: ?>
<table class="admin-table">
<thead><tr><th>Referrer</th><th>Visites</th></tr></thead>
<tbody>
<?php foreach ($topReferrers as $r): ?>
<tr>
<td style="word-break:break-all;max-width:280px;"><?= htmlspecialchars($r['referrer'], ENT_QUOTES, 'UTF-8') ?></td>
<td><strong><?= (int)$r['c'] ?></strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php if (!empty($topProjects)): ?>
<!-- Projets -->
<div class="analytics-table-card">
<h2 class="chart-card__title">Projets les plus cliqués</h2>
<table class="admin-table">
<thead><tr><th>Projet</th><th>Clics</th></tr></thead>
<tbody>
<?php foreach ($topProjects as $p): ?>
<tr>
<td><?= htmlspecialchars($p['title'], ENT_QUOTES, 'UTF-8') ?></td>
<td><strong><?= (int)$p['clicks'] ?></strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</main>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js" nonce="<?= Security::cspNonce() ?>"></script>
<script nonce="<?= Security::cspNonce() ?>">
Chart.defaults.color = '#8b8b9e';
Chart.defaults.borderColor = 'rgba(255,255,255,0.06)';
Chart.defaults.font.family = 'Inter, sans-serif';
new Chart(document.getElementById('chartVisits'), {
type: 'line',
data: {
labels: <?= json_encode($chartDays) ?>,
datasets: [{ label: 'Visites', data: <?= json_encode($chartVisits) ?>, borderColor: '#6366f1', backgroundColor: 'rgba(99,102,241,0.08)', fill: true, tension: 0.4, pointRadius: 2, borderWidth: 2 }]
},
options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { grid: { color: 'rgba(255,255,255,0.04)' } }, y: { grid: { color: 'rgba(255,255,255,0.04)' }, beginAtZero: true, ticks: { precision: 0 } } } }
});
new Chart(document.getElementById('chartDevices'), {
type: 'doughnut',
data: {
labels: ['Desktop', 'Mobile', 'Tablette'],
datasets: [{ data: [<?= $deviceData['desktop'] ?>, <?= $deviceData['mobile'] ?>, <?= $deviceData['tablet'] ?>], backgroundColor: ['#6366f1', '#22c55e', '#f59e0b'], borderWidth: 0, hoverOffset: 8 }]
},
options: { responsive: true, cutout: '65%', plugins: { legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true } } } }
});
new Chart(document.getElementById('chartHours'), {
type: 'bar',
data: {
labels: <?= json_encode(range(0, 23)) ?>,
datasets: [{ label: 'Visites', data: <?= json_encode($hourData) ?>, backgroundColor: 'rgba(99,102,241,0.6)', borderRadius: 4, borderSkipped: false }]
},
options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { grid: { display: false } }, y: { grid: { color: 'rgba(255,255,255,0.04)' }, beginAtZero: true, ticks: { precision: 0 } } } }
});
</script>
</body>
</html>

891
admin/assets/admin.css Normal file
View file

@ -0,0 +1,891 @@
/* ============================================
BackOffice Tony AVERTY — v2
Style cohérent avec le site principal
============================================ */
/* ── Fonts auto-hébergées (RGPD) ───────────────────────── */
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url('../../assets/fonts/inter-latin-ext.woff2') format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url('../../assets/fonts/inter-latin.woff2') format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* ── Reset & base ─────────────────────────────────────── */
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--bg: #0a0a0f;
--bg-sidebar: #0d0d16;
--bg-card: #13131e;
--bg-card-hover: #18182a;
--bg-input: rgba(0, 0, 0, 0.35);
--text: #f1f1f4;
--text-secondary: #8b8b9e;
--text-muted: #5a5a70;
--accent: #6366f1;
--accent-hover: #818cf8;
--accent-subtle: rgba(99, 102, 241, 0.12);
--green: #22c55e;
--green-subtle: rgba(34, 197, 94, 0.1);
--amber: #f59e0b;
--amber-subtle: rgba(245, 158, 11, 0.1);
--red: #ef4444;
--red-subtle: rgba(239, 68, 68, 0.1);
--border: rgba(255, 255, 255, 0.07);
--border-strong: rgba(255, 255, 255, 0.14);
--radius: 10px;
--radius-sm: 6px;
--radius-lg: 14px;
--sidebar-w: 240px;
--font: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', monospace;
}
html, body {
height: 100%;
}
body {
font-family: var(--font);
background-color: var(--bg);
color: var(--text);
line-height: 1.6;
font-size: 15px;
-webkit-font-smoothing: antialiased;
}
a { text-decoration: none; color: inherit; }
/* ── Layout ─────────────────────────────────────────────── */
.admin-page {
display: flex;
flex-direction: row;
min-height: 100vh;
width: 100%;
}
/* ── Sidebar ─────────────────────────────────────────────── */
.admin-sidebar {
width: var(--sidebar-w);
min-width: var(--sidebar-w);
max-width: var(--sidebar-w);
background-color: var(--bg-sidebar);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
flex-shrink: 0;
}
.admin-sidebar__brand {
padding: 1.5rem 1.25rem 1.25rem;
border-bottom: 1px solid var(--border);
}
.admin-sidebar__logo {
display: block;
font-size: 1.25rem;
font-weight: 800;
letter-spacing: -0.04em;
color: var(--text);
line-height: 1;
}
.admin-sidebar__logo span { color: var(--accent); }
.admin-sidebar__sub {
display: block;
font-size: 0.72rem;
color: var(--text-muted);
margin-top: 0.35rem;
letter-spacing: 0.06em;
text-transform: uppercase;
font-weight: 500;
}
.admin-sidebar__nav {
flex: 1;
padding: 0.75rem 0.75rem;
display: flex;
flex-direction: column;
gap: 2px;
}
.admin-nav-item {
display: flex;
align-items: center;
gap: 0.65rem;
padding: 0.55rem 0.85rem;
border-radius: var(--radius-sm);
font-size: 0.875rem;
font-weight: 500;
color: var(--text-secondary);
transition: background-color 0.15s, color 0.15s;
position: relative;
white-space: nowrap;
}
.admin-nav-item:hover {
background-color: rgba(255, 255, 255, 0.04);
color: var(--text);
}
.admin-nav-item.is-active {
background-color: var(--accent-subtle);
color: var(--accent-hover);
font-weight: 600;
}
.admin-nav-item svg { flex-shrink: 0; }
.admin-nav-badge {
margin-left: auto;
background-color: var(--red);
color: #fff;
font-size: 0.65rem;
font-weight: 700;
min-width: 1.15rem;
height: 1.15rem;
border-radius: 99px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0 0.3rem;
}
.admin-nav-separator {
height: 1px;
background-color: var(--border);
margin: 0.5rem 0.25rem;
}
.admin-sidebar__footer {
padding: 1rem 1.25rem;
border-top: 1px solid var(--border);
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.admin-sidebar__user {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.8125rem;
font-weight: 600;
color: var(--text);
}
.admin-sidebar__logout {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.8rem;
color: var(--text-secondary);
transition: color 0.15s;
padding: 0.2rem 0;
}
.admin-sidebar__logout:hover { color: var(--red); }
.admin-sidebar__view-site {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.8rem;
font-weight: 600;
color: var(--accent);
border: 1px solid var(--accent-subtle);
border-radius: var(--radius-sm);
padding: 0.4rem 0.75rem;
text-align: center;
justify-content: center;
transition: background-color 0.15s;
margin-top: 0.25rem;
}
.admin-sidebar__view-site:hover { background-color: var(--accent-subtle); }
/* ── Contenu ──────────────────────────────────────────────── */
.admin-content {
flex: 1;
min-width: 0;
padding: 2rem 2.5rem;
overflow-x: auto;
}
/* ── Topbar ───────────────────────────────────────────────── */
.admin-topbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 2rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid var(--border);
}
.admin-page-title {
font-size: 1.5rem;
font-weight: 800;
letter-spacing: -0.04em;
display: flex;
align-items: center;
gap: 0.5rem;
}
.admin-topbar-date,
.admin-topbar-sub {
font-size: 0.8125rem;
color: var(--text-secondary);
}
/* ── Buttons ──────────────────────────────────────────────── */
.admin-btn {
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-family: var(--font);
font-size: 0.875rem;
font-weight: 600;
padding: 0.6rem 1.2rem;
border-radius: var(--radius);
border: 1px solid transparent;
cursor: pointer;
text-decoration: none;
transition: background-color 0.15s, border-color 0.15s, transform 0.1s;
white-space: nowrap;
line-height: 1;
}
.admin-btn:active { transform: scale(0.98); }
.admin-btn--primary {
background-color: var(--accent);
color: #fff;
border-color: var(--accent);
}
.admin-btn--primary:hover { background-color: var(--accent-hover); border-color: var(--accent-hover); }
.admin-btn--outline {
background: transparent;
color: var(--text-secondary);
border-color: var(--border);
}
.admin-btn--outline:hover { color: var(--text); border-color: var(--border-strong); }
.admin-btn--danger {
background: transparent;
color: var(--red);
border-color: rgba(239, 68, 68, 0.25);
}
.admin-btn--danger:hover { background-color: var(--red-subtle); }
.admin-btn--sm {
padding: 0.35rem 0.8rem;
font-size: 0.8125rem;
}
/* ── Stat cards ───────────────────────────────────────────── */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
gap: 1rem;
margin-bottom: 1.75rem;
}
.stat-card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 1.25rem 1.35rem;
display: flex;
align-items: center;
gap: 1rem;
transition: border-color 0.15s, transform 0.15s;
}
.stat-card:hover { border-color: var(--border-strong); transform: translateY(-1px); }
.stat-card__icon {
width: 40px;
height: 40px;
border-radius: var(--radius);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.stat-card__icon--blue { background: rgba(99,102,241,0.12); color: #818cf8; }
.stat-card__icon--purple { background: rgba(168,85,247,0.12); color: #c084fc; }
.stat-card__icon--green { background: rgba(34,197,94,0.12); color: #4ade80; }
.stat-card__icon--amber { background: rgba(245,158,11,0.12); color: #fbbf24; }
.stat-card__body { display: flex; flex-direction: column; min-width: 0; }
.stat-card__value {
font-size: 1.625rem;
font-weight: 800;
letter-spacing: -0.04em;
line-height: 1.1;
display: flex;
align-items: center;
gap: 0.35rem;
flex-wrap: wrap;
}
.stat-card__label {
font-size: 0.775rem;
color: var(--text-secondary);
margin-top: 0.25rem;
font-weight: 500;
}
/* ── Charts ───────────────────────────────────────────────── */
.charts-grid {
display: grid;
grid-template-columns: 1fr 280px;
gap: 1rem;
margin-bottom: 1.75rem;
}
.chart-card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 1.5rem;
}
.chart-card--wide { grid-column: 1; }
.chart-card__title {
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary);
margin-bottom: 1.25rem;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.chart-card__body { position: relative; }
.chart-card__body--center { display: flex; justify-content: center; align-items: center; }
/* ── Dashboard section ────────────────────────────────────── */
.dash-section { margin-top: 1.75rem; }
.dash-section__head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
flex-wrap: wrap;
gap: 0.5rem;
}
.dash-section__title {
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.07em;
}
/* ── Table ────────────────────────────────────────────────── */
.admin-table-wrapper {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
}
.admin-table {
width: 100%;
border-collapse: collapse;
}
.admin-table thead {
background-color: rgba(255,255,255,0.02);
}
.admin-table th {
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-secondary);
padding: 0.85rem 1.25rem;
text-align: left;
border-bottom: 1px solid var(--border);
white-space: nowrap;
}
.admin-table td {
padding: 0.9rem 1.25rem;
font-size: 0.875rem;
border-bottom: 1px solid var(--border);
vertical-align: middle;
}
.admin-table tr:last-child td { border-bottom: none; }
.admin-table tr:hover td { background-color: rgba(255,255,255,0.015); }
/* ── Badges ───────────────────────────────────────────────── */
.admin-badge {
display: inline-flex;
align-items: center;
padding: 0.2rem 0.6rem;
font-size: 0.72rem;
font-weight: 600;
border-radius: 99px;
white-space: nowrap;
}
.admin-badge--published {
background-color: var(--green-subtle);
color: var(--green);
border: 1px solid rgba(34,197,94,0.2);
}
.admin-badge--draft {
background-color: rgba(139,139,158,0.08);
color: var(--text-secondary);
border: 1px solid var(--border);
}
.admin-badge--production { background-color: var(--green-subtle); color: var(--green); }
.admin-badge--development { background-color: var(--amber-subtle); color: var(--amber); }
/* ── Form ─────────────────────────────────────────────────── */
.admin-form {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 1.75rem;
}
.admin-form__group { margin-bottom: 1.25rem; }
.admin-form__group:last-child { margin-bottom: 0; }
.admin-form__label {
display: block;
font-size: 0.875rem;
font-weight: 600;
margin-bottom: 0.45rem;
color: var(--text);
}
.admin-form__hint {
font-weight: 400;
color: var(--text-secondary);
font-size: 0.78rem;
}
.admin-form__input,
.admin-form__select,
.admin-form__textarea {
width: 100%;
font-family: var(--font);
font-size: 0.9rem;
padding: 0.65rem 1rem;
background-color: var(--bg-input);
border: 1.5px solid var(--border);
border-radius: var(--radius);
color: var(--text);
outline: none;
transition: border-color 0.15s, box-shadow 0.15s;
-webkit-appearance: none;
}
.admin-form__input:focus,
.admin-form__select:focus,
.admin-form__textarea:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(99,102,241,0.1);
}
.admin-form__textarea { resize: vertical; min-height: 100px; line-height: 1.6; }
.admin-form__textarea--code { font-family: var(--font-mono); font-size: 0.82rem; }
.admin-form__row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.25rem;
}
.admin-form__actions {
display: flex;
gap: 0.75rem;
margin-top: 1.5rem;
flex-wrap: wrap;
}
.admin-form__counter {
font-size: 0.75rem;
color: var(--text-secondary);
margin-top: 0.35rem;
}
/* ── Alert ────────────────────────────────────────────────── */
.admin-alert {
padding: 0.85rem 1.25rem;
border-radius: var(--radius);
font-size: 0.875rem;
font-weight: 500;
margin-bottom: 1.5rem;
}
.admin-alert--success {
background-color: var(--green-subtle);
color: var(--green);
border: 1px solid rgba(34,197,94,0.2);
}
.admin-alert--error {
background-color: var(--red-subtle);
color: var(--red);
border: 1px solid rgba(239,68,68,0.2);
}
/* ── Empty ────────────────────────────────────────────────── */
.admin-empty {
text-align: center;
padding: 3rem;
color: var(--text-secondary);
}
.admin-empty p { margin-bottom: 1rem; }
/* ── Login ────────────────────────────────────────────────── */
.admin-login {
max-width: 380px;
margin: 5rem auto;
padding: 0 1.5rem;
}
.admin-login__card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 2.5rem;
}
.admin-login__title {
font-size: 1.25rem;
font-weight: 800;
letter-spacing: -0.04em;
text-align: center;
margin-bottom: 2rem;
}
/* ── Modal ────────────────────────────────────────────────── */
.admin-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.65);
display: none;
align-items: center;
justify-content: center;
z-index: 9999;
padding: 1rem;
backdrop-filter: blur(4px);
}
.admin-modal-overlay.is-active { display: flex; }
.admin-modal {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 2rem;
max-width: 400px;
width: 100%;
text-align: center;
}
.admin-modal__title { font-size: 1.0625rem; font-weight: 700; margin-bottom: 0.6rem; }
.admin-modal__text { font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 1.5rem; }
.admin-modal__actions { display: flex; gap: 0.75rem; justify-content: center; }
/* Modal large (réponse) */
.admin-modal--wide {
max-width: 600px;
text-align: left;
}
.admin-modal--wide .admin-modal__actions { justify-content: flex-end; }
/* Textarea admin */
.admin-textarea {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: var(--radius-md);
color: var(--text-primary);
font-family: var(--font-main);
font-size: 0.9375rem;
line-height: 1.6;
padding: 0.875rem 1rem;
resize: vertical;
transition: border-color 0.15s ease;
box-sizing: border-box;
}
.admin-textarea:focus {
outline: none;
border-color: var(--accent);
}
/* Fil de réponses */
.msg-replies {
margin-top: 1rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.msg-reply {
background: color-mix(in srgb, var(--accent) 6%, var(--bg-secondary));
border-left: 3px solid var(--accent);
border-radius: 0 var(--radius-md) var(--radius-md) 0;
padding: 0.75rem 1rem;
}
.msg-reply__meta {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.75rem;
color: var(--accent);
font-weight: 600;
margin-bottom: 0.4rem;
}
.msg-reply__text {
font-size: 0.875rem;
line-height: 1.6;
color: var(--text-secondary);
}
/* Réponse sortante (envoyée depuis le BO) */
.msg-reply--out {
background: color-mix(in srgb, var(--accent) 6%, var(--bg-secondary));
border-left: 3px solid var(--accent);
border-radius: 0 var(--radius-md) var(--radius-md) 0;
}
/* Réponse entrante (reçue du client via IMAP) */
.msg-reply--in {
background: color-mix(in srgb, var(--green) 7%, var(--bg-secondary));
border-left: 3px solid var(--green);
border-radius: 0 var(--radius-md) var(--radius-md) 0;
}
.msg-reply--in .msg-reply__meta {
color: var(--green);
}
/* ── Analytics ────────────────────────────────────────────── */
.analytics-tables {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1rem;
margin-top: 1.5rem;
}
.analytics-table-card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 1.5rem;
}
/* ── Security ─────────────────────────────────────────────── */
.security-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
}
.form-section-title {
font-size: 0.9375rem;
font-weight: 700;
margin-bottom: 1.5rem;
letter-spacing: -0.02em;
}
/* ── Content tabs ─────────────────────────────────────────── */
.content-tabs {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.content-tab {
font-family: var(--font);
font-size: 0.82rem;
font-weight: 500;
padding: 0.42rem 0.9rem;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.15s;
}
.content-tab:hover { color: var(--text); border-color: var(--border-strong); }
.content-tab.is-active { background: var(--accent); color: #fff; border-color: var(--accent); }
.content-section.is-hidden { display: none; }
/* ── Messages ─────────────────────────────────────────────── */
.msg-filters { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
.msg-filter {
padding: 0.4rem 0.9rem;
border-radius: var(--radius-sm);
font-size: 0.82rem;
font-weight: 500;
border: 1px solid var(--border);
color: var(--text-secondary);
transition: all 0.15s;
}
.msg-filter:hover, .msg-filter.is-active {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.msg-unread-badge {
display: inline-flex;
align-items: center;
justify-content: center;
background: var(--red);
color: #fff;
font-size: 0.65rem;
font-weight: 700;
border-radius: 99px;
min-width: 1.25rem;
height: 1.25rem;
padding: 0 0.35rem;
}
.msg-list { display: flex; flex-direction: column; gap: 1rem; }
.msg-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 1.25rem 1.5rem;
transition: border-color 0.15s;
}
.msg-card.is-unread { border-left: 3px solid var(--accent); }
.msg-card:hover { border-color: var(--border-strong); }
.msg-card__head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 0.75rem;
}
.msg-card__meta { display: flex; flex-direction: column; gap: 0.2rem; }
.msg-card__name { font-weight: 700; font-size: 0.9375rem; }
.msg-card__email { font-size: 0.8125rem; color: var(--accent); }
.msg-card__date { font-size: 0.75rem; color: var(--text-secondary); white-space: nowrap; }
.msg-card__subject { font-size: 0.8125rem; font-weight: 600; color: var(--text-secondary); margin-bottom: 0.5rem; }
.msg-card__body {
font-size: 0.875rem;
line-height: 1.65;
white-space: pre-wrap;
word-break: break-word;
background: rgba(255,255,255,0.025);
border-radius: var(--radius-sm);
padding: 0.75rem 1rem;
margin-bottom: 1rem;
}
.msg-card__actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.msg-empty { text-align: center; padding: 3rem 1rem; color: var(--text-secondary); }
.msg-empty svg { margin-bottom: 1rem; opacity: 0.25; }
/* ── Utility ──────────────────────────────────────────────── */
.is-hidden { display: none !important; }
code {
font-family: var(--font-mono);
font-size: 0.82em;
background: rgba(255,255,255,0.06);
padding: 0.1em 0.4em;
border-radius: 4px;
}
/* ── Responsive ───────────────────────────────────────────── */
@media (max-width: 1024px) {
.charts-grid { grid-template-columns: 1fr; }
}
@media (max-width: 900px) {
.security-grid { grid-template-columns: 1fr; }
.admin-content { padding: 1.5rem; }
}
@media (max-width: 768px) {
.admin-sidebar {
position: fixed;
left: -100%;
z-index: 1000;
transition: left 0.25s ease;
box-shadow: 4px 0 24px rgba(0,0,0,0.5);
}
.admin-sidebar.is-open { left: 0; }
.admin-content { padding: 1.25rem; }
.stats-grid { grid-template-columns: 1fr 1fr; }
.admin-form__row { grid-template-columns: 1fr; }
.admin-topbar { gap: 1rem; }
}
@media (max-width: 480px) {
.stats-grid { grid-template-columns: 1fr; }
.admin-page-title { font-size: 1.25rem; }
}

179
admin/content.php Normal file
View file

@ -0,0 +1,179 @@
<?php
/**
* BackOffice — Contenu & SEO
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
$feedback = '';
$feedbackType = '';
// ── Sauvegarde ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$saved = 0;
foreach ($_POST as $key => $value) {
if (str_starts_with($key, 'content_')) {
$contentKey = substr($key, 8); // retire "content_"
$stmt = $db->prepare(
'UPDATE site_content SET content_value = :val WHERE content_key = :key'
);
$stmt->execute([
'val' => trim($value),
'key' => $contentKey,
]);
$saved++;
}
}
$feedback = "{$saved} champ(s) enregistré(s) avec succès.";
$feedbackType = 'success';
}
// ── Chargement du contenu ─────────────────────────────────
$rows = $db->query('SELECT * FROM site_content ORDER BY section ASC, id ASC')->fetchAll();
$content = [];
$sections = [];
foreach ($rows as $row) {
$content[$row['content_key']] = $row;
$sections[$row['section']][] = $row;
}
$sectionLabels = [
'seo' => '🔍 SEO & Métadonnées',
'hero' => '🚀 Hero — Section principale',
'about' => '👤 À propos',
'contact' => '📬 Contact',
'footer' => '🔻 Footer',
'general' => '⚙️ Général',
];
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Contenu & SEO — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Contenu & SEO</h1>
<span class="admin-topbar-sub">Tous les textes visibles sur le site</span>
</div>
<?php if ($feedback): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= htmlspecialchars($feedback, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<form method="post">
<?= Security::csrfInput() ?>
<!-- Tabs sections -->
<div class="content-tabs">
<?php foreach ($sectionLabels as $secKey => $secLabel): ?>
<?php if (!isset($sections[$secKey])) continue; ?>
<button type="button" class="content-tab <?= $secKey === 'seo' ? 'is-active' : '' ?>"
data-section="section-<?= $secKey ?>">
<?= $secLabel ?>
</button>
<?php endforeach; ?>
</div>
<?php foreach ($sectionLabels as $secKey => $secLabel): ?>
<?php if (!isset($sections[$secKey])) continue; ?>
<div id="section-<?= $secKey ?>" class="content-section <?= $secKey === 'seo' ? '' : 'is-hidden' ?>">
<div class="admin-form" style="margin-bottom:1.5rem;">
<h2 style="font-size:1rem;font-weight:700;margin-bottom:1.5rem;"><?= $secLabel ?></h2>
<?php foreach ($sections[$secKey] as $field): ?>
<div class="admin-form__group">
<label class="admin-form__label" for="field_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>">
<?= htmlspecialchars($field['label'], ENT_QUOTES, 'UTF-8') ?>
<span class="admin-form__hint">· <?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?></span>
</label>
<?php if ($field['content_type'] === 'textarea'): ?>
<textarea
id="field_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
name="content_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
class="admin-form__textarea"
rows="4"><?= htmlspecialchars($field['content_value'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
<?php elseif ($field['content_type'] === 'html'): ?>
<textarea
id="field_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
name="content_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
class="admin-form__textarea admin-form__textarea--code"
rows="6"><?= htmlspecialchars($field['content_value'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
<?php else: ?>
<input
type="text"
id="field_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
name="content_<?= htmlspecialchars($field['content_key'], ENT_QUOTES, 'UTF-8') ?>"
class="admin-form__input"
value="<?= htmlspecialchars($field['content_value'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
<?php endif; ?>
<?php if ($field['content_key'] === 'seo_description'): ?>
<p class="admin-form__counter" id="counter_seo_description">
<span id="count_seo_description"><?= mb_strlen($field['content_value'] ?? '') ?></span> / 160 caractères
</p>
<?php endif; ?>
<?php if ($field['content_key'] === 'seo_title'): ?>
<p class="admin-form__counter" id="counter_seo_title">
<span id="count_seo_title"><?= mb_strlen($field['content_value'] ?? '') ?></span> / 65 caractères
</p>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
<div style="position:sticky;bottom:1.5rem;z-index:10;text-align:right;padding:0.5rem 0;">
<button type="submit" class="admin-btn admin-btn--primary" style="box-shadow:0 4px 20px rgba(99,102,241,0.4);">
💾 Enregistrer toutes les modifications
</button>
</div>
</form>
</main>
</div>
<script nonce="<?= Security::cspNonce() ?>">
// Tabs
document.querySelectorAll('.content-tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.content-tab').forEach(t => t.classList.remove('is-active'));
document.querySelectorAll('.content-section').forEach(s => s.classList.add('is-hidden'));
tab.classList.add('is-active');
document.getElementById(tab.dataset.section).classList.remove('is-hidden');
});
});
// Compteurs SEO
function attachCounter(fieldKey, maxLen) {
const input = document.querySelector(`[name="content_${fieldKey}"]`);
const span = document.getElementById(`count_${fieldKey}`);
if (!input || !span) return;
input.addEventListener('input', () => {
const len = input.value.length;
span.textContent = len;
span.style.color = len > maxLen ? '#ef4444' : '#8b8b9e';
});
}
attachCounter('seo_description', 160);
attachCounter('seo_title', 65);
</script>
</body>
</html>

317
admin/dashboard.php Normal file
View file

@ -0,0 +1,317 @@
<?php
/**
* BackOffice — Dashboard
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true, 'allow_analytics_cdn' => true]);
Security::requireAdmin();
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
// ── Stats générales ───────────────────────────────────────
$today = $db->query("SELECT COUNT(*) FROM visits WHERE DATE(created_at) = CURDATE()")->fetchColumn();
$month = $db->query("SELECT COUNT(*) FROM visits WHERE YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) = MONTH(NOW())")->fetchColumn();
$total = $db->query("SELECT COUNT(*) FROM visits")->fetchColumn();
$avgTime = $db->query("SELECT ROUND(AVG(duration_s)) FROM visits WHERE duration_s IS NOT NULL AND duration_s < 3600")->fetchColumn();
$unread = $db->query("SELECT COUNT(*) FROM contact_messages WHERE is_read = 0")->fetchColumn();
$msgTotal = $db->query("SELECT COUNT(*) FROM contact_messages")->fetchColumn();
$projects = $db->query("SELECT COUNT(*) FROM projects WHERE status = 'published'")->fetchColumn();
// ── Visits 30 derniers jours (pour chart) ─────────────────
$visits30 = $db->query(
"SELECT DATE(created_at) as d, COUNT(*) as c
FROM visits
WHERE created_at >= NOW() - INTERVAL 30 DAY
GROUP BY DATE(created_at)
ORDER BY d ASC"
)->fetchAll();
// Remplir les jours manquants
$visitsChart = [];
for ($i = 29; $i >= 0; $i--) {
$date = date('Y-m-d', strtotime("-{$i} days"));
$visitsChart[$date] = 0;
}
foreach ($visits30 as $row) {
$visitsChart[$row['d']] = (int) $row['c'];
}
// ── Répartition devices ───────────────────────────────────
$devices = $db->query(
"SELECT device_type, COUNT(*) as c FROM visits
WHERE created_at >= NOW() - INTERVAL 30 DAY
GROUP BY device_type"
)->fetchAll();
$deviceData = ['desktop' => 0, 'mobile' => 0, 'tablet' => 0];
foreach ($devices as $d) { $deviceData[$d['device_type']] = (int) $d['c']; }
// ── Top projets par clics ─────────────────────────────────
$topProjects = $db->query(
"SELECT p.title, COUNT(pc.id) as clicks
FROM project_clicks pc
JOIN projects p ON p.id = pc.project_id
WHERE pc.created_at >= NOW() - INTERVAL 30 DAY
GROUP BY pc.project_id
ORDER BY clicks DESC
LIMIT 5"
)->fetchAll();
// ── Derniers messages ─────────────────────────────────────
$lastMessages = $db->query(
"SELECT sender_name, sender_email, subject, created_at, is_read
FROM contact_messages
ORDER BY created_at DESC LIMIT 5"
)->fetchAll();
// ── Helpers ───────────────────────────────────────────────
function fmtTime(int|null|false $s): string {
if (!$s) return '—';
if ($s < 60) return $s . 's';
return floor($s / 60) . 'min ' . ($s % 60) . 's';
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Dashboard — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Dashboard</h1>
<span class="admin-topbar-date"><?= date('d/m/Y') ?></span>
</div>
<!-- ── Stats cards ─────────────────────────────── -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--blue">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= number_format((int)$today) ?></span>
<span class="stat-card__label">Visites aujourd'hui</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--purple">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= number_format((int)$month) ?></span>
<span class="stat-card__label">Visites ce mois</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--green">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= fmtTime($avgTime) ?></span>
<span class="stat-card__label">Temps moyen / visite</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--amber">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value">
<?= $unread ?>
<?php if ($unread > 0): ?>
<a href="messages.php" style="font-size:0.75rem;font-weight:600;color:var(--admin-amber);margin-left:0.4rem;">Voir</a>
<?php endif; ?>
</span>
<span class="stat-card__label">Messages non lus</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--blue">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= number_format((int)$total) ?></span>
<span class="stat-card__label">Visites totales</span>
</div>
</div>
<div class="stat-card">
<div class="stat-card__icon stat-card__icon--green">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
</div>
<div class="stat-card__body">
<span class="stat-card__value"><?= $projects ?></span>
<span class="stat-card__label">Projets publiés</span>
</div>
</div>
</div>
<!-- ── Charts ──────────────────────────────────── -->
<div class="charts-grid">
<div class="chart-card chart-card--wide">
<h2 class="chart-card__title">Visites — 30 derniers jours</h2>
<div class="chart-card__body">
<canvas id="chartVisits" height="100"></canvas>
</div>
</div>
<div class="chart-card">
<h2 class="chart-card__title">Appareils</h2>
<div class="chart-card__body chart-card__body--center">
<canvas id="chartDevices" height="180"></canvas>
</div>
</div>
</div>
<?php if (!empty($topProjects)): ?>
<div class="charts-grid">
<div class="chart-card chart-card--wide">
<h2 class="chart-card__title">Projets les plus cliqués (30j)</h2>
<div class="chart-card__body">
<canvas id="chartProjects" height="80"></canvas>
</div>
</div>
</div>
<?php endif; ?>
<!-- ── Derniers messages ────────────────────────── -->
<div class="dash-section">
<div class="dash-section__head">
<h2 class="dash-section__title">Derniers messages</h2>
<a href="messages.php" class="admin-btn admin-btn--outline admin-btn--sm">Tous les messages</a>
</div>
<?php if (empty($lastMessages)): ?>
<div class="admin-empty"><p>Aucun message reçu.</p></div>
<?php else: ?>
<div class="admin-table-wrapper">
<table class="admin-table">
<thead><tr>
<th>Expéditeur</th><th>Sujet</th><th>Date</th><th>Statut</th>
</tr></thead>
<tbody>
<?php foreach ($lastMessages as $msg): ?>
<tr>
<td>
<strong><?= htmlspecialchars($msg['sender_name'], ENT_QUOTES, 'UTF-8') ?></strong><br>
<small style="color:var(--admin-text-secondary)"><?= htmlspecialchars($msg['sender_email'], ENT_QUOTES, 'UTF-8') ?></small>
</td>
<td><?= htmlspecialchars($msg['subject'] ?: '(sans sujet)', ENT_QUOTES, 'UTF-8') ?></td>
<td><?= date('d/m/Y H:i', strtotime($msg['created_at'])) ?></td>
<td>
<?php if (!$msg['is_read']): ?>
<span class="admin-badge admin-badge--published">Non lu</span>
<?php else: ?>
<span class="admin-badge admin-badge--draft">Lu</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</main>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js" nonce="<?= Security::cspNonce() ?>"></script>
<script nonce="<?= Security::cspNonce() ?>">
// ── Palette ───────────────────────────────────────────────
Chart.defaults.color = '#8b8b9e';
Chart.defaults.borderColor = 'rgba(255,255,255,0.06)';
Chart.defaults.font.family = 'Inter, sans-serif';
// ── Visites 30j ───────────────────────────────────────────
const visitsLabels = <?= json_encode(array_map(fn($d) => date('d/m', strtotime($d)), array_keys($visitsChart))) ?>;
const visitsData = <?= json_encode(array_values($visitsChart)) ?>;
new Chart(document.getElementById('chartVisits'), {
type: 'line',
data: {
labels: visitsLabels,
datasets: [{
label: 'Visites',
data: visitsData,
borderColor: '#6366f1',
backgroundColor: 'rgba(99,102,241,0.08)',
fill: true,
tension: 0.4,
pointRadius: 3,
pointHoverRadius: 6,
borderWidth: 2,
}]
},
options: {
responsive: true,
plugins: { legend: { display: false } },
scales: {
x: { grid: { color: 'rgba(255,255,255,0.04)' } },
y: { grid: { color: 'rgba(255,255,255,0.04)' }, beginAtZero: true, ticks: { precision: 0 } }
}
}
});
// ── Devices ───────────────────────────────────────────────
new Chart(document.getElementById('chartDevices'), {
type: 'doughnut',
data: {
labels: ['Desktop', 'Mobile', 'Tablette'],
datasets: [{
data: [<?= $deviceData['desktop'] ?>, <?= $deviceData['mobile'] ?>, <?= $deviceData['tablet'] ?>],
backgroundColor: ['#6366f1', '#22c55e', '#f59e0b'],
borderWidth: 0,
hoverOffset: 8,
}]
},
options: {
responsive: true,
cutout: '65%',
plugins: {
legend: { position: 'bottom', labels: { padding: 20, usePointStyle: true } }
}
}
});
<?php if (!empty($topProjects)): ?>
// ── Top projets ───────────────────────────────────────────
new Chart(document.getElementById('chartProjects'), {
type: 'bar',
data: {
labels: <?= json_encode(array_column($topProjects, 'title')) ?>,
datasets: [{
label: 'Clics',
data: <?= json_encode(array_column($topProjects, 'clicks')) ?>,
backgroundColor: 'rgba(99,102,241,0.7)',
borderRadius: 6,
borderSkipped: false,
}]
},
options: {
responsive: true,
indexAxis: 'y',
plugins: { legend: { display: false } },
scales: {
x: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { precision: 0 } },
y: { grid: { display: false } }
}
}
});
<?php endif; ?>
</script>
</body>
</html>

76
admin/includes/nav.php Normal file
View file

@ -0,0 +1,76 @@
<?php
/**
* Navigation sidebar - BackOffice.
*/
$unreadCount = 0;
try {
$dbNav = getDatabase();
$unreadCount = (int) $dbNav->query('SELECT COUNT(*) FROM contact_messages WHERE is_read = 0')->fetchColumn();
} catch (Throwable) {
}
$currentPage = basename($_SERVER['PHP_SELF']);
?>
<aside class="admin-sidebar">
<div class="admin-sidebar__brand">
<span class="admin-sidebar__logo">Tony<span>.</span></span>
<span class="admin-sidebar__sub">BackOffice</span>
</div>
<nav class="admin-sidebar__nav" aria-label="Navigation backoffice">
<a href="dashboard.php" class="admin-nav-item <?= $currentPage === 'dashboard.php' ? 'is-active' : '' ?>">
Dashboard
</a>
<a href="index.php" class="admin-nav-item <?= $currentPage === 'index.php' ? 'is-active' : '' ?>">
Projets
</a>
<a href="messages.php" class="admin-nav-item <?= $currentPage === 'messages.php' ? 'is-active' : '' ?>">
Messages
<?php if ($unreadCount > 0): ?>
<span class="admin-nav-badge"><?= $unreadCount ?></span>
<?php endif; ?>
</a>
<a href="services.php" class="admin-nav-item <?= $currentPage === 'services.php' ? 'is-active' : '' ?>">
Services
</a>
<a href="content.php" class="admin-nav-item <?= $currentPage === 'content.php' ? 'is-active' : '' ?>">
Contenu & SEO
</a>
<a href="analytics.php" class="admin-nav-item <?= $currentPage === 'analytics.php' ? 'is-active' : '' ?>">
Analytics
</a>
<div class="admin-nav-separator"></div>
<a href="security.php" class="admin-nav-item <?= $currentPage === 'security.php' ? 'is-active' : '' ?>">
Securite & Admins
</a>
<a href="settings.php" class="admin-nav-item <?= $currentPage === 'settings.php' ? 'is-active' : '' ?>">
Parametres
</a>
</nav>
<div class="admin-sidebar__footer">
<a href="../index.php" class="admin-sidebar__view-site">
Acceder au site
</a>
<span class="admin-sidebar__user">
<?= Security::e((string) ($_SESSION['admin_username'] ?? 'Admin')) ?>
</span>
<form method="post" action="/admin/logout.php" class="admin-sidebar__logout" style="margin:0;">
<?= Security::csrfInput() ?>
<button type="submit" style="all:unset;display:inline-flex;align-items:center;gap:0.5rem;cursor:pointer;color:inherit;">
Deconnexion
</button>
</form>
</div>
</aside>

192
admin/index.php Normal file
View file

@ -0,0 +1,192 @@
<?php
/**
* BackOffice — Gestion des projets
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
$feedback = '';
$feedbackType = '';
// ── Actions rapides (publier / dépublier) ─────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$action = $_POST['action'];
$projectId = (int) ($_POST['project_id'] ?? 0);
if ($projectId > 0) {
switch ($action) {
case 'publish':
$db->prepare('UPDATE projects SET status = :s WHERE id = :id')
->execute(['s' => 'published', 'id' => $projectId]);
$feedback = 'Projet publié avec succès.';
$feedbackType = 'success';
break;
case 'unpublish':
$db->prepare('UPDATE projects SET status = :s WHERE id = :id')
->execute(['s' => 'draft', 'id' => $projectId]);
$feedback = 'Projet repassé en brouillon.';
$feedbackType = 'success';
break;
}
}
}
// ── Message après création / modif / suppression ──────────
if (isset($_GET['success'])) {
$msgs = [
'created' => 'Projet créé avec succès.',
'updated' => 'Projet mis à jour avec succès.',
'deleted' => 'Projet supprimé avec succès.',
];
$feedback = $msgs[$_GET['success']] ?? 'Opération réussie.';
$feedbackType = 'success';
}
// ── Liste des projets ─────────────────────────────────────
$projects = $db->query('SELECT * FROM projects ORDER BY display_order ASC, created_at DESC')->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Projets — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Projets</h1>
<a href="project-form.php" class="admin-btn admin-btn--primary">+ Nouveau projet</a>
</div>
<?php if ($feedback): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= htmlspecialchars($feedback, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<?php if (empty($projects)): ?>
<div class="admin-table-wrapper">
<div class="admin-empty">
<p>Aucun projet pour le moment.</p>
<a href="project-form.php" class="admin-btn admin-btn--primary">Créer le premier projet</a>
</div>
</div>
<?php else: ?>
<div class="admin-table-wrapper">
<table class="admin-table">
<thead>
<tr>
<th>Ordre</th>
<th>Titre</th>
<th>Statut</th>
<th>Badge</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($projects as $project): ?>
<tr>
<td><?= (int) $project['display_order'] ?></td>
<td><strong><?= htmlspecialchars($project['title'], ENT_QUOTES, 'UTF-8') ?></strong></td>
<td>
<?php if ($project['status'] === 'published'): ?>
<span class="admin-badge admin-badge--published">Publié</span>
<?php else: ?>
<span class="admin-badge admin-badge--draft">Brouillon</span>
<?php endif; ?>
</td>
<td>
<?php if ($project['badge'] === 'production'): ?>
<span class="admin-badge admin-badge--production">En production</span>
<?php else: ?>
<span class="admin-badge admin-badge--development">En développement</span>
<?php endif; ?>
</td>
<td><?= date('d/m/Y', strtotime($project['created_at'])) ?></td>
<td>
<div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
<a href="project-form.php?id=<?= (int) $project['id'] ?>"
class="admin-btn admin-btn--outline admin-btn--sm">Modifier</a>
<?php if ($project['status'] === 'draft'): ?>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="project_id" value="<?= (int) $project['id'] ?>">
<input type="hidden" name="action" value="publish">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Publier</button>
</form>
<?php else: ?>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="project_id" value="<?= (int) $project['id'] ?>">
<input type="hidden" name="action" value="unpublish">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Dépublier</button>
</form>
<?php endif; ?>
<button type="button" class="admin-btn admin-btn--danger admin-btn--sm"
data-delete-project
data-project-id="<?= (int) $project['id'] ?>"
data-project-name="<?= htmlspecialchars($project['title'], ENT_QUOTES, 'UTF-8') ?>">
Supprimer
</button>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</main>
</div>
<!-- Modal suppression -->
<div class="admin-modal-overlay" id="deleteModal">
<div class="admin-modal">
<h2 class="admin-modal__title">Supprimer ce projet ?</h2>
<p class="admin-modal__text">Le projet "<span id="deleteProjectName"></span>" sera définitivement supprimé.</p>
<div class="admin-modal__actions">
<button type="button" class="admin-btn admin-btn--outline" id="closeDeleteModal">Annuler</button>
<form method="post" action="project-delete.php" id="deleteForm">
<?= Security::csrfInput() ?>
<input type="hidden" name="project_id" id="deleteProjectId">
<button type="submit" class="admin-btn admin-btn--danger">Supprimer</button>
</form>
</div>
</div>
</div>
<script nonce="<?= Security::cspNonce() ?>">
function openDeleteModal(id, name) {
document.getElementById('deleteProjectId').value = id;
document.getElementById('deleteProjectName').textContent = name;
document.getElementById('deleteModal').classList.add('is-active');
}
function closeDeleteModal() {
document.getElementById('deleteModal').classList.remove('is-active');
}
document.getElementById('deleteModal').addEventListener('click', function(e) {
if (e.target === this) closeDeleteModal();
});
document.getElementById('closeDeleteModal').addEventListener('click', closeDeleteModal);
document.querySelectorAll('[data-delete-project]').forEach(function (button) {
button.addEventListener('click', function () {
openDeleteModal(button.dataset.projectId, button.dataset.projectName);
});
});
</script>
</body>
</html>

139
admin/login.php Normal file
View file

@ -0,0 +1,139 @@
<?php
/**
* BackOffice — Page de connexion avec protection brute force
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
if (!empty($_SESSION['admin_id'])) {
header('Location: dashboard.php');
exit;
}
// Déconnexion (redirige vers le handler dédié)
if (isset($_GET['logout'])) {
header('Location: /admin/login.php');
exit;
}
$error = '';
$username = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::enforceSameOrigin();
Security::verifyCsrf($_POST['csrf_token'] ?? '');
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
$ip = Security::clientIp();
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
// Vérifier les tentatives récentes
$attempts = $db->prepare(
'SELECT COUNT(*) FROM login_attempts
WHERE ip = :ip AND created_at > NOW() - INTERVAL 15 MINUTE'
);
$attempts->execute(['ip' => $ip]);
$attemptCount = (int) $attempts->fetchColumn();
if ($attemptCount >= 5) {
$error = 'Trop de tentatives. Réessayez dans 15 minutes.';
} elseif (empty($username) || empty($password)) {
$error = 'Veuillez remplir tous les champs.';
} else {
try {
$stmt = $db->prepare(
'SELECT id, username, password_hash FROM admins WHERE username = :username LIMIT 1'
);
$stmt->execute(['username' => $username]);
$admin = $stmt->fetch();
if ($admin && password_verify($password, $admin['password_hash'])) {
// Connexion réussie
session_regenerate_id(true);
$_SESSION['admin_id'] = $admin['id'];
$_SESSION['admin_username'] = $admin['username'];
// Log succès
$db->prepare(
'INSERT INTO admin_logs (admin_id, username, action, ip, success)
VALUES (:id, :u, :a, :ip, 1)'
)->execute([
'id' => $admin['id'],
'u' => $admin['username'],
'a' => 'login',
'ip' => $ip,
]);
// Purger les tentatives de cette IP
$db->prepare('DELETE FROM login_attempts WHERE ip = :ip')->execute(['ip' => $ip]);
header('Location: dashboard.php');
exit;
} else {
// Échec — enregistrer la tentative
$db->prepare(
'INSERT INTO login_attempts (ip, username) VALUES (:ip, :u)'
)->execute(['ip' => $ip, 'u' => $username]);
// Log échec
$db->prepare(
'INSERT INTO admin_logs (username, action, ip, success)
VALUES (:u, :a, :ip, 0)'
)->execute(['u' => $username, 'a' => 'login_failed', 'ip' => $ip]);
$remaining = 5 - ($attemptCount + 1);
$error = 'Identifiants incorrects.' . ($remaining > 0 ? " ({$remaining} tentative(s) restante(s))" : '');
}
} catch (PDOException $e) {
error_log('Erreur login admin : ' . $e->getMessage());
$error = 'Une erreur est survenue. Veuillez réessayer.';
}
}
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Connexion — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-login">
<div class="admin-login__card">
<h1 class="admin-login__title">Tony<span style="color:#6366f1">.</span> BackOffice</h1>
<?php if ($error): ?>
<div class="admin-alert admin-alert--error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<form method="post" action="">
<?= Security::csrfInput() ?>
<div class="admin-form__group">
<label for="username" class="admin-form__label">Identifiant</label>
<input type="text" id="username" name="username" class="admin-form__input"
required autofocus autocomplete="username"
value="<?= htmlspecialchars($username, ENT_QUOTES, 'UTF-8') ?>">
</div>
<div class="admin-form__group">
<label for="password" class="admin-form__label">Mot de passe</label>
<input type="password" id="password" name="password" class="admin-form__input"
required autocomplete="current-password">
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary" style="width:100%;justify-content:center;">
Se connecter
</button>
</div>
</form>
</div>
</div>
</body>
</html>

35
admin/logout.php Normal file
View file

@ -0,0 +1,35 @@
<?php
/**
* BackOffice - deconnexion.
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /admin/login.php');
exit;
}
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$_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: /');
exit;

468
admin/messages.php Normal file
View file

@ -0,0 +1,468 @@
<?php
/**
* BackOffice - messages de contact et reponses.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/smtp.php';
require_once __DIR__ . '/../includes/Mailer.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
$db = getDatabase();
$db->exec("CREATE TABLE IF NOT EXISTS message_replies (
id INT AUTO_INCREMENT PRIMARY KEY,
message_id INT NOT NULL,
reply_text TEXT NOT NULL,
direction ENUM('out','in') NOT NULL DEFAULT 'out',
sender_email VARCHAR(255) DEFAULT NULL,
message_id_sent VARCHAR(255) DEFAULT NULL,
sent_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");
foreach ([
"ALTER TABLE message_replies ADD COLUMN direction ENUM('out','in') NOT NULL DEFAULT 'out'",
"ALTER TABLE message_replies ADD COLUMN sender_email VARCHAR(255) DEFAULT NULL",
"ALTER TABLE message_replies ADD COLUMN message_id_sent VARCHAR(255) DEFAULT NULL",
] as $alterSql) {
try {
$db->exec($alterSql);
} catch (Throwable) {
}
}
$db->exec("CREATE TABLE IF NOT EXISTS sent_message_ids (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id VARCHAR(255) NOT NULL,
contact_message_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_message_id (message_id),
INDEX idx_smid_contact (contact_message_id)
) ENGINE=InnoDB");
$feedback = '';
$feedbackType = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['msg_id'])) {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$action = (string) $_POST['action'];
$msgId = (int) $_POST['msg_id'];
if ($msgId > 0) {
if ($action === 'mark_read') {
$db->prepare('UPDATE contact_messages SET is_read = 1 WHERE id = :id')->execute(['id' => $msgId]);
} elseif ($action === 'mark_unread') {
$db->prepare('UPDATE contact_messages SET is_read = 0 WHERE id = :id')->execute(['id' => $msgId]);
} elseif ($action === 'delete') {
$db->prepare('DELETE FROM contact_messages WHERE id = :id')->execute(['id' => $msgId]);
$db->prepare('DELETE FROM message_replies WHERE message_id = :id')->execute(['id' => $msgId]);
$feedback = 'Message supprime.';
$feedbackType = 'success';
} elseif ($action === 'reply') {
$replyText = trim((string) ($_POST['reply_text'] ?? ''));
if ($replyText === '') {
$feedback = 'La reponse ne peut pas etre vide.';
$feedbackType = 'error';
} else {
$messageStmt = $db->prepare('SELECT * FROM contact_messages WHERE id = :id LIMIT 1');
$messageStmt->execute(['id' => $msgId]);
$message = $messageStmt->fetch();
if ($message) {
$db->prepare('UPDATE contact_messages SET is_read = 1 WHERE id = :id')->execute(['id' => $msgId]);
$repliesStmt = $db->prepare(
'SELECT * FROM message_replies WHERE message_id = :id ORDER BY sent_at ASC'
);
$repliesStmt->execute(['id' => $msgId]);
$previousReplies = $repliesStmt->fetchAll();
$subject = 'Re: ' . ($message['subject'] ?: 'Votre message');
$bodyHtml = buildReplyHtml(
(string) $message['sender_name'],
$replyText,
$message,
$previousReplies
);
$bodyText = buildReplyText(
(string) $message['sender_name'],
$replyText,
$message,
$previousReplies
);
$mailer = new Mailer();
$sent = $mailer->sendHtml(
(string) $message['sender_email'],
$subject,
$bodyHtml,
$bodyText,
NOTIFY_EMAIL
);
$replyMsgId = $mailer->getLastMessageId();
$db->prepare(
'INSERT INTO message_replies (message_id, reply_text, direction, message_id_sent)
VALUES (:message_id, :reply_text, :direction, :message_id_sent)'
)->execute([
'message_id' => $msgId,
'reply_text' => $replyText,
'direction' => 'out',
'message_id_sent' => $replyMsgId !== '' ? $replyMsgId : null,
]);
if ($replyMsgId !== '') {
try {
$db->prepare(
'INSERT IGNORE INTO sent_message_ids (message_id, contact_message_id)
VALUES (:message_id, :contact_message_id)'
)->execute([
'message_id' => $replyMsgId,
'contact_message_id' => $msgId,
]);
} catch (Throwable) {
}
}
$feedback = $sent
? 'Reponse envoyee et enregistree.'
: 'Reponse enregistree, mais l\'envoi email a echoue.';
$feedbackType = $sent ? 'success' : 'warning';
}
}
}
}
}
$filter = (string) ($_GET['filter'] ?? 'all');
$where = match ($filter) {
'unread' => 'WHERE is_read = 0',
'read' => 'WHERE is_read = 1',
default => '',
};
$messages = $db->query("SELECT * FROM contact_messages {$where} ORDER BY created_at DESC")->fetchAll();
$unreadCount = (int) $db->query('SELECT COUNT(*) FROM contact_messages WHERE is_read = 0')->fetchColumn();
$totalCount = (int) $db->query('SELECT COUNT(*) FROM contact_messages')->fetchColumn();
$repliesMap = [];
$allReplies = $db->query('SELECT * FROM message_replies ORDER BY sent_at ASC')->fetchAll();
foreach ($allReplies as $reply) {
$repliesMap[(int) $reply['message_id']][] = $reply;
}
function buildReplyHtml(string $clientName, string $replyText, array $message, array $previousReplies): string
{
$safeClientName = Security::e($clientName);
$safeReply = nl2br(Security::e($replyText));
$threadHtml = '';
foreach (array_reverse($previousReplies) as $reply) {
$isIncoming = ($reply['direction'] ?? 'out') === 'in';
$who = $isIncoming ? $safeClientName : 'Tony AVERTY';
$date = date('d/m/Y H:i', strtotime($reply['sent_at']));
$bg = $isIncoming ? '#f0fdf4' : '#eff6ff';
$border = $isIncoming ? '#16a34a' : '#2563eb';
$text = nl2br(Security::e((string) $reply['reply_text']));
$threadHtml .= <<<HTML
<tr>
<td style="padding:0 28px 12px;">
<div style="padding:14px 16px;background:{$bg};border-left:3px solid {$border};border-radius:0 8px 8px 0;">
<p style="margin:0 0 8px;font-size:12px;color:#6b7280;"><strong>{$who}</strong> · {$date}</p>
<div style="font-size:14px;line-height:1.7;color:#1f2937;">{$text}</div>
</div>
</td>
</tr>
HTML;
}
$originalText = nl2br(Security::e((string) $message['message']));
$originalDate = date('d/m/Y H:i', strtotime($message['created_at']));
$threadHtml .= <<<HTML
<tr>
<td style="padding:0 28px 24px;">
<div style="padding:14px 16px;background:#f8fafc;border-left:3px solid #94a3b8;border-radius:0 8px 8px 0;">
<p style="margin:0 0 8px;font-size:12px;color:#6b7280;"><strong>{$safeClientName}</strong> · {$originalDate} (message initial)</p>
<div style="font-size:14px;line-height:1.7;color:#1f2937;">{$originalText}</div>
</div>
</td>
</tr>
HTML;
return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body style="margin:0;padding:24px;background:#f4f4f5;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="620" cellpadding="0" cellspacing="0" style="max-width:620px;width:100%;background:#ffffff;border:1px solid #e5e7eb;border-radius:14px;overflow:hidden;">
<tr>
<td style="padding:28px;background:#111827;color:#ffffff;">
<strong>Tony AVERTY</strong><br>
<span style="font-size:13px;opacity:.8;">Reponse a votre message</span>
</td>
</tr>
<tr>
<td style="padding:28px;color:#111827;">
<p style="margin:0 0 14px;">Bonjour {$safeClientName},</p>
<div style="font-size:15px;line-height:1.75;color:#374151;">{$safeReply}</div>
</td>
</tr>
{$threadHtml}
<tr>
<td style="padding:18px 28px;background:#f9fafb;border-top:1px solid #e5e7eb;color:#6b7280;font-size:12px;">
Tony AVERTY · <a href="mailto:contact@tony-averty.dev" style="color:#2563eb;text-decoration:none;">contact@tony-averty.dev</a> · <a href="https://tony-averty.dev" style="color:#2563eb;text-decoration:none;">tony-averty.dev</a>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
HTML;
}
function buildReplyText(string $clientName, string $replyText, array $message, array $previousReplies): string
{
$lines = [
"Bonjour {$clientName},",
'',
$replyText,
'',
'---',
'Tony AVERTY - contact@tony-averty.dev - tony-averty.dev',
'',
];
if (!empty($previousReplies)) {
$lines[] = 'Conversation precedente';
$lines[] = '-----------------------';
foreach (array_reverse($previousReplies) as $reply) {
$who = ($reply['direction'] ?? 'out') === 'in' ? $clientName : 'Tony AVERTY';
$date = date('d/m/Y H:i', strtotime($reply['sent_at']));
$lines[] = "Le {$date}, {$who} a ecrit :";
$lines[] = (string) $reply['reply_text'];
$lines[] = '';
}
}
$lines[] = "Message initial de {$clientName} :";
$lines[] = (string) $message['message'];
return implode("\n", $lines);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Messages - BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">
Messages
<?php if ($unreadCount > 0): ?>
<span class="msg-unread-badge"><?= $unreadCount ?></span>
<?php endif; ?>
</h1>
<span class="admin-topbar-sub"><?= $totalCount ?> message(s) au total</span>
</div>
<?php if ($feedback !== ''): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= Security::e($feedback) ?></div>
<?php endif; ?>
<div class="msg-filters">
<a href="?filter=all" class="msg-filter <?= $filter === 'all' ? 'is-active' : '' ?>">Tous (<?= $totalCount ?>)</a>
<a href="?filter=unread" class="msg-filter <?= $filter === 'unread' ? 'is-active' : '' ?>">Non lus (<?= $unreadCount ?>)</a>
<a href="?filter=read" class="msg-filter <?= $filter === 'read' ? 'is-active' : '' ?>">Lus</a>
</div>
<?php if (empty($messages)): ?>
<div class="msg-empty">
<p>Aucun message<?= $filter !== 'all' ? ' dans cette categorie' : '' ?>.</p>
</div>
<?php else: ?>
<div class="msg-list">
<?php foreach ($messages as $message): ?>
<?php $messageReplies = $repliesMap[(int) $message['id']] ?? []; ?>
<article class="msg-card <?= $message['is_read'] ? '' : 'is-unread' ?>">
<div class="msg-card__head">
<div class="msg-card__meta">
<span class="msg-card__name"><?= Security::e((string) $message['sender_name']) ?></span>
<a href="mailto:<?= Security::e((string) $message['sender_email']) ?>" class="msg-card__email">
<?= Security::e((string) $message['sender_email']) ?>
</a>
</div>
<span class="msg-card__date"><?= date('d/m/Y H:i', strtotime($message['created_at'])) ?></span>
</div>
<?php if (!empty($message['subject'])): ?>
<div class="msg-card__subject">Sujet : <?= Security::e((string) $message['subject']) ?></div>
<?php endif; ?>
<div class="msg-card__body"><?= nl2br(Security::e((string) $message['message'])) ?></div>
<?php if (!empty($messageReplies)): ?>
<div class="msg-replies">
<?php foreach ($messageReplies as $reply): ?>
<?php $incoming = ($reply['direction'] ?? 'out') === 'in'; ?>
<div class="msg-reply msg-reply--<?= $incoming ? 'in' : 'out' ?>">
<div class="msg-reply__meta">
<?= $incoming ? 'Reponse recue' : 'Reponse envoyee' ?>
<?php if ($incoming && !empty($reply['sender_email'])): ?>
de <strong><?= Security::e((string) $reply['sender_email']) ?></strong>
<?php endif; ?>
le <?= date('d/m/Y H:i', strtotime($reply['sent_at'])) ?>
</div>
<div class="msg-reply__text"><?= nl2br(Security::e((string) $reply['reply_text'])) ?></div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="msg-card__actions">
<button
type="button"
class="admin-btn admin-btn--primary admin-btn--sm"
data-open-reply
data-message-id="<?= (int) $message['id'] ?>"
data-sender-name="<?= Security::e((string) $message['sender_name']) ?>"
data-sender-email="<?= Security::e((string) $message['sender_email']) ?>">
Repondre
</button>
<?php if (empty($message['is_read'])): ?>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="msg_id" value="<?= (int) $message['id'] ?>">
<input type="hidden" name="action" value="mark_read">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Marquer lu</button>
</form>
<?php else: ?>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="msg_id" value="<?= (int) $message['id'] ?>">
<input type="hidden" name="action" value="mark_unread">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Marquer non lu</button>
</form>
<?php endif; ?>
<button
type="button"
class="admin-btn admin-btn--danger admin-btn--sm"
data-delete-message
data-message-id="<?= (int) $message['id'] ?>"
data-sender-name="<?= Security::e((string) $message['sender_name']) ?>">
Supprimer
</button>
</div>
</article>
<?php endforeach; ?>
</div>
<?php endif; ?>
</main>
</div>
<div class="admin-modal-overlay" id="replyModal">
<div class="admin-modal admin-modal--wide">
<h2 class="admin-modal__title">Repondre a <span id="replyName"></span></h2>
<p class="admin-modal__text" id="replyEmailLabel" style="margin-bottom:1rem;"></p>
<form method="post" id="replyForm">
<?= Security::csrfInput() ?>
<input type="hidden" name="msg_id" id="replyMsgId">
<input type="hidden" name="action" value="reply">
<textarea name="reply_text" id="replyText" class="admin-textarea" rows="7" placeholder="Votre reponse..." required></textarea>
<div class="admin-modal__actions" style="margin-top:1rem;">
<button type="button" class="admin-btn admin-btn--outline" id="closeReplyModal">Annuler</button>
<button type="submit" class="admin-btn admin-btn--primary">Envoyer la reponse</button>
</div>
</form>
</div>
</div>
<div class="admin-modal-overlay" id="deleteModal">
<div class="admin-modal">
<h2 class="admin-modal__title">Supprimer ce message ?</h2>
<p class="admin-modal__text">Le message de "<span id="deleteName"></span>" et toutes ses reponses seront supprimes.</p>
<div class="admin-modal__actions">
<button type="button" class="admin-btn admin-btn--outline" id="closeDeleteModal">Annuler</button>
<form method="post" id="deleteForm">
<?= Security::csrfInput() ?>
<input type="hidden" name="msg_id" id="deleteMsgId">
<input type="hidden" name="action" value="delete">
<button type="submit" class="admin-btn admin-btn--danger">Supprimer</button>
</form>
</div>
</div>
</div>
<script nonce="<?= Security::cspNonce() ?>">
function openReplyModal(id, name, email) {
document.getElementById('replyMsgId').value = id;
document.getElementById('replyName').textContent = name;
document.getElementById('replyEmailLabel').textContent = 'A : ' + email;
document.getElementById('replyText').value = '';
document.getElementById('replyModal').classList.add('is-active');
document.getElementById('replyText').focus();
}
function closeReplyModal() {
document.getElementById('replyModal').classList.remove('is-active');
}
function confirmDelete(id, name) {
document.getElementById('deleteMsgId').value = id;
document.getElementById('deleteName').textContent = name;
document.getElementById('deleteModal').classList.add('is-active');
}
function closeDeleteModal() {
document.getElementById('deleteModal').classList.remove('is-active');
}
document.querySelectorAll('[data-open-reply]').forEach(function (button) {
button.addEventListener('click', function () {
openReplyModal(button.dataset.messageId, button.dataset.senderName, button.dataset.senderEmail);
});
});
document.querySelectorAll('[data-delete-message]').forEach(function (button) {
button.addEventListener('click', function () {
confirmDelete(button.dataset.messageId, button.dataset.senderName);
});
});
document.getElementById('closeReplyModal').addEventListener('click', closeReplyModal);
document.getElementById('closeDeleteModal').addEventListener('click', closeDeleteModal);
document.getElementById('replyModal').addEventListener('click', function (event) {
if (event.target === this) {
closeReplyModal();
}
});
document.getElementById('deleteModal').addEventListener('click', function (event) {
if (event.target === this) {
closeDeleteModal();
}
});
</script>
</body>
</html>

58
admin/project-delete.php Normal file
View file

@ -0,0 +1,58 @@
<?php
/**
* BackOffice — Suppression d'un projet
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: index.php');
exit;
}
Security::verifyCsrf($_POST['csrf_token'] ?? '');
require_once __DIR__ . '/../config/database.php';
$projectId = (int) ($_POST['project_id'] ?? 0);
if ($projectId > 0) {
try {
$db = getDatabase();
// Récupérer l'image pour la supprimer du disque
$stmt = $db->prepare('SELECT image FROM projects WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $projectId]);
$project = $stmt->fetch();
if ($project) {
// Supprimer l'image si elle existe
if (!empty($project['image'])) {
$uploadDir = realpath(__DIR__ . '/../assets/img/projects');
if ($uploadDir !== false) {
$imagePath = $uploadDir . DIRECTORY_SEPARATOR . basename((string) $project['image']);
if (is_file($imagePath)) {
unlink($imagePath);
}
}
}
// Supprimer le projet
$stmt = $db->prepare('DELETE FROM projects WHERE id = :id');
$stmt->execute(['id' => $projectId]);
}
header('Location: index.php?success=deleted');
exit;
} catch (PDOException $e) {
error_log('Erreur suppression projet : ' . $e->getMessage());
header('Location: index.php');
exit;
}
}
header('Location: index.php');
exit;

269
admin/project-form.php Normal file
View file

@ -0,0 +1,269 @@
<?php
/**
* BackOffice - ajout et edition de projet.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
$db = getDatabase();
$error = '';
$isEdit = false;
$project = [
'id' => '',
'title' => '',
'slug' => '',
'short_description' => '',
'full_description' => '',
'image' => '',
'status' => 'published',
'badge' => 'development',
'technologies' => '',
'project_url' => '',
'display_order' => 0,
];
if (!empty($_GET['id'])) {
$stmt = $db->prepare('SELECT * FROM projects WHERE id = :id LIMIT 1');
$stmt->execute(['id' => (int) $_GET['id']]);
$existing = $stmt->fetch();
if (!$existing) {
header('Location: index.php');
exit;
}
$project = $existing;
$isEdit = true;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$project['title'] = trim((string) ($_POST['title'] ?? ''));
$project['slug'] = trim((string) ($_POST['slug'] ?? ''));
$project['short_description'] = trim((string) ($_POST['short_description'] ?? ''));
$project['full_description'] = trim((string) ($_POST['full_description'] ?? ''));
$project['status'] = in_array($_POST['status'] ?? '', ['draft', 'published'], true) ? $_POST['status'] : 'draft';
$project['badge'] = in_array($_POST['badge'] ?? '', ['development', 'production'], true) ? $_POST['badge'] : 'development';
$project['technologies'] = trim((string) ($_POST['technologies'] ?? ''));
$project['project_url'] = trim((string) ($_POST['project_url'] ?? ''));
$project['display_order'] = max(0, (int) ($_POST['display_order'] ?? 0));
$project['slug'] = Security::slugify($project['slug'] !== '' ? $project['slug'] : $project['title']);
if ($project['title'] === '') {
$error = 'Le titre est requis.';
} elseif ($project['short_description'] === '') {
$error = 'La description courte est requise.';
} elseif ($project['project_url'] !== '' && !preg_match('#^https://#i', $project['project_url'])) {
$error = 'Le lien du projet doit commencer par https://';
}
$imageFilename = (string) ($project['image'] ?? '');
if ($error === '' && !empty($_FILES['image_file']['name']) && (int) $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['image_file']['tmp_name']) ?: '';
$allowed = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
];
if (!isset($allowed[$mime])) {
$error = 'Format d\'image non autorise. Utilisez JPG, PNG ou WebP.';
} elseif ((int) $_FILES['image_file']['size'] > 5 * 1024 * 1024) {
$error = 'L\'image ne doit pas depasser 5 Mo.';
} elseif (!is_uploaded_file($_FILES['image_file']['tmp_name'])) {
$error = 'Upload invalide.';
} else {
$uploadDir = realpath(__DIR__ . '/../assets/img/projects');
if ($uploadDir === false) {
$error = 'Dossier d\'upload introuvable.';
} else {
$previousImage = $imageFilename;
$imageFilename = $project['slug'] . '-' . bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
$uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $imageFilename;
if (!move_uploaded_file($_FILES['image_file']['tmp_name'], $uploadPath)) {
$error = 'Erreur lors de l\'upload de l\'image.';
$imageFilename = $previousImage;
} else {
@chmod($uploadPath, 0644);
if ($previousImage !== '' && $previousImage !== $imageFilename) {
$oldPath = $uploadDir . DIRECTORY_SEPARATOR . basename($previousImage);
if (is_file($oldPath)) {
@unlink($oldPath);
}
}
}
}
}
}
if ($error === '') {
try {
if ($isEdit) {
$stmt = $db->prepare(
'UPDATE projects SET
title = :title,
slug = :slug,
short_description = :short_description,
full_description = :full_description,
image = :image,
status = :status,
badge = :badge,
technologies = :technologies,
project_url = :project_url,
display_order = :display_order
WHERE id = :id'
);
$stmt->execute([
'title' => $project['title'],
'slug' => $project['slug'],
'short_description' => $project['short_description'],
'full_description' => $project['full_description'],
'image' => $imageFilename,
'status' => $project['status'],
'badge' => $project['badge'],
'technologies' => $project['technologies'],
'project_url' => $project['project_url'],
'display_order' => $project['display_order'],
'id' => (int) $_GET['id'],
]);
header('Location: index.php?success=updated');
exit;
}
$stmt = $db->prepare(
'INSERT INTO projects (
title, slug, short_description, full_description, image, status, badge, technologies, project_url, display_order
) VALUES (
:title, :slug, :short_description, :full_description, :image, :status, :badge, :technologies, :project_url, :display_order
)'
);
$stmt->execute([
'title' => $project['title'],
'slug' => $project['slug'],
'short_description' => $project['short_description'],
'full_description' => $project['full_description'],
'image' => $imageFilename,
'status' => $project['status'],
'badge' => $project['badge'],
'technologies' => $project['technologies'],
'project_url' => $project['project_url'],
'display_order' => $project['display_order'],
]);
header('Location: index.php?success=created');
exit;
} catch (PDOException $e) {
error_log('[ProjectForm] ' . $e->getMessage());
$error = 'Une erreur est survenue. Veuillez reessayer.';
}
}
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title><?= $isEdit ? 'Modifier' : 'Nouveau' ?> projet - BackOffice</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-layout">
<header class="admin-header">
<h1 class="admin-header__title"><?= $isEdit ? 'Modifier' : 'Nouveau' ?> <span>projet</span></h1>
<div class="admin-header__actions">
<a href="index.php" class="admin-btn admin-btn--outline">Retour</a>
</div>
</header>
<?php if ($error !== ''): ?>
<div class="admin-alert admin-alert--error"><?= Security::e($error) ?></div>
<?php endif; ?>
<form class="admin-form" method="post" enctype="multipart/form-data">
<?= Security::csrfInput() ?>
<div class="admin-form__group">
<label for="title" class="admin-form__label">Titre du projet</label>
<input type="text" id="title" name="title" class="admin-form__input" required value="<?= Security::e((string) $project['title']) ?>">
</div>
<div class="admin-form__group">
<label for="slug" class="admin-form__label">Slug <span class="admin-form__hint">(genere automatiquement si vide)</span></label>
<input type="text" id="slug" name="slug" class="admin-form__input" value="<?= Security::e((string) $project['slug']) ?>">
</div>
<div class="admin-form__group">
<label for="short_description" class="admin-form__label">Description courte</label>
<textarea id="short_description" name="short_description" class="admin-form__textarea" rows="3" required><?= Security::e((string) $project['short_description']) ?></textarea>
</div>
<div class="admin-form__group">
<label for="full_description" class="admin-form__label">Description detaillee <span class="admin-form__hint">(optionnel)</span></label>
<textarea id="full_description" name="full_description" class="admin-form__textarea" rows="6"><?= Security::e((string) ($project['full_description'] ?? '')) ?></textarea>
</div>
<div class="admin-form__group">
<label for="image_file" class="admin-form__label">Image <span class="admin-form__hint">(JPG, PNG ou WebP - max 5 Mo)</span></label>
<input type="file" id="image_file" name="image_file" class="admin-form__input" accept=".jpg,.jpeg,.png,.webp">
<?php if (!empty($project['image'])): ?>
<p style="margin-top:0.5rem;font-size:0.8125rem;color:var(--admin-text-secondary);">
Image actuelle : <?= Security::e((string) $project['image']) ?>
</p>
<?php endif; ?>
</div>
<div class="admin-form__row">
<div class="admin-form__group">
<label for="status" class="admin-form__label">Statut de publication</label>
<select id="status" name="status" class="admin-form__select">
<option value="draft" <?= ($project['status'] === 'draft') ? 'selected' : '' ?>>Brouillon</option>
<option value="published" <?= ($project['status'] === 'published') ? 'selected' : '' ?>>Publie</option>
</select>
</div>
<div class="admin-form__group">
<label for="badge" class="admin-form__label">Badge d'etat</label>
<select id="badge" name="badge" class="admin-form__select">
<option value="development" <?= ($project['badge'] === 'development') ? 'selected' : '' ?>>En developpement</option>
<option value="production" <?= ($project['badge'] === 'production') ? 'selected' : '' ?>>En production</option>
</select>
</div>
</div>
<div class="admin-form__group">
<label for="technologies" class="admin-form__label">Technologies <span class="admin-form__hint">(separees par des virgules)</span></label>
<input type="text" id="technologies" name="technologies" class="admin-form__input" placeholder="HTML, CSS, PHP, JavaScript" value="<?= Security::e((string) ($project['technologies'] ?? '')) ?>">
</div>
<div class="admin-form__row">
<div class="admin-form__group">
<label for="project_url" class="admin-form__label">Lien du projet <span class="admin-form__hint">(https uniquement)</span></label>
<input type="url" id="project_url" name="project_url" class="admin-form__input" placeholder="https://..." value="<?= Security::e((string) ($project['project_url'] ?? '')) ?>">
</div>
<div class="admin-form__group">
<label for="display_order" class="admin-form__label">Ordre d'affichage</label>
<input type="number" id="display_order" name="display_order" class="admin-form__input" min="0" value="<?= (int) $project['display_order'] ?>">
</div>
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary"><?= $isEdit ? 'Mettre a jour' : 'Creer le projet' ?></button>
<a href="index.php" class="admin-btn admin-btn--outline">Annuler</a>
</div>
</form>
</div>
</body>
</html>

339
admin/security.php Normal file
View file

@ -0,0 +1,339 @@
<?php
/**
* BackOffice - securite et gestion des admins.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
$db = getDatabase();
$feedback = '';
$feedbackType = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$action = (string) ($_POST['action'] ?? '');
if ($action === 'change_password') {
$current = (string) ($_POST['current_password'] ?? '');
$new = (string) ($_POST['new_password'] ?? '');
$confirm = (string) ($_POST['confirm_password'] ?? '');
if ($current === '' || $new === '' || $confirm === '') {
$feedback = 'Tous les champs sont requis.';
$feedbackType = 'error';
} elseif ($new !== $confirm) {
$feedback = 'Les nouveaux mots de passe ne correspondent pas.';
$feedbackType = 'error';
} elseif (strlen($new) < 12 || !preg_match('/[A-Z]/', $new) || !preg_match('/[a-z]/', $new) || !preg_match('/\d/', $new)) {
$feedback = 'Le mot de passe doit contenir au moins 12 caracteres, une majuscule, une minuscule et un chiffre.';
$feedbackType = 'error';
} else {
$stmt = $db->prepare('SELECT password_hash FROM admins WHERE id = :id');
$stmt->execute(['id' => $_SESSION['admin_id']]);
$hash = (string) $stmt->fetchColumn();
if ($hash === '' || !password_verify($current, $hash)) {
$feedback = 'Mot de passe actuel incorrect.';
$feedbackType = 'error';
} else {
$newHash = password_hash($new, PASSWORD_DEFAULT);
$db->prepare('UPDATE admins SET password_hash = :hash WHERE id = :id')
->execute([
'hash' => $newHash,
'id' => $_SESSION['admin_id'],
]);
$db->prepare(
'INSERT INTO admin_logs (admin_id, username, action, ip, success)
VALUES (:admin_id, :username, :action, :ip, 1)'
)->execute([
'admin_id' => $_SESSION['admin_id'],
'username' => $_SESSION['admin_username'],
'action' => 'change_password',
'ip' => Security::clientIp(),
]);
$feedback = 'Mot de passe modifie avec succes.';
$feedbackType = 'success';
}
}
} elseif ($action === 'create_admin') {
$username = trim((string) ($_POST['new_username'] ?? ''));
$password = (string) ($_POST['new_admin_password'] ?? '');
if (!preg_match('/^[a-zA-Z0-9._-]{3,50}$/', $username)) {
$feedback = 'Identifiant invalide. Utilisez 3 a 50 caracteres alphanumeriques.';
$feedbackType = 'error';
} elseif (strlen($password) < 12 || !preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/\d/', $password)) {
$feedback = 'Le mot de passe doit contenir au moins 12 caracteres, une majuscule, une minuscule et un chiffre.';
$feedbackType = 'error';
} else {
try {
$db->prepare('INSERT INTO admins (username, password_hash) VALUES (:username, :hash)')
->execute([
'username' => $username,
'hash' => password_hash($password, PASSWORD_DEFAULT),
]);
$db->prepare(
'INSERT INTO admin_logs (admin_id, username, action, detail, ip, success)
VALUES (:admin_id, :username, :action, :detail, :ip, 1)'
)->execute([
'admin_id' => $_SESSION['admin_id'],
'username' => $_SESSION['admin_username'],
'action' => 'create_admin',
'detail' => 'Cree : ' . $username,
'ip' => Security::clientIp(),
]);
$feedback = 'Compte admin cree avec succes.';
$feedbackType = 'success';
} catch (PDOException) {
$feedback = 'Cet identifiant existe deja.';
$feedbackType = 'error';
}
}
} elseif ($action === 'delete_admin') {
$adminId = (int) ($_POST['admin_id'] ?? 0);
if ($adminId === (int) $_SESSION['admin_id']) {
$feedback = 'Vous ne pouvez pas supprimer votre propre compte.';
$feedbackType = 'error';
} elseif ($adminId > 0) {
$db->prepare('DELETE FROM admins WHERE id = :id')->execute(['id' => $adminId]);
$feedback = 'Compte admin supprime.';
$feedbackType = 'success';
}
} elseif ($action === 'purge_logs') {
$db->exec('DELETE FROM admin_logs WHERE created_at < NOW() - INTERVAL 90 DAY');
$db->exec('DELETE FROM login_attempts WHERE created_at < NOW() - INTERVAL 7 DAY');
$feedback = 'Logs anciens purges.';
$feedbackType = 'success';
} elseif ($action === 'unblock_ip') {
$ip = trim((string) ($_POST['ip'] ?? ''));
if ($ip !== '') {
$db->prepare('DELETE FROM login_attempts WHERE ip = :ip')->execute(['ip' => $ip]);
$feedback = 'IP debloquee.';
$feedbackType = 'success';
}
}
}
$admins = $db->query('SELECT id, username, created_at FROM admins ORDER BY created_at ASC')->fetchAll();
$logs = $db->query(
'SELECT * FROM admin_logs ORDER BY created_at DESC LIMIT 50'
)->fetchAll();
$blockedIps = $db->query(
"SELECT ip, COUNT(*) AS attempts, MAX(created_at) AS last_attempt
FROM login_attempts
WHERE created_at > NOW() - INTERVAL 15 MINUTE
GROUP BY ip
HAVING attempts >= 5
ORDER BY attempts DESC"
)->fetchAll();
$totalAttempts = (int) $db->query(
'SELECT COUNT(*) FROM login_attempts WHERE created_at > NOW() - INTERVAL 24 HOUR'
)->fetchColumn();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Securite - BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Securite et admins</h1>
</div>
<?php if ($feedback !== ''): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= Security::e($feedback) ?></div>
<?php endif; ?>
<div class="security-grid">
<div class="admin-form">
<h2 class="form-section-title">Changer mon mot de passe</h2>
<form method="post">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="change_password">
<div class="admin-form__group">
<label class="admin-form__label" for="current_password">Mot de passe actuel</label>
<input type="password" id="current_password" name="current_password" class="admin-form__input" required autocomplete="current-password">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="new_password">Nouveau mot de passe</label>
<input type="password" id="new_password" name="new_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="confirm_password">Confirmer le nouveau mot de passe</label>
<input type="password" id="confirm_password" name="confirm_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary">Modifier le mot de passe</button>
</div>
</form>
</div>
<div class="admin-form">
<h2 class="form-section-title">Creer un compte admin</h2>
<form method="post">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="create_admin">
<div class="admin-form__group">
<label class="admin-form__label" for="new_username">Identifiant</label>
<input type="text" id="new_username" name="new_username" class="admin-form__input" required maxlength="50" autocomplete="off">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="new_admin_password">Mot de passe</label>
<input type="password" id="new_admin_password" name="new_admin_password" class="admin-form__input" required minlength="12" autocomplete="new-password">
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary">Creer le compte</button>
</div>
</form>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<h2 class="form-section-title">Comptes administrateurs</h2>
<table class="admin-table" style="margin-top:1rem;">
<thead>
<tr><th>ID</th><th>Identifiant</th><th>Cree le</th><th>Action</th></tr>
</thead>
<tbody>
<?php foreach ($admins as $admin): ?>
<tr>
<td><?= (int) $admin['id'] ?></td>
<td>
<strong><?= Security::e($admin['username']) ?></strong>
<?php if ((int) $admin['id'] === (int) $_SESSION['admin_id']): ?>
<span class="admin-badge admin-badge--published" style="margin-left:0.5rem;">Vous</span>
<?php endif; ?>
</td>
<td><?= date('d/m/Y', strtotime($admin['created_at'])) ?></td>
<td>
<?php if ((int) $admin['id'] !== (int) $_SESSION['admin_id']): ?>
<form method="post" style="display:inline;" data-confirm-message="Supprimer cet admin ?">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="delete_admin">
<input type="hidden" name="admin_id" value="<?= (int) $admin['id'] ?>">
<button type="submit" class="admin-btn admin-btn--danger admin-btn--sm">Supprimer</button>
</form>
<?php else: ?>
<span style="color:var(--admin-text-secondary);font-size:0.8125rem;">-</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;flex-wrap:wrap;gap:0.75rem;">
<h2 class="form-section-title" style="margin:0;">IPs bloquees</h2>
<span style="font-size:0.8125rem;color:var(--admin-text-secondary);">
<?= $totalAttempts ?> tentative(s) sur 24h
</span>
</div>
<?php if (empty($blockedIps)): ?>
<p style="color:var(--admin-text-secondary);font-size:0.875rem;">Aucune IP bloquee en ce moment.</p>
<?php else: ?>
<table class="admin-table">
<thead>
<tr><th>IP</th><th>Tentatives</th><th>Derniere tentative</th><th>Action</th></tr>
</thead>
<tbody>
<?php foreach ($blockedIps as $blockedIp): ?>
<tr>
<td><code><?= Security::e($blockedIp['ip']) ?></code></td>
<td><strong><?= (int) $blockedIp['attempts'] ?></strong></td>
<td><?= date('d/m/Y H:i:s', strtotime($blockedIp['last_attempt'])) ?></td>
<td>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="unblock_ip">
<input type="hidden" name="ip" value="<?= Security::e($blockedIp['ip']) ?>">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Debloquer</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<div class="admin-form" style="grid-column:1/-1;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;flex-wrap:wrap;gap:0.75rem;">
<h2 class="form-section-title" style="margin:0;">Logs d'activite</h2>
<form method="post" data-confirm-message="Purger les logs de plus de 90 jours ?">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="purge_logs">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">Purger les anciens logs</button>
</form>
</div>
<?php if (empty($logs)): ?>
<p style="color:var(--admin-text-secondary);font-size:0.875rem;">Aucun log disponible.</p>
<?php else: ?>
<table class="admin-table">
<thead>
<tr><th>Date</th><th>Admin</th><th>Action</th><th>Detail</th><th>IP</th><th>Statut</th></tr>
</thead>
<tbody>
<?php foreach ($logs as $log): ?>
<tr>
<td style="white-space:nowrap;"><?= date('d/m/Y H:i', strtotime($log['created_at'])) ?></td>
<td><?= Security::e((string) ($log['username'] ?? '-')) ?></td>
<td><code style="font-size:0.8rem;"><?= Security::e((string) $log['action']) ?></code></td>
<td style="color:var(--admin-text-secondary);font-size:0.8125rem;"><?= Security::e((string) ($log['detail'] ?? '-')) ?></td>
<td style="font-size:0.8rem;"><code><?= Security::e((string) ($log['ip'] ?? '-')) ?></code></td>
<td>
<?php if (!empty($log['success'])): ?>
<span class="admin-badge admin-badge--published">OK</span>
<?php else: ?>
<span class="admin-badge" style="background:rgba(239,68,68,0.1);color:var(--admin-red);">Echec</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</main>
</div>
<script nonce="<?= Security::cspNonce() ?>">
document.querySelectorAll('form[data-confirm-message]').forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!window.confirm(form.dataset.confirmMessage || 'Confirmer cette action ?')) {
event.preventDefault();
}
});
});
</script>
</body>
</html>

267
admin/services.php Normal file
View file

@ -0,0 +1,267 @@
<?php
/**
* BackOffice - gestion des services.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
$db = getDatabase();
$feedback = '';
$feedbackType = '';
$editService = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$action = (string) ($_POST['action'] ?? '');
if ($action === 'create' || $action === 'update') {
$title = trim((string) ($_POST['title'] ?? ''));
$description = trim((string) ($_POST['description'] ?? ''));
$icon = trim((string) ($_POST['icon'] ?? '🚀'));
$displayOrder = max(0, (int) ($_POST['display_order'] ?? 0));
$isActive = isset($_POST['is_active']) ? 1 : 0;
if ($title === '' || $description === '') {
$feedback = 'Le titre et la description sont requis.';
$feedbackType = 'error';
} else {
if ($action === 'create') {
$db->prepare(
'INSERT INTO services (icon, title, description, display_order, is_active)
VALUES (:icon, :title, :description, :display_order, :is_active)'
)->execute([
'icon' => mb_substr($icon, 0, 10),
'title' => $title,
'description' => $description,
'display_order' => $displayOrder,
'is_active' => $isActive,
]);
$feedback = 'Service cree avec succes.';
} else {
$serviceId = (int) ($_POST['service_id'] ?? 0);
$db->prepare(
'UPDATE services
SET icon = :icon, title = :title, description = :description, display_order = :display_order, is_active = :is_active
WHERE id = :id'
)->execute([
'icon' => mb_substr($icon, 0, 10),
'title' => $title,
'description' => $description,
'display_order' => $displayOrder,
'is_active' => $isActive,
'id' => $serviceId,
]);
$feedback = 'Service mis a jour.';
}
$feedbackType = 'success';
header('Location: services.php?ok=' . urlencode($feedback));
exit;
}
} elseif ($action === 'toggle') {
$serviceId = (int) ($_POST['service_id'] ?? 0);
$db->prepare('UPDATE services SET is_active = NOT is_active WHERE id = :id')
->execute(['id' => $serviceId]);
header('Location: services.php?ok=Statut+mis+a+jour');
exit;
} elseif ($action === 'delete') {
$serviceId = (int) ($_POST['service_id'] ?? 0);
$db->prepare('DELETE FROM services WHERE id = :id')->execute(['id' => $serviceId]);
header('Location: services.php?ok=Service+supprime');
exit;
}
}
$stmt = $db->prepare('SELECT * FROM services WHERE id = :id');
$stmt->execute(['id' => (int) ($_GET['edit'] ?? 0)]);
$editService = $stmt->fetch() ?: null;
$services = $db->query('SELECT * FROM services ORDER BY display_order ASC, id ASC')->fetchAll();
if (isset($_GET['ok'])) {
$feedback = (string) $_GET['ok'];
$feedbackType = 'success';
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Services - BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Services</h1>
<?php if ($editService === null): ?>
<button type="button" id="toggleServiceForm" class="admin-btn admin-btn--primary">+ Nouveau service</button>
<?php endif; ?>
</div>
<?php if ($feedback !== ''): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= Security::e($feedback) ?></div>
<?php endif; ?>
<div id="formNew" class="admin-form <?= $editService ? '' : 'is-hidden' ?>" style="margin-bottom:2rem;">
<h2 style="font-size:1rem;font-weight:700;margin-bottom:1.5rem;">
<?= $editService ? 'Modifier le service' : 'Nouveau service' ?>
</h2>
<form method="post">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="<?= $editService ? 'update' : 'create' ?>">
<?php if ($editService): ?>
<input type="hidden" name="service_id" value="<?= (int) $editService['id'] ?>">
<?php endif; ?>
<div class="admin-form__row">
<div class="admin-form__group">
<label class="admin-form__label" for="service_icon">Emoji / Icône</label>
<input type="text" id="service_icon" name="icon" class="admin-form__input" value="<?= Security::e((string) ($editService['icon'] ?? '🚀')) ?>" maxlength="10">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="service_order">Ordre d'affichage</label>
<input type="number" id="service_order" name="display_order" class="admin-form__input" value="<?= (int) ($editService['display_order'] ?? 0) ?>" min="0">
</div>
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="service_title">Titre</label>
<input type="text" id="service_title" name="title" class="admin-form__input" required value="<?= Security::e((string) ($editService['title'] ?? '')) ?>">
</div>
<div class="admin-form__group">
<label class="admin-form__label" for="service_description">Description</label>
<textarea id="service_description" name="description" class="admin-form__textarea" rows="3" required><?= Security::e((string) ($editService['description'] ?? '')) ?></textarea>
</div>
<div class="admin-form__group">
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;">
<input type="checkbox" name="is_active" value="1" <?= (!$editService || !empty($editService['is_active'])) ? 'checked' : '' ?>>
<span class="admin-form__label" style="margin:0;">Actif (visible sur le site)</span>
</label>
</div>
<div class="admin-form__actions">
<button type="submit" class="admin-btn admin-btn--primary"><?= $editService ? 'Enregistrer' : 'Creer le service' ?></button>
<a href="services.php" class="admin-btn admin-btn--outline">Annuler</a>
</div>
</form>
</div>
<?php if (empty($services)): ?>
<div class="admin-empty"><p>Aucun service configure.</p></div>
<?php else: ?>
<div class="admin-table-wrapper">
<table class="admin-table">
<thead>
<tr><th>Ordre</th><th>Icone</th><th>Titre</th><th>Statut</th><th>Actions</th></tr>
</thead>
<tbody>
<?php foreach ($services as $service): ?>
<tr>
<td><?= (int) $service['display_order'] ?></td>
<td style="font-size:1.5rem"><?= Security::e((string) $service['icon']) ?></td>
<td>
<strong><?= Security::e((string) $service['title']) ?></strong><br>
<small style="color:var(--admin-text-secondary)"><?= Security::e(mb_substr((string) $service['description'], 0, 80)) ?>…</small>
</td>
<td>
<?php if (!empty($service['is_active'])): ?>
<span class="admin-badge admin-badge--published">Actif</span>
<?php else: ?>
<span class="admin-badge admin-badge--draft">Inactif</span>
<?php endif; ?>
</td>
<td>
<div style="display:flex;gap:0.5rem;flex-wrap:wrap;">
<a href="?edit=<?= (int) $service['id'] ?>" class="admin-btn admin-btn--outline admin-btn--sm">Modifier</a>
<form method="post" style="display:inline;">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="toggle">
<input type="hidden" name="service_id" value="<?= (int) $service['id'] ?>">
<button type="submit" class="admin-btn admin-btn--outline admin-btn--sm">
<?= !empty($service['is_active']) ? 'Desactiver' : 'Activer' ?>
</button>
</form>
<button
type="button"
class="admin-btn admin-btn--danger admin-btn--sm"
data-delete-service
data-service-id="<?= (int) $service['id'] ?>"
data-service-name="<?= Security::e((string) $service['title']) ?>">
Supprimer
</button>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</main>
</div>
<div class="admin-modal-overlay" id="deleteModal">
<div class="admin-modal">
<h2 class="admin-modal__title">Supprimer ce service ?</h2>
<p class="admin-modal__text">Le service "<span id="deleteName"></span>" sera definitivement supprime.</p>
<div class="admin-modal__actions">
<button type="button" class="admin-btn admin-btn--outline" id="closeServiceDeleteModal">Annuler</button>
<form method="post" id="deleteForm">
<?= Security::csrfInput() ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="service_id" id="deleteId">
<button type="submit" class="admin-btn admin-btn--danger">Supprimer</button>
</form>
</div>
</div>
</div>
<script nonce="<?= Security::cspNonce() ?>">
function deleteService(id, name) {
document.getElementById('deleteId').value = id;
document.getElementById('deleteName').textContent = name;
document.getElementById('deleteModal').classList.add('is-active');
}
document.getElementById('deleteModal').addEventListener('click', function (event) {
if (event.target === this) {
this.classList.remove('is-active');
}
});
document.getElementById('closeServiceDeleteModal').addEventListener('click', function () {
document.getElementById('deleteModal').classList.remove('is-active');
});
var toggleServiceForm = document.getElementById('toggleServiceForm');
if (toggleServiceForm) {
toggleServiceForm.addEventListener('click', function () {
document.getElementById('formNew').classList.toggle('is-hidden');
});
}
document.querySelectorAll('[data-delete-service]').forEach(function (button) {
button.addEventListener('click', function () {
deleteService(button.dataset.serviceId, button.dataset.serviceName);
});
});
</script>
</body>
</html>

129
admin/settings.php Normal file
View file

@ -0,0 +1,129 @@
<?php
/**
* BackOffice — Paramètres globaux
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../includes/Security.php';
Security::bootstrap(true, ['no_store' => true]);
Security::requireAdmin();
require_once __DIR__ . '/../config/database.php';
$db = getDatabase();
$feedback = '';
$feedbackType = '';
// ── Sauvegarde ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Security::verifyCsrf($_POST['csrf_token'] ?? '');
$saved = 0;
foreach ($_POST as $key => $value) {
if (str_starts_with($key, 'setting_')) {
$settingKey = substr($key, 8);
$db->prepare('UPDATE site_settings SET setting_value = :val WHERE setting_key = :key')
->execute(['val' => trim($value), 'key' => $settingKey]);
$saved++;
}
}
$feedback = "{$saved} paramètre(s) enregistré(s).";
$feedbackType = 'success';
}
// ── Chargement ────────────────────────────────────────────
$settings = [];
foreach ($db->query('SELECT * FROM site_settings ORDER BY id ASC')->fetchAll() as $row) {
$settings[$row['setting_key']] = $row;
}
$settingGroups = [
'Identité' => ['site_name', 'owner_name', 'owner_email', 'site_url'],
'Notifications' => ['notify_email'],
'Comportement' => ['availability', 'maintenance_mode'],
'Intégrations' => ['google_analytics_id'],
];
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>Paramètres — BackOffice Tony AVERTY</title>
<link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<div class="admin-page">
<?php require __DIR__ . '/includes/nav.php'; ?>
<main class="admin-content">
<div class="admin-topbar">
<h1 class="admin-page-title">Paramètres globaux</h1>
</div>
<?php if ($feedback): ?>
<div class="admin-alert admin-alert--<?= $feedbackType ?>"><?= htmlspecialchars($feedback, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<form method="post">
<?= Security::csrfInput() ?>
<?php foreach ($settingGroups as $groupLabel => $keys): ?>
<div class="admin-form" style="margin-bottom:1.5rem;">
<h2 class="form-section-title"><?= $groupLabel ?></h2>
<?php foreach ($keys as $key): ?>
<?php if (!isset($settings[$key])) continue; ?>
<?php $s = $settings[$key]; ?>
<div class="admin-form__group">
<label class="admin-form__label" for="setting_<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>">
<?= htmlspecialchars($s['label'], ENT_QUOTES, 'UTF-8') ?>
<span class="admin-form__hint">· <?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?></span>
</label>
<?php if (in_array($key, ['availability', 'maintenance_mode'])): ?>
<select name="setting_<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>"
class="admin-form__select"
id="setting_<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>">
<?php if ($key === 'availability'): ?>
<option value="1" <?= $s['setting_value'] === '1' ? 'selected' : '' ?>>Disponible</option>
<option value="0" <?= $s['setting_value'] === '0' ? 'selected' : '' ?>>Non disponible</option>
<?php else: ?>
<option value="0" <?= $s['setting_value'] === '0' ? 'selected' : '' ?>>Désactivé</option>
<option value="1" <?= $s['setting_value'] === '1' ? 'selected' : '' ?>>Activé</option>
<?php endif; ?>
</select>
<?php else: ?>
<input type="<?= $key === 'owner_email' || $key === 'notify_email' ? 'email' : 'text' ?>"
id="setting_<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>"
name="setting_<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>"
class="admin-form__input"
value="<?= htmlspecialchars($s['setting_value'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<div style="position:sticky;bottom:1.5rem;z-index:10;text-align:right;">
<button type="submit" class="admin-btn admin-btn--primary" style="box-shadow:0 4px 20px rgba(99,102,241,0.4);">
💾 Enregistrer les paramètres
</button>
</div>
</form>
<!-- ── Infos système ─────────────────────────────── -->
<div class="admin-form" style="margin-top:2rem;">
<h2 class="form-section-title">ℹ️ Infos système</h2>
<table class="admin-table" style="margin-top:1rem;">
<tbody>
<tr><td style="color:var(--admin-text-secondary);">PHP</td><td><strong><?= phpversion() ?></strong></td></tr>
<tr><td style="color:var(--admin-text-secondary);">Serveur</td><td><strong><?= htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'PHP built-in', ENT_QUOTES, 'UTF-8') ?></strong></td></tr>
<tr><td style="color:var(--admin-text-secondary);">Date serveur</td><td><strong><?= date('d/m/Y H:i:s') ?></strong></td></tr>
<tr><td style="color:var(--admin-text-secondary);">Timezone</td><td><strong><?= date_default_timezone_get() ?></strong></td></tr>
<tr><td style="color:var(--admin-text-secondary);">Backoffice version</td><td><strong>1.0.0</strong></td></tr>
</tbody>
</table>
</div>
</main>
</div>
</body>
</html>

328
api/contact.php Normal file
View file

@ -0,0 +1,328 @@
<?php
/**
* Traitement du formulaire de contact.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/recaptcha.php';
require_once __DIR__ . '/../includes/Mailer.php';
Security::bootstrap(true, ['api' => true, 'no_store' => true]);
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
Security::jsonResponse([
'success' => false,
'message' => 'Methode non autorisee.',
]);
}
Security::enforceSameOrigin(true);
Security::verifyCsrf($_POST['csrf_token'] ?? '', true);
if (!empty($_POST['website'])) {
Security::jsonResponse([
'success' => true,
'message' => 'Message envoye avec succes.',
]);
}
// Google reCAPTCHA v3 (si configure) : filtre les bots via un score anti-spam.
if (RECAPTCHA_ENABLED) {
$recaptchaOk = Security::verifyRecaptcha(
(string) ($_POST['recaptcha_token'] ?? ''),
RECAPTCHA_SECRET_KEY,
Security::clientIp(),
RECAPTCHA_MIN_SCORE,
'contact'
);
if (!$recaptchaOk) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'Verification anti-robot echouee. Merci de reessayer.',
]);
}
}
$captchaInput = (int) ($_POST['captcha'] ?? -1);
$captchaAnswer = (int) ($_SESSION['captcha_answer'] ?? -99);
unset($_SESSION['captcha_answer']);
if ($captchaInput !== $captchaAnswer) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'La reponse au CAPTCHA est incorrecte. Veuillez reessayer.',
]);
}
$ip = Security::clientIp();
try {
$db = getDatabase();
} catch (Throwable $e) {
error_log('[Contact] DB unavailable: ' . $e->getMessage());
http_response_code(500);
Security::jsonResponse([
'success' => false,
'message' => 'Une erreur est survenue. Veuillez reessayer.',
]);
}
if (Security::isRateLimited($db, 'contact', $ip, 5, 15)) {
http_response_code(429);
Security::jsonResponse([
'success' => false,
'message' => 'Trop de messages envoyes. Reessayez dans 15 minutes.',
]);
}
$name = trim((string) ($_POST['name'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$subject = trim((string) ($_POST['subject'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
$name = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $name) ?? $name;
$subject = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $subject) ?? $subject;
$message = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', '', $message) ?? $message;
if (mb_strlen($name) < 2 || mb_strlen($name) > 255) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'Le nom est requis (2 a 255 caracteres).',
]);
}
$cleanEmail = Security::sanitizeEmail($email);
if ($cleanEmail === false) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'Une adresse email valide est requise.',
]);
}
if ($subject !== '' && mb_strlen($subject) > 255) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'Le sujet depasse 255 caracteres.',
]);
}
if (mb_strlen($message) < 10 || mb_strlen($message) > 5000) {
http_response_code(422);
Security::jsonResponse([
'success' => false,
'message' => 'Le message doit contenir entre 10 et 5000 caracteres.',
]);
}
// Filtre anti-spam : les bots injectent souvent plusieurs liens ou du BBCode.
$haystack = mb_strtolower($name . ' ' . $subject . ' ' . $message, 'UTF-8');
$linkCount = preg_match_all('~https?://|www\.|\[url|\[link|</?a\b~i', $haystack);
if ($linkCount >= 4 || preg_match('~\[url|\[link|\[/url\]|xn--~i', $haystack)) {
// On enregistre la tentative (rate limit) mais on ne notifie pas : reponse neutre.
Security::recordAttempt($db, 'contact', $ip);
Security::jsonResponse([
'success' => true,
'message' => 'Message envoye avec succes.',
]);
}
Security::recordAttempt($db, 'contact', $ip);
try {
$stmt = $db->prepare(
'INSERT INTO contact_messages (sender_name, sender_email, subject, message)
VALUES (:name, :email, :subject, :message)'
);
$stmt->execute([
'name' => $name,
'email' => $cleanEmail,
'subject' => $subject,
'message' => $message,
]);
$contactMessageId = (int) $db->lastInsertId();
$notifyEmail = NOTIFY_EMAIL;
try {
$setting = $db->prepare('SELECT setting_value FROM site_settings WHERE setting_key = :key LIMIT 1');
$setting->execute(['key' => 'notify_email']);
$stored = $setting->fetchColumn();
if (is_string($stored) && $stored !== '') {
$notifyEmail = $stored;
}
} catch (Throwable) {
}
$mailSubject = $subject !== ''
? '[Contact] ' . mb_substr($subject, 0, 100)
: '[Contact] Nouveau message de ' . $name;
$mailer = new Mailer();
$mailer->sendHtml(
$notifyEmail,
$mailSubject,
buildAdminNotificationHtml($name, $cleanEmail, $subject, $message),
buildAdminNotificationText($name, $cleanEmail, $subject, $message),
$cleanEmail
);
$confirmMailer = new Mailer();
$confirmMailer->sendHtml(
$cleanEmail,
'Votre message a bien ete recu - Tony AVERTY',
buildClientConfirmationHtml($name, $subject, $message),
buildClientConfirmationText($name, $subject, $message),
SMTP_FROM_EMAIL
);
$confirmMsgId = $confirmMailer->getLastMessageId();
if ($confirmMsgId !== '' && $contactMessageId > 0) {
try {
$db->prepare(
'INSERT IGNORE INTO sent_message_ids (message_id, contact_message_id)
VALUES (:mid, :cid)'
)->execute([
'mid' => $confirmMsgId,
'cid' => $contactMessageId,
]);
} catch (Throwable) {
}
}
Security::jsonResponse([
'success' => true,
'message' => 'Message envoye avec succes. Je vous repondrai rapidement.',
]);
} catch (PDOException $e) {
error_log('[Contact] Erreur DB : ' . $e->getMessage());
http_response_code(500);
Security::jsonResponse([
'success' => false,
'message' => 'Une erreur est survenue. Veuillez reessayer.',
]);
}
function buildAdminNotificationHtml(string $name, string $email, string $subject, string $message): string
{
$safeName = Security::e($name);
$safeEmail = Security::e($email);
$safeSubject = Security::e($subject !== '' ? $subject : '(non renseigne)');
$safeMessage = nl2br(Security::e($message));
return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="UTF-8"></head>
<body style="margin:0;padding:24px;background:#f4f4f5;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="620" cellpadding="0" cellspacing="0" style="max-width:620px;width:100%;background:#ffffff;border:1px solid #e4e4e7;border-radius:12px;overflow:hidden;">
<tr>
<td style="padding:24px 28px;background:#111827;color:#ffffff;">
<strong>Nouveau message de contact</strong><br>
<span style="font-size:13px;opacity:.8;">tony-averty.dev</span>
</td>
</tr>
<tr>
<td style="padding:24px 28px;color:#111827;font-size:14px;line-height:1.7;">
<p style="margin:0 0 12px;"><strong>Nom :</strong> {$safeName}</p>
<p style="margin:0 0 12px;"><strong>Email :</strong> <a href="mailto:{$safeEmail}" style="color:#2563eb;text-decoration:none;">{$safeEmail}</a></p>
<p style="margin:0 0 12px;"><strong>Sujet :</strong> {$safeSubject}</p>
<div style="margin-top:18px;padding:16px;background:#f9fafb;border-left:3px solid #2563eb;">{$safeMessage}</div>
<p style="margin:24px 0 0;">
<a href="https://tony-averty.dev/admin/messages.php" style="display:inline-block;padding:11px 18px;background:#2563eb;color:#ffffff;text-decoration:none;border-radius:8px;">Ouvrir le BackOffice</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
HTML;
}
function buildAdminNotificationText(string $name, string $email, string $subject, string $message): string
{
$lines = [
"Nouveau message de {$name} ({$email})",
'',
'Sujet : ' . ($subject !== '' ? $subject : '(non renseigne)'),
'',
$message,
'',
'BackOffice : https://tony-averty.dev/admin/messages.php',
];
return implode("\n", $lines);
}
function buildClientConfirmationHtml(string $name, string $subject, string $message): string
{
$safeName = Security::e($name);
$safeSubject = Security::e($subject !== '' ? $subject : 'votre message');
$safeMessage = nl2br(Security::e($message));
return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="UTF-8"></head>
<body style="margin:0;padding:24px;background:#f4f4f5;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="620" cellpadding="0" cellspacing="0" style="max-width:620px;width:100%;background:#ffffff;border:1px solid #e4e4e7;border-radius:12px;overflow:hidden;">
<tr>
<td style="padding:24px 28px;background:#111827;color:#ffffff;">
<strong>Tony AVERTY</strong><br>
<span style="font-size:13px;opacity:.8;">Confirmation de reception</span>
</td>
</tr>
<tr>
<td style="padding:24px 28px;color:#111827;font-size:14px;line-height:1.7;">
<p style="margin:0 0 14px;">Bonjour {$safeName},</p>
<p style="margin:0 0 14px;">Merci pour votre message. Il a bien ete recu et je vous repondrai sous 24 heures.</p>
<div style="margin-top:18px;padding:16px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:10px;">
<p style="margin:0 0 10px;"><strong>Sujet :</strong> {$safeSubject}</p>
<div>{$safeMessage}</div>
</div>
<p style="margin:18px 0 0;color:#6b7280;font-size:13px;">Si vous n'etes pas a l'origine de cette demande, ignorez simplement cet email.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
HTML;
}
function buildClientConfirmationText(string $name, string $subject, string $message): string
{
$lines = [
"Bonjour {$name},",
'',
"Merci pour votre message. Il a bien ete recu et je vous repondrai sous 24 heures.",
'',
'Sujet : ' . ($subject !== '' ? $subject : '(non renseigne)'),
$message,
'',
'Tony AVERTY - tony-averty.dev',
];
return implode("\n", $lines);
}

144
api/track.php Normal file
View file

@ -0,0 +1,144 @@
<?php
/**
* Tracking des visites sans cookies.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/bootstrap.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(false, ['api' => true, 'no_store' => true]);
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
Security::jsonResponse(['ok' => false]);
}
Security::enforceSameOrigin(true);
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody ?: '', true);
if (!is_array($data)) {
http_response_code(400);
Security::jsonResponse(['ok' => false]);
}
$action = (string) ($data['action'] ?? '');
$sessionId = (string) ($data['session_id'] ?? '');
$page = (string) ($data['page'] ?? '/');
$referrer = $data['referrer'] ?? null;
$duration = isset($data['duration']) ? (int) $data['duration'] : null;
$device = (string) ($data['device'] ?? 'desktop');
$projectId = isset($data['project_id']) ? (int) $data['project_id'] : 0;
if (!preg_match('/^[a-z0-9]{8,64}$/i', $sessionId)) {
http_response_code(400);
Security::jsonResponse(['ok' => false]);
}
$page = mb_substr((string) preg_replace('/[^\x20-\x7E]/', '', $page), 0, 500);
$referrer = is_string($referrer)
? mb_substr((string) preg_replace('/[^\x20-\x7E]/', '', $referrer), 0, 500)
: null;
$device = in_array($device, ['desktop', 'mobile', 'tablet'], true) ? $device : 'desktop';
$ip = Security::clientIp();
$salt = config_required('analytics_salt');
$ipHash = hash('sha256', $ip . $salt);
$ua = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
$botPatterns = ['bot', 'crawler', 'spider', 'curl', 'wget', 'python', 'java', 'go-http'];
foreach ($botPatterns as $pattern) {
if (str_contains($ua, $pattern)) {
Security::jsonResponse(['ok' => true, 'skipped' => 'bot']);
}
}
try {
$db = getDatabase();
if (Security::isRateLimited($db, 'track', $ip, 240, 10)) {
Security::jsonResponse(['ok' => true, 'skipped' => 'rate_limited']);
}
Security::recordAttempt($db, 'track', $ip);
switch ($action) {
case 'visit':
$check = $db->prepare(
'SELECT id FROM visits
WHERE session_id = :sid AND page = :page
AND created_at > NOW() - INTERVAL 5 MINUTE
LIMIT 1'
);
$check->execute([
'sid' => $sessionId,
'page' => $page,
]);
if ($check->fetchColumn()) {
Security::jsonResponse(['ok' => true, 'skipped' => 'duplicate']);
}
$db->prepare(
'INSERT INTO visits (ip_hash, session_id, page, referrer, device_type)
VALUES (:ip, :sid, :page, :ref, :device)'
)->execute([
'ip' => $ipHash,
'sid' => $sessionId,
'page' => $page,
'ref' => $referrer,
'device' => $device,
]);
break;
case 'duration':
if ($duration !== null && $duration > 0 && $duration < 86400) {
$db->prepare(
'UPDATE visits
SET duration_s = :duration
WHERE session_id = :sid
ORDER BY created_at DESC
LIMIT 1'
)->execute([
'duration' => $duration,
'sid' => $sessionId,
]);
}
break;
case 'project_click':
if ($projectId > 0) {
$db->prepare(
'INSERT INTO project_clicks (project_id, ip_hash)
VALUES (:project_id, :ip_hash)'
)->execute([
'project_id' => $projectId,
'ip_hash' => $ipHash,
]);
}
break;
default:
http_response_code(400);
Security::jsonResponse(['ok' => false, 'error' => 'unknown_action']);
}
if (random_int(1, 100) === 1) {
try {
$db->exec("DELETE FROM visits WHERE created_at < NOW() - INTERVAL 13 MONTH");
$db->exec("DELETE FROM project_clicks WHERE created_at < NOW() - INTERVAL 13 MONTH");
} catch (Throwable) {
}
}
Security::jsonResponse(['ok' => true]);
} catch (Throwable $e) {
error_log('[Track] ' . $e->getMessage());
http_response_code(500);
Security::jsonResponse(['ok' => false]);
}

2410
assets/css/style.css Normal file

File diff suppressed because it is too large Load diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

19
assets/img/favicon.svg Normal file
View file

@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<style>
.bg { fill: #12121a; }
.mark { fill: #6366f1; }
@media (prefers-color-scheme: light) {
.bg { fill: #ededec; }
.mark { fill: #4f46e5; }
}
</style>
<!-- Fond arrondi -->
<rect class="bg" width="32" height="32" rx="6"/>
<!-- Lettre T (crossbar x 4→20, stem x 9→15, hauteur y 7→25) -->
<path class="mark" d="M4,7 H20 V11 H15 V25 H9 V11 H4 Z"/>
<!-- Point accent — clin d'œil au logo "Tony." -->
<circle class="mark" cx="24" cy="24" r="3"/>
</svg>

After

Width:  |  Height:  |  Size: 573 B

View file

BIN
assets/img/tony.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

129
assets/js/error-page.js Normal file
View file

@ -0,0 +1,129 @@
/**
* error-page.js — Thème + curseur personnalisé pour les pages d'erreur
* Autonome : ne dépend pas de main.js
*/
(function () {
'use strict';
var html = document.documentElement;
/* ============================================
THEME SWITCH
============================================ */
function getStoredTheme() {
return localStorage.getItem('theme') || 'light';
}
function setTheme(theme) {
html.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
}
var themeBtn = document.getElementById('themeSwitch');
if (themeBtn) {
themeBtn.addEventListener('click', function () {
var current = html.getAttribute('data-theme');
setTheme(current === 'dark' ? 'light' : 'dark');
});
}
/* Suppression de la classe no-transition après le premier rendu
(déjà ajoutée dans le <head> inline) */
requestAnimationFrame(function () {
requestAnimationFrame(function () {
html.classList.remove('no-transition');
});
});
/* ============================================
CUSTOM CURSOR — Dot + Ring
Actif uniquement sur devices à pointeur précis
============================================ */
var cursorDot = document.getElementById('cursorDot');
var cursorRing = document.getElementById('cursorRing');
var isPointer = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
if (cursorDot && cursorRing && isPointer) {
var mouseX = 0, mouseY = 0;
var ringX = 0, ringY = 0;
var cursorVisible = false;
/* Suivi instantané du point */
document.addEventListener('mousemove', function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
cursorDot.style.left = mouseX + 'px';
cursorDot.style.top = mouseY + 'px';
if (!cursorVisible) {
cursorVisible = true;
ringX = mouseX;
ringY = mouseY;
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
}
}, { passive: true });
/* Détection position initiale après Ctrl+R sans mouvement */
document.addEventListener('mouseover', function onFirstOver(e) {
if (!cursorVisible) {
mouseX = e.clientX;
mouseY = e.clientY;
cursorDot.style.left = mouseX + 'px';
cursorDot.style.top = mouseY + 'px';
ringX = mouseX;
ringY = mouseY;
cursorVisible = true;
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
}
document.removeEventListener('mouseover', onFirstOver);
}, { passive: true });
document.addEventListener('mouseleave', function () {
cursorDot.classList.remove('is-visible');
cursorRing.classList.remove('is-visible');
});
document.addEventListener('mouseenter', function () {
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
});
/* RAF : anneau avec lerp */
function animateCursor() {
requestAnimationFrame(animateCursor);
ringX += (mouseX - ringX) * 0.11;
ringY += (mouseY - ringY) * 0.11;
cursorRing.style.left = ringX + 'px';
cursorRing.style.top = ringY + 'px';
}
requestAnimationFrame(animateCursor);
/* Hover sur éléments interactifs */
var INTERACTIVE = 'a, button, input, textarea, select, label, [role="button"]';
document.querySelectorAll(INTERACTIVE).forEach(function (el) {
el.addEventListener('mouseenter', function () {
cursorDot.classList.add('is-hovering');
cursorRing.classList.add('is-hovering');
}, { passive: true });
el.addEventListener('mouseleave', function () {
cursorDot.classList.remove('is-hovering');
cursorRing.classList.remove('is-hovering');
}, { passive: true });
});
/* Clic */
document.addEventListener('mousedown', function () {
cursorDot.classList.add('is-clicking');
cursorRing.classList.add('is-clicking');
});
document.addEventListener('mouseup', function () {
cursorDot.classList.remove('is-clicking');
cursorRing.classList.remove('is-clicking');
});
}
})();

674
assets/js/main.js Normal file
View file

@ -0,0 +1,674 @@
/**
* Portfolio Tony AVERTY — JavaScript principal
* Interactions, animations et logique front-end
*/
// Paramètres globaux partagés entre modules
var settingsFPS = parseInt(localStorage.getItem('devFPS') || '60', 10);
var settingsSmoothScroll = localStorage.getItem('devSmoothScroll') !== 'off';
var lerpTarget = 0;
var lerpCurrent = 0;
(function () {
'use strict';
/* ============================================
THEME SWITCH
============================================ */
const themeSwitch = document.getElementById('themeSwitch');
const html = document.documentElement;
function getPreferredTheme() {
const stored = localStorage.getItem('theme');
if (stored) return stored;
return 'light'; // défaut clair
}
// Exposée globalement pour le dev panel
window.setTheme = function setTheme(theme) {
html.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
// Sync segment du devpanel si ouvert
document.querySelectorAll('[data-theme-val]').forEach(function (btn) {
btn.classList.toggle('is-active', btn.dataset.themeVal === theme);
});
};
// Init theme sans transition (évite le flash au chargement)
html.classList.add('no-transition');
window.setTheme(getPreferredTheme());
requestAnimationFrame(function () {
requestAnimationFrame(function () {
html.classList.remove('no-transition');
});
});
themeSwitch.addEventListener('click', function () {
const current = html.getAttribute('data-theme');
window.setTheme(current === 'dark' ? 'light' : 'dark');
});
/* ============================================
MOBILE NAVIGATION
============================================ */
const burger = document.getElementById('navBurger');
const navMenu = document.getElementById('navMenu');
burger.addEventListener('click', function () {
const isOpen = burger.getAttribute('aria-expanded') === 'true';
burger.setAttribute('aria-expanded', !isOpen);
navMenu.classList.toggle('is-open');
document.body.style.overflow = isOpen ? '' : 'hidden';
});
// Close menu on link click
navMenu.querySelectorAll('.navbar__link').forEach(function (link) {
link.addEventListener('click', function () {
burger.setAttribute('aria-expanded', 'false');
navMenu.classList.remove('is-open');
document.body.style.overflow = '';
});
});
/* ============================================
SCROLL PROGRESS BAR
============================================ */
const scrollProgress = document.getElementById('scrollProgress');
function updateScrollProgress() {
const scrollTop = window.scrollY;
const docHeight = document.documentElement.scrollHeight - window.innerHeight;
const progress = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
scrollProgress.style.width = progress + '%';
}
window.addEventListener('scroll', updateScrollProgress, { passive: true });
/* ============================================
NAVBAR BACKGROUND ON SCROLL
============================================ */
const navbar = document.getElementById('navbar');
let lastScroll = 0;
function updateNavbar() {
const scrollTop = window.scrollY;
if (scrollTop > 100) {
navbar.style.borderBottomColor = '';
}
lastScroll = scrollTop;
}
window.addEventListener('scroll', updateNavbar, { passive: true });
/* ============================================
REVEAL ON SCROLL (Intersection Observer)
============================================ */
const revealElements = document.querySelectorAll('.reveal');
if ('IntersectionObserver' in window) {
const revealObserver = new IntersectionObserver(
function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
entry.target.classList.add('is-visible');
revealObserver.unobserve(entry.target);
}
});
},
{
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
}
);
revealElements.forEach(function (el) {
revealObserver.observe(el);
});
} else {
// Fallback: show all
revealElements.forEach(function (el) {
el.classList.add('is-visible');
});
}
/* ============================================
HIDE NAV PROJECT LINK IF NO PROJECTS SECTION
============================================ */
const projectsSection = document.getElementById('projects');
const navProjectsLink = document.getElementById('navProjects');
if (!projectsSection && navProjectsLink) {
navProjectsLink.parentElement.classList.add('nav-projects-hidden');
}
/* ============================================
ACTIVE NAV LINK ON SCROLL
============================================ */
const sections = document.querySelectorAll('.section[id]');
const navLinks = document.querySelectorAll('.navbar__link[href^="#"]');
function updateActiveNavLink() {
const scrollPos = window.scrollY + 150;
sections.forEach(function (section) {
const top = section.offsetTop;
const height = section.offsetHeight;
const id = section.getAttribute('id');
if (scrollPos >= top && scrollPos < top + height) {
navLinks.forEach(function (link) {
link.classList.remove('is-active');
if (link.getAttribute('href') === '#' + id) {
link.classList.add('is-active');
}
});
}
});
}
window.addEventListener('scroll', updateActiveNavLink, { passive: true });
/* ============================================
CONTACT FORM
============================================ */
const contactForm = document.getElementById('contactForm');
const formSubmit = document.getElementById('formSubmit');
if (contactForm) {
const recaptchaSite = contactForm.dataset.recaptchaSite || '';
function submitContact(token) {
const formData = new FormData(contactForm);
if (token) {
formData.set('recaptcha_token', token);
}
fetch(contactForm.action, {
method: 'POST',
body: formData
})
.then(function (response) {
return response.json();
})
.then(function (data) {
if (data.success) {
showToast(data.message, 'success');
contactForm.reset();
} else {
showToast(data.message || 'Une erreur est survenue.', 'error');
}
})
.catch(function () {
showToast('Impossible d\'envoyer le message. Veuillez réessayer.', 'error');
})
.finally(function () {
formSubmit.classList.remove('is-loading');
formSubmit.disabled = false;
});
}
contactForm.addEventListener('submit', function (e) {
e.preventDefault();
// Basic client-side validation
if (!contactForm.checkValidity()) {
contactForm.reportValidity();
return;
}
// Show loading state
formSubmit.classList.add('is-loading');
formSubmit.disabled = true;
// reCAPTCHA v3 : on récupère un token frais avant l'envoi
if (recaptchaSite && window.grecaptcha && typeof grecaptcha.ready === 'function') {
grecaptcha.ready(function () {
grecaptcha.execute(recaptchaSite, { action: 'contact' })
.then(submitContact)
.catch(function () {
submitContact('');
});
});
} else {
submitContact('');
}
});
}
/* ============================================
TOAST NOTIFICATION
============================================ */
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toastMessage');
const toastClose = document.getElementById('toastClose');
let toastTimeout;
function showToast(message, type) {
clearTimeout(toastTimeout);
toastMessage.textContent = message;
toast.className = 'toast is-visible';
if (type) {
toast.classList.add('toast--' + type);
}
toastTimeout = setTimeout(function () {
hideToast();
}, 5000);
}
function hideToast() {
toast.classList.remove('is-visible');
}
toastClose.addEventListener('click', hideToast);
/* ============================================
SMOOTH SCROLL — Lerp (desktop) + anchor links
============================================ */
var isLerpScroll = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
lerpTarget = window.scrollY;
lerpCurrent = window.scrollY;
var lerpRaf = null;
var LERP_FACTOR = 0.095; // 0 = jamais atteint, 1 = instantané
function maxScroll() {
return document.documentElement.scrollHeight - window.innerHeight;
}
function lerpTick() {
var diff = lerpTarget - lerpCurrent;
if (Math.abs(diff) < 0.4) {
lerpCurrent = lerpTarget;
document.scrollingElement.scrollTop = lerpCurrent;
lerpRaf = null;
return;
}
lerpCurrent += diff * LERP_FACTOR;
document.scrollingElement.scrollTop = lerpCurrent;
lerpRaf = requestAnimationFrame(lerpTick);
}
if (isLerpScroll) {
window.addEventListener('wheel', function (e) {
if (!settingsSmoothScroll) return; // scroll natif si désactivé
e.preventDefault();
// Resynchroniser si la page a été scrollée par autre chose (ancres, clavier)
if (Math.abs(lerpCurrent - window.scrollY) > 8) {
lerpCurrent = window.scrollY;
lerpTarget = window.scrollY;
}
lerpTarget = Math.max(0, Math.min(maxScroll(), lerpTarget + e.deltaY));
if (!lerpRaf) lerpTick();
}, { passive: false });
}
// Ancres : scroll animé avec easing cubic
function easeInOutCubic(t) {
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
}
function smoothScrollTo(targetPos, duration) {
var start = window.scrollY;
var distance = targetPos - start;
var startTime = null;
// Synchroniser lerp avec la destination
lerpCurrent = start;
lerpTarget = targetPos;
function step(timestamp) {
if (!startTime) startTime = timestamp;
var elapsed = timestamp - startTime;
var progress = Math.min(elapsed / duration, 1);
var ease = easeInOutCubic(progress);
document.scrollingElement.scrollTop = start + distance * ease;
lerpCurrent = document.scrollingElement.scrollTop;
if (progress < 1) requestAnimationFrame(step);
else {
lerpCurrent = targetPos;
lerpTarget = targetPos;
}
}
requestAnimationFrame(step);
}
document.querySelectorAll('a[href^="#"]').forEach(function (anchor) {
anchor.addEventListener('click', function (e) {
var targetId = this.getAttribute('href');
if (targetId === '#') return;
var target = document.querySelector(targetId);
if (target) {
e.preventDefault();
var navHeight = navbar.offsetHeight;
var targetPos = Math.max(0, target.getBoundingClientRect().top + window.scrollY - navHeight);
var distance = Math.abs(targetPos - window.scrollY);
var duration = Math.min(1200, Math.max(400, distance * 0.6));
smoothScrollTo(targetPos, duration);
}
});
});
/* ============================================
CUSTOM CURSOR — Dot + Ring + Stretch scroll
Actif uniquement sur devices à pointeur précis
============================================ */
var cursorDot = document.getElementById('cursorDot');
var cursorRing = document.getElementById('cursorRing');
var isPointerDevice = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
if (cursorDot && cursorRing && isPointerDevice) {
var mouseX = 0, mouseY = 0;
var ringX = 0, ringY = 0;
var cursorVisible = false;
// Vélocité de scroll accumulée — s'accumule sur wheel, décroît dans le RAF
var scrollVel = 0; // + = bas, - = haut (clamped ±220)
var stretchCurrent = 0; // hauteur additionnelle courante (lerp)
/* -- Suivi instantané du point -- */
document.addEventListener('mousemove', function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
cursorDot.style.left = mouseX + 'px';
cursorDot.style.top = mouseY + 'px';
if (!cursorVisible) {
cursorVisible = true;
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
ringX = mouseX;
ringY = mouseY;
}
}, { passive: true });
// Détection position initiale si la souris est déjà sur la page (après Ctrl+R sans mouvement)
document.addEventListener('mouseover', function onFirstOver(e) {
if (!cursorVisible) {
mouseX = e.clientX;
mouseY = e.clientY;
cursorDot.style.left = mouseX + 'px';
cursorDot.style.top = mouseY + 'px';
ringX = mouseX;
ringY = mouseY;
cursorVisible = true;
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
}
document.removeEventListener('mouseover', onFirstOver);
}, { passive: true });
document.addEventListener('mouseleave', function () {
cursorVisible = false;
cursorDot.classList.remove('is-visible');
cursorRing.classList.remove('is-visible');
});
document.addEventListener('mouseenter', function () {
cursorVisible = true;
cursorDot.classList.add('is-visible');
cursorRing.classList.add('is-visible');
});
/* -- Capture de la vélocité de scroll -- */
window.addEventListener('wheel', function (e) {
var delta = e.deltaY;
if (e.deltaMode === 1) delta *= 16; // lignes → pixels
if (e.deltaMode === 2) delta *= window.innerHeight;
// Vraie accumulation — scroll rapide = beaucoup d'événements = grande vélocité
scrollVel += delta * 0.38;
// Clamp pour éviter des stretches extrêmes
scrollVel = Math.max(-220, Math.min(220, scrollVel));
}, { passive: true });
/* -- RAF : position anneau + stretch vélocité -- */
var cursorLastFrame = 0;
function animateCursor(timestamp) {
requestAnimationFrame(animateCursor);
// Throttle FPS si < 60 demandé
if (settingsFPS < 60) {
var interval = 1000 / settingsFPS;
if (timestamp - cursorLastFrame < interval) return;
}
cursorLastFrame = timestamp;
// 1. Suivi position (lerp)
ringX += (mouseX - ringX) * 0.11;
ringY += (mouseY - ringY) * 0.11;
// 2. Friction par frame — decay adapté à 60fps
scrollVel *= 0.80;
// 3. Cible de stretch : linéaire sur la magnitude, max 34px
// scroll lent (~vel 10) → ~1.5px | scroll rapide (~vel 200) → 34px
var mag = Math.abs(scrollVel);
var targetStretch = Math.min(mag * 0.17, 34);
stretchCurrent += (targetStretch - stretchCurrent) * 0.13;
// 4. Application du stretch si significatif
var s = stretchCurrent;
if (!cursorDot.classList.contains('is-hovering') &&
!cursorDot.classList.contains('is-clicking') && s > 0.3) {
var dir = scrollVel >= 0 ? 1 : -1;
var offsetY = dir * s * 0.44;
var ringH = 38 + s;
var ringW = Math.max(26, 38 - s * 0.32);
var dotH = 7 + s * 0.24;
var dotOff = dir * s * 0.13;
var ringOpacity = Math.min(0.42 + s * 0.009, 0.70);
cursorRing.style.width = ringW + 'px';
cursorRing.style.height = ringH + 'px';
cursorRing.style.transform = 'translate(-50%, calc(-50% + ' + offsetY + 'px))';
cursorRing.style.opacity = ringOpacity;
cursorDot.style.width = '5px';
cursorDot.style.height = dotH + 'px';
cursorDot.style.borderRadius = '3px';
cursorDot.style.transform = 'translate(-50%, calc(-50% + ' + dotOff + 'px))';
} else if (s <= 0.4) {
// Retour aux valeurs CSS par défaut
cursorRing.style.width = '';
cursorRing.style.height = '';
cursorRing.style.transform = '';
cursorRing.style.opacity = '';
cursorDot.style.width = '';
cursorDot.style.height = '';
cursorDot.style.borderRadius = '';
cursorDot.style.transform = '';
}
cursorRing.style.left = ringX + 'px';
cursorRing.style.top = ringY + 'px';
}
requestAnimationFrame(animateCursor);
/* -- Hover sur éléments interactifs -- */
var INTERACTIVE = 'a, button, input, textarea, select, label, [role="button"]';
document.querySelectorAll(INTERACTIVE).forEach(function (el) {
el.addEventListener('mouseenter', function () {
cursorDot.classList.add('is-hovering');
cursorRing.classList.add('is-hovering');
}, { passive: true });
el.addEventListener('mouseleave', function () {
cursorDot.classList.remove('is-hovering');
cursorRing.classList.remove('is-hovering');
}, { passive: true });
});
/* -- Clic -- */
document.addEventListener('mousedown', function () {
cursorDot.classList.add('is-clicking');
cursorRing.classList.add('is-clicking');
});
document.addEventListener('mouseup', function () {
cursorDot.classList.remove('is-clicking');
cursorRing.classList.remove('is-clicking');
});
}
/* ============================================
DEV PANEL — Réglages
============================================ */
var devTrigger = document.getElementById('devPanelTrigger');
var devPanel = document.getElementById('devPanel');
var devFpsVal = document.getElementById('devFpsVal');
var devFpsDot = document.getElementById('devFpsDot');
var devFpsBar = document.getElementById('devFpsBar');
var devThemeSeg = document.getElementById('devThemeSeg');
var devFpsSeg = document.getElementById('devFpsSeg');
var devToggleCursor = document.getElementById('devToggleCursor');
var devToggleAnimations = document.getElementById('devToggleAnimations');
if (devTrigger && devPanel) {
// ── Ouvrir / fermer ───────────────────────────────
function toggleDevPanel() {
var isOpen = devPanel.classList.contains('is-open');
devPanel.classList.toggle('is-open');
devTrigger.classList.toggle('is-open');
devTrigger.setAttribute('aria-expanded', !isOpen);
devPanel.setAttribute('aria-hidden', isOpen);
}
devTrigger.addEventListener('click', toggleDevPanel);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && devPanel.classList.contains('is-open')) {
toggleDevPanel();
}
});
document.addEventListener('click', function (e) {
if (devPanel.classList.contains('is-open') &&
!devPanel.contains(e.target) &&
!devTrigger.contains(e.target)) {
toggleDevPanel();
}
});
// ── Thème ─────────────────────────────────────────
// Sync initial
document.querySelectorAll('[data-theme-val]').forEach(function (btn) {
btn.classList.toggle('is-active', btn.dataset.themeVal === document.documentElement.getAttribute('data-theme'));
});
devThemeSeg.addEventListener('click', function (e) {
var btn = e.target.closest('[data-theme-val]');
if (!btn) return;
window.setTheme(btn.dataset.themeVal);
});
// ── Curseur ───────────────────────────────────────
var savedCursor = localStorage.getItem('devCursor') !== 'off';
devToggleCursor.checked = savedCursor;
if (!savedCursor) html.classList.add('cursor-disabled');
devToggleCursor.addEventListener('change', function () {
var enabled = this.checked;
localStorage.setItem('devCursor', enabled ? 'on' : 'off');
html.classList.toggle('cursor-disabled', !enabled);
if (!enabled) {
document.getElementById('cursorDot').classList.remove('is-visible');
document.getElementById('cursorRing').classList.remove('is-visible');
}
});
// ── Scroll lisse ──────────────────────────────────
var devToggleSmoothScroll = document.getElementById('devToggleSmoothScroll');
devToggleSmoothScroll.checked = settingsSmoothScroll;
devToggleSmoothScroll.addEventListener('change', function () {
settingsSmoothScroll = this.checked;
localStorage.setItem('devSmoothScroll', settingsSmoothScroll ? 'on' : 'off');
// Resync la position lerp pour éviter un saut au réactivation
lerpCurrent = window.scrollY;
lerpTarget = window.scrollY;
});
// ── Animations ────────────────────────────────────
var savedAnim = localStorage.getItem('devAnimations') !== 'off';
devToggleAnimations.checked = savedAnim;
if (!savedAnim) html.classList.add('no-animations');
devToggleAnimations.addEventListener('change', function () {
var enabled = this.checked;
localStorage.setItem('devAnimations', enabled ? 'on' : 'off');
html.classList.toggle('no-animations', !enabled);
});
// ── FPS cible ─────────────────────────────────────
var savedFPS = parseInt(localStorage.getItem('devFPS') || '60', 10);
settingsFPS = savedFPS;
function syncFpsSeg(fps) {
devFpsSeg.querySelectorAll('.devpanel__seg-btn').forEach(function (btn) {
btn.classList.toggle('is-active', parseInt(btn.dataset.fpsVal, 10) === fps);
});
}
syncFpsSeg(savedFPS);
devFpsSeg.addEventListener('click', function (e) {
var btn = e.target.closest('[data-fps-val]');
if (!btn) return;
settingsFPS = parseInt(btn.dataset.fpsVal, 10);
localStorage.setItem('devFPS', settingsFPS);
syncFpsSeg(settingsFPS);
});
// ── Compteur FPS live ─────────────────────────────
var fpsFrames = [];
var fpsPrev = performance.now();
function updateFpsDisplay() {
var now = performance.now();
var delta = now - fpsPrev;
fpsPrev = now;
fpsFrames.push(1000 / delta);
if (fpsFrames.length > 30) fpsFrames.shift();
var avg = Math.round(fpsFrames.reduce(function (a, b) { return a + b; }, 0) / fpsFrames.length);
devFpsVal.textContent = avg + ' fps';
// Couleur indicateur
devFpsDot.className = 'devpanel__fps-dot';
if (avg < 25) devFpsDot.classList.add('is-low');
else if (avg < 50) devFpsDot.classList.add('is-medium');
// Barre (max référence = 60)
var pct = Math.min(avg / 60 * 100, 100);
devFpsBar.style.width = pct + '%';
devFpsBar.style.background = avg < 25 ? '#ff5f56' : avg < 50 ? '#ffbd2e' : '#27c93f';
requestAnimationFrame(updateFpsDisplay);
}
requestAnimationFrame(updateFpsDisplay);
}
})();

114
config/bootstrap.php Normal file
View file

@ -0,0 +1,114 @@
<?php
/**
* Bootstrap de configuration.
* Charge les secrets depuis les variables d'environnement ou un fichier local non versionne.
*/
if (!function_exists('loadLocalConfig')) {
/**
* Charge la configuration locale optionnelle.
*
* @return array<string, mixed>
*/
function loadLocalConfig(): array
{
static $config = null;
if ($config !== null) {
return $config;
}
$config = [];
$paths = [
__DIR__ . '/local.php',
dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config.local.php',
];
foreach ($paths as $path) {
if (!is_file($path)) {
continue;
}
$loaded = require $path;
if (is_array($loaded)) {
$config = array_replace($config, $loaded);
}
}
return $config;
}
}
if (!function_exists('config_value')) {
/**
* Retourne une valeur de configuration issue de l'environnement ou du fichier local.
*/
function config_value(string $key, mixed $default = null): mixed
{
$envKey = strtoupper(str_replace('.', '_', $key));
$sources = [
getenv($envKey),
$_ENV[$envKey] ?? null,
$_SERVER[$envKey] ?? null,
];
foreach ($sources as $value) {
if ($value !== false && $value !== null && $value !== '') {
return $value;
}
}
$localConfig = loadLocalConfig();
return $localConfig[$key] ?? $default;
}
}
if (!function_exists('config_required')) {
/**
* Retourne une valeur de configuration obligatoire.
*/
function config_required(string $key): string
{
$value = config_value($key);
if (!is_scalar($value) || trim((string) $value) === '') {
throw new RuntimeException("Configuration manquante: {$key}");
}
return trim((string) $value);
}
}
if (!function_exists('config_bool')) {
/**
* Retourne une valeur booleenne interpretee proprement.
*/
function config_bool(string $key, bool $default = false): bool
{
$value = config_value($key, $default);
if (is_bool($value)) {
return $value;
}
$filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return $filtered ?? $default;
}
}
if (!function_exists('config_int')) {
/**
* Retourne une valeur entiere.
*/
function config_int(string $key, int $default = 0): int
{
$value = config_value($key, $default);
if (is_int($value)) {
return $value;
}
return is_numeric($value) ? (int) $value : $default;
}
}

44
config/database.php Normal file
View file

@ -0,0 +1,44 @@
<?php
/**
* Configuration de la base de donnees.
*/
require_once __DIR__ . '/bootstrap.php';
if (!defined('DB_HOST')) {
define('DB_HOST', config_required('db_host'));
define('DB_PORT', config_int('db_port', 3306));
define('DB_NAME', config_required('db_name'));
define('DB_USER', config_required('db_user'));
define('DB_PASS', config_required('db_pass'));
define('DB_CHARSET', (string) config_value('db_charset', 'utf8mb4'));
}
/**
* Connexion PDO securisee.
*/
function getDatabase(): PDO
{
static $pdo = null;
if ($pdo === null) {
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
DB_HOST,
DB_PORT,
DB_NAME,
DB_CHARSET
);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_STRINGIFY_FETCHES => false,
];
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
}
return $pdo;
}

15
config/imap.php Normal file
View file

@ -0,0 +1,15 @@
<?php
/**
* Configuration IMAP.
*/
require_once __DIR__ . '/bootstrap.php';
if (!defined('IMAP_HOST')) {
define('IMAP_HOST', config_required('imap_host'));
define('IMAP_PORT', config_int('imap_port', 993));
define('IMAP_USER', config_required('imap_user'));
define('IMAP_PASS', config_required('imap_pass'));
define('IMAP_FOLDER', (string) config_value('imap_folder', 'INBOX'));
define('IMAP_VALIDATE_CERT', config_bool('imap_validate_cert', true));
}

36
config/local.example.php Normal file
View file

@ -0,0 +1,36 @@
<?php
return [
'db_host' => 'localhost',
'db_port' => 3306,
'db_name' => 'portfolio',
'db_user' => 'portfoliouser',
'db_pass' => '9CkQETF6o6TKfhPWGsP0',
'db_charset' => 'utf8mb4',
'smtp_host' => 'smtp.ionos.fr',
'smtp_port' => 587,
'smtp_user' => 'contact@tony-averty.dev',
'smtp_pass' => 'Ltony4425!',
'smtp_from_email' => 'contact@tony-averty.dev',
'smtp_from_name' => 'Tony AVERTY · Portfolio',
'notify_email' => 'contact@tony-averty.dev',
'imap_host' => 'imap.ionos.com',
'imap_port' => 993,
'imap_user' => 'contact@tony-averty.dev',
'imap_pass' => 'Ltony4425!',
'imap_folder' => 'INBOX',
'imap_validate_cert' => true,
'analytics_salt' => 'change-me-with-a-long-random-string',
'setup_enabled' => false,
'setup_token' => 'replace-with-a-long-random-token',
// Google reCAPTCHA v3 (anti-bot invisible).
// Cles a generer sur https://www.google.com/recaptcha/admin/create (type "v3").
// Laissez vide pour desactiver (le captcha mathematique reste actif).
'recaptcha_site_key' => '',
'recaptcha_secret_key' => '',
'recaptcha_min_score' => 0.5,
];

27
config/recaptcha.php Normal file
View file

@ -0,0 +1,27 @@
<?php
/**
* Configuration Google reCAPTCHA v3.
*
* Renseignez vos cles dans config/local.php (ou via variables d'environnement) :
* 'recaptcha_site_key' => 'votre_cle_site',
* 'recaptcha_secret_key' => 'votre_cle_secrete',
* 'recaptcha_min_score' => 0.5, // seuil anti-bot (0.0 = bot, 1.0 = humain)
*
* Tant que les cles ne sont pas renseignees, reCAPTCHA reste desactive
* et le site continue de fonctionner normalement (captcha maths conserve).
*/
require_once __DIR__ . '/bootstrap.php';
if (!defined('RECAPTCHA_SITE_KEY')) {
define('RECAPTCHA_SITE_KEY', trim((string) config_value('recaptcha_site_key', '')));
define('RECAPTCHA_SECRET_KEY', trim((string) config_value('recaptcha_secret_key', '')));
$score = (float) config_value('recaptcha_min_score', 0.5);
if ($score < 0.0 || $score > 1.0) {
$score = 0.5;
}
define('RECAPTCHA_MIN_SCORE', $score);
define('RECAPTCHA_ENABLED', RECAPTCHA_SITE_KEY !== '' && RECAPTCHA_SECRET_KEY !== '');
}

16
config/smtp.php Normal file
View file

@ -0,0 +1,16 @@
<?php
/**
* Configuration SMTP.
*/
require_once __DIR__ . '/bootstrap.php';
if (!defined('SMTP_HOST')) {
define('SMTP_HOST', config_required('smtp_host'));
define('SMTP_PORT', config_int('smtp_port', 587));
define('SMTP_USER', config_required('smtp_user'));
define('SMTP_PASS', config_required('smtp_pass'));
define('SMTP_FROM_EMAIL', config_required('smtp_from_email'));
define('SMTP_FROM_NAME', config_required('smtp_from_name'));
define('NOTIFY_EMAIL', (string) config_value('notify_email', SMTP_FROM_EMAIL));
}

1
cron/.htaccess Normal file
View file

@ -0,0 +1 @@
Require all denied

341
cron/check_replies.php Normal file
View file

@ -0,0 +1,341 @@
<?php
// Cron — Lecture des réponses email entrants (IMAP)
// Portfolio Tony AVERTY
//
// Ajouter au crontab du VPS :
// crontab -e
// puis ajouter : */5 * * * * php /var/www/html/cron/check_replies.php
//
// Prérequis : sudo apt install php-imap
//
// Fonctionnement :
// 1. Se connecte à la boîte IMAP Ionos
// 2. Lit les emails non lus
// 3. Pour chaque email, extrait le header "In-Reply-To"
// 4. Cherche le Message-ID dans sent_message_ids
// 5. Si trouvé → insère la réponse dans message_replies (direction='in')
// 6. Marque l'email comme lu dans la boîte
// 7. Remet le contact_message en is_read=0 pour notifier dans le BO
// Sécurité : ce script ne doit être exécuté que depuis CLI
if (PHP_SAPI !== 'cli' && !defined('CRON_INTERNAL')) {
http_response_code(403);
exit('Accès refusé.');
}
define('ROOT', dirname(__DIR__));
require_once ROOT . '/config/database.php';
require_once ROOT . '/config/imap.php';
// ── Connexion IMAP ─────────────────────────────────────────
$mailboxFlags = '/ssl' . (IMAP_VALIDATE_CERT ? '' : '/novalidate-cert');
$mailboxStr = '{' . IMAP_HOST . ':' . IMAP_PORT . $mailboxFlags . '}' . IMAP_FOLDER;
$imap = @imap_open($mailboxStr, IMAP_USER, IMAP_PASS, 0, 1);
if (!$imap) {
$err = imap_last_error();
error_log('[CheckReplies] Connexion IMAP impossible : ' . $err);
exit(1);
}
// ── Recherche des emails non lus ───────────────────────────
$uids = imap_search($imap, 'UNSEEN', SE_UID);
if (!$uids) {
imap_close($imap);
exit(0);
}
try {
$db = getDatabase();
// Créer la table si la migration n'a pas encore été jouée
$db->exec("CREATE TABLE IF NOT EXISTS sent_message_ids (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id VARCHAR(255) NOT NULL,
contact_message_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_message_id (message_id),
INDEX idx_smid_contact (contact_message_id)
) ENGINE=InnoDB");
} catch (Throwable $e) {
error_log('[CheckReplies] DB unavailable : ' . $e->getMessage());
imap_close($imap);
exit(1);
}
$processed = 0;
$skipped = 0;
foreach ($uids as $uid) {
// ── Récupérer les headers bruts ───────────────────────
$rawHeader = imap_fetchheader($imap, $uid, FT_UID);
// Extraire In-Reply-To et References
$inReplyTo = extractHeader($rawHeader, 'In-Reply-To');
$references = extractHeader($rawHeader, 'References');
// Construire la liste de tous les Message-IDs référencés
$candidates = [];
if ($inReplyTo) $candidates = array_merge($candidates, parseMessageIds($inReplyTo));
if ($references) $candidates = array_merge($candidates, parseMessageIds($references));
$candidates = array_unique(array_filter($candidates));
if (empty($candidates)) {
// Pas de threading → email non lié, on marque quand même comme vu
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
$skipped++;
continue;
}
// ── Chercher le contact_message correspondant ─────────
$placeholders = implode(',', array_fill(0, count($candidates), '?'));
$stmt = $db->prepare(
"SELECT contact_message_id FROM sent_message_ids
WHERE message_id IN ({$placeholders})
ORDER BY created_at DESC LIMIT 1"
);
$stmt->execute(array_values($candidates));
$row = $stmt->fetch();
if (!$row) {
// Message-ID inconnu (email sans rapport)
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
$skipped++;
continue;
}
$contactMessageId = (int) $row['contact_message_id'];
// ── Vérifier que ce n'est pas un doublon ──────────────
// (sécurité en cas d'exécution multiple avant flag \Seen)
$currentMsgId = extractHeader($rawHeader, 'Message-ID');
if ($currentMsgId) {
$dup = $db->prepare(
"SELECT COUNT(*) FROM sent_message_ids WHERE message_id = :mid"
);
$dup->execute(['mid' => trim($currentMsgId)]);
if ((int)$dup->fetchColumn() > 0) {
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
$skipped++;
continue;
}
}
// ── Extraire l'expéditeur ─────────────────────────────
$header = imap_headerinfo($imap, imap_msgno($imap, $uid));
$senderEmail = '';
if (!empty($header->from[0])) {
$from = $header->from[0];
$senderEmail = ($from->mailbox ?? '') . '@' . ($from->host ?? '');
}
// Ignorer les réponses qui viennent de notre propre adresse (évite les boucles)
if (strtolower($senderEmail) === strtolower(IMAP_USER)) {
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
$skipped++;
continue;
}
// ── Extraire le corps du message ──────────────────────
$structure = imap_fetchstructure($imap, $uid, FT_UID);
$body = extractBody($imap, $uid, $structure, '1');
$body = stripQuotedContent($body);
$body = trim($body);
if ($body === '') {
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
$skipped++;
continue;
}
// ── Insérer la réponse dans message_replies ───────────
try {
// S'assurer que les colonnes existent (migration défensive, compatible MySQL 5.7+)
foreach ([
"ALTER TABLE message_replies ADD COLUMN direction ENUM('out','in') NOT NULL DEFAULT 'out'",
"ALTER TABLE message_replies ADD COLUMN sender_email VARCHAR(255) DEFAULT NULL",
"ALTER TABLE message_replies ADD COLUMN message_id_sent VARCHAR(255) DEFAULT NULL",
] as $alterSql) {
try { $db->exec($alterSql); } catch (Throwable) {}
}
$db->prepare(
"INSERT INTO message_replies (message_id, reply_text, direction, sender_email)
VALUES (:mid, :txt, 'in', :email)"
)->execute([
'mid' => $contactMessageId,
'txt' => $body,
'email' => $senderEmail,
]);
// Remettre le contact_message en "non lu" pour alerter dans le BO
$db->prepare("UPDATE contact_messages SET is_read = 0 WHERE id = :id")
->execute(['id' => $contactMessageId]);
$processed++;
} catch (Throwable $e) {
error_log('[CheckReplies] Erreur INSERT : ' . $e->getMessage());
}
// ── Marquer comme lu dans la boîte ───────────────────
imap_setflag_full($imap, (string)$uid, '\\Seen', ST_UID);
}
imap_expunge($imap);
imap_close($imap);
if ($processed > 0 || $skipped > 0) {
error_log("[CheckReplies] Traités : {$processed} | Ignorés : {$skipped}");
}
exit(0);
// ═══════════════════════════════════════════════════════════
// Fonctions utilitaires
// ═══════════════════════════════════════════════════════════
/**
* Extrait la valeur d'un header dans les headers bruts.
*/
function extractHeader(string $rawHeader, string $name): string
{
if (preg_match('/^' . preg_quote($name, '/') . ':\s*(.+?)(?=\r?\n\S|\r?\n\r?\n|$)/ims', $rawHeader, $m)) {
// Normaliser les folded headers (continuation sur la ligne suivante)
return preg_replace('/\r?\n\s+/', ' ', trim($m[1]));
}
return '';
}
/**
* Extrait tous les Message-IDs d'une chaîne (format <id@domain>).
*/
function parseMessageIds(string $str): array
{
preg_match_all('/<[^>]+>/', $str, $matches);
return $matches[0] ?? [];
}
/**
* Extrait le corps texte d'un email (préfère plain text, fallback HTML).
*/
function extractBody($imap, int $uid, object $part, string $partNum): string
{
// Message simple
if ($part->type === TYPETEXT) {
$raw = imap_fetchbody($imap, $uid, $partNum, FT_UID);
$body = decodeBody($raw, $part->encoding ?? ENC7BIT);
$body = convertCharset($body, $part->parameters ?? []);
if (strtolower($part->subtype ?? '') === 'html') {
$body = htmlToText($body);
}
return $body;
}
// Multipart — parcourir les sous-parties
if ($part->type === TYPEMULTIPART && !empty($part->parts)) {
$plainText = '';
$htmlText = '';
foreach ($part->parts as $i => $subPart) {
// Numérotation IMAP : première partie = '1', imbriquée = '1.1', '1.2'…
$subNum = ($partNum === '1' && !str_contains($partNum, '.'))
? (string)($i + 1)
: $partNum . '.' . ($i + 1);
// Réévaluation récursive pour les multipart imbriqués
$result = extractBody($imap, $uid, $subPart, $subNum);
if ($subPart->type === TYPETEXT && strtolower($subPart->subtype ?? '') === 'plain' && $plainText === '') {
$plainText = $result;
} elseif ($subPart->type === TYPETEXT && strtolower($subPart->subtype ?? '') === 'html' && $htmlText === '') {
$htmlText = $result;
} elseif ($subPart->type === TYPEMULTIPART && $plainText === '') {
$plainText = $result; // résultat du multipart imbriqué
}
}
return $plainText !== '' ? $plainText : $htmlText;
}
return '';
}
/**
* Décode le corps selon l'encodage MIME.
*/
function decodeBody(string $body, int $encoding): string
{
return match ($encoding) {
ENCBASE64 => base64_decode($body),
ENCQUOTEDPRINTABLE => quoted_printable_decode($body),
default => $body,
};
}
/**
* Convertit le charset en UTF-8 si nécessaire.
*/
function convertCharset(string $body, array $params): string
{
foreach ($params as $param) {
if (strtolower($param->attribute ?? '') === 'charset') {
$charset = strtoupper($param->value ?? 'UTF-8');
if ($charset !== 'UTF-8') {
$converted = @mb_convert_encoding($body, 'UTF-8', $charset);
if ($converted !== false) {
return $converted;
}
}
}
}
return $body;
}
/**
* Convertit du HTML en texte lisible.
*/
function htmlToText(string $html): string
{
$html = preg_replace('/<br\s*\/?>/i', "\n", $html);
$html = preg_replace('/<\/p>/i', "\n\n", $html);
$html = preg_replace('/<\/div>/i', "\n", $html);
return html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Supprime les parties citées d'un email (lignes >, "On ... wrote:", etc.)
*/
function stripQuotedContent(string $text): string
{
$lines = preg_split('/\r?\n/', $text);
$result = [];
foreach ($lines as $line) {
$trimmed = ltrim($line);
// Ligne citée avec >
if (str_starts_with($trimmed, '>')) break;
// "On [date], X wrote:" (anglais/français)
if (preg_match('/^(On|Le) .{5,120} (wrote|a écrit)\s*:?\s*$/iu', $trimmed)) break;
// Séparateurs classiques de clients mail
if (preg_match('/^-{5,}\s*(Original Message|Forwarded|Message d\'origine)/i', $trimmed)) break;
if (preg_match('/^_{10,}$/', $trimmed)) break;
// Ligne de type "De : / From : / Sent :" des Outlook
if (preg_match('/^(De|From|Envoyé|Sent|À|To|Objet|Subject)\s*:/ui', $trimmed) && count($result) > 0) break;
$result[] = $line;
}
// Retirer les lignes vides en fin
while (!empty($result) && trim(end($result)) === '') {
array_pop($result);
}
return implode("\n", $result);
}

View file

@ -0,0 +1,13 @@
# ============================================================
# Pages d'erreur personnalisées — tony-averty.dev
# À ajouter dans le bloc server { listen 8080; ... }
# ============================================================
error_page 403 /errors/403.php;
error_page 404 /errors/404.php;
error_page 500 502 503 504 /errors/500.php;
# Interdit l'accès direct aux pages d'erreur (internes uniquement)
location ^~ /errors/ {
internal;
}

View file

@ -0,0 +1,52 @@
# Exemple de configuration Nginx a adapter a ton vhost.
# Important : l'audit detecte Nginx, donc .htaccess seul ne te protege pas.
server {
listen 80;
server_name tony-averty.dev www.tony-averty.dev;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name tony-averty.dev www.tony-averty.dev;
root /var/www/tony-averty.dev;
index index.php;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=()" always;
location ~ /\.(?!well-known/) {
deny all;
}
location ~* ^/(?:config|sql|includes|cron)/ {
deny all;
}
location ~* ^/(?:setup\.php|server-status)$ {
deny all;
}
location ~* \.(?:env|ini|log|sql|bak|old|tmp|swp|md|zip|tar|gz|7z|yml|yaml|dist|example)$ {
deny all;
}
location ~* ^/assets/img/projects/.*\.(?:php|phtml|phar|php\d*)$ {
deny all;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

146
errors/403.php Normal file
View file

@ -0,0 +1,146 @@
<?php http_response_code(403); ?>
<!DOCTYPE html>
<html lang="fr" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accès refusé — Tony AVERTY</title>
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="/assets/img/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/assets/css/style.css">
<script>
(function () {
var t = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', t);
document.documentElement.classList.add('no-transition');
})();
</script>
<style>
.error-page__nav { justify-content: space-between; }
</style>
<style>
.error-page {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.error-page__nav {
height: var(--navbar-height);
display: flex;
align-items: center;
padding: 0 var(--space-xl);
border-bottom: 1px solid var(--border);
background: var(--navbar-bg);
backdrop-filter: blur(12px);
}
.error-page__logo {
font-family: var(--font-main);
font-size: 1.25rem;
font-weight: 800;
color: var(--text-primary);
text-decoration: none;
letter-spacing: -0.02em;
}
.error-page__logo span { color: var(--accent); }
.error-page__main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4xl) var(--space-xl);
}
.error-page__inner {
max-width: 560px;
width: 100%;
text-align: center;
}
.error-page__code {
font-family: var(--font-mono);
font-size: clamp(5rem, 15vw, 9rem);
font-weight: 800;
line-height: 1;
color: var(--accent);
opacity: 0.15;
letter-spacing: -0.04em;
margin-bottom: -1rem;
display: block;
}
.error-page__title {
font-size: clamp(1.5rem, 4vw, 2.25rem);
font-weight: 700;
color: var(--text-primary);
margin-bottom: var(--space-md);
line-height: 1.2;
}
.error-page__desc {
font-size: 1rem;
color: var(--text-secondary);
line-height: 1.7;
margin-bottom: var(--space-2xl);
}
.error-page__actions {
display: flex;
gap: var(--space-md);
justify-content: center;
flex-wrap: wrap;
}
.error-page__footer {
padding: var(--space-xl);
text-align: center;
border-top: 1px solid var(--border);
}
.error-page__footer-text {
font-size: 0.8125rem;
color: var(--text-tertiary);
}
.error-page__footer-text a {
color: var(--accent);
text-decoration: none;
}
.error-page__footer-text a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="error-page">
<nav class="error-page__nav">
<a href="/" class="error-page__logo">Tony<span>.</span></a>
<button class="theme-switch" id="themeSwitch" type="button" aria-label="Changer de thème">
<span class="theme-switch__icon theme-switch__icon--sun" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
</span>
<span class="theme-switch__icon theme-switch__icon--moon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
</span>
</button>
</nav>
<main class="error-page__main">
<div class="error-page__inner">
<span class="error-page__code" aria-hidden="true">403</span>
<h1 class="error-page__title">Accès non autorisé</h1>
<p class="error-page__desc">
Vous n'avez pas les droits nécessaires pour accéder à cette ressource. Si vous pensez qu'il s'agit d'une erreur, n'hésitez pas à me contacter.
</p>
<div class="error-page__actions">
<a href="/" class="btn btn--primary">Retour à l'accueil</a>
<a href="/#contact" class="btn btn--outline">Me contacter</a>
</div>
</div>
</main>
<footer class="error-page__footer">
<p class="error-page__footer-text">
Tony AVERTY — Développeur web freelance &bull; <a href="mailto:contact@tony-averty.dev">contact@tony-averty.dev</a>
</p>
</footer>
</div>
<!-- Curseur personnalisé -->
<div class="cursor-dot" id="cursorDot" aria-hidden="true"></div>
<div class="cursor-ring" id="cursorRing" aria-hidden="true"></div>
<script src="/assets/js/error-page.js"></script>
</body>
</html>

146
errors/404.php Normal file
View file

@ -0,0 +1,146 @@
<?php http_response_code(404); ?>
<!DOCTYPE html>
<html lang="fr" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page introuvable — Tony AVERTY</title>
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="/assets/img/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/assets/css/style.css">
<script>
(function () {
var t = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', t);
document.documentElement.classList.add('no-transition');
})();
</script>
<style>
.error-page__nav { justify-content: space-between; }
</style>
<style>
.error-page {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.error-page__nav {
height: var(--navbar-height);
display: flex;
align-items: center;
padding: 0 var(--space-xl);
border-bottom: 1px solid var(--border);
background: var(--navbar-bg);
backdrop-filter: blur(12px);
}
.error-page__logo {
font-family: var(--font-main);
font-size: 1.25rem;
font-weight: 800;
color: var(--text-primary);
text-decoration: none;
letter-spacing: -0.02em;
}
.error-page__logo span { color: var(--accent); }
.error-page__main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4xl) var(--space-xl);
}
.error-page__inner {
max-width: 560px;
width: 100%;
text-align: center;
}
.error-page__code {
font-family: var(--font-mono);
font-size: clamp(5rem, 15vw, 9rem);
font-weight: 800;
line-height: 1;
color: var(--accent);
opacity: 0.15;
letter-spacing: -0.04em;
margin-bottom: -1rem;
display: block;
}
.error-page__title {
font-size: clamp(1.5rem, 4vw, 2.25rem);
font-weight: 700;
color: var(--text-primary);
margin-bottom: var(--space-md);
line-height: 1.2;
}
.error-page__desc {
font-size: 1rem;
color: var(--text-secondary);
line-height: 1.7;
margin-bottom: var(--space-2xl);
}
.error-page__actions {
display: flex;
gap: var(--space-md);
justify-content: center;
flex-wrap: wrap;
}
.error-page__footer {
padding: var(--space-xl);
text-align: center;
border-top: 1px solid var(--border);
}
.error-page__footer-text {
font-size: 0.8125rem;
color: var(--text-tertiary);
}
.error-page__footer-text a {
color: var(--accent);
text-decoration: none;
}
.error-page__footer-text a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="error-page">
<nav class="error-page__nav">
<a href="/" class="error-page__logo">Tony<span>.</span></a>
<button class="theme-switch" id="themeSwitch" type="button" aria-label="Changer de thème">
<span class="theme-switch__icon theme-switch__icon--sun" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
</span>
<span class="theme-switch__icon theme-switch__icon--moon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
</span>
</button>
</nav>
<main class="error-page__main">
<div class="error-page__inner">
<span class="error-page__code" aria-hidden="true">404</span>
<h1 class="error-page__title">Cette page n'existe pas</h1>
<p class="error-page__desc">
L'adresse que vous avez demandée est introuvable — elle a peut-être été déplacée, supprimée, ou vous avez suivi un lien incorrect.
</p>
<div class="error-page__actions">
<a href="/" class="btn btn--primary">Retourner au site</a>
<a href="mailto:contact@tony-averty.dev?subject=Page introuvable — <?php echo htmlspecialchars($_SERVER['REQUEST_URI'] ?? ''); ?>&body=Bonjour, j'ai tenté d'accéder à cette adresse : <?php echo htmlspecialchars('https://' . ($_SERVER['HTTP_HOST'] ?? 'tony-averty.dev') . ($_SERVER['REQUEST_URI'] ?? '')); ?>" class="btn btn--outline">Signaler le problème</a>
</div>
</div>
</main>
<footer class="error-page__footer">
<p class="error-page__footer-text">
Tony AVERTY — Développeur web freelance &bull; <a href="mailto:contact@tony-averty.dev">contact@tony-averty.dev</a>
</p>
</footer>
</div>
<!-- Curseur personnalisé -->
<div class="cursor-dot" id="cursorDot" aria-hidden="true"></div>
<div class="cursor-ring" id="cursorRing" aria-hidden="true"></div>
<script src="/assets/js/error-page.js"></script>
</body>
</html>

146
errors/500.php Normal file
View file

@ -0,0 +1,146 @@
<?php http_response_code(500); ?>
<!DOCTYPE html>
<html lang="fr" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Erreur serveur — Tony AVERTY</title>
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="/assets/img/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/assets/css/style.css">
<script>
(function () {
var t = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', t);
document.documentElement.classList.add('no-transition');
})();
</script>
<style>
.error-page__nav { justify-content: space-between; }
</style>
<style>
.error-page {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.error-page__nav {
height: var(--navbar-height);
display: flex;
align-items: center;
padding: 0 var(--space-xl);
border-bottom: 1px solid var(--border);
background: var(--navbar-bg);
backdrop-filter: blur(12px);
}
.error-page__logo {
font-family: var(--font-main);
font-size: 1.25rem;
font-weight: 800;
color: var(--text-primary);
text-decoration: none;
letter-spacing: -0.02em;
}
.error-page__logo span { color: var(--accent); }
.error-page__main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4xl) var(--space-xl);
}
.error-page__inner {
max-width: 560px;
width: 100%;
text-align: center;
}
.error-page__code {
font-family: var(--font-mono);
font-size: clamp(5rem, 15vw, 9rem);
font-weight: 800;
line-height: 1;
color: var(--accent);
opacity: 0.15;
letter-spacing: -0.04em;
margin-bottom: -1rem;
display: block;
}
.error-page__title {
font-size: clamp(1.5rem, 4vw, 2.25rem);
font-weight: 700;
color: var(--text-primary);
margin-bottom: var(--space-md);
line-height: 1.2;
}
.error-page__desc {
font-size: 1rem;
color: var(--text-secondary);
line-height: 1.7;
margin-bottom: var(--space-2xl);
}
.error-page__actions {
display: flex;
gap: var(--space-md);
justify-content: center;
flex-wrap: wrap;
}
.error-page__footer {
padding: var(--space-xl);
text-align: center;
border-top: 1px solid var(--border);
}
.error-page__footer-text {
font-size: 0.8125rem;
color: var(--text-tertiary);
}
.error-page__footer-text a {
color: var(--accent);
text-decoration: none;
}
.error-page__footer-text a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="error-page">
<nav class="error-page__nav">
<a href="/" class="error-page__logo">Tony<span>.</span></a>
<button class="theme-switch" id="themeSwitch" type="button" aria-label="Changer de thème">
<span class="theme-switch__icon theme-switch__icon--sun" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
</span>
<span class="theme-switch__icon theme-switch__icon--moon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
</span>
</button>
</nav>
<main class="error-page__main">
<div class="error-page__inner">
<span class="error-page__code" aria-hidden="true">500</span>
<h1 class="error-page__title">Une erreur est survenue</h1>
<p class="error-page__desc">
Le serveur a rencontré un problème inattendu. Ce n'est pas de votre côté — je suis probablement déjà au courant. Vous pouvez réessayer dans quelques instants.
</p>
<div class="error-page__actions">
<a href="/" class="btn btn--primary">Retour à l'accueil</a>
<a href="mailto:contact@tony-averty.dev" class="btn btn--outline">Me signaler le problème</a>
</div>
</div>
</main>
<footer class="error-page__footer">
<p class="error-page__footer-text">
Tony AVERTY — Développeur web freelance &bull; <a href="mailto:contact@tony-averty.dev">contact@tony-averty.dev</a>
</p>
</footer>
</div>
<!-- Curseur personnalisé -->
<div class="cursor-dot" id="cursorDot" aria-hidden="true"></div>
<div class="cursor-ring" id="cursorRing" aria-hidden="true"></div>
<script src="/assets/js/error-page.js"></script>
</body>
</html>

251
includes/Mailer.php Normal file
View file

@ -0,0 +1,251 @@
<?php
/**
* Mailer - envoi SMTP sans dependance externe.
*/
require_once __DIR__ . '/../config/smtp.php';
class Mailer
{
private string $host;
private int $port;
private string $user;
private string $pass;
private string $fromEmail;
private string $fromName;
private string $lastMessageId = '';
/** @var resource|false */
private mixed $sock = false;
public function __construct()
{
$this->host = SMTP_HOST;
$this->port = SMTP_PORT;
$this->user = SMTP_USER;
$this->pass = SMTP_PASS;
$this->fromEmail = SMTP_FROM_EMAIL;
$this->fromName = SMTP_FROM_NAME;
}
/**
* Retourne le Message-ID du dernier email envoye.
*/
public function getLastMessageId(): string
{
return $this->lastMessageId;
}
/**
* Envoie un email texte brut.
*/
public function send(string $to, string $subject, string $body, string $replyTo = ''): bool
{
return $this->dispatch($to, $subject, $body, '', $replyTo);
}
/**
* Envoie un email HTML avec fallback texte.
*/
public function sendHtml(string $to, string $subject, string $htmlBody, string $textBody = '', string $replyTo = ''): bool
{
return $this->dispatch($to, $subject, $textBody, $htmlBody, $replyTo);
}
/**
* Envoi SMTP interne.
*/
private function dispatch(string $to, string $subject, string $textBody, string $htmlBody, string $replyTo): bool
{
try {
$to = $this->normalizeEmail($to);
$replyTo = $replyTo !== '' ? $this->normalizeEmail($replyTo) : '';
$subject = $this->normalizeHeaderText($subject);
$this->connect();
$this->read(220);
$this->cmd("EHLO {$this->host}", 250);
if ($this->port === 587) {
$this->cmd('STARTTLS', 220);
if (!stream_socket_enable_crypto($this->sock, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
throw new RuntimeException('STARTTLS negotiation failed');
}
$this->cmd("EHLO {$this->host}", 250);
}
$this->cmd('AUTH LOGIN', 334);
$this->cmd(base64_encode($this->user), 334);
$this->cmd(base64_encode($this->pass), 235);
$this->cmd("MAIL FROM: <{$this->fromEmail}>", 250);
$this->cmd("RCPT TO: <{$to}>", [250, 251]);
$this->cmd('DATA', 354);
$this->lastMessageId = '<' . bin2hex(random_bytes(16)) . '@tony-averty.dev>';
$msg = 'From: ' . $this->encodeHeader($this->fromName) . " <{$this->fromEmail}>\r\n";
$msg .= "To: <{$to}>\r\n";
if ($replyTo !== '') {
$msg .= "Reply-To: <{$replyTo}>\r\n";
}
$msg .= 'Subject: ' . $this->encodeHeader($subject) . "\r\n";
$msg .= "Message-ID: {$this->lastMessageId}\r\n";
$msg .= "MIME-Version: 1.0\r\n";
$msg .= "X-Mailer: TonyPortfolio/1.0\r\n";
if ($htmlBody !== '') {
$boundary = 'boundary_' . bin2hex(random_bytes(12));
$plain = $textBody !== '' ? $textBody : strip_tags($htmlBody);
$msg .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n\r\n";
$msg .= "--{$boundary}\r\n";
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
$msg .= chunk_split(base64_encode($plain)) . "\r\n";
$msg .= "--{$boundary}\r\n";
$msg .= "Content-Type: text/html; charset=UTF-8\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
$msg .= chunk_split(base64_encode($htmlBody)) . "\r\n";
$msg .= "--{$boundary}--\r\n";
} else {
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
$msg .= chunk_split(base64_encode($textBody));
}
$msg .= "\r\n.\r\n";
fwrite($this->sock, $msg);
$this->read(250);
$this->cmd('QUIT', 221);
fclose($this->sock);
$this->sock = false;
return true;
} catch (Throwable $e) {
error_log('[Mailer] ' . $e->getMessage());
if ($this->sock) {
@fclose($this->sock);
$this->sock = false;
}
return false;
}
}
/**
* Ouvre la connexion SMTP avec verification TLS.
*/
private function connect(): void
{
$transport = $this->port === 465 ? 'tls' : 'tcp';
$timeout = 20;
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'allow_self_signed' => false,
'peer_name' => $this->host,
'SNI_enabled' => true,
],
]);
$errno = 0;
$errstr = '';
$this->sock = @stream_socket_client(
"{$transport}://{$this->host}:{$this->port}",
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$context
);
if (!$this->sock) {
throw new RuntimeException("Connexion SMTP impossible : {$errstr} ({$errno})");
}
stream_set_timeout($this->sock, $timeout);
}
/**
* Envoie une commande SMTP.
*/
private function cmd(string $cmd, int|array $expect = 250): string
{
fwrite($this->sock, $cmd . "\r\n");
return $this->read($expect);
}
/**
* Lit la reponse SMTP.
*/
private function read(int|array $expect): string
{
$response = '';
while ($line = fgets($this->sock, 1024)) {
$response .= $line;
if (isset($line[3]) && $line[3] === ' ') {
break;
}
}
$code = (int) substr($response, 0, 3);
$expected = is_array($expect) ? $expect : [$expect];
if (!in_array($code, $expected, true)) {
throw new RuntimeException(
'Erreur SMTP (attendu ' . implode('/', $expected) . ", recu {$code}) : " . trim($response)
);
}
return $response;
}
/**
* Encode un header UTF-8 si necessaire.
*/
private function encodeHeader(string $value): string
{
if (preg_match('/[^\x20-\x7E]/', $value)) {
return '=?UTF-8?B?' . base64_encode($value) . '?=';
}
return $value;
}
/**
* Valide une adresse email avant injection SMTP.
*/
private function normalizeEmail(string $value): string
{
$value = trim(str_replace(["\r", "\n"], '', $value));
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Adresse email invalide.');
}
return $value;
}
/**
* Nettoie les retours a la ligne dans un header texte.
*/
private function normalizeHeaderText(string $value): string
{
return trim(str_replace(["\r", "\n"], ' ', $value));
}
}

484
includes/Security.php Normal file
View file

@ -0,0 +1,484 @@
<?php
/**
* Security - protections centralisees.
*/
class Security
{
private static ?string $cspNonce = null;
private static bool $headersApplied = false;
/**
* Initialise les headers de securite et, si besoin, la session.
*
* @param array<string, mixed> $options
*/
public static function bootstrap(bool $withSession = true, array $options = []): void
{
if (PHP_SAPI !== 'cli') {
self::applySecurityHeaders($options);
}
if ($withSession) {
self::startSession();
}
}
/**
* Applique les headers de securite HTTP.
*
* @param array<string, mixed> $options
*/
public static function applySecurityHeaders(array $options = []): void
{
if (PHP_SAPI === 'cli' || headers_sent() || self::$headersApplied) {
return;
}
$isApi = (bool) ($options['api'] ?? false);
$noStore = (bool) ($options['no_store'] ?? false);
$allowAnalyticsCdn = (bool) ($options['allow_analytics_cdn'] ?? false);
$allowRecaptcha = (bool) ($options['recaptcha'] ?? false);
header_remove('X-Powered-By');
@ini_set('expose_php', '0');
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), payment=(), usb=()');
header('Cross-Origin-Opener-Policy: same-origin');
header('Cross-Origin-Resource-Policy: same-origin');
header('X-Permitted-Cross-Domain-Policies: none');
if (self::isHttps()) {
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
if ($isApi || $noStore) {
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
}
header('Content-Security-Policy: ' . self::buildCsp($allowAnalyticsCdn, $allowRecaptcha));
self::$headersApplied = true;
}
/**
* Construit la politique CSP.
*/
private static function buildCsp(bool $allowAnalyticsCdn, bool $allowRecaptcha = false): string
{
$scriptSources = [
"'self'",
"'nonce-" . self::cspNonce() . "'",
];
if ($allowAnalyticsCdn) {
$scriptSources[] = 'https://cdn.jsdelivr.net';
}
$connectSources = ["'self'"];
$frameSources = [];
$imgSources = ["'self'", 'data:'];
if ($allowRecaptcha) {
// Google reCAPTCHA v3 : script, iframe du badge, images et appels reseau.
$scriptSources[] = 'https://www.google.com';
$scriptSources[] = 'https://www.gstatic.com';
$connectSources[] = 'https://www.google.com';
$connectSources[] = 'https://www.gstatic.com';
$frameSources[] = 'https://www.google.com';
$imgSources[] = 'https://www.gstatic.com';
}
$directives = [
"default-src 'self'",
'script-src ' . implode(' ', array_unique($scriptSources)),
"style-src 'self' 'unsafe-inline'",
'img-src ' . implode(' ', array_unique($imgSources)),
"font-src 'self'",
'connect-src ' . implode(' ', array_unique($connectSources)),
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"script-src-attr 'none'",
'upgrade-insecure-requests',
];
if ($frameSources !== []) {
array_splice($directives, 6, 0, ['frame-src ' . implode(' ', array_unique($frameSources))]);
}
return implode('; ', $directives) . ';';
}
/**
* Retourne le nonce CSP courant.
*/
public static function cspNonce(): string
{
if (self::$cspNonce === null) {
self::$cspNonce = rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '=');
}
return self::$cspNonce;
}
/**
* Demarre la session avec des parametres securises.
*/
public static function startSession(): void
{
if (session_status() === PHP_SESSION_NONE) {
@ini_set('session.use_strict_mode', '1');
@ini_set('session.use_only_cookies', '1');
@ini_set('session.use_trans_sid', '0');
@ini_set('session.cookie_httponly', '1');
@ini_set('session.cookie_secure', self::isHttps() ? '1' : '0');
@ini_set('session.cookie_samesite', 'Strict');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => self::isHttps(),
'httponly' => true,
'samesite' => 'Strict',
]);
session_start();
}
if (!isset($_SESSION['_created'])) {
$_SESSION['_created'] = time();
} elseif (time() - (int) $_SESSION['_created'] > 1800) {
session_regenerate_id(true);
$_SESSION['_created'] = time();
}
}
/**
* Genere (ou recupere) le token CSRF de la session courante.
*/
public static function csrfToken(): string
{
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
/**
* Retourne un champ CSRF pret a injecter dans un formulaire HTML.
*/
public static function csrfInput(): string
{
return '<input type="hidden" name="csrf_token" value="' . self::e(self::csrfToken()) . '">';
}
/**
* Valide le token CSRF soumis.
*/
public static function verifyCsrf(string $submitted, bool $json = false): void
{
$token = $_SESSION['csrf_token'] ?? '';
if ($token === '' || $submitted === '' || !hash_equals($token, $submitted)) {
http_response_code(403);
if ($json) {
self::jsonResponse([
'success' => false,
'message' => 'Requete invalide.',
]);
}
exit('Requete invalide.');
}
}
/**
* Verifie l'origine quand le navigateur envoie Origin/Referer.
*/
public static function enforceSameOrigin(bool $json = false): void
{
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if ($origin !== '' && !self::matchesCurrentOrigin($origin)) {
self::abortOriginMismatch($json);
}
if ($referer !== '' && !self::matchesCurrentOrigin($referer)) {
self::abortOriginMismatch($json);
}
}
/**
* Redirige vers la page de login si aucune session admin n'est ouverte.
*/
public static function requireAdmin(): void
{
if (empty($_SESSION['admin_id'])) {
header('Location: login.php');
exit;
}
}
/**
* Retourne l'IP client.
*/
public static function clientIp(): string
{
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
/**
* Verifie si l'action depasse le nombre de requetes autorisees.
*/
public static function isRateLimited(PDO $db, string $action, string $ip, int $max, int $windowMinutes): bool
{
try {
$db->exec("CREATE TABLE IF NOT EXISTS rate_limits (
id INT AUTO_INCREMENT PRIMARY KEY,
action VARCHAR(64) NOT NULL,
ip VARCHAR(45) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_action_ip_time (action, ip, created_at)
)");
$cutoff = (new DateTimeImmutable("-{$windowMinutes} minutes"))->format('Y-m-d H:i:s');
$stmt = $db->prepare(
'SELECT COUNT(*) FROM rate_limits
WHERE action = :action AND ip = :ip AND created_at > :cutoff'
);
$stmt->execute([
'action' => $action,
'ip' => $ip,
'cutoff' => $cutoff,
]);
return (int) $stmt->fetchColumn() >= $max;
} catch (Throwable) {
return false;
}
}
/**
* Enregistre une tentative pour le rate limiting.
*/
public static function recordAttempt(PDO $db, string $action, string $ip): void
{
try {
$db->prepare('INSERT INTO rate_limits (action, ip) VALUES (:action, :ip)')
->execute([
'action' => $action,
'ip' => $ip,
]);
$db->exec("DELETE FROM rate_limits WHERE created_at < NOW() - INTERVAL 24 HOUR");
} catch (Throwable) {
}
}
/**
* Nettoie une chaine pour l'affichage HTML.
*/
public static function e(string $str): string
{
return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
/**
* Valide et nettoie un email.
*/
public static function sanitizeEmail(string $email): string|false
{
$email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : false;
}
/**
* Nettoie un slug.
*/
public static function slugify(string $value): string
{
$value = mb_strtolower(trim($value), 'UTF-8');
$value = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value) ?: $value;
$value = preg_replace('/[^a-z0-9]+/', '-', $value);
$value = trim((string) $value, '-');
return $value !== '' ? $value : 'projet';
}
/**
* Retourne true si l'URL est en HTTPS.
*/
public static function isHttps(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
if ((int) ($_SERVER['SERVER_PORT'] ?? 0) === 443) {
return true;
}
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
return true;
}
return false;
}
/**
* Retourne true si une URL partage la meme origine que la requete courante.
*/
private static function matchesCurrentOrigin(string $url): bool
{
$parts = parse_url($url);
if (!is_array($parts)) {
return false;
}
$host = strtolower((string) ($parts['host'] ?? ''));
$currentHost = strtolower((string) ($_SERVER['HTTP_HOST'] ?? ''));
if ($host === '' || $currentHost === '' || $host !== $currentHost) {
return false;
}
$scheme = strtolower((string) ($parts['scheme'] ?? ''));
$currentScheme = self::isHttps() ? 'https' : 'http';
return $scheme === '' || $scheme === $currentScheme;
}
/**
* Verifie un token Google reCAPTCHA v3 aupres de l'API de verification.
*
* Comportement de tolerance :
* - secret vide => reCAPTCHA non configure, on ne bloque pas (true).
* - reseau HS => on ne bloque pas les vrais visiteurs (true), les autres
* protections (honeypot, captcha maths, rate limit) restent actives.
* - token vide / score trop bas / mauvaise action => bloque (false).
*/
public static function verifyRecaptcha(
string $token,
string $secret,
string $ip,
float $minScore = 0.5,
string $expectedAction = ''
): bool {
if (trim($secret) === '') {
return true;
}
if (trim($token) === '') {
return false;
}
$payload = http_build_query([
'secret' => $secret,
'response' => $token,
'remoteip' => $ip,
]);
$endpoint = 'https://www.google.com/recaptcha/api/siteverify';
$raw = null;
if (function_exists('curl_init')) {
$ch = curl_init($endpoint);
if ($ch !== false) {
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$result = curl_exec($ch);
curl_close($ch);
if (is_string($result) && $result !== '') {
$raw = $result;
}
}
}
if ($raw === null) {
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $payload,
'timeout' => 8,
],
]);
$result = @file_get_contents($endpoint, false, $context);
if (is_string($result) && $result !== '') {
$raw = $result;
}
}
if ($raw === null) {
error_log('[Security] reCAPTCHA : reponse reseau indisponible, tolerance appliquee.');
return true;
}
$data = json_decode($raw, true);
if (!is_array($data)) {
error_log('[Security] reCAPTCHA : reponse JSON invalide, tolerance appliquee.');
return true;
}
if (empty($data['success'])) {
return false;
}
if (isset($data['score']) && (float) $data['score'] < $minScore) {
return false;
}
if ($expectedAction !== '' && isset($data['action']) && $data['action'] !== $expectedAction) {
return false;
}
return true;
}
/**
* Retourne une reponse JSON et arrete l'execution.
*
* @param array<string, mixed> $payload
*/
public static function jsonResponse(array $payload): never
{
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
/**
* Coupe la requete en cas d'origine non fiable.
*/
private static function abortOriginMismatch(bool $json): void
{
http_response_code(403);
if ($json) {
self::jsonResponse([
'success' => false,
'message' => 'Origine non autorisee.',
]);
}
exit('Origine non autorisee.');
}
}

173
includes/footer.php Normal file
View file

@ -0,0 +1,173 @@
<!-- Footer -->
<footer class="footer">
<div class="container">
<div class="footer__inner">
<div class="footer__brand">
<span class="footer__logo">Tony<span class="navbar__logo-accent">.</span></span>
<p class="footer__tagline">Développeur web freelance</p>
<p class="footer__tagline footer__tagline--sub">Fondateur de CodeBzh · Disponible pour nouveaux projets</p>
</div>
<div class="footer__links">
<a href="#about">À propos</a>
<a href="#skills">Compétences</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
<a href="/legal.php">Mentions légales</a>
</div>
<p class="footer__copy">&copy; <?= date('Y') ?> Tony AVERTY — <a href="/legal.php" style="color:inherit;opacity:.6;text-decoration:none;">Mentions légales &amp; RGPD</a></p>
</div>
</div>
</footer>
<!-- Curseur personnalisé -->
<div class="cursor-dot" id="cursorDot" aria-hidden="true"></div>
<div class="cursor-ring" id="cursorRing" aria-hidden="true"></div>
<!-- Dev Panel (réglages) -->
<button class="devpanel-trigger" id="devPanelTrigger" aria-label="Réglages" aria-expanded="false" aria-controls="devPanel">
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="3"/>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
</svg>
</button>
<div class="devpanel" id="devPanel" role="dialog" aria-label="Réglages du site" aria-hidden="true">
<div class="devpanel__header">
<span class="devpanel__title">
<span class="devpanel__title-dot devpanel__title-dot--r"></span>
<span class="devpanel__title-dot devpanel__title-dot--y"></span>
<span class="devpanel__title-dot devpanel__title-dot--g"></span>
<span class="devpanel__title-label">settings.json</span>
</span>
<div class="devpanel__fps-live" id="devFpsLive">
<span class="devpanel__fps-dot" id="devFpsDot"></span>
<span id="devFpsVal">-- fps</span>
</div>
</div>
<div class="devpanel__body">
<!-- Thème -->
<div class="devpanel__section">
<span class="devpanel__section-label">// apparence</span>
<div class="devpanel__row">
<span class="devpanel__row-label">Thème</span>
<div class="devpanel__seg" id="devThemeSeg">
<button class="devpanel__seg-btn" data-theme-val="light">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
Clair
</button>
<button class="devpanel__seg-btn" data-theme-val="dark">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
Sombre
</button>
</div>
</div>
</div>
<!-- Expérience -->
<div class="devpanel__section">
<span class="devpanel__section-label">// expérience</span>
<div class="devpanel__row">
<span class="devpanel__row-label">Curseur custom</span>
<label class="devpanel__toggle">
<input type="checkbox" id="devToggleCursor" checked>
<span class="devpanel__toggle-track"><span class="devpanel__toggle-thumb"></span></span>
</label>
</div>
<div class="devpanel__row">
<span class="devpanel__row-label">Animations</span>
<label class="devpanel__toggle">
<input type="checkbox" id="devToggleAnimations" checked>
<span class="devpanel__toggle-track"><span class="devpanel__toggle-thumb"></span></span>
</label>
</div>
<div class="devpanel__row">
<span class="devpanel__row-label">Scroll lisse</span>
<label class="devpanel__toggle">
<input type="checkbox" id="devToggleSmoothScroll" checked>
<span class="devpanel__toggle-track"><span class="devpanel__toggle-thumb"></span></span>
</label>
</div>
</div>
<!-- Performance -->
<div class="devpanel__section">
<span class="devpanel__section-label">// performance</span>
<div class="devpanel__row">
<span class="devpanel__row-label">FPS cible</span>
<div class="devpanel__seg" id="devFpsSeg">
<button class="devpanel__seg-btn" data-fps-val="15">15</button>
<button class="devpanel__seg-btn" data-fps-val="30">30</button>
<button class="devpanel__seg-btn is-active" data-fps-val="60">60</button>
</div>
</div>
<div class="devpanel__fps-bar-wrap">
<div class="devpanel__fps-bar" id="devFpsBar"></div>
</div>
</div>
</div>
<div class="devpanel__footer">
<span class="devpanel__footer-line">tony-averty.dev · v1.0</span>
</div>
</div>
<!-- Toast notification -->
<div class="toast" id="toast" role="alert" aria-live="polite" aria-atomic="true">
<span class="toast__message" id="toastMessage"></span>
<button class="toast__close" id="toastClose" type="button" aria-label="Fermer">&times;</button>
</div>
<?php if (defined('RECAPTCHA_ENABLED') && RECAPTCHA_ENABLED): ?>
<!-- Google reCAPTCHA v3 (invisible, anti-bot) -->
<script src="https://www.google.com/recaptcha/api.js?render=<?= urlencode(RECAPTCHA_SITE_KEY) ?>" nonce="<?= Security::cspNonce() ?>" async defer></script>
<?php endif; ?>
<script src="assets/js/main.js" nonce="<?= Security::cspNonce() ?>"></script>
<script nonce="<?= Security::cspNonce() ?>">
// ── Tracking maison — sans cookies, RGPD-friendly ────────
(function() {
// Générer / récupérer un session ID en localStorage (pas de cookie)
var sessionId = sessionStorage.getItem('_tsid');
if (!sessionId) {
sessionId = Math.random().toString(36).slice(2) + Date.now().toString(36);
sessionStorage.setItem('_tsid', sessionId);
}
// Détecter le type d'appareil
var device = 'desktop';
if (/Mobi|Android|iPhone|iPod/i.test(navigator.userAgent)) device = 'mobile';
else if (/Tablet|iPad/i.test(navigator.userAgent)) device = 'tablet';
var startTime = Date.now();
function track(action, extra) {
var payload = Object.assign({
action: action,
session_id: sessionId,
page: location.pathname,
referrer: document.referrer || null,
device: device,
}, extra || {});
navigator.sendBeacon('/api/track.php', JSON.stringify(payload));
}
// Tracker la visite au chargement
track('visit');
// Tracker la durée en quittant la page
window.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
track('duration', { duration: Math.round((Date.now() - startTime) / 1000) });
}
});
// Exposer la fonction pour les clics projets
window.trackProjectClick = function(projectId) {
track('project_click', { project_id: projectId });
};
})();
</script>
</body>
</html>

84
includes/header.php Normal file
View file

@ -0,0 +1,84 @@
<!DOCTYPE html>
<html lang="fr" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Tony AVERTY, développeur web freelance et fondateur de CodeBzh. Création de sites sur mesure, refonte, back-end et UI design. Code propre, livraison rigoureuse, réponse sous 24h.">
<meta name="author" content="Tony AVERTY">
<meta name="robots" content="index, follow">
<!-- Open Graph -->
<meta property="og:title" content="Tony AVERTY — Développeur Web Freelance">
<meta property="og:description" content="Développeur web freelance et fondateur de CodeBzh. Sites sur mesure, refonte, back-end, UI design.">
<meta property="og:url" content="https://tony-averty.dev/">
<meta property="og:type" content="website">
<meta property="og:locale" content="fr_FR">
<title>Tony AVERTY — Développeur Web Freelance | Sites sur mesure &amp; Applications</title>
<!-- Favicon -->
<link rel="icon" href="/assets/img/favicon.svg" type="image/svg+xml">
<!-- Styles -->
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<!-- Barre de progression scroll -->
<div class="scroll-progress" id="scrollProgress" aria-hidden="true"></div>
<!-- Navigation -->
<nav class="navbar" id="navbar" role="navigation" aria-label="Navigation principale">
<div class="navbar__container">
<a href="#hero" class="navbar__logo" aria-label="Retour à l'accueil">
<span class="navbar__logo-text">Tony<span class="navbar__logo-accent">.</span></span>
</a>
<ul class="navbar__menu" id="navMenu" role="menubar">
<li role="none"><a href="#about" class="navbar__link" role="menuitem">À propos</a></li>
<li role="none"><a href="#skills" class="navbar__link" role="menuitem">Compétences</a></li>
<li role="none"><a href="#projects" class="navbar__link" role="menuitem" id="navProjects">Projets</a></li>
<li role="none"><a href="#services" class="navbar__link" role="menuitem">Services</a></li>
<li role="none"><a href="#contact" class="navbar__link navbar__link--cta" role="menuitem">Contact</a></li>
</ul>
<div class="navbar__actions">
<!-- Lien BackOffice (admin connecté uniquement) -->
<?php if (!empty($_SESSION['admin_id'])): ?>
<a href="/admin/dashboard.php" class="navbar__admin-link" aria-label="Accéder au BackOffice">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
BackOffice
</a>
<?php endif; ?>
<!-- Theme switch -->
<button class="theme-switch" id="themeSwitch" type="button" aria-label="Changer de thème">
<span class="theme-switch__icon theme-switch__icon--sun" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
</span>
<span class="theme-switch__icon theme-switch__icon--moon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
</svg>
</span>
</button>
<!-- Burger mobile -->
<button class="navbar__burger" id="navBurger" type="button" aria-label="Ouvrir le menu" aria-expanded="false" aria-controls="navMenu">
<span class="navbar__burger-line"></span>
<span class="navbar__burger-line"></span>
<span class="navbar__burger-line"></span>
</button>
</div>
</div>
</nav>

65
includes/projects.php Normal file
View file

@ -0,0 +1,65 @@
<?php
/**
* Logique de récupération des projets publiés
* Portfolio Tony AVERTY
*/
require_once __DIR__ . '/../config/database.php';
/**
* Récupère tous les projets publiés, triés par ordre d'affichage
*
* @return array Liste des projets publiés
*/
function getPublishedProjects(): array
{
try {
$db = getDatabase();
$stmt = $db->prepare(
'SELECT id, title, slug, short_description, full_description,
image, badge, technologies, project_url, display_order, created_at
FROM projects
WHERE status = :status
ORDER BY display_order ASC, created_at DESC'
);
$stmt->execute(['status' => 'published']);
return $stmt->fetchAll();
} catch (PDOException $e) {
error_log('[Portfolio] Erreur récupération projets : ' . $e->getMessage());
return [];
} catch (Throwable $e) {
error_log('[Portfolio] Erreur inattendue projets : ' . $e->getMessage());
return [];
}
}
/**
* Formate le badge d'état pour l'affichage
*
* @param string $badge 'development' ou 'production'
* @return array ['label' => string, 'class' => string]
*/
function formatBadge(string $badge): array
{
return match ($badge) {
'production' => ['label' => 'En production', 'class' => 'badge--production'],
'development' => ['label' => 'En développement', 'class' => 'badge--development'],
default => ['label' => 'En cours', 'class' => 'badge--development'],
};
}
/**
* Transforme la chaîne de technologies en tableau
*
* @param string|null $technologies Chaîne séparée par des virgules
* @return array
*/
function parseTechnologies(?string $technologies): array
{
if (empty($technologies)) {
return [];
}
return array_map('trim', explode(',', $technologies));
}

566
index.php Normal file
View file

@ -0,0 +1,566 @@
<?php
/**
* Portfolio Tony AVERTY — Page principale
* Développeur Web Freelance
*/
require_once __DIR__ . '/includes/Security.php';
require_once __DIR__ . '/config/recaptcha.php';
Security::bootstrap(true, ['recaptcha' => RECAPTCHA_ENABLED]);
require_once __DIR__ . '/includes/projects.php';
// Récupération des projets publiés
$projects = getPublishedProjects();
$hasProjects = !empty($projects);
$isAdmin = !empty($_SESSION['admin_id']);
// Génération du CAPTCHA mathématique
$captchaA = random_int(2, 9);
$captchaB = random_int(1, 6);
$_SESSION['captcha_answer'] = $captchaA + $captchaB;
$captchaQuestion = "{$captchaA} + {$captchaB} = ?";
?>
<?php require_once __DIR__ . '/includes/header.php'; ?>
<main id="main-content">
<!-- ============================================ -->
<!-- HERO -->
<!-- ============================================ -->
<section class="hero" id="hero" aria-label="Accueil">
<div class="hero__grid-bg" aria-hidden="true"></div>
<div class="hero__grain" aria-hidden="true"></div>
<div class="container">
<div class="hero__inner">
<div class="hero__content">
<div class="hero__badge">
<span class="hero__badge-dot" aria-hidden="true"></span>
Disponible pour nouveaux projets
</div>
<h1 class="hero__title">
Du code propre.<br>
Des interfaces claires.<br>
<span class="hero__title-accent">Des projets qui tiennent.</span>
</h1>
<p class="hero__subtitle">
Je conçois des sites et applications web sur mesure, adaptés à votre activité. Design soigné, code solide, livraison dans les délais convenus.
</p>
<div class="hero__actions">
<a href="#contact" class="btn btn--primary btn--lg">
Parlons de votre projet →
</a>
<a href="#projects" class="btn btn--outline btn--lg">Voir ce que j'ai construit</a>
</div>
<div class="hero__stack" aria-label="Technologies maîtrisées">
<span class="hero__stack-label">Stack principale :</span>
<div class="hero__stack-tags">
<span class="tag">HTML / CSS</span>
<span class="tag">JavaScript</span>
<span class="tag">PHP</span>
<span class="tag">SQL</span>
</div>
</div>
</div>
<!-- Visuel hero : carte code éditeur -->
<div class="hero__visual" aria-hidden="true">
<div class="hero__code-card">
<div class="hero__code-header">
<span class="hero__code-dot hero__code-dot--red"></span>
<span class="hero__code-dot hero__code-dot--yellow"></span>
<span class="hero__code-dot hero__code-dot--green"></span>
<span class="hero__code-filename">TonyAverty.php</span>
</div>
<div class="hero__code-body">
<pre class="hero__code-pre"><code><span class="tok-tag">&lt;?php</span>
<span class="tok-keyword">class</span> <span class="tok-class">TonyAverty</span>
<span class="tok-punct">{</span>
<span class="tok-keyword">public string</span> <span class="tok-var">$stack</span> <span class="tok-punct">=</span>
<span class="tok-string">'PHP · JS · CSS'</span><span class="tok-punct">;</span>
<span class="tok-keyword">public string</span> <span class="tok-var">$dispo</span> <span class="tok-punct">=</span>
<span class="tok-string">'Disponible'</span><span class="tok-punct">;</span>
<span class="tok-keyword">public function</span> <span class="tok-fn">livrer</span><span class="tok-punct">(</span>
<span class="tok-class">Project</span> <span class="tok-var">$projet</span>
<span class="tok-punct">):</span> <span class="tok-keyword">void</span>
<span class="tok-punct">{</span>
<span class="tok-comment">// Code propre.</span>
<span class="tok-comment">// Design soigné.</span>
<span class="tok-comment">// Livré avec rigueur.</span>
<span class="tok-punct">}</span>
<span class="tok-punct">}</span></code></pre>
</div>
</div>
<!-- Badges flottants -->
<div class="hero__stat hero__stat--response">
<span class="hero__stat-icon" aria-hidden="true">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
</span>
<div>
<span class="hero__stat-value">24h</span>
<span class="hero__stat-label">Délai de réponse</span>
</div>
</div>
<div class="hero__stat hero__stat--codebzh">
<span class="hero__stat-icon" aria-hidden="true">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
</span>
<div>
<span class="hero__stat-value">CodeBzh</span>
<span class="hero__stat-label">Fondateur & Dev</span>
</div>
</div>
</div>
</div>
</div>
<div class="hero__scroll" aria-hidden="true">
<span class="hero__scroll-line"></span>
</div>
</section>
<!-- ============================================ -->
<!-- À PROPOS -->
<!-- ============================================ -->
<section class="section about" id="about" aria-labelledby="about-title">
<div class="container">
<div class="section__header">
<span class="section__number" aria-hidden="true">01</span>
<span class="section__label">À propos</span>
</div>
<div class="about__grid">
<div class="about__photo-wrapper reveal">
<div class="about__photo-frame">
<img src="assets/img/tony.png" alt="Tony AVERTY, développeur web freelance" class="about__photo" width="400" height="500" loading="lazy">
</div>
<div class="timeline timeline--compact" aria-label="Parcours">
<div class="timeline__item">
<div class="timeline__marker" aria-hidden="true"></div>
<div class="timeline__content">
<span class="timeline__date">Aujourd'hui</span>
<h3 class="timeline__title">Développeur freelance &amp; fondateur CodeBzh</h3>
</div>
</div>
<div class="timeline__item">
<div class="timeline__marker" aria-hidden="true"></div>
<div class="timeline__content">
<span class="timeline__date">Formation</span>
<h3 class="timeline__title">Développement web — HTML, CSS, JS, PHP, SQL</h3>
</div>
</div>
<div class="timeline__item">
<div class="timeline__marker" aria-hidden="true"></div>
<div class="timeline__content">
<span class="timeline__date">Les débuts</span>
<h3 class="timeline__title">Passion pour le web et le code</h3>
</div>
</div>
</div>
</div>
<div class="about__content reveal">
<h2 id="about-title" class="section__title">Développeur freelance. Fondateur d'agence. La même exigence pour votre projet.</h2>
<p class="about__text">
Je suis Tony AVERTY, développeur web freelance basé en Bretagne. J'ai fondé CodeBzh pour proposer une approche différente des agences classiques : chaque site est conçu sur mesure, développé entièrement par mes soins.
</p>
<p class="about__text">
Avant d'écrire la moindre ligne, je prends le temps de comprendre votre activité — ce que vous proposez, à qui, et comment vos clients vous trouvent. C'est ce qui guide chaque décision, du design au référencement.
</p>
<p class="about__text">
Un site bien conçu est avant tout un outil commercial. Je le construis pour générer des contacts, être visible sur Google, et rester performant dans le temps.
</p>
<p class="about__text">
Chaque projet est développé en partant de votre contexte. Pas de raccourci, pas de réutilisation générique — un résultat propre, pensé pour vos visiteurs, livré avec rigueur.
</p>
<div class="about__highlights">
<div class="about__highlight">
<span class="about__highlight-icon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
</span>
<span>Fondateur de CodeBzh, agence web active en Bretagne</span>
</div>
<div class="about__highlight">
<span class="about__highlight-icon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
</span>
<span>Chaque projet construit sur mesure, de la maquette à la mise en ligne</span>
</div>
<div class="about__highlight">
<span class="about__highlight-icon" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
</span>
<span>Réponse garantie sous 24h — toujours</span>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- ============================================ -->
<!-- COMPÉTENCES -->
<!-- ============================================ -->
<section class="section skills" id="skills" aria-labelledby="skills-title">
<div class="container">
<div class="section__header">
<span class="section__number" aria-hidden="true">02</span>
<span class="section__label">Compétences</span>
</div>
<h2 id="skills-title" class="section__title">Les technologies que je maîtrise</h2>
<p class="section__intro">Chaque technologie présentée ici est utilisée sur des projets réels. Des choix fondés sur la fiabilité et la pertinence, pas sur les tendances du moment.</p>
<div class="skills__grid">
<!-- Maîtrise avancée -->
<div class="skills__category reveal">
<h3 class="skills__category-title">
<span class="skills__category-badge skills__category-badge--expert">Maîtrise avancée</span>
</h3>
<div class="skills__cards">
<div class="skill-card" data-skill="html-css">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
</div>
<h4 class="skill-card__name">HTML / CSS</h4>
<p class="skill-card__desc">Structure visuelle, mise en page, animations, compatibilité tous appareils.</p>
</div>
<div class="skill-card" data-skill="php">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
</div>
<h4 class="skill-card__name">PHP</h4>
<p class="skill-card__desc">Développement côté serveur : gestion des données, authentification, formulaires, espaces membres.</p>
</div>
<div class="skill-card" data-skill="javascript">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="2"/><path d="M8 12h8M12 8v8"/></svg>
</div>
<h4 class="skill-card__name">JavaScript</h4>
<p class="skill-card__desc">Interactions, animations et éléments dynamiques côté navigateur.</p>
</div>
</div>
</div>
<!-- Bon niveau -->
<div class="skills__category reveal">
<h3 class="skills__category-title">
<span class="skills__category-badge skills__category-badge--solid">Bon niveau</span>
</h3>
<div class="skills__cards">
<div class="skill-card" data-skill="python">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>
</div>
<h4 class="skill-card__name">Python</h4>
<p class="skill-card__desc">Automatisation, traitement de données et développement d'outils utilitaires.</p>
</div>
<div class="skill-card" data-skill="sql">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg>
</div>
<h4 class="skill-card__name">SQL</h4>
<p class="skill-card__desc">Modélisation, création et gestion de bases de données relationnelles.</p>
</div>
<div class="skill-card" data-skill="linux">
<div class="skill-card__icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
</div>
<h4 class="skill-card__name">Linux / VPS</h4>
<p class="skill-card__desc">Administration serveur, déploiement et configuration d'environnements d'hébergement.</p>
</div>
</div>
</div>
</div>
<!-- Outils et méthodes -->
<div class="skills__tools reveal">
<h3 class="skills__tools-title">Outils &amp; méthodes</h3>
<div class="skills__tools-list">
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="5" r="2"/><circle cx="5" cy="19" r="2"/><circle cx="19" cy="19" r="2"/><path d="M12 7v5M12 12l-5.5 5M12 12l5.5 5"/></svg></span>
Git
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg></span>
VS Code
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 5.5A3.5 3.5 0 0 1 8.5 2H12v7H8.5A3.5 3.5 0 0 1 5 5.5z"/><path d="M12 2h3.5a3.5 3.5 0 1 1 0 7H12V2z"/><path d="M12 12.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 1 1-7 0z"/><path d="M5 19.5A3.5 3.5 0 0 1 8.5 16H12v3.5a3.5 3.5 0 1 1-7 0z"/></svg></span>
Figma
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/></svg></span>
MySQL
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg></span>
Terminal
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg></span>
Linux
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg></span>
SSH
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><path d="M2 14h20M6 18h.01M10 18h.01"/></svg></span>
VPS
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg></span>
Réseau
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2"/><rect x="2" y="7" width="4" height="10" rx="1"/><rect x="18" y="7" width="4" height="10" rx="1"/></svg></span>
Responsive Design
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></span>
SEO
</span>
<span class="tool-chip">
<span class="tool-chip__icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg></span>
Performance Web
</span>
</div>
</div>
</div>
</section>
<!-- ============================================ -->
<!-- PROJETS (conditionnel) -->
<!-- ============================================ -->
<?php if ($hasProjects): ?>
<section class="section projects" id="projects" aria-labelledby="projects-title">
<div class="container">
<div class="section__header">
<span class="section__number" aria-hidden="true">03</span>
<span class="section__label">Projets</span>
</div>
<h2 id="projects-title" class="section__title">Ce que j'ai construit</h2>
<p class="section__intro">Chaque projet présenté ici a été conçu et développé entièrement par mes soins — sans thème pré-acheté, sans constructeur de page. Du code écrit sur mesure, pour un résultat solide et durable.</p>
<div class="projects__grid">
<?php foreach ($projects as $project):
$badge = formatBadge($project['badge']);
$techs = parseTechnologies($project['technologies']);
?>
<article class="project-card reveal" aria-label="<?= htmlspecialchars($project['title'], ENT_QUOTES, 'UTF-8') ?>">
<?php if (!empty($project['image'])): ?>
<div class="project-card__image">
<img src="assets/img/projects/<?= htmlspecialchars($project['image'], ENT_QUOTES, 'UTF-8') ?>"
alt="<?= htmlspecialchars($project['title'], ENT_QUOTES, 'UTF-8') ?>"
loading="lazy" width="600" height="400">
<span class="project-card__badge <?= $badge['class'] ?>"><?= $badge['label'] ?></span>
</div>
<?php else: ?>
<div class="project-card__image project-card__image--placeholder">
<span class="project-card__badge <?= $badge['class'] ?>"><?= $badge['label'] ?></span>
</div>
<?php endif; ?>
<div class="project-card__body">
<h3 class="project-card__title"><?= htmlspecialchars($project['title'], ENT_QUOTES, 'UTF-8') ?></h3>
<p class="project-card__desc"><?= htmlspecialchars($project['short_description'], ENT_QUOTES, 'UTF-8') ?></p>
<?php if (!empty($techs)): ?>
<div class="project-card__techs">
<?php foreach ($techs as $tech): ?>
<span class="tag tag--sm"><?= htmlspecialchars($tech, ENT_QUOTES, 'UTF-8') ?></span>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if (!empty($project['project_url'])): ?>
<a href="<?= htmlspecialchars($project['project_url'], ENT_QUOTES, 'UTF-8') ?>"
class="project-card__link" target="_blank" rel="noopener noreferrer">
Voir le projet
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3"/></svg>
</a>
<?php endif; ?>
</div>
</article>
<?php endforeach; ?>
</div>
</div>
</section>
<?php endif; ?>
<!-- ============================================ -->
<!-- SERVICES -->
<!-- ============================================ -->
<section class="section services" id="services" aria-labelledby="services-title">
<div class="container">
<div class="section__header">
<span class="section__number" aria-hidden="true"><?= $hasProjects ? '04' : '03' ?></span>
<span class="section__label">Services</span>
</div>
<h2 id="services-title" class="section__title">Ce que je peux faire pour vous</h2>
<p class="section__intro">Que vous souhaitiez créer un site ou améliorer un existant, je commence par analyser votre situation avant de formuler la moindre proposition. Un échange d'abord, une solution adaptée ensuite — pas de devis générique.</p>
<div class="services__grid">
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
</div>
<h3 class="service-card__title">Site vitrine</h3>
<p class="service-card__desc">Un site professionnel qui représente votre activité avec précision. Design soigné, contenu structuré, conçu pour inciter vos visiteurs à vous contacter.</p>
</article>
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</div>
<h3 class="service-card__title">Refonte</h3>
<p class="service-card__desc">Votre site actuel est dépassé ou ne reflète plus votre activité ? Je le reprends dans son ensemble — structure, design et code — pour un résultat cohérent et performant.</p>
</article>
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
</div>
<h3 class="service-card__title">Maintenance</h3>
<p class="service-card__desc">Corrections, mises à jour, évolutions : je m'occupe de garder votre site fonctionnel, sécurisé et à jour dans la durée.</p>
</article>
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>
</div>
<h3 class="service-card__title">UI Design</h3>
<p class="service-card__desc">Des interfaces conçues pour que vos visiteurs trouvent l'information sans effort. Navigation claire, design cohérent, rendu soigné sur tous les supports.</p>
</article>
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 14h3M1 9h3M1 14h3"/></svg>
</div>
<h3 class="service-card__title">Back-end</h3>
<p class="service-card__desc">Développement côté serveur : formulaires, espaces membres, gestion de contenu, tableau de bord administrateur — tout ce qui structure le fonctionnement de votre site.</p>
</article>
<article class="service-card reveal">
<div class="service-card__icon" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
</div>
<h3 class="service-card__title">SEO</h3>
<p class="service-card__desc">Apparaître sur Google lorsqu'un client recherche votre activité. Structure technique optimisée, contenu pertinent, référencement naturel solide.</p>
</article>
</div>
<div class="services__cta">
<a href="#contact" class="btn btn--primary btn--lg">Un de ces besoins vous parle ? Je vous réponds sous 24h →</a>
</div>
</div>
</section>
<!-- ============================================ -->
<!-- CONTACT -->
<!-- ============================================ -->
<section class="section contact" id="contact" aria-labelledby="contact-title">
<div class="container">
<div class="section__header">
<span class="section__number" aria-hidden="true"><?= $hasProjects ? '05' : '04' ?></span>
<span class="section__label">Contact</span>
</div>
<h2 id="contact-title" class="section__title">Un projet en tête ? Même flou, même en deux lignes.</h2>
<p class="section__intro">Vous n'avez pas besoin d'un cahier des charges complet pour me contacter. Une idée, un besoin, une question suffisent. Je lis chaque message personnellement, je réponds sous 24h, et je vous donne un retour honnête sur votre situation — sans engagement de votre part.</p>
<div class="contact__grid">
<div class="contact__info reveal">
<div class="contact__info-card">
<h3 class="contact__info-title">Parlons de votre projet</h3>
<p class="contact__info-text">
Que vous ayez un projet défini ou simplement une question, n'hésitez pas à m'écrire. Je préfère un échange direct à un formulaire bâclé.
</p>
<div class="contact__process">
<p class="contact__process-title">Comment ça se passe ensuite ?</p>
<ol class="contact__process-list">
<li>Vous m'écrivez</li>
<li>On échange 20 minutes</li>
<li>Je vous propose une approche claire</li>
</ol>
</div>
<div class="contact__email">
<span class="contact__email-icon" aria-hidden="true">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
</span>
<a href="mailto:contact@tony-averty.dev" class="contact__email-link">contact@tony-averty.dev</a>
</div>
<div class="contact__response">
<span class="contact__response-icon" aria-hidden="true">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
</span>
<span>Réponse sous 24 à 48h</span>
</div>
</div>
</div>
<form class="contact__form reveal" id="contactForm" method="post" action="api/contact.php" novalidate<?= RECAPTCHA_ENABLED ? ' data-recaptcha-site="' . htmlspecialchars(RECAPTCHA_SITE_KEY, ENT_QUOTES, 'UTF-8') . '"' : '' ?>>
<!-- Token CSRF -->
<input type="hidden" name="csrf_token" value="<?= Security::csrfToken() ?>">
<!-- Honeypot anti-spam -->
<div class="form__honeypot" aria-hidden="true">
<label for="website" aria-hidden="true">Ne pas remplir</label>
<input type="text" name="website" id="website" tabindex="-1" autocomplete="off" aria-hidden="true">
</div>
<div class="form__group">
<label for="name" class="form__label">Nom complet</label>
<input type="text" id="name" name="name" class="form__input" required minlength="2" maxlength="255" autocomplete="name" placeholder="Votre nom">
</div>
<div class="form__group">
<label for="email" class="form__label">Email</label>
<input type="email" id="email" name="email" class="form__input" required maxlength="255" autocomplete="email" placeholder="votre@email.com">
</div>
<div class="form__group">
<label for="subject" class="form__label">Sujet <span class="form__optional">(optionnel)</span></label>
<input type="text" id="subject" name="subject" class="form__input" maxlength="255" placeholder="De quoi s'agit-il ?">
</div>
<div class="form__group">
<label for="message" class="form__label">Message</label>
<textarea id="message" name="message" class="form__input form__textarea" required minlength="10" maxlength="5000" rows="5" placeholder="Décrivez votre projet, votre besoin ou votre question..."></textarea>
</div>
<div class="form__group form__group--captcha">
<label for="captcha" class="form__label">
Vérification anti-spam
<span class="form__captcha-question" aria-label="Question : <?= htmlspecialchars($captchaQuestion, ENT_QUOTES, 'UTF-8') ?>">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
<?= htmlspecialchars($captchaQuestion, ENT_QUOTES, 'UTF-8') ?>
</span>
</label>
<input type="number" id="captcha" name="captcha" class="form__input form__input--captcha"
required inputmode="numeric" min="0" max="20"
placeholder="Votre réponse" autocomplete="off">
</div>
<button type="submit" class="btn btn--primary btn--lg form__submit" id="formSubmit">
<span class="form__submit-text">Envoyer mon message</span>
<span class="form__submit-loader" aria-hidden="true">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>
</span>
</button>
<?php if (RECAPTCHA_ENABLED): ?>
<p class="form__recaptcha-note">
Ce site est protégé par reCAPTCHA. La
<a href="https://policies.google.com/privacy" target="_blank" rel="noopener">politique de confidentialité</a>
et les
<a href="https://policies.google.com/terms" target="_blank" rel="noopener">conditions d'utilisation</a>
de Google s'appliquent.
</p>
<?php endif; ?>
</form>
</div>
</div>
</section>
</main>
<?php require_once __DIR__ . '/includes/footer.php'; ?>

433
legal.php Normal file
View file

@ -0,0 +1,433 @@
<?php
/**
* Mentions légales, Politique de confidentialité & Cookies
* Portfolio Tony AVERTY — CodeBzh
*/
require_once __DIR__ . '/includes/Security.php';
Security::bootstrap();
?>
<!DOCTYPE html>
<html lang="fr" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, follow">
<meta name="description" content="Mentions légales, politique de confidentialité et informations sur l'utilisation des cookies du site tony-averty.dev.">
<title>Mentions légales &amp; RGPD — Tony AVERTY</title>
<link rel="stylesheet" href="assets/css/style.css">
<style nonce="<?= Security::cspNonce() ?>">
.legal-page {
min-height: 100vh;
padding: var(--space-3xl) 0;
}
.legal-page .container {
max-width: 820px;
}
.legal-page__back {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: var(--text-secondary);
text-decoration: none;
margin-bottom: var(--space-2xl);
transition: color .2s;
}
.legal-page__back:hover { color: var(--accent); }
.legal-page__title {
font-size: clamp(1.75rem, 4vw, 2.5rem);
font-weight: 800;
color: var(--text-primary);
margin-bottom: 0.25rem;
}
.legal-page__subtitle {
font-size: 0.9rem;
color: var(--text-secondary);
margin-bottom: var(--space-2xl);
}
.legal-nav {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: var(--space-2xl);
padding-bottom: var(--space-lg);
border-bottom: 1px solid var(--border);
}
.legal-nav a {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-secondary);
text-decoration: none;
padding: 0.35rem 0.85rem;
border-radius: 100px;
border: 1px solid var(--border);
background: var(--bg-secondary);
transition: all .2s;
}
.legal-nav a:hover {
color: var(--accent);
border-color: var(--accent);
background: var(--accent-subtle);
}
.legal-section {
margin-bottom: var(--space-3xl);
scroll-margin-top: 90px;
}
.legal-section__title {
font-size: 1.3rem;
font-weight: 700;
color: var(--text-primary);
margin-bottom: var(--space-lg);
padding-bottom: 0.6rem;
border-bottom: 2px solid var(--accent);
display: inline-block;
}
.legal-section h3 {
font-size: 1rem;
font-weight: 700;
color: var(--text-primary);
margin: var(--space-lg) 0 var(--space-sm);
}
.legal-section p,
.legal-section li {
font-size: 0.93rem;
line-height: 1.75;
color: var(--text-secondary);
}
.legal-section ul {
padding-left: 1.2rem;
margin: var(--space-sm) 0;
}
.legal-section li { margin-bottom: 0.3rem; }
.legal-table {
width: 100%;
border-collapse: collapse;
font-size: 0.88rem;
margin: var(--space-md) 0;
}
.legal-table th,
.legal-table td {
text-align: left;
padding: 0.6rem 0.8rem;
border: 1px solid var(--border);
color: var(--text-secondary);
}
.legal-table th {
background: var(--bg-secondary);
font-weight: 600;
color: var(--text-primary);
}
.legal-badge {
display: inline-block;
font-size: 0.72rem;
font-weight: 700;
padding: 0.2rem 0.6rem;
border-radius: 100px;
background: var(--accent-subtle);
color: var(--accent);
margin-bottom: var(--space-md);
}
.legal-highlight {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-left: 3px solid var(--accent);
border-radius: 0 8px 8px 0;
padding: var(--space-md) var(--space-lg);
margin: var(--space-md) 0;
}
.legal-highlight p { margin: 0; }
.legal-contact-block {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
padding: var(--space-lg);
margin-top: var(--space-md);
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-md);
}
@media (max-width: 600px) {
.legal-contact-block { grid-template-columns: 1fr; }
}
.legal-contact-block dt {
font-size: 0.75rem;
font-weight: 700;
color: var(--text-tertiary, var(--text-secondary));
text-transform: uppercase;
letter-spacing: 0.06em;
margin-bottom: 0.2rem;
}
.legal-contact-block dd {
font-size: 0.9rem;
color: var(--text-secondary);
margin: 0 0 var(--space-md);
}
.legal-contact-block dd:last-child { margin-bottom: 0; }
.legal-contact-block a { color: var(--accent); text-decoration: none; }
.legal-contact-block a:hover { text-decoration: underline; }
</style>
</head>
<body>
<?php require_once __DIR__ . '/includes/header.php'; ?>
<main class="legal-page" id="main">
<div class="container">
<a href="/" class="legal-page__back">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
Retour au portfolio
</a>
<h1 class="legal-page__title">Informations légales</h1>
<p class="legal-page__subtitle">Dernière mise à jour : <?= date('d/m/Y') ?></p>
<nav class="legal-nav" aria-label="Sommaire">
<a href="#mentions">Mentions légales</a>
<a href="#confidentialite">Confidentialité</a>
<a href="#cookies">Cookies &amp; Stockage</a>
</nav>
<!-- ══════════════════════════════════════════
1. MENTIONS LÉGALES
══════════════════════════════════════════ -->
<section class="legal-section" id="mentions" aria-labelledby="title-mentions">
<h2 class="legal-section__title" id="title-mentions">Mentions légales</h2>
<h3>Éditeur du site</h3>
<dl class="legal-contact-block">
<div>
<dt>Nom</dt>
<dd>Tony AVERTY</dd>
</div>
<div>
<dt>Statut</dt>
<dd>Auto-entrepreneur</dd>
</div>
<div>
<dt>Enseigne commerciale</dt>
<dd>CodeBzh</dd>
</div>
<div>
<dt>SIRET (CodeBzh)</dt>
<dd>100 142 819 00018</dd>
</div>
<div>
<dt>Adresse</dt>
<dd>Disponible sur demande</dd>
</div>
<div>
<dt>Contact</dt>
<dd><a href="mailto:contact@tony-averty.dev">contact@tony-averty.dev</a></dd>
</div>
</dl>
<h3>Hébergeur</h3>
<dl class="legal-contact-block">
<div>
<dt>Société</dt>
<dd>ELYPSECLOUD</dd>
</div>
<div>
<dt>SIRET</dt>
<dd>978 470 680 00015</dd>
</div>
<div>
<dt>Adresse</dt>
<dd>29 Rue Lebrix Mesmin<br>33700 Mérignac, France</dd>
</div>
<div>
<dt>Type d'hébergement</dt>
<dd>Serveur privé virtuel (VPS) auto-géré</dd>
</div>
</dl>
<h3>Propriété intellectuelle</h3>
<p>L'ensemble des contenus présents sur ce site (textes, visuels, code, structure) est la propriété exclusive de Tony AVERTY sauf mention contraire. Toute reproduction, même partielle, est interdite sans accord préalable.</p>
<h3>Responsabilité</h3>
<p>Les informations publiées sur ce site sont fournies à titre indicatif. Tony AVERTY s'efforce de les maintenir à jour mais ne peut garantir leur exactitude ou exhaustivité. Tony AVERTY ne saurait être tenu responsable des dommages directs ou indirects résultant de l'utilisation de ce site.</p>
</section>
<!-- ══════════════════════════════════════════
2. POLITIQUE DE CONFIDENTIALITÉ
══════════════════════════════════════════ -->
<section class="legal-section" id="confidentialite" aria-labelledby="title-confidentialite">
<h2 class="legal-section__title" id="title-confidentialite">Politique de confidentialité</h2>
<span class="legal-badge">RGPD — Règlement (UE) 2016/679</span>
<h3>Responsable du traitement</h3>
<p>Tony AVERTY (CodeBzh) — <a href="mailto:contact@tony-averty.dev" style="color:var(--accent)">contact@tony-averty.dev</a></p>
<h3>Données traitées</h3>
<h4 style="font-size:.88rem;font-weight:600;color:var(--text-primary);margin:.8rem 0 .4rem;">Formulaire de contact</h4>
<table class="legal-table">
<thead>
<tr>
<th>Donnée</th>
<th>Finalité</th>
<th>Base légale</th>
<th>Durée de conservation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nom, prénom</td>
<td>Identifier l'expéditeur du message</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>3 ans</td>
</tr>
<tr>
<td>Adresse e-mail</td>
<td>Répondre au message</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>3 ans</td>
</tr>
<tr>
<td>Sujet &amp; message</td>
<td>Traiter la demande</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>3 ans</td>
</tr>
</tbody>
</table>
<h4 style="font-size:.88rem;font-weight:600;color:var(--text-primary);margin:.8rem 0 .4rem;">Analytics internes (sans cookie)</h4>
<table class="legal-table">
<thead>
<tr>
<th>Donnée</th>
<th>Finalité</th>
<th>Base légale</th>
<th>Durée de conservation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adresse IP (hachée SHA-256, non réversible)</td>
<td>Comptage de sessions uniques</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>13 mois glissants</td>
</tr>
<tr>
<td>Type d'appareil</td>
<td>Statistiques d'usage (mobile / desktop)</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>13 mois glissants</td>
</tr>
<tr>
<td>Page visitée, référent</td>
<td>Comprendre les sources de trafic</td>
<td>Intérêt légitime (art. 6.1.f RGPD)</td>
<td>13 mois glissants</td>
</tr>
</tbody>
</table>
<div class="legal-highlight">
<p>Les analytics sont 100&nbsp;% auto-hébergés sur le VPS d'ELYPSECLOUD (France). Aucune donnée n'est transmise à des tiers (Google, Meta, etc.). L'adresse IP n'est jamais stockée en clair — elle est hachée avant tout enregistrement.</p>
</div>
<h3>Vos droits (RGPD art. 15 à 22)</h3>
<ul>
<li><strong>Droit d'accès</strong> — obtenir une copie de vos données</li>
<li><strong>Droit de rectification</strong> — corriger des données inexactes</li>
<li><strong>Droit à l'effacement</strong> — demander la suppression de vos données</li>
<li><strong>Droit d'opposition</strong> — vous opposer à un traitement fondé sur l'intérêt légitime</li>
<li><strong>Droit à la portabilité</strong> — recevoir vos données dans un format structuré</li>
<li><strong>Droit de limitation</strong> — suspendre temporairement un traitement</li>
</ul>
<p>Pour exercer ces droits, contactez : <a href="mailto:contact@tony-averty.dev" style="color:var(--accent)">contact@tony-averty.dev</a>. Réponse sous 30 jours.</p>
<p>Si vous estimez que vos droits ne sont pas respectés, vous pouvez introduire une réclamation auprès de la <strong>CNIL</strong> (<a href="https://www.cnil.fr" target="_blank" rel="noopener noreferrer" style="color:var(--accent)">cnil.fr</a>).</p>
<h3>Sécurité des données</h3>
<p>Les données sont hébergées sur un serveur privé. L'accès au back-office est protégé par authentification avec limitation des tentatives. Les échanges sont chiffrés via HTTPS (TLS). Aucun mot de passe n'est stocké en clair.</p>
</section>
<!-- ══════════════════════════════════════════
3. COOKIES & STOCKAGE LOCAL
══════════════════════════════════════════ -->
<section class="legal-section" id="cookies" aria-labelledby="title-cookies">
<h2 class="legal-section__title" id="title-cookies">Cookies &amp; Stockage local</h2>
<h3>Cookies déposés</h3>
<table class="legal-table">
<thead>
<tr>
<th>Nom</th>
<th>Type</th>
<th>Finalité</th>
<th>Durée</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>PHPSESSID</code></td>
<td>Strictement nécessaire</td>
<td>Gestion de la session sécurisée (CSRF, CAPTCHA, protection anti-spam)</td>
<td>Session (supprimé à la fermeture du navigateur)</td>
</tr>
</tbody>
</table>
<div class="legal-highlight">
<p>Le cookie de session <code>PHPSESSID</code> est strictement nécessaire au fonctionnement du formulaire de contact (protection CSRF et CAPTCHA). Il ne peut pas être désactivé. Aucun consentement n'est requis pour les cookies strictement nécessaires (directive ePrivacy 2002/58/CE, art. 5.3).</p>
</div>
<h3>Stockage local (localStorage / sessionStorage)</h3>
<p>Ce site utilise le <strong>stockage local du navigateur</strong> (localStorage) pour mémoriser vos préférences visuelles (thème, animations, FPS, curseur). Ces données ne quittent jamais votre appareil, ne sont pas transmises au serveur et ne constituent pas des cookies au sens de la directive ePrivacy. Aucun consentement n'est requis.</p>
<table class="legal-table">
<thead>
<tr>
<th>Clé localStorage</th>
<th>Contenu</th>
<th>Transmis au serveur ?</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>theme</code></td>
<td>Préférence de thème (clair / sombre)</td>
<td>Non</td>
</tr>
<tr>
<td><code>cursorEnabled</code></td>
<td>Activation du curseur personnalisé</td>
<td>Non</td>
</tr>
<tr>
<td><code>animationsEnabled</code></td>
<td>Activation des animations CSS</td>
<td>Non</td>
</tr>
<tr>
<td><code>smoothScroll</code></td>
<td>Activation du défilement lisse</td>
<td>Non</td>
</tr>
<tr>
<td><code>targetFPS</code></td>
<td>FPS cible sélectionné</td>
<td>Non</td>
</tr>
</tbody>
</table>
<h3>Cookies tiers</h3>
<p>Ce site ne dépose <strong>aucun cookie tiers</strong>. Aucun outil de tracking externe (Google Analytics, Meta Pixel, Hotjar, etc.) n'est utilisé. Les polices d'écriture sont auto-hébergées sur le VPS — aucune requête n'est envoyée vers Google Fonts ou un CDN externe.</p>
<h3>Pas de bandeau cookies</h3>
<p>Conformément aux recommandations de la CNIL (délibération n°2020-091), un bandeau de consentement aux cookies n'est pas requis lorsque les seuls cookies présents sont strictement nécessaires au service. C'est le cas de ce site.</p>
</section>
</div>
</main>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

View file

@ -0,0 +1,203 @@
-- ============================================
-- Migration 001 — Backoffice complet
-- Portfolio Tony AVERTY
-- ============================================
-- Usage : mysql -u root -p portfoliotony < 001_backoffice.sql
-- (remplacer "portfoliotony" par le nom réel de ta base)
-- ============================================
-- ── Administrateurs ───────────────────────────────────────
-- Le mot de passe est créé via setup.php (hash bcrypt)
CREATE TABLE IF NOT EXISTS admins (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- ── Messages du formulaire de contact ─────────────────────
CREATE TABLE IF NOT EXISTS contact_messages (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sender_name VARCHAR(255) NOT NULL,
sender_email VARCHAR(255) NOT NULL,
subject VARCHAR(255) DEFAULT NULL,
message TEXT NOT NULL,
is_read TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_msg_read (is_read),
INDEX idx_msg_date (created_at)
) ENGINE=InnoDB;
-- ── Réponses aux messages (thread email backoffice) ────────
CREATE TABLE IF NOT EXISTS message_replies (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id INT UNSIGNED NOT NULL,
reply_text TEXT NOT NULL,
sent_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_replies_msg (message_id)
) ENGINE=InnoDB;
-- ── Rate limiting (anti-spam / brute force) ───────────────
CREATE TABLE IF NOT EXISTS rate_limits (
id INT AUTO_INCREMENT PRIMARY KEY,
action VARCHAR(64) NOT NULL,
ip VARCHAR(45) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_action_ip_time (action, ip, created_at)
) ENGINE=InnoDB;
-- ── Projets (portfolio) ───────────────────────────────────
CREATE TABLE IF NOT EXISTS projects (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
short_description VARCHAR(500) DEFAULT NULL,
full_description TEXT DEFAULT NULL,
image VARCHAR(500) DEFAULT NULL,
badge ENUM('production', 'development') NOT NULL DEFAULT 'development',
technologies TEXT DEFAULT NULL,
project_url VARCHAR(500) DEFAULT NULL,
status ENUM('published', 'draft') NOT NULL DEFAULT 'draft',
display_order INT UNSIGNED NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_projects_status (status),
INDEX idx_projects_order (display_order)
) ENGINE=InnoDB;
-- ── Tracking des visites ──────────────────────────────────
CREATE TABLE IF NOT EXISTS visits (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ip_hash VARCHAR(64) NOT NULL,
session_id VARCHAR(64) NOT NULL,
page VARCHAR(500) NOT NULL DEFAULT '/',
referrer VARCHAR(500) DEFAULT NULL,
device_type ENUM('desktop', 'mobile', 'tablet') NOT NULL DEFAULT 'desktop',
duration_s INT UNSIGNED DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_visits_date (created_at),
INDEX idx_visits_session (session_id),
INDEX idx_visits_page (page(100))
) ENGINE=InnoDB;
-- ── Clics sur les projets ─────────────────────────────────
CREATE TABLE IF NOT EXISTS project_clicks (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
project_id INT UNSIGNED NOT NULL,
ip_hash VARCHAR(64) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_clicks_project (project_id),
INDEX idx_clicks_date (created_at)
) ENGINE=InnoDB;
-- ── Services (éditable depuis le backoffice) ──────────────
CREATE TABLE IF NOT EXISTS services (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
icon VARCHAR(10) NOT NULL DEFAULT '🚀',
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
display_order INT UNSIGNED NOT NULL DEFAULT 0,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_services_order (display_order)
) ENGINE=InnoDB;
-- ── Contenu du site (clé/valeur) ──────────────────────────
CREATE TABLE IF NOT EXISTS site_content (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
content_key VARCHAR(100) NOT NULL UNIQUE,
content_value MEDIUMTEXT DEFAULT NULL,
content_type ENUM('text', 'textarea', 'html') NOT NULL DEFAULT 'text',
label VARCHAR(255) NOT NULL,
section VARCHAR(100) NOT NULL DEFAULT 'general',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_content_section (section)
) ENGINE=InnoDB;
-- ── Paramètres globaux ────────────────────────────────────
CREATE TABLE IF NOT EXISTS site_settings (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
setting_key VARCHAR(100) NOT NULL UNIQUE,
setting_value TEXT DEFAULT NULL,
label VARCHAR(255) NOT NULL DEFAULT '',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- ── Tentatives de connexion (brute force) ─────────────────
CREATE TABLE IF NOT EXISTS login_attempts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ip VARCHAR(45) NOT NULL,
username VARCHAR(100) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_attempts_ip_date (ip, created_at)
) ENGINE=InnoDB;
-- ── Logs des actions admin ────────────────────────────────
CREATE TABLE IF NOT EXISTS admin_logs (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
admin_id INT UNSIGNED DEFAULT NULL,
username VARCHAR(100) DEFAULT NULL,
action VARCHAR(100) NOT NULL,
detail TEXT DEFAULT NULL,
ip VARCHAR(45) NOT NULL,
success TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_logs_date (created_at),
INDEX idx_logs_admin (admin_id)
) ENGINE=InnoDB;
-- ── Données par défaut : Services ─────────────────────────
INSERT IGNORE INTO services (icon, title, description, display_order) VALUES
('🌐', 'Site vitrine & portfolio', 'Un site professionnel qui reflète votre activité et donne envie de vous contacter. Design soigné, contenu structuré, référencement local intégré.', 1),
('🛒', 'E-commerce & boutique en ligne', 'De la boutique simple au catalogue complet, avec paiement sécurisé, gestion des stocks et interface admin intuitive.', 2),
('⚙️', 'Application web sur mesure', 'Outils métiers, espaces clients, tableaux de bord, automatisations — développés exactement pour votre usage, pas plus, pas moins.', 3),
('🔍', 'SEO & optimisation', 'Audit, structure, contenu et vitesse optimisés pour que Google vous trouve — et surtout, vos clients locaux aussi.', 4),
('🔧', 'Maintenance & évolution', 'Mises à jour, corrections, nouvelles fonctionnalités — votre site reste en bonne santé et évolue avec votre activité.', 5),
('📱', 'Refonte & modernisation', 'Votre site est vieillissant ? Je le remets à niveau : design, performance, responsive et standards modernes.', 6);
-- ── Données par défaut : Contenu ──────────────────────────
INSERT IGNORE INTO site_content (content_key, content_value, content_type, label, section) VALUES
-- SEO
('seo_title', 'Tony AVERTY — Développeur Web Freelance | Sites sur mesure & Applications', 'text', 'Balise <title>', 'seo'),
('seo_description', 'Développeur web freelance basé en Bretagne. Je crée des sites et applications sur mesure, livrés en moins de 24h de délai de réponse. Fondateur de CodeBzh.', 'textarea', 'Meta description', 'seo'),
('seo_og_title', 'Tony AVERTY — Développeur Web Freelance', 'text', 'OG Title (réseaux sociaux)', 'seo'),
('seo_og_description', 'Sites et applications sur mesure. Réponse en 24h. Fondateur de CodeBzh.', 'textarea', 'OG Description', 'seo'),
-- Hero
('hero_badge', 'Disponible pour nouveaux projets', 'text', 'Badge disponibilité', 'hero'),
('hero_line1', 'Du code propre.', 'text', 'Titre ligne 1', 'hero'),
('hero_line2', 'Des interfaces claires.', 'text', 'Titre ligne 2', 'hero'),
('hero_line3', 'Des projets qui tiennent.', 'text', 'Titre ligne 3 (accentuée)', 'hero'),
('hero_subtitle', 'Je suis Tony AVERTY — développeur web freelance et fondateur de CodeBzh. Je conçois des sites et applications sur mesure : bien structurés, bien pensés, construits pour servir votre activité sur le long terme.', 'textarea', 'Sous-titre', 'hero'),
('hero_cta_primary', 'Parlons de votre projet →', 'text', 'CTA principal', 'hero'),
('hero_cta_secondary', 'Voir ce que j\'ai construit', 'text', 'CTA secondaire', 'hero'),
-- À propos
('about_title', 'Développeur web freelance, basé en Bretagne.', 'text', 'Titre section', 'about'),
('about_text', 'Je construis des sites et applications web depuis plusieurs années. Mon approche : du code propre, des interfaces pensées pour l\'utilisateur, et un accompagnement direct sans intermédiaire.\n\nPas d\'agence, pas de sous-traitant. Vous travaillez directement avec moi, du brief à la mise en ligne.', 'textarea', 'Texte principal', 'about'),
('about_stat1_value', '5+', 'text', 'Stat 1 — Valeur', 'about'),
('about_stat1_label', 'Années d\'expérience', 'text', 'Stat 1 — Label', 'about'),
('about_stat2_value', '30+', 'text', 'Stat 2 — Valeur', 'about'),
('about_stat2_label', 'Projets livrés', 'text', 'Stat 2 — Label', 'about'),
('about_stat3_value', '24h', 'text', 'Stat 3 — Valeur', 'about'),
('about_stat3_label', 'Délai de réponse garanti', 'text', 'Stat 3 — Label', 'about'),
-- Contact
('contact_title', 'Un projet en tête ?', 'text', 'Titre section', 'contact'),
('contact_subtitle', 'Parlez-moi de votre projet. Je vous réponds sous 24h pour un premier échange sans engagement.', 'textarea', 'Sous-titre', 'contact'),
('contact_email', 'contact@tonyaverty.fr', 'text', 'Email affiché', 'contact'),
('contact_phone', '', 'text', 'Téléphone affiché', 'contact'),
('contact_location', 'Bretagne, France', 'text', 'Localisation affichée', 'contact'),
-- Footer
('footer_tagline', 'Développeur web freelance', 'text', 'Tagline footer', 'footer'),
('footer_tagline_sub', 'Fondateur de CodeBzh · Disponible pour nouveaux projets', 'text', 'Sous-tagline footer', 'footer');
-- ── Données par défaut : Paramètres ──────────────────────
INSERT IGNORE INTO site_settings (setting_key, setting_value, label) VALUES
('site_name', 'Portfolio Tony AVERTY', 'Nom du site'),
('owner_name', 'Tony AVERTY', 'Nom du propriétaire'),
('owner_email', 'contact@tonyaverty.fr', 'Email principal'),
('notify_email', 'contact@tony-averty.dev', 'Email de notification (contact form)'),
('availability', '1', 'Disponible pour nouveaux projets (1=oui, 0=non)'),
('maintenance_mode', '0', 'Mode maintenance (1=activé)'),
('google_analytics_id', '', 'Google Analytics ID (optionnel)'),
('site_url', 'https://tonyaverty.fr', 'URL du site');

View file

@ -0,0 +1,24 @@
-- ============================================
-- Migration 002 — Threading email entrant
-- Portfolio Tony AVERTY
-- ============================================
-- Usage : mysql -u root -p portfoliotony < 002_email_threading.sql
-- ============================================
-- ── Table des Message-ID envoyés ──────────────────────────
-- Permet de faire le lien IMAP : In-Reply-To → contact_message
CREATE TABLE IF NOT EXISTS sent_message_ids (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id VARCHAR(255) NOT NULL,
contact_message_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_message_id (message_id),
INDEX idx_smid_contact (contact_message_id)
) ENGINE=InnoDB;
-- ── Ajout des colonnes de threading sur message_replies ───
-- direction : 'out' = envoyé depuis le BO | 'in' = reçu du client via IMAP
-- (ignorer les erreurs si les colonnes existent déjà)
ALTER TABLE message_replies ADD COLUMN direction ENUM('out','in') NOT NULL DEFAULT 'out' AFTER reply_text;
ALTER TABLE message_replies ADD COLUMN sender_email VARCHAR(255) DEFAULT NULL AFTER direction;
ALTER TABLE message_replies ADD COLUMN message_id_sent VARCHAR(255) DEFAULT NULL AFTER sender_email;

64
sql/schema.sql Normal file
View file

@ -0,0 +1,64 @@
-- ============================================
-- Portfolio Tony AVERTY — Schéma de base de données
-- ============================================
CREATE DATABASE IF NOT EXISTS portfolio_tony
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
USE portfolio_tony;
-- ============================================
-- Table des projets
-- ============================================
CREATE TABLE IF NOT EXISTS projects (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
short_description VARCHAR(500) NOT NULL,
full_description TEXT,
image VARCHAR(255) DEFAULT NULL,
status ENUM('draft', 'published') NOT NULL DEFAULT 'draft',
badge ENUM('development', 'production') NOT NULL DEFAULT 'development',
technologies VARCHAR(500) DEFAULT NULL,
project_url VARCHAR(500) DEFAULT NULL,
display_order INT UNSIGNED NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- Index pour les requêtes fréquentes
CREATE INDEX idx_projects_status ON projects(status);
CREATE INDEX idx_projects_order ON projects(display_order);
-- ============================================
-- Table admin (authentification BackOffice)
-- ============================================
CREATE TABLE IF NOT EXISTS admins (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- ============================================
-- Table messages de contact
-- ============================================
CREATE TABLE IF NOT EXISTS contact_messages (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sender_name VARCHAR(255) NOT NULL,
sender_email VARCHAR(255) NOT NULL,
subject VARCHAR(255) DEFAULT NULL,
message TEXT NOT NULL,
is_read TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
-- ============================================
-- Insertion admin par défaut (mot de passe : à changer)
-- password_hash = password_hash('admin', PASSWORD_DEFAULT)
-- ============================================
INSERT INTO admins (username, password_hash) VALUES (
'tony',
'$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'
);

125
vhost.txt Normal file
View file

@ -0,0 +1,125 @@
server {
listen 80;
listen [::]:80;
listen 443 quic;
listen 443 ssl;
listen [::]:443 quic;
listen [::]:443 ssl;
http2 on;
http3 off;
{{ssl_certificate_key}}
{{ssl_certificate}}
server_name www.tony-averty.dev;
return 301 https://tony-averty.dev$request_uri;
}
server {
listen 80;
listen [::]:80;
listen 443 quic;
listen 443 ssl;
listen [::]:443 quic;
listen [::]:443 ssl;
http2 on;
http3 off;
{{ssl_certificate_key}}
{{ssl_certificate}}
server_name tony-averty.dev www1.tony-averty.dev;
{{root}}
{{nginx_access_log}}
{{nginx_error_log}}
if ($scheme != "https") {
rewrite ^ https://$host$request_uri permanent;
}
location ~ /.well-known {
auth_basic off;
allow all;
}
{{settings}}
location / {
{{varnish_proxy_pass}}
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_hide_header X-Varnish;
proxy_redirect off;
proxy_max_temp_file_size 0;
proxy_connect_timeout 720;
proxy_send_timeout 720;
proxy_read_timeout 720;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
}
location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map|mjs)$ {
add_header Access-Control-Allow-Origin "*";
add_header alt-svc 'h3=":443"; ma=86400';
expires max;
access_log off;
}
location ~ /\.(ht|svn|git) {
deny all;
}
if (-f $request_filename) {
break;
}
}
server {
listen 8080;
listen [::]:8080;
server_name tony-averty.dev www1.tony-averty.dev;
{{root}}
include /etc/nginx/global_settings;
try_files $uri $uri/ =404;
index index.php index.html;
error_page 403 /errors/403.php;
error_page 404 /errors/404.php;
error_page 500 502 503 504 /errors/500.php;
location ^~ /errors/ {
internal;
location ~ \.php$ {
include fastcgi_params;
fastcgi_intercept_errors off;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_read_timeout 3600;
fastcgi_send_timeout 3600;
fastcgi_param HTTPS "on";
fastcgi_param SERVER_PORT 443;
fastcgi_pass 127.0.0.1:{{php_fpm_port}};
fastcgi_param PHP_VALUE "{{php_settings}}";
}
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_intercept_errors on;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files $uri =404;
fastcgi_read_timeout 3600;
fastcgi_send_timeout 3600;
fastcgi_param HTTPS "on";
fastcgi_param SERVER_PORT 443;
fastcgi_pass 127.0.0.1:{{php_fpm_port}};
fastcgi_param PHP_VALUE "{{php_settings}}";
}
if (-f $request_filename) {
break;
}
}