SOURCE DOWNLOAD

木漏茶室源码下载中心

整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。

发布版本 v6.25.232 升级后自动生成独立源码包,下载中心只发送这份冻结包 已排除 config.php / 用户数据 / 上传文件 / 升级备份
komorebi-forum 183 个节点 · PHP 8.3.37 · 完整源码 ZIP 1.31 MB
下载完整源码 ZIP 源码包大小:1.31 MB 安装教程 作者主页 免费开源 免费下载 ↓
COMMUNITY DEPLOYMENTS

已经跑起来的木漏茶室

从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。

实时检测
2 个站点已部署

已展示全部 2 个站点。

inc/upgrade.php 31.3 KB · 发布包 v6.25.232
下载
<?php
/**
 * 系统升级包:校验、备份、应用、健康检查与文件回滚。
 * 升级包必须包含 komorebi-upgrade.json 与完整站点源码,且版本必须高于当前站点。
 */

function upgrade_manifest_defaults()
{
    return [
        'type' => 'komorebi-upgrade',
        'name' => '木漏茶室系统升级包',
        'version' => '',
        'app_min' => '1.0',
        'app_max' => '',
        'php_min' => '7.4',
        'php_max' => '',
        'changelog' => '',
        'delete' => [],
    ];
}

function upgrade_core_required_files()
{
    return ['index.php', 'inc/bootstrap.php', 'inc/helpers.php', 'inc/db.php', 'inc/install_dist.php', 'pages/admin.php', 'assets/css/app.css'];
}

function upgrade_allowed_top_dirs()
{
    return ['assets', 'inc', 'pages', 'admin', 'plugins'];
}

function upgrade_allowed_top_files()
{
    return ['index.php', 'api.php', 'manifest.php', 'robots.txt', 'rss.php', 'sitemap.php', 'sw.js', 'README.md'];
}

function upgrade_allowed_exts()
{
    return ['php', 'css', 'js', 'svg', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'woff2', 'woff', 'ttf', 'otf', 'json', 'md', 'txt', 'mp3', 'mp4'];
}

function upgrade_bootstrap_version($file)
{
    if (!is_file($file)) {
        return '';
    }
    $code = (string) @file_get_contents($file, false, null, 0, 4096);
    if (preg_match("/define\\s*\\(\\s*'APP_VERSION'\\s*,\\s*'([^']+)'\\s*\\)/", $code, $m)) {
        return trim($m[1]);
    }
    if (preg_match('/define\\s*\\(\\s*"APP_VERSION"\\s*,\\s*"([^"]+)"\\s*\\)/', $code, $m)) {
        return trim($m[1]);
    }
    return '';
}

