timestamp <= $at && $event->timestamp >= $earliest ) { return true; } if ( ! wp_schedule_single_event( $at, $hook ) ) { // WordPress deduplicates single events within ten minutes of each other. $existing = wp_next_scheduled( $hook ); return $existing && $existing <= $at + 10 * MINUTE_IN_SECONDS; } if ( ! wp_get_scheduled_event( $hook, array(), $at ) ) { return false; } if ( $event ) { wp_unschedule_event( $event->timestamp, $hook ); } return true; } /** Initialize independently of the release number; an aborted upgrade retains its original baseline. */ function ai4seo_get_taxonomy_cadence(): ?array { $cadence = get_option( AI4SEO_TAXONOMY_CADENCE_OPTION, false ); if ( false === $cadence ) { add_option( AI4SEO_TAXONOMY_CADENCE_OPTION, array( 'installed' => time(), 'next' => 0, 'last' => '', ), '', false ); $cadence = get_option( AI4SEO_TAXONOMY_CADENCE_OPTION ); } return is_array( $cadence ) && is_int( $cadence['installed'] ?? null ) && $cadence['installed'] > 0 && is_int( $cadence['next'] ?? null ) && $cadence['next'] >= 0 && in_array( $cadence['last'] ?? null, array( '', 'audit', 'changes' ), true ) ? $cadence : null; } /** * A completed 2.6.3 checkpoint receives a full quiet week starting at upgrade. * * @param array $progress Durable inventory checkpoint. * @param array $cadence Site-local scheduler state. */ function ai4seo_taxonomy_audit_due( array $progress, array $cadence ): int { return 'completed' === ( $progress['phase'] ?? '' ) ? ( $progress['last_full'] ?? $cadence['installed'] ) + WEEK_IN_SECONDS : ( $progress['retry_at'] ?? 0 ); } /** * Find bounded pending work using the option-name index. Each row has its own revision. * * @param bool $ready Return only work whose retry delay has elapsed. * @param int $limit Maximum rows to read. */ function ai4seo_taxonomy_work_names( bool $ready, int $limit ): ?array { global $wpdb; $like = $wpdb->esc_like( AI4SEO_TAXONOMY_WORK_PREFIX ) . '%'; // phpcs:disable WordPress.DB.DirectDatabaseQuery -- Indexed, uncached work admission must see concurrent writers. if ( $ready ) { $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_value < %s ORDER BY option_name LIMIT %d", $like, sprintf( '%010d', time() + 1 ), $limit ) ); } else { $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d", $like, $limit ) ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery return $wpdb->last_error ? null : $names; } /** * Schedule the surviving release single at the next useful deadline. * * @param bool $repair Whether background admission should also check a parked queue. */ function ai4seo_schedule_legacy_taxonomy_continuation( bool $repair = true ): bool { $short = time() + AI4SEO_TAXONOMY_BATCH_INTERVAL; $progress = get_option( AI4SEO_TAXONOMY_PROXY_SYNC_OPTION_NAME, array() ); $cadence = ai4seo_get_taxonomy_cadence(); $hook = 'ai4seo_taxonomy_proxy_sync_continue'; $existing = wp_next_scheduled( $hook ); $can_wait = $cadence && ai4seo_is_valid_taxonomy_proxy_sync_progress( $progress ) && 'completed' === $progress['phase'] && empty( $progress['pending_delete'] ) && empty( $progress['post_issues_pending'] ); $audit_at = $can_wait ? max( $short, ai4seo_taxonomy_audit_due( $progress, $cadence ) ) : $short; if ( ! $repair && $audit_at > $short && $existing > $short && abs( $existing - $audit_at ) <= 10 * MINUTE_IN_SECONDS ) { return true; } $idle = $can_wait && array() === ai4seo_taxonomy_work_names( false, 1 ); $at = $idle ? $audit_at : $short; if ( ! ai4seo_schedule_taxonomy_event( $hook, $at, $idle ? $at : 0 ) ) { return false; } // A producer may have seen the old short event just before we moved it to the weekly deadline. if ( $at > $short && $at !== $existing && wp_next_scheduled( $hook ) !== $existing && array() !== ai4seo_taxonomy_work_names( false, 1 ) ) { return ai4seo_schedule_taxonomy_event( $hook, $short ); } return true; } /** Let the retained release schedule dispatch eligible work while its replacement is unavailable. */ function ai4seo_dispatch_legacy_taxonomy_event(): void { // Core consumes a single event before delivery. Keep a successor until the worker verifies the replacement. if ( 'ai4seo_taxonomy_proxy_sync_continue' === current_filter() && AI4SEO_CRON_JOBS_ENABLED && ! ai4seo_does_user_need_to_accept_tos_toc_and_pp() && ! wp_next_scheduled( 'ai4seo_taxonomy_proxy_sync' ) && ! wp_next_scheduled( 'ai4seo_taxonomy_proxy_sync_continue' ) ) { if ( ! ai4seo_schedule_legacy_taxonomy_continuation() ) { ai4seo_debug_message( 852107606, 'Unable to retain the legacy taxonomy continuation.', true ); } } // The shared worker rechecks the durable cadence and work under the site lock. ai4seo_taxonomy_proxy_sync_cron_job(); } /** * Plan verified replacements before retiring either legacy event. * * @param bool $worker Whether a worker has just released its processing lock. */ function ai4seo_schedule_taxonomy_proxy_sync( bool $worker = false ): void { if ( ! AI4SEO_CRON_JOBS_ENABLED || ai4seo_does_user_need_to_accept_tos_toc_and_pp() ) { return; } // WP-Cron reschedules the legacy recurring event before its callback, even without an initialized account. if ( ! has_filter( 'cron_schedules', 'ai4seo_add_cron_job_intervals' ) ) { // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- Retained release events use the existing five-minute interval. add_filter( 'cron_schedules', 'ai4seo_add_cron_job_intervals' ); } $cadence = ai4seo_get_taxonomy_cadence(); $progress = get_option( AI4SEO_TAXONOMY_PROXY_SYNC_OPTION_NAME, array() ); if ( ! $cadence || ( array() !== $progress && ! ai4seo_is_valid_taxonomy_proxy_sync_progress( $progress ) ) ) { ai4seo_debug_message( 852107602, 'Unreadable taxonomy inventory checkpoint.', true ); return; } $due = ai4seo_taxonomy_audit_due( $progress, $cadence ); $at = max( time() + 1, $cadence['next'], $due ); $was_scheduled = wp_next_scheduled( AI4SEO_TAXONOMY_PROXY_SYNC_CRON_HOOK ); $scheduled = ai4seo_schedule_taxonomy_event( AI4SEO_TAXONOMY_PROXY_SYNC_CRON_HOOK, $at, $due ); // The signal is autoloaded only after both wake-ups failed. A newer producer owns its own revision. if ( isset( wp_load_alloptions()[ AI4SEO_TAXONOMY_WAKE_REPAIR_OPTION ] ) ) { $signal = ai4seo_get_raw_option_snapshot( AI4SEO_TAXONOMY_WAKE_REPAIR_OPTION ); if ( $signal && $signal['exists'] ) { $work = ai4seo_taxonomy_work_names( false, 1 ); $idle = array() === $work && empty( $progress['pending_delete'] ) && empty( $progress['post_issues_pending'] ); $weekly_at = $idle && $scheduled ? wp_next_scheduled( AI4SEO_TAXONOMY_PROXY_SYNC_CRON_HOOK ) : false; $repair_at = $idle ? $at : max( time() + AI4SEO_TAXONOMY_BATCH_INTERVAL, $cadence['next'] ); $repaired = ( $weekly_at && $weekly_at >= $due && $weekly_at <= $at + 10 * MINUTE_IN_SECONDS ) || ai4seo_schedule_taxonomy_change_wake( $repair_at, true ); if ( $repaired && null !== $work ) { ai4seo_compare_and_delete_option_snapshot( AI4SEO_TAXONOMY_WAKE_REPAIR_OPTION, $signal ); } } } if ( ! $scheduled ) { $legacy_single = wp_next_scheduled( 'ai4seo_taxonomy_proxy_sync_continue' ); $legacy_recurring = wp_next_scheduled( 'ai4seo_taxonomy_proxy_sync' ); // Once both release events have retired, the continuation also carries the next weekly audit. $fallback_at = $legacy_single || $legacy_recurring ? 0 : $at; if ( $worker ) { $wake_at = max( time() + AI4SEO_TAXONOMY_BATCH_INTERVAL, $cadence['next'] ); if ( ! empty( $progress['pending_delete'] ) || ! empty( $progress['post_issues_pending'] ) || array() !== ai4seo_taxonomy_work_names( false, 1 ) ) { $fallback_at = $wake_at; } elseif ( 'completed' !== ( $progress['phase'] ?? '' ) ) { $fallback_at = max( $wake_at, $due ); } } if ( $fallback_at ) { ai4seo_schedule_taxonomy_change_wake( $fallback_at, ! $worker && isset( wp_load_alloptions()[ AI4SEO_TAXONOMY_WAKE_REPAIR_OPTION ] ) ); } if ( $legacy_single && ! $legacy_recurring ) { ai4seo_schedule_legacy_taxonomy_continuation( $worker || wp_doing_cron() || is_admin() ); } ai4seo_debug_message( 852107601, 'Unable to schedule taxonomy inventory.', true ); return; } $legacy = array( 'ai4seo_taxonomy_proxy_sync', 'ai4seo_taxonomy_proxy_sync_continue' ); $old = array_filter( $legacy, 'wp_next_scheduled' ); if ( ! $old && ! $worker && $was_scheduled && ! wp_doing_cron() && ! is_admin() ) { return; } $wake_at = max( time() + AI4SEO_TAXONOMY_BATCH_INTERVAL, $cadence['next'] ); $short = wp_next_scheduled( AI4SEO_TAXONOMY_PROXY_CONTINUATION_CRON_HOOK ); if ( ! $short || $short > $wake_at ) { $work = ai4seo_taxonomy_work_names( false, 1 ); if ( null === $work ) { return; } if ( $work || ! empty( $progress['pending_delete'] ) || ! empty( $progress['post_issues_pending'] ) ) { if ( ! ai4seo_schedule_taxonomy_event( AI4SEO_TAXONOMY_PROXY_CONTINUATION_CRON_HOOK, $wake_at ) ) { if ( ! ai4seo_retain_legacy_taxonomy_wake( $wake_at ) ) { ai4seo_debug_message( 852107606, 'Unable to schedule pending taxonomy work.', true ); } return; } } } foreach ( $old as $hook ) { wp_clear_scheduled_hook( $hook ); } } /** * A fixed-width due time permits SQL to skip deferred entries before applying its row limit. * * @param string $kind Term, subtree or archive work type. * @param string $taxonomy WordPress taxonomy slug. * @param int $id Source key for this work type. * @param int $cursor Last confirmed key in a scoped scan. * @param int $attempt Retry step for this revision. * @param int $due Earliest retry timestamp. * @param array $deletion Confirmed WooCommerce deletion identity. */ function ai4seo_taxonomy_work_value( string $kind, string $taxonomy, int $id, int $cursor = 0, int $attempt = 0, int $due = 0, array $deletion = array() ): string { $job = array( $kind, $taxonomy, $id, $cursor, $attempt, wp_generate_uuid4() ); if ( $deletion ) { $job[] = $deletion; } return sprintf( '%010d', $due ) . '|' . wp_json_encode( $job ); } /** * Replace one revision atomically. Bulk imports never rewrite an array containing the whole queue. * * @param string $kind Term, subtree or archive work type. * @param string $taxonomy WordPress taxonomy slug. * @param int $id Source key for this work type. * @param array $deletion Confirmed WooCommerce deletion identity. */ function ai4seo_queue_taxonomy_change( string $kind, string $taxonomy, int $id = 0, array $deletion = array() ): bool { if ( ! AI4SEO_CRON_JOBS_ENABLED || ai4seo_does_user_need_to_accept_tos_toc_and_pp() ) { return true; } $name = AI4SEO_TAXONOMY_WORK_PREFIX . $kind . '_' . $taxonomy . '_' . $id; // An acknowledgement can race an update that observed the previous row. Retry against the new snapshot. $saved = false; for ( $try = 0; $try < 4 && false === $saved; ++$try ) { $observed = ai4seo_get_raw_option_snapshot( $name ); if ( null === $observed ) { break; } $saved = ai4seo_compare_and_swap_option_snapshot( $name, $observed, ai4seo_taxonomy_work_value( $kind, $taxonomy, $id, 0, 0, 0, $deletion ) ); } if ( true !== $saved ) { ai4seo_debug_message( 852107608, 'Could not record taxonomy change.', true ); return false; } if ( ! ai4seo_schedule_taxonomy_change_wake( time() + AI4SEO_TAXONOMY_BATCH_INTERVAL ) ) { ai4seo_debug_message( 852107606, 'Unable to schedule recorded taxonomy changes.', true ); } return true; } /** * WordPress supplies the immutable term-taxonomy ID for creates, edits and confirmed deletes. * * @param int $term_id WordPress term ID. * @param int $tt_id Immutable term-taxonomy ID. * @param string $taxonomy WordPress taxonomy slug. */ function ai4seo_capture_taxonomy_term( int $term_id, int $tt_id, string $taxonomy ): void { ai4seo_queue_taxonomy_change( 'term', $taxonomy, $tt_id ); } /** * Keep the two WordPress identifiers and the attribute owner after core confirms deletion. * * @param int $term_id WordPress term ID. * @param int $tt_id Immutable term-taxonomy ID. * @param string $taxonomy Taxonomy at the time of deletion. */ function ai4seo_capture_deleted_taxonomy_term( int $term_id, int $tt_id, string $taxonomy ): void { if ( ! AI4SEO_CRON_JOBS_ENABLED || ai4seo_does_user_need_to_accept_tos_toc_and_pp() ) { return; } $attribute_id = 0 === strpos( $taxonomy, 'pa_' ) && function_exists( 'wc_attribute_taxonomy_id_by_name' ) ? (int) wc_attribute_taxonomy_id_by_name( $taxonomy ) : 0; if ( $attribute_id ) { $deletion = array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id, 'taxonomy' => $taxonomy, 'attribute_id' => $attribute_id, ); $proxy = ai4seo_read_taxonomy_proxy( $tt_id ); $source = is_array( $proxy ) ? $proxy['source'] : null; $path = array(); if ( ( $source['term_id'] ?? 0 ) === $term_id && ( $source['term_taxonomy_id'] ?? 0 ) === $tt_id && ai4seo_attribute_rename_reaches( $attribute_id, $source['taxonomy'], $taxonomy, $path ) ) { // The owner can reuse a slug before a worker finishes writing an intermediate name. $deletion['proxy_id'] = (int) $proxy['ID']; $deletion['proxy_taxonomy'] = $source['taxonomy']; $deletion['rename_path'] = $path; // A later rename can overwrite the outgoing edge of a name used twice. $deletion['rename_aliases'] = ai4seo_attribute_names_reaching( $attribute_id, $taxonomy ); } ai4seo_queue_taxonomy_change( 'deleted', $taxonomy, $tt_id, $deletion ); } else { ai4seo_capture_taxonomy_term( $term_id, $tt_id, $taxonomy ); } } /** * Capture finalized counts, including deferred recounts and WooCommerce count callbacks. * * @param array $term_ids Term IDs whose counts may have changed. * @param string $taxonomy WordPress taxonomy slug. * @param bool $clean_taxonomy Whether WordPress invalidated the whole taxonomy cache. */ function ai4seo_capture_taxonomy_counts( array $term_ids, string $taxonomy, bool $clean_taxonomy ): void { if ( $clean_taxonomy ) { return; } foreach ( array_unique( $term_ids ) as $id ) { ai4seo_queue_taxonomy_change( 'count', $taxonomy, (int) $id ); } } /** * WordPress reparents children directly in SQL when deleting their parent. * * @param array $tt_ids Reparented term-taxonomy IDs. */ function ai4seo_capture_reparented_taxonomy_terms( array $tt_ids ): void { foreach ( $tt_ids as $tt_id ) { ai4seo_queue_taxonomy_change( 'term', '', (int) $tt_id ); } } /** * Reconcile both the sources and the retained proxies of one changed archive. * * @param string $taxonomy WordPress taxonomy slug. */ function ai4seo_queue_taxonomy_archive( string $taxonomy ): void { ai4seo_queue_taxonomy_change( 'sources', $taxonomy ); ai4seo_queue_taxonomy_change( 'proxies', $taxonomy ); } /** * WooCommerce reports both slugs when renaming an attribute. * * @param int $attribute_id WooCommerce attribute ID. * @param array $data WooCommerce attribute data. * @param string $old_slug Previous attribute slug. */ function ai4seo_capture_attribute_archive( int $attribute_id, array $data, string $old_slug = '' ): void { $new_slug = $data['attribute_name'] ?? ''; if ( $attribute_id > 0 && '' !== $old_slug && '' !== $new_slug && $old_slug !== $new_slug ) { $name = AI4SEO_TAXONOMY_ATTRIBUTE_RENAMES_PREFIX . $attribute_id; $old = wc_attribute_taxonomy_name( $old_slug ); $new = wc_attribute_taxonomy_name( $new_slug ); // WooCommerce fires the hook before changing the term rows. Keep chained renames across worker restarts. $saved = false; for ( $try = 0; $try < 4 && false === $saved; ++$try ) { $observed = ai4seo_get_raw_option_snapshot( $name ); if ( null === $observed || ( $observed['exists'] && ! is_array( $observed['value'] ) ) ) { break; } $renames = $observed['value'] ?? array(); if ( ( $renames[ $old ] ?? null ) === $new ) { $saved = true; break; } $renames[ $old ] = $new; $saved = ai4seo_compare_and_swap_option_snapshot( $name, $observed, $renames, false ); } if ( true !== $saved ) { ai4seo_debug_message( 852107608, 'Could not record WooCommerce attribute rename.', true ); } } foreach ( array_unique( array_filter( array( $old_slug, $data['attribute_name'] ?? '' ) ) ) as $slug ) { ai4seo_queue_taxonomy_archive( wc_attribute_taxonomy_name( $slug ) ); } } /** * Verify a recorded slug transition against the current WooCommerce attribute and both immutable term keys. * * @param array $previous Stored proxy source. * @param string $taxonomy Current taxonomy from the term row. * @param int $term_id Current term ID. * @param int $tt_id Current term-taxonomy ID. */ function ai4seo_is_confirmed_attribute_rename( array $previous, string $taxonomy, int $term_id, int $tt_id ): bool { if ( ( $previous['term_id'] ?? 0 ) !== $term_id || ( $previous['term_taxonomy_id'] ?? 0 ) !== $tt_id || 0 !== strpos( $taxonomy, 'pa_' ) || ! function_exists( 'wc_attribute_taxonomy_id_by_name' ) ) { return false; } return ai4seo_attribute_rename_reaches( (int) wc_attribute_taxonomy_id_by_name( $taxonomy ), $previous['taxonomy'], $taxonomy ); } /** * Walk only transitions recorded for the same WooCommerce attribute owner. * * @param int $attribute_id Stable WooCommerce attribute ID. * @param string $slug Earlier taxonomy name. * @param string $taxonomy Required later taxonomy name. * @param array $path Verified names in chronological order. */ function ai4seo_attribute_rename_reaches( int $attribute_id, string $slug, string $taxonomy, array &$path = array() ): bool { $path = array(); if ( $attribute_id <= 0 || '' === $slug || '' === $taxonomy ) { return false; } $chain = array( $slug ); if ( $slug !== $taxonomy ) { $renames = get_option( AI4SEO_TAXONOMY_ATTRIBUTE_RENAMES_PREFIX . $attribute_id, array() ); if ( ! is_array( $renames ) ) { return false; } while ( $slug !== $taxonomy ) { $next = $renames[ $slug ] ?? null; if ( ! is_string( $next ) || '' === $next ) { return false; } unset( $renames[ $slug ] ); $chain[] = $next; $slug = $next; } } $path = $chain; return true; } /** * Collect distinct slugs with recorded transitions to this name for one attribute. * * @param int $attribute_id Stable WooCommerce attribute ID. * @param string $taxonomy Confirmed attribute taxonomy. * @return string[] */ function ai4seo_attribute_names_reaching( int $attribute_id, string $taxonomy ): array { $renames = get_option( AI4SEO_TAXONOMY_ATTRIBUTE_RENAMES_PREFIX . $attribute_id, array() ); $parents = array(); foreach ( is_array( $renames ) ? $renames : array() as $from => $to ) { if ( is_string( $from ) && is_string( $to ) ) { $parents[ $to ][] = $from; } } $names = array( $taxonomy => true ); $queue = array( $taxonomy ); while ( $queue ) { $name = array_pop( $queue ); foreach ( $parents[ $name ] ?? array() as $from ) { if ( ! isset( $names[ $from ] ) ) { $names[ $from ] = true; $queue[] = $from; } } } return array_keys( $names ); } /** * A removed WooCommerce provider can leave retained proxies. * * @param int $attribute_id WooCommerce attribute ID. * @param string $name Deleted attribute name. * @param string $taxonomy WordPress taxonomy slug. */ function ai4seo_capture_removed_attribute_archive( int $attribute_id, string $name, string $taxonomy ): void { delete_option( AI4SEO_TAXONOMY_ATTRIBUTE_RENAMES_PREFIX . $attribute_id ); ai4seo_queue_taxonomy_archive( $taxonomy ); } /** * Capture the specific taxonomy diagnostics verified by this change. * * @param int $tt_id Term-taxonomy ID if known. * @param int $post_id Proxy post ID if known. */ function ai4seo_read_taxonomy_change_issues( int $tt_id, int $post_id ): ?array { $issues = array(); $entities = array( 'term_taxonomy' => $tt_id, 'post' => $post_id, ); foreach ( $entities as $entity => $id ) { if ( ! $id ) { continue; } $observed = ai4seo_get_raw_option_snapshot( ai4seo_analysis_issue_option_name( $entity, $id ) ); if ( null === $observed ) { return null; } if ( $observed['exists'] && ! ai4seo_is_malformed_taxonomy_diagnostic( $observed ) ) { $observed['value']['reasons'] = wp_list_filter( $observed['value']['reasons'], array( 'stage' => 'taxonomy_sync' ) ); if ( $observed['value']['reasons'] ) { $issues[] = $observed; } } } return $issues; } /** * Requeue analysis before resolving only the evidence observed before the source check. * * @param array $issues Observed taxonomy diagnostics. * @param int $post_id Existing, newly created or just deleted proxy. */ function ai4seo_finish_taxonomy_change_issues( array $issues, int $post_id ): bool { if ( $issues && $post_id && ! ai4seo_enqueue_analysis_reconciliation( array( $post_id ), true ) ) { return false; } foreach ( $issues as $observed ) { if ( ! ai4seo_resolve_analysis_issue( $observed, 'taxonomy_sync' ) ) { return false; } } return true; } /** * Reconcile one changed source or proxy and the matching diagnostic evidence. * * @param int $id Source key for this work type. * @param bool $by_post Whether the key is a proxy post ID. * @param array $progress Durable inventory checkpoint. * @param array $snapshot Exact persisted checkpoint bytes. * @param array $deletion Confirmed WooCommerce deletion identity. */ function ai4seo_reconcile_taxonomy_change( int $id, bool $by_post, array &$progress, array &$snapshot, array $deletion = array() ): bool { $proxy = $by_post ? ai4seo_get_taxonomy_proxy_by_id( $id ) : ai4seo_read_taxonomy_proxy( $id ); if ( is_wp_error( $proxy ) ) { // The worker can acknowledge this revision without touching the ordinary post or its diagnostics. return $by_post && true === ( $proxy->get_error_data()['left_inventory'] ?? false ); } $post_id = $by_post ? $id : (int) ( $proxy['ID'] ?? 0 ); $tt_id = $by_post ? (int) ( $proxy['source']['term_taxonomy_id'] ?? 0 ) : $id; $issues = ai4seo_read_taxonomy_change_issues( $tt_id, $post_id ); if ( null === $issues ) { return false; } if ( $proxy ) { $result = ai4seo_reconcile_taxonomy_proxy( $post_id, $progress, $snapshot, $proxy, $deletion ); } elseif ( ! $by_post ) { $result = ai4seo_get_taxonomy_proxy_source_state( $id ); if ( ! is_wp_error( $result ) && 'available' === $result['state'] ) { $result = ai4seo_upsert_taxonomy_proxy( $result ); } } else { $result = true; } if ( is_wp_error( $result ) ) { return false; } if ( ! ai4seo_finish_taxonomy_change_issues( $issues, is_int( $result ) ? $result : $post_id ) ) { // Keep the deletion identity available even after WordPress has removed the post. $pending = $snapshot['value']['pending_delete'] ?? null; if ( $pending && $post_id === $pending['post_id'] ) { $progress['pending_delete'] = $pending; } return false; } return true; } /** * Expand only one keyset page of the affected archive or subtree; the worker charges each row to its budget. * * @param string $kind Term, subtree or archive work type. * @param string $taxonomy WordPress taxonomy slug. * @param int $id Source key for this work type. * @param int $cursor Last confirmed key in a scoped scan. * @param int $limit Maximum rows to read. */ function ai4seo_taxonomy_change_ids( string $kind, string $taxonomy, int $id, int $cursor, int $limit ): ?array { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery -- Bounded local inventory keysets, including unavailable archives. switch ( $kind ) { case 'term': case 'deleted': case 'proxy': return array( $id ); case 'count': $ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy=%s AND term_id=%d LIMIT 1", $taxonomy, $id ) ); break; case 'children': $ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy=%s AND parent=%d AND term_taxonomy_id>%d ORDER BY term_taxonomy_id LIMIT %d", $taxonomy, $id, $cursor, $limit ) ); break; case 'sources': $ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy=%s AND term_taxonomy_id>%d ORDER BY term_taxonomy_id LIMIT %d", $taxonomy, $cursor, $limit ) ); break; case 'proxies': $ids = $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} m ON m.post_id=p.ID WHERE p.post_type=%s AND m.meta_key=%s AND m.meta_value=%s AND p.ID>%d ORDER BY p.ID LIMIT %d", AI4SEO_TAXONOMY_PROXY_POST_TYPE, AI4SEO_TAXONOMY_PROXY_NAME_META_KEY, $taxonomy, $cursor, $limit ) ); break; default: return null; } // phpcs:enable WordPress.DB.DirectDatabaseQuery return $wpdb->last_error ? null : array_map( 'intval', $ids ); } /** * Replay journaled deletion and only retire its diagnostic once the cleanup is durable. * * @param array $progress Durable inventory checkpoint. * @param array $snapshot Exact persisted checkpoint bytes. * @return WP_Error|null Error to retry, or null once deletion and diagnostic cleanup succeed. */ function ai4seo_recover_taxonomy_deletion( array &$progress, array &$snapshot ) { $pending = $progress['pending_delete']; $post_id = $pending['post_id']; $issues = ai4seo_read_taxonomy_change_issues( $pending['source']['term_taxonomy_id'], $post_id ); if ( null === $issues ) { return new WP_Error( 'taxonomy_issue_read_failed' ); } $result = ai4seo_delete_taxonomy_proxy( $post_id, $progress, $snapshot ); if ( is_wp_error( $result ) ) { return $result; } if ( ! ai4seo_finish_taxonomy_change_issues( $issues, $post_id ) ) { // The post may already be gone; keep its journal until diagnostic cleanup also commits. $progress['pending_delete'] = $pending; return new WP_Error( 'taxonomy_issue_write_failed' ); } return null; } /** * Consume exact revisions, yielding between records and leaving concurrently replaced work intact. * * @param array $progress Durable inventory checkpoint. * @param array $snapshot Exact persisted checkpoint bytes. * @param float $started Start time of the shared processing budget. * @param bool $terms_ready Whether the worker found an eligible change under its lock. */ function ai4seo_run_taxonomy_changes( array &$progress, array &$snapshot, float $started, bool $terms_ready = false ): bool { $remaining = AI4SEO_TAXONOMY_PROXY_SYNC_BATCH_SIZE; $deadline = $started + AI4SEO_TAXONOMY_PROXY_SYNC_TIME_LIMIT; if ( ! empty( $progress['pending_delete'] ) && ( $progress['retry_at'] ?? 0 ) <= time() && ( $progress['repair_at'] ?? 0 ) <= time() ) { if ( is_wp_error( ai4seo_recover_taxonomy_deletion( $progress, $snapshot ) ) ) { $attempt = min( 2, $progress['repair_failures'] ?? 0 ); $progress['repair_at'] = time() + AI4SEO_TAXONOMY_RETRY_MINUTES[ $attempt ] * MINUTE_IN_SECONDS; $progress['repair_failures'] = min( 2, $attempt + 1 ); } else { unset( $progress['repair_at'], $progress['repair_failures'] ); } if ( is_wp_error( ai4seo_save_taxonomy_proxy_sync_progress( $progress, $snapshot ) ) ) { return false; } --$remaining; } if ( $terms_ready && ! empty( $progress['post_issues_yield'] ) ) { unset( $progress['post_issues_yield'] ); if ( is_wp_error( ai4seo_save_taxonomy_proxy_sync_progress( $progress, $snapshot ) ) ) { return false; } } elseif ( ! empty( $progress['post_issues_pending'] ) ) { unset( $progress['post_issues_yield'] ); $ok = ai4seo_recheck_deleted_proxy_issues( $progress, $remaining, $deadline ); if ( ! $ok ) { $progress['post_issues_yield'] = true; $progress['last_status'] = 'error'; $progress['last_error'] = 'taxonomy_post_issue_read_failed'; ai4seo_debug_message( 852107604, 'taxonomy_post_issue_read_failed', true ); } elseif ( 'taxonomy_post_issue_read_failed' === $progress['last_error'] ) { $progress['last_status'] = 'completed'; $progress['last_error'] = ''; unset( $progress['retry_at'], $progress['failures'] ); } if ( is_wp_error( ai4seo_save_taxonomy_proxy_sync_progress( $progress, $snapshot ) ) || ! $ok ) { return false; } } $names = ai4seo_taxonomy_work_names( true, $remaining ); if ( null === $names ) { return false; } foreach ( $names as $name ) { if ( $remaining < 1 || microtime( true ) >= $deadline ) { break; } $observed = ai4seo_get_raw_option_snapshot( $name ); if ( null === $observed ) { return false; } if ( ! $observed['exists'] ) { continue; } $value = $observed['value']; $job = is_string( $value ) ? json_decode( substr( $value, 11 ), true ) : null; if ( ! is_array( $job ) || ! in_array( count( $job ), array( 6, 7 ), true ) ) { return false; } if ( (int) substr( $value, 0, 10 ) > time() ) { continue; } list( $kind, $taxonomy, $id, $cursor, $attempt ) = $job; $deletion = $job[6] ?? array(); if ( ! is_array( $deletion ) || ( 'deleted' === $kind && ( $deletion['term_taxonomy_id'] ?? 0 ) !== $id ) ) { return false; } $limit = $remaining; $rows = ai4seo_taxonomy_change_ids( $kind, $taxonomy, $id, $cursor, $limit ); $ok = null !== $rows; $by_post = in_array( $kind, array( 'proxy', 'proxies' ), true ); $single = in_array( $kind, array( 'term', 'deleted', 'proxy', 'count' ), true ); $done = $ok && ( $single || count( $rows ) < $limit ); foreach ( $rows ?? array() as $row ) { if ( microtime( true ) >= $deadline ) { $done = false; break; } --$remaining; $pending = $progress['pending_delete'] ?? null; $ok = ! $pending || ( $by_post ? $pending['post_id'] : $pending['source']['term_taxonomy_id'] ) !== $row; if ( $ok ) { $ok = ai4seo_reconcile_taxonomy_change( $row, $by_post, $progress, $snapshot, $deletion ); } if ( $ok && $snapshot['value'] !== $progress && is_wp_error( ai4seo_save_taxonomy_proxy_sync_progress( $progress, $snapshot ) ) ) { return false; } // Isolate one failed archive member so the rest of the keyset can advance. if ( ! $ok && ! $single ) { $ok = ai4seo_queue_taxonomy_change( $by_post ? 'proxy' : 'term', $taxonomy, $row ); } if ( ! $ok ) { break; } $cursor = $row; } if ( ! ai4seo_is_database_advisory_lock_owned_by_current_connection( ai4seo_get_taxonomy_proxy_sync_lock_name() ) ) { return false; } if ( $done && $ok ) { $saved = ai4seo_compare_and_delete_option_snapshot( $name, $observed ); } else { $due = $ok ? 0 : time() + MINUTE_IN_SECONDS * AI4SEO_TAXONOMY_RETRY_MINUTES[ min( 2, $attempt ) ]; $saved = ai4seo_compare_and_swap_option_snapshot( $name, $observed, ai4seo_taxonomy_work_value( $kind, $taxonomy, $id, $cursor, $ok ? 0 : min( 2, $attempt + 1 ), $due, $deletion ) ); } if ( null === $saved ) { return false; } } return true; }