Files
laysite/app/Content/Repository.php

476 lines
23 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class Repository
{
public const DIRECTORIES = [
'catalog' => '目录', '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
{
$where = $publishedOnly ? " WHERE pages.status = 'published' AND pages.layout_id IS NULL" : '';
return $this->pdo->query('SELECT pages.slug, pages.name, pages.title, pages.updated_at, pages.status, pages.version, d.kind AS layout_kind
FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id' . $where . ' ORDER BY pages.rowid')->fetchAll();
}
public function createPage(string $slug, string $name, array $template = []): void
{
Database::write(static fn (PDO $pdo) => self::insertPage($pdo, $slug, $name, $template));
}
public static function insertPage(PDO $pdo, string $slug, string $name, array $template = [], ?int $layoutId = null): 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, status, updated_at)
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, $layoutId === null ? 'draft' : 'published', self::now(),
]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此页面地址已存在。');
}
foreach ($template['sections'] ?? [] as $section) {
self::insertSection($pdo, $slug, $section['key'], $section);
}
}
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 * FROM sections WHERE page_slug = ? ORDER BY position, key');
$query->execute([$slug]);
$page['sections'] = $query->fetchAll();
return $page;
}
public function layoutPage(int $id): ?array
{
$row = $this->one('SELECT slug FROM pages WHERE layout_id = ?', [$id]);
return $row ? $this->page($row['slug']) : null;
}
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);
$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'] = empty($page['layout_kind']) && $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 * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
}
public function publishedFeed(string $page, string $key): ?array
{
return $this->one("SELECT sections.title, sections.feed FROM sections
JOIN pages ON pages.slug = sections.page_slug
WHERE pages.slug = ? AND pages.status = 'published' AND pages.layout_id IS NULL AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
}
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
{
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void {
$query = $pdo->prepare('UPDATE pages SET 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), version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([
$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'], $data['status'], self::now(),
isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, $slug, $version,
]);
self::checkVersion($query->rowCount());
if ($replaceDraftSections) {
$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);
}
if (isset($data['layoutConfig'])) {
LayoutPage::saveSettings($pdo, $this->page($slug), $data['layoutConfig']);
}
});
}
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
{
$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 = ''): void
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
self::touchPage($pdo, $page, structureChanged: true);
});
}
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 = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $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, structureChanged: true);
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, structureChanged: true);
});
}
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, bool $structureChanged = false): void
{
$revision = $structureChanged ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
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 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('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
}
}
}