www
/
wwwroot
/
codedabster.com
/
workspace
/
modules
/
chatgpt
➕ New
📤 Upload
✎ Editing:
chatgpt.php
← Back
<?php /* ============================================================================ AI Bridge (ChatGPT) + Conversații FileManager - endpoint compatibil cu: action=ai -> cheamă OpenAI și întoarce răspuns + new_content action=save_conversation -> salvează conversația pentru fișier (user+ai) action=load_conversation -> încarcă conversația pentru fișier ============================================================================ */ @ini_set('display_errors', 0); @error_reporting(E_ALL); session_start(); // Include utilitare tale. Trebuie să expună $database și respond($arr, $code?). $__fn = __DIR__ . '/includes/functions.php'; if (is_file($__fn)) { include_once $__fn; } // Fallback pt respond() dacă nu vine din functions.php if (!function_exists('respond')) { function respond(array $arr, int $http = 200) { http_response_code($http); header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } } // Helpers scurte function req_action(): string { return isset($_GET['action']) ? trim($_GET['action']) : ''; } function admin_id(): int { return isset($_SESSION['admin']) ? (int)$_SESSION['admin'] : 0; } function now_dt(): string { return date('Y-m-d H:i:s'); } // Așteptăm ca $database să existe (wrapper-ul tău) if (!isset($database)) { respond(['ok'=>false, 'error'=>'Database handle ($database) missing. Include functions.php first.'], 500); } $action = req_action(); /* ============================================================================ ACTION: ai (apelează OpenAI cu istoric scurt) ============================================================================ */ if ($action === 'ai') { // Acceptă JSON (recomandat) sau form $raw = file_get_contents('php://input'); $isJson = isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== false; $p = $isJson ? json_decode($raw, true) : null; $prompt = $isJson ? ($p['prompt'] ?? '') : ($_POST['prompt'] ?? ''); $intent = $isJson ? ($p['intent'] ?? '') : ($_POST['intent'] ?? ''); $language = $isJson ? ($p['language'] ?? '') : ($_POST['language'] ?? ''); $filename = $isJson ? ($p['filename'] ?? '') : ($_POST['filename'] ?? ''); $filepath = $isJson ? ($p['filepath'] ?? '') : ($_POST['filepath'] ?? ''); $selection = $isJson ? ($p['selection'] ?? '') : ($_POST['selection'] ?? ''); $content = $isJson ? ($p['content'] ?? '') : ($_POST['content'] ?? ''); if (trim($prompt) === '') { respond(['ok'=>false, 'error'=>'Missing "prompt"'], 400); } $OPENAI_API_KEY = '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'; if (!$OPENAI_API_KEY) { respond(['ok'=>false, 'error'=>'OPENAI_API_KEY not set as environment variable'], 500); } // — Model OpenAI folosit (poți schimba la gpt-4o-mini pentru cost/latency) $model = 'gpt-5'; // — Construim istoric scurt pe baza fișierului (dacă avem file path) $user_id = admin_id(); $project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 1; $conversation_id = 0; if ($filepath !== '') { $q = $database->execute(" SELECT id FROM ai_conversations WHERE user_id=? AND project_id=? AND context='filemanager' AND file_path=? LIMIT 1 ", [$user_id, $project_id, $filepath]); if ($q['status'] && $q['rows'] > 0) { $conversation_id = (int)$q['data'][0]['id']; } } $historyMessages = []; if ($conversation_id > 0) { $h = $database->execute(" SELECT role, content FROM ai_messages WHERE conversation_id=? ORDER BY id DESC LIMIT 8 ", [$conversation_id]); if ($h['status'] && $h['rows'] > 0) { $historyMessages = array_reverse($h['data']); // plafon ~3000 chars combinat (poți ajusta) $acc = 0; $MAX = 3000; $trimmed = []; foreach ($historyMessages as $m) { $c = (string)$m['content']; $len = mb_strlen($c); if ($acc + $len > $MAX) break; $trimmed[] = $m; $acc += $len; } $historyMessages = $trimmed; } } // — System prompt: scurt și țintit $sys = "You are a helpful coding assistant. Be concise. ". "When asked to fix code, return a single fenced code block containing ONLY the final code."; // — Construim messages: SYSTEM + HISTORY + USER(CURRENT) $messages = [ ["role" => "system", "content" => $sys], ]; // Adăugăm un mic context textual ca modelul să știe despre fișierul curent (fără a trimite codul complet) if ($filename || $filepath) { $ctxStr = "Context: file=".($filename ?: basename($filepath)).", path=".$filepath; if ($intent) $ctxStr .= ", intent=".$intent; $messages[] = ["role"=>"system", "content"=>$ctxStr]; } foreach ($historyMessages as $m) { $role = ($m['role'] === 'assistant') ? 'assistant' : 'user'; $messages[] = ["role"=>$role, "content"=>(string)$m['content']]; } // Mesajul actual al utilizatorului $messages[] = ["role" => "user", "content" => $prompt]; // — Pregătim requestul $postData = [ "model" => $model, "messages" => $messages, "temperature" => 1 ]; $dataString = json_encode($postData); // — cURL către OpenAI $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer '.$OPENAI_API_KEY, ]); $result = curl_exec($ch); if (curl_errno($ch)) { $err = curl_error($ch); curl_close($ch); respond(['ok'=>false, 'error'=>"cURL error: $err"], 500); } $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $responseData = json_decode($result, true); if (!$responseData) respond(['ok'=>false, 'error'=>'Invalid response from OpenAI', 'raw'=>$result], 500); if ($httpStatus >= 400 || !empty($responseData['error'])) { $message = $responseData['error']['message'] ?? ('HTTP '.$httpStatus); respond(['ok'=>false, 'error'=>"OpenAI: $message", 'status'=>$httpStatus], 500); } $assistantMessage = $responseData['choices'][0]['message']['content'] ?? ''; // Extragem un bloc de cod ca new_content (util pt "fix") $new_content = null; if ($assistantMessage) { if (preg_match('/```[a-zA-Z0-9_+\-]*\n([\s\S]*?)```/m', $assistantMessage, $m)) { $new_content = $m[1]; } } respond([ 'ok' => true, 'reply' => $assistantMessage, 'new_content' => $new_content, 'model' => $model, 'intent' => $intent ?: null, 'filename' => $filename ?: null, 'filepath' => $filepath ?: null ]); } /* ============================================================================ ACTION: save_conversation (upsert conv + insert mesaje) ============================================================================ */ if ($action === 'save_conversation') { $user_id = admin_id(); $project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 1; $file_path = isset($_POST['file_path']) ? trim($_POST['file_path']) : ''; $model = isset($_POST['model']) ? trim($_POST['model']) : 'gpt-4o'; $user_msg = isset($_POST['user_message']) ? trim($_POST['user_message']) : ''; $ai_msg = isset($_POST['ai_message']) ? trim($_POST['ai_message']) : ''; $provider = isset($_POST['provider']) ? trim($_POST['provider']) : 'ollama'; $now = now_dt(); if ($file_path === '' || $user_msg === '') { respond(['ok'=>false, 'error'=>'Missing parameters (file_path or user_message)']); } // Caută conversația pentru fișier $check = $database->execute(" SELECT id FROM ai_conversations WHERE user_id=? AND project_id=? AND context='filemanager' AND file_path=? LIMIT 1 ", [$user_id, $project_id, $file_path]); if (!$check['status']) { respond(['ok'=>false, 'error'=>'DB error: '.$check['error']]); } if ($check['rows'] > 0) { $conversation_id = (int)$check['data'][0]['id']; $database->execute("UPDATE ai_conversations SET updated_at=? WHERE id=?", [$now, $conversation_id]); } else { $title = basename($file_path); $ins = $database->execute(" INSERT INTO ai_conversations (user_id, project_id, title, model, file_path, context, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'filemanager', ?, ?) ", [$user_id, $project_id, $title, $model, $file_path, $now, $now]); if (!$ins['status']) respond(['ok'=>false, 'error'=>'Insert failed: '.$ins['error']]); $conversation_id = (int)$ins['last_id']; } // Inserează mesajele $insUser = $database->execute(" INSERT INTO ai_messages (conversation_id, role, content, created_at) VALUES (?, 'user', ?, ?) ", [$conversation_id, $user_msg, $now]); if (!$insUser['status']) respond(['ok'=>false, 'error'=>'Insert user message failed: '.$insUser['error']]); if ($ai_msg !== '') { $insAi = $database->execute(" INSERT INTO ai_messages (conversation_id, role, content, created_at) VALUES (?, 'assistant', ?, ?) ", [$conversation_id, $ai_msg, $now]); if (!$insAi['status']) respond(['ok'=>false, 'error'=>'Insert AI message failed: '.$insAi['error']]); } // Integrare opțională cu ai_files* dacă există în functions.php if (function_exists('ai_files_upsert')) { try { ai_files_upsert($database, $user_id, $project_id, $provider, $file_path, $conversation_id); } catch (\Throwable $e) { // nu blocăm salvarea conversației dacă helperul dă eroare } } respond(['ok'=>true, 'conversation_id'=>$conversation_id, 'message'=>'Saved successfully']); } /* ============================================================================ ACTION: load_conversation (returnează conv + mesaje) ============================================================================ */ if ($action === 'load_conversation') { $user_id = admin_id(); $project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 1; $file_path = isset($_GET['file_path']) ? trim($_GET['file_path']) : ''; if ($file_path === '') { respond(['ok'=>false, 'error'=>'Missing file_path']); } // Conversația $conv = $database->execute(" SELECT id, title, model FROM ai_conversations WHERE user_id=? AND project_id=? AND context='filemanager' AND file_path=? LIMIT 1 ", [$user_id, $project_id, $file_path]); if (!$conv['status']) { respond(['ok'=>false, 'error'=>'DB error: '.$conv['error']]); } if ($conv['rows'] === 0) { respond(['ok'=>true, 'conversation'=>null, 'messages'=>[]]); } $conversation = $conv['data'][0]; $conversation_id = (int)$conversation['id']; // Mesaje $msgs = $database->execute(" SELECT role, content, created_at FROM ai_messages WHERE conversation_id=? ORDER BY id ASC ", [$conversation_id]); if (!$msgs['status']) { respond(['ok'=>false, 'error'=>'Messages query failed: '.$msgs['error']]); } // Integrare opțională: ai_files_get_conv_id $provider = $_GET['provider'] ?? 'ollama'; if (function_exists('ai_files_get_conv_id')) { try { $convIdXref = ai_files_get_conv_id($database, $user_id, $project_id, $provider, $file_path); if ($convIdXref) { $conversation_id = (int)$convIdXref; } } catch (\Throwable $e) { // ignori } } respond([ 'ok' => true, 'conversation' => $conversation, 'conversation_id' => $conversation_id, 'messages' => $msgs['data'] ]); } /* ============================================================================ Default ============================================================================ */ respond(['ok'=>false, 'error'=>'Unknown action'], 400);
💾 Save Changes
Cancel
📤 Upload File
×
Select File
Upload
Cancel
➕ Create New
×
Type
📄 File
📁 Folder
Name
Create
Cancel
✎ Rename Item
×
Current Name
New Name
Rename
Cancel
🔐 Change Permissions
×
Target File
Permission (e.g., 0755, 0644)
0755
0644
0777
Apply
Cancel