php /** * defaut.php - Sistema UIG IA / IZE * Arquivo único: HTML5 + CSS + JavaScript + PHP * Chat público com identificação por nome, sem login. * Cria estrutura de pastas automaticamente em public_html. * * Autor: Luiz Carlos de Jesus (UIG IA) */ // ============================================================ // CONFIGURAÇÃO // ============================================================ define('UIG_API_KEY', 'wignar_ize_sk_a4ce4f7b1832654774568286d54b2810f1fc5df0'); define('UIG_API_URL', 'https://mundomgtow.com/api/uig_ia/v1/chat'); define('UIG_MODEL', 'ize-default'); // Diretório base (dentro do public_html) $BASE_DIR = __DIR__ . '/uig_data'; $USERS_DIR = $BASE_DIR . '/users'; $LOG_DIR = $BASE_DIR . '/logs'; $SESS_DIR = $BASE_DIR . '/sessions'; // ============================================================ // FUNÇÃO: cria estrutura de pastas // ============================================================ function uig_bootstrap_dirs($base, $users, $logs, $sessions) { $dirs = [$base, $users, $logs, $sessions]; foreach ($dirs as $d) { if (!is_dir($d)) { @mkdir($d, 0755, true); } // proteção $ht = $d . '/.htaccess'; if (!file_exists($ht)) { @file_put_contents($ht, "Options -Indexes\n"); } } // protege o diretório base contra acesso direto de arquivos sensíveis $protect = $base . '/.htaccess'; if (!file_exists($protect)) { @file_put_contents($protect, "Options -Indexes\n" . "\n" . " Require all denied\n" . "\n" ); } } // ============================================================ // FUNÇÃO: sanitiza nome de usuário para pasta // ============================================================ function uig_slug($name) { $name = trim((string)$name); $name = preg_replace('/\s+/u', '_', $name); $name = preg_replace('/[^\p{L}\p{N}_\-]/u', '', $name); $name = mb_substr($name, 0, 40, 'UTF-8'); if ($name === '') $name = 'anonimo'; return $name; } // ============================================================ // FUNÇÃO: chama a API da IZE // ============================================================ function uig_call_api($messages) { $payload = json_encode([ 'model' => UIG_MODEL, 'messages' => $messages, 'stream' => false ], JSON_UNESCAPED_UNICODE); $ch = curl_init(UIG_API_URL); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . UIG_API_KEY, 'Content-Type: application/json', 'Accept: application/json' ], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 90, CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => true, ]); $raw = curl_exec($ch); $err = curl_error($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($raw === false) { return ['ok' => false, 'error' => 'Falha de conexão: ' . $err]; } $data = json_decode($raw, true); if ($code < 200 || $code >= 300) { $msg = is_array($data) && isset($data['error']['message']) ? $data['error']['message'] : ('HTTP ' . $code); return ['ok' => false, 'error' => $msg, 'raw' => $raw]; } // Formatos de resposta possíveis $reply = null; if (is_array($data)) { if (isset($data['choices'][0]['message']['content'])) { $reply = $data['choices'][0]['message']['content']; } elseif (isset($data['response'])) { $reply = $data['response']; } elseif (isset($data['reply'])) { $reply = $data['reply']; } elseif (isset($data['message'])) { $reply = is_array($data['message']) ? ($data['message']['content'] ?? null) : $data['message']; } elseif (isset($data['content'])) { $reply = $data['content']; } } if ($reply === null) { return ['ok' => false, 'error' => 'Resposta inesperada da API.', 'raw' => $raw]; } return ['ok' => true, 'reply' => $reply, 'raw_data' => $data]; } // ============================================================ // BOOTSTRAP // ============================================================ uig_bootstrap_dirs($BASE_DIR, $USERS_DIR, $LOG_DIR, $SESS_DIR); // ============================================================ // ROTEAMENTO AJAX // ============================================================ $action = $_POST['action'] ?? $_GET['action'] ?? ''; if ($action === 'send') { header('Content-Type: application/json; charset=utf-8'); $user = trim((string)($_POST['user'] ?? '')); $message = trim((string)($_POST['message'] ?? '')); $history = $_POST['history'] ?? '[]'; if ($user === '' || $message === '') { echo json_encode(['ok' => false, 'error' => 'Nome e mensagem obrigatórios.']); exit; } $slug = uig_slug($user); $userDir = $USERS_DIR . '/' . $slug; if (!is_dir($userDir)) { @mkdir($userDir, 0755, true); @file_put_contents($userDir . '/.htaccess', "Options -Indexes\n\n Require all denied\n\n"); } // Histórico enviado do cliente (últimas 20 mensagens) $h = json_decode($history, true); if (!is_array($h)) $h = []; $messages = []; // Mensagem de sistema interna (a API ignora system do cliente, mas mantemos estrutura) $messages[] = ['role' => 'system', 'content' => 'Você é a IZE, agente oficial da UIG IA.']; foreach ($h as $m) { if (!is_array($m) || !isset($m['role'], $m['content'])) continue; $role = $m['role'] === 'assistant' ? 'assistant' : 'user'; $messages[] = ['role' => $role, 'content' => (string)$m['content']]; } $messages[] = ['role' => 'user', 'content' => $message]; $result = uig_call_api($messages); // Log $logFile = $LOG_DIR . '/' . date('Y-m-d') . '.log'; $logLine = sprintf("[%s] user=%s msg=%s status=%s\n", date('c'), $slug, mb_substr($message, 0, 200, 'UTF-8'), $result['ok'] ? 'ok' : 'err:' . ($result['error'] ?? '?') ); @file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX); // Salva conversa do usuário $convFile = $userDir . '/conversa.json'; $conv = []; if (file_exists($convFile)) { $tmp = json_decode((string)@file_get_contents($convFile), true); if (is_array($tmp)) $conv = $tmp; } $conv[] = ['t' => time(), 'role' => 'user', 'content' => $message]; if ($result['ok']) { $conv[] = ['t' => time(), 'role' => 'assistant', 'content' => $result['reply']]; } // Mantém últimas 200 entradas if (count($conv) > 200) $conv = array_slice($conv, -200); @file_put_contents($convFile, json_encode($conv, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX); if ($result['ok']) { echo json_encode(['ok' => true, 'reply' => $result['reply']], JSON_UNESCAPED_UNICODE); } else { echo json_encode(['ok' => false, 'error' => $result['error'] ?? 'Erro desconhecido.'], JSON_UNESCAPED_UNICODE); } exit; } if ($action === 'history') { header('Content-Type: application/json; charset=utf-8'); $user = trim((string)($_GET['user'] ?? '')); if ($user === '') { echo json_encode(['ok' => false, 'error' => 'Nome obrigatório.']); exit; } $slug = uig_slug($user); $file = $USERS_DIR . '/' . $slug . '/conversa.json'; $conv = []; if (file_exists($file)) { $tmp = json_decode((string)@file_get_contents($file), true); if (is_array($tmp)) $conv = $tmp; $conv = array_slice($conv, -40); } echo json_encode(['ok' => true, 'history' => $conv], JSON_UNESCAPED_UNICODE); exit; } if ($action === 'list_users') { header('Content-Type: application/json; charset=utf-8'); $list = []; if ($dh = @opendir($USERS_DIR)) { while (($f = readdir($dh)) !== false) { if ($f === '.' || $f === '..') continue; if (is_dir($USERS_DIR . '/' . $f)) $list[] = $f; } closedir($dh); } echo json_encode(['ok' => true, 'users' => array_values($list)], JSON_UNESCAPED_UNICODE); exit; } // ============================================================ // PÁGINA HTML // ============================================================ ?> IZE — UIG IA

IZE

UIG IA · Sistema Oficial
— trocar