<?php
/**
 * PHP File Manager
 * A complete web-based file management solution
 */

// =============================================
// CONFIGURATION SECTION
// =============================================

// Basic Configuration
$starttime = explode(' ', microtime());
$starttime = $starttime[1] + $starttime[0];
$fm_version = '2.0';

// Supported Languages
$langs = array('en', 'ru', 'de', 'fr', 'ja', 'uk');
$default_language = 'en';
$detect_lang = true;

// Path Configuration
$path = empty($_REQUEST['path']) ? realpath('.') : realpath($_REQUEST['path']);
if (!$path) $path = realpath('.');
$path = str_replace('\\', '/', $path) . '/';
$main_path = str_replace('\\', '/', realpath('./'));

// PHP Version Check
$phar_maybe = (version_compare(phpversion(), "5.3.0", "<")) ? true : false;

// Message Container
$msg = '';

// =============================================
// AUTHORIZATION CONFIGURATION
// =============================================

$authorization = '{
    "authorize": 0,
    "days_authorization": 30,
    "login": "admin",
    "password": "phpfm",
    "cookie_name": "fm_user",
    "script": ""
}';

$auth = json_decode($authorization, true);

// =============================================
// TRANSLATION SYSTEM
// =============================================

$translation = '{
    "id": "en",
    "File manager": "File Manager",
    "Login": "Login",
    "Password": "Password",
    "Enter": "Enter",
    "Language": "Language",
    "English": "English",
    "German": "German",
    "Russian": "Russian",
    "French": "French",
    "Ukrainian": "Ukrainian",
    "Settings": "Settings",
    "done": "done",
    "Error occurred": "Error occurred",
    "File updated": "File updated",
    "Back": "Back",
    "Edit": "Edit",
    "Submit": "Submit",
    "Cancel": "Cancel",
    "Rights": "Permissions",
    "Recursively": "Recursively",
    "Rename": "Rename",
    "Files uploaded": "Files uploaded",
    "Deleted": "Deleted",
    "Created": "Created",
    "Make directory": "Create Directory",
    "New file": "New File",
    "Select the file": "Select the file",
    "Upload": "Upload",
    "Hello": "Hello",
    "Quit": "Logout",
    "Filename": "Filename",
    "Size": "Size",
    "Date": "Date",
    "Manage": "Manage",
    "Show": "Show",
    "Download": "Download",
    "Delete": "Delete",
    "Are you sure you want to delete this directory (recursively)?": "Are you sure you want to delete this directory (recursively)?",
    "Are you sure you want to delete this file?": "Are you sure you want to delete this file?",
    "File selected": "File selected",
    "Compress": "Compress",
    "Archiving": "Archiving",
    "Task": "Task",
    "Reset settings": "Reset Settings",
    "Cookie": "Cookie",
    "Days": "Days",
    "Script": "Script",
    "Save": "Save",
    "Add": "Add",
    "Name": "Name",
    "Value": "Value",
    "templates": "templates",
    "Console": "Console",
    "Result": "Result",
    "Reset": "Reset",
    "Select": "Select",
    "Template": "Template",
    "Home": "Home",
    "Generation time": "Generation time",
    "Recursive search": "Recursive search",
    "Mask": "Mask",
    "Search": "Search",
    "Found in files": "Found in files",
    "Nothing founded": "Nothing found",
    "No file": "No file",
    "to": "to",
    "Archive": "Archive",
    "Mode is incorrect": "Mode is incorrect",
    "Directory is not readable": "Directory is not readable",
    "File already exists": "File already exists",
    "as folder": "as folder",
    "Cannot create directory": "Cannot create directory",
    "Cannot write to file": "Cannot write to file",
    "Size of file": "Size of file",
    "is incorrect": "is incorrect",
    "Invalid file descriptor": "Invalid file descriptor",
    "is not readable": "is not readable",
    "Cannot rename": "Cannot rename",
    "Error": "Error",
    "Authorization": "Authorization",
    "Restore file time after editing": "Restore file time after editing",
    "Show size of the folder": "Show folder size",
    "Show pictures": "Show images",
    "Show PHP version": "Show PHP version",
    "Show PHP ini": "Show PHP configuration",
    "Show generation time": "Show generation time",
    "Show PHP Console": "Show PHP Console",
    "Show SQL Console": "Show SQL Console",
    "Show Proxy": "Show Proxy",
    "Show xls": "Show Excel export",
    "Decompress": "Decompress",
    "no files": "no files",
    "Success": "Success"
}';

