Files
laysense.cn/app/Content/SiteBackup.php
T

290 lines
13 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use PharData;
use RuntimeException;
use Throwable;
final class SiteBackup
{
private const FORMAT = 'laysite-site';
private const VERSION = 2;
private const TABLES = [
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
'article_category_links', 'article_redirects', 'article_deletions', 'media',
];
private const MANIFEST_LIMIT = 32 * 1024 * 1024;
public static function export(string $path): void
{
if (!str_ends_with($path, '.tar') || file_exists($path)) {
throw new RuntimeException('请选择尚不存在的 .tar 备份路径。');
}
try {
Database::write(function (PDO $pdo) use ($path): void {
$tables = [];
foreach (self::TABLES as $table) {
$tables[$table] = $pdo->query('SELECT * FROM ' . $table)->fetchAll();
}
$files = [];
$archive = new PharData($path);
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name']);
$file = Media::directory() . '/' . $name;
if (!is_file($file) || is_link($file) || filesize($file) !== (int) $asset['size']) {
throw new RuntimeException('资源文件缺失或大小已变更:' . $name);
}
$files[$name] = hash_file('sha256', $file);
$archive->addFile($file, 'media/' . $name);
}
$manifest = Database::json(['format' => self::FORMAT, 'version' => self::VERSION, 'exported_at' => gmdate('c'), 'tables' => $tables, 'files' => $files]);
if (strlen($manifest) > self::MANIFEST_LIMIT) {
throw new RuntimeException('站点内容超过当前备份格式的大小上限。');
}
$archive->addFromString('site.json', $manifest);
});
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function import(string $path): void
{
$archive = new PharData($path);
if (!isset($archive['site.json']) || $archive['site.json']->isLink() || $archive['site.json']->getSize() > self::MANIFEST_LIMIT) {
throw new RuntimeException('备份清单缺失或过大。');
}
$manifest = json_decode($archive['site.json']->getContent(), true, 48, JSON_THROW_ON_ERROR);
$tables = self::prepare($manifest);
$files = $manifest['files'] ?? [];
if (!is_array($files) || count($files) !== count($tables['media'])) {
throw new RuntimeException('备份资源清单不完整。');
}
$directory = Media::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('不能写入资源目录。');
}
$stage = $directory . '/.restore-' . bin2hex(random_bytes(12));
if (!mkdir($stage, 0700)) {
throw new RuntimeException('不能创建临时资源目录。');
}
$staged = [];
$installed = [];
try {
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name'] ?? null);
$size = $asset['size'] ?? 0;
if (!is_int($size) || $size < 1 || $size > Media::MAX_BYTES || isset($staged[$name])
|| !is_string($files[$name] ?? null) || !isset($archive['media/' . $name])
|| $archive['media/' . $name]->isLink() || !$archive['media/' . $name]->isFile() || $archive['media/' . $name]->getSize() !== $size) {
throw new RuntimeException('备份资源不完整:' . $name);
}
$staged[$name] = $stage . '/' . $name;
$source = fopen('phar://' . $path . '/media/' . $name, 'rb');
if ($source === false) {
throw new RuntimeException('不能读取备份资源。');
}
try {
$destination = fopen($staged[$name], 'xb');
if ($destination === false) {
throw new RuntimeException('不能暂存备份资源。');
}
try {
$written = stream_copy_to_stream($source, $destination, $size + 1);
} finally {
fclose($destination);
}
} finally {
fclose($source);
}
if ($written !== $size || !hash_equals($files[$name], hash_file('sha256', $staged[$name]))) {
throw new RuntimeException('备份资源校验失败:' . $name);
}
Media::validateBackup($staged[$name], $name, $asset['mime'] ?? '', $size);
}
Database::write(function (PDO $pdo) use ($tables, $staged, $directory, &$installed): void {
self::replaceTables($pdo, $tables);
foreach ($staged as $name => $source) {
$target = $directory . '/' . $name;
if (is_file($target) && !is_link($target) && hash_file('sha256', $target) === hash_file('sha256', $source)) {
continue;
}
if (file_exists($target) || is_link($target) || !link($source, $target)) {
throw new RuntimeException('资源名称冲突:' . $name);
}
$installed[] = $target;
}
});
} catch (Throwable $error) {
foreach ($installed as $file) {
unlink($file);
}
throw $error;
} finally {
foreach ($staged as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($stage);
}
}
private static function prepare(mixed $manifest): array
{
if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT
|| !in_array($manifest['version'] ?? null, [1, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
}
$tables = $manifest['tables'];
if ($manifest['version'] === 1) {
$tables += ['design_presets' => [], 'article_deletions' => []];
}
foreach (self::TABLES as $table) {
if (!is_array($tables[$table] ?? null) || !array_is_list($tables[$table])) {
throw new RuntimeException('备份数据表不完整。');
}
foreach ($tables[$table] as $row) {
if (!is_array($row) || array_is_list($row)) {
throw new RuntimeException('备份数据行格式无效。');
}
}
}
if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
throw new RuntimeException('备份缺少站点身份或首页。');
}
$designs = [];
foreach ($tables['design_presets'] as &$row) {
$payload = self::decode($row['payload'] ?? '');
$row['payload'] = Database::json(DesignLibrary::normalize($row['kind'] ?? '', $row['preset'] ?? '', $payload));
$designs[$row['id']] = $row['kind'];
}
unset($row);
$settings = self::decode($tables['site_settings'][0]['payload'] ?? '');
if (!is_string($settings['name'] ?? null) || trim($settings['name']) === '' || mb_strlen($settings['name']) > 100) {
throw new RuntimeException('备份的站点名称无效。');
}
$site = ['name' => $settings['name'], 'cdn' => ['origin' => Assets::cdn($settings['cdn']['origin'] ?? '')], 'revisions' => ['general' => time()]];
foreach (['header', 'footer'] as $kind) {
if (isset($settings[$kind . '_id'])) {
$site[$kind . '_id'] = self::selection($designs, $kind, $settings[$kind . '_id']);
}
}
$tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
foreach ($tables['pages'] as &$row) {
PageDraft::slug($row['slug'] ?? null, ['admin', 'assets', 'account', 'mcp', 'palette', 'favicon']);
self::validateAssetUrl($row['image'] ?? '', true);
$row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
$row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = '';
}
foreach (['header', 'footer', 'palette'] as $kind) {
$row[$kind . '_id'] = self::selection($designs, $kind, $row[$kind . '_id'] ?? null);
}
}
unset($row);
foreach ($tables['sections'] as &$row) {
PageDraft::slug($row['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links'], true)) {
throw new RuntimeException('备份包含未知区块样式。');
}
$row['body'] = Html::sanitize($row['body'] ?? '');
if (isset($row['feed'])) {
$feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|| !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
|| array_diff($feed['categories'], array_column($tables['article_categories'], 'slug'))
|| !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
throw new RuntimeException('备份的动态区块配置无效。');
}
}
}
unset($row);
foreach ($tables['articles'] as &$row) {
if (($row['body_format'] ?? '') === 'html') {
$row['body'] = Html::sanitize($row['body'] ?? '');
}
$card = self::decode($row['card'] ?? '{}');
foreach (['url', 'extra_url', 'image'] as $field) {
self::validateAssetUrl($card[$field] ?? '', $field === 'image');
}
$row['tags'] = Database::json(self::decode($row['tags'] ?? '[]'));
}
unset($row);
return $tables;
}
private static function replaceTables(PDO $pdo, array $tables): void
{
$revisions = [];
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
$revisions[$table] = in_array('version', $columns, true) ? max(1, (int) $pdo->query('SELECT MAX(version) FROM ' . $table)->fetchColumn() + 1) : 0;
}
foreach (array_reverse(self::TABLES) as $table) {
$pdo->exec('DELETE FROM ' . $table);
}
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
foreach ($tables[$table] as $row) {
$row = array_intersect_key($row, array_flip($columns));
if ($revisions[$table]) {
$row['version'] = $revisions[$table];
}
if (!$row) {
throw new RuntimeException('备份缺少必要的数据列。');
}
$keys = array_keys($row);
$query = $pdo->prepare('INSERT INTO ' . $table . ' ("' . implode('","', $keys) . '") VALUES (' . implode(',', array_fill(0, count($row), '?')) . ')');
$query->execute(array_values($row));
}
}
}
private static function selection(array $designs, string $kind, mixed $id): ?int
{
if ($id === null) {
return null;
}
if (!is_int($id) || ($designs[$id] ?? '') !== $kind) {
throw new RuntimeException('备份引用了缺失的设计方案。');
}
return $id;
}
private static function decode(mixed $value): array
{
$data = is_string($value) ? json_decode($value, true, 32, JSON_THROW_ON_ERROR) : null;
if (!is_array($data)) {
throw new RuntimeException('备份中的配置格式无效。');
}
return $data;
}
private static function validateAssetUrl(mixed $url, bool $media): void
{
if (!is_string($url) || ($url !== '' && !Html::url($url, $media))) {
throw new RuntimeException('备份含有无效的资源地址。');
}
}
private static function mediaName(mixed $name): string
{
if (!is_string($name) || !preg_match('/^[a-f0-9]{32}\.[a-z0-9]+$/D', $name)) {
throw new RuntimeException('备份含有无效的资源名称。');
}
return $name;
}
}