diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/Action.php b/Action.php new file mode 100644 index 0000000..385bed4 --- /dev/null +++ b/Action.php @@ -0,0 +1,148 @@ +test(); + } + + public function test() + { + $auth = isset($_REQUEST['auth']) ? trim((string) $_REQUEST['auth']) : ''; + $savedAuth = MailNotifier_Plugin::configStr('auth', ''); + header('Content-Type: text/html; charset=UTF-8'); + + if ($savedAuth === '' || !hash_equals($savedAuth, $auth)) { + $this->renderResult(false, '测试密钥不正确,请从插件设置页点击“测试发送”。'); + return; + } + + $to = isset($_REQUEST['to']) ? trim((string) $_REQUEST['to']) : ''; + $result = MailNotifier_Plugin::sendTest($to); + $this->renderResult(!empty($result['ok']), isset($result['message']) ? $result['message'] : ''); + } + + /** + * 插件设置备份 / 恢复 + * + * 入口在「插件设置」页顶部,但动作不能交给 options-plugin.php: + * 那页的表单是 Typecho 自己的保存表单,里面再嵌一个 form 属于非法 HTML, + * 浏览器会把内层 form 丢掉,点备份反而触发一次「保存设置」。 + * 所以走独立路由,处理完 302 回设置页,用 _cnot 参数把结果带回去。 + */ + public function settings() + { + if (!class_exists('MailNotifier_Settings')) { + require_once dirname(__FILE__) . '/Settings.php'; + } + + $user = null; + try { + $user = Typecho_Widget::widget('Widget_User'); + } catch (Exception $e) { + $user = null; + } catch (Throwable $e) { + $user = null; + } + + $isAdmin = false; + try { + $isAdmin = $user && $user->pass('administrator', true); + } catch (Exception $e) { + $isAdmin = false; + } catch (Throwable $e) { + $isAdmin = false; + } + + if (!$isAdmin) { + $this->redirectTo(MailNotifier_Plugin::configUrl('_cnot=auth')); + return; + } + + if (!MailNotifier_Plugin::checkMailLogToken(isset($_GET['_']) ? (string) $_GET['_'] : '')) { + $this->redirectTo(MailNotifier_Plugin::configUrl('_cnot=token')); + return; + } + + $action = isset($_GET['do']) ? trim((string) $_GET['do']) : ''; + + if ($action === 'backup') { + $result = MailNotifier_Settings::backup(); + if (!empty($result['ok'])) { + $this->redirectTo(MailNotifier_Plugin::configUrl( + '_cnot=backup_ok&n=' . intval($result['count']) + . '&t=' . intval($result['created']) + . '&f=' . intval(isset($result['total']) ? $result['total'] : 0) + . '&k=' . intval(isset($result['keep']) ? $result['keep'] : 0) + )); + return; + } + $this->redirectTo(MailNotifier_Plugin::configUrl( + '_cnot=backup_fail&detail=' . rawurlencode((string) $result['message']) + )); + return; + } + + if ($action === 'restore') { + /* 不传 file 就是恢复最新一份;传了走文件名白名单校验(restoreLatest 内部 + 还会再 basename + isBackupName 校验一次,这里只挡住数组之类的怪值) */ + $file = isset($_GET['file']) && is_scalar($_GET['file']) ? trim((string) $_GET['file']) : ''; + $result = MailNotifier_Settings::restoreLatest($file); + if (!empty($result['ok'])) { + $this->redirectTo(MailNotifier_Plugin::configUrl( + '_cnot=restore_ok&n=' . intval($result['count']) . '&t=' . intval($result['created']) + )); + return; + } + $this->redirectTo(MailNotifier_Plugin::configUrl( + '_cnot=restore_fail&detail=' . rawurlencode((string) $result['message']) + )); + return; + } + + $this->redirectTo(MailNotifier_Plugin::configUrl('_cnot=unknown')); + } + + /** + * 跳转(优先走 Typecho 的 Response,它会正确记下 302) + */ + private function redirectTo($url) + { + try { + if (isset($this->response) && is_object($this->response) && method_exists($this->response, 'redirect')) { + $this->response->redirect($url); + exit; + } + } catch (Exception $e) { + } catch (Throwable $e) { + } + + header('Location: ' . $url, true, 302); + exit; + } + + private function renderResult($ok, $message) + { + $title = $ok ? '测试邮件发送成功' : '测试邮件发送失败'; + $badge = $ok ? '成功' : '失败'; + $color = $ok ? '#2f8a57' : '#b4503f'; + $bg = $ok ? 'rgba(47,138,87,.10)' : 'rgba(180,80,63,.10)'; + echo '' . MailNotifier_Plugin::e($title) . '
' . $badge . '

' . MailNotifier_Plugin::e($title) . '

' . MailNotifier_Plugin::e($message) . '

关闭页面
'; + } +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4d24b35 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,38 @@ +# MailNotifier 更新日志 + +> 本文件记录本插件的所有修改与变化。本次整理(2026-11-22)为规范化记录起点。 + +## 插件信息 + +- 名称:MailNotifier +- 版本:2.0.3 +- 作者:石头厝 +- 说明:邮件通知插件 + +## 记录格式约定 + +每次修改按如下格式在**最上方**追加一条记录(新的在上): + +``` +## YYYY-MM-DD · 版本号 —— 一句话概述 + +- 改动点 1 +- 改动点 2 +- 影响范围 / 注意事项(若有) +- 对应备份:备份/YYYY-MM-DD-修改内容简短说明修改前/ +``` + +## 2026-11-22 · 2.0.3 —— 统一作者与链接 + +- `Plugin.php` 头部 `@author` 统一为「石头厝」 +- `@link` 统一为 `https://www.shitoucuo.com/` +- 影响范围:仅头部元信息,不涉及功能代码 +- 对应备份:`备份/2026-11-22-统一作者和链接修改前/` + +--- + +## 2026-11-22 · 2.0.3 —— 建立规范化备份与更新日志 + +- 建立 `备份/` 文件夹并生成本次整理前全量备份 `备份/2026-11-22-规范化整理修改前/` +- 创建本更新日志,作为后续所有修改的记录起点 +- 说明:本次仅做规范化整理,未改动插件功能代码 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7951bd8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 石头厝 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MailLog.php b/MailLog.php new file mode 100644 index 0000000..f7f0212 --- /dev/null +++ b/MailLog.php @@ -0,0 +1,813 @@ + zlib 压缩(最常见,体积约为原文的 1/7) + * b64: 环境没有 zlib 时的退路 + * 其它 早期手工写入的原文 + * 好处有两个:一是不用担心数据库字符集是 utf8 还是 utf8mb4(编码后全是 ASCII), + * 二是邮件正文里那套内联样式压缩后能省掉大量空间。 + * + * @package MailNotifier + */ + +if (!defined('__TYPECHO_ROOT_DIR__')) { + exit; +} + +class MailNotifier_MailLog +{ + /** 逻辑表名(Typecho 会替换 table. 前缀) */ + const TABLE = 'table.mailnotifier_mail'; + + /** 物理表名后缀 */ + const TABLE_SUFFIX = 'mailnotifier_mail'; + + /** 最多保留多少条记录,超出后自动清理最旧的(默认值,实际值可在插件设置「发送记录」里改) */ + const KEEP = 2000; + + /** + * 实际生效的记录上限 + * + * 设置页「发送记录」页签可以改这个数;这里统一做一次夹取: + * 填 0 或负数会退成默认值,小于 50 按 50 算 —— 否则清理逻辑会变成 + * 「每次发信都把旧记录全清掉」,比不清理更难发现。 + */ + public static function keepLimit() + { + $value = self::KEEP; + + if (class_exists('MailNotifier_Plugin') && method_exists('MailNotifier_Plugin', 'configRaw')) { + $configured = intval(MailNotifier_Plugin::configRaw('mailKeep', (string) self::KEEP)); + if ($configured > 0) { + $value = $configured; + } + } + + return max(50, min(50000, $value)); + } + + /** 本请求内是否已确认表存在 */ + private static $tableReady = false; + + /** 本请求内是否已经试过旧表改名 */ + private static $migrated = false; + + /** + * 邮件类型 → 中文名 + */ + public static function typeLabels() + { + return array( + 'owner' => '站长通知', + 'guest' => '回复通知', + 'notice' => '通知邮件', + 'test' => '测试邮件', + ); + } + + public static function typeLabel($type) + { + $labels = self::typeLabels(); + if (isset($labels[$type])) { + return $labels[$type]; + } + return $type === '' ? '未分类' : $type; + } + + /** + * 取数据库对象 + */ + public static function db() + { + if (class_exists('Typecho_Db')) { + try { + return Typecho_Db::get(); + } catch (Exception $e) { + } + } + if (class_exists('Typecho\\Db')) { + try { + return \Typecho\Db::get(); + } catch (Exception $e) { + } + } + return null; + } + + /** + * 物理表名 + */ + public static function tableName($db = null) + { + $db = $db ? $db : self::db(); + if (!$db) { + return ''; + } + $prefix = ''; + try { + $prefix = $db->getPrefix(); + } catch (Exception $e) { + $prefix = ''; + } + return $prefix . self::TABLE_SUFFIX; + } + + /** + * 建表(幂等) + * + * 发信时插入失败会自己补建一次,管理页打开时也会补一次, + * 所以「覆盖升级、没重新启用插件」的站也能自己长出新表。 + */ + public static function ensureTable() + { + if (self::$tableReady) { + return true; + } + + $db = self::db(); + if (!$db) { + return false; + } + + $table = self::tableName($db); + $adapter = ''; + try { + $adapter = strtolower((string) $db->getAdapterName()); + } catch (Exception $e) { + $adapter = ''; + } + + // 插件原名 CommentNotifier:老表还叫 *_commentnotifier_mail, + // 建新表之前先把它改名接过来,已有记录就不会凭空消失。 + self::migrateLegacyTable($db, $table, $adapter); + + /* + * 字符集分两步走:先试 utf8mb4(能存 emoji 与生僻字), + * 老版本 MySQL(5.5.3 以前)不认 utf8mb4 会报错,这时退成「不指定字符集」, + * 交给数据库默认值 —— 也就是这个站本来就用的编码。 + */ + $attempts = array(); + if (strpos($adapter, 'pgsql') !== false || strpos($adapter, 'postgre') !== false) { + $attempts[] = self::pgsqlDdl($table); + } elseif (strpos($adapter, 'sqlite') !== false) { + $attempts[] = self::sqliteDdl($table); + $attempts[] = self::mysqlDdl($table, ''); + } else { + $attempts[] = self::mysqlDdl($table, 'utf8mb4'); + $attempts[] = self::mysqlDdl($table, ''); + } + + foreach ($attempts as $sql) { + try { + $db->query($sql, 2); // 2 = Typecho_Db::WRITE + self::$tableReady = true; + return true; + } catch (Exception $e) { + self::logError('建表失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('建表失败:' . $e->getMessage()); + } + } + + return false; + } + + /** + * 把改名前的记录表接过来(幂等) + * + * 只在旧表存在、新表还不存在时才会成功;其余情况 RENAME 会失败, + * 直接忽略即可 —— 不能因为迁移失败挡住后面的建表。 + * + * @param object $db + * @param string $table 新表名(带前缀) + * @param string $adapter 适配器名(小写) + */ + private static function migrateLegacyTable($db, $table, $adapter) + { + if (self::$migrated) { + return; + } + self::$migrated = true; + + if (!is_string($table) || $table === '') { + return; + } + + $legacy = ''; + try { + $legacy = (string) $db->getPrefix() . 'commentnotifier_mail'; + } catch (Exception $e) { + return; + } catch (Throwable $e) { + return; + } + + if ($legacy === '' || $legacy === $table) { + return; + } + + // 先确认「新表还没有、旧表确实在」,不能直接试 RENAME: + // SQLite 适配器在 prepare 阶段失败时打印的是 Warning 而不是抛异常, + // 页面上会冒一条 "no such table: ...",很难看。 + if (self::tableExists($db, $table, $adapter) || !self::tableExists($db, $legacy, $adapter)) { + return; + } + + $sql = ''; + if (strpos($adapter, 'sqlite') !== false || strpos($adapter, 'pgsql') !== false || strpos($adapter, 'postgre') !== false) { + $sql = 'ALTER TABLE "' . $legacy . '" RENAME TO "' . $table . '"'; + } else { + $sql = 'RENAME TABLE `' . $legacy . '` TO `' . $table . '`'; + } + + try { + $db->query($sql, 2); // 2 = 写操作 + } catch (Exception $e) { + // 旧表不存在 / 新表已建好,都属于正常情况 + } catch (Throwable $e) { + } + } + + /** + * 表是否存在(三种适配器各查各的元数据) + * + * @param object $db + * @param string $table + * @param string $adapter + * @return bool + */ + private static function tableExists($db, $table, $adapter) + { + try { + if (strpos($adapter, 'sqlite') !== false) { + $row = $db->fetchRow( + $db->select(array('COUNT(*)' => 'num')) + ->from('sqlite_master') + ->where('type = ?', 'table') + ->where('name = ?', $table) + ); + return !empty($row) && intval($row['num']) > 0; + } + + $schema = (strpos($adapter, 'pgsql') !== false || strpos($adapter, 'postgre') !== false) + ? 'public' + : null; + + $query = $db->select(array('COUNT(*)' => 'num')) + ->from('information_schema.tables') + ->where('table_name = ?', $table); + + if ($schema === null) { + $query->where('table_schema = DATABASE()'); + } else { + $query->where('table_schema = ?', $schema); + } + + $row = $db->fetchRow($query); + return !empty($row) && intval($row['num']) > 0; + } catch (Exception $e) { + return false; + } catch (Throwable $e) { + return false; + } + } + + private static function mysqlDdl($table, $charset) + { + $sql = 'CREATE TABLE IF NOT EXISTS `' . $table . '` (' + . '`id` int(10) unsigned NOT NULL AUTO_INCREMENT,' + . '`coid` int(10) unsigned NOT NULL DEFAULT 0,' + . '`cid` int(10) unsigned NOT NULL DEFAULT 0,' + . "`post_title` varchar(255) NOT NULL DEFAULT ''," + . "`post_url` varchar(500) NOT NULL DEFAULT ''," + . "`mail_type` varchar(20) NOT NULL DEFAULT ''," + . "`to_mail` varchar(190) NOT NULL DEFAULT ''," + . "`to_name` varchar(120) NOT NULL DEFAULT ''," + . "`subject` varchar(255) NOT NULL DEFAULT ''," + . '`body` mediumtext,' + . '`body_size` int(10) unsigned NOT NULL DEFAULT 0,' + . "`status` varchar(10) NOT NULL DEFAULT ''," + . "`message` varchar(500) NOT NULL DEFAULT ''," + . '`created` int(10) unsigned NOT NULL DEFAULT 0,' + . 'PRIMARY KEY (`id`),' + . 'KEY `created` (`created`)' + . ') ENGINE=InnoDB'; + + if ($charset !== '') { + $sql .= ' DEFAULT CHARSET=' . $charset; + } + + return $sql; + } + + private static function sqliteDdl($table) + { + return 'CREATE TABLE IF NOT EXISTS "' . $table . '" (' + . '"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,' + . '"coid" INTEGER NOT NULL DEFAULT 0,' + . '"cid" INTEGER NOT NULL DEFAULT 0,' + . '"post_title" VARCHAR(255) NOT NULL DEFAULT \'\',' + . '"post_url" VARCHAR(500) NOT NULL DEFAULT \'\',' + . '"mail_type" VARCHAR(20) NOT NULL DEFAULT \'\',' + . '"to_mail" VARCHAR(190) NOT NULL DEFAULT \'\',' + . '"to_name" VARCHAR(120) NOT NULL DEFAULT \'\',' + . '"subject" VARCHAR(255) NOT NULL DEFAULT \'\',' + . '"body" TEXT,' + . '"body_size" INTEGER NOT NULL DEFAULT 0,' + . '"status" VARCHAR(10) NOT NULL DEFAULT \'\',' + . '"message" VARCHAR(500) NOT NULL DEFAULT \'\',' + . '"created" INTEGER NOT NULL DEFAULT 0' + . ')'; + } + + private static function pgsqlDdl($table) + { + return 'CREATE TABLE IF NOT EXISTS "' . $table . '" (' + . '"id" SERIAL PRIMARY KEY,' + . '"coid" integer NOT NULL DEFAULT 0,' + . '"cid" integer NOT NULL DEFAULT 0,' + . '"post_title" varchar(255) NOT NULL DEFAULT \'\',' + . '"post_url" varchar(500) NOT NULL DEFAULT \'\',' + . '"mail_type" varchar(20) NOT NULL DEFAULT \'\',' + . '"to_mail" varchar(190) NOT NULL DEFAULT \'\',' + . '"to_name" varchar(120) NOT NULL DEFAULT \'\',' + . '"subject" varchar(255) NOT NULL DEFAULT \'\',' + . '"body" text,' + . '"body_size" integer NOT NULL DEFAULT 0,' + . '"status" varchar(10) NOT NULL DEFAULT \'\',' + . '"message" varchar(500) NOT NULL DEFAULT \'\',' + . '"created" integer NOT NULL DEFAULT 0' + . ')'; + } + + /** + * 写入一条发送记录 + * + * @param array $mail 发信参数(to/name/subject/html + 可选 mailType/coid/cid/postTitle/postUrl) + * @param array $result sendNow() 的返回值,ok / message + * @return bool + */ + public static function add(array $mail, array $result) + { + $db = self::db(); + if (!$db) { + return false; + } + + $html = isset($mail['html']) ? (string) $mail['html'] : ''; + $row = array( + 'coid' => isset($mail['coid']) ? intval($mail['coid']) : 0, + 'cid' => isset($mail['cid']) ? intval($mail['cid']) : 0, + 'post_title' => self::cut(isset($mail['postTitle']) ? $mail['postTitle'] : '', 250), + 'post_url' => self::cut(isset($mail['postUrl']) ? $mail['postUrl'] : '', 490), + 'mail_type' => self::cut(isset($mail['mailType']) ? $mail['mailType'] : 'owner', 18), + 'to_mail' => self::cut(isset($mail['to']) ? $mail['to'] : '', 180), + 'to_name' => self::cut(isset($mail['name']) ? $mail['name'] : '', 110), + 'subject' => self::cut(isset($mail['subject']) ? $mail['subject'] : '', 250), + 'body' => self::encodeBody($html), + 'body_size' => strlen($html), + 'status' => !empty($result['ok']) ? 'ok' : 'fail', + 'message' => self::cut(isset($result['message']) ? $result['message'] : '', 490), + 'created' => time(), + ); + + $saved = self::insert($db, $row); + + /* 第一次失败最常见的原因就是「表还没建」—— 覆盖升级、没重新启用插件的站。 + 补建一次再试;还不成就把 4 字节字符(emoji 之类)洗掉再试, + 保证数据库是 utf8(三字节)的老站也不会丢记录。 */ + if (!$saved) { + self::$tableReady = false; + self::ensureTable(); + $saved = self::insert($db, $row); + } + if (!$saved) { + $saved = self::insert($db, self::scrubRow($row)); + } + + if ($saved) { + self::prune(); + } + + return $saved; + } + + private static function insert($db, array $row) + { + try { + $db->query($db->insert(self::TABLE)->rows($row)); + return true; + } catch (Exception $e) { + self::logError('写入发送记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('写入发送记录失败:' . $e->getMessage()); + } + return false; + } + + /** + * 只保留最近 keepLimit() 条 + */ + private static function prune() + { + $db = self::db(); + if (!$db) { + return; + } + + $keep = self::keepLimit(); + + try { + if (self::countAll() <= $keep) { + return; + } + + $edge = $db->fetchRow( + $db->select('id')->from(self::TABLE) + ->order('id', Typecho_Db::SORT_DESC) + ->offset($keep - 1) + ->limit(1) + ); + + if ($edge && !empty($edge['id'])) { + $db->query($db->delete(self::TABLE)->where('id < ?', intval($edge['id']))); + } + } catch (Exception $e) { + self::logError('清理旧记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('清理旧记录失败:' . $e->getMessage()); + } + } + + public static function countAll() + { + $db = self::db(); + if (!$db) { + return 0; + } + try { + $row = $db->fetchObject($db->select(array('COUNT(*)' => 'num'))->from(self::TABLE)); + return $row ? intval($row->num) : 0; + } catch (Exception $e) { + } catch (Throwable $e) { + } + return 0; + } + + /** + * 统计:总 / 成功 / 失败 + */ + public static function stats() + { + $stats = array('total' => 0, 'ok' => 0, 'fail' => 0); + $db = self::db(); + if (!$db) { + return $stats; + } + + try { + $rows = $db->fetchAll( + $db->select('status', array('COUNT(*)' => 'num'))->from(self::TABLE)->group('status') + ); + foreach ((array) $rows as $row) { + $key = isset($row['status']) ? (string) $row['status'] : ''; + $num = isset($row['num']) ? intval($row['num']) : 0; + $stats['total'] += $num; + if ($key === 'ok') { + $stats['ok'] += $num; + } elseif ($key === 'fail') { + $stats['fail'] += $num; + } + } + } catch (Exception $e) { + } catch (Throwable $e) { + } + + return $stats; + } + + /** + * 分页取记录(不取正文,正文走 find() 单独读) + * + * @param array $filter status / type / keyword + * @param int $page + * @param int $perPage + * @return array rows / total / pages / page + */ + public static function page(array $filter, $page = 1, $perPage = 20) + { + $db = self::db(); + $result = array('rows' => array(), 'total' => 0, 'pages' => 0, 'page' => 1); + if (!$db) { + return $result; + } + + $page = max(1, intval($page)); + $perPage = max(1, min(200, intval($perPage))); + $status = isset($filter['status']) ? (string) $filter['status'] : ''; + $type = isset($filter['type']) ? (string) $filter['type'] : ''; + $keyword = isset($filter['keyword']) ? trim((string) $filter['keyword']) : ''; + $types = self::typeLabels(); + + try { + $countQuery = $db->select(array('COUNT(*)' => 'num'))->from(self::TABLE); + $listQuery = $db->select( + 'id', 'coid', 'cid', 'post_title', 'post_url', 'mail_type', + 'to_mail', 'to_name', 'subject', 'body_size', 'status', 'message', 'created' + )->from(self::TABLE); + + if ($status === 'ok' || $status === 'fail') { + $countQuery->where('status = ?', $status); + $listQuery->where('status = ?', $status); + } + if ($type !== '' && array_key_exists($type, $types)) { + $countQuery->where('mail_type = ?', $type); + $listQuery->where('mail_type = ?', $type); + } + if ($keyword !== '') { + $like = '%' . $keyword . '%'; + $countQuery->where('to_mail LIKE ? OR subject LIKE ? OR post_title LIKE ?', $like, $like, $like); + $listQuery->where('to_mail LIKE ? OR subject LIKE ? OR post_title LIKE ?', $like, $like, $like); + } + + $countRow = $db->fetchObject($countQuery); + $total = $countRow ? intval($countRow->num) : 0; + $pages = $total > 0 ? (int) ceil($total / $perPage) : 0; + if ($pages > 0 && $page > $pages) { + $page = $pages; + } + + $rows = $db->fetchAll( + $listQuery->order('id', Typecho_Db::SORT_DESC) + ->limit($perPage) + ->offset(($page - 1) * $perPage) + ); + + return array( + 'rows' => (array) $rows, + 'total' => $total, + 'pages' => $pages, + 'page' => $page, + ); + } catch (Exception $e) { + self::logError('读取发送记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('读取发送记录失败:' . $e->getMessage()); + } + + return $result; + } + + /** + * 取单条记录,正文已解码到 body_text + */ + public static function find($id) + { + $db = self::db(); + if (!$db) { + return null; + } + + try { + $row = $db->fetchRow( + $db->select()->from(self::TABLE)->where('id = ?', intval($id))->limit(1) + ); + if (!$row) { + return null; + } + $row['body_text'] = self::decodeBody(isset($row['body']) ? $row['body'] : ''); + return $row; + } catch (Exception $e) { + self::logError('读取单条记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('读取单条记录失败:' . $e->getMessage()); + } + return null; + } + + public static function remove($id) + { + $db = self::db(); + if (!$db) { + return false; + } + try { + $db->query($db->delete(self::TABLE)->where('id = ?', intval($id))); + return true; + } catch (Exception $e) { + self::logError('删除记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('删除记录失败:' . $e->getMessage()); + } + return false; + } + + /** + * 批量删除(邮件历史页的多选删除) + * + * id 全部过 intval 再拼进 IN 列表,没有注入面;每 100 个一组, + * 防止一次勾选过多把 SQL 撑得过长。 + * + * @param array $ids 记录 id 列表 + * @return int 实际删掉的条数 + */ + public static function removeMany(array $ids) + { + $db = self::db(); + if (!$db) { + return 0; + } + + $clean = array(); + foreach ($ids as $id) { + $id = intval($id); + if ($id > 0) { + $clean[$id] = true; + } + } + $clean = array_keys($clean); + if (empty($clean)) { + return 0; + } + + $count = 0; + foreach (array_chunk($clean, 100) as $chunk) { + try { + $db->query($db->delete(self::TABLE)->where('id IN (' . implode(',', $chunk) . ')')); + $count += count($chunk); + } catch (Exception $e) { + self::logError('批量删除记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('批量删除记录失败:' . $e->getMessage()); + } + } + return $count; + } + + /** + * 清空所有记录 + * + * @return int 清掉的条数 + */ + public static function clearAll() + { + $db = self::db(); + if (!$db) { + return 0; + } + + $total = self::countAll(); + try { + $db->query($db->delete(self::TABLE)); + return $total; + } catch (Exception $e) { + self::logError('清空记录失败:' . $e->getMessage()); + } catch (Throwable $e) { + self::logError('清空记录失败:' . $e->getMessage()); + } + return 0; + } + + /* ------------------------------------------------------------------ + * 正文编码 / 解码 + * ------------------------------------------------------------------ */ + + public static function encodeBody($html) + { + $html = (string) $html; + if ($html === '') { + return ''; + } + + if (function_exists('gzcompress')) { + $gz = @gzcompress($html, 6); + if ($gz !== false && $gz !== '') { + return 'gz:' . base64_encode($gz); + } + } + + return 'b64:' . base64_encode($html); + } + + public static function decodeBody($stored) + { + $stored = (string) $stored; + if ($stored === '') { + return ''; + } + + if (strncmp($stored, 'gz:', 3) === 0) { + if (!function_exists('gzuncompress')) { + return ''; + } + $raw = base64_decode(substr($stored, 3)); + if ($raw === false) { + return ''; + } + $out = @gzuncompress($raw); + return $out === false ? '' : $out; + } + + if (strncmp($stored, 'b64:', 4) === 0) { + $raw = base64_decode(substr($stored, 4)); + return $raw === false ? '' : $raw; + } + + return $stored; + } + + /* ------------------------------------------------------------------ + * 小工具 + * ------------------------------------------------------------------ */ + + /** + * 按字符截断 + */ + public static function cut($text, $length) + { + $text = (string) $text; + $length = intval($length); + if ($length <= 0) { + return ''; + } + + if (function_exists('mb_substr')) { + return mb_substr($text, 0, $length, 'UTF-8'); + } + + if (strlen($text) <= $length) { + return $text; + } + + $cut = substr($text, 0, $length); + // 往回退到完整的 UTF-8 字符边界 + $i = strlen($cut) - 1; + while ($i >= 0 && (ord($cut[$i]) & 0xC0) === 0x80) { + $i--; + } + if ($i >= 0) { + $need = 1; + $byte = ord($cut[$i]); + if (($byte & 0xF8) === 0xF0) { + $need = 4; + } elseif (($byte & 0xF0) === 0xE0) { + $need = 3; + } elseif (($byte & 0xE0) === 0xC0) { + $need = 2; + } + if ($i + $need > strlen($cut)) { + $cut = substr($cut, 0, $i); + } + } + + return $cut; + } + + /** + * 去掉 4 字节 UTF-8 字符(emoji 等),给三字节 utf8 的老库兜底 + */ + private static function scrubRow(array $row) + { + foreach ($row as $key => $value) { + if (is_string($value) && $key !== 'body') { + $row[$key] = preg_replace('/[\xF0-\xF4][\x80-\xBF]{3}/', '', $value); + } + } + return $row; + } + + public static function jsonEncode($data) + { + $flags = 0; + if (defined('JSON_UNESCAPED_UNICODE')) { + $flags |= JSON_UNESCAPED_UNICODE; + } + if (defined('JSON_UNESCAPED_SLASHES')) { + $flags |= JSON_UNESCAPED_SLASHES; + } + + $json = json_encode($data, $flags); + if ($json === false && defined('JSON_PARTIAL_OUTPUT_ON_ERROR')) { + $json = json_encode($data, $flags | JSON_PARTIAL_OUTPUT_ON_ERROR); + } + + return $json; + } + + public static function logError($message) + { + if (function_exists('error_log')) { + @error_log('[MailNotifier] ' . $message); + } + } +} diff --git a/Manage.php b/Manage.php new file mode 100644 index 0000000..cd06a34 --- /dev/null +++ b/Manage.php @@ -0,0 +1,916 @@ +pass('administrator', true); + } +} catch (Exception $e) { + $cnotIsAdmin = false; +} catch (Throwable $e) { + $cnotIsAdmin = false; +} + +if (!$cnotIsAdmin) { + include 'header.php'; + include 'menu.php'; + echo '
' + . '
只有管理员可以查看邮件历史的发送记录。
'; + include 'footer.php'; + return; +} + +/* ------------------------------------------------------------------ + * 动作:预览邮件正文(GET,输出原始 HTML) + * ------------------------------------------------------------------ */ +if ($cnotAction === 'preview') { + if (!MailNotifier_Plugin::checkMailLogToken($cnotGet('_'))) { + while (ob_get_level() > 0) { + ob_end_clean(); + } + header('Content-Type: text/plain; charset=UTF-8', true, 403); + echo '链接已失效,请回到「邮件历史」页面重新打开。'; + return; + } + + $cnotRow = MailNotifier_MailLog::find(intval($cnotGet('id'))); + while (ob_get_level() > 0) { + ob_end_clean(); + } + header('Content-Type: text/html; charset=UTF-8'); + + if (!$cnotRow) { + echo '
记录不存在或已被删除。
'; + return; + } + + $cnotBody = isset($cnotRow['body_text']) ? $cnotRow['body_text'] : ''; + if (trim($cnotBody) === '') { + echo '
这条记录没有保存邮件正文。
'; + return; + } + + echo $cnotBody; + return; +} + +/* ------------------------------------------------------------------ + * 动作:备份 / 恢复 / 清空 / 删除(POST + 令牌) + * ------------------------------------------------------------------ */ +if ($_SERVER['REQUEST_METHOD'] === 'POST' && $cnotAction !== '') { + /* + * 跳转必须走 Typecho 的 Response,不能只 header('Location:'): + * 后台的响应是在 shutdown 阶段由 Response 统一发出的,它会用自己记的状态码 + * (默认 200)盖掉我们设的 302,浏览器于是把「跳转」当成一个普通页面, + * 刷新就会重复提交。Response::redirect() 会把状态码记成 302,才是对的。 + */ + $cnotResponse = (isset($response) && is_object($response) && method_exists($response, 'redirect')) ? $response : null; + + $cnotRedirect = function ($query) use ($cnotBase, $cnotResponse) { + $url = $cnotBase . '&' . $query; + if ($cnotResponse) { + try { + $cnotResponse->redirect($url); + return $url; + } catch (Exception $e) { + } catch (Throwable $e) { + } + } + header('Location: ' . $url, true, 302); + return $url; + }; + + if (!MailNotifier_Plugin::checkMailLogToken($cnotPost('_'))) { + $cnotRedirect('msg=token'); + exit; + } + + if ($cnotAction === 'clear') { + $cnotCount = MailNotifier_MailLog::clearAll(); + $cnotRedirect('msg=clear_ok&n=' . intval($cnotCount)); + exit; + } + + if ($cnotAction === 'delete') { + MailNotifier_MailLog::remove(intval($cnotPost('id'))); + $cnotRedirect('msg=delete_ok'); + exit; + } + + /* 多选删除:ids 是逗号分隔的记录 id,由列表页的表单提交 */ + if ($cnotAction === 'delete_multi') { + $cnotIds = array(); + foreach (explode(',', (string) $cnotPost('ids')) as $cnotId) { + $cnotId = intval(trim($cnotId)); + if ($cnotId > 0) { + $cnotIds[] = $cnotId; + } + } + $cnotCount = MailNotifier_MailLog::removeMany($cnotIds); + $cnotRedirect('msg=delete_multi_ok&n=' . intval($cnotCount)); + exit; + } + + /* 重发:按记录里存的正文、当前的 SMTP 配置再发一次,结果记成新记录 */ + if ($cnotAction === 'resend') { + $cnotRow = MailNotifier_MailLog::find(intval($cnotPost('id'))); + if (!$cnotRow) { + $cnotRedirect('msg=resend_fail&detail=' . rawurlencode('记录不存在或已被删除')); + exit; + } + + $cnotResult = MailNotifier_Plugin::resendFromLog($cnotRow); + if (!empty($cnotResult['ok'])) { + $cnotRedirect('msg=resend_ok'); + } else { + $cnotRedirect('msg=resend_fail&detail=' . rawurlencode(MailNotifier_MailLog::cut( + isset($cnotResult['message']) ? $cnotResult['message'] : '未知原因', + 180 + ))); + } + exit; + } + + $cnotRedirect('msg=unknown'); + exit; +} + +/* ------------------------------------------------------------------ + * 列表数据 + * ------------------------------------------------------------------ */ +$cnotFilters = array( + 'status' => $cnotGet('status'), + 'type' => $cnotGet('type'), + 'keyword' => $cnotGet('keyword'), +); +if ($cnotFilters['status'] !== 'ok' && $cnotFilters['status'] !== 'fail') { + $cnotFilters['status'] = ''; +} +if (!array_key_exists($cnotFilters['type'], MailNotifier_MailLog::typeLabels())) { + $cnotFilters['type'] = ''; +} + +/* 每页条数:列表上可以临时切,没传参时用插件设置里存的默认值 */ +$cnotPerPage = intval($cnotGet('per', (string) MailNotifier_Plugin::configRaw('mailPer', '20'))); +$cnotPerOptions = array(20, 50, 100); +if (!in_array($cnotPerPage, $cnotPerOptions, true)) { + $cnotPerPage = 20; +} + +$cnotPage = max(1, intval($cnotGet('page', '1'))); +$cnotTableOk = MailNotifier_MailLog::ensureTable(); +$cnotList = MailNotifier_MailLog::page($cnotFilters, $cnotPage, $cnotPerPage); +$cnotStats = MailNotifier_MailLog::stats(); + +/* 分页 / 筛选链接 */ +$cnotQuery = function ($overrides = array()) use ($cnotBase, $cnotFilters, $cnotPerPage) { + $query = array( + 'status' => $cnotFilters['status'], + 'type' => $cnotFilters['type'], + 'keyword' => $cnotFilters['keyword'], + 'per' => $cnotPerPage, + ); + foreach ($overrides as $key => $value) { + $query[$key] = $value; + } + + $parts = array(); + foreach ($query as $key => $value) { + if ($value === '' || $value === null) { + continue; + } + $parts[] = $key . '=' . rawurlencode((string) $value); + } + + return $cnotBase . (empty($parts) ? '' : '&' . implode('&', $parts)); +}; + +/* 顶部提示条 */ +$cnotMsg = $cnotGet('msg'); +$cnotNoticeCount = intval($cnotGet('n')); + +$cnotNotice = null; +if ($cnotMsg === 'clear_ok') { + $cnotNotice = array('ok', '已清空 ' . $cnotNoticeCount . ' 条发送记录。'); +} elseif ($cnotMsg === 'delete_ok') { + $cnotNotice = array('ok', '记录已删除。'); +} elseif ($cnotMsg === 'delete_multi_ok') { + $cnotNotice = array($cnotNoticeCount > 0 ? 'ok' : 'fail', $cnotNoticeCount > 0 ? '已删除 ' . $cnotNoticeCount . ' 条发送记录。' : '没有删掉任何记录,可能已被删除过。'); +} elseif ($cnotMsg === 'resend_ok') { + $cnotNotice = array('ok', '已重新发送,发送结果会作为新记录出现在列表顶部。'); +} elseif ($cnotMsg === 'resend_fail') { + $cnotNotice = array('fail', '重发失败:' . ($cnotGet('detail') !== '' ? $cnotGet('detail') : '未知原因')); +} elseif ($cnotMsg === 'token') { + $cnotNotice = array('fail', '安全令牌校验失败,请刷新页面后重试。'); +} elseif ($cnotMsg === 'unknown') { + $cnotNotice = array('fail', '无法识别的操作。'); +} + +include 'header.php'; +include 'menu.php'; +?> + + + +
+
+ +
+
+
+
+ + +
+ +
+ + + +
+ 发送记录表创建失败,记录暂时无法写入。请检查数据库账号是否有建表权限,或到 error_log 里搜 [MailNotifier] 看具体报错。 +
+ + +
+
+ + 发送记录总数(最多保留 条) +
+
+ + 发送成功 +
+
+ + 发送失败 +
+
+ + +
+
+ 发送记录 + 每封邮件发完就记一条,失败的也会记下来并写明原因 +
+ + +
+
+ + + + + + + + 重置 + +
+ + + +
+ 已选 0 项 + +
+ +
+ + +
+ + + 换个筛选条件试试。 + + 等有人评论、或者点一次插件设置里的「测试发送」,这里就会出现记录。 + +
+ + +
+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
状态邮件收件人关联文章邮件内容发送时间操作
+ + 成功 + + 失败 + + + + + + + + + + + + + + + + + + + + + — + + + 查看 + + 0 ? date('Y-m-d H:i', $cnotCreated) : '—'); ?> + +
+ + +
+
+
+
+ + 1): ?> + 1) { + array_unshift($cnotPageList, 1, 0); + } + if ($cnotEnd < $cnotList['pages']) { + $cnotPageList[] = 0; + $cnotPageList[] = $cnotList['pages']; + } + } + ?> +
+ 共 条 · 第 / 页 + 1): ?> + 上一页 + + 上一页 + + + + … + + + + + + + + 下一页 + + 下一页 + +
+ + +
+ + + +
+
+ 清空发送记录 +