$lang = json_decode($translation, true);

// =============================================
// DEFAULT CONFIGURATION
// =============================================

$fm_default_config = array(
    'make_directory' => true,
    'new_file' => true,
    'upload_file' => true,
    'show_dir_size' => false,
    'show_img' => true,
    'show_php_ver' => true,
    'show_php_ini' => false,
    'show_gt' => true,
    'enable_php_console' => true,
    'enable_sql_console' => true,
    'sql_server' => 'localhost',
    'sql_username' => 'root',
    'sql_password' => '',
    'sql_db' => 'test_base',
    'enable_proxy' => false,
    'show_phpinfo' => true,
    'show_xls' => true,
    'fm_settings' => true,
    'restore_time' => true,
    'fm_restore_time' => false,
);

// Load user configuration
if (empty($_COOKIE['fm_config'])) {
    $fm_config = $fm_default_config;
} else {
    $fm_config = unserialize($_COOKIE['fm_config']);
    if (!is_array($fm_config)) {
        $fm_config = $fm_default_config;
    }
}

// =============================================
// LANGUAGE DETECTION
// =============================================

// Change language from POST
if (isset($_POST['fm_lang'])) {
    setcookie('fm_lang', $_POST['fm_lang'], time() + (86400 * $auth['days_authorization']));
    $_COOKIE['fm_lang'] = $_POST['fm_lang'];
}

$language = $default_language;

// Detect browser language
if ($detect_lang && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && empty($_COOKIE['fm_lang'])) {
    $lang_priority = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    if (!empty($lang_priority)) {
        foreach ($lang_priority as $lang_arr) {
            $lng = explode(';', $lang_arr);
            $lng = substr($lng[0], 0, 2);
            if (in_array($lng, $langs)) {
                $language = $lng;
                break;
            }
        }
    }
}

// Use cookie language if set
$language = (empty($_COOKIE['fm_lang'])) ? $language : $_COOKIE['fm_lang'];

// =============================================
// CORE FUNCTIONS
// =============================================

/**
 * Translation function
 */
function __($text) {
    global $lang;
    return isset($lang[$text]) ? $lang[$text] : $text;
}

/**
 * Delete files and directories recursively
 */
function fm_del_files($file, $recursive = false) {
    if ($recursive && @is_dir($file)) {
        $els = fm_scan_dir($file, '', '', true);
        foreach ($els as $el) {
            if ($el != '.' && $el != '..') {
                fm_del_files($file . '/' . $el, true);
            }
        }
    }
    if (@is_dir($file)) {
        return rmdir($file);
    } else {
        return @unlink($file);
    }
}

/**
 * Get file permissions string
 */
function fm_rights_string($file, $if = false) {
    $perms = fileperms($file);
    $info = '';
    
    if (!$if) {
        if (($perms & 0xC000) == 0xC000) {
            $info = 's'; // Socket
        } elseif (($perms & 0xA000) == 0xA000) {
            $info = 'l'; // Symbolic Link
        } elseif (($perms & 0x8000) == 0x8000) {
            $info = '-'; // Regular
        } elseif (($perms & 0x6000) == 0x6000) {
            $info = 'b'; // Block special
        } elseif (($perms & 0x4000) == 0x4000) {
            $info = 'd'; // Directory
        } elseif (($perms & 0x2000) == 0x2000) {
            $info = 'c'; // Character special
        } elseif (($perms & 0x1000) == 0x1000) {
            $info = 'p'; // FIFO pipe
        } else {
            $info = 'u'; // Unknown
        }
    }
    
    // Owner
    $info .= (($perms & 0x0100) ? 'r' : '-');
    $info .= (($perms & 0x0080) ? 'w' : '-');
    $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x') : (($perms & 0x0800) ? 'S' : '-'));
    
    // Group
    $info .= (($perms & 0x0020) ? 'r' : '-');
    $info .= (($perms & 0x0010) ? 'w' : '-');
    $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x') : (($perms & 0x0400) ? 'S' : '-'));
    
    // World
    $info .= (($perms & 0x0004) ? 'r' : '-');
    $info .= (($perms & 0x0002) ? 'w' : '-');
    $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x') : (($perms & 0x0200) ? 'T' : '-'));
    
    return $info;
}

