๐Ÿ“‚ File Browser

AgentAIv3
๐ŸŒ™ Dark Mode
๐ŸŽฏ Quick Launch:

๐Ÿ“ Directories

๐Ÿ“ tmp/ ๐Ÿ”“ Open
๐Ÿ“ vendor/ ๐Ÿ”“ Open

๐Ÿ“„ Files

๐Ÿ“„ README.md
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“ README.txt
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“ README_content.txt
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ chat_handler.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ check_auth.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ cleanup.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ“„ composer.json
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ database.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_email.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_email_parts.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ debug_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ delete_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ fetch_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ find_models.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ gemini_direct.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ get_chats.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ get_email.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_simple.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_test.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ logout.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ mark_read.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ new_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ oauth2callback.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ refresh_token.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ rename_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ session_config.php
โ–ถ Open ๐Ÿ“„ View Source
๐ŸŽจ style.css
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ switch_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ sync_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ajax.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_api.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_cmd.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_curl.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_db.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_db_ops.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_endpoint.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ollama.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_ollama_direct.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_openrouter.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_shell.php
โ–ถ Open ๐Ÿ“„ View Source

๐Ÿ“„ 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