-
Notifications
You must be signed in to change notification settings - Fork 591
Expand file tree
/
Copy pathProtection.php
More file actions
1708 lines (1539 loc) · 52.8 KB
/
Copy pathProtection.php
File metadata and controls
1708 lines (1539 loc) · 52.8 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;
/**
* 原图保护存储。
*
* 私有目录按 usr/uploads 后的相对路径镜像保存原图,公开目录只保存派生图。
*
* @author NHPT
* @copyright Copyright (c) 2026 NHPT
* @license GNU General Public License 2.0
* @link https://github.com/NHPT/Watermark
*/
class Watermark_Protection
{
const STORE_FORMAT = 1;
const TASK_FORMAT = 1;
const STORE_MARKER = '.watermark-store.json';
const RELOCATION_MARKER = '.watermark-relocation.json';
const TASK_PREFIX = '.watermark-task-';
const METADATA_SUFFIX = '.watermark.json';
const LOCK_SUFFIX = '.watermark.lock';
private static $lastError = '';
private static $managed = array();
/**
* 是否启用原图保护模式。
*
* @param object $config
* @return bool
*/
public static function enabled($config)
{
return 'protected' === Watermark_Plugin::configValue(
$config,
'vm_mode',
'dynamic'
);
}
/**
* 获取最后一次错误。
*
* @return string
*/
public static function lastError()
{
return self::$lastError;
}
/**
* 获取默认私有目录。
*
* @return string
*/
public static function defaultDirectory()
{
$root = realpath(__TYPECHO_ROOT_DIR__);
$root = false === $root ? __TYPECHO_ROOT_DIR__ : $root;
return dirname($root) . DIRECTORY_SEPARATOR . '.typecho-watermark';
}
/**
* 获取配置的私有目录。
*
* @param object $config
* @return string
*/
public static function configuredDirectory($config)
{
if (defined('__TYPECHO_WATERMARK_PRIVATE_DIR__')) {
return rtrim((string) constant('__TYPECHO_WATERMARK_PRIVATE_DIR__'), '/\\');
}
$directory = trim((string) Watermark_Plugin::configValue(
$config,
'vm_private_dir',
self::defaultDirectory()
));
return rtrim($directory, '/\\');
}
/**
* 校验并初始化私有目录。
*
* @param object $config
* @return string|false
*/
public static function ensureStore($config)
{
self::$lastError = '';
$directory = self::configuredDirectory($config);
if (!self::isAbsolutePath($directory) || self::containsParentTraversal($directory)) {
return self::fail('私有原图目录必须是绝对路径,且不能包含 ..');
}
if (!self::isAllowedByOpenBaseDir($directory)) {
return self::fail(
'PHP open_basedir 禁止访问私有原图目录:' . $directory
. '。当前允许路径:' . self::openBaseDirSetting()
. '。请在当前 PHP 运行环境的生效配置中加入私有目录,并使配置重新生效'
);
}
$publicRoots = array(__TYPECHO_ROOT_DIR__);
if (defined('__TYPECHO_UPLOAD_ROOT_DIR__')) {
$publicRoots[] = constant('__TYPECHO_UPLOAD_ROOT_DIR__');
}
$resolvedPublicRoots = array();
foreach ($publicRoots as $publicRoot) {
$publicRoot = @realpath($publicRoot);
if (false === $publicRoot) {
continue;
}
$resolvedPublicRoots[] = $publicRoot;
if (self::isWithin($directory, $publicRoot)) {
return self::fail('私有原图目录必须位于网站公开根目录之外');
}
}
if (
!@is_dir($directory)
&& !@mkdir($directory, 0700, true)
&& !@is_dir($directory)
) {
return self::fail(
'无法创建私有原图目录:' . $directory
. '。请确认父目录权限以及当前 Web/PHP 服务账户的写权限'
);
}
$resolved = @realpath($directory);
if (false === $resolved || !@is_dir($resolved)) {
return self::fail('无法解析私有原图目录');
}
foreach ($resolvedPublicRoots as $publicRoot) {
if (self::isWithin($resolved, $publicRoot)) {
return self::fail('私有原图目录必须位于网站公开根目录之外');
}
}
$marker = $resolved . DIRECTORY_SEPARATOR . self::STORE_MARKER;
if (!is_file($marker)) {
$entries = @scandir($resolved);
if (false === $entries || array_diff($entries, array('.', '..'))) {
return self::fail('私有目录非空且缺少 Watermark 存储标记');
}
if (!self::writeJsonAtomic($marker, array(
'format' => self::STORE_FORMAT,
'createdAt' => gmdate('c')
), 0600)) {
return self::fail('无法初始化私有原图目录');
}
}
$metadata = json_decode((string) @file_get_contents($marker), true);
if (
!is_array($metadata)
|| !isset($metadata['format'])
|| self::STORE_FORMAT !== (int) $metadata['format']
) {
return self::fail('私有原图目录格式不受支持');
}
if (!@is_writable($resolved)) {
return self::fail('私有原图目录不可写');
}
return $resolved;
}
/**
* 获取 PHP open_basedir 原始设置。
*
* @return string
*/
public static function openBaseDirSetting()
{
$setting = trim((string) ini_get('open_basedir'));
return '' === $setting ? '未限制' : $setting;
}
/**
* 生成包含私有目录的 open_basedir 建议值。
*
* @param string $directory
* @return string
*/
public static function recommendedOpenBaseDir($directory)
{
$setting = trim((string) ini_get('open_basedir'));
if ('' === $setting) {
return $directory;
}
if (self::isAllowedByOpenBaseDir($directory)) {
return $setting;
}
$paths = array_values(array_filter(
explode(PATH_SEPARATOR, $setting),
function ($path) {
return '' !== trim($path);
}
));
array_splice($paths, max(0, count($paths) - 1), 0, array(
rtrim($directory, '/\\') . DIRECTORY_SEPARATOR
));
return implode(PATH_SEPARATOR, $paths);
}
/**
* 判断图片是否已有可信的私有原图。
*
* @param string $relativePath
* @param object $config
* @return bool
*/
public static function isManaged($relativePath, $config)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return false;
}
$cacheKey = self::configuredDirectory($config) . '|' . $relativePath;
if (array_key_exists($cacheKey, self::$managed)) {
return self::$managed[$cacheKey];
}
$private = self::privatePath($relativePath, $config, false);
if (false === $private || !is_file($private)) {
return self::$managed[$cacheKey] = false;
}
$metadata = self::readMetadata($private);
$managed = is_array($metadata)
&& isset($metadata['relative'], $metadata['originalSha256'], $metadata['state'])
&& $relativePath === $metadata['relative']
&& preg_match('/^[a-f0-9]{64}$/', $metadata['originalSha256'])
&& 'protected' === $metadata['state'];
return self::$managed[$cacheKey] = $managed;
}
/**
* 获取公开水印成品的缓存版本。
*
* @param string $relativePath
* @param object $config
* @return string
*/
public static function publicVersion($relativePath, $config)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return '';
}
$private = self::privatePath($relativePath, $config, false);
$metadata = false !== $private && is_file($private)
? self::readMetadata($private)
: false;
if (
!is_array($metadata)
|| !isset($metadata['relative'], $metadata['state'], $metadata['publicSha256'])
|| $relativePath !== $metadata['relative']
|| 'protected' !== $metadata['state']
|| !preg_match('/^[a-f0-9]{64}$/', $metadata['publicSha256'])
) {
return '';
}
return substr($metadata['publicSha256'], 0, 16);
}
/**
* 捕获刚上传的原图并生成公开派生图。
*
* @param string $relativePath
* @param object $config
* @param bool $reuseExisting
* @return array
*/
public static function captureAndProtect($relativePath, $config, $reuseExisting = false)
{
self::$lastError = '';
$source = Watermark_Plugin::resolveImagePath($relativePath);
if (false === $source) {
return self::result(false, 'error', '上传文件不是受支持的本地图片');
}
if (Watermark_Plugin::isAnimatedGif($source['absolute'])) {
return self::result(false, 'error', '原图保护模式不支持动态 GIF');
}
$store = self::ensureStore($config);
if (false === $store) {
return self::result(false, 'error', self::$lastError);
}
$private = self::privatePath($source['relative'], $config, true);
if (false === $private) {
return self::result(false, 'error', self::$lastError);
}
$lock = self::lock($private);
if (false === $lock) {
return self::result(false, 'error', self::$lastError);
}
if ($reuseExisting && is_file($private)) {
$result = self::isCurrent($source['relative'], $private, $config)
? self::result(true, 'skipped', '水印成品与当前配置一致')
: self::renderPrivateToPublic($source['relative'], $private, $config);
self::invalidateManagedCache($source['relative'], $config);
self::unlock($lock);
return $result;
}
$hasOldPrivate = is_file($private);
$oldPrivate = $hasOldPrivate
? self::temporaryPath(dirname($private), '.previous-')
: false;
if ($hasOldPrivate && false === $oldPrivate) {
self::unlock($lock);
return self::result(false, 'error', '无法创建私有原图备份');
}
$staged = self::temporaryPath(dirname($private), '.original-');
if (false === $staged || !self::copyVerified($source['absolute'], $staged, 0600)) {
if (false !== $staged) {
@unlink($staged);
}
if (false !== $oldPrivate) {
@unlink($oldPrivate);
}
self::unlock($lock);
return self::result(false, 'error', '无法保存私有原图');
}
if (false !== $oldPrivate) {
@unlink($oldPrivate);
if (!@rename($private, $oldPrivate)) {
@unlink($staged);
self::unlock($lock);
return self::result(false, 'error', '无法备份已有私有原图');
}
}
if (!@rename($staged, $private)) {
if (false !== $oldPrivate) {
@rename($oldPrivate, $private);
}
@unlink($staged);
self::unlock($lock);
return self::result(false, 'error', '无法提交私有原图');
}
if (!@unlink($source['absolute'])) {
@unlink($private);
if (false !== $oldPrivate) {
@rename($oldPrivate, $private);
}
self::unlock($lock);
return self::result(false, 'error', '无法移除公开目录中的原图');
}
$result = self::renderPrivateToPublic($source['relative'], $private, $config);
if (empty($result['success'])) {
if (false !== $oldPrivate) {
@unlink($private);
@rename($oldPrivate, $private);
self::renderPrivateToPublic($source['relative'], $private, $config);
} else {
self::copyVerified($private, $source['absolute'], 0644);
@unlink($private);
@unlink(self::metadataPath($private));
}
self::invalidateManagedCache($source['relative'], $config);
self::unlock($lock);
return $result;
}
if (false !== $oldPrivate) {
@unlink($oldPrivate);
}
self::invalidateManagedCache($source['relative'], $config);
self::unlock($lock);
return $result;
}
/**
* 迁移或重新生成一张公开图片。
*
* @param string $relativePath
* @param object $config
* @return array
*/
public static function protectExisting($relativePath, $config)
{
self::$lastError = '';
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return self::result(false, 'error', '上传路径无效');
}
$private = self::privatePath($relativePath, $config, true);
if (false === $private) {
return self::result(false, 'error', self::$lastError);
}
if (!is_file($private)) {
return self::captureAndProtect($relativePath, $config, true);
}
$lock = self::lock($private);
if (false === $lock) {
return self::result(false, 'error', self::$lastError);
}
if (self::isCurrent($relativePath, $private, $config)) {
self::unlock($lock);
return self::result(true, 'skipped', '水印成品与当前配置一致');
}
$result = self::renderPrivateToPublic($relativePath, $private, $config);
self::invalidateManagedCache($relativePath, $config);
self::unlock($lock);
return $result;
}
/**
* 将一张私有原图恢复到公开路径,保留私有副本。
*
* @param string $relativePath
* @param object $config
* @return array
*/
public static function restore($relativePath, $config)
{
self::$lastError = '';
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return self::result(false, 'error', '上传路径无效');
}
$private = self::privatePath($relativePath, $config, false);
$public = self::publicPath($relativePath, true);
if (false === $private || !is_file($private)) {
return self::result(true, 'skipped', '没有对应的私有原图');
}
if (false === $public) {
return self::result(false, 'error', self::$lastError);
}
$lock = self::lock($private);
if (false === $lock) {
return self::result(false, 'error', self::$lastError);
}
if (!self::copyVerified($private, $public, 0644)) {
self::unlock($lock);
return self::result(false, 'error', '恢复公开原图失败');
}
$metadata = self::buildMetadata($relativePath, $private, $public, $config, 'restored');
if (!self::writeMetadata($private, $metadata)) {
self::unlock($lock);
return self::result(false, 'error', '原图已恢复,但状态元数据写入失败');
}
self::invalidateManagedCache($relativePath, $config);
self::unlock($lock);
return self::result(true, 'restored', '原图已恢复');
}
/**
* 删除附件对应的私有原图与状态文件。
*
* @param string $relativePath
* @param object $config
* @return void
*/
public static function remove($relativePath, $config)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return;
}
$private = self::privatePath($relativePath, $config, false);
if (false === $private) {
return;
}
@unlink($private);
@unlink(self::metadataPath($private));
self::invalidateManagedCache($relativePath, $config);
}
/**
* 获取公开上传目录中的图片路径。
*
* @return array
*/
public static function publicImages()
{
$root = realpath(__TYPECHO_ROOT_DIR__ . '/' . Watermark_Plugin::UPLOAD_RELATIVE_DIR);
if (false === $root) {
return array();
}
return self::listImages($root, '/' . Watermark_Plugin::UPLOAD_RELATIVE_DIR);
}
/**
* 获取私有目录中的原图路径。
*
* @param object $config
* @return array
*/
public static function privateImages($config)
{
$root = self::ensureStore($config);
if (false === $root) {
return array();
}
return self::listImages($root, '/' . Watermark_Plugin::UPLOAD_RELATIVE_DIR);
}
/**
* 返回图片在保护任务中的状态。
*
* @param string $relativePath
* @param object $config
* @return string
*/
public static function protectionState($relativePath, $config)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return 'error';
}
$private = self::privatePath($relativePath, $config, true);
if (false === $private) {
return 'error';
}
if (!is_file($private)) {
return 'migrate';
}
return self::isCurrent($relativePath, $private, $config)
? 'current'
: 'regenerate';
}
/**
* 返回图片在公开原图恢复任务中的状态。
*
* @param string $relativePath
* @param object $config
* @return string
*/
public static function restorationState($relativePath, $config)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return 'error';
}
$private = self::privatePath($relativePath, $config, false);
if (false === $private || !is_file($private)) {
return 'error';
}
$public = self::publicPath($relativePath);
if (false === $public || !is_file($public)) {
return 'restore';
}
$privateHash = @hash_file('sha256', $private);
$publicHash = @hash_file('sha256', $public);
return false !== $privateHash
&& false !== $publicHash
&& hash_equals($privateHash, $publicHash)
? 'current'
: 'restore';
}
/**
* 返回私有原图在目录迁移任务中的状态。
*
* @param string $relativePath
* @param object $config
* @param string $targetDirectory
* @return string
*/
public static function relocationState($relativePath, $config, $targetDirectory)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return 'error';
}
$source = self::privatePath($relativePath, $config, false);
$targetConfig = self::configWithDirectory($config, $targetDirectory);
$target = self::privatePath($relativePath, $targetConfig, true);
if (false === $source || !is_file($source) || false === $target) {
return 'error';
}
if (!is_file($target) || !is_file(self::metadataPath($target))) {
return 'copy';
}
$sourceHash = @hash_file('sha256', $source);
$targetHash = @hash_file('sha256', $target);
$sourceMetadataHash = @hash_file('sha256', self::metadataPath($source));
$targetMetadataHash = @hash_file('sha256', self::metadataPath($target));
return false !== $sourceHash
&& false !== $targetHash
&& false !== $sourceMetadataHash
&& false !== $targetMetadataHash
&& hash_equals($sourceHash, $targetHash)
&& hash_equals($sourceMetadataHash, $targetMetadataHash)
? 'current'
: 'copy';
}
/**
* 读取持久化管理任务。
*
* @param object $config
* @param string $operation
* @return array|false
*/
public static function loadTask($config, $operation)
{
$path = self::taskPath($config, $operation);
if (false === $path || !is_file($path)) {
return false;
}
$task = json_decode((string) @file_get_contents($path), true);
return is_array($task)
&& isset($task['format'], $task['operation'])
&& self::TASK_FORMAT === (int) $task['format']
&& $operation === $task['operation']
? $task
: false;
}
/**
* 原子保存管理任务。
*
* @param object $config
* @param string $operation
* @param array $task
* @return bool
*/
public static function saveTask($config, $operation, array $task)
{
$path = self::taskPath($config, $operation);
if (false === $path) {
return false;
}
$task['format'] = self::TASK_FORMAT;
$task['operation'] = $operation;
$task['updatedAt'] = gmdate('c');
return self::writeJsonAtomic($path, $task, 0600);
}
/**
* 删除指定管理任务。
*
* @param object $config
* @param string $operation
* @return void
*/
public static function deleteTask($config, $operation)
{
$path = self::taskPath($config, $operation);
if (false !== $path) {
@unlink($path);
}
}
/**
* 获取管理任务独占锁。
*
* @param object $config
* @param string $operation
* @return resource|false
*/
public static function lockTask($config, $operation)
{
$path = self::taskPath($config, $operation);
if (false === $path) {
return false;
}
$handle = @fopen($path . self::LOCK_SUFFIX, 'c');
if (!$handle || !@flock($handle, LOCK_EX | LOCK_NB)) {
if ($handle) {
@fclose($handle);
}
return self::fail('无法锁定批处理任务');
}
return $handle;
}
/**
* 释放管理任务锁。
*
* @param resource $handle
* @return void
*/
public static function unlockTask($handle)
{
self::unlock($handle);
}
/**
* 返回私有存储状态。
*
* @param object $config
* @return array
*/
public static function status($config)
{
$directory = self::ensureStore($config);
return array(
'ready' => false !== $directory,
'directory' => self::configuredDirectory($config),
'error' => false === $directory ? self::$lastError : ''
);
}
/**
* 判断私有存储中是否已有原图。
*
* @param object $config
* @return bool
*/
public static function hasOriginals($config)
{
return (bool) self::privateImages($config);
}
/**
* 判断两个目录配置是否指向同一路径。
*
* @param string $first
* @param string $second
* @return bool
*/
public static function sameDirectory($first, $second)
{
$first = self::normalizeAbsolutePath($first);
$second = self::normalizeAbsolutePath($second);
return false !== $first && false !== $second && $first === $second;
}
/**
* 初始化可恢复的私有目录迁移。
*
* @param object $config
* @param string $targetDirectory
* @return array
*/
public static function prepareRelocation($config, $targetDirectory)
{
self::$lastError = '';
$source = self::ensureStore($config);
if (false === $source) {
return self::result(false, 'error', self::$lastError);
}
if (self::sameDirectory($source, $targetDirectory)) {
return self::result(false, 'error', '新目录与当前私有目录相同');
}
$targetConfig = self::configWithDirectory($config, $targetDirectory);
$target = self::ensureStore($targetConfig);
if (false === $target) {
return self::result(false, 'error', self::$lastError);
}
$relocationFile = $target . DIRECTORY_SEPARATOR . self::RELOCATION_MARKER;
$relocation = is_file($relocationFile)
? json_decode((string) @file_get_contents($relocationFile), true)
: false;
if (is_array($relocation)) {
if (
empty($relocation['source'])
|| !self::sameDirectory($relocation['source'], $source)
) {
return self::result(false, 'error', '目标目录属于另一项未完成的迁移');
}
} else {
$sourcePaths = self::privateImages($config);
$targetPaths = self::privateImages($targetConfig);
if (array_diff($targetPaths, $sourcePaths)) {
return self::result(false, 'error', '目标目录包含当前源目录中不存在的原图');
}
foreach ($targetPaths as $relativePath) {
$sourceFile = self::privatePath($relativePath, $config, false);
$targetFile = self::privatePath($relativePath, $targetConfig, false);
$sourceHash = false !== $sourceFile
? @hash_file('sha256', $sourceFile)
: false;
$targetHash = false !== $targetFile
? @hash_file('sha256', $targetFile)
: false;
if (
false === $sourceHash
|| false === $targetHash
|| !hash_equals($sourceHash, $targetHash)
) {
return self::result(false, 'error', '目标目录存在内容冲突:' . $relativePath);
}
}
if (!self::writeJsonAtomic($relocationFile, array(
'format' => self::STORE_FORMAT,
'source' => $source,
'createdAt' => gmdate('c')
), 0600)) {
return self::result(false, 'error', '无法初始化目录迁移状态');
}
}
return self::result(true, 'ready', '目标私有目录已就绪');
}
/**
* 将一张私有原图和元数据复制到迁移目标。
*
* @param string $relativePath
* @param object $config
* @param string $targetDirectory
* @return array
*/
public static function relocateOriginal($relativePath, $config, $targetDirectory)
{
$relativePath = self::normalizeRelativePath($relativePath);
if (false === $relativePath) {
return self::result(false, 'error', '上传路径无效');
}
$source = self::privatePath($relativePath, $config, false);
$targetConfig = self::configWithDirectory($config, $targetDirectory);
$target = self::privatePath($relativePath, $targetConfig, true);
if (false === $source || !is_file($source) || false === $target) {
return self::result(false, 'error', self::$lastError ?: '私有原图不存在');
}
$lock = self::lock($source);
if (false === $lock) {
return self::result(false, 'error', self::$lastError);
}
try {
$metadata = self::readMetadata($source);
if (
!is_array($metadata)
|| empty($metadata['originalSha256'])
|| $relativePath !== $metadata['relative']
) {
return self::result(false, 'error', '源原图元数据缺失或无效');
}
$sourceHash = @hash_file('sha256', $source);
if (
false === $sourceHash
|| !hash_equals($metadata['originalSha256'], $sourceHash)
) {
return self::result(false, 'error', '源原图 SHA-256 校验失败');
}
if (is_file($target)) {
$targetHash = @hash_file('sha256', $target);
if (false === $targetHash || !hash_equals($sourceHash, $targetHash)) {
return self::result(false, 'error', '目标目录存在同名但内容不同的原图');
}
} elseif (!self::copyVerified($source, $target, 0600)) {
return self::result(false, 'error', '复制私有原图失败');
}
if (
!self::copyVerified(
self::metadataPath($source),
self::metadataPath($target),
0600
)
) {
@unlink($target);
return self::result(false, 'error', '复制原图元数据失败');
}
$targetHash = @hash_file('sha256', $target);
if (false === $targetHash || !hash_equals($sourceHash, $targetHash)) {
@unlink($target);
@unlink(self::metadataPath($target));
return self::result(false, 'error', '迁移后 SHA-256 校验失败');
}
return self::result(true, 'copied', '原图和元数据已复制并校验');
} finally {
self::unlock($lock);
}
}
/**
* 验证迁移目标完整性并结束迁移状态。
*
* @param object $config
* @param string $targetDirectory
* @return array
*/
public static function finishRelocation($config, $targetDirectory)
{
$prepared = self::prepareRelocation($config, $targetDirectory);
if (empty($prepared['success'])) {
return $prepared;
}
$sourcePaths = self::privateImages($config);
$targetConfig = self::configWithDirectory($config, $targetDirectory);
$targetPaths = self::privateImages($targetConfig);
sort($sourcePaths, SORT_STRING);
sort($targetPaths, SORT_STRING);
if ($sourcePaths !== $targetPaths) {
return self::result(false, 'error', '目标目录的原图清单与源目录不一致');
}
foreach ($sourcePaths as $relativePath) {
$source = self::privatePath($relativePath, $config, false);
$target = self::privatePath($relativePath, $targetConfig, false);
$sourceHash = false !== $source ? @hash_file('sha256', $source) : false;
$targetHash = false !== $target ? @hash_file('sha256', $target) : false;
if (
false === $sourceHash
|| false === $targetHash
|| !hash_equals($sourceHash, $targetHash)
|| !is_file(self::metadataPath($target))
) {
return self::result(false, 'error', '目标目录完整性校验失败:' . $relativePath);
}
}
if (false === self::ensureStore($targetConfig)) {
return self::result(false, 'error', self::$lastError);
}
return self::result(true, 'complete', '全部私有原图和元数据已校验');
}
/**
* 配置切换成功后清理目标目录的迁移状态。
*
* @param string $targetDirectory
* @return void
*/
public static function completeRelocation($targetDirectory)
{
$targetDirectory = @realpath($targetDirectory);
if (false !== $targetDirectory) {
@unlink($targetDirectory . DIRECTORY_SEPARATOR . self::RELOCATION_MARKER);
}
}
/**
* 从私有原图生成公开文件。
*
* @param string $relativePath
* @param string $private
* @param object $config
* @return array
*/
private static function renderPrivateToPublic($relativePath, $private, $config)
{
$source = self::sourceInfo($relativePath, $private);
if (false === $source) {
return self::result(false, 'error', '私有原图不是受支持的图片');
}
if (Watermark_Plugin::isAnimatedGif($private)) {
return self::result(false, 'error', '原图保护模式不支持动态 GIF');
}
$public = self::publicPath($relativePath, true);
if (false === $public) {
return self::result(false, 'error', self::$lastError);
}
if (!Watermark_Plugin::isImageEligible($source, $config)) {
if (!self::copyVerified($private, $public, 0644)) {
return self::result(false, 'error', '写入排除图片失败');
}