better-staridc-MNBT
1<?php
2/**
3 * 定时任务:每日到期维护 + 状态/用量同步。
4 *
5 * @package MnbtWp
6 */
7
8namespace MnbtWp\Services;
9
10use MnbtWp\Helpers;
11
12if ( ! defined( 'ABSPATH' ) ) {
13 exit;
14}
15
16/**
17 * 定时任务调度。
18 */
19class Cron {
20
21 /**
22 * 注册定时任务回调。
23 */
24 public static function init() {
25 add_action( 'mnbtwp_daily_maintenance', array( __CLASS__, 'daily' ) );
26 add_action( 'mnbtwp_sync_hosts', array( __CLASS__, 'sync' ) );
27 }
28
29 /**
30 * 每日到期维护。
31 */
32 public static function daily() {
33 Billing::expire_maintenance();
34 }
35
36 /**
37 * 同步主机状态与用量(ztcx),带锁防并发。
38 */
39 public static function sync() {
40 if ( get_transient( 'mnbtwp_sync_lock' ) ) {
41 return;
42 }
43 set_transient( 'mnbtwp_sync_lock', 1, 10 * MINUTE_IN_SECONDS );
44
45 global $wpdb;
46 $hosts = $wpdb->get_results(
47 "SELECT * FROM {$wpdb->prefix}mnbt_hosts WHERE status IN ('active','suspended','expired')",
48 ARRAY_A
49 );
50
51 foreach ( $hosts as $host ) {
52 $provider = Helpers::get_provider( $host['provider_id'] );
53 if ( ! $provider ) {
54 continue;
55 }
56 try {
57 $result = Helpers::client_for_provider( $provider )->getHostStatus( $host['username'] );
58 $data = isset( $result['data'] ) && is_array( $result['data'] ) ? $result['data'] : array();
59
60 $quota = Helpers::parse_quota( $host['quota_json'] );
61 if ( isset( $data['quota'] ) && is_array( $data['quota'] ) ) {
62 $q = $data['quota'];
63 $quota['web']['max'] = (int) ( $q['web_size_max'] ?? $quota['web']['max'] );
64 $quota['web']['used'] = (int) ( $q['web_size_used'] ?? $quota['web']['used'] );
65 $quota['sql']['max'] = (int) ( $q['sql_size_max'] ?? $quota['sql']['max'] );
66 $quota['sql']['used'] = (int) ( $q['sql_size_used'] ?? $quota['sql']['used'] );
67 $quota['flow']['max'] = (int) ( $q['flow_max'] ?? $quota['flow']['max'] );
68 $quota['flow']['used'] = (int) ( $q['flow_used'] ?? $quota['flow']['used'] );
69 }
70
71 $site_domain = isset( $data['user']['domain'] ) ? (string) $data['user']['domain'] : '';
72
73 $wpdb->update(
74 $wpdb->prefix . 'mnbt_hosts',
75 array(
76 'site_domain' => $site_domain ? $site_domain : $host['site_domain'],
77 'quota_json' => wp_json_encode( $quota ),
78 'updated_at' => current_time( 'mysql' ),
79 ),
80 array( 'id' => (int) $host['id'] )
81 );
82 } catch ( \Exception $e ) {
83 // 单台同步失败不影响其他主机。
84 continue;
85 }
86 }
87
88 delete_transient( 'mnbtwp_sync_lock' );
89 }
90}