/**
 * Convert rights string to octal
 */
function fm_convert_rights($mode) {
    $mode = str_pad($mode, 9, '-');
    $trans = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
    $mode = strtr($mode, $trans);
    $newmode = '0';
    $owner = (int)$mode[0] + (int)$mode[1] + (int)$mode[2];
    $group = (int)$mode[3] + (int)$mode[4] + (int)$mode[5];
    $world = (int)$mode[6] + (int)$mode[7] + (int)$mode[8];
    $newmode .= $owner . $group . $world;
    return intval($newmode, 8);
}

/**
 * Change file permissions
 */
function fm_chmod($file, $val, $rec = false) {
    $res = @chmod(realpath($file), $val);
    if (@is_dir($file) && $rec) {
        $els = fm_scan_dir($file);
        foreach ($els as $el) {
            $res = $res && fm_chmod($file . '/' . $el, $val, true);
        }
    }
    return $res;
}

/**
 * Download file
 */
function fm_download($file_name) {
    if (!empty($file_name) && file_exists($file_name)) {
        header("Content-Disposition: attachment; filename=" . basename($file_name));
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($file_name));
        readfile($file_name);
        exit;
    } else {
        header('HTTP/1.0 404 Not Found', true, 404);
        exit;
    }
}

/**
 * Calculate directory size
 */
function fm_dir_size($f, $format = true) {
    if (is_file($f)) {
        $size = filesize($f);
    } else {
        $size = 0;
        $dh = opendir($f);
        while (($file = readdir($dh)) !== false) {
            if ($file == '.' || $file == '..') continue;
            $filepath = $f . '/' . $file;
            $size += is_file($filepath) ? filesize($filepath) : fm_dir_size($filepath, false);
        }
        closedir($dh);
    }
    
    if (!$format) return $size;
    
    if ($size == 0) return '0 bytes';
    $units = array('bytes', 'KB', 'MB', 'GB', 'TB');
    $i = floor(log($size, 1024));
    return round($size / pow(1024, $i), 2) . ' ' . $units[$i];
}

/**
 * Scan directory
 */
function fm_scan_dir($directory, $exp = '', $type = 'all', $do_not_filter = false) {
    $dir = array();
    if (!empty($exp)) {
        $exp = '/^' . str_replace('*', '(.*)', str_replace('.', '\\.', $exp)) . '$/';
    }
    
    if (!empty($type) && $type !== 'all') {
        $func = 'is_' . $type;
    }
    
    if (@is_dir($directory)) {
        $fh = opendir($directory);
        while (false !== ($filename = readdir($fh))) {
            if (substr($filename, 0, 1) != '.' || $do_not_filter) {
                if ((empty($type) || $type == 'all' || $func($directory . '/' . $filename)) && 
                    (empty($exp) || preg_match($exp, $filename))) {
                    $dir[] = $filename;
                }
            }
        }
        closedir($fh);
        natsort($dir);
    }
    return $dir;
}

/**
 * Create navigation link
 */
function fm_link($get, $link, $name, $title = '') {
    if (empty($title)) $title = $name . ' ' . basename($link);
    return '&nbsp;&nbsp;<a href="?' . $get . '=' . base64_encode($link) . '" title="' . $title . '">' . $name . '</a>';
}

/**
 * Language selection form
 */
function fm_lang_form($current = 'en') {
    $languages = array(
        'en' => __('English'),
        'de' => __('German'),
        'ru' => __('Russian'),
        'fr' => __('French'),
        'uk' => __('Ukrainian')
    );
    
    $options = '';
    foreach ($languages as $code => $name) {
        $selected = ($current == $code) ? 'selected="selected"' : '';
        $options .= '<option value="' . $code . '" ' . $selected . '>' . $name . '</option>';
    }
    
    return '
    <form name="change_lang" method="post" action="">
        <select name="fm_lang" title="' . __('Language') . '" onchange="this.form.submit()">
            ' . $options . '
        </select>
    </form>';
}

/**
 * Check if directory is root
 */
function fm_root($dirname) {
    return ($dirname == '.' || $dirname == '..');
}

