Files
wevads-platform/scripts/api_brain-trainer.php
2026-02-26 04:53:11 +01:00

151 lines
7.6 KiB
PHP
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* BRAIN ENGINE TRAINER
* Trains the Brain to autonomously select: send_method × domain × ISP × headers × timing
* Uses brain_send_configs + brain_winners + isp_profiles + domain_performance
*/
header('Content-Type: application/json');
require_once("/opt/wevads/config/credentials.php"); $db = pg_connect("host=localhost dbname=adx_system user=admin password=".WEVADS_DB_PASS);
pg_query($db, "SET search_path TO admin");
$action = $_GET['action'] ?? $_POST['action'] ?? 'status';
switch($action) {
case 'generate_configs':
// Generate ALL possible send configs: method × isp × headers
$methods = pg_fetch_all(pg_query($db, "SELECT method_key, name, type, best_for_isps FROM send_methods WHERE is_active=true"));
$isps = pg_fetch_all(pg_query($db, "SELECT isp_name, isp_code, filter_type, recommended_volume, recommended_delay, best_send_time FROM isp_profiles"));
$configs_created = 0;
// Header variations that bypass filters
$header_sets = [
['x_mailer' => '', 'priority' => '3', 'content_type' => 'text/html', 'custom_headers' => '{}', 'notes' => 'Clean no X-Mailer (97% inbox on Exchange)'],
['x_mailer' => 'Microsoft Outlook 16.0', 'priority' => '3', 'content_type' => 'text/html', 'custom_headers' => '{"X-MS-Exchange-Organization-AuthSource":"exchange.local"}', 'notes' => 'Outlook mimicry'],
['x_mailer' => 'Apple Mail', 'priority' => '3', 'content_type' => 'multipart/alternative', 'custom_headers' => '{}', 'notes' => 'Apple Mail mimicry'],
['x_mailer' => '', 'priority' => '1', 'content_type' => 'text/html', 'custom_headers' => '{"X-Priority":"1","Importance":"high"}', 'notes' => 'High priority clean'],
['x_mailer' => 'Thunderbird 115.0', 'priority' => '3', 'content_type' => 'text/html', 'custom_headers' => '{"User-Agent":"Thunderbird 115.0"}', 'notes' => 'Thunderbird mimicry']
];
foreach ($methods as $m) {
$target_isps = json_decode($m['best_for_isps'], true) ?: ['ALL'];
foreach ($isps as $isp) {
// Only create if method is good for this ISP
$match = in_array('ALL', $target_isps) || in_array(strtoupper($isp['isp_name']), array_map('strtoupper', $target_isps));
if (!$match) continue;
foreach ($header_sets as $h) {
$mk = pg_escape_string($db, $m['method_key']);
$isn = pg_escape_string($db, $isp['isp_name']);
$xm = pg_escape_string($db, $h['x_mailer']);
$ct = pg_escape_string($db, $h['content_type']);
$ch = pg_escape_string($db, $h['custom_headers']);
$nt = pg_escape_string($db, $h['notes'] . ' | ' . $isp['filter_type'] . ' filter | delay:' . $isp['recommended_delay'] . 's');
$r = pg_query($db, "INSERT INTO brain_send_configs(send_method, isp_target, from_domain, smtp_host, smtp_port, x_mailer, priority, content_type, custom_headers, inbox_rate, status, notes, created_at)
VALUES('$mk', '$isn', 'culturellemejean.charity', '', 0, '$xm', '{$h['priority']}', '$ct', '$ch', 0, 'untested', '$nt', NOW())
ON CONFLICT DO NOTHING");
if (pg_affected_rows($r) > 0) $configs_created++;
}
}
}
echo json_encode([
'status' => 'success',
'configs_created' => $configs_created,
'methods_used' => count($methods),
'isps_targeted' => count($isps),
'header_variations' => count($header_sets),
'total_configs' => pg_fetch_result(pg_query($db, "SELECT COUNT(*) FROM brain_send_configs"), 0)
]);
break;
case 'auto_select':
// Brain selects best config for given ISP
$isp = $_GET['isp'] ?? 'Gmail';
// Try winner first
$winner = pg_fetch_assoc(pg_query($db, "SELECT * FROM brain_send_configs WHERE isp_target='".pg_escape_string($db,$isp)."' AND is_winner=true AND status='active' ORDER BY inbox_rate DESC LIMIT 1"));
if ($winner) {
echo json_encode(['status' => 'success', 'source' => 'winner', 'config' => $winner]);
break;
}
// Fall back to best tested
$best = pg_fetch_assoc(pg_query($db, "SELECT * FROM brain_send_configs WHERE isp_target='".pg_escape_string($db,$isp)."' AND inbox_rate > 0 ORDER BY inbox_rate DESC LIMIT 1"));
if ($best) {
echo json_encode(['status' => 'success', 'source' => 'best_tested', 'config' => $best]);
break;
}
// Fall back to default safe config
echo json_encode([
'status' => 'success',
'source' => 'default_safe',
'config' => [
'send_method' => 'o365_smtp',
'isp_target' => $isp,
'from_domain' => 'culturellemejean.charity',
'x_mailer' => '',
'priority' => '3',
'content_type' => 'text/html',
'custom_headers' => '{}',
'notes' => 'Default safe: O365 SMTP, no X-Mailer'
]
]);
break;
case 'record_result':
// Record a send test result to learn
$config_id = (int)($_POST['config_id'] ?? 0);
$inbox = (bool)($_POST['inbox'] ?? false);
if (!$config_id) { echo json_encode(['error' => 'Need config_id']); break; }
$field = $inbox ? 'total_inbox' : 'total_sent';
pg_query($db, "UPDATE brain_send_configs SET
total_sent = total_sent + 1,
total_inbox = total_inbox + " . ($inbox ? 1 : 0) . ",
inbox_rate = CASE WHEN total_sent > 0 THEN (total_inbox::float / total_sent * 100) ELSE 0 END,
is_winner = CASE WHEN total_sent >= 10 AND (total_inbox::float / total_sent) >= 0.85 THEN true ELSE false END,
status = CASE WHEN total_sent >= 10 THEN 'tested' ELSE 'testing' END,
updated_at = NOW()
WHERE id = $config_id");
// Auto-promote to winner if >=85% inbox after 10+ sends
$cfg = pg_fetch_assoc(pg_query($db, "SELECT * FROM brain_send_configs WHERE id=$config_id"));
if ($cfg && $cfg['is_winner'] == 't') {
pg_query($db, "INSERT INTO brain_winners(send_method, isp_target, from_domain, inbox_rate, total_sent, total_inbox, config_data, promoted_at)
VALUES('{$cfg['send_method']}', '{$cfg['isp_target']}', '{$cfg['from_domain']}', {$cfg['inbox_rate']}, {$cfg['total_sent']}, {$cfg['total_inbox']}, '".pg_escape_string($db, json_encode($cfg))."', NOW())
ON CONFLICT DO NOTHING");
}
echo json_encode(['status' => 'success', 'config' => $cfg]);
break;
case 'leaderboard':
$r = pg_query($db, "SELECT send_method, isp_target, x_mailer, inbox_rate, total_sent, total_inbox, is_winner, status, notes
FROM brain_send_configs WHERE total_sent > 0 ORDER BY inbox_rate DESC, total_sent DESC LIMIT 50");
$configs = [];
while ($row = pg_fetch_assoc($r)) $configs[] = $row;
echo json_encode(['status' => 'success', 'leaderboard' => $configs]);
break;
case 'status':
$s = pg_fetch_assoc(pg_query($db, "
SELECT
(SELECT COUNT(*) FROM brain_send_configs) as total_configs,
(SELECT COUNT(*) FROM brain_send_configs WHERE status='tested') as tested,
(SELECT COUNT(*) FROM brain_send_configs WHERE is_winner=true) as winners,
(SELECT COUNT(*) FROM brain_send_configs WHERE status='untested') as untested,
(SELECT COUNT(DISTINCT isp_target) FROM brain_send_configs) as isps_covered,
(SELECT COUNT(DISTINCT send_method) FROM brain_send_configs) as methods_used,
(SELECT COALESCE(MAX(inbox_rate),0) FROM brain_send_configs) as best_inbox_rate,
(SELECT COUNT(*) FROM brain_winners) as promoted_winners
"));
echo json_encode(['status' => 'success', 'brain' => $s]);
break;
}