-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.php
More file actions
998 lines (898 loc) · 31.2 KB
/
Plugin.php
File metadata and controls
998 lines (898 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
<?php
/**
* 智能评论审核插件 - 敏感词检测、广告拦截、外语拦截、中文检测、百度内容审核、管理员豁免、一键拉黑、拦截日志
*
* @package TSpamReview
* @author 森木志
* @version 2.0.1
* @link https://oxxx.cn
* @license MIT
*/
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
require_once __DIR__ . '/ReviewEngine.php';
class TSpamReview_Plugin implements Typecho_Plugin_Interface
{
private static $blacklistBackupFile = __DIR__ . DIRECTORY_SEPARATOR . '.blacklist_backup.json';
public static function activate()
{
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
throw new Typecho_Plugin_Exception(_t('TSpamReview 插件需要 PHP 7.0 或更高版本'));
}
foreach (['json', 'mbstring'] as $extension) {
if (!extension_loaded($extension)) {
throw new Typecho_Plugin_Exception(_t('TSpamReview 插件需要 PHP %s 扩展', $extension));
}
}
TSpamReview_ReviewEngine::ensureRuntimeFiles();
Typecho_Plugin::factory('Widget_Feedback')->comment = [__CLASS__, 'onBeforeComment'];
Typecho_Plugin::factory('Widget_Feedback')->finishComment = [__CLASS__, 'onFinishComment'];
Typecho_Plugin::factory('Widget_Archive')->footer = [__CLASS__, 'footer'];
Typecho_Plugin::factory('admin/footer.php')->end = [__CLASS__, 'adminFooter'];
Helper::addAction('TSpamReview', 'TSpamReview_Action');
Helper::addAction('TSpamReviewBlacklist', 'TSpamReview_BlacklistAction');
Helper::addPanel(1, 'TSpamReview/logs.php', _t('TSpamReview 日志'), _t('查看评论拦截日志'), 'administrator');
self::restoreBlacklistBackup();
self::cleanupLegacyConfigKeys();
return _t('TSpamReview 插件已成功激活!');
}
public static function deactivate()
{
self::backupBlacklist();
if (class_exists('Helper')) {
Helper::removeAction('TSpamReview');
Helper::removeAction('TSpamReviewBlacklist');
Helper::removePanel(1, 'TSpamReview/logs.php');
}
return _t('TSpamReview 插件已禁用。');
}
public static function config(Typecho_Widget_Helper_Form $form)
{
self::cleanupLegacyConfigKeys();
self::addSection($form, '评论审核策略', '推荐默认值:先完成基础与推荐两组;高级设置仅在主题兼容或精细调优时再修改。', 'overview', 'tspamreview-panel');
self::addSection($form, '基础设置', '推荐默认值:填写敏感词,保留昵称限制 30,开启拦截日志。适合大多数站点。', 'basic');
$sensitiveWords = new Typecho_Widget_Helper_Form_Element_Textarea(
'sensitiveWords',
null,
'',
_t('敏感词汇列表'),
_t('每行一个词汇;会同时检测评论内容、昵称和邮箱。')
);
$sensitiveWords->setAttribute('rows', 8);
$form->addInput($sensitiveWords);
$authorMaxLength = new Typecho_Widget_Helper_Form_Element_Text(
'authorMaxLength',
null,
'30',
_t('昵称最大长度'),
_t('超过限制即拦截,填 0 表示不限制。')
);
$form->addInput($authorMaxLength);
$ipBlacklist = new Typecho_Widget_Helper_Form_Element_Textarea(
'ipBlacklist',
null,
'',
_t('IP 黑名单'),
_t('每行一个 IP;评论管理页支持一键拉黑。')
);
$ipBlacklist->setAttribute('rows', 5);
$form->addInput($ipBlacklist);
$emailBlacklist = new Typecho_Widget_Helper_Form_Element_Textarea(
'emailBlacklist',
null,
'',
_t('邮箱黑名单'),
_t('每行一个邮箱;评论管理页支持一键拉黑。')
);
$emailBlacklist->setAttribute('rows', 5);
$form->addInput($emailBlacklist);
$blacklistAction = new Typecho_Widget_Helper_Form_Element_Radio(
'blacklistDeleteComment',
[
'0' => _t('只加入黑名单,保留当前评论'),
'1' => _t('加入黑名单并删除当前评论'),
],
'0',
_t('一键拉黑后的处理'),
_t('删除操作不可恢复,建议仅在确认是垃圾评论时开启。')
);
$form->addInput($blacklistAction);
$blockLog = new Typecho_Widget_Helper_Form_Element_Checkbox(
'blockLog',
['enable' => _t('记录被拦截的评论')],
['enable'],
_t('拦截日志'),
_t('建议开启,方便查看命中情况与复盘规则效果。')
);
$form->addInput($blockLog->multiMode());
self::addSection($form, '推荐设置', '推荐默认值:广告拦截、乱码拦截、严格邮箱、外语拦截全部开启;中英文策略按站点语言决定。', 'recommended');
$blockSpam = new Typecho_Widget_Helper_Form_Element_Checkbox(
'blockSpam',
['enable' => _t('启用广告内容拦截')],
['enable'],
_t('广告内容拦截'),
_t('检测电话号码、微信号、URL 链接和明显重复内容。')
);
$form->addInput($blockSpam->multiMode());
$blockGarbledAuthor = new Typecho_Widget_Helper_Form_Element_Checkbox(
'blockGarbledAuthor',
['enable' => _t('拦截乱码或异常字符内容')],
['enable'],
_t('乱码拦截'),
_t('同时检测昵称、邮箱和评论内容中的异常字符比例。')
);
$form->addInput($blockGarbledAuthor->multiMode());
$strictEmailCheck = new Typecho_Widget_Helper_Form_Element_Checkbox(
'strictEmailCheck',
['enable' => _t('启用严格邮箱格式检查')],
['enable'],
_t('邮箱格式验证'),
_t('拦截明显异常的邮箱格式和可疑临时邮箱。')
);
$form->addInput($strictEmailCheck->multiMode());
$blockForeignLanguage = new Typecho_Widget_Helper_Form_Element_Checkbox(
'blockForeignLanguage',
['enable' => _t('拦截纯外语评论')],
['enable'],
_t('外语拦截'),
_t('针对常见俄文、韩文、日文、阿拉伯文、泰文垃圾评论。')
);
$form->addInput($blockForeignLanguage->multiMode());
$actionOptions = [
'A' => _t('允许通过'),
'B' => _t('转为待审核'),
'C' => _t('直接拦截'),
];
$contentChineseAction = new Typecho_Widget_Helper_Form_Element_Select(
'contentChineseAction',
$actionOptions,
'A',
_t('评论内容缺少中文时'),
_t('适合屏蔽机器英文模板评论。')
);
$form->addInput($contentChineseAction->multiMode());
$authorChineseAction = new Typecho_Widget_Helper_Form_Element_Select(
'authorChineseAction',
$actionOptions,
'A',
_t('昵称缺少中文时'),
_t('适合限制站点仅接受中文昵称。')
);
$form->addInput($authorChineseAction->multiMode());
self::addSection($form, '百度审核', '推荐默认值:疑似内容转待审核,服务失败也转待审核;先本地规则,再百度复核。', 'baidu');
$enableBaidu = new Typecho_Widget_Helper_Form_Element_Checkbox(
'baiduEnable',
['enable' => _t('启用百度文本内容审核')],
[],
_t('启用百度审核'),
_t('开启后会在本地规则通过后调用百度接口。')
);
$form->addInput($enableBaidu->multiMode());
$baiduApiKey = new Typecho_Widget_Helper_Form_Element_Text(
'baiduApiKey',
null,
'',
_t('百度 API Key'),
_t('在百度智能云内容审核应用中获取。')
);
$form->addInput($baiduApiKey);
$baiduSecretKey = new Typecho_Widget_Helper_Form_Element_Text(
'baiduSecretKey',
null,
'',
_t('百度 Secret Key'),
_t('与 API Key 配套使用。')
);
$form->addInput($baiduSecretKey);
$baiduFailPolicy = new Typecho_Widget_Helper_Form_Element_Select(
'baiduFailPolicy',
[
'allow' => _t('审核服务失败时直接放行'),
'review' => _t('审核服务失败时转为待审核'),
],
'review',
_t('百度审核失败时'),
_t('推荐保守模式:转为待审核。')
);
$form->addInput($baiduFailPolicy->multiMode());
$baiduReviewAction = new Typecho_Widget_Helper_Form_Element_Select(
'baiduReviewAction',
[
'B' => _t('百度返回需审核时转为待审核'),
'C' => _t('百度返回需审核时直接拦截'),
],
'B',
_t('百度“需审核”处理方式'),
_t('建议先转为待审核,避免误杀正常评论。')
);
$form->addInput($baiduReviewAction->multiMode());
$tokenStatus = TSpamReview_ReviewEngine::getTokenStatus();
$tokenStateClass = $tokenStatus['cached'] ? 'is-ok' : 'is-warning';
$tokenStateText = $tokenStatus['cached'] ? '已缓存' : '未缓存 / 已过期';
$refreshStateText = $tokenStatus['last_refresh_status'] === 'success' ? '最近刷新成功' : ($tokenStatus['last_refresh_status'] === 'failed' ? '最近刷新失败' : '尚未刷新');
$tokenErrorText = $tokenStatus['last_error'] !== '' ? htmlspecialchars($tokenStatus['last_error'], ENT_QUOTES, 'UTF-8') : '无';
$refreshTokenUrl = Helper::security()->getIndex('/action/TSpamReview');
$refreshTokenUrl .= (strpos($refreshTokenUrl, '?') === false ? '?' : '&') . 'do=refreshToken';
$tokenInfo = new Typecho_Widget_Helper_Layout('div', ['class' => 'typecho-option tspamreview-note']);
$tokenInfo->html(
'<div class="tspamreview-inline-card ' . $tokenStateClass . '">' .
'<strong>百度 Token 状态</strong>' .
'<span data-token-field="cached">缓存状态:' . $tokenStateText . '</span>' .
'<span data-token-field="remaining">剩余有效期:' . htmlspecialchars($tokenStatus['remaining_text'], ENT_QUOTES, 'UTF-8') . '</span>' .
'<span data-token-field="refresh">最近刷新:' . htmlspecialchars($tokenStatus['last_refresh_text'], ENT_QUOTES, 'UTF-8') . '(' . $refreshStateText . ')</span>' .
'<span data-token-field="error">最近错误:' . $tokenErrorText . '</span>' .
'<button type="button" class="btn btn-s tspamreview-refresh-token" data-url="' . htmlspecialchars($refreshTokenUrl, ENT_QUOTES, 'UTF-8') . '">立即刷新 Token</button>' .
'</div>'
);
$form->addItem($tokenInfo);
self::addSection($form, '高级设置', '推荐默认值:当前为后端审核模式。仅在非标准评论模块、主题说说或排障时修改。', 'advanced');
$skipAdmin = new Typecho_Widget_Helper_Form_Element_Checkbox(
'skipAdminReview',
['enable' => _t('管理员评论不参与审核')],
['enable'],
_t('管理员豁免'),
_t('已登录管理员发表评论时跳过全部规则。')
);
$form->addInput($skipAdmin->multiMode());
$moduleWhitelistKeywords = new Typecho_Widget_Helper_Form_Element_Textarea(
'moduleWhitelistKeywords',
null,
"memos\nmemo\nshuoshuo\nshuo\nmoment\nmoments\ndynamic\ndynamics\ntweet\nstatus\ntalk",
_t('模块白名单关键词'),
_t('每行一个关键词;请求地址、来源地址或提交字段命中后,将跳过审核。适合说说、memos、动态流等非标准评论模块。')
);
$moduleWhitelistKeywords->setAttribute('rows', 6);
$form->addInput($moduleWhitelistKeywords);
$debugLog = new Typecho_Widget_Helper_Form_Element_Checkbox(
'debugLog',
['enable' => _t('启用调试日志')],
[],
_t('调试日志'),
_t('仅在排查问题时开启,会写入 PHP error_log。')
);
$form->addInput($debugLog->multiMode());
$logViewUrl = Helper::options()->adminUrl . 'extending.php?panel=TSpamReview/logs.php';
$logDir = __DIR__ . DIRECTORY_SEPARATOR . 'logs';
$logWritable = is_dir($logDir) && is_writable($logDir);
$statusText = $logWritable ? '日志目录可写' : '日志目录不可写';
$statusClass = $logWritable ? 'is-ok' : 'is-warning';
$logInfo = new Typecho_Widget_Helper_Layout('div', ['class' => 'typecho-option tspamreview-note']);
$logInfo->html(
'<div class="tspamreview-inline-card ' . $statusClass . '">' .
'<strong>日志中心</strong>' .
'<span>' . $statusText . '</span>' .
'<a class="btn btn-s" href="' . $logViewUrl . '">查看拦截日志</a>' .
'</div>'
);
$form->addItem($logInfo);
}
public static function personalConfig(Typecho_Widget_Helper_Form $form)
{
}
public static function uninstall()
{
$tokenFile = __DIR__ . DIRECTORY_SEPARATOR . '.baidu_token.json';
if (file_exists($tokenFile)) {
@unlink($tokenFile);
}
if (file_exists(self::$blacklistBackupFile)) {
@unlink(self::$blacklistBackupFile);
}
}
private static function backupBlacklist()
{
try {
$opts = Typecho_Widget::widget('Widget_Options')->plugin('TSpamReview');
$data = [
'ipBlacklist' => isset($opts->ipBlacklist) ? (string) $opts->ipBlacklist : '',
'emailBlacklist' => isset($opts->emailBlacklist) ? (string) $opts->emailBlacklist : '',
'blacklistDeleteComment' => isset($opts->blacklistDeleteComment) ? (string) $opts->blacklistDeleteComment : '0',
'time' => time(),
];
if ($data['ipBlacklist'] === '' && $data['emailBlacklist'] === '') {
return;
}
@file_put_contents(self::$blacklistBackupFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
} catch (Exception $e) {
}
}
private static function restoreBlacklistBackup()
{
try {
if (!is_file(self::$blacklistBackupFile)) {
return;
}
$raw = @file_get_contents(self::$blacklistBackupFile);
$backup = $raw ? json_decode($raw, true) : null;
if (!is_array($backup)) {
return;
}
$opts = Typecho_Widget::widget('Widget_Options')->plugin('TSpamReview');
$currentIp = isset($opts->ipBlacklist) ? trim((string) $opts->ipBlacklist) : '';
$currentEmail = isset($opts->emailBlacklist) ? trim((string) $opts->emailBlacklist) : '';
$update = [];
if ($currentIp === '' && !empty($backup['ipBlacklist'])) {
$update['ipBlacklist'] = (string) $backup['ipBlacklist'];
}
if ($currentEmail === '' && !empty($backup['emailBlacklist'])) {
$update['emailBlacklist'] = (string) $backup['emailBlacklist'];
}
if (isset($backup['blacklistDeleteComment']) && !isset($opts->blacklistDeleteComment)) {
$update['blacklistDeleteComment'] = (string) $backup['blacklistDeleteComment'];
}
if (!empty($update)) {
Helper::configPlugin('TSpamReview', $update);
}
} catch (Exception $e) {
}
}
private static function cleanupLegacyConfigKeys()
{
try {
$db = Typecho_Db::get();
$option = $db->fetchRow(
$db->select('value')->from('table.options')->where('name = ?', 'plugin:TSpamReview')->limit(1)
);
if (!$option || !isset($option['value'])) {
return;
}
$data = json_decode((string) $option['value'], true);
if (!is_array($data)) {
return;
}
$changed = false;
foreach (['frontPrecheck', 'moduleWhitelistSelectors'] as $key) {
if (array_key_exists($key, $data)) {
unset($data[$key]);
$changed = true;
}
}
if ($changed) {
$db->query(
$db->update('table.options')
->rows(['value' => json_encode($data)])
->where('name = ?', 'plugin:TSpamReview')
);
}
} catch (Exception $e) {
}
}
public static function footer()
{
// Keep frontend behavior untouched by theme scripts.
}
public static function adminFooter()
{
$request = Typecho_Request::getInstance();
$uri = (string) $request->getRequestUri();
if (strpos($uri, 'options-plugin.php') !== false && strpos($uri, 'config=TSpamReview') !== false) {
self::renderConfigStyle();
}
if (strpos($uri, 'manage-comments.php') !== false) {
self::renderCommentAdminEnhancement();
}
}
private static function addSection(Typecho_Widget_Helper_Form $form, $title, $desc, $tabKey = 'basic', $extraClass = '')
{
$class = trim('typecho-option tspamreview-section-head ' . $extraClass);
$layout = new Typecho_Widget_Helper_Layout('div', ['class' => $class, 'data-tab' => $tabKey]);
$layout->html(
'<div class="tspamreview-section-title">' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</div>' .
'<p class="tspamreview-section-desc">' . htmlspecialchars($desc, ENT_QUOTES, 'UTF-8') . '</p>'
);
$form->addItem($layout);
}
private static function renderConfigStyle()
{
?>
<style>
.tspamreview-tabs {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin: 0 0 18px;
}
.tspamreview-tab {
padding: 9px 14px;
border: 1px solid #d5e0e8;
border-radius: 999px;
background: #fff;
color: #60707f;
cursor: pointer;
transition: all .2s ease;
}
.tspamreview-tab:hover {
border-color: #b8ccd8;
background: #f8fbfd;
}
.tspamreview-tab.active {
background: #2f6f8f;
border-color: #2f6f8f;
color: #fff;
}
.tspamreview-group {
display: none;
gap: 14px;
}
.tspamreview-group.active {
display: block;
}
.tspamreview-savebar {
margin-top: 14px;
padding-top: 14px;
border-top: 1px dashed #d9e2ea;
text-align: right;
}
.tspamreview-native-submit {
display: none !important;
}
.tspamreview-panel,
.tspamreview-section-head,
.tspamreview-note {
background: linear-gradient(180deg, #ffffff 0%, #fbfcfd 100%);
border: 1px solid #d9e2ea;
border-radius: 14px;
padding: 18px 20px;
box-shadow: 0 10px 28px rgba(54, 84, 107, 0.06);
}
.tspamreview-panel {
background: linear-gradient(135deg, #f5fafb 0%, #ffffff 60%, #fdf7f2 100%);
border-color: #cddce5;
}
.tspamreview-section-title {
font-size: 16px;
font-weight: 600;
color: #22313f;
margin-bottom: 6px;
}
.tspamreview-section-desc {
margin: 0;
color: #637381;
line-height: 1.7;
}
.typecho-option label {
font-weight: 600;
color: #22313f;
}
.typecho-option .description {
color: #728191;
line-height: 1.7;
}
.typecho-option textarea,
.typecho-option input[type=text],
.typecho-option select {
border-radius: 10px;
border-color: #ccd7e1;
background: #fff;
}
.tspamreview-inline-card {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
flex-wrap: wrap;
}
.tspamreview-inline-card button[disabled] {
opacity: .7;
cursor: wait;
}
.tspamreview-inline-card strong {
width: 100%;
}
.tspamreview-inline-card .btn {
margin-left: auto;
}
.tspamreview-inline-card strong {
color: #22313f;
}
.tspamreview-inline-card span {
color: #637381;
}
.tspamreview-inline-card.is-ok,
.tspamreview-inline-card.is-warning {
border-left: none;
}
.tspamreview-inline-card.is-ok {
border-color: #cfe7db;
background: linear-gradient(180deg, #ffffff 0%, #f7fcf9 100%);
}
.tspamreview-inline-card.is-warning {
border-color: #eadfcd;
background: linear-gradient(180deg, #ffffff 0%, #fffbf2 100%);
}
@media (max-width: 768px) {
.tspamreview-panel,
.tspamreview-section-head,
.tspamreview-note {
padding: 16px;
border-radius: 12px;
}
.tspamreview-tabs {
gap: 8px;
}
.tspamreview-tab {
width: calc(50% - 4px);
text-align: center;
}
}
</style>
<script>
(function() {
function initTabs() {
var sections = Array.prototype.slice.call(document.querySelectorAll('.tspamreview-section-head[data-tab]'));
if (!sections.length) {
return;
}
var host = sections[0].parentNode;
if (!host || host.dataset.tspamInit === '1') {
return;
}
host.dataset.tspamInit = '1';
var firstSection = sections[0];
var form = host.closest ? host.closest('form') : null;
var map = {
overview: '基础',
basic: '基础',
recommended: '推荐',
baidu: '百度',
advanced: '高级'
};
var order = ['basic', 'recommended', 'baidu', 'advanced'];
var tabs = document.createElement('div');
tabs.className = 'tspamreview-tabs';
var anchor = document.createElement('div');
anchor.className = 'tspamreview-tabs-anchor';
var groups = {};
// Insert tabs before moving any nodes
host.insertBefore(tabs, firstSection);
host.insertBefore(anchor, tabs.nextSibling);
order.forEach(function(key) {
groups[key] = document.createElement('div');
groups[key].className = 'tspamreview-group';
groups[key].setAttribute('data-tab-group', key);
});
sections.forEach(function(section) {
var key = section.getAttribute('data-tab') || 'basic';
var currentKey = key === 'overview' ? 'basic' : key;
var bucket = groups[currentKey] || groups.basic;
var node = section;
while (node) {
var next = node.nextElementSibling;
if (node.classList && node.classList.contains('submit')) {
break;
}
bucket.appendChild(node);
if (!next || (next.classList && next.classList.contains('tspamreview-section-head'))) {
break;
}
node = next;
}
});
order.forEach(function(key, index) {
var button = document.createElement('button');
button.type = 'button';
button.className = 'tspamreview-tab' + (index === 0 ? ' active' : '');
button.setAttribute('data-tab-target', key);
button.textContent = map[key] || key;
tabs.appendChild(button);
if (index === 0) {
groups[key].classList.add('active');
}
host.insertBefore(groups[key], anchor.nextSibling);
});
Array.prototype.forEach.call(tabs.querySelectorAll('.tspamreview-tab'), function(tab) {
tab.addEventListener('click', function() {
var target = this.getAttribute('data-tab-target');
Array.prototype.forEach.call(tabs.querySelectorAll('.tspamreview-tab'), function(item) { item.classList.remove('active'); });
Array.prototype.forEach.call(host.querySelectorAll('.tspamreview-group'), function(group) { group.classList.remove('active'); });
this.classList.add('active');
var panel = host.querySelector('.tspamreview-group[data-tab-group="' + target + '"]');
if (panel) {
panel.classList.add('active');
}
});
});
// Move original submit row(s) to the end of the form
if (form) {
var submitRows = Array.prototype.slice.call(form.querySelectorAll('.submit'));
submitRows.forEach(function(row) {
form.appendChild(row);
if (row.classList) {
row.classList.add('tspamreview-native-submit');
}
});
}
// Add a save button under every tab
order.forEach(function(key) {
var group = host.querySelector('.tspamreview-group[data-tab-group="' + key + '"]');
if (!group) {
return;
}
var bar = document.createElement('div');
bar.className = 'tspamreview-savebar';
bar.innerHTML = '<button type="button" class="btn primary">保存设置</button>';
bar.querySelector('button').addEventListener('click', function() {
var targetForm = form || (host.closest ? host.closest('form') : null) || document.querySelector('form');
if (!targetForm) {
return;
}
var btn = targetForm.querySelector('button[type=submit],input[type=submit]');
if (btn) {
btn.click();
return;
}
try { targetForm.submit(); } catch (e) {}
});
group.appendChild(bar);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initTabs, {once: true});
} else {
initTabs();
}
var button = document.querySelector('.tspamreview-refresh-token');
if (!button) {
return;
}
button.addEventListener('click', function() {
var url = this.getAttribute('data-url');
if (!url) {
return;
}
var original = this.textContent;
var card = this.closest('.tspamreview-inline-card');
this.disabled = true;
this.textContent = '刷新中...';
fetch(url, {method: 'POST', credentials: 'same-origin'})
.then(function(response) { return response.json(); })
.then(function(data) {
if (!card || !data || !data.status) {
window.alert(data && data.message ? data.message : '刷新完成');
button.disabled = false;
button.textContent = original;
return;
}
card.classList.remove('is-ok', 'is-warning');
card.classList.add(data.status.cached ? 'is-ok' : 'is-warning');
var refreshState = data.status.last_refresh_status === 'success' ? '最近刷新成功' : (data.status.last_refresh_status === 'failed' ? '最近刷新失败' : '尚未刷新');
var errorText = data.status.last_error ? data.status.last_error : '无';
var cacheText = data.status.cached ? '已缓存' : '未缓存 / 已过期';
var mapping = {
cached: '缓存状态:' + cacheText,
remaining: '剩余有效期:' + data.status.remaining_text,
refresh: '最近刷新:' + data.status.last_refresh_text + '(' + refreshState + ')',
error: '最近错误:' + errorText
};
Object.keys(mapping).forEach(function(key) {
var el = card.querySelector('[data-token-field="' + key + '"]');
if (el) { el.textContent = mapping[key]; }
});
button.disabled = false;
button.textContent = original;
})
.catch(function() {
window.alert('Token 刷新失败,请稍后重试');
button.disabled = false;
button.textContent = original;
});
});
})();
</script>
<?php
}
private static function renderCommentAdminEnhancement()
{
$securityUrl = Helper::security()->getIndex('/action/TSpamReviewBlacklist');
$pluginConfigUrl = '';
try {
$user = Typecho_Widget::widget('Widget_User');
if ($user->pass('administrator', true)) {
$pluginConfigUrl = Typecho_Widget::widget('Widget_Options')->adminUrl('options-plugin.php?config=TSpamReview', true);
}
} catch (Exception $e) {
}
?>
<style>
.tspam-blacklist-row {
display: inline-flex;
align-items: center;
margin-left: 8px;
}
.tspam-blacklist-btn {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 999px;
background: #fff1ef;
color: #c0392b !important;
cursor: pointer !important;
transition: background .2s ease, color .2s ease;
}
.tspam-blacklist-btn:hover {
background: #ffe3dd;
text-decoration: none;
}
@media (max-width: 575px) {
.tspam-blacklist-row {
display: block;
margin: 6px 0 0;
}
}
</style>
<script>
(function($) {
'use strict';
var securityUrl = <?php echo json_encode($securityUrl); ?>;
var pluginConfigUrl = <?php echo json_encode($pluginConfigUrl); ?>;
if (pluginConfigUrl && !$('.typecho-list-operate .operate .tspam-config-btn').length) {
$('.typecho-list-operate .operate').append('<button class="btn btn-s tspam-config-btn" type="button">拉黑管理</button>');
$('.tspam-config-btn').on('click', function() {
window.location.href = pluginConfigUrl;
});
}
$('.typecho-list-table tbody tr').each(function() {
var $row = $(this);
var commentData = $row.data('comment');
if (!commentData || $row.find('.tspam-blacklist-btn').length) {
return;
}
var coid = $row.find('input[type=checkbox]').first().val();
var ip = commentData.ip || '';
var email = commentData.mail || '';
var author = commentData.author || '匿名';
if (!ip && !email) {
return;
}
var html = '';
html += '<div class="tspam-blacklist-row">';
html += '<span class="tspam-blacklist-btn" data-coid="' + coid + '" data-ip="' + ip + '" data-email="' + email + '" data-author="' + author + '">拉黑</span>';
html += '</div>';
$row.find('.comment-action').append(html);
});
$(document).on('click', '.tspam-blacklist-btn', function(e) {
e.preventDefault();
e.stopPropagation();
var $btn = $(this);
var coid = $btn.data('coid');
var ip = $btn.data('ip');
var email = $btn.data('email');
var author = $btn.data('author');
var message = '确认拉黑该评论?\n\n评论者:' + author;
if (ip) {
message += '\nIP:' + ip;
}
if (email) {
message += '\n邮箱:' + email;
}
message += '\n\n拉黑后将阻止其再次评论。';
if (!window.confirm(message)) {
return false;
}
var params = [];
if (ip) {
params.push('ip=' + encodeURIComponent(ip));
}
if (email) {
params.push('email=' + encodeURIComponent(email));
}
params.push('coid=' + encodeURIComponent(coid));
window.location.href = securityUrl + '&' + params.join('&');
return false;
});
})(jQuery);
</script>
<?php
}
public static function onBeforeComment($comment, $post = null, $widget = null)
{
$opts = Typecho_Widget::widget('Widget_Options')->plugin('TSpamReview');
$logContext = array_merge(TSpamReview_ReviewEngine::buildRequestContext(), ['stage' => 'before_comment', 'runBaidu' => true]);
$evaluation = TSpamReview_ReviewEngine::evaluate($comment, $opts, array_merge(
$logContext,
['runBaidu' => true]
));
if ($evaluation['decision'] === 'deny') {
TSpamReview_ReviewEngine::logBlockedComment($comment, $evaluation['reason'], $opts, $logContext);
throw new Typecho_Widget_Exception(_t('评论提交失败'));
}
if ($evaluation['decision'] === 'hold') {
$comment['status'] = 'waiting';
}
return $comment;
}
public static function onFinishComment()
{
$args = func_get_args();
$widget = isset($args[0]) ? $args[0] : null;
$comment = count($args) === 2 ? $args[1] : (isset($args[0]) ? $args[0] : null);
$returnValue = count($args) === 2 ? $args[1] : $comment;
if (!$comment) {
return $returnValue;
}
$opts = Typecho_Widget::widget('Widget_Options')->plugin('TSpamReview');
$type = (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'type');
$status = (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'status');
if (($type !== '' && $type !== 'comment') || in_array($status, ['waiting', 'hidden'], true)) {
return $returnValue;
}
$coid = (int) TSpamReview_ReviewEngine::getFieldValue($comment, 'coid');
if (!$coid && $widget) {
$coid = (int) TSpamReview_ReviewEngine::getFieldValue($widget, 'coid');
}
$data = [
'text' => (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'text'),
'author' => (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'author'),
'mail' => (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'mail'),
'ip' => (string) TSpamReview_ReviewEngine::getFieldValue($comment, 'ip'),
'status' => $status,
];
$logContext = array_merge(TSpamReview_ReviewEngine::buildRequestContext(), ['stage' => 'finish_comment', 'runBaidu' => true]);
$evaluation = TSpamReview_ReviewEngine::evaluate($data, $opts, array_merge(
$logContext,
['runBaidu' => true]
));
if ($evaluation['decision'] === 'deny' && $coid > 0) {
TSpamReview_ReviewEngine::logBlockedComment($data + ['coid' => $coid], $evaluation['reason'], $opts, $logContext);
self::deleteCommentById($coid);
}
if ($evaluation['decision'] === 'hold' && $coid > 0) {
self::updateCommentStatus($coid, 'waiting');
}
return $returnValue;
}
private static function updateCommentStatus($coid, $status)
{
try {
$db = Typecho_Db::get();
$db->query(
$db->update('table.comments')
->rows(['status' => $status])
->where('coid = ?', $coid)
);
} catch (Exception $e) {
}
}
private static function deleteCommentById($coid)
{
try {
$db = Typecho_Db::get();
$comment = $db->fetchRow($db->select()->from('table.comments')->where('coid = ?', $coid)->limit(1));
if (!$comment) {
return;
}
$cid = isset($comment['cid']) ? (int) $comment['cid'] : 0;
$db->query($db->delete('table.comments')->where('coid = ?', $coid));
if ($cid > 0) {
$content = $db->fetchRow($db->select('commentsNum')->from('table.contents')->where('cid = ?', $cid)->limit(1));
if ($content && isset($content['commentsNum'])) {
$db->query(
$db->update('table.contents')
->rows(['commentsNum' => max(0, (int) $content['commentsNum'] - 1)])
->where('cid = ?', $cid)
);
}
}
} catch (Exception $e) {
}
}
}
if (!class_exists('TSpamReview_Action')) {
require_once __DIR__ . '/Action.php';
}
if (!class_exists('TSpamReview_BlacklistAction')) {
try {
$isAdmin = defined('__TYPECHO_ADMIN__');
$uri = '';
try {
$uri = (string) Typecho_Request::getInstance()->getRequestUri();
} catch (Exception $e) {
}
if ($isAdmin || strpos($uri, 'action/TSpamReviewBlacklist') !== false) {
require_once __DIR__ . '/BlacklistAction.php';
}
} catch (Exception $e) {
}
}