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