๐ Source: chat_handler.php
<?php
session_name('INBOXZERO');
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['access_token'])) {
echo json_encode(['reply' => 'Please login first']);
exit();
}
require_once 'vendor/autoload.php';
$input = json_decode(file_get_contents('php://input'), true);
$query = trim($input['query'] ?? '');
$lang = $input['lang'] ?? 'en';
$requestedChatId = $input['conversation_id'] ?? null;
$maxEmails = intval($input['max_emails'] ?? 50);
if (empty($query)) {
echo json_encode(['reply' => 'What would you like to know about your emails?']);
exit();
}
function getEmailBodyContent($service, $messageId) {
try {
$message = $service->users_messages->get('me', $messageId, ['format' => 'full']);
$payload = $message->getPayload();
$decode = function($data) {
return base64_decode(strtr($data, '-_', '+/'));
};
$body = "";
if ($payload->getParts()) {
foreach ($payload->getParts() as $part) {
if ($part->getMimeType() == 'text/plain' && $part->getBody() && $part->getBody()->getData()) {
$body = $decode($part->getBody()->getData());
break;
}
}
}
if (empty($body) && $payload->getBody() && $payload->getBody()->getData()) {
$body = $decode($payload->getBody()->getData());
}
if (empty($body) && $payload->getParts()) {
foreach ($payload->getParts() as $part) {
if ($part->getMimeType() == 'text/html' && $part->getBody() && $part->getBody()->getData()) {
$body = $decode($part->getBody()->getData());
break;
}
}
}
if (empty($body)) return "";
$body = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $body);
$body = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $body);
$body = strip_tags($body);
$body = html_entity_decode($body, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$body = preg_replace('/\s+/', ' ', $body);
$body = trim($body);
$body = preg_replace('/https?:\/\/[^\s]+/i', '', $body);
$body = preg_replace('/unsubscribe.*$/i', '', $body);
if (strlen($body) < 20) return "";
return substr($body, 0, 1000);
} catch (Exception $e) {
return "";
}
}
function saveToHistory($chatId, $userMsg, $assistantMsg) {
if (!isset($_SESSION['chat_histories'])) {
$_SESSION['chat_histories'] = [];
}
if (!isset($_SESSION['chat_histories'][$chatId])) {
$_SESSION['chat_histories'][$chatId] = [];
}
$_SESSION['chat_histories'][$chatId][] = "User: $userMsg";
$_SESSION['chat_histories'][$chatId][] = "Assistant: $assistantMsg";
if (count($_SESSION['chat_histories'][$chatId]) > 30) {
$_SESSION['chat_histories'][$chatId] = array_slice($_SESSION['chat_histories'][$chatId], -30);
}
}
// Iniศializare chat ID
if (!$requestedChatId) {
if (isset($_SESSION['current_conversation_id'])) {
$requestedChatId = $_SESSION['current_conversation_id'];
} else {
$requestedChatId = time() . '_' . rand(1000, 9999);
$_SESSION['current_conversation_id'] = $requestedChatId;
}
}
$currentChatId = $requestedChatId;
// Fetch emails
$emailListForDisplay = [];
$totalEmails = 0;
$allEmails = [];
try {
$client = new Google\Client();
$client->setAccessToken($_SESSION['access_token']);
$service = new Google\Service\Gmail($client);
$optParams = ['maxResults' => $maxEmails, 'labelIds' => ['INBOX']];
$messages = $service->users_messages->listUsersMessages('me', $optParams);
if ($messages->getMessages()) {
foreach ($messages->getMessages() as $msg) {
$message = $service->users_messages->get('me', $msg->getId(), [
'format' => 'metadata',
'metadataHeaders' => ['From', 'Subject', 'Date']
]);
$headers = $message->getPayload()->getHeaders();
$from = 'Unknown';
$subject = '(no subject)';
$date = '';
$threadId = $message->getThreadId();
foreach ($headers as $header) {
if ($header->getName() == 'From') $from = $header->getValue();
if ($header->getName() == 'Subject') $subject = $header->getValue();
if ($header->getName() == 'Date') $date = $header->getValue();
}
try {
$dateObj = new DateTime($date);
$dateObj->setTimezone(new DateTimeZone('Europe/Bucharest'));
$dateFormatted = $dateObj->format('d M Y, H:i');
$timestamp = $dateObj->getTimestamp();
} catch (Exception $e) {
$dateFormatted = 'unknown date';
$timestamp = 0;
}
$allEmails[] = [
'from' => $from,
'subject' => $subject,
'date' => $dateFormatted,
'timestamp' => $timestamp,
'threadId' => $threadId,
'id' => $msg->getId()
];
}
}
usort($allEmails, function($a, $b) {
return $b['timestamp'] - $a['timestamp'];
});
$totalEmails = count($allEmails);
foreach ($allEmails as $email) {
$emailListForDisplay[] = [
'from' => htmlspecialchars($email['from']),
'subject' => htmlspecialchars($email['subject']),
'date' => $email['date'],
'id' => $email['id'],
'threadId' => $email['threadId']
];
}
// ============================================
// ANALIZฤ INTELIGENTฤ
// ============================================
$q = strtolower($query);
$reply = "";
$isRomanian = ($lang == 'ro' || strpos($q, 'ศ') !== false || strpos($q, 'ศ') !== false || strpos($q, 'ฤ') !== false);
// ============================================
// 1. REMINDER (prioritate maximฤ)
// ============================================
if (preg_match('/(remind me|set a reminder|set a timer|aminteศte-mi|seteazฤ un reminder|reminder)/i', $query, $matches)) {
// Extrage minutele
if (preg_match('/(\d+)\s*(minute|minutes|min|m)/i', $query, $timeMatches)) {
$minutes = intval($timeMatches[1]);
$reminderText = "Check your email";
// Extrage textul reminder-ului
if (preg_match('/(?:to|about|for|pentru|sฤ)\s+(.+)$/i', $query, $textMatches)) {
$reminderText = trim($textMatches[1]);
}
$reply = $isRomanian
? "๐ Voi trimite o notificare รฎn $minutes minut(e): \"$reminderText\""
: "๐ I'll send a notification in $minutes minute(s): \"$reminderText\"";
// Trimite reminder-ul cฤtre frontend
echo json_encode([
'reply' => $reply,
'reminder' => ['text' => $reminderText, 'minutes' => $minutes],
'emails' => $emailListForDisplay,
'total_emails' => $totalEmails,
'conversation_id' => $currentChatId
]);
exit();
} else {
$reply = $isRomanian
? "โฐ Spune-mi cรขte minute: 'aminteศte-mi รฎn 5 minute sฤ verific emailul'"
: "โฐ Tell me how many minutes: 'remind me in 5 minutes to check my email'";
}
}
// ============================================
// 2. SCRIERE EMAIL (nu e implementat รฎncฤ, dar dฤ un rฤspuns util)
// ============================================
elseif (preg_match('/(write an email|send an email|scrie un email|trimite un email)/i', $query)) {
$reply = $isRomanian
? "๐ง Funcศia de trimis emailuri va fi disponibilฤ รฎn versiunea viitoare. Momentan, รฎศi pot doar citi emailurile."
: "๐ง The email sending feature will be available in a future version. For now, I can only read your emails.";
}
// ============================================
// 3. CONศINUT EMAIL
// ============================================
elseif (strpos($q, 'conศine') !== false || strpos($q, 'spune') !== false ||
strpos($q, 'conศinut') !== false || strpos($q, 'ce scrie') !== false ||
strpos($q, 'what does') !== false || strpos($q, 'what is in') !== false) {
$targetEmail = null;
// Cautฤ "de la X"
if (preg_match('/de la (\w+)/i', $query, $matches)) {
$senderName = strtolower($matches[1]);
foreach ($allEmails as $email) {
if (stripos($email['from'], $senderName) !== false) {
$targetEmail = $email;
break;
}
}
}
// Cautฤ "ultimul"
if (!$targetEmail && (strpos($q, 'ultimul') !== false || strpos($q, 'latest') !== false)) {
$targetEmail = $allEmails[0];
}
if (!$targetEmail) {
$targetEmail = $allEmails[0];
}
$content = getEmailBodyContent($service, $targetEmail['id']);
if (!empty($content)) {
if ($isRomanian) {
$reply = "๐ง Email de la {$targetEmail['from']}:\nSubiect: {$targetEmail['subject']}\nData: {$targetEmail['date']}\n\n---\n" . $content . "\n---";
} else {
$reply = "๐ง Email from {$targetEmail['from']}:\nSubject: {$targetEmail['subject']}\nDate: {$targetEmail['date']}\n\n---\n" . $content . "\n---";
}
} else {
$reply = $isRomanian ? "Nu am putut extrage conศinutul acestui email." : "Could not extract content from this email.";
}
}
// ============================================
// 4. OFERTE
// ============================================
elseif (strpos($q, 'oferte') !== false || strpos($q, 'offers') !== false || strpos($q, 'reduceri') !== false) {
$offerWords = ['sale', 'discount', 'reducere', 'promo', 'offer', 'voucher', '%', 'gratis', 'free'];
$offers = [];
// Verificฤ expeditor specific
$targetOfferSender = null;
if (preg_match('/de la (\w+)/i', $query, $matches)) {
$targetOfferSender = strtolower($matches[1]);
}
foreach ($allEmails as $email) {
$subject = strtolower($email['subject']);
$isOffer = false;
foreach ($offerWords as $kw) {
if (strpos($subject, $kw) !== false) {
$isOffer = true;
break;
}
}
if ($isOffer) {
if ($targetOfferSender === null || stripos($email['from'], $targetOfferSender) !== false) {
$offers[] = $email;
}
}
}
if (count($offers) > 0) {
if ($isRomanian) {
$reply = "๐ Ai " . count($offers) . " email(uri) cu oferte:\n";
} else {
$reply = "๐ You have " . count($offers) . " emails with offers:\n";
}
for ($i = 0; $i < min(10, count($offers)); $i++) {
$reply .= "โข {$offers[$i]['from']} - {$offers[$i]['subject']}\n";
}
} else {
$reply = $isRomanian ? "Nu am gฤsit oferte." : "No offers found.";
}
}
// ============================================
// 5. LISTARE EMAILURI
// ============================================
elseif (strpos($q, 'list') !== false || strpos($q, 'lista') !== false || strpos($q, 'aratฤ') !== false) {
$numEmails = 10;
if (preg_match('/\b(\d+)\b/', $q, $matches)) {
$numEmails = min(intval($matches[1]), $totalEmails);
}
if (strpos($q, 'all') !== false || strpos($q, 'toate') !== false) {
$numEmails = min(30, $totalEmails);
}
if ($isRomanian) {
$reply = "Ultimele $numEmails emailuri:\n";
} else {
$reply = "Latest $numEmails emails:\n";
}
for ($i = 0; $i < $numEmails; $i++) {
$reply .= ($i+1) . ". {$allEmails[$i]['from']} - {$allEmails[$i]['subject']}\n";
}
}
// ============================================
// 6. EXPEDITOR SPECIFIC
// ============================================
elseif (preg_match('/(de la|from)\s+(\w+)/i', $query, $matches)) {
$senderName = strtolower($matches[2]);
$filtered = array_filter($allEmails, function($email) use ($senderName) {
return stripos($email['from'], $senderName) !== false;
});
$filtered = array_values($filtered);
$count = count($filtered);
if ($count > 0) {
if ($isRomanian) {
$reply = "Ai $count email(uri) de la " . ucfirst($senderName) . ":\n";
} else {
$reply = "You have $count email(s) from " . ucfirst($senderName) . ":\n";
}
for ($i = 0; $i < min(5, $count); $i++) {
$reply .= "โข {$filtered[$i]['subject']} [{$filtered[$i]['date']}]\n";
}
if ($count > 5) $reply .= ($isRomanian ? "...ศi " : "...and ") . ($count - 5) . " more.";
} else {
$reply = $isRomanian ? "Nu am gฤsit emailuri de la " . ucfirst($senderName) : "No emails from " . ucfirst($senderName) . " found";
}
}
// ============================================
// 7. NUMฤRARE
// ============================================
elseif (strpos($q, 'how many') !== false || strpos($q, 'cรขte') !== false || strpos($q, 'cati') !== false) {
$reply = $isRomanian ? "Ai $totalEmails emailuri รฎn inbox." : "You have $totalEmails emails in your inbox.";
}
// ============================================
// 8. CEL MAI RECENT
// ============================================
elseif (strpos($q, 'ultimul') !== false || strpos($q, 'latest') !== false) {
if ($isRomanian) {
$reply = "๐ง Ultimul email:\nDe la: {$allEmails[0]['from']}\nSubiect: {$allEmails[0]['subject']}\nData: {$allEmails[0]['date']}";
} else {
$reply = "๐ง Latest email:\nFrom: {$allEmails[0]['from']}\nSubject: {$allEmails[0]['subject']}\nDate: {$allEmails[0]['date']}";
}
}
// ============================================
// 9. SALUT / HELP
// ============================================
elseif (strpos($q, 'salut') !== false || strpos($q, 'hello') !== false || strpos($q, 'hi') !== false || strpos($q, 'help') !== false) {
if ($isRomanian) {
$reply = "๐ Salut! Sunt InboxZero AI. Te pot ajuta:\n\nโข Gฤsesc emailuri ('emailuri de la Steam')\nโข Citesc conศinut ('ce spune ultimul email')\nโข Listeazฤ emailuri ('list 20 emailuri')\nโข Gฤsesc oferte ('ce oferte am')\nโข Setez reminder ('aminteศte-mi รฎn 5 minute')\nโข Numฤrฤ emailuri ('cรขte emailuri am')\n\nCu ce te pot ajuta?";
} else {
$reply = "๐ Hello! I'm InboxZero AI. I can:\n\nโข Find emails ('emails from Steam')\nโข Read content ('what does the latest email say')\nโข List emails ('list 20 emails')\nโข Find offers ('what offers do I have')\nโข Set reminders ('remind me in 5 minutes')\nโข Count emails ('how many emails')\n\nWhat would you like to know?";
}
}
// ============================================
// 10. DEFAULT
// ============================================
else {
if ($isRomanian) {
$reply = "๐ฌ Vฤd $totalEmails emailuri. รncearcฤ:\nโข 'list emailuri'\nโข 'ultimul email'\nโข 'emailuri de la Steam'\nโข 'ce oferte am'\nโข 'aminteศte-mi รฎn 5 minute'";
} else {
$reply = "๐ฌ I see $totalEmails emails. Try:\nโข 'list emails'\nโข 'latest email'\nโข 'emails from Steam'\nโข 'what offers do I have'\nโข 'remind me in 5 minutes'";
}
}
} catch (Exception $e) {
$reply = "Error: " . $e->getMessage();
}
saveToHistory($currentChatId, $query, $reply);
echo json_encode([
'reply' => $reply,
'emails' => $emailListForDisplay,
'total_emails' => $totalEmails,
'conversation_id' => $currentChatId
]);
?>
โ Back