function upgrade_stage_validate($zipPath)
{
    $limits = ['max_files' => 6000, 'max_total' => 300 * 1024 * 1024, 'max_single' => 60 * 1024 * 1024, 'max_ratio' => 150];
    $work = package_extract_zip($zipPath, $limits);
    $keep = false;
    try {
        $manifests = package_find_manifest($work, 'komorebi-upgrade.json');
        if (count($manifests) === 0) {
            throw new Exception('升级包缺少 komorebi-upgrade.json');
        }
        if (count($manifests) > 1) {
            throw new Exception('升级包内只能有一个 komorebi-upgrade.json');
        }
        $root = dirname($manifests[0]);
        $raw = json_decode((string) file_get_contents($manifests[0]), true);
        if (!is_array($raw)) {
            throw new Exception('komorebi-upgrade.json 不是有效的 JSON');
        }
        $manifest = array_merge(upgrade_manifest_defaults(), $raw);
        if ((string) $manifest['type'] !== 'komorebi-upgrade') {
            throw new Exception('升级包类型不正确,type 必须是 komorebi-upgrade');
        }
        $version = trim((string) $manifest['version']);
        if (!preg_match('/^\d+(\.\d+){1,3}$/', $version)) {
            throw new Exception('升级包版本号必须类似 6.24.0');
        }
        foreach (['app_min', 'app_max', 'php_min', 'php_max'] as $field) {
            $val = trim((string) $manifest[$field]);
            if ($val !== '' && !preg_match('/^\d+(\.\d+){0,3}$/', $val)) {
                throw new Exception($field . ' 必须是数字点号版本');
            }
        }
        if (!package_version_matches(PHP_VERSION, (string) $manifest['php_min'], (string) $manifest['php_max'])) {
            throw new Exception('升级包要求 PHP ' . $manifest['php_min'] . ($manifest['php_max'] !== '' ? ' ~ ' . $manifest['php_max'] : '') . ',当前 PHP ' . PHP_VERSION . ' 不兼容');
        }
        if (!package_version_matches(APP_VERSION, (string) $manifest['app_min'], (string) $manifest['app_max'])) {
            throw new Exception('升级包要求站点版本 ' . $manifest['app_min'] . ($manifest['app_max'] !== '' ? ' ~ ' . $manifest['app_max'] : '') . ',当前版本 ' . APP_VERSION . ' 不兼容');
        }
        if (version_compare($version, APP_VERSION, '<=')) {
            throw new Exception('升级包版本 ' . $version . ' 不高于当前版本 ' . APP_VERSION . ',已拒绝');
        }
        $bootstrapVersion = upgrade_bootstrap_version($root . '/inc/bootstrap.php');
        if ($bootstrapVersion === '') {
            throw new Exception('升级包的 inc/bootstrap.php 未声明 APP_VERSION');
        }
        if ($bootstrapVersion !== $version) {
            throw new Exception('升级包清单版本 ' . $version . ' 与源码 APP_VERSION ' . $bootstrapVersion . ' 不一致');
        }
        foreach (upgrade_core_required_files() as $required) {
            if (!is_file($root . '/' . $required)) {
                throw new Exception('升级包缺少核心文件:' . $required);
            }
        }
        $files = [];
        $total = 0;
        foreach (package_scan_files($root, $limits) as $f) {
            $rel = $f['rel'];
            if ($rel === 'komorebi-upgrade.json') {
                continue;
            }
            if (package_path_blocked($rel, true)) {
                throw new Exception('升级包包含受保护路径:' . $rel);
            }
            $top = explode('/', $rel)[0];
            if (strpos($rel, '/') === false) {
                if (!in_array($rel, upgrade_allowed_top_files(), true)) {
                    throw new Exception('升级包根目录包含不允许的文件:' . $rel);
                }
            } elseif (!in_array($top, upgrade_allowed_top_dirs(), true)) {
                throw new Exception('升级包包含不允许的目录:' . $top);
            }
            $ext = strtolower(pathinfo($rel, PATHINFO_EXTENSION));
            if (!in_array($ext, upgrade_allowed_exts(), true)) {
                throw new Exception('升级包包含不允许的文件类型:' . $rel);
            }
            if ($ext === 'php') {
                $lint = package_php_lint($f['full']);
                if ($lint !== '') {
                    throw new Exception($rel . ' ' . $lint);
                }
            }
            $files[] = ['rel' => $rel, 'full' => $f['full'], 'size' => (int) $f['size']];
            $total += (int) $f['size'];
        }
        $delete = $manifest['delete'] ?? [];
        if (!is_array($delete)) {
            throw new Exception('delete 字段必须是数组');
        }
        $cleanDelete = [];
        foreach ($delete as $del) {
            $del = str_replace('\\', '/', trim((string) $del));
            if ($del === '' || !package_relpath_ok($del) || package_path_blocked($del, true)) {
                throw new Exception('delete 含非法路径:' . $del);
            }
            if ($del === 'inc/install_dist.php') {
                throw new Exception('升级包不能删除源码重建模板 inc/install_dist.php');
            }
            $top = explode('/', $del)[0];
            if (!in_array($top, upgrade_allowed_top_dirs(), true) && !in_array($del, upgrade_allowed_top_files(), true)) {
                throw new Exception('delete 含不允许的路径:' . $del);
            }
            $cleanDelete[] = $del;
        }
        $manifest['delete'] = $cleanDelete;
        $manifest['name'] = mb_substr(trim((string) $manifest['name']), 0, 80, 'UTF-8');
        if ($manifest['name'] === '') {
            $manifest['name'] = '木漏茶室 ' . $version . ' 系统升级包';
        }
        $manifest['changelog'] = mb_substr((string) $manifest['changelog'], 0, 20000, 'UTF-8');
        $applyCount = 0;
        foreach ($files as $f) {
            $applyCount++;
        }
        $keep = true;
        return [
            'ok' => true,
            'manifest' => $manifest,
            'version' => $version,
            'root' => $root,
            'work' => $work,
            'files' => $files,
            'file_count' => $applyCount,
            'total_size' => $total,
            'sha256' => hash_file('sha256', $zipPath),
        ];
    } finally {
        if (!$keep) {
            package_remove_dir($work);
        }
    }
}

