-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.php
More file actions
2716 lines (2483 loc) · 89.5 KB
/
Copy pathPlugin.php
File metadata and controls
2716 lines (2483 loc) · 89.5 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
999
1000
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
require_once __DIR__ . '/Protection.php';
/**
* 为 Typecho 图片添加图片或文字水印,支持动态水印与原图保护模式;
* 可将无水印原图存储在 Web 根目录外,并提供历史图片迁移、原图恢复、
* 平铺、旋转、尺寸过滤及缓存。
*
* @package Watermark
* @author NHPT, DEFE
* @version 2.0.0
* @dependence 1.2.0-*
* @copyright Copyright (c) 2013 DEFE
* @copyright Modifications Copyright (c) 2026 NHPT
* @license GNU General Public License 2.0
* @link https://github.com/NHPT/Watermark
*/
class Watermark_Plugin implements Typecho_Plugin_Interface
{
const VERSION = '2.0.0';
const CACHE_RELATIVE_DIR = 'usr/cache/watermark';
const UPLOAD_RELATIVE_DIR = 'usr/uploads';
const BACKUP_PLUGIN_NAME = 'WatermarkBackup';
private static $lastRenderError = '';
/**
* 激活插件
*
* @return string
* @throws Typecho_Plugin_Exception
*/
public static function activate()
{
if (!function_exists('gd_info')) {
throw new Typecho_Plugin_Exception(_t('对不起,您的 PHP 环境没有开启 GD 扩展'));
}
$backup = self::backupSettings();
if (
'protected' === self::arrayValue($backup, 'vm_mode', 'dynamic')
) {
$store = Watermark_Protection::status((object) $backup);
if (empty($store['ready'])) {
$directory = (string) self::arrayValue(
$backup,
'vm_private_dir',
Watermark_Protection::defaultDirectory()
);
throw new Typecho_Plugin_Exception(_t(
'无法恢复原图保护配置:%s',
self::privateDirectoryHelp($directory, $store['error'])
));
}
}
// Typecho 1.2/1.3 在 Markdown 渲染完成后处理正文。
Typecho_Plugin::factory('Widget\\Base\\Contents')->contentEx = array(
'Watermark_Plugin',
'parseContent'
);
// 保留旧版 Typecho 的内容过滤入口。
Typecho_Plugin::factory('Widget_Abstract_Contents')->filter = array(
'Watermark_Plugin',
'parseLegacy'
);
$upload = Typecho_Plugin::factory('Widget\\Upload');
$upload->beforeUpload = array('Watermark_Plugin', 'beforeUpload');
$upload->beforeModify = array('Watermark_Plugin', 'beforeModify');
$upload->upload = array('Watermark_Plugin', 'afterUpload');
$upload->modify = array('Watermark_Plugin', 'afterUpload');
Typecho_Plugin::factory('Widget\\Contents\\Attachment\\Edit')->finishDelete = array(
'Watermark_Plugin',
'afterDelete'
);
Helper::addAction('Watermark', 'Watermark_Action');
if (!self::ensureCacheDirectory()) {
return _t('插件已经激活,但缓存目录不可写;请关闭缓存或检查 usr/cache 目录权限');
}
return _t(
'插件已经激活。原图保护模式需要在设置页保存后,再执行“迁移或重新生成现有图片”'
);
}
/**
* 禁用插件
*/
public static function deactivate()
{
$settings = self::settingsToArray(self::pluginOptions());
if ($settings) {
Helper::configPlugin(self::BACKUP_PLUGIN_NAME, $settings);
}
Helper::removeAction('Watermark');
}
/**
* 插件配置
*
* @param Typecho_Widget_Helper_Form $form
*/
public static function config(Typecho_Widget_Helper_Form $form)
{
$options = Typecho_Widget::widget('Widget_Options');
$security = Typecho_Widget::widget('Widget_Security');
$manageToken = rawurlencode($security->getToken('watermark-manage'));
$manageBase = $options->index . '/action/Watermark?_=' . $manageToken;
$protectUrl = $manageBase . '&manage=protect';
$restoreUrl = $manageBase . '&manage=restore';
$relocateUrl = $manageBase . '&manage=relocate';
$savedConfig = self::pluginOptions($options);
$defaultPrivateDir = defined('__TYPECHO_WATERMARK_PRIVATE_DIR__')
? (string) constant('__TYPECHO_WATERMARK_PRIVATE_DIR__')
: Watermark_Protection::defaultDirectory();
$currentPrivateDir = Watermark_Protection::configuredDirectory($savedConfig);
$submittedMode = isset($_POST['vm_mode'])
? (string) $_POST['vm_mode']
: (Watermark_Protection::enabled($savedConfig) ? 'protected' : 'dynamic');
$submittedPrivateDir = isset($_POST['vm_private_dir'])
? trim((string) $_POST['vm_private_dir'])
: $currentPrivateDir;
$privateValidationMessage = _t(
'原图保护目录无法初始化:%s',
$submittedPrivateDir
);
$submittedPrivateError = '';
$directoryChanged = !Watermark_Protection::sameDirectory(
$currentPrivateDir,
$submittedPrivateDir
);
$savedStore = Watermark_Protection::enabled($savedConfig)
? Watermark_Protection::status($savedConfig)
: null;
$changeBlocked = $directoryChanged
&& (
(is_array($savedStore) && empty($savedStore['ready']))
|| Watermark_Protection::hasOriginals($savedConfig)
);
if ($changeBlocked) {
$submittedPrivateError = _t(
'当前私有目录已有原图,不能直接修改路径;请使用“安全迁移私有目录”'
);
$privateValidationMessage = $submittedPrivateError;
} elseif ('protected' === $submittedMode) {
$storeReady = false !== Watermark_Protection::ensureStore((object) array(
'vm_private_dir' => $submittedPrivateDir
));
if (!$storeReady) {
$submittedPrivateError = Watermark_Protection::lastError();
$privateValidationMessage = self::privateDirectoryHelp(
$submittedPrivateDir,
$submittedPrivateError
);
}
}
if (Watermark_Protection::enabled($savedConfig)) {
$store = $savedStore;
$modeMessage = empty($store['ready'])
? _t(
'<span style="color:#c62828;font-weight:600">'
. '当前状态:原图保护模式,但私有原图目录不可用:%s</span>',
htmlspecialchars($store['error'], ENT_QUOTES, 'UTF-8')
)
: _t(
'<span style="color:#2e7d32;font-weight:600">'
. '当前状态:原图保护模式。该模式会在正文图片首次访问时'
. '自动迁移原图到私有原图目录,但建议仍执行批量迁移以覆盖'
. '正文外图片。</span>'
);
} else {
$modeMessage = _t(
'<span style="color:#2e7d32;font-weight:600">'
. '当前状态:动态模式。该模式不会创建私有原图目录,'
. '也不能阻止直接访问原图。</span>'
);
}
$vmMode = new Typecho_Widget_Helper_Form_Element_Radio(
'vm_mode',
array(
'dynamic' => _t('动态模式'),
'protected' => _t('原图保护模式')
),
'dynamic',
_t('工作模式'),
$modeMessage
);
$form->addInput($vmMode);
$privateMessage = _t(
'必须使用网站公开根目录之外的绝对路径。目录结构与 usr/uploads 对应,'
. '更新、停用或删除插件代码不会删除原图。'
);
if (
'protected' === $submittedMode
&& '' !== $submittedPrivateError
) {
$privateMessage .= self::privateDirectoryHelpHtml(
$submittedPrivateDir,
$submittedPrivateError
);
}
if (defined('__TYPECHO_WATERMARK_PRIVATE_DIR__')) {
$privateMessage .= _t(
'<br>当前目录由 __TYPECHO_WATERMARK_PRIVATE_DIR__ 常量锁定。'
);
}
$vmPrivateDir = new Typecho_Widget_Helper_Form_Element_Text(
'vm_private_dir',
NULL,
$defaultPrivateDir,
_t('私有原图目录'),
NULL
);
if ('protected' === $submittedMode && !empty($storeReady)) {
$privateStatus = new Typecho_Widget_Helper_Layout(
'p',
array('class' => 'watermark-private-status')
);
$privateStatus->html(_t(
'目录校验成功:%s',
htmlspecialchars($submittedPrivateDir, ENT_QUOTES, 'UTF-8')
));
$vmPrivateDir->container->removeItem($vmPrivateDir->input);
$vmPrivateDir->container($privateStatus);
$vmPrivateDir->container($vmPrivateDir->input);
}
$vmPrivateDir->description($privateMessage);
if (defined('__TYPECHO_WATERMARK_PRIVATE_DIR__')) {
$vmPrivateDir->input->setAttribute('readonly', 'readonly');
}
$form->addInput($vmPrivateDir->addRule(
array('Watermark_Plugin', 'validatePrivateDirectory'),
$privateValidationMessage
));
$form->addItem(self::managementTools(
$protectUrl,
$restoreUrl,
$relocateUrl
));
$vmType = new Typecho_Widget_Helper_Form_Element_Checkbox(
'vm_type',
array('pic' => _t('图片'), 'text' => _t('文字')),
array('pic'),
_t('水印类型')
);
$form->addInput($vmType);
$vmLayout = new Typecho_Widget_Helper_Form_Element_Radio(
'vm_layout',
array('single' => _t('单点'), 'tile' => _t('全图平铺')),
'single',
_t('水印布局'),
_t('单点模式保持原有位置设置;全图平铺模式按间距重复绘制水印')
);
$form->addInput($vmLayout);
$positions = array(
_t('随机'),
_t('顶端左侧'),
_t('顶端中间'),
_t('顶端右侧'),
_t('中部左侧'),
_t('正中'),
_t('中部右侧'),
_t('底部左侧'),
_t('底部中间'),
_t('底部右侧')
);
$vmPosPic = new Typecho_Widget_Helper_Form_Element_Select(
'vm_pos_pic',
$positions,
9,
_t('水印图片位置')
);
$form->addInput($vmPosPic);
$vmPosText = new Typecho_Widget_Helper_Form_Element_Select(
'vm_pos_text',
$positions,
9,
_t('水印文字位置')
);
$form->addInput($vmPosText);
$vmAngle = new Typecho_Widget_Helper_Form_Element_Text(
'vm_angle',
NULL,
'0',
_t('旋转角度'),
_t('取 -180 到 180 之间的整数,正数逆时针旋转')
);
$vmAngle->input->setAttribute('class', 'mini');
$form->addInput($vmAngle->addRule('isInteger', _t('必须是整数')));
$vmGapX = new Typecho_Widget_Helper_Form_Element_Text(
'vm_gap_x',
NULL,
'80',
_t('平铺水平间距'),
_t('相邻水印之间的水平空白像素,仅全图平铺模式生效')
);
$vmGapX->input->setAttribute('class', 'mini');
$form->addInput($vmGapX->addRule('isInteger', _t('必须是整数')));
$vmGapY = new Typecho_Widget_Helper_Form_Element_Text(
'vm_gap_y',
NULL,
'60',
_t('平铺垂直间距'),
_t('相邻水印之间的垂直空白像素,仅全图平铺模式生效')
);
$vmGapY->input->setAttribute('class', 'mini');
$form->addInput($vmGapY->addRule('isInteger', _t('必须是整数')));
$images = array();
$fonts = array();
$fileList = @scandir(__DIR__);
if (is_array($fileList)) {
foreach ($fileList as $file) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($extension, array('ttf', 'ttc'), true)) {
$fonts[] = $file;
}
if (in_array($extension, array('png', 'gif', 'jpg', 'jpeg', 'webp'), true)) {
$images[] = $file;
}
}
}
$imageMessage = $images
? _t('可用图片:%s', implode('、', $images))
: _t('插件目录中没有可用的水印图片');
$fontMessage = $fonts
? _t('可用字体:%s', implode('、', $fonts))
: _t('插件目录中没有可用的字体文件');
$vmPic = new Typecho_Widget_Helper_Form_Element_Text(
'vm_pic',
NULL,
'WM.png',
_t('水印图片'),
$imageMessage
);
$vmPic->input->setAttribute('class', 'mini');
$form->addInput($vmPic);
$vmText = new Typecho_Widget_Helper_Form_Element_Text(
'vm_text',
NULL,
'Typecho)))',
_t('水印文字')
);
$form->addInput($vmText);
$vmFont = new Typecho_Widget_Helper_Form_Element_Text(
'vm_font',
NULL,
'lh.ttf',
_t('文字字体'),
$fontMessage
);
$vmFont->input->setAttribute('class', 'mini');
$form->addInput($vmFont);
$vmSize = new Typecho_Widget_Helper_Form_Element_Text(
'vm_size',
NULL,
'16',
_t('文字大小')
);
$vmSize->input->setAttribute('class', 'mini');
$form->addInput($vmSize->addRule('isInteger', _t('必须是整数')));
$vmColor = new Typecho_Widget_Helper_Form_Element_Text(
'vm_color',
NULL,
'255,0,0',
_t('文字颜色'),
_t('格式:255,255,255 或 #FF0000')
);
$vmColor->input->setAttribute('class', 'mini');
$form->addInput($vmColor);
$vmMX = new Typecho_Widget_Helper_Form_Element_Text(
'vm_m_x',
NULL,
'0',
_t('水平微调'),
_t('输入整数,可以为负数')
);
$vmMX->input->setAttribute('class', 'mini');
$form->addInput($vmMX->addRule('isInteger', _t('必须是整数')));
$vmMY = new Typecho_Widget_Helper_Form_Element_Text(
'vm_m_y',
NULL,
'0',
_t('竖直微调'),
_t('输入整数,可以为负数')
);
$vmMY->input->setAttribute('class', 'mini');
$form->addInput($vmMY->addRule('isInteger', _t('必须是整数')));
$vmWidth = new Typecho_Widget_Helper_Form_Element_Text(
'vm_width',
NULL,
'0',
_t('调整图片宽度'),
_t('设为 0 表示不调整;大于 0 时仅缩小宽度超过该值的图片')
);
$vmWidth->input->setAttribute('class', 'mini');
$form->addInput($vmWidth->addRule('isInteger', _t('必须是整数')));
$vmMinWidth = new Typecho_Widget_Helper_Form_Element_Text(
'vm_min_width',
NULL,
'0',
_t('原图最小宽度'),
_t('原图宽度小于该值时不添加水印,0 表示不限制')
);
$vmMinWidth->input->setAttribute('class', 'mini');
$form->addInput($vmMinWidth->addRule('isInteger', _t('必须是整数')));
$vmMinHeight = new Typecho_Widget_Helper_Form_Element_Text(
'vm_min_height',
NULL,
'0',
_t('原图最小高度'),
_t('原图高度小于该值时不添加水印,0 表示不限制')
);
$vmMinHeight->input->setAttribute('class', 'mini');
$form->addInput($vmMinHeight->addRule('isInteger', _t('必须是整数')));
$vmExclude = new Typecho_Widget_Helper_Form_Element_Textarea(
'vm_exclude',
NULL,
'',
_t('图片排除列表'),
_t(
'每行一条规则,支持完整上传路径、上传目录相对路径、文件名及 *、? 通配符;'
. '例如 /usr/uploads/avatar/、2026/logo.png、logo-*'
)
);
$form->addInput($vmExclude);
$vmAlpha = new Typecho_Widget_Helper_Form_Element_Text(
'vm_alpha',
NULL,
'0',
_t('图片透明度'),
_t('取 0-100 之间的整数,0 为不透明,100 为全透明')
);
$vmAlpha->input->setAttribute('class', 'mini');
$form->addInput($vmAlpha->addRule('isInteger', _t('必须是整数')));
$vmTextAlpha = new Typecho_Widget_Helper_Form_Element_Text(
'vm_text_alpha',
NULL,
'0',
_t('文字透明度'),
_t('取 0-100 之间的整数,0 为不透明,100 为全透明')
);
$vmTextAlpha->input->setAttribute('class', 'mini');
$form->addInput($vmTextAlpha->addRule('isInteger', _t('必须是整数')));
$clearUrl = $options->index . '/action/Watermark?clear=1&_='
. rawurlencode($security->getToken('watermark-clear'));
$cacheMessage = self::ensureCacheDirectory()
? _t(
'缓存目录:%s。<a href="%s" target="_blank">清除水印缓存</a>',
self::CACHE_RELATIVE_DIR,
htmlspecialchars($clearUrl, ENT_QUOTES, 'UTF-8')
)
: _t('缓存目录不可写,请检查 usr/cache 目录权限');
$vmCache = new Typecho_Widget_Helper_Form_Element_Radio(
'vm_cache',
array('cache' => _t('使用缓存'), 'nocache' => _t('不使用缓存')),
'nocache',
_t('使用缓存'),
$cacheMessage
);
$form->addInput($vmCache);
}
/**
* 个人配置
*
* @param Typecho_Widget_Helper_Form $form
*/
public static function personalConfig(Typecho_Widget_Helper_Form $form)
{
}
/**
* 构建设置页内的图片管理工具和模态对话框。
*
* @param string $protectUrl
* @param string $restoreUrl
* @param string $relocateUrl
* @return Typecho_Widget_Helper_Layout
*/
private static function managementTools($protectUrl, $restoreUrl, $relocateUrl)
{
$layout = new Typecho_Widget_Helper_Layout(
'ul',
array('class' => 'typecho-option', 'id' => 'watermark-management-tools')
);
$item = new Typecho_Widget_Helper_Layout('li');
$item->html(
'<label class="typecho-label">' . _t('图片管理') . '</label>'
. '<div class="message error watermark-private-warning">'
. '<strong>'
. _t(
'注意:删除、清空或覆盖私有原图目录会导致无水印原图永久丢失。'
)
. '</strong> '
. _t(
'该目录保存唯一可恢复的无水印版本;即使公开水印图片仍能显示,'
. '也无法再恢复原图。'
)
. '</div>'
. '<div class="watermark-tool-actions">'
. self::managementButton(
_t('迁移或重新生成现有图片'),
$protectUrl,
_t('迁移或重新生成现有图片'),
'btn',
_t('正在扫描现有图片'),
_t('正在检查公开上传目录、私有原图和当前水印配置,请稍候。')
)
. self::managementButton(
_t('恢复公开原图'),
$restoreUrl,
_t('恢复公开原图'),
'btn btn-warn',
_t('正在检测可恢复原图'),
_t('正在比对私有原图与公开文件,请稍候。')
)
. self::managementButton(
_t('安全迁移私有目录'),
$relocateUrl,
_t('安全迁移私有目录'),
'btn',
_t('正在读取目录迁移状态'),
_t('正在检查私有目录和未完成任务,请稍候。')
)
. '</div>'
. '<p class="description">'
. _t('管理操作会在当前页面打开;请阅读弹窗说明后再执行。')
. '</p>'
. self::managementDialog()
);
$layout->addItem($item);
return $layout;
}
/**
* 生成设置页管理按钮。
*
* @param string $label
* @param string $url
* @param string $title
* @param string $class
* @param string $loading
* @param string $loadingDetail
* @return string
*/
private static function managementButton(
$label,
$url,
$title,
$class,
$loading,
$loadingDetail
) {
return '<button type="button" class="'
. htmlspecialchars($class, ENT_QUOTES, 'UTF-8')
. ' watermark-open-dialog" data-url="'
. htmlspecialchars($url, ENT_QUOTES, 'UTF-8')
. '" data-title="'
. htmlspecialchars($title, ENT_QUOTES, 'UTF-8')
. '" data-loading="'
. htmlspecialchars($loading, ENT_QUOTES, 'UTF-8')
. '" data-loading-detail="'
. htmlspecialchars($loadingDetail, ENT_QUOTES, 'UTF-8')
. '">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</button>';
}
/**
* 生成当前页面模态对话框。
*
* @return string
*/
private static function managementDialog()
{
return <<<'HTML'
<div id="watermark-dialog" class="watermark-dialog" hidden aria-hidden="true">
<div class="watermark-dialog-backdrop" data-watermark-close></div>
<section class="watermark-dialog-panel" role="dialog" aria-modal="true"
aria-labelledby="watermark-dialog-title">
<header class="watermark-dialog-header">
<strong id="watermark-dialog-title"></strong>
<button type="button" class="watermark-dialog-close" data-watermark-close
aria-label="关闭">×</button>
</header>
<div id="watermark-dialog-loading" class="watermark-dialog-loading"
role="status" aria-live="polite">
<span class="watermark-loading-spinner" aria-hidden="true"></span>
<strong id="watermark-loading-title">正在读取任务状态</strong>
<span id="watermark-loading-detail">请稍候。</span>
</div>
<iframe id="watermark-dialog-frame" title="Watermark 图片管理"></iframe>
</section>
</div>
<style>
.watermark-private-status {
margin: 0 0 .5em; color: #2e7d32; font-weight: 600;
}
.watermark-private-warning { margin: 0 0 12px; }
.watermark-tool-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.watermark-tool-actions .btn { margin: 0; }
.watermark-dialog[hidden] { display: none; }
.watermark-dialog { position: fixed; inset: 0; z-index: 1000; }
.watermark-dialog-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, .42); }
.watermark-dialog-panel {
position: absolute; top: 50%; left: 50%; box-sizing: border-box;
width: calc(100% - 32px); max-width: 760px; height: 360px; max-height: calc(100% - 48px);
transform: translate(-50%, -50%); transition: height .16s ease;
background: #fff; border-radius: 2px; box-shadow: 0 12px 40px rgba(0, 0, 0, .28);
overflow: hidden;
}
.watermark-dialog-header {
box-sizing: border-box; display: flex; align-items: center; justify-content: space-between;
height: 48px; padding: 0 12px 0 16px; border-bottom: 1px solid #d9d9d6;
background: #f6f6f3;
}
.watermark-dialog-close {
border: 0; background: transparent; color: #666; cursor: pointer;
width: 32px; height: 32px; padding: 0; font-size: 24px; line-height: 30px;
}
.watermark-dialog-close:hover { color: #b94a48; }
#watermark-dialog-frame { display: block; border: 0; width: 100%; height: calc(100% - 48px); }
.watermark-dialog-loading {
position: absolute; z-index: 2; inset: 48px 0 0; display: none;
box-sizing: border-box; padding: 24px; background: #fff;
align-items: center; justify-content: center; flex-direction: column;
text-align: center; color: #555;
}
.watermark-dialog-loading strong { margin-top: 14px; color: #333; font-size: 16px; }
.watermark-dialog-loading span:last-child { margin-top: 5px; color: #888; }
.watermark-dialog-panel.is-loading .watermark-dialog-loading { display: flex; }
.watermark-dialog-panel.is-loading #watermark-dialog-frame { visibility: hidden; }
.watermark-loading-spinner {
box-sizing: border-box; width: 34px; height: 34px; border: 3px solid #d9d9d6;
border-top-color: #467b96; border-radius: 50%;
animation: watermark-loading-spin .75s linear infinite;
}
@keyframes watermark-loading-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.watermark-loading-spinner { animation-duration: 1.5s; }
}
@media (max-width: 575px) {
.watermark-tool-actions { display: grid; }
.watermark-tool-actions .btn { width: 100%; }
.watermark-dialog-panel {
width: calc(100% - 16px); height: calc(100% - 16px); max-height: none;
}
}
</style>
<script>
(function () {
function ready(fn) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
ready(function () {
var dialog = document.getElementById('watermark-dialog');
var frame = document.getElementById('watermark-dialog-frame');
var title = document.getElementById('watermark-dialog-title');
var panel = dialog ? dialog.querySelector('.watermark-dialog-panel') : null;
var loadingTitle = document.getElementById('watermark-loading-title');
var loadingDetail = document.getElementById('watermark-loading-detail');
var previousOverflow = '';
var activeTrigger = null;
if (!dialog || !frame || !title || !panel || !loadingTitle || !loadingDetail) {
return;
}
function showLoading(message, detail) {
loadingTitle.textContent = message || '正在处理任务';
loadingDetail.textContent = detail || '正在保存进度并加载最新统计,请稍候。';
panel.classList.add('is-loading');
}
function hideLoading() {
panel.classList.remove('is-loading');
}
frame.addEventListener('load', function () {
try {
var frameWindow = frame.contentWindow;
var frameDocument = frame.contentDocument;
if (!frameWindow || frameWindow.location.href === 'about:blank') {
if (dialog.hidden) {
hideLoading();
}
return;
}
hideLoading();
frameWindow.addEventListener('beforeunload', function () {
if (!panel.classList.contains('is-loading')) {
showLoading(
'正在处理任务',
'正在保存本批结果并加载最新统计,请稍候。'
);
}
});
frameDocument.addEventListener('submit', function (event) {
var control = event.target.querySelector(
'input[name="control"]'
);
var messages = {
rescan: ['正在重新扫描', '正在重新检查全部图片状态,请稍候。'],
prepare: ['正在验证目标目录', '正在检查目录并建立迁移任务,请稍候。'],
retry: ['正在重试失败项', '正在重新处理失败项目,请稍候。'],
pause: ['正在暂停任务', '正在保存当前进度,请稍候。']
};
var message = control ? messages[control.value] : null;
showLoading(
message ? message[0] : '正在处理任务',
message
? message[1]
: '正在保存本批结果并加载最新统计,请稍候。'
);
});
if (window.innerWidth <= 575) {
panel.style.height = 'calc(100% - 16px)';
return;
}
var body = frameDocument.body;
var root = frameDocument.documentElement;
var contentHeight = Math.max(
body ? body.scrollHeight : 0,
root ? root.scrollHeight : 0
);
panel.style.height = Math.min(680, Math.max(300, contentHeight + 48)) + 'px';
} catch (error) {
panel.style.height = '680px';
}
});
function closeDialog() {
dialog.hidden = true;
dialog.setAttribute('aria-hidden', 'true');
frame.src = 'about:blank';
hideLoading();
document.body.style.overflow = previousOverflow;
if (activeTrigger) {
activeTrigger.focus();
activeTrigger = null;
}
}
Array.prototype.forEach.call(
document.querySelectorAll('.watermark-open-dialog'),
function (button) {
button.addEventListener('click', function () {
activeTrigger = button;
previousOverflow = document.body.style.overflow;
title.textContent = button.getAttribute('data-title') || '';
showLoading(
button.getAttribute('data-loading'),
button.getAttribute('data-loading-detail')
);
dialog.hidden = false;
dialog.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
dialog.querySelector('.watermark-dialog-close').focus();
frame.src = button.getAttribute('data-url');
});
}
);
Array.prototype.forEach.call(
dialog.querySelectorAll('[data-watermark-close]'),
function (button) {
button.addEventListener('click', closeDialog);
}
);
document.addEventListener('keydown', function (event) {
if (!dialog.hidden && (event.key === 'Escape' || event.keyCode === 27)) {
closeDialog();
}
});
});
}());
</script>
HTML;
}
/**
* 在保存设置时创建并校验私有目录。
*
* @param string $directory
* @return bool
*/
public static function validatePrivateDirectory($directory)
{
$mode = isset($_POST['vm_mode']) ? (string) $_POST['vm_mode'] : 'dynamic';
$savedConfig = self::pluginOptions();
$currentDirectory = Watermark_Protection::configuredDirectory($savedConfig);
if (
!Watermark_Protection::sameDirectory($currentDirectory, $directory)
&& (
(
Watermark_Protection::enabled($savedConfig)
&& empty(Watermark_Protection::status($savedConfig)['ready'])
)
|| Watermark_Protection::hasOriginals($savedConfig)
)
) {
return false;
}
return 'protected' !== $mode
|| false !== Watermark_Protection::ensureStore((object) array(
'vm_private_dir' => $directory
));
}
/**
* 生成纯文本目录修复提示。
*
* @param string $directory
* @param string $error
* @return string
*/
private static function privateDirectoryHelp($directory, $error)
{
$permission = self::permissionInstruction($directory);
return _t(
'%s。目标目录:%s。建议 open_basedir:%s。'
. '请在当前 PHP 运行环境的生效配置中修改 open_basedir;配置位置可能是 '
. 'php.ini、PHP-FPM 池、Web 服务器虚拟主机、.user.ini 或托管控制面板。'
. '%s。%s',
$error,
$directory,
Watermark_Protection::recommendedOpenBaseDir($directory),
$permission['text'],
self::reloadInstruction()
);
}
/**
* 生成设置页目录修复提示。
*
* @param string $directory
* @param string $error
* @return string
*/
private static function privateDirectoryHelpHtml($directory, $error)
{
$openBaseDir = Watermark_Protection::recommendedOpenBaseDir($directory);
$permission = self::permissionInstruction($directory);
return '<br><strong>目录校验失败:</strong>'
. htmlspecialchars($error, ENT_QUOTES, 'UTF-8')
. '<br><strong>建议 open_basedir:</strong><code>'
. htmlspecialchars($openBaseDir, ENT_QUOTES, 'UTF-8')
. '</code><br>请在当前环境实际生效的 php.ini、PHP-FPM 池、'
. 'Web 服务器虚拟主机、.user.ini 或托管控制面板中修改。'
. '<br><strong>目录权限:</strong>'
. htmlspecialchars($permission['text'], ENT_QUOTES, 'UTF-8')
. ('' !== $permission['command']
? '<br><code>'
. htmlspecialchars($permission['command'], ENT_QUOTES, 'UTF-8')
. '</code>'
: '')
. '<br>' . htmlspecialchars(self::reloadInstruction(), ENT_QUOTES, 'UTF-8');
}
/**
* 生成适配当前操作系统和进程账户的权限提示。
*
* @param string $directory
* @return array
*/
private static function permissionInstruction($directory)
{
if ('\\' === DIRECTORY_SEPARATOR) {
return array(
'text' => _t(
'请创建该目录,并通过 NTFS ACL 授予当前 Web 应用程序池或 PHP 服务账户读写权限'
),
'command' => ''
);
}
$account = self::runtimeAccount();
$placeholder = '<PHP运行用户>:<PHP运行组>';
$owner = '' !== $account ? $account : $placeholder;
$command = 'mkdir -p ' . escapeshellarg($directory)
. ' && chown ' . escapeshellarg($owner) . ' ' . escapeshellarg($directory)
. ' && chmod 700 ' . escapeshellarg($directory);
$text = '' !== $account
? _t('检测到当前 PHP 进程账户为 %s;无法自动创建时可由管理员执行:', $account)
: _t(
'无法检测当前 PHP 进程账户;请将命令中的 %s 替换为实际 Web/PHP 服务账户:',
$placeholder
);
return array('text' => $text, 'command' => $command);
}
/**
* 获取当前 PHP 进程的有效用户和组。
*
* @return string
*/
private static function runtimeAccount()
{
if (
!function_exists('posix_geteuid')
|| !function_exists('posix_getegid')
|| !function_exists('posix_getpwuid')
|| !function_exists('posix_getgrgid')
) {
return '';
}
$user = @posix_getpwuid(posix_geteuid());
$group = @posix_getgrgid(posix_getegid());
if (
!is_array($user)
|| !is_array($group)
|| empty($user['name'])
|| empty($group['name'])
) {
return '';
}
return $user['name'] . ':' . $group['name'];
}
/**
* 根据 PHP SAPI 生成配置生效提示。
*
* @return string
*/
private static function reloadInstruction()
{
$sapi = strtolower(PHP_SAPI);
if (false !== strpos($sapi, 'apache')) {
return _t('修改后请重新加载 Apache,使 PHP 配置生效。');
}
if (false !== strpos($sapi, 'litespeed')) {
return _t('修改后请重新加载 LiteSpeed,使 PHP 配置生效。');
}
if (false !== strpos($sapi, 'fpm') || false !== strpos($sapi, 'fastcgi')) {
return _t('修改后请重新加载对应的 PHP-FPM/FastCGI 服务,使配置生效。');
}
return _t(
'修改后请重新加载当前 Web/PHP 服务,或按托管平台要求等待配置生效。'
);
}
/**
* 接管配置保存,确保无效保护配置不会写入数据库。
*
* @param array $settings
* @param bool $isInit
*/
public static function configHandle($settings, $isInit)
{
$settings = is_array($settings) ? $settings : array();
if ($isInit) {
$backup = self::backupSettings();
if ($backup) {
$settings = array_merge($settings, $backup);
}
}
$savedConfig = self::pluginOptions();
$currentDirectory = Watermark_Protection::configuredDirectory($savedConfig);
$newDirectory = (string) self::arrayValue(
$settings,
'vm_private_dir',
Watermark_Protection::defaultDirectory()
);
$savedStore = Watermark_Protection::enabled($savedConfig)
? Watermark_Protection::status($savedConfig)
: null;