阶段 0 完整版:名册 + 账号 + 安装向导 + 设置(宣纸主题)

这一版把「家」的地基铺完:

功能
- 安装向导 install.php:建四张表 → 建家庭 → 建第一人(兼管理员),装完自删;
  「是否已装」以数据库四张表为准,不以文件是否存在为准
- 家庭名册:成员增删改查、头像上传(居中裁方 512×512 转 JPEG、finfo 校验、
  随机文件名)、生日自动算年龄与倒数天数
- 敏感信息加密存储:手机号双写(SHA-256 哈希用于登录 + AES-256-CBC 密文用于显示)、
  身份证只存密文;页面上永远只显示脱敏后的 138****8000 / 前 6 后 4
- 账号体系:人与账号分离(孩子可入名册但无需密码)、开通/停用/角色、
  防爆破(5 次失败锁 60 秒)、修改密码、最后一个管理员不可移除
- 设置页:家庭名称与座右铭、加密密钥状态
- 宣纸主题 UI:砖红取自图标,扁平、留白充足;移动端顶栏收紧不换行

安全
- 所有 POST 走 CSRF;输出全量 e() 转义;uploads/ 禁执行脚本
- app/ 与 templates/ 加 .htaccess 整体拒绝直连(直接请求模板会 Fatal 并
  把服务器绝对路径打在页面上 —— 这是线上真实抓到过的问题)
- 已安装的 install.php 返回 404;display_errors 线上关闭

工程
- 无框架无 Composer,query-string 路由(index.php?r=模块/动作),不依赖 rewrite
- 静态资源带 mtime+size 版本号,改版后浏览器不会吃旧缓存
- 配套部署与冒烟(_tooling/,不入库):部署脚本容忍 tar 对非属主目录的
  元数据回填失败;冒烟断言「状态码 + 正文无 PHP 错误 + </html> 收尾 +
  无绝对路径泄露 + 断言总数下限」—— 只看状态码会把「200 但正文中间
  Fatal」当成通过,这一版在线上真实抓到过一次