function upgrade_history_file_path()
{
    $dir = APP_ROOT . '/storage/upgrades';
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        return '';
    }
    return $dir . '/history.json';
}

function upgrade_history()
{
    $file = upgrade_history_file_path();
    if ($file !== '' && is_file($file)) {
        $rows = json_decode((string) @file_get_contents($file), true);
        if (is_array($rows)) {
            return $rows;
        }
    }
    $raw = setting('site_upgrade_history', '');
    $rows = $raw !== '' ? json_decode($raw, true) : [];
    return is_array($rows) ? $rows : [];
}

function upgrade_history_save(array $rows)
{
    $rows = array_slice(array_values($rows), 0, 20);
    // 完整记录写入文件,避免 MySQL 的 settings.svalue 字段被长更新说明撑爆。
    $file = upgrade_history_file_path();
    $fileSaved = false;
    if ($file !== '') {
        $json = json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if ($json !== false) {
            $tmp = $file . '.tmp';
            if (@file_put_contents($tmp, $json, LOCK_EX) !== false && @rename($tmp, $file)) {
                @chmod($file, 0644);
                $fileSaved = true;
            } else {
                @unlink($tmp);
            }
        }
    }
    // 数据库只保留精简副本,作为文件不可写或旧环境下的兜底。
    $compact = [];
    foreach ($rows as $row) {
        unset($row['written'], $row['deleted']);
        $row['changelog'] = mb_substr((string) ($row['changelog'] ?? ''), 0, 200, 'UTF-8');
        $compact[] = $row;
    }
    try {
        set_setting('site_upgrade_history', json_encode($compact, JSON_UNESCAPED_SLASHES));
    } catch (Throwable $e) {
        // 完整记录已写文件时,数据库兜底写入失败不再阻塞升级。
        if (!$fileSaved) {
            throw $e;
        }
    }
}

function upgrade_copy_core_tree($src, $dst)
{
    if (!is_dir($dst) && !@mkdir($dst, 0775, true) && !is_dir($dst)) {
        throw new Exception('无法创建备份目录');
    }
    $items = @scandir($src);
    if (!is_array($items)) {
        throw new Exception('无法读取源码目录');
    }
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $s = $src . '/' . $item;
        $d = $dst . '/' . $item;
        $rel = str_replace('\\', '/', $s);
        if (package_path_blocked(substr($rel, strlen(APP_ROOT) + 1), true)) {
            continue;
        }
        if (is_link($s)) {
            continue;
        }
        if (is_dir($s)) {
            upgrade_copy_core_tree($s, $d);
        } elseif (is_file($s)) {
            if (!@copy($s, $d)) {
                throw new Exception('备份文件失败:' . $item);
            }
        }
    }
}

function upgrade_copy_tree_into($src, $dst)
{
    if (!is_dir($dst) && !@mkdir($dst, 0775, true) && !is_dir($dst)) {
        throw new Exception('无法创建目标目录');
    }
    foreach (array_diff(scandir($src), ['.', '..']) as $item) {
        $s = $src . '/' . $item;
        $d = $dst . '/' . $item;
        if (is_dir($s)) {
            upgrade_copy_tree_into($s, $d);
        } elseif (!@copy($s, $d)) {
            throw new Exception('恢复文件失败:' . $item);
        }
    }
}

