init(); } return self::$instance; } private function __construct() {} // ─── Activation ─────────────────────────────────────────────────────────── // phpcs:disable WordPress.Security.NonceVerification.Recommended -- WordPress core sets activate-multi itself on bulk activation; this only reads it and changes nothing. public static function activate( $network_wide = false ): void { // Not built for a multisite network: it keeps one set of tables and settings per // install, and a network-wide activation would leave every other site half-set-up // with the failover and sync hooks live. Activating per site is fine. if ( is_multisite() && $network_wide ) { deactivate_plugins( WARDPAIR_BASENAME, true, true ); wp_die( esc_html__( 'Wardpair cannot be network-activated. Activate it on the individual site that you want to protect.', 'wardpair' ), esc_html__( 'Wardpair', 'wardpair' ), array( 'back_link' => true ) ); } // Only record the schema as current when every table really exists. If the database user // cannot CREATE TABLE, Sentinel_Migrate keeps retrying (and shows a notice) instead of // believing a half-built install is finished. if ( self::create_tables() ) { Sentinel_Migrate::mark_current(); } Sentinel_Backup::create_backup_dir(); flush_rewrite_rules(); // Ask the next admin page load to start the guided tour (see // Sentinel_Admin::maybe_start_tour). Not for bulk activations. if ( ! isset( $_GET['activate-multi'] ) ) { set_transient( 'wardpair_welcome_redirect', 1, 5 * MINUTE_IN_SECONDS ); } } // phpcs:enable WordPress.Security.NonceVerification.Recommended public static function deactivate(): void { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( 'wardpair_monitor_cycle', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_push_bootstrap', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_scheduled_backup', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_clone_start', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_clone_check_backup', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_clone_transfer_chunk', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_clone_restore', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_sync_options_diff', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_sync_upload_diff', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_push_option', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_push_attachment_file', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_zip_restore_commit', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_verify_scan_page', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_verify_repair_batch', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_journal_flush', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_lane_tick', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_switch_back_run', array(), 'wardpair' ); as_unschedule_all_actions( 'wardpair_finish_switchback', array(), 'wardpair' ); } wp_clear_scheduled_hook( 'wardpair_fence_tick' ); flush_rewrite_rules(); } // ─── DB Tables ──────────────────────────────────────────────────────────── /** * Create or bring up to date every table the plugin owns. * * The statements are plain "CREATE TABLE", not "CREATE TABLE IF NOT EXISTS": * dbDelta() reads the table name from the text after "CREATE TABLE", so with * IF NOT EXISTS it read the word "IF", never compared the real table with * the definition, and a column or index added in a later release never * reached an existing install. Without it, dbDelta adds what is missing and * leaves existing rows alone. Sentinel_Migrate runs this once per update. * * dbDelta() reports nothing when the database user lacks CREATE or ALTER rights, so after * running it this checks that every table is really there. * * @return bool True when every table exists afterwards; false when one is missing. */ public static function create_tables(): bool { global $wpdb; $charset = $wpdb->get_charset_collate(); require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_events ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, event_type VARCHAR(50) NOT NULL, triggered_at DATETIME NOT NULL, resolved_at DATETIME NULL, notes TEXT NULL, partner VARCHAR(32) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY idx_partner (partner) ) $charset;" ); dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_pings ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, tcp_status TINYINT(1) NOT NULL DEFAULT 0, app_status TINYINT(1) NOT NULL DEFAULT 0, dns_status TINYINT(1) NOT NULL DEFAULT 0, response_time_ms INT NOT NULL DEFAULT 0, reason VARCHAR(160) NOT NULL DEFAULT '', created_at DATETIME NOT NULL, PRIMARY KEY (id) ) $charset;" ); dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_backups ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, filename VARCHAR(255) NOT NULL, size_bytes BIGINT NOT NULL DEFAULT 0, type VARCHAR(20) NOT NULL DEFAULT 'manual', notes VARCHAR(255) NULL, created_at DATETIME NOT NULL, PRIMARY KEY (id) ) $charset;" ); dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_sync_log ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, direction VARCHAR(10) NOT NULL DEFAULT 'push', type VARCHAR(30) NOT NULL, status VARCHAR(10) NOT NULL DEFAULT 'ok', detail VARCHAR(255) NOT NULL DEFAULT '', error VARCHAR(255) NOT NULL DEFAULT '', created_at DATETIME NOT NULL, partner VARCHAR(32) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY idx_partner (partner), KEY idx_direction (direction), KEY idx_status (status), KEY idx_created (created_at) ) $charset;" ); dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_activity_logs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, type VARCHAR(20) NOT NULL DEFAULT 'backup', scope VARCHAR(20) NOT NULL DEFAULT 'db', filename VARCHAR(255) NOT NULL DEFAULT '', status VARCHAR(20) NOT NULL DEFAULT 'pending', step VARCHAR(50) NOT NULL DEFAULT '', progress_pct TINYINT NOT NULL DEFAULT 0, message VARCHAR(255) NOT NULL DEFAULT '', job_key VARCHAR(100) NOT NULL DEFAULT '', started_at DATETIME NOT NULL, completed_at DATETIME NULL, PRIMARY KEY (id), KEY idx_status (status), KEY idx_job_key (job_key) ) $charset;" ); // A durable, append-only record of "this site's content was last // known to be synced as of THIS point" — a real history, kept on // both primary and secondary, instead of a single boolean option // that a disconnect/reconnect or any other bookkeeping slip can // silently reset out from under the actual content. Each row is a // commit in the git sense: a hash of what the tables looked like at // that moment, plus a pointer to the commit it followed. dbDelta( "CREATE TABLE {$wpdb->prefix}wardpair_commits ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, commit_hash VARCHAR(40) NOT NULL, parent_hash VARCHAR(40) NOT NULL DEFAULT '', side VARCHAR(10) NOT NULL, commit_type VARCHAR(20) NOT NULL, status VARCHAR(10) NOT NULL DEFAULT 'complete', partner_url VARCHAR(255) NOT NULL DEFAULT '', table_count INT NOT NULL DEFAULT 0, total_rows BIGINT NOT NULL DEFAULT 0, summary TEXT NULL, notes VARCHAR(255) NOT NULL DEFAULT '', created_at DATETIME NOT NULL, PRIMARY KEY (id), KEY idx_hash (commit_hash), KEY idx_created (created_at) ) $charset;" ); $missing = array(); foreach ( array( 'events', 'pings', 'backups', 'sync_log', 'activity_logs', 'commits' ) as $short ) { $table = $wpdb->prefix . 'wardpair_' . $short; if ( $table !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ) { $missing[] = $table; } } if ( ! empty( $missing ) ) { update_option( 'wardpair_db_missing_tables', array_values( $missing ), false ); return false; } delete_option( 'wardpair_db_missing_tables' ); update_option( 'wardpair_db_version', WARDPAIR_VERSION ); return true; } // ─── Init ───────────────────────────────────────────────────────────────── private function init(): void { Sentinel_Migrate::register(); Sentinel_Support::register(); add_action( 'admin_init', array( $this, 'check_as_available' ) ); add_action( 'admin_notices', array( $this, 'maybe_show_waf_block_notice' ) ); add_action( 'admin_notices', array( $this, 'maybe_show_origin_cert_notice' ) ); add_action( 'admin_post_wardpair_retrust_origin', array( $this, 'handle_retrust_origin' ) ); // (Sentinel_Migrate now owns schema changes between releases; the // checks below stay as a second line of defence.) // create_tables() uses dbDelta(), so it's safe to re-run — existing tables and their rows are left // alone. Dropping the plugin's files onto a site and letting // WordPress pick them up (the normal update path for a // non-wp.org plugin) never fires the activation hook, so a new // table added in an update would otherwise only appear after an // explicit deactivate/reactivate. // Checks for the table directly rather than comparing version // strings — this plugin isn't published, so there's no reliable // "did the version change" signal (files just get dropped in // place), and a missed version bump would silently skip this. // A SHOW TABLES lookup is cheap and self-correcting either way. // // Once confirmed current, that fact is cached in an option so // healthy sites skip the SHOW COLUMNS check on every load forever // after. A site where it's NOT current (e.g. a DB user without // ALTER privileges — dbDelta() then can't add the column, no // matter how many times it's retried) is rate-limited to one // retry + one admin notice per day instead of hammering the // query — and the retry itself, on failure, has no other effect: // Sentinel_Ledger's read/write paths degrade gracefully without // that column, so the site keeps working either way. // The notice feed works in the free version too. (Plain email alerts are sent directly by // the backup, clone and pairing code; the multi-channel router is a paid feature.) Sentinel_Notices::register(); Sentinel_Pairing::register_hooks(); // Repairs plugin settings that an older clone restore saved as plain text (one time per site). add_action( 'admin_init', array( 'Sentinel_Utils', 'heal_flattened_options' ) ); // Everything in init_premium__premium_only() needs a valid licence or trial: the write fence, // change journal, sync lanes, failover, Cloudflare and their scheduled work. // Backup runs on all sites regardless of pairing. Sentinel_Backup::get_instance(); if ( is_admin() ) { Sentinel_Admin::get_instance(); } // Register all ajax communication actions. $this->register_ajax_actions(); // Register clone hooks for both roles Sentinel_Clone_Sync::register_hooks(); Sentinel_Cron::register_hooks(); $role = get_option( 'wardpair_role', '' ); if ( 'primary' === $role ) { Sentinel_Sync::get_instance(); } elseif ( 'secondary' === $role ) { Sentinel_SEO::get_instance(); // Sentinel_Sync's own register_hooks() has a 'secondary' branch // (it registers wardpair_pull_files, which is how the secondary // fetches large files from the primary), but the instance was only // ever constructed on the primary — so that branch never ran and // every queued pull silently did nothing. Sentinel_Sync::get_instance(); } if ( 'primary' === $role && get_option( 'wardpair_is_paired', false ) ) { add_action( 'init', array( 'Sentinel_Clone_Sync', 'release_stuck_claims' ) ); } } // ─── Ajax Action Registration ───────────────────────────────────────────── /** * Register all admin-ajax.php actions. * * wp_ajax_nopriv_ makes actions available to unauthenticated requests. * Security is enforced inside each handler via HMAC verification — not * by WordPress's authentication layer. This is intentional and mirrors * the approach used by every major backup/migration plugin. * * The pairing action uses a static name (wardpair_pair) because the * shared secret doesn't exist yet. It is protected by the 64-char * cryptographic pairing token and strict rate limiting. * * All post-pairing actions use dynamic names derived from the endpoint * slug (an 8-char hex value generated at pairing time). The names are * not enumerable without knowing the slug. */ private function register_ajax_actions(): void { // ── Pairing (static action, token-protected, rate-limited) ──────────── add_action( 'wp_ajax_nopriv_wardpair_pair', array( 'Sentinel_Pairing', 'handle_pair_request' ) ); add_action( 'wp_ajax_wardpair_pair', array( 'Sentinel_Pairing', 'handle_pair_request' ) ); // Read-only restore progress that still works after a restore has ended the admin's login. add_action( 'wp_ajax_nopriv_wardpair_restore_status', array( 'Sentinel_Activity_Logger', 'handle_public_status' ) ); add_action( 'wp_ajax_wardpair_restore_status', array( 'Sentinel_Activity_Logger', 'handle_public_status' ) ); // Retry for a failed disconnect notification. Registered // unconditionally (not gated on pairing status below) since by the // time a retry fires, this site's own pairing state — including the // slug — has already been wiped by disconnect(). add_action( 'wardpair_retry_disconnect_notify', array( 'Sentinel_Pairing', 'retry_disconnect_notify' ), 10, 6 ); // Retry for a failed clone-complete acknowledgement to primary. add_action( 'wardpair_retry_clone_complete_ack', array( 'Sentinel_Clone_Secondary', 'notify_primary_clone_complete' ), 10, 1 ); // ── Post-pairing dynamic actions ────────────────────────────────────── $slug = get_option( 'wardpair_endpoint_slug', '' ); $role = get_option( 'wardpair_role', '' ); if ( empty( $slug ) ) { return; // Not yet paired — no dynamic actions to register. } // Certificate-key challenge: lets the partner confirm a changed server key without a click // (Sentinel_Transport::origin_request). Both roles answer it. add_action( 'wp_ajax_nopriv_swp_' . $slug . '_pin', array( 'Sentinel_Transport', 'handle_pin_challenge' ) ); add_action( 'wp_ajax_swp_' . $slug . '_pin', array( 'Sentinel_Transport', 'handle_pin_challenge' ) ); // Serves a file to a partner that pulls it (large files are fetched, not pushed). Both roles // answer: during a failover the secondary is the sender and the original primary does the pulling. add_action( 'wp_ajax_nopriv_swp_' . $slug . '_mf', array( 'Sentinel_Sync', 'handle_media_file_request' ) ); add_action( 'wp_ajax_swp_' . $slug . '_mf', array( 'Sentinel_Sync', 'handle_media_file_request' ) ); if ( 'primary' === $role ) { // This is missing — pair_ack hits this action on the PRIMARY add_action( 'wp_ajax_nopriv_swp_' . $slug . '_sync', array( 'Sentinel_Sync', 'handle_incoming_payload' ) ); add_action( 'wp_ajax_swp_' . $slug . '_sync', array( 'Sentinel_Sync', 'handle_incoming_payload' ) ); } if ( 'secondary' === $role ) { add_action( 'wp_ajax_nopriv_swp_' . $slug . '_sync', array( 'Sentinel_Sync', 'handle_incoming_payload' ) ); add_action( 'wp_ajax_swp_' . $slug . '_sync', array( 'Sentinel_Sync', 'handle_incoming_payload' ) ); // Binary chunk endpoint (raw encrypted body, no base64/JSON wrapping). add_action( 'wp_ajax_nopriv_swp_' . $slug . '_bin', array( 'Sentinel_Transport', 'handle_binary' ) ); add_action( 'wp_ajax_swp_' . $slug . '_bin', array( 'Sentinel_Transport', 'handle_binary' ) ); // Note: the actual file-pull flow runs internally via // as_enqueue_async_action( 'wardpair_pull_files', ... ), which is // handled by Sentinel_Sync::register_hooks() — no public AJAX endpoint // is needed for it. } } // ─── Helpers ────────────────────────────────────────────────────────────── /** * Shareable server notices that Core shows, as data for Sentinel_Notices. Local rendering is * unchanged (those notices have dismiss links and a form); this only feeds the other site. * Each block mirrors the condition of the maybe_show_*() notice it is named after. * * @return array */ public static function notice_items(): array { $items = array(); $waf = get_option( 'wardpair_waf_block_detected', false ); if ( $waf && ! empty( $waf['time'] ) && (int) get_option( 'wardpair_waf_block_dismissed_at', 0 ) < (int) $waf['time'] ) { $items[] = array( 'id' => 'waf_block', 'severity' => 'warning', 'title' => __( 'Transfer blocked by the hosting firewall', 'wardpair' ), 'paras' => array( __( 'The last transfer attempt got a generic server-level block, almost always a hosting firewall or security module. Add this IP address to its allow list:', 'wardpair' ), __( 'Then re-run the clone.', 'wardpair' ), ), 'code' => ! empty( $waf['our_ip'] ) ? (string) $waf['our_ip'] : '', ); } $bad = get_option( Sentinel_Transport::PIN_BAD_OPTION ); if ( is_array( $bad ) ) { $items[] = array( 'id' => 'origin_cert_changed', 'severity' => 'warning', 'title' => __( 'Its server certificate changed', 'wardpair' ), 'paras' => array( sprintf( /* translators: 1: host name, 2: IP address */ __( 'The server for %1$s (%2$s) now presents a different certificate key than the one Wardpair recorded. Direct connections to it are paused and the normal domain route is used, so syncing keeps working. If the certificate was renewed or replaced, trust the new one in Wardpair on that site.', 'wardpair' ), (string) ( $bad['host'] ?? '' ), (string) ( $bad['ip'] ?? '' ) ) ), ); } // Pending database update, and server requirements / version mismatch. $items = array_merge( $items, Sentinel_Migrate::notice_items(), Sentinel_Compat::notice_items() ); return $items; } public function check_as_available(): void { if ( ! class_exists( 'ActionScheduler' ) && ! function_exists( 'as_enqueue_async_action' ) ) { add_action( 'admin_notices', function () { echo '

