forked from laysense/laysite
274 lines
12 KiB
PHP
274 lines
12 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use PDO;
|
|
use RuntimeException;
|
|
|
|
final class DesignLibrary
|
|
{
|
|
public const PRESETS = [
|
|
'header' => ['inline' => '横排导航', 'center' => '居中品牌', 'member' => '会员导航'],
|
|
'footer' => ['columns' => '多栏链接', 'compact' => '简约横栏', 'band' => '全宽深色'],
|
|
'palette' => ['custom' => '自定义配色'],
|
|
];
|
|
|
|
public const COMPONENTS = [
|
|
'header' => ['brand' => '站点标识', 'links' => '导航链接', 'action' => '行动按钮', 'account' => '用户区'],
|
|
'footer' => ['brand' => '站点标识', 'text' => '说明文字', 'links' => '页脚链接', 'legal' => '版权文字'],
|
|
];
|
|
|
|
public const COLORS = [
|
|
'white' => ['页面背景', '#ffffff'], 'paper' => ['区块背景', '#f5f7fb'],
|
|
'ink' => ['正文', '#111a2e'], 'muted' => ['次要文字', '#505d73'],
|
|
'accent' => ['强调色', '#214ed7'], 'accent-deep' => ['强调色悬停', '#173bae'],
|
|
'accent-light' => ['强调色浅底', '#e8efff'], 'line' => ['边框', '#dbe3f0'],
|
|
'button-ink' => ['填充按钮文字', '#ffffff'],
|
|
];
|
|
public const PROVIDER_FIELDS = ['mode', 'client_id', 'scope', 'issuer', 'authorization', 'token', 'userinfo',
|
|
'subject_field', 'name_field', 'avatar_field', 'token_auth'];
|
|
|
|
public static function all(?string $kind = null): array
|
|
{
|
|
$query = Database::connect()->prepare('SELECT id, kind, name, preset, version FROM design_presets'
|
|
. ($kind === null ? '' : ' WHERE kind = ?') . ' ORDER BY kind, id');
|
|
$query->execute($kind === null ? [] : [$kind]);
|
|
|
|
return $query->fetchAll();
|
|
}
|
|
|
|
public static function find(int $id, string $kind): ?array
|
|
{
|
|
if ($id < 1) {
|
|
return null;
|
|
}
|
|
$query = Database::connect()->prepare('SELECT design_presets.*, credentials.revision AS credential_revision
|
|
FROM design_presets LEFT JOIN layout_oauth_credentials credentials ON credentials.layout_id = design_presets.id
|
|
WHERE design_presets.id = ? AND kind = ?');
|
|
$query->execute([$id, $kind]);
|
|
$row = $query->fetch();
|
|
if (!$row) {
|
|
return null;
|
|
}
|
|
$row['payload'] = self::normalize($kind, $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
|
|
|
|
return $row;
|
|
}
|
|
|
|
public static function defaults(string $kind): array
|
|
{
|
|
if ($kind === 'palette') {
|
|
return array_map(static fn (array $color): string => $color[1], self::COLORS);
|
|
}
|
|
|
|
return [
|
|
'components' => array_keys(self::COMPONENTS[$kind]), 'logo' => '', 'brand' => '', 'text' => '',
|
|
'legal' => '', 'links' => $kind === 'header' ? [['/', '首页'], ['/articles', '文章']] : [],
|
|
'action' => [], 'provider' => [],
|
|
];
|
|
}
|
|
|
|
public static function layout(string $kind, array $site, array $page): array
|
|
{
|
|
$id = (int) ($page[$kind . '_id'] ?? 0) ?: (int) ($site[$kind . '_id'] ?? 0);
|
|
|
|
return self::find($id, $kind) ?? [
|
|
'id' => 0, 'preset' => array_key_first(self::PRESETS[$kind]), 'payload' => self::defaults($kind),
|
|
];
|
|
}
|
|
|
|
public static function selection(string $kind, mixed $value): ?int
|
|
{
|
|
if ($value === '' || $value === null || $value === 0) {
|
|
return null;
|
|
}
|
|
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
|
if ($id === false || !self::find($id, $kind)) {
|
|
throw new RuntimeException('所选页头、页脚或配色方案不存在。');
|
|
}
|
|
|
|
return $id;
|
|
}
|
|
|
|
public static function normalize(string $kind, string $preset, array $data): array
|
|
{
|
|
if (!isset(self::PRESETS[$kind][$preset])) {
|
|
throw new DesignFieldError('preset', '请选择可用的组件模板。');
|
|
}
|
|
if ($kind === 'palette') {
|
|
$colors = [];
|
|
foreach (self::COLORS as $key => [, $default]) {
|
|
$color = $data[$key] ?? $default;
|
|
if (!is_string($color) || !preg_match('/^#[\da-f]{6}$/iD', $color)) {
|
|
throw new DesignFieldError($key, '颜色必须使用六位十六进制表示。');
|
|
}
|
|
$colors[$key] = strtolower($color);
|
|
}
|
|
|
|
return $colors;
|
|
}
|
|
|
|
$clean = self::defaults($kind);
|
|
foreach (['brand' => 100, 'text' => 1200, 'legal' => 300, 'logo' => 1000] as $field => $limit) {
|
|
$clean[$field] = self::string($data[$field] ?? '', $limit, $field);
|
|
}
|
|
if ($clean['logo'] !== '' && !Html::url($clean['logo'], true)) {
|
|
throw new DesignFieldError('logo', '请检查站点标识地址。');
|
|
}
|
|
$components = $data['components'] ?? $clean['components'];
|
|
if (!is_array($components) || !array_is_list($components)) {
|
|
throw new DesignFieldError('components', '组件顺序无效。');
|
|
}
|
|
foreach ($components as $component) {
|
|
if (!is_string($component) || !isset(self::COMPONENTS[$kind][$component])) {
|
|
throw new DesignFieldError('components', '布局包含未知组件。');
|
|
}
|
|
}
|
|
$clean['components'] = array_values(array_unique($components));
|
|
try {
|
|
$clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20);
|
|
} catch (RuntimeException $error) {
|
|
throw new DesignFieldError('links', $error->getMessage());
|
|
}
|
|
try {
|
|
$clean['action'] = Buttons::validate($data['action'] ?? []);
|
|
} catch (RuntimeException $error) {
|
|
throw new DesignFieldError('action', $error->getMessage());
|
|
}
|
|
$clean['provider'] = $kind === 'header' && $preset === 'member'
|
|
? self::provider($data['provider'] ?? []) : [];
|
|
|
|
return $clean;
|
|
}
|
|
|
|
public static function provider(array $data): array
|
|
{
|
|
$mode = $data['mode'] ?? '';
|
|
if ($mode === '') {
|
|
return [];
|
|
}
|
|
if (!in_array($mode, ['oidc', 'oauth2'], true)) {
|
|
throw new DesignFieldError('provider_mode', '请选择 OIDC 或 OAuth 2.0。');
|
|
}
|
|
$result = ['mode' => $mode];
|
|
foreach (array_slice(self::PROVIDER_FIELDS, 1) as $field) {
|
|
$result[$field] = self::string($data[$field] ?? '', 600, 'provider_' . $field);
|
|
}
|
|
if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) {
|
|
throw new DesignFieldError('provider_token_auth', '令牌端点认证方式无效。');
|
|
}
|
|
if ($result['client_id'] === '') {
|
|
throw new DesignFieldError('provider_client_id', '请填写客户端 ID。');
|
|
}
|
|
foreach ($mode === 'oidc' ? ['issuer'] : ['authorization', 'token', 'userinfo'] as $field) {
|
|
$url = parse_url($result[$field]);
|
|
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|
|
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || ($field === 'issuer' && isset($url['query'])) || !Html::url($result[$field], true)) {
|
|
throw new DesignFieldError('provider_' . $field, '认证端点必须使用完整的 HTTPS 地址。');
|
|
}
|
|
}
|
|
if ($mode === 'oauth2' && $result['subject_field'] === '') {
|
|
throw new DesignFieldError('provider_subject_field', 'OAuth 2.0 用户资料需要指定稳定的用户 ID 字段。');
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
public static function hasAccount(string $preset, array $components): bool
|
|
{
|
|
return $preset === 'member' && in_array('account', $components, true);
|
|
}
|
|
|
|
public static function identity(?array $layout): ?string
|
|
{
|
|
if (empty($layout['credential_revision']) || empty($layout['payload']['provider'])
|
|
|| !self::hasAccount($layout['preset'], $layout['payload']['components'])) {
|
|
return null;
|
|
}
|
|
|
|
$page = (new Repository())->layoutPage((int) $layout['id']);
|
|
if ($page !== null && !LayoutPage::hasMember($page['sections'])) {
|
|
return null;
|
|
}
|
|
|
|
return hash('sha256', Database::json([$layout['payload']['provider'], $layout['credential_revision']]));
|
|
}
|
|
|
|
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int
|
|
{
|
|
return Database::write(static fn (PDO $pdo): int => self::saveIn($pdo, $kind, $id, $name, $preset, $data, $version, $default, $secret));
|
|
}
|
|
|
|
public static function saveIn(PDO $pdo, string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int
|
|
{
|
|
$name = self::string($name, 100, 'name');
|
|
if ($name === '') {
|
|
throw new DesignFieldError('name', '请填写配置名称。');
|
|
}
|
|
$clean = self::normalize($kind, $preset, $data);
|
|
$payload = Database::json($clean);
|
|
$provider = $clean['provider'] ?? [];
|
|
$active = $provider !== [] && self::hasAccount($preset, $clean['components']);
|
|
|
|
if ($active && $secret === '') {
|
|
$saved = $id === null ? null : self::find($id, $kind);
|
|
$fields = array_flip(['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id']);
|
|
if (empty($saved['credential_revision'])
|
|
|| array_intersect_key($provider, $fields) !== array_intersect_key($saved['payload']['provider'], $fields)) {
|
|
throw new DesignFieldError('provider_secret', '启用登录或变更身份提供商时,请填写客户端密钥。');
|
|
}
|
|
}
|
|
if ($id === null) {
|
|
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')->execute([$kind, $name, $preset, $payload]);
|
|
$id = (int) $pdo->lastInsertId();
|
|
} else {
|
|
$query = $pdo->prepare('UPDATE design_presets SET name = ?, preset = ?, payload = ?, version = version + 1 WHERE id = ? AND kind = ? AND version = ?');
|
|
$query->execute([$name, $preset, $payload, $id, $kind, $version]);
|
|
if ($query->rowCount() !== 1) {
|
|
throw new RuntimeException('配置已更新,请重新打开后再保存。');
|
|
}
|
|
}
|
|
if ($kind === 'header') {
|
|
if ($provider === []) {
|
|
$pdo->prepare('DELETE FROM layout_oauth_credentials WHERE layout_id = ?')->execute([$id]);
|
|
} elseif ($active && $secret !== '') {
|
|
OAuthCredentials::store($pdo, $id, $secret);
|
|
}
|
|
}
|
|
if ($kind !== 'palette') {
|
|
self::setDefault($pdo, $kind, $id, $default);
|
|
}
|
|
|
|
return $id;
|
|
}
|
|
|
|
public static function setDefault(PDO $pdo, string $kind, int $id, bool $default): void
|
|
{
|
|
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
|
$field = $kind . '_id';
|
|
if ($default) {
|
|
$site[$field] = $id;
|
|
} elseif (($site[$field] ?? null) === $id) {
|
|
if (!isset($site['layout_defaults'][$kind])) {
|
|
unset($site[$field]);
|
|
} else {
|
|
$site[$field] = $site['layout_defaults'][$kind];
|
|
}
|
|
} else {
|
|
return;
|
|
}
|
|
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
|
}
|
|
|
|
private static function string(mixed $value, int $limit, string $field): string
|
|
{
|
|
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit) {
|
|
throw new DesignFieldError($field, '配置包含无效或过长的文字。');
|
|
}
|
|
|
|
return trim($value);
|
|
}
|
|
}
|