function upgrade_cli_binary()
{
    $bin = (string) PHP_BINARY;
    if ($bin !== '' && strpos(basename($bin), 'php-fpm') === false && strpos(basename($bin), 'php-cgi') === false) {
        return $bin;
    }
    $guess = rtrim((string) PHP_BINDIR, '/\\') . '/php';
    return is_file($guess) ? $guess : 'php';
}

function upgrade_runtime_check($root)
{
    if (!is_file($root . '/inc/install_dist.php')) {
        return ['ok' => false, 'skipped' => false, 'detail' => '升级后缺少源码重建模板 inc/install_dist.php,后续升级与源码包重建会中断'];
    }
    $disabled = (string) ini_get('disable_functions');
    if ($disabled !== '' && preg_match('/\b(exec|proc_open|shell_exec)\b/i', $disabled)) {
        return ['ok' => true, 'skipped' => true, 'detail' => '主机禁用了命令执行,已跳过运行时健康检查'];
    }
    if (!function_exists('exec')) {
        return ['ok' => true, 'skipped' => true, 'detail' => '缺少 exec,已跳过运行时健康检查'];
    }
    $code = 'chdir(' . var_export($root, true) . '); $_SERVER["REQUEST_METHOD"]="GET"; require "inc/bootstrap.php"; echo "KM_BOOT_OK";';
    $cmd = escapeshellarg(upgrade_cli_binary()) . ' -d display_errors=1 -d error_reporting=E_ALL -r ' . escapeshellarg($code) . ' 2>&1';
    $out = [];
    $status = 0;
    @exec($cmd, $out, $status);
    $text = implode("\n", $out);
    if (strpos($text, 'KM_BOOT_OK') !== false) {
        return ['ok' => true, 'skipped' => false, 'detail' => '运行时引导检查通过'];
    }
    return ['ok' => false, 'skipped' => false, 'detail' => mb_substr(trim($text), 0, 500, 'UTF-8') ?: '运行时引导检查失败'];
}

function upgrade_clear_source_release_cache()
{
    // 升级完成后让源码下载中心重新扫描当前站点,自动把新文件合并进完整源码包。
    foreach ((array) glob(APP_ROOT . '/storage/tmp/source-channel-*') as $file) {
        if (is_file($file)) {
            @unlink($file);
        }
    }
}

function upgrade_warm_source_package()
{
    // 升级成功后立即用新版本源码重建完整包,保证下载中心不会继续发出旧结构。
    try {
        require_once APP_ROOT . '/inc/source_release.php';
        source_release_snapshot_publish(true);
        return ['ok' => true, 'detail' => '已重建并发布独立源码包'];
    } catch (Throwable $e) {
        return ['ok' => false, 'detail' => '源码包发布失败:' . $e->getMessage()];
    }
}

function upgrade_rollback_allowed($row, $user = null)
{
    if ($user === null) { $user = current_user(); }
    if (!is_superadmin($user) || !is_array($row)) { return false; }
    // 回滚权限收紧:只有绑定指定邮箱的超级管理员可见、可用。
    return function_exists('is_upgrade_superadmin') ? is_upgrade_superadmin($user) : false;
}

