commit 87957dd70650d73a0159bb979ece145afec5eb5f Author: Tony AVERTY Date: Thu Sep 3 13:27:06 2026 +0200 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e5d77f6 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..4a940dc --- /dev/null +++ b/.htaccess @@ -0,0 +1,54 @@ +Options -Indexes -MultiViews +ServerSignature Off + + + 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] + + + + Require all denied + + + + Require all denied + + + + 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 + + + + 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 + + + + 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 + diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c1c0bd2 --- /dev/null +++ b/AGENTS.md @@ -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. diff --git a/Claude.md b/Claude.md new file mode 100644 index 0000000..fbf3291 --- /dev/null +++ b/Claude.md @@ -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. diff --git a/admin/.htaccess b/admin/.htaccess new file mode 100644 index 0000000..5a81a9a --- /dev/null +++ b/admin/.htaccess @@ -0,0 +1,15 @@ +# ── Admin : headers + PHP sécurisé ────────────────────────── + + 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 + + +# Bloquer tout accès direct aux includes du BO + + RewriteEngine On + RewriteRule ^includes/ - [F,L] + diff --git a/admin/analytics.php b/admin/analytics.php new file mode 100644 index 0000000..93b44e9 --- /dev/null +++ b/admin/analytics.php @@ -0,0 +1,276 @@ + 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'; +} +?> + + + + + + + Analytics — BackOffice Tony AVERTY + + + +
+ + +
+
+

Analytics

+
+ '7j', 30 => '30j', 90 => '90j'] as $d => $label): ?> + + + + +
+
+ + +
+
+
+ +
+
+ + Visites totales (j) +
+
+
+
+ +
+
+ + Sessions uniques +
+
+
+
+ +
+
+ + Durée moyenne +
+
+
+ + +
+
+

Visites / jour (j)

+
+
+
+

Appareils

+
+
+
+ + +
+
+

Heures de pointe

+
+
+
+ + +
+ +
+

Pages les plus visitées

+ +

Aucune donnée.

+ + + + + + + + + + + +
PageVisites
+ +
+ + +
+

Sources de trafic

+ +

Aucune donnée.

+ + + + + + + + + + + +
ReferrerVisites
+ +
+ + + +
+

Projets les plus cliqués

+ + + + + + + + + + +
ProjetClics
+
+ +
+
+
+ + + + + diff --git a/admin/assets/admin.css b/admin/assets/admin.css new file mode 100644 index 0000000..3ef1bce --- /dev/null +++ b/admin/assets/admin.css @@ -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; } +} diff --git a/admin/content.php b/admin/content.php new file mode 100644 index 0000000..261624a --- /dev/null +++ b/admin/content.php @@ -0,0 +1,179 @@ + 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', +]; +?> + + + + + + + Contenu & SEO — BackOffice Tony AVERTY + + + +
+ + +
+
+

Contenu & SEO

+ Tous les textes visibles sur le site +
+ + +
+ + +
+ + +
+ $secLabel): ?> + + + +
+ + $secLabel): ?> + +
+
+

+ + +
+ + + + + + + + + + + + + +

+ / 160 caractères +

+ + +

+ / 65 caractères +

+ +
+ +
+
+ + +
+ +
+
+
+
+ + + + diff --git a/admin/dashboard.php b/admin/dashboard.php new file mode 100644 index 0000000..f8fb618 --- /dev/null +++ b/admin/dashboard.php @@ -0,0 +1,317 @@ + 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'; +} +?> + + + + + + + Dashboard — BackOffice Tony AVERTY + + + +
+ + +
+
+

Dashboard

+ +
+ + +
+
+
+ +
+
+ + Visites aujourd'hui +
+
+ +
+
+ +
+
+ + Visites ce mois +
+
+ +
+
+ +
+
+ + Temps moyen / visite +
+
+ +
+
+ +
+
+ + + 0): ?> + Voir + + + Messages non lus +
+
+ +
+
+ +
+
+ + Visites totales +
+
+ +
+
+ +
+
+ + Projets publiés +
+
+
+ + +
+
+

Visites — 30 derniers jours

+
+ +
+
+ +
+

Appareils

+
+ +
+
+
+ + +
+
+

Projets les plus cliqués (30j)

+
+ +
+
+
+ + + +
+
+

Derniers messages

+ Tous les messages +
+ + +

Aucun message reçu.

+ +
+ + + + + + + + + + + + + + +
ExpéditeurSujetDateStatut
+
+ +
+ + Non lu + + Lu + +
+
+ +
+
+
+ + + + + diff --git a/admin/includes/nav.php b/admin/includes/nav.php new file mode 100644 index 0000000..fbaf22a --- /dev/null +++ b/admin/includes/nav.php @@ -0,0 +1,76 @@ +query('SELECT COUNT(*) FROM contact_messages WHERE is_read = 0')->fetchColumn(); +} catch (Throwable) { +} + +$currentPage = basename($_SERVER['PHP_SELF']); +?> + diff --git a/admin/index.php b/admin/index.php new file mode 100644 index 0000000..422d8e0 --- /dev/null +++ b/admin/index.php @@ -0,0 +1,192 @@ + 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(); +?> + + + + + + + Projets — BackOffice Tony AVERTY + + + +
+ + +
+
+

Projets

+ + Nouveau projet +
+ + +
+ + + +
+
+

Aucun projet pour le moment.

+ Créer le premier projet +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
OrdreTitreStatutBadgeDateActions
+ + Publié + + Brouillon + + + + En production + + En développement + + +
+ Modifier + + +
+ + + + +
+ +
+ + + + +
+ + + +
+
+
+ +
+
+ + +
+
+

Supprimer ce projet ?

+

Le projet "" sera définitivement supprimé.

+
+ +
+ + + +
+
+
+
+ + + + diff --git a/admin/login.php b/admin/login.php new file mode 100644 index 0000000..f7cb5b0 --- /dev/null +++ b/admin/login.php @@ -0,0 +1,139 @@ + 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.'; + } + } +} +?> + + + + + + + Connexion — BackOffice Tony AVERTY + + + +
+ +
+ + diff --git a/admin/logout.php b/admin/logout.php new file mode 100644 index 0000000..8bfc722 --- /dev/null +++ b/admin/logout.php @@ -0,0 +1,35 @@ + 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; diff --git a/admin/messages.php b/admin/messages.php new file mode 100644 index 0000000..3596126 --- /dev/null +++ b/admin/messages.php @@ -0,0 +1,468 @@ + 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 .= << + +
+

{$who} · {$date}

+
{$text}
+
+ + +HTML; + } + + $originalText = nl2br(Security::e((string) $message['message'])); + $originalDate = date('d/m/Y H:i', strtotime($message['created_at'])); + $threadHtml .= << + +
+

{$safeClientName} · {$originalDate} (message initial)

+
{$originalText}
+
+ + +HTML; + + return << + + + + + + + +
+ + + + + + + + {$threadHtml} + + + +
+ Tony AVERTY
+ Reponse a votre message +
+

Bonjour {$safeClientName},

+
{$safeReply}
+
+ Tony AVERTY · contact@tony-averty.dev · tony-averty.dev +
+
+ + +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); +} +?> + + + + + + + Messages - BackOffice Tony AVERTY + + + +
+ + +
+
+

+ Messages + 0): ?> + + +

+ message(s) au total +
+ + +
+ + + + + +
+

Aucun message.

+
+ +
+ + +
+
+
+ + +
+ +
+ + +
Sujet :
+ + +
+ + +
+ + +
+
+ + + de + + le +
+
+
+ +
+ + +
+ + + +
+ + + + +
+ +
+ + + + +
+ + + +
+
+ +
+ +
+
+ +
+
+

Repondre a

+

+
+ + + + +
+ + +
+
+
+
+ +
+
+

Supprimer ce message ?

+

Le message de "" et toutes ses reponses seront supprimes.

+
+ +
+ + + + +
+
+
+
+ + + + diff --git a/admin/project-delete.php b/admin/project-delete.php new file mode 100644 index 0000000..59542a8 --- /dev/null +++ b/admin/project-delete.php @@ -0,0 +1,58 @@ + 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; diff --git a/admin/project-form.php b/admin/project-form.php new file mode 100644 index 0000000..a3119c5 --- /dev/null +++ b/admin/project-form.php @@ -0,0 +1,269 @@ + 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.'; + } + } +} +?> + + + + + + + <?= $isEdit ? 'Modifier' : 'Nouveau' ?> projet - BackOffice + + + +
+
+

projet

+
+ Retour +
+
+ + +
+ + +
+ + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + + +

+ Image actuelle : +

+ +
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + Annuler +
+
+
+ + diff --git a/admin/security.php b/admin/security.php new file mode 100644 index 0000000..5d0bf26 --- /dev/null +++ b/admin/security.php @@ -0,0 +1,339 @@ + 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(); +?> + + + + + + + Securite - BackOffice Tony AVERTY + + + +
+ + +
+
+

Securite et admins

+
+ + +
+ + +
+
+

Changer mon mot de passe

+
+ + + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+
+
+ +
+

Creer un compte admin

+
+ + + +
+ + +
+ +
+ + +
+ +
+ +
+
+
+ +
+

Comptes administrateurs

+ + + + + + + + + + + + + + +
IDIdentifiantCree leAction
+ + + Vous + + + +
+ + + + +
+ + - + +
+
+ +
+
+

IPs bloquees

+ + tentative(s) sur 24h + +
+ + +

