Files
MixIAProxy/lib_base.php
T
thiagoandClaude Opus 5.5 22c1e121fc feat: proxy do Assistente IA do MixGestao
Proxy PHP compativel com OpenAI (v1/chat/completions, v1/saldo, v1/ping)
autenticado por token mix_ por cliente. Debita 1 pergunta por GUID
(Analise IA pesa 3), franquia mensal com virada de mes e avulso, estorna
em falha do provedor, troca modelo/esforco pelos do plano, grava tokens e
custo em ia_consumo sem texto de pergunta/resposta. Tetos diarios em US$.

Admin com token proprio (token, plano, avulso, consumo, resumo) auditado
em auditoria_app. Schema 010 para a base liberacao (nao aplicado).
Teste HTTP com banco sintetico e OpenAI simulada: 53/53.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 09:03:18 -03:00

291 lines
8.8 KiB
PHP

<?php
// Base do proxy do Assistente IA: config, resposta JSON e banco.
//
// Copia enxuta do lib_licenca.php do license_api (MixCupom), de proposito: o
// proxy nao depende daquele repositorio. Mesmas regras:
// - display_errors desligado (warning nao vaza schema nem caminho);
// - valor da requisicao nunca entra em SQL por concatenacao;
// - erro sai como {"ok":false,"erro":...,"mensagem":...}.
declare(strict_types=1);
ini_set('display_startup_errors', '0');
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);
// PHP 8.1+ liga excecao do mysqli por padrao; aqui todo retorno e conferido.
mysqli_report(MYSQLI_REPORT_OFF);
// Mes da franquia e "hoje" do teto seguem o relogio do cliente.
date_default_timezone_set('America/Sao_Paulo');
// --------------------------------------------------------------------------
// Config
// --------------------------------------------------------------------------
function iaConfig(): array
{
static $cfg = null;
if ($cfg !== null) {
return $cfg;
}
$cfg = [
'db_host' => getenv('MIXIA_DB_HOST') ?: '127.0.0.1',
'db_port' => (int) (getenv('MIXIA_DB_PORT') ?: 3306),
'db_name' => getenv('MIXIA_DB_NAME') ?: 'liberacao',
'db_user' => getenv('MIXIA_DB_USER') ?: '',
'db_pass' => getenv('MIXIA_DB_PASS') ?: '',
// Chave OpenAI da Softsan. NUNCA no repositorio: variavel de ambiente
// ou config.php (fora do git, bloqueado pelo .htaccess).
'openai_key' => getenv('MIXIA_OPENAI_KEY') ?: '',
'openai_url' => getenv('MIXIA_OPENAI_URL') ?: 'https://api.openai.com/v1/chat/completions',
'openai_timeout_s' => 110,
// Token da administracao (admin/). Sem ele o admin fica FECHADO.
'admin_token' => getenv('MIXIA_ADMIN_TOKEN') ?: '',
'modelo_padrao' => 'gpt-5.6-luna',
'esforco_padrao' => 'medium',
// Analise IA debita mais que uma pergunta comum.
'peso_analise' => 3,
// Plano TESTE criado junto com o primeiro token.
'teste_franquia' => 50,
'teste_dias' => 30,
// Tetos de gasto por dia (US$). Cliente: vale ia_saldo.teto_dia_usd
// quando preenchido. 0 desliga.
'teto_cliente_dia_usd' => 1.00,
'teto_global_dia_usd' => 20.00,
// Tokens invalidos por IP por minuto antes de 429. 0 desliga.
'rate_limite_min' => 20,
];
$arquivo = __DIR__ . '/config.php';
if (is_file($arquivo)) {
$local = require $arquivo;
if (is_array($local)) {
$cfg = array_merge($cfg, $local);
}
}
return $cfg;
}
// --------------------------------------------------------------------------
// Resposta
// --------------------------------------------------------------------------
function iaJson(int $status, array $payload, array $cabecalhos = []): void
{
header('Content-Type: application/json; charset=utf-8', true, $status);
foreach ($cabecalhos as $nome => $valor) {
header($nome . ': ' . $valor);
}
echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
/** Erro no formato da casa. `mensagem` e texto pronto para o exe mostrar. */
function iaErro(int $status, string $codigo, string $mensagem, array $extra = []): void
{
iaJson($status, array_merge(['ok' => false, 'erro' => $codigo, 'mensagem' => $mensagem], $extra));
}
// --------------------------------------------------------------------------
// Banco
// --------------------------------------------------------------------------
function iaDb()
{
static $cn = null;
if ($cn !== null) {
return $cn;
}
$c = iaConfig();
$cn = @mysqli_connect($c['db_host'], $c['db_user'], $c['db_pass'], $c['db_name'], $c['db_port']);
if (!$cn) {
error_log('ia_proxy: falha de conexao: ' . mysqli_connect_error());
iaErro(503, 'banco_indisponivel',
'Assistente IA indisponível no momento. Tente novamente em alguns minutos.');
}
// utf8, nao utf8mb4: MariaDB 5.1 nao conhece utf8mb4.
mysqli_set_charset($cn, 'utf8');
return $cn;
}
function iaExec(string $sql, string $tipos, array $valores)
{
$cn = iaDb();
$stmt = mysqli_prepare($cn, $sql);
if ($stmt === false) {
error_log('ia_proxy: prepare falhou: ' . mysqli_error($cn) . ' -- ' . $sql);
iaErro(500, 'erro_interno', 'Falha ao processar a requisição do Assistente IA.');
}
if ($tipos !== '') {
$valores = array_values($valores);
$refs = [$stmt, $tipos];
foreach ($valores as $i => $ignorado) {
$refs[] = &$valores[$i];
}
call_user_func_array('mysqli_stmt_bind_param', $refs);
}
if (!mysqli_stmt_execute($stmt)) {
error_log('ia_proxy: execute falhou: ' . mysqli_stmt_error($stmt) . ' -- ' . $sql);
mysqli_stmt_close($stmt);
iaErro(500, 'erro_interno', 'Falha ao processar a requisição do Assistente IA.');
}
return $stmt;
}
function iaLinha(string $sql, string $tipos, array $valores): ?array
{
$stmt = iaExec($sql, $tipos, $valores);
$res = mysqli_stmt_get_result($stmt);
$linha = $res ? mysqli_fetch_assoc($res) : null;
mysqli_stmt_close($stmt);
return $linha ?: null;
}
function iaLinhas(string $sql, string $tipos, array $valores): array
{
$stmt = iaExec($sql, $tipos, $valores);
$res = mysqli_stmt_get_result($stmt);
$out = [];
while ($res && ($r = mysqli_fetch_assoc($res))) {
$out[] = $r;
}
mysqli_stmt_close($stmt);
return $out;
}
function iaInserir(string $sql, string $tipos, array $valores): int
{
$stmt = iaExec($sql, $tipos, $valores);
$id = (int) mysqli_insert_id(iaDb());
mysqli_stmt_close($stmt);
return $id;
}
/** Executa e devolve linhas afetadas (alteradas, nao so casadas). */
function iaAtualizar(string $sql, string $tipos, array $valores): int
{
$stmt = iaExec($sql, $tipos, $valores);
$n = (int) mysqli_stmt_affected_rows($stmt);
mysqli_stmt_close($stmt);
return $n;
}
function iaTransacao(): void
{
mysqli_begin_transaction(iaDb());
}
function iaCommit(): void
{
if (!mysqli_commit(iaDb())) {
error_log('ia_proxy: commit falhou: ' . mysqli_error(iaDb()));
iaErro(500, 'erro_interno', 'Falha ao processar a requisição do Assistente IA.');
}
}
function iaRollback(): void
{
mysqli_rollback(iaDb());
}
// --------------------------------------------------------------------------
// Entrada
// --------------------------------------------------------------------------
function iaIp(): string
{
return substr((string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 45);
}
function iaDigitos($v): string
{
return (string) preg_replace('/\D/', '', (string) $v);
}
function iaTexto($v, int $max): ?string
{
$s = trim((string) ($v ?? ''));
if ($s === '') {
return null;
}
$s = (string) preg_replace('/[\x00-\x1F\x7F]/u', '', $s);
if ($s === '') {
return null;
}
return mb_substr($s, 0, $max);
}
/** Cabecalho da requisicao, sem diferenca de caixa. */
function iaCabecalho(string $nome): string
{
static $todos = null;
if ($todos === null) {
$todos = [];
$lista = function_exists('getallheaders') ? (getallheaders() ?: []) : [];
foreach ($lista as $k => $v) {
$todos[strtolower((string) $k)] = (string) $v;
}
// Apache em CGI: o Authorization chega por variavel (ver .htaccess).
foreach (['HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION'] as $var) {
if (!isset($todos['authorization']) && !empty($_SERVER[$var])) {
$todos['authorization'] = (string) $_SERVER[$var];
}
}
}
return trim($todos[strtolower($nome)] ?? '');
}
/** CNPJ normalizado em Clientes (o cadastro guarda formatado). */
const IA_CNPJ_NORM = "REPLACE(REPLACE(REPLACE(CNPJ,'.',''),'/',''),'-','')";
// --------------------------------------------------------------------------
// Eventos e rate limit
// --------------------------------------------------------------------------
function iaEvento(?string $cnpj, string $tipo, ?string $detalhe = null): void
{
iaInserir(
'INSERT INTO ia_evento (cnpj, tipo, detalhe, ip, criado_em) VALUES (?,?,?,?,NOW())',
'ssss',
[$cnpj, $tipo, $detalhe !== null ? mb_substr($detalhe, 0, 255) : null, iaIp()]
);
}
function iaRateLimit(string $tipo): void
{
$teto = (int) iaConfig()['rate_limite_min'];
if ($teto <= 0) {
return;
}
$r = iaLinha(
'SELECT COUNT(*) n FROM ia_evento
WHERE ip = ? AND tipo = ? AND criado_em > DATE_SUB(NOW(), INTERVAL 1 MINUTE)',
'ss',
[iaIp(), $tipo]
);
if ($r !== null && (int) $r['n'] >= $teto) {
iaErro(429, 'rate_limit', 'Muitas tentativas recusadas. Aguarde um minuto e tente novamente.');
}
}