function upgrade_apply($report)
{
    $manifest = $report['manifest'];
    $version = $report['version'];
    $backupId = 'up_' . date('Ymd_His') . '_' . bin2hex(random_bytes(3));
    $backupRoot = APP_ROOT . '/storage/upgrades/' . $backupId;
    $backupFiles = $backupRoot . '/files';
    if (!@mkdir($backupRoot, 0775, true) && !is_dir($backupRoot)) {
        throw new Exception('无法创建升级备份目录,请检查 storage/upgrades 权限');
    }
    upgrade_copy_core_tree(APP_ROOT, $backupFiles);

    $dbBackup = '';
    if (DB::$driver === 'sqlite') {
        $sqlitePath = $GLOBALS['CONFIG']['sqlite_path'] ?? (APP_ROOT . '/data/komorebi.sqlite');
        if (is_file($sqlitePath)) {
            $dbBackup = $backupRoot . '/database.sqlite';
            if (!@copy($sqlitePath, $dbBackup)) {
                $dbBackup = '';
            }
        }
    }
    $actor = current_user();
    $meta = [
        'id' => $backupId,
        'name' => $manifest['name'],
        'actor_id' => (int) ($actor['id'] ?? 0),
        'actor_name' => (string) ($actor['nickname'] ?? $actor['username'] ?? ''),
        'actor_email' => strtolower(trim((string) ($actor['email'] ?? ''))),
        'from' => APP_VERSION,
        'to' => $version,
        'at' => now(),
        'backup' => 'storage/upgrades/' . $backupId . '/files',
        'database' => $dbBackup !== '' ? 'storage/upgrades/' . $backupId . '/database.sqlite' : '',
        'zip_sha256' => $report['sha256'],
        'file_count' => $report['file_count'],
        'total_size' => $report['total_size'],
        'changelog' => $manifest['changelog'],
        'status' => 'applying',
        'written' => [],
        'deleted' => [],
    ];
    file_put_contents($backupRoot . '/meta.json', json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

    $previousMaintenance = setting('maintenance', '0');
    $written = [];
    $deleted = [];
    try {
        set_setting('maintenance', '1');
        foreach ($report['files'] as $file) {
            $rel = $file['rel'];
            $target = APP_ROOT . '/' . $rel;
            if (!package_relpath_ok($rel) || package_path_blocked($rel, true)) {
                throw new Exception('应用时发现非法路径:' . $rel);
            }
            $dir = dirname($target);
            if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
                throw new Exception('无法创建目录:' . dirname($rel));
            }
            if (!@copy($file['full'], $target)) {
                throw new Exception('写入文件失败:' . $rel);
            }
            @chmod($target, 0644);
            $written[] = $rel;
        }
        foreach ($manifest['delete'] as $rel) {
            if ($rel === 'inc/install_dist.php') {
                throw new Exception('升级包不能删除源码重建模板 inc/install_dist.php');
            }
            $target = APP_ROOT . '/' . $rel;
            if (is_file($target)) {
                if (!@unlink($target)) {
                    throw new Exception('删除旧文件失败:' . $rel);
                }
                $deleted[] = $rel;
            }
        }
        $check = upgrade_runtime_check(APP_ROOT);
        if (empty($check['ok'])) {
            throw new Exception('新版本运行时检查未通过:' . $check['detail']);
        }
        // 升级会合法替换实时保护脚本,成功后重建完整性基线,避免被误报为文件篡改。
        if (function_exists('realtime_guard_self_check')) {
            try { realtime_guard_self_check(true); } catch (Throwable $e) {}
        }
        $meta['status'] = 'success';
        $meta['written'] = $written;
        $meta['deleted'] = $deleted;
        $meta['health'] = $check['detail'];
        file_put_contents($backupRoot . '/meta.json', json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        $history = upgrade_history();
        array_unshift($history, $meta);
        upgrade_history_save($history);
        set_setting('maintenance', $previousMaintenance);
        if (function_exists('opcache_reset')) {
            @opcache_reset();
        }
        upgrade_clear_source_release_cache();
        $sourcePackage = upgrade_warm_source_package();
        // 升级完成后主动重试部署回传:证书或协议切换失败过的站点会在这里补记。
        if (function_exists('source_deploy_report')) {
            try { source_deploy_report(''); } catch (Throwable $e) { /* 回传失败不阻塞升级 */ }
        }
        // 升级成功后清掉升级源缓存,避免顶部横幅继续提示已经升过的版本。
        $feedCache = APP_ROOT . '/storage/cache/upgrade_feed.json';
        if (is_file($feedCache)) {
            @unlink($feedCache);
        }
        package_remove_dir($report['work']);
        return $meta;
    } catch (Exception $e) {
        set_setting('maintenance', $previousMaintenance);
        try {
            upgrade_restore_from_backup($backupFiles, $written, $deleted);
        } catch (Exception $re) {
            // 回滚失败时保留备份,管理员可从备份目录手工恢复
        }
        package_remove_dir($report['work']);
        throw new Exception($e->getMessage() . ';已尝试回滚文件,备份保留在 storage/upgrades/' . $backupId);
    }
}

function upgrade_restore_from_backup($backupFiles, array $written, array $deleted)
{
    if (!is_dir($backupFiles)) {
        throw new Exception('备份目录不存在');
    }
    foreach ($written as $rel) {
        $old = $backupFiles . '/' . $rel;
        $target = APP_ROOT . '/' . $rel;
        if (is_file($old)) {
            @copy($old, $target);
        } elseif (is_file($target)) {
            @unlink($target);
        }
    }
    foreach ($deleted as $rel) {
        $old = $backupFiles . '/' . $rel;
        $target = APP_ROOT . '/' . $rel;
        if (is_file($old)) {
            @copy($old, $target);
        }
    }
    // 升级包新增、原站点不存在的文件:备份中不存在则删除
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($backupFiles, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $f) {
        if (!$f->isFile()) {
            continue;
        }
        $rel = str_replace('\\', '/', substr($f->getPathname(), strlen($backupFiles) + 1));
        $target = APP_ROOT . '/' . $rel;
        if (!is_file($target)) {
            if (!@copy($f->getPathname(), $target)) {
                throw new Exception('回滚文件失败:' . $rel);
            }
        }
    }
}

function upgrade_rollback($id)
{
    $id = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string) $id);
    $history = upgrade_history();
    $row = null;
    $index = null;
    foreach ($history as $i => $item) {
        if ((string) ($item['id'] ?? '') === $id) {
            $row = $item;
            $index = $i;
            break;
        }
    }
    if (!$row) {
        throw new Exception('升级记录不存在');
    }
    if (($row['status'] ?? '') !== 'success') {
        throw new Exception('这条升级记录当前不能回滚');
    }
    if (!upgrade_rollback_allowed($row)) {
        throw new Exception('回滚文件仅对绑定指定邮箱的超级管理员开放');
    }
    $backupDir = APP_ROOT . '/' . (string) ($row['backup'] ?? '');
    if (strpos($backupDir, APP_ROOT . '/storage/upgrades/') !== 0 || !is_dir($backupDir)) {
        throw new Exception('升级备份不存在,无法回滚');
    }
    $written = is_array($row['written'] ?? null) ? $row['written'] : [];
    $deleted = is_array($row['deleted'] ?? null) ? $row['deleted'] : [];
    // 先删掉升级新增的文件,再恢复升级前的文件
    foreach ($written as $rel) {
        $old = $backupDir . '/' . $rel;
        $target = APP_ROOT . '/' . $rel;
        if (!is_file($old) && is_file($target)) {
            @unlink($target);
        }
    }
    upgrade_restore_from_backup($backupDir, $written, $deleted);
    if (function_exists('opcache_reset')) {
        @opcache_reset();
    }
    $history[$index]['status'] = 'rolled_back';
    $history[$index]['rolled_back_at'] = now();
    upgrade_history_save($history);
    return $history[$index];
}

