<?php
session_start();
error_reporting(0);

// ========== CONFIGURATION ==========
// Set to null for full filesystem access, or an absolute path to restrict (e.g., '/home/username/domains')
define('FM_BASE_PATH', null);
define('FM_USE_AUTH', false);      // Set true to enable password protection
define('FM_PASSWORD', 'admin123');
define('FM_DATE_FORMAT', 'Y-m-d H:i:s');

// ========== AUTHENTICATION (optional) ==========
if (FM_USE_AUTH && empty($_SESSION['fm_logged_in'])) {
    if (isset($_POST['fm_pass']) && $_POST['fm_pass'] === FM_PASSWORD) {
        $_SESSION['fm_logged_in'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Login</title>
    <style>body{background:#1e1e2f;font-family:Arial;display:flex;justify-content:center;align-items:center;height:100vh;}
    form{background:#2d2d3a;padding:30px;border-radius:8px;}input{padding:10px;margin:10px 0;width:200px;}
    button{padding:8px 20px;}</style></head><body><form method="post"><h2 style="color:#fff">Login</h2>
    <input type="password" name="fm_pass" placeholder="Password"><br><button type="submit">Enter</button></form></body></html>';
    exit;
}

// ========== SECURE PATH RESOLUTION (full access or restricted) ==========
function fm_resolve_path($p) {
    $p = str_replace('\\', '/', $p);
    $real = realpath($p);
    if ($real === false) return $p; // fallback to raw path
    if (defined('FM_BASE_PATH') && FM_BASE_PATH !== null) {
        $base = rtrim(FM_BASE_PATH, '/');
        if (strpos($real, $base) !== 0) return $base;
    }
    return $real;
}

$current = isset($_GET['p']) ? fm_resolve_path($_GET['p']) : fm_resolve_path(dirname(__FILE__));
if (!is_dir($current)) $current = fm_resolve_path(dirname(__FILE__));

// ========== HELPER FUNCTIONS ==========
function fm_perms($f) {
    $p = fileperms($f);
    $r = ($p & 0x4000) ? 'd' : '-';
    $r .= ($p & 0x0100) ? 'r' : '-';
    $r .= ($p & 0x0080) ? 'w' : '-';
    $r .= ($p & 0x0040) ? 'x' : '-';
    $r .= ($p & 0x0020) ? 'r' : '-';
    $r .= ($p & 0x0010) ? 'w' : '-';
    $r .= ($p & 0x0008) ? 'x' : '-';
    $r .= ($p & 0x0004) ? 'r' : '-';
    $r .= ($p & 0x0002) ? 'w' : '-';
    $r .= ($p & 0x0001) ? 'x' : '-';
    return $r;
}

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

function fm_delete($target) {
    if (!file_exists($target)) return;
    if (is_dir($target)) {
        $d = opendir($target);
        while (($f = readdir($d)) !== false) {
            if ($f != '.' && $f != '..') fm_delete($target.'/'.$f);
        }
        closedir($d);
        rmdir($target);
    } else {
        unlink($target);
    }
}

function fm_copy($src, $dst) {
    if (!is_dir($dst)) mkdir($dst, 0755, true);
    $d = opendir($src);
    while (($f = readdir($d)) !== false) {
        if ($f == '.' || $f == '..') continue;
        $sp = $src.'/'.$f;
        $dp = $dst.'/'.$f;
        if (is_dir($sp)) fm_copy($sp, $dp);
        else copy($sp, $dp);
    }
    closedir($d);
}

function fm_zip_available() {
    return class_exists('ZipArchive');
}

function fm_zip_items($items, $destZip, $basePath) {
    if (!fm_zip_available()) return false;
    $zip = new ZipArchive();
    if ($zip->open($destZip, ZipArchive::CREATE) !== true) return false;
    foreach ($items as $item) {
        $full = $basePath . '/' . $item;
        if (is_file($full)) {
            $zip->addFile($full, $item);
        } elseif (is_dir($full)) {
            $stack = array($full);
            while (!empty($stack)) {
                $dir = array_pop($stack);
                $d = opendir($dir);
                while (($f = readdir($d)) !== false) {
                    if ($f == '.' || $f == '..') continue;
                    $sub = $dir . '/' . $f;
                    $rel = substr($sub, strlen($basePath)+1);
                    if (is_dir($sub)) {
                        $zip->addEmptyDir($rel);
                        array_push($stack, $sub);
                    } else {
                        $zip->addFile($sub, $rel);
                    }
                }
                closedir($d);
            }
        }
    }
    $zip->close();
    return true;
}

function fm_extract_zip($zipFile, $dest) {
    if (!fm_zip_available()) return false;
    $zip = new ZipArchive();
    if ($zip->open($zipFile) === true) {
        $zip->extractTo($dest);
        $zip->close();
        return true;
    }
    return false;
}

function fm_set_msg($msg, $type='success') {
    $_SESSION['fm_msg'] = array('text'=>$msg, 'type'=>$type);
}

function fm_get_msg() {
    if (isset($_SESSION['fm_msg'])) {
        $m = $_SESSION['fm_msg'];
        unset($_SESSION['fm_msg']);
        return $m;
    }
    return null;
}

// ========== PROCESS ACTIONS ==========
$msg = fm_get_msg();

if (isset($_GET['delete'])) {
    $target = $current . '/' . basename($_GET['delete']);
    if (file_exists($target)) fm_delete($target);
    fm_set_msg("Deleted: " . basename($target));
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_GET['download'])) {
    $file = $current . '/' . basename($_GET['download']);
    if (is_file($file)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

if (isset($_POST['savefile'], $_POST['content'])) {
    $save = $current . '/' . basename($_POST['savefile']);
    file_put_contents($save, $_POST['content']);
    fm_set_msg("Saved: " . basename($_POST['savefile']));
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['rename_old'], $_POST['rename_new'])) {
    $old = $current . '/' . basename($_POST['rename_old']);
    $new = $current . '/' . basename($_POST['rename_new']);
    if (file_exists($old) && !file_exists($new)) {
        rename($old, $new);
        fm_set_msg("Renamed to: " . basename($new));
    } else {
        fm_set_msg("Rename failed", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['copy_source'], $_POST['copy_dest'], $_POST['copy_action'])) {
    $src = $current . '/' . basename($_POST['copy_source']);
    $destDir = fm_resolve_path($_POST['copy_dest']);
    $dest = $destDir . '/' . basename($_POST['copy_source']);
    if (file_exists($src)) {
        if ($_POST['copy_action'] == 'copy') {
            if (is_dir($src)) fm_copy($src, $dest);
            else copy($src, $dest);
            fm_set_msg("Copied to: " . $destDir);
        } else {
            rename($src, $dest);
            fm_set_msg("Moved to: " . $destDir);
        }
    } else {
        fm_set_msg("Source not found", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['chmod_target'], $_POST['chmod_value'])) {
    $target = $current . '/' . basename($_POST['chmod_target']);
    $perms = octdec(str_pad($_POST['chmod_value'], 4, '0', STR_PAD_LEFT));
    if (chmod($target, $perms)) {
        fm_set_msg("Permissions changed for: " . basename($target));
    } else {
        fm_set_msg("Chmod failed", 'error');
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if (isset($_POST['bulk_action']) && isset($_POST['selected']) && is_array($_POST['selected'])) {
    $selected = $_POST['selected'];
    $action = $_POST['bulk_action'];
    if ($action == 'delete') {
        foreach ($selected as $item) {
            $target = $current . '/' . basename($item);
            if (file_exists($target)) fm_delete($target);
        }
        fm_set_msg("Deleted " . count($selected) . " items");
    } elseif ($action == 'zip') {
        if (fm_zip_available()) {
            $zipName = 'bulk_' . date('Ymd_His') . '.zip';
            $zipPath = $current . '/' . $zipName;
            if (fm_zip_items($selected, $zipPath, $current)) {
                fm_set_msg("Created archive: " . $zipName);
            } else {
                fm_set_msg("Failed to create zip", 'error');
            }
        } else {
            fm_set_msg("Zip extension not installed", 'error');
        }
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && 
    !isset($_POST['savefile']) && 
    !isset($_POST['rename_old']) && 
    !isset($_POST['copy_source']) && 
    !isset($_POST['chmod_target']) && 
    !isset($_POST['bulk_action'])) {
    
    if (isset($_FILES['up']) && $_FILES['up']['error'] == UPLOAD_ERR_OK) {
        move_uploaded_file($_FILES['up']['tmp_name'], $current . '/' . basename($_FILES['up']['name']));
        fm_set_msg("Uploaded: " . $_FILES['up']['name']);
    }
    if (!empty($_POST['folder'])) {
        $newFolder = $current . '/' . basename($_POST['folder']);
        if (!file_exists($newFolder)) mkdir($newFolder, 0755, true);
        fm_set_msg("Created folder: " . $_POST['folder']);
    }
    if (!empty($_POST['newfile'])) {
        $newFile = $current . '/' . basename($_POST['newfile']);
        if (!file_exists($newFile)) file_put_contents($newFile, '');
        fm_set_msg("Created file: " . $_POST['newfile']);
    }
    if (!empty($_POST['extract_zip'])) {
        $zipFile = $current . '/' . basename($_POST['extract_zip']);
        if (file_exists($zipFile) && pathinfo($zipFile, PATHINFO_EXTENSION) == 'zip') {
            $extractTo = $current . '/' . pathinfo($zipFile, PATHINFO_FILENAME);
            if (fm_extract_zip($zipFile, $extractTo)) {
                fm_set_msg("Extracted to: " . basename($extractTo));
            } else {
                fm_set_msg("Extraction failed", 'error');
            }
        }
    }
    header("Location: ?p=" . urlencode($current));
    exit;
}

// ========== LIST DIRECTORY WITH SORTING ==========
$items = scandir($current);
$dirs = array();
$files = array();
foreach ($items as $item) {
    if ($item == '.' || $item == '..') continue;
    if (is_dir($current . '/' . $item)) $dirs[] = $item;
    else $files[] = $item;
}
sort($dirs);
sort($files);
$all = array_merge($dirs, $files);

$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sort_dir = isset($_GET['dir']) ? $_GET['dir'] : 'asc';

function fm_cmp_name_asc($a, $b) { return strcasecmp($a, $b); }
function fm_cmp_name_desc($a, $b) { return strcasecmp($b, $a); }
function fm_cmp_size_asc($a, $b) {
    global $current;
    $sa = is_file($current.'/'.$a) ? filesize($current.'/'.$a) : 0;
    $sb = is_file($current.'/'.$b) ? filesize($current.'/'.$b) : 0;
    if ($sa == $sb) return 0;
    return ($sa < $sb) ? -1 : 1;
}
function fm_cmp_size_desc($a, $b) {
    global $current;
    $sa = is_file($current.'/'.$a) ? filesize($current.'/'.$a) : 0;
    $sb = is_file($current.'/'.$b) ? filesize($current.'/'.$b) : 0;
    if ($sa == $sb) return 0;
    return ($sa < $sb) ? 1 : -1;
}
function fm_cmp_time_asc($a, $b) {
    global $current;
    $ta = filemtime($current.'/'.$a);
    $tb = filemtime($current.'/'.$b);
    if ($ta == $tb) return 0;
    return ($ta < $tb) ? -1 : 1;
}
function fm_cmp_time_desc($a, $b) {
    global $current;
    $ta = filemtime($current.'/'.$a);
    $tb = filemtime($current.'/'.$b);
    if ($ta == $tb) return 0;
    return ($ta < $tb) ? 1 : -1;
}

if ($sort_by == 'size') {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_size_asc');
    else usort($all, 'fm_cmp_size_desc');
} elseif ($sort_by == 'time') {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_time_asc');
    else usort($all, 'fm_cmp_time_desc');
} else {
    if ($sort_dir == 'asc') usort($all, 'fm_cmp_name_asc');
    else usort($all, 'fm_cmp_name_desc');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ultimate File Manager - Full Access</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
*{box-sizing:border-box;}
body{background:#0f172a;font-family:'Segoe UI',sans-serif;margin:0;padding:20px;color:#e2e8f0;}
.container{max-width:1400px;margin:0 auto;background:#1e293b;border-radius:16px;padding:20px;}
h2{margin-top:0;}
.breadcrumb{background:#0f172a;padding:10px 15px;border-radius:10px;margin:15px 0;word-break:break-all;}
.toolbar{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:20px;background:#0f172a;padding:15px;border-radius:12px;}
.toolbar-group{display:flex;gap:8px;flex-wrap:wrap;align-items:center;background:#1e293b;padding:8px 12px;border-radius:10px;}
input,select,button{background:#334155;border:none;padding:8px 14px;border-radius:8px;color:#f1f5f9;font-size:14px;cursor:pointer;}
input,select{background:#1e293b;border:1px solid #475569;cursor:auto;}
button:hover{background:#3b82f6;}
.message{padding:12px;border-radius:10px;margin-bottom:20px;background:#0f172a;border-left:4px solid #3b82f6;}
.message.error{border-left-color:#ef4444;background:#450a0a;}
table{width:100%;border-collapse:collapse;background:#0f172a;}
th,td{padding:12px 10px;text-align:left;border-bottom:1px solid #334155;}
th{background:#1e293b;}
tr:hover{background:#1e293b;}
a{color:#60a5fa;text-decoration:none;}
.actions a{margin-right:12px;}
.checkbox-col{width:30px;}
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);justify-content:center;align-items:center;z-index:1000;}
.modal-content{background:#1e293b;padding:25px;border-radius:20px;width:90%;max-width:500px;}
.modal-content input,.modal-content button{width:100%;margin:8px 0;}
.close{float:right;font-size:28px;cursor:pointer;}
@media (max-width:768px){th,td{font-size:12px;padding:8px 5px;}}
</style>
</head>
<body>
<div class="container">
<h2><i class="fas fa-folder-open"></i> Ultimate File Manager (Full Filesystem Access)</h2>
<?php $msg = fm_get_msg(); if ($msg): ?>
<div class="message <?php echo $msg['type']=='error'?'error':''; ?>"><i class="fas fa-<?php echo $msg['type']=='error'?'exclamation-circle':'check-circle'; ?>"></i> <?php echo htmlspecialchars($msg['text']); ?></div>
<?php endif; ?>
<div class="breadcrumb">
<i class="fas fa-location-dot"></i> <?php echo htmlspecialchars($current); ?>
<?php 
$parent = dirname($current);
if ($parent !== $current) { ?>
    <a href="?p=<?php echo urlencode($parent); ?>"><i class="fas fa-arrow-up"></i> Up one level</a>
<?php } ?>
</div>
<div class="toolbar">
<div class="toolbar-group"><form method="get"><input type="text" name="p" value="<?php echo htmlspecialchars($current); ?>"><button><i class="fas fa-search"></i> Go</button></form></div>
<div class="toolbar-group"><form method="post" enctype="multipart/form-data" style="display:flex;gap:5px;"><input type="file" name="up"><button><i class="fas fa-upload"></i> Upload</button><input type="text" name="folder" placeholder="Folder"><button><i class="fas fa-folder-plus"></i> Create</button><input type="text" name="newfile" placeholder="File"><button><i class="fas fa-file"></i> Create</button></form></div>
</div>

<form method="post" id="bulkForm">
<div class="toolbar-group" style="margin-bottom:15px;">
<button type="button" onclick="selectAll()"><i class="fas fa-check-double"></i> Select All</button>
<select name="bulk_action"><option value="">Bulk Actions</option><option value="delete">Delete</option><option value="zip">Zip</option></select>
<button type="submit"><i class="fas fa-play"></i> Apply</button>
</div>
<table>
<thead><tr>
<th class="checkbox-col"><input type="checkbox" id="selectAllCheckbox"></th>
<th><a href="?p=<?php echo urlencode($current); ?>&sort=name&dir=<?php echo ($sort_by=='name' && $sort_dir=='asc')?'desc':'asc'; ?>">Name <?php echo ($sort_by=='name')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
<th><a href="?p=<?php echo urlencode($current); ?>&sort=size&dir=<?php echo ($sort_by=='size' && $sort_dir=='asc')?'desc':'asc'; ?>">Size <?php echo ($sort_by=='size')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
<th><a href="?p=<?php echo urlencode($current); ?>&sort=time&dir=<?php echo ($sort_by=='time' && $sort_dir=='asc')?'desc':'asc'; ?>">Modified <?php echo ($sort_by=='time')?($sort_dir=='asc'?'↑':'↓'):''; ?></a></th>
<th>Perms</th><th>Actions</th></tr></thead>
<tbody>
<?php foreach ($all as $item):
    $full = $current.'/'.$item;
    $isDir = is_dir($full);
    $icon = $isDir ? '<i class="fas fa-folder"></i>' : '<i class="fas fa-file"></i>';
    $size = $isDir ? '-' : fm_size(filesize($full));
    $time = date(FM_DATE_FORMAT, filemtime($full));
    $perms = fm_perms($full);
?>
<tr>
<td class="checkbox-col"><input type="checkbox" name="selected[]" value="<?php echo htmlspecialchars($item); ?>"></td>
<td><?php echo $icon; ?> <?php if ($isDir): ?><a href="?p=<?php echo urlencode($full); ?>"><strong><?php echo htmlspecialchars($item); ?></strong></a><?php else: ?><a href="?p=<?php echo urlencode($current); ?>&edit=<?php echo urlencode($item); ?>"><?php echo htmlspecialchars($item); ?></a><?php endif; ?></td>
<td><?php echo $size; ?></td>
<td><?php echo $time; ?></td>
<td><?php echo $perms; ?></td>
<td class="actions">
<?php if (!$isDir): ?><a href="?p=<?php echo urlencode($current); ?>&edit=<?php echo urlencode($item); ?>"><i class="fas fa-edit"></i> Edit</a> <a href="?p=<?php echo urlencode($current); ?>&download=<?php echo urlencode($item); ?>"><i class="fas fa-download"></i> DL</a> <?php endif; ?>
<a href="#" onclick="showRename('<?php echo htmlspecialchars($item); ?>')"><i class="fas fa-i-cursor"></i> Rename</a>
<a href="#" onclick="showCopyMove('<?php echo htmlspecialchars($item); ?>','copy')"><i class="fas fa-copy"></i> Copy</a>
<a href="#" onclick="showCopyMove('<?php echo htmlspecialchars($item); ?>','move')"><i class="fas fa-cut"></i> Move</a>
<a href="#" onclick="showChmod('<?php echo htmlspecialchars($item); ?>')"><i class="fas fa-lock"></i> Chmod</a>
<a href="?p=<?php echo urlencode($current); ?>&delete=<?php echo urlencode($item); ?>" onclick="return confirm('Delete <?php echo addslashes($item); ?>?')"><i class="fas fa-trash"></i> Del</a>
<?php if (!$isDir && pathinfo($item, PATHINFO_EXTENSION)=='zip'): ?>
<form method="post" style="display:inline;"><input type="hidden" name="extract_zip" value="<?php echo htmlspecialchars($item); ?>"><button type="submit" style="background:none;padding:0;"><i class="fas fa-archive"></i> Extract</button></form>
<?php endif; ?>
</tr>
<?php endforeach; ?>
<?php if (empty($all)): ?><tr><td colspan="6" style="text-align:center;">Empty folder</td></tr><?php endif; ?>
</tbody>
</table>
</form>

<?php if (isset($_GET['edit']) && is_file($current.'/'.basename($_GET['edit']))):
    $ef = basename($_GET['edit']);
    $cont = htmlspecialchars(file_get_contents($current.'/'.$ef));
?>
<div style="margin-top:30px; background:#0f172a; padding:20px; border-radius:12px;">
<h3>Editing: <?php echo htmlspecialchars($ef); ?></h3>
<form method="post"><textarea name="content" style="width:100%; height:400px; font-family:monospace; background:#1e293b; border:1px solid #334155; color:#f1f5f9; padding:10px;"><?php echo $cont; ?></textarea><input type="hidden" name="savefile" value="<?php echo htmlspecialchars($ef); ?>"><br><button type="submit">Save</button> <a href="?p=<?php echo urlencode($current); ?>">Cancel</a></form>
</div>
<?php endif; ?>
</div>

<div id="renameModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('renameModal')">&times;</span><h3>Rename</h3><form method="post"><input type="hidden" name="rename_old" id="renameOld"><input type="text" name="rename_new" id="renameNew" required><button>Rename</button></form></div></div>
<div id="copymoveModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('copymoveModal')">&times;</span><h3 id="cmTitle">Copy</h3><form method="post"><input type="hidden" name="copy_source" id="copySource"><input type="hidden" name="copy_action" id="copyAction"><input type="text" name="copy_dest" id="copyDest" value="<?php echo htmlspecialchars($current); ?>" required><button>Execute</button></form></div></div>
<div id="chmodModal" class="modal"><div class="modal-content"><span class="close" onclick="closeModal('chmodModal')">&times;</span><h3>Chmod</h3><form method="post"><input type="hidden" name="chmod_target" id="chmodTarget"><input type="text" name="chmod_value" id="chmodValue" placeholder="755"><button>Apply</button></form></div></div>

<script>
function selectAll(){var c=document.querySelectorAll('input[name="selected[]"]');var a=true;for(var i=0;i<c.length;i++){if(!c[i].checked){a=false;break;}}for(var i=0;i<c.length;i++){c[i].checked=!a;}document.getElementById('selectAllCheckbox').checked=!a;}
document.getElementById('selectAllCheckbox').addEventListener('change',function(e){var c=document.querySelectorAll('input[name="selected[]"]');for(var i=0;i<c.length;i++){c[i].checked=e.target.checked;}});
function showRename(n){document.getElementById('renameOld').value=n;document.getElementById('renameNew').value=n;document.getElementById('renameModal').style.display='flex';}
function showCopyMove(n,a){document.getElementById('copySource').value=n;document.getElementById('copyAction').value=a;document.getElementById('cmTitle').innerText=(a=='copy'?'Copy':'Move')+' Item';document.getElementById('copyDest').value='<?php echo addslashes($current); ?>';document.getElementById('copymoveModal').style.display='flex';}
function showChmod(n){document.getElementById('chmodTarget').value=n;document.getElementById('chmodValue').value='';document.getElementById('chmodModal').style.display='flex';}
function closeModal(id){document.getElementById(id).style.display='none';}
window.onclick=function(e){if(e.target.classList.contains('modal')) e.target.style.display='none';}
</script>
</body>
</html>