303 lines
13 KiB
PHP
303 lines
13 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use PDO;
|
|
use RuntimeException;
|
|
|
|
final class Repository
|
|
{
|
|
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'];
|
|
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 FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
|
|
}
|
|
|
|
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', ?)");
|
|
$query->execute([$slug, $name, $name . ' · 来笙', $name, self::now()]);
|
|
if ($query->rowCount() !== 1) {
|
|
throw new RuntimeException('此页面地址已存在。');
|
|
}
|
|
}
|
|
|
|
public function page(string $slug): ?array
|
|
{
|
|
$page = $this->one('SELECT * FROM pages WHERE slug = ?', [$slug]);
|
|
if (!$page) {
|
|
return null;
|
|
}
|
|
foreach (['actions', 'quicklinks', 'partners'] 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 savePage(string $slug, array $data, int $version, array $sections = []): void
|
|
{
|
|
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections): void {
|
|
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
|
|
image = ?, alt = ?, actions = ?, quicklinks = ?, 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'], Database::json($data['actions']), Database::json($data['quicklinks']),
|
|
$data['status'], self::now(), $slug, $version,
|
|
]);
|
|
self::checkVersion($query->rowCount());
|
|
foreach ($sections as $section) {
|
|
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 = ?, version = version + 1
|
|
WHERE page_slug = ? AND key = ? AND version = ?');
|
|
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
|
|
self::checkVersion($query->rowCount());
|
|
}
|
|
|
|
public function createSection(string $page, string $key, string $title, string $style, string $body): void
|
|
{
|
|
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body): 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, $title, '', $style, $body, $page]);
|
|
if ($query->rowCount() !== 1) {
|
|
throw new RuntimeException('此区块锚点已被使用。');
|
|
}
|
|
self::touchPage($pdo, $page, structureChanged: true);
|
|
});
|
|
}
|
|
|
|
public function arrangeSection(string $page, string $key, string $operation, int $version): void
|
|
{
|
|
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version): void {
|
|
if ($operation === 'delete') {
|
|
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
|
|
$query->execute([$page, $key, $version]);
|
|
self::checkVersion($query->rowCount());
|
|
self::touchPage($pdo, $page, structureChanged: true);
|
|
|
|
return;
|
|
}
|
|
$query = $pdo->prepare('SELECT key FROM sections WHERE page_slug = ? ORDER BY position, key');
|
|
$query->execute([$page]);
|
|
$keys = $query->fetchAll(PDO::FETCH_COLUMN);
|
|
$index = array_search($key, $keys, true);
|
|
if ($index === false) {
|
|
throw new RuntimeException('找不到该区块。');
|
|
}
|
|
$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);
|
|
});
|
|
}
|
|
|
|
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 articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array
|
|
{
|
|
$sql = 'SELECT * FROM articles WHERE 1 = 1';
|
|
$args = [];
|
|
if ($public) {
|
|
$sql .= " AND status = 'published' AND published_at IS NOT NULL";
|
|
}
|
|
if ($category !== null) {
|
|
$sql .= ' AND category = ?';
|
|
$args[] = $category;
|
|
}
|
|
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 ?');
|
|
$query->execute([...$args, $limit, $offset]);
|
|
|
|
return array_map(self::decodeArticle(...), $query->fetchAll());
|
|
}
|
|
|
|
public function articleById(int $id): ?array
|
|
{
|
|
return self::decodeArticle($this->one('SELECT * 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]));
|
|
}
|
|
|
|
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' ? self::now() : null);
|
|
$values = [
|
|
$data['slug'], $data['title'], $data['category'], $data['summary'], $data['body'],
|
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
$query->execute($values);
|
|
|
|
return (int) $pdo->lastInsertId();
|
|
}
|
|
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 = ?, 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;
|
|
});
|
|
}
|
|
|
|
public function sitemapArticles(): iterable
|
|
{
|
|
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published' AND trim(body) <> '' 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) {
|
|
$article['tags'] = json_decode($article['tags'], 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('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
|
|
}
|
|
}
|
|
}
|