// ---------- v6.25 在线升级:远程升级源与分阶段安装 ----------

function upgrade_feed_default_url()
{
    return 'http://csrc.954377.xyz/index.php?page=source&act=upgrade_meta';
}

function upgrade_feed_url()
{
    // 升级源完全自动绑定,不再允许后台手工修改:
    // 1) 源码站检测到同邮箱新部署站点后,自动切到该新站的升级源;
    // 2) 站外站点沿用源码包内 deploy_origin 记录的源码站;
    // 3) 其余情况使用官方源码下载中心。
    $auto = trim((string) setting('upgrade_auto_feed_url', ''));
    if ($auto !== '') {
        return $auto;
    }
    if (function_exists('source_deploy_origin')) {
        $origin = source_deploy_origin();
        if (is_array($origin) && !empty($origin['source'])) {
            return rtrim((string) $origin['source'], '/') . '/index.php?page=source&act=upgrade_meta';
        }
    }
    return upgrade_feed_default_url();
}

function upgrade_feed_cache_file()
{
    $dir = APP_ROOT . '/storage/cache';
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        return '';
    }
    return $dir . '/upgrade_feed.json';
}

function upgrade_feed_same_host($url)
{
    $p = parse_url((string) $url);
    if (!is_array($p) || empty($p['host'])) {
        return false;
    }
    $scheme = strtolower((string) ($p['scheme'] ?? 'http'));
    $port = (int) ($p['port'] ?? ($scheme === 'https' ? 443 : 80));
    $selfHost = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    $selfName = strtolower((string) ($selfHost['host'] ?? 'localhost'));
    $selfPort = (int) ($selfHost['port'] ?? 80);
    $host = strtolower((string) $p['host']);
    if ($host === 'localhost' && $selfName === '127.0.0.1') {
        $host = '127.0.0.1';
    }
    if ($selfName === 'localhost' && $host === '127.0.0.1') {
        $selfName = '127.0.0.1';
    }
    if ($scheme === 'https' && $port === 443 && $selfPort === 80) {
        // 同一台主机的 HTTP / HTTPS 端口都视为自请求,避免单进程服务器死锁。
        $port = 80;
    }
    return $host === $selfName && $port === $selfPort;
}