只删记录,不影响插件设置和已发出的邮件。要备份设置,请到插件设置页顶部的「插件设置备份」。

+
+
+
+ + + +
+
+
+ + + + + +
+
+
+
+
+ + + + + + \ No newline at end of file diff --git a/Plugin.php b/Plugin.php new file mode 100644 index 0000000..13c0e03 --- /dev/null +++ b/Plugin.php @@ -0,0 +1,1897 @@ + '/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 = '' + . ''; + } + + 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]) . '' + . '' + . '
'; + } + $html .= '
'; + return $html; + } + + private static function configStyleHtml() + { + return <<<'HTML' + +HTML; + } +} diff --git a/README.md b/README.md index 6719ab1..066281a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,33 @@ # MailNotifier +> 仓库:`MailNotifier` · 类型:Typecho 插件 · 版本:`2.0.3` · 作者:石头厝 + +Typecho 邮件通知插件。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `Action.php` +- `MailLog.php` +- `Manage.php` +- `Plugin.php` +- `Settings.php` +- `template/` + +## 安装与使用 + +1. 将本仓库目录复制到 Typecho 站点的 `usr/plugins/<仓库名>/`。 +2. 在 Typecho 后台「插件」管理中启用并按站点配置。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/Settings.php b/Settings.php new file mode 100644 index 0000000..dd6d22e --- /dev/null +++ b/Settings.php @@ -0,0 +1,722 @@ +fetchRow( + $db->select('name')->from(self::TABLE) + ->where('name = ?', self::OPTION_NAME) + ->limit(1) + ); + + if ($row) { + $db->query( + $db->update(self::TABLE) + ->rows(array('value' => $legacy)) + ->where('name = ?', self::OPTION_NAME) + ); + } else { + $db->query( + $db->insert(self::TABLE)->rows(array( + 'name' => self::OPTION_NAME, + 'user' => 0, + 'value' => $legacy, + )) + ); + } + + return true; + } catch (Exception $e) { + MailNotifier_MailLog::logError('迁移旧配置失败:' . $e->getMessage()); + } catch (Throwable $e) { + MailNotifier_MailLog::logError('迁移旧配置失败:' . $e->getMessage()); + } + + return false; + } + + /** + * 按 options.name 读原始值 + * + * @param string $name + * @return string|null + */ + private static function readRawByName($name) + { + $db = self::db(); + if (!$db) { + return null; + } + + try { + $row = $db->fetchRow( + $db->select()->from(self::TABLE) + ->where('name = ?', $name) + ->limit(1) + ); + if (!$row || !isset($row['value']) || $row['value'] === '') { + return null; + } + return (string) $row['value']; + } catch (Exception $e) { + MailNotifier_MailLog::logError('读取插件配置失败:' . $e->getMessage()); + } catch (Throwable $e) { + MailNotifier_MailLog::logError('读取插件配置失败:' . $e->getMessage()); + } + + return null; + } + + /** + * 当前插件设置(解码后) + * + * @return array + */ + public static function read() + { + $raw = self::readRaw(); + if ($raw === null || $raw === '') { + return array(); + } + + $isSerialized = strpos($raw, 'a:') === 0 || $raw === 'b:0;'; + $data = $isSerialized ? @unserialize($raw) : json_decode($raw, true); + + return is_array($data) ? $data : array(); + } + + /** + * 把一个设置数组写回 options 表 + * + * @param array $settings + * @return bool + */ + public static function write(array $settings) + { + $db = self::db(); + if (!$db) { + return false; + } + + $value = self::encode($settings); + if ($value === false || $value === '') { + return false; + } + + try { + $rows = $db->fetchAll( + $db->select('name', 'user')->from(self::TABLE) + ->where('name = ?', self::OPTION_NAME) + ); + $rows = (array) $rows; + + if (empty($rows)) { + $db->query($db->insert(self::TABLE)->rows(array( + 'name' => self::OPTION_NAME, + 'value' => $value, + 'user' => 0, + ))); + return true; + } + + foreach ($rows as $row) { + $db->query( + $db->update(self::TABLE) + ->rows(array('value' => $value)) + ->where('name = ?', self::OPTION_NAME) + ->where('user = ?', intval($row['user'])) + ); + } + + return true; + } catch (Exception $e) { + MailNotifier_MailLog::logError('写回插件配置失败:' . $e->getMessage()); + } catch (Throwable $e) { + MailNotifier_MailLog::logError('写回插件配置失败:' . $e->getMessage()); + } + + return false; + } + + /** + * 按「这个站当前用的格式」编码 + * + * 判断依据是库里现存的字符串:以 a: 开头就是 serialize(Typecho 1.1/1.2), + * 否则按 JSON(1.2+)。一条记录都没有时才退回去看版本号。 + */ + private static function encode(array $settings) + { + $raw = self::readRaw(); + + if ($raw !== null && $raw !== '') { + if (strpos($raw, 'a:') === 0) { + return serialize($settings); + } + return MailNotifier_MailLog::jsonEncode($settings); + } + + $version = ''; + try { + if (class_exists('Typecho_Common') && defined('Typecho_Common::VERSION')) { + $version = Typecho_Common::VERSION; + } elseif (class_exists('Typecho\\Common') && defined('Typecho\\Common::VERSION')) { + $version = \Typecho\Common::VERSION; + } + } catch (Exception $e) { + } + + if ($version !== '' && version_compare($version, '1.2', '<')) { + return serialize($settings); + } + + return MailNotifier_MailLog::jsonEncode($settings); + } + + /* ------------------------------------------------------------------ + * 备份文件 + * ------------------------------------------------------------------ */ + + public static function backupDir() + { + return dirname(__FILE__) . '/data/backup'; + } + + /** + * 备份最多保留几份(读设置项 backupKeep) + * + * 读不到、写成空、写成非数字都回落默认值;超出范围就夹到上下限, + * 免得有人填个 0 把自己的备份全删了。 + * + * @return int + */ + public static function backupKeep() + { + $default = self::BACKUP_KEEP; + + if (!class_exists('MailNotifier_Plugin') || !method_exists('MailNotifier_Plugin', 'configRaw')) { + return $default; + } + + $raw = trim((string) MailNotifier_Plugin::configRaw('backupKeep', (string) $default)); + if ($raw === '' || !preg_match('/^\d+$/', $raw)) { + return $default; + } + + $value = intval($raw); + if ($value < self::BACKUP_KEEP_MIN) { + return self::BACKUP_KEEP_MIN; + } + if ($value > self::BACKUP_KEEP_MAX) { + return self::BACKUP_KEEP_MAX; + } + + return $value; + } + + /** + * 把旧插件目录里的备份复制过来(幂等) + * + * 改名升级时用户是「新增 MailNotifier 目录」,旧的 usr/plugins/CommentNotifier + * 可能还留着也可能已经删掉。留着的话,把里面 cn-settings-* 复制一份, + * 升级完「恢复」按钮还能用;已经删了就只能靠用户自己拷,跳过即可。 + * + * @return int 实际复制的文件数 + */ + public static function migrateLegacyBackups() + { + if (!self::ensureBackupDir()) { + return 0; + } + + $target = self::backupDir(); + $legacyDir = dirname(dirname(__FILE__)) . '/CommentNotifier/data/backup'; + + if (!is_dir($legacyDir)) { + return 0; + } + + $realtarget = @realpath($target); + $realledgacy = @realpath($legacyDir); + if ($realtarget && $realledgacy && $realtarget === $realledgacy) { + return 0; + } + + $files = glob($legacyDir . '/' . self::LEGACY_BACKUP_PREFIX . '*.php'); + if (empty($files)) { + return 0; + } + + $copied = 0; + foreach ($files as $file) { + $name = basename($file); + if (!self::isBackupName($name)) { + continue; + } + $dest = $target . '/' . $name; + // 不覆盖同名文件,避免把新目录里已经有的备份覆盖掉 + if (is_file($dest)) { + continue; + } + if (@copy($file, $dest)) { + $copied++; + } + } + + return $copied; + } + + private static function ensureBackupDir() + { + $dir = self::backupDir(); + + if (!is_dir($dir)) { + @mkdir($dir, 0755, true); + } + if (!is_dir($dir)) { + return false; + } + + /* + * 备份里有 SMTP 授权码,属于「不该被公网读到」的东西。 + * 插件目录一般是能直接访问的,所以两层保护: + * 文件本体是 .php(直接访问只会执行 exit,看不到内容) + * 目录里再放 .htaccess(Apache 直接拒掉整个目录) + */ + if (!is_file($dir . '/.htaccess')) { + @file_put_contents($dir . '/.htaccess', "Require all denied\nDeny from all\n"); + } + if (!is_file($dir . '/index.html')) { + @file_put_contents($dir . '/index.html', ''); + } + + return true; + } + + /** + * 手动备份一次插件设置 + * + * @return array ok / message / file / count / created + */ + public static function backup() + { + $fail = array('ok' => false, 'message' => '', 'file' => '', 'count' => 0, 'created' => 0); + + $settings = self::read(); + if (empty($settings)) { + $fail['message'] = '还没读到插件设置,请先保存一次插件设置再备份'; + return $fail; + } + + if (!self::ensureBackupDir()) { + $fail['message'] = '备份目录 data/backup 不可写,请给该目录写入权限'; + return $fail; + } + + $created = time(); + $meta = array( + 'plugin' => 'MailNotifier', + 'version' => self::version(), + 'created' => $created, + 'count' => count($settings), + 'siteUrl' => self::siteUrl(), + ); + + $payload = array_merge($meta, array('settings' => $settings)); + $json = MailNotifier_MailLog::jsonEncode($payload); + if ($json === false) { + $fail['message'] = '序列化设置失败'; + return $fail; + } + + if (function_exists('gzcompress')) { + $gz = @gzcompress($json, 6); + $encoded = ($gz === false || $gz === '') ? base64_encode($json) : 'gz:' . base64_encode($gz); + } else { + $encoded = 'b64:' . base64_encode($json); + } + + $content = '' . "\n" . $encoded; + + $file = self::backupDir() . '/' . self::BACKUP_PREFIX . date('Ymd-His', $created) . '.php'; + if (@file_put_contents($file, $content, LOCK_EX) === false) { + $fail['message'] = '写入备份文件失败,请检查 data/backup 目录权限'; + return $fail; + } + + $removed = self::pruneBackups(); + $total = count(self::backups()); + + return array( + 'ok' => true, + 'message' => '设置已备份', + 'file' => basename($file), + 'count' => count($settings), + 'created' => $created, + 'keep' => self::backupKeep(), + 'total' => $total, + 'removed' => $removed, + ); + } + + /** + * 备份列表(新 → 旧) + * + * 同时包含改名前的 cn-settings-* 备份:老站升级后第一次进来 + * 「恢复」按钮不应该突然变成灰的。 + */ + public static function backups() + { + $dir = self::backupDir(); + if (!is_dir($dir)) { + return array(); + } + + $files = array_merge( + (array) glob($dir . '/' . self::BACKUP_PREFIX . '*.php'), + (array) glob($dir . '/' . self::LEGACY_BACKUP_PREFIX . '*.php') + ); + if (empty($files)) { + return array(); + } + + $list = array(); + foreach ($files as $file) { + $meta = self::readMeta($file); + $list[] = array( + 'file' => basename($file), + 'size' => (int) @filesize($file), + 'created' => !empty($meta['created']) ? intval($meta['created']) : (int) @filemtime($file), + 'count' => !empty($meta['count']) ? intval($meta['count']) : 0, + 'version' => isset($meta['version']) ? (string) $meta['version'] : '', + ); + } + + // 两种前缀混在一起,文件名排序不可靠,改成按备份时间倒序 + usort($list, function ($a, $b) { + if ($a['created'] === $b['created']) { + return strcmp($b['file'], $a['file']); + } + return $a['created'] < $b['created'] ? 1 : -1; + }); + + return $list; + } + + /** + * 最近一次手动备份,没有则 null + */ + public static function latest() + { + $list = self::backups(); + return empty($list) ? null : $list[0]; + } + + private static function readMeta($file) + { + $head = @file_get_contents($file, false, null, 0, 512); + if ($head === false || $head === '') { + return array(); + } + // MN- 是新版标记,CN- 是改名前的旧标记,两种都认 + if (preg_match('~MN-SETTINGS-BACKUP\s*(\{.*?\})\s*\*/~s', $head, $m) + || preg_match('~CN-SETTINGS-BACKUP\s*(\{.*?\})\s*\*/~s', $head, $m) + ) { + $meta = json_decode($m[1], true); + if (is_array($meta)) { + return $meta; + } + } + return array(); + } + + /** + * 只保留最近 backupKeep() 份,多出来的从最旧的开始删 + * + * 顺序必须按备份时间(文件头里的 meta.created,缺失时退回 filemtime)排, + * 不能像以前那样 rsort 文件名:改名前的 cn-settings-* 和现在的 + * mn-settings-* 混在一起按字符串排,前缀会把顺序带偏,删掉新的留下旧的。 + * + * @return int 实际删掉几份 + */ + private static function pruneBackups() + { + $keep = self::backupKeep(); + $list = self::backups(); + if (count($list) <= $keep) { + return 0; + } + + $removed = 0; + foreach (array_slice($list, $keep) as $item) { + if (@unlink(self::backupDir() . '/' . $item['file'])) { + $removed++; + } + } + + return $removed; + } + + /** + * 恢复一份手动备份 + * + * 不传文件名 = 最新那一份(顶部「恢复」按钮);传了就是历史备份列表里点的那一份。 + * 文件名会过 basename + isBackupName 白名单,不收路径。 + * + * @param string $file 指定文件名(留空 = 最新一份) + * @return array ok / message / count / created + */ + public static function restoreLatest($file = '') + { + $fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0); + + $latest = self::latest(); + if (!$latest) { + $fail['message'] = '还没有手动备份,先点一次「备份设置」'; + return $fail; + } + + $name = $file !== '' ? basename($file) : $latest['file']; + if (!self::isBackupName($name)) { + $fail['message'] = '备份文件名不合法'; + return $fail; + } + + $path = self::backupDir() . '/' . $name; + if (!is_file($path)) { + $fail['message'] = '备份文件不存在:' . $name; + return $fail; + } + + $content = @file_get_contents($path); + if ($content === false || $content === '') { + $fail['message'] = '读取备份文件失败'; + return $fail; + } + + $pos = strpos($content, '?>'); + if ($pos === false) { + $fail['message'] = '备份文件格式不正确'; + return $fail; + } + + $encoded = trim(substr($content, $pos + 2)); + if (strncmp($encoded, 'gz:', 3) === 0) { + $json = function_exists('gzuncompress') + ? @gzuncompress((string) base64_decode(substr($encoded, 3))) + : false; + } elseif (strncmp($encoded, 'b64:', 4) === 0) { + $json = base64_decode(substr($encoded, 4)); + } else { + // 没有前缀:按 base64 直接解,失败再当明文 JSON + $json = base64_decode($encoded); + if ($json === false || substr(ltrim($json), 0, 1) !== '{') { + $json = $encoded; + } + } + + if ($json === false || $json === '') { + $fail['message'] = '备份文件内容已损坏,无法解析'; + return $fail; + } + + $payload = json_decode($json, true); + if (!is_array($payload) || !isset($payload['settings']) || !is_array($payload['settings'])) { + $fail['message'] = '备份文件内容已损坏,没有找到设置'; + return $fail; + } + // 旧版备份里写的是 CommentNotifier,改名后仍然允许恢复 + if ( + isset($payload['plugin']) + && $payload['plugin'] !== 'MailNotifier' + && $payload['plugin'] !== self::LEGACY_PLUGIN_KEY + ) { + $fail['message'] = '这份备份不属于 MailNotifier'; + return $fail; + } + if (empty($payload['settings'])) { + $fail['message'] = '备份里的设置是空的,已停止恢复'; + return $fail; + } + + if (!self::write($payload['settings'])) { + $fail['message'] = '写回设置失败,请检查数据库权限'; + return $fail; + } + + return array( + 'ok' => true, + 'message' => '设置已恢复', + 'count' => count($payload['settings']), + 'created' => !empty($payload['created']) ? intval($payload['created']) : intval($latest['created']), + ); + } + + /** + * 文件名是不是本插件生成的备份(新旧两种前缀都算) + * + * @param string $name + * @return bool + */ + public static function isBackupName($name) + { + $name = (string) $name; + foreach (array(self::BACKUP_PREFIX, self::LEGACY_BACKUP_PREFIX) as $prefix) { + if (preg_match('/^' . preg_quote($prefix, '/') . '[0-9][0-9\-]*\.php$/', $name)) { + return true; + } + } + return false; + } + + /** + * 删除一份备份(目前界面没开放,留着给以后用) + */ + public static function removeBackup($file) + { + $name = basename((string) $file); + if (!self::isBackupName($name)) { + return false; + } + + $path = self::backupDir() . '/' . $name; + return is_file($path) ? @unlink($path) : false; + } + + public static function version() + { + if (class_exists('MailNotifier_Plugin') && defined('MailNotifier_Plugin::VERSION')) { + return MailNotifier_Plugin::VERSION; + } + return ''; + } + + public static function siteUrl() + { + try { + if (class_exists('Helper') && method_exists('Helper', 'options')) { + $options = Helper::options(); + if ($options && isset($options->siteUrl)) { + return (string) $options->siteUrl; + } + } + } catch (Exception $e) { + } + return ''; + } +} diff --git a/template/bamboo/guest.html b/template/bamboo/guest.html new file mode 100644 index 0000000..305835a --- /dev/null +++ b/template/bamboo/guest.html @@ -0,0 +1,25 @@ + + +评论回复通知 + +
+ + + +
 
+ + + + +
回复通知
你的评论收到了回复
你在文章《{title}》下的评论有了新回复。
+
你的评论:
{Ptext}
 新的回复:
{commentText}
+ + + + + +
回复人:{author}
邮箱:{mail}
IP 地址:{ip}
时间:{time}
+
查看回复内容
+
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
diff --git a/template/bamboo/notice.html b/template/bamboo/notice.html new file mode 100644 index 0000000..c9195c2 --- /dev/null +++ b/template/bamboo/notice.html @@ -0,0 +1,25 @@ + + +待审核评论 + +
+ + + +
 
+ + + + +
评论通知
有一条评论等待审核
文章《{title}》收到待审核评论。
+
{commentText}
+ + + + + +
评论人:{author}
邮箱:{mail}
IP 地址:{ip}
时间:{time}
+
立即前往审核
+
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
diff --git a/template/bamboo/owner.html b/template/bamboo/owner.html new file mode 100644 index 0000000..d988655 --- /dev/null +++ b/template/bamboo/owner.html @@ -0,0 +1,25 @@ + + +新评论通知 + +
+ + + +
 
+ + + + +
评论通知
你的文章收到新评论
文章《{title}》收到一条新评论。
+
{commentText}
+ + + + + +
评论人:{author}
邮箱:{mail}
IP 地址:{ip}
时间:{time}
+
查看评论详情
+
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
diff --git a/template/inkcard/guest.html b/template/inkcard/guest.html new file mode 100644 index 0000000..461ba06 --- /dev/null +++ b/template/inkcard/guest.html @@ -0,0 +1,40 @@ + + + + + + +评论回复通知 + + + + + + +
+ + + + + +
+ + + + + +
回复通知
你的评论收到了回复
你在文章《{title}》下的评论有了新回复。
 
+ + +
你的评论:
{Ptext}
 新的回复:
{commentText}
+ + + + + +
回复人:{author}
邮箱:{mail}
IP:{ip}
时间:{time}
+
查看回复内容
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
+ + diff --git a/template/inkcard/notice.html b/template/inkcard/notice.html new file mode 100644 index 0000000..70de085 --- /dev/null +++ b/template/inkcard/notice.html @@ -0,0 +1,39 @@ + + + + + +待审核评论 + + + + + + +
+ + + + + +
+ + + + + +
评论通知
有一条评论等待审核
文章《{title}》收到待审核评论。
 
+ + +
{commentText}
+ + + + + +
评论人:{author}
邮箱:{mail}
IP:{ip}
时间:{time}
+
立即前往审核
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
+ + diff --git a/template/inkcard/owner.html b/template/inkcard/owner.html new file mode 100644 index 0000000..2b0dfb6 --- /dev/null +++ b/template/inkcard/owner.html @@ -0,0 +1,39 @@ + + + + + +新评论通知 + + + + + + +
+ + + + + +
+ + + + + +
评论通知
你的文章收到新评论
文章《{title}》收到一条新评论。
 
+ + +
{commentText}
+ + + + + +
评论人:{author}
邮箱:{mail}
IP:{ip}
时间:{time}
+
查看评论详情
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
+
+ + diff --git a/template/landscape/guest.html b/template/landscape/guest.html new file mode 100644 index 0000000..eb35506 --- /dev/null +++ b/template/landscape/guest.html @@ -0,0 +1,25 @@ + + +评论回复通知 + +
+ + + +
 
+ + + + + + +
!
回复通知
你的评论收到了回复
你在文章《{title}》下的评论有了新回复。
 
+
你的评论:
{Ptext}
 新的回复:
{commentText}
+ + + + + +
回复人{author}
邮箱{mail}
IP 地址{ip}
回复时间{time}
+
查看回复内容
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
diff --git a/template/landscape/notice.html b/template/landscape/notice.html new file mode 100644 index 0000000..118a651 --- /dev/null +++ b/template/landscape/notice.html @@ -0,0 +1,24 @@ + + +待审核评论 + +
+ + + +
 
+ + + + + +
评论通知
有一条评论等待审核
文章《{title}》收到待审核评论。
 
+
{commentText}
+ + + + + +
评论人{author}
邮箱{mail}
IP 地址{ip}
评论时间{time}
+
立即前往审核
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
diff --git a/template/landscape/owner.html b/template/landscape/owner.html new file mode 100644 index 0000000..30f54d2 --- /dev/null +++ b/template/landscape/owner.html @@ -0,0 +1,24 @@ + + +新评论通知 + +
+ + + +
 
+ + + + + +
评论通知
你的文章收到新评论
文章《{title}》收到一条新评论。
 
+
{commentText}
+ + + + + +
评论人{author}
邮箱{mail}
IP 地址{ip}
评论时间{time}
+
查看评论详情
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
diff --git a/template/seal/1.webp b/template/seal/1.webp new file mode 100644 index 0000000..297fa8b Binary files /dev/null and b/template/seal/1.webp differ diff --git a/template/seal/2.webp b/template/seal/2.webp new file mode 100644 index 0000000..0f49afb Binary files /dev/null and b/template/seal/2.webp differ diff --git a/template/seal/3.webp b/template/seal/3.webp new file mode 100644 index 0000000..1491813 Binary files /dev/null and b/template/seal/3.webp differ diff --git a/template/seal/4.webp b/template/seal/4.webp new file mode 100644 index 0000000..68abcfc Binary files /dev/null and b/template/seal/4.webp differ diff --git a/template/seal/guest.html b/template/seal/guest.html new file mode 100644 index 0000000..f8f68f9 --- /dev/null +++ b/template/seal/guest.html @@ -0,0 +1,25 @@ + + +评论回复通知 + +
+ + + + +
+ + + + +
回复通知
你的评论收到了回复
你在文章《{title}》下的评论有了新回复。
+
+
你的评论:
{Ptext}
 新的回复:
{commentText}
+ + + + + +
回复人{author}
邮箱{mail}
IP 地址{ip}
回复时间{time}
+
查看回复内容
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
diff --git a/template/seal/notice.html b/template/seal/notice.html new file mode 100644 index 0000000..deffaaa --- /dev/null +++ b/template/seal/notice.html @@ -0,0 +1,25 @@ + + +待审核评论 + +
+ + + + +
+ + + + +
评论通知
有一条评论等待审核
文章《{title}》收到待审核评论。
+
+
{commentText}
+ + + + + +
评论人{author}
邮箱{mail}
IP 地址{ip}
评论时间{time}
+
立即前往审核
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。
diff --git a/template/seal/owner.html b/template/seal/owner.html new file mode 100644 index 0000000..1e6bd09 --- /dev/null +++ b/template/seal/owner.html @@ -0,0 +1,25 @@ + + +新评论通知 + +
+ + + + +
+ + + + +
评论通知
你的文章收到新评论
文章《{title}》收到一条新评论。
+
+
{commentText}
+ + + + + +
评论人{author}
邮箱{mail}
IP 地址{ip}
评论时间{time}
+
查看评论详情
+
此邮件由 {siteTitle} 自动发送,请勿直接回复。