'目录', 'projects' => '项目', 'partners' => '合作伙伴', ]; public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'] + self::DIRECTORIES; private const ARTICLE_FIELDS = 'articles.*, (SELECT json_group_object(c.slug, c.name) FROM article_category_links l JOIN article_categories c ON c.slug = l.category_slug WHERE l.article_id = articles.id) AS categories'; private PDO $pdo; public function __construct() { $this->pdo = Database::connect(); } public function site(): array { return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR); } public function pages(bool $publishedOnly = false): array { if ($publishedOnly) { return $this->pdo->query("SELECT p.route_slug AS slug, json_extract(r.payload, '$.updated_at') AS updated_at, json_extract(r.payload, '$.page_type') AS page_type FROM page_publications p JOIN page_revisions r ON r.id = p.revision_id WHERE json_extract(r.payload, '$.layout_kind') IS NULL AND json_extract(r.payload, '$.page_type') IN ('page', 'home') ORDER BY p.rowid")->fetchAll(); } return $this->pdo->query("SELECT pages.slug, pages.name, pages.title, pages.updated_at, pages.status, pages.version, pages.page_type, pages.layout_id, d.kind AS layout_kind, CASE WHEN json_extract(r.payload, '$.layout_kind') IS NULL AND json_extract(r.payload, '$.page_type') IN ('page', 'home') THEN p.route_slug END AS public_slug FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id LEFT JOIN page_publications p ON p.draft_slug = pages.slug LEFT JOIN page_revisions r ON r.id = p.revision_id ORDER BY pages.rowid")->fetchAll(); } public function systemPublications(): array { return $this->pdo->query("SELECT p.route_slug AS slug, json_extract(r.payload, '$.name') AS name, json_extract(r.payload, '$.page_type') AS page_type FROM page_publications p JOIN page_revisions r ON r.id = p.revision_id WHERE json_extract(r.payload, '$.page_type') IN ('maintenance', 'not-found')")->fetchAll(); } public function homepage(): ?array { $row = $this->one("SELECT r.payload FROM page_publications p JOIN page_revisions r ON r.id = p.revision_id WHERE json_extract(r.payload, '$.layout_kind') IS NULL AND json_extract(r.payload, '$.page_type') = 'home' ORDER BY RANDOM() LIMIT 1", []); return $row ? $this->decodePublication($row) : null; } public function publishedPage(string $slug): ?array { $row = $this->one('SELECT r.payload FROM page_publications p JOIN page_revisions r ON r.id = p.revision_id WHERE p.route_slug = ?', [$slug]); return $row ? $this->decodePublication($row) : null; } private function decodePublication(array $row): array { return ReusableBlocks::resolve($this->pdo, json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR), false); } public function resolveDraft(array $page): array { return ReusableBlocks::resolve($this->pdo, $page, true); } public function createPage(string $slug, string $name, array $template = [], string $type = 'page'): void { Database::write(function (PDO $pdo) use ($slug, $name, $template, $type): void { if (($template['palette_id'] ?? null) === null && ($template['theme'] ?? '') !== '') { $suffix = ' · 模板配色'; $paletteName = mb_substr($name, 0, 100 - mb_strlen($suffix)) . $suffix; $template['palette_id'] = DesignLibrary::saveIn($pdo, 'palette', null, $paletteName, 'custom', PageTemplates::palette($template['theme']), 0, false); } $layout = in_array($type, ['header', 'footer'], true) ? LayoutPage::insertPreset($pdo, $type, $name) : null; $this->checkRouteAvailable($slug); self::insertPage($pdo, $slug, $name, $template, $layout, $layout === null ? $type : 'page'); $pdo->prepare("UPDATE pages SET status = 'draft' WHERE slug = ?")->execute([$slug]); PageRevisions::record($pdo, $this->page($slug), 'initial'); }); } public static function insertPage(PDO $pdo, string $slug, string $name, array $template = [], ?int $layoutId = null, string $type = 'page'): void { $query = $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks, theme, visibility, header_id, footer_id, palette_id, layout_id, page_type, status, updated_at, presentation, head_html) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $query->execute([ $slug, $name, $template['title'] ?? $name, $template['description'] ?? '', $template['heading'] ?? $name, $template['accent'] ?? '', $template['lead'] ?? '', $template['image'] ?? '', $template['alt'] ?? '', Database::json($template['actions'] ?? []), Database::json($template['quicklinks'] ?? []), $template['theme'] ?? '', Database::json($template['visibility'] ?? []), $template['header_id'] ?? null, $template['footer_id'] ?? null, $template['palette_id'] ?? null, $layoutId, $type, $layoutId === null ? 'draft' : 'published', self::now(), CanvasStyle::encode($template['presentation'] ?? []), $template['head_html'] ?? '', ]); if ($query->rowCount() !== 1) { throw new RuntimeException('此页面地址已存在。'); } foreach ($template['sections'] ?? [] as $section) { self::insertSection($pdo, $slug, $section['key'], $section); } } private function checkRouteAvailable(string $slug): void { if ($this->one('SELECT 1 FROM page_publications WHERE route_slug = ?', [$slug])) { throw new RuntimeException('此网址仍由另一页面的公开版本使用。'); } } public function page(string $slug): ?array { $page = $this->one('SELECT pages.*, d.kind AS layout_kind FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]); if (!$page) { return null; } foreach (['actions', 'quicklinks', 'alignments', 'visibility', 'presentation'] as $key) { $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR); } $query = $this->pdo->prepare('SELECT sections.*, r.main_id, r.mirror_id FROM sections LEFT JOIN section_reuse r ON r.page_slug = sections.page_slug AND r.section_key = sections.key WHERE sections.page_slug = ? ORDER BY position, key'); $query->execute([$slug]); $page['sections'] = $query->fetchAll(); return $page; } public function layoutPage(int $id, bool $preview = false): ?array { if ($preview) { $row = $this->one('SELECT slug FROM pages WHERE layout_id = ?', [$id]); return $row ? $this->resolveDraft($this->page($row['slug'])) : null; } $publication = $this->one("SELECT r.payload FROM page_publications p JOIN page_revisions r ON r.id = p.revision_id WHERE json_extract(r.payload, '$.layout_id') = CAST(? AS INTEGER)", [$id]); return $publication ? $this->decodePublication($publication) : null; } public function copyPage(string $slug, string $target, string $name, int $version): void { Database::write(function (PDO $pdo) use ($slug, $target, $name, $version): void { $page = $this->page($slug); self::checkVersion($page && $page['version'] === $version ? 1 : 0); $page = $this->resolveDraft($page); $layout = $page['layout_kind'] === null ? null : LayoutPage::insertPreset($pdo, $page['layout_kind'], $name); $page['sections'] = array_map(static function (array $section): array { unset($section['main_id'], $section['mirror_id'], $section['mirror_source']); return $section; }, $page['sections']); $this->checkRouteAvailable($target); self::insertPage($pdo, $target, $name, $page, $layout, $page['page_type']); $pdo->prepare("UPDATE pages SET status = 'draft', image_scale = ?, alignments = ? WHERE slug = ?") ->execute([$page['image_scale'], Database::json($page['alignments']), $target]); PageRevisions::record($pdo, $this->page($target), 'copied'); }); } public function restorePage(string $slug, int $revision, int $version): bool { return Database::write(function (PDO $pdo) use ($slug, $revision, $version): bool { $page = $this->page($slug); self::checkVersion($page && $page['version'] === $version ? 1 : 0); $saved = PageRevisions::find($pdo, $slug, $revision); if ($saved === null) { return false; } $fields = ['name', 'title', 'description', 'heading', 'accent', 'lead', 'image', 'alt', 'image_scale', 'head_html', 'theme', 'actions', 'quicklinks', 'alignments', 'visibility', 'presentation', 'header_id', 'footer_id', 'palette_id']; foreach (['actions', 'quicklinks', 'alignments', 'visibility', 'presentation'] as $field) { $saved[$field] = Database::json($saved[$field]); } foreach (['header', 'footer', 'palette'] as $kind) { $field = $kind . '_id'; if (isset($saved[$field]) && !DesignLibrary::find($saved[$field], $kind)) { $saved[$field] = null; } } $changes = implode(', ', array_map(static fn (string $field): string => $field . ' = ?', $fields)); $pdo->prepare('UPDATE pages SET ' . $changes . ', updated_at = ?, version = version + 1 WHERE slug = ?') ->execute([...array_map(static fn (string $field): mixed => $saved[$field], $fields), self::now(), $slug]); $currentVersions = array_column($page['sections'], 'version', 'key'); $pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]); $updateVersion = $pdo->prepare('UPDATE sections SET version = ? WHERE page_slug = ? AND key = ?'); foreach ($saved['sections'] as $section) { self::insertSection($pdo, $slug, $section['key'], $section); // Stale single-section forms must also conflict after a restore. $updateVersion->execute([max($version, (int) $section['version'], $currentVersions[$section['key']] ?? 0) + 1, $slug, $section['key']]); ReusableBlocks::restore($pdo, $slug, $section); } PageRevisions::record($pdo, $this->page($slug), 'restored'); return true; }); } public function editReusableBlock(string $slug, int $version, string $operation, string $value): string { return Database::write(function (PDO $pdo) use ($slug, $version, $operation, $value): string { $page = $this->page($slug); self::checkVersion($page && $page['version'] === $version ? 1 : 0); $key = $value; if ($operation === 'add') { $source = ReusableBlocks::source($pdo, $value, true); if (!$source || !$this->one('SELECT 1 FROM section_reuse WHERE main_id = ?', [$value])) { throw new RuntimeException('找不到此主区块。'); } $key = 'block-' . bin2hex(random_bytes(16)); $mirror = ReusableBlocks::materialize(['key' => $key], $source); self::insertSection($pdo, $slug, $key, $mirror); ReusableBlocks::set($pdo, $slug, $key, mirror: $value); } else { $section = array_column($page['sections'], null, 'key')[$key] ?? null; if (!$section || $section['style'] === 'hero-links') { throw new RuntimeException('找不到可复用的区块。'); } if ($operation === 'main' && !isset($section['mirror_id'])) { if (!isset($section['main_id'])) { ReusableBlocks::set($pdo, $slug, $key, main: bin2hex(random_bytes(16))); } } elseif ($operation === 'detach' && isset($section['mirror_id'])) { $source = ReusableBlocks::source($pdo, $section['mirror_id'], true); $copy = $source ? ReusableBlocks::materialize($section, $source) : $section; ReusableBlocks::set($pdo, $slug, $key); unset($copy['mirror_id']); self::updateSection($pdo, $slug, $key, $copy, $section['version']); } else { throw new RuntimeException('此区块无法执行该操作。'); } } self::touchPage($pdo, $slug); return $key; }); } public function withSectionFeeds(array $page): array { $categories = null; foreach ($page['sections'] as &$section) { if (!$section['feed']) { continue; } $categories ??= $this->categories(); $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); $feed['categories'] = array_values(array_intersect($feed['categories'], array_keys($categories))); $network = $feed['mode'] === 'network'; $catalog = $feed['mode'] === 'catalog'; $grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1); $archivePath = '/articles/feed/' . $page['slug'] . '/' . $section['key']; $section['archivePath'] = $feed['categories'] && empty($page['layout_kind']) && in_array($page['page_type'] ?? 'page', ['page', 'home'], true) && $page['status'] === 'published' ? $archivePath : null; $section['articleFeed'] = []; $section['networkFeed'] = $network; $section['catalogFeed'] = $catalog; $section['feedLimit'] = $feed['limit']; foreach ($grouped ? $feed['categories'] : [''] as $category) { $selected = $category === '' ? $feed['categories'] : [$category]; $section['articleFeed'][] = [ 'categories' => $selected, 'label' => $categories[$category] ?? '', 'articles' => $this->articles($selected, limit: $feed['limit'], directoryOrder: $network || $catalog), ]; } } unset($section); return $page; } public function section(string $page, string $key): ?array { return $this->one('SELECT sections.*, r.main_id, r.mirror_id FROM sections LEFT JOIN section_reuse r ON r.page_slug = sections.page_slug AND r.section_key = sections.key WHERE sections.page_slug = ? AND sections.key = ?', [$page, $key]); } public function publishedFeed(string $page, string $key): ?array { $published = $this->publishedPage($page); if (!$published || $published['layout_kind'] !== null || !in_array($published['page_type'], ['page', 'home'], true)) { return null; } $section = array_column($published['sections'], null, 'key')[$key] ?? null; return !empty($section['feed']) ? $section : null; } public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): array { return Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): array { $existing = $this->one('SELECT pages.version, pages.page_type, pages.layout_id, pages.header_id, pages.footer_id, d.kind AS layout_kind FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]); if ($existing !== null && $existing['version'] !== $version) { $this->checkRemovedPageLayouts($existing, $data['originalLayoutIds'] ?? []); } self::checkVersion($existing !== null && $existing['version'] === $version ? 1 : 0); $publication = PageRevisions::publicationInfo($pdo, $slug); $publicationAction = $data['publicationAction'] ?? ''; $status = ($publicationAction === 'published' || ($publication !== null && $publicationAction !== 'draft')) ? 'published' : 'draft'; $target = $data['slug'] ?? $slug; if ($target !== $slug && ($this->one('SELECT 1 FROM pages WHERE slug = ?', [$target]) || $this->one('SELECT 1 FROM page_publications WHERE route_slug = ? AND draft_slug <> ?', [$target, $slug]))) { throw new RuntimeException('此页面地址已存在。'); } $previousType = $existing['layout_kind'] ?? $existing['page_type']; $type = $data['type'] ?? $previousType; $layout = $existing['layout_id']; if ($type !== $previousType) { $layout = in_array($type, ['header', 'footer'], true) ? LayoutPage::insertPreset($pdo, $type, $data['name']) : null; } $head = $data['head_html'] ?? null; $query = $pdo->prepare('UPDATE pages SET slug = ?, page_type = ?, layout_id = ?, name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, presentation = COALESCE(?, presentation), ' . ($head === null ? '' : 'head_html = ?, ') . 'version = version + 1 WHERE slug = ? AND version = ?'); $query->execute([ $target, $layout === null ? $type : 'page', $layout, $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $status, self::now(), isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, ...($head === null ? [] : [$head]), $slug, $version, ]); self::checkVersion($query->rowCount()); if ($existing['layout_id'] !== null && $layout !== $existing['layout_id'] && $existing['layout_id'] !== ($publication['layout_id'] ?? null)) { LayoutPage::deletePreset($pdo, $existing['layout_kind'], $existing['layout_id']); } $slug = $target; if ($replaceDraftSections) { if ($this->one('SELECT 1 FROM section_reuse WHERE page_slug = ?', [$slug])) { throw new RuntimeException('此页包含复用区块,请按锚点编辑普通区块。'); } $pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]); } foreach ($sections as $section) { if (!empty($section['delete'])) { self::deleteSection($pdo, $slug, $section['key'], $section['version']); } elseif ($section['version'] === null) { self::insertSection($pdo, $slug, $section['key'], $section); } else { self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); } } if ($sectionOrder !== null) { self::writeSectionOrder($pdo, $slug, $sectionOrder); } $page = $this->page($slug); if ($type === $previousType && $layout !== null && isset($data['layoutConfig'])) { LayoutPage::stageSettings($pdo, $this->resolveDraft($page), $data['layoutConfig']); } if ($publicationAction === 'published') { if ($layout !== null) { LayoutPage::publishSettings($pdo, $this->resolveDraft($page)); } PageRevisions::publish($pdo, $page); } elseif ($publicationAction === 'draft') { PageRevisions::unpublish($pdo, $page); } else { PageRevisions::record($pdo, $page, 'saved'); } if ($publicationAction !== '' && isset($publication['layout_id']) && $publication['layout_id'] !== $layout) { LayoutPage::deletePreset($pdo, $publication['layout_kind'], $publication['layout_id']); } return $page; }); } private function checkRemovedPageLayouts(array $page, array $originalIds): void { foreach (['header' => '页头', 'footer' => '页脚'] as $kind => $label) { $id = $originalIds[$kind] ?? 0; if ($id > 0 && $page[$kind . '_id'] === null && !$this->one('SELECT 1 FROM design_presets WHERE id = ? AND kind = ?', [$id, $kind])) { throw new RuntimeException('此页面引用的' . $label . '已被移除。请保留修改,重新打开编辑器后再保存。'); } } } public function deletePage(string $slug, int $version): bool { return Database::write(function (PDO $pdo) use ($slug, $version): bool { $page = $this->one('SELECT pages.layout_id, d.kind AS layout_kind FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]); if ($page === null) { return false; } $publication = PageRevisions::publicationInfo($pdo, $slug); $delete = $pdo->prepare('DELETE FROM pages WHERE slug = ? AND version = ?'); $delete->execute([$slug, $version]); self::checkVersion($delete->rowCount()); if ($page['layout_id'] !== null) { LayoutPage::deletePreset($pdo, $page['layout_kind'], $page['layout_id']); } if (isset($publication['layout_id']) && $publication['layout_id'] !== $page['layout_id']) { LayoutPage::deletePreset($pdo, $publication['layout_kind'], $publication['layout_id']); } SiteDesign::replaceSystemPage($pdo, $publication['slug'] ?? $slug); return true; }); } public function saveSection(string $page, string $key, array $data, int $version): void { Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void { self::updateSection($pdo, $page, $key, $data, $version); self::touchPage($pdo, $page); }); } private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void { if (!empty($data['mirror_id']) || self::isMirror($pdo, $page, $key)) { throw new RuntimeException('镜像区块只读,修改请前往主区块或取消关联。'); } $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), presentation = COALESCE(?, presentation), version = version + 1 WHERE page_slug = ? AND key = ? AND version = ?'); $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $data['presentation'] ?? null, $page, $key, $version]); self::checkVersion($query->rowCount()); } public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = '', ?string $template = null): void { Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead, $template): void { $presentation = CanvasStyle::encode($template === null ? [] : ['template' => $template]); self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead', 'presentation')); self::touchPage($pdo, $page); }); } private static function insertSection(PDO $pdo, string $page, string $key, array $data): void { $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, presentation, position) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); $feed = $data['feed'] ?? null; if ($feed !== null) { $config = json_decode($feed, true, flags: JSON_THROW_ON_ERROR); $available = $pdo->query('SELECT slug FROM article_categories')->fetchAll(PDO::FETCH_COLUMN); $config['categories'] = array_values(array_intersect($config['categories'], $available)); $feed = Database::json($config); } $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $feed, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]); if ($query->rowCount() !== 1) { throw new RuntimeException('此区块锚点已被使用。'); } } private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void { $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); $query->execute([$page, $key, $version]); self::checkVersion($query->rowCount()); $query = $pdo->prepare('SELECT actions, quicklinks, presentation FROM pages WHERE slug = ?'); $query->execute([$page]); $row = $query->fetch(); $styles = json_decode($row['presentation'], true, flags: JSON_THROW_ON_ERROR); foreach (['actions' => 'action-', 'quicklinks' => 'nav-'] as $column => $prefix) { $links = json_decode($row[$column], true, flags: JSON_THROW_ON_ERROR); $kept = array_filter($links, static fn (array $link): bool => $link[0] !== '#' . $key); if (count($kept) !== count($links)) { $row[$column] = Database::json(array_values($kept)); $styles = CanvasStyle::remapSlots($styles, $prefix, array_keys($kept)); } } $pdo->prepare('UPDATE pages SET actions = ?, quicklinks = ?, presentation = ? WHERE slug = ?') ->execute([$row['actions'], $row['quicklinks'], CanvasStyle::encode($styles), $page]); } public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void { Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void { $current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?'); $current->execute([$page]); $revision = $current->fetchColumn(); self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0); if ($operation === 'delete') { self::deleteSection($pdo, $page, $key, $version); self::touchPage($pdo, $page); return; } $query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key"); $query->execute([$page]); $revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR); if (!array_key_exists($key, $revisions)) { throw new RuntimeException('找不到该区块。'); } self::checkVersion((int) $revisions[$key] === $version ? 1 : 0); $keys = array_map('strval', array_keys($revisions)); $index = array_search($key, $keys, true); $other = $index + ($operation === 'up' ? -1 : 1); if (!isset($keys[$other])) { return; } [$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]]; self::writeSectionOrder($pdo, $page, $keys); self::touchPage($pdo, $page); }); } private static function writeSectionOrder(PDO $pdo, string $slug, array $keys): void { $query = $pdo->prepare("SELECT key FROM sections WHERE page_slug = ? AND style <> 'hero-links'"); $query->execute([$slug]); $available = $query->fetchAll(PDO::FETCH_COLUMN); if (count($available) !== count($keys) || array_diff($available, $keys)) { throw new RuntimeException('区块顺序已变更,请重新打开编辑页。'); } $query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?'); foreach ($keys as $position => $key) { $query->execute([$position, $slug, $key]); } } private static function touchPage(PDO $pdo, string $slug): void { $pdo->prepare('UPDATE pages SET updated_at = ?, version = version + 1 WHERE slug = ?') ->execute([self::now(), $slug]); PageRevisions::record($pdo, (new self())->page($slug), 'saved'); } private static function isMirror(PDO $pdo, string $page, string $key): bool { $query = $pdo->prepare('SELECT 1 FROM section_reuse WHERE page_slug = ? AND section_key = ? AND mirror_id IS NOT NULL'); $query->execute([$page, $key]); return (bool) $query->fetchColumn(); } public function categories(): array { return $this->pdo->query('SELECT slug, name FROM article_categories ORDER BY rowid')->fetchAll(PDO::FETCH_KEY_PAIR); } public function createCategory(string $slug, string $name): void { $query = $this->pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)'); $query->execute([$slug, $name]); if ($query->rowCount() !== 1) { throw new RuntimeException('此分类网址标识已被使用。'); } } public function deleteCategory(string $slug): bool { return Database::write(function (PDO $pdo) use ($slug): bool { if ($this->one('SELECT 1 FROM article_categories WHERE slug = ?', [$slug]) === null) { return false; } $pdo->prepare('UPDATE articles SET version = version + 1 WHERE id IN (SELECT article_id FROM article_category_links WHERE category_slug = ?)')->execute([$slug]); $pdo->prepare('DELETE FROM article_category_links WHERE category_slug = ?')->execute([$slug]); $pdo->prepare('DELETE FROM article_categories WHERE slug = ?')->execute([$slug]); $sections = $pdo->prepare("SELECT page_slug, key, feed FROM sections WHERE EXISTS (SELECT 1 FROM json_each(sections.feed, '$.categories') WHERE value = ?)"); $sections->execute([$slug]); $update = $pdo->prepare('UPDATE sections SET feed = ?, version = version + 1 WHERE page_slug = ? AND key = ?'); $affected = []; foreach ($sections->fetchAll() as $section) { $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR); $feed['categories'] = array_values(array_diff($feed['categories'], [$slug])); $update->execute([Database::json($feed), $section['page_slug'], $section['key']]); $affected[$section['page_slug']] = true; } foreach (array_keys($affected) as $page) { self::touchPage($pdo, $page); } return true; }); } public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0, bool $directoryOrder = false): array { if ($category === []) { return []; } $sql = 'SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE 1 = 1'; $args = []; if ($public) { $sql .= " AND status = 'published'"; } if ($category !== null) { $args = (array) $category; $marks = implode(', ', array_fill(0, count($args), '?')); $sql .= " AND EXISTS (SELECT 1 FROM article_category_links WHERE article_id = articles.id AND category_slug IN ($marks))"; } if ($tag !== null) { $sql .= ' AND EXISTS (SELECT 1 FROM json_each(articles.tags) WHERE value = ?)'; $args[] = $tag; } $order = $public ? 'published_at' : 'updated_at'; $order = $directoryOrder ? "COALESCE(json_extract(card, '$.position'), 0), id" : "$order DESC, id DESC"; $query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' LIMIT ? OFFSET ?'); $query->execute([...$args, $limit, $offset]); return array_map(self::decodeArticle(...), $query->fetchAll()); } public function articleById(int $id): ?array { return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE id = ?', [$id])); } public function published(string $slug): ?array { return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug])); } public function articleRedirect(string $slug): ?array { return $this->one("SELECT articles.slug FROM article_redirects JOIN articles ON articles.id = article_redirects.article_id WHERE article_redirects.slug = ? AND articles.status = 'published'", [$slug]); } public function legacyArticle(string $path): ?array { return $this->one("SELECT slug FROM articles WHERE legacy_path = ? AND status = 'published'", [$path]); } public function saveArticle(?int $id, array $data, int $version): int { return Database::write(function (PDO $pdo) use ($id, $data, $version): int { $old = $id !== null ? $this->articleById($id) : null; if ($id !== null && (!$old || $old['version'] !== $version)) { self::checkVersion(0); } $existing = $this->one('SELECT id FROM articles WHERE slug = ?', [$data['slug']]); $redirect = $this->one('SELECT article_id FROM article_redirects WHERE slug = ?', [$data['slug']]); if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) { throw new RuntimeException('此网址标识已被使用。'); } $publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null); $values = [ $data['slug'], $data['title'], $data['summary'], $data['body'], $data['body_format'], Database::json($data['card']), Database::json($data['tags']), $data['status'], $publishedAt, self::now(), ]; if ($id === null) { $query = $pdo->prepare('INSERT INTO articles (id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at) VALUES (' . Database::NEXT_ARTICLE_ID . ', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); $query->execute($values); $id = (int) $pdo->lastInsertId(); } else { if ($old['slug'] !== $data['slug']) { $pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]); $pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]); } $query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, summary = ?, body = ?, body_format = ?, card = ?, tags = ?, status = ?, published_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?'); $query->execute([...$values, $id, $version]); self::checkVersion($query->rowCount()); $pdo->prepare('DELETE FROM article_category_links WHERE article_id = ?')->execute([$id]); } $link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)'); foreach ($data['categories'] as $category) { $link->execute([$id, $category]); } return $id; }); } public function deleteArticle(int $id, int $version): void { Database::write(function (PDO $pdo) use ($id, $version): void { // Keep the original seed slug even if the article has been renamed. $deletions = $pdo->prepare('INSERT INTO article_deletions (slug, article_id) SELECT slug, id FROM articles WHERE id = :id UNION ALL SELECT slug, article_id FROM article_redirects WHERE article_id = :id ON CONFLICT (slug) DO UPDATE SET article_id = excluded.article_id'); $deletions->execute(['id' => $id]); $delete = $pdo->prepare('DELETE FROM articles WHERE id = ? AND version = ?'); $delete->execute([$id, $version]); self::checkVersion($delete->rowCount()); }); } public function sitemapArticles(): iterable { $query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published' AND (trim(body) <> '' OR trim(summary) <> '' OR json_extract(card, '$.image') <> '' OR json_extract(card, '$.url') <> '') ORDER BY slug"); yield from $query; } public function administrator(string $email): ?array { return $this->one('SELECT id, email, password_hash FROM users WHERE email = ?', [$email]); } public function administratorById(int $id): ?array { return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]); } public function changePassword(array $user, string $newHash): bool { $query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?'); $query->execute([$newHash, $user['id'], $user['password_hash']]); return $query->rowCount() === 1; } public function recordFailedLogin(string $address): int { $now = time(); $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]); if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) { return $current['expires_at'] - $now; } return Database::write(function (PDO $pdo) use ($address, $now): int { $pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]); $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]); if ($current && $current['attempts'] >= 12) { return $current['expires_at'] - $now; } $query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?) ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1'); $query->execute([$address, $now + 900]); return 0; }); } private function one(string $sql, array $args): ?array { $query = $this->pdo->prepare($sql); $query->execute($args); return $query->fetch() ?: null; } private static function decodeArticle(?array $article): ?array { if ($article !== null) { foreach (['tags', 'categories', 'card'] as $field) { $article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR); } } return $article; } private static function now(): string { return date('Y-m-d H:i:s'); } private static function checkVersion(int $count): void { if ($count !== 1) { throw new RuntimeException('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。'); } } }