function upgrade_feed_scheme_alternate($url)
{
    $url = trim((string) $url);
    if (preg_match('#^https://#i', $url)) {
        return preg_replace('#^https://#i', 'http://', $url);
    }
    if (preg_match('#^http://#i', $url)) {
        return preg_replace('#^http://#i', 'https://', $url);
    }
    return '';
}

function upgrade_feed_candidate_urls()
{
    $primary = upgrade_feed_url();
    $urls = [];
    foreach ([$primary, upgrade_feed_scheme_alternate($primary), upgrade_feed_default_url()] as $url) {
        $url = trim((string) $url);
        if ($url !== '' && !in_array($url, $urls, true)) {
            $urls[] = $url;
        }
    }
    return $urls;
}

function upgrade_feed_cache_bust_url($url)
{
    $sep = strpos($url, '?') === false ? '?' : '&';
    return $url . $sep . '_kmts=' . time() . '&_kmr=' . bin2hex(random_bytes(3));
}

function upgrade_feed_http_get($url, $timeout = 8)
{
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CONNECTTIMEOUT => 4,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_USERAGENT => 'Komorebi-Upgrade-Feed/1.0',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => ['Accept: application/json', 'Cache-Control: no-cache', 'Pragma: no-cache'],
        ]);
        $body = curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        if ($body === false || $code >= 400) {
            return [false, $err !== '' ? $err : ('HTTP ' . $code)];
        }
        return [true, (string) $body];
    }
    $ctx = stream_context_create(['http' => ['method' => 'GET', 'timeout' => $timeout, 'header' => "User-Agent: Komorebi-Upgrade-Feed/1.0\r\nAccept: application/json\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n"]]);
    $body = @file_get_contents($url, false, $ctx);
    if ($body === false) {
        return [false, '无法连接升级源'];
    }
    return [true, (string) $body];
}

