register_adapter( new AILM_Adapter_Classic() ); $this->register_adapter( new AILM_Adapter_Gutenberg() ); $this->register_adapter( new AILM_Adapter_Elementor() ); $this->register_adapter( new AILM_Adapter_Postmeta() ); $this->register_adapter( new AILM_Adapter_Nav_Menu() ); } /** * Register a content adapter. * * @param AILM_Content_Adapter $adapter Adapter instance. * @return void */ public function register_adapter( AILM_Content_Adapter $adapter ) { $this->adapters[] = $adapter; } /** * Get the registered adapters. * * Exposes the private $adapters array so other classes (e.g. the engine's * dry-run analysis) can iterate adapters without accessing the private * property directly. * * @return AILM_Content_Adapter[] */ public function get_adapters() { return $this->adapters; } /** * Hook the AJAX endpoints and cron fallback. * * Called from AILM_Core::define_admin_hooks(). * * @return void */ public static function init() { add_action( 'wp_ajax_ailm_url_rewrite_start', array( __CLASS__, 'ajax_start' ) ); add_action( 'wp_ajax_ailm_url_rewrite_status', array( __CLASS__, 'ajax_status' ) ); add_action( 'wp_ajax_ailm_url_rewrite_cancel', array( __CLASS__, 'ajax_cancel' ) ); add_action( self::CRON_HOOK, array( __CLASS__, 'cron_process_batch' ) ); add_filter( 'cron_schedules', array( __CLASS__, 'add_cron_schedule' ) ); } /** * Register the custom cron interval. * * @param array $schedules Existing schedules. * @return array */ public static function add_cron_schedule( $schedules ) { $schedules['ailm_url_rewrite_interval'] = array( 'interval' => self::CRON_INTERVAL, 'display' => __( 'AILM URL Rewrite Fallback (2 min)', 'ailinkmaster-internal-auto-manager' ), ); return $schedules; } // ========================================================================= // AJAX endpoints // ========================================================================= /** * AJAX: start the rewrite process. * * @return void */ public static function ajax_start() { check_ajax_referer( 'ailm_url_migrator_nonce', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( __( 'Permission denied.', 'ailinkmaster-internal-auto-manager' ) ); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended $batch_id = isset( $_POST['batch_id'] ) ? sanitize_text_field( wp_unslash( $_POST['batch_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $mapping = isset( $_POST['mapping'] ) ? (array) wp_unslash( $_POST['mapping'] ) : array(); if ( empty( $batch_id ) || empty( $mapping ) ) { wp_send_json_error( __( 'Missing batch_id or mapping.', 'ailinkmaster-internal-auto-manager' ) ); } // Sanitize mapping keys/values as URLs. $clean_mapping = array(); foreach ( $mapping as $old => $new ) { $clean_mapping[ esc_url_raw( $old ) ] = esc_url_raw( $new ); } if ( self::is_running() ) { wp_send_json_error( __( 'Rewrite is already running.', 'ailinkmaster-internal-auto-manager' ) ); } self::start_rewrite( $batch_id, $clean_mapping ); wp_send_json_success( array( 'message' => __( 'Rewrite started.', 'ailinkmaster-internal-auto-manager' ) ) ); } /** * AJAX: get current status AND process one batch. * * @return void */ public static function ajax_status() { check_ajax_referer( 'ailm_url_migrator_nonce', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( __( 'Permission denied.', 'ailinkmaster-internal-auto-manager' ) ); } if ( self::is_running() && ! self::is_batch_locked() ) { self::process_batch(); } wp_send_json_success( self::get_status() ); } /** * AJAX: cancel a running rewrite. * * @return void */ public static function ajax_cancel() { check_ajax_referer( 'ailm_url_migrator_nonce', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( __( 'Permission denied.', 'ailinkmaster-internal-auto-manager' ) ); } if ( ! self::is_running() ) { wp_send_json_error( __( 'No rewrite is currently running.', 'ailinkmaster-internal-auto-manager' ) ); } self::cancel_rewrite(); wp_send_json_success( array( 'message' => __( 'Rewrite cancelled.', 'ailinkmaster-internal-auto-manager' ) ) ); } // ========================================================================= // State management // ========================================================================= /** * Start the rewrite: count posts, set options. * * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @return void */ public static function start_rewrite( $batch_id, $mapping ) { global $wpdb; $allowed_types = get_option( 'ailm_allowed_post_types', array( 'post', 'page' ) ); $type_placeholders = implode( ',', array_fill( 0, count( $allowed_types ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $total_posts = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type IN ($type_placeholders) AND post_status = 'publish'", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $allowed_types ) ); update_option( 'ailm_url_rewrite_batch_id', $batch_id ); update_option( 'ailm_url_rewrite_mapping', $mapping ); update_option( 'ailm_url_rewrite_last_post_id', 0 ); update_option( 'ailm_url_rewrite_total_posts', $total_posts ); update_option( 'ailm_url_rewrite_processed_posts', 0 ); update_option( 'ailm_url_rewrite_changed_posts', 0 ); update_option( 'ailm_url_rewrite_running', 'yes' ); update_option( 'ailm_url_rewrite_status_text', __( 'Rewriting URLs in content...', 'ailinkmaster-internal-auto-manager' ) ); update_option( 'ailm_url_rewrite_last_heartbeat', time() ); delete_option( 'ailm_url_rewrite_batch_lock' ); self::schedule_cron_fallback(); } /** * Check if rewrite is currently running. * * @return bool */ public static function is_running() { return get_option( 'ailm_url_rewrite_running', 'no' ) === 'yes'; } /** * Get current status for UI polling. * * @return array */ public static function get_status() { $total = (int) get_option( 'ailm_url_rewrite_total_posts', 0 ); $processed = (int) get_option( 'ailm_url_rewrite_processed_posts', 0 ); $changed = (int) get_option( 'ailm_url_rewrite_changed_posts', 0 ); $running = self::is_running(); $percent = $total > 0 ? round( ( $processed / $total ) * 100 ) : 0; return array( 'running' => $running, 'total_posts' => $total, 'processed_posts' => $processed, 'changed_posts' => $changed, 'percent' => $percent, 'status_text' => get_option( 'ailm_url_rewrite_status_text', '' ), ); } /** * Check if a batch is currently being processed (lock active). * * @return bool */ private static function is_batch_locked() { $lock = (int) get_option( 'ailm_url_rewrite_batch_lock', 0 ); if ( 0 === $lock ) { return false; } if ( ( time() - $lock ) > self::LOCK_TIMEOUT ) { delete_option( 'ailm_url_rewrite_batch_lock' ); return false; } return true; } /** * Acquire the batch lock. * * @return bool */ private static function acquire_batch_lock() { if ( self::is_batch_locked() ) { return false; } update_option( 'ailm_url_rewrite_batch_lock', time() ); return true; } /** * Release the batch lock. * * @return void */ private static function release_batch_lock() { delete_option( 'ailm_url_rewrite_batch_lock' ); } // ========================================================================= // Batch processing // ========================================================================= /** * Process one batch of posts: rewrite URLs via adapters. * * @return void */ public static function process_batch() { if ( ! self::acquire_batch_lock() ) { return; } global $wpdb; $rewriter = self::instance(); $batch_id = get_option( 'ailm_url_rewrite_batch_id', '' ); $mapping = get_option( 'ailm_url_rewrite_mapping', array() ); $last_id = (int) get_option( 'ailm_url_rewrite_last_post_id', 0 ); $batch_size = (int) apply_filters( 'ailm_url_migrator_batch_size', self::BATCH_SIZE ); $allowed_types = get_option( 'ailm_allowed_post_types', array( 'post', 'page' ) ); $type_placeholders = implode( ',', array_fill( 0, count( $allowed_types ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $posts = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_type IN ($type_placeholders) AND post_status = 'publish' AND ID > %d ORDER BY ID ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared array_merge( $allowed_types, array( $last_id, $batch_size ) ) ) ); if ( empty( $posts ) ) { self::release_batch_lock(); self::complete_rewrite(); return; } $changed_this_batch = 0; $processed_this_batch = 0; $batch_start = microtime( true ); // Track the last post ID that was actually processed (rewritten or // attempted). The post where the time-guard break fires must NOT be // recorded as last_id, otherwise it is skipped forever (next batch // starts at ID > last_id). $last_processed_id = $last_id; foreach ( $posts as $p ) { // Time guard — check BEFORE processing so an unprocessed post is // not recorded as the checkpoint. if ( ( microtime( true ) - $batch_start ) > self::TIME_LIMIT_SECONDS ) { break; } if ( $rewriter->rewrite_post( $p->ID, $batch_id, $mapping ) ) { $changed_this_batch++; } $last_processed_id = $p->ID; $processed_this_batch++; } // Update progress — use the actual count processed, not the batch size. $processed = (int) get_option( 'ailm_url_rewrite_processed_posts', 0 ) + $processed_this_batch; $changed = (int) get_option( 'ailm_url_rewrite_changed_posts', 0 ) + $changed_this_batch; $total = (int) get_option( 'ailm_url_rewrite_total_posts', 1 ); $percent = $total > 0 ? round( ( $processed / $total ) * 100 ) : 0; update_option( 'ailm_url_rewrite_last_post_id', $last_processed_id ); update_option( 'ailm_url_rewrite_processed_posts', $processed ); update_option( 'ailm_url_rewrite_changed_posts', $changed ); update_option( 'ailm_url_rewrite_status_text', sprintf( /* translators: 1: processed, 2: total, 3: changed */ __( 'Rewriting: %1$d / %2$d posts (%3$d changed)', 'ailinkmaster-internal-auto-manager' ), $processed, $total, $changed ) ); update_option( 'ailm_url_rewrite_last_heartbeat', time() ); self::release_batch_lock(); } /** * Rewrite URLs in a single post using the applicable adapters. * * For each adapter that supports the post: * 1. Call replace_urls() to get the new content. * 2. If changed, back up old + new (with hash) to wp_ailm_url_backup. * 3. Persist via the adapter. * * @param int $post_id Post ID. * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @return bool True if any changes were made. */ public function rewrite_post( $post_id, $batch_id, $mapping ) { $changed = false; foreach ( $this->adapters as $adapter ) { // Nav menu adapter is invoked separately (not per-post). if ( $adapter instanceof AILM_Adapter_Nav_Menu ) { continue; } // Postmeta adapter is gated by the "process postmeta" option. if ( $adapter instanceof AILM_Adapter_Postmeta ) { if ( ! get_option( 'ailm_url_migrator_process_postmeta', 0 ) ) { continue; } } if ( ! $adapter->supports( 'post', $post_id ) ) { continue; } // Determine the field name and old value for backup based on // the adapter type. Classic/Gutenberg/Elementor rewrite // post_content (or _elementor_data); Postmeta returns a JSON // summary of meta changes. if ( $adapter instanceof AILM_Adapter_Postmeta ) { $field_name = '_postmeta_json'; $old_value = null; // Postmeta old values are inside the JSON. } elseif ( $adapter instanceof AILM_Adapter_Elementor ) { $field_name = '_elementor_data'; $old_value = get_post_meta( $post_id, '_elementor_data', true ); } else { // Classic / Gutenberg — post_content. $field_name = 'post_content'; $post = get_post( $post_id ); $old_value = $post ? $post->post_content : ''; } $new_value = $adapter->replace_urls( 'post', $post_id, $mapping ); if ( null === $new_value ) { continue; // No changes from this adapter. } // Back up old + new (with hash) for safe rollback. AILM_URL_Redirect_DB::add_backup_row( $batch_id, 'post', $post_id, $field_name, $old_value, $new_value, 'info', 'URL rewrite' ); // Persist via the adapter (direct SQL, no wp_update_post storm). $adapter->persist( 'post', $post_id, $new_value ); $changed = true; } return $changed; } /** * Rewrite URLs in all nav menus (called once by the engine, not per-post). * * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @return int Number of changed menu items. */ public function rewrite_nav_menus( $batch_id, $mapping ) { foreach ( $this->adapters as $adapter ) { if ( $adapter instanceof AILM_Adapter_Nav_Menu ) { $summary = $adapter->replace_urls( 'nav_menu', 0, $mapping ); if ( null === $summary ) { return 0; } // Back up the summary for rollback. AILM_URL_Redirect_DB::add_backup_row( $batch_id, 'nav_menu', 0, '_menu_item_url', null, $summary, 'info', 'Nav menu URL rewrite' ); $adapter->persist( 'nav_menu', 0, $summary ); $changes = json_decode( $summary, true ); return is_array( $changes ) ? count( $changes ) : 0; } } return 0; } /** * Complete the rewrite: clean up. * * @return void */ private static function complete_rewrite() { $changed = (int) get_option( 'ailm_url_rewrite_changed_posts', 0 ); update_option( 'ailm_url_rewrite_running', 'no' ); update_option( 'ailm_url_rewrite_status_text', sprintf( /* translators: 1: changed post count */ __( 'Rewrite complete: %d posts changed.', 'ailinkmaster-internal-auto-manager' ), $changed ) ); delete_option( 'ailm_url_rewrite_batch_lock' ); delete_option( 'ailm_url_rewrite_mapping' ); self::clear_cron_fallback(); // Purge page caches. self::purge_page_caches(); do_action( 'ailm_url_rewrite_completed', get_option( 'ailm_url_rewrite_batch_id', '' ) ); } /** * Cancel a running rewrite and clean up. * * @return void */ public static function cancel_rewrite() { update_option( 'ailm_url_rewrite_running', 'no' ); update_option( 'ailm_url_rewrite_status_text', __( 'Rewrite cancelled by user.', 'ailinkmaster-internal-auto-manager' ) ); delete_option( 'ailm_url_rewrite_batch_lock' ); delete_option( 'ailm_url_rewrite_mapping' ); self::clear_cron_fallback(); } /** * Purge common page caches after rewriting content. * * @return void */ private static function purge_page_caches() { // WP Rocket. if ( function_exists( 'rocket_clean_domain' ) ) { rocket_clean_domain(); } // LiteSpeed. if ( did_action( 'litespeed_init' ) || class_exists( 'LiteSpeed\Purge' ) ) { do_action( 'litespeed_purge_all' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound } // W3 Total Cache. if ( function_exists( 'w3tc_flush_all' ) ) { w3tc_flush_all(); } } // ========================================================================= // CRON FALLBACK // ========================================================================= /** * Schedule the recurring cron fallback. * * @return void */ private static function schedule_cron_fallback() { if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_event( time() + self::CRON_INTERVAL, 'ailm_url_rewrite_interval', self::CRON_HOOK ); } } /** * Clear the cron fallback event. * * @return void */ private static function clear_cron_fallback() { $timestamp = wp_next_scheduled( self::CRON_HOOK ); if ( $timestamp ) { wp_unschedule_event( $timestamp, self::CRON_HOOK ); } wp_clear_scheduled_hook( self::CRON_HOOK ); } /** * Cron callback: process one batch if the rewrite is running. * * @return void */ public static function cron_process_batch() { if ( ! self::is_running() ) { self::clear_cron_fallback(); return; } if ( self::is_batch_locked() ) { return; } self::process_batch(); } }