forked from laysense/laysense.cn
Rebuild Laysense site with Webman and SQLite CMS
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use PDO;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class Database
|
||||
{
|
||||
private static ?PDO $connection = null;
|
||||
|
||||
public static function connect(): PDO
|
||||
{
|
||||
if (self::$connection !== null) {
|
||||
return self::$connection;
|
||||
}
|
||||
|
||||
$path = getenv('LAYSENSE_DB') ?: dirname(__DIR__, 2) . '/storage/laysense.sqlite';
|
||||
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0750, true) && !is_dir(dirname($path))) {
|
||||
throw new RuntimeException('无法创建 SQLite 存放目录。');
|
||||
}
|
||||
|
||||
$pdo = new PDO('sqlite:' . $path, options: [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
|
||||
$pdo->exec('PRAGMA busy_timeout = 5000');
|
||||
$pdo->exec('PRAGMA foreign_keys = ON');
|
||||
self::$connection = $pdo;
|
||||
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
public static function initialize(): void
|
||||
{
|
||||
$root = dirname(__DIR__, 2);
|
||||
$seed = json_decode(file_get_contents($root . '/resources/seed.json'), true, flags: JSON_THROW_ON_ERROR);
|
||||
$pdo = self::connect();
|
||||
$pdo->exec('PRAGMA journal_mode = WAL');
|
||||
|
||||
self::write(function (PDO $pdo) use ($root, $seed): void {
|
||||
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
|
||||
$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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
$sectionQuery = $pdo->prepare('INSERT OR IGNORE INTO sections
|
||||
(page_slug, key, title, lead, style, body, 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'] ?? []),
|
||||
]);
|
||||
if ($pageQuery->rowCount() !== 1) {
|
||||
continue;
|
||||
}
|
||||
foreach ($page['sections'] as $index => $section) {
|
||||
$sectionQuery->execute([
|
||||
$page['slug'], $section['key'], $section['title'], $section['lead'],
|
||||
$section['style'], Html::sanitize($section['body']), $index,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$article = $pdo->prepare('INSERT OR IGNORE INTO articles
|
||||
(slug, title, category, summary, body, tags, status, published_at, updated_at, legacy_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
||||
foreach ($seed['articles'] as $item) {
|
||||
$exists = $pdo->prepare('SELECT 1 FROM article_redirects WHERE slug = ?');
|
||||
$exists->execute([$item['slug']]);
|
||||
if ($exists->fetchColumn()) {
|
||||
continue;
|
||||
}
|
||||
$article->execute([
|
||||
$item['slug'], $item['title'], $item['category'], $item['summary'], $item['body'],
|
||||
self::json($item['tags']), $item['status'], $item['date'], $item['date'], $item['legacy'],
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static function write(callable $operation): mixed
|
||||
{
|
||||
$pdo = self::connect();
|
||||
$pdo->exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
$result = $operation($pdo);
|
||||
$pdo->exec('COMMIT');
|
||||
|
||||
return $result;
|
||||
} catch (Throwable $error) {
|
||||
$pdo->exec('ROLLBACK');
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
public static function json(array $data): string
|
||||
{
|
||||
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMNode;
|
||||
use League\CommonMark\CommonMarkConverter;
|
||||
|
||||
final class Html
|
||||
{
|
||||
private const TAGS = [
|
||||
'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'hr' => [], 'i' => [],
|
||||
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
|
||||
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
|
||||
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
|
||||
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
|
||||
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
|
||||
'video' => ['controls', 'muted', 'playsinline', 'poster', 'preload'],
|
||||
];
|
||||
|
||||
public static function url(string $value, bool $media = false): bool
|
||||
{
|
||||
if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) {
|
||||
return false;
|
||||
}
|
||||
if (str_starts_with($value, '/')) {
|
||||
return !str_starts_with($value, '//');
|
||||
}
|
||||
if (str_starts_with($value, '#')) {
|
||||
return !$media && strlen($value) > 1;
|
||||
}
|
||||
$scheme = strtolower((string) parse_url($value, PHP_URL_SCHEME));
|
||||
|
||||
return in_array($scheme, $media ? ['https'] : ['https', 'http', 'mailto', 'tel'], true);
|
||||
}
|
||||
|
||||
public static function markdown(string $text): string
|
||||
{
|
||||
static $converter;
|
||||
$converter ??= new CommonMarkConverter(['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 sanitize(string $html): string
|
||||
{
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$body = $document->getElementsByTagName('body')->item(0);
|
||||
if (!$body) {
|
||||
return '';
|
||||
}
|
||||
self::sanitizeChildren($body);
|
||||
$output = '';
|
||||
foreach ($body->childNodes as $child) {
|
||||
$output .= $document->saveHTML($child);
|
||||
}
|
||||
|
||||
return trim($output);
|
||||
}
|
||||
|
||||
private static function sanitizeChildren(DOMNode $parent): void
|
||||
{
|
||||
foreach (iterator_to_array($parent->childNodes) as $element) {
|
||||
if ($element->nodeType === XML_COMMENT_NODE) {
|
||||
$parent->removeChild($element);
|
||||
continue;
|
||||
}
|
||||
if (!$element instanceof DOMElement) {
|
||||
continue;
|
||||
}
|
||||
if (!array_key_exists($element->tagName, self::TAGS)) {
|
||||
$parent->removeChild($element);
|
||||
continue;
|
||||
}
|
||||
$allowed = [...self::TAGS[$element->tagName], 'class', 'id'];
|
||||
foreach (iterator_to_array($element->attributes) as $attribute) {
|
||||
$name = $attribute->name;
|
||||
$value = $attribute->value;
|
||||
if (!in_array($name, $allowed, true)
|
||||
|| ($name === 'href' && !self::url($value))
|
||||
|| (in_array($name, ['src', 'poster'], true) && !self::url($value, true))
|
||||
|| ($name === 'tabindex' && $value !== '0')) {
|
||||
$element->removeAttribute($name);
|
||||
}
|
||||
}
|
||||
self::sanitizeChildren($element);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
<?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(): array
|
||||
{
|
||||
return $this->pdo->query('SELECT slug, name, title, updated_at FROM pages ORDER BY rowid')->fetchAll();
|
||||
}
|
||||
|
||||
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): void
|
||||
{
|
||||
$query = $this->pdo->prepare('UPDATE pages SET title = ?, description = ?, heading = ?, accent = ?, lead = ?,
|
||||
image = ?, alt = ?, actions = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
|
||||
$query->execute([
|
||||
$data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
|
||||
$data['image'], $data['alt'], Database::json($data['actions']), self::now(), $slug, $version,
|
||||
]);
|
||||
self::checkVersion($query->rowCount());
|
||||
}
|
||||
|
||||
public function saveSection(string $page, string $key, array $data, int $version): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
|
||||
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, version = version + 1
|
||||
WHERE page_slug = ? AND key = ? AND version = ?');
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
$query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?');
|
||||
$query->execute([self::now(), $page]);
|
||||
});
|
||||
}
|
||||
|
||||
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 recordLoginAttempt(string $address): bool
|
||||
{
|
||||
return Database::write(function (PDO $pdo) use ($address): bool {
|
||||
$now = time();
|
||||
$pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]);
|
||||
$current = $this->one('SELECT attempts FROM login_attempts WHERE address = ?', [$address]);
|
||||
if ($current && $current['attempts'] >= 12) {
|
||||
return false;
|
||||
}
|
||||
$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 true;
|
||||
});
|
||||
}
|
||||
|
||||
public function clearLoginAttempts(string $address): void
|
||||
{
|
||||
$this->pdo->prepare('DELETE FROM login_attempts WHERE address = ?')->execute([$address]);
|
||||
}
|
||||
|
||||
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('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use support\Response;
|
||||
|
||||
final class View
|
||||
{
|
||||
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
|
||||
{
|
||||
$html = self::fragment($template, $data);
|
||||
$page = self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]);
|
||||
$headers = [
|
||||
'Content-Type' => 'text/html; charset=utf-8',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Referrer-Policy' => 'strict-origin-when-cross-origin',
|
||||
'X-Frame-Options' => 'DENY',
|
||||
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; "
|
||||
. "style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'; object-src 'none'",
|
||||
];
|
||||
if ($admin) {
|
||||
$headers['Cache-Control'] = 'no-store';
|
||||
$headers['X-Robots-Tag'] = 'noindex, nofollow';
|
||||
} elseif (($data['noindex'] ?? false) || $status >= 400) {
|
||||
$headers['X-Robots-Tag'] = 'noindex';
|
||||
}
|
||||
|
||||
return new Response($status, $headers, $page);
|
||||
}
|
||||
|
||||
public static function fragment(string $template, array $data = []): string
|
||||
{
|
||||
extract($data, EXTR_SKIP);
|
||||
ob_start();
|
||||
try {
|
||||
require dirname(__DIR__) . '/view/' . $template . '.php';
|
||||
|
||||
return (string) ob_get_contents();
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
}
|
||||
|
||||
public static function escape(string|int|null $value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
public static function absolute(string $path): string
|
||||
{
|
||||
return rtrim(getenv('LAYSENSE_SITE_URL') ?: 'https://laysense.cn', '/') . $path;
|
||||
}
|
||||
|
||||
public static function date(?string $value, string $format = 'Y年n月j日'): string
|
||||
{
|
||||
return $value ? date($format, strtotime($value)) : '';
|
||||
}
|
||||
|
||||
public static function redirect(string $path, int $status = 303): Response
|
||||
{
|
||||
return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], '');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user