/**
 * Execute PHP code
 */
function fm_php($string) {
    $display_errors = ini_get('display_errors');
    ini_set('display_errors', '1');
    ob_start();
    eval(trim($string));
    $text = ob_get_contents();
    ob_end_clean();
    ini_set('display_errors', $display_errors);
    return $text;
}

/**
 * SQL Connection
 */
function fm_sql_connect() {
    global $fm_config;
    return new mysqli($fm_config['sql_server'], $fm_config['sql_username'], $fm_config['sql_password'], $fm_config['sql_db']);
}

/**
 * Execute SQL query
 */
function fm_sql($query) {
    $connection = fm_sql_connect();
    if ($connection->connect_error) {
        return $connection->connect_error;
    }
    
    $connection->set_charset('utf8');
    $result = $connection->query($query);
    
    if ($result === false) {
        return mysqli_error($connection);
    }
    
    $output = '';
    if ($result instanceof mysqli_result) {
        $output .= '<table border="1" cellpadding="4" cellspacing="0">';
        $first = true;
        while ($row = $result->fetch_assoc()) {
            if ($first) {
                $output .= '<tr>';
                foreach (array_keys($row) as $key) {
                    $output .= '<th>' . htmlspecialchars($key) . '</th>';
                }
                $output .= '</tr>';
                $first = false;
            }
            $output .= '<tr>';
            foreach ($row as $value) {
                $output .= '<td>' . htmlspecialchars($value) . '</td>';
            }
            $output .= '</tr>';
        }
        $output .= '</table>';
        $result->free();
    } else {
        $output = __('Query executed successfully');
    }
    
    $connection->close();
    return $output;
}

/**
 * Get image link
 */
function fm_img_link($filename) {
    return './' . basename(__FILE__) . '?img=' . base64_encode($filename);
}

/**
 * Home button style
 */
function fm_home_style() {
    return '
    .home {
        background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAdgAAAHYBTnsmCAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFYSURBVDiNpZM9SwNBEIafg4iFhY2N2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFjY2Ih/YGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWHxX+zu3eY0kA8vszO7O/PO7M4q/keU/6vUfQ1AKaUBWoA2YAA4gA/gBXi11l5lBpRSOgA9wCgwDgwC3UAn0A40A1XgG3gC7oBL4Nxae5sCaK31gCFgCpgFJoA+oA1oARqBBkADv4ACvoBH4AY4A46stZcOoLXWAkaAeWABmAR6gVagCWhQShml1K9S6gdQgAJegGvgBDiw1l44gNZaD5gBloB5YALoAdqAJqWUVkr9KKW0UsoopX6VUt/AM3ALnAL71tpzB9Ba6wPzwAqwCIwD3UAr0KyU0kqpL6WUVkr9KKW+HIgH4Ao4BPastRcOoLXWBxaBVWABGAO6gBagUSn0opT6UEp9KKU+lFIfSqkP4AW4A06APWvtuQNorQ2AJWAVmANGgS6gBWhUSn0opd6VUu9KqXel1LtS6g14BW6BE2DPWnvmAFprA2AZWAPmgFGgE2gGGpRS70qpd6XUm1LqTSn1ppR6A96AO+AE2LXWnjmA1toAWAHWgTlgBOgAmoAGpdSbUupNKfWqlHpVSr0qpd6Bd+AOOAZ2rbVnDvAHs5xZ3Cz7j5AAAAAASUVORK5CYII=");
        background-repeat: no-repeat;
        display: inline-block;
        width: 16px;
        height: 16px;
        vertical-align: middle;
    }';
}

/**
 * Get site URL
 */
function fm_site_url() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    return $protocol . "://" . $_SERVER['HTTP_HOST'];
}

/**
 * Get file manager URL
 */
function fm_url($full = false) {
    $host = $full ? fm_site_url() : '.';
    return $host . '/' . basename(__FILE__);
}

/**
 * Home link
 */
function fm_home($full = false) {
    return '&nbsp;<a href="' . fm_url($full) . '" title="' . __('Home') . '"><span class="home"></span></a>';
}

// =============================================
// AUTHORIZATION CHECK
// =============================================

