forked from laysense/laysense.cn
Add canvas element tools and categorized article editing
This commit is contained in:
@@ -6,10 +6,13 @@ namespace App\Content;
|
||||
|
||||
final class BlockTemplates
|
||||
{
|
||||
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
|
||||
|
||||
public const GROUPS = [
|
||||
'content' => ['标题与正文', [
|
||||
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
|
||||
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
|
||||
'articles' => ['分类文章', ''],
|
||||
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
|
||||
]],
|
||||
'cover' => ['封面与横幅', [
|
||||
|
||||
+29
-36
@@ -39,27 +39,24 @@ final class Database
|
||||
$pdo->exec('PRAGMA journal_mode = WAL');
|
||||
|
||||
self::write(function (PDO $pdo) use ($root, $seed): void {
|
||||
$articleColumns = array_column($pdo->query('PRAGMA table_info(articles)')->fetchAll(), 'name');
|
||||
if (in_array('category', $articleColumns, true)) {
|
||||
throw new RuntimeException('请将 LAYSENSE_DB 指向一个新的 SQLite 文件,再运行安装命令。');
|
||||
}
|
||||
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
|
||||
$pageColumns = array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name');
|
||||
if (!in_array('status', $pageColumns, true)) {
|
||||
$pdo->exec("ALTER TABLE pages ADD COLUMN status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published'))");
|
||||
}
|
||||
if (!in_array('image_scale', $pageColumns, true)) {
|
||||
$pdo->exec('ALTER TABLE pages ADD COLUMN image_scale INTEGER NOT NULL DEFAULT 0');
|
||||
}
|
||||
$site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)');
|
||||
$site->execute([self::json($seed['site'])]);
|
||||
|
||||
$pageQuery = $pdo->prepare('INSERT OR IGNORE INTO pages
|
||||
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks, partners)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
$sectionQuery = $pdo->prepare('INSERT OR IGNORE INTO sections
|
||||
(page_slug, key, title, lead, style, body, position) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
||||
(page_slug, key, title, lead, style, body, feed, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
foreach ($seed['pages'] as $page) {
|
||||
$pageQuery->execute([
|
||||
$page['slug'], $page['name'], $page['title'], $page['description'], $page['heading'],
|
||||
$page['accent'], $page['lead'], $page['image'], $page['alt'],
|
||||
self::json($page['actions']), self::json($page['quicklinks']), self::json($page['partners'] ?? []),
|
||||
self::json($page['actions']), self::json($page['quicklinks']),
|
||||
]);
|
||||
if ($pageQuery->rowCount() !== 1) {
|
||||
continue;
|
||||
@@ -67,38 +64,34 @@ final class Database
|
||||
foreach ($page['sections'] as $index => $section) {
|
||||
$sectionQuery->execute([
|
||||
$page['slug'], $section['key'], $section['title'], $section['lead'],
|
||||
$section['style'], Html::sanitize($section['body']), $index,
|
||||
$section['style'], Html::sanitize($section['body']), isset($section['feed']) ? self::json($section['feed']) : null, $index,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$article = $pdo->prepare('INSERT OR IGNORE INTO articles
|
||||
(slug, title, category, summary, body, tags, status, published_at, updated_at, legacy_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
|
||||
foreach (Repository::CATEGORIES as $slug => $name) {
|
||||
$category->execute([$slug, $name]);
|
||||
}
|
||||
$article = $pdo->prepare("INSERT OR IGNORE INTO articles
|
||||
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at, legacy_path)
|
||||
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM article_redirects WHERE slug = ?)");
|
||||
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
|
||||
foreach ($seed['articles'] as $item) {
|
||||
$exists = $pdo->prepare('SELECT 1 FROM article_redirects WHERE slug = ?');
|
||||
$exists->execute([$item['slug']]);
|
||||
if ($exists->fetchColumn()) {
|
||||
continue;
|
||||
}
|
||||
$format = $item['body_format'] ?? 'markdown';
|
||||
$date = $item['date'] ?? null;
|
||||
$article->execute([
|
||||
$item['slug'], $item['title'], $item['category'], $item['summary'], $item['body'],
|
||||
self::json($item['tags']), $item['status'], $item['date'], $item['date'], $item['legacy'],
|
||||
$item['slug'], $item['title'], $item['summary'] ?? '',
|
||||
$format === 'html' ? Html::sanitize($item['body']) : $item['body'], $format,
|
||||
self::json($item['card'] ?? []), self::json($item['tags'] ?? []),
|
||||
$item['status'] ?? 'published', $date, $date ?? gmdate(DATE_ATOM), $item['legacy'] ?? null, $item['slug'],
|
||||
]);
|
||||
}
|
||||
|
||||
$migration = $pdo->prepare('INSERT OR IGNORE INTO schema_migrations (name) VALUES (?)');
|
||||
$migration->execute(['restore_pagepan_feature_icons']);
|
||||
if ($migration->rowCount() === 1) {
|
||||
PagepanFeatureIcons::migrate($pdo);
|
||||
}
|
||||
$migration->execute(['product_directory_and_service_icons']);
|
||||
if ($migration->rowCount() === 1) {
|
||||
DesignMigration::apply($pdo);
|
||||
}
|
||||
$migration->execute(['restore_home_featured_products']);
|
||||
if ($migration->rowCount() === 1) {
|
||||
DesignMigration::restoreFeaturedProducts($pdo, $seed);
|
||||
if ($article->rowCount() === 1) {
|
||||
$id = $pdo->lastInsertId();
|
||||
foreach ($item['categories'] as $slug) {
|
||||
$link->execute([$id, $slug]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use PDO;
|
||||
|
||||
final class DesignMigration
|
||||
{
|
||||
private const DIRECTORY_SUMMARY = '<p>浏览来笙的建站工具、智能 DNS 和软件著作权服务。</p><a class="button button-primary" href="/services">查看产品与服务</a>';
|
||||
|
||||
public static function apply(PDO $pdo): void
|
||||
{
|
||||
$stock = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
|
||||
$home = array_column($stock['pages'], null, 'slug')['home'];
|
||||
$stockBody = Html::sanitize(array_column($home['sections'], 'body', 'key')['product']);
|
||||
$doc = new DOMDocument('1.0', 'UTF-8');
|
||||
$doc->loadHTML('<meta charset="UTF-8">' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$xpath = new DOMXPath($doc);
|
||||
$insert = $pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, extra_url, extra_label, position)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
foreach ($xpath->query('//article[contains(concat(" ", @class, " "), " project ")]') as $position => $card) {
|
||||
$image = $xpath->query('.//img', $card)->item(0);
|
||||
$links = $xpath->query('.//a', $card);
|
||||
$body = '';
|
||||
foreach ($xpath->query('.//p', $card) as $paragraph) {
|
||||
$body .= $doc->saveHTML($paragraph);
|
||||
}
|
||||
$insert->execute([
|
||||
trim($xpath->evaluate('string(.//h3)', $card)), trim($xpath->evaluate('string(.//span)', $card)),
|
||||
Html::sanitize($body), $image->getAttribute('src'), $image->getAttribute('alt'),
|
||||
$links->item(0)->getAttribute('href'), trim($links->item(0)->textContent),
|
||||
$links->item(1)?->getAttribute('href') ?? '', trim($links->item(1)?->textContent ?? ''), $position * 10,
|
||||
]);
|
||||
}
|
||||
$pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
|
||||
->execute(['SHNU 学生软著服务', '校园服务', '<p>面向 SHNU 学生的软件著作权申请服务。</p>',
|
||||
'/assets/original/shnu-hero.webp', '', '/shnu-sc', '查看学生方案', 30]);
|
||||
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1
|
||||
WHERE page_slug = 'home' AND key = 'product' AND version = 0 AND body = ?")
|
||||
->execute([self::DIRECTORY_SUMMARY, $stockBody]);
|
||||
|
||||
$choices = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'why' AND page_slug IN ('sc', 'shnu-sc')");
|
||||
$updateChoice = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'why'");
|
||||
foreach ($choices->fetchAll() as $section) {
|
||||
$body = preg_replace('~(<article\b[^>]*class="[^"]*\bfeature-card)("(?:[^>]*>)\s*<h[2-4]>选择来笙</h[2-4]>)~u',
|
||||
'$1 choice-card$2', $section['body']);
|
||||
if ($body !== null && $body !== $section['body']) {
|
||||
$updateChoice->execute([$body, $section['page_slug']]);
|
||||
}
|
||||
}
|
||||
|
||||
$icons = ['/assets/original/10-1.png' => '/assets/service/project.svg',
|
||||
'/assets/original/10-2.png' => '/assets/service/code.svg', '/assets/original/10-3.png' => '/assets/service/support.svg'];
|
||||
$sections = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'options' AND page_slug IN ('sc', 'shnu-sc')");
|
||||
$update = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'options'");
|
||||
foreach ($sections->fetchAll() as $section) {
|
||||
$body = strtr($section['body'], $icons);
|
||||
$body = preg_replace('/(<article\b[^>]*>)\s*<li\b[^>]*>(.*?)<\/li>\s*(<\/article>)/s', '$1$2$3', $body);
|
||||
if ($body !== $section['body']) {
|
||||
$update->execute([$body, $section['page_slug']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function restoreFeaturedProducts(PDO $pdo, array $seed): void
|
||||
{
|
||||
$home = array_column($seed['pages'], null, 'slug')['home'];
|
||||
$stockBody = Html::sanitize(array_column($home['sections'], 'body', 'key')['product']);
|
||||
$doc = new DOMDocument('1.0', 'UTF-8');
|
||||
$doc->loadHTML('<meta charset="UTF-8">' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$projects = $doc->getElementsByTagName('article');
|
||||
$body = '<div class="project-stack">' . $doc->saveHTML($projects->item(0))
|
||||
. $doc->saveHTML($projects->item(1)) . '</div>';
|
||||
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1
|
||||
WHERE page_slug = 'home' AND key = 'product' AND body = ?")
|
||||
->execute([Html::sanitize($body), self::DIRECTORY_SUMMARY]);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ namespace App\Content;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMNode;
|
||||
use League\CommonMark\CommonMarkConverter;
|
||||
use League\CommonMark\GithubFlavoredMarkdownConverter;
|
||||
use RuntimeException;
|
||||
|
||||
final class Html
|
||||
@@ -43,13 +43,18 @@ final class Html
|
||||
public static function markdown(string $text): string
|
||||
{
|
||||
static $converter;
|
||||
$converter ??= new CommonMarkConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
|
||||
$converter ??= new GithubFlavoredMarkdownConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
|
||||
|
||||
$html = $converter->convert($text)->getContent();
|
||||
|
||||
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
|
||||
}
|
||||
|
||||
public static function articleBody(array $article): string
|
||||
{
|
||||
return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
|
||||
}
|
||||
|
||||
public static function applyCanvasEdits(string $body, array $edits): string
|
||||
{
|
||||
if (!array_is_list($edits) || count($edits) > 512) {
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use PDO;
|
||||
|
||||
final class PagepanFeatureIcons
|
||||
{
|
||||
public static function migrate(PDO $pdo): void
|
||||
{
|
||||
$query = $pdo->query("SELECT body FROM sections WHERE page_slug = 'pagepan' AND key = 'features'");
|
||||
$body = $query->fetchColumn();
|
||||
if (!is_string($body) || $body === '') {
|
||||
return;
|
||||
}
|
||||
$paths = json_decode(file_get_contents(dirname(__DIR__, 2) . '/resources/pagepan-feature-icons.json'), true, flags: JSON_THROW_ON_ERROR);
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $body . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$xpath = new DOMXPath($document);
|
||||
|
||||
$changed = false;
|
||||
foreach ($xpath->query('//article[contains(concat(" ", normalize-space(@class), " "), " feature-card ")]') as $card) {
|
||||
$heading = $xpath->query('(./h2 | ./h3 | ./h4)[1]', $card)->item(0);
|
||||
if (!$heading instanceof DOMElement || $card->getElementsByTagName('img')->length > 0) {
|
||||
continue;
|
||||
}
|
||||
$title = trim($heading->textContent);
|
||||
if (!isset($paths[$title])) {
|
||||
continue;
|
||||
}
|
||||
$icon = $document->createElement('img');
|
||||
foreach (['src' => $paths[$title], 'alt' => '', 'width' => '50', 'height' => '50', 'loading' => 'lazy'] as $key => $value) {
|
||||
$icon->setAttribute($key, $value);
|
||||
}
|
||||
$card->insertBefore($icon, $card->firstChild);
|
||||
$changed = true;
|
||||
}
|
||||
|
||||
if ($changed) {
|
||||
$updated = '';
|
||||
foreach ($document->getElementsByTagName('body')->item(0)->childNodes as $child) {
|
||||
$updated .= $document->saveHTML($child);
|
||||
}
|
||||
$pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = 'pagepan' AND key = 'features'")
|
||||
->execute([trim($updated)]);
|
||||
$pdo->prepare("UPDATE pages SET updated_at = ? WHERE slug = 'pagepan'")
|
||||
->execute([(new \DateTimeImmutable('now', new \DateTimeZone('Asia/Shanghai')))->format('Y-m-d H:i:s')]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
-34
@@ -9,7 +9,13 @@ use RuntimeException;
|
||||
|
||||
final class Repository
|
||||
{
|
||||
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'];
|
||||
public const DIRECTORIES = [
|
||||
'services' => '产品与服务', 'supported-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()
|
||||
@@ -32,8 +38,8 @@ final class Repository
|
||||
public function createPage(string $slug, string $name): void
|
||||
{
|
||||
$query = $this->pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
|
||||
lead, image, alt, actions, quicklinks, partners, status, updated_at)
|
||||
VALUES (?, ?, ?, '', ?, '', '', '', '', '[]', '[]', '[]', 'draft', ?)");
|
||||
lead, image, alt, actions, quicklinks, status, updated_at)
|
||||
VALUES (?, ?, ?, '', ?, '', '', '', '', '[]', '[]', 'draft', ?)");
|
||||
$query->execute([$slug, $name, $name . ' · 来笙', $name, self::now()]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此页面地址已存在。');
|
||||
@@ -46,7 +52,7 @@ final class Repository
|
||||
if (!$page) {
|
||||
return null;
|
||||
}
|
||||
foreach (['actions', 'quicklinks', 'partners'] as $key) {
|
||||
foreach (['actions', 'quicklinks'] 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');
|
||||
@@ -92,25 +98,25 @@ final class Repository
|
||||
|
||||
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 = ?, version = version + 1
|
||||
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, version = version + 1
|
||||
WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
}
|
||||
|
||||
public function createSection(string $page, string $key, string $title, string $style, string $body): void
|
||||
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body): void {
|
||||
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body') + ['lead' => '']);
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed): 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, position)
|
||||
SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
|
||||
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $page]);
|
||||
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, 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, $page]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此区块锚点已被使用。');
|
||||
}
|
||||
@@ -159,23 +165,44 @@ final class Repository
|
||||
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
|
||||
}
|
||||
|
||||
public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array
|
||||
public function categories(): array
|
||||
{
|
||||
$sql = 'SELECT * FROM articles WHERE 1 = 1';
|
||||
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' AND published_at IS NOT NULL";
|
||||
$sql .= " AND status = 'published'";
|
||||
}
|
||||
if ($category !== null) {
|
||||
$sql .= ' AND category = ?';
|
||||
$args[] = $category;
|
||||
$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';
|
||||
$query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' DESC, id DESC LIMIT ? OFFSET ?');
|
||||
$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());
|
||||
@@ -183,12 +210,12 @@ final class Repository
|
||||
|
||||
public function articleById(int $id): ?array
|
||||
{
|
||||
return self::decodeArticle($this->one('SELECT * FROM articles WHERE id = ?', [$id]));
|
||||
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 * FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
|
||||
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
|
||||
}
|
||||
|
||||
public function articleRedirect(string $slug): ?array
|
||||
@@ -215,26 +242,34 @@ final class Repository
|
||||
if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) {
|
||||
throw new RuntimeException('此网址标识已被使用。');
|
||||
}
|
||||
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' ? self::now() : null);
|
||||
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null);
|
||||
$values = [
|
||||
$data['slug'], $data['title'], $data['category'], $data['summary'], $data['body'],
|
||||
$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
|
||||
(slug, title, category, summary, body, tags, status, published_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
(slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
$query->execute($values);
|
||||
|
||||
return (int) $pdo->lastInsertId();
|
||||
$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]);
|
||||
}
|
||||
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]);
|
||||
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
|
||||
foreach ($data['categories'] as $category) {
|
||||
$link->execute([$id, $category]);
|
||||
}
|
||||
$query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, category = ?, summary = ?, body = ?, tags = ?,
|
||||
status = ?, published_at = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?');
|
||||
$query->execute([...$values, $id, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
|
||||
return $id;
|
||||
});
|
||||
@@ -242,7 +277,9 @@ final class Repository
|
||||
|
||||
public function sitemapArticles(): iterable
|
||||
{
|
||||
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published' AND trim(body) <> '' ORDER BY slug");
|
||||
$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;
|
||||
}
|
||||
|
||||
@@ -297,7 +334,9 @@ final class Repository
|
||||
private static function decodeArticle(?array $article): ?array
|
||||
{
|
||||
if ($article !== null) {
|
||||
$article['tags'] = json_decode($article['tags'], true, flags: JSON_THROW_ON_ERROR);
|
||||
foreach (['tags', 'categories', 'card'] as $field) {
|
||||
$article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
return $article;
|
||||
|
||||
@@ -58,50 +58,4 @@ final class SiteDesign
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
});
|
||||
}
|
||||
|
||||
public static function catalog(): array
|
||||
{
|
||||
return Database::connect()->query('SELECT * FROM catalog ORDER BY position, id')->fetchAll();
|
||||
}
|
||||
|
||||
public static function product(int $id): ?array
|
||||
{
|
||||
$query = Database::connect()->prepare('SELECT * FROM catalog WHERE id = ?');
|
||||
$query->execute([$id]);
|
||||
|
||||
return $query->fetch() ?: null;
|
||||
}
|
||||
|
||||
public static function saveProduct(?int $id, array $product, int $version): int
|
||||
{
|
||||
$pdo = Database::connect();
|
||||
$fields = ['name', 'category', 'body', 'image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'position'];
|
||||
$values = array_map(static fn (string $field) => $product[$field], $fields);
|
||||
if ($id === null) {
|
||||
$pdo->prepare('INSERT INTO catalog (' . implode(', ', $fields) . ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
||||
->execute($values);
|
||||
|
||||
return (int) $pdo->lastInsertId();
|
||||
}
|
||||
|
||||
$query = $pdo->prepare('UPDATE catalog SET ' . implode(' = ?, ', $fields) . ' = ?, version = version + 1 WHERE id = ? AND version = ?');
|
||||
$query->execute([...$values, $id, $version]);
|
||||
self::checkProduct($query->rowCount());
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public static function deleteProduct(int $id, int $version): void
|
||||
{
|
||||
$query = Database::connect()->prepare('DELETE FROM catalog WHERE id = ? AND version = ?');
|
||||
$query->execute([$id, $version]);
|
||||
self::checkProduct($query->rowCount());
|
||||
}
|
||||
|
||||
private static function checkProduct(int $count): void
|
||||
{
|
||||
if ($count !== 1) {
|
||||
throw new RuntimeException('此项目已在另一页面更新,请重新打开。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,13 +15,16 @@ final class View
|
||||
$html = self::fragment($template, $data);
|
||||
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
|
||||
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
|
||||
$articleEditor = $admin && !empty($data['articleEditor']);
|
||||
$editorImages = $articleEditor ? ' data:' : '';
|
||||
$editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
|
||||
$headers = [
|
||||
'Content-Type' => 'text/html; charset=utf-8',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Referrer-Policy' => 'strict-origin-when-cross-origin',
|
||||
'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
|
||||
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; "
|
||||
. "style-src $assetSources; script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
|
||||
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:$editorImages; media-src 'self' https:; "
|
||||
. "style-src $assetSources; {$editorStyles}script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
|
||||
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
|
||||
];
|
||||
if ($admin || !empty($data['previewMode'])) {
|
||||
|
||||
Reference in New Issue
Block a user