-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
3003 lines (2629 loc) · 103 KB
/
functions.php
File metadata and controls
3003 lines (2629 loc) · 103 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('ABSPATH')) {
exit;
}
// ====== CDN 配置常量 ======
// 可在 wp-config.php 中使用 define() 覆盖这些值
if (!defined('LARED_CDN_FONTAWESOME')) {
define('LARED_CDN_FONTAWESOME', 'https://static.utterlog.com/libs/fontawesome/7.2.0/css/all.min.css');
}
if (!defined('LARED_CDN_STATIC')) {
define('LARED_CDN_STATIC', 'https://jsd.bluecdn.com/npm');
}
// =========================
// 内容与展示模块
require_once get_template_directory() . '/inc/inc-image.php';
require_once get_template_directory() . '/inc/inc-hero.php';
require_once get_template_directory() . '/inc/inc-comments.php';
// 数据与扩展模块
require_once get_template_directory() . '/inc/inc-rss.php';
require_once get_template_directory() . '/inc/inc-memos.php';
require_once get_template_directory() . '/inc/inc-ai-summary.php';
require_once get_template_directory() . '/inc/inc-email.php';
// 后台设置模块
require_once get_template_directory() . '/inc/inc-theme-settings.php';
/* ===========================================
Inlined from inc/inc-editor.php
TinyMCE 编辑器「排版指南」按钮与样式
=========================================== */
// 注册 TinyMCE 外部插件
function lared_mce_external_plugins(array $plugins): array
{
$url = get_template_directory_uri() . '/assets/js/editor-admin.min.js';
$plugins['laredThemeGuide'] = $url;
return $plugins;
}
add_filter('mce_external_plugins', 'lared_mce_external_plugins');
// 将按钮添加到工具栏
function lared_mce_buttons(array $buttons): array
{
$buttons[] = 'lared_theme_guide';
return $buttons;
}
add_filter('mce_buttons', 'lared_mce_buttons');
// 编辑页面注入排版指南模态窗 CSS
function lared_editor_theme_guide_css(): void
{
$screen = get_current_screen();
if (!$screen || !in_array($screen->base, ['post', 'page'], true)) {
return;
}
echo '<style id="lared-guide-modal-css">
/* ===== 主题排版指南模态窗 ===== */
.lared-guide-backdrop {
position: fixed; inset: 0; z-index: 100100;
display: flex; align-items: center; justify-content: center;
background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
opacity: 0; transition: opacity .2s ease;
}
.lared-guide-backdrop.is-visible { opacity: 1; }
.lared-guide-modal {
position: relative; width: 92%; max-width: 720px; max-height: 85vh;
display: flex; flex-direction: column;
background: #fff; border: 1px solid #d9d9d9;
box-shadow: 0 8px 32px rgba(0,0,0,.15);
transform: translateY(12px) scale(.97); transition: transform .2s ease;
}
.lared-guide-backdrop.is-visible .lared-guide-modal { transform: translateY(0) scale(1); }
.lared-guide-header {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 20px; border-bottom: 1px solid #e5e5e5;
}
.lared-guide-header-left { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.lared-guide-title { font-size: 15px; font-weight: 600; color: #1d2327; }
.lared-guide-mode {
display: inline-flex; align-items: center; font-size: 11px; padding: 2px 8px;
border-radius: 3px; font-weight: 500;
}
.lared-guide-mode.is-text { background: #ecfdf5; color: #059669; }
.lared-guide-mode.is-visual { background: #eff6ff; color: #2563eb; }
.lared-guide-close {
width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center;
border: none; background: transparent; font-size: 22px; color: #999; cursor: pointer;
border-radius: 0; padding: 0; line-height: 1; flex-shrink: 0;
}
.lared-guide-close:hover { color: #333; }
.lared-guide-notice {
padding: 8px 20px; background: #fffbeb; border-bottom: 1px solid #e5e5e5;
font-size: 12px; color: #92400e; line-height: 1.5;
}
.lared-guide-tabs {
display: flex; gap: 0; border-bottom: 1px solid #e5e5e5; overflow-x: auto;
}
.lared-guide-tab {
padding: 10px 18px; font-size: 13px; font-weight: 500; color: #666;
background: transparent; border: none; border-bottom: 2px solid transparent;
cursor: pointer; transition: color .15s, border-color .15s; white-space: nowrap;
}
.lared-guide-tab:hover { color: #333; }
.lared-guide-tab.is-active { color: #1d2327; border-bottom-color: #f53004; }
.lared-guide-body { flex: 1; overflow-y: auto; padding: 16px 20px; }
.lared-guide-card {
margin-bottom: 16px; border: 1px solid #e8e8e8; background: #fafafa;
}
.lared-guide-card-header {
display: flex; align-items: center; justify-content: space-between;
padding: 10px 14px; background: #fff; border-bottom: 1px solid #e8e8e8;
}
.lared-guide-card-title { font-size: 14px; font-weight: 600; color: #1d2327; }
.lared-guide-card-actions { display: flex; gap: 6px; }
.lared-guide-copy-btn,
.lared-guide-insert-btn {
display: inline-flex; align-items: center; justify-content: center;
height: 28px; padding: 0 12px; font-size: 12px; font-weight: 500;
border: 1px solid #d9d9d9; cursor: pointer; transition: all .15s;
background: #fff; color: #555; border-radius: 0;
}
.lared-guide-copy-btn:hover { background: #f5f5f5; border-color: #bbb; }
.lared-guide-insert-btn {
background: #f53004; color: #fff; border-color: #f53004;
}
.lared-guide-insert-btn:hover { background: #d42a03; border-color: #d42a03; }
.lared-guide-card-desc {
margin: 0; padding: 8px 14px 4px; font-size: 12px; color: #888; line-height: 1.5;
}
.lared-guide-code {
margin: 0; padding: 10px 14px; background: #282a36; color: #f8f8f2;
font-size: 12px; line-height: 1.6; overflow-x: auto; white-space: pre-wrap;
word-break: break-all; max-height: 200px;
}
.lared-guide-code code {
font-family: "SFMono-Regular",Consolas,"Liberation Mono",Menlo,monospace;
color: inherit; background: none; padding: 0; font-size: inherit;
}
@media (max-width: 600px) {
.lared-guide-modal { max-width: 100%; max-height: 100vh; }
}
</style>';
}
add_action('admin_head', 'lared_editor_theme_guide_css');
// 编辑页面加载排版指南脚本
function lared_editor_enqueue_guide_script(): void
{
$screen = get_current_screen();
if (!$screen || !in_array($screen->base, ['post', 'page'], true)) {
return;
}
wp_enqueue_script(
'lared-editor-admin',
get_template_directory_uri() . '/assets/js/editor-admin.min.js',
[],
wp_get_theme()->get('Version'),
true
);
}
add_action('admin_enqueue_scripts', 'lared_editor_enqueue_guide_script');
// 主题设置页面加载媒体上传器 + 后台样式
function lared_admin_enqueue_media(string $hook): void
{
if ('appearance_page_lared-theme-settings' !== $hook) {
return;
}
wp_enqueue_media();
wp_enqueue_style(
'lared-admin',
get_template_directory_uri() . '/assets/css/lared-admin.min.css',
[],
wp_get_theme()->get('Version')
);
}
add_action('admin_enqueue_scripts', 'lared_admin_enqueue_media');
function lared_setup(): void
{
add_theme_support('title-tag');
add_theme_support('post-thumbnails');
add_theme_support('html5', ['search-form', 'gallery', 'caption', 'style', 'script']);
add_theme_support('custom-logo');
register_nav_menus([
'primary' => __('Primary Menu', 'lared'),
'hero_sidebar' => __('Hero 侧边栏', 'lared'),
]);
}
add_action('after_setup_theme', 'lared_setup');
/**
* 禁用 XML-RPC 和 Pingback,防止 wp-cron 中
* preg_match() 收到 array 参数导致 Fatal Error。
*/
add_filter('xmlrpc_enabled', '__return_false');
add_filter('pre_option_default_pingback_flag', '__return_zero');
add_action('init', function () {
remove_action('do_pings', 'do_all_pingbacks', 10);
remove_action('do_pings', 'do_all_trackbacks', 10);
});
/**
* 主题激活时自动创建缓存目录并设置写入权限。
* 目录:data(Memos / 表情 缓存)、data/rss(RSS 缓存)
*/
function lared_activate_create_cache_dirs(): void
{
$dirs = [
get_template_directory() . '/data',
get_template_directory() . '/data/rss',
];
foreach ($dirs as $dir) {
if (!is_dir($dir)) {
wp_mkdir_p($dir);
}
// 确保 Web 服务器可写(0755 权限)
if (is_dir($dir) && !wp_is_writable($dir)) {
chmod($dir, 0755);
}
}
}
add_action('after_switch_theme', 'lared_activate_create_cache_dirs');
/**
* 主题激活后显示引导通知,提示用户前往数据维护初始化数据
*/
function lared_activate_setup_notice(): void
{
set_transient('lared_activation_notice', true, 60 * 5);
}
add_action('after_switch_theme', 'lared_activate_setup_notice');
function lared_show_activation_notice(): void
{
if (!get_transient('lared_activation_notice')) {
return;
}
$data_tab_url = add_query_arg(
['page' => 'lared-theme-settings', 'tab' => 'data'],
admin_url('themes.php')
);
echo '<div class="notice notice-info is-dismissible" style="border-left-color:#f53004;">'
. '<p><strong>Lared 主题已激活!</strong> 请前往 '
. '<a href="' . esc_url($data_tab_url) . '"><strong>主题设置 → 数据维护</strong></a>'
. ' 执行以下操作以确保主题正常运行:</p>'
. '<ol style="margin:4px 0 8px 20px;">'
. '<li><strong>评论等级缓存</strong> — 点击「扫描」→「重建缓存」</li>'
. '<li><strong>评论 Meta 合并迁移</strong> — 如从旧版升级,点击「扫描」→「执行迁移」</li>'
. '<li><strong>文章字数统计</strong> — 点击「扫描」→「更新」</li>'
. '</ol></div>';
delete_transient('lared_activation_notice');
}
add_action('admin_notices', 'lared_show_activation_notice');
function lared_primary_menu_fallback(): void
{
echo '<ul class="nav"><li><a href="' . esc_url(home_url('/')) . '">' . esc_html__('首页', 'lared') . '</a></li></ul>';
}
/**
* 全局强制 Gravatar 请求尺寸为 128px,以便在高分屏下保持高清。
* 实际显示大小仍由 CSS / HTML 属性控制。
*/
function lared_force_avatar_hd(array $args): array
{
$args['size'] = 128;
return $args;
}
add_filter('pre_get_avatar_data', 'lared_force_avatar_hd');
/**
* 将 Gravatar 默认域名替换为 gravatar.bluecdn.com 加速镜像。
* 同时覆盖 get_avatar() 和 get_avatar_url() 输出。
*/
function lared_gravatar_cdn(string $url): string
{
return str_replace(
['www.gravatar.com', 'secure.gravatar.com', '0.gravatar.com', '1.gravatar.com', '2.gravatar.com'],
'gravatar.bluecdn.com',
$url
);
}
add_filter('get_avatar_url', 'lared_gravatar_cdn', 10, 1);
// ====== 热力图文件缓存 — uploads/lared-cache/heatmap/ ======
/**
* 热力图缓存目录
*/
function lared_get_heatmap_cache_dir(): string
{
$upload_dir = wp_upload_dir();
return $upload_dir['basedir'] . '/lared-cache/heatmap';
}
/**
* 热力图缓存文件路径
*/
function lared_get_heatmap_cache_file(): string
{
return lared_get_heatmap_cache_dir() . '/heatmap-data.json';
}
/**
* 读取热力图缓存(60 天文章+说说计数)
*
* @return array|false 缓存数据数组,不存在或已过期返回 false
*/
function lared_get_heatmap_cache(): array|false
{
$cache_file = lared_get_heatmap_cache_file();
if (!file_exists($cache_file)) {
return false;
}
$content = file_get_contents($cache_file);
if (!is_string($content) || '' === $content) {
return false;
}
$data = json_decode($content, true);
if (!is_array($data) || empty($data['cells'])) {
return false;
}
// 1 小时过期检查
$cached_at = (int) ($data['cached_at'] ?? 0);
if ((time() - $cached_at) > HOUR_IN_SECONDS) {
return false;
}
return $data['cells'];
}
/**
* 生成并保存热力图缓存
*
* @return array 热力图单元格数组
*/
function lared_build_heatmap_cache(): array
{
$days_total = 60;
$day_counts = [];
$post_ids = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'date_query' => [
[
'after' => ($days_total - 1) . ' days ago',
'inclusive' => true,
],
],
]);
foreach ($post_ids as $pid) {
$day_key = get_the_date('Y-m-d', (int) $pid);
if ('' === $day_key) {
continue;
}
$day_counts[$day_key] = ($day_counts[$day_key] ?? 0) + 1;
}
// Memos 说说数据
$memo_counts = [];
if (function_exists('lared_get_memos_json_cache')) {
$today_date = wp_date('Y-m-d');
$start_ts = strtotime($today_date . ' -' . ($days_total - 1) . ' days');
$memos = lared_get_memos_json_cache();
if (!empty($memos['items']) && is_array($memos['items'])) {
foreach ($memos['items'] as $memo) {
$memo_ts = (int) ($memo['created_timestamp'] ?? 0);
if ($memo_ts <= 0 || $memo_ts < $start_ts) {
continue;
}
$memo_day = wp_date('Y-m-d', $memo_ts);
if ('' === $memo_day) {
continue;
}
$memo_counts[$memo_day] = ($memo_counts[$memo_day] ?? 0) + 1;
}
}
}
// 合并计数,计算热力等级
$combined = [];
$all_days = array_unique(array_merge(array_keys($day_counts), array_keys($memo_counts)));
foreach ($all_days as $day) {
$combined[$day] = ($day_counts[$day] ?? 0) + ($memo_counts[$day] ?? 0);
}
$max_count = !empty($combined) ? max($combined) : 0;
$cells = [];
$today_ts = strtotime(wp_date('Y-m-d') . ' 12:00:00');
for ($i = $days_total - 1; $i >= 0; $i--) {
$cell_ts = $today_ts - ($i * DAY_IN_SECONDS);
$cell_date = wp_date('Y-m-d', $cell_ts);
$cell_post_count = (int) ($day_counts[$cell_date] ?? 0);
$cell_memo_count = (int) ($memo_counts[$cell_date] ?? 0);
$cell_total = $cell_post_count + $cell_memo_count;
$cell_level = 0;
if ($cell_total > 0 && $max_count > 0) {
$cell_level = (int) ceil(($cell_total / $max_count) * 5);
$cell_level = max(1, min(5, $cell_level));
}
$cells[] = [
'date' => $cell_date,
'count' => $cell_total,
'post_count' => $cell_post_count,
'memo_count' => $cell_memo_count,
'level' => $cell_level,
];
}
// 保存到文件
$cache_dir = lared_get_heatmap_cache_dir();
if (!is_dir($cache_dir)) {
wp_mkdir_p($cache_dir);
}
$payload = wp_json_encode([
'cells' => $cells,
'cached_at' => time(),
], JSON_UNESCAPED_UNICODE);
@file_put_contents(lared_get_heatmap_cache_file(), $payload);
return $cells;
}
/**
* 清除热力图缓存文件
*/
function lared_clear_heatmap_cache(): void
{
$file = lared_get_heatmap_cache_file();
if (file_exists($file)) {
@unlink($file);
}
}
// ====== Gravatar 本地缓存 — 减少外部请求 ======
/**
* 检查是否禁用了所有本地缓存(后台「缓存管理」开关)
*/
function lared_is_cache_disabled(): bool
{
return '1' === (string) get_option('lared_disable_cache', '0');
}
/**
* 获取 Gravatar 缓存目录路径(uploads/lared-cache/gravatar/)
*/
function lared_get_gravatar_cache_dir(): string
{
$upload_dir = wp_upload_dir();
return $upload_dir['basedir'] . '/lared-cache/gravatar';
}
/**
* 获取 Gravatar 缓存 URL 前缀
*/
function lared_get_gravatar_cache_url(): string
{
$upload_dir = wp_upload_dir();
return $upload_dir['baseurl'] . '/lared-cache/gravatar';
}
/**
* 将 Gravatar URL 替换为本地缓存副本。
* 如果本地缓存不存在或已过期(7 天),则从 CDN 下载。
* 下载失败时回退到原始 CDN URL。
*
* @param string $url Gravatar URL(已经过 lared_gravatar_cdn 替换为 bluecdn)
* @return string 本地缓存 URL 或原始 URL(回退)
*/
function lared_cache_gravatar(string $url): string
{
// 缓存全局关闭:直接返回 (已经过 lared_gravatar_cdn 替换为 bluecdn) URL
if (lared_is_cache_disabled()) {
return $url;
}
// 仅处理 Gravatar URL
if (false === strpos($url, 'gravatar') && false === strpos($url, '/avatar/')) {
return $url;
}
// 从 URL 提取 hash 和参数
$parsed = wp_parse_url($url);
if (empty($parsed['path'])) {
return $url;
}
// 路径格式: /avatar/HASH
if (!preg_match('#/avatar/([a-f0-9]{32,64})#i', $parsed['path'], $matches)) {
return $url;
}
$hash = strtolower($matches[1]);
// 解析查询参数获取 size
$query_params = [];
if (!empty($parsed['query'])) {
parse_str($parsed['query'], $query_params);
}
$size = isset($query_params['s']) ? (int) $query_params['s'] : 128;
// 缓存文件路径
$cache_dir = lared_get_gravatar_cache_dir();
$cache_file = $cache_dir . '/' . $hash . '_' . $size . '.jpg';
$cache_url = lared_get_gravatar_cache_url() . '/' . $hash . '_' . $size . '.jpg';
// 检查缓存是否存在且未过期(30 天)
if (file_exists($cache_file) && (time() - filemtime($cache_file)) < 30 * DAY_IN_SECONDS) {
return $cache_url;
}
// 确保缓存目录存在
if (!is_dir($cache_dir)) {
wp_mkdir_p($cache_dir);
}
// 从 CDN 下载
$response = wp_remote_get($url, [
'timeout' => 5,
'sslverify' => false,
]);
if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
// 下载失败:如果旧缓存存在则续用,否则回退 CDN
return file_exists($cache_file) ? $cache_url : $url;
}
$body = wp_remote_retrieve_body($response);
if (empty($body)) {
return file_exists($cache_file) ? $cache_url : $url;
}
// 写入缓存文件
file_put_contents($cache_file, $body, LOCK_EX);
return $cache_url;
}
add_filter('get_avatar_url', 'lared_cache_gravatar', 20, 1);
/**
* 定期清理过期的 Gravatar 缓存文件(超过 30 天)
*/
function lared_cleanup_gravatar_cache(): void
{
$cache_dir = lared_get_gravatar_cache_dir();
if (!is_dir($cache_dir)) {
return;
}
$files = glob($cache_dir . '/*.jpg');
if (empty($files)) {
return;
}
$expire = time() - 60 * DAY_IN_SECONDS;
foreach ($files as $file) {
if (filemtime($file) < $expire) {
@unlink($file);
}
}
}
add_action('wp_scheduled_delete', 'lared_cleanup_gravatar_cache');
// ====== 友链图标本地缓存 — uploads/lared-cache/links-ico/ ======
/**
* 获取友链图标缓存目录
*/
function lared_get_link_ico_cache_dir(): string
{
$upload_dir = wp_upload_dir();
return $upload_dir['basedir'] . '/lared-cache/links-ico';
}
function lared_get_link_ico_cache_url(): string
{
$upload_dir = wp_upload_dir();
return $upload_dir['baseurl'] . '/lared-cache/links-ico';
}
/**
* 获取友链图标(带本地缓存)
*
* 尝试从站点直接获取 favicon,成功则缓存到本地并返回本地 URL。
* 失败或获取到的是文字占位图则返回空字符串(由模板显示字母 fallback)。
*
* @param string $host 域名(如 example.com)
* @return string 本地缓存 URL 或空字符串
*/
function lared_get_cached_link_icon(string $host): string
{
if ('' === $host) {
return '';
}
// 缓存全局关闭:直接返回 favicon.im 远端 URL
if (lared_is_cache_disabled()) {
return 'https://favicon.im/' . urlencode($host) . '?larger=true';
}
$safe_name = preg_replace('/[^a-z0-9.\-]/i', '_', $host);
$cache_dir = lared_get_link_ico_cache_dir();
$cache_file = $cache_dir . '/' . $safe_name . '.ico';
$miss_file = $cache_dir . '/' . $safe_name . '.miss';
$cache_url = lared_get_link_ico_cache_url() . '/' . $safe_name . '.ico';
// 已缓存的成功图标(30 天有效)
if (file_exists($cache_file) && (time() - filemtime($cache_file)) < 30 * DAY_IN_SECONDS) {
return $cache_url;
}
// 已标记为失败(30 天内不重试)
if (file_exists($miss_file) && (time() - filemtime($miss_file)) < 30 * DAY_IN_SECONDS) {
return '';
}
// 确保目录存在
if (!is_dir($cache_dir)) {
wp_mkdir_p($cache_dir);
}
// 从 favicon.im 获取(larger=true 拿大尺寸版本)
$ico_url = 'https://favicon.im/' . urlencode($host) . '?larger=true';
$response = wp_remote_get($ico_url, [
'timeout' => 5,
'sslverify' => false,
]);
if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
@file_put_contents($miss_file, '', LOCK_EX);
return '';
}
$body = wp_remote_retrieve_body($response);
$content_type = wp_remote_retrieve_header($response, 'content-type');
// favicon.im 对无 favicon 的站点返回 image/svg+xml 占位 (~257 bytes)
$is_placeholder = false;
if (false !== stripos($content_type, 'svg')) {
$is_placeholder = true;
}
if (strlen($body) < 500) {
$is_placeholder = true;
}
if ($is_placeholder || empty($body)) {
@file_put_contents($miss_file, '', LOCK_EX);
return '';
}
// 写入缓存
file_put_contents($cache_file, $body, LOCK_EX);
// 清除旧的 miss 标记
if (file_exists($miss_file)) {
@unlink($miss_file);
}
return $cache_url;
}
/**
* 定期清理过期的友链图标缓存
*/
function lared_cleanup_link_ico_cache(): void
{
$cache_dir = lared_get_link_ico_cache_dir();
if (!is_dir($cache_dir)) {
return;
}
$expire = time() - 90 * DAY_IN_SECONDS;
foreach (glob($cache_dir . '/*') as $file) {
if (is_file($file) && filemtime($file) < $expire) {
@unlink($file);
}
}
}
add_action('wp_scheduled_delete', 'lared_cleanup_link_ico_cache');
/**
* 始终输出英文日期(不受 WordPress 语言设置影响)
* 使用站点时区,格式字符同 PHP date()
*/
function lared_date_en(string $format, int $utc_timestamp): string
{
return (new DateTimeImmutable('@' . $utc_timestamp))
->setTimezone(wp_timezone())
->format($format);
}
function lared_minify_css_contents(string $css): string
{
$banner = '';
$offset = 0;
while (preg_match('/\A\s*\/\*.*?\*\//s', substr($css, $offset), $match)) {
$banner .= trim($match[0]) . "\n";
$offset += strpos(substr($css, $offset), $match[0]) + strlen($match[0]);
}
$body = substr($css, $offset);
$body = preg_replace('/\/\*[^!].*?\*\//s', '', $body) ?? $body;
$body = preg_replace('/\s+/', ' ', $body) ?? $body;
$body = preg_replace('/\s*([{};,>])\s*/', '$1', $body) ?? $body;
$body = str_replace(';}', '}', trim($body));
return trim($banner) !== '' ? trim($banner) . "\n" . $body . "\n" : $body . "\n";
}
function lared_refresh_min_css_if_needed(): void
{
$main_css_path = get_template_directory() . '/assets/css/lared-main.css';
$main_min_css_path = get_template_directory() . '/assets/css/lared-main.min.css';
if (! file_exists($main_css_path)) {
return;
}
$source_mtime = (int) filemtime($main_css_path);
$target_mtime = file_exists($main_min_css_path) ? (int) filemtime($main_min_css_path) : 0;
if ($target_mtime >= $source_mtime) {
return;
}
$css = file_get_contents($main_css_path);
if (! is_string($css) || $css === '') {
return;
}
$minified = lared_minify_css_contents($css);
@file_put_contents($main_min_css_path, $minified);
}
function lared_after_switch_theme_refresh_assets(): void
{
lared_refresh_min_css_if_needed();
}
add_action('after_switch_theme', 'lared_after_switch_theme_refresh_assets');
function lared_after_theme_update_refresh_assets($upgrader, array $options): void
{
if (($options['action'] ?? '') !== 'update' || ($options['type'] ?? '') !== 'theme') {
return;
}
$themes = $options['themes'] ?? [];
if (is_array($themes) && in_array(get_template(), $themes, true)) {
lared_refresh_min_css_if_needed();
}
}
add_action('upgrader_process_complete', 'lared_after_theme_update_refresh_assets', 10, 2);
// ====== Preconnect 资源提示 — 加速 CDN 域名连接 ======
function lared_resource_hints(array $urls, string $relation_type): array
{
if ('preconnect' === $relation_type) {
$urls[] = ['href' => 'https://icons.bluecdn.com', 'crossorigin' => true];
$urls[] = ['href' => 'https://static.bluecdn.com', 'crossorigin' => true];
$urls[] = ['href' => 'https://flagcdn.io', 'crossorigin' => true];
}
return $urls;
}
add_filter('wp_resource_hints', 'lared_resource_hints', 10, 2);
function lared_assets(): void
{
// CDN 配置(默认从常量,可在 wp-config.php 覆盖)
$cdn_icons = LARED_CDN_FONTAWESOME;
$cdn_static = LARED_CDN_STATIC;
lared_refresh_min_css_if_needed();
$style_rel_path = '/assets/css/lared-main.min.css';
$style_abs_path = get_template_directory() . $style_rel_path;
if (! file_exists($style_abs_path)) {
$style_rel_path = '/assets/css/lared-main.css';
$style_abs_path = get_template_directory() . $style_rel_path;
}
// Plyr — 仅在文章页或有音乐播放器配置时加载(提前判断,用于主题样式依赖)
$need_plyr = is_single() || ('' !== trim((string) get_option('lared_music_playlist', '')));
// 主题样式(默认优先 lared-main.min.css,不存在时回退 lared-main.css)
wp_enqueue_style(
'lared-style',
get_template_directory_uri() . $style_rel_path,
$need_plyr ? ['lared-plyr'] : [],
(string) filemtime($style_abs_path)
);
// Font Awesome Pro
wp_enqueue_style(
'lared-fontawesome',
$cdn_icons,
[],
null
);
// Google Fonts 已移除 — 全部使用系统字体
// Font Awesome Sharp 变体(补充 all.min.css 缺失的 sharp 字体定义)
// 兼容 all.css 和 all.min.css 两种 base URL
$fa_dir = dirname($cdn_icons);
foreach (['sharp-thin', 'sharp-light', 'sharp-solid'] as $sharp_variant) {
wp_enqueue_style(
'lared-fa-' . $sharp_variant,
$fa_dir . '/' . $sharp_variant . '.min.css',
['lared-fontawesome'],
null
);
}
// Flag Icons CSS — 仅在首页/文章页/页面加载(用于访客来源国旗和评论区 UA 检测)
if (is_front_page() || is_single() || is_page()) {
wp_enqueue_style(
'lared-flag-icons',
'https://flagcdn.io/css/flag-icons.min.css',
[],
null
);
}
// Plyr CSS + JS($need_plyr 已在上方判断)
if ($need_plyr) {
wp_enqueue_style(
'lared-plyr',
$cdn_static . '/plyr@3.7.8/dist/plyr.css',
[],
'3.7.8'
);
wp_enqueue_script(
'lared-plyr',
$cdn_static . '/plyr@3.7.8/dist/plyr.min.js',
[],
'3.7.8',
true
);
}
// PrismJS — 仅在文章页加载(代码高亮)
if (is_single()) {
wp_enqueue_style(
'lared-prism-theme',
$cdn_static . '/prism-themes@1.9.0/themes/prism-dracula.min.css',
[],
'1.9.0'
);
wp_enqueue_style(
'lared-prism-line-numbers',
$cdn_static . '/prismjs@1.29.0/plugins/line-numbers/prism-line-numbers.min.css',
['lared-prism-theme'],
'1.29.0'
);
wp_enqueue_script(
'lared-prism-core',
$cdn_static . '/prismjs@1.29.0/components/prism-core.min.js',
[],
'1.29.0',
true
);
wp_enqueue_script(
'lared-prism-autoloader',
$cdn_static . '/prismjs@1.29.0/plugins/autoloader/prism-autoloader.js',
['lared-prism-core'],
'1.29.0',
true
);
wp_enqueue_script(
'lared-prism-line-numbers',
$cdn_static . '/prismjs@1.29.0/plugins/line-numbers/prism-line-numbers.min.js',
['lared-prism-core'],
'1.29.0',
true
);
}
// Theme JS — merged bundle: lazysizes + Pjax + ViewImage + Theme main
// min 文件存在即优先使用,确保生产环境始终加载压缩版。
$js_min_file = get_template_directory() . '/assets/js/lared-app.min.js';
$js_file = file_exists($js_min_file)
? '/assets/js/lared-app.min.js'
: '/assets/js/lared-app.js';
$theme_deps = [];
if ($need_plyr) {
$theme_deps[] = 'lared-plyr';
}
if (is_single()) {
$theme_deps[] = 'lared-prism-autoloader';
$theme_deps[] = 'lared-prism-line-numbers';
}
wp_enqueue_script(
'lared-theme',
get_template_directory_uri() . $js_file,
$theme_deps,
(string) filemtime(get_template_directory() . $js_file),
['strategy' => 'defer', 'in_footer' => false] // <head> + defer:不阻塞渲染,lazysizes 仍尽早初始化
);
// WordPress 内置回复脚本(moveForm)— 因使用 PJAX,需始终加载,
// 否则从非 singular 页面导航到文章页时 window.addComment 不存在
wp_enqueue_script('comment-reply');
}
add_action('wp_enqueue_scripts', 'lared_assets');
// ====================================================================
// 主题配色方案 — 根据后台选项输出 inline CSS 覆盖 :root 变量
// ====================================================================
/**
* 返回所有配色方案的定义
*/
function lared_get_color_schemes(): array
{
return [
'red' => [
'accent' => '#f53004',
'hover' => '#d42a03',
'accent-rgb' => '245,48,4',
'heat-1' => '#fdd9d2',
'heat-2' => '#fbb0a2',
'heat-3' => '#f98470',
'heat-4' => '#f75a3a',
'heat-5' => '#f53004',
],
'blue' => [
'accent' => '#2563eb',
'hover' => '#1d4ed8',
'accent-rgb' => '37,99,235',
'heat-1' => '#dbeafe',
'heat-2' => '#93c5fd',
'heat-3' => '#3b82f6',
'heat-4' => '#2563eb',
'heat-5' => '#1d4ed8',
],
'green' => [
'accent' => '#16a34a',
'hover' => '#15803d',
'accent-rgb' => '22,163,74',
'heat-1' => '#dcfce7',
'heat-2' => '#86efac',
'heat-3' => '#4ade80',
'heat-4' => '#22c55e',
'heat-5' => '#16a34a',
],
'pink' => [
'accent' => '#e8437f',
'hover' => '#d6336c',
'accent-rgb' => '232,67,127',
'heat-1' => '#fce7f3',
'heat-2' => '#f9a8d4',
'heat-3' => '#f472b6',
'heat-4' => '#ec4899',
'heat-5' => '#e8437f',
],
'black' => [
'accent' => '#2d2d2d',
'hover' => '#1a1a1a',
'accent-rgb' => '45,45,45',
'heat-1' => '#e5e5e5',
'heat-2' => '#bfbfbf',
'heat-3' => '#8c8c8c',
'heat-4' => '#595959',
'heat-5' => '#2d2d2d',
],
];
}
/**
* 输出主题配色 inline CSS — 附加到 lared-style 之后,确保层叠顺序正确覆盖 :root 变量
*/
function lared_output_color_scheme_css(): void
{
$scheme_key = (string) get_option('lared_color_scheme', 'red');
$schemes = lared_get_color_schemes();
// 默认红色不需要额外输出(已在 CSS 文件中定义)
if ('red' === $scheme_key || !isset($schemes[$scheme_key])) {
return;
}
$s = $schemes[$scheme_key];
$css = ":root {";