'/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('
测试发送邮件测试接口读的是已保存的配置,先保存再点。
测试发送 ');
$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 = '设置已备份:' . $count . ' 项配置,' . self::e(date('Y-m-d H:i:s', $time)) . '。'
. ($total > 0 && $limit > 0 ? '当前共 ' . $total . ' 份(上限 ' . $limit . ' 份)。' : '')
. '
';
} elseif ($get['_cnot'] === 'restore_ok') {
$notice = '已恢复到 ' . self::e(date('Y-m-d H:i:s', $time)) . ' 的备份(' . $count . ' 项配置)。刷新本页即可看到表单里的值。
';
} elseif ($get['_cnot'] === 'backup_fail' || $get['_cnot'] === 'restore_fail') {
$notice = ''
. ($get['_cnot'] === 'backup_fail' ? '备份失败:' : '恢复失败:')
. self::e($get['detail'] !== '' ? $get['detail'] : '未知原因') . '
';
} elseif ($get['_cnot'] === 'token') {
$notice = '安全令牌校验失败,请刷新本页后重试。
';
} elseif ($get['_cnot'] === 'auth') {
$notice = '只有管理员可以备份或恢复插件设置。
';
} elseif ($get['_cnot'] === 'unknown') {
$notice = '无法识别的操作。
';
}
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
? '恢复'
: '恢复';
/* 历史备份:只有一份时「恢复」就是它,不必再展开列表 */
$historyBtn = '';
$historyBox = '';
if (count($list) > 1) {
$rows = '';
foreach ($list as $index => $item) {
$rows .= ''
. '
'
. '' . self::e(date('Y-m-d H:i:s', $item['created'])) . ''
. ($index === 0 ? '最新' : '')
. '' . intval($item['count']) . ' 项配置 · '
. self::e(self::formatBytes($item['size']))
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
. ''
. '
'
. '
恢复'
. '
';
}
$historyBtn = '历史备份';
$historyBox = ''
. '
历史备份从新到旧,点「恢复」就用那一份覆盖当前设置
'
. $rows
. '
'
. '';
}
return ''
. '
✉
'
. '
'
. '
'
. '
配置 SMTP 后,新评论、待审评论和评论回复及其他二次开发调用邮件功能会自动发送邮件。
'
. '
'
. '
备份'
. $restoreBtn
. $historyBtn
. '
' . $meta . ''
. '
'
. '
'
. '
'
. $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('' . self::e($title) . '
' . ($desc !== '' ? '
' . self::e($desc) . '
' : '') . '
');
$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 内容为空时会渲染成 ,浏览器会把后面的设置项全吞进去 */
$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'
JS;
return ''
. ''
. ''
. $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('
', '
', '
'), "\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);
$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 '{title}
{commentText}
{author} · {time}
';
}
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('', 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 = '';
$imageBase = self::previewImageBaseUrl();
foreach ($templates as $key => $info) {
$active = $key === $current ? ' is-active' : '';
$img = $imageBase . '/' . $info[1];
$html .= '
'
. '
' . self::e($info[0]) . ''
. '
![' . self::e($info[0]) . '](' . self::e($img) . ')
'
. '
'
. '
';
}
$html .= '
';
return $html;
}
private static function configStyleHtml()
{
return <<<'HTML'
HTML;
}
}