new_url ]. * @type array $by_post [ post_id => [ 'old' => url, 'new' => url ] ]. * @type array $warnings List of warning messages. * } */ public static function build_post_mapping( $post_ids ) { $warnings = array(); $mapping = array(); $by_post = array(); if ( empty( $post_ids ) ) { return array( 'mapping' => array(), 'by_post' => array(), 'warnings' => $warnings ); } // Old URLs under the snapshot structure. $old_urls = AILM_URL_Snapshot::compute_old_post_urls( $post_ids ); // New URLs under the live structure (current get_permalink). foreach ( $post_ids as $pid ) { $pid = (int) $pid; $new_url = get_permalink( $pid ); if ( ! $new_url || is_wp_error( $new_url ) ) { $warnings[] = sprintf( /* translators: %d: post ID */ __( 'Post %d: could not compute new URL — skipped.', 'ailinkmaster-internal-auto-manager' ), $pid ); continue; } if ( ! isset( $old_urls[ $pid ] ) ) { $warnings[] = sprintf( /* translators: %d: post ID */ __( 'Post %d: could not compute old URL — skipped.', 'ailinkmaster-internal-auto-manager' ), $pid ); continue; } $old_url = $old_urls[ $pid ]; if ( $old_url === $new_url ) { continue; // No change for this post. } $mapping[ $old_url ] = $new_url; $by_post[ $pid ] = array( 'old' => $old_url, 'new' => $new_url ); } return array( 'mapping' => $mapping, 'by_post' => $by_post, 'warnings' => $warnings ); } /** * Build the old_url → new_url mapping for a batch of terms. * * @param array $term_ids Term IDs to map. * @return array Same shape as build_post_mapping(). */ public static function build_term_mapping( $term_ids ) { $warnings = array(); $mapping = array(); $by_term = array(); if ( empty( $term_ids ) ) { return array( 'mapping' => array(), 'by_term' => array(), 'warnings' => $warnings ); } $old_urls = AILM_URL_Snapshot::compute_old_term_urls( $term_ids ); foreach ( $term_ids as $tid ) { $tid = (int) $tid; $new_url = get_term_link( $tid ); if ( ! $new_url || is_wp_error( $new_url ) ) { $warnings[] = sprintf( /* translators: %d: term ID */ __( 'Term %d: could not compute new URL — skipped.', 'ailinkmaster-internal-auto-manager' ), $tid ); continue; } if ( ! isset( $old_urls[ $tid ] ) ) { continue; } $old_url = $old_urls[ $tid ]; if ( $old_url === $new_url ) { continue; } $mapping[ $old_url ] = $new_url; $by_term[ $tid ] = array( 'old' => $old_url, 'new' => $new_url ); } return array( 'mapping' => $mapping, 'by_term' => $by_term, 'warnings' => $warnings ); } // ========================================================================= // Step 3: Dry Run // ========================================================================= /** * Run a dry-run analysis and return a report without writing anything. * * @return array { * @type string $old_structure Old permalink structure. * @type string $new_structure New permalink structure. * @type array $redirects { @type int $posts, @type int $pages, @type int $terms, @type int $total } * @type array $content { @type int $classic, @type int $gutenberg, @type int $elementor, @type int $nav_menu, @type int $postmeta, @type int $total } * @type array $plugin_db { @type int $rules, @type int $links } * @type array $warnings List of warning messages. * @type array $mapping The full old_url => new_url mapping. * } */ public static function dry_run() { $snapshot = AILM_URL_Snapshot::get(); $old_structure = $snapshot ? $snapshot['structure'] : ''; $new_structure = (string) get_option( 'permalink_structure' ); // Collect all published post IDs. $allowed_types = get_option( 'ailm_allowed_post_types', array( 'post', 'page' ) ); $post_ids = get_posts( array( 'numberposts' => -1, 'post_type' => $allowed_types, 'post_status' => 'publish', 'fields' => 'ids', ) ); // Split by type for the report. $post_count = 0; $page_count = 0; foreach ( $post_ids as $pid ) { $type = get_post_type( $pid ); if ( 'page' === $type ) { $page_count++; } else { $post_count++; } } // Build post mapping. $post_result = self::build_post_mapping( $post_ids ); // Terms (optional, on by default). $term_count = 0; $term_mapping = array(); if ( get_option( 'ailm_url_migrator_process_terms', 1 ) ) { $terms = get_terms( array( 'taxonomy' => array( 'category', 'post_tag' ), 'hide_empty' => false, 'fields' => 'ids', ) ); if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { $term_count = count( $terms ); $term_result = self::build_term_mapping( $terms ); $term_mapping = $term_result['mapping']; $post_result['warnings'] = array_merge( $post_result['warnings'], $term_result['warnings'] ); } } $full_mapping = array_merge( $post_result['mapping'], $term_mapping ); // Count content that would be affected (if rewriting is enabled). $content_counts = array( 'classic' => 0, 'gutenberg' => 0, 'elementor' => 0, 'nav_menu' => 0, 'postmeta' => 0, 'total' => 0, ); if ( get_option( 'ailm_url_migrator_rewrite_content', 0 ) ) { $rewriter = AILM_URL_Content_Rewriter::instance(); $adapters = $rewriter->get_adapters(); foreach ( $post_ids as $pid ) { foreach ( $adapters as $adapter ) { if ( $adapter instanceof AILM_Adapter_Nav_Menu ) { continue; } if ( $adapter instanceof AILM_Adapter_Postmeta && ! get_option( 'ailm_url_migrator_process_postmeta', 0 ) ) { continue; } if ( $adapter->supports( 'post', $pid ) ) { if ( $adapter instanceof AILM_Adapter_Classic ) { $content_counts['classic']++; } elseif ( $adapter instanceof AILM_Adapter_Gutenberg ) { $content_counts['gutenberg']++; } elseif ( $adapter instanceof AILM_Adapter_Elementor ) { $content_counts['elementor']++; } elseif ( $adapter instanceof AILM_Adapter_Postmeta ) { $content_counts['postmeta']++; } $content_counts['total']++; break; // one adapter per post } } } // Nav menu count. $nav_adapter = new AILM_Adapter_Nav_Menu(); $nav_urls = $nav_adapter->extract_urls( 'nav_menu', 0 ); $content_counts['nav_menu'] = count( $nav_urls ); } // Plugin DB counts. $rules_count = 0; $links_count = 0; if ( class_exists( 'AILM_Link_DB' ) ) { global $wpdb; $rules_table = AILM_Link_DB::get_rules_table(); $links_table = AILM_Link_DB::get_links_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $rules_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$rules_table}" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $links_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$links_table}" ); } // Warnings about rules with target_id=0. $warnings = $post_result['warnings']; if ( $rules_count > 0 && class_exists( 'AILM_Link_DB' ) ) { global $wpdb; $rules_table = AILM_Link_DB::get_rules_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $zero_target = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$rules_table} WHERE target_id = 0" ); if ( $zero_target > 0 ) { $warnings[] = sprintf( /* translators: %d: rule count */ __( '%d rules with target_id=0 — will be updated by URL match instead of ID.', 'ailinkmaster-internal-auto-manager' ), $zero_target ); } } return array( 'old_structure' => $old_structure, 'new_structure' => $new_structure, 'redirects' => array( 'posts' => $post_count, 'pages' => $page_count, 'terms' => $term_count, 'total' => $post_count + $page_count + $term_count, ), 'content' => $content_counts, 'plugin_db' => array( 'rules' => $rules_count, 'links' => $links_count, ), 'warnings' => $warnings, 'mapping' => $full_mapping, ); } // ========================================================================= // Step 4–10: Run migration // ========================================================================= /** * Run the full migration pipeline. * * This is the synchronous part (redirects + DB update + validate + commit). * Content rewriting is async (handled by AILM_URL_Content_Rewriter). * * @param array $args { * @type bool $rewrite_content Whether to rewrite content (starts async). * @type bool $process_terms Whether to process terms. * @type int $redirect_type 301 or 302. * } * @return array { * @type string $batch_id Migration batch ID. * @type int $redirects Number of redirects created. * @type int $db_updated Number of plugin DB rows updated. * @type array $warnings List of warnings. * @type array $validation Validation results. * } */ public static function run_migration( $args = array() ) { $batch_id = self::generate_batch_id(); $rewrite_content = ! empty( $args['rewrite_content'] ); $process_terms = isset( $args['process_terms'] ) ? $args['process_terms'] : (bool) get_option( 'ailm_url_migrator_process_terms', 1 ); $redirect_type = isset( $args['redirect_type'] ) ? (int) $args['redirect_type'] : 301; $warnings = array(); $redirects_created = 0; $db_updated = 0; // --- Step 2: Build mapping --- $allowed_types = get_option( 'ailm_allowed_post_types', array( 'post', 'page' ) ); $post_ids = get_posts( array( 'numberposts' => -1, 'post_type' => $allowed_types, 'post_status' => 'publish', 'fields' => 'ids', ) ); $post_result = self::build_post_mapping( $post_ids ); $mapping = $post_result['mapping']; $warnings = $post_result['warnings']; if ( $process_terms ) { $terms = get_terms( array( 'taxonomy' => array( 'category', 'post_tag' ), 'hide_empty' => false, 'fields' => 'ids', ) ); if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { $term_result = self::build_term_mapping( $terms ); $mapping = array_merge( $mapping, $term_result['mapping'] ); $warnings = array_merge( $warnings, $term_result['warnings'] ); } } if ( empty( $mapping ) ) { return array( 'batch_id' => $batch_id, 'redirects' => 0, 'db_updated' => 0, 'warnings' => array( __( 'No URL changes detected — nothing to migrate.', 'ailinkmaster-internal-auto-manager' ) ), 'validation' => array(), ); } // --- Step 4: Backup plugin DB + old permalink structure --- self::backup_plugin_db( $batch_id, $mapping ); self::backup_permalink_structure( $batch_id ); // --- Step 5: Create redirects (with compression + cycle blocking) --- $redirects_created = self::create_redirects( $batch_id, $mapping, $post_result['by_post'], $redirect_type ); // --- Step 6: Update plugin DB (bulk mode, Reconciler disabled) --- self::disable_reconciler_and_bulk_mode(); $db_updated = self::update_plugin_db( $batch_id, $mapping ); self::enable_reconciler_and_bulk_mode(); // --- Step 7: Rewrite content (async) --- if ( $rewrite_content ) { // Enrich the mapping with bare-slug → current-permalink entries so that // links in content that use a bare-slug format (e.g. /post-slug/) are also // rewritten to the current permalink structure. The base mapping only // contains old-structure → new-structure URLs; content may contain links // in a third format (bare slug) that would otherwise be missed. $content_mapping = self::enrich_mapping_for_content( $mapping, $post_ids ); AILM_URL_Content_Rewriter::start_rewrite( $batch_id, $content_mapping ); // Also rewrite nav menus synchronously (small, fast). AILM_URL_Content_Rewriter::instance()->rewrite_nav_menus( $batch_id, $content_mapping ); } // --- Step 9: Validate --- $validation = self::validate( $mapping ); // --- Step 10: Commit --- self::commit( $batch_id ); return array( 'batch_id' => $batch_id, 'redirects' => $redirects_created, 'db_updated' => $db_updated, 'warnings' => $warnings, 'validation' => $validation, ); } /** * Back up the plugin's link rules and links (target_url) before updating. * * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @return void */ private static function backup_plugin_db( $batch_id, $mapping ) { if ( ! class_exists( 'AILM_Link_DB' ) ) { return; } global $wpdb; $rules_table = AILM_Link_DB::get_rules_table(); // Back up rules whose target_url matches any old URL in the mapping. $old_urls = array_keys( $mapping ); if ( empty( $old_urls ) ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $rules = $wpdb->get_results( $wpdb->prepare( "SELECT id, target_url FROM {$rules_table} WHERE target_url IN (" . implode( ',', array_fill( 0, count( $old_urls ), '%s' ) ) . ")", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $old_urls ) ); foreach ( $rules as $rule ) { $new_url = isset( $mapping[ $rule->target_url ] ) ? $mapping[ $rule->target_url ] : $rule->target_url; AILM_URL_Redirect_DB::add_backup_row( $batch_id, 'link_rules', (int) $rule->id, 'target_url', $rule->target_url, $new_url, 'info', 'Plugin rule target_url backup' ); } } /** * Back up the current (old) permalink structure before commit() overwrites * the snapshot. This allows rollback to restore the old structure. * * @param string $batch_id Migration batch ID. * @return void */ private static function backup_permalink_structure( $batch_id ) { $snapshot = AILM_URL_Snapshot::get(); if ( ! $snapshot ) { return; } $old_structure = wp_json_encode( $snapshot ); $new_structure = wp_json_encode( array( 'structure' => (string) get_option( 'permalink_structure' ), 'category_base' => (string) get_option( 'category_base' ), 'tag_base' => (string) get_option( 'tag_base' ), ) ); AILM_URL_Redirect_DB::add_backup_row( $batch_id, 'option', 0, 'permalink_structure', $old_structure, $new_structure, 'info', 'Permalink structure backup for rollback' ); } /** * Create 301 redirects for every old_url → new_url in the mapping. * * Uses AILM_URL_Redirect_DB::upsert_redirect() which enforces chain * compression and cycle blocking (architecture doc §6). * * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @param array $by_post [ post_id => [ 'old' => url, 'new' => url ] ]. * @param int $redirect_type HTTP status (301/302). * @return int Number of redirects created. */ private static function create_redirects( $batch_id, $mapping, $by_post, $redirect_type ) { $count = 0; // Post redirects — attach post_id. foreach ( $by_post as $post_id => $urls ) { $result = AILM_URL_Redirect_DB::upsert_redirect( $urls['old'], $urls['new'], array( 'post_id' => $post_id, 'object_type' => 'post', 'redirect_type' => $redirect_type, 'migration_batch' => $batch_id, ) ); if ( ! is_wp_error( $result ) ) { $count++; } } // Term redirects (and any mapping entries not in by_post). foreach ( $mapping as $old => $new ) { // Skip if already created as a post redirect. $already = false; foreach ( $by_post as $urls ) { if ( $urls['old'] === $old ) { $already = true; break; } } if ( $already ) { continue; } $result = AILM_URL_Redirect_DB::upsert_redirect( $old, $new, array( 'object_type' => 'term', 'redirect_type' => $redirect_type, 'migration_batch' => $batch_id, ) ); if ( ! is_wp_error( $result ) ) { $count++; } } return $count; } /** * Update the plugin's link rules and links tables with new target URLs. * * Uses direct SQL (bulk) for performance. Reconciler is disabled and * bulk mode is on (caller's responsibility). * * @param string $batch_id Migration batch ID. * @param array $mapping [ old_url => new_url ]. * @return int Number of rows updated. */ private static function update_plugin_db( $batch_id, $mapping ) { if ( ! class_exists( 'AILM_Link_DB' ) ) { return 0; } global $wpdb; $rules_table = AILM_Link_DB::get_rules_table(); $links_table = AILM_Link_DB::get_links_table(); $updated = 0; foreach ( $mapping as $old => $new ) { // Update rules.target_url. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $r = $wpdb->query( $wpdb->prepare( "UPDATE {$rules_table} SET target_url = %s WHERE target_url = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $new, $old ) ); if ( false !== $r ) { $updated += $r; } // Update links.url. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $l = $wpdb->query( $wpdb->prepare( "UPDATE {$links_table} SET url = %s WHERE url = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $new, $old ) ); if ( false !== $l ) { $updated += $l; } } // Invalidate plugin caches. if ( class_exists( 'AILM_Link_Repository' ) ) { AILM_Link_Repository::invalidate_cache(); } return $updated; } /** * Validate the migration using DB-only checks (architecture doc §11). * * @param array $mapping [ old_url => new_url ]. * @return array { * @type int $redirects_exist Number of old URLs with a redirect. * @type int $targets_published Number of new URLs resolving to a published post. * @type int $cycles Number of cycles detected (should be 0). * @type int $duplicates Number of duplicate from_urls (should be 0). * } */ public static function validate( $mapping ) { $redirects_exist = 0; $targets_published = 0; $cycles = 0; foreach ( $mapping as $old => $new ) { $redirect = AILM_URL_Redirect_DB::get_redirect( $old ); if ( $redirect ) { $redirects_exist++; // Check target is published/reachable. // // url_to_postid() only resolves post/page URLs — it returns 0 // for term archive URLs, which would undercount // targets_published. Use the redirect's stored object_type and // post_id when available; fall back to url_to_postid() for // rows without metadata. $is_published = false; if ( ! empty( $redirect->post_id ) && 'post' === $redirect->object_type ) { $is_published = 'publish' === get_post_status( (int) $redirect->post_id ); } elseif ( 'term' === $redirect->object_type && ! empty( $redirect->post_id ) ) { // post_id stores the term ID for term redirects. $term = get_term( (int) $redirect->post_id ); $is_published = ( $term && ! is_wp_error( $term ) ); } else { $target_id = url_to_postid( $new ); $is_published = ( $target_id && 'publish' === get_post_status( $target_id ) ); } if ( $is_published ) { $targets_published++; } // Check for cycle (to_url redirects back to from_url). $back = AILM_URL_Redirect_DB::get_redirect( $redirect->to_url ); if ( $back && $back->to_url === $old ) { $cycles++; } } } // Duplicate from_urls check. $duplicates = 0; if ( class_exists( 'AILM_URL_Redirect_DB' ) ) { global $wpdb; $table = AILM_URL_Redirect_DB::get_redirects_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $dup_rows = $wpdb->get_results( "SELECT from_url, COUNT(*) AS cnt FROM {$table} WHERE status = 'active' GROUP BY from_url HAVING cnt > 1" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared ); $duplicates = is_array( $dup_rows ) ? count( $dup_rows ) : 0; } return array( 'redirects_exist' => $redirects_exist, 'targets_published' => $targets_published, 'cycles' => $cycles, 'duplicates' => $duplicates, ); } /** * Enrich the URL mapping for content rewriting. * * The base mapping (from build_post_mapping) only contains old-structure → * new-structure URLs. However, post content may contain internal links in * other formats — most commonly bare-slug links (e.g. /post-slug/) that * don't include the category/author/date segments. These links would never * match the base mapping and would be left unrewritten, causing 404s after * the permalink structure changes. * * This method adds bare-slug → current-permalink entries for every published * post, so the content rewriter can catch and fix those links too. * * @param array $mapping The base mapping [ old_url => new_url ]. * @param array $post_ids List of post IDs included in the migration. * @return array Enriched mapping with bare-slug entries added. */ private static function enrich_mapping_for_content( $mapping, $post_ids ) { $home = home_url(); foreach ( $post_ids as $post_id ) { $post = get_post( $post_id ); if ( ! $post || empty( $post->post_name ) ) { continue; } $permalink = get_permalink( $post_id ); if ( ! $permalink ) { continue; } $perm_path = wp_parse_url( $permalink, PHP_URL_PATH ); if ( ! $perm_path ) { continue; } // Bare-slug path: /post-slug $bare_path = '/' . $post->post_name; // Only add if the bare slug differs from the current permalink path // (if they're the same, the link is already correct). if ( rtrim( $bare_path, '/' ) === rtrim( $perm_path, '/' ) ) { continue; } $perm_path_no_ts = rtrim( $perm_path, '/' ); $bare_path_no_ts = rtrim( $bare_path, '/' ); // Path-only (no trailing slash). $mapping[ $bare_path_no_ts ] = $perm_path_no_ts; // Path-only WITH trailing slash. $mapping[ $bare_path_no_ts . '/' ] = $perm_path_no_ts . '/'; // Absolute URL (no trailing slash). $mapping[ $home . $bare_path_no_ts ] = $home . $perm_path_no_ts; // Absolute URL WITH trailing slash. $mapping[ $home . $bare_path_no_ts . '/' ] = $home . $perm_path_no_ts . '/'; } return $mapping; } /** * Commit the migration: capture new snapshot, sync SaaS, purge caches. * * @param string $batch_id Migration batch ID. * @return void */ private static function commit( $batch_id ) { // Capture the new (current) structure as the baseline snapshot. AILM_URL_Snapshot::capture_current(); // Purge page caches. if ( function_exists( 'rocket_clean_domain' ) ) { rocket_clean_domain(); } if ( did_action( 'litespeed_init' ) || class_exists( 'LiteSpeed\Purge' ) ) { do_action( 'litespeed_purge_all' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound } if ( function_exists( 'w3tc_flush_all' ) ) { w3tc_flush_all(); } // Fire completion action for integrations. do_action( 'ailm_url_migration_completed', $batch_id ); } /** * Disable the Reconciler and enable bulk mode (architecture doc §7). * * @return void */ private static function disable_reconciler_and_bulk_mode() { if ( class_exists( 'AILM_Reconciler' ) ) { AILM_Reconciler::disable(); } if ( class_exists( 'AILM_Link_Repository' ) ) { AILM_Link_Repository::set_bulk_mode( true ); } } /** * Re-enable the Reconciler and disable bulk mode. * * @return void */ private static function enable_reconciler_and_bulk_mode() { if ( class_exists( 'AILM_Reconciler' ) ) { AILM_Reconciler::enable(); } if ( class_exists( 'AILM_Link_Repository' ) ) { AILM_Link_Repository::set_bulk_mode( false ); AILM_Link_Repository::invalidate_cache(); } } }