-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
sync-qcloud-cos.php
1866 lines (1633 loc) · 72.8 KB
/
sync-qcloud-cos.php
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
/*
Plugin Name: Sync QCloud COS
Plugin URI: https://qq52o.me/2518.html
Description: 使用腾讯云对象存储服务 COS 作为附件存储空间。(Using Tencent Cloud Object Storage Service COS as Attachment Storage Space.)
Version: 2.6.1
Author: 沈唁
Author URI: https://qq52o.me
License: Apache2.0
*/
if (!defined('ABSPATH')) {
exit;
}
require_once 'cos-sdk-v5/vendor/autoload.php';
use Qcloud\Cos\Client;
use Qcloud\Cos\Exception\ServiceResponseException;
use SyncQcloudCos\CI\Audit;
use SyncQcloudCos\CI\FilePreview;
use SyncQcloudCos\CI\ImageSlim;
use SyncQcloudCos\CI\OriginProtect;
use SyncQcloudCos\CI\Service;
use SyncQcloudCos\ErrorCode;
use SyncQcloudCos\Monitor\Charts;
use SyncQcloudCos\Monitor\DataPoints;
use SyncQcloudCos\Object\Head;
define('COS_VERSION', '2.6.1');
define('COS_PLUGIN_SLUG', 'sync-qcloud-cos');
define('COS_PLUGIN_PAGE', plugin_basename(dirname(__FILE__)) . '%2F' . basename(__FILE__));
if (!function_exists('get_home_path')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
if (defined('WP_CLI') && WP_CLI) {
require_once plugin_dir_path(__FILE__) . 'cos-commands.php';
}
// 初始化选项
register_activation_hook(__FILE__, 'cos_set_options');
function cos_get_default_options()
{
return [
'bucket' => '',
'regional' => 'ap-beijing',
'app_id' => '',
'secret_id' => '',
'secret_key' => '',
'nothumb' => 'false', // 是否上传缩略图
'nolocalsaving' => 'false', // 是否保留本地备份
'delete_options' => 'true',
'upload_subdirectory' => '',
'upload_url_path' => '', // URL前缀
'update_file_name' => 'false', // 是否重命名文件名
'ci_style' => '',
'ci_image_slim' => 'off',
'ci_image_slim_mode' => '',
'ci_image_slim_suffix' => '',
'attachment_preview' => 'off',
'ci_text_comments' => 'off',
'skip_comment_validation_on_login' => 'off',
'ci_text_comments_strategy' => '',
'ci_text_comments_check_roles' => '',
'origin_protect' => 'off',
];
}
function cos_set_options()
{
add_option('cos_options', cos_get_default_options(), '', 'yes');
}
/**
* @param array $cos_options
* @return Client
*/
function cos_get_client($cos_options = null)
{
if ($cos_options === null) {
$cos_options = get_option('cos_options', cos_get_default_options());
}
$config = [
'region' => esc_attr($cos_options['regional']),
'scheme' => cos_get_url_scheme(''),
'credentials' => [
'secretId' => esc_attr($cos_options['secret_id']),
'secretKey' => esc_attr($cos_options['secret_key'])
],
'userAgent' => 'WordPress v' . $GLOBALS['wp_version'] . '; SyncQCloudCOS v' . COS_VERSION . '; SDK v' . Client::VERSION,
];
return new Client($config);
}
function cos_get_bucket_name($cos_options = null)
{
if ($cos_options === null) {
$cos_options = get_option('cos_options', cos_get_default_options());
}
$cos_bucket = esc_attr($cos_options['bucket']);
$cos_app_id = esc_attr($cos_options['app_id']);
if (empty($cos_bucket) && empty($cos_app_id)) {
return '';
}
$needle = '-' . $cos_app_id;
if (strpos($cos_bucket, $needle) !== false) {
return $cos_bucket;
}
return $cos_bucket . $needle;
}
function cos_check_bucket($cos_options)
{
try {
$client = cos_get_client($cos_options);
$bucket = cos_get_bucket_name($cos_options);
$client->HeadBucket(['Bucket' => $bucket]);
$upload = $client->upload($bucket, 'sync-qcloud-cos.txt', COS_PLUGIN_SLUG);
if ($upload) {
$client->DeleteObject(['Bucket' => $bucket, 'Key' => 'sync-qcloud-cos.txt']);
}
return true;
} catch (ServiceResponseException $e) {
$message = (string)$e;
$errorCode = $e->getCosErrorCode();
if ($errorCode == ErrorCode::NO_SUCH_BUCKET) {
$message = '<code>Bucket</code> 不存在,请检查存储桶名称和 <code>APP ID</code> 参数!';
} elseif ($errorCode == ErrorCode::ACCESS_DENIED) {
$message = '<code>SecretID</code> 或 <code>SecretKey</code> 有误,请检查配置信息!';
}
echo "<div class='error'><p><strong>{$message}</strong></p></div>";
} catch (\Throwable $e) {
$message = (string)$e;
echo "<div class='error'><p><strong>{$message}</strong></p></div>";
}
return false;
}
/**
* @param Client $client
* @param string $bucket
* @return Client
*/
function cos_replace_client_region($client, $bucket)
{
if ($client->getCosConfig('region') != 'accelerate') {
return $client;
}
$list = $client->listBuckets();
$buckets = $list['Buckets'][0]['Bucket'];
$buckets = array_column($buckets, null, 'Name');
if (isset($buckets[$bucket])) {
$client->setCosConfig('region', $buckets[$bucket]['Location']);
}
return $client;
}
$cos_options = get_option('cos_options', cos_get_default_options());
if (!empty($cos_options['origin_protect']) && esc_attr($cos_options['origin_protect']) === 'on' && !empty(esc_attr($cos_options['ci_style']))) {
add_filter('wp_get_attachment_url', 'cos_add_suffix_to_attachment_url', 10, 2);
add_filter('wp_get_attachment_thumb_url', 'cos_add_suffix_to_attachment_url', 10, 2);
add_filter('wp_get_original_image_url', 'cos_add_suffix_to_attachment_url', 10, 2);
add_filter('wp_prepare_attachment_for_js', 'cos_add_suffix_to_attachment', 10, 2);
add_filter('image_get_intermediate_size', 'cos_add_suffix_for_media_send_to_editor');
}
/**
* @param string $url
* @param int $post_id
* @return string
*/
function cos_add_suffix_to_attachment_url($url, $post_id)
{
if (cos_is_image_type($url)) {
$url .= cos_get_image_style();
}
return $url;
}
/**
* @param array $response
* @param array $attachment
* @return array
*/
function cos_add_suffix_to_attachment($response, $attachment)
{
if ($response['type'] != 'image') {
return $response;
}
$style = cos_get_image_style();
if (!empty($response['sizes'])) {
foreach ($response['sizes'] as $size_key => $size_file) {
if (cos_is_image_type($size_file['url'])) {
$response['sizes'][$size_key]['url'] .= $style;
}
}
}
if(!empty($response['originalImageURL'])) {
if (cos_is_image_type($response['originalImageURL'])) {
$response['originalImageURL'] .= $style;
}
}
return $response;
}
/**
* @param array $data
* @return array
*/
function cos_add_suffix_for_media_send_to_editor($data)
{
// https://github.com/WordPress/wordpress-develop/blob/43d2455dc68072fdd43c3c800cc8c32590f23cbe/src/wp-includes/media.php#L239
if (cos_is_image_type($data['file'])) {
$data['file'] .= cos_get_image_style();
}
return $data;
}
/**
* @param string $url
* @return bool
*/
function cos_is_image_type($url)
{
return (bool) preg_match('/\.(jpg|jpeg|jpe|gif|png|bmp|webp|heic|heif)$/i', $url);
}
/**
* @return string
*/
function cos_get_image_style()
{
$cos_options = get_option('cos_options', cos_get_default_options());
return esc_attr($cos_options['ci_style']);
}
/**
* @param string $object
* @param string $filename
* @param bool $no_local_file
* @return bool
*/
function cos_file_upload($object, $filename, $no_local_file = false)
{
//如果文件不存在,直接返回false
if (!@file_exists($filename)) {
return false;
}
$options = get_option('cos_options', cos_get_default_options());
$bucket = cos_get_bucket_name($options);
try {
$file = fopen($filename, 'rb');
if ($file) {
if (!empty($options['upload_subdirectory'])) {
$object = '/' . esc_attr($options['upload_subdirectory']) . $object;
}
$cosClient = cos_get_client($options);
$cosClient->upload($bucket, $object, $file);
if (is_resource($file)) {
fclose($file);
}
if ($no_local_file) {
cos_delete_local_file($filename);
}
return true;
}
} catch (\Throwable $e) {
error_log($e->getMessage());
}
return false;
}
/**
* 是否需要删除本地文件
*
* @return bool
*/
function cos_is_delete_local_file()
{
$cos_options = get_option('cos_options', cos_get_default_options());
return esc_attr($cos_options['nolocalsaving']) == 'true';
}
/**
* 删除本地文件
*
* @param string $file
* @return bool
*/
function cos_delete_local_file($file)
{
try {
//文件不存在
if (!@file_exists($file)) {
return true;
}
//删除文件
if (!@unlink($file)) {
return false;
}
return true;
} catch (Exception $ex) {
return false;
}
}
/**
* 删除cos中的单个文件
* @param string $file
*/
function cos_delete_cos_file($file)
{
$options = get_option('cos_options', cos_get_default_options());
$bucket = cos_get_bucket_name($options);
$cosClient = cos_get_client($options);
if (!empty($options['upload_subdirectory'])) {
$file = esc_attr($options['upload_subdirectory']) . '/' . ltrim($file, '/');
}
$cosClient->deleteObject(['Bucket' => $bucket, 'Key' => $file]);
}
/**
* 批量删除cos中的文件
* @param array $files
*/
function cos_delete_cos_files(array $files)
{
$options = get_option('cos_options', cos_get_default_options());
$subdirectory = !empty($options['upload_subdirectory']) ? esc_attr($options['upload_subdirectory']) . '/' : '';
$deleteObjects = [];
foreach ($files as $file) {
$fileKey = str_replace(["\\", './'], ['/', ''], $subdirectory . $file);
$deleteObjects[] = ['Key' => $fileKey];
}
$bucket = cos_get_bucket_name($options);
$cosClient = cos_get_client($options);
$cosClient->deleteObjects(['Bucket' => $bucket, 'Objects' => $deleteObjects]);
}
function cos_get_option($key)
{
return esc_attr(get_option($key));
}
/**
* 上传附件(包括图片的原图)
*
* @param $metadata
* @return array
*/
function cos_upload_attachments($metadata)
{
$mime_types = wp_get_mime_types();
$image_mime_types = [
$mime_types['jpg|jpeg|jpe'],
$mime_types['gif'],
$mime_types['png'],
$mime_types['bmp'],
$mime_types['tiff|tif'],
$mime_types['webp'],
$mime_types['ico'],
];
// 例如mp4等格式 上传后根据配置选择是否删除 删除后媒体库会显示默认图片 点开内容是正常的
// 图片在缩略图处理
if (!in_array($metadata['type'], $image_mime_types)) {
//生成object在COS中的存储路径
if (cos_get_option('upload_path') == '.') {
$metadata['file'] = str_replace('./', '', $metadata['file']);
}
$object = str_replace("\\", '/', $metadata['file']);
$home_path = get_home_path();
$object = str_replace($home_path, '', $object);
//在本地的存储路径
$file = $home_path . $object; //向上兼容,较早的WordPress版本上$metadata['file']存放的是相对路径
//执行上传操作
cos_file_upload('/' . $object, $file, cos_is_delete_local_file());
}
return $metadata;
}
//避免上传插件/主题时出现同步到COS的情况
if (substr_count($_SERVER['REQUEST_URI'], '/update.php') <= 0) {
add_filter('wp_handle_upload', 'cos_upload_attachments', 50);
add_filter('wp_generate_attachment_metadata', 'cos_upload_thumbs', 100);
add_filter('wp_save_image_editor_file', 'cos_save_image_editor_file', 101);
}
/**
* 上传图片的缩略图
*/
function cos_upload_thumbs($metadata)
{
if (empty($metadata['file'])) {
return $metadata;
}
//获取上传路径
$wp_uploads = wp_upload_dir();
$basedir = $wp_uploads['basedir'];
$upload_path = cos_get_option('upload_path');
$cos_options = get_option('cos_options', cos_get_default_options());
$no_local_file = esc_attr($cos_options['nolocalsaving']) == 'true';
$no_thumb = esc_attr($cos_options['nothumb']) == 'true';
// Maybe there is a problem with the old version
$file = $basedir . '/' . $metadata['file'];
if ($upload_path != '.') {
$path_array = explode($upload_path, $file);
if (count($path_array) >= 2) {
$object = '/' . $upload_path . end($path_array);
}
} else {
$object = '/' . $metadata['file'];
$file = str_replace('./', '', $file);
}
cos_file_upload($object, $file, $no_local_file);
//得到本地文件夹和远端文件夹
$dirname = dirname($metadata['file']);
$file_path = $dirname != '.' ? "{$basedir}/{$dirname}/" : "{$basedir}/";
$file_path = str_replace("\\", '/', $file_path);
if ($upload_path == '.') {
$file_path = str_replace('./', '', $file_path);
}
$object_path = str_replace(get_home_path(), '', $file_path);
if (!empty($metadata['original_image'])) {
cos_file_upload("/{$object_path}{$metadata['original_image']}", "{$file_path}{$metadata['original_image']}", $no_local_file);
}
//如果禁止上传缩略图,就不用继续执行了
if ($no_thumb) {
return $metadata;
}
//上传所有缩略图
if (!empty($metadata['sizes'])) {
//there may be duplicated filenames,so ....
foreach ($metadata['sizes'] as $val) {
//生成object在COS中的存储路径
$object = '/' . $object_path . $val['file'];
//生成本地存储路径
$file = $file_path . $val['file'];
cos_file_upload($object, $file, $no_local_file);
}
}
return $metadata;
}
/**
* @param $override
* @return mixed
*/
function cos_save_image_editor_file($override)
{
add_filter('wp_update_attachment_metadata', 'cos_image_editor_file_do');
return $override;
}
/**
* @param $metadata
* @return mixed
*/
function cos_image_editor_file_do($metadata)
{
return cos_upload_thumbs($metadata);
}
/**
* 删除远端文件,删除文件时触发
* @param $post_id
*/
function cos_delete_remote_attachment($post_id)
{
$wp_uploads = wp_upload_dir();
$basedir = $wp_uploads['basedir'];
$upload_path = str_replace(get_home_path(), '', $basedir);
// 获取图片类附件的meta信息
$meta = wp_get_attachment_metadata($post_id);
if (!empty($meta['file'])) {
$deleteObjects = [];
// meta['file']的格式为 "2020/01/wp-bg.png"
$file_path = $upload_path . '/' . $meta['file'];
$dirname = dirname($file_path) . '/';
$deleteObjects[] = $file_path;
// 超大图原图
if (!empty($meta['original_image'])) {
$deleteObjects[] = $dirname . $meta['original_image'];
}
// 删除缩略图
if (!empty($meta['sizes'])) {
foreach ($meta['sizes'] as $val) {
$deleteObjects[] = $dirname . $val['file'];
}
}
$backup_sizes = get_post_meta($post_id, '_wp_attachment_backup_sizes', true);
if (is_array($backup_sizes)) {
foreach ($backup_sizes as $size) {
$deleteObjects[] = $dirname . $size['file'];
}
}
cos_delete_cos_files($deleteObjects);
} else {
// 获取链接删除
$link = wp_get_attachment_url($post_id);
if ($link) {
$cos_options = get_option('cos_options', cos_get_default_options());
$subdirectory = !empty($cos_options['upload_subdirectory']) ? '/' . esc_attr($cos_options['upload_subdirectory']) : '';
if ($upload_path != '.') {
$file_info = explode($upload_path, $link);
if (count($file_info) >= 2) {
$file = $subdirectory . $upload_path . end($file_info);
}
} else {
$cos_upload_url = esc_attr($cos_options['upload_url_path']);
$file_info = explode($cos_upload_url, $link);
if (count($file_info) >= 2) {
$file = $subdirectory . end($file_info);
}
}
cos_delete_cos_file($file);
}
}
}
add_action('delete_attachment', 'cos_delete_remote_attachment');
// 当upload_path为根目录时,需要移除URL中出现的“绝对路径”
function cos_modefiy_img_url($url, $post_id)
{
// 移除 ./ 和 项目根路径
return str_replace(['./', get_home_path()], '', $url);
}
if (cos_get_option('upload_path') == '.') {
add_filter('wp_get_attachment_url', 'cos_modefiy_img_url', 30, 2);
}
function cos_sanitize_file_name($filename)
{
$cos_options = get_option('cos_options', cos_get_default_options());
switch ($cos_options['update_file_name']) {
case 'md5':
return md5($filename) . '.' . pathinfo($filename, PATHINFO_EXTENSION);
case 'time':
return gmdate('YmdHis', current_time('timestamp')) . wp_rand(100, 999) . '.' . pathinfo($filename, PATHINFO_EXTENSION);
default:
return $filename;
}
}
add_filter('sanitize_file_name', 'cos_sanitize_file_name', 10, 1);
/**
* @param string $homePath
* @param string $uploadPath
* @return array
*/
function cos_read_dir_queue($homePath, $uploadPath)
{
$dir = $homePath . $uploadPath;
$dirsToProcess = new SplQueue();
$dirsToProcess->enqueue([$dir, '']);
$foundFiles = [];
while (!$dirsToProcess->isEmpty()) {
[$currentDir, $relativeDir] = $dirsToProcess->dequeue();
foreach (new DirectoryIterator($currentDir) as $fileInfo) {
if ($fileInfo->isDot()) continue;
$filepath = $fileInfo->getRealPath();
// Compute the relative path of the file/directory with respect to upload path
$currentRelativeDir = "{$relativeDir}/{$fileInfo->getFilename()}";
if ($fileInfo->isDir()) {
$dirsToProcess->enqueue([$filepath, $currentRelativeDir]);
} else {
// Add file path and key to the result array
$foundFiles[] = [
'filepath' => $filepath,
'key' => '/' . $uploadPath . $currentRelativeDir
];
}
}
}
return $foundFiles;
}
// 在插件列表页添加设置按钮
function cos_plugin_action_links($links, $file)
{
if ($file == urldecode(COS_PLUGIN_PAGE)) {
$page = COS_PLUGIN_SLUG;
$links[] = "<a href='admin.php?page={$page}'>设置</a>";
}
return $links;
}
add_filter('plugin_action_links', 'cos_plugin_action_links', 10, 2);
add_filter('the_content', 'cos_setting_content_ci');
add_filter('post_thumbnail_html', 'cos_setting_post_thumbnail_ci', 10, 3);
add_filter('wp_calculate_image_srcset', 'cos_custom_image_srcset', 10, 5);
add_filter('wp_prepare_attachment_for_js', 'cos_wp_prepare_attachment_for_js');
function cos_wp_prepare_attachment_for_js($response)
{
if (empty($response['filesizeInBytes']) || empty($response['filesizeHumanReadable'])) {
$cos_options = get_option('cos_options', cos_get_default_options());
$upload_url_path = esc_attr($cos_options['upload_url_path']);
$upload_path = get_option('upload_path');
$object = str_replace($upload_url_path, $upload_path, $response['url']);
$contentLength = Head::getContentLength(cos_get_client($cos_options), cos_get_bucket_name($cos_options), $object);
if (!empty($contentLength)) {
$response['filesizeInBytes'] = $contentLength;
$response['filesizeHumanReadable'] = size_format($contentLength);
}
}
return $response;
}
function cos_custom_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id)
{
$option = get_option('cos_options', cos_get_default_options());
$style = !empty($option['ci_style']) ? esc_attr($option['ci_style']) : '';
$upload_url_path = esc_attr($option['upload_url_path']);
if (empty($style)) {
return $sources;
}
foreach ($sources as $index => $source) {
if (strpos($source['url'], $upload_url_path) !== false && strpos($source['url'], $style) === false) {
$sources[$index]['url'] .= $style;
}
}
return $sources;
}
function cos_setting_content_ci($content)
{
$option = get_option('cos_options', cos_get_default_options());
$style = esc_attr($option['ci_style']);
$upload_url_path = esc_attr($option['upload_url_path']);
if (!empty($style)) {
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $images);
if (!empty($images) && isset($images[1])) {
$images[1] = array_unique($images[1]);
foreach ($images[1] as $item) {
if (strpos($item, $upload_url_path) !== false && strpos($item, $style) === false) {
$content = str_replace($item, $item . $style, $content);
}
}
$content = str_replace($style . $style, $style, $content);
}
}
if (!empty($option['attachment_preview']) && $option['attachment_preview'] == 'on') {
preg_match_all('/<a.*?href="(.*?)".*?\/a>/is', $content, $matches);
if (!empty($matches)) {
[$tags, $links] = $matches;
$handledLinks = [];
foreach ($links as $index => $link) {
if (in_array($link, $handledLinks)) {
continue;
}
if (FilePreview::isFileExtensionSupported($link, $option['upload_url_path'])) {
$iframe = '<iframe src="' . $link . '?ci-process=doc-preview&dstType=html" width="100%" allowFullScreen="true" height="800"></iframe>';
$content = str_replace($tags[$index], $iframe, $content);
$handledLinks[] = $link;
}
}
}
}
return $content;
}
function cos_setting_post_thumbnail_ci($html, $post_id, $post_image_id)
{
$option = get_option('cos_options', cos_get_default_options());
$style = esc_attr($option['ci_style']);
$upload_url_path = esc_attr($option['upload_url_path']);
if (!empty($style) && has_post_thumbnail()) {
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $html, $images);
if (!empty($images) && isset($images[1])) {
$images[1] = array_unique($images[1]);
foreach ($images[1] as $item) {
if (strpos($item, $upload_url_path) !== false && strpos($item, $style) === false) {
$html = str_replace($item, $item . $style, $html);
}
}
$html = str_replace($style . $style, $style, $html);
}
}
return $html;
}
/**
* @param array $options
* @return array
*/
function cos_append_options($options)
{
$cos_options = get_option('cos_options', cos_get_default_options());
$options['ci_image_slim'] = $cos_options['ci_image_slim'] ?? 'off';
$options['ci_image_slim_mode'] = $cos_options['ci_image_slim_mode'] ?? '';
$options['ci_image_slim_suffix'] = $cos_options['ci_image_slim_suffix'] ?? '';
$options['attachment_preview'] = $cos_options['attachment_preview'] ?? 'off';
$options['ci_text_comments'] = $cos_options['ci_text_comments'] ?? 'off';
$options['skip_comment_validation_on_login'] = $cos_options['skip_comment_validation_on_login'] ?? 'off';
$options['ci_text_comments_strategy'] = $cos_options['ci_text_comments_strategy'] ?? '';
$options['ci_text_comments_check_roles'] = $cos_options['ci_text_comments_check_roles'] ?? '';
return $options;
}
/**
* @param array $parametersToUpdate
* @param array|null $currentParameters
* @return array
*/
function cos_update_config_parameters($parametersToUpdate, $currentOptions = null)
{
$currentOptions = $currentOptions ?: get_option('cos_options', cos_get_default_options());
$options = array_merge($currentOptions, $parametersToUpdate);
update_option('cos_options', $options);
return $options;
}
/**
* @param array $slimConfigData
* @param array $currentOptions
* @return array
*/
function cos_sync_image_slim_config($slimConfigData, $currentOptions)
{
$sanitizedConfig = [
'ci_image_slim' => sanitize_text_field($slimConfigData['Status']),
'ci_image_slim_mode' => sanitize_text_field($slimConfigData['SlimMode']),
'ci_image_slim_suffix' => implode(',', ($slimConfigData['Suffixs']['Suffix'] ?? []))
];
return cos_update_config_parameters($sanitizedConfig, $currentOptions);
}
/**
* @param string $url
* @param array|null $options
* @return string
*/
function cos_append_ci_style($url, $options = null)
{
if (empty($options)) $options = get_option('cos_options', cos_get_default_options());
if (!empty($options['ci_style']) && !empty($options['upload_url_path']) && strpos($url, esc_attr($options['upload_url_path'])) !== false) {
$url .= esc_attr($options['ci_style']);
}
return $url;
}
/**
* @param string $url
* @param array|null $options
* @return string
*/
function cos_local2remote($url, $options = null)
{
if (empty($options)) $options = get_option('cos_options', cos_get_default_options());
$upload_path = get_option('upload_path');
if ($upload_path != '.' && !empty($options['upload_url_path']) && strpos($url, $upload_path) !== false) {
return $options['upload_url_path'] . explode($upload_path, $url)[1];
}
return $url;
}
function cos_get_regional($regional)
{
$options = [
'ap-beijing-1' => ['tj', '北京一区(华北)'],
'ap-beijing' => ['bj', '北京'],
'ap-nanjing' => ['ap-nanjing', '南京'],
'ap-shanghai' => ['sh', '上海(华东)'],
'ap-guangzhou' => ['gz', '广州(华南)'],
'ap-chengdu' => ['cd', '成都(西南)'],
'ap-chongqing' => ['ap-chongqing', '重庆'],
'ap-shenzhen-fsi' => ['ap-shenzhen-fsi', '深圳金融'],
'ap-shanghai-fsi' => ['ap-shanghai-fsi', '上海金融'],
'ap-beijing-fsi' => ['ap-beijing-fsi', '北京金融'],
'ap-hongkong' => ['hk', '中国香港'],
'ap-singapore' => ['sgp', '新加坡'],
'ap-mumbai' => ['ap-mumbai', '孟买'],
'ap-jakarta' => ['ap-jakarta', '雅加达'],
'ap-seoul' => ['ap-seoul', '首尔'],
'ap-bangkok' => ['ap-bangkok', '曼谷'],
'ap-tokyo' => ['ap-tokyo', '东京'],
'na-siliconvalley' => ['na-siliconvalley', '硅谷(美西)'],
'na-ashburn' => ['na-ashburn', '弗吉尼亚(美东)'],
'na-toronto' => ['ca', '多伦多'],
'sa-saopaulo' => ['sa-saopaulo', '圣保罗'],
'eu-frankfurt' => ['ger', '法兰克福'],
'eu-moscow' => ['eu-moscow', '莫斯科'],
'accelerate' => ['accelerate', '全球加速']
];
foreach ($options as $value => $info) {
$selected = ($regional == $info[0] || $regional == $value) ? ' selected="selected"' : '';
echo '<option value="' . $value . '"' . $selected . '>' . $info[1] . '</option>';
}
}
/**
* Generate URL scheme
*
* Decides whether 'http' or 'https' should be used based on the server configuration.
*
* @param string $separator separator used between the schema and the rest of the URL.
* @return string 'http' or 'https' followed by the separator.
*/
function cos_get_url_scheme($separator = '://')
{
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
$scheme = $isHttps ? 'https' : 'http';
return $scheme . $separator;
}
function cos_sync_setting_form($cos_options)
{
$protocol = cos_get_url_scheme();
$upload_path = cos_get_option('upload_path');
$upload_path = $upload_path == '.' ? '' : $upload_path;
$old_url = "{$protocol}{$_SERVER['HTTP_HOST']}/{$upload_path}";
$new_url = $cos_options['upload_url_path'];
$nonce = wp_nonce_field('qcloud_cos_replace', 'qcloud_cos_replace-nonce', true, false);
return <<<HTML
<form method="post">
<table class="form-table">
<tr>
<th>
<legend>数据库内容替换</legend>
</th>
<td>
<input type="text" name="old_url" size="50" placeholder="请输入要替换的内容"/>
<p><b>可能会填入:<code>{$old_url}</code></b></p>
<p>例如:<code>https://qq52o.me</code></p>
</td>
</tr>
<tr>
<th>
<legend></legend>
</th>
<td>
<input type="text" name="new_url" size="50" placeholder="请输入要替换为的内容"/>
<p><b>可能会填入:<code>{$new_url}</code></b></p>
<p>例如:COS访问域名<code>https://bucket-appid.cos.ap-xxx.myqcloud.com</code>或自定义域名<code>https://resources.qq52o.me</code></p>
</td>
</tr>
<tr>
<th>
<legend></legend>
</th>
<input type="hidden" name="type" value="qcloud_cos_replace">
{$nonce}
<td>
<input type="submit" class="button button-secondary" value="开始替换"/>
<p><b>注意:如果是首次替换,请注意备份!此功能会替换文章以及设置的特色图片(题图)等使用的资源链接,也可用于其他需要替换文章内容的场景。</b></p>
</td>
</tr>
</table>
</form>
<form method="post">
<table class="form-table">
<tr>
<th>
<legend>同步历史附件</legend>
</th>
<input type="hidden" name="type" value="qcloud_cos_all">
<td>
<input type="submit" class="button button-secondary" value="开始同步"/>
<p><b>注意:如果是首次同步,执行时间将会非常长(根据你的历史附件数量),有可能会因为执行时间过长,导致页面显示超时或者报错。<br> 所以,建议附件数量过多的用户,直接使用官方的<a target="_blank" rel="nofollow" href="https://cloud.tencent.com/document/product/436/63143">COSCLI 工具</a>进行迁移,具体可参考<a target="_blank" rel="nofollow" href="https://qq52o.me/2809.html">使用 COSCLI 快速迁移本地数据到 COS</a></b></p>
</td>
</tr>
</table>
</form>
HTML;
}
/**
* @param array $content
* @return bool
*/
function cos_ci_image_slim_setting($content)
{
$cos_options = get_option('cos_options', cos_get_default_options());
if (!cos_validate_configuration($cos_options)) {
return false;
}
$slim = !empty($content['ci_image_slim']) ? sanitize_text_field($content['ci_image_slim']) : 'off';
$mode = !empty($content['ci_image_slim_mode']) ? implode(',', $content['ci_image_slim_mode']) : '';
$suffix = !empty($content['ci_image_slim_suffix']) ? implode(',', $content['ci_image_slim_suffix']) : '';
if ($slim == 'on') {
if (empty($mode)) {
echo '<div class="error"><p><strong>图片极智压缩模式不能为空!</strong></p></div>';
return false;
}
if (strpos($mode, 'Auto') !== false && empty($suffix)) {
echo '<div class="error"><p><strong>图片极智压缩使用模式包含自动时,图片格式不能为空!</strong></p></div>';
return false;
}
}
try {
$client = cos_get_client($cos_options);
$bucket = cos_get_bucket_name($cos_options);
$client = cos_replace_client_region($client, $bucket);
ImageSlim::checkStatus($client, $bucket);
if ($slim == 'on') {
ImageSlim::open($client, $bucket, $mode, $suffix);
} else {
ImageSlim::close($client, $bucket);
}
} catch (ServiceResponseException $e) {
$msg = (string)$e;
if ($e->getExceptionCode() === ErrorCode::NO_BIND_CI) {
$msg = "存储桶 {$bucket} 未绑定数据万象,若要开启极智压缩,请先 <a href='https://console.cloud.tencent.com/ci' target='_blank'>绑定数据万象服务</a >";
}
if ($e->getExceptionCode() === ErrorCode::REGION_UNSUPPORTED) {
$msg = "存储桶所在地域 {$cos_options['regional']} 暂不支持图片极智压缩";
}
echo "<div class='error'><p><strong>{$msg}</strong></p></div>";
return false;
} catch (\Throwable $e) {
$message = (string)$e;
echo "<div class='error'><p><strong>{$message}</strong></p></div>";
return false;
}