Aucune IP bloquee en ce moment.

+ + + + + + + + + + + + + + + +
IPTentativesDerniere tentativeAction
+
+ + + + +
+
+ +
+ +
+
+

Logs d'activite

+
+ + + +
+
+ + +

Aucun log disponible.

+ + + + + + + + + + + + + + + + + +
DateAdminActionDetailIPStatut
+ + OK + + Echec + +
+ +
+
+
+
+ + + + diff --git a/admin/services.php b/admin/services.php new file mode 100644 index 0000000..1808454 --- /dev/null +++ b/admin/services.php @@ -0,0 +1,267 @@ + 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'; +} +?> + + + + + + + Services - BackOffice Tony AVERTY + + + +
+ + +
+
+

Services

+ + + +
+ + +
+ + +
+

+ +

+ +
+ + + + + + +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+ + Annuler +
+
+
+ + +

Aucun service configure.

+ +
+ + + + + + + + + + + + + + + +
OrdreIconeTitreStatutActions
+
+ … +
+ + Actif + + Inactif + + +
+ Modifier + +
+ + + + +
+ + +
+
+
+ +
+
+ +
+
+

Supprimer ce service ?

+

Le service "" sera definitivement supprime.

+
+ +
+ + + + +
+
+
+
+ + + + diff --git a/admin/settings.php b/admin/settings.php new file mode 100644 index 0000000..420b7b8 --- /dev/null +++ b/admin/settings.php @@ -0,0 +1,129 @@ + 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'], +]; +?> + + + + + + + Paramètres — BackOffice Tony AVERTY + + + +
+ + +
+
+

Paramètres globaux

+
+ + +
+ + +
+ + $keys): ?> +
+

+ + + +
+ + + + + + + +
+ +
+ + +
+ +
+
+ + +
+

ℹ️ Infos système

+ + + + + + + + +
PHP
Serveur
Date serveur
Timezone
Backoffice version1.0.0
+
+
+
+ + diff --git a/api/contact.php b/api/contact.php new file mode 100644 index 0000000..3674623 --- /dev/null +++ b/api/contact.php @@ -0,0 +1,328 @@ + 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|= 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 << + + + + + + + +
+ + + + + + + +
+ Nouveau message de contact
+ tony-averty.dev +
+

Nom : {$safeName}

+

Email : {$safeEmail}

+

Sujet : {$safeSubject}

+
{$safeMessage}
+

+ Ouvrir le BackOffice +

+
+
+ + +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 << + + + + + + + +
+ + + + + + + +
+ Tony AVERTY
+ Confirmation de reception +
+

Bonjour {$safeName},

+

Merci pour votre message. Il a bien ete recu et je vous repondrai sous 24 heures.

+
+

Sujet : {$safeSubject}

+
{$safeMessage}
+
+

Si vous n'etes pas a l'origine de cette demande, ignorez simplement cet email.