' . esc_html__( 'Wardpair requires Action Scheduler. Install WooCommerce or place the standalone Action Scheduler in vendor/action-scheduler/.', 'wardpair' ) . '

'; } ); } } /** * Records that a transfer request looked like it was blocked by the * *host's* firewall/WAF (a generic server-level block page) rather than * failing at the application level. Called from * Sentinel_Clone_Primary::send_to_secondary(). */ public static function flag_waf_block( string $target_ip, int $http_code, string $body_preview ): void { update_option( 'wardpair_waf_block_detected', array( 'time' => time(), 'http_code' => $http_code, 'preview' => $body_preview, 'our_ip' => $target_ip, ), false ); } /** Called on the next successful transfer — the block notice no longer applies. */ public static function clear_waf_block(): void { if ( get_option( 'wardpair_waf_block_detected', false ) ) { delete_option( 'wardpair_waf_block_detected' ); } } /** * Shows a plain-language admin notice — with the exact IP to allowlist — * when transfers are being blocked at the host/WAF level rather than * failing for an application reason. This is the difference between a * user staring at "HTTP 403" in a log and knowing exactly what to paste * into their host's firewall settings. */ public function maybe_show_waf_block_notice(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } $info = get_option( 'wardpair_waf_block_detected', false ); if ( ! $info || empty( $info['time'] ) ) { return; } $dismissed_at = (int) get_option( 'wardpair_waf_block_dismissed_at', 0 ); if ( $dismissed_at >= $info['time'] ) { return; } if ( isset( $_GET['wardpair_dismiss_waf_notice'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['wardpair_dismiss_waf_notice'] ) ), 'wardpair_dismiss_waf' ) ) { update_option( 'wardpair_waf_block_dismissed_at', time(), false ); return; } $ip = ! empty( $info['our_ip'] ) ? $info['our_ip'] : __( '(could not detect — see logs)', 'wardpair' ); $dismiss_url = wp_nonce_url( add_query_arg( 'wardpair_dismiss_waf_notice', '1' ), 'wardpair_dismiss_waf', 'wardpair_dismiss_waf_notice' ); echo '