This commit is contained in:
2026-09-30 00:49:53 +08:00
parent ecafa110f2
commit 8eb19267bc
30 changed files with 2462 additions and 123 deletions
+9
View File
@@ -0,0 +1,9 @@
# app/ 里的文件只会被 PHP include,绝不允许被 Web 直接请求。
# 一旦能被直接请求,缺上下文的执行会 Fatal,并把服务器绝对路径打到页面上(信息泄露)。
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* 登录账号。一个人最多一个账号,账号依附于「人」而存在。
*/
declare(strict_types=1);
namespace App;
final class Account
{
public static function findByPerson(int $personId): ?array
{
$st = Database::get()->prepare('SELECT * FROM accounts WHERE person_id = ?');
$st->execute([$personId]);
$row = $st->fetch();
return $row ?: null;
}
public static function create(int $personId, string $password, string $role = 'member'): int
{
$st = Database::get()->prepare(
'INSERT INTO accounts (person_id, password_hash, role) VALUES (?, ?, ?)'
);
$st->execute([$personId, password_hash($password, PASSWORD_DEFAULT), $role]);
return (int)Database::get()->lastInsertId();
}
public static function setPassword(int $accountId, string $password): void
{
Database::get()->prepare('UPDATE accounts SET password_hash = ? WHERE id = ?')
->execute([password_hash($password, PASSWORD_DEFAULT), $accountId]);
}
public static function setRole(int $accountId, string $role): void
{
Database::get()->prepare('UPDATE accounts SET role = ? WHERE id = ?')
->execute([$role, $accountId]);
}
public static function setStatus(int $accountId, string $status): void
{
Database::get()->prepare('UPDATE accounts SET status = ? WHERE id = ?')
->execute([$status, $accountId]);
}
/** 管理员不能被停用/降权 —— 否则全家人都会被锁在系统外面 */
public static function adminCount(): int
{
$st = Database::get()->prepare(
"SELECT COUNT(*) FROM accounts a
JOIN persons p ON p.id = a.person_id
WHERE a.role = 'admin' AND a.status = 'active'"
);
$st->execute();
return (int)$st->fetchColumn();
}
public static function validatePassword(string $password): array
{
$err = [];
if (strlen($password) < 8) {
$err[] = '密码至少 8 位';
}
if (!preg_match('/[0-9]/', $password) || !preg_match('/[A-Za-z]/', $password)) {
$err[] = '密码要同时包含字母和数字';
}
return $err;
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
/**
* 登录态与权限。
*
* 一个重要设计:**人(Person)≠ 账号(Account)**。
* 六岁的孩子应该出现在家庭名册、照片、活动参与人里,但不必有密码。
* 所以 person 可以先于 account 存在,将来再「开通账号」。
*/
declare(strict_types=1);
namespace App;
final class Auth
{
public static function check(): bool
{
return !empty($_SESSION['account_id']);
}
public static function id(): ?int
{
return isset($_SESSION['account_id']) ? (int)$_SESSION['account_id'] : null;
}
public static function personId(): ?int
{
return isset($_SESSION['person_id']) ? (int)$_SESSION['person_id'] : null;
}
public static function familyId(): ?int
{
return isset($_SESSION['family_id']) ? (int)$_SESSION['family_id'] : null;
}
public static function name(): string
{
return $_SESSION['name'] ?? '';
}
public static function isAdmin(): bool
{
return ($_SESSION['role'] ?? '') === 'admin';
}
/** 未登录跳登录页 */
public static function requireLogin(): void
{
if (!self::check()) {
redirect('auth/login');
}
}
public static function requireAdmin(): void
{
self::requireLogin();
if (!self::isAdmin()) {
http_response_code(403);
\App\View::render('error', [
'title' => '没有权限',
'message' => '这一页只有家庭管理员可以操作。',
], 'home');
exit;
}
}
/**
* 手机号 + 密码登录。
* 返回 true 表示成功并已写入会话。
*/
public static function login(string $phone, string $password): bool
{
// 简单节流:5 次失败后 60 秒内不再尝试。
// 防爆破的关键不在判定多严,而在于「尝试次数有成本」。
$fail = $_SESSION['login_fail'] ?? ['n' => 0, 't' => 0];
if ($fail['n'] >= 5 && (time() - $fail['t']) < 60) {
usleep(500000);
return false;
}
$hash = Crypto::hash($phone);
$stmt = Database::get()->prepare(
'SELECT a.id AS account_id, a.password_hash, a.role, a.status,
p.id AS person_id, p.family_id, p.name, p.avatar
FROM accounts a
JOIN persons p ON p.id = a.person_id
WHERE p.phone_hash = ? LIMIT 1'
);
$stmt->execute([$hash]);
$row = $stmt->fetch();
if (!$row || $row['status'] !== 'active'
|| !password_verify($password, (string)$row['password_hash'])) {
$_SESSION['login_fail'] = ['n' => $fail['n'] + 1, 't' => time()];
usleep(300000);
return false;
}
unset($_SESSION['login_fail']);
session_regenerate_id(true);
$_SESSION['account_id'] = (int)$row['account_id'];
$_SESSION['person_id'] = (int)$row['person_id'];
$_SESSION['family_id'] = (int)$row['family_id'];
$_SESSION['name'] = $row['name'];
$_SESSION['role'] = $row['role'];
$_SESSION['avatar'] = $row['avatar'];
Database::get()->prepare('UPDATE accounts SET last_login_at = NOW() WHERE id = ?')
->execute([$row['account_id']]);
return true;
}
public static function logout(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_destroy();
}
/** 头像改动后刷新会话里的缓存 */
public static function refreshAvatar(string $avatar): void
{
$_SESSION['avatar'] = $avatar;
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
/**
* 敏感字段加密。
*
* 身份证号、手机号这类个人信息,一律加密后再进库:
* - 加密用 AES-256-CBC,密钥 = sha256(app_key)(app_key 是 32 位十六进制,
* raw bytes 只有 16 字节,不够 256 位,所以必须再过一次 sha256)
* - 手机号另存一份 sha256 明文哈希,专门用于「登录时按手机号查找」
*
* ⚠️ app_key 换掉,已有数据就再解开不了 —— 见 README 的备份说明。
*/
declare(strict_types=1);
namespace App;
final class Crypto
{
private const CIPHER = 'aes-256-cbc';
private static function key(): string
{
$raw = $GLOBALS['config']['app_key'] ?? '';
if ($raw === '' || strpos($raw, '请填写') === 0) {
throw new \RuntimeException('config.php 里的 app_key 还没填写');
}
return hash('sha256', $raw, true);
}
public static function encrypt(string $plain): string
{
if ($plain === '') {
return '';
}
$iv = random_bytes(openssl_cipher_iv_length(self::CIPHER));
$raw = openssl_encrypt($plain, self::CIPHER, self::key(), OPENSSL_RAW_DATA, $iv);
if ($raw === false) {
throw new \RuntimeException('加密失败');
}
return base64_encode($iv . $raw);
}
/** 解密失败返回空串,不抛异常 —— 展示层宁可空白,也不让整页崩掉 */
public static function decrypt(string $blob): string
{
if ($blob === '') {
return '';
}
$data = base64_decode($blob, true);
if ($data === false) {
return '';
}
$len = openssl_cipher_iv_length(self::CIPHER);
if (strlen($data) <= $len) {
return '';
}
$iv = substr($data, 0, $len);
$raw = substr($data, $len);
$out = openssl_decrypt($raw, self::CIPHER, self::key(), OPENSSL_RAW_DATA, $iv);
return $out === false ? '' : $out;
}
/** 手机号 / 登录名查找用的哈希(确定性,不需要可逆) */
public static function hash(string $plain): string
{
return hash('sha256', self::normalizePhone($plain));
}
/** 去掉号码里的空格、横线、加号前缀,避免"138 0000 0000"和"13800000000"存成两个人 */
public static function normalizePhone(string $phone): string
{
$p = preg_replace('/[\s\-()]/', '', trim($phone));
return preg_replace('/^\+?86/', '', $p) === '' ? '' : preg_replace('/^\+?86/', '', $p);
}
/** 掩码显示:手机保留前 3 后 4,身份证保留前 6 后 4 */
public static function maskPhone(string $phone): string
{
$p = self::decrypt($phone);
if ($p === '') {
return '—';
}
$n = strlen($p);
return $n <= 7 ? substr($p, 0, 1) . str_repeat('*', max($n - 1, 0))
: substr($p, 0, 3) . '****' . substr($p, -4);
}
public static function maskIdCard(string $blob): string
{
$c = self::decrypt($blob);
if ($c === '') {
return '—';
}
$n = strlen($c);
if ($n <= 10) {
return str_repeat('*', $n);
}
return substr($c, 0, 6) . str_repeat('*', $n - 10) . substr($c, -4);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
/**
* 数据库:PDO 单例。
* 只依赖 config.php 里的 db 配置,方言差异集中在这里。
*/
declare(strict_types=1);
namespace App;
use PDO;
final class Database
{
/** @var PDO|null */
private static $pdo = null;
public static function get(): PDO
{
if (self::$pdo instanceof PDO) {
return self::$pdo;
}
$c = $GLOBALS['config']['db'];
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
$c['host'],
$c['port'],
$c['name'],
$c['charset']
);
self::$pdo = new PDO($dsn, $c['user'], $c['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
return self::$pdo;
}
/** 表是否存在(安装判定用,不依赖异常) */
public static function hasTables(): bool
{
try {
$st = self::get()->prepare(
'SELECT COUNT(*) FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name IN
(\'families\',\'persons\',\'accounts\',\'settings\')'
);
$st->execute();
return (int)$st->fetchColumn() === 4;
} catch (\Throwable $e) {
return false;
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* 家庭:数据空间的根,所有名册条目都挂在它下面。
*/
declare(strict_types=1);
namespace App;
final class Family
{
public static function find(int $id): ?array
{
$st = Database::get()->prepare('SELECT * FROM families WHERE id = ?');
$st->execute([$id]);
$row = $st->fetch();
return $row ?: null;
}
public static function create(string $name, string $motto = ''): int
{
$st = Database::get()->prepare('INSERT INTO families (name, motto) VALUES (?, ?)');
$st->execute([$name, $motto !== '' ? $motto : null]);
return (int)Database::get()->lastInsertId();
}
public static function update(int $id, string $name, string $motto = ''): void
{
$st = Database::get()->prepare('UPDATE families SET name = ?, motto = ? WHERE id = ?');
$st->execute([$name, $motto !== '' ? $motto : null, $id]);
}
public static function countMembers(int $familyId): int
{
$st = Database::get()->prepare(
"SELECT COUNT(*) FROM persons WHERE family_id = ? AND kind = 'member'"
);
$st->execute([$familyId]);
return (int)$st->fetchColumn();
}
}
+189
View File
@@ -0,0 +1,189 @@
<?php
/**
* 家庭名册(家庭成员 + 将来的外部联系人共用一张表)。
*
* 之所以不拆成两张表:两者字段几乎一样;而且需要互相转换 ——
* 一个「认识的人」随时可能变成家庭成员,一个家庭成员也可能只作为联系人存在。
*/
declare(strict_types=1);
namespace App;
final class Person
{
/** 名册列表(连带账号信息,用于显示「是否已开通登录」) */
public static function all(int $familyId, string $q = '', string $kind = 'member'): array
{
$sql = 'SELECT p.*, a.id AS account_id, a.role AS account_role, a.status AS account_status,
a.last_login_at
FROM persons p
LEFT JOIN accounts a ON a.person_id = p.id
WHERE p.family_id = ? AND p.kind = ?';
$args = [$familyId, $kind];
if ($q !== '') {
$sql .= ' AND (p.name LIKE ? OR p.nickname LIKE ? OR p.email LIKE ?)';
$like = '%' . $q . '%';
$args[] = $like;
$args[] = $like;
$args[] = $like;
}
$sql .= ' ORDER BY p.sort_order ASC, p.id ASC';
$st = Database::get()->prepare($sql);
$st->execute($args);
return $st->fetchAll();
}
public static function find(int $id): ?array
{
$st = Database::get()->prepare('SELECT * FROM persons WHERE id = ?');
$st->execute([$id]);
$row = $st->fetch();
return $row ?: null;
}
/** 带账号信息的详情(详情页用) */
public static function findWithAccount(int $id): ?array
{
$st = Database::get()->prepare(
'SELECT p.*, a.id AS account_id, a.role AS account_role,
a.status AS account_status, a.last_login_at
FROM persons p LEFT JOIN accounts a ON a.person_id = p.id
WHERE p.id = ?'
);
$st->execute([$id]);
$row = $st->fetch();
return $row ?: null;
}
public static function findByPhoneHash(string $hash): ?array
{
$st = Database::get()->prepare('SELECT * FROM persons WHERE phone_hash = ? LIMIT 1');
$st->execute([$hash]);
$row = $st->fetch();
return $row ?: null;
}
/**
* 新增。手机号是敏感字段,进来就加密 + 哈希。
* @return int 新 id
*/
public static function create(int $familyId, array $d): int
{
$phone = $d['phone'] ?? '';
$sql = 'INSERT INTO persons
(family_id, kind, name, nickname, gender, birthday, avatar,
phone_hash, phone_encrypted, id_card_encrypted, email, address, note, sort_order)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
$st = Database::get()->prepare($sql);
$st->execute([
$familyId,
$d['kind'] ?? 'member',
$d['name'],
$d['nickname'] !== '' ? $d['nickname'] : null,
$d['gender'] !== '' ? $d['gender'] : null,
$d['birthday'] !== '' ? $d['birthday'] : null,
$d['avatar'] !== '' ? $d['avatar'] : null,
$phone !== '' ? Crypto::hash($phone) : null,
$phone !== '' ? Crypto::encrypt($phone) : null,
($d['id_card'] ?? '') !== '' ? Crypto::encrypt($d['id_card']) : null,
$d['email'] !== '' ? $d['email'] : null,
$d['address'] !== '' ? $d['address'] : null,
$d['note'] !== '' ? $d['note'] : null,
(int)($d['sort_order'] ?? 1000),
]);
return (int)Database::get()->lastInsertId();
}
public static function update(int $id, array $d): void
{
$phone = $d['phone'] ?? '';
$sql = 'UPDATE persons SET
name = ?, nickname = ?, gender = ?, birthday = ?, avatar = ?,
phone_hash = ?, phone_encrypted = ?, id_card_encrypted = ?,
email = ?, address = ?, note = ?, sort_order = ?
WHERE id = ?';
Database::get()->prepare($sql)->execute([
$d['name'],
$d['nickname'] !== '' ? $d['nickname'] : null,
$d['gender'] !== '' ? $d['gender'] : null,
$d['birthday'] !== '' ? $d['birthday'] : null,
$d['avatar'] !== '' ? $d['avatar'] : null,
$phone !== '' ? Crypto::hash($phone) : null,
$phone !== '' ? Crypto::encrypt($phone) : null,
($d['id_card'] ?? '') !== '' ? Crypto::encrypt($d['id_card']) : null,
$d['email'] !== '' ? $d['email'] : null,
$d['address'] !== '' ? $d['address'] : null,
$d['note'] !== '' ? $d['note'] : null,
(int)($d['sort_order'] ?? 1000),
$id,
]);
}
/** 只改头像(上传后单独调用,避免整条记录被表单覆盖) */
public static function setAvatar(int $id, ?string $avatar): void
{
Database::get()->prepare('UPDATE persons SET avatar = ? WHERE id = ?')
->execute([$avatar, $id]);
}
public static function delete(int $id): void
{
Database::get()->prepare('DELETE FROM persons WHERE id = ?')->execute([$id]);
}
/**
* 最近要过生日的人(首页用)。
* 直接算「今天是今年的第几天」与生日的差值,跨年自动处理。
*/
public static function upcomingBirthdays(int $familyId, int $withinDays = 60): array
{
$st = Database::get()->prepare(
"SELECT id, name, avatar, birthday FROM persons
WHERE family_id = ? AND kind = 'member' AND birthday IS NOT NULL
ORDER BY DAYOFYEAR(birthday)"
);
$st->execute([$familyId]);
$rows = $st->fetchAll();
$out = [];
foreach ($rows as $r) {
$days = days_until_birthday($r['birthday']);
if ($days !== null && $days <= $withinDays) {
$r['days_left'] = $days;
$out[] = $r;
}
}
usort($out, function ($a, $b) {
return $a['days_left'] <=> $b['days_left'];
});
return $out;
}
/** 校验表单,返回错误数组(空数组表示通过) */
public static function validate(array $d): array
{
$err = [];
if (trim((string)($d['name'] ?? '')) === '') {
$err['name'] = '姓名不能为空';
}
$phone = trim((string)($d['phone'] ?? ''));
if ($phone !== '' && !preg_match('/^\+?[0-9\-]{6,20}$/', $phone)) {
$err['phone'] = '手机号格式看起来不对';
}
$email = trim((string)($d['email'] ?? ''));
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err['email'] = '邮箱格式看起来不对';
}
$b = trim((string)($d['birthday'] ?? ''));
if ($b !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $b)) {
$err['birthday'] = '生日请按 年-月-日 填写';
}
// 身份证号只做很松的校验:家庭场景里要不要存它,本来就值得三思
$idc = trim((string)($d['id_card'] ?? ''));
if ($idc !== '' && !preg_match('/^[0-9Xx]{15,18}$/', $idc)) {
$err['id_card'] = '身份证号应为 15 或 18 位';
}
return $err;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
/**
* 建表语句(安装向导与 tests 共用同一份)。
*
* 四条约定:
* 1. 全部 IF NOT EXISTS —— 重复执行不破坏已有数据
* 2. 字符集一律 utf8mb4_unicode_ci,emoji 与人名生僻字都不会乱码
* 3. 一切业务数据挂在 family_id 下,将来要支持多个家庭也不必改模型
* 4. 手机号存两份:phone_hash 用于登录查找(确定性哈希),phone_encrypted 用于展示
*/
declare(strict_types=1);
namespace App;
final class Schema
{
/** @return string[] */
public static function statements(): array
{
return [
<<<'SQL'
CREATE TABLE IF NOT EXISTS `families` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL COMMENT '家庭名称',
`motto` VARCHAR(200) DEFAULT NULL COMMENT '一句话,展示在首页',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭空间(一切数据的根)'
SQL,
<<<'SQL'
CREATE TABLE IF NOT EXISTS `persons` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`family_id` INT UNSIGNED NOT NULL,
`kind` ENUM('member','contact') NOT NULL DEFAULT 'member' COMMENT '家庭成员 / 外部联系人',
`name` VARCHAR(50) NOT NULL COMMENT '姓名',
`nickname` VARCHAR(50) DEFAULT NULL COMMENT '小名',
`gender` ENUM('m','f','x') DEFAULT NULL COMMENT '男 / 女 / 未填写',
`birthday` DATE DEFAULT NULL COMMENT '生日(自动生成日历上的生日日程用)',
`avatar` VARCHAR(255) DEFAULT NULL COMMENT '头像,相对于 uploads/avatars',
`phone_hash` CHAR(64) DEFAULT NULL COMMENT '手机号 sha256,登录查找用;NULL 不参与唯一约束',
`phone_encrypted` VARCHAR(512) DEFAULT NULL COMMENT 'AES 加密的手机号',
`id_card_encrypted` VARCHAR(512) DEFAULT NULL COMMENT 'AES 加密的身份证号',
`email` VARCHAR(120) DEFAULT NULL,
`address` VARCHAR(200) DEFAULT NULL,
`note` TEXT DEFAULT NULL COMMENT '备注',
`sort_order` INT NOT NULL DEFAULT 1000 COMMENT '名册排序,小的在前',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_phone_hash` (`phone_hash`),
KEY `idx_family_kind` (`family_id`, `kind`, `sort_order`),
CONSTRAINT `fk_persons_family` FOREIGN KEY (`family_id`) REFERENCES `families` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭名册'
SQL,
<<<'SQL'
CREATE TABLE IF NOT EXISTS `accounts` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`person_id` INT UNSIGNED NOT NULL COMMENT '一个人最多一个账号',
`password_hash` VARCHAR(255) NOT NULL,
`role` ENUM('admin','member') NOT NULL DEFAULT 'member' COMMENT '管理员 / 普通成员',
`status` ENUM('active','disabled') NOT NULL DEFAULT 'active',
`last_login_at` DATETIME DEFAULT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_account_person` (`person_id`),
CONSTRAINT `fk_accounts_person` FOREIGN KEY (`person_id`) REFERENCES `persons` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录账号'
SQL,
<<<'SQL'
CREATE TABLE IF NOT EXISTS `settings` (
`family_id` INT UNSIGNED NOT NULL,
`k` VARCHAR(64) NOT NULL,
`v` TEXT DEFAULT NULL,
PRIMARY KEY (`family_id`, `k`),
CONSTRAINT `fk_settings_family` FOREIGN KEY (`family_id`) REFERENCES `families` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭级键值对设置'
SQL,
];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
/**
* 家庭级键值对设置。
*/
declare(strict_types=1);
namespace App;
final class Setting
{
public static function get(int $familyId, string $key, $default = null)
{
$st = Database::get()->prepare('SELECT v FROM settings WHERE family_id = ? AND k = ?');
$st->execute([$familyId, $key]);
$v = $st->fetchColumn();
return $v === false ? $default : $v;
}
public static function set(int $familyId, string $key, string $value): void
{
$st = Database::get()->prepare(
'INSERT INTO settings (family_id, k, v) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE v = VALUES(v)'
);
$st->execute([$familyId, $key, $value]);
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
/**
* 头像上传:裁成正方形、缩到 512×512、转成 JPEG 落盘。
*
* 安全要点:
* - 用 finfo 判断真实 MIME,不信浏览器给的扩展名
* - 文件名随机,绝不使用用户提供的名字(防路径穿越与扩展名绕过)
* - 只写进 uploads/avatars/,该目录有 .htaccess 禁止执行脚本
*/
declare(strict_types=1);
namespace App;
final class Upload
{
private const MAX_BYTES = 5 * 1024 * 1024;
private const SIZE = 512;
/** @return array{ok:bool,file?:string,error?:string} */
public static function avatar(array $file): array
{
if (!isset($file['error']) || is_array($file['error'])) {
return ['ok' => false, 'error' => '上传参数不对'];
}
switch ($file['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
return ['ok' => false, 'error' => ''];
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
return ['ok' => false, 'error' => '图片太大了(上限 5MB)'];
default:
return ['ok' => false, 'error' => '上传失败(错误码 ' . (int)$file['error'] . ')'];
}
if ($file['size'] > self::MAX_BYTES) {
return ['ok' => false, 'error' => '图片太大了(上限 5MB)'];
}
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allow = ['image/jpeg' => 'imagecreatefromjpeg', 'image/png' => 'imagecreatefrompng',
'image/gif' => 'imagecreatefromgif', 'image/webp' => 'imagecreatefromwebp'];
if (!isset($allow[$mime])) {
return ['ok' => false, 'error' => '只支持 JPG / PNG / GIF / WebP 图片'];
}
$src = $allow[$mime]($file['tmp_name']);
if (!$src) {
return ['ok' => false, 'error' => '图片读不出来'];
}
$w = imagesx($src);
$h = imagesy($src);
// 居中裁成正方形
$side = min($w, $h);
$sx = (int)(($w - $side) / 2);
$sy = (int)(($h - $side) / 2);
$canvas = imagecreatetruecolor(self::SIZE, self::SIZE);
// PNG/GIF 的透明区转成纸白,不然头像会是黑底
$bg = imagecolorallocate($canvas, 253, 251, 245);
imagefilledrectangle($canvas, 0, 0, self::SIZE, self::SIZE, $bg);
imagecopyresampled($canvas, $src, 0, 0, $sx, $sy, self::SIZE, self::SIZE, $side, $side);
$dir = FB_UPLOADS . '/avatars';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$name = bin2hex(random_bytes(12)) . '.jpg';
if (!imagejpeg($canvas, $dir . '/' . $name, 88)) {
imagedestroy($canvas);
imagedestroy($src);
return ['ok' => false, 'error' => '保存失败'];
}
imagedestroy($canvas);
imagedestroy($src);
return ['ok' => true, 'file' => 'avatars/' . $name];
}
/** 头像访问地址(无头像时回退到内置剪影,保证永远不出现破图) */
public static function avatarUrl(?string $rel): string
{
if ($rel && is_file(FB_UPLOADS . '/' . $rel)) {
$p = FB_UPLOADS . '/' . $rel;
// 注意:filemtime() 返回 int,本文件开了 strict_types,直接喂给 md5() 会 TypeError
return 'uploads/' . $rel . '?v=' . substr(md5(filemtime($p) . filesize($p)), 0, 8);
}
return asset('/assets/avatar-default.svg');
}
public static function remove(?string $rel): void
{
if (!$rel) {
return;
}
$p = FB_UPLOADS . '/' . $rel;
if (is_file($p)) {
@unlink($p);
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/**
* 视图渲染。
*
* 流程:render() 把数据展开 → 把「本页模板文件路径 / 当前页标识 / 标题」交给
* layout.php → layout 在正文位置 require 本页模板。
*/
declare(strict_types=1);
namespace App;
final class View
{
public static function render(string $tpl, array $data = [], string $page = ''): void
{
$file = dirname(__DIR__) . '/templates/' . $tpl . '.php';
if (!is_file($file)) {
throw new \RuntimeException('模板不存在:' . $tpl);
}
$tplFile = $file;
$pageKey = $page ?: $tpl;
$pageTitle = $data['title'] ?? '家书';
$extraHead = $data['extraHead'] ?? '';
extract($data, EXTR_SKIP);
require dirname(__DIR__) . '/templates/layout.php';
}
/** 独立的整页(登录、安装、错误),不套顶栏 */
public static function renderBare(string $tpl, array $data = []): void
{
$file = dirname(__DIR__) . '/templates/' . $tpl . '.php';
if (!is_file($file)) {
throw new \RuntimeException('模板不存在:' . $tpl);
}
$pageTitle = $data['title'] ?? '家书';
extract($data, EXTR_SKIP);
require $file;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* 应用引导:配置加载、会话、自动加载、全局辅助函数。
* 每个页面/入口只需 require 这一个文件。
*/
declare(strict_types=1);
// ---------------- 自动加载(避免「新增类忘了 require」这类事故)----------------
spl_autoload_register(function ($class) {
if (strpos($class, 'App\\') !== 0) {
return;
}
$rel = str_replace('\\', '/', substr($class, 4));
$file = __DIR__ . '/' . $rel . '.php';
if (is_file($file)) {
require $file;
}
});
define('FB_ROOT', dirname(__DIR__));
define('FB_APP', __DIR__);
define('FB_UPLOADS', FB_ROOT . '/uploads');
// ---------------- 配置 ----------------
$configFile = FB_ROOT . '/config.php';
if (!is_file($configFile)) {
http_response_code(500);
echo '<!doctype html><meta charset="utf-8"><title>家书 · 未配置</title>'
. '<div style="max-width:520px;margin:12vh auto;padding:28px 32px;'
. 'background:#fff;border:1px solid rgba(47,36,30,.1);border-radius:16px;'
. 'font:15px/1.8 -apple-system,\'PingFang SC\',\'Microsoft YaHei\',sans-serif;color:#2F241E">'
. '<h1 style="font-size:18px;margin:0 0 12px">还差一步:没有找到 config.php</h1>'
. '<p style="color:#7C6A5B;margin:0 0 16px">'
. '请复制同目录下的 <code>config.example.php</code> 为 <code>config.php</code>,'
. '填好数据库连接与 app_key 后再访问。</p>'
. '</div>';
exit;
}
$GLOBALS['config'] = require $configFile;
// ---------------- 错误报告(线上不显示错误,避免泄露路径与库信息)----------------
$debug = !empty($GLOBALS['config']['debug']);
error_reporting(E_ALL);
ini_set('display_errors', $debug ? '1' : '0');
ini_set('log_errors', '1');
// ---------------- 时区:日期是家书的核心数据,一开始就必须明确 ----------------
date_default_timezone_set($GLOBALS['config']['timezone'] ?? 'Asia/Shanghai');
// ---------------- 会话 ----------------
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
session_name('fbsid');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => $isHttps,
'httponly' => true,
'samesite' => 'Lax',
]);
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
require FB_APP . '/helpers.php';
+139
View File
@@ -0,0 +1,139 @@
<?php
/**
* 全局辅助函数(由 bootstrap.php 引入,页面无需重复 require)
*/
declare(strict_types=1);
/** HTML 转义:所有输出到页面的动态值都必须过一道 */
function e($value): string
{
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}
/** 静态资源地址,带版本号(mtime + size)——没版本号的话浏览器会一直用旧缓存 */
function asset(string $rel): string
{
$p = dirname(__DIR__) . $rel;
if (!is_file($p)) {
return $rel;
}
return $rel . '?v=' . substr(md5(filemtime($p) . filesize($p)), 0, 8);
}
/** 站内链接(统一走 query-string 路由,不依赖 Apache 重写) */
function url(string $route = 'home', array $query = []): string
{
$q = array_merge(['r' => $route], $query);
return 'index.php?' . http_build_query($q);
}
function redirect(string $route = 'home', array $query = []): void
{
header('Location: ' . url($route, $query));
exit;
}
function is_post(): bool
{
return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
}
function fb_config(string $key = null, $default = null)
{
$c = $GLOBALS['config'];
if ($key === null) {
return $c;
}
return array_key_exists($key, $c) ? $c[$key] : $default;
}
// ---------------- CSRF ----------------
function csrf_token(): string
{
if (empty($_SESSION['_csrf'])) {
$_SESSION['_csrf'] = bin2hex(random_bytes(16));
}
return $_SESSION['_csrf'];
}
function csrf_field(): string
{
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
}
/**
* 校验 CSRF。失败直接结束请求 —— 不做这种假返回:
* 「返回 false 让调用层自己处理」的写法,迟早有人忘了判断。
*/
function csrf_check(): void
{
$ok = isset($_POST['_csrf'], $_SESSION['_csrf'])
&& hash_equals($_SESSION['_csrf'], (string)$_POST['_csrf']);
if (!$ok) {
http_response_code(419);
echo '页面已过期,请刷新后重试(CSRF 校验失败)';
exit;
}
}
// ---------------- 一次性提示 ----------------
function flash(string $type, string $message): void
{
$_SESSION['_flash'][] = ['type' => $type, 'message' => $message];
}
function take_flash(): array
{
$f = $_SESSION['_flash'] ?? [];
unset($_SESSION['_flash']);
return $f;
}
/** 表单回填(校验失败时保留用户输入) */
function old(string $key, $default = '')
{
return $_SESSION['_old'][$key] ?? $default;
}
function set_old(array $data): void
{
$_SESSION['_old'] = $data;
}
function clear_old(): void
{
unset($_SESSION['_old']);
}
/** 生日相关:返回年龄与距下次生日天数 */
function age_from(string $birthday): ?int
{
if ($birthday === '' || $birthday === null) {
return null;
}
try {
$b = new DateTimeImmutable($birthday);
} catch (Exception $ex) {
return null;
}
return (int)$b->diff(new DateTimeImmutable('today'))->y;
}
function days_until_birthday(string $birthday): ?int
{
if (!$birthday) {
return null;
}
try {
$b = new DateTimeImmutable($birthday);
$now = new DateTimeImmutable('today');
$next = new DateTimeImmutable($now->format('Y') . '-' . $b->format('m-d'));
if ($next < $now) {
$next = $next->modify('+1 year');
}
return (int)$now->diff($next)->days;
} catch (Exception $ex) {
return null;
}
}
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="默认头像">
<rect width="64" height="64" fill="#F1E7D6"/>
<circle cx="32" cy="24" r="11" fill="#D8C4AC"/>
<path d="M32 38c-11 0-20 7-21 17v9h42v-9c-1-10-10-17-21-17z" fill="#D8C4AC"/>
</svg>

After

Width:  |  Height:  |  Size: 283 B

+269
View File
@@ -0,0 +1,269 @@
/* ============================================================
家书 FamilyBook · 界面样式
配色取自图标:宣纸米 / 砖红封面 / 深褐书脊 / 纸白
原则:扁平、留白充足、字重克制(正文 400,标题 500-600)
============================================================ */
:root {
--paper: #F7F3EA;
--surface: #FFFFFF;
--ink: #2C231D;
--muted: #7E6B5A;
--faint: #A8988A;
--brand: #A84A28;
--brand-2: #C96F45;
--brand-ink:#6E3820;
--green: #6F9E5C;
--red: #C0533F;
--line: rgba(44, 35, 29, .10);
--line-2: rgba(44, 35, 29, .06);
--radius: 16px;
--radius-s: 10px;
--shadow: 0 1px 2px rgba(44, 35, 29, .05);
--shadow-l: 0 4px 16px rgba(44, 35, 29, .08);
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background: var(--paper);
color: var(--ink);
font: 15px/1.7 -apple-system, BlinkMacSystemFont, "PingFang SC",
"Microsoft YaHei", "Hiragino Sans GB", sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: var(--brand); text-decoration: none; }
a:hover { text-decoration: underline; }
/* ---------------- 顶栏 ---------------- */
.topbar {
position: sticky; top: 0; z-index: 20;
background: var(--surface);
border-bottom: 1px solid var(--line);
}
.topbar-inner {
max-width: 1080px; margin: 0 auto; padding: 0 24px;
height: 60px; display: flex; align-items: center; gap: 24px;
}
.brand { display: flex; align-items: center; gap: 10px; color: var(--ink); }
.brand:hover { text-decoration: none; }
.brand img { width: 30px; height: 30px; border-radius: 8px; display: block; }
.brand span { font-size: 16px; font-weight: 600; letter-spacing: .5px; }
.nav { display: flex; gap: 4px; margin-left: 8px; }
.nav a {
padding: 6px 12px; border-radius: 999px; color: var(--muted);
font-size: 14px;
}
.nav a:hover { background: var(--line-2); text-decoration: none; }
.nav a.on { background: var(--brand); color: #fff; }
.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 12px; }
.who { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 14px; }
.who img { width: 30px; height: 30px; border-radius: 50%; object-fit: cover; }
.link-quiet { color: var(--muted); font-size: 14px; }
.link-quiet:hover { color: var(--brand); }
/* 顶栏里的文字一律不许换行 —— 一换行就是「首/页」「名/册」竖排,很难看 */
.nav a, .topbar-right a, .who-name { white-space: nowrap; }
/* ---------------- 布局 ---------------- */
.container { max-width: 1080px; margin: 0 auto; padding: 28px 24px 64px; }
.container-narrow { max-width: 560px; margin: 0 auto; padding: 28px 24px 64px; }
.page-head { display: flex; align-items: flex-end; gap: 16px; margin-bottom: 20px; }
.page-head h1 { font-size: 22px; font-weight: 600; margin: 0; }
.page-head .sub { color: var(--muted); font-size: 14px; }
.page-head .actions { margin-left: auto; display: flex; gap: 8px; }
.section { margin-top: 28px; }
.section-title {
display: flex; align-items: center; gap: 10px;
font-size: 15px; font-weight: 600; margin: 0 0 12px;
}
.section-title .hint { font-weight: 400; color: var(--muted); font-size: 13px; }
/* ---------------- 卡片 ---------------- */
.card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
.card-pad { padding: 20px; }
/* 首页头图 */
.hero {
background: var(--surface); border: 1px solid var(--line);
border-radius: var(--radius); box-shadow: var(--shadow);
padding: 26px 28px;
display: flex; align-items: center; gap: 20px; flex-wrap: wrap;
}
.hero-logo { width: 64px; height: 64px; border-radius: 16px; flex: 0 0 auto; }
.hero h1 { font-size: 24px; font-weight: 600; margin: 0 0 4px; }
.hero .motto { color: var(--muted); margin: 0; font-size: 14px; }
.hero-stats { margin-left: auto; display: flex; gap: 28px; }
.stat { text-align: center; }
.stat b { display: block; font-size: 24px; font-weight: 600; line-height: 1.2; }
.stat span { font-size: 12px; color: var(--muted); }
/* ---------------- 成员卡 ---------------- */
.people-grid {
display: grid; gap: 16px; margin-top: 4px;
grid-template-columns: repeat(auto-fill, minmax(168px, 1fr));
}
.person {
display: block; color: var(--ink);
background: var(--surface); border: 1px solid var(--line);
border-radius: var(--radius); overflow: hidden;
box-shadow: var(--shadow);
transition: transform .15s ease, box-shadow .15s ease;
}
.person:hover { transform: translateY(-2px); box-shadow: var(--shadow-l); text-decoration: none; }
.person .ph {
background: #F1E7D6; aspect-ratio: 1 / 1; overflow: hidden;
}
.person .ph img { width: 100%; height: 100%; object-fit: cover; display: block; }
.person .pb { padding: 12px 14px 14px; }
.person .pname { font-weight: 600; font-size: 15px; display: flex; align-items: center; gap: 6px; }
.person .pmeta { color: var(--muted); font-size: 13px; margin-top: 2px; }
.badge {
display: inline-block; padding: 1px 8px; border-radius: 999px;
font-size: 11px; font-weight: 500; line-height: 1.7;
background: var(--line-2); color: var(--muted);
}
.badge-admin { background: #F6E3D7; color: var(--brand-ink); }
.badge-open { background: #E6F0DC; color: #4A7226; }
/* 生日条 */
.bdays { display: flex; gap: 12px; flex-wrap: wrap; }
.bday {
display: flex; align-items: center; gap: 10px;
background: var(--surface); border: 1px solid var(--line);
border-radius: 999px; padding: 6px 16px 6px 6px; box-shadow: var(--shadow);
}
.bday img { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; }
.bday b { font-weight: 500; }
.bday .d { color: var(--brand); font-size: 13px; }
/* ---------------- 表单 ---------------- */
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.field.full { grid-column: 1 / -1; }
.field label { font-size: 13px; color: var(--muted); font-weight: 500; }
.field .tip { font-size: 12px; color: var(--muted); }
.input, .select, textarea.input {
width: 100%; padding: 10px 12px; font: inherit; font-size: 14px;
color: var(--ink); background: #fff;
border: 1px solid var(--line); border-radius: var(--radius-s);
transition: border-color .15s ease, box-shadow .15s ease;
}
.input:focus, .select:focus, textarea.input:focus {
outline: none; border-color: var(--brand);
box-shadow: 0 0 0 3px rgba(168, 74, 40, .12);
}
textarea.input { min-height: 76px; resize: vertical; }
.err { color: var(--red); font-size: 12px; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
padding: 9px 16px; font: inherit; font-size: 14px; font-weight: 500;
border-radius: var(--radius-s); border: 1px solid transparent; cursor: pointer;
background: var(--brand); color: #fff; transition: background .15s ease;
}
.btn:hover { background: #944022; text-decoration: none; }
.btn-ghost { background: #fff; color: var(--ink); border-color: var(--line); }
.btn-ghost:hover { background: #FAF7F1; }
.btn-danger { background: #fff; color: var(--red); border-color: rgba(192,83,63,.35); }
.btn-danger:hover { background: #FDF1EE; }
.btn-sm { padding: 5px 12px; font-size: 13px; }
.btn-row { display: flex; gap: 10px; margin-top: 20px; }
/* ---------------- 详情 ---------------- */
.detail { display: grid; grid-template-columns: 260px 1fr; gap: 24px; }
.detail-photo {
background: var(--surface); border: 1px solid var(--line);
border-radius: var(--radius); padding: 16px; text-align: center;
box-shadow: var(--shadow);
}
.detail-photo img {
width: 100%; aspect-ratio: 1/1; object-fit: cover;
border-radius: 12px; display: block;
}
.detail-photo .name { font-size: 18px; font-weight: 600; margin: 14px 0 4px; }
.detail-photo .sub { color: var(--muted); font-size: 13px; }
.kv { display: flex; flex-direction: column; }
.kv-row {
display: grid; grid-template-columns: 96px 1fr; gap: 12px;
padding: 12px 0; border-bottom: 1px solid var(--line-2);
}
.kv-row:last-child { border-bottom: 0; }
.kv-row dt { color: var(--muted); font-size: 13px; }
.kv-row dd { margin: 0; font-size: 14px; word-break: break-all; }
.mono { font-family: ui-monospace, "SFMono-Regular", Consolas, monospace; letter-spacing: .5px; }
/* ---------------- 提示 ---------------- */
.flash { display: flex; flex-direction: column; gap: 8px; margin-bottom: 18px; }
.flash-item {
padding: 10px 14px; border-radius: var(--radius-s); font-size: 14px;
background: #E6F0DC; color: #3D6B1F;
}
.flash-item.err { background: #F8DDDA; color: #A1341F; }
.empty {
background: var(--surface); border: 1px dashed var(--line);
border-radius: var(--radius); padding: 40px 20px; text-align: center;
color: var(--muted);
}
.empty b { display: block; color: var(--ink); font-weight: 500; margin-bottom: 4px; }
/* ---------------- 登录 / 安装 ---------------- */
.auth-wrap {
min-height: 100vh; display: flex; align-items: center; justify-content: center;
padding: 40px 20px;
}
.auth-card {
width: 100%; max-width: 400px; background: var(--surface);
border: 1px solid var(--line); border-radius: 20px; box-shadow: var(--shadow-l);
padding: 32px;
}
.auth-card .logo { width: 56px; height: 56px; border-radius: 14px; margin-bottom: 14px; }
.auth-card h1 { font-size: 20px; font-weight: 600; margin: 0 0 4px; }
.auth-card .lead { color: var(--muted); font-size: 14px; margin: 0 0 24px; }
.auth-card .btn { width: 100%; margin-top: 20px; }
.auth-foot { margin-top: 18px; font-size: 13px; color: var(--muted); text-align: center; }
/* ---------------- 其他 ---------------- */
.muted { color: var(--muted); }
.small { font-size: 13px; }
.nowrap { white-space: nowrap; }
.search { display: flex; gap: 8px; margin-bottom: 16px; }
.search .input { max-width: 260px; }
@media (max-width: 720px) {
/* 390px 宽度放不下整套顶栏:只留 图标 + 导航 + 头像 + 退出 */
.topbar-inner { gap: 8px; padding: 0 12px; height: 54px; }
.brand img { width: 26px; height: 26px; }
.nav { gap: 0; }
.nav a { padding: 6px 9px; font-size: 14px; }
.topbar-right { gap: 8px; }
.who-name, .who-pwd { display: none; } /* 名字与「改密码」收起,设置页里都有 */
.who img { width: 26px; height: 26px; }
.container, .container-narrow { padding: 20px 16px 48px; }
.form-grid { grid-template-columns: 1fr; }
.detail { grid-template-columns: 1fr; }
.hero { padding: 20px; gap: 14px; }
.hero h1 { font-size: 20px; }
.hero-stats { margin-left: 0; gap: 20px; }
.page-head { flex-wrap: wrap; align-items: center; }
.page-head .actions { margin-left: 0; width: 100%; }
.kv-row { grid-template-columns: 84px 1fr; }
.search { flex-wrap: wrap; }
.search .input { max-width: none; flex: 1 1 auto; }
}
+27
View File
@@ -0,0 +1,27 @@
/* 家书 · 前端小助手(无框架,无构建步骤) */
(function () {
'use strict';
// 头像选好后即时预览,别等上传完才知道选错了
var fileInput = document.getElementById('avatar');
if (fileInput && window.FileReader) {
fileInput.addEventListener('change', function () {
var f = this.files && this.files[0];
if (!f) { return; }
var img = document.getElementById('avatar-preview');
if (!img) { return; }
var reader = new FileReader();
reader.onload = function (ev) { img.src = ev.target.result; };
reader.readAsDataURL(f);
});
}
// 头像加载失败时换回内置剪影 —— 保证任何时候都不会出现破图
Array.prototype.forEach.call(document.querySelectorAll('img'), function (img) {
img.addEventListener('error', function () {
if (img.dataset.fallbackDone) { return; }
img.dataset.fallbackDone = '1';
img.src = '/assets/avatar-default.svg';
});
});
})();
+397 -128
View File
@@ -1,141 +1,410 @@
<?php
/**
* FamilyBook · 家书 —— 阶段 0 引导页
* 家书 FamilyBook · 前端控制器
*
* 这一页不是首页。它的职责是:部署之后先看这里,确认
* 「PHP 版本 / 扩展 / 配置文件 / 数据库连接」四件事都通了,再往上盖功能。
* 正式首页做好之后会替换掉它。
*
* ⚠️ 线上请把 config.php 里的 debug 设为 false:
* 连接报错时,详情里可能含数据库账号名,不该公开展示。
* 路由走 query-string(index.php?r=模块/动作),不依赖 Apache 重写,
* 换服务器、换 Nginx 都不用改配置。
*/
declare(strict_types=1);
define('FB_ROOT', __DIR__);
require __DIR__ . '/app/bootstrap.php';
$configFile = FB_ROOT . '/config.php';
$hasConfig = is_file($configFile);
$config = $hasConfig ? require $configFile : null;
$debug = is_array($config) && !empty($config['debug']);
use App\Account;
use App\Auth;
use App\Crypto;
use App\Database;
use App\Family;
use App\Person;
use App\Setting;
use App\Upload;
use App\View;
/**
* 静态资源带版本号(mtime + size)。
* 不带版本号的话,文件换了浏览器还在用旧缓存 —— 详见踩坑记录。
*/
function fb_asset(string $rel): string
{
$p = FB_ROOT . $rel;
if (!is_file($p)) {
return $rel;
if (!Database::hasTables()) {
header('Location: install.php');
exit;
}
$r = isset($_GET['r']) ? trim((string)$_GET['r'], '/') : 'home';
$r = $r === '' ? 'home' : $r;
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$publicRoutes = ['auth/login'];
if (!Auth::check() && !in_array($r, $publicRoutes, true)) {
redirect('auth/login');
}
switch ($r) {
// ==================== 登录 / 退出 ====================
case 'auth/login':
if (Auth::check()) {
redirect('home');
}
return $rel . '?v=' . substr(md5(filemtime($p) . filesize($p)), 0, 8);
}
$checks = [];
// 1. PHP 版本:以 PHP 7.4 为底线(线上同时存在 7.4 与 8.1 两套)
$checks['PHP 版本'] = [
'ok' => PHP_VERSION_ID >= 70400,
'val' => PHP_VERSION . '(需 7.4 以上)',
];
// 2. 必需扩展
$needExt = ['pdo_mysql' => '数据库', 'mbstring' => '中文处理', 'openssl' => '敏感字段加密', 'json' => '配置与接口', 'gd' => '图片裁剪'];
foreach ($needExt as $ext => $why) {
$ok = extension_loaded($ext);
$checks['扩展 ' . $ext] = ['ok' => $ok, 'val' => $ok ? '已加载 · ' . $why : '缺失 · ' . $why];
}
// 3. 配置文件
$checks['配置文件 config.php'] = [
'ok' => $hasConfig,
'val' => $hasConfig ? '已就位' : '未找到(请复制 config.example.php 后填写)',
];
// 4. 数据库连接(只有配置齐全才去连)
if (is_array($config) && !empty($config['db'])) {
$d = $config['db'];
try {
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
$d['host'], $d['port'], $d['name'], $d['charset']
);
$pdo = new PDO($dsn, $d['user'], $d['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
if ($method === 'POST') {
csrf_check();
$phone = trim((string)($_POST['phone'] ?? ''));
$pass = (string)($_POST['password'] ?? '');
if (Auth::login($phone, $pass)) {
redirect('home');
}
View::renderBare('login', [
'title' => '登录',
'familyName' => fb_config('site_name', '家书'),
'error' => '手机号或密码不对,或者账号还没开通/已被停用。',
'phone' => $phone,
]);
$ver = $pdo->query('SELECT VERSION()')->fetchColumn();
$checks['数据库连接'] = ['ok' => true, 'val' => 'MySQL ' . $ver . ' · 库 ' . $d['name']];
} catch (Throwable $e) {
$checks['数据库连接'] = [
'ok' => false,
'val' => $debug ? $e->getMessage() : '连接失败(把 config.php 的 debug 设为 true 可看详情)',
];
exit;
}
View::renderBare('login', [
'title' => '登录',
'familyName' => fb_config('site_name', '家书'),
]);
break;
case 'auth/logout':
if (isset($_GET['_csrf'], $_SESSION['_csrf'])
&& hash_equals($_SESSION['_csrf'], (string)$_GET['_csrf'])) {
Auth::logout();
}
redirect('auth/login');
break;
case 'auth/password':
Auth::requireLogin();
if ($method === 'POST') {
csrf_check();
$old = (string)($_POST['old_password'] ?? '');
$new = (string)($_POST['password'] ?? '');
$new2 = (string)($_POST['password2'] ?? '');
$st = Database::get()->prepare('SELECT password_hash FROM accounts WHERE id = ?');
$st->execute([Auth::id()]);
$hash = (string)$st->fetchColumn();
$err = null;
if (!password_verify($old, $hash)) {
$err = '当前密码不对';
} elseif ($new !== $new2) {
$err = '两次输入的新密码不一致';
} elseif (Account::validatePassword($new)) {
$err = implode(';', Account::validatePassword($new));
}
if ($err) {
View::render('auth/password', ['title' => '修改密码', 'error' => $err], 'home');
exit;
}
Account::setPassword((int)Auth::id(), $new);
flash('ok', '密码已更新,下次登录用新密码。');
redirect('home');
}
View::render('auth/password', ['title' => '修改密码'], 'home');
break;
// ==================== 首页 ====================
case 'home':
$familyId = (int)Auth::familyId();
View::render('home', [
'title' => '首页',
'family' => Family::find($familyId),
'people' => Person::all($familyId),
'birthdays' => Person::upcomingBirthdays($familyId),
], 'home');
break;
// ==================== 名册 ====================
case 'people':
$q = trim((string)($_GET['q'] ?? ''));
View::render('people/index', [
'title' => '家庭名册',
'people' => Person::all((int)Auth::familyId(), $q),
'q' => $q,
], 'people');
break;
case 'people/new':
Auth::requireAdmin();
clear_old();
View::render('people/form', [
'title' => '添加成员',
'person' => null,
'errors' => [],
], 'people');
break;
case 'people/create':
Auth::requireAdmin();
csrf_check();
$d = [
'name' => trim((string)($_POST['name'] ?? '')),
'nickname' => trim((string)($_POST['nickname'] ?? '')),
'gender' => (string)($_POST['gender'] ?? ''),
'birthday' => trim((string)($_POST['birthday'] ?? '')),
'phone' => trim((string)($_POST['phone'] ?? '')),
'id_card' => trim((string)($_POST['id_card'] ?? '')),
'email' => trim((string)($_POST['email'] ?? '')),
'address' => trim((string)($_POST['address'] ?? '')),
'note' => trim((string)($_POST['note'] ?? '')),
'sort_order'=> (int)($_POST['sort_order'] ?? 1000),
'avatar' => '',
'kind' => 'member',
];
$errors = Person::validate($d);
$up = Upload::avatar($_FILES['avatar'] ?? []);
if (!$up['ok'] && ($up['error'] ?? '') !== '') {
$errors['avatar'] = $up['error'];
}
if ($errors) {
set_old($_POST);
View::render('people/form', [
'title' => '添加成员',
'person' => null,
'errors' => $errors,
'phoneValue' => $d['phone'],
'idCardValue'=> $d['id_card'],
], 'people');
exit;
}
if ($up['ok']) {
$d['avatar'] = $up['file'];
}
try {
$id = Person::create((int)Auth::familyId(), $d);
} catch (\PDOException $ex) {
set_old($_POST);
View::render('people/form', [
'title' => '添加成员',
'person' => null,
'errors' => ['phone' => '这个手机号已经在名册里了'],
'phoneValue' => $d['phone'],
'idCardValue'=> $d['id_card'],
], 'people');
exit;
}
clear_old();
flash('ok', '已把「' . $d['name'] . '」加进名册。');
redirect('people/show', ['id' => $id]);
break;
case 'people/edit':
Auth::requireAdmin();
$p = Person::find((int)($_GET['id'] ?? 0));
if (!$p || (int)$p['family_id'] !== (int)Auth::familyId()) {
flash('err', '找不到这个人。');
redirect('people');
}
clear_old();
View::render('people/form', [
'title' => '编辑成员',
'person' => $p,
'errors' => [],
'phoneValue' => Crypto::decrypt((string)$p['phone_encrypted']),
'idCardValue' => Crypto::decrypt((string)$p['id_card_encrypted']),
], 'people');
break;
case 'people/update':
Auth::requireAdmin();
csrf_check();
$id = (int)($_POST['id'] ?? 0);
$p = Person::find($id);
if (!$p || (int)$p['family_id'] !== (int)Auth::familyId()) {
flash('err', '找不到这个人。');
redirect('people');
}
$d = [
'name' => trim((string)($_POST['name'] ?? '')),
'nickname' => trim((string)($_POST['nickname'] ?? '')),
'gender' => (string)($_POST['gender'] ?? ''),
'birthday' => trim((string)($_POST['birthday'] ?? '')),
'phone' => trim((string)($_POST['phone'] ?? '')),
'id_card' => trim((string)($_POST['id_card'] ?? '')),
'email' => trim((string)($_POST['email'] ?? '')),
'address' => trim((string)($_POST['address'] ?? '')),
'note' => trim((string)($_POST['note'] ?? '')),
'sort_order'=> (int)($_POST['sort_order'] ?? 1000),
'avatar' => (string)$p['avatar'],
];
$errors = Person::validate($d);
$up = Upload::avatar($_FILES['avatar'] ?? []);
if (!$up['ok'] && ($up['error'] ?? '') !== '') {
$errors['avatar'] = $up['error'];
}
if ($errors) {
set_old($_POST);
View::render('people/form', [
'title' => '编辑成员',
'person' => $p,
'errors' => $errors,
'phoneValue' => $d['phone'],
'idCardValue' => $d['id_card'],
], 'people');
exit;
}
if ($up['ok']) {
Upload::remove((string)$p['avatar']);
$d['avatar'] = $up['file'];
}
try {
Person::update($id, $d);
} catch (\PDOException $ex) {
set_old($_POST);
View::render('people/form', [
'title' => '编辑成员',
'person' => $p,
'errors' => ['phone' => '这个手机号已经被名册里的另一个人用了'],
'phoneValue' => $d['phone'],
'idCardValue' => $d['id_card'],
], 'people');
exit;
}
if ((int)$p['id'] === (int)Auth::personId()) {
Auth::refreshAvatar((string)$d['avatar']);
}
clear_old();
flash('ok', '已保存。');
redirect('people/show', ['id' => $id]);
break;
case 'people/show':
$p = Person::findWithAccount((int)($_GET['id'] ?? 0));
if (!$p || (int)$p['family_id'] !== (int)Auth::familyId()) {
flash('err', '找不到这个人。');
redirect('people');
}
View::render('people/show', [
'title' => $p['name'],
'person' => $p,
], 'people');
break;
case 'people/destroy':
Auth::requireAdmin();
csrf_check();
$id = (int)($_POST['id'] ?? 0);
$p = Person::find($id);
if ($p && (int)$p['family_id'] === (int)Auth::familyId()) {
if ((int)$p['id'] === (int)Auth::personId()) {
flash('err', '不能把自己从名册里移除。');
redirect('people/show', ['id' => $id]);
}
// 不让最后一个管理员消失:系统里没人能管理家庭就锁死了
$acc = Account::findByPerson($id);
if ($acc && $acc['role'] === 'admin' && Account::adminCount() <= 1) {
flash('err', '这是唯一的管理员,先把另一个人设为管理员再移除。');
redirect('people/show', ['id' => $id]);
}
Upload::remove((string)$p['avatar']);
Person::delete($id);
flash('ok', '已从名册移除「' . $p['name'] . '」。');
}
redirect('people');
break;
// ==================== 账号 ====================
case 'accounts/create':
Auth::requireAdmin();
csrf_check();
$personId = (int)($_POST['person_id'] ?? 0);
$p = Person::find($personId);
if (!$p || (int)$p['family_id'] !== (int)Auth::familyId()) {
flash('err', '找不到这个人。');
redirect('people');
}
if (Account::findByPerson($personId)) {
flash('err', '这个人的账号已经开通过了。');
redirect('people/show', ['id' => $personId]);
}
if (Crypto::decrypt((string)$p['phone_encrypted']) === '') {
flash('err', '要先填手机号,才能开通登录。');
redirect('people/show', ['id' => $personId]);
}
$pass = (string)($_POST['password'] ?? '');
$errs = Account::validatePassword($pass);
if ($errs) {
flash('err', implode(';', $errs));
redirect('people/show', ['id' => $personId]);
}
Account::create($personId, $pass, ($_POST['role'] ?? '') === 'admin' ? 'admin' : 'member');
flash('ok', '账号已开通,用手机号就能登录。');
redirect('people/show', ['id' => $personId]);
break;
case 'accounts/role':
Auth::requireAdmin();
csrf_check();
$personId = (int)($_POST['person_id'] ?? 0);
$role = ($_POST['role'] ?? '') === 'admin' ? 'admin' : 'member';
$p = Person::find($personId);
$acc = Account::findByPerson($personId);
if ($p && $acc) {
if ($role === 'member' && $acc['role'] === 'admin' && Account::adminCount() <= 1) {
flash('err', '至少要留一位管理员。');
redirect('people/show', ['id' => $personId]);
}
Account::setRole((int)$acc['id'], $role);
flash('ok', '权限已更新。');
}
redirect('people/show', ['id' => $personId]);
break;
case 'accounts/status':
Auth::requireAdmin();
csrf_check();
$personId = (int)($_POST['person_id'] ?? 0);
$status = ($_POST['status'] ?? '') === 'active' ? 'active' : 'disabled';
$acc = Account::findByPerson($personId);
if ($acc) {
if ((int)$acc['person_id'] === (int)Auth::personId()) {
flash('err', '不能停用自己。');
redirect('people/show', ['id' => $personId]);
}
if ($status === 'disabled' && $acc['role'] === 'admin' && Account::adminCount() <= 1) {
flash('err', '至少要留一位管理员。');
redirect('people/show', ['id' => $personId]);
}
Account::setStatus((int)$acc['id'], $status);
flash('ok', $status === 'active' ? '账号已启用。' : '账号已停用。');
}
redirect('people/show', ['id' => $personId]);
break;
// ==================== 设置 ====================
case 'settings':
Auth::requireAdmin();
$dbVersion = '未知';
try {
$dbVersion = Database::get()->query('SELECT VERSION()')->fetchColumn();
} catch (\Throwable $ex) {
// 拿不到版本不影响页面
}
$rawKey = (string)fb_config('app_key', '');
View::render('settings', [
'title' => '设置',
'family' => Family::find((int)Auth::familyId()),
'dbVersion' => $dbVersion,
'keyOk' => $rawKey !== '' && strpos($rawKey, '请填写') !== 0,
], 'settings');
break;
case 'settings/update':
Auth::requireAdmin();
csrf_check();
Family::update(
(int)Auth::familyId(),
trim((string)($_POST['name'] ?? '家书')),
trim((string)($_POST['motto'] ?? ''))
);
flash('ok', '已保存。');
redirect('settings');
break;
default:
http_response_code(404);
View::render('error', [
'title' => '页面不存在',
'message' => '找不到这一页。',
], 'home');
break;
}
$allOk = true;
foreach ($checks as $c) {
$allOk = $allOk && $c['ok'];
}
$siteName = is_array($config) && !empty($config['site_name']) ? $config['site_name'] : '家书';
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8') ?> · 环境自检</title>
<link rel="icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
<style>
:root { --paper:#F2E9D8; --cover:#A84A28; --cover2:#C96F45; --ink:#6E3820; --white:#FDFBF5; }
* { box-sizing:border-box; }
body { margin:0; padding:40px 20px; background:var(--paper); color:var(--ink);
font:15px/1.7 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif; }
.wrap { max-width:560px; margin:0 auto; }
.head { display:flex; align-items:center; gap:14px; margin-bottom:6px; }
.head img { width:64px; height:64px; border-radius:14px; }
h1 { font-size:22px; margin:0; font-weight:600; }
.sub { color:#8a6a52; font-size:13px; margin:0 0 24px 78px; }
ul { list-style:none; margin:0; padding:0; background:var(--white);
border-radius:12px; overflow:hidden; }
li { display:flex; align-items:baseline; gap:10px; padding:12px 16px;
border-bottom:1px solid rgba(110,56,32,.08); }
li:last-child { border-bottom:0; }
.dot { width:9px; height:9px; border-radius:50%; flex:0 0 auto; margin-top:8px; }
.ok { background:#6f9e5c; } .bad { background:#c0533f; }
.k { font-weight:600; flex:0 0 auto; }
.v { color:#7a5a42; font-size:13px; word-break:break-all; }
.banner { padding:10px 16px; border-radius:10px; margin-bottom:18px; font-size:14px; }
.pass { background:#e6f0dc; color:#3d6b1f; }
.fail { background:#f8ddda; color:#a1341f; }
</style>
</head>
<body>
<div class="wrap">
<div class="head">
<img src="<?= htmlspecialchars(fb_asset('/assets/icons/icon-192.png'), ENT_QUOTES, 'UTF-8') ?>" alt="">
<div>
<h1><?= htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8') ?> · 环境自检</h1>
</div>
</div>
<p class="sub">FamilyBook —— 一本用岁月写成的家谱</p>
<div class="banner <?= $allOk ? 'pass' : 'fail' ?>">
<?= $allOk ? '全部通过,可以开始盖功能了。' : '还有未通过项,处理后请刷新这一页。' ?>
</div>
<ul>
<?php foreach ($checks as $name => $c): ?>
<li>
<span class="dot <?= $c['ok'] ? 'ok' : 'bad' ?>"></span>
<span class="k"><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></span>
<span class="v"><?= htmlspecialchars((string)$c['val'], ENT_QUOTES, 'UTF-8') ?></span>
</li>
<?php endforeach; ?>
</ul>
</div>
</body>
</html>
+97
View File
@@ -0,0 +1,97 @@
<?php
/**
* 安装向导:建表 → 建家庭 → 建第一个人(同时是他/她的管理员账号)。
*
* 「是否已安装」以**数据库里的四张表**为准,不以某个文件是否存在为准 ——
* 文件可能被删、可能被恢复,表在就是装过了。
*/
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';
use App\Account;
use App\Crypto;
use App\Database;
use App\Family;
use App\Person;
use App\Schema;
use App\View;
if (Database::hasTables()) {
// 装过之后这个入口就该消失:给 404,别让它在公网一直挂着、也别让爬虫收录
http_response_code(404);
View::renderBare('error', [
'title' => '已经装好了',
'message' => '「家书」已经安装过。如果要重新安装,请先清空数据库里的 families / persons / accounts / settings 四张表。',
]);
exit;
}
$dbName = $GLOBALS['config']['db']['name'];
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
csrf_check();
$familyName = trim((string)($_POST['family_name'] ?? ''));
$motto = trim((string)($_POST['motto'] ?? ''));
$name = trim((string)($_POST['name'] ?? ''));
$phone = trim((string)($_POST['phone'] ?? ''));
$password = (string)($_POST['password'] ?? '');
$errors = [];
if ($familyName === '') { $errors['_'] = '家庭名称不能为空'; }
if ($name === '') { $errors['name'] = '请填写你的姓名'; }
if (!preg_match('/^\+?[0-9\-]{6,20}$/', $phone)) {
$errors['phone'] = '手机号格式看起来不对';
}
$pwErr = Account::validatePassword($password);
if ($pwErr) { $errors['password'] = implode(';', $pwErr); }
if (!$errors) {
try {
foreach (Schema::statements() as $sql) {
Database::get()->exec($sql);
}
$familyId = Family::create($familyName, $motto);
$personId = Person::create($familyId, [
'name' => $name,
'nickname' => '',
'gender' => '',
'birthday' => '',
'avatar' => '',
'phone' => $phone,
'id_card' => '',
'email' => '',
'address' => '',
'note' => '',
'sort_order'=> 1,
'kind' => 'member',
]);
Account::create($personId, $password, 'admin');
// 装完就删掉自己 —— 避免把安装入口长期暴露在公网
@unlink(__FILE__);
header('Location: index.php?r=auth/login');
exit;
} catch (\Throwable $ex) {
$errors['_'] = '安装失败:' . $ex->getMessage();
}
}
set_old($_POST);
View::renderBare('install', [
'title' => '安装家书',
'dbName' => $dbName,
'errors' => $errors,
]);
exit;
}
clear_old();
View::renderBare('install', [
'title' => '安装家书',
'dbName' => $dbName,
'errors' => [],
]);
+9
View File
@@ -0,0 +1,9 @@
# templates/ 里的文件只会被 PHP include,绝不允许被 Web 直接请求。
# 直接请求 layout.php / show.php 会因为缺少变量而 Fatal,并把服务器绝对路径暴露出去。
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
+27
View File
@@ -0,0 +1,27 @@
<div class="page-head">
<h1>修改密码</h1>
<span class="sub"><?= e(\App\Auth::name()) ?></span>
</div>
<form method="post" action="<?= e(url('auth/password')) ?>" class="card card-pad">
<?= csrf_field() ?>
<div class="form-grid">
<div class="field full">
<label for="old_password">当前密码</label>
<input class="input" id="old_password" name="old_password" type="password" required>
<?php if (!empty($error)): ?><span class="err"><?= e($error) ?></span><?php endif; ?>
</div>
<div class="field">
<label for="password">新密码</label>
<input class="input" id="password" name="password" type="password" required>
</div>
<div class="field">
<label for="password2">再输入一次</label>
<input class="input" id="password2" name="password2" type="password" required>
</div>
</div>
<div class="btn-row">
<button class="btn" type="submit">保存新密码</button>
<a class="btn btn-ghost" href="<?= e(url('home')) ?>">取消</a>
</div>
</form>
+5
View File
@@ -0,0 +1,5 @@
<div style="max-width:520px;margin:10vh auto;padding:28px 32px;background:#fff;border:1px solid rgba(44,35,29,.1);border-radius:16px;font:15px/1.8 -apple-system,'PingFang SC','Microsoft YaHei',sans-serif;color:#2C231D">
<h1 style="font-size:18px;font-weight:600;margin:0 0 10px"><?= e($title ?? '没有权限') ?></h1>
<p style="color:#7E6B5A;margin:0 0 18px"><?= e($message ?? '你不能访问这一页。') ?></p>
<a href="<?= e(url('home')) ?>" style="color:#A84A28">返回首页</a>
</div>
+84
View File
@@ -0,0 +1,84 @@
<?php
$memberCount = count($people);
$openCount = 0;
foreach ($people as $p) { if (!empty($p['account_id'])) { $openCount++; } }
?>
<section class="hero">
<img class="hero-logo" src="<?= e(asset('/assets/icons/icon-192.png')) ?>" alt="">
<div>
<h1><?= e($family['name']) ?></h1>
<p class="motto"><?= e($family['motto'] ?: '一本用岁月写成的家谱') ?></p>
</div>
<div class="hero-stats">
<div class="stat"><b><?= (int)$memberCount ?></b><span>位家庭成员</span></div>
<div class="stat"><b><?= (int)$openCount ?></b><span>已开通登录</span></div>
<div class="stat"><b><?= count($birthdays) ?></b><span>近期生日</span></div>
</div>
</section>
<?php if ($birthdays): ?>
<section class="section">
<h2 class="section-title">接下来的日子 <span class="hint">两个月内</span></h2>
<div class="bdays">
<?php foreach ($birthdays as $b): ?>
<div class="bday">
<img src="<?= e(\App\Upload::avatarUrl($b['avatar'])) ?>" alt="">
<div>
<b><?= e($b['name']) ?></b>
<div class="d">
<?php if ($b['days_left'] === 0): ?>
就是今天,生日快乐
<?php else: ?>
还有 <?= (int)$b['days_left'] ?> 天过生日
<?php endif; ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<section class="section">
<div class="page-head" style="margin-bottom:12px">
<h1 style="font-size:15px">家庭成员</h1>
<div class="actions">
<a class="btn btn-ghost btn-sm" href="<?= e(url('people')) ?>">管理名册</a>
<?php if (\App\Auth::isAdmin()): ?>
<a class="btn btn-sm" href="<?= e(url('people/new')) ?>">添加成员</a>
<?php endif; ?>
</div>
</div>
<?php if (!$people): ?>
<div class="empty">
<b>名册还是空的</b>
先把家里人加进来,之后他们就能出现在每一条记录里。
</div>
<?php else: ?>
<div class="people-grid">
<?php foreach ($people as $p): ?>
<a class="person" href="<?= e(url('people/show', ['id' => (int)$p['id']])) ?>">
<div class="ph"><img src="<?= e(\App\Upload::avatarUrl($p['avatar'])) ?>" alt=""></div>
<div class="pb">
<div class="pname"><?= e($p['name']) ?></div>
<div class="pmeta">
<?php if ($p['account_role'] === 'admin' && $p['account_status'] === 'active'): ?>
<span class="badge badge-admin">管理员</span>
<?php elseif (!empty($p['account_id'])): ?>
<span class="badge badge-open">已开通</span>
<?php else: ?>
<span class="badge">未开通</span>
<?php endif; ?>
<?php
$age = age_from($p['birthday'] ?? '');
if ($age !== null) { echo ' · ' . (int)$age . ' 岁'; }
?>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</section>
+49
View File
@@ -0,0 +1,49 @@
<div class="auth-wrap">
<div class="auth-card">
<img class="logo" src="/assets/icons/icon-192.png" alt="">
<h1>安装「家书」</h1>
<p class="lead">先建好你的家庭空间,再给家里人开通知。填完这一步就能用了。</p>
<?php if (!empty($errors['_'])): ?>
<div class="flash"><div class="flash-item err"><?= e($errors['_']) ?></div></div>
<?php endif; ?>
<form method="post" action="install.php">
<?= csrf_field() ?>
<div class="form-grid">
<div class="field full">
<label for="family_name">家庭名称</label>
<input class="input" id="family_name" name="family_name"
value="<?= e(old('family_name', '我们家')) ?>" placeholder="比如:我们家" required>
</div>
<div class="field full">
<label for="motto">一句话</label>
<input class="input" id="motto" name="motto" value="<?= e(old('motto')) ?>"
placeholder="写在首页的一行小字,可留空">
</div>
<div class="field">
<label for="name">你的姓名</label>
<input class="input" id="name" name="name" value="<?= e(old('name')) ?>" required>
<?php if (!empty($errors['name'])): ?><span class="err"><?= e($errors['name']) ?></span><?php endif; ?>
</div>
<div class="field">
<label for="phone">手机号</label>
<input class="input" id="phone" name="phone" value="<?= e(old('phone')) ?>"
inputmode="numeric" placeholder="登录用" required>
<span class="tip">家里每个人都可以有自己的手机号和密码。</span>
<?php if (!empty($errors['phone'])): ?><span class="err"><?= e($errors['phone']) ?></span><?php endif; ?>
</div>
<div class="field full">
<label for="password">登录密码</label>
<input class="input" id="password" name="password" type="password" required>
<span class="tip">至少 8 位,且同时含字母和数字。</span>
<?php if (!empty($errors['password'])): ?><span class="err"><?= e($errors['password']) ?></span><?php endif; ?>
</div>
</div>
<button class="btn" type="submit">建好,进去看看</button>
<p class="auth-foot">
数据库:<?= e($dbName) ?> · 手机号与身份证号都会加密后入库
</p>
</form>
</div>
</div>
+63
View File
@@ -0,0 +1,63 @@
<?php
$navItems = [
'home' => ['首页', 'home'],
'people' => ['名册', 'people'],
];
if (\App\Auth::isAdmin()) {
$navItems['settings'] = ['设置', 'settings'];
}
$me = \App\Auth::check();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($pageTitle) ?> · 家书</title>
<link rel="icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
<meta name="theme-color" content="#A84A28">
<link rel="stylesheet" href="<?= e(asset('/assets/css/app.css')) ?>">
</head>
<body>
<?php if ($me): ?>
<header class="topbar">
<div class="topbar-inner">
<a class="brand" href="<?= e(url('home')) ?>">
<img src="<?= e(asset('/assets/icons/icon-96.png')) ?>" alt="">
<span>家书</span>
</a>
<nav class="nav">
<?php foreach ($navItems as $route => list($label, $key)): ?>
<a class="<?= $pageKey === $key ? 'on' : '' ?>" href="<?= e(url($route)) ?>"><?= e($label) ?></a>
<?php endforeach; ?>
</nav>
<div class="topbar-right">
<span class="who">
<img src="<?= e(\App\Upload::avatarUrl($_SESSION['avatar'] ?? null)) ?>" alt="">
<span class="who-name"><?= e(\App\Auth::name()) ?></span>
</span>
<a class="link-quiet who-pwd" href="<?= e(url('auth/password')) ?>">改密码</a>
<a class="link-quiet" href="<?= e(url('auth/logout', ['_csrf' => csrf_token()])) ?>">退出</a>
</div>
</div>
</header>
<?php endif; ?>
<main class="<?= in_array($pageKey, ['install', 'login'], true) ? 'container-narrow' : 'container' ?>">
<?php foreach (take_flash() as $f): ?>
<div class="flash">
<div class="flash-item <?= $f['type'] === 'err' ? 'err' : '' ?>"><?= e($f['message']) ?></div>
</div>
<?php endforeach; ?>
<?php require $tplFile; ?>
</main>
<script src="<?= e(asset('/assets/js/app.js')) ?>"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
<div class="auth-wrap">
<div class="auth-card">
<img class="logo" src="/assets/icons/icon-192.png" alt="">
<h1><?= e($familyName) ?></h1>
<p class="lead">用手机号登录你的家书。</p>
<?php if (!empty($error)): ?>
<div class="flash"><div class="flash-item err"><?= e($error) ?></div></div>
<?php endif; ?>
<form method="post" action="<?= e(url('auth/login')) ?>">
<?= csrf_field() ?>
<div class="form-grid">
<div class="field full">
<label for="phone">手机号</label>
<input class="input" id="phone" name="phone" value="<?= e($phone ?? '') ?>"
inputmode="numeric" autocomplete="username" required autofocus>
</div>
<div class="field full">
<label for="password">密码</label>
<input class="input" id="password" name="password" type="password"
autocomplete="current-password" required>
</div>
</div>
<button class="btn" type="submit">登录</button>
</form>
<p class="auth-foot">忘记密码?让家里有管理员权限的人帮你重置。</p>
</div>
</div>
+113
View File
@@ -0,0 +1,113 @@
<?php
$isEdit = !empty($person['id']);
$avatarUrl = \App\Upload::avatarUrl($person['avatar'] ?? null);
?>
<div class="page-head">
<h1><?= $isEdit ? '编辑成员' : '添加成员' ?></h1>
<span class="sub"><?= $isEdit ? e($person['name']) : '填姓名就行,其他都可以以后再补' ?></span>
</div>
<form method="post" enctype="multipart/form-data"
action="<?= e(url($isEdit ? 'people/update' : 'people/create')) ?>">
<?= csrf_field() ?>
<?php if ($isEdit): ?>
<input type="hidden" name="id" value="<?= (int)$person['id'] ?>">
<?php endif; ?>
<div class="card card-pad">
<div class="form-grid">
<div class="field">
<label for="name">姓名 *</label>
<input class="input" id="name" name="name" value="<?= e(old('name', $person['name'] ?? '')) ?>" required>
<?php if (!empty($errors['name'])): ?><span class="err"><?= e($errors['name']) ?></span><?php endif; ?>
</div>
<div class="field">
<label for="nickname">小名</label>
<input class="input" id="nickname" name="nickname"
value="<?= e(old('nickname', $person['nickname'] ?? '')) ?>" placeholder="家里怎么叫他/她">
</div>
<div class="field">
<label for="gender">性别</label>
<select class="select" id="gender" name="gender">
<?php $g = old('gender', $person['gender'] ?? ''); ?>
<option value="" <?= $g === '' ? 'selected' : '' ?>>不填</option>
<option value="m" <?= $g === 'm' ? 'selected' : '' ?>>男</option>
<option value="f" <?= $g === 'f' ? 'selected' : '' ?>>女</option>
</select>
</div>
<div class="field">
<label for="birthday">生日</label>
<input class="input" id="birthday" name="birthday" type="date"
value="<?= e(old('birthday', $person['birthday'] ?? '')) ?>">
<span class="tip">填了之后,首页会提醒还有几天过生日。</span>
<?php if (!empty($errors['birthday'])): ?><span class="err"><?= e($errors['birthday']) ?></span><?php endif; ?>
</div>
<div class="field">
<label for="phone">手机号</label>
<input class="input" id="phone" name="phone" inputmode="numeric"
value="<?= e(old('phone', $phoneValue ?? '')) ?>" placeholder="可留空">
<span class="tip">开通登录后用它登录;加密存储,列表里只显示部分。</span>
<?php if (!empty($errors['phone'])): ?><span class="err"><?= e($errors['phone']) ?></span><?php endif; ?>
</div>
<div class="field">
<label for="email">邮箱</label>
<input class="input" id="email" name="email" type="email"
value="<?= e(old('email', $person['email'] ?? '')) ?>">
<?php if (!empty($errors['email'])): ?><span class="err"><?= e($errors['email']) ?></span><?php endif; ?>
</div>
<div class="field full">
<label for="id_card">身份证号</label>
<input class="input mono" id="id_card" name="id_card"
value="<?= e(old('id_card', $idCardValue ?? '')) ?>" placeholder="可留空">
<span class="tip">
加密存储,页面上一律只显示前 6 后 4 位。
家庭场景里真正需要它的场合很少 —— 能不填就别填。
</span>
<?php if (!empty($errors['id_card'])): ?><span class="err"><?= e($errors['id_card']) ?></span><?php endif; ?>
</div>
<div class="field full">
<label for="address">住址</label>
<input class="input" id="address" name="address"
value="<?= e(old('address', $person['address'] ?? '')) ?>">
</div>
<div class="field full">
<label for="note">备注</label>
<textarea class="input" id="note" name="note" placeholder="爱吃辣、对芒果过敏、怕坐过山车……"><?= e(old('note', $person['note'] ?? '')) ?></textarea>
</div>
<div class="field">
<label for="avatar">头像</label>
<input class="input" id="avatar" name="avatar" type="file" accept="image/*">
<span class="tip">会自动裁成正方形,上限 5MB。</span>
</div>
<div class="field">
<label>当前头像</label>
<img id="avatar-preview" src="<?= e($avatarUrl) ?>" alt=""
style="width:88px;height:88px;border-radius:12px;object-fit:cover;border:1px solid var(--line)">
</div>
<div class="field">
<label for="sort_order">排序号</label>
<input class="input" id="sort_order" name="sort_order" type="number"
value="<?= e(old('sort_order', $person['sort_order'] ?? 1000)) ?>">
<span class="tip">小的排前面。</span>
</div>
</div>
<div class="btn-row">
<button class="btn" type="submit"><?= $isEdit ? '保存' : '加入名册' ?></button>
<a class="btn btn-ghost" href="<?= e($isEdit ? url('people/show', ['id' => (int)$person['id']]) : url('people')) ?>">取消</a>
</div>
</div>
</form>
+46
View File
@@ -0,0 +1,46 @@
<div class="page-head">
<h1>家庭名册</h1>
<span class="sub">共 <?= count($people) ?> 人</span>
<div class="actions">
<?php if (\App\Auth::isAdmin()): ?>
<a class="btn btn-sm" href="<?= e(url('people/new')) ?>">添加成员</a>
<?php endif; ?>
</div>
</div>
<form class="search" method="get" action="index.php">
<input type="hidden" name="r" value="people">
<input class="input" name="q" value="<?= e($q) ?>" placeholder="按姓名、小名或邮箱搜索">
<button class="btn btn-ghost btn-sm" type="submit">搜索</button>
<?php if ($q !== ''): ?>
<a class="link-quiet" href="<?= e(url('people')) ?>">清除</a>
<?php endif; ?>
</form>
<?php if (!$people): ?>
<div class="empty">
<b><?= $q !== '' ? '没有匹配的人' : '名册还是空的' ?></b>
<?= $q !== '' ? '换个词试试。' : '把家里人加进来,之后观影、旅行的同行人就可以直接从名册里选。' ?>
</div>
<?php else: ?>
<div class="people-grid">
<?php foreach ($people as $p): ?>
<a class="person" href="<?= e(url('people/show', ['id' => (int)$p['id']])) ?>">
<div class="ph"><img src="<?= e(\App\Upload::avatarUrl($p['avatar'])) ?>" alt=""></div>
<div class="pb">
<div class="pname"><?= e($p['name']) ?></div>
<div class="pmeta">
<?php if ($p['account_role'] === 'admin' && $p['account_status'] === 'active'): ?>
<span class="badge badge-admin">管理员</span>
<?php elseif (!empty($p['account_id'])): ?>
<span class="badge badge-open">已开通</span>
<?php else: ?>
<span class="badge">未开通</span>
<?php endif; ?>
<?php if (!empty($p['nickname'])): ?> · <?= e($p['nickname']) ?><?php endif; ?>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
<?php endif; ?>
+147
View File
@@ -0,0 +1,147 @@
<?php
$age = age_from($person['birthday'] ?? '');
$isMe = (int)$person['id'] === (int)\App\Auth::personId();
$admin = \App\Auth::isAdmin();
?>
<div class="page-head">
<h1><?= e($person['name']) ?></h1>
<span class="sub">
<?php if (!empty($person['nickname'])): ?>小名 <?= e($person['nickname']) ?><?php endif; ?>
</span>
<div class="actions">
<?php if ($admin): ?>
<a class="btn btn-ghost btn-sm" href="<?= e(url('people/edit', ['id' => (int)$person['id']])) ?>">编辑</a>
<form method="post" action="<?= e(url('people/destroy')) ?>" style="display:inline"
onsubmit="return confirm('确定要从名册里移除 <?= e($person['name']) ?> 吗?相关的账号也会一起删掉。')">
<?= csrf_field() ?>
<input type="hidden" name="id" value="<?= (int)$person['id'] ?>">
<button class="btn btn-danger btn-sm" type="submit">移除</button>
</form>
<?php endif; ?>
</div>
</div>
<div class="detail">
<aside class="detail-photo">
<img src="<?= e(\App\Upload::avatarUrl($person['avatar'])) ?>" alt="">
<div class="name"><?= e($person['name']) ?></div>
<div class="sub">
<?php if ($person['account_role'] === 'admin' && $person['account_status'] === 'active'): ?>
家庭管理员
<?php elseif (!empty($person['account_id'])): ?>
已开通登录<?= $person['account_status'] === 'disabled' ? '(已停用)' : '' ?>
<?php else: ?>
还没有开通登录
<?php endif; ?>
</div>
</aside>
<div>
<div class="card card-pad">
<dl class="kv">
<div class="kv-row">
<dt>姓名</dt><dd><?= e($person['name']) ?></dd>
</div>
<?php if (!empty($person['nickname'])): ?>
<div class="kv-row"><dt>小名</dt><dd><?= e($person['nickname']) ?></dd></div>
<?php endif; ?>
<div class="kv-row">
<dt>性别</dt>
<dd><?= $person['gender'] === 'm' ? '男' : ($person['gender'] === 'f' ? '女' : '未填写') ?></dd>
</div>
<div class="kv-row">
<dt>生日</dt>
<dd>
<?php if (!empty($person['birthday'])): ?>
<?= e($person['birthday']) ?>
<?php if ($age !== null): ?> · <?= (int)$age ?> 岁<?php endif; ?>
<?php $d = days_until_birthday($person['birthday']); ?>
<?php if ($d === 0): ?> · <span style="color:var(--brand)">今天生日</span>
<?php elseif ($d !== null): ?> · 还有 <?= (int)$d ?> 天<?php endif; ?>
<?php else: ?>
<span class="muted">未填写</span>
<?php endif; ?>
</dd>
</div>
<div class="kv-row">
<dt>手机号</dt>
<dd class="mono"><?= e(\App\Crypto::maskPhone($person['phone_encrypted'] ?? '')) ?></dd>
</div>
<div class="kv-row">
<dt>身份证号</dt>
<dd class="mono"><?= e(\App\Crypto::maskIdCard($person['id_card_encrypted'] ?? '')) ?></dd>
</div>
<?php if (!empty($person['email'])): ?>
<div class="kv-row"><dt>邮箱</dt><dd><?= e($person['email']) ?></dd></div>
<?php endif; ?>
<?php if (!empty($person['address'])): ?>
<div class="kv-row"><dt>住址</dt><dd><?= e($person['address']) ?></dd></div>
<?php endif; ?>
<?php if (!empty($person['note'])): ?>
<div class="kv-row"><dt>备注</dt><dd><?= nl2br(e($person['note'])) ?></dd></div>
<?php endif; ?>
<div class="kv-row">
<dt>最近登录</dt>
<dd><?= !empty($person['last_login_at']) ? e($person['last_login_at']) : '从未登录' ?></dd>
</div>
</dl>
</div>
<?php if ($admin): ?>
<div class="card card-pad" style="margin-top:16px">
<h2 class="section-title">登录账号</h2>
<?php if (empty($person['account_id'])): ?>
<p class="small muted" style="margin:0 0 14px">
开通后,<?= e($person['name']) ?> 就能用手机号和密码登录家书了。
</p>
<form method="post" action="<?= e(url('accounts/create')) ?>" class="form-grid">
<?= csrf_field() ?>
<input type="hidden" name="person_id" value="<?= (int)$person['id'] ?>">
<div class="field">
<label>登录密码</label>
<input class="input" name="password" type="password" placeholder="至少 8 位,含字母和数字" required>
</div>
<div class="field">
<label>角色</label>
<select class="select" name="role">
<option value="member">普通成员</option>
<option value="admin">管理员</option>
</select>
</div>
<div class="field full">
<button class="btn btn-sm" type="submit">开通账号</button>
</div>
</form>
<?php else: ?>
<p class="small muted" style="margin:0 0 14px">
账号已开通,登录名是 <?= e($person['name']) ?> 的手机号。
</p>
<div class="btn-row" style="margin-top:0;flex-wrap:wrap">
<?php if (!$isMe): ?>
<form method="post" action="<?= e(url('accounts/role')) ?>" style="display:inline">
<?= csrf_field() ?>
<input type="hidden" name="person_id" value="<?= (int)$person['id'] ?>">
<input type="hidden" name="role" value="<?= $person['account_role'] === 'admin' ? 'member' : 'admin' ?>">
<button class="btn btn-ghost btn-sm" type="submit">
<?= $person['account_role'] === 'admin' ? '取消管理员' : '设为管理员' ?>
</button>
</form>
<form method="post" action="<?= e(url('accounts/status')) ?>" style="display:inline">
<?= csrf_field() ?>
<input type="hidden" name="person_id" value="<?= (int)$person['id'] ?>">
<input type="hidden" name="status" value="<?= $person['account_status'] === 'active' ? 'disabled' : 'active' ?>">
<button class="btn btn-ghost btn-sm" type="submit">
<?= $person['account_status'] === 'active' ? '停用账号' : '启用账号' ?>
</button>
</form>
<?php else: ?>
<span class="small muted">这是你自己 —— 要改自己的权限,请让另一位管理员来操作。</span>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
+30
View File
@@ -0,0 +1,30 @@
<form method="post" action="<?= e(url('settings/update')) ?>" class="card card-pad">
<?= csrf_field() ?>
<div class="form-grid">
<div class="field full">
<label for="name">家庭名称</label>
<input class="input" id="name" name="name" value="<?= e($family['name']) ?>" required>
</div>
<div class="field full">
<label for="motto">一句话</label>
<input class="input" id="motto" name="motto" value="<?= e($family['motto'] ?? '') ?>"
placeholder="展示在首页的一行小字">
</div>
</div>
<div class="btn-row">
<button class="btn" type="submit">保存</button>
</div>
</form>
<div class="card card-pad" style="margin-top:20px">
<h2 class="section-title">运行环境 <span class="hint">排错时看这一块</span></h2>
<dl class="kv">
<div class="kv-row"><dt>PHP</dt><dd><?= e(PHP_VERSION) ?></dd></div>
<div class="kv-row"><dt>数据库</dt><dd><?= e($dbVersion) ?></dd></div>
<div class="kv-row"><dt>加密密钥</dt><dd><?= $keyOk ? '已配置' : '<span style="color:var(--red)">未配置</span>' ?></dd></div>
</dl>
<p class="small muted" style="margin:14px 0 0">
手机号与身份证号都是加密后入库的。这个密钥一旦换掉,已有数据就再也解不开 ——
请把它和数据库分开、各备份一份。
</p>
</div>
+14
View File
@@ -0,0 +1,14 @@
# 上传目录里禁止执行任何脚本 —— 没有这条,上传的 .php 就能被直接访问执行。
# 同时兼容 Apache 2.4(Require)与 2.2(Order)。
<FilesMatch "\.(?i:php|php3|php4|php5|php7|phtml|pht|phar|cgi|pl|asp|aspx|jsp|sh|py)$">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</FilesMatch>
# 关掉目录列表
Options -Indexes