๐Ÿ“‚ File Browser

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

๐Ÿ“ Directories

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

๐Ÿ“„ Files

๐Ÿ˜ chat_handler.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ chat_handler_test.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ check_db.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ cleanup.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ config.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ database.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ delete_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ fetch_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ get_email.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_minimal.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ index_simple.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
๐Ÿ˜ rename_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐ŸŽจ style.css
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ switch_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ sync_emails.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_chat.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_error.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_session.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_session2.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_session_check.php
โ–ถ Open ๐Ÿ“„ View Source
๐Ÿ˜ test_simple.php
โ–ถ Open ๐Ÿ“„ View Source

๐Ÿ“„ Source: chat_handler.php

<?php
session_name('INBOXZERO');
session_set_cookie_params(0, '/', '', false, true);
session_start();

if (!isset($_SESSION['access_token'])) {
    http_response_code(401);
    echo json_encode(['reply' => 'Please login first']);
    exit();
}

require_once 'vendor/autoload.php';
require_once 'database.php';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$query = $input['query'] ?? '';
$lang = $input['lang'] ?? 'en';
$requestedChatId = $input['conversation_id'] ?? null;

if (empty($query)) {
    echo json_encode(['reply' => 'What would you like to know about your emails?']);
    exit();
}

// Get user email
if (!isset($_SESSION['user_email']) && isset($_SESSION['access_token'])) {
    try {
        $tempClient = new Google\Client();
        $tempClient->setAccessToken($_SESSION['access_token']);
        $oauth2 = new Google\Service\Oauth2($tempClient);
        $userInfo = $oauth2->userinfo->get();
        $_SESSION['user_email'] = $userInfo->email;
    } catch (Exception $e) {
        $_SESSION['user_email'] = 'user_' . session_id();
    }
}
$userEmail = $_SESSION['user_email'] ?? 'guest_' . session_id();

$db = new ChatDatabase();

// Handle chat ID
if ($requestedChatId) {
    $currentChatId = intval($requestedChatId);
    $_SESSION['current_conversation_id'] = $currentChatId;
} elseif (isset($_SESSION['current_conversation_id'])) {
    $currentChatId = $_SESSION['current_conversation_id'];
} else {
    $currentChatId = $db->createConversation($userEmail);
    $_SESSION['current_conversation_id'] = $currentChatId;
}

$previousMessages = $db->getMessages($currentChatId);

// Fetch emails
$emailListForDisplay = [];
$totalEmails = 0;

try {
    $client = new Google\Client();
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google\Service\Gmail($client);
    
    $optParams = ['maxResults' => 30, 'labelIds' => ['INBOX']];
    $messages = $service->users_messages->listUsersMessages('me', $optParams);
    
    $allEmails = [];
    
    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()
            ];
        }
    }
    
    // Sort newest first
    usort($allEmails, function($a, $b) {
        return $b['timestamp'] - $a['timestamp'];
    });
    
    $totalEmails = count($allEmails);
    
    foreach ($allEmails as $newIndex => $email) {
        $emailListForDisplay[] = [
            'from' => htmlspecialchars($email['from']),
            'subject' => htmlspecialchars($email['subject']),
            'date' => $email['date'],
            'id' => $email['id'],
            'threadId' => $email['threadId']
        ];
    }
    
    // Construieศ™te rฤƒspunsul bazat pe รฎntrebare
    $reply = "";
    $queryLower = strtolower($query);
    
    // List emails
    if (strpos($queryLower, 'list') !== false || strpos($queryLower, 'show') !== false || 
        strpos($queryLower, 'care sunt') !== false || strpos($queryLower, 'what are') !== false ||
        strpos($queryLower, 'list them') !== false) {
        
        $list = "";
        if (strpos($queryLower, 'all') !== false || strpos($queryLower, 'toate') !== false) {
            $list = "All $totalEmails emails:\n";
            for ($i = 0; $i < $totalEmails; $i++) {
                $list .= ($i+1) . ". " . $allEmails[$i]['from'] . " - " . $allEmails[$i]['subject'] . "\n";
            }
        } elseif (preg_match('/\d+/', $query, $matches)) {
            $num = min(intval($matches[0]), $totalEmails);
            $list = "Latest $num emails:\n";
            for ($i = 0; $i < $num; $i++) {
                $list .= ($i+1) . ". " . $allEmails[$i]['from'] . " - " . $allEmails[$i]['subject'] . "\n";
            }
        } else {
            $list = "Latest emails:\n";
            for ($i = 0; $i < min(10, $totalEmails); $i++) {
                $list .= ($i+1) . ". " . $allEmails[$i]['from'] . " - " . $allEmails[$i]['subject'] . "\n";
            }
        }
        $reply = $list;
    }
    // Email count
    elseif (strpos($queryLower, 'how many') !== false || strpos($queryLower, 'cรขte') !== false || 
            strpos($queryLower, 'how much') !== false) {
        $reply = "I can see $totalEmails emails in your inbox.";
    }
    // Specific sender
    elseif (strpos($queryLower, 'steam') !== false) {
        $steamEmails = array_filter($allEmails, function($e) {
            return stripos($e['from'], 'steam') !== false;
        });
        $count = count($steamEmails);
        if ($count > 0) {
            $reply = "You have $count email(s) from Steam:\n";
            foreach (array_slice($steamEmails, 0, 5) as $e) {
                $reply .= "โ€ข " . $e['subject'] . " [" . $e['date'] . "]\n";
            }
        } else {
            $reply = "You don't have any emails from Steam.";
        }
    }
    elseif (strpos($queryLower, 'chess') !== false) {
        $chessEmails = array_filter($allEmails, function($e) {
            return stripos($e['from'], 'chess') !== false;
        });
        $count = count($chessEmails);
        $reply = "You have $count email(s) from Chess.com.";
    }
    elseif (strpos($queryLower, 'hi') !== false || strpos($queryLower, 'hello') !== false) {
        $reply = "Hello! I'm InboxZero AI v3. I can see $totalEmails emails in your inbox. Ask me to list them or ask about specific senders!";
    }
    else {
        $reply = "I can see $totalEmails emails in your inbox. Try asking: 'list emails', 'emails from Steam', or 'how many emails'.";
    }
    
    // Save to database
    $db->addMessage($currentChatId, 'user', $query);
    $db->addMessage($currentChatId, 'assistant', $reply);
    
    echo json_encode([
        'reply' => $reply,
        'emails' => $emailListForDisplay,
        'total_emails' => $totalEmails,
        'conversation_id' => $currentChatId
    ]);
    
} catch (Exception $e) {
    error_log("Error in chat_handler: " . $e->getMessage());
    echo json_encode(['reply' => 'Error: ' . $e->getMessage(), 'emails' => []]);
}
?>
โ† Back