Files
MailNotifier/MailLog.php

814 lines
26 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* MailNotifier 发送记录存储
*
* 为什么单独一个文件:Plugin.php 里全是发信逻辑,把「记录 / 查询」塞进去会越来越
* 难读,而面板页 Manage.php 也要用到这些方法。这里只管数据,不参与发信 ——
* 记录失败绝不能连累发信,所以所有方法都不抛异常,只在 error_log 里留一句。
*
* 表结构(prefix + mailnotifier_mail):
* id / coid / cid / post_title / post_url / mail_type / to_mail / to_name
* subject / body / body_size / status / message / created
*
* body 存的是「编码后的邮件正文」而不是原文:
* gz:<base64> zlib 压缩(最常见,体积约为原文的 1/7)
* b64:<base64> 环境没有 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);
}
}
}