๐ Source: index.php
<?php
session_name('INBOXZERO');
session_set_cookie_params(0, '/', '', false, true);
session_start();
require_once 'vendor/autoload.php';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$baseUrl = "http://createcraftweb.playit.plus/AgentAIv3";
$client = new Google\Client();
$client->setClientId('1082083393389-c5uekspcp2boc1gd0n0gr3v1a5vbb3jg.apps.googleusercontent.com');
$client->setClientSecret('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');
$client->setRedirectUri("$baseUrl/oauth2callback.php");
$client->addScope('https://www.googleapis.com/auth/gmail.readonly');
$client->setAccessType('offline');
$client->setPrompt('consent');
$isMobile = preg_match('/(android|iphone|ipad|mobile)/i', $_SERVER['HTTP_USER_AGENT']);
$lang = $_COOKIE['inboxzero_lang'] ?? 'en';
$isLoggedIn = isset($_SESSION['access_token']);
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InboxZero AI v3</title>
<link rel="stylesheet" href="style.css">
</head>
<body data-theme="light">
<div class="container">
<div class="header">
<div class="header-top">
<h1>๐ง InboxZero AI <span class="badge">v3.0</span></h1>
<div class="controls">
<button class="theme-toggle" id="themeBtn" onclick="toggleTheme()">๐ Dark</button>
<select class="lang-select" id="langSelect" onchange="changeLanguage()">
<option value="en" <?php echo $lang == 'en' ? 'selected' : ''; ?>>๐ฌ๐ง English</option>
<option value="ro" <?php echo $lang == 'ro' ? 'selected' : ''; ?>>๐ท๐ด Romรขnฤ</option>
</select>
<button class="settings-btn" onclick="openSettings()">โ๏ธ Settings</button>
</div>
</div>
<p id="headerDescription">Your intelligent email assistant - ask anything about your emails</p>
<div class="status">๐ง <?php echo date('Y-m-d H:i:s'); ?></div>
</div>
<div class="content">
<div class="sidebar">
<div class="chat-history-section">
<h3>๐ฌ Recent Chats</h3>
<div id="chatHistoryList" class="chat-history-list"></div>
<button onclick="newChat()" class="new-chat-btn" id="newChatBtn">+ New Chat</button>
</div>
<hr>
<h3 id="inboxTitle">๐ฌ Your Inbox</h3>
<?php if ($isLoggedIn): ?>
<button onclick="logout()" class="logout-btn" id="logoutBtn">๐ช Logout</button>
<div id="emailList" style="margin-top: 15px;">
<div class="loading" id="loadingEmails">๐ฅ Loading your emails...</div>
</div>
<?php else: ?>
<p id="loginPrompt">๐ Login to access your Gmail inbox</p>
<a href="<?php echo $client->createAuthUrl(); ?>" class="login-btn" id="loginBtn">๐ Sign in with Google</a>
<?php endif; ?>
</div>
<div class="chat-area">
<div class="messages" id="messages">
<div class="message ai-message" id="welcomeMessage">
๐ค <strong>Hello! I'm InboxZero AI v3.</strong><br><br>
I can help you:<br>
โข ๐ Summarize unread emails<br>
โข ๐ Find specific messages<br>
โข ๐
Extract important dates<br>
โข โก Answer questions about your emails<br><br>
<em>Try: "Show me emails from Steam" or "Do I have emails from ChatGPT?"</em>
</div>
</div>
<?php if ($isLoggedIn): ?>
<div class="input-area">
<textarea id="userInput" placeholder="Ask about your emails..." rows="1" onkeypress="if(event.key==='Enter' && !event.shiftKey) { event.preventDefault(); sendMessage(); }" style="overflow-y: hidden; resize: none;"></textarea>
<button onclick="sendMessage()" id="sendBtn">๐ค Send</button>
</div>
<?php endif; ?>
</div>
</div>
</div>
<script>
// ============================================
// CONFIGURARE INIศIALฤ
// ============================================
let currentLang = '<?php echo $lang; ?>';
let currentEmails = [];
let currentConversationId = null;
let reminderTimeout = null;
// รncarcฤ setฤrile din localStorage
let maxEmailsSetting = parseInt(localStorage.getItem('inboxzero_max_emails')) || 50;
let aiModelSetting = localStorage.getItem('inboxzero_ai_model') || 'tinyllama';
let autoDeleteSetting = localStorage.getItem('inboxzero_auto_delete') || '3';
let fontSizeSetting = localStorage.getItem('inboxzero_font_size') || '16';
// Aplicฤ font size
document.body.style.fontSize = fontSizeSetting + 'px';
// ============================================
// TRADUCERI
// ============================================
const translations = {
en: {
headerDesc: "Your intelligent email assistant - ask anything about your emails",
inboxTitle: "๐ฌ Your Inbox",
logoutBtn: "๐ช Logout",
loadingEmails: "๐ฅ Loading your emails...",
loginPrompt: "๐ Login to access your Gmail inbox",
loginBtn: "๐ Sign in with Google",
welcomeMsg: "๐ค <strong>Hello! I'm InboxZero AI v3.</strong><br><br>I can help you:<br>โข ๐ Summarize unread emails<br>โข ๐ Find specific messages<br>โข ๐
Extract important dates<br>โข โก Answer questions about your emails<br><br><em>Try: \"Show me emails from Steam\" or \"Do I have emails from ChatGPT?\"</em>",
inputPlaceholder: "Ask about your emails...",
sendBtn: "๐ค Send",
thinking: "๐ค Thinking...",
error: "โ Error: ",
noEmailsDetail: "๐ญ No emails found",
failedToLoad: "โ Failed to load emails",
newChatBtn: "+ New Chat"
},
ro: {
headerDesc: "Asistentul tฤu inteligent pentru emailuri - รฎntreabฤ orice",
inboxTitle: "๐ฌ Inbox-ul Tฤu",
logoutBtn: "๐ช Deconectare",
loadingEmails: "๐ฅ Se รฎncarcฤ emailurile...",
loginPrompt: "๐ Autentificฤ-te pentru a accesa Gmail",
loginBtn: "๐ Conectare cu Google",
welcomeMsg: "๐ค <strong>Salut! Sunt InboxZero AI v3.</strong><br><br>Te pot ajuta:<br>โข ๐ Rezumatul emailurilor necitite<br>โข ๐ Gฤsirea mesajelor specifice<br>โข ๐
Extragerea datelor importante<br>โข โก Rฤspuns la รฎntrebฤri despre emailuri<br><br><em>รncearcฤ: \"Aratฤ-mi emailurile de la Steam\" sau \"Am emailuri de la ChatGPT?\"</em>",
inputPlaceholder: "รntreabฤ despre emailurile tale...",
sendBtn: "๐ค Trimite",
thinking: "๐ค Analizez...",
error: "โ Eroare: ",
noEmailsDetail: "๐ญ Nu s-au gฤsit emailuri",
failedToLoad: "โ Nu s-au putut รฎncฤrca emailurile",
newChatBtn: "+ Chat Nou"
}
};
// ============================================
// FUNCศII UI (Limbฤ, Temฤ)
// ============================================
function updateLanguage() {
const t = translations[currentLang];
const headerDesc = document.getElementById('headerDescription');
if (headerDesc) headerDesc.innerText = t.headerDesc;
const inboxTitle = document.getElementById('inboxTitle');
if (inboxTitle) inboxTitle.innerText = t.inboxTitle;
const logoutBtn = document.getElementById('logoutBtn');
if (logoutBtn) logoutBtn.innerText = t.logoutBtn;
const loginPrompt = document.getElementById('loginPrompt');
if (loginPrompt) loginPrompt.innerText = t.loginPrompt;
const loginBtn = document.getElementById('loginBtn');
if (loginBtn) loginBtn.innerText = t.loginBtn;
const welcomeMessage = document.getElementById('welcomeMessage');
if (welcomeMessage) welcomeMessage.innerHTML = t.welcomeMsg;
const userInput = document.getElementById('userInput');
if (userInput) userInput.placeholder = t.inputPlaceholder;
const sendBtn = document.getElementById('sendBtn');
if (sendBtn) sendBtn.innerText = t.sendBtn;
const newChatBtn = document.getElementById('newChatBtn');
if (newChatBtn) newChatBtn.innerText = t.newChatBtn;
const loadingEmails = document.getElementById('loadingEmails');
if (loadingEmails) loadingEmails.innerText = t.loadingEmails;
}
function changeLanguage() {
const select = document.getElementById('langSelect');
currentLang = select.value;
document.documentElement.lang = currentLang;
document.cookie = `inboxzero_lang=${currentLang}; path=/; max-age=${365 * 24 * 60 * 60}`;
updateLanguage();
}
function toggleTheme() {
const body = document.body;
const currentTheme = body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
body.setAttribute('data-theme', newTheme);
localStorage.setItem('inboxzero_theme', newTheme);
const themeBtn = document.getElementById('themeBtn');
if (themeBtn) themeBtn.innerHTML = newTheme === 'dark' ? 'โ๏ธ Light' : '๐ Dark';
}
const savedTheme = localStorage.getItem('inboxzero_theme') || 'light';
document.body.setAttribute('data-theme', savedTheme);
const themeBtn = document.getElementById('themeBtn');
if (themeBtn) themeBtn.innerHTML = savedTheme === 'dark' ? 'โ๏ธ Light' : '๐ Dark';
// ============================================
// REMINDER
// ============================================
function setReminder(text, minutes) {
if (reminderTimeout) clearTimeout(reminderTimeout);
addMessage('ai', `โฐ Reminder set for ${minutes} minute(s): "${text}"`);
if (Notification.permission !== 'granted') Notification.requestPermission();
reminderTimeout = setTimeout(() => {
if (Notification.permission === 'granted') new Notification('InboxZero Reminder', { body: text });
addMessage('ai', `๐ REMINDER: ${text}`);
}, minutes * 60 * 1000);
}
// ============================================
// CHAT PRINCIPAL
// ============================================
async function sendMessage() {
const input = document.getElementById('userInput');
const message = input.value.trim();
if (!message) return;
addMessage('user', message);
input.value = '';
input.disabled = true;
const t = translations[currentLang];
const thinkingMsg = addMessage('ai', t.thinking, true);
try {
const response = await fetch('chat_handler.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: message,
lang: currentLang,
conversation_id: currentConversationId,
max_emails: maxEmailsSetting,
ai_model: aiModelSetting
})
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (thinkingMsg) thinkingMsg.remove();
addMessage('ai', data.reply);
if (data.reminder) setReminder(data.reminder.text, data.reminder.minutes);
if (data.emails && data.emails.length > 0) {
currentEmails = data.emails;
displayEmails(currentEmails);
}
if (data.conversation_id && !currentConversationId) {
currentConversationId = data.conversation_id;
}
} catch (error) {
if (thinkingMsg) thinkingMsg.remove();
console.error('Error:', error);
addMessage('ai', t.error + error.message);
}
input.disabled = false;
input.focus();
}
function addMessage(role, text, returnElement = false, isHtml = false) {
const messagesDiv = document.getElementById('messages');
const div = document.createElement('div');
div.className = `message ${role === 'user' ? 'user-message' : 'ai-message'}`;
if (isHtml) {
div.innerHTML = (role === 'user' ? '๐ค ' : '๐ค ') + text;
} else {
div.innerHTML = (role === 'user' ? '๐ค ' : '๐ค ') + text.replace(/\n/g, '<br>');
}
messagesDiv.appendChild(div);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
if (returnElement) return div;
return div;
}
// ============================================
// EMAIL LIST
// ============================================
async function loadEmails() {
const t = translations[currentLang];
try {
const response = await fetch('fetch_emails.php');
const emails = await response.json();
if (emails.error) {
document.getElementById('emailList').innerHTML = `<div class="loading">โ ${emails.error}</div>`;
} else if (emails.length === 0) {
document.getElementById('emailList').innerHTML = `<div class="loading">${t.noEmailsDetail}</div>`;
} else {
currentEmails = emails;
displayEmails(emails);
}
} catch (error) {
document.getElementById('emailList').innerHTML = `<div class="loading">${t.failedToLoad}</div>`;
}
}
function displayEmails(emails) {
if (!emails || emails.length === 0) {
document.getElementById('emailList').innerHTML = '<div class="loading">๐ญ No emails found</div>';
return;
}
let html = '<ul class="email-list">';
for (let i = 0; i < Math.min(emails.length, maxEmailsSetting); i++) {
const email = emails[i];
const fromShort = email.from.length > 35 ? email.from.substring(0, 32) + '...' : email.from;
const subjectShort = email.subject.length > 45 ? email.subject.substring(0, 42) + '...' : email.subject;
html += `<li class="email-item" onclick="viewEmail('${email.id}', '${email.threadId}')">
<div class="email-from">๐จ ${escapeHtml(fromShort)}</div>
<div class="email-subject">${escapeHtml(subjectShort)}</div>
<div class="email-date">๐
${escapeHtml(email.date)}</div>
</li>`;
}
html += '</ul>';
document.getElementById('emailList').innerHTML = html;
}
async function viewEmail(emailId, threadId) {
addMessage('ai', '๐ Opening email...');
try {
const response = await fetch('get_email.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email_id: emailId })
});
const data = await response.json();
if (data.content) {
addMessage('ai', data.content);
if (threadId) {
const gmailLink = `https://mail.google.com/mail/u/0/#inbox/${threadId}`;
addMessage('ai', `<a href="${gmailLink}" target="_blank" class="gmail-link">๐ง Open in Gmail</a>`, false, true);
}
} else {
addMessage('ai', 'โ Could not load email content.');
}
} catch (error) {
addMessage('ai', 'โ Failed to load email.');
}
}
// ============================================
// CHAT HISTORY
// ============================================
let lastChatLoad = 0;
async function loadChatHistory() {
// Nu รฎncฤrca mai des de o datฤ la 2 secunde
const now = Date.now();
if (now - lastChatLoad < 2000) return;
lastChatLoad = now;
try {
const response = await fetch('get_chats.php');
const chats = await response.json();
const container = document.getElementById('chatHistoryList');
if (container && !chats.error) {
if (chats.length === 0) {
container.innerHTML = '<div class="chat-history-item" style="opacity:0.6;">No previous chats</div>';
} else {
container.innerHTML = chats.map(chat => `
<div class="chat-history-item-wrapper">
<div class="chat-history-item ${currentConversationId == chat.id ? 'active' : ''}" onclick="switchChat('${chat.id}')">
${escapeHtml(chat.title)}
</div>
<div class="chat-history-actions">
<button onclick="event.stopPropagation(); renameChat('${chat.id}')">โ๏ธ</button>
<button onclick="event.stopPropagation(); deleteChat('${chat.id}')">๐๏ธ</button>
</div>
</div>
`).join('');
}
}
} catch (e) {
console.error('Load chat history error:', e);
}
}
async function newChat() {
try {
const response = await fetch('new_chat.php', { method: 'POST' });
const data = await response.json();
if (data.success) {
currentConversationId = data.chat_id;
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '';
const welcomeMsg = document.createElement('div');
welcomeMsg.className = 'message ai-message';
welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
messagesDiv.appendChild(welcomeMsg);
// Nu mai reรฎncฤrca emailurile - pฤstreazฤ lista existentฤ
loadChatHistory(); // Doar asta, pentru a vedea chat-ul nou
}
} catch(e) {
console.error('New chat error:', e);
}
}
async function renameChat(chatId) {
const newTitle = prompt('Enter new chat name:');
if (newTitle && newTitle.trim()) {
await fetch('rename_chat.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, title: newTitle.trim() })
});
loadChatHistory();
}
}
async function deleteChat(chatId) {
if (confirm('Delete this chat?')) {
await fetch('delete_chat.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId })
});
if (currentConversationId == chatId) {
currentConversationId = null;
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '';
const welcomeMsg = document.createElement('div');
welcomeMsg.className = 'message ai-message';
welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
messagesDiv.appendChild(welcomeMsg);
const newChatResp = await fetch('new_chat.php', { method: 'POST' });
const newChatData = await newChatResp.json();
if (newChatData.success) currentConversationId = newChatData.chat_id;
}
loadChatHistory();
}
}
async function switchChat(chatId) {
if (currentConversationId == chatId) return; // Nu schimba la acelaศi chat
currentConversationId = chatId;
try {
const response = await fetch('switch_chat.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId })
});
const data = await response.json();
if (data.messages) {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '';
for (const msg of data.messages) {
addMessage(msg.role, msg.content);
}
if (data.messages.length === 0) {
const welcomeMsg = document.createElement('div');
welcomeMsg.className = 'message ai-message';
welcomeMsg.innerHTML = translations[currentLang].welcomeMsg;
messagesDiv.appendChild(welcomeMsg);
}
}
// Actualizeazฤ doar clasa activฤ, fฤrฤ reรฎncฤrcare completฤ
const chatItems = document.querySelectorAll('.chat-history-item');
chatItems.forEach(item => {
const onclickAttr = item.getAttribute('onclick');
if (onclickAttr && onclickAttr.includes(`switchChat('${chatId}')`)) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
} catch (e) {
console.error('Switch chat error:', e);
window.location.reload();
}
}
function logout() {
fetch('logout.php').then(() => window.location.reload());
}
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// ============================================
// SETฤRI COMPLETE
// ============================================
function openSettings() {
const currentMax = localStorage.getItem('inboxzero_max_emails') || '50';
const currentModel = localStorage.getItem('inboxzero_ai_model') || 'tinyllama';
const currentAutoDelete = localStorage.getItem('inboxzero_auto_delete') || '3';
const currentFontSize = localStorage.getItem('inboxzero_font_size') || '16';
const settingsHtml = `
<div id="settingsModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 1000;">
<div style="background: var(--bg-secondary); border-radius: 15px; padding: 25px; max-width: 450px; width: 90%; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
<h3 style="margin-top: 0;">โ๏ธ Settings</h3>
<div style="margin-bottom: 20px;">
<label>๐ง Max emails to show: <span id="maxEmailsValue">${currentMax}</span></label>
<input type="range" id="maxEmails" min="10" max="100" step="5" value="${currentMax}" style="width: 100%; margin: 10px 0;">
</div>
<div style="margin-bottom: 20px;">
<label>๐ค Font size: <span id="fontSizeValue">${currentFontSize}px</span></label>
<input type="range" id="fontSize" min="12" max="24" step="1" value="${currentFontSize}" style="width: 100%; margin: 10px 0;">
</div>
<div style="margin-bottom: 20px;">
<label>๐ค AI Model:</label>
<select id="aiModel" style="width: 100%; padding: 8px; margin-top: 5px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg-primary); color: var(--text-primary);">
<option value="tinyllama" ${currentModel === 'tinyllama' ? 'selected' : ''}>TinyLlama (Fast - 1.1GB)</option>
<option value="llama3.2:3b" ${currentModel === 'llama3.2:3b' ? 'selected' : ''}>Llama 3.2 (Smarter - 2GB)</option>
</select>
</div>
<div style="margin-bottom: 20px;">
<label>๐๏ธ Auto-delete old emails:</label>
<select id="autoDelete" style="width: 100%; padding: 8px; margin-top: 5px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg-primary); color: var(--text-primary);">
<option value="0" ${currentAutoDelete === '0' ? 'selected' : ''}>Disabled</option>
<option value="3" ${currentAutoDelete === '3' ? 'selected' : ''}>After 3 months</option>
<option value="6" ${currentAutoDelete === '6' ? 'selected' : ''}>After 6 months</option>
<option value="9" ${currentAutoDelete === '9' ? 'selected' : ''}>After 9 months</option>
<option value="12" ${currentAutoDelete === '12' ? 'selected' : ''}>After 12 months</option>
</select>
</div>
<div style="margin-bottom: 20px;">
<button onclick="syncEmailsNow()" style="width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 8px; cursor: pointer;">๐ Sync Emails Now</button>
</div>
<div style="display: flex; gap: 10px; justify-content: flex-end;">
<button onclick="closeSettings()" style="padding: 8px 16px; background: #666; color: white; border: none; border-radius: 8px; cursor: pointer;">Cancel</button>
<button onclick="saveSettings()" style="padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer;">Save</button>
</div>
</div>
</div>
`;
document.body.insertAdjacentHTML('beforeend', settingsHtml);
const maxSlider = document.getElementById('maxEmails');
const maxVal = document.getElementById('maxEmailsValue');
maxSlider.addEventListener('input', function() { maxVal.innerText = this.value; });
const fontSlider = document.getElementById('fontSize');
const fontVal = document.getElementById('fontSizeValue');
fontSlider.addEventListener('input', function() {
fontVal.innerText = this.value + 'px';
document.body.style.fontSize = this.value + 'px';
});
}
function closeSettings() {
const modal = document.getElementById('settingsModal');
if (modal) modal.remove();
}
function saveSettings() {
const maxEmails = document.getElementById('maxEmails').value;
const fontSize = document.getElementById('fontSize').value;
const aiModel = document.getElementById('aiModel').value;
const autoDelete = document.getElementById('autoDelete').value;
localStorage.setItem('inboxzero_max_emails', maxEmails);
localStorage.setItem('inboxzero_font_size', fontSize);
localStorage.setItem('inboxzero_ai_model', aiModel);
localStorage.setItem('inboxzero_auto_delete', autoDelete);
document.body.style.fontSize = fontSize + 'px';
maxEmailsSetting = parseInt(maxEmails);
aiModelSetting = aiModel;
closeSettings();
addMessage('ai', 'โ
Settings saved! Refresh page to see more emails.');
}
async function syncEmailsNow() {
closeSettings();
addMessage('ai', '๐ Syncing emails... This may take a moment.');
try {
const response = await fetch('sync_emails.php');
const text = await response.text();
addMessage('ai', 'โ
Sync completed!');
setTimeout(() => loadEmails(), 2000);
} catch (error) {
addMessage('ai', 'โ Sync failed: ' + error.message);
}
}
// Auto-resize textarea
const textarea = document.getElementById('userInput');
if (textarea) {
textarea.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 100) + 'px';
});
}
if ('Notification' in window && Notification.permission !== 'denied' && Notification.permission !== 'granted') {
Notification.requestPermission();
}
updateLanguage();
<?php if ($isLoggedIn): ?>
window.onload = async function() {
await loadEmails();
await loadChatHistory();
if (!currentConversationId) {
const response = await fetch('new_chat.php', { method: 'POST' });
const data = await response.json();
if (data.success) currentConversationId = data.chat_id;
}
};
<?php endif; ?>
</script>
</body>
</html>
โ Back