+
+
+ + +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); +} diff --git a/api/track.php b/api/track.php new file mode 100644 index 0000000..2396889 --- /dev/null +++ b/api/track.php @@ -0,0 +1,144 @@ + 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]); +} diff --git a/assets/css/style.css b/assets/css/style.css new file mode 100644 index 0000000..3760232 --- /dev/null +++ b/assets/css/style.css @@ -0,0 +1,2410 @@ +/* ============================================ + Portfolio Tony AVERTY — Styles principaux + Direction artistique : Structured Elegance + ============================================ */ + +/* ============================================ + FONTS AUTO-HÉBERGÉES (RGPD) + ============================================ */ + +/* Inter — latin-ext */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url('../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; +} + +/* Inter — latin */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url('../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; +} + +/* JetBrains Mono — latin-ext */ +@font-face { + font-family: 'JetBrains Mono'; + font-style: normal; + font-weight: 100 800; + font-display: swap; + src: url('../fonts/jetbrains-mono-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; +} + +/* JetBrains Mono — latin */ +@font-face { + font-family: 'JetBrains Mono'; + font-style: normal; + font-weight: 100 800; + font-display: swap; + src: url('../fonts/jetbrains-mono-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; +} + +/* ============================================ + CUSTOM PROPERTIES (Design Tokens) + ============================================ */ + +:root { + /* Typography */ + --font-main: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', monospace; + + /* Spacing */ + --space-xs: 0.25rem; + --space-sm: 0.5rem; + --space-md: 1rem; + --space-lg: 1.5rem; + --space-xl: 2rem; + --space-2xl: 3rem; + --space-3xl: 4rem; + --space-4xl: 6rem; + --space-5xl: 8rem; + + /* Borders */ + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + --radius-xl: 20px; + --radius-full: 9999px; + + /* Transitions */ + --ease-out: cubic-bezier(0.16, 1, 0.3, 1); + --ease-in-out: cubic-bezier(0.65, 0, 0.35, 1); + --duration-fast: 0.15s; + --duration-normal: 0.3s; + --duration-slow: 0.5s; + --duration-theme: 0.5s; + + /* Layout */ + --container-max: 1200px; + --navbar-height: 72px; +} + +/* ============================================ + THEME: DARK (default) + ============================================ */ + +[data-theme="dark"] { + --bg-primary: #0a0a0f; + --bg-secondary: #12121a; + --bg-tertiary: #1a1a26; + --bg-card: #14141e; + --bg-card-hover: #1a1a28; + + --text-primary: #f1f1f4; + --text-secondary: #8b8b9e; + --text-tertiary: #5a5a70; + + --accent: #6366f1; + --accent-hover: #818cf8; + --accent-subtle: rgba(99, 102, 241, 0.1); + --accent-glow: rgba(99, 102, 241, 0.15); + --accent-warm: #f59e0b; + --accent-warm-subtle: rgba(245, 158, 11, 0.1); + --accent-green: #22c55e; + --accent-green-subtle: rgba(34, 197, 94, 0.1); + + --border: rgba(255, 255, 255, 0.06); + --border-hover: rgba(255, 255, 255, 0.12); + --border-accent: rgba(99, 102, 241, 0.3); + + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.4); + --shadow-md: 0 4px 20px rgba(0, 0, 0, 0.3); + --shadow-lg: 0 8px 40px rgba(0, 0, 0, 0.4); + --shadow-glow: 0 0 30px rgba(99, 102, 241, 0.08); + + --navbar-bg: rgba(10, 10, 15, 0.85); + --hero-gradient: radial-gradient(ellipse at 50% 0%, rgba(99, 102, 241, 0.08) 0%, transparent 60%); +} + +/* ============================================ + THEME: LIGHT + ============================================ */ + +[data-theme="light"] { + --bg-primary: #fafaf9; + --bg-secondary: #ffffff; + --bg-tertiary: #f3f3f2; + --bg-card: #ffffff; + --bg-card-hover: #f8f8f7; + + --text-primary: #1a1a2e; + --text-secondary: #6b7280; + --text-tertiary: #9ca3af; + + --accent: #4f46e5; + --accent-hover: #6366f1; + --accent-subtle: rgba(79, 70, 229, 0.06); + --accent-glow: rgba(79, 70, 229, 0.1); + --accent-warm: #d97706; + --accent-warm-subtle: rgba(217, 119, 6, 0.08); + --accent-green: #16a34a; + --accent-green-subtle: rgba(22, 163, 74, 0.08); + + --border: rgba(0, 0, 0, 0.06); + --border-hover: rgba(0, 0, 0, 0.12); + --border-accent: rgba(79, 70, 229, 0.25); + + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.06); + --shadow-md: 0 4px 20px rgba(0, 0, 0, 0.06); + --shadow-lg: 0 8px 40px rgba(0, 0, 0, 0.08); + --shadow-glow: 0 0 30px rgba(79, 70, 229, 0.06); + + --navbar-bg: rgba(250, 250, 249, 0.85); + --hero-gradient: radial-gradient(ellipse at 50% 0%, rgba(79, 70, 229, 0.05) 0%, transparent 60%); +} + +/* ============================================ + THEME TRANSITION + ============================================ */ + +html, +html *, +html *::before, +html *::after { + transition: + background-color var(--duration-theme) ease-in-out, + border-color var(--duration-theme) ease-in-out, + color var(--duration-theme) ease-in-out, + box-shadow var(--duration-theme) ease-in-out, + fill var(--duration-theme) ease-in-out, + stroke var(--duration-theme) ease-in-out; +} + +/* Désactive les transitions au chargement initial pour éviter le flash */ +.no-transition, +.no-transition *, +.no-transition *::before, +.no-transition *::after { + transition: none !important; +} + +/* ============================================ + RESET & BASE + ============================================ */ + +*, +*::before, +*::after { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html { + /* scroll-behavior géré en JS (lerp) sur desktop, smooth natif sur mobile */ + scroll-padding-top: var(--navbar-height); + -webkit-text-size-adjust: 100%; +} + +html { + overflow-x: hidden; +} + +body { + font-family: var(--font-main); + font-size: 1rem; + line-height: 1.7; + color: var(--text-primary); + background-color: var(--bg-primary); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + overflow-x: hidden; +} + +img { + max-width: 100%; + height: auto; + display: block; +} + +a { + color: var(--accent); + text-decoration: none; + transition: color var(--duration-fast) var(--ease-out); +} + +a:hover { + color: var(--accent-hover); +} + +::selection { + background-color: var(--accent); + color: #fff; +} + +/* ============================================ + CONTAINER + ============================================ */ + +.container { + width: 100%; + max-width: var(--container-max); + margin: 0 auto; + padding: 0 var(--space-xl); +} + +@media (max-width: 768px) { + .container { + padding: 0 var(--space-lg); + } +} + +/* ============================================ + SCROLL PROGRESS BAR + ============================================ */ + +.scroll-progress { + position: fixed; + top: 0; + left: 0; + width: 0; + height: 3px; + background: linear-gradient(90deg, var(--accent), var(--accent-hover)); + z-index: 10001; + transition: none; +} + +/* ============================================ + NAVBAR + ============================================ */ + +.navbar { + position: fixed; + top: 0; + left: 0; + right: 0; + height: var(--navbar-height); + background: var(--navbar-bg); + backdrop-filter: blur(20px); + -webkit-backdrop-filter: blur(20px); + border-bottom: 1px solid var(--border); + z-index: 10000; + display: flex; + align-items: center; +} + +.navbar__container { + width: 100%; + max-width: var(--container-max); + margin: 0 auto; + padding: 0 var(--space-xl); + display: flex; + align-items: center; + justify-content: space-between; +} + +.navbar__logo { + text-decoration: none; + color: var(--text-primary); +} + +.navbar__logo-text { + font-size: 1.35rem; + font-weight: 800; + letter-spacing: -0.03em; +} + +.navbar__logo-accent { + color: var(--accent); +} + +.navbar__menu { + list-style: none; + display: flex; + gap: var(--space-sm); + align-items: center; +} + +.navbar__link { + color: var(--text-secondary); + font-size: 0.875rem; + font-weight: 500; + padding: var(--space-sm) var(--space-md); + border-radius: var(--radius-sm); + transition: color var(--duration-fast) var(--ease-out), + background-color var(--duration-fast) var(--ease-out); + text-decoration: none; +} + +.navbar__link:hover { + color: var(--text-primary); + background-color: var(--accent-subtle); +} + +.navbar__link--cta { + color: #fff; + background-color: var(--accent); + padding: var(--space-sm) var(--space-lg); + border-radius: var(--radius-full); + font-weight: 600; +} + +.navbar__link--cta:hover { + color: #fff; + background-color: var(--accent-hover); +} + +.navbar__actions { + display: flex; + align-items: center; + gap: var(--space-md); +} + +/* ============================================ + THEME SWITCH + ============================================ */ + +.theme-switch { + position: relative; + width: 44px; + height: 44px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-secondary); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + color: var(--text-secondary); + transition: border-color var(--duration-fast) var(--ease-out), + color var(--duration-fast) var(--ease-out), + transform var(--duration-fast) var(--ease-out); +} + +.theme-switch:hover { + border-color: var(--border-hover); + color: var(--accent); + transform: scale(1.05); +} + +.theme-switch:active { + transform: scale(0.95); +} + +.theme-switch__icon { + position: absolute; + transition: opacity var(--duration-normal) var(--ease-out), + transform var(--duration-normal) var(--ease-out); + display: flex; + align-items: center; + justify-content: center; +} + +/* Dark mode: show sun, hide moon */ +[data-theme="dark"] .theme-switch__icon--sun { + opacity: 1; + transform: rotate(0deg) scale(1); +} + +[data-theme="dark"] .theme-switch__icon--moon { + opacity: 0; + transform: rotate(-90deg) scale(0.5); +} + +/* Light mode: show moon, hide sun */ +[data-theme="light"] .theme-switch__icon--sun { + opacity: 0; + transform: rotate(90deg) scale(0.5); +} + +[data-theme="light"] .theme-switch__icon--moon { + opacity: 1; + transform: rotate(0deg) scale(1); +} + +/* ============================================ + BURGER MENU (Mobile) + ============================================ */ + +.navbar__burger { + display: none; + flex-direction: column; + justify-content: center; + align-items: center; + width: 44px; + height: 44px; + background: none; + border: 1px solid var(--border); + border-radius: var(--radius-md); + cursor: pointer; + gap: 5px; + padding: 0; +} + +.navbar__burger-line { + display: block; + width: 20px; + height: 2px; + background-color: var(--text-primary); + border-radius: 2px; + transition: transform var(--duration-normal) var(--ease-out), + opacity var(--duration-normal) var(--ease-out); +} + +.navbar__burger[aria-expanded="true"] .navbar__burger-line:nth-child(1) { + transform: translateY(7px) rotate(45deg); +} + +.navbar__burger[aria-expanded="true"] .navbar__burger-line:nth-child(2) { + opacity: 0; +} + +.navbar__burger[aria-expanded="true"] .navbar__burger-line:nth-child(3) { + transform: translateY(-7px) rotate(-45deg); +} + +@media (max-width: 900px) { + /* Supprimer backdrop-filter sur mobile : il crée un containing block + qui empêche les enfants position:fixed de se positionner par rapport + à la viewport. On met un fond solide à la place. */ + .navbar { + backdrop-filter: none; + -webkit-backdrop-filter: none; + background: var(--bg-primary); + border-bottom-color: var(--border); + } + + .navbar__burger { + display: flex; + } + + .navbar__menu { + position: fixed; + top: var(--navbar-height); + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + background: var(--bg-primary); + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--space-lg); + opacity: 0; + visibility: hidden; + transform: translateY(-8px); + transition: opacity var(--duration-normal) var(--ease-out), + visibility var(--duration-normal) var(--ease-out), + transform var(--duration-normal) var(--ease-out); + } + + .navbar__menu.is-open { + opacity: 1; + visibility: visible; + transform: translateY(0); + } + + .navbar__link { + font-size: 1.25rem; + padding: var(--space-md) var(--space-xl); + } + + /* Le bouton Contact dans le menu mobile reprend un style simple */ + .navbar__link--cta { + margin-top: var(--space-sm); + padding: var(--space-sm) var(--space-2xl); + } +} + +/* ============================================ + BUTTONS + ============================================ */ + +.btn { + display: inline-flex; + align-items: center; + gap: var(--space-sm); + font-family: var(--font-main); + font-weight: 600; + font-size: 0.9375rem; + padding: 0.75rem 1.5rem; + border-radius: var(--radius-md); + border: none; + cursor: pointer; + text-decoration: none; + transition: transform var(--duration-fast) var(--ease-out), + box-shadow var(--duration-fast) var(--ease-out), + background-color var(--duration-fast) var(--ease-out), + border-color var(--duration-fast) var(--ease-out); + white-space: nowrap; +} + +.btn:active { + transform: scale(0.98); +} + +.btn--primary { + background-color: var(--accent); + color: #fff; + box-shadow: var(--shadow-sm); +} + +.btn--primary:hover { + background-color: var(--accent-hover); + color: #fff; + box-shadow: var(--shadow-md), var(--shadow-glow); + transform: translateY(-1px); +} + +.btn--outline { + background: transparent; + color: var(--accent); + border: 1.5px solid var(--border-accent); +} + +.btn--outline:hover { + background-color: var(--accent-subtle); + color: var(--accent-hover); + border-color: var(--accent-hover); + transform: translateY(-1px); +} + +.btn--lg { + padding: 0.875rem 2rem; + font-size: 1rem; +} + +/* ============================================ + TAGS + ============================================ */ + +.tag { + display: inline-block; + padding: 0.25rem 0.75rem; + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + color: var(--accent); + background-color: var(--accent-subtle); + border: 1px solid var(--border-accent); + border-radius: var(--radius-full); + white-space: nowrap; +} + +.tag--sm { + padding: 0.15rem 0.55rem; + font-size: 0.75rem; +} + +/* ============================================ + SECTION SYSTEM + ============================================ */ + +.section { + padding: 4.5rem 0; + position: relative; +} + +@media (max-width: 768px) { + .section { + padding: 3rem 0; + } +} + +.section__header { + display: flex; + align-items: center; + gap: var(--space-md); + margin-bottom: var(--space-lg); +} + +.section__number { + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + color: var(--accent); + opacity: 0.5; +} + +.section__label { + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + color: var(--accent); + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.section__title { + font-size: clamp(1.75rem, 4vw, 2.5rem); + font-weight: 800; + letter-spacing: -0.03em; + line-height: 1.2; + color: var(--text-primary); + margin-bottom: var(--space-md); +} + +.section__intro { + font-size: 1.0625rem; + color: var(--text-secondary); + max-width: 100%; + margin-bottom: var(--space-3xl); +} + +/* ============================================ + HERO + ============================================ */ + +.hero { + min-height: 100vh; + display: flex; + align-items: center; + position: relative; + overflow: hidden; + padding-top: var(--navbar-height); +} + +.hero__grid-bg { + position: absolute; + inset: 0; + background-image: + linear-gradient(var(--border) 1px, transparent 1px), + linear-gradient(90deg, var(--border) 1px, transparent 1px); + background-size: 60px 60px; + opacity: 0.4; + mask-image: radial-gradient(ellipse at 50% 50%, black 20%, transparent 70%); + -webkit-mask-image: radial-gradient(ellipse at 50% 50%, black 20%, transparent 70%); +} + +.hero__grain { + position: absolute; + inset: 0; + background: var(--hero-gradient); + pointer-events: none; +} + +/* Layout hero 2 colonnes */ +.hero__inner { + position: relative; + z-index: 1; + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-4xl); + align-items: center; + width: 100%; + padding: var(--space-4xl) 0; +} + +.hero__content { + min-width: 0; +} + +/* ============================================ + HERO VISUAL — Code card + ============================================ */ + +.hero__visual { + position: relative; + transform: translateY(100px); + animation: hero-fade-in 0.8s var(--ease-out) 0.5s both; +} + +/* Carte éditeur */ +.hero__code-card { + background-color: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + overflow: hidden; + box-shadow: var(--shadow-lg); + position: relative; + z-index: 1; +} + +.hero__code-header { + display: flex; + align-items: center; + gap: 6px; + padding: 0.85rem 1.25rem; + background-color: var(--bg-tertiary); + border-bottom: 1px solid var(--border); +} + +.hero__code-dot { + width: 12px; + height: 12px; + border-radius: 50%; + flex-shrink: 0; +} + +.hero__code-dot--red { background-color: #ff5f57; } +.hero__code-dot--yellow { background-color: #ffbd2e; } +.hero__code-dot--green { background-color: #28ca41; } + +.hero__code-filename { + margin-left: var(--space-md); + font-family: var(--font-mono); + font-size: 0.75rem; + color: var(--text-tertiary); + font-weight: 500; +} + +.hero__code-body { + padding: 1.5rem 1.75rem; + overflow-x: auto; +} + +.hero__code-pre { + margin: 0; + font-family: var(--font-mono); + font-size: 0.8125rem; + line-height: 1.85; + white-space: pre; + color: var(--text-primary); +} + +/* Syntax tokens */ +.tok-tag { color: var(--accent); font-weight: 500; } +.tok-keyword { color: #c678dd; } +.tok-class { color: #e5c07b; } +.tok-fn { color: #61afef; } +.tok-var { color: #e06c75; } +.tok-string { color: var(--accent-green); } +.tok-comment { color: var(--text-tertiary); font-style: italic; } +.tok-punct { color: var(--text-secondary); } + +[data-theme="light"] .tok-keyword { color: #7c3aed; } +[data-theme="light"] .tok-class { color: #b45309; } +[data-theme="light"] .tok-fn { color: #1d4ed8; } +[data-theme="light"] .tok-var { color: #dc2626; } + +/* Badges flottants */ +.hero__stat { + position: absolute; + display: flex; + align-items: center; + gap: var(--space-md); + padding: 0.75rem 1.1rem; + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow-md); + z-index: 2; + white-space: nowrap; + animation: hero-float 4s ease-in-out infinite; +} + +.hero__stat--response { + bottom: -1.5rem; + left: -1.5rem; + animation-delay: 0s; +} + +.hero__stat--codebzh { + top: -1.25rem; + right: -1.25rem; + animation-delay: 2s; +} + +@keyframes hero-float { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-6px); } +} + +.hero__stat-icon { + font-size: 1.125rem; + line-height: 1; +} + +.hero__stat-value { + display: block; + font-size: 0.9375rem; + font-weight: 700; + color: var(--text-primary); + letter-spacing: -0.02em; +} + +.hero__stat-label { + display: block; + font-size: 0.6875rem; + color: var(--text-tertiary); + font-weight: 500; +} + +/* Responsive : masquer le visuel sous 960px */ +@media (max-width: 960px) { + .hero__inner { + grid-template-columns: 1fr; + padding-bottom: var(--space-2xl); + } + + .hero__visual { + display: none; + } +} + +.hero__badge { + display: inline-flex; + align-items: center; + gap: var(--space-sm); + padding: 0.4rem 1rem; + font-size: 0.8125rem; + font-weight: 500; + color: var(--accent-green); + background-color: var(--accent-green-subtle); + border: 1px solid rgba(34, 197, 94, 0.2); + border-radius: var(--radius-full); + margin-bottom: var(--space-xl); + animation: hero-fade-in 0.8s var(--ease-out) 0.2s both; +} + +.hero__badge-dot { + width: 8px; + height: 8px; + background-color: var(--accent-green); + border-radius: 50%; + animation: pulse-dot 2s ease-in-out infinite; +} + +@keyframes pulse-dot { + 0%, 100% { opacity: 1; transform: scale(1); } + 50% { opacity: 0.5; transform: scale(0.8); } +} + +.hero__title { + font-size: clamp(2.25rem, 6vw, 3.75rem); + font-weight: 800; + letter-spacing: -0.04em; + line-height: 1.1; + margin-bottom: var(--space-xl); + animation: hero-fade-in 0.8s var(--ease-out) 0.4s both; +} + +.hero__title-accent { + color: var(--accent); +} + +.hero__subtitle { + font-size: 1.125rem; + line-height: 1.7; + color: var(--text-secondary); + max-width: 580px; + margin-bottom: var(--space-2xl); + animation: hero-fade-in 0.8s var(--ease-out) 0.6s both; +} + +.hero__actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-md); + margin-bottom: var(--space-3xl); + animation: hero-fade-in 0.8s var(--ease-out) 0.8s both; +} + +.hero__stack { + display: flex; + align-items: center; + gap: var(--space-md); + flex-wrap: wrap; + animation: hero-fade-in 0.8s var(--ease-out) 1s both; +} + +.hero__stack-label { + font-size: 0.8125rem; + color: var(--text-tertiary); + font-weight: 500; +} + +.hero__stack-tags { + display: flex; + flex-wrap: wrap; + gap: var(--space-sm); +} + +@keyframes hero-fade-in { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.hero__scroll { + position: absolute; + bottom: 2rem; + left: 50%; + transform: translateX(-50%); + animation: hero-fade-in 0.8s var(--ease-out) 1.2s both; +} + +.hero__scroll-line { + display: block; + width: 1px; + height: 40px; + background: linear-gradient(to bottom, var(--accent), transparent); + animation: scroll-line 2s ease-in-out infinite; +} + +@keyframes scroll-line { + 0% { opacity: 0; transform: scaleY(0); transform-origin: top; } + 50% { opacity: 1; transform: scaleY(1); transform-origin: top; } + 100% { opacity: 0; transform: scaleY(1); transform-origin: bottom; } +} + +/* ============================================ + ABOUT + ============================================ */ + +.about__grid { + display: grid; + grid-template-columns: 340px 1fr; + gap: var(--space-4xl); + align-items: stretch; +} + +@media (max-width: 900px) { + .about__grid { + grid-template-columns: 1fr; + gap: var(--space-2xl); + } +} + +.about__photo-wrapper { + position: relative; + display: flex; + flex-direction: column; + align-self: stretch; + height: 100%; +} + +.about__photo-wrapper .timeline--compact { + flex: 1; + display: flex; + flex-direction: column; + justify-content: space-evenly; + margin-top: var(--space-2xl); +} + +.about__photo-wrapper .timeline--compact .timeline__item { + padding-bottom: 0; + flex: 1; + display: flex; + flex-direction: column; + justify-content: center; +} + +.about__photo-frame { + position: relative; + border-radius: var(--radius-lg); + overflow: hidden; + aspect-ratio: 4 / 5; + background-color: var(--bg-tertiary); +} + +.about__photo-frame::before { + content: ''; + position: absolute; + top: -2px; + left: -2px; + right: 50%; + bottom: 50%; + border: 2px solid var(--accent); + border-radius: var(--radius-lg) 0 0 0; + border-right: none; + border-bottom: none; + z-index: 1; + pointer-events: none; +} + +.about__photo-frame::after { + content: ''; + position: absolute; + bottom: -2px; + right: -2px; + left: 50%; + top: 50%; + border: 2px solid var(--accent); + border-radius: 0 0 var(--radius-lg) 0; + border-left: none; + border-top: none; + z-index: 1; + pointer-events: none; +} + +.about__photo { + width: 100%; + height: 100%; + object-fit: cover; + object-position: center top; +} + +.about__content { + padding-top: var(--space-md); +} + +.about__text { + font-size: 1.0625rem; + color: var(--text-secondary); + margin-bottom: var(--space-lg); + line-height: 1.8; +} + +.about__highlights { + display: flex; + flex-direction: column; + gap: var(--space-md); + margin-top: var(--space-xl); +} + +.about__highlight { + display: flex; + align-items: center; + gap: var(--space-md); + font-size: 0.9375rem; + font-weight: 500; + color: var(--text-primary); +} + +.about__highlight-icon { + display: flex; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: var(--radius-sm); + background-color: var(--accent-subtle); + color: var(--accent); + flex-shrink: 0; +} + +/* ============================================ + SKILLS + ============================================ */ + +.skills__grid { + display: flex; + flex-direction: column; + gap: var(--space-3xl); +} + +.skills__category-title { + margin-bottom: var(--space-xl); +} + +.skills__category-badge { + display: inline-block; + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + padding: 0.3rem 0.85rem; + border-radius: var(--radius-full); +} + +.skills__category-badge--expert { + color: var(--accent); + background-color: var(--accent-subtle); + border: 1px solid var(--border-accent); +} + +.skills__category-badge--solid { + color: var(--accent-warm); + background-color: var(--accent-warm-subtle); + border: 1px solid rgba(245, 158, 11, 0.2); +} + +.skills__cards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: var(--space-lg); +} + +.skill-card { + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: var(--space-xl); + transition: transform var(--duration-normal) var(--ease-out), + box-shadow var(--duration-normal) var(--ease-out), + border-color var(--duration-normal) var(--ease-out); +} + +.skill-card:hover { + transform: translateY(-4px); + box-shadow: var(--shadow-md), var(--shadow-glow); + border-color: var(--border-accent); +} + +.skill-card__icon { + width: 48px; + height: 48px; + display: flex; + align-items: center; + justify-content: center; + border-radius: var(--radius-md); + background-color: var(--accent-subtle); + color: var(--accent); + margin-bottom: var(--space-lg); +} + +.skill-card__name { + font-size: 1.125rem; + font-weight: 700; + letter-spacing: -0.01em; + margin-bottom: var(--space-sm); +} + +.skill-card__desc { + font-size: 0.875rem; + color: var(--text-secondary); + line-height: 1.6; +} + +/* Skills tools */ +.skills__tools { + margin-top: var(--space-3xl); + padding: var(--space-2xl); + background-color: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: var(--radius-lg); +} + +.skills__tools-title { + font-size: 1rem; + font-weight: 600; + color: var(--text-secondary); + margin-bottom: var(--space-lg); +} + +.skills__tools-list { + display: flex; + flex-wrap: wrap; + gap: var(--space-sm); +} + +.tool-chip { + display: inline-flex; + align-items: center; + gap: 0.45rem; + padding: 0.35rem 0.85rem; + font-size: 0.8125rem; + font-weight: 500; + color: var(--text-secondary); + background-color: var(--bg-tertiary); + border: 1px solid var(--border); + border-radius: var(--radius-full); + transition: color var(--duration-fast) var(--ease-out), + border-color var(--duration-fast) var(--ease-out); +} + +.tool-chip:hover { + color: var(--text-primary); + border-color: var(--border-hover); +} + +.tool-chip__icon { + width: 22px; + height: 22px; + border-radius: 50%; + background: var(--accent-subtle); + color: var(--accent); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +/* ============================================ + PROJECTS + ============================================ */ + +.projects__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: var(--space-lg); +} + +@media (max-width: 1024px) { + .projects__grid { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 640px) { + .projects__grid { + grid-template-columns: 1fr; + } +} + +.project-card { + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + overflow: hidden; + transition: transform var(--duration-normal) var(--ease-out), + box-shadow var(--duration-normal) var(--ease-out), + border-color var(--duration-normal) var(--ease-out); +} + +.project-card:hover { + transform: translateY(-4px); + box-shadow: var(--shadow-md), var(--shadow-glow); + border-color: var(--border-accent); +} + +.project-card__image { + position: relative; + aspect-ratio: 16 / 9; + background-color: var(--bg-tertiary); + overflow: hidden; +} + +.project-card__image img { + width: 100%; + height: 100%; + object-fit: cover; + transition: transform var(--duration-slow) var(--ease-out); +} + +.project-card:hover .project-card__image img { + transform: scale(1.04); +} + +.project-card__image--placeholder { + display: flex; + align-items: center; + justify-content: center; +} + +.project-card__badge { + position: absolute; + top: var(--space-sm); + left: var(--space-sm); + padding: 0.2rem 0.6rem; + font-size: 0.7rem; + font-weight: 600; + border-radius: var(--radius-full); + z-index: 1; +} + +.badge--production { + background-color: var(--accent-green); + color: #fff; +} + +.badge--development { + background-color: var(--accent-warm); + color: #fff; +} + +.project-card__body { + padding: var(--space-md) var(--space-lg); +} + +.project-card__title { + font-size: 0.9375rem; + font-weight: 700; + margin-bottom: var(--space-xs); +} + +.project-card__desc { + font-size: 0.8125rem; + color: var(--text-secondary); + line-height: 1.55; + margin-bottom: var(--space-md); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.project-card__techs { + display: flex; + flex-wrap: wrap; + gap: 0.25rem; + margin-bottom: var(--space-md); +} + +.project-card__link { + display: inline-flex; + align-items: center; + gap: var(--space-xs); + font-size: 0.8125rem; + font-weight: 600; + color: var(--accent); +} + +.project-card__link:hover { + color: var(--accent-hover); +} + +/* ============================================ + SERVICES + ============================================ */ + +.services__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: var(--space-lg); +} + +.services__cta { + margin-top: var(--space-3xl); + text-align: center; +} + +@media (max-width: 900px) { + .services__grid { + grid-template-columns: repeat(2, 1fr); + } + + .services__cta .btn { + white-space: normal; + text-align: center; + } +} + +@media (max-width: 600px) { + .services__grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 600px) { + .services__grid { + grid-template-columns: 1fr; + } +} + +.service-card { + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: var(--space-2xl); + transition: transform var(--duration-normal) var(--ease-out), + box-shadow var(--duration-normal) var(--ease-out), + border-color var(--duration-normal) var(--ease-out); +} + +.service-card:hover { + transform: translateY(-4px); + box-shadow: var(--shadow-md), var(--shadow-glow); + border-color: var(--border-accent); +} + +.service-card__icon { + width: 48px; + height: 48px; + display: flex; + align-items: center; + justify-content: center; + border-radius: var(--radius-md); + background-color: var(--accent-subtle); + color: var(--accent); + margin-bottom: var(--space-lg); +} + +.service-card__title { + font-size: 1.0625rem; + font-weight: 700; + margin-bottom: var(--space-sm); + letter-spacing: -0.01em; +} + +.service-card__desc { + font-size: 0.875rem; + color: var(--text-secondary); + line-height: 1.7; +} + +/* ============================================ + JOURNEY / TIMELINE + ============================================ */ + +.timeline { + position: relative; + padding-left: var(--space-3xl); + max-width: 700px; +} + +.timeline--compact { + margin-top: var(--space-2xl); + padding-left: var(--space-xl); + max-width: 100%; +} + +.timeline--compact .timeline__item { + padding-bottom: var(--space-lg); +} + +.timeline--compact .timeline__marker { + left: calc(-1 * var(--space-xl) + 1px); +} + +.timeline--compact .timeline__title { + font-size: 0.9rem; + font-weight: 600; + margin-bottom: 0; +} + +.timeline::before { + content: ''; + position: absolute; + left: 7px; + top: 8px; + bottom: 8px; + width: 2px; + background: linear-gradient(to bottom, var(--accent), var(--border)); + border-radius: 2px; +} + +.timeline__item { + position: relative; + padding-bottom: var(--space-3xl); +} + +.timeline__item:last-child { + padding-bottom: 0; +} + +.timeline__marker { + position: absolute; + left: calc(-1 * var(--space-3xl) + 1px); + top: 6px; + width: 14px; + height: 14px; + border-radius: 50%; + background-color: var(--accent); + border: 3px solid var(--bg-primary); + box-shadow: 0 0 0 2px var(--accent); +} + +.timeline__date { + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + color: var(--accent); + margin-bottom: var(--space-xs); + display: block; +} + +.timeline__title { + font-size: 1.125rem; + font-weight: 700; + margin-bottom: var(--space-sm); +} + +.timeline__desc { + font-size: 0.9375rem; + color: var(--text-secondary); + line-height: 1.7; +} + +/* ============================================ + CONTACT + ============================================ */ + +.contact__grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-3xl); + align-items: start; +} + +@media (max-width: 900px) { + .contact__grid { + grid-template-columns: 1fr; + gap: var(--space-2xl); + } +} + +.contact__info-card { + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: var(--space-2xl); +} + +.contact__info-title { + font-size: 1.25rem; + font-weight: 700; + margin-bottom: var(--space-md); +} + +.contact__info-text { + font-size: 0.9375rem; + color: var(--text-secondary); + line-height: 1.7; + margin-bottom: var(--space-xl); +} + +.contact__email { + display: flex; + align-items: center; + gap: var(--space-md); + padding: var(--space-md) var(--space-lg); + background-color: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: var(--radius-md); + margin-top: var(--space-2xl); + margin-bottom: var(--space-md); + color: var(--text-primary); + text-decoration: none; + transition: border-color var(--duration-fast) var(--ease-out); +} + +.contact__email:hover { + border-color: var(--border-accent); +} + +.contact__email-icon { + display: flex; + align-items: center; + justify-content: center; + width: 34px; + height: 34px; + background-color: var(--accent-subtle); + border-radius: var(--radius-md); + color: var(--accent); + flex-shrink: 0; +} + +.contact__email-link { + font-weight: 600; + font-size: 0.9375rem; + color: var(--accent); + word-break: break-all; +} + +.contact__process { + margin-top: var(--space-xl); + padding-top: var(--space-xl); + border-top: 1px solid var(--border); +} + +.contact__process-title { + font-size: 0.8125rem; + font-weight: 600; + color: var(--text-secondary); + text-transform: uppercase; + letter-spacing: 0.06em; + margin-bottom: var(--space-md); +} + +.contact__process-list { + list-style: none; + counter-reset: process-counter; + display: flex; + flex-direction: column; + gap: var(--space-sm); +} + +.contact__process-list li { + counter-increment: process-counter; + display: flex; + align-items: center; + gap: var(--space-md); + font-size: 0.9375rem; + color: var(--text-primary); +} + +.contact__process-list li::before { + content: counter(process-counter); + display: flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + min-width: 28px; + border-radius: 50%; + background-color: var(--accent-subtle); + color: var(--accent); + font-family: var(--font-mono); + font-size: 0.75rem; + font-weight: 600; + border: 1px solid var(--border-accent); +} + +.contact__response { + display: flex; + align-items: center; + gap: var(--space-sm); + font-size: 0.8125rem; + color: var(--text-tertiary); + font-weight: 500; +} + +.contact__response-icon { + display: flex; + align-items: center; + flex-shrink: 0; +} + +/* ============================================ + FORM + ============================================ */ + +.contact__form { + display: flex; + flex-direction: column; + gap: var(--space-lg); +} + +.form__honeypot { + position: absolute; + left: -9999px; + opacity: 0; + height: 0; + width: 0; + overflow: hidden; + pointer-events: none; +} + +.form__group { + display: flex; + flex-direction: column; + gap: var(--space-sm); +} + +.form__label { + font-size: 0.875rem; + font-weight: 600; + color: var(--text-primary); +} + +.form__optional { + font-weight: 400; + color: var(--text-tertiary); +} + +.form__input { + font-family: var(--font-main); + font-size: 0.9375rem; + padding: 0.75rem 1rem; + background-color: var(--bg-card); + border: 1.5px solid var(--border); + border-radius: var(--radius-md); + color: var(--text-primary); + transition: border-color var(--duration-fast) var(--ease-out), + box-shadow var(--duration-fast) var(--ease-out); + outline: none; +} + +.form__input::placeholder { + color: var(--text-tertiary); +} + +.form__input:focus { + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-subtle); +} + +.form__input:invalid:not(:placeholder-shown) { + border-color: #ef4444; +} + +.form__textarea { + resize: vertical; + min-height: 120px; +} + +.form__submit { + align-self: flex-start; +} + +/* CAPTCHA */ +.form__group--captcha .form__label { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--space-sm); +} + +.form__captcha-question { + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-family: var(--font-mono, 'JetBrains Mono', monospace); + font-size: 0.875rem; + font-weight: 700; + color: var(--accent); + background: var(--accent-subtle); + border: 1px solid var(--border-accent); + border-radius: var(--radius-md); + padding: 0.25rem 0.75rem; + letter-spacing: 0.02em; +} + +.form__input--captcha { + max-width: 140px; +} + +/* Enlever les flèches number input */ +.form__input--captcha::-webkit-outer-spin-button, +.form__input--captcha::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} +.form__input--captcha[type=number] { + -moz-appearance: textfield; +} + +.form__submit-loader { + display: none; + animation: spin 1s linear infinite; +} + +.form__submit.is-loading .form__submit-text { + opacity: 0.6; +} + +.form__submit.is-loading .form__submit-loader { + display: inline-flex; +} + +/* reCAPTCHA v3 : badge masque (evite le chevauchement avec le bouton reglages). + La mention legale ci-dessous remplace le badge, comme l'exige Google. */ +.grecaptcha-badge { + visibility: hidden; +} + +.form__recaptcha-note { + margin-top: var(--space-sm); + font-size: 0.75rem; + line-height: 1.5; + color: var(--text-muted, #6b7280); +} + +.form__recaptcha-note a { + color: inherit; + text-decoration: underline; +} + +.form__recaptcha-note a:hover { + color: var(--accent); +} + +@keyframes spin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } +} + +/* ============================================ + FOOTER + ============================================ */ + +.footer { + padding: var(--space-3xl) 0; + border-top: 1px solid var(--border); + background-color: var(--bg-secondary); +} + +.footer__inner { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-lg); + text-align: center; +} + +.footer__logo { + font-size: 1.25rem; + font-weight: 800; + color: var(--text-primary); + letter-spacing: -0.03em; +} + +.footer__tagline { + font-size: 0.8125rem; + color: var(--text-tertiary); + margin-top: var(--space-xs); +} + +.footer__tagline--sub { + font-size: 0.75rem; + color: var(--text-tertiary); + margin-top: var(--space-xs); +} + +/* ── Lien BackOffice dans la navbar (admin connecté) ─────── */ +.navbar__admin-link { + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-size: 0.8125rem; + font-weight: 700; + color: var(--accent); + background-color: var(--accent-subtle); + border: 1px solid var(--border-accent); + border-radius: var(--radius-full); + padding: 0.4rem 0.9rem; + text-decoration: none; + transition: background-color var(--duration-fast) var(--ease-out), + color var(--duration-fast) var(--ease-out); + letter-spacing: -0.01em; + white-space: nowrap; +} + +.navbar__admin-link:hover { + background-color: var(--accent); + color: #fff; +} + +@media (max-width: 900px) { + .navbar__admin-link { + display: none; + } +} + +@media (max-width: 480px) { + .navbar__admin-link span { display: none; } +} + +.footer__links { + display: flex; + gap: var(--space-lg); + flex-wrap: wrap; + justify-content: center; +} + +.footer__links a { + font-size: 0.875rem; + color: var(--text-secondary); + text-decoration: none; + transition: color var(--duration-fast) var(--ease-out); +} + +.footer__links a:hover { + color: var(--accent); +} + +.footer__copy { + font-size: 0.8125rem; + color: var(--text-tertiary); +} + +/* ============================================ + TOAST NOTIFICATION + ============================================ */ + +.toast { + position: fixed; + bottom: 2rem; + right: 2rem; + display: flex; + align-items: center; + gap: var(--space-md); + padding: var(--space-md) var(--space-xl); + background-color: var(--bg-card); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow-lg); + font-size: 0.875rem; + font-weight: 500; + color: var(--text-primary); + z-index: 20000; + opacity: 0; + visibility: hidden; + transform: translateY(10px); + transition: opacity var(--duration-normal) var(--ease-out), + visibility var(--duration-normal) var(--ease-out), + transform var(--duration-normal) var(--ease-out); +} + +.toast.is-visible { + opacity: 1; + visibility: visible; + transform: translateY(0); +} + +.toast.toast--success { + border-color: var(--accent-green); +} + +.toast.toast--error { + border-color: #ef4444; +} + +.toast__close { + background: none; + border: none; + color: var(--text-tertiary); + cursor: pointer; + font-size: 1.25rem; + padding: 0; + line-height: 1; +} + +/* ============================================ + REVEAL ANIMATIONS + ============================================ */ + +.reveal { + opacity: 0; + transform: translateY(30px); + transition: opacity 0.6s var(--ease-out), + transform 0.6s var(--ease-out); +} + +.reveal.is-visible { + opacity: 1; + transform: translateY(0); +} + +/* ============================================ + UTILITY: hidden nav project link when no projects + ============================================ */ + +.nav-projects-hidden { + display: none !important; +} + +/* ============================================ + RESPONSIVE FINE-TUNING + ============================================ */ + +@media (max-width: 480px) { + .hero__title { + font-size: 1.85rem; + } + + .hero__actions { + flex-direction: column; + } + + .hero__actions .btn { + width: 100%; + justify-content: center; + } + + .hero__stack { + flex-direction: column; + align-items: flex-start; + } + + .section__title { + font-size: 1.5rem; + } +} + +/* ============================================ + NO-ANIMATIONS MODE + ============================================ */ + +.no-animations *, +.no-animations *::before, +.no-animations *::after { + animation: none !important; + transition: none !important; +} + +/* ============================================ + DEV PANEL — Réglages flottant + ============================================ */ + +.devpanel-trigger { + position: fixed; + bottom: 1.5rem; + right: 1.5rem; + z-index: 9997; + width: 42px; + height: 42px; + background: rgba(10, 10, 20, 0.92); + border: 1px solid rgba(99, 102, 241, 0.35); + border-radius: 10px; + color: rgba(255, 255, 255, 0.65); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + transition: border-color 0.2s ease, color 0.2s ease, transform 0.2s ease, background 0.2s ease; +} + +[data-theme="light"] .devpanel-trigger { + background: rgba(250, 250, 249, 0.92); + border-color: rgba(79, 70, 229, 0.25); + color: rgba(26, 26, 46, 0.6); +} + +.devpanel-trigger:hover { + border-color: rgba(99, 102, 241, 0.7); + color: #fff; + transform: rotate(30deg); +} + +[data-theme="light"] .devpanel-trigger:hover { + background: rgba(255, 255, 255, 0.98); + color: #4f46e5; +} + +.devpanel-trigger.is-open { + border-color: rgba(99, 102, 241, 0.8); + color: #a5b4fc; + transform: rotate(60deg); +} + +[data-theme="light"] .devpanel-trigger.is-open { + background: rgba(255, 255, 255, 0.98); + color: #4f46e5; +} + +.devpanel { + position: fixed; + bottom: calc(42px + 1.5rem + 0.75rem); + right: 1.5rem; + z-index: 9996; + width: 290px; + background: rgba(9, 9, 18, 0.97); + border: 1px solid rgba(99, 102, 241, 0.22); + border-radius: 14px; + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + box-shadow: 0 24px 48px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(99,102,241,0.08); + font-family: 'JetBrains Mono', monospace; + font-size: 0.75rem; + color: #c4c4d4; + + /* Fermé par défaut */ + opacity: 0; + pointer-events: none; + transform: translateY(12px) scale(0.96); + transform-origin: bottom right; + transition: opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1), + transform 0.22s cubic-bezier(0.16, 1, 0.3, 1); +} + +.devpanel.is-open { + opacity: 1; + pointer-events: auto; + transform: translateY(0) scale(1); +} + +/* Header type macOS */ +.devpanel__header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.65rem 1rem; + border-bottom: 1px solid rgba(255,255,255,0.06); +} + +.devpanel__title { + display: flex; + align-items: center; + gap: 0.35rem; +} + +.devpanel__title-dot { + width: 11px; + height: 11px; + border-radius: 50%; + flex-shrink: 0; +} +.devpanel__title-dot--r { background: #ff5f56; } +.devpanel__title-dot--y { background: #ffbd2e; } +.devpanel__title-dot--g { background: #27c93f; } + +.devpanel__title-label { + margin-left: 0.4rem; + font-size: 0.7rem; + color: rgba(255,255,255,0.4); + letter-spacing: 0.02em; +} + +.devpanel__fps-live { + display: flex; + align-items: center; + gap: 0.35rem; + font-size: 0.7rem; + font-weight: 600; + color: rgba(255,255,255,0.5); +} + +.devpanel__fps-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: #27c93f; + transition: background 0.3s ease; +} +.devpanel__fps-dot.is-medium { background: #ffbd2e; } +.devpanel__fps-dot.is-low { background: #ff5f56; } + +/* Body */ +.devpanel__body { + padding: 0.5rem 0; +} + +.devpanel__section { + padding: 0.65rem 1rem; + border-bottom: 1px solid rgba(255,255,255,0.05); +} +.devpanel__section:last-child { border-bottom: none; } + +.devpanel__section-label { + display: block; + font-size: 0.65rem; + color: rgba(99, 102, 241, 0.65); + letter-spacing: 0.04em; + margin-bottom: 0.6rem; +} + +.devpanel__row { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 28px; + margin-bottom: 0.4rem; +} +.devpanel__row:last-child { margin-bottom: 0; } + +.devpanel__row-label { + font-size: 0.72rem; + color: rgba(255,255,255,0.72); +} + +/* Segmented control */ +.devpanel__seg { + display: flex; + background: rgba(255,255,255,0.06); + border-radius: 6px; + padding: 2px; + gap: 2px; +} + +.devpanel__seg-btn { + display: flex; + align-items: center; + gap: 4px; + padding: 3px 9px; + background: transparent; + border: none; + border-radius: 4px; + color: rgba(255,255,255,0.45); + font-family: 'JetBrains Mono', monospace; + font-size: 0.7rem; + cursor: pointer; + transition: background 0.15s ease, color 0.15s ease; +} + +.devpanel__seg-btn:hover { + color: rgba(255,255,255,0.75); +} + +.devpanel__seg-btn.is-active { + background: rgba(99, 102, 241, 0.85); + color: #fff; +} + +/* Toggle switch */ +.devpanel__toggle { + position: relative; + display: inline-flex; + cursor: pointer; +} +.devpanel__toggle input { display: none; } + +.devpanel__toggle-track { + width: 36px; + height: 20px; + background: rgba(255,255,255,0.1); + border-radius: 99px; + display: flex; + align-items: center; + padding: 2px; + transition: background 0.2s ease; +} + +.devpanel__toggle input:checked + .devpanel__toggle-track { + background: rgba(99, 102, 241, 0.85); +} + +.devpanel__toggle-thumb { + width: 16px; + height: 16px; + border-radius: 50%; + background: #fff; + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.devpanel__toggle input:checked + .devpanel__toggle-track .devpanel__toggle-thumb { + transform: translateX(16px); +} + +/* FPS bar */ +.devpanel__fps-bar-wrap { + height: 3px; + background: rgba(255,255,255,0.08); + border-radius: 99px; + margin-top: 0.6rem; + overflow: hidden; +} +.devpanel__fps-bar { + height: 100%; + width: 100%; + border-radius: 99px; + background: #27c93f; + transition: width 0.3s ease, background 0.3s ease; +} + +/* Footer */ +.devpanel__footer { + padding: 0.5rem 1rem; + border-top: 1px solid rgba(255,255,255,0.05); + text-align: center; +} +.devpanel__footer-line { + font-size: 0.62rem; + color: rgba(255,255,255,0.2); + letter-spacing: 0.04em; +} + +/* ============================================ + DEVPANEL — Thème clair + ============================================ */ + +[data-theme="light"] .devpanel { + background: rgba(250, 250, 249, 0.97); + border-color: rgba(79, 70, 229, 0.18); + box-shadow: 0 24px 48px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(79,70,229,0.06); + color: #4b5563; +} + +[data-theme="light"] .devpanel__header { + border-bottom-color: rgba(0, 0, 0, 0.06); +} + +[data-theme="light"] .devpanel__title-label { + color: rgba(26, 26, 46, 0.35); +} + +[data-theme="light"] .devpanel__fps-live { + color: rgba(26, 26, 46, 0.45); +} + +[data-theme="light"] .devpanel__section { + border-bottom-color: rgba(0, 0, 0, 0.05); +} + +[data-theme="light"] .devpanel__section-label { + color: rgba(79, 70, 229, 0.7); +} + +[data-theme="light"] .devpanel__row-label { + color: rgba(26, 26, 46, 0.65); +} + +[data-theme="light"] .devpanel__seg { + background: rgba(0, 0, 0, 0.05); +} + +[data-theme="light"] .devpanel__seg-btn { + color: rgba(26, 26, 46, 0.4); +} + +[data-theme="light"] .devpanel__seg-btn:hover { + color: rgba(26, 26, 46, 0.7); +} + +[data-theme="light"] .devpanel__toggle-track { + background: rgba(0, 0, 0, 0.1); +} + +[data-theme="light"] .devpanel__fps-bar-wrap { + background: rgba(0, 0, 0, 0.07); +} + +[data-theme="light"] .devpanel__footer { + border-top-color: rgba(0, 0, 0, 0.05); +} + +[data-theme="light"] .devpanel__footer-line { + color: rgba(26, 26, 46, 0.2); +} + +/* Curseur désactivé */ +.cursor-disabled .cursor-dot, +.cursor-disabled .cursor-ring { + display: none !important; +} + +@media (hover: hover) and (pointer: fine) { + html:not(.cursor-disabled), + html:not(.cursor-disabled) * { + cursor: none !important; + } +} + +/* ============================================ + CUSTOM CURSOR — Dot + Ring + Uniquement sur appareils à pointeur précis + ============================================ */ + +@media (hover: hover) and (pointer: fine) { + + /* Base commune aux deux éléments */ + .cursor-dot, + .cursor-ring { + position: fixed; + top: 0; + left: 0; + border-radius: 50%; + pointer-events: none; + /* transform: translate(-50%, -50%) gère le centrage sur la position JS */ + transform: translate(-50%, -50%); + opacity: 0; + /* left/top mis à jour par JS sans transition (smooth natif via RAF) */ + /* Les autres props ont des transitions CSS */ + transition: + width 0.3s var(--ease-out), + height 0.3s var(--ease-out), + opacity 0.3s var(--ease-out), + background-color var(--duration-theme) var(--ease-out), + border-color var(--duration-theme) var(--ease-out); + } + + /* ── Point central (suit la souris instantanément) ── */ + .cursor-dot { + width: 7px; + height: 7px; + background-color: var(--accent); + z-index: 999999; + } + + /* ── Anneau (suit avec un léger retard via lerp JS) ── */ + .cursor-ring { + width: 38px; + height: 38px; + border: 1.5px solid var(--accent); + background-color: transparent; + z-index: 999998; + } + + /* États : visible */ + .cursor-dot.is-visible { opacity: 1; } + .cursor-ring.is-visible { opacity: 0.45; } + + /* États : survol d'un élément interactif */ + .cursor-dot.is-hovering { opacity: 0; } + .cursor-ring.is-hovering { + width: 52px; + height: 52px; + border-color: #c8fa00; + border-width: 2px; + opacity: 0.9; + } + + /* États : clic */ + .cursor-dot.is-clicking { width: 12px; height: 12px; } + .cursor-ring.is-clicking { + width: 28px; + height: 28px; + opacity: 0.8; + transition-duration: 0.08s; + } + + /* Le stretch de scroll est géré entièrement en JS (RAF + vélocité) + — pas de classes CSS pour cet état */ +} diff --git a/assets/fonts/inter-latin-ext.woff2 b/assets/fonts/inter-latin-ext.woff2 new file mode 100644 index 0000000..479d010 Binary files /dev/null and b/assets/fonts/inter-latin-ext.woff2 differ diff --git a/assets/fonts/inter-latin.woff2 b/assets/fonts/inter-latin.woff2 new file mode 100644 index 0000000..d15208d Binary files /dev/null and b/assets/fonts/inter-latin.woff2 differ diff --git a/assets/fonts/jetbrains-mono-latin-ext.woff2 b/assets/fonts/jetbrains-mono-latin-ext.woff2 new file mode 100644 index 0000000..82f9668 Binary files /dev/null and b/assets/fonts/jetbrains-mono-latin-ext.woff2 differ diff --git a/assets/fonts/jetbrains-mono-latin.woff2 b/assets/fonts/jetbrains-mono-latin.woff2 new file mode 100644 index 0000000..4d09cda Binary files /dev/null and b/assets/fonts/jetbrains-mono-latin.woff2 differ diff --git a/assets/img/favicon.svg b/assets/img/favicon.svg new file mode 100644 index 0000000..9b225f4 --- /dev/null +++ b/assets/img/favicon.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + diff --git a/assets/img/projects/.gitkeep b/assets/img/projects/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/assets/img/tony.png b/assets/img/tony.png new file mode 100644 index 0000000..e2205f6 Binary files /dev/null and b/assets/img/tony.png differ diff --git a/assets/js/error-page.js b/assets/js/error-page.js new file mode 100644 index 0000000..9a55501 --- /dev/null +++ b/assets/js/error-page.js @@ -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 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'); + }); + } + +})(); diff --git a/assets/js/main.js b/assets/js/main.js new file mode 100644 index 0000000..1c9e8d9 --- /dev/null +++ b/assets/js/main.js @@ -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); + } + +})(); diff --git a/config/bootstrap.php b/config/bootstrap.php new file mode 100644 index 0000000..2223fb7 --- /dev/null +++ b/config/bootstrap.php @@ -0,0 +1,114 @@ + + */ + 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; + } +} diff --git a/config/database.php b/config/database.php new file mode 100644 index 0000000..850e962 --- /dev/null +++ b/config/database.php @@ -0,0 +1,44 @@ + 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; +} diff --git a/config/imap.php b/config/imap.php new file mode 100644 index 0000000..72dc6d5 --- /dev/null +++ b/config/imap.php @@ -0,0 +1,15 @@ + '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, +]; diff --git a/config/recaptcha.php b/config/recaptcha.php new file mode 100644 index 0000000..dbfa939 --- /dev/null +++ b/config/recaptcha.php @@ -0,0 +1,27 @@ + '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 !== ''); +} diff --git a/config/smtp.php b/config/smtp.php new file mode 100644 index 0000000..d5db4cc --- /dev/null +++ b/config/smtp.php @@ -0,0 +1,16 @@ +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 ). + */ +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('//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); +} diff --git a/deploy/nginx-error-pages.conf b/deploy/nginx-error-pages.conf new file mode 100644 index 0000000..bddcf5a --- /dev/null +++ b/deploy/nginx-error-pages.conf @@ -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; +} diff --git a/deploy/nginx-security.conf.example b/deploy/nginx-security.conf.example new file mode 100644 index 0000000..f7545da --- /dev/null +++ b/deploy/nginx-security.conf.example @@ -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; + } +} diff --git a/errors/403.php b/errors/403.php new file mode 100644 index 0000000..73483d6 --- /dev/null +++ b/errors/403.php @@ -0,0 +1,146 @@ + + + + + + + Accès refusé — Tony AVERTY + + + + + + + + +
+ + +
+
+ +

Accès non autorisé

+

+ 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. +

+ +
+
+ + +
+ + + + + + + + diff --git a/errors/404.php b/errors/404.php new file mode 100644 index 0000000..39000c3 --- /dev/null +++ b/errors/404.php @@ -0,0 +1,146 @@ + + + + + + + Page introuvable — Tony AVERTY + + + + + + + + +
+ + +
+
+ +

Cette page n'existe pas

+

+ 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. +

+ +
+
+ + +
+ + + + + + + + diff --git a/errors/500.php b/errors/500.php new file mode 100644 index 0000000..7922f2f --- /dev/null +++ b/errors/500.php @@ -0,0 +1,146 @@ + + + + + + + Erreur serveur — Tony AVERTY + + + + + + + + +
+ + +
+
+ +

Une erreur est survenue

+

+ 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. +

+ +
+
+ + +
+ + + + + + + + diff --git a/includes/Mailer.php b/includes/Mailer.php new file mode 100644 index 0000000..546e422 --- /dev/null +++ b/includes/Mailer.php @@ -0,0 +1,251 @@ +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)); + } +} diff --git a/includes/Security.php b/includes/Security.php new file mode 100644 index 0000000..1584fec --- /dev/null +++ b/includes/Security.php @@ -0,0 +1,484 @@ + $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 $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 ''; + } + + /** + * 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 $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.'); + } +} diff --git a/includes/footer.php b/includes/footer.php new file mode 100644 index 0000000..8b7c740 --- /dev/null +++ b/includes/footer.php @@ -0,0 +1,173 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/includes/header.php b/includes/header.php new file mode 100644 index 0000000..c3e8ff0 --- /dev/null +++ b/includes/header.php @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + Tony AVERTY — Développeur Web Freelance | Sites sur mesure & Applications + + + + + + + + + + + + + + diff --git a/includes/projects.php b/includes/projects.php new file mode 100644 index 0000000..141b81d --- /dev/null +++ b/includes/projects.php @@ -0,0 +1,65 @@ +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)); +} diff --git a/index.php b/index.php new file mode 100644 index 0000000..6a01024 --- /dev/null +++ b/index.php @@ -0,0 +1,566 @@ + 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} = ?"; +?> + + +
+ + + + +
+ + +
+
+
+
+ + Disponible pour nouveaux projets +
+

+ Du code propre.
+ Des interfaces claires.
+ Des projets qui tiennent. +

+

+ Je conçois des sites et applications web sur mesure, adaptés à votre activité. Design soigné, code solide, livraison dans les délais convenus. +

+ +
+ Stack principale : +
+ HTML / CSS + JavaScript + PHP + SQL +
+
+
+ + + +
+
+ +
+ + + + +
+
+
+ + +
+
+
+
+ Tony AVERTY, développeur web freelance +
+
+
+ +
+ Aujourd'hui +

Développeur freelance & fondateur CodeBzh

+
+
+
+ +
+ Formation +

Développement web — HTML, CSS, JS, PHP, SQL

+
+
+
+ +
+ Les débuts +

Passion pour le web et le code

+
+
+
+
+
+

Développeur freelance. Fondateur d'agence. La même exigence pour votre projet.

+

+ 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. +

+

+ 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. +

+

+ 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. +

+

+ 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. +

+
+
+ + Fondateur de CodeBzh, agence web active en Bretagne +
+
+ + Chaque projet construit sur mesure, de la maquette à la mise en ligne +
+
+ + Réponse garantie sous 24h — toujours +
+
+
+
+
+
+ + + + +
+
+
+ + +
+

Les technologies que je maîtrise

+

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.

+ +
+ +
+

+ Maîtrise avancée +

+
+
+
+ +
+

HTML / CSS

+

Structure visuelle, mise en page, animations, compatibilité tous appareils.

+
+
+
+ +
+

PHP

+

Développement côté serveur : gestion des données, authentification, formulaires, espaces membres.

+
+
+
+ +
+

JavaScript

+

Interactions, animations et éléments dynamiques côté navigateur.

+
+
+
+ + +
+

+ Bon niveau +

+
+
+
+ +
+

Python

+

Automatisation, traitement de données et développement d'outils utilitaires.

+
+
+
+ +
+

SQL

+

Modélisation, création et gestion de bases de données relationnelles.

+
+
+
+ +
+

Linux / VPS

+

Administration serveur, déploiement et configuration d'environnements d'hébergement.

+
+
+
+
+ + +
+

Outils & méthodes

+
+ + + Git + + + + VS Code + + + + Figma + + + + MySQL + + + + Terminal + + + + Linux + + + + SSH + + + + VPS + + + + Réseau + + + + Responsive Design + + + + SEO + + + + Performance Web + +
+
+
+
+ + + + + +
+
+
+ + +
+

Ce que j'ai construit

+

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.

+ +
+ + + +
+
+
+ + + + + +
+
+
+ + +
+

Ce que je peux faire pour vous

+

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.

+ +
+
+ +

Site vitrine

+

Un site professionnel qui représente votre activité avec précision. Design soigné, contenu structuré, conçu pour inciter vos visiteurs à vous contacter.

+
+ +
+ +

Refonte

+

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.

+
+ +
+ +

Maintenance

+

Corrections, mises à jour, évolutions : je m'occupe de garder votre site fonctionnel, sécurisé et à jour dans la durée.

+
+ +
+ +

UI Design

+

Des interfaces conçues pour que vos visiteurs trouvent l'information sans effort. Navigation claire, design cohérent, rendu soigné sur tous les supports.

+
+ +
+ +

Back-end

+

Développement côté serveur : formulaires, espaces membres, gestion de contenu, tableau de bord administrateur — tout ce qui structure le fonctionnement de votre site.

+
+ +
+ +

SEO

+

Apparaître sur Google lorsqu'un client recherche votre activité. Structure technique optimisée, contenu pertinent, référencement naturel solide.

+
+
+ + +
+
+ + + + +
+
+
+ + +
+

Un projet en tête ? Même flou, même en deux lignes.

+

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.

+ +
+
+
+

Parlons de votre projet

+

+ 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é. +

+
+

Comment ça se passe ensuite ?

+
    +
  1. Vous m'écrivez
  2. +
  3. On échange 20 minutes
  4. +
  5. Je vous propose une approche claire
  6. +
+
+ +
+ + Réponse sous 24 à 48h +
+
+
+ +
> + + + + + + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ + + + +

+ Ce site est protégé par reCAPTCHA. La + politique de confidentialité + et les + conditions d'utilisation + de Google s'appliquent. +

+ +
+
+
+
+ +
+ + diff --git a/legal.php b/legal.php new file mode 100644 index 0000000..5b99449 --- /dev/null +++ b/legal.php @@ -0,0 +1,433 @@ + + + + + + + + + Mentions légales & RGPD — Tony AVERTY + + + + + + + +
+
+ + + + Retour au portfolio + + +

Informations légales

+ + + + + + + + + + + + + +
+
+ + + + + diff --git a/sql/migrations/001_backoffice.sql b/sql/migrations/001_backoffice.sql new file mode 100644 index 0000000..f551504 --- /dev/null +++ b/sql/migrations/001_backoffice.sql @@ -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 ', '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'); diff --git a/sql/migrations/002_email_threading.sql b/sql/migrations/002_email_threading.sql new file mode 100644 index 0000000..914d55a --- /dev/null +++ b/sql/migrations/002_email_threading.sql @@ -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; diff --git a/sql/schema.sql b/sql/schema.sql new file mode 100644 index 0000000..e6e2282 --- /dev/null +++ b/sql/schema.sql @@ -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' +); diff --git a/vhost.txt b/vhost.txt new file mode 100644 index 0000000..acc1f62 --- /dev/null +++ b/vhost.txt @@ -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; + } +} \ No newline at end of file