Files
MailNotifier/Plugin.php

1898 lines
91 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* 邮件通知插件
*
* @package MailNotifier
* @author 石头厝
* @version 2.0.3
* @link https://www.shitoucuo.com/
*/
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
// 兼容 Typecho 1.1 / 1.2 的类名差异。
if (!interface_exists('Typecho_Plugin_Interface')) {
if (interface_exists('Typecho\\Plugin\\PluginInterface')) {
class_alias('Typecho\\Plugin\\PluginInterface', 'Typecho_Plugin_Interface');
} else {
interface Typecho_Plugin_Interface {}
}
}
if (!class_exists('Typecho_Widget_Helper_Form') && class_exists('Typecho\\Widget\\Helper\\Form')) {
class_alias('Typecho\\Widget\\Helper\\Form', 'Typecho_Widget_Helper_Form');
}
if (!class_exists('Typecho_Widget_Helper_Layout') && class_exists('Typecho\\Widget\\Helper\\Layout')) {
class_alias('Typecho\\Widget\\Helper\\Layout', 'Typecho_Widget_Helper_Layout');
}
$__cn_form_elements = array('Text', 'Radio', 'Checkbox', 'Select', 'Textarea', 'Hidden');
foreach ($__cn_form_elements as $__cn_el) {
$__cn_old = 'Typecho_Widget_Helper_Form_Element_' . $__cn_el;
$__cn_new = 'Typecho\\Widget\\Helper\\Form\\Element\\' . $__cn_el;
if (!class_exists($__cn_old) && class_exists($__cn_new)) {
class_alias($__cn_new, $__cn_old);
}
}
unset($__cn_form_elements, $__cn_el, $__cn_old, $__cn_new);
class MailNotifier_Plugin implements Typecho_Plugin_Interface
{
/**
* 插件版本(与文件头 @version 保持一致,备份文件里也记这个号)
*/
const VERSION = '2.0.3';
/**
* 后台「邮件历史」面板文件
*/
const PANEL_FILE = 'MailNotifier/Manage.php';
/**
* 面板挂在哪个菜单下:3 = 扩展管理(NewAdmin 的分组)
*/
const PANEL_INDEX = 3;
/**
* 面板标题 / 副标题(原「评论邮件」,2026-11-12 改名「邮件历史」)
*/
const PANEL_TITLE = '邮件历史';
const PANEL_DESC = '邮件历史发送记录';
/* --------------------------------------------------------------
* 改名兼容:本插件原名 CommentNotifier。
* 老站的 activated、后台菜单、路由、配置项都还挂在旧名下,
* 启用新版时统一清理 / 接管,常量里的旧名不要动。
* -------------------------------------------------------------- */
const LEGACY_NAME = 'CommentNotifier';
const LEGACY_PANEL_FILE = 'CommentNotifier/Manage.php';
/**
* 本次请求是否已经处理过菜单注册
*
* @var bool
*/
private static $panelEnsured = false;
public static function activate()
{
// 先把旧插件从内存里摘掉:它的钩子还指向已经删掉的 CommentNotifier_Plugin,
// 不清掉的话,评论一提交就会回调到不存在的类
self::migrateLegacy();
self::registerHook('Widget\\Feedback', 'Widget_Feedback', 'finishComment', 'refinishComment');
self::registerHook('Widget\\Comments\\Edit', 'Widget_Comments_Edit', 'finishComment', 'refinishComment');
self::registerHook('Widget\\Comments\\Edit', 'Widget_Comments_Edit', 'mark', 'mark');
self::registerHook('Widget\\Service', 'Widget_Service', 'mailNotifierSend', 'serviceSend');
// 发送记录表:老站覆盖升级时不会走 activate(),所以还要靠 initSupport() 兜底
if (class_exists('Helper')) {
// 清理旧版自定义面板和旧测试路由,设置项统一回到插件设置页。
Helper::removePanel(1, self::PANEL_FILE);
Helper::removePanel(1, 'MailNotifier/console.php');
Helper::removeRoute('zemail');
Helper::removeRoute('mailNotifierTest');
Helper::removeRoute('mailNotifierSettings');
Helper::addRoute('mailNotifierTest', '/mail-notifier-test', 'MailNotifier_Action', 'test');
// 设置页顶部的备份 / 恢复按钮走这个路由
Helper::addRoute('mailNotifierSettings', '/mail-notifier-settings', 'MailNotifier_Action', 'settings');
}
// 建表 + 注册后台菜单(扩展管理 → 邮件历史),已有就不会重复加
self::initSupport();
return _t('MailNotifier v2.0.3 已启用(原 CommentNotifier)。「扩展管理 → 邮件历史」可查看发送记录,备份 / 恢复在插件设置页标题右侧。');
}
/**
* 改名迁移:CommentNotifier → MailNotifier
*
* 处理三样旧东西:
* ① activated 里的旧插件,以及它注册在 handles 里的回调
* ② 后台菜单的旧面板、路由表里的旧路由
* ③ plugin:CommentNotifier 这份配置(整串搬到新键,格式原样复制)
*/
private static function migrateLegacy()
{
// ① 摘掉旧插件。Typecho 1.2+ 是 Typecho\Plugin,老版本是 Typecho_Plugin,
// 这里都试一遍,失败也不打断启用流程。
foreach (array('Typecho_Plugin', 'Typecho\\Plugin') as $pluginClass) {
if (class_exists($pluginClass) && method_exists($pluginClass, 'deactivate')) {
try {
call_user_func(array($pluginClass, 'deactivate'), self::LEGACY_NAME);
} catch (Exception $e) {
} catch (Throwable $e) {
}
break;
}
}
// ② 菜单与路由
if (class_exists('Helper')) {
try {
Helper::removePanel(self::PANEL_INDEX, self::LEGACY_PANEL_FILE);
Helper::removePanel(1, self::LEGACY_PANEL_FILE);
Helper::removePanel(1, 'CommentNotifier/console.php');
Helper::removeRoute('commentNotifierTest');
Helper::removeRoute('commentNotifierSettings');
Helper::removeRoute('zemail');
} catch (Exception $e) {
} catch (Throwable $e) {
}
}
// ③ 配置与备份文件
self::loadSupport();
if (class_exists('MailNotifier_Settings')) {
MailNotifier_Settings::migrateLegacyOption();
// 旧插件目录还在的话,把里面的备份也接过来
MailNotifier_Settings::migrateLegacyBackups();
}
}
public static function deactivate()
{
if (class_exists('Helper')) {
Helper::removeRoute('mailNotifierTest');
Helper::removeRoute('mailNotifierSettings');
Helper::removeRoute('zemail');
Helper::removePanel(self::PANEL_INDEX, self::PANEL_FILE);
Helper::removePanel(1, self::PANEL_FILE);
Helper::removePanel(1, 'MailNotifier/console.php');
}
return _t('MailNotifier 已停用。配置和发送记录都会保留,重新启用后菜单会自动加回来。');
}
/**
* 载入附加类(发送记录 / 设置备份)
*/
private static function loadSupport()
{
if (!class_exists('MailNotifier_MailLog')) {
require_once dirname(__FILE__) . '/MailLog.php';
}
if (!class_exists('MailNotifier_Settings')) {
require_once dirname(__FILE__) . '/Settings.php';
}
}
/**
* 准备运行环境:建记录表 + 补后台菜单
*
* 覆盖升级(只传文件、不重新启用插件)时 activate() 不会被调用,
* 菜单和表都不会出现。设置页打开时调一次这里,问题就地解决,
* 站长不用去停用再启用一遍。
*/
public static function initSupport()
{
self::loadSupport();
try {
MailNotifier_MailLog::ensureTable();
} catch (Exception $e) {
} catch (Throwable $e) {
}
self::ensurePanel();
self::ensureRoutes();
}
/**
* 路由不存在就补上(幂等)
*
* 同 ensurePanel:覆盖升级不会走 activate(),而设置页顶部的备份 / 恢复
* 按钮靠 /mail-notifier-settings 这条路由吃饭,路由丢了点下去就是 404。
* 这里直接查库判断,同一次请求里调多次也不会重复写。
*/
public static function ensureRoutes()
{
if (!class_exists('Helper')) {
return false;
}
$routes = array(
'mailNotifierSettings' => '/mail-notifier-settings',
'mailNotifierTest' => '/mail-notifier-test',
);
try {
$db = MailNotifier_MailLog::db();
if (!$db) {
return false;
}
$row = $db->fetchRow(
$db->select()->from('table.options')->where('name = ?', 'routingTable')->limit(1)
);
$raw = $row && isset($row['value']) ? (string) $row['value'] : '';
$data = array();
if ($raw !== '') {
$data = (strpos($raw, 'a:') === 0) ? @unserialize($raw) : json_decode($raw, true);
}
$exists = array();
if (is_array($data)) {
foreach ($data as $item) {
if (is_array($item) && isset($item['url'])) {
$exists[(string) $item['url']] = true;
}
}
}
foreach ($routes as $name => $url) {
if (!isset($exists[$url])) {
Helper::addRoute($name, $url, 'MailNotifier_Action', $name === 'mailNotifierTest' ? 'test' : 'settings');
}
}
return true;
} catch (Exception $e) {
return false;
} catch (Throwable $e) {
return false;
}
}
/**
* 菜单不存在就加上(幂等)
*
* 幂等这件事必须自己保证,不能指望 Helper::addPanel:它只是往 panelTable
* 里追加一条,同一条菜单加两次,后台就会看到两个「邮件历史」。
* 而 $options->panelTable 是请求开始时读进内存的,同一次请求里加完再查
* 还是旧值 —— 所以这里①同请求内用静态标记短路,②判断时直接查库拿最新值。
*/
public static function ensurePanel()
{
if (self::$panelEnsured) {
return true;
}
if (!class_exists('Helper')) {
return false;
}
self::loadSupport();
try {
$files = self::panelFilesFromDb();
if (!in_array(urlencode(self::PANEL_FILE), $files, true)) {
Helper::addPanel(self::PANEL_INDEX, self::PANEL_FILE, self::PANEL_TITLE, self::PANEL_DESC, 'administrator');
} elseif (self::panelTitleFromDb() !== self::PANEL_TITLE) {
/* 老站菜单还叫「评论邮件」:先摘掉再按新名字登记。
setOption() 会同步内存里的 options,同一个请求里 remove + add 是安全的。 */
Helper::removePanel(self::PANEL_INDEX, self::PANEL_FILE);
Helper::removePanel(1, self::PANEL_FILE);
Helper::addPanel(self::PANEL_INDEX, self::PANEL_FILE, self::PANEL_TITLE, self::PANEL_DESC, 'administrator');
}
self::$panelEnsured = true;
return true;
} catch (Exception $e) {
return false;
} catch (Throwable $e) {
return false;
}
}
/**
* 面板当前登记在库里的标题
*
* panelTable 的结构是 child[菜单组][] = [标题, 副标题, extending.php?panel=xxx, ...],
* 按第 3 个元素(面板地址)反查标题,用来发现「评论邮件 → 历史邮件 → 邮件历史」这类改名需求。
*/
private static function panelTitleFromDb()
{
$db = MailNotifier_MailLog::db();
if (!$db) {
return '';
}
try {
$row = $db->fetchRow(
$db->select()->from('table.options')->where('name = ?', 'panelTable')->limit(1)
);
} catch (Exception $e) {
return '';
} catch (Throwable $e) {
return '';
}
if (!$row || empty($row['value'])) {
return '';
}
$raw = (string) $row['value'];
$data = (strpos($raw, 'a:') === 0) ? @unserialize($raw) : json_decode($raw, true);
if (!is_array($data) || empty($data['child']) || !is_array($data['child'])) {
return '';
}
$target = 'extending.php?panel=' . urlencode(self::PANEL_FILE);
foreach ($data['child'] as $group) {
if (!is_array($group)) {
continue;
}
foreach ($group as $panel) {
if (is_array($panel) && isset($panel[2]) && $panel[2] === $target && isset($panel[0])) {
return (string) $panel[0];
}
}
}
return '';
}
/**
* 直接查库拿当前已登记的面板文件列表
*
* 不用 $options->panelTable:那是请求开始时的快照,同一个请求里
* addPanel() 之后它不会更新,拿它判断必然重复添加。
*/
private static function panelFilesFromDb()
{
$db = MailNotifier_MailLog::db();
if (!$db) {
return array();
}
$row = $db->fetchRow(
$db->select()->from('table.options')->where('name = ?', 'panelTable')->limit(1)
);
if (!$row || !isset($row['value']) || $row['value'] === '') {
return array();
}
$raw = (string) $row['value'];
$data = (strpos($raw, 'a:') === 0) ? @unserialize($raw) : json_decode($raw, true);
if (!is_array($data) || !isset($data['file'])) {
return array();
}
return array_map('strval', (array) $data['file']);
}
/**
* 面板页的动作令牌
*
* 用插件设置里的 auth 做密钥,绑当前管理员 uid:
* 换了账号或改了密钥,旧链接立刻失效。比拿 Referer 算 token 稳,
* 也不会因为页面上多一个筛选参数就误判。
*/
public static function mailLogToken()
{
$uid = 0;
try {
$user = Typecho_Widget::widget('Widget_User');
if ($user && $user->hasLogin()) {
$uid = intval($user->uid);
}
} catch (Exception $e) {
$uid = 0;
} catch (Throwable $e) {
$uid = 0;
}
if ($uid <= 0) {
return '';
}
$secret = self::configStr('auth', '');
if ($secret === '') {
$options = self::options();
$secret = $options && isset($options->secret) ? (string) $options->secret : '';
}
if ($secret === '') {
return '';
}
return substr(hash_hmac('sha256', 'mailnotifier-maillog|' . $uid, $secret), 0, 32);
}
/**
* 校验面板页动作令牌
*/
public static function checkMailLogToken($token)
{
$expected = self::mailLogToken();
if ($expected === '') {
return false;
}
return hash_equals($expected, (string) $token);
}
/**
* 站点地址(给备份文件记一份环境信息)
*/
public static function siteUrlPublic()
{
return self::siteUrl();
}
public static function config(Typecho_Widget_Helper_Form $form)
{
// 覆盖升级过的站不会走 activate(),这里顺手把记录表和后台菜单补齐
self::initSupport();
$auth = self::configStr('auth', '');
if ($auth === '') {
$auth = self::randString(32);
}
$style = new Typecho_Widget_Helper_Layout();
$style->html(self::configStyleHtml());
$form->addItem($style);
/* 标题卡:标题右边放「记录」入口,左侧描述下方放「备份 / 恢复」,备份结果提示条跟在卡片下面 */
$heroCard = new Typecho_Widget_Helper_Layout();
$heroCard->html(self::heroCardHtml());
$form->addItem($heroCard);
/* 设置页外壳:Tab 样式 + 分组脚本(参考 RssUnion 的实现,标签靠 JS 归组,字段照常提交) */
$shell = new Typecho_Widget_Helper_Layout('div', array('class' => 'cnot-config-shell'));
$shell->html(self::configShellHtml());
$form->addItem($shell);
/* ================== 一、基础设置:SMTP 账户、测试发送、测试模板 ================== */
$form->addItem(self::configTabStart('basic', '基础设置'));
$enabled = new Typecho_Widget_Helper_Form_Element_Radio('enabled', array('1' => _t('启用'), '0' => _t('关闭')), self::configStr('enabled', '1'), _t('是否开启邮件通知'), _t('关闭后不会发送任何通知,但会保留所有配置。'));
self::addInput($form, $enabled);
$yibu = new Typecho_Widget_Helper_Form_Element_Radio('yibu', array('0' => _t('不启用'), '1' => _t('启用')), self::configStr('yibu', '0'), _t('异步提交'), _t('启用后会尽量使用 Typecho 后台服务接口发送,减少评论提交等待时间;如果当前环境不支持,会自动回落为同步发送。'));
self::addInput($form, $yibu);
self::addSection($form, 'SMTP 服务配置', 'QQ 邮箱请填写授权码,不是 QQ 登录密码。常用配置:smtp.qq.com / SSL / 465。');
$STMPHost = new Typecho_Widget_Helper_Form_Element_Text('STMPHost', null, self::configStr('STMPHost', 'smtp.qq.com'), _t('SMTP 服务器地址'), _t('例如:smtp.qq.com、smtp.163.com、smtp.gmail.com、smtp.exmail.qq.com。'));
self::addInput($form, $STMPHost);
$SMTPUserName = new Typecho_Widget_Helper_Form_Element_Text('SMTPUserName', null, self::configStr('SMTPUserName', ''), _t('SMTP 登录用户'), _t('一般填写完整邮箱地址。'));
self::addInput($form, $SMTPUserName);
$from = new Typecho_Widget_Helper_Form_Element_Text('from', null, self::configStr('from', ''), _t('SMTP 邮箱地址'), _t('用于发送邮件的邮箱,一般与 SMTP 登录用户一致。'));
self::addInput($form, $from);
$SMTPPassword = new Typecho_Widget_Helper_Form_Element_Text('SMTPPassword', null, self::configStr('SMTPPassword', ''), _t('SMTP 登录密码 / 授权码'), _t('QQ 邮箱、163 邮箱等通常需要在邮箱后台生成 SMTP 授权码。'));
self::addInput($form, $SMTPPassword);
$SMTPSecure = new Typecho_Widget_Helper_Form_Element_Radio('SMTPSecure', array('' => _t('无安全加密'), 'ssl' => _t('SSL 加密'), 'tls' => _t('TLS 加密')), self::configRaw('SMTPSecure', 'ssl'), _t('SMTP 加密模式'), _t('QQ 邮箱建议 SSL。'));
self::addInput($form, $SMTPSecure);
$SMTPPort = new Typecho_Widget_Helper_Form_Element_Text('SMTPPort', null, self::configStr('SMTPPort', '465'), _t('SMTP 服务端口'), _t('常用端口:无加密 25,SSL 465,TLS 587。'));
self::addInput($form, $SMTPPort);
self::addSection($form, '发件人与测试', '发件人姓名随邮件一起显示;先保存一次设置,再点「测试发送」验证 SMTP 是否可用。');
$fromName = new Typecho_Widget_Helper_Form_Element_Text('fromName', null, self::configStr('fromName', self::siteTitle()), _t('发件人姓名'), _t('邮件中显示的发件人名称,建议填写博客名称。'));
self::addInput($form, $fromName);
$testTo = new Typecho_Widget_Helper_Form_Element_Text('testTo', null, self::configStr('testTo', self::adminMail()), _t('测试收件邮箱'), _t('测试发送会优先发到这里;留空则发到站长收件邮箱。'));
self::addInput($form, $testTo);
/* 测试发送卡:紧跟在「发件人与测试」这两个字段后面,
不再被模板预览压到下面去(2026-11-12 按需求上移) */
$testUrl = self::testUrl($auth);
$test = new Typecho_Widget_Helper_Layout('div', array('data-mn-tab-follow' => '1'));
$test->html('<div class="cnot-test-card"><div><strong>测试发送邮件</strong><p>测试接口读的是已保存的配置,先保存再点。</p></div><a class="cnot-btn" href="' . self::e($testUrl) . '" target="_blank" rel="noopener noreferrer">测试发送</a></div>');
$form->addItem($test);
/* 邮件模板:单独一个小节标题,和上面「SMTP 服务配置」「发件人与测试」格式一致 */
self::addSection($form, '邮件模板', '点击「启用」选择模板,保存设置后生效;点「预览」查看大图。');
$template = new Typecho_Widget_Helper_Form_Element_Hidden('template', null, self::configStr('template', 'inkcard'));
$form->addInput($template);
$preview = new Typecho_Widget_Helper_Layout('div', array('data-mn-tab-follow' => '1'));
$preview->html(self::templatePreviewHtml());
$form->addItem($preview);
/* ================== 二、评论通知:通知对象、通知场景、邮件标题 ================== */
$form->addItem(self::configTabStart('notify', '评论通知'));
self::addSection($form, '通知对象与邮件标题', '设置站长收件邮箱、要不要打扰站长,以及各类通知邮件的标题格式。');
$adminfrom = new Typecho_Widget_Helper_Form_Element_Text('adminfrom', null, self::configStr('adminfrom', self::adminMail()), _t('站长收件邮箱'), _t('评论通知会发送到这个邮箱。'));
self::addInput($form, $adminfrom);
$zznotice = new Typecho_Widget_Helper_Form_Element_Radio('zznotice', array('0' => _t('通知'), '1' => _t('不通知')), self::configStr('zznotice', '0'), _t('是否通知站长'), _t('如果你已经有其他评论通知方式,可以选择不通知。'));
self::addInput($form, $zznotice);
$replynotice = new Typecho_Widget_Helper_Form_Element_Radio('replynotice', array('0' => _t('通知'), '1' => _t('不通知')), self::configStr('replynotice', '0'), _t('评论回复通知'), _t('有人回复访客评论时,是否通知被回复者。'));
self::addInput($form, $replynotice);
/* 前缀允许留空(清空 = 标题不加前缀),所以用 configRaw 读,不能用 configStr:
后者把空串当成「没配置过」,会把默认前缀又塞回表单 */
$subjectPrefix = new Typecho_Widget_Helper_Form_Element_Text('subjectPrefix', null, self::configRaw('subjectPrefix', '[' . self::siteTitle() . '] '), _t('邮件标题前缀'), _t('例如:[周天记] ,留空则不添加前缀。'));
self::addInput($form, $subjectPrefix);
/* ================== 三、记录与备份:发送记录保留条数、插件设置备份份数 ================== */
$form->addItem(self::configTabStart('record', '记录与备份'));
self::addSection($form, '记录保留与分页', '发送记录存在插件自己的数据表里,超出条数上限会自动清理最旧的,不影响已经发出的邮件。');
$mailKeep = new Typecho_Widget_Helper_Form_Element_Text('mailKeep', null, self::configRaw('mailKeep', (string) MailNotifier_MailLog::KEEP), _t('记录保留条数'), _t('只保留最近这么多条,多出来的从最旧的开始删。默认 2000,最少 50,最多 50000。'));
self::addInput($form, $mailKeep);
$mailPer = new Typecho_Widget_Helper_Form_Element_Radio('mailPer', array('20' => _t('20 条'), '50' => _t('50 条'), '100' => _t('100 条')), self::configRaw('mailPer', '20'), _t('每页显示条数'), _t('邮件历史列表默认每页显示多少条,列表上还能临时切换。'));
self::addInput($form, $mailPer);
self::addSection($form, '设置备份', '备份文件放在 data/backup/,每点一次顶部「备份」新增一份,超出份数上限时从最旧的开始删。份数改小后,下次备份时才会清掉多出来的部分。');
$backupKeep = new Typecho_Widget_Helper_Form_Element_Text('backupKeep', null, self::configRaw('backupKeep', (string) MailNotifier_Settings::BACKUP_KEEP), _t('备份最多保留份数'), _t('默认 5 份,最少 3 份,最多 20 份。顶部「历史备份」可以挑任意一份恢复,不必只认最新那份。'));
self::addInput($form, $backupKeep);
$hiddenAuth = new Typecho_Widget_Helper_Form_Element_Hidden('auth', null, $auth);
$form->addInput($hiddenAuth);
}
/**
* 设置页顶部的标题卡
*
* 标题右边放「记录」入口,左侧描述下方放「备份 / 恢复」。
* 只读 $_GET 里的 _cnot 结果参数来显示提示,不在这里做任何写操作。
*/
private static function heroCardHtml()
{
self::loadSupport();
$list = array();
try {
$list = MailNotifier_Settings::backups();
} catch (Exception $e) {
$list = array();
} catch (Throwable $e) {
$list = array();
}
$latest = empty($list) ? null : $list[0];
/* 上限读配置项,读失败也不能让设置页白屏 */
$keep = MailNotifier_Settings::BACKUP_KEEP;
try {
$keep = MailNotifier_Settings::backupKeep();
} catch (Exception $e) {
} catch (Throwable $e) {
}
$get = array();
foreach (array('_cnot', 'n', 't', 'detail', 'f', 'k') as $key) {
$get[$key] = isset($_GET[$key]) && is_scalar($_GET[$key]) ? (string) $_GET[$key] : '';
}
$notice = '';
$count = intval($get['n']);
$time = intval($get['t']);
$total = intval($get['f']);
$limit = intval($get['k']);
if ($get['_cnot'] === 'backup_ok') {
$notice = '<div class="cnot-note cnot-note-ok">设置已备份:' . $count . ' 项配置,' . self::e(date('Y-m-d H:i:s', $time)) . '。'
. ($total > 0 && $limit > 0 ? '当前共 ' . $total . ' 份(上限 ' . $limit . ' 份)。' : '')
. '</div>';
} elseif ($get['_cnot'] === 'restore_ok') {
$notice = '<div class="cnot-note cnot-note-ok">已恢复到 ' . self::e(date('Y-m-d H:i:s', $time)) . ' 的备份(' . $count . ' 项配置)。刷新本页即可看到表单里的值。</div>';
} elseif ($get['_cnot'] === 'backup_fail' || $get['_cnot'] === 'restore_fail') {
$notice = '<div class="cnot-note cnot-note-fail">'
. ($get['_cnot'] === 'backup_fail' ? '备份失败:' : '恢复失败:')
. self::e($get['detail'] !== '' ? $get['detail'] : '未知原因') . '</div>';
} elseif ($get['_cnot'] === 'token') {
$notice = '<div class="cnot-note cnot-note-fail">安全令牌校验失败,请刷新本页后重试。</div>';
} elseif ($get['_cnot'] === 'auth') {
$notice = '<div class="cnot-note cnot-note-fail">只有管理员可以备份或恢复插件设置。</div>';
} elseif ($get['_cnot'] === 'unknown') {
$notice = '<div class="cnot-note cnot-note-fail">无法识别的操作。</div>';
}
if ($latest) {
$meta = '上次备份 ' . self::e(date('Y-m-d H:i', $latest['created']))
. ' · 当前 ' . count($list) . ' 份(上限 ' . intval($keep) . ' 份)';
} else {
$meta = '还没有备份,点「备份」把当前设置存一份';
}
$backupUrl = self::settingsActionUrl('backup');
$restoreUrl = self::settingsActionUrl('restore');
$restoreBtn = $latest
? '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl) . '" onclick="return confirm(\'恢复会用最新一份备份覆盖当前插件设置,确定继续?\');">恢复</a>'
: '<span class="cnot-btn cnot-btn-ghost is-disabled" aria-disabled="true" title="还没有备份">恢复</span>';
/* 历史备份:只有一份时「恢复」就是它,不必再展开列表 */
$historyBtn = '';
$historyBox = '';
if (count($list) > 1) {
$rows = '';
foreach ($list as $index => $item) {
$rows .= '<div class="cnot-backup-item">'
. '<div class="cnot-backup-main">'
. '<span class="cnot-backup-time">' . self::e(date('Y-m-d H:i:s', $item['created'])) . '</span>'
. ($index === 0 ? '<span class="cnot-backup-tag">最新</span>' : '')
. '<span class="cnot-backup-desc">' . intval($item['count']) . ' 项配置 · '
. self::e(self::formatBytes($item['size']))
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
. '</span>'
. '</div>'
. '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl . '&file=' . rawurlencode($item['file'])) . '"'
. ' onclick="return confirm(\'用 ' . self::e(date('Y-m-d H:i', $item['created'])) . ' 的这份备份覆盖当前插件设置?\');">恢复</a>'
. '</div>';
}
$historyBtn = '<a class="cnot-btn cnot-btn-ghost" id="cnot-backups-btn" href="#cnot-backups"'
. ' aria-expanded="false" aria-controls="cnot-backups">历史备份</a>';
$historyBox = '<div class="cnot-backups" id="cnot-backups" hidden>'
. '<div class="cnot-backups-head"><strong>历史备份</strong><span>从新到旧,点「恢复」就用那一份覆盖当前设置</span></div>'
. $rows
. '</div>'
. '<script>(function(){var box=document.getElementById("cnot-backups");'
. 'var btn=document.getElementById("cnot-backups-btn");'
. 'if(!box||!btn||!btn.addEventListener){return;}'
. 'btn.addEventListener("click",function(e){'
. 'if(e&&e.preventDefault){e.preventDefault();}'
. 'var open=box.hasAttribute("hidden");'
. 'if(open){box.removeAttribute("hidden");}else{box.setAttribute("hidden","hidden");}'
. 'btn.textContent=open?"收起备份":"历史备份";'
. 'btn.setAttribute("aria-expanded",open?"true":"false");'
. 'return false;});'
. '})();</script>';
}
return '<div class="cnot-hero">'
. '<div class="cnot-hero-icon">✉</div>'
. '<div class="cnot-hero-text">'
. '<div class="cnot-hero-title">'
. '<h2>邮件通知</h2>'
. '<a class="cnot-btn cnot-btn-ghost cnot-hero-log" href="' . self::e(self::manageUrl()) . '">记录</a>'
. '</div>'
. '<p>配置 SMTP 后,新评论、待审评论和评论回复及其他二次开发调用邮件功能会自动发送邮件。</p>'
. '<div class="cnot-hero-ops">'
. '<a class="cnot-btn" href="' . self::e($backupUrl) . '">备份</a>'
. $restoreBtn
. $historyBtn
. '<span class="cnot-hero-meta">' . $meta . '</span>'
. '</div>'
. '</div>'
. '</div>'
. $notice
. $historyBox;
}
/**
* 备份文件大小的好读写法
*/
private static function formatBytes($bytes)
{
$bytes = max(0, intval($bytes));
if ($bytes < 1024) {
return $bytes . ' B';
}
if ($bytes < 1048576) {
return round($bytes / 1024, 1) . ' KB';
}
return round($bytes / 1048576, 1) . ' MB';
}
/**
* 后台「邮件历史」面板地址
*/
public static function manageUrl()
{
$options = self::options();
$adminUrl = '';
if ($options && isset($options->adminUrl)) {
$adminUrl = rtrim((string) $options->adminUrl, '/') . '/';
}
return $adminUrl . 'extending.php?panel=' . rawurlencode(self::PANEL_FILE);
}
/**
* 本插件的设置页地址(option-plugin.php?config=MailNotifier)
*
* @param string $query 追加的查询串,例如 _cnot=backup_ok
*/
public static function configUrl($query = '')
{
$options = self::options();
$adminUrl = '';
if ($options && isset($options->adminUrl)) {
$adminUrl = rtrim((string) $options->adminUrl, '/') . '/';
}
$url = $adminUrl . 'options-plugin.php?config=MailNotifier';
if ($query !== '') {
$url .= '&' . ltrim($query, '&');
}
return $url;
}
/**
* 备份 / 恢复动作的路由地址
*
* 和测试接口一样按站点的 rewrite 设置拼路径,没开 rewrite 时补 index.php。
*/
public static function settingsActionUrl($do)
{
$options = self::options();
$siteUrl = $options && isset($options->siteUrl) ? (string) $options->siteUrl : '';
$rewrite = $options && isset($options->rewrite) ? intval($options->rewrite) : 1;
return rtrim($siteUrl, '/') . '/' . ($rewrite ? '' : 'index.php/')
. 'mail-notifier-settings?do=' . rawurlencode($do)
. '&_=' . rawurlencode(self::mailLogToken());
}
public static function personalConfig(Typecho_Widget_Helper_Form $form) {}
private static function addSection($form, $title, $desc = '')
{
/* data-mn-tab-follow 让分组脚本把小节标题归进所在 Tab,跟着一起显隐 */
$layout = new Typecho_Widget_Helper_Layout('div', array('data-mn-tab-follow' => '1'));
$layout->html('<div class="cnot-section"><h3>' . self::e($title) . '</h3>' . ($desc !== '' ? '<p>' . self::e($desc) . '</p>' : '') . '</div>');
$form->addItem($layout);
}
private static function addInput($form, $input)
{
$input->setAttribute('class', 'typecho-option cnot-field');
$form->addInput($input);
}
/**
* Tab 分组标记:一个隐藏的 div,后面的设置项在浏览器里被归进这个 Tab
*
* 参考了 RssUnion 的做法:Typecho 的插件配置表单只能按顺序 addItem,
* 没法自己套容器,所以靠前端脚本按标记分组、用 display 控制显隐。
* 隐藏只是不显示,字段照旧提交,不会丢值。
*
* @param string $key Tab 的 key(也是 localStorage 记忆的值)
* @param string $title Tab 上显示的名字
*/
private static function configTabStart($key, $title)
{
$layout = new Typecho_Widget_Helper_Layout('div', array(
'class' => 'cnot-tab-start',
'data-mn-tab-start' => $key,
'data-mn-tab-title' => $title,
'style' => 'display:none',
));
/* 必须给点内容:Layout 内容为空时会渲染成 <div ... />,浏览器会把后面的设置项全吞进去 */
$layout->html(' ');
return $layout;
}
/**
* 设置页外壳:Tab 样式 + 分组脚本
*
* 输出锚点、Tab 条容器、一段 CSS 和一段 JS。JS 按 DOM 顺序遍历表单里
* 的所有元素:遇到 data-mn-tab-start 标记就切换当前组,遇到 typecho-option
* 或带 data-mn-tab-follow 的元素就归进当前组;「保存设置」按钮和只剩
* 隐藏域的占位项不归组。当前 Tab 记在 localStorage,刷新后停在原页签。
*/
private static function configShellHtml()
{
$css = '#mn-cfg-anchor{display:none}'
. '#mn-cfg-tabs{display:flex;flex-wrap:wrap;gap:2px;margin:0 0 16px;padding:0 0 0 2px;'
. 'max-width:920px;box-sizing:border-box;border-bottom:1px solid rgba(126,96,60,.30);font-size:14px;'
. 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}'
. '#mn-cfg-tabs .mn-tab{appearance:none;-webkit-appearance:none;background:none;border:1px solid transparent;'
. 'border-bottom:2px solid transparent;border-radius:10px 10px 0 0;padding:10px 20px;margin:0 0 -1px;'
. 'font-size:13.5px;line-height:1.4;font-family:inherit;color:#5d4c3d;opacity:.62;cursor:pointer;'
. 'font-weight:700;transition:opacity .15s,background .15s}'
. '#mn-cfg-tabs .mn-tab:hover{opacity:1;background:rgba(126,96,60,.08)}'
. '#mn-cfg-tabs .mn-tab:focus{outline:none;box-shadow:0 0 0 2px rgba(139,99,59,.30)}'
. '#mn-cfg-tabs .mn-tab.mn-active{opacity:1;color:#8b633b;border-bottom-color:#8b633b;'
. 'background:rgba(139,99,59,.08)}'
/* 深色(NewAdmin 的 body/#newadmin.dark) */
. '.dark #mn-cfg-tabs,#newadmin.dark #mn-cfg-tabs{border-bottom-color:rgba(255,255,255,.12)}'
. '.dark #mn-cfg-tabs .mn-tab,#newadmin.dark #mn-cfg-tabs .mn-tab{color:#9aa8bb}'
. '.dark #mn-cfg-tabs .mn-tab:hover,#newadmin.dark #mn-cfg-tabs .mn-tab:hover{background:rgba(255,255,255,.06)}'
. '.dark #mn-cfg-tabs .mn-tab.mn-active,#newadmin.dark #mn-cfg-tabs .mn-tab.mn-active{color:#d0a877;'
. 'border-bottom-color:#d0a877;background:rgba(208,168,119,.10)}';
$js = <<<'JS'
<script>
(function () {
"use strict";
function boot() {
var anchor = document.getElementById("mn-cfg-anchor");
if (!anchor) { return; }
var form = anchor.closest ? anchor.closest("form") : null;
if (!form) {
var node = anchor.parentNode;
while (node && node.nodeName !== "FORM") { node = node.parentNode; }
form = node;
}
if (!form) { return; }
var bar = document.getElementById("mn-cfg-tabs");
if (!bar) { return; }
var tabs = [], groups = {}, current = null;
var loose = [], skipped = [];
/* 按 DOM 顺序遍历所有后代元素,而不是只看 form.children:
Typecho 的 Layout 没内容时会渲染成自闭合标签,浏览器把它当开标签,
后面的设置项会全被裹进这个 div —— 只遍历直接子节点会漏归组。 */
var all = Array.prototype.slice.call(form.getElementsByTagName("*"));
for (var i = 0; i < all.length; i++) {
var el = all[i];
var start = el.getAttribute("data-mn-tab-start");
if (start) {
current = start;
if (!groups[start]) {
groups[start] = [];
tabs.push({ key: start, title: el.getAttribute("data-mn-tab-title") || start });
}
el.style.display = "none"; /* 标记本身不显示,但留在原地做锚点 */
continue;
}
var isItem = (el.className && (" " + el.className + " ").indexOf(" typecho-option ") >= 0)
|| (el.getAttribute && el.getAttribute("data-mn-tab-follow") !== null);
if (!isItem) { continue; }
/* 已经归到某个 Tab 的容器内部的元素,不再重复收一次 */
if (el.parentNode && el.parentNode.closest) {
var outer = el.parentNode.closest(".typecho-option");
if (outer && outer.getAttribute("data-mn-tab-owner")) { continue; }
}
/* 「保存设置」按钮也是 typecho-option 结构,不能收进来,否则会被某个 tab 带走 */
if (el.querySelector && el.querySelector('input[type="submit"], button[type="submit"]')) {
continue;
}
/* 只剩隐藏域的占位项(auth / template):永远不占地方 */
var text = (el.textContent || "").replace(/\s/g, "");
if (text === "" && el.querySelector && el.querySelector('input[type="hidden"]')) {
skipped.push(el);
continue;
}
if (!current) {
/* 第一个 Tab 标记之前就出现的设置项:兜底塞进第一个 Tab */
loose.push(el);
continue;
}
el.setAttribute("data-mn-tab-owner", current);
groups[current].push(el);
}
if (!tabs.length) { return; }
/* 开头漏网的设置项补进第一个 Tab */
if (loose.length) {
for (var q = 0; q < loose.length; q++) {
loose[q].setAttribute("data-mn-tab-owner", tabs[0].key);
groups[tabs[0].key].unshift(loose[q]);
}
}
var active = "";
var storeKey = "mailnotifier_cfg_tab";
function paint() {
for (var t = 0; t < tabs.length; t++) {
var list = groups[tabs[t].key] || [];
for (var n = 0; n < list.length; n++) {
list[n].style.display = (tabs[t].key === active) ? "" : "none";
}
}
for (var s = 0; s < skipped.length; s++) {
skipped[s].style.display = "none";
}
var btns = bar.children;
for (var b = 0; b < btns.length; b++) {
btns[b].className = btns[b].getAttribute("data-mn-tab-btn") === active
? "mn-tab mn-active" : "mn-tab";
}
}
function activate(key) {
active = key;
try { window.localStorage.setItem(storeKey, key); } catch (e) {}
paint();
}
bar.innerHTML = "";
for (var k = 0; k < tabs.length; k++) {
(function (tab) {
var btn = document.createElement("button");
btn.type = "button";
btn.className = "mn-tab";
btn.setAttribute("data-mn-tab-btn", tab.key);
btn.appendChild(document.createTextNode(tab.title));
btn.addEventListener("click", function () { activate(tab.key); });
bar.appendChild(btn);
})(tabs[k]);
}
var remembered = "";
try { remembered = window.localStorage.getItem(storeKey) || ""; } catch (e) {}
var hit = false;
for (var m = 0; m < tabs.length; m++) {
if (tabs[m].key === remembered) { hit = true; }
}
activate(hit ? remembered : tabs[0].key);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();
</script>
JS;
return '<span id="mn-cfg-anchor"></span>'
. '<style>' . $css . '</style>'
. '<div id="mn-cfg-tabs" role="tablist"></div>'
. $js;
}
private static function registerHook($newClass, $oldFactory, $hook, $method)
{
$callback = __CLASS__ . '::' . $method;
if (class_exists($newClass) && method_exists($newClass, 'pluginHandle')) {
$newClass::pluginHandle()->$hook = $callback;
return;
}
if (class_exists('Typecho_Plugin')) {
Typecho_Plugin::factory($oldFactory)->$hook = array(__CLASS__, $method);
}
}
public static function refinishComment($comment, $post = null)
{
if (self::configStr('enabled', '1') !== '1') {
return;
}
self::sendApprovedNotifications($comment, false);
}
public static function mark($comment, $edit, $status)
{
if (self::configStr('enabled', '1') !== '1') {
return;
}
if ($status === 'approved') {
self::sendApprovedNotifications($edit, true);
}
}
public static function serviceSend($param)
{
return self::sendNow((array) $param);
}
private static function sendApprovedNotifications($comment, $approvedFromAdmin = false)
{
/* 钩子传进来的评论对象偶尔会是「空壳」——异步链路里 Widget 的保护属性
过不了 JSON 序列化,走到这里只剩一个空对象,正文、作者、邮箱全都取
不到,邮件就成了只有一句提示的空壳信。只要 coid 还在,就回库按它把
关键字段补齐;字段齐全的原样返回,不多查一次库。 */
$comment = self::hydrateComment($comment);
$adminMail = self::configStr('adminfrom', self::adminMail());
$commentMail = self::value($comment, 'mail', '');
$parentId = intval(self::value($comment, 'parent', 0));
$sent = array();
/* 发信参数里顺手带上「这条通知是哪篇文章、哪条评论引起的」,
发送记录页要靠它显示关联文章。取不到的字段留空即可,不影响发信。 */
$ctx = array(
'coid' => intval(self::value($comment, 'coid', 0)),
'cid' => intval(self::value($comment, 'cid', 0)),
'postTitle' => (string) self::value($comment, 'title', ''),
'postUrl' => (string) self::value($comment, 'permalink', ''),
);
if (self::configStr('zznotice', '0') !== '1' && !$approvedFromAdmin && !self::sameMail($commentMail, $adminMail)) {
self::queueMail($adminMail, self::configStr('fromName', self::siteTitle()), self::subject('文章《' . self::value($comment, 'title', '') . '》有了新的评论'), self::mailBody($comment, 'owner'), $sent, array_merge($ctx, array('mailType' => 'owner')));
}
if ($parentId > 0 && self::configStr('replynotice', '0') !== '1') {
$parent = self::getParent($comment);
if (!empty($parent['mail']) && !self::sameMail($parent['mail'], $commentMail) && !self::sameMail($parent['mail'], $adminMail)) {
self::queueMail($parent['mail'], $parent['name'], self::subject('你在《' . self::value($comment, 'title', '') . '》的评论有了新回复'), self::mailBody($comment, 'guest'), $sent, array_merge($ctx, array('mailType' => 'guest')));
}
}
}
/**
* 把残缺的评论对象补齐
*
* 无论钩子从哪条链路进来(前台 Feedback、后台回复/审核 Edit、异步 service),
* 传进来的对象都可能是被序列化剥掉字段的空壳。这里按 coid 回库把
* 作者 / 邮箱 / 正文 / 标题 / cid 补上,让邮件正文永远有内容可填。
* 字段都在的对象原样返回,不发多余查询。
*
* @return mixed 原样返回传入的数组或对象(可能已被就地补全)
*/
private static function hydrateComment($comment)
{
$coid = intval(self::value($comment, 'coid', 0));
if ($coid <= 0) {
return $comment;
}
$needText = trim((string) self::value($comment, 'content', self::value($comment, 'text', ''))) === '';
$needAuthor = trim((string) self::value($comment, 'author', '')) === '';
$needMail = trim((string) self::value($comment, 'mail', '')) === '';
$needCid = intval(self::value($comment, 'cid', 0)) <= 0;
$needTitle = trim((string) self::value($comment, 'title', '')) === '';
if (!$needText && !$needAuthor && !$needMail && !$needCid && !$needTitle) {
return $comment;
}
try {
$db = self::db();
if ($db) {
$row = $db->fetchRow($db->select()->from('table.comments')->where('coid = ?', $coid));
if ($row) {
$cid = $needCid ? intval(isset($row['cid']) ? $row['cid'] : 0) : intval(self::value($comment, 'cid', 0));
if ($needCid) {
$comment = self::hydrateSet($comment, 'cid', $cid);
}
if ($needText) {
$comment = self::hydrateSet($comment, 'text', isset($row['text']) ? (string) $row['text'] : '');
}
if ($needAuthor) {
$comment = self::hydrateSet($comment, 'author', isset($row['author']) ? (string) $row['author'] : '');
}
if ($needMail) {
$comment = self::hydrateSet($comment, 'mail', isset($row['mail']) ? (string) $row['mail'] : '');
}
if ($needTitle && $cid > 0) {
$post = $db->fetchRow($db->select('title')->from('table.contents')->where('cid = ?', $cid));
if ($post && isset($post['title'])) {
$comment = self::hydrateSet($comment, 'title', (string) $post['title']);
}
}
}
}
} catch (Exception $e) {
} catch (Throwable $e) {
}
return $comment;
}
/**
* 就地给评论对象/数组补一个字段
*
* Widget 走 __set(会写进 row,title 这类派生字段会落到 #title 缓存键),
* stdClass 走动态属性,数组走下标。都失败也不抛错。
*/
private static function hydrateSet($comment, $key, $value)
{
if (is_array($comment)) {
$comment[$key] = $value;
return $comment;
}
if (is_object($comment)) {
try {
$comment->$key = $value;
} catch (Exception $e) {
} catch (Throwable $e) {
}
}
return $comment;
}
private static function queueMail($to, $name, $subject, $html, &$sent, $ctx = array())
{
$to = trim((string) $to);
if ($to === '' || isset($sent[strtolower($to)])) {
return false;
}
$sent[strtolower($to)] = true;
$param = array('to' => $to, 'name' => (string) $name, 'subject' => (string) $subject, 'html' => (string) $html);
// 记录用的上下文跟着一起去(异步发送时也随 JSON 传到 service 那一端)
foreach (array('mailType', 'coid', 'cid', 'postTitle', 'postUrl') as $key) {
if (isset($ctx[$key])) {
$param[$key] = $ctx[$key];
}
}
return self::dispatchMail($param);
}
private static function dispatchMail(array $param)
{
if (self::configStr('yibu', '0') === '1' && class_exists('Helper') && method_exists('Helper', 'requestService')) {
try {
Helper::requestService('mailNotifierSend', $param);
return true;
} catch (Exception $e) {
}
}
return self::sendNow($param);
}
public static function sendNow(array $param)
{
$result = self::deliverMail($param);
// 记录和发信解耦:记录写不进去也不能影响发信结果
self::logSentMail($param, $result);
return $result;
}
/**
* 真正发信(不含记录)
*
* 拆出来的原因:sendNow() 是插件对外的发信入口(Action 测试、Service 异步都走它),
* 记录逻辑只该挂在最外层,不应该跟着邮件正文构造混在一起。
*/
private static function deliverMail(array $param)
{
self::loadMailer();
$to = isset($param['to']) ? trim((string) $param['to']) : '';
if ($to === '') {
return array('ok' => false, 'message' => '收件邮箱为空');
}
$host = self::configStr('STMPHost', 'smtp.qq.com');
$user = self::configStr('SMTPUserName', '');
$password = self::configStr('SMTPPassword', '');
$from = self::configStr('from', $user);
$fromName = self::configStr('fromName', self::siteTitle());
/* configRaw:选「无安全加密」时存的是空串,用 configStr 会被回落成 ssl */
$secure = self::configRaw('SMTPSecure', 'ssl');
$port = intval(self::configStr('SMTPPort', $secure === 'ssl' ? '465' : ($secure === 'tls' ? '587' : '25')));
if ($port <= 0) {
$port = $secure === 'ssl' ? 465 : ($secure === 'tls' ? 587 : 25);
}
try {
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = $host;
$mail->Username = $user;
$mail->Password = $password;
if ($secure !== '') {
$mail->SMTPSecure = $secure;
}
$mail->Port = $port;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
),
);
$mail->setFrom($from, $fromName);
$mail->addAddress($to, isset($param['name']) ? (string) $param['name'] : '');
$mail->Subject = isset($param['subject']) ? (string) $param['subject'] : self::subject('评论通知');
$mail->isHTML(true);
$mail->Body = isset($param['html']) ? (string) $param['html'] : '';
$mail->AltBody = trim(strip_tags(str_replace(array('<br>', '<br/>', '<br />'), "\n", $mail->Body)));
$mail->send();
return array('ok' => true, 'message' => '发送成功');
} catch (Exception $e) {
return array('ok' => false, 'message' => $e->getMessage());
} catch (Throwable $e) {
return array('ok' => false, 'message' => $e->getMessage());
}
}
/**
* 写一条发送记录
*
* 任何异常都吞掉:这里只是「留个台账」,不能反过来把发信流程搞挂。
*/
private static function logSentMail(array $param, array $result)
{
try {
self::loadSupport();
MailNotifier_MailLog::add($param, $result);
} catch (Exception $e) {
} catch (Throwable $e) {
}
}
public static function sendTest($to = '')
{
if (self::configStr('enabled', '1') !== '1') {
return array('ok' => false, 'message' => '通知开关当前为关闭状态');
}
$to = trim((string) $to);
if ($to === '') {
$to = self::configStr('testTo', '');
}
if ($to === '') {
$to = self::configStr('adminfrom', self::adminMail());
}
$comment = self::testComment();
return self::sendNow(array(
'to' => $to,
'name' => self::configStr('fromName', self::siteTitle()),
'mailType' => 'test',
'postTitle' => '测试邮件',
'postUrl' => '',
'subject' => self::subject('测试邮件发送成功'),
'html' => self::mailBody($comment, 'notice'),
));
}
/**
* 按历史记录重发一封邮件(邮件历史页的「重发」按钮)
*
* 正文用记录里存的原文,SMTP 用当前保存的配置 —— 也就是说改过配置再重发,
* 走的是新配置。重发结果由 sendNow() 记成一条新记录,出现在列表顶部。
*
* @param array $row MailNotifier_MailLog::find() 取出的整行记录(body_text 已解码)
* @return array ok / message
*/
public static function resendFromLog(array $row)
{
$to = isset($row['to_mail']) ? trim((string) $row['to_mail']) : '';
if ($to === '') {
return array('ok' => false, 'message' => '这条记录没有收件邮箱');
}
$html = isset($row['body_text']) ? (string) $row['body_text'] : '';
if (trim($html) === '') {
return array('ok' => false, 'message' => '这条记录没有保存邮件正文,无法重发');
}
return self::sendNow(array(
'to' => $to,
'name' => isset($row['to_name']) ? (string) $row['to_name'] : '',
'subject' => isset($row['subject']) && $row['subject'] !== '' ? (string) $row['subject'] : self::subject('评论通知'),
'html' => $html,
'mailType' => isset($row['mail_type']) ? (string) $row['mail_type'] : 'notice',
'coid' => isset($row['coid']) ? intval($row['coid']) : 0,
'cid' => isset($row['cid']) ? intval($row['cid']) : 0,
'postTitle' => isset($row['post_title']) ? (string) $row['post_title'] : '',
'postUrl' => isset($row['post_url']) ? (string) $row['post_url'] : '',
));
}
private static function mailBody($comment, $type = 'owner')
{
$type = in_array($type, array('owner', 'guest', 'notice'), true) ? $type : 'owner';
$template = self::getTemplate($type);
$template = preg_replace('#<\?php#', '<!--', $template);
$template = preg_replace('#\?>#', '-->', $template);
$parent = array('name' => '', 'mail' => '', 'text' => '', 'md5' => '');
if (intval(self::value($comment, 'parent', 0)) > 0) {
$p = self::getParent($comment);
$parent = array(
'name' => isset($p['name']) ? $p['name'] : '',
'mail' => isset($p['mail']) ? $p['mail'] : '',
'text' => isset($p['text']) ? $p['text'] : '',
'md5' => isset($p['mail']) ? md5((string) $p['mail']) : '',
);
}
$created = self::value($comment, 'created', time());
if (!is_numeric($created)) {
$created = strtotime((string) $created);
}
if (!$created) {
$created = time();
}
$options = self::options();
$siteUrl = $options && isset($options->siteUrl) ? $options->siteUrl : '';
$siteTitle = $options && isset($options->title) ? $options->title : self::siteTitle();
$adminUrl = $options && isset($options->adminUrl) ? rtrim($options->adminUrl, '/') . '/manage-comments.php' : '';
$templateName = self::configStr('template', 'inkcard');
$statusText = array('approved' => '通过', 'waiting' => '待审', 'spam' => '垃圾');
$status = self::value($comment, 'status', 'approved');
$search = array('{title}', '{PostAuthor}', '{time}', '{commentText}', '{author}', '{mail}', '{md5}', '{ip}', '{permalink}', '{siteUrl}', '{siteTitle}', '{Pname}', '{Ptext}', '{Pmail}', '{Pmd5}', '{url}', '{manageurl}', '{status}');
$replace = array(
self::e(self::value($comment, 'title', '')),
self::e(self::getPostAuthorName($comment)),
date('Y-m-d H:i:s', intval($created)),
self::commentHtml(self::value($comment, 'content', self::value($comment, 'text', ''))),
self::e(self::value($comment, 'author', '')),
self::e(self::value($comment, 'mail', '')),
md5((string) self::value($comment, 'mail', '')),
self::e(self::value($comment, 'ip', '')),
self::e(self::value($comment, 'permalink', $siteUrl)),
self::e($siteUrl),
self::e($siteTitle),
self::e($parent['name']),
self::commentHtml($parent['text']),
self::e($parent['mail']),
self::e($parent['md5']),
self::e(self::templateAssetBaseUrl($templateName)),
self::e($adminUrl),
self::e(isset($statusText[$status]) ? $statusText[$status] : $status),
);
return str_replace($search, $replace, $template);
}
private static function templateAssetBaseUrl($templateName)
{
$templateName = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string) $templateName);
if ($templateName === '') {
$templateName = 'inkcard';
}
$siteUrl = rtrim(self::siteUrl(), '/');
if ($siteUrl === '') {
$scheme = 'http';
if ((!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
|| (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
|| (!empty($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443)) {
$scheme = 'https';
}
$host = isset($_SERVER['HTTP_HOST']) ? (string) $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? (string) $_SERVER['SERVER_NAME'] : '');
if ($host !== '') {
$siteUrl = $scheme . '://' . $host;
}
}
$origin = self::originUrl($siteUrl);
if ($origin === '') {
$origin = $siteUrl;
}
$options = self::options();
$pluginUrl = '';
if ($options && isset($options->pluginUrl)) {
$pluginUrl = trim((string) $options->pluginUrl);
}
if ($pluginUrl === '') {
$pluginUrl = '/usr/plugins';
}
if (preg_match('#^https?://#i', $pluginUrl)) {
$base = rtrim($pluginUrl, '/');
} elseif (strpos($pluginUrl, '//') === 0) {
$scheme = parse_url($siteUrl, PHP_URL_SCHEME);
$base = ($scheme ? $scheme : 'https') . ':' . rtrim($pluginUrl, '/');
} elseif (strpos($pluginUrl, '/') === 0) {
// 邮件客户端必须使用完整 URL。pluginUrl 通常是 /usr/plugins 或 /子目录/usr/plugins。
$base = rtrim($origin, '/') . rtrim($pluginUrl, '/');
} else {
$base = rtrim($siteUrl, '/') . '/' . trim($pluginUrl, '/');
}
return rtrim($base, '/') . '/MailNotifier/template/' . $templateName;
}
private static function originUrl($url)
{
$url = trim((string) $url);
if ($url === '') {
return '';
}
$parts = @parse_url($url);
if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) {
return rtrim($url, '/');
}
$origin = $parts['scheme'] . '://' . $parts['host'];
if (!empty($parts['port'])) {
$origin .= ':' . $parts['port'];
}
return $origin;
}
private static function getTemplate($type)
{
$template = preg_replace('/[^a-zA-Z0-9_\-]/', '', self::configStr('template', 'inkcard'));
$files = array(
dirname(__FILE__) . '/template/' . $template . '/' . $type . '.html',
dirname(__FILE__) . '/template/inkcard/' . $type . '.html',
);
foreach ($files as $file) {
if (is_file($file)) {
return (string) file_get_contents($file);
}
}
return '<div style="font-family:Arial,sans-serif;line-height:1.8"><h2>{title}</h2><div>{commentText}</div><p>{author} · {time}</p></div>';
}
private static function getParent($comment)
{
$parentId = intval(self::value($comment, 'parent', 0));
if ($parentId <= 0) {
return array('name' => '', 'mail' => '', 'text' => '');
}
try {
if (class_exists('Helper') && method_exists('Helper', 'widgetById')) {
$parent = Helper::widgetById('comments', $parentId);
return array(
'name' => self::value($parent, 'author', ''),
'mail' => self::value($parent, 'mail', ''),
'text' => self::value($parent, 'content', self::value($parent, 'text', '')),
);
}
} catch (Exception $e) {}
try {
$db = self::db();
if ($db) {
$row = $db->fetchRow($db->select()->from('table.comments')->where('coid = ?', $parentId));
if ($row) {
return array(
'name' => isset($row['author']) ? $row['author'] : '',
'mail' => isset($row['mail']) ? $row['mail'] : '',
'text' => isset($row['text']) ? $row['text'] : (isset($row['content']) ? $row['content'] : ''),
);
}
}
} catch (Exception $e) {}
return array('name' => '', 'mail' => '', 'text' => '');
}
private static function getPostAuthor($comment)
{
$ownerId = intval(self::value($comment, 'ownerId', 0));
if ($ownerId > 0) {
try {
$db = self::db();
if ($db) {
$row = $db->fetchRow($db->select()->from('table.users')->where('uid = ?', $ownerId));
if ($row && !empty($row['mail'])) {
return array('name' => !empty($row['screenName']) ? $row['screenName'] : (!empty($row['name']) ? $row['name'] : self::siteTitle()), 'mail' => $row['mail']);
}
}
} catch (Exception $e) {}
}
return array('name' => self::configStr('fromName', self::siteTitle()), 'mail' => self::configStr('adminfrom', self::adminMail()));
}
private static function getPostAuthorName($comment)
{
$author = self::getPostAuthor($comment);
return isset($author['name']) ? $author['name'] : self::siteTitle();
}
private static function value($source, $key, $default = '')
{
if (is_array($source) && array_key_exists($key, $source)) {
return $source[$key];
}
if (is_object($source)) {
try {
if (isset($source->$key)) {
return $source->$key;
}
} catch (Exception $e) {}
try {
if (method_exists($source, '__get')) {
$value = $source->$key;
return $value === null ? $default : $value;
}
} catch (Exception $e) {}
}
return $default;
}
/**
* 读一项插件配置
*
* 先读新键 plugin:MailNotifier;老站改名升级后、还没保存过一次设置之前,
* 配置只存在 plugin:CommentNotifier 里,这里回退过去读,功能不会因为改名断掉。
*/
public static function configStr($key, $default = '')
{
foreach (array('MailNotifier', self::LEGACY_NAME) as $pluginName) {
$value = self::pluginConfigValue($pluginName, $key);
if ($value !== null) {
return $value === '' ? $default : $value;
}
}
return $default;
}
/**
* 读一项配置,但保留「显式保存为空」的语义
*
* configStr() 把空字符串当成「没配置过」,会回落到默认值 —— 对 SMTP 服务器地址
* 这类字段是对的,但对「允许留空」的字段就成了「改不掉」:
* ① 邮件标题前缀:清空保存后又被拼回 [站点名]
* ② SMTP 加密模式:「无安全加密」存的就是空串,读出来却变成了 ssl
* 这些地方改用本方法:只有配置项根本不存在(null)时才用默认值。
*/
public static function configRaw($key, $default = '')
{
foreach (array('MailNotifier', self::LEGACY_NAME) as $pluginName) {
$value = self::pluginConfigValue($pluginName, $key);
if ($value !== null) {
return $value;
}
}
return $default;
}
/**
* 取某个插件配置项,读不到返回 null(用来区分「没有」和「空字符串」)
*
* @param string $pluginName
* @param string $key
* @return string|null
*/
private static function pluginConfigValue($pluginName, $key)
{
try {
$options = self::options();
if ($options && method_exists($options, 'plugin')) {
$plugin = $options->plugin($pluginName);
if ($plugin && isset($plugin->$key)) {
$value = $plugin->$key;
if (is_array($value)) {
return empty($value) ? '' : (string) reset($value);
}
return (string) $value;
}
}
} catch (Exception $e) {
} catch (Throwable $e) {
}
return null;
}
private static function templateOptions()
{
return array(
'inkcard' => _t('雅致风'),
'landscape' => _t('清爽风'),
'seal' => _t('科技风'),
'bamboo' => _t('温馨风'),
);
}
private static function testComment()
{
return array(
'title' => '测试邮件',
'author' => '测试访客',
'mail' => self::configStr('testTo', self::adminMail()),
'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',
'created' => time(),
'content' => '这是一封测试邮件。如果你能收到它,说明 SMTP 配置已经可以正常发送。',
'status' => 'waiting',
'permalink' => self::siteUrl(),
'parent' => 0,
);
}
private static function commentHtml($text)
{
$text = trim((string) $text);
if ($text === strip_tags($text)) {
return nl2br(self::breakAutoLinkedNumbers(self::e($text)));
}
return self::breakAutoLinkedNumbers($text);
}
private static function breakAutoLinkedNumbers($text)
{
return preg_replace_callback('/\d{7,}/', function ($matches) {
return implode('&#8203;', str_split($matches[0], 3));
}, (string) $text);
}
private static function subject($subject)
{
/* configRaw:前缀留空就是真的不加前缀,别回落成默认的 [站点名] */
return self::configRaw('subjectPrefix', '[' . self::siteTitle() . '] ') . $subject;
}
private static function sameMail($a, $b)
{
return strtolower(trim((string) $a)) === strtolower(trim((string) $b));
}
private static function loadMailer()
{
require_once dirname(__FILE__) . '/PHPMailer/Exception.php';
require_once dirname(__FILE__) . '/PHPMailer/PHPMailer.php';
require_once dirname(__FILE__) . '/PHPMailer/SMTP.php';
}
private static function db()
{
if (class_exists('Typecho_Db')) {
return Typecho_Db::get();
}
if (class_exists('Typecho\\Db')) {
return \Typecho\Db::get();
}
return null;
}
private static function options()
{
try {
if (class_exists('Helper') && method_exists('Helper', 'options')) {
return Helper::options();
}
} catch (Exception $e) {}
try {
if (class_exists('Typecho_Widget')) {
return Typecho_Widget::widget('Widget_Options');
}
} catch (Exception $e) {}
try {
if (class_exists('Widget\\Options')) {
return \Widget\Options::alloc();
}
} catch (Exception $e) {}
return null;
}
private static function siteTitle()
{
$options = self::options();
return $options && isset($options->title) ? (string) $options->title : '博客';
}
private static function siteUrl()
{
$options = self::options();
return $options && isset($options->siteUrl) ? (string) $options->siteUrl : '';
}
private static function adminMail()
{
$options = self::options();
if ($options && isset($options->adminEmail) && $options->adminEmail) {
return (string) $options->adminEmail;
}
return '';
}
private static function testUrl($auth)
{
$options = self::options();
$siteUrl = $options && isset($options->siteUrl) ? (string) $options->siteUrl : '';
$rewrite = $options && isset($options->rewrite) ? intval($options->rewrite) : 1;
$url = rtrim($siteUrl, '/') . '/' . ($rewrite ? '' : 'index.php/') . 'mail-notifier-test?auth=' . rawurlencode($auth);
$to = self::configStr('testTo', '');
if ($to !== '') {
$url .= '&to=' . rawurlencode($to);
}
return $url;
}
private static function randString($length = 32)
{
if (class_exists('Typecho_Common') && method_exists('Typecho_Common', 'randString')) {
return Typecho_Common::randString($length);
}
if (class_exists('Typecho\\Common') && method_exists('Typecho\\Common', 'randString')) {
return \Typecho\Common::randString($length);
}
return substr(hash('sha256', uniqid('', true) . mt_rand()), 0, $length);
}
public static function e($text)
{
return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}
/**
* 模板预览图的地址前缀
*
* 四张预览截图(1-4.webp)统一放在 template/seal/ 下,不跟随当前选中的模板目录:
* 它们只是「四套模板长什么样」的效果图,跟现在用哪套模板没关系。
* 单独抽这个方法是为了把这件事写清楚 —— 之前直接写 templateAssetBaseUrl('seal'),
* 读代码的人容易误以为是写错了目录。
*/
private static function previewImageBaseUrl()
{
return self::templateAssetBaseUrl('seal');
}
private static function templatePreviewHtml()
{
$current = self::configStr('template', 'inkcard');
$templates = array(
'inkcard' => array('雅致风', '1.webp'),
'landscape' => array('清爽风', '2.webp'),
'seal' => array('科技风', '3.webp'),
'bamboo' => array('温馨风', '4.webp'),
);
$html = '<div class="cnot-preview-wrap"><div class="cnot-preview-grid">';
$imageBase = self::previewImageBaseUrl();
foreach ($templates as $key => $info) {
$active = $key === $current ? ' is-active' : '';
$img = $imageBase . '/' . $info[1];
$html .= '<div class="cnot-preview-card' . $active . '" data-template="' . self::e($key) . '" data-title="' . self::e($info[0]) . '" data-img="' . self::e($img) . '">'
. '<span class="cnot-preview-title">' . self::e($info[0]) . '</span>'
. '<span class="cnot-preview-img"><img src="' . self::e($img) . '" alt="' . self::e($info[0]) . '"></span>'
. '<span class="cnot-preview-actions"><button type="button" class="cnot-preview-use">' . ($key === $current ? '已选择' : '启用') . '</button><button type="button" class="cnot-preview-open">预览</button></span>'
. '</div>';
}
$html .= '</div><div class="cnot-preview-modal" aria-hidden="true"><div class="cnot-preview-modal-box"><button type="button" class="cnot-preview-close">关闭</button><strong class="cnot-preview-modal-title"></strong><div class="cnot-preview-modal-body"></div></div></div></div><script>(function(){var cards=document.querySelectorAll(".cnot-preview-card");var field=document.querySelector("input[name=template]");var modal=document.querySelector(".cnot-preview-modal");var modalTitle=modal?modal.querySelector(".cnot-preview-modal-title"):null;var modalBody=modal?modal.querySelector(".cnot-preview-modal-body"):null;var closeBtn=modal?modal.querySelector(".cnot-preview-close"):null;if(!field){return;}function sync(v){for(var i=0;i<cards.length;i++){cards[i].className=cards[i].className.replace(/\\s?is-active/g,"");var btn=cards[i].querySelector(".cnot-preview-use");if(btn){btn.innerHTML="启用";btn.disabled=false;}if(cards[i].getAttribute("data-template")===v){cards[i].className += " is-active";if(btn){btn.innerHTML="已选择";btn.disabled=true;}}}}function choose(card){var v=card.getAttribute("data-template");field.value=v;sync(v);}function openPreview(card){if(!modal||!modalBody){return;}var title=card.getAttribute("data-title")||"";var img=card.getAttribute("data-img")||"";if(modalTitle){modalTitle.innerHTML=title;}modalBody.innerHTML="";if(img){var el=document.createElement("img");el.src=img;el.alt=title;modalBody.appendChild(el);}modal.className += " is-open";modal.setAttribute("aria-hidden","false");}function closePreview(){if(!modal){return;}modal.className=modal.className.replace(/\\s?is-open/g,"");modal.setAttribute("aria-hidden","true");}for(var i=0;i<cards.length;i++){(function(card){var use=card.querySelector(".cnot-preview-use");var open=card.querySelector(".cnot-preview-open");if(use){use.onclick=function(){choose(card);};}if(open){open.onclick=function(){openPreview(card);};}})(cards[i]);}if(closeBtn){closeBtn.onclick=closePreview;}if(modal){modal.onclick=function(e){e=e||window.event;if((e.target||e.srcElement)===modal){closePreview();}};}document.onkeydown=function(e){e=e||window.event;if(e.key==="Escape"||e.keyCode===27){closePreview();}};sync(field.value);})();</script>';
return $html;
}
private static function configStyleHtml()
{
return <<<'HTML'
<style>
.cnot-hero,.cnot-section,.cnot-test-card{box-sizing:border-box;max-width:920px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;}
.cnot-hero{position:relative;display:flex;align-items:flex-start;gap:18px;flex-wrap:wrap;margin:6px 0 12px;padding:22px 24px;border:1px solid rgba(126,96,60,.15);border-radius:18px;background:linear-gradient(135deg,rgba(255,253,248,.98),rgba(246,236,223,.86));box-shadow:0 14px 34px rgba(75,56,35,.075);overflow:hidden;}
.cnot-hero:after{content:"";position:absolute;right:-44px;top:-50px;width:170px;height:170px;border-radius:50%;background:rgba(126,96,60,.065);}
.cnot-hero-icon{position:relative;z-index:1;width:54px;height:54px;display:grid;place-items:center;flex:0 0 54px;border-radius:16px;color:#7f603d;background:linear-gradient(145deg,rgba(255,253,248,.88),rgba(239,225,207,.72));border:1px solid rgba(126,96,60,.18);font-size:25px;box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 12px 24px rgba(93,68,43,.08);}
.cnot-hero-text{position:relative;z-index:1;min-width:0;flex:1 1 300px;}
.cnot-hero h2{position:relative;z-index:1;margin:0;color:#2d2824;font-size:24px;line-height:1.25;font-weight:800;}
.cnot-hero p{position:relative;z-index:1;margin:8px 0 0;color:#6f6153;font-size:14px;line-height:1.75;}
.cnot-hero-title{position:relative;z-index:1;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
.cnot-hero-ops{position:relative;z-index:1;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:14px;}
.cnot-hero-meta{flex-basis:100%;margin-top:2px;color:#8d7b6a;font-size:11.5px;line-height:1.5;}
.cnot-hero .cnot-btn{height:36px;padding:0 16px;font-size:12.5px;}
.cnot-hero .cnot-hero-log{height:30px;padding:0 14px;font-size:12px;}
.cnot-section{margin:22px 0 12px;padding:16px 20px;border:1px solid rgba(126,96,60,.13);border-radius:16px;background:rgba(255,255,255,.78);box-shadow:0 12px 28px rgba(75,56,35,.04);}
.cnot-section h3{margin:0;color:#342b24;font-size:17px;font-weight:800;}
.cnot-section p{margin:7px 0 0;color:#887767;font-size:13px;line-height:1.6;}
.typecho-option.cnot-field{box-sizing:border-box;max-width:920px;margin:0 0 12px!important;padding:16px 18px!important;border:1px solid rgba(126,96,60,.14)!important;border-radius:16px!important;background:rgba(255,255,255,.84)!important;box-shadow:0 10px 28px rgba(75,56,35,.045)!important;}
.typecho-option.cnot-field label.typecho-label,.typecho-option.cnot-field .typecho-label{color:#5d4c3d!important;font-weight:800!important;font-size:13px!important;}
.typecho-option.cnot-field .description,.typecho-option.cnot-field p.description{color:#8d7b6a!important;font-size:12px!important;line-height:1.65!important;}
.typecho-option.cnot-field input[type=text],.typecho-option.cnot-field input[type=password],.typecho-option.cnot-field textarea,.typecho-option.cnot-field select{box-sizing:border-box;min-height:40px;border:1px solid rgba(126,96,60,.18)!important;border-radius:13px!important;background:rgba(255,252,247,.86)!important;padding:9px 12px!important;color:#2d2824!important;outline:none!important;box-shadow:inset 0 1px 0 rgba(255,255,255,.65)!important;}
.typecho-option.cnot-field input[type=text]:focus,.typecho-option.cnot-field textarea:focus,.typecho-option.cnot-field select:focus{border-color:rgba(125,94,57,.44)!important;box-shadow:0 0 0 4px rgba(125,94,57,.08)!important;}
.typecho-option.cnot-field input[type=radio],.typecho-option.cnot-field input[type=checkbox]{margin-right:5px;}
.cnot-test-card{display:flex;align-items:center;justify-content:space-between;gap:16px;box-sizing:border-box;max-width:920px;margin:18px 0 22px;padding:18px 20px;border:1px solid rgba(126,96,60,.16);border-radius:18px;background:linear-gradient(135deg,rgba(255,255,255,.92),rgba(249,241,230,.82));box-shadow:0 14px 34px rgba(75,56,35,.06);}
.cnot-test-card>div{min-width:0;flex:1 1 auto;}
.cnot-test-card strong{display:block;color:#342b24;font-size:16px;}
.cnot-test-card p{margin:6px 0 0;color:#887767;font-size:13px;line-height:1.6;}
.cnot-btn{height:40px;padding:0 18px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;text-decoration:none!important;color:#fff!important;background:linear-gradient(135deg,#8b633b,#a77b4c);box-shadow:0 12px 24px rgba(125,90,50,.20);font-size:13px;font-weight:800;white-space:nowrap;}
.cnot-btn:hover{transform:translateY(-1px);}
.cnot-preview-wrap{box-sizing:border-box;max-width:920px;margin:0 0 18px;padding:16px 18px 18px;border:1px solid rgba(126,96,60,.14);border-radius:18px;background:rgba(255,255,255,.86);box-shadow:0 12px 30px rgba(75,56,35,.045);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;}
.cnot-preview-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;}
.cnot-preview-card{position:relative;display:block;box-sizing:border-box;width:100%;padding:8px;border:1px solid rgba(126,96,60,.13);border-radius:16px;background:#fffaf4;text-align:left;cursor:default;transition:.18s ease;box-shadow:0 8px 18px rgba(75,56,35,.04);}
.cnot-preview-card:hover{transform:translateY(-2px);border-color:rgba(126,96,60,.34);box-shadow:0 14px 28px rgba(75,56,35,.09);}
.cnot-preview-card.is-active{border-color:#8b633b;background:#fbf2e6;box-shadow:0 0 0 3px rgba(139,99,59,.12),0 14px 28px rgba(75,56,35,.09);}
.cnot-preview-card.is-active:after{content:"当前使用";position:absolute;right:12px;top:10px;padding:3px 8px;border-radius:999px;background:#8b633b;color:#fff;font-size:11px;font-weight:800;box-shadow:0 6px 14px rgba(75,56,35,.16);}
.cnot-preview-img{display:block;border-radius:12px;overflow:hidden;background:#f3eadf;border:1px solid rgba(126,96,60,.10);}
.cnot-preview-img img{display:block;width:100%;height:auto;border:0;background:#f8f2e8;}
.cnot-preview-title{display:block;margin:0 2px 8px;color:#342b24;font-weight:800;font-size:14px;line-height:1.4;}
.cnot-preview-actions{display:flex;gap:8px;margin:9px 2px 0;}
.cnot-preview-actions button{height:28px;padding:0 14px;border-radius:999px;font-size:12px;font-weight:700;cursor:pointer;transition:.18s ease;}
.cnot-preview-use{border:1px solid rgba(126,96,60,.20);background:#f3eadf;color:#765438;box-shadow:none;}
.cnot-preview-card.is-active .cnot-preview-use{background:#eadfce;color:#6d4a2b;border-color:rgba(126,96,60,.24);box-shadow:none;}
.cnot-preview-card.is-active .cnot-preview-use:disabled{cursor:default;opacity:1;}
.cnot-preview-open{background:#fff;color:#6d4a2b;border:1px solid rgba(126,96,60,.18);}
.cnot-preview-actions button:hover{transform:translateY(-1px);}
.cnot-preview-modal{position:fixed;z-index:99999;left:0;right:0;top:0;bottom:0;display:none;align-items:center;justify-content:center;padding:28px;background:rgba(34,28,22,.62);}
.cnot-preview-modal.is-open{display:flex;}
.cnot-preview-modal-box{position:relative;box-sizing:border-box;width:min(920px,96vw);max-height:92vh;padding:18px;border-radius:18px;background:#fffaf4;box-shadow:0 24px 80px rgba(0,0,0,.28);overflow:auto;}
.cnot-preview-close{position:absolute;right:14px;top:14px;border:0;border-radius:999px;background:#efe2d1;color:#6d4a2b;padding:7px 12px;font-size:12px;font-weight:800;cursor:pointer;}
.cnot-preview-modal-title{display:block;margin:2px 80px 14px 4px;color:#342b24;font-size:18px;}
.cnot-preview-modal-body{border:1px solid rgba(126,96,60,.14);border-radius:14px;background:#fff;overflow:hidden;}
.cnot-preview-modal-body img{display:block;width:100%;height:auto;max-height:78vh;object-fit:contain;background:#f8f2e8;}
/* 标题右边的「记录」小按钮 + 左侧的「备份 / 恢复」 */
.cnot-btn-ghost{color:#6d4a2b!important;background:rgba(255,255,255,.92)!important;border:1px solid rgba(126,96,60,.22);box-shadow:0 8px 18px rgba(75,56,35,.06);}
.cnot-btn-ghost.is-disabled{opacity:.42;cursor:not-allowed;box-shadow:none;}
.cnot-btn-ghost.is-disabled:hover{transform:none;}
.cnot-note{box-sizing:border-box;max-width:920px;margin:-2px 0 16px;padding:10px 14px;border-radius:12px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;font-size:12.5px;line-height:1.65;}
.cnot-note-ok{color:#2f8a57;background:rgba(47,138,87,.10);border:1px solid rgba(47,138,87,.18);}
.cnot-note-fail{color:#b4503f;background:rgba(180,80,63,.10);border:1px solid rgba(180,80,63,.18);}
/* 历史备份列表:默认 hidden,点「历史备份」按钮展开 */
.cnot-backups{box-sizing:border-box;max-width:920px;margin:-6px 0 18px;padding:4px 6px 6px;border:1px solid rgba(126,96,60,.14);border-radius:16px;background:rgba(255,255,255,.86);box-shadow:0 12px 30px rgba(75,56,35,.045);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;}
.cnot-backups[hidden]{display:none;}
.cnot-backups-head{display:flex;align-items:baseline;gap:9px;flex-wrap:wrap;padding:11px 11px 9px;}
.cnot-backups-head strong{color:#342b24;font-size:14px;}
.cnot-backups-head span{color:#8d7b6a;font-size:11.5px;line-height:1.5;}
.cnot-backup-item{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 11px;border-radius:12px;}
.cnot-backup-item+.cnot-backup-item{border-top:1px solid rgba(126,96,60,.10);}
.cnot-backup-main{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;min-width:0;}
.cnot-backup-time{color:#3f342a;font-size:13px;font-weight:700;font-variant-numeric:tabular-nums;}
.cnot-backup-tag{padding:1px 7px;border-radius:999px;background:#8b633b;color:#fff;font-size:10.5px;font-weight:800;line-height:1.7;}
.cnot-backup-desc{color:#8d7b6a;font-size:11.5px;}
.cnot-backup-item .cnot-btn{flex:0 0 auto;height:30px;padding:0 14px;font-size:12px;}
/* ------------------------------------------------------------------
* 深色模式
*
* NewAdmin 把 dark 加在 body 上(服务端按 cookie 渲染),切换主题时
* Alpine 会立刻给 #newadmin 也加上 dark;两种都命中,写成 .dark 前缀
* 就同时覆盖,点切换不用刷新也能跟着变。
* 其余后台没有 dark 类,保持上面的浅色规则。
* ------------------------------------------------------------------ */
.dark .cnot-hero{background:linear-gradient(135deg,#1b2635,#18212f);border-color:rgba(255,255,255,.10);box-shadow:0 14px 34px rgba(0,0,0,.28);}
.dark .cnot-hero:after{background:rgba(208,168,119,.07);}
.dark .cnot-hero-icon{color:#d0a877;background:linear-gradient(145deg,#202c3d,#1a2434);border-color:rgba(255,255,255,.10);box-shadow:inset 0 1px 0 rgba(255,255,255,.06),0 12px 24px rgba(0,0,0,.30);}
.dark .cnot-hero h2{color:#e8eef7;}
.dark .cnot-hero p{color:#9aa8bb;}
.dark .cnot-section{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 28px rgba(0,0,0,.22);}
.dark .cnot-section h3{color:#e8eef7;}
.dark .cnot-section p{color:#93a2b8;}
.dark .typecho-option.cnot-field{background:#1b2635!important;border-color:rgba(255,255,255,.10)!important;box-shadow:0 10px 28px rgba(0,0,0,.22)!important;}
.dark .typecho-option.cnot-field label.typecho-label,.dark .typecho-option.cnot-field .typecho-label{color:#dbe4f0!important;}
.dark .typecho-option.cnot-field label{color:#dbe4f0;}
.dark .typecho-option.cnot-field .description,.dark .typecho-option.cnot-field p.description{color:#93a2b8!important;}
.dark .typecho-option.cnot-field input[type=text],.dark .typecho-option.cnot-field input[type=password],.dark .typecho-option.cnot-field textarea,.dark .typecho-option.cnot-field select{background:#141e2b!important;border-color:rgba(255,255,255,.12)!important;color:#e8eef7!important;box-shadow:none!important;}
.dark .typecho-option.cnot-field input[type=text]:focus,.dark .typecho-option.cnot-field textarea:focus,.dark .typecho-option.cnot-field select:focus{border-color:rgba(208,168,119,.50)!important;box-shadow:0 0 0 4px rgba(208,168,119,.12)!important;}
.dark .typecho-option.cnot-field input[type=text]::placeholder,.dark .typecho-option.cnot-field textarea::placeholder{color:#6b7a8d!important;}
.dark .cnot-test-card{background:linear-gradient(135deg,#1b2635,#18212f);border-color:rgba(255,255,255,.10);box-shadow:0 14px 34px rgba(0,0,0,.26);}
.dark .cnot-test-card strong{color:#e8eef7;}
.dark .cnot-test-card p{color:#93a2b8;}
.dark .cnot-btn{background:linear-gradient(135deg,#9d7247,#bb8c57);box-shadow:0 12px 24px rgba(0,0,0,.30);}
.dark .cnot-hero-meta{color:#93a2b8;}
.dark .cnot-btn-ghost{color:#e8d0ad!important;background:rgba(255,255,255,.06)!important;border-color:rgba(255,255,255,.14);box-shadow:none;}
.dark .cnot-note-ok{color:#4ade80;background:rgba(74,222,128,.10);border-color:rgba(74,222,128,.20);}
.dark .cnot-note-fail{color:#f87171;background:rgba(248,113,113,.10);border-color:rgba(248,113,113,.20);}
.dark .cnot-backups{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 30px rgba(0,0,0,.22);}
.dark .cnot-backups-head strong{color:#e8eef7;}
.dark .cnot-backups-head span{color:#93a2b8;}
.dark .cnot-backup-item+.cnot-backup-item{border-top-color:rgba(255,255,255,.08);}
.dark .cnot-backup-time{color:#e8eef7;}
.dark .cnot-backup-tag{background:#d0a877;color:#18212f;}
.dark .cnot-backup-desc{color:#93a2b8;}
.dark .cnot-preview-wrap{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 30px rgba(0,0,0,.22);}
.dark .cnot-preview-card{background:#16202d;border-color:rgba(255,255,255,.10);box-shadow:0 8px 18px rgba(0,0,0,.22);}
.dark .cnot-preview-card:hover{border-color:rgba(208,168,119,.42);box-shadow:0 14px 28px rgba(0,0,0,.32);}
.dark .cnot-preview-card.is-active{border-color:#d0a877;background:#1e2a3a;box-shadow:0 0 0 3px rgba(208,168,119,.16),0 14px 28px rgba(0,0,0,.26);}
.dark .cnot-preview-card.is-active:after{background:#d0a877;color:#18212f;}
.dark .cnot-preview-title{color:#e8eef7;}
.dark .cnot-preview-img{background:#101928;border-color:rgba(255,255,255,.08);}
.dark .cnot-preview-img img{background:#101928;}
.dark .cnot-preview-use{background:#243247;color:#d0a877;border-color:rgba(255,255,255,.12);}
.dark .cnot-preview-card.is-active .cnot-preview-use{background:#2b3a4f;color:#e8d0ad;border-color:rgba(208,168,119,.28);}
.dark .cnot-preview-open{background:#1f2b3d;color:#e8d0ad;border-color:rgba(255,255,255,.12);}
.dark .cnot-preview-modal-box{background:#1b2635;box-shadow:0 24px 80px rgba(0,0,0,.55);}
.dark .cnot-preview-close{background:#243247;color:#d0a877;}
.dark .cnot-preview-modal-title{color:#e8eef7;}
.dark .cnot-preview-modal-body{background:#0e1621;border-color:rgba(255,255,255,.08);}
.dark .cnot-preview-modal-body img{background:#0e1621;}
@media(max-width:680px){.cnot-hero{padding:16px 14px;align-items:flex-start}.cnot-hero-icon{width:44px;height:44px;flex-basis:44px;border-radius:14px}.cnot-hero h2{font-size:20px}.cnot-hero p{font-size:12px;line-height:1.55}.cnot-section{padding:13px 14px}.typecho-option.cnot-field{padding:13px 14px!important}.cnot-test-card{align-items:stretch;flex-direction:column;padding:15px 14px;gap:12px}.cnot-test-card strong{font-size:15px}.cnot-test-card p{font-size:12px;line-height:1.55}.cnot-btn{box-sizing:border-box;width:100%;height:42px;display:flex;}.cnot-preview-grid{grid-template-columns:1fr;gap:12px}.cnot-preview-title{font-size:14px}.cnot-preview-actions button{height:28px}.cnot-preview-modal{padding:10px}.cnot-preview-modal-box{width:100%;max-height:94vh;padding:12px}.cnot-preview-modal-title{font-size:16px;margin-right:70px}.cnot-hero-title{gap:10px}.cnot-hero .cnot-hero-log{width:auto;flex:0 0 auto;height:28px;padding:0 12px;font-size:12px}.cnot-hero-ops{margin-top:10px;gap:8px}.cnot-hero-ops .cnot-btn{box-sizing:border-box;width:auto;flex:1 1 0;min-width:0;height:38px;padding:0 8px;font-size:12px}.cnot-hero-meta{flex-basis:100%}.cnot-backups{padding:2px 4px 4px}.cnot-backups-head{padding:10px 9px 8px;gap:5px}.cnot-backup-item{padding:9px;gap:9px}.cnot-backup-item .cnot-btn{box-sizing:border-box;width:auto;flex:0 0 auto;height:32px;padding:0 12px;font-size:12px}}
</style>
HTML;
}
}