forked from laysense/laysite
Launch LaySite visual editor and MCP workspace
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
<?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 status = 'published'" : '';
|
||||
|
||||
return $this->pdo->query('SELECT slug, name, title, updated_at, status, version FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
|
||||
}
|
||||
|
||||
public function createPage(string $slug, string $name, array $template = []): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($slug, $name, $template): 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, status, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?)");
|
||||
$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, 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 * FROM pages WHERE slug = ?', [$slug]);
|
||||
if (!$page) {
|
||||
return null;
|
||||
}
|
||||
foreach (['actions', 'quicklinks', 'alignments', 'visibility'] 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 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 sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
|
||||
}
|
||||
|
||||
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): 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 = ?, 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(), $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']);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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), 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, $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, 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'] ?? '{}', $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());
|
||||
$pdo->prepare("UPDATE pages SET
|
||||
quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor),
|
||||
actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor)
|
||||
WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $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]];
|
||||
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
|
||||
foreach ($keys as $position => $section) {
|
||||
$query->execute([$position, $page, $section]);
|
||||
}
|
||||
self::touchPage($pdo, $page, structureChanged: true);
|
||||
});
|
||||
}
|
||||
|
||||
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('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user