*/ private static array $url_post_ids = array(); public function __construct( private readonly ?ContentIndexRepository $repository = null ) { } /** * Delete queued indexing state and scheduled index jobs. */ public static function delete_options(): void { ContentIndexQueue::delete_all(); if ( function_exists( 'wp_unschedule_hook' ) ) { wp_unschedule_hook( self::STALE_SWEEP_HOOK ); wp_unschedule_hook( self::STALE_SWEEP_RECOVERY_HOOK ); wp_unschedule_hook( self::INDEX_RETRY_HOOK ); wp_unschedule_hook( self::REFRESH_JOB_HOOK ); wp_unschedule_hook( self::REFRESH_RECOVERY_HOOK ); } } /** * Defer indexing of one post to the queued stale sweep. * * Used by bulk contexts (WP-CLI imports, cron, REST batch writes) where * running the full indexer inline per post would multiply request time. * * @param int $post_id Post ID. */ public function defer_index_post( int $post_id ): bool { $result = $this->defer_index_post_result( $post_id ); return $result['scheduled']; } /** * Defer one post and retain the exact queue generation for durable retry. * * @param int $post_id Post ID. * @return array{queued: bool, scheduled: bool, queue_token: string} */ public function defer_index_post_result( int $post_id ): array { return ( new ContentIndexDeferrer() )->defer( $post_id, $this ); } /** * Retry queue persistence without performing full indexing inline. * * @param int $post_id Post ID. */ public function retry_deferred_index( int $post_id ): void { if ( ! $this->is_indexable_post_id( $post_id ) ) { $this->delete_post( $post_id ); return; } $this->defer_index_post_result( $post_id ); } /** * Schedule one debounced stale-sweep cron event. * * @param int $delay Seconds before the sweep runs. */ public function schedule_stale_sweep( int $delay = 60 ): bool { if ( ! function_exists( 'wp_schedule_single_event' ) ) { return false; } $timestamp = time() + max( 5, $delay ); if ( function_exists( 'wp_next_scheduled' ) ) { $scheduled = wp_next_scheduled( self::STALE_SWEEP_HOOK ); if ( false !== $scheduled ) { return true; } } $scheduled = wp_schedule_single_event( $timestamp, self::STALE_SWEEP_HOOK, array(), true ); return false !== $scheduled && ! is_wp_error( $scheduled ); } /** * Return the number of pending object IDs waiting for a stale sweep. */ public function pending_index_count(): int { return ( new ContentIndexQueue() )->pending_count(); } /** * Return the scheduled stale-sweep timestamp, if available. */ public function stale_sweep_scheduled_at(): int { if ( ! function_exists( 'wp_next_scheduled' ) ) { return 0; } $scheduled = wp_next_scheduled( self::STALE_SWEEP_HOOK ); return is_numeric( $scheduled ) ? max( 0, (int) $scheduled ) : 0; } /** * Re-index deferred posts and stale rows in bounded batches. * * @return array */ public function run_stale_sweep(): array { $queue = new ContentIndexQueue(); if ( ! $this->schedule_stale_sweep_recovery() ) { $remaining = $queue->pending_count(); $this->schedule_stale_sweep( 30 ); return array( 'status' => 0 < $remaining ? 'partial' : 'complete', 'processed_items' => 0, 'error_count' => 0 < $remaining ? 1 : 0, 'remaining_items' => $remaining, ); } $room = max( 0, self::MAX_BATCH_LIMIT - $queue->pending_count() ); if ( 0 < $room ) { foreach ( $this->repo()->stale_object_ids( $room ) as $stale_id ) { $queue->enqueue_if_absent( $stale_id ); } } $claims = $queue->claim( self::STALE_SWEEP_SLICE_SIZE ); $started_at = microtime( true ); $processed = 0; $errors = 0; foreach ( $claims as $position => $claim ) { if ( 0 < $processed && microtime( true ) - $started_at >= self::STALE_SWEEP_TIME_BUDGET ) { foreach ( array_slice( $claims, $position ) as $unprocessed_claim ) { $queue->release_claim( $unprocessed_claim['object_id'], $unprocessed_claim['lock_token'] ); } break; } $post_id = $claim['object_id']; if ( 'delete' === $claim['action'] ) { if ( $this->repo()->delete_content_item( $post_id ) ) { $queue->acknowledge( $post_id, $claim['queue_token'], $claim['lock_token'] ); } else { ++$errors; $queue->retry( $post_id, $claim['queue_token'], $claim['lock_token'] ); } ++$processed; continue; } $result = $this->index_post( $post_id ); if ( 'error' === ( $result['status'] ?? '' ) ) { ++$errors; $queue->retry( $post_id, $claim['queue_token'], $claim['lock_token'] ); } else { $this->finalize_deferred_index( $post_id, $claim['queue_token'], $claim['lock_token'] ); } ++$processed; } $remaining = $queue->pending_count(); if ( 0 < $remaining ) { if ( $this->schedule_stale_sweep( 30 ) ) { $this->clear_stale_sweep_recovery(); } } else { $this->clear_stale_sweep_recovery(); } return array( 'status' => 0 < $remaining ? 'partial' : 'complete', 'processed_items' => $processed, 'error_count' => $errors, 'remaining_items' => $remaining, ); } /** * Keep an independent post-lease recovery event while a sweep owns claims. */ private function schedule_stale_sweep_recovery(): bool { if ( ! function_exists( 'wp_schedule_single_event' ) ) { return false; } if ( function_exists( 'wp_next_scheduled' ) && false !== wp_next_scheduled( self::STALE_SWEEP_RECOVERY_HOOK ) ) { return true; } $scheduled = wp_schedule_single_event( time() + ContentIndexRepository::DEFAULT_JOB_LEASE_TTL + 5, self::STALE_SWEEP_RECOVERY_HOOK, array(), true ); return false !== $scheduled && ! is_wp_error( $scheduled ); } /** * Remove the recovery event only after continuation or completion is durable. */ private function clear_stale_sweep_recovery(): void { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_unschedule_event' ) ) { return; } $scheduled = wp_next_scheduled( self::STALE_SWEEP_RECOVERY_HOOK ); if ( false !== $scheduled ) { wp_unschedule_event( (int) $scheduled, self::STALE_SWEEP_RECOVERY_HOOK ); } } /** * Index one WordPress post-like object. * * @param int $post_id Post ID. * @return array */ public function index_post( int $post_id ): array { $post_id = absint( $post_id ); if ( 0 >= $post_id || ! function_exists( 'get_post' ) ) { return $this->result( 'skipped', $post_id, 'invalid_post_id' ); } $post = get_post( $post_id ); if ( ! $post instanceof \WP_Post ) { if ( ! $this->repo()->delete_content_item( $post_id ) ) { return $this->result( 'error', $post_id, 'delete_failed' ); } return $this->result( 'deleted', $post_id, 'post_not_found' ); } if ( ! $this->is_indexable_post( $post ) ) { if ( ! $this->repo()->delete_content_item( $post_id ) ) { return $this->result( 'error', $post_id, 'delete_failed' ); } return $this->result( 'deleted', $post_id, 'post_not_indexable' ); } $plain_text = $this->plain_text( $post->post_content ); $terms = $this->terms_for_post( $post ); $record = array( 'object_id' => (int) $post->ID, 'object_type' => 'post', 'post_type' => (string) $post->post_type, 'post_status' => (string) $post->post_status, 'title' => $this->post_title( $post ), 'slug' => (string) $post->post_name, 'permalink' => $this->permalink( $post ), 'excerpt' => $this->excerpt( $post ), 'summary' => $this->summary( $plain_text ), 'word_count' => $this->word_count( $plain_text ), 'content_hash' => hash( 'sha256', $post->post_title . "\n" . $post->post_excerpt . "\n" . $post->post_content ), 'modified_gmt' => (string) $post->post_modified_gmt, 'stale' => false, 'search_text' => $this->search_text( $post, $plain_text, $terms ), 'metadata' => array( 'author' => (int) $post->post_author, 'terms' => $terms, 'section_ids' => array(), ), ); $chunks = $this->chunks_from_content( (int) $post->ID, (string) $post->post_content ); $links = $this->links_from_content( (int) $post->ID, (string) $post->post_content ); $record['metadata']['section_ids'] = array_values( array_column( $chunks, 'chunk_id' ) ); $stored = ( new ContentProjectionWriter( $this->repo() ) )->replace( $record, $chunks, $links ); if ( false === $stored ) { $this->mark_post_stale( $post_id ); return $this->result( 'error', $post_id, 'index_write_failed' ); } return array( 'status' => 'indexed', 'post_id' => $post_id, 'post_type' => (string) $post->post_type, 'post_status' => (string) $post->post_status, 'chunks' => $stored['chunks'], 'links' => $stored['links'], ); } /** * Check whether a WordPress post is eligible for content indexing. * * @param int $post_id WordPress post ID. */ public function is_indexable_post_id( int $post_id ): bool { $post = function_exists( 'get_post' ) ? get_post( absint( $post_id ) ) : null; return $post instanceof \WP_Post && $this->is_indexable_post( $post ); } /** * Delete all index rows for one post. * * @param int $post_id Post ID. */ public function delete_post( int $post_id ): void { ( new ContentIndexRetryScheduler() )->clear( $post_id ); $tombstone = ( new ContentIndexQueue() )->invalidate_for_delete( $post_id ); $this->repo()->delete_content_item( $post_id ); if ( '' !== $tombstone ) { $this->schedule_stale_sweep( 5 ); } } /** * Finalize one indexed generation without erasing newer work. * * @param int $post_id WordPress post ID. * @param string $queue_token Indexed queue generation, when one was persisted. * @param string $lock_token Optional claimed lease token. */ public function finalize_deferred_index( int $post_id, string $queue_token = '', string $lock_token = '' ): void { $queue = new ContentIndexQueue(); $acknowledged = '' !== $lock_token ? $queue->acknowledge( $post_id, $queue_token, $lock_token ) : $queue->clear_generation( $post_id, $queue_token ); if ( $acknowledged ) { return; } $current = $queue->current_generation( $post_id ); if ( 'delete' === $current['action'] || ! $this->is_indexable_post_id( $post_id ) ) { $deleted = $this->repo()->delete_content_item( $post_id ); if ( $deleted && 'delete' === $current['action'] ) { $queue->clear_generation( $post_id, $current['queue_token'] ); } elseif ( ! $deleted ) { $this->schedule_stale_sweep( 30 ); } return; } $this->defer_index_post( $post_id ); } /** * Mark one post stale so MCP clients know cached context needs refresh. * * @param int $post_id Post ID. */ public function mark_post_stale( int $post_id ): bool { return $this->repo()->mark_stale( $post_id ); } /** * Refresh a bounded batch synchronously. * * @param array $args Batch args. * @return array */ public function refresh_batch( array $args ): array { $post_ids = $this->post_ids_for_batch( $args ); $job = $this->repo()->create_job( 'content_index_refresh', $this->batch_public_args( $args ), count( $post_ids ) ); if ( '' === (string) ( $job['job_key'] ?? '' ) ) { return array( 'status' => 'error', 'error' => 'job_create_failed', 'message' => 'The content index refresh job could not be created.', ); } return $this->run_refresh_job( (string) ( $job['job_key'] ?? '' ), $post_ids ); } /** * Queue a bounded refresh batch for WordPress cron. * * @param array $args Batch args. * @return array */ public function queue_refresh_batch( array $args ): array { $post_ids = $this->post_ids_for_batch( $args ); $public_args = $this->batch_public_args( $args ); $public_args['ids'] = $post_ids; $job = $this->repo()->create_job( 'content_index_refresh', $public_args, count( $post_ids ), 'queued' ); $job_key = (string) ( $job['job_key'] ?? '' ); if ( '' === $job_key ) { return array( 'status' => 'error', 'error' => 'job_create_failed', 'message' => 'The queued content index refresh job could not be created.', ); } if ( ! $this->schedule_refresh_worker( $job_key ) ) { $failed_job = $this->repo()->update_job( $job_key, array( 'status' => 'failed', 'processed_items' => 0, 'error_count' => 1, 'result' => array( 'error' => 'job_schedule_failed', 'recovery_action' => 'Restore WP-Cron or a system cron runner, then submit a new queued refresh.', ), ) ); return array( 'status' => 'error', 'error' => 'job_schedule_failed', 'message' => 'The content index refresh job was created but could not be scheduled.', 'job' => array() === $failed_job ? $job : $failed_job, ); } if ( ! $this->schedule_refresh_recovery( $job_key ) ) { $this->clear_refresh_worker( $job_key ); $failed_job = $this->repo()->update_job( $job_key, array( 'status' => 'failed', 'processed_items' => 0, 'error_count' => 1, 'result' => array( 'error' => 'job_recovery_schedule_failed', 'recovery_action' => 'Restore WP-Cron or a system cron runner, then submit a new queued refresh.', ), ) ); return array( 'status' => 'error', 'error' => 'job_recovery_schedule_failed', 'message' => 'The content index refresh job could not create its recovery watchdog.', 'job' => array() === $failed_job ? $job : $failed_job, ); } return array( 'status' => 'queued', 'job' => $job, 'total_items' => count( $post_ids ), 'processed_items' => 0, 'errors' => array(), 'index' => $this->job_index_summary( count( $post_ids ), 0, 0 ), ); } /** * Execute a queued refresh job. * * @param string $job_key Job key. * @return array */ public function run_queued_refresh_job( string $job_key ): array { $job = $this->repo()->job_by_key( $job_key ); if ( array() === $job ) { return array( 'status' => 'error', 'error' => 'job_not_found', 'message' => 'No queued content index refresh job exists for that key.', ); } if ( in_array( (string) ( $job['status'] ?? '' ), array( 'complete', 'partial', 'failed' ), true ) ) { return array( 'status' => 'skipped', 'job' => $job, 'message' => 'The queued content index refresh job has already finished.', 'index' => $this->job_index_summary( (int) ( $job['total_items'] ?? 0 ), (int) ( $job['processed_items'] ?? 0 ), (int) ( $job['error_count'] ?? 0 ) ), ); } if ( ! $this->ensure_refresh_recovery( $job_key ) ) { $failed_job = $job; if ( in_array( (string) ( $job['status'] ?? '' ), array( 'queued', 'stale' ), true ) ) { $unprotected_claim = $this->repo()->claim_job( $job_key, self::REFRESH_LEASE_TTL ); $lease_token = (string) ( $unprotected_claim['_lease_token'] ?? '' ); if ( '' !== $lease_token ) { $failed_job = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => 'failed', 'processed_items' => (int) ( $unprotected_claim['processed_items'] ?? 0 ), 'error_count' => (int) ( $unprotected_claim['error_count'] ?? 0 ) + 1, 'result' => array_merge( is_array( $unprotected_claim['result'] ?? null ) ? $unprotected_claim['result'] : array(), array( 'error' => 'job_recovery_schedule_failed', 'recovery_action' => 'Restore WP-Cron or a system cron runner, then submit a new queued refresh.', ) ), ), true ); } } return array( 'status' => 'error', 'error' => 'job_recovery_schedule_failed', 'message' => 'The worker stopped before claiming the job because no recovery watchdog could be scheduled.', 'job' => $failed_job, ); } $claimed = $this->repo()->claim_job( $job_key, self::REFRESH_LEASE_TTL ); if ( array() === $claimed ) { return array( 'status' => 'skipped', 'job' => $job, 'message' => 'The queued content index refresh job is already running or has already finished.', 'index' => $this->job_index_summary( (int) ( $job['total_items'] ?? 0 ), (int) ( $job['processed_items'] ?? 0 ), (int) ( $job['error_count'] ?? 0 ) ), ); } $lease_token = (string) ( $claimed['_lease_token'] ?? '' ); if ( ! $this->schedule_refresh_recovery( $job_key ) ) { $failed_job = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => 'failed', 'processed_items' => (int) ( $claimed['processed_items'] ?? 0 ), 'error_count' => (int) ( $claimed['error_count'] ?? 0 ) + 1, 'result' => array_merge( is_array( $claimed['result'] ?? null ) ? $claimed['result'] : array(), array( 'error' => 'job_recovery_schedule_failed', 'recovery_action' => 'Restore WP-Cron or a system cron runner, then submit a new queued refresh.', ) ), ), true ); return array( 'status' => 'error', 'error' => 'job_recovery_schedule_failed', 'message' => 'The worker could not schedule its recovery event, so no new items were processed.', 'job' => $failed_job, ); } $args = is_array( $claimed['args'] ?? null ) ? (array) $claimed['args'] : array(); $post_ids = isset( $args['ids'] ) && is_array( $args['ids'] ) ? array_values( array_filter( array_map( 'absint', $args['ids'] ) ) ) : $this->post_ids_for_batch( $args ); return $this->run_queued_refresh_slice( $claimed, $post_ids ); } /** * Process one bounded, resumable queued-job slice. * * @param array $job Claimed job row. * @param array $post_ids Complete stable work list. * @phpstan-param list $post_ids * @return array */ private function run_queued_refresh_slice( array $job, array $post_ids ): array { $job_key = (string) ( $job['job_key'] ?? '' ); $lease_token = (string) ( $job['_lease_token'] ?? '' ); $total = count( $post_ids ); $processed = min( $total, max( 0, (int) ( $job['processed_items'] ?? 0 ) ) ); $job_result = is_array( $job['result'] ?? null ) ? $job['result'] : array(); $errors = isset( $job_result['errors'] ) && is_array( $job_result['errors'] ) ? array_values( $job_result['errors'] ) : array(); $indexed_ids = isset( $job_result['indexed_ids'] ) && is_array( $job_result['indexed_ids'] ) ? array_values( array_filter( array_map( 'absint', $job_result['indexed_ids'] ) ) ) : array(); $deadline = microtime( true ) + self::REFRESH_TIME_BUDGET; $slice = array_slice( $post_ids, $processed, self::REFRESH_SLICE_SIZE ); foreach ( $slice as $post_id ) { if ( 0 < $processed && microtime( true ) >= $deadline ) { break; } $result = $this->index_post( $post_id ); if ( 'error' === ( $result['status'] ?? '' ) ) { $errors[] = $result; } else { $indexed_ids[] = $post_id; } ++$processed; $checkpoint = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => 'running', 'processed_items' => $processed, 'error_count' => count( $errors ), 'result' => $this->refresh_job_result( $indexed_ids, $errors, $total, $processed ), ) ); if ( array() === $checkpoint ) { return array( 'status' => 'error', 'error' => 'job_lease_lost', 'message' => 'The refresh worker stopped because its lease was reclaimed before the progress checkpoint.', 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, ); } } if ( $processed < $total ) { if ( ! $this->schedule_refresh_worker( $job_key ) ) { $failed_job = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => 'failed', 'processed_items' => $processed, 'error_count' => count( $errors ) + 1, 'result' => array_merge( $this->refresh_job_result( $indexed_ids, $errors, $total, $processed ), array( 'error' => 'job_continuation_schedule_failed', 'recovery_action' => 'Restore WP-Cron or a system cron runner, then submit a new queued refresh.', ) ), ), true ); if ( array() !== $failed_job ) { $this->clear_refresh_recovery( $job_key ); } return array( 'status' => 'error', 'error' => 'job_continuation_schedule_failed', 'message' => 'The refresh slice completed, but its continuation could not be scheduled.', 'job' => $failed_job, 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, ); } $queued_job = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => 'queued', 'processed_items' => $processed, 'error_count' => count( $errors ), 'result' => array_merge( $this->refresh_job_result( $indexed_ids, $errors, $total, $processed ), array( 'continuation_pending' => true ) ), ), true ); if ( array() === $queued_job ) { return array( 'status' => 'error', 'error' => 'job_lease_lost', 'message' => 'The refresh worker stopped because its lease was reclaimed before queuing the continuation.', 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, ); } return array( 'status' => 'queued', 'job' => $queued_job, 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, 'index' => $this->job_index_summary( $total, $processed, count( $errors ) ), ); } $this->refresh_detected_memories(); $status = array() === $errors ? 'complete' : 'partial'; $job = $this->repo()->update_claimed_job( $job_key, $lease_token, array( 'status' => $status, 'processed_items' => $processed, 'error_count' => count( $errors ), 'result' => $this->refresh_job_result( $indexed_ids, $errors, $total, $processed ), ), true ); if ( array() === $job ) { return array( 'status' => 'error', 'error' => 'job_lease_lost', 'message' => 'The refresh worker stopped because its lease was reclaimed before the terminal checkpoint.', 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, ); } $this->clear_refresh_recovery( $job_key ); return array( 'status' => $status, 'job' => $job, 'total_items' => $total, 'processed_items' => $processed, 'errors' => $errors, 'index' => $this->job_index_summary( $total, $processed, count( $errors ) ), ); } /** * Build the bounded durable result stored at each checkpoint. * * @param array $indexed_ids Processed IDs without index-write errors. * @param array $errors Bounded per-item errors. * @param int $total Total work items. * @param int $processed Completed work items. * @phpstan-param list $indexed_ids * @phpstan-param list> $errors * @return array */ private function refresh_job_result( array $indexed_ids, array $errors, int $total, int $processed ): array { return array( 'indexed_ids' => array_values( array_unique( $indexed_ids ) ), 'errors' => array_slice( $errors, 0, self::MAX_BATCH_LIMIT ), 'summary' => $this->job_index_summary( $total, $processed, count( $errors ) ), ); } /** * Schedule one worker or replace a later recovery event with an earlier continuation. * * @param string $job_key Job key. * @param int $delay Seconds before execution. */ private function schedule_refresh_worker( string $job_key, int $delay = 5 ): bool { if ( '' === $job_key || ! function_exists( 'wp_schedule_single_event' ) ) { return false; } $args = array( $job_key ); $timestamp = time() + max( 5, $delay ); if ( function_exists( 'wp_next_scheduled' ) ) { $scheduled = wp_next_scheduled( self::REFRESH_JOB_HOOK, $args ); if ( false !== $scheduled && (int) $scheduled <= $timestamp ) { return true; } if ( false !== $scheduled ) { if ( ! function_exists( 'wp_unschedule_event' ) ) { return false; } $unscheduled = wp_unschedule_event( (int) $scheduled, self::REFRESH_JOB_HOOK, $args, true ); if ( is_wp_error( $unscheduled ) ) { return false; } } } $scheduled = wp_schedule_single_event( $timestamp, self::REFRESH_JOB_HOOK, $args, true ); return false !== $scheduled && ! is_wp_error( $scheduled ); } /** * Ensure at least one post-lease recovery event remains scheduled. * * @param string $job_key Job key. */ private function schedule_refresh_recovery( string $job_key ): bool { if ( '' === $job_key || ! function_exists( 'wp_schedule_single_event' ) ) { return false; } $args = array( $job_key ); if ( function_exists( 'wp_next_scheduled' ) && false !== wp_next_scheduled( self::REFRESH_RECOVERY_HOOK, $args ) ) { return true; } $scheduled = wp_schedule_single_event( time() + self::REFRESH_LEASE_TTL + 5, self::REFRESH_RECOVERY_HOOK, $args, true ); return false !== $scheduled && ! is_wp_error( $scheduled ); } /** * Ensure a watchdog exists before attempting an atomic claim. * * @param string $job_key Job key. */ private function ensure_refresh_recovery( string $job_key ): bool { if ( '' === $job_key || ! function_exists( 'wp_schedule_single_event' ) ) { return false; } $args = array( $job_key ); if ( function_exists( 'wp_next_scheduled' ) && false !== wp_next_scheduled( self::REFRESH_RECOVERY_HOOK, $args ) ) { return true; } $scheduled = wp_schedule_single_event( time() + self::REFRESH_LEASE_TTL + 5, self::REFRESH_RECOVERY_HOOK, $args, true ); return false !== $scheduled && ! is_wp_error( $scheduled ); } /** * Remove an initial worker event when its watchdog cannot be created. * * @param string $job_key Job key. */ private function clear_refresh_worker( string $job_key ): void { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_unschedule_event' ) ) { return; } $args = array( $job_key ); $scheduled = wp_next_scheduled( self::REFRESH_JOB_HOOK, $args ); if ( false !== $scheduled ) { wp_unschedule_event( (int) $scheduled, self::REFRESH_JOB_HOOK, $args ); } } /** * Remove the watchdog after a terminal job transition. * * @param string $job_key Job key. */ private function clear_refresh_recovery( string $job_key ): void { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_unschedule_event' ) ) { return; } $args = array( $job_key ); $scheduled = wp_next_scheduled( self::REFRESH_RECOVERY_HOOK, $args ); if ( false !== $scheduled ) { wp_unschedule_event( (int) $scheduled, self::REFRESH_RECOVERY_HOOK, $args ); } } /** * Process a resolved set of post IDs for a refresh job. * * @param string $job_key Job key. * @param array $post_ids Resolved post IDs. * @phpstan-param list $post_ids * @return array */ private function run_refresh_job( string $job_key, array $post_ids ): array { if ( '' !== $job_key ) { $this->repo()->update_job( $job_key, array( 'status' => 'running', 'processed_items' => 0, 'error_count' => 0, 'result' => array(), ) ); } $processed = 0; $errors = array(); foreach ( $post_ids as $post_id ) { $result = $this->index_post( $post_id ); if ( 'error' === ( $result['status'] ?? '' ) ) { $errors[] = $result; } ++$processed; } $this->refresh_detected_memories(); $status = array() === $errors ? 'complete' : 'partial'; $job = '' === $job_key ? array() : $this->repo()->update_job( $job_key, array( 'status' => $status, 'processed_items' => $processed, 'error_count' => count( $errors ), 'result' => array( 'indexed_ids' => $post_ids, 'errors' => $errors, 'summary' => $this->job_index_summary( count( $post_ids ), $processed, count( $errors ) ), ), ) ); return array( 'status' => $status, 'job' => $job, 'total_items' => count( $post_ids ), 'processed_items' => $processed, 'errors' => $errors, 'index' => $this->job_index_summary( count( $post_ids ), $processed, count( $errors ) ), ); } /** * Return a dry-run preview for a refresh batch. * * @param array $args Batch args. * @return array */ public function preview_refresh_batch( array $args ): array { $post_ids = $this->post_ids_for_batch( $args ); return array( 'status' => 'preview', 'dry_run' => true, 'total_items' => count( $post_ids ), 'post_ids' => $post_ids, 'index' => $this->job_index_summary( count( $post_ids ), 0, 0 ), 'next_actions' => array( 'Repeat content_index_refresh_batch without dry_run to refresh these index rows.' ), ); } /** * Store detected brand/site memory from saved profile and site options. */ public function refresh_detected_memories(): void { if ( ! function_exists( 'get_option' ) ) { return; } $profile = ( new BrandProfile() )->public_profile(); $items = array( 'brand.site.name' => $profile['site']['name']['value'] ?? '', 'brand.site.tagline' => $profile['site']['tagline']['value'] ?? '', 'brand.editorial.tone' => $profile['editorial']['tone']['value'] ?? '', 'brand.editorial.audience' => $profile['editorial']['audience']['value'] ?? '', 'brand.editorial.avoid' => $profile['editorial']['avoid']['value'] ?? '', 'brand.colors.primary' => $profile['colors']['primary']['value'] ?? '', 'brand.colors.accent' => $profile['colors']['accent']['value'] ?? '', ); foreach ( $items as $key => $value ) { if ( ! is_scalar( $value ) || '' === trim( (string) $value ) ) { continue; } ( new Memory\MemoryService() )->save( array( 'key' => $key, 'domain' => str_starts_with( $key, 'brand.' ) ? 'brand' : 'site', 'value' => (string) $value, 'evidence' => 'Detected from saved Aculect brand profile or WordPress site defaults.', 'confidence' => 'high', 'status' => 'approved', 'source' => 'detected', ) ); } } /** * Convert serialized block content into section-level chunks. * * @param int $post_id Post ID. * @param string $content Post content. * @return list> */ public function chunks_from_content( int $post_id, string $content ): array { $blocks = $this->serialized_blocks( $content ); if ( array() === $blocks ) { $text = $this->plain_text( $content ); return '' === $text ? array() : array( $this->chunk_row( $post_id, 1, 'content', 'content', 0, 1, $text, $content ), ); } $chunks = array(); $current = null; $position = 0; foreach ( $blocks as $block ) { $is_heading = 'core/heading' === $block['name']; $text = $this->plain_text( $block['markup'] ); if ( '' === $text && ! $is_heading ) { ++$position; continue; } if ( $is_heading && null !== $current && array() !== $current['blocks'] ) { $chunks[] = $this->chunk_from_accumulator( $post_id, count( $chunks ) + 1, $current ); $current = null; } if ( null === $current ) { $heading = $is_heading ? $text : sprintf( 'Section %d', count( $chunks ) + 1 ); $current = array( 'heading' => $heading, 'anchor' => $this->slug( $heading ), 'block_start' => $position, 'blocks' => array(), 'texts' => array(), ); } $current['blocks'][] = $block['markup']; if ( '' !== $text ) { $current['texts'][] = $text; } if ( $this->word_count( implode( ' ', $current['texts'] ) ) >= self::MAX_CHUNK_WORDS ) { $chunks[] = $this->chunk_from_accumulator( $post_id, count( $chunks ) + 1, $current ); $current = null; } ++$position; } if ( null !== $current && array() !== $current['blocks'] ) { $chunks[] = $this->chunk_from_accumulator( $post_id, count( $chunks ) + 1, $current ); } return $chunks; } /** * Extract outbound links from content. * * @param int $post_id Post ID. * @param string $content Post content. * @return list> */ public function links_from_content( int $post_id, string $content ): array { unset( $post_id ); if ( ! preg_match_all( '/]*href=(["\'])(.*?)\1[^>]*>(.*?)<\/a>/is', $content, $matches, PREG_SET_ORDER ) ) { return array(); } $links = array(); $resolved = 0; foreach ( array_slice( $matches, 0, 300 ) as $match ) { $url = esc_url_raw( html_entity_decode( (string) $match[2], ENT_QUOTES ) ); if ( '' === $url ) { continue; } $target_id = 0; if ( $resolved < self::MAX_RESOLVED_LINKS && $this->is_internal_url( $url ) ) { $target_id = $this->target_post_id( $url ); ++$resolved; } $links[] = array( 'target_id' => $target_id, 'target_url' => $url, 'anchor_text' => $this->plain_text( (string) $match[3] ), 'rel' => '', 'context' => $this->summary( $this->plain_text( (string) $match[0] ), 20 ), ); } return $links; } /** * Check whether a URL points at this site before resolving it to a post. * * Cheap host comparison so external links never trigger url_to_postid(). * * @param string $url Link URL. */ private function is_internal_url( string $url ): bool { $host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) ); if ( '' === $host ) { return str_starts_with( $url, '/' ); } if ( ! function_exists( 'home_url' ) ) { return false; } return strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ) === $host; } /** * Return queryable post IDs for a refresh batch. * * @param array $args Batch args. * @return list */ private function post_ids_for_batch( array $args ): array { if ( isset( $args['ids'] ) && is_array( $args['ids'] ) ) { $ids = array_values( array_filter( array_map( 'absint', $args['ids'] ) ) ); $ids = array_values( array_unique( $ids ) ); sort( $ids ); return array_slice( $ids, 0, self::MAX_BATCH_LIMIT ); } if ( ! function_exists( 'get_posts' ) ) { return array(); } $post_type = sanitize_key( (string) ( $args['post_type'] ?? 'post' ) ); $limit = min( self::MAX_BATCH_LIMIT, max( 1, absint( $args['limit'] ?? self::DEFAULT_BATCH_LIMIT ) ) ); $status = $this->status_arg( $args['status'] ?? self::INDEXABLE_STATUSES ); $ids = get_posts( array( 'post_type' => '' === $post_type ? 'post' : $post_type, 'post_status' => $status, 'posts_per_page' => $limit, 'fields' => 'ids', 'orderby' => 'modified', 'order' => 'DESC', 'perm' => 'readable', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ) ); return array_values( array_filter( array_map( 'absint', $ids ) ) ); } /** * Return public batch args for job storage. * * @param array $args Batch args. * @return array */ private function batch_public_args( array $args ): array { return array( 'post_type' => sanitize_key( (string) ( $args['post_type'] ?? 'post' ) ), 'status' => $this->status_arg( $args['status'] ?? self::INDEXABLE_STATUSES ), 'limit' => min( self::MAX_BATCH_LIMIT, max( 1, absint( $args['limit'] ?? self::DEFAULT_BATCH_LIMIT ) ) ), 'ids' => isset( $args['ids'] ) && is_array( $args['ids'] ) ? array_slice( array_values( array_filter( array_map( 'absint', $args['ids'] ) ) ), 0, self::MAX_BATCH_LIMIT ) : array(), ); } /** * Check whether a post should be indexed. * * @param \WP_Post $post Post object. */ private function is_indexable_post( \WP_Post $post ): bool { if ( ! in_array( (string) $post->post_status, self::INDEXABLE_STATUSES, true ) ) { return false; } if ( in_array( (string) $post->post_type, array( 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request' ), true ) ) { return false; } if ( ! function_exists( 'get_post_type_object' ) ) { return true; } $type = get_post_type_object( (string) $post->post_type ); if ( ! $type instanceof \WP_Post_Type ) { return false; } return (bool) $type->public || (bool) $type->show_ui || (bool) $type->show_in_rest; } /** * Extract a deterministic block list from serialized block markup. * * Uses the core block parser so nested inner blocks of layout containers * are chunked individually instead of being swallowed into the parent * match, which degraded chunk quality on builder-style pages. The regex * path remains as a non-WordPress fallback for isolated unit tests. * * @param string $content Serialized content. * @return list */ private function serialized_blocks( string $content ): array { if ( ! function_exists( 'parse_blocks' ) || ! function_exists( 'serialize_block' ) ) { return $this->serialized_blocks_from_regex( $content ); } $flat = array(); $this->flatten_blocks( (array) parse_blocks( $content ), $flat ); return $flat; } /** * Flatten parsed blocks, recursing into layout containers. * * @param array $blocks Parsed block list. * @param list $flat Output accumulator. */ private function flatten_blocks( array $blocks, array &$flat ): void { $containers = array( 'core/group', 'core/columns', 'core/column', 'core/cover', 'core/stack', 'core/row' ); foreach ( $blocks as $block ) { if ( ! is_array( $block ) ) { continue; } $name = (string) ( $block['blockName'] ?? '' ); if ( '' === $name ) { $html = trim( (string) ( $block['innerHTML'] ?? '' ) ); if ( '' !== $html ) { $flat[] = array( 'name' => 'core/freeform', 'markup' => $html, ); } continue; } $inner = is_array( $block['innerBlocks'] ?? null ) ? $block['innerBlocks'] : array(); if ( array() !== $inner && in_array( $name, $containers, true ) ) { $this->flatten_blocks( $inner, $flat ); continue; } $flat[] = array( 'name' => $name, 'markup' => (string) serialize_block( $block ), ); } } /** * Regex fallback block extraction for environments without the parser. * * @param string $content Serialized content. * @return list */ private function serialized_blocks_from_regex( string $content ): array { if ( ! preg_match_all( '/(?:(.*?))?/is', $content, $matches, PREG_SET_ORDER ) ) { return array(); } $blocks = array(); foreach ( $matches as $match ) { $name = (string) $match[1]; $name = str_contains( $name, '/' ) ? $name : 'core/' . $name; $blocks[] = array( 'name' => $name, 'markup' => (string) $match[0], ); } return $blocks; } /** * Build one chunk from accumulated blocks. * * @param int $post_id Content ID. * @param int $index Section index. * @param array $current Accumulator. * @return array */ private function chunk_from_accumulator( int $post_id, int $index, array $current ): array { $text = implode( "\n\n", array_map( 'strval', (array) ( $current['texts'] ?? array() ) ) ); $markup = implode( "\n", array_map( 'strval', (array) ( $current['blocks'] ?? array() ) ) ); $heading = sanitize_text_field( (string) ( $current['heading'] ?? sprintf( 'Section %d', $index ) ) ); $anchor = sanitize_key( (string) ( $current['anchor'] ?? $this->slug( $heading ) ) ); return $this->chunk_row( $post_id, $index, '' === $anchor ? 'section-' . $index : $anchor, $heading, absint( $current['block_start'] ?? 0 ), count( (array) ( $current['blocks'] ?? array() ) ), $text, $markup ); } /** * Build one chunk row. * * @param int $post_id Content ID. * @param int $index Section index. * @param string $chunk_id Stable chunk ID. * @param string $heading Section heading. * @param int $block_start First block index. * @param int $block_count Block count. * @param string $text Plain text. * @param string $markup Block markup. * @return array */ private function chunk_row( int $post_id, int $index, string $chunk_id, string $heading, int $block_start, int $block_count, string $text, string $markup ): array { return array( 'object_id' => $post_id, 'chunk_id' => sprintf( 'section-%03d-%s', $index, substr( sanitize_key( $chunk_id ), 0, 80 ) ), 'heading' => $heading, 'anchor' => sanitize_key( $chunk_id ), 'section_index' => $index, 'word_count' => $this->word_count( $text ), 'content_hash' => hash( 'sha256', $markup ), 'block_start' => $block_start, 'block_count' => $block_count, 'text' => $text, 'block_markup' => $markup, 'metadata' => array( 'post_id' => $post_id, ), ); } /** * Return plain text from block or HTML content. * * @param string $content Raw content. */ private function plain_text( string $content ): string { $content = preg_replace( '//i', ' ', $content ) ?? $content; $content = html_entity_decode( $content, ENT_QUOTES ); $text = wp_strip_all_tags( $content ); return preg_replace( '/\s+/', ' ', trim( $text ) ) ?? ''; } /** * Build a summary from the first words. * * @param string $text Source text. * @param int $words Max words. */ private function summary( string $text, int $words = 45 ): string { $parts = preg_split( '/\s+/', trim( $text ) ); if ( ! is_array( $parts ) ) { return ''; } $summary = implode( ' ', array_slice( array_filter( $parts ), 0, max( 1, $words ) ) ); return strlen( $summary ) < strlen( $text ) ? $summary . '...' : $summary; } /** * Count words in plain text. * * @param string $text Plain text. */ private function word_count( string $text ): int { $words = preg_split( '/\s+/', trim( $text ) ); return is_array( $words ) ? count( array_filter( $words ) ) : 0; } /** * Build a slug. * * @param string $value Raw value. */ private function slug( string $value ): string { if ( function_exists( 'sanitize_title' ) ) { return sanitize_title( $value ); } return trim( strtolower( preg_replace( '/[^A-Za-z0-9]+/', '-', $value ) ?? '' ), '-' ); } /** * Build searchable text. * * @param \WP_Post $post Post. * @param string $plain_text Plain content text. * @param list> $terms Term metadata. */ private function search_text( \WP_Post $post, string $plain_text, array $terms ): string { $term_names = array_values( array_filter( array_map( static fn ( array $term ): string => (string) ( $term['name'] ?? '' ), $terms ) ) ); return trim( implode( "\n", array( $post->post_title, $post->post_excerpt, implode( ' ', $term_names ), $plain_text ) ) ); } /** * Return post title. * * @param \WP_Post $post Post object. */ private function post_title( \WP_Post $post ): string { return function_exists( 'get_the_title' ) ? (string) get_the_title( $post ) : (string) $post->post_title; } /** * Return post excerpt. * * @param \WP_Post $post Post object. */ private function excerpt( \WP_Post $post ): string { return $this->plain_text( (string) $post->post_excerpt ); } /** * Return permalink when available. * * @param \WP_Post $post Post object. */ private function permalink( \WP_Post $post ): string { if ( function_exists( 'get_permalink' ) ) { return get_permalink( $post ); } return ''; } /** * Return safe term metadata for a post. * * @param \WP_Post $post Post object. * @return list> */ private function terms_for_post( \WP_Post $post ): array { if ( ! function_exists( 'get_object_taxonomies' ) || ! function_exists( 'wp_get_post_terms' ) ) { return array(); } $taxonomies = get_object_taxonomies( (string) $post->post_type, 'names' ); if ( ! is_array( $taxonomies ) ) { return array(); } $items = array(); foreach ( $taxonomies as $taxonomy ) { $terms = wp_get_post_terms( (int) $post->ID, (string) $taxonomy, array( 'fields' => 'all', ) ); if ( is_wp_error( $terms ) || ! is_array( $terms ) ) { continue; } foreach ( $terms as $term ) { if ( $term instanceof \WP_Term ) { $items[] = array( 'id' => (int) $term->term_id, 'taxonomy' => (string) $term->taxonomy, 'name' => (string) $term->name, 'slug' => (string) $term->slug, ); } } } return $items; } /** * Resolve an internal URL to a target post ID when WordPress can do so. * * @param string $url Target URL. */ private function target_post_id( string $url ): int { if ( ! function_exists( 'url_to_postid' ) ) { return 0; } if ( ! isset( self::$url_post_ids[ $url ] ) ) { self::$url_post_ids[ $url ] = absint( url_to_postid( $url ) ); } return self::$url_post_ids[ $url ]; } /** * Normalize status input. * * @param mixed $status Raw status value. * @return list */ private function status_arg( mixed $status ): array { if ( is_string( $status ) ) { $status = array_map( 'trim', explode( ',', $status ) ); } $statuses = is_array( $status ) ? $status : array( $status ); $statuses = array_values( array_intersect( array_map( 'sanitize_key', array_map( 'strval', $statuses ) ), self::INDEXABLE_STATUSES ) ); return array() === $statuses ? self::INDEXABLE_STATUSES : $statuses; } /** * Build a small status payload. * * @param string $status Status. * @param int $post_id Post ID. * @param string $reason Reason. * @return array */ private function result( string $status, int $post_id, string $reason ): array { return array( 'status' => $status, 'post_id' => $post_id, 'reason' => $reason, ); } /** * Return an index summary that does not leak global content counts to normal users. * * @param int $total_items Job total item count. * @param int $processed_items Job processed item count. * @param int $error_count Job error count. * @return array */ private function job_index_summary( int $total_items, int $processed_items, int $error_count ): array { if ( ! function_exists( 'current_user_can' ) || current_user_can( 'manage_options' ) ) { return $this->repo()->summary(); } return array( 'filtered_by_access' => true, 'job_total_items' => max( 0, $total_items ), 'job_processed_items' => max( 0, $processed_items ), 'job_error_count' => max( 0, $error_count ), ); } /** * Return repository instance. */ private function repo(): ContentIndexRepository { return $this->repository ?? new ContentIndexRepository(); } }