Add visual CMS, media library and product directory
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMXPath;
|
||||
use RuntimeException;
|
||||
|
||||
final class Assets
|
||||
{
|
||||
public static function cdn(string $value): string
|
||||
{
|
||||
$value = rtrim(trim($value), '/');
|
||||
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
|
||||
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.laysense.cn。');
|
||||
}
|
||||
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
|
||||
throw new RuntimeException('CDN 端口无效。');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function url(string $path, string $cdn): string
|
||||
{
|
||||
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
|
||||
}
|
||||
|
||||
public static function rewrite(string $html, string $cdn): string
|
||||
{
|
||||
if ($cdn === '') {
|
||||
return $html;
|
||||
}
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$document->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$xpath = new DOMXPath($document);
|
||||
foreach ($xpath->query('//@src | //@href | //@poster') as $attribute) {
|
||||
$attribute->value = self::url($attribute->value, $cdn);
|
||||
}
|
||||
|
||||
return $document->saveHTML();
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,9 @@ final class Database
|
||||
|
||||
self::write(function (PDO $pdo) use ($root, $seed): void {
|
||||
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
|
||||
if (!in_array('status', array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'), true)) {
|
||||
$pdo->exec("ALTER TABLE pages ADD COLUMN status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published'))");
|
||||
}
|
||||
$site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)');
|
||||
$site->execute([self::json($seed['site'])]);
|
||||
|
||||
@@ -85,6 +88,10 @@ final class Database
|
||||
if ($migration->rowCount() === 1) {
|
||||
PagepanFeatureIcons::migrate($pdo);
|
||||
}
|
||||
$migration->execute(['product_directory_and_service_icons']);
|
||||
if ($migration->rowCount() === 1) {
|
||||
DesignMigration::apply($pdo);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use PDO;
|
||||
|
||||
final class DesignMigration
|
||||
{
|
||||
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(['<p>浏览来笙的建站工具、智能 DNS 和软件著作权服务。</p><a class="button button-primary" href="/services">查看产品与服务</a>', $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']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use League\CommonMark\CommonMarkConverter;
|
||||
final class Html
|
||||
{
|
||||
private const TAGS = [
|
||||
'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
|
||||
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
|
||||
@@ -20,7 +20,7 @@ final class Html
|
||||
'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'],
|
||||
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
|
||||
];
|
||||
|
||||
public static function url(string $value, bool $media = false): bool
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use Webman\Http\UploadFile;
|
||||
|
||||
final class Media
|
||||
{
|
||||
public const MAX_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
private const EXTENSIONS = [
|
||||
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
|
||||
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
|
||||
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
|
||||
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
|
||||
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
|
||||
];
|
||||
|
||||
public static function all(bool $includeArchived = false): array
|
||||
{
|
||||
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
|
||||
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
|
||||
foreach ($files as &$file) {
|
||||
$file['url'] = '/assets/uploads/' . $file['name'];
|
||||
}
|
||||
unset($file);
|
||||
|
||||
$root = dirname(__DIR__, 2) . '/public/assets';
|
||||
$builtIn = [];
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root)) as $file) {
|
||||
if (!$file->isFile() || $file->isLink() || str_starts_with($file->getFilename(), '.')) {
|
||||
continue;
|
||||
}
|
||||
$path = str_replace(DIRECTORY_SEPARATOR, '/', substr($file->getPathname(), strlen($root) + 1));
|
||||
$label = $file->getFilename();
|
||||
$type = array_search(strtolower($file->getExtension()), self::EXTENSIONS, true) ?: 'application/octet-stream';
|
||||
$builtIn[] = ['label' => $label, 'name' => '', 'mime' => $type, 'size' => $file->getSize(),
|
||||
'url' => '/assets/' . $path, 'archived' => 0];
|
||||
}
|
||||
usort($builtIn, static fn (array $left, array $right): int => strnatcasecmp($left['url'], $right['url']));
|
||||
|
||||
return [...$files, ...$builtIn];
|
||||
}
|
||||
|
||||
public static function upload(UploadFile $file, string $label): void
|
||||
{
|
||||
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
|
||||
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
|
||||
}
|
||||
$source = $file->getPathname();
|
||||
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
|
||||
$extension = self::EXTENSIONS[$mime] ?? null;
|
||||
if ($extension === null) {
|
||||
throw new RuntimeException('文件类型不受支持。');
|
||||
}
|
||||
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
|
||||
$name = bin2hex(random_bytes(16)) . '.' . $extension;
|
||||
$directory = self::directory();
|
||||
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
|
||||
throw new RuntimeException('资源目录无法创建。');
|
||||
}
|
||||
$path = $directory . '/' . $name;
|
||||
try {
|
||||
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
|
||||
if (!$written) {
|
||||
throw new RuntimeException('文件写入失败。');
|
||||
}
|
||||
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
|
||||
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
|
||||
} catch (Throwable $error) {
|
||||
if (is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
public static function find(string $name): ?array
|
||||
{
|
||||
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
|
||||
$query->execute([$name]);
|
||||
|
||||
return $query->fetch() ?: null;
|
||||
}
|
||||
|
||||
public static function update(string $name, string $label, bool $archived): void
|
||||
{
|
||||
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
|
||||
->execute([$label, (int) $archived, $name]);
|
||||
}
|
||||
|
||||
public static function directory(): string
|
||||
{
|
||||
return rtrim(getenv('LAYSENSE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
|
||||
}
|
||||
|
||||
private static function safeSvg(string $source, int $size): string
|
||||
{
|
||||
if ($size > 512 * 1024) {
|
||||
throw new RuntimeException('SVG 图标最大支持 512 KB。');
|
||||
}
|
||||
$svg = new DOMDocument();
|
||||
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|
||||
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
|
||||
throw new RuntimeException('SVG 图标格式无效。');
|
||||
}
|
||||
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
|
||||
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
|
||||
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
|
||||
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
|
||||
foreach ((new DOMXPath($svg))->query('//*') as $element) {
|
||||
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|
||||
|| !in_array($element->localName, $tags, true)) {
|
||||
throw new RuntimeException('SVG 仅支持基础矢量元素。');
|
||||
}
|
||||
foreach ($element->attributes as $attribute) {
|
||||
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|
||||
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
|
||||
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $svg->saveXML($svg->documentElement);
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,22 @@ final class Repository
|
||||
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
|
||||
public function pages(bool $publishedOnly = false): array
|
||||
{
|
||||
return $this->pdo->query('SELECT slug, name, title, updated_at FROM pages ORDER BY rowid')->fetchAll();
|
||||
$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
|
||||
@@ -50,11 +63,12 @@ final class Repository
|
||||
|
||||
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 = $this->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['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
|
||||
$data['image'], $data['alt'], Database::json($data['actions']), self::now(), $slug, $version,
|
||||
$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());
|
||||
}
|
||||
@@ -62,15 +76,64 @@ final class Repository
|
||||
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
|
||||
$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'], $page, $key, $version]);
|
||||
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]);
|
||||
self::checkVersion($query->rowCount());
|
||||
$query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?');
|
||||
$query->execute([self::now(), $page]);
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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): void
|
||||
{
|
||||
$pdo->prepare('UPDATE pages SET updated_at = ? 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';
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use PDO;
|
||||
use RuntimeException;
|
||||
|
||||
final class SiteDesign
|
||||
{
|
||||
public const DEFAULT_HEADER = [
|
||||
'logo' => '/assets/wordmark.webp', 'alt' => 'Laysense 来笙',
|
||||
'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']],
|
||||
'button' => ['#contact', '联系来笙'],
|
||||
];
|
||||
|
||||
public const DEFAULT_FOOTER = [
|
||||
'logo' => '/assets/wordmark.webp', 'alt' => '来笙 Laysense',
|
||||
'products_title' => '产品与服务',
|
||||
'products' => [['/pagepan', 'PAGEPAN 小飞页'], ['/highspeaker', 'HighSpeaker DNS'], ['/sc', '软著代理服务'], ['/shnu-sc', 'SHNU 学生软著服务']],
|
||||
'company_title' => '公司',
|
||||
'company' => [['/#about', '关于来笙'], ['/articles', '来笙动态'], ['https://git.laysense.com', 'Laysense Git'], ['https://www.layso.de', 'LaySo']],
|
||||
'phones' => [['tel:+16699004532', '+1 (669) 900 4532'], ['tel:+85257012856', '+852 5701 2856']],
|
||||
];
|
||||
|
||||
public static function parseLinks(string $value): array
|
||||
{
|
||||
$links = [];
|
||||
foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) {
|
||||
if (trim($line) === '') {
|
||||
continue;
|
||||
}
|
||||
[$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, ''));
|
||||
if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
|
||||
throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
|
||||
}
|
||||
$links[] = [$url, $label];
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
public static function linkText(array $links): string
|
||||
{
|
||||
return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
|
||||
}
|
||||
|
||||
public static function saveSettings(string $part, array $data, int $version): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($part, $data, $version): void {
|
||||
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if (($site['revisions'][$part] ?? 0) !== $version) {
|
||||
throw new RuntimeException('设置已在另一页面更新。请复制本次修改后重新打开。');
|
||||
}
|
||||
$site[$part] = $data;
|
||||
$site['revisions'][$part] = $version + 1;
|
||||
$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('此项目已在另一页面更新,请重新打开。');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,17 +10,21 @@ final class View
|
||||
{
|
||||
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
|
||||
{
|
||||
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
|
||||
$data['cdn'] = $cdn;
|
||||
$html = self::fragment($template, $data);
|
||||
$page = self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]);
|
||||
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
|
||||
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
|
||||
$headers = [
|
||||
'Content-Type' => 'text/html; charset=utf-8',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Referrer-Policy' => 'strict-origin-when-cross-origin',
|
||||
'X-Frame-Options' => 'DENY',
|
||||
'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : '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'",
|
||||
. "style-src $assetSources; 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) {
|
||||
if ($admin || !empty($data['previewMode'])) {
|
||||
$headers['Cache-Control'] = 'no-store';
|
||||
$headers['X-Robots-Tag'] = 'noindex, nofollow';
|
||||
} elseif (($data['noindex'] ?? false) || $status >= 400) {
|
||||
|
||||
Reference in New Issue
Block a user