Pdo\Sqlite::OPEN_READONLY] : [PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY]) : []; $pdo = new PDO('sqlite:' . $path, options: $options + [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]); $pdo->exec('PRAGMA busy_timeout = 5000'); return $pdo; } function alignSiteData(PDO $db): void { $categories = ['services' => 'catalog', 'supported-projects' => 'projects']; $db->exec('PRAGMA foreign_keys = ON'); $db->beginTransaction(); foreach ($categories as $legacy => $standard) { $db->prepare('INSERT INTO article_categories (slug, name) SELECT ?, name FROM article_categories WHERE slug = ? ON CONFLICT(slug) DO UPDATE SET name = excluded.name')->execute([$standard, $legacy]); $db->prepare('INSERT OR IGNORE INTO article_category_links (article_id, category_slug) SELECT article_id, ? FROM article_category_links WHERE category_slug = ?')->execute([$standard, $legacy]); $db->prepare('DELETE FROM article_category_links WHERE category_slug = ?')->execute([$legacy]); $db->prepare('DELETE FROM article_categories WHERE slug = ?')->execute([$legacy]); } $replace = $db->prepare('UPDATE sections SET feed = ? WHERE page_slug = ? AND key = ?'); foreach ($db->query("SELECT page_slug, key, feed FROM sections WHERE feed IS NOT NULL AND feed <> ''")->fetchAll() as $row) { $feed = json_decode($row['feed'], true, flags: JSON_THROW_ON_ERROR); $mapped = array_values(array_unique(array_map(static fn (string $slug): string => $categories[$slug] ?? $slug, $feed['categories']))); if ($mapped !== $feed['categories']) { $feed['categories'] = $mapped; $replace->execute([json_encode($feed, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), $row['page_slug'], $row['key']]); } } $db->exec("UPDATE sections SET style = 'plain' WHERE style IN ('about', 'projects', 'demos')"); $db->exec("UPDATE sections SET body = replace(replace(body, '
', '
'), '
', '') WHERE body LIKE '%
%'"); if ($db->query('PRAGMA foreign_key_check')->fetch() !== false) { throw new RuntimeException('迁移数据包含无效的关联记录。'); } $db->commit(); } function removeStage(string $directory): void { $entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($entries as $entry) { if ($entry->isDir() && !$entry->isLink()) { rmdir($entry->getPathname()); } else { unlink($entry->getPathname()); } } rmdir($directory); } umask(0077); if ($argc !== 3) { fwrite(STDERR, "用法:php site/migrate.php 旧站根目录 新站数据目录\n"); exit(2); } $stage = null; $exitCode = 0; try { $source = realpath($argv[1]); $parent = realpath(dirname($argv[2])); $target = $parent . '/' . basename($argv[2]); if ($source === false || $parent === false || !is_dir($parent) || file_exists($target) || is_link($target)) { throw new RuntimeException('请选择现有的旧站根目录和一个尚未使用的新数据目录。'); } $env = Dotenv::createArrayBacked($source)->safeLoad(); $original = sourcePath($source, $env, 'LAYSITE_DB', 'storage/laysite.sqlite'); $uploads = sourcePath($source, $env, 'LAYSITE_MEDIA_DIR', 'storage/media'); if (!is_file($original)) { throw new RuntimeException('旧站目录缺少 SQLite 数据库。'); } $stage = $parent . '/.laysense-migration-' . bin2hex(random_bytes(8)); if (!mkdir($stage, 0700)) { throw new RuntimeException('无法创建迁移目录。'); } $oldDb = openSqlite($original, true); if ($oldDb->query('PRAGMA quick_check')->fetchColumn() !== 'ok') { throw new RuntimeException('旧站 SQLite 未通过完整性检查。'); } // SQLite reads the live WAL when taking the consistent snapshot. $oldDb->exec('VACUUM INTO ' . $oldDb->quote($stage . '/laysite.sqlite')); $oldDb = null; if (is_file($original . '.key')) { copyFile($original . '.key', $stage . '/laysite.sqlite.key'); } $db = openSqlite($stage . '/laysite.sqlite'); mkdir($stage . '/media', 0700); if (is_dir($uploads)) { foreach (new FilesystemIterator($uploads, FilesystemIterator::SKIP_DOTS) as $entry) { if ($entry->isFile()) { copyFile($entry->getPathname(), $stage . '/media/' . $entry->getFilename()); } } } foreach ($db->query('SELECT name, size FROM media') as $media) { if (!preg_match('/^[a-f0-9]{32}\.[a-z0-9]+$/D', $media['name']) || !is_file($stage . '/media/' . $media['name']) || filesize($stage . '/media/' . $media['name']) !== (int) $media['size']) { throw new RuntimeException('旧站媒体清单中的文件缺失或大小不一致。'); } } alignSiteData($db); $db = null; $assets = json_decode(file_get_contents(dirname(__DIR__) . '/plugin/laysense/assets.json'), true, flags: JSON_THROW_ON_ERROR); foreach ($assets as $asset) { copyFile($source . '/public/' . $asset, $stage . '/' . $asset); } if (is_file($source . '/backup.tar')) { copyFile($source . '/backup.tar', $stage . '/backups/legacy-backup.tar'); } $dotenv = is_file($source . '/.env') ? file_get_contents($source . '/.env') : "LAYSITE_SITE_URL=https://laysense.cn\n"; $dotenv = preg_replace('/^\h*(?:export\h+)?(?:LAYSITE_DB|LAYSITE_MEDIA_DIR|LAYSENSE_SITE_DIR)\h*=.*(?:\R|$)/m', '', $dotenv); foreach (['LAYSITE_DB' => $target . '/laysite.sqlite', 'LAYSITE_MEDIA_DIR' => $target . '/media', 'LAYSENSE_SITE_DIR' => $target] as $key => $value) { if (preg_match('/[\r\n\x00]/', $value)) { throw new RuntimeException('数据目录包含无效字符。'); } $dotenv = rtrim($dotenv) . "\n" . $key . '="' . addcslashes($value, "\\\"$") . "\"\n"; } if (file_put_contents($stage . '/.env', $dotenv) === false || file_exists($target) || !rename($stage, $target)) { throw new RuntimeException('无法写入站点数据目录。'); } $stage = null; printf("站点数据已迁至 %s\n", $target); } catch (Throwable $error) { fwrite(STDERR, $error->getMessage() . PHP_EOL); $exitCode = 1; } finally { if ($stage !== null && is_dir($stage)) { removeStage($stage); } } exit($exitCode);