Files
laysense.cn/site/migrate-content.php

205 lines
10 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
use App\Content\Database;
use App\Content\Html;
use App\Content\Media;
use App\Content\PageHead;
use App\Content\SiteIcon;
use App\Content\View;
use Webman\Http\UploadFile;
function findAsset(array $roots, string $asset): string
{
foreach ($roots as $root) {
$source = $root . '/' . $asset;
if (is_file($source) && is_readable($source)) {
return $source;
}
}
throw new RuntimeException('找不到旧站素材 ' . $asset);
}
function readText(string $path): string
{
$contents = file_get_contents($path);
if ($contents === false) {
throw new RuntimeException('读取文件失败 ' . basename($path));
}
return $contents;
}
function normalizeLegacySvg(string $path): string
{
$contents = str_replace('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">', '', readText($path));
$document = new DOMDocument();
if (!$document->loadXML($contents, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)
|| $document->doctype || !$document->documentElement) {
throw new RuntimeException('无法读取旧站 SVG ' . basename($path));
}
foreach ($document->getElementsByTagName('*') as $node) {
foreach (['id', 'version', 'class', 'enable-background', 'xml:space', 'p-id', 't'] as $name) {
$node->removeAttribute($name);
}
if ($node->hasAttribute('style') && preg_match('/^fill:\s*(#[a-f0-9]{3,8});?$/iD', $node->getAttribute('style'), $fill)) {
$node->setAttribute('fill', $fill[1]);
$node->removeAttribute('style');
}
}
return $document->saveXML($document->documentElement);
}
function importMedia(string $source, string $label): string
{
try {
Media::upload(new UploadFile($source, $label, '', UPLOAD_ERR_OK), $label);
} catch (RuntimeException $error) {
throw new RuntimeException('无法导入媒体 ' . $label . ':' . $error->getMessage(), previous: $error);
}
$name = Database::connect()->query('SELECT name FROM media WHERE rowid = last_insert_rowid()')->fetchColumn();
if (!is_string($name)) {
throw new RuntimeException('找不到导入后的媒体 ' . $label);
}
return '/assets/uploads/' . $name;
}
function importText(string $stage, string $label, string $contents): string
{
$temporary = $stage . '/asset-import';
if (file_put_contents($temporary, $contents) !== strlen($contents)) {
throw new RuntimeException('无法暂存媒体 ' . $label);
}
try {
return importMedia($temporary, $label);
} finally {
unlink($temporary);
}
}
function rewriteReferences(PDO $db, array $assets, array $links, array $origins): void
{
$replacements = $assets + $links;
$origins = array_map(static fn (string $origin): string => preg_quote(rtrim($origin, '/'), '~'), array_filter($origins));
$alternatives = array_keys($replacements);
usort($alternatives, static fn (string $a, string $b): int => strlen($b) <=> strlen($a));
$alternatives = array_map(static fn (string $path): string => preg_quote($path, '~'), $alternatives);
$pattern = '~(?<![a-z0-9_.:/%-])(?:' . implode('|', $origins) . ')?(' . implode('|', $alternatives) . ')(?=$|[\s"\'<>?#(),\[\]])~i';
$columnsByTable = [
'site_settings' => ['payload'],
'pages' => ['image', 'heading', 'description', 'lead', 'actions', 'quicklinks', 'presentation', 'head_html'],
'sections' => ['body', 'lead', 'presentation'],
'articles' => ['body', 'summary', 'card'],
'design_presets' => ['payload'],
];
foreach ($columnsByTable as $table => $columns) {
$assignments = implode(', ', array_map(static fn (string $key): string => $key . ' = ?', $columns));
$update = $db->prepare("UPDATE $table SET $assignments WHERE rowid = ?");
foreach ($db->query('SELECT rowid AS record_id, ' . implode(', ', $columns) . ' FROM ' . $table)->fetchAll() as $row) {
$id = array_shift($row);
$values = array_values($row);
$newValues = array_map(static fn (string $value): string => preg_replace_callback(
$pattern, static fn (array $match): string => $replacements[$match[1]] ?? $match[0], $value
) ?? throw new RuntimeException('无法迁移旧链接。'), $values);
if ($values !== $newValues) {
$update->execute([...$newValues, $id]);
}
}
}
}
function migrateAssetsAndDesign(array $roots, string $stage): void
{
$inventory = json_decode(readText(__DIR__ . '/legacy-assets.json'), true, flags: JSON_THROW_ON_ERROR);
$assets = [];
$iconFile = findAsset($roots, 'assets/favicon.png');
$legacyCss = readText(findAsset($roots, 'assets/laysense.css'));
foreach ($inventory as $asset) {
if ($asset === 'assets/laysense.css') {
continue;
}
$file = findAsset($roots, $asset);
$label = basename($file);
$assets['/' . $asset] = str_ends_with($asset, '.svg')
? importText($stage, $label, normalizeLegacySvg($file)) : importMedia($file, $label);
}
$brandCss = strtr($legacyCss, $assets + [
'.hero-service-art' => '.hero-visual.app-frame',
'.copyright-service' => '#main-content:has(> :is(.hero-sc, .hero-shnu-sc))',
]) . "\n" . readText(__DIR__ . '/footer.css') . "\n" . readText(__DIR__ . '/brand.css');
$style = importText($stage, 'laysense.css', $brandCss);
$homeImage = $assets['/assets/original/home-hero.webp'];
$homeMotion = "(() => {\n" . strtr(readText(__DIR__ . '/home.js'), [
'HOME_IMAGE_PATH' => json_encode($homeImage, JSON_THROW_ON_ERROR),
'HOME_MOTION_SVG' => json_encode(readText(__DIR__ . '/home-motion.svg'), JSON_THROW_ON_ERROR),
]) . "\n})();\n";
$script = importText($stage, 'laysense-home.js', $homeMotion);
$assets['/assets/laysense.css'] = $style;
$assets['/assets/laysense-site-compat.css'] = $style;
Database::write(static function (PDO $db) use ($assets, $iconFile, $style, $script, $homeImage): void {
$site = json_decode($db->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
$links = [
'/main' => '/articles', '/main/category/1.html' => '/articles/category/product',
'/main/category/2.html' => '/articles/category/news', '/main/category/3.html' => '/articles/category/announcement',
'/main/category/5.html' => '/#projects', '/main/category/6.html' => '/#partners',
'/articles/category/services' => '/articles/category/catalog',
'/articles/category/supported-projects' => '/articles/category/projects',
'/#supported-projects' => '/#projects', '/home#supported-projects' => '/home#projects',
'/network#supported-projects' => '/network#network-group-projects', '/network#partners' => '/network#network-group-partners',
];
foreach ($db->query("SELECT legacy_path, slug FROM articles WHERE status = 'published' AND legacy_path LIKE '/news/id/%'") as $article) {
$links[$article['legacy_path']] = '/articles/' . $article['slug'];
}
rewriteReferences($db, $assets, $links, ['https://laysense.cn', 'http://laysense.cn', $site['cdn']['origin'] ?? '']);
$site = json_decode($db->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if (empty($site['favicon'])) {
$site['favicon'] = SiteIcon::normalize(base64_encode(readText($iconFile)));
}
$head = $site['head_html'] ?? '';
$head .= "\n<link rel=\"stylesheet\" href=\"" . View::escape($style) . '">';
if (!str_contains($head, 'og:image')) {
$image = rtrim($site['cdn']['origin'] ?? 'https://laysense.cn', '/') ?: 'https://laysense.cn';
$head .= "\n<meta property=\"og:image\" content=\"" . View::escape($image . $homeImage) . '">'
. "\n<meta property=\"og:image:alt\" content=\"来笙 Laysense\">";
}
$site['head_html'] = PageHead::normalize($head);
$db->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
$head = $db->query("SELECT head_html FROM pages WHERE slug = 'home'")->fetchColumn();
if ($head !== false) {
$head = PageHead::normalize($head . "\n<script src=\"" . View::escape($script) . "\" defer></script>");
$db->prepare("UPDATE pages SET head_html = ? WHERE slug = 'home'")->execute([$head]);
}
migratePhotoCredits($db, $assets);
if ($db->query('PRAGMA foreign_key_check')->fetch() !== false) {
throw new RuntimeException('迁移数据包含无效的关联记录。');
}
});
}
function migratePhotoCredits(PDO $db, array $assets): void
{
$credits = [
'studio-letterpress.webp' => ['Adam Lusch', 'CC BY-SA 2.0', 'https://commons.wikimedia.org/wiki/File:Wood_Type_close-up.jpg', 'https://creativecommons.org/licenses/by-sa/2.0/'],
'dusk-dunes.webp' => ['Bob Wick / BLM Utah', '公有领域', 'https://commons.wikimedia.org/wiki/File:Utah_Dunes_Landscape_-_West_Desert_District.jpg', ''],
];
$pages = $db->prepare('SELECT slug, visibility FROM pages WHERE image = ? AND layout_id IS NULL');
$insert = $db->prepare("INSERT OR IGNORE INTO sections (page_slug, key, title, lead, body, style, position)
VALUES (?, 'photo-credit', '摄影署名', '', ?, 'layout', (SELECT COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?))");
foreach ($credits as $image => [$author, $license, $source, $terms]) {
$pages->execute([$assets['/assets/page-templates/' . $image]]);
$authorLink = '<a href="' . View::escape($source) . '">' . View::escape($author) . '</a>';
$termsLink = $terms === '' ? View::escape($license) : '<a href="' . View::escape($terms) . '">' . View::escape($license) . '</a>';
$body = Html::sanitize('<p class="wrap page-photo-credit">摄影 ' . $authorLink . ' · ' . $termsLink . '</p>');
foreach ($pages->fetchAll() as $page) {
if (json_decode($page['visibility'], true, flags: JSON_THROW_ON_ERROR)['hero'] ?? true) {
$insert->execute([$page['slug'], $body, $page['slug']]);
}
}
}
}