init(); } return self::$instance; } private function __construct() {} private function init(): void { add_action( 'admin_menu', array( $this, 'register_menus' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'admin_init', array( $this, 'register_settings' ) ); add_action( 'admin_init', array( 'Sentinel_Log_Viewer', 'maybe_export' ) ); add_action( 'admin_init', array( $this, 'maybe_start_tour' ) ); $ajax_actions = array( 'sentinel_generate_token', 'sentinel_connect_pair', 'sentinel_disconnect', 'sentinel_hard_reset', 'sentinel_get_status', 'sentinel_run_backup', 'sentinel_delete_backup', 'sentinel_restore_backup', 'sentinel_save_backup_schedule', 'sentinel_estimate_size', 'sentinel_poll_backup_job', 'sentinel_poll_db_backup_job', 'sentinel_poll_zip_restore_job', 'sentinel_restore_progress', 'sentinel_start_restore', 'sentinel_get_active_restores', 'sentinel_tour_done', 'sentinel_get_restore_progress', 'sentinel_get_activity_logs', 'sentinel_get_active_activities', 'sentinel_get_terminal_activities', 'sentinel_bulk_delete_backups', 'sentinel_bulk_download_backups', 'sentinel_bulk_restore_backups', 'sentinel_get_sync_log', 'sentinel_reset_bootstrap', 'sentinel_start_clone', 'sentinel_clone_state', 'sentinel_reset_queue', 'sentinel_resume_clone', 'sentinel_continue_db_only', 'sentinel_pause_clone', 'sentinel_revert_pre_clone', 'sentinel_verify_secondary_hostname', 'sentinel_support_report', 'sentinel_standby_lost', 'sentinel_check_server_ip', ); foreach ( $ajax_actions as $action ) { add_action( 'wp_ajax_' . $action, array( $this, 'handle_ajax' ) ); } } // ─── First-run guided tour ───────────────────────────────────────────────── // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation parameters; nothing is changed or output unescaped. Only reads a tour flag from the query string. /** * Start the guided tour once, right after activation, and again the first * time an unconfigured site opens Wardpair. * * Two triggers, because either alone can miss: Freemius takes over the * screen right after activation and can swallow an activation redirect, and * a plugin copied into place never fires the activation hook at all. * Waits for the Freemius activation screen to be completed or skipped first. * Starts at most once per site (wardpair_welcome_seen), never during AJAX, * never for someone who already finished it, and never on a site that * already has a role. The tour can be replayed from the page title. */ public function maybe_start_tour(): void { if ( wp_doing_ajax() || wp_doing_cron() || ! current_user_can( 'manage_options' ) ) { return; } if ( get_option( 'wardpair_welcome_seen' ) || get_user_meta( get_current_user_id(), 'wardpair_tour_done', true ) || get_option( 'wardpair_role', '' ) ) { delete_transient( 'wardpair_welcome_redirect' ); return; } // Freemius shows its own activation (opt-in) screen first. Wait until that is done, so the // two never fight over the screen. Nothing is consumed while waiting: once the person has // connected or skipped, Freemius sends them to the Wardpair page and the tour starts there. $fs = function_exists( 'wardpair_fs' ) ? wardpair_fs() : null; if ( $fs && $fs->is_activation_mode() ) { return; } $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; $just_enabled = (bool) get_transient( 'wardpair_welcome_redirect' ); $opening_us = ( 'wardpair' === $page && empty( $_GET['tab'] ) ); if ( ! $just_enabled && ! $opening_us ) { return; } delete_transient( 'wardpair_welcome_redirect' ); update_option( 'wardpair_welcome_seen', time(), false ); wp_safe_redirect( admin_url( 'admin.php?page=wardpair&tab=dashboard&swp_tour=0' ) ); exit; } // phpcs:enable WordPress.Security.NonceVerification.Recommended // ─── Menu ───────────────────────────────────────────────────────────────── /** * One-colour Wardpair mark for the admin menu. WordPress recolours SVG * data URIs that carry a root fill to match the active admin colour scheme. */ private function menu_icon(): string { $svg = <<<'SVG' SVG; return 'data:image/svg+xml;base64,' . base64_encode( $svg ); } public function register_menus(): void { add_menu_page( __( 'Wardpair', 'wardpair' ), __( 'Wardpair', 'wardpair' ), 'manage_options', 'wardpair', array( $this, 'render_page' ), $this->menu_icon(), 80 ); } // ─── Assets ─────────────────────────────────────────────────────────────── /** Collects up to 10 script errors and failed file loads on this page, for the Support tab's display check. */ public function print_error_collector(): void { $js = <<<'JS' window.__swpErr = []; window.addEventListener( 'error', function ( e ) { if ( window.__swpErr.length >= 10 ) { return; } var t = e.target, url = t && ( t.src || t.href ); if ( url && t !== window ) { window.__swpErr.push( 'Failed to load ' + String( url ).split( '/' ).slice( -3 ).join( '/' ) ); return; } window.__swpErr.push( String( e.message || 'error' ) + ' (' + String( e.filename || '' ).split( '/' ).slice( -3 ).join( '/' ) + ':' + ( e.lineno || 0 ) + ')' ); }, true ); JS; wp_print_inline_script_tag( $js, array( 'id' => 'wardpair-error-collector' ) ); } public function enqueue_assets( string $hook ): void { $allowed = array( 'toplevel_page_wardpair' ); if ( ! in_array( $hook, $allowed, true ) ) { return; } // Records script errors and files that fail to load, so the Support tab can list them. add_action( 'admin_head', array( $this, 'print_error_collector' ), 1 ); wp_enqueue_style( 'wardpair-admin', WARDPAIR_URL . 'assets/css/sentinel-admin.css', array(), self::asset_version( 'assets/css/sentinel-admin.css' ) ); wp_enqueue_script( 'wardpair-admin', WARDPAIR_URL . 'assets/js/sentinel-admin.js', array( 'jquery' ), self::asset_version( 'assets/js/sentinel-admin.js' ), true ); wp_localize_script( 'wardpair-admin', 'wardpair', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'admin_url' => admin_url(), 'nonce' => wp_create_nonce( 'wardpair_admin' ), 'is_paired' => (bool) get_option( 'wardpair_is_paired', false ), // ← added 'login_url' => wp_login_url( admin_url( 'admin.php?page=wardpair&tab=backup' ) ), 'strings' => array( 'confirm_failover' => __( 'Trigger manual failover? Traffic will be redirected to this secondary site.', 'wardpair' ), 'confirm_failback' => __( 'Switch back to the original server? This site becomes read-only for a short while, hands over every change, then traffic returns to the original server.', 'wardpair' ), 'confirm_disconnect' => __( 'Disconnect this site pair? License pair binding is preserved.', 'wardpair' ), 'confirm_delete_backup' => __( 'Delete this backup? This cannot be undone.', 'wardpair' ), 'confirm_restore' => __( 'Restore this backup? Your current database will be overwritten. A safety backup will be taken first.', 'wardpair' ), 'copied' => __( 'Copied!', 'wardpair' ), 'backup_queued' => __( 'Backup queued — running in the background. You will receive an email when it completes.', 'wardpair' ), 'zip_restore_queued' => __( 'ZIP restore queued — running in the background. You will receive an email when it completes.', 'wardpair' ), 'confirm_full_clone' => __( 'Run a full clone? Everything on the secondary is overwritten with a fresh copy of this site. On a secondary that already holds a copy, "Check & repair" does the same job far faster.', 'wardpair' ), 'confirm_repair' => __( 'Compare both sites and send anything missing or different to the secondary?', 'wardpair' ), 'restore_session_lost' => __( 'The restore is still running on the server. It replaces your user accounts, so your login ends. This page keeps following the restore and will tell you when it is done.', 'wardpair' ), 'restore_session_lost_nokey' => __( 'The restore replaced your login session. It carries on in the background and this page can no longer follow it. Wait a minute, then log in again to confirm it worked.', 'wardpair' ), 'restore_busy' => __( 'The server is busy. The restore is still running; checking again…', 'wardpair' ), 'restore_done_login' => __( 'Restore complete. Log in again to continue.', 'wardpair' ), 'restore_failed_login' => __( 'The restore reported a problem. Log in again to see the full log in the Activity Monitor.', 'wardpair' ), 'restore_unknown_login' => __( 'This page can no longer follow the restore. It may well have finished. Log in again and check the Activity Monitor for its result.', 'wardpair' ), 'login_again' => __( 'Log in again', 'wardpair' ), ), ) ); wp_enqueue_script( 'wardpair-tour', WARDPAIR_URL . 'assets/js/sentinel-tour.js', array(), self::asset_version( 'assets/js/sentinel-tour.js' ), true ); wp_localize_script( 'wardpair-tour', 'wardpairTour', array( 'base' => admin_url( 'admin.php?page=wardpair' ), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'wardpair_admin' ), 'steps' => $this->tour_steps(), 'i18n' => array( 'next' => __( 'Next', 'wardpair' ), 'back' => __( 'Back', 'wardpair' ), 'skip' => __( 'Skip tour', 'wardpair' ), 'done' => __( 'Finish', 'wardpair' ), 'step' => __( 'Step {n} of {total}', 'wardpair' ), ), ) ); } /** * Steps of the guided tour. A step with an empty target is shown centred. * A target that is missing on the page (for example the clone panel on a * secondary site) falls back to the same centred card. * * @return array */ private function tour_steps(): array { // Steps that only make sense with the paid code (failover routing, Cloudflare, alerts) are added // inside is__premium_only() blocks, so the free build never mentions controls it does not have. $tabs_body = __( 'Dashboard shows health and logs, Pairing connects your two sites, Backup handles backups and restores, and Settings holds your alert email.', 'wardpair' ); $log_target = ''; $log_body = __( 'The Event Log and Sync Log on this tab record backups, copies and pairing changes, so you can see what happened and when.', 'wardpair' ); $steps = array( array( 'tab' => 'dashboard', 'target' => '', 'title' => __( 'Welcome to Wardpair', 'wardpair' ), 'body' => __( 'This short tour shows where everything lives. It takes about a minute, and you can leave at any point.', 'wardpair' ) ), array( 'tab' => 'dashboard', 'target' => '.swp-tabs', 'title' => __( 'Four tabs', 'wardpair' ), 'body' => $tabs_body ), array( 'tab' => 'dashboard', 'target' => '.swp-status-banner', 'title' => __( 'Status at a glance', 'wardpair' ), 'body' => __( 'This banner shows whether the live site is healthy and when it was last checked.', 'wardpair' ) ), ); $steps[] = array( 'tab' => 'dashboard', 'target' => $log_target, 'title' => __( 'Checks and events', 'wardpair' ), 'body' => $log_body ); $steps[] = array( 'tab' => 'pairing', 'target' => '#swp-role-selector', 'title' => __( 'Pair your two sites', 'wardpair' ), 'body' => __( 'Install Wardpair on both sites. Choose Primary on the live site and Secondary on the standby, then connect them with a one-time token.', 'wardpair' ) ); $steps[] = array( 'tab' => 'pairing', 'target' => '#swp-clone-panel', 'title' => __( 'Copy the site to the standby', 'wardpair' ), 'body' => __( 'Once paired, the primary offers Check and repair, Check only, or a Full clone to bring the standby in line with the live site.', 'wardpair' ) ); $steps[] = array( 'tab' => 'backup', 'target' => '[data-swp-tour="backup-run"]', 'title' => __( 'Backups', 'wardpair' ), 'body' => __( 'Run a database or full-site backup here. Below it you can restore from history or upload a backup file. A safety backup is taken before a restore.', 'wardpair' ) ); // The free build ends on the alert email step. Paid code swaps that for the failover steps. // (No else branch: Freemius's handling of an else on a premium-only if is not documented.) $last_steps = array( array( 'tab' => 'settings', 'target' => '#swp-set-email', 'title' => __( 'Alert email', 'wardpair' ), 'body' => __( 'Set the address Wardpair writes to when a backup or a copy finishes or fails. You can replay this tour from the button beside the page title.', 'wardpair' ) ), ); return array_merge( $steps, $last_steps ); } // ─── Settings ───────────────────────────────────────────────────────────── public function register_settings(): void { register_setting( 'wardpair_settings', 'wardpair_alert_email', array( 'sanitize_callback' => 'sanitize_email', ) ); register_setting( 'wardpair_settings', 'wardpair_backup_schedule', array( 'sanitize_callback' => 'sanitize_key', ) ); register_setting( 'wardpair_settings', 'wardpair_backup_format', array( 'sanitize_callback' => 'sanitize_key', ) ); register_setting( 'wardpair_settings', 'wardpair_backup_scope', array( 'sanitize_callback' => 'sanitize_key', ) ); // Its own group (its own form), like the others: a missing checkbox must not blank other options. register_setting( 'wardpair_ip', Sentinel_Pairing::OPT_IP_LOOKUP, array( 'sanitize_callback' => function ( $v ) { return empty( $v ) ? '0' : '1'; }, 'default' => '0', ) ); // Its own group (its own form): see the note on register_protection_settings(). register_setting( 'wardpair_data', 'wardpair_delete_data_on_uninstall', array( 'sanitize_callback' => function ( $v ) { return empty( $v ) ? 0 : 1; }, 'default' => 0, ) ); } // Failover control has its own group for the same reason: every registered option missing from // the submitted form is blanked, so these must not share a form with anything else. // Safety, retention and reporting have their own group for the same reason as the others. // Sync speed lives in its own settings group: options.php blanks every // registered option that is missing from the submitted form, so sharing // a group with the alert-email form would reset these on every email save. // ─── Page Router ────────────────────────────────────────────────────────── // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin tab selection (page and tab); nothing is changed. public function render_page(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Permission denied.', 'wardpair' ) ); } $active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'dashboard'; if ( ! in_array( $active_tab, array( 'dashboard', 'pairing', 'backup', 'settings', 'support' ), true ) ) { $active_tab = 'dashboard'; } $base = admin_url( 'admin.php?page=wardpair' ); ?>

__( 'Permission denied.', 'wardpair' ) ), 403 ); } check_ajax_referer( 'wardpair_admin', 'nonce' ); $action = sanitize_key( str_replace( 'sentinel_', '', sanitize_text_field( wp_unslash( $_POST['action'] ?? '' ) ) ) ); switch ( $action ) { case 'generate_token': $this->ajax_generate_token(); break; case 'connect_pair': $this->ajax_connect_pair(); break; case 'disconnect': $this->ajax_disconnect(); break; case 'hard_reset': $this->ajax_hard_reset(); break; case 'get_status': $this->ajax_get_status(); break; case 'run_backup': $this->ajax_run_backup(); break; case 'delete_backup': $this->ajax_delete_backup(); break; case 'restore_backup': $this->ajax_restore_backup(); break; case 'save_backup_schedule': $this->ajax_save_backup_schedule(); break; case 'estimate_size': $this->ajax_estimate_size(); break; case 'poll_backup_job': $this->ajax_poll_backup_job(); break; case 'poll_db_backup_job': $this->ajax_poll_db_backup_job(); break; case 'poll_zip_restore_job': $this->ajax_poll_zip_restore_job(); break; case 'get_active_restores': $this->ajax_get_active_restores(); break; case 'start_restore': $this->ajax_start_restore(); break; case 'restore_progress': $this->ajax_restore_progress(); break; case 'tour_done': $this->ajax_tour_done(); break; case 'get_restore_progress': $this->ajax_get_restore_progress(); break; case 'get_activity_logs': $this->ajax_get_activity_logs(); break; case 'get_terminal_activities': $this->ajax_get_terminal_activities(); break; case 'get_sync_log': $this->ajax_get_sync_log(); break; case 'reset_bootstrap': $this->ajax_reset_bootstrap(); break; case 'get_active_activities': $this->ajax_get_active_activities(); break; case 'bulk_delete_backups': $this->ajax_bulk_delete_backups(); break; case 'bulk_download_backups': $this->ajax_bulk_download_backups(); break; case 'bulk_restore_backups': $this->ajax_bulk_restore_backups(); break; case 'start_clone': $this->ajax_start_clone(); break; case 'reset_queue': $this->ajax_reset_queue(); break; case 'resume_clone': $this->ajax_resume_clone(); break; case 'continue_db_only': $this->ajax_continue_db_only(); break; case 'pause_clone': $this->ajax_pause_clone(); break; case 'revert_pre_clone': $this->ajax_revert_pre_clone(); break; case 'verify_secondary_hostname': $this->ajax_verify_secondary_hostname(); break; case 'clone_state': $this->ajax_clone_state(); break; case 'support_report': $this->ajax_support_report(); break; case 'standby_lost': $this->ajax_standby_lost(); break; case 'check_server_ip': $this->ajax_check_server_ip(); break; default: // Paid actions (Cloudflare, failover, reconcile, runner, readiness, reports, alert channels). wp_send_json_error( array( 'message' => 'Unknown action.' ), 400 ); } } // ─── Structure copy AJAX ────────────────────────────────────────────────── // ─── Support AJAX ───────────────────────────────────────────────────────── /** Plain-text report the admin can copy into a support message. Redacted by Sentinel_Support. */ private function ajax_support_report(): void { wp_send_json_success( array( 'report' => Sentinel_Support::report() ) ); } // ─── Pairing AJAX ───────────────────────────────────────────────────────── private function ajax_generate_token(): void { $blocked = Sentinel_Compat::pairing_block_message(); if ( '' !== $blocked ) { wp_send_json_error( array( 'message' => $blocked ) ); } $token = Sentinel_Pairing::generate_token(); wp_send_json_success( array( 'token' => $token, 'expires_at' => get_option( 'wardpair_pairing_token_expiry' ), 'site_url' => get_site_url(), ) ); } // phpcs:disable WordPress.Security.NonceVerification.Missing -- Every ajax_* handler below is reached only through handle_ajax(), which checks the manage_options capability and the wardpair_admin nonce first. private function ajax_connect_pair(): void { $blocked = Sentinel_Compat::pairing_block_message(); if ( '' !== $blocked ) { wp_send_json_error( array( 'message' => $blocked ) ); } $token = sanitize_text_field( wp_unslash( $_POST['token'] ?? '' ) ); $primary_url = esc_url_raw( wp_unslash( $_POST['primary_url'] ?? '' ) ); if ( empty( $token ) || empty( $primary_url ) ) { wp_send_json_error( array( 'message' => __( 'Token and primary URL are required.', 'wardpair' ) ) ); } $result = Sentinel_Pairing::connect_to_primary( $token, $primary_url ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Pairing successful. This site is now the secondary.', 'wardpair' ) ) ); } private function ajax_disconnect(): void { Sentinel_Pairing::disconnect(); $notified = get_option( 'wardpair_last_disconnect_notify', '' ); $message = ( 'pending' === $notified ) ? __( 'Disconnected. The other site could not be reached just now. Wardpair keeps retrying, and the other site also disconnects itself within a few minutes once it sees this one has gone.', 'wardpair' ) : __( 'Disconnected.', 'wardpair' ); wp_send_json_success( array( 'message' => $message ) ); } /** The two buttons under "The standby site is not answering". */ private function ajax_standby_lost(): void { $do = isset( $_POST['do'] ) ? sanitize_key( wp_unslash( $_POST['do'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce and capability are checked in handle_ajax(). if ( ! in_array( $do, array( 'disconnect', 'snooze' ), true ) || 'primary' !== get_option( 'wardpair_role', '' ) ) { wp_send_json_error( array( 'message' => __( 'Nothing to do.', 'wardpair' ) ), 400 ); } $token = isset( $_POST['cf_token'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['cf_token'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce and capability are checked in handle_ajax(). $r = Sentinel_Pairing::standby_lost_action( $do, $token ); if ( empty( $r['ok'] ) ) { wp_send_json_error( array( 'message' => $r['message'] ) ); } wp_send_json_success( array( 'message' => $r['message'] ) ); } /** The "Check now" button under the outside IP lookup box. */ private function ajax_check_server_ip(): void { $r = Sentinel_Pairing::check_now(); $r['message'] = $r['message'] . "\n" . implode( "\n", array_map( 'sanitize_text_field', $r['trace'] ) ); if ( $r['ok'] ) { wp_send_json_success( array( 'message' => $r['message'] ) ); } wp_send_json_error( array( 'message' => $r['message'] ) ); } private function ajax_hard_reset(): void { Sentinel_Pairing::hard_reset(); wp_send_json_success( array( 'message' => __( 'Full reset complete.', 'wardpair' ) ) ); } // ─── Cloudflare AJAX ────────────────────────────────────────────────────── /** * "Verify Hostname" button: a sanity check on the CNAME target the * user is about to save, run BEFORE saving it — catches a typo'd or * not-yet-live ingress hostname while it's still easy to fix, rather * than only finding out at actual failover time. * * Checks two things: the value is a bare hostname (not a pasted URL * or path), and it currently resolves to something. A hostname that * doesn't resolve yet isn't necessarily wrong — some hosts only * activate it once traffic is pointed there — so that reports as a * warning the user can proceed past, not a hard failure. */ private function ajax_verify_secondary_hostname(): void { $hostname = trim( sanitize_text_field( wp_unslash( $_POST['hostname'] ?? '' ) ) ); if ( '' === $hostname ) { wp_send_json_error( array( 'message' => __( 'Enter a hostname first.', 'wardpair' ) ) ); } if ( filter_var( $hostname, FILTER_VALIDATE_URL ) || false !== strpos( $hostname, '/' ) ) { wp_send_json_error( array( 'message' => __( 'Enter just the hostname (e.g. server-123.yourhost.com), not a full URL or path.', 'wardpair' ) ) ); } if ( ! preg_match( '/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/i', $hostname ) ) { wp_send_json_error( array( 'message' => __( 'That doesn\'t look like a valid hostname.', 'wardpair' ) ) ); } $records = @dns_get_record( $hostname, DNS_A + DNS_CNAME ); if ( empty( $records ) ) { wp_send_json_error( array( 'message' => sprintf( /* translators: %s: hostname */ __( '"%s" doesn\'t resolve yet. If your host hasn\'t activated it, you can still save it — just confirm before relying on failover.', 'wardpair' ), $hostname ) ) ); } $targets = array(); foreach ( $records as $r ) { if ( 'A' === $r['type'] ) { $targets[] = $r['ip']; } elseif ( 'CNAME' === $r['type'] ) { $targets[] = $r['target']; } } wp_send_json_success( array( 'message' => sprintf( /* translators: 1: hostname, 2: what it resolves to */ __( '"%1$s" resolves to %2$s.', 'wardpair' ), $hostname, implode( ', ', array_unique( $targets ) ) ), ) ); } /** * "Check Failover Readiness" button: confirms the saved token can reach the * Worker and Worker-route endpoints failover uses, and names any missing * permission in plain language. Read-only — nothing is created or changed. */ /** * Cache-busting version for admin assets: version + file modification time, * so browsers/CDNs fetch the new file as soon as it is updated on disk * (a fixed version string leaves everyone on the old JS after an update). */ private static function asset_version( string $relative ): string { $file = plugin_dir_path( dirname( __FILE__ ) ) . $relative; $mtime = file_exists( $file ) ? (string) filemtime( $file ) : ''; return WARDPAIR_VERSION . ( $mtime ? '.' . $mtime : '' ); } // ─── Failover AJAX ──────────────────────────────────────────────────────── // ─── Protection: breaker, readiness, drill, report, cutover ─────────────── private function ajax_get_status(): void { global $wpdb; $pings = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id DESC LIMIT 20', $wpdb->prefix . 'wardpair_pings' ), ARRAY_A ); $events = Sentinel_Connections::events( 10, Sentinel_Connections::current() ); wp_send_json_success( array( 'role' => get_option( 'wardpair_role', '' ), 'status' => get_option( 'wardpair_status', 'normal' ), 'is_paired' => (bool) get_option( 'wardpair_is_paired', false ), 'last_seen' => get_option( 'wardpair_last_seen', 0 ), 'partner_url' => get_option( 'wardpair_partner_url', '' ), 'bootstrap' => (bool) get_option( 'wardpair_bootstrap_complete', false ), 'pings' => $pings, 'events' => $events, ) ); } // ─── Backup AJAX ────────────────────────────────────────────────────────── private function ajax_run_backup(): void { $scope = sanitize_key( wp_unslash( $_POST['scope'] ?? Sentinel_Backup::SCOPE_DB ) ); $format = sanitize_text_field( wp_unslash( $_POST['format'] ?? Sentinel_Backup::FORMAT_SQL_GZ ) ); if ( ! in_array( $format, array_keys( Sentinel_Backup::ALL_FORMATS ), true ) ) { $format = Sentinel_Backup::FORMAT_SQL_GZ; } if ( ! in_array( $scope, array( Sentinel_Backup::SCOPE_DB, Sentinel_Backup::SCOPE_FILES, Sentinel_Backup::SCOPE_FULL ), true ) ) { $scope = Sentinel_Backup::SCOPE_DB; } $result = Sentinel_Backup::run( Sentinel_Backup::TYPE_MANUAL, 'Manual backup from admin', $format, $scope ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } if ( ! empty( $result['queued'] ) ) { wp_send_json_success( array( 'queued' => true, 'job_key' => $result['job_key'], 'scope' => $scope, 'message' => __( 'Backup queued — running in the background. You will receive an email when it completes.', 'wardpair' ), ) ); return; } wp_send_json_success( array( 'queued' => false, 'message' => sprintf( /* translators: 1: backup file name, 2: backup file size */ __( 'Backup created: %1$s (%2$s)', 'wardpair' ), $result['filename'], size_format( $result['size_bytes'] ) ), 'filename' => $result['filename'], 'download' => Sentinel_Backup::download_url( $result['filename'] ), 'size' => size_format( $result['size_bytes'] ), 'format' => $result['format'], ) ); } private function ajax_delete_backup(): void { $id = absint( wp_unslash( $_POST['backup_id'] ?? 0 ) ); if ( ! $id ) { wp_send_json_error( array( 'message' => __( 'Invalid backup ID.', 'wardpair' ) ) ); } $result = Sentinel_Backup::delete( $id ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Backup deleted.', 'wardpair' ) ) ); } private function ajax_restore_backup(): void { $filename = basename( sanitize_text_field( wp_unslash( $_POST['filename'] ?? '' ) ) ); $filename = preg_replace( '/[^a-zA-Z0-9\-_.]/', '', $filename ); if ( empty( $filename ) ) { wp_send_json_error( array( 'message' => __( 'No backup specified.', 'wardpair' ) ) ); } // Look up backup by filename to get the ID global $wpdb; $backup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}wardpair_backups WHERE filename = %s LIMIT 1", $filename ) ); if ( ! $backup ) { wp_send_json_error( array( 'message' => __( 'Backup record not found.', 'wardpair' ) ) ); } // Route through restore_with_progress which handles logging $result = Sentinel_Backup::restore_with_progress( (int) $backup->id ); if ( is_wp_error( $result ) ) { // ZIP/DB queued are not real errors — they're async jobs now running // in the background. Return the job_key so the UI can track it, // though the activity monitor also picks these up automatically. $code = $result->get_error_code(); if ( 'zip_queued' === $code || 'db_queued' === $code ) { wp_send_json_success( array( 'message' => 'zip_queued' === $code ? __( 'ZIP restore queued as background job.', 'wardpair' ) : __( 'Database restore queued as background job.', 'wardpair' ), 'queued' => true, 'job_key' => $result->get_error_data(), ) ); return; } wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Database restored successfully.', 'wardpair' ), ) ); } private function ajax_save_backup_schedule(): void { $schedule = sanitize_key( wp_unslash( $_POST['schedule'] ?? 'none' ) ); if ( ! in_array( $schedule, array( 'none', 'daily', 'weekly' ), true ) ) { $schedule = 'none'; } $scope = sanitize_key( wp_unslash( $_POST['scope'] ?? Sentinel_Backup::SCOPE_DB ) ); if ( ! in_array( $scope, array( Sentinel_Backup::SCOPE_DB, Sentinel_Backup::SCOPE_FILES, Sentinel_Backup::SCOPE_FULL ), true ) ) { $scope = Sentinel_Backup::SCOPE_DB; } $format = sanitize_text_field( wp_unslash( $_POST['format'] ?? Sentinel_Backup::FORMAT_SQL_GZ ) ); $format = Sentinel_Backup::resolve_format( $format ); update_option( 'wardpair_backup_schedule', $schedule ); update_option( 'wardpair_backup_scope', $scope ); update_option( 'wardpair_backup_format', $format ); do_action( 'wardpair_schedule_update' ); $labels = array( 'none' => __( 'Disabled', 'wardpair' ), 'daily' => __( 'Daily', 'wardpair' ), 'weekly' => __( 'Weekly', 'wardpair' ), ); wp_send_json_success( array( 'message' => sprintf( /* translators: 1: schedule frequency, 2: schedule details */ __( 'Schedule saved: %1$s — %2$s', 'wardpair' ), $labels[ $schedule ], ucfirst( $scope ) . ( 'db' === $scope ? ' (' . strtoupper( $format ) . ')' : '' ) ), ) ); } private function ajax_estimate_size(): void { $bytes = Sentinel_Backup_Files::estimate_content_size(); wp_send_json_success( array( 'bytes' => $bytes, 'formatted' => size_format( $bytes ), 'warn' => $bytes > Sentinel_Backup_Files::WARN_SIZE_BYTES, 'too_large' => $bytes > Sentinel_Backup_Files::MAX_SIZE_BYTES, ) ); } private function ajax_poll_backup_job(): void { $job_key = sanitize_key( wp_unslash( $_POST['job_key'] ?? '' ) ); if ( empty( $job_key ) ) { wp_send_json_error( array( 'message' => 'Missing job_key.' ) ); } $status = Sentinel_Backup_Files::get_job_status( $job_key ); if ( ! $status ) { wp_send_json_error( array( 'message' => 'Job not found.' ) ); } // Safety net: while a job is still waiting to start, nudge the queue (at most every 10 s). if ( in_array( $status['status'] ?? '', array( 'inventory', 'pending', 'queued' ), true ) && ! get_transient( 'wardpair_poll_kick' ) ) { set_transient( 'wardpair_poll_kick', 1, 10 ); Sentinel_Cron::kick(); } if ( 'complete' === $status['status'] && ! empty( $status['filename'] ) ) { $status['download'] = Sentinel_Backup::download_url( $status['filename'] ); $status['size_fmt'] = size_format( $status['size'] ); } wp_send_json_success( $status ); } private function ajax_poll_db_backup_job(): void { $job_key = sanitize_key( wp_unslash( $_POST['job_key'] ?? '' ) ); if ( empty( $job_key ) ) { wp_send_json_error( array( 'message' => 'Missing job_key.' ) ); } $status = Sentinel_Backup_DB::get_job_status( $job_key ); if ( ! $status ) { wp_send_json_error( array( 'message' => 'Job not found.' ) ); } // Safety net: while a job is still waiting to start, nudge the queue (at most every 10 s). if ( in_array( $status['status'] ?? '', array( 'inventory', 'pending', 'queued' ), true ) && ! get_transient( 'wardpair_poll_kick' ) ) { set_transient( 'wardpair_poll_kick', 1, 10 ); Sentinel_Cron::kick(); } if ( 'complete' === $status['status'] && ! empty( $status['filename'] ) ) { $status['download'] = Sentinel_Backup::download_url( $status['filename'] ); } wp_send_json_success( $status ); } /** * Poll the progress of an async ZIP restore job. * The UI calls this every few seconds after receiving zip_queued = true. */ private function ajax_poll_zip_restore_job(): void { $job_key = sanitize_key( wp_unslash( $_POST['job_key'] ?? '' ) ); if ( empty( $job_key ) ) { wp_send_json_error( array( 'message' => 'Missing job_key.' ) ); } $status = Sentinel_Backup::get_zip_restore_status( $job_key ); if ( ! $status ) { wp_send_json_error( array( 'message' => 'Job not found.' ) ); } wp_send_json_success( $status ); } private function ajax_start_restore(): void { $backup_id = absint( wp_unslash( $_POST['backup_id'] ?? 0 ) ); if ( ! $backup_id ) { wp_send_json_error( array( 'message' => 'Invalid backup ID.' ) ); } $result = Sentinel_Backup::restore_with_progress( $backup_id ); // ZIP restores return WP_Error with code 'zip_queued' — this is not // a real error. Unwrap it and return a success response with the job key // so the UI can start polling sentinel_poll_zip_restore_job. if ( is_wp_error( $result ) && 'zip_queued' === $result->get_error_code() ) { // Extract the job key from the error message data. $data = $result->get_error_data( 'zip_queued' ); $job_key = is_string( $data ) ? $data : ''; wp_send_json_success( array( 'zip_queued' => true, 'job_key' => $job_key, 'message' => __( 'ZIP restore queued — running in the background. You will receive an email when it completes.', 'wardpair' ), ) ); return; } if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => 'Restore completed successfully.' ) ); } private function ajax_restore_progress(): void { global $wpdb; $backup_id = absint( wp_unslash( $_POST['backup_id'] ?? 0 ) ); if ( ! $backup_id ) { wp_send_json_error( array( 'message' => 'Invalid backup ID.' ) ); } $log = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}wardpair_activity_logs WHERE type = 'restore' AND backup_id = %d ORDER BY id DESC LIMIT 1", $backup_id ), ARRAY_A ); if ( ! $log ) { wp_send_json_success( array( 'status' => 'pending', 'progress' => 0 ) ); return; } wp_send_json_success( array( 'status' => $log['status'], 'step' => $log['step'], 'progress' => (int) $log['progress_pct'], 'message' => $log['message'], 'started_at' => $log['started_at'], 'completed_at' => $log['completed_at'], ) ); } private function ajax_get_active_restores(): void { global $wpdb; $logs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE type = 'restore' AND status IN ('pending', 'running') ORDER BY id DESC LIMIT 10", $wpdb->prefix . 'wardpair_activity_logs' ), ARRAY_A ); wp_send_json_success( array( 'logs' => $logs ) ); } // ─── Tour AJAX ──────────────────────────────────────────────────────────── private function ajax_tour_done(): void { update_user_meta( get_current_user_id(), 'wardpair_tour_done', time() ); wp_send_json_success(); } private function ajax_get_restore_progress(): void { $job_key = sanitize_key( wp_unslash( $_POST['job_key'] ?? '' ) ); if ( empty( $job_key ) ) { wp_send_json_error( array( 'message' => 'Missing job_key.' ) ); } $log = Sentinel_Activity_Logger::get_by_job_key( $job_key ); if ( ! $log ) { wp_send_json_error( array( 'message' => 'Job not found.' ) ); } wp_send_json_success( array( 'status' => $log['status'], 'step' => $log['step'], 'pct' => (int) $log['progress_pct'], 'message' => $log['message'], 'complete' => in_array( $log['status'], array( 'complete', 'failed' ), true ), ) ); } private function ajax_get_activity_logs(): void { $logs = Sentinel_Activity_Logger::get_recent( 30 ); wp_send_json_success( array( 'activities' => $logs ) ); } private function ajax_get_active_activities(): void { $activities = Sentinel_Activity_Logger::get_active(); // Also clears rows that can never finish. // For each active activity, also fetch the latest job status if available foreach ( $activities as &$activity ) { $job_key = $activity['job_key']; if ( ! empty( $job_key ) ) { // Check if this is a file backup job if ( strpos( $job_key, 'wardpair_filejob_' ) === 0 ) { $status = Sentinel_Backup_Files::get_job_status( $job_key ); if ( $status ) { $activity['progress_pct'] = $status['pct']; $activity['step'] = $status['status']; $activity['message'] = $status['status'] === 'chunking' ? "Processing chunk {$status['done_chunks']} of {$status['total_chunks']}..." : $activity['message']; } } // Check if this is a DB backup job elseif ( strpos( $job_key, 'wardpair_dbjob_' ) === 0 ) { $status = Sentinel_Backup_DB::get_job_status( $job_key ); if ( $status ) { $activity['progress_pct'] = $status['pct']; $activity['step'] = $status['status']; } } // Check if this is a ZIP restore job elseif ( strpos( $job_key, 'wardpair_ziprestore_' ) === 0 ) { $status = Sentinel_Backup::get_zip_restore_status( $job_key ); if ( $status ) { $activity['progress_pct'] = $status['pct']; $activity['step'] = $status['status']; $activity['message'] = $status['error'] ?: $activity['message']; } } } } wp_send_json_success( array( 'activities' => $activities ) ); } private function ajax_get_terminal_activities(): void { global $wpdb; Sentinel_Activity_Logger::reap_orphans(); // started_at / completed_at are written in the SITE's time zone (current_time('mysql')), so the // cut-offs must be in the same zone. NOW() is the database server's clock: where the two differ, // finished and stale rows kept counting as "recent" for hours. $cut_hour = wp_date( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS ); $cut_5min = wp_date( 'Y-m-d H:i:s', time() - 5 * MINUTE_IN_SECONDS ); // Get all activities from the last hour that are still relevant $activities = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}wardpair_activity_logs WHERE started_at > %s AND status IN ('pending', 'running') ORDER BY id DESC", $cut_hour ), ARRAY_A ); // Also include recently completed ones (last 5 minutes) $recent_completed = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}wardpair_activity_logs WHERE status IN ('complete', 'failed') AND completed_at > %s ORDER BY id DESC LIMIT 10", $cut_5min ), ARRAY_A ); $activities = array_merge($activities, $recent_completed); // Update progress for each foreach ($activities as &$activity) { $job_key = $activity['job_key']; if (!empty($job_key)) { if (strpos($job_key, 'wardpair_filejob_') === 0) { $status = Sentinel_Backup_Files::get_job_status($job_key); if ($status) { $activity['progress_pct'] = $status['pct']; } } elseif (strpos($job_key, 'wardpair_dbjob_') === 0) { $status = Sentinel_Backup_DB::get_job_status($job_key); if ($status) { $activity['progress_pct'] = $status['pct']; } } } } wp_send_json_success(array('activities' => $activities)); } private function ajax_bulk_delete_backups(): void { $backup_ids = array_map( 'intval', (array) wp_unslash( $_POST['backup_ids'] ?? array() ) ); if ( empty( $backup_ids ) ) { wp_send_json_error( array( 'message' => __( 'No backups selected.', 'wardpair' ) ) ); } $deleted = 0; $errors = 0; foreach ( $backup_ids as $id ) { $result = Sentinel_Backup::delete( $id ); if ( is_wp_error( $result ) ) { $errors++; } else { $deleted++; } } wp_send_json_success( array( 'message' => sprintf( /* translators: 1: number of backups deleted, 2: number of errors */ __( '%1$d backups deleted. %2$d errors.', 'wardpair' ), $deleted, $errors ), 'deleted' => $deleted, 'errors' => $errors, ) ); } private function ajax_bulk_download_backups(): void { $filenames = array_map( 'sanitize_file_name', (array) wp_unslash( $_POST['filenames'] ?? array() ) ); if ( empty( $filenames ) ) { wp_send_json_error( array( 'message' => __( 'No backups selected.', 'wardpair' ) ) ); } // Create a temporary zip file containing all selected backups $zip_filename = 'wardpair-backups-' . gmdate( 'Y-m-d_H-i-s' ) . '.zip'; $zip_filepath = WARDPAIR_BACKUP_DIR . '/' . $zip_filename; $zip = new ZipArchive(); if ( $zip->open( $zip_filepath, ZipArchive::CREATE ) !== true ) { wp_send_json_error( array( 'message' => __( 'Could not create zip file.', 'wardpair' ) ) ); } foreach ( $filenames as $filename ) { $filepath = WARDPAIR_BACKUP_DIR . '/' . $filename; if ( file_exists( $filepath ) ) { $zip->addFile( $filepath, $filename ); } } $zip->close(); wp_send_json_success( array( 'download_url' => Sentinel_Backup::download_url( $zip_filename ), 'filename' => $zip_filename, ) ); } private function ajax_bulk_restore_backups(): void { $backup_ids = array_map( 'intval', (array) wp_unslash( $_POST['backup_ids'] ?? array() ) ); if ( empty( $backup_ids ) ) { wp_send_json_error( array( 'message' => __( 'No backups selected.', 'wardpair' ) ) ); } // Only restore the first selected backup (sequential restore is dangerous) $backup_id = $backup_ids[0]; $result = Sentinel_Backup::restore_with_progress( $backup_id ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Restore started. Check Activity Monitor for progress.', 'wardpair' ), 'backup_id' => $backup_id, ) ); } private function ajax_get_sync_log(): void { // The dashboard sends the connection it is showing; anything unknown falls back to the live one. $conn = Sentinel_Connections::resolve( sanitize_key( wp_unslash( $_POST['conn'] ?? '' ) ) ); $logs = Sentinel_Sync::get_recent_log( 50, $conn ); wp_send_json_success( array( 'logs' => $logs ) ); } /** * Manual escape hatch for a stuck "Initial content sync in progress" * banner on primary. Normally this clears itself automatically once * secondary's clone finishes and notifies primary — this exists for a * pairing that finished cloning before that notification existed, or * for the rare case the notification itself never arrived. */ // ─── Clone / Verify AJAX ────────────────────────────────────────────────── /** * Starts a transfer to the secondary. Three modes: * * full — the original pipeline: ZIP all of wp-content, dump the whole * DB, ship both, restore. Correct for a secondary that has * never held a copy. * repair — compare file-by-file, send only what's missing or different, * and re-run the DB phase only if the DB actually differs. * verify — the same comparison, reporting only. Nothing is written. */ private function ajax_start_clone(): void { if ( 'primary' !== get_option( 'wardpair_role' ) || ! get_option( 'wardpair_is_paired', false ) ) { wp_send_json_error( array( 'message' => __( 'This site is not a paired primary.', 'wardpair' ) ) ); return; } $mode = sanitize_key( wp_unslash( $_POST['mode'] ?? '' ) ); if ( in_array( $mode, array( 'verify', 'repair' ), true ) ) { $result = Sentinel_Clone_Verify::start( $mode ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); return; } wp_send_json_success( array( 'message' => 'repair' === $mode ? __( 'Check & repair started. Comparing every file with the secondary and sending anything missing or different. Live progress appears below.', 'wardpair' ) : __( 'Check started. Comparing files with the secondary. Nothing will be changed; the results appear below.', 'wardpair' ), 'mode' => $mode, ) ); return; } if ( 'full' !== $mode ) { wp_send_json_error( array( 'message' => __( 'Unknown clone mode.', 'wardpair' ) ) ); return; } $writable = Sentinel_Backup::require_writable_dir(); if ( is_wp_error( $writable ) ) { wp_send_json_error( array( 'message' => $writable->get_error_message() ) ); return; } if ( Sentinel_Clone_Verify::is_running() ) { wp_send_json_error( array( 'message' => __( 'A check is already running. Wait for it to finish.', 'wardpair' ) ) ); return; } if ( get_option( 'wardpair_clone_files_started', false ) && ! get_option( 'wardpair_clone_complete', false ) ) { wp_send_json_error( array( 'message' => __( 'A clone is already in progress.', 'wardpair' ) ) ); return; } if ( ! function_exists( 'as_enqueue_async_action' ) ) { wp_send_json_error( array( 'message' => __( 'Action Scheduler is unavailable.', 'wardpair' ) ) ); return; } // A full clone restarts from zero by definition, so clear the guards // a previous attempt may have left set — otherwise start_clone() // sees "already in progress" and silently does nothing. Sentinel_Clone_Sync::kill_stale_jobs(); as_enqueue_async_action( 'wardpair_clone_negotiate_chunk_size', array(), 'wardpair' ); Sentinel_Cron::kick(); Sentinel_Core::log_event( 'clone_requested', 'Full clone started manually by admin.' ); wp_send_json_success( array( 'message' => __( 'Full clone started. Files are sent first, then the database. Progress appears below and in the activity log.', 'wardpair' ), 'mode' => 'full', ) ); } // phpcs:enable WordPress.Security.NonceVerification.Missing /** * Combined state for the clone panel: whether a full clone is running, * and where any verify/repair run has got to. */ private function ajax_clone_state(): void { $verify = Sentinel_Clone_Verify::get_state(); // "Running" means started and not yet complete. A stale started-flag // left over from a finished clone must not read as a live run. $clone_running = ( (bool) get_option( 'wardpair_clone_files_started', false ) || (bool) get_option( 'wardpair_clone_db_started', false ) ) && ! (bool) get_option( 'wardpair_clone_complete', false ); // The panel polls this every few seconds while a check or clone is // running. If the queue has stalled (no working loopback / cron), // run it from here rather than waiting for someone to press Run in // Tools → Scheduled Actions. Throttled by a lock inside. if ( $clone_running || Sentinel_Clone_Verify::is_running() ) { Sentinel_Cron::drive_queue(); } // A clone phase that stopped moving with nothing queued for it resumes from its saved position. if ( $clone_running ) { Sentinel_Clone_Sync::maybe_resume_stalled(); } $progress = $this->clone_progress_summary(); $pct = 0; if ( $verify['total'] > 0 ) { $pct = min( 100, (int) round( $verify['scanned'] / $verify['total'] * 100 ) ); } // When did this result come from, and has something newer made it untrue? $finished = (int) $verify['finished_at']; $cold_at = 0; $stale = ''; if ( $finished > 0 && ! Sentinel_Clone_Verify::is_running() ) { if ( $cold_at > $finished ) { $stale = 'newer'; // a full comparison has finished since } elseif ( ( time() - $finished ) > DAY_IN_SECONDS ) { $stale = 'old'; } } wp_send_json_success( array( 'verify' => array( 'finished_at' => $finished, 'checked' => $finished ? sprintf( /* translators: 1: how long ago, 2: date and time */ __( 'Checked %1$s ago (%2$s).', 'wardpair' ), human_time_diff( $finished ), wp_date( 'j M Y, H:i', $finished ) ) : '', 'stale' => $stale, 'stale_text' => ( 'newer' === $stale ) ? __( 'A newer full comparison has finished since. This result may no longer be true. Run the check again.', 'wardpair' ) : ( ( 'old' === $stale ) ? __( 'This result is more than a day old and may no longer be true. Run the check again.', 'wardpair' ) : '' ), 'phase' => $verify['phase'], 'mode' => $verify['mode'], 'message' => $verify['message'], 'pct' => $pct, 'scanned' => $verify['scanned'], 'total' => $verify['total'], 'missing_count' => $verify['missing_count'], 'changed_count' => $verify['changed_count'], 'repaired' => $verify['repaired'], 'repair_failed' => $verify['repair_failed'], 'missing' => array_slice( $verify['missing'], 0, 25 ), 'changed' => array_slice( $verify['changed'], 0, 25 ), 'db' => $verify['db'], ), 'clone_running' => $clone_running, 'progress' => $progress, 'clone_complete' => (bool) get_option( 'wardpair_clone_complete', false ), 'is_reconnect' => (bool) get_option( 'wardpair_clone_is_reconnect', false ), ) ); } /** One line the Pairing panel can show: where the clone is, or why it is not moving. */ private function clone_progress_summary(): array { $p = Sentinel_Clone_Sync::progress_get(); if ( empty( $p['phase'] ) ) { return array( 'status' => '', 'label' => '' ); } $names = array( 'zip_build' => __( 'Building the file archive', 'wardpair' ), 'file_transfer' => __( 'Sending files', 'wardpair' ), 'db_dump' => __( 'Dumping the database', 'wardpair' ), 'db_transfer' => __( 'Sending the database', 'wardpair' ), ); $name = $names[ $p['phase'] ] ?? (string) $p['phase']; $total = (int) ( $p['total_chunks'] ?? 0 ); $cursor = (int) ( $p['cursor'] ?? 0 ); $where = ( $total > 0 && in_array( $p['phase'], array( 'file_transfer', 'db_transfer' ), true ) ) ? sprintf( /* translators: 1: chunk, 2: total */ __( ' (chunk %1$d of %2$d)', 'wardpair' ), min( $cursor + 1, $total ), $total ) : ''; $status = (string) ( $p['status'] ?? '' ); if ( 'paused' === $status ) { $label = sprintf( /* translators: 1: task name, 2: where the task stopped */ __( 'Paused: %1$s%2$s. Resume continues from here.', 'wardpair' ), $name, $where ); } elseif ( 'failed' === $status ) { $label = sprintf( /* translators: 1: task name, 2: where the task stopped, 3: extra note */ __( 'Stopped: %1$s%2$s. %3$s', 'wardpair' ), $name, $where, (string) ( $p['note'] ?? '' ) ); } elseif ( 'complete' === $status ) { $label = ''; } else { $label = sprintf( /* translators: 1: task name, 2: where the task stopped */ __( 'Running: %1$s%2$s.', 'wardpair' ), $name, $where ); } return array( 'status' => $status, 'label' => $label ); } /** Continue the clone from its last saved position. */ private function ajax_resume_clone(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } $r = Sentinel_Clone_Sync::resume( 'admin' ); if ( $r['ok'] ) { Sentinel_Core::log_event( 'clone_resumed', 'Clone resumed from saved progress by admin.' ); wp_send_json_success( array( 'message' => $r['message'] ) ); } wp_send_json_error( array( 'message' => $r['message'] ) ); } /** Files already arrived, database did not: confirm with the secondary, then send only the database. */ private function ajax_continue_db_only(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } $r = Sentinel_Clone_Sync::continue_db_only(); if ( $r['ok'] ) { wp_send_json_success( array( 'message' => $r['message'] ) ); } wp_send_json_error( array( 'message' => $r['message'] ) ); } /** Stop the queue without losing the position, so the clone can be resumed later. */ private function ajax_pause_clone(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } if ( empty( Sentinel_Clone_Sync::progress_get() ) ) { wp_send_json_error( array( 'message' => __( 'No clone is in progress.', 'wardpair' ) ) ); return; } Sentinel_Clone_Sync::pause_keep_progress(); wp_send_json_success( array( 'message' => __( 'Clone paused. Your progress is kept; use "Resume from last progress" to continue.', 'wardpair' ) ) ); } private function ajax_reset_bootstrap(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } if ( 'primary' !== get_option( 'wardpair_role' ) || ! get_option( 'wardpair_is_paired' ) ) { wp_send_json_error( array( 'message' => __( 'Not applicable — this site is not a paired primary.', 'wardpair' ) ) ); return; } update_option( 'wardpair_bootstrap_complete', true ); Sentinel_Core::log_event( 'clone_complete', 'Bootstrap manually marked complete by admin (stuck-banner override).' ); wp_send_json_success( array( 'message' => __( 'Marked as complete.', 'wardpair' ), ) ); } /** * Manual "unstick everything" button: fails every pending/in-progress * Wardpair action and resets clone/verify state on primary. For a * queue that has built up a backlog (a repair that queued far more file * pulls than the host can work through) and stopped making progress — * the same cleanup a fresh pairing runs, run on demand instead of * waiting on Tools → Scheduled Actions. */ private function ajax_reset_queue(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } global $wpdb; $group_id = $wpdb->get_var( $wpdb->prepare( "SELECT group_id FROM {$wpdb->prefix}actionscheduler_groups WHERE slug = %s", 'wardpair' ) ); $pending = $group_id ? (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE group_id = %d AND status IN ('in-progress', 'pending')", $group_id ) ) : 0; Sentinel_Clone_Sync::kill_stale_jobs(); Sentinel_Core::log_event( 'queue_reset', "Queue manually reset by admin — {$pending} pending/stuck action(s) cleared." ); wp_send_json_success( array( 'message' => sprintf( /* translators: %d: number of actions cleared */ __( 'Queue cleared — %d pending action(s) removed. Clone and repair state was reset; you can start a new one.', 'wardpair' ), $pending ), 'cleared' => $pending, ) ); } /** * Restores this secondary to exactly how it was right before it first * accepted the pairing that made it a secondary, then unpairs. For an * owner who decides they don't want to run as a secondary any more and * wants their own content back, rather than whatever the primary last * cloned onto this site. * * The restore is queued (it can be a full files+DB job) and is not * waited on here; disconnect happens immediately after queuing it, * since disconnect only clears Wardpair's own bookkeeping and * doesn't touch the filesystem or DB the restore job is about to work * on — there's nothing for the two to race over. */ private function ajax_revert_pre_clone(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wardpair' ) ) ); return; } if ( 'secondary' !== get_option( 'wardpair_role', '' ) ) { wp_send_json_error( array( 'message' => __( 'This site is not currently a secondary.', 'wardpair' ) ) ); return; } $backup_id = Sentinel_Backup::find_pre_clone_backup_id(); if ( $backup_id <= 0 ) { wp_send_json_error( array( 'message' => __( 'No pre-clone snapshot was found for this site — nothing to revert to.', 'wardpair' ) ) ); return; } // Consumed: a future re-pairing should take a fresh snapshot rather // than pointing at this one again. delete_option( 'wardpair_pre_clone_snapshot_id' ); delete_option( 'wardpair_pre_clone_snapshot_queued' ); // Disconnect FIRST. disconnect() calls Sentinel_Clone_Sync::kill_stale_jobs(), // which force-fails every pending/in-progress Action Scheduler action in the // 'wardpair' group — including a zip-restore job queued moments earlier in // the same request. Queuing the restore before disconnecting used to mean the // freshly-queued job got killed by disconnect() before it ever ran, so the // "revert" silently did nothing. Disconnecting first means kill_stale_jobs() // only ever sees genuinely old leftovers, never the job we're about to start. Sentinel_Pairing::disconnect(); $result = Sentinel_Backup::restore_with_progress( $backup_id ); // restore_with_progress() reports a queued async job as a WP_Error // whose code ends in '_queued' — that's success here, not failure; // only anything else means the restore genuinely didn't start. $queued = is_wp_error( $result ) && in_array( $result->get_error_code(), array( 'zip_queued', 'db_queued' ), true ); if ( ! $queued && is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); return; } Sentinel_Core::log_event( 'pre_clone_reverted', "Owner requested revert to the pre-clone snapshot (backup #{$backup_id}). Disconnected from primary; restore queued." ); wp_send_json_success( array( 'message' => __( 'Restore to your pre-clone content has been queued, and this site has been disconnected. Track progress in the Backups tab.', 'wardpair' ), ) ); } }