Paaxio 1.0
Plateforme de streaming musical - SAE IUT Bayonne
Chargement...
Recherche...
Aucune correspondance
email.class.php
Aller à la documentation de ce fichier.
1<?php
2
3use PHPMailer\PHPMailer\PHPMailer;
4use PHPMailer\PHPMailer\SMTP;
5use PHPMailer\PHPMailer\Exception;
6
11class Email
12{
13 private array $mailConfig;
14 private \Twig\Environment $twig;
15
20 public function __construct(\Twig\Environment $twig)
21 {
22 $this->twig = $twig;
23 $this->loadMailConfig();
24 }
25
30 private function loadMailConfig(): void
31 {
32 $configPath = __DIR__ . '/../config/config.json';
33 if (!file_exists($configPath)) {
34 throw new Exception('Fichier de configuration introuvable.');
35 }
36
37 $config = json_decode(file_get_contents($configPath), true);
38 if (!isset($config['mail'])) {
39 throw new Exception('Configuration email manquante dans config.json');
40 }
41
42 $this->mailConfig = $config['mail'];
43 }
44
49 private function createMailer(): PHPMailer
50 {
51 $mail = new PHPMailer(true);
52
53 // Configuration du serveur SMTP
54 $mail->isSMTP();
55 $mail->Host = $this->mailConfig['host'];
56 $mail->SMTPAuth = true;
57 $mail->Username = $this->mailConfig['username'];
58 $mail->Password = $this->mailConfig['password'];
59 $mail->Port = $this->mailConfig['port'];
60
61 // Configuration du chiffrement
62 $encryption = $this->mailConfig['encryption'] ?? 'tls';
63 if ($encryption === 'tls') {
64 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
65 } elseif ($encryption === 'ssl') {
66 $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
67 }
68
69 // Configuration de l'expéditeur
70 $mail->setFrom(
71 $this->mailConfig['from_email'],
72 $this->mailConfig['from_name']
73 );
74
75 // Configuration du charset
76 $mail->CharSet = 'UTF-8';
77 $mail->isHTML(true);
78
79 return $mail;
80 }
81
92 public function sendEmail(string $to, string $toName, string $subject, string $htmlBody, ?string $textBody = null): bool
93 {
94 try {
95 $mail = $this->createMailer();
96 $mail->addAddress($to, $toName);
97 $mail->Subject = $subject;
98 $mail->Body = $htmlBody;
99 $mail->AltBody = $textBody ?? strip_tags($htmlBody);
100
101 return $mail->send();
102 } catch (Exception $e) {
103 error_log("Erreur d'envoi d'email: " . $e->getMessage());
104 throw new Exception("Impossible d'envoyer l'email: " . $e->getMessage());
105 }
106 }
107
115 public function sendWelcomeEmail(string $email, string $pseudo, string $type): bool
116 {
117 $subject = "Bienvenue sur Paaxio, $pseudo !";
118
119 $htmlBody = $this->twig->render('emails/welcome.html.twig', [
120 'pseudo' => $pseudo,
121 'email' => $email,
122 'type' => $type,
123 'site_url' => $this->getSiteUrl()
124 ]);
125
126 $textBody = "Bienvenue sur Paaxio, $pseudo !\n\n";
127 $textBody .= "Votre compte $type a été créé avec succès.\n";
128 $textBody .= "Vous pouvez dès maintenant vous connecter et profiter de toutes les fonctionnalités de Paaxio.\n\n";
129 $textBody .= "À bientôt sur Paaxio !";
130
131 return $this->sendEmail($email, $pseudo, $subject, $htmlBody, $textBody);
132 }
133
141 public function sendConfirmationEmail(string $email, string $pseudo, string $confirmationToken): bool
142 {
143 $subject = "Confirmez votre inscription sur Paaxio";
144
145 $confirmationUrl = $this->getSiteUrl() . "/?controller=utilisateur&method=confirmer&token=" . urlencode($confirmationToken);
146
147 $htmlBody = $this->twig->render('emails/confirmation.html.twig', [
148 'pseudo' => $pseudo,
149 'confirmation_url' => $confirmationUrl,
150 'site_url' => $this->getSiteUrl()
151 ]);
152
153 $textBody = "Bonjour $pseudo,\n\n";
154 $textBody .= "Merci de vous être inscrit sur Paaxio !\n\n";
155 $textBody .= "Pour confirmer votre inscription, veuillez cliquer sur le lien suivant :\n";
156 $textBody .= "$confirmationUrl\n\n";
157 $textBody .= "Ce lien est valable 24 heures.\n\n";
158 $textBody .= "Si vous n'avez pas créé de compte sur Paaxio, ignorez cet email.";
159
160 return $this->sendEmail($email, $pseudo, $subject, $htmlBody, $textBody);
161 }
162
170 public function sendPasswordResetEmail(string $email, string $pseudo, string $resetToken): bool
171 {
172 $subject = "Réinitialisation de votre mot de passe Paaxio";
173
174 $resetUrl = $this->getSiteUrl() . "/?controller=utilisateur&method=resetPassword&token=" . urlencode($resetToken);
175
176 $htmlBody = $this->twig->render('emails/password_reset.html.twig', [
177 'pseudo' => $pseudo,
178 'reset_url' => $resetUrl,
179 'site_url' => $this->getSiteUrl()
180 ]);
181
182 $textBody = "Bonjour $pseudo,\n\n";
183 $textBody .= "Vous avez demandé la réinitialisation de votre mot de passe sur Paaxio.\n\n";
184 $textBody .= "Pour réinitialiser votre mot de passe, cliquez sur le lien suivant :\n";
185 $textBody .= "$resetUrl\n\n";
186 $textBody .= "Ce lien est valable 1 heure.\n\n";
187 $textBody .= "Si vous n'avez pas demandé cette réinitialisation, ignorez cet email.";
188
189 return $this->sendEmail($email, $pseudo, $subject, $htmlBody, $textBody);
190 }
191
200 public function sendNewsletterEmail(string $email, string $subject, string $content, ?string $unsubscribeToken = null): bool
201 {
202 $unsubscribeUrl = $unsubscribeToken
203 ? $this->getSiteUrl() . "/?controller=newsletter&method=desinscrire&token=" . urlencode($unsubscribeToken)
204 : null;
205
206 $htmlBody = $this->twig->render('emails/newsletter.html.twig', [
207 'content' => $content,
208 'unsubscribe_url' => $unsubscribeUrl,
209 'site_url' => $this->getSiteUrl()
210 ]);
211
212 $textBody = strip_tags($content);
213 if ($unsubscribeUrl) {
214 $textBody .= "\n\n---\nPour vous désinscrire : $unsubscribeUrl";
215 }
216
217 return $this->sendEmail($email, '', $subject, $htmlBody, $textBody);
218 }
219
228 public function sendNotificationEmail(string $email, string $pseudo, string $type, array $data = []): bool
229 {
230 $subjects = [
231 'new_album' => 'Nouvel album disponible !',
232 'new_follower' => 'Vous avez un nouveau follower !',
233 'new_like' => 'Quelqu\'un a aimé votre musique !',
234 'battle_invite' => 'Invitation à une battle musicale !',
235 'battle_result' => 'Résultats de la battle musicale'
236 ];
237
238 $subject = $subjects[$type] ?? 'Notification Paaxio';
239
240 $htmlBody = $this->twig->render("emails/notification_$type.html.twig", array_merge([
241 'pseudo' => $pseudo,
242 'site_url' => $this->getSiteUrl()
243 ], $data));
244
245 return $this->sendEmail($email, $pseudo, $subject, $htmlBody);
246 }
247
256 public function sendContactEmail(string $fromEmail, string $fromName, string $subject, string $message): bool
257 {
258 $contactEmail = $this->mailConfig['from_email']; // Email de contact de Paaxio
259
260 $htmlBody = $this->twig->render('emails/contact.html.twig', [
261 'from_email' => $fromEmail,
262 'from_name' => $fromName,
263 'subject' => $subject,
264 'message' => $message,
265 'site_url' => $this->getSiteUrl()
266 ]);
267
268 $textBody = "Message de contact reçu\n\n";
269 $textBody .= "De: $fromName <$fromEmail>\n";
270 $textBody .= "Sujet: $subject\n\n";
271 $textBody .= "Message:\n$message";
272
273 try {
274 $mail = $this->createMailer();
275 $mail->addAddress($contactEmail, 'Paaxio Contact');
276 $mail->addReplyTo($fromEmail, $fromName);
277 $mail->Subject = "[Contact] $subject";
278 $mail->Body = $htmlBody;
279 $mail->AltBody = $textBody;
280
281 return $mail->send();
282 } catch (Exception $e) {
283 error_log("Erreur d'envoi d'email de contact: " . $e->getMessage());
284 throw new Exception("Impossible d'envoyer le message de contact: " . $e->getMessage());
285 }
286 }
287
295 public function sendBulkEmail(array $recipients, string $subject, string $content): array
296 {
297 $results = [
298 'success' => 0,
299 'failed' => 0,
300 'errors' => []
301 ];
302
303 foreach ($recipients as $recipient) {
304 try {
305 $email = is_array($recipient) ? $recipient['email'] : $recipient;
306 $token = is_array($recipient) ? ($recipient['token'] ?? null) : null;
307
308 if ($this->sendNewsletterEmail($email, $subject, $content, $token)) {
309 $results['success']++;
310 } else {
311 $results['failed']++;
312 $results['errors'][] = "Échec de l'envoi à $email";
313 }
314
315 // Petite pause pour éviter de surcharger le serveur SMTP
316 usleep(100000); // 100ms
317 } catch (Exception $e) {
318 $results['failed']++;
319 $results['errors'][] = "Erreur pour $email: " . $e->getMessage();
320 }
321 }
322
323 return $results;
324 }
325
330 private function getSiteUrl(): string
331 {
332 $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
333 $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
334 return "$protocol://$host";
335 }
336
342 public static function generateToken(int $length = 32): string
343 {
344 return bin2hex(random_bytes($length));
345 }
346
351 public function testSmtpConnection(): array
352 {
353 try {
354 $mail = $this->createMailer();
355 $mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
356
357 ob_start();
358 $mail->smtpConnect();
359 $mail->smtpClose();
360 $debug = ob_get_clean();
361
362 return [
363 'success' => true,
364 'message' => 'Connexion SMTP réussie',
365 'debug' => $debug
366 ];
367 } catch (Exception $e) {
368 return [
369 'success' => false,
370 'message' => 'Échec de la connexion SMTP: ' . $e->getMessage()
371 ];
372 }
373 }
374
380 public function testEmail(): array
381 {
382 $fakeName = "Angel Ramirez";
383 $fakeEmail = "contact@angelbatalla.com";
384 $fakeType = "auditeur";
385
386 try {
387 $result = $this->sendWelcomeEmail($fakeEmail, $fakeName, $fakeType);
388 if ($result) {
389 return [
390 'success' => true,
391 'message' => "L'email de bienvenue a bien été envoyé à $fakeEmail."
392 ];
393 } else {
394 return [
395 'success' => false,
396 'message' => "L'envoi de l'email de bienvenue a échoué pour $fakeEmail."
397 ];
398 }
399 } catch (Exception $e) {
400 return [
401 'success' => false,
402 'message' => "Erreur lors de l'envoi de l'email : " . $e->getMessage()
403 ];
404 }
405 }
406}
Classe de gestion des emails pour Paaxio Utilise PHPMailer pour l'envoi d'emails via SMTP.
sendContactEmail(string $fromEmail, string $fromName, string $subject, string $message)
Envoie un email de contact (depuis le formulaire de contact)
sendNotificationEmail(string $email, string $pseudo, string $type, array $data=[])
Envoie un email de notification (nouvel album, nouveau follower, etc.)
sendNewsletterEmail(string $email, string $subject, string $content, ?string $unsubscribeToken=null)
Envoie un email de newsletter.
Twig Environment $twig
sendWelcomeEmail(string $email, string $pseudo, string $type)
Envoie un email de bienvenue à un nouvel utilisateur.
sendPasswordResetEmail(string $email, string $pseudo, string $resetToken)
Envoie un email de réinitialisation de mot de passe.
array $mailConfig
__construct(\Twig\Environment $twig)
Constructeur de la classe Email.
testEmail()
Fonction de test simple de la classe Email avec un nom et un email factices.
sendConfirmationEmail(string $email, string $pseudo, string $confirmationToken)
Envoie un email de confirmation d'inscription.
sendEmail(string $to, string $toName, string $subject, string $htmlBody, ?string $textBody=null)
Envoie un email générique.
loadMailConfig()
Charge la configuration email depuis le fichier config.json.
sendBulkEmail(array $recipients, string $subject, string $content)
Envoie un email en masse à plusieurs destinataires (pour la newsletter)
createMailer()
Crée et configure une instance PHPMailer.
static generateToken(int $length=32)
Génère un token sécurisé
testSmtpConnection()
Teste la configuration SMTP.
getSiteUrl()
Récupère l'URL du site.