-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp-hyperdb-manager.php
More file actions
1342 lines (1170 loc) · 50.7 KB
/
wp-hyperdb-manager.php
File metadata and controls
1342 lines (1170 loc) · 50.7 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
/**
* Plugin Name: WP HyperDB Manager
* Plugin URI: https://wphyperdb.com/
* Description: 为WP Multisite提供HyperDB图形化管理界面
* Version: 1.0.0
* Author: WPHyperdb.com
* Author URI: https://wphyperdb.com
* Network: true
* Requires at least: 6.0
* Tested up to: 6.8
* Requires PHP: 8.0
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: wp-hyperdb-manager
* Domain Path: /languages
* Update URI: https://updates.wenpai.net
*/
// 防止直接访问
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// 定义插件常量
define( 'HYPERDB_MANAGER_VERSION', '1.0.0' );
define( 'HYPERDB_MANAGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'HYPERDB_MANAGER_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'HYPERDB_MANAGER_PLUGIN_FILE', __FILE__ );
require_once HYPERDB_MANAGER_PLUGIN_DIR . 'includes/class-wenpai-updater.php';
new WenPai_Updater( plugin_basename( __FILE__ ), HYPERDB_MANAGER_VERSION );
/**
* HyperDB管理器主类
*/
class HyperDB_Manager {
/**
* 单例实例
*
* @var HyperDB_Manager
*/
private static $instance = null;
/**
* 配置文件路径
*
* @var string
*/
private $config_path;
/**
* 备份文件路径
*
* @var string
*/
private $backup_path;
/**
* 获取单例实例
*
* @return HyperDB_Manager
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 构造函数
*/
private function __construct() {
$this->config_path = WP_CONTENT_DIR . '/db-config.php';
$this->backup_path = WP_CONTENT_DIR . '/db-config-backup.php';
$this->init_hooks();
}
/**
* 初始化钩子
*/
private function init_hooks() {
add_action( 'init', array( $this, 'load_textdomain' ) );
add_action( 'network_admin_menu', array( $this, 'add_network_menu' ) );
add_action( 'wp_ajax_hyperdb_test_connection', array( $this, 'ajax_test_connection' ) );
add_action( 'wp_ajax_hyperdb_save_config', array( $this, 'ajax_save_config' ) );
add_action( 'wp_ajax_hyperdb_get_stats', array( $this, 'ajax_get_stats' ) );
add_action( 'wp_ajax_hyperdb_backup_config', array( $this, 'ajax_backup_config' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
// 插件激活和停用钩子
register_activation_hook( HYPERDB_MANAGER_PLUGIN_FILE, array( $this, 'activate' ) );
register_deactivation_hook( HYPERDB_MANAGER_PLUGIN_FILE, array( $this, 'deactivate' ) );
}
/**
* 加载文本域
*/
public function load_textdomain() {
load_plugin_textdomain(
'wp-hyperdb-manager',
false,
dirname( plugin_basename( HYPERDB_MANAGER_PLUGIN_FILE ) ) . '/languages'
);
}
/**
* 插件激活
*/
public function activate() {
// 检查是否为网络管理员
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( '您没有足够的权限激活此插件。', 'wp-hyperdb-manager' ) );
}
// 检查HyperDB是否存在
if ( ! file_exists( WP_CONTENT_DIR . '/db.php' ) ) {
wp_die( esc_html__( '请先安装HyperDB。需要将HyperDB的db.php文件放置在wp-content目录下。', 'wp-hyperdb-manager' ) );
}
// 创建默认配置(如果不存在)
$this->create_default_config();
// 清理旧缓存
delete_site_transient( 'hyperdb_manager_stats' );
}
/**
* 插件停用
*/
public function deactivate() {
// 清理临时数据
delete_site_transient( 'hyperdb_manager_stats' );
}
/**
* 创建默认配置
*/
private function create_default_config() {
if ( ! file_exists( $this->config_path ) ) {
$default_config = $this->generate_default_config();
if ( ! wp_is_writable( WP_CONTENT_DIR ) ) {
error_log( 'HyperDB Manager: wp-content目录不可写,无法创建配置文件' );
return false;
}
$result = file_put_contents( $this->config_path, $default_config );
if ( false === $result ) {
error_log( 'HyperDB Manager: 无法创建配置文件 ' . $this->config_path );
return false;
}
}
return true;
}
/**
* 生成默认配置
*
* @return string
*/
private function generate_default_config() {
$config = "<?php\n";
$config .= "/**\n";
$config .= " * HyperDB Configuration\n";
$config .= " * Generated by HyperDB Manager\n";
$config .= " * " . current_time( 'Y-m-d H:i:s' ) . "\n";
$config .= " */\n\n";
$config .= "if ( ! defined( 'ABSPATH' ) ) {\n";
$config .= " exit;\n";
$config .= "}\n\n";
$config .= "global \$wpdb;\n";
$config .= "\$wpdb = new hyperdb();\n\n";
$config .= "// 主数据库配置\n";
$config .= "\$wpdb->add_database( array(\n";
$config .= " 'host' => DB_HOST,\n";
$config .= " 'user' => DB_USER,\n";
$config .= " 'password' => DB_PASSWORD,\n";
$config .= " 'name' => DB_NAME,\n";
$config .= " 'write' => 1,\n";
$config .= " 'read' => 1,\n";
$config .= " 'dataset' => 'global',\n";
$config .= " 'timeout' => 0.2,\n";
$config .= ") );\n";
return $config;
}
/**
* 添加网络管理菜单
*/
public function add_network_menu() {
add_menu_page(
__( 'HyperDB 管理器', 'wp-hyperdb-manager' ),
__( 'HyperDB', 'wp-hyperdb-manager' ),
'manage_network_options',
'wp-hyperdb-manager',
array( $this, 'render_admin_page' ),
'dashicons-database-view',
30
);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
// 权限检查
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( '您没有权限访问此页面。', 'wp-hyperdb-manager' ) );
}
$databases = $this->get_database_config();
$stats = $this->get_connection_stats();
?>
<div class="wrap">
<h1><?php esc_html_e( 'HyperDB 数据库管理', 'wp-hyperdb-manager' ); ?></h1>
<?php $this->render_notices(); ?>
<!-- 连接状态概览 -->
<div class="hyperdb-stats">
<h2><?php esc_html_e( '连接状态', 'wp-hyperdb-manager' ); ?></h2>
<div class="stats-grid">
<div class="stat-item">
<span class="stat-number"><?php echo esc_html( $stats['total_connections'] ); ?></span>
<span class="stat-label"><?php esc_html_e( '总连接数', 'wp-hyperdb-manager' ); ?></span>
</div>
<div class="stat-item">
<span class="stat-number"><?php echo esc_html( $stats['active_connections'] ); ?></span>
<span class="stat-label"><?php esc_html_e( '活跃连接', 'wp-hyperdb-manager' ); ?></span>
</div>
<div class="stat-item">
<span class="stat-number"><?php echo esc_html( $stats['read_queries'] ); ?></span>
<span class="stat-label"><?php esc_html_e( '读查询', 'wp-hyperdb-manager' ); ?></span>
</div>
<div class="stat-item">
<span class="stat-number"><?php echo esc_html( $stats['write_queries'] ); ?></span>
<span class="stat-label"><?php esc_html_e( '写查询', 'wp-hyperdb-manager' ); ?></span>
</div>
</div>
</div>
<!-- 数据库配置 -->
<div class="hyperdb-config">
<h2><?php esc_html_e( '数据库配置', 'wp-hyperdb-manager' ); ?></h2>
<form id="hyperdb-config-form">
<?php wp_nonce_field( 'hyperdb_save_config', 'hyperdb_nonce' ); ?>
<input type="hidden" name="action" value="hyperdb_save_config" />
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php esc_html_e( '主机', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '数据库名', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '用户名', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '密码', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '类型', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '状态', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '延迟 (ms)', 'wp-hyperdb-manager' ); ?></th>
<th><?php esc_html_e( '操作', 'wp-hyperdb-manager' ); ?></th>
</tr>
</thead>
<tbody id="database-rows">
<?php if ( ! empty( $databases ) ) : ?>
<?php foreach ( $databases as $key => $db ) : ?>
<tr data-db-key="<?php echo esc_attr( $key ); ?>">
<td>
<input type="text"
name="databases[<?php echo esc_attr( $key ); ?>][host]"
value="<?php echo esc_attr( $this->resolve_constant_value( $db['host'] ?? '' ) ); ?>"
class="regular-text"
required />
</td>
<td>
<input type="text"
name="databases[<?php echo esc_attr( $key ); ?>][name]"
value="<?php echo esc_attr( $this->resolve_constant_value( $db['name'] ?? '' ) ); ?>"
class="regular-text"
required />
</td>
<td>
<input type="text"
name="databases[<?php echo esc_attr( $key ); ?>][user]"
value="<?php echo esc_attr( $this->resolve_constant_value( $db['user'] ?? '' ) ); ?>"
class="regular-text"
required />
</td>
<td>
<input type="password"
name="databases[<?php echo esc_attr( $key ); ?>][password]"
value="<?php echo esc_attr( $this->resolve_constant_value( $db['password'] ?? '' ) ); ?>"
class="regular-text"
placeholder="<?php esc_attr_e( '留空保持不变', 'wp-hyperdb-manager' ); ?>" />
</td>
<td>
<select name="databases[<?php echo esc_attr( $key ); ?>][type]" required>
<option value="master" <?php selected( $db['write'] ?? 0, 1 ); ?>>
<?php esc_html_e( '主库', 'wp-hyperdb-manager' ); ?>
</option>
<option value="slave" <?php selected( $db['write'] ?? 0, 0 ); ?>>
<?php esc_html_e( '从库', 'wp-hyperdb-manager' ); ?>
</option>
</select>
</td>
<td>
<span class="connection-status" data-host="<?php echo esc_attr( $this->resolve_constant_value( $db['host'] ?? '' ) ); ?>">
<?php esc_html_e( '检测中...', 'wp-hyperdb-manager' ); ?>
</span>
</td>
<td>
<span class="connection-lag" data-host="<?php echo esc_attr( $this->resolve_constant_value( $db['host'] ?? '' ) ); ?>">
-
</span>
</td>
<td>
<button type="button"
class="button test-connection"
data-db-key="<?php echo esc_attr( $key ); ?>">
<?php esc_html_e( '测试', 'wp-hyperdb-manager' ); ?>
</button>
<button type="button"
class="button button-link-delete remove-db"
data-db-key="<?php echo esc_attr( $key ); ?>">
<?php esc_html_e( '删除', 'wp-hyperdb-manager' ); ?>
</button>
</td>
</tr>
<?php endforeach; ?>
<?php else : ?>
<tr class="no-items">
<td colspan="8">
<?php esc_html_e( '未找到数据库配置', 'wp-hyperdb-manager' ); ?>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p class="submit">
<button type="button" id="add-database" class="button">
<?php esc_html_e( '添加数据库', 'wp-hyperdb-manager' ); ?>
</button>
<button type="submit" class="button button-primary">
<?php esc_html_e( '保存配置', 'wp-hyperdb-manager' ); ?>
</button>
<button type="button" id="backup-config" class="button">
<?php esc_html_e( '备份当前配置', 'wp-hyperdb-manager' ); ?>
</button>
</p>
</form>
</div>
</div>
<?php
}
/**
* 解析常量值
*
* @param string $value 可能包含常量的值
* @return string 解析后的值
*/
private function resolve_constant_value( $value ) {
// 移除空格
$value = trim( $value );
// 如果是WordPress数据库常量,返回实际值
switch ( $value ) {
case 'DB_HOST':
return defined( 'DB_HOST' ) ? DB_HOST : 'localhost';
case 'DB_NAME':
return defined( 'DB_NAME' ) ? DB_NAME : '';
case 'DB_USER':
return defined( 'DB_USER' ) ? DB_USER : '';
case 'DB_PASSWORD':
return defined( 'DB_PASSWORD' ) ? DB_PASSWORD : '';
default:
return $value;
}
}
/**
* 渲染通知信息
*/
private function render_notices() {
// 检查HyperDB是否正常工作
global $wpdb;
if ( ! class_exists( 'hyperdb' ) ) {
?>
<div class="notice notice-error">
<p>
<?php esc_html_e( '错误:HyperDB类未找到。请确保已正确安装HyperDB。', 'wp-hyperdb-manager' ); ?>
</p>
</div>
<?php
} elseif ( ! is_a( $wpdb, 'hyperdb' ) ) {
?>
<div class="notice notice-warning">
<p>
<?php esc_html_e( '警告:HyperDB未正确加载。请检查db.php文件配置。', 'wp-hyperdb-manager' ); ?>
</p>
</div>
<?php
}
// 检查配置文件是否可写
if ( file_exists( $this->config_path ) && ! is_writable( $this->config_path ) ) {
?>
<div class="notice notice-error">
<p>
<?php
printf(
/* translators: %s: 配置文件路径 */
esc_html__( '错误:配置文件 %s 不可写。请检查文件权限。', 'wp-hyperdb-manager' ),
'<code>' . esc_html( $this->config_path ) . '</code>'
);
?>
</p>
</div>
<?php
}
// 检查wp-content目录权限
if ( ! wp_is_writable( WP_CONTENT_DIR ) ) {
?>
<div class="notice notice-warning">
<p>
<?php esc_html_e( '警告:wp-content目录不可写,可能影响配置文件的创建和备份。', 'wp-hyperdb-manager' ); ?>
</p>
</div>
<?php
}
}
/**
* 获取数据库配置
*
* @return array
*/
private function get_database_config() {
if ( ! file_exists( $this->config_path ) ) {
return array();
}
$config_content = file_get_contents( $this->config_path );
if ( false === $config_content ) {
return array();
}
return $this->parse_config_content( $config_content );
}
/**
* 解析配置文件内容
*
* @param string $content 配置文件内容
* @return array
*/
private function parse_config_content( $content ) {
$databases = array();
// 改进的正则表达式,处理多行和嵌套结构
$pattern = '/\$wpdb->add_database\s*\(\s*array\s*\(((?:[^()]|(?R))*)\)\s*\)\s*;/s';
preg_match_all( $pattern, $content, $matches );
foreach ( $matches[1] as $index => $match ) {
$db_config = $this->parse_array_string( $match );
if ( ! empty( $db_config ) ) {
$databases[ 'db_' . $index ] = $db_config;
}
}
return $databases;
}
/**
* 解析数组字符串(改进版)
*
* @param string $array_string 数组字符串
* @return array
*/
private function parse_array_string( $array_string ) {
$config = array();
// 移除注释和多余空白
$array_string = preg_replace( '/\/\/.*$/m', '', $array_string );
$array_string = preg_replace( '/\/\*.*?\*\//s', '', $array_string );
// 按行分割并处理每一项
$lines = preg_split( '/[,\n]/', $array_string );
foreach ( $lines as $line ) {
$line = trim( $line );
if ( empty( $line ) ) {
continue;
}
// 寻找键值对
if ( strpos( $line, '=>' ) !== false ) {
$parts = explode( '=>', $line, 2 );
if ( count( $parts ) === 2 ) {
$key = trim( $parts[0], " '\"\t" );
$value = trim( $parts[1], " '\"\t," );
// 处理不同类型的值
if ( $value === '1' || $value === 'true' ) {
$value = 1;
} elseif ( $value === '0' || $value === 'false' ) {
$value = 0;
} elseif ( is_numeric( $value ) ) {
$value = is_float( $value + 0 ) ? (float) $value : (int) $value;
}
$config[ $key ] = $value;
}
}
}
return $config;
}
/**
* 获取连接统计信息
*
* @return array
*/
private function get_connection_stats() {
// 检查缓存
$cached_stats = get_site_transient( 'hyperdb_manager_stats' );
if ( false !== $cached_stats && is_array( $cached_stats ) ) {
return $cached_stats;
}
global $wpdb;
$stats = array(
'total_connections' => 0,
'active_connections' => 0,
'read_queries' => 0,
'write_queries' => 0,
);
if ( class_exists( 'hyperdb' ) && is_a( $wpdb, 'hyperdb' ) ) {
// 获取连接数
if ( isset( $wpdb->dbhs ) && is_array( $wpdb->dbhs ) ) {
$stats['total_connections'] = count( $wpdb->dbhs );
$stats['active_connections'] = $this->count_active_connections();
}
// 获取查询数
if ( isset( $wpdb->num_queries ) ) {
$stats['read_queries'] = (int) $wpdb->num_queries;
}
// 尝试获取写查询数(如果HyperDB有相关统计)
if ( method_exists( $wpdb, 'get_write_queries' ) ) {
$stats['write_queries'] = (int) $wpdb->get_write_queries();
}
}
// 缓存30秒
set_site_transient( 'hyperdb_manager_stats', $stats, 30 );
return $stats;
}
/**
* 计算活跃连接数
*
* @return int
*/
private function count_active_connections() {
global $wpdb;
if ( ! class_exists( 'hyperdb' ) || ! is_a( $wpdb, 'hyperdb' ) || ! isset( $wpdb->dbhs ) || ! is_array( $wpdb->dbhs ) ) {
return 0;
}
$active = 0;
foreach ( $wpdb->dbhs as $dbh ) {
if ( $dbh instanceof mysqli && mysqli_ping( $dbh ) ) {
$active++;
} elseif ( is_resource( $dbh ) ) {
// 对于旧版本的MySQL资源
$active++;
}
}
return $active;
}
/**
* AJAX测试连接
*/
public function ajax_test_connection() {
// 验证nonce
if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'hyperdb_test_connection' ) ) {
wp_send_json_error( array( 'message' => __( 'Nonce验证失败', 'wp-hyperdb-manager' ) ) );
}
// 权限检查
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_send_json_error( array( 'message' => __( '权限不足', 'wp-hyperdb-manager' ) ) );
}
$host = sanitize_text_field( $_POST['host'] ?? '' );
$user = sanitize_text_field( $_POST['user'] ?? '' );
$password = $_POST['password'] ?? ''; // 密码不使用sanitize_text_field以保持特殊字符
$name = sanitize_text_field( $_POST['name'] ?? '' );
// 验证必填字段
if ( empty( $host ) || empty( $user ) || empty( $name ) ) {
wp_send_json_error( array( 'message' => __( '主机、用户名和数据库名不能为空', 'wp-hyperdb-manager' ) ) );
}
$result = $this->test_database_connection( $host, $user, $password, $name );
if ( is_wp_error( $result ) ) {
wp_send_json_error( array(
'message' => $result->get_error_message(),
'status' => 'offline'
) );
}
wp_send_json_success( array(
'status' => 'online',
'lag' => $result['lag'] ?? 0,
'version' => $result['version'] ?? '',
'message' => __( '连接成功', 'wp-hyperdb-manager' )
) );
}
/**
* 测试数据库连接
*
* @param string $host 主机
* @param string $user 用户名
* @param string $password 密码
* @param string $name 数据库名
* @return array|WP_Error
*/
private function test_database_connection( $host, $user, $password, $name ) {
// 设置连接超时
$old_timeout = ini_get( 'default_socket_timeout' );
ini_set( 'default_socket_timeout', 10 );
// 使用mysqli测试连接
$connection = @mysqli_connect( $host, $user, $password, $name );
// 恢复超时设置
ini_set( 'default_socket_timeout', $old_timeout );
if ( ! $connection ) {
return new WP_Error( 'connection_failed', sprintf(
/* translators: %s: MySQL错误信息 */
__( '连接失败: %s', 'wp-hyperdb-manager' ),
mysqli_connect_error()
) );
}
// 获取服务器信息
$version = mysqli_get_server_info( $connection );
// 测试复制延迟
$lag = $this->measure_replication_lag( $connection );
mysqli_close( $connection );
return array(
'lag' => $lag,
'version' => $version
);
}
/**
* 测量复制延迟
*
* @param mysqli $connection 数据库连接
* @return int
*/
private function measure_replication_lag( $connection ) {
$result = mysqli_query( $connection, "SHOW SLAVE STATUS" );
if ( $result && $row = mysqli_fetch_assoc( $result ) ) {
return isset( $row['Seconds_Behind_Master'] ) && null !== $row['Seconds_Behind_Master']
? (int) $row['Seconds_Behind_Master']
: 0;
}
return 0;
}
/**
* AJAX保存配置
*/
public function ajax_save_config() {
// 验证nonce
if ( ! wp_verify_nonce( $_POST['hyperdb_nonce'] ?? '', 'hyperdb_save_config' ) ) {
wp_send_json_error( array( 'message' => __( 'Nonce验证失败', 'wp-hyperdb-manager' ) ) );
}
// 权限检查
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_send_json_error( array( 'message' => __( '权限不足', 'wp-hyperdb-manager' ) ) );
}
$databases = $_POST['databases'] ?? array();
// 验证配置
$validation_result = $this->validate_database_config( $databases );
if ( is_wp_error( $validation_result ) ) {
wp_send_json_error( array( 'message' => $validation_result->get_error_message() ) );
}
// 备份当前配置
if ( file_exists( $this->config_path ) ) {
if ( ! copy( $this->config_path, $this->backup_path ) ) {
wp_send_json_error( array(
'message' => __( '无法创建配置备份,保存已取消', 'wp-hyperdb-manager' )
) );
}
}
// 生成新配置
$config_content = $this->generate_config_file_content( $databases );
// 保存配置
$result = file_put_contents( $this->config_path, $config_content );
if ( false === $result ) {
// 尝试恢复备份
if ( file_exists( $this->backup_path ) ) {
copy( $this->backup_path, $this->config_path );
}
wp_send_json_error( array( 'message' => __( '配置文件写入失败', 'wp-hyperdb-manager' ) ) );
}
// 清理缓存
delete_site_transient( 'hyperdb_manager_stats' );
wp_send_json_success( array( 'message' => __( '配置保存成功', 'wp-hyperdb-manager' ) ) );
}
/**
* AJAX备份配置
*/
public function ajax_backup_config() {
// 验证nonce - 使用通用nonce
if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'hyperdb_test_connection' ) ) {
wp_send_json_error( array( 'message' => __( 'Nonce验证失败', 'wp-hyperdb-manager' ) ) );
}
// 权限检查
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_send_json_error( array( 'message' => __( '权限不足', 'wp-hyperdb-manager' ) ) );
}
if ( ! file_exists( $this->config_path ) ) {
wp_send_json_error( array( 'message' => __( '配置文件不存在', 'wp-hyperdb-manager' ) ) );
}
$backup_name = 'db-config-backup-' . date( 'Y-m-d-H-i-s' ) . '.php';
$backup_path = WP_CONTENT_DIR . '/' . $backup_name;
if ( copy( $this->config_path, $backup_path ) ) {
wp_send_json_success( array(
'message' => sprintf(
/* translators: %s: 备份文件名 */
__( '配置备份成功:%s', 'wp-hyperdb-manager' ),
$backup_name
)
) );
} else {
wp_send_json_error( array( 'message' => __( '备份失败', 'wp-hyperdb-manager' ) ) );
}
}
/**
* 验证数据库配置
*
* @param array $databases 数据库配置数组
* @return true|WP_Error
*/
private function validate_database_config( $databases ) {
if ( empty( $databases ) || ! is_array( $databases ) ) {
return new WP_Error( 'empty_config', __( '数据库配置不能为空', 'wp-hyperdb-manager' ) );
}
$has_master = false;
foreach ( $databases as $key => $db ) {
if ( ! is_array( $db ) ) {
continue;
}
// 验证必填字段
if ( empty( $db['host'] ) || empty( $db['user'] ) || empty( $db['name'] ) ) {
return new WP_Error( 'missing_fields', sprintf(
/* translators: %s: 数据库键名 */
__( '数据库 %s 缺少必填字段', 'wp-hyperdb-manager' ),
esc_html( $key )
) );
}
// 检查是否有主数据库
if ( 'master' === ( $db['type'] ?? '' ) ) {
$has_master = true;
}
// 验证主机格式(基础验证)
$host = $db['host'];
if ( ! preg_match( '/^[a-zA-Z0-9\.\-_:]+$/', $host ) ) {
return new WP_Error( 'invalid_host', sprintf(
/* translators: %s: 主机名 */
__( '无效的主机名格式: %s', 'wp-hyperdb-manager' ),
esc_html( $host )
) );
}
}
if ( ! $has_master ) {
return new WP_Error( 'no_master', __( '至少需要一个主数据库', 'wp-hyperdb-manager' ) );
}
return true;
}
/**
* 生成配置文件内容
*
* @param array $databases 数据库配置
* @return string
*/
private function generate_config_file_content( $databases ) {
$config = "<?php\n";
$config .= "/**\n";
$config .= " * HyperDB Configuration\n";
$config .= " * Generated by HyperDB Manager\n";
$config .= " * " . current_time( 'Y-m-d H:i:s' ) . "\n";
$config .= " */\n\n";
$config .= "if ( ! defined( 'ABSPATH' ) ) {\n";
$config .= " exit;\n";
$config .= "}\n\n";
$config .= "global \$wpdb;\n";
$config .= "\$wpdb = new hyperdb();\n\n";
foreach ( $databases as $key => $db ) {
if ( ! is_array( $db ) ) {
continue;
}
$config .= "// " . esc_html( $db['host'] ?? 'Unknown' ) . " - " . esc_html( $db['type'] ?? 'slave' ) . "\n";
$config .= "\$wpdb->add_database( array(\n";
$config .= " 'host' => '" . $this->escape_config_value( $db['host'] ?? '' ) . "',\n";
$config .= " 'user' => '" . $this->escape_config_value( $db['user'] ?? '' ) . "',\n";
$config .= " 'password' => '" . $this->escape_config_value( $db['password'] ?? '' ) . "',\n";
$config .= " 'name' => '" . $this->escape_config_value( $db['name'] ?? '' ) . "',\n";
$config .= " 'write' => " . ( 'master' === ( $db['type'] ?? '' ) ? '1' : '0' ) . ",\n";
$config .= " 'read' => 1,\n";
$config .= " 'dataset' => 'global',\n";
$config .= " 'timeout' => 0.2,\n";
$config .= ") );\n\n";
}
return $config;
}
/**
* 转义配置值
*
* @param string $value 要转义的值
* @return string 转义后的值
*/
private function escape_config_value( $value ) {
return str_replace( array( '\\', "'" ), array( '\\\\', "\\'" ), $value );
}
/**
* AJAX获取统计信息
*/
public function ajax_get_stats() {
// 验证nonce
if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'hyperdb_get_stats' ) ) {
wp_send_json_error( array( 'message' => __( 'Nonce验证失败', 'wp-hyperdb-manager' ) ) );
}
// 权限检查
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_send_json_error( array( 'message' => __( '权限不足', 'wp-hyperdb-manager' ) ) );
}
$stats = $this->get_connection_stats();
wp_send_json_success( $stats );
}
/**
* 加载管理脚本
*
* @param string $hook 页面钩子
*/
public function enqueue_admin_scripts( $hook ) {
// 只在HyperDB管理页面加载
if ( 'toplevel_page_hyperdb-manager-network' !== $hook ) {
return;
}
// 内联JavaScript和CSS
$this->enqueue_inline_scripts();
$this->enqueue_inline_styles();
}
/**
* 加载内联脚本
*/
private function enqueue_inline_scripts() {
$js_code = $this->get_admin_javascript();
wp_add_inline_script( 'jquery', $js_code );
// 本地化脚本
wp_localize_script( 'jquery', 'hyperdbManager', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonces' => array(
'test_connection' => wp_create_nonce( 'hyperdb_test_connection' ),
'get_stats' => wp_create_nonce( 'hyperdb_get_stats' ),
),
'i18n' => array(
'confirmDelete' => __( '确定要删除这个数据库配置吗?', 'wp-hyperdb-manager' ),
'testing' => __( '检测中...', 'wp-hyperdb-manager' ),
'online' => __( '在线', 'wp-hyperdb-manager' ),
'offline' => __( '离线', 'wp-hyperdb-manager' ),
'error' => __( '错误', 'wp-hyperdb-manager' ),
'saving' => __( '保存中...', 'wp-hyperdb-manager' ),
'saveConfig' => __( '保存配置', 'wp-hyperdb-manager' ),
'test' => __( '测试', 'wp-hyperdb-manager' ),
'delete' => __( '删除', 'wp-hyperdb-manager' ),
'masterDb' => __( '主库', 'wp-hyperdb-manager' ),
'slaveDb' => __( '从库', 'wp-hyperdb-manager' ),
'passwordPlaceholder' => __( '留空保持不变', 'wp-hyperdb-manager' ),
)
) );
}
/**
* 获取管理页面JavaScript代码
*
* @return string
*/
private function get_admin_javascript() {
ob_start();
?>
(function($) {
'use strict';
var HyperDBManager = {
init: function() {
this.bindEvents();
this.checkAllConnections();
this.initStatsRefresh();
},
bindEvents: function() {
$(document)
.on('click', '#add-database', this.addDatabaseRow)
.on('click', '.remove-db', this.removeDatabaseRow)
.on('click', '.test-connection', this.testConnection)
.on('submit', '#hyperdb-config-form', this.saveConfiguration)
.on('click', '#backup-config', this.backupConfiguration);
},
checkAllConnections: function() {
$('.connection-status').each(function() {
var $status = $(this);
var $row = $status.closest('tr');
var dbKey = $row.data('db-key');
if (dbKey) {
HyperDBManager.testConnectionStatus(dbKey, $status);
}
});
},
testConnectionStatus: function(dbKey, $statusElement) {
var $row = $('[data-db-key="' + dbKey + '"]');
if ($row.length === 0) {
return;
}
var data = {
action: 'hyperdb_test_connection',
nonce: hyperdbManager.nonces.test_connection,
host: $row.find('input[name*="[host]"]').val() || '',
user: $row.find('input[name*="[user]"]').val() || '',
password: $row.find('input[name*="[password]"]').val() || '',
name: $row.find('input[name*="[name]"]').val() || ''