function upgrade_feed_fetch($force = false)
{
    $feedUrl = upgrade_feed_url();
    $cacheFile = upgrade_feed_cache_file();
    $cache = $cacheFile !== '' && is_file($cacheFile) ? json_decode((string) @file_get_contents($cacheFile), true) : null;
    if (!$force && is_array($cache) && !empty($cache['checked_at']) && time() - (int) $cache['checked_at'] < 1800) {
        return $cache;
    }
    if (upgrade_feed_same_host($feedUrl)) {
        $result = [
            'ok' => true,
            'self' => true,
            'feed_url' => $feedUrl,
            'version' => APP_VERSION,
            'name' => '木漏茶室',
            'available' => false,
            'changelog' => '',
            'checked_at' => time(),
            'msg' => '当前站点就是升级源站点',
        ];
        if ($cacheFile !== '') {
            @file_put_contents($cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
        }
        return $result;
    }
    $result = [
        'ok' => false,
        'feed_url' => $feedUrl,
        'available' => false,
        'version' => '',
        'checked_at' => time(),
        'msg' => '无法连接升级源',
    ];
    $lastError = '无法连接升级源';
    foreach (upgrade_feed_candidate_urls() as $candidate) {
        $fetchUrl = upgrade_feed_cache_bust_url($candidate);
        list($ok, $bodyOrError) = upgrade_feed_http_get($fetchUrl);
        if (!$ok) {
            $lastError = $bodyOrError;
            continue;
        }
        $data = json_decode($bodyOrError, true);
        if (!is_array($data)) {
            $lastError = '升级源返回的不是有效 JSON';
            continue;
        }
        if (empty($data['version']) || empty($data['package_url'])) {
            $lastError = '升级源缺少 version 或 package_url';
            continue;
        }
        if (!preg_match('/^\d+(\.\d+){1,3}$/', (string) $data['version'])) {
            $lastError = '升级源版本号格式不正确';
            continue;
        }
        if (!preg_match('#^https?://#i', (string) $data['package_url'])) {
            $lastError = '升级源 package_url 必须是 http/https 地址';
            continue;
        }
        $result['ok'] = true;
        $result['feed_url'] = $candidate;
        $result['fallback'] = $candidate !== $feedUrl;
        $result['name'] = trim((string) ($data['name'] ?? '木漏茶室系统升级包'));
        $result['version'] = trim((string) $data['version']);
        $result['package_url'] = (string) $data['package_url'];
        $result['sha256'] = (string) ($data['sha256'] ?? '');
        $result['size'] = (int) ($data['size'] ?? 0);
        $result['changelog'] = mb_substr((string) ($data['changelog'] ?? ''), 0, 20000, 'UTF-8');
        $result['app_min'] = (string) ($data['app_min'] ?? '6.0.0');
        $result['php_min'] = (string) ($data['php_min'] ?? '7.4');
        $result['published_at'] = (string) ($data['published_at'] ?? '');
        $result['available'] = version_compare($result['version'], APP_VERSION, '>');
        $result['msg'] = $result['available'] ? '发现新版本 v' . $result['version'] : '当前已是最新版本';
        break;
    }
    if (!$result['ok']) { $result['msg'] = $lastError; }
    if ($cacheFile !== '') {
        @file_put_contents($cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    }
    return $result;
}

function upgrade_remote_status($force = false)
{
    return upgrade_feed_fetch($force);
}

function upgrade_online_root()
{
    $dir = APP_ROOT . '/storage/upgrades/online';
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new Exception('无法创建在线升级临时目录');
    }
    return $dir;
}

function upgrade_online_token_new()
{
    $token = bin2hex(random_bytes(12));
    $dir = upgrade_online_root() . '/' . $token;
    if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new Exception('无法创建在线升级任务目录');
    }
    return $token;
}

function upgrade_online_token_dir($token)
{
    $token = (string) $token;
    if (!preg_match('/^[a-f0-9]{24}$/', $token)) {
        throw new Exception('在线升级任务标识无效');
    }
    $dir = upgrade_online_root() . '/' . $token;
    if (!is_dir($dir)) {
        throw new Exception('在线升级任务已过期,请重新发起升级');
    }
    return $dir;
}

function upgrade_online_cleanup($token)
{
    try {
        $dir = upgrade_online_token_dir($token);
        package_remove_dir($dir);
    } catch (Exception $e) {
        // 已清理或标识无效
    }
}

function upgrade_online_report_save($token, array $report)
{
    $dir = upgrade_online_token_dir($token);
    $json = json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($json === false || @file_put_contents($dir . '/report.json', $json, LOCK_EX) === false) {
        throw new Exception('无法保存在线升级检测报告');
    }
}

function upgrade_online_report_load($token)
{
    $dir = upgrade_online_token_dir($token);
    $raw = @file_get_contents($dir . '/report.json');
    $report = json_decode((string) $raw, true);
    if (!is_array($report) || empty($report['files']) || empty($report['manifest'])) {
        throw new Exception('在线升级检测报告不存在或已过期');
    }
    return $report;
}
主题