<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 如果带 dl=1 参数：下载自身源码
if(isset($_GET['dl']) && $_GET['dl'] == 1){
    $code = file_get_contents(__FILE__);
    $fname = basename(__FILE__);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.$fname.'"');
    header('Content-Length: '.strlen($code));
    echo $code;
    exit;
}

// ========== 下面是原本的扫描+读取数据库配置逻辑 ==========
$init_host = '127.0.0.1';
$init_user = 'root';
$init_pwd  = '123456';
$init_db   = 'db_config_db';

$conn_init = mysqli_connect($init_host, $init_user, $init_pwd, $init_db);
if (!$conn_init) {
    die("<div style='color:red;font-size:18px'>初始配置库连接失败：" . mysqli_connect_error() . "</div>");
}

$sql = "SELECT db_host,db_name,db_user,db_pass FROM db_config LIMIT 1";
$res = mysqli_query($conn_init, $sql);
$db_cfg = mysqli_fetch_assoc($res);
mysqli_close($conn_init);

if (!$db_cfg) {
    die("<div style='color:red;font-size:18px'>数据库内没有找到配置记录！先执行建表SQL</div>");
}

$db_host = $db_cfg['db_host'];
$db_name = $db_cfg['db_name'];
$db_user = $db_cfg['db_user'];
$db_pass = $db_cfg['db_pass'];

$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$db) {
    die("<div style='color:red;font-size:18px'>目标数据库连接失败：" . mysqli_connect_error() . "</div>");
}
echo "<div style='background:#e8f5e9;padding:10px;border-radius:6px;color:#2e7d32;font-size:18px'>✅ 成功连接数据库【{$db_name}】</div>";


function scanDirAll(string $path, int $level = 0): void
{
    if (!is_dir($path)) {
        echo "<div style='padding-left:".($level*20)."px;color:#444'>📄 " . htmlspecialchars($path) . "</div>";
        return;
    }
    $list = scandir($path);
    foreach ($list as $item) {
        if ($item === '.' || $item === '..') continue;
        $fullPath = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $item;
        if (is_dir($fullPath)) {
            echo "<div style='padding-left:".($level*20)."px;color:#1976d2;font-weight:bold'>📂 " . htmlspecialchars($fullPath) . "</div>";
            scanDirAll($fullPath, $level + 1);
        } else {
            echo "<div style='padding-left:".($level*20)."px;color:#444'>📄 " . htmlspecialchars($fullPath) . "</div>";
        }
    }
}

$root_path = $_SERVER['DOCUMENT_ROOT'];
echo "<h3>📁 正在遍历网站根目录：" . htmlspecialchars($root_path) . "</h3>";
scanDirAll($root_path);

echo "<hr><div style='color:#666'>扫描完成 | <a href='?dl=1'>👉 点击下载本脚本源码</a></div>";
mysqli_close($db);
?>
