From 9fb69f4d00c1b0d1c78e7b7e62f98db249cc1726 Mon Sep 17 00:00:00 2001 From: ChatGPT Date: Fri, 27 Nov 2026 17:19:02 +0800 Subject: [PATCH] Use a standalone PHP updater with release compatibility rules --- README.md | 23 ++-- app/Content/Updates.php | 30 ++--- bin/update.php | 252 ++++++++++++++++++++++++++++++++-------- bin/update.sh | 5 - updatescript_map.json | 6 + 5 files changed, 239 insertions(+), 77 deletions(-) delete mode 100755 bin/update.sh create mode 100644 updatescript_map.json diff --git a/README.md b/README.md index 9e5cb4b..ddce5fa 100644 --- a/README.md +++ b/README.md @@ -109,21 +109,24 @@ php bin/backup.php export /srv/backups/laysite-2026-11.tar php bin/backup.php import /srv/backups/laysite-2026-11.tar --replace ``` -可在「账户 → 关于系统」点击「检查更新」,比较本机版本与 `git.laysense.com/laysense/laysite` 的最新 `vX.Y.Z` 发布标签。已合并但尚未打标签的版本不会出现在检查结果里。检查结果缓存 5 分钟。 +可在「账户 → 关于系统」点击「检查更新」,比较本机版本和 LaySite 仓库的最新正式发布。检查结果缓存 5 分钟。维护者发版时,先更新 `VERSION`,再用该提交创建同版本标签与正式 Release。 -维护者发布新版本时,在发布提交上创建并推送与 `VERSION` 对应的标签,例如 `v1.4.0`。 - -更新脚本从 LaySite 上游下载发布标签对应的 ZIP,通过 PHP 的 Phar 和 zlib 读取,部署目录无需安装 Git。更新前请暂停 Webman,并选择部署目录以外的备份路径。脚本先比较当前发布包、新发布包和本地文件,再备份站点、按需安装 Composer 依赖、替换程序文件并运行 SQLite 迁移。 - -站点设置、SQLite、媒体和站点新增的文件保留原位。对于本地与上游都改过的同一文件,脚本会在替换前列出冲突路径。处理这些定制后再更新。更新旧版本时,也可在旧站点的根目录直接运行单独取得的新版 `update.php`,避免修改旧站点的更新脚本。 +独立更新器 `bin/update.php` 可从已安装站点的根目录运行。它先读取官方主分支的 [更新器兼容表](updatescript_map.json),按内置的更新器版本选择起始和目标范围,再从 Gitea 的 Release 列表查找可用版本。范围包含两端,`v1.1.0-latest` 上限为当前最新正式发布。可通过兼容表收紧旧更新器的适用范围。 ```sh -bin/update.sh check -bin/update.sh v1.4.0 /srv/backups/pre-update.tar -# 旧安装可从站点根目录运行独立更新器 -php /path/to/update.php v1.4.0 /srv/backups/pre-update.tar +php bin/update.php +php bin/update.php check +php bin/update.php v1.4.2 /srv/backups/pre-update.tar +# 从旧安装运行单独下载的更新器 +php /path/to/update.php v1.4.2 ``` +无参数时会显示可选版本及发布说明,选择编号或标签后开始更新。指定版本会直接检查并执行。省略备份路径时会写入 `storage/backups/`。原 `bin/update.sh` 入口已停用。 + +更新前请暂停 Webman。脚本从 LaySite 上游下载所选标签的 ZIP,通过 PHP 的 Phar 和 zlib 读取。它先比较当前发布包、新发布包和本地文件,再备份站点、按需安装 Composer 依赖、替换程序文件并运行 SQLite 迁移。 + +站点设置、SQLite、媒体和站点新增的文件保留原位。对于本地与上游都改过的同一文件,脚本会在替换前列出冲突路径。处理这些定制后再更新。 + 从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。 从 v1.1.0 更新画布功能时,更新脚本会添加样式字段,并将已有页头和页脚迁到「网站页面」,保留页面引用和已有认证配置。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。 diff --git a/app/Content/Updates.php b/app/Content/Updates.php index 06e8b6b..b53c677 100644 --- a/app/Content/Updates.php +++ b/app/Content/Updates.php @@ -10,7 +10,7 @@ use RuntimeException; final class Updates { public const REPOSITORY = 'https://git.laysense.com/laysense/laysite'; - private const TAGS = 'https://git.laysense.com/api/v1/repos/laysense/laysite/tags'; + private const RELEASES = 'https://git.laysense.com/api/v1/repos/laysense/laysite/releases'; public static function current(): string { @@ -44,7 +44,7 @@ final class Updates $record = self::cached($path); if (($record['until'] ?? 0) <= time()) { try { - $record = ['latest' => self::latestTag(), 'until' => time() + 300]; + $record = ['latest' => self::latestRelease(), 'until' => time() + 300]; } catch (RuntimeException $exception) { $record = ['error' => $exception->getMessage(), 'until' => time() + 30]; } @@ -97,7 +97,7 @@ final class Updates } } - private static function latestTag(): ?string + private static function latestRelease(): ?string { $latest = null; $deadline = hrtime(true) + 3_000_000_000; @@ -107,25 +107,25 @@ final class Updates if ($remaining <= 0) { throw new RuntimeException('读取上游版本超时,请稍后重试。'); } - $tags = self::tags($page++, $remaining); - foreach ($tags as $tag) { - $name = $tag['name'] ?? null; - if (!is_string($name)) { + $releases = self::releases($page++, $remaining); + foreach ($releases as $release) { + $name = $release['tag_name'] ?? null; + if (!is_string($name) || !is_bool($release['draft'] ?? null) || !is_bool($release['prerelease'] ?? null)) { throw new RuntimeException('上游仓库返回的版本列表无效。'); } - if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match) + if (!$release['draft'] && !$release['prerelease'] && preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match) && ($latest === null || version_compare($match[1], $latest, '>'))) { $latest = $match[1]; } } - } while (count($tags) === 50); + } while (count($releases) === 50); return $latest; } - private static function tags(int $page, int $timeout): array + private static function releases(int $page, int $timeout): array { - $curl = curl_init(self::TAGS . '?limit=50&page=' . $page); + $curl = curl_init(self::RELEASES . '?limit=50&page=' . $page); if ($curl === false) { throw new RuntimeException('无法连接上游仓库,请稍后重试。'); } @@ -138,7 +138,7 @@ final class Updates CURLOPT_HTTPHEADER => ['Accept: application/json'], CURLOPT_USERAGENT => 'LaySite version check', CURLOPT_WRITEFUNCTION => static function (CurlHandle $handle, string $chunk) use (&$body, &$overflow): int { - if (strlen($body) + strlen($chunk) > 256 * 1024) { + if (strlen($body) + strlen($chunk) > 1024 * 1024) { $overflow = true; return 0; } @@ -155,11 +155,11 @@ final class Updates if ($status !== 200) { throw new RuntimeException('上游版本列表暂不可用(HTTP ' . $status . ')。'); } - $tags = json_decode($body); - if (!is_array($tags) || !array_is_list($tags)) { + $releases = json_decode($body); + if (!is_array($releases) || !array_is_list($releases)) { throw new RuntimeException('上游仓库返回的版本列表无效。'); } - return array_map(static fn ($tag): array => is_object($tag) ? get_object_vars($tag) : [], $tags); + return array_map(static fn ($release): array => is_object($release) ? get_object_vars($release) : [], $releases); } } diff --git a/bin/update.php b/bin/update.php index ba7827e..414a0d6 100644 --- a/bin/update.php +++ b/bin/update.php @@ -5,10 +5,25 @@ declare(strict_types=1); final class LaySiteUpdater { + private const UPDATESCRIPT_VERSION = '1.0.0'; private const HOST = 'https://git.laysense.com'; private const PROJECT = '/laysense/laysite'; + private const MAP_PATH = self::PROJECT . '/raw/branch/main/updatescript_map.json'; + private const RELEASES_PATH = '/api/v1/repos' . self::PROJECT . '/releases'; + private const TAG = '/^v(\d+\.\d+\.\d+)$/D'; + + // These two releases shipped with 1.4.0 in VERSION. Identify their original files when updating old installations. + private const LEGACY_VERSIONS = [ + '1.4.2' => [ + 'bin/update.sh' => 'a1cc96a5ecc3db3074563877dec07f0ebf8689e90e0e9aece838071df4793e26', + 'bin/update.php' => 'b13d3e925b59589f4d599d6deebb1fb27fa81ad0b98e5d0c67199279c3de9635', + ], + '1.4.1' => [ + 'public/assets/vendor/codemirror/xml.min.js' => 'c0c38a5cf20549c4e20d90428edd830cbbf6a631245a1ac2fb8e88676d4c0b7a', + ], + ]; private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f']; - private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|composer\.(?:json|lock)|start\.php)$/D'; + private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|updatescript_map\.json|composer\.(?:json|lock)|start\.php)$/D'; private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024; private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024; @@ -16,46 +31,160 @@ final class LaySiteUpdater { } - public function check(): void + public function execute(?string $target, ?string $backup): void { $current = $this->version(); - $latest = null; + $map = self::remoteJson(self::MAP_PATH, 65536, 10000); + $rule = is_object($map) ? ($map->{self::UPDATESCRIPT_VERSION} ?? null) : null; + if (!is_object($rule)) { + throw new RuntimeException('当前更新器未列入兼容表,请下载新版 update.php。'); + } + $from = self::parseRange($rule->from ?? null); + $to = self::parseRange($rule->to ?? null); + $releases = self::releases(); + $latest = array_key_first($releases); + $latestVersion = $latest === null ? null : substr($latest, 1); + if (!self::inRange($current, $from, $latestVersion)) { + throw new RuntimeException("当前站点 v$current 超出此更新器的起始版本范围 {$rule->from}。"); + } + $eligible = array_filter($releases, static function (string $tag) use ($current, $to, $latestVersion): bool { + $version = substr($tag, 1); + + return version_compare($version, $current, '>') && self::inRange($version, $to, $latestVersion); + }, ARRAY_FILTER_USE_KEY); + printf("更新器 v%s,当前站点 v%s\n兼容起始版本 %s,目标范围 %s\n", + self::UPDATESCRIPT_VERSION, $current, $rule->from, $rule->to); + + if ($target === 'check') { + if ($latest !== null) { + printf("上游最新正式发布 %s\n", $latest); + } + echo $eligible === [] ? "暂无可升级的正式发布版本。\n" + : '可升级至 ' . implode('、', array_keys($eligible)) . PHP_EOL; + return; + } + if ($target === null) { + $target = self::chooseRelease($eligible); + if ($target === null) { + return; + } + } elseif ($target === 'v' . $current) { + printf("当前已安装 %s。\n", $target); + return; + } + + if (!isset($eligible[$target])) { + throw new RuntimeException("无法从 v$current 升级到 {$target}。可选版本为 " + . ($eligible === [] ? '无。' : implode('、', array_keys($eligible)) . '。')); + } + $this->update($current, $target, $backup); + } + + private static function parseRange(mixed $value): array + { + if (!is_string($value) || !preg_match('/^v(\d+\.\d+\.\d+)-(?:v(\d+\.\d+\.\d+)|latest)$/D', $value, $parts) + || (isset($parts[2]) && version_compare($parts[1], $parts[2], '>'))) { + throw new RuntimeException('更新器兼容表中的版本范围无效。'); + } + + return [$parts[1], $parts[2] ?? null]; + } + + private static function inRange(string $version, array $range, ?string $latest): bool + { + [$minimum, $maximum] = $range; + $maximum ??= $latest; + + return version_compare($version, $minimum, '>=') && ($maximum === null || version_compare($version, $maximum, '<=')); + } + + private static function releases(): array + { + $result = []; $deadline = hrtime(true) + 10_000_000_000; for ($page = 1; ; $page++) { $timeout = (int) (($deadline - hrtime(true)) / 1_000_000); if ($timeout <= 0) { throw new RuntimeException('查询 LaySite 发布列表超时。'); } - $stream = fopen('php://temp', 'w+b'); - try { - self::download('/api/v1/repos' . self::PROJECT . "/tags?limit=50&page=$page", $stream, 262144, $timeout); - rewind($stream); - $tags = json_decode(stream_get_contents($stream), flags: JSON_THROW_ON_ERROR); - } finally { - fclose($stream); - } - if (!is_array($tags)) { + $entries = self::remoteJson(self::RELEASES_PATH . "?limit=50&page=$page", 1024 * 1024, $timeout); + if (!is_array($entries)) { throw new RuntimeException('LaySite 发布列表格式无效。'); } - foreach ($tags as $tag) { - $name = $tag->name ?? null; - if (!is_string($name)) { + foreach ($entries as $entry) { + if (!is_string($entry->tag_name ?? null) || !is_bool($entry->draft ?? null) || !is_bool($entry->prerelease ?? null)) { throw new RuntimeException('LaySite 发布列表格式无效。'); } - if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match) - && ($latest === null || version_compare($match[1], $latest, '>'))) { - $latest = $match[1]; + if (!$entry->draft && !$entry->prerelease && preg_match(self::TAG, $entry->tag_name)) { + $result[$entry->tag_name] = $entry; } } - if (count($tags) < 50) { + if (count($entries) < 50) { break; } } + uksort($result, static fn (string $a, string $b): int => version_compare(substr($b, 1), substr($a, 1))); - printf("当前版本 v%s\n%s\n", $current, $latest === null ? '上游暂无发布版本。' : '最新发布版本 v' . $latest); + return $result; } - public function update(string $target, string $backup): void + private static function remoteJson(string $path, int $limit, int $timeout): mixed + { + $stream = fopen('php://temp', 'w+b'); + if ($stream === false) { + throw new RuntimeException('无法创建更新查询缓冲区。'); + } + try { + self::download($path, $stream, $limit, $timeout); + rewind($stream); + + return json_decode((string) stream_get_contents($stream), flags: JSON_THROW_ON_ERROR); + } finally { + fclose($stream); + } + } + + private static function chooseRelease(array $releases): ?string + { + if ($releases === []) { + echo "暂无可升级的正式发布版本。\n"; + return null; + } + $tags = array_keys($releases); + foreach ($tags as $index => $tag) { + $release = $releases[$tag]; + $title = self::terminalText($release->name ?? ''); + $details = self::terminalText($release->body ?? ''); + printf("\n%d. %s%s\n", $index + 1, $tag, $title === '' || $title === $tag ? '' : ' · ' . str_replace("\n", ' ', $title)); + echo ' ' . str_replace("\n", "\n ", $details === '' ? '暂无发布说明。' : $details) . PHP_EOL; + } + + while (true) { + echo "\n请选择版本编号或输入标签,回车取消\n> "; + $selection = trim((string) fgets(STDIN)); + if ($selection === '' || strtolower($selection) === 'q') { + return null; + } + if (isset($releases[$selection])) { + return $selection; + } + if (ctype_digit($selection) && isset($tags[(int) $selection - 1])) { + return $tags[(int) $selection - 1]; + } + echo "请输入列表中的编号或版本。\n"; + } + } + + private static function terminalText(mixed $value): string + { + if (!is_string($value)) { + return ''; + } + + return trim(preg_replace('/[^\P{C}\n\t]/u', '', str_replace(["\r\n", "\r"], "\n", $value)) ?? ''); + } + + private function update(string $current, string $target, ?string $backup): void { $runtime = $this->root . '/runtime'; self::makeDirectory($runtime); @@ -69,20 +198,17 @@ final class LaySiteUpdater if (file_exists($pending) || is_link($pending)) { throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending))); } - $current = $this->version(); - $comparison = version_compare(substr($target, 1), $current); - if ($comparison === 0) { - printf("当前已安装 %s。\n", $target); - return; - } - if ($comparison < 0) { - throw new RuntimeException('更新目标必须高于已安装版本。'); + if ($this->version() !== $current) { + throw new RuntimeException('站点版本已经变更,请重新选择更新目标。'); } + $backup = $this->backupPath($backup, $current, $target); if (!mkdir($work, 0700)) { throw new RuntimeException('无法建立更新暂存目录。'); } $base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip'); + // Accept the VERSION file already identified above, including the old release numbering. + $base['VERSION']['hash'] = hash_file('sha256', $this->root . '/VERSION'); $release = $this->archive($target, substr($target, 1), $work . '/release.zip'); $plan = $this->plan($base, $release, $backup); $php = getenv('LAYSITE_PHP') ?: PHP_BINARY; @@ -101,6 +227,25 @@ final class LaySiteUpdater } } + private function backupPath(?string $path, string $current, string $target): string + { + if ($path === null) { + $directory = $this->root . '/storage/backups'; + self::makeDirectory($directory); + $path = sprintf('%s/laysite-v%s-%s-%s-%s.tar', $directory, $current, $target, gmdate('Ymd-His'), bin2hex(random_bytes(4))); + } elseif (!str_starts_with($path, '/')) { + $path = $this->root . '/' . $path; + } + $directory = realpath(dirname($path)); + if ($directory === false || !str_ends_with($path, '.tar') || file_exists($path) || is_link($path)) { + throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。'); + } + $path = $directory . '/' . basename($path); + printf("站点备份将写入 %s\n", $path); + + return $path; + } + private function version(): string { $version = trim((string) @file_get_contents($this->root . '/VERSION')); @@ -108,6 +253,16 @@ final class LaySiteUpdater throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。'); } + if ($version === '1.4.0') { + foreach (self::LEGACY_VERSIONS as $tag => $files) { + foreach ($files as $path => $hash) { + if (@hash_file('sha256', $this->root . '/' . $path) === $hash) { + return $tag; + } + } + } + } + return $version; } @@ -131,7 +286,7 @@ final class LaySiteUpdater } $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); if ($status !== 200) { - throw new RuntimeException("无法读取 LaySite 发布文件 $path(HTTP $status)。"); + throw new RuntimeException("无法读取 LaySite 发布文件 {$path}(HTTP $status)。"); } } @@ -178,8 +333,17 @@ final class LaySiteUpdater throw new RuntimeException('发布 ZIP 缺少 ' . $required); } } - if (trim((string) file_get_contents($files['VERSION']['uri'])) !== $version) { - throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。'); + $embedded = trim((string) file_get_contents($files['VERSION']['uri'])); + if ($embedded !== $version) { + if ($embedded !== '1.4.0' || !isset(self::LEGACY_VERSIONS[$version])) { + throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。'); + } + $canonical = $path . '.version'; + $contents = $version . "\n"; + if (file_put_contents($canonical, $contents) !== strlen($contents)) { + throw new RuntimeException('无法暂存发布版本号。'); + } + $files['VERSION'] = ['uri' => $canonical, 'hash' => hash('sha256', $contents), 'mode' => 0644]; } return $files; @@ -394,23 +558,17 @@ final class LaySiteUpdater } } +$target = $argv[1] ?? null; +$backup = $argv[2] ?? null; +if ($argc > 3 || ($target === 'check' && $backup !== null) + || ($target !== null && $target !== 'check' && !preg_match('/^v\d+\.\d+\.\d+$/D', $target))) { + fwrite(STDERR, "用法:php bin/update.php [check | vX.Y.Z [备份路径.tar]]\n"); + exit(2); +} + umask(0027); try { - $updater = new LaySiteUpdater(getcwd()); - $target = $argv[1] ?? 'check'; - if ($target === 'check' && $argc <= 2) { - $updater->check(); - } elseif ($argc === 3 && preg_match('/^v\d+\.\d+\.\d+$/D', $target)) { - $backup = str_starts_with($argv[2], '/') ? $argv[2] : getcwd() . '/' . $argv[2]; - $directory = realpath(dirname($backup)); - if ($directory === false || !str_ends_with($backup, '.tar') || file_exists($backup) || is_link($backup)) { - throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。'); - } - $updater->update($target, $directory . '/' . basename($backup)); - } else { - fwrite(STDERR, "Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar\n"); - exit(2); - } + (new LaySiteUpdater(getcwd()))->execute($target, $backup); } catch (Throwable $error) { fwrite(STDERR, $error->getMessage() . PHP_EOL); exit(1); diff --git a/bin/update.sh b/bin/update.sh deleted file mode 100755 index c70a1f8..0000000 --- a/bin/update.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh -set -eu - -cd "$(dirname "$0")/.." -exec "${LAYSITE_PHP:-php}" bin/update.php "$@" diff --git a/updatescript_map.json b/updatescript_map.json new file mode 100644 index 0000000..d05f2f3 --- /dev/null +++ b/updatescript_map.json @@ -0,0 +1,6 @@ +{ + "1.0.0": { + "from": "v1.1.0-latest", + "to": "v1.1.0-latest" + } +} -- 2.52.0