if ($auth['authorize']) {
    if (isset($_POST['login']) && isset($_POST['password'])) {
        if ($_POST['login'] == $auth['login'] && $_POST['password'] == $auth['password']) {
            setcookie($auth['cookie_name'], $auth['login'] . '|' . md5($auth['password']), time() + (86400 * $auth['days_authorization']));
            $_COOKIE[$auth['cookie_name']] = $auth['login'] . '|' . md5($auth['password']);
        }
    }
    
    if (!isset($_COOKIE[$auth['cookie_name']]) || $_COOKIE[$auth['cookie_name']] != $auth['login'] . '|' . md5($auth['password'])) {
        echo '<!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>' . __('File manager') . '</title>
            <style>
                body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; }
                .login-form { background: #f5f5f5; padding: 20px; border-radius: 5px; }
                input[type="text"], input[type="password"] { width: 100%; padding: 8px; margin: 5px 0; }
                input[type="submit"] { background: #006699; color: white; padding: 10px 20px; border: none; cursor: pointer; }
            </style>
        </head>
        <body>
            <div class="login-form">
                <h2>' . __('File manager') . '</h2>
                <form action="" method="post">
                    <p><input type="text" name="login" placeholder="' . __('Login') . '" required></p>
                    <p><input type="password" name="password" placeholder="' . __('Password') . '" required></p>
                    <p><input type="submit" value="' . __('Enter') . '"></p>
                </form>
                ' . fm_lang_form($language) . '
            </div>
        </body>
        </html>';
        exit;
    }
    
    if (isset($_POST['quit'])) {
        setcookie($auth['cookie_name'], '', time() - 3600);
        header('Location: ' . fm_site_url() . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// =============================================
// MAIN REQUEST HANDLING
// =============================================

// Handle file download
if (isset($_GET['download'])) {
    fm_download(base64_decode($_GET['download']));
}

// Handle image display
if (isset($_GET['img'])) {
    $file = base64_decode($_GET['img']);
    if ($info = getimagesize($file)) {
        switch ($info[2]) {
            case 1: $ext = 'gif'; break;
            case 2: $ext = 'jpeg'; break;
            case 3: $ext = 'png'; break;
            case 6: $ext = 'bmp'; break;
            default: exit;
        }
        header("Content-type: image/$ext");
        readfile($file);
        exit;
    }
}

// Show PHP info
if (isset($_GET['phpinfo'])) {
    phpinfo();
    exit;
}

// =============================================
// EDIT FILE HANDLING
// =============================================

// Handle file editing
if (isset($_GET['edit'])) {
    $file_to_edit = $path . $_GET['edit'];
    $file_content = '';
    
    if (file_exists($file_to_edit) && is_file($file_to_edit)) {
        $file_content = file_get_contents($file_to_edit);
    }
    
    // Handle form submission for saving edited file
    if (isset($_POST['file_content']) && isset($_POST['filename'])) {
        $new_content = $_POST['file_content'];
        $filename = $path . $_POST['filename'];
        
        if (file_put_contents($filename, $new_content)) {
            $msg = __('File updated');
            echo '<script>setTimeout(function(){ window.location.href = "?path=' . urlencode($path) . '"; }, 1000);</script>';
        } else {
            $msg = __('Error occurred');
        }
    }
    
    // Display edit form
    echo '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>' . __('Edit') . ' - ' . htmlspecialchars($_GET['edit']) . '</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
            .edit-form { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
            textarea { width: 100%; height: 400px; font-family: monospace; padding: 10px; border: 1px solid #ddd; }
            .buttons { margin-top: 10px; }
            input[type="submit"] { background: #006699; color: white; padding: 8px 16px; border: none; cursor: pointer; margin-right: 10px; }
            a.button { background: #666; color: white; padding: 8px 16px; text-decoration: none; display: inline-block; }
        </style>
    </head>
    <body>
        <div class="edit-form">
            <h2>' . __('Edit') . ': ' . htmlspecialchars($_GET['edit']) . '</h2>';
            
            if (!empty($msg)) {
                echo '<div style="background: #dff0d8; color: #3c763d; padding: 10px; margin-bottom: 15px; border-radius: 3px;">' . $msg . '</div>';
            }
            
            echo '
            <form method="post" action="">
                <input type="hidden" name="filename" value="' . htmlspecialchars($_GET['edit']) . '">
                <textarea name="file_content" spellcheck="false">' . htmlspecialchars($file_content) . '</textarea>
                <div class="buttons">
                    <input type="submit" value="' . __('Save') . '">
                    <a href="?path=' . urlencode($path) . '" class="button">' . __('Cancel') . '</a>
                </div>
            </form>
        </div>
    </body>
    </html>';
    exit;
}

// =============================================
// HTML OUTPUT
// =============================================
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= __('File manager') ?></title>
    <style>
        body {
            background-color: white;
            font-family: Verdana, Arial, Helvetica, sans-serif;
            font-size: 8pt;
            margin: 0;
        }
        
        a { color: #006699; text-decoration: none; }
        a:hover { color: #DD6900; text-decoration: underline; }
        
        table { width: 100%; border-collapse: collapse; }
        th { background: #006699; color: #FFA34F; padding: 8px; text-align: left; }
        td { padding: 6px; border-bottom: 1px solid #ddd; }
        
        .row1 { background: #EFEFEF; }
        .row2 { background: #DEE3E7; }
        .row3 { background: #D1D7DC; padding: 10px; }
        
        .folder, .file, .img {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 5px;
            vertical-align: middle;
        }
        
        .folder { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAdgAAAHYBTnsmCAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFYSURBVDiNpZM9SwNBEIafg4iFhY2N2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFjY2Ih/YGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWHxX+zu3eY0kA8vszO7O/PO7M4q/keU/6vUfQ1AKaUBWoA2YAA4gA/gBXi11l5lBpRSOgA9wCgwDgwC3UAn0A40A1XgG3gC7oBL4Nxae5sCaK31gCFgCpgFJoA+oA1oARqBBkADv4ACvoBH4AY4A46stZcOoLXWAkaAeWABmAR6gVagCWhQShml1K9S6gdQgAJegGvgBDiw1l44gNZaD5gBloB5YALoAdqAJqWUVkr9KKW0UsoopX6VUt/AM3ALnAL71tpzB9Ba6wPzwAqwCIwD3UAr0KyU0kqpL6WUVkr9KKW+HIgH4Ao4BPastRcOoLXWBxaBVWABGAO6gBagUSn0opT6UEp9KKU+lFIfSqkP4AW4A06APWvtuQNorQ2AJWAVmANGgS6gBWhUSn0opd6VUu9KqXel1LtS6g14BW6BE2DPWnvmAFprA2AZWAPmgFGgE2gGGpRS70qpd6XUm1LqTSn1ppR6A96AO+AE2LXWnjmA1toAWAHWgTlgBOgAmoAGpdSbUupNKfWqlHpVSr0qpd6Bd+AOOAZ2rbVnDvAHs5xZ3Cz7j5AAAAAASUVORK5CYII="); }
        .file { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAdgAAAHYBTnsmCAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFYSURBVDiNpZM9SwNBEIafg4iFhY2N2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFjY2Ih/YGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWHxX+zu3eY0kA8vszO7O/PO7M4q/keU/6vUfQ1AKaUBWoA2YAA4gA/gBXi11l5lBpRSOgA9wCgwDgwC3UAn0A40A1XgG3gC7oBL4Nxae5sCaK31gCFgCpgFJoA+oA1oARqBBkADv4ACvoBH4AY4A46stZcOoLXWAkaAeWABmAR6gVagCWhQShml1K9S6gdQgAJegGvgBDiw1l44gNZaD5gBloB5YALoAdqAJqWUVkr9KKW0UsoopX6VUt/AM3ALnAL71tpzB9Ba6wPzwAqwCIwD3UAr0KyU0kqpL6WUVkr9KKW+HIgH4Ao4BPastRcOoLXWBxaBVWABGAO6gBagUSn0opd6VUu9KqXel1LtS6g14BW6BE2DPWnvmAFprA2AZWAPmgFGgE2gGGpRS70qpd6XUm1LqTSn1ppR6A96AO+AE2LXWnjmA1toAWAHWgTlgBOgAmoAGpdSbUupNKfWqlHpVSr0qpd6Bd+AOOAZ2rbVnDvAHs5xZ3Cz7j5AAAAAASUVORK5CYII="); }
        .img { background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAdgAAAHYBTnsmCAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFYSURBVDiNpZM9SwNBEIafg4iFhY2N2FhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFjY2Ih/YGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWHxX+zu3eY0kA8vszO7O/PO7M4q/keU/6vUfQ1AKaUBWoA2YAA4gA/gBXi11l5lBpRSOgA9wCgwDgwC3UAn0A40A1XgG3gC7oBL4Nxae5sCaK31gCFgCpgFJoA+oA1oARqBBkADv4ACvoBH4AY4A46stZcOoLXWAkaAeWABmAR6gVagCWhQShml1K9S6gdQgAJegGvgBDiw1l44gNZaD5gBloB5YALoAdqAJqWUVkr9KKW0UsoopX6VUt/AM3ALnAL71tpzB9Ba6wPzwAqwCIwD3UAr0KyU0kqpL6WUVkr9KKW+HIgH4Ao4BPastRcOoLXWBxaBVWABGAO6gBagUSn0opd6VUu9KqXel1LtS6g14BW6BE2DPWnvmAFprA2AZWAPmgFGgE2gGGpRS70qpd6XUm1LqTSn1ppR6A96AO+AE2LXWnjmA1toAWAHWgTlgBOgAmoAGpdSbUopNKfWqlHpVSr0qpd6Bd+AOOAZ2rbVnDvAHs5xZ3Cz7j5AAAAAASUVORK5CYII="); }
        
        input, textarea, select {
            font: normal 8pt Verdana, Arial, Helvetica, sans-serif;
            border: 1px solid #ccc;
            padding: 4px;
            margin: 2px;
        }
        
        input[type="submit"] {
            background: #006699;
            color: white;
            border: none;
            padding: 6px 12px;
            cursor: pointer;
        }
        
        <?= fm_home_style() ?>
        
        @media screen and (max-width: 768px) {
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            tr { border: 1px solid #ccc; margin-bottom: 10px; }
            td { border: none; position: relative; padding-left: 50%; }
            td:before { position: absolute; left: 6px; content: attr(data-label); font-weight: bold; }
        }
    </style>
</head>
<body>
    <!-- Header Section -->
    <table>
        <tr>
            <th colspan="2"><?= __('File manager') ?> - <?= htmlspecialchars($path) ?></th>
        </tr>
        <?php if (!empty($msg)): ?>
        <tr>
            <td colspan="2" class="row2"><?= $msg ?></td>
        </tr>
        <?php endif; ?>
        <tr>
            <td class="row2">
                <?= fm_home() ?>
                <?php if ($fm_config['make_directory']): ?>
                <form method="post" action="" style="display: inline;">
                    <input type="text" name="dirname" placeholder="<?= __('Make directory') ?>" size="15">
                    <input type="submit" name="mkdir" value="<?= __('Make directory') ?>">
                </form>
                <?php endif; ?>
                
                <?php if ($fm_config['new_file']): ?>
                <form method="post" action="" style="display: inline;">
                    <input type="text" name="filename" placeholder="<?= __('New file') ?>" size="15">
                    <input type="submit" name="mkfile" value="<?= __('New file') ?>">
                </form>
                <?php endif; ?>
            </td>
            <td class="row3" style="text-align: right;">
                <?php if ($fm_config['upload_file']): ?>
                <form method="post" action="" enctype="multipart/form-data" style="display: inline;">
                    <input type="file" name="upload" id="upload">
                    <input type="submit" value="<?= __('Upload') ?>">
                </form>
                <?php endif; ?>
                
                <?php if ($auth['authorize']): ?>
                <form action="" method="post" style="display: inline;">
                    <?= __('Hello') ?>, <?= $auth['login'] ?>
                    <input type="hidden" name="quit" value="1">
                    <input type="submit" value="<?= __('Quit') ?>">
                </form>
                <?php endif; ?>
                
                <?= fm_lang_form($language) ?>
            </td>
        </tr>
    </table>

    <!-- File Listing -->
    <table>
        <thead>
            <tr>
                <th><?= __('Filename') ?></th>
                <th><?= __('Size') ?></th>
                <th><?= __('Date') ?></th>
                <th><?= __('Rights') ?></th>
                <th colspan="4"><?= __('Manage') ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $elements = fm_scan_dir($path, '', 'all', true);
            $dirs = $files = array();
            
            foreach ($elements as $file) {
                if (@is_dir($path . $file)) {
                    $dirs[] = $file;
                } else {
                    $files[] = $file;
                }
            }
            
            natsort($dirs);
            natsort($files);
            $elements = array_merge($dirs, $files);
            
            foreach ($elements as $file):
                $filename = $path . $file;
                $filedata = @stat($filename);
                $is_dir = @is_dir($filename);
                $style = $is_dir ? 'row2' : 'row1';
                
                if ($is_dir) {
                    $icon = 'folder';
                    $link = '<a href="?path=' . urlencode($path . $file) . '"><span class="' . $icon . '"></span> ' . htmlspecialchars($file) . '</a>';
                    $size = $fm_config['show_dir_size'] ? fm_dir_size($filename) : '';
                } else {
                    $icon = @getimagesize($filename) && $fm_config['show_img'] ? 'img' : 'file';
                    if ($icon == 'img') {
                        $link = '<a href="' . fm_img_link($filename) . '" target="_blank"><span class="' . $icon . '"></span> ' . htmlspecialchars($file) . '</a>';
                    } else {
                        $link = '<a href="?edit=' . urlencode($file) . '&path=' . urlencode($path) . '"><span class="' . $icon . '"></span> ' . htmlspecialchars($file) . '</a>';
                    }
                    $size = fm_dir_size($filename);
                }
            ?>
            <tr class="<?= $style ?>">
                <td data-label="<?= __('Filename') ?>"><?= $link ?></td>
                <td data-label="<?= __('Size') ?>"><?= $size ?></td>
                <td data-label="<?= __('Date') ?>"><?= date('Y-m-d H:i:s', $filedata[9]) ?></td>
                <td data-label="<?= __('Rights') ?>"><?= fm_rights_string($filename) ?></td>
                <td data-label="<?= __('Manage') ?>">
                    <?php if (!fm_root($file)): ?>
                    <a href="#" onclick="if(confirm('<?= $is_dir ? __('Are you sure you want to delete this directory (recursively)?') : __('Are you sure you want to delete this file?') ?>')) location.href='?delete=<?= urlencode($file) ?>&path=<?= urlencode($path) ?>'"><?= __('Delete') ?></a>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if (!fm_root($file)): ?>
                    <a href="?rename=<?= urlencode($file) ?>&path=<?= urlencode($path) ?>"><?= __('Rename') ?></a>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if (!$is_dir): ?>
                    <a href="?download=<?= base64_encode($filename) ?>"><?= __('Download') ?></a>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if (!fm_root($file)): ?>
                    <a href="?edit=<?= urlencode($file) ?>&path=<?= urlencode($path) ?>"><?= __('Edit') ?></a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Footer -->
    <div class="row3">
        <?= fm_home() ?> | Version <?= $fm_version ?> | 
        <?php if ($fm_config['show_php_ver']): ?>PHP <?= phpversion() ?> | <?php endif; ?>
        <?php if ($fm_config['show_gt']): ?><?= __('Generation time') ?>: <?= round(microtime(true) - $starttime, 2) ?>s | <?php endif; ?>
        <?php if ($fm_config['show_phpinfo']): ?><a href="?phpinfo=true">phpinfo()</a> | <?php endif; ?>
        <?php if ($fm_config['fm_settings']): ?><a href="?fm_settings=true"><?= __('Settings') ?></a><?php endif; ?>
    </div>

    <?php
    // Handle file operations
    if (isset($_FILES['upload']) && $fm_config['upload_file']) {
        if (move_uploaded_file($_FILES['upload']['tmp_name'], $path . $_FILES['upload']['name'])) {
            echo '<script>location.reload();</script>';
        }
    }
    
    if (isset($_POST['mkdir']) && $fm_config['make_directory'] && !empty($_POST['dirname'])) {
        mkdir($path . $_POST['dirname'], 0755);
        echo '<script>location.reload();</script>';
    }
    
    if (isset($_POST['mkfile']) && $fm_config['new_file'] && !empty($_POST['filename'])) {
        file_put_contents($path . $_POST['filename'], '');
        echo '<script>location.reload();</script>';
    }
    
    if (isset($_GET['delete']) && !fm_root($_GET['delete'])) {
        fm_del_files($path . $_GET['delete'], true);
        echo '<script>location.href = "?path=' . urlencode($path) . '";</script>';
    }
    ?>
</body>
</html>