' . esc_html__( 'Wardpair: transfer blocked by your hosting firewall', 'wardpair' ) . '

' . esc_html__( "The last transfer attempt got a generic server-level block (not a WordPress error) — this is almost always a hosting firewall or security module (ModSecurity, Imunify360, Sucuri, Cloudflare, etc.), not a problem with Wardpair itself.", 'wardpair' ) . '

' . esc_html__( 'In your hosting control panel, look for a firewall/security tool (often called ModSecurity, Imunify360, or similar) and add this IP address to its allow list:', 'wardpair' ) . '

' . esc_html( $ip ) . '

' . esc_html__( 'Once added, re-run the clone — no changes needed on this end.', 'wardpair' ) . '

' . esc_html__( 'Dismiss', 'wardpair' ) . '

'; } /** * The partner's server presented a different certificate key than the one recorded the first * time (see Sentinel_Transport::origin_request). Direct connections are refused until an admin * confirms the change is expected: a renewed or replaced certificate is normal, a swapped one is not. */ public function maybe_show_origin_cert_notice(): void { $bad = get_option( Sentinel_Transport::PIN_BAD_OPTION ); if ( ! current_user_can( 'manage_options' ) || ! is_array( $bad ) ) { return; } echo '

' . esc_html__( "Wardpair: your other site's server certificate changed", 'wardpair' ) . '

' . sprintf( /* translators: 1: host name, 2: IP address */ esc_html__( 'The server for %1$s (%2$s) now presents a different certificate key than the one Wardpair recorded. Direct connections to it are paused and the normal domain route is being used instead, so syncing keeps working. If you or your host renewed or replaced that certificate, trust the new one. If you did not, leave this and ask your host.', 'wardpair' ), '' . esc_html( (string) ( $bad['host'] ?? '' ) ) . '', '' . esc_html( (string) ( $bad['ip'] ?? '' ) ) . '' ) . '

' . '
' . wp_nonce_field( 'wardpair_retrust_origin', '_wpnonce', true, false ) . // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_nonce_field() returns safe, already-escaped markup. '

'; } public function handle_retrust_origin(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'wardpair' ), '', array( 'response' => 403 ) ); } check_admin_referer( 'wardpair_retrust_origin' ); Sentinel_Transport::retrust_origin(); Sentinel_Core::log_event( 'origin_cert_trusted', 'An administrator chose to trust the other site\'s current certificate.' ); wp_safe_redirect( wp_get_referer() ?: admin_url( 'admin.php?page=wardpair' ) ); exit; } // ─── Event Logger ───────────────────────────────────────────────────────── public static function log_event( string $type, string $notes = '', ?string $resolved_at = null ): void { global $wpdb; list( $row, $fmt ) = Sentinel_Connections::stamp( array( 'event_type' => $type, 'triggered_at' => current_time( 'mysql' ), 'resolved_at' => $resolved_at, 'notes' => $notes, ), array( '%s', '%s', '%s', '%s' ) ); $wpdb->insert( $wpdb->prefix . 'wardpair_events', $row, $fmt ); // Tell the alert channels (hot / warm now, routine in the daily digest). Never throws. } /** * A milestone for the dashboard event log and the social channels. * Never emails: email stays for the few things that need a person. * * @param string $slug Short id for this milestone (also keeps repeats from flooding a channel). * @param string $tier 'hot' for something that needs attention, 'warm' for normal progress. * @param string $event_type Dashboard event type. */ public static function progress( string $slug, string $title, string $text = '', string $tier = 'warm', string $event_type = 'clone_progress' ): void { global $wpdb; list( $row, $fmt ) = Sentinel_Connections::stamp( array( 'event_type' => $event_type, 'triggered_at' => current_time( 'mysql' ), 'resolved_at' => null, 'notes' => $title . ( '' !== $text ? ': ' . $text : '' ), ), array( '%s', '%s', '%s', '%s' ) ); $wpdb->insert( $wpdb->prefix . 'wardpair_events', $row, $fmt ); } /** * Turns the clone and verification lines already written to the sync log * into milestones. Only the lines listed here are sent; the rest (every * chunk, every batch) stay in the log. Never throws. */ public static function progress_from_log( string $type, string $status, string $detail ): void { try { $failed = ( 'failed' === $status ); if ( 'clone' === $type ) { if ( 0 === strpos( $detail, 'Prefix detection:' ) ) { if ( preg_match( "/dump='([^']*)'.*secondary='([^']*)'/", $detail, $m ) ) { if ( $m[1] === $m[2] ) { self::progress( 'prefix', 'Table prefix checked', "Both sites use '{$m[1]}'. No conversion needed." ); } else { self::progress( 'prefix', 'Converting table prefix', "Converting tables from '{$m[1]}' to '{$m[2]}' as the database is restored." ); } } return; } $map = array( '#^extract_zip: initialised#' => array( 'extract_start', 'File extraction started', 'warm' ), '#^All DB chunks received#' => array( 'db_received', 'Database received', 'warm' ), '#^Starting DB restore#' => array( 'restore_start', 'Database restore started', 'warm' ), '#^SQL import complete#' => array( 'sql_done', 'Database import finished', 'warm' ), '#^Prefix fix \(#' => array( 'prefix_done', 'Table prefix conversion finished', 'warm' ), '#^URL search-replace complete#' => array( 'urls_done', 'Site address corrected throughout the database', 'warm' ), '#^Role check passed#' => array( 'role_ok', 'Administrator access confirmed', 'warm' ), '#^Role check repaired#' => array( 'role_fixed', 'Administrator access repaired', 'warm' ), '#^Role check FAILED#' => array( 'role_failed', 'Administrator access could not be confirmed', 'hot' ), '#^Full clone complete#' => array( 'complete', 'Clone complete', 'warm' ), '#^ZIP ready:#' => array( 'zip_ready', 'Files packed, transfer starting', 'warm' ), '#^DB backup ready#' => array( 'db_ready', 'Database exported, transfer starting', 'warm' ), '#^All DB chunks transferred#' => array( 'db_sent', 'Database sent to the standby', 'warm' ), ); foreach ( $map as $re => $row ) { if ( preg_match( $re, $detail ) ) { $text = ( 'Prefix fix' === substr( $detail, 0, 10 ) || 'Role check' === substr( $detail, 0, 10 ) || 'ZIP ready' === substr( $detail, 0, 9 ) || 'DB backup ready' === substr( $detail, 0, 15 ) ) ? $detail : ''; self::progress( $row[0], $row[1], $text, $row[2] ); return; } } if ( 0 === strpos( $detail, 'Chunk probe' ) ) { // Finding the largest request size the standby accepts is routine, not a fault. self::progress( 'chunk_probe', 'Transfer size adjusted', $detail, 'warm' ); return; } if ( $failed ) { self::progress( 'problem', 'Clone problem', $detail, 'hot' ); } return; } if ( 'verify' === $type ) { if ( 0 === strpos( $detail, 'DB fingerprint compared' ) ) { self::progress( 'verify_tables', $failed ? 'Tables differ between the sites' : 'Tables match', $detail ); } elseif ( 0 === strpos( $detail, 'Repair:' ) || 0 === strpos( $detail, 'Repair batch:' ) ) { self::progress( 'verify_repair', 'Repairing differences', $detail, $failed ? 'hot' : 'warm' ); } elseif ( $failed ) { self::progress( 'verify_problem', 'Standby check found a problem', $detail, 'hot' ); } } } catch ( \Throwable $e ) { // A notification must never break the work it reports on. } } /** * Build the admin-ajax.php URL for the partner site. * All inter-site communication goes to wp-admin/admin-ajax.php on the partner. * This path is universal — works on every host including EasyWP. * * @param string $partner_url The partner site's WordPress URL (siteurl). * @return string */ public static function partner_ajax_url( string $partner_url ): string { return trailingslashit( $partner_url ) . 'wp-admin/admin-ajax.php'; } }