| Server IP : 80.211.21.168 / Your IP : 216.73.217.143 Web Server : Apache System : Linux alex-webdesign.it 3.10.0-1160.119.1.el7.tuxcare.els22.x86_64 #1 SMP Mon Aug 18 06:07:12 UTC 2025 x86_64 User : admin_japan ( 10003) PHP Version : 8.2.32 Disable Function : opcache_get_status MySQL : OFF | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /var/www/vhosts/cerchijapan.it/ai4dealers.com/ |
Upload File : |
<?php
// ──────────────────────────────────────────────────────────────────────────────
// STAMPA ULTIME 10 MAIL DA UN MITTENTE (con ricerca <phone> + numeri in span)
// v5 – parsing MIME "a mano" + DOM/XPath per <span class="details-variable">
// ──────────────────────────────────────────────────────────────────────────────
header('Content-Type: text/plain; charset=UTF-8');
// ── CONFIGURAZIONE ────────────────────────────────────────────────────────────
$tenantId = 'e3b2c92f-a03f-4cd7-919d-29e57ef9c4d2';
$clientId = '29b2b722-1833-4976-b6c1-1a68db0a6427';
$clientSecret = 'lty8Q~EAe2u.9GfurQ8IvwPK.Mtwp2pNGPtUFcKd';
$mailboxUser = 'richieste@liberini.it';
$targetSender = 'no-reply@rtm.autoscout24.com';
$maxToShow = 10; // quante email mostrare
// ── FUNZIONE NUOVA: estrae numeri telefono da HTML ───────────────────────────
function estraiNumeriTelefono(string $html, bool $strip = true): array
{
$doc = new DOMDocument();
@$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//span[contains(@class,"details-variable")]');
$trovati = [];
foreach ($nodes as $n) {
$txt = trim($n->textContent);
if (preg_match('/^\+?\d[\d .]{5,}$/', $txt)) {
if ($strip) {
$txt = preg_replace('/\D+/', '', $txt);
}
$trovati[] = $txt;
}
}
return $trovati;
}
// ── FUNZIONE NUOVA: estrae URL annuncio da redirect esvalabs ────────────────
/**
* Cerca in $html un link a urlsand.esvalabs.com, estrae il parametro "u",
* decodifica l'URL e restituisce solo se contiene "autoscout24.it/annunci/".
*
* @param string $html
* @return string|null
*/
function estraiUrlAnnuncio(string $html): ?string
{
// trova tutte le occorrenze
if (preg_match_all('#https?://urlsand\.esvalabs\.com/\?[^"\s]+#i', $html, $matches)) {
foreach ($matches[0] as $redir) {
$parts = parse_url($redir);
if (empty($parts['query'])) {
continue;
}
// parse query string
parse_str($parts['query'], $qs);
if (empty($qs['u'])) {
continue;
}
$decoded = urldecode($qs['u']);
// verifica che sia un URL AutoScout con /annunci/
if (stripos($decoded, 'autoscout24.it') !== false
&& stripos($decoded, '/annunci/') !== false
) {
// rimuove eventuale "www."
$clean = preg_replace('#^https?://www\.#i', 'https://', $decoded);
return $clean;
}
}
}
return null;
}
// ── FUNZIONI UTILITY HTTP / GRAPH / MIME (invariato) ─────────────────────────
function request(string $method, string $url, array $headers = [], $postFields = null): array {
$ch = curl_init($url);
$opts = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FAILONERROR => false,
];
if ($method === 'POST') {
if (is_array($postFields)) {
$opts[CURLOPT_POSTFIELDS] = http_build_query($postFields);
} elseif (is_string($postFields)) {
$opts[CURLOPT_POSTFIELDS] = $postFields;
}
}
curl_setopt_array($ch, $opts);
$raw = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($raw === false) {
die("Errore cURL su {$url}: " . curl_error($ch));
}
curl_close($ch);
return [$http, $raw];
}
function getAccessToken(): string {
global $tenantId, $clientId, $clientSecret;
[$http, $raw] = request('POST',
"https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/token",
['Content-Type: application/x-www-form-urlencoded'],
[
'client_id' => $clientId,
'scope' => 'https://graph.microsoft.com/.default',
'client_secret' => $clientSecret,
'grant_type' => 'client_credentials'
]
);
if ($http !== 200) {
die("Errore fetching token (HTTP {$http}):\n{$raw}\n");
}
$data = json_decode($raw, true);
return $data['access_token'] ?? die("Impossibile ottenere access_token\n");
}
function graphGetJSON(string $url, string $token): array {
[$http, $raw] = request('GET', $url, [
"Authorization: Bearer {$token}",
'Accept: application/json'
]);
if ($http >= 400) {
die("Errore Graph (HTTP {$http}) su {$url}:\n{$raw}\n");
}
$data = json_decode($raw, true);
if ($data === null) {
die("Risposta non valida JSON da Graph:\n{$raw}\n");
}
return $data;
}
function getRawMime(string $messageId, string $token, string $mailboxUser): string {
[$http, $raw] = request('GET',
"https://graph.microsoft.com/v1.0/users/{$mailboxUser}/messages/{$messageId}/\$value",
["Authorization: Bearer {$token}"]
);
if ($http >= 400) {
die("Errore Graph (HTTP {$http}) per .eml:\n{$raw}\n");
}
return $raw;
}
function decodeBodyParts(string $rawMime): array {
$parts = [];
if (!preg_match('/\bboundary="?([^";]+)"?/i', $rawMime, $m)) {
$parts[] = transferDecode($rawMime, 'quoted-printable');
return $parts;
}
$boundary = trim($m[1]);
$chunks = preg_split('/--' . preg_quote($boundary, '/') . '(?:--)?\s*\r?\n/', $rawMime);
array_shift($chunks);
foreach ($chunks as $chunk) {
if (trim($chunk) === '') continue;
[$hdr, $body] = preg_split("/\r?\n\r?\n/", $chunk, 2);
$ctype = 'text/plain'; $enc = '7bit';
if (preg_match('/Content-Type:\s*([^;\r\n]+)/i', $hdr, $mm)) $ctype = strtolower(trim($mm[1]));
if (preg_match('/Content-Transfer-Encoding:\s*([^\r\n]+)/i', $hdr, $mm)) $enc = strtolower(trim($mm[1]));
if (strpos($ctype, 'multipart/') === 0) {
$parts = array_merge($parts, decodeBodyParts($chunk));
continue;
}
if ($ctype === 'text/html' || $ctype === 'text/plain') {
$parts[] = transferDecode($body, $enc);
}
}
return $parts;
}
function transferDecode(string $data, string $encoding): string {
return match ($encoding) {
'base64' => base64_decode(trim($data), true) ?: $data,
'quoted-printable' => quoted_printable_decode($data),
default => $data
};
}
// ── MAIN ─────────────────────────────────────────────────────────────────────
$token = getAccessToken();
$query = http_build_query([
'$top' => 100,
'$select' => 'id,from,subject,receivedDateTime',
'$orderby' => 'receivedDateTime desc'
]);
$list = graphGetJSON("https://graph.microsoft.com/v1.0/users/{$mailboxUser}/mailFolders/Inbox/messages?{$query}", $token);
if (empty($list['value'])) die("Nessuna mail nella Inbox\n");
$matches = array_values(array_filter($list['value'], fn($m) => strcasecmp($m['from']['emailAddress']['address'] ?? '', $targetSender) === 0));
if (!$matches) die("Nessuna mail da {$targetSender}\n");
usort($matches, fn($a,$b) => strcmp($b['receivedDateTime'], $a['receivedDateTime']));
$matches = array_slice($matches, 0, $maxToShow);
foreach ($matches as $idx => $msg) {
echo "=== MAIL #" . ($idx + 1) . " ============================================\n";
echo "Da: {$msg['from']['emailAddress']['address']}\n";
echo "Oggetto: " . ($msg['subject'] ?: '(nessun oggetto)') . "\n";
echo "Ricevuta: {$msg['receivedDateTime']}\n\n";
// --- RAW MIME ------------------------------------------------------------
$rawMime = getRawMime($msg['id'], $token, $mailboxUser);
// --- PARSING MIME & RICERCA <phone> --------------------------------------
$decodedParts = decodeBodyParts($rawMime);
$allHtml = implode("\n\n", $decodedParts);
// 1) <phone> tag eventualmente presenti:
if (preg_match_all('/<phone\b[^>]*>(.*?)<\/phone>/is', $allHtml, $phones)) {
echo "=== TAG <phone> TROVATI ===\n";
foreach ($phones[1] as $p) echo trim($p) . "\n";
echo "\n";
} else {
echo "(Nessun tag <phone> trovato)\n";
}
// 2) <span class="details-variable"> con numero di telefono:
$numeri = estraiNumeriTelefono($allHtml);
if ($numeri) {
echo "=== NUMERI in <span class=\"details-variable\"> ===\n";
foreach ($numeri as $n) echo $n . "\n";
} else {
echo "(Nessun numero individuato negli span)\n";
}
echo "\n";
// 3) URL annuncio AutoScout24:
$annuncio = estraiUrlAnnuncio($allHtml);
if ($annuncio) {
echo "=== URL ANNUNCIO ===\n{$annuncio}\n\n";
} else {
echo "(Nessun URL AutoScout24 trovato)\n\n";
}
// --- DEBUG opzionale: snippet HTML -----------------
echo "--- snippet HTML estratto (primi 300 char) ---\n";
echo $allHtml . " …\n\n";
}
?>