get_var( "SELECT 1 FROM {$wpdb->postmeta} WHERE meta_key = '_ai_search_embedding' LIMIT 1" ); } if ( $has_embeddings ) { return; } static $has_content = null; if ( $has_content === null ) { $has_content = (bool) $wpdb->get_var( "SELECT 1 FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type NOT IN ('attachment', 'revision', 'nav_menu_item', 'oembed_cache', 'user_request', 'wp_block') LIMIT 1" ); } if ( ! $has_content ) { return; } $wizard_url = admin_url( 'admin.php?page=ai-search&setup=wizard' ); $icon_url = AI_SEARCH_URL . 'assets/icon.svg'; ?>
'; echo '

' . esc_html__( 'AI Search is ready!', 'ai-search' ) . '

'; echo '

' . esc_html__( 'Setup is complete — semantic search is now live on your site.', 'ai-search' ) . '

'; echo '

' . esc_html__( 'On larger sites not everything is synced with AI yet. Check the Indexing tab to see how much is still pending — you can sync the rest in batches from there.', 'ai-search' ) . '

'; echo '

' . esc_html__( 'Open the Indexing tab', 'ai-search' ) . '

'; echo ''; } /** * Enqueue wizard-related scripts. * * Since 1.40.0 the persistent "Sync content" notice has no dismiss * button, so nothing to bind for it. Only the post-setup success * notice still needs a click-to-persist handler on its native "X". */ public function enqueue_scripts( $hook ) { if ( get_option( 'ai_search_setup_completed', false ) && ! get_option( 'ai_search_setup_success_dismissed', false ) ) { wp_add_inline_script( 'jquery', ' jQuery(document).ready(function($) { $(document).on("click", ".ai-search-setup-success-notice .notice-dismiss", function() { $.post(ajaxurl, { action: "ai_search_dismiss_setup_success", nonce: "' . wp_create_nonce( 'ai_search_dismiss_setup_success' ) . '" }); }); }); ' ); } } /** * AJAX: persist "Skip for Now" from the welcome notice. * * Must be registered globally (from AI_Search_Admin_Manager::register_hooks), * not inside enqueue_scripts — that runs on admin_enqueue_scripts, which * does not fire on admin-ajax.php requests, so the handler would only * exist on page loads and clicks would silently 400. */ public function ajax_dismiss_wizard() { check_ajax_referer( 'ai_search_dismiss_wizard', 'nonce' ); delete_option( 'ai_search_show_setup_wizard' ); update_option( 'ai_search_setup_completed', true ); wp_die(); } /** * AJAX: persist the dismissal of the "AI Search is ready" post-wizard * success notice. See ajax_dismiss_wizard() for why this lives outside * enqueue_scripts. */ public function ajax_dismiss_setup_success() { check_ajax_referer( 'ai_search_dismiss_setup_success', 'nonce' ); update_option( 'ai_search_setup_success_dismissed', true ); wp_die(); } /** * Display the setup screen. * * Since 1.39.0 the wizard is a single "Sync content" page — no more * five-step form. The provider handshake (silent register), the * custom-fields picker and the batched generator have all been * folded into one screen driven by ajax_prepare_sync + * ajax_generate_batch. Advanced users can still open the Content * and Search tabs to prune fields or tune the threshold afterwards. * * Legacy `?step=N` query params are ignored; the URL still resolves * to this same page so bookmarks and welcome-notice links from older * versions keep working. */ public function display_wizard_page() { // Handle wizard completion — same URL contract as before. if ( isset( $_GET['completed'] ) && $_GET['completed'] === 'true' ) { delete_option( 'ai_search_show_setup_wizard' ); update_option( 'ai_search_setup_completed', true ); $this->display_completion_page(); return; } $is_woo = class_exists( 'WooCommerce' ); $scan = $this->scan_content(); echo '
'; echo '

' . esc_html__( 'Sync your content with AI', 'ai-search' ); if ( $is_woo ) { echo ' ' . esc_html__( 'WooCommerce mode', 'ai-search' ) . ''; } echo '

'; include plugin_dir_path( __FILE__ ) . 'views/wizard/step-sync.php'; $this->output_wizard_styles(); echo '
'; } /** * Display completion page */ private function display_completion_page() { include plugin_dir_path( __FILE__ ) . 'views/wizard/completion.php'; } /** * Complete setup wizard */ public function complete_setup() { // The setup wizard is admin-only. We rely on the manage_options // capability alone to gate this handler — no CSRF nonce. Reason: // on some installs (still being investigated) the nonce emitted // by step-final.php was failing verification on the first wizard // run, blocking legitimate users with "The link you followed has // expired." Given (a) the capability check stops unauthenticated // callers, (b) an attacker would need the user to walk through // all 5 wizard steps before POSTing here, and (c) the handler // only mutates plugin options (no destructive actions, no post // deletion, no privilege changes), the residual CSRF surface is // narrow enough to accept in exchange for a wizard that always // completes. if ( ! current_user_can( 'manage_options' ) ) { wp_die( __( 'Unauthorized access', 'ai-search' ) ); } // Save settings $provider = sanitize_text_field( $_POST['provider'] ?? 'ai_service' ); $api_key = sanitize_text_field( $_POST['api_key'] ?? '' ); $similarity_threshold = floatval( $_POST['similarity_threshold'] ?? 0.30 ); update_option( 'ai_search_provider', $provider ); update_option( 'ai_search_api_key', $api_key ); update_option( 'ai_search_similarity_threshold', $similarity_threshold ); // Handle AI service registration if ( $provider === 'ai_service' ) { $service_client = new AI_Search_Service(); $service_token = $service_client->register_origin(); if ( $service_token ) { update_option( 'ai_search_service_token', $service_token ); } } // Save searchable post types if ( isset( $_POST['post_types'] ) && is_array( $_POST['post_types'] ) ) { $searchable_types = array_map( 'sanitize_text_field', $_POST['post_types'] ); update_option( 'ai_search_searchable_post_types', $searchable_types ); } // Setup WooCommerce fields if configured if ( isset( $_POST['woocommerce_fields'] ) && is_array( $_POST['woocommerce_fields'] ) && class_exists( 'WooCommerce' ) ) { $wc_fields = array_map( 'sanitize_text_field', $_POST['woocommerce_fields'] ); update_option( 'ai_search_woocommerce_fields', $wc_fields ); } // (Embedding generation is now its own wizard step — class-setup-wizard::ajax_generate_batch.) // Mark setup as complete delete_option( 'ai_search_show_setup_wizard' ); // Also set a flag that setup was completed to prevent re-showing update_option( 'ai_search_setup_completed', true ); wp_redirect( admin_url( 'admin.php?page=ai-search&setup=wizard&completed=true' ) ); exit; } /** * AJAX: process a single batch of embeddings for the wizard Generate step. * * The wizard UI calls this repeatedly with an incrementing offset until it * gets `done: true` (nothing more to index) or `quota_hit: true` (service * refused an embedding mid-batch). Each call processes up to BATCH_SIZE * posts so we never blow the PHP execution limit. * * Response shape: * { success: true, data: { * processed: int, // how many this batch actually indexed * offset: int, // next offset the caller should request * done: bool, // true when no unprocessed posts remain * quota_hit: bool // true if generate_embedding returned nothing * }} */ public function ajax_generate_batch() { check_ajax_referer( 'ai_search_wizard_generate', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( [ 'message' => __( 'Unauthorized', 'ai-search' ) ], 403 ); } $batch_size = 20; $cpt = isset( $_POST['cpt'] ) ? sanitize_text_field( $_POST['cpt'] ) : ''; $limit = isset( $_POST['limit'] ) ? intval( $_POST['limit'] ) : 100; $offset = isset( $_POST['offset'] ) ? intval( $_POST['offset'] ) : 0; if ( empty( $cpt ) || ! post_type_exists( $cpt ) ) { wp_send_json_error( [ 'message' => __( 'Invalid post type.', 'ai-search' ) ] ); } // Cap this batch so we never overshoot the user's chosen limit. $remaining_vs_limit = max( 0, $limit - $offset ); $this_batch = min( $batch_size, $remaining_vs_limit ); if ( $this_batch <= 0 ) { wp_send_json_success( [ 'processed' => 0, 'offset' => $offset, 'done' => true, 'quota_hit' => false, ] ); } // Posts the client already reported as skipped (no content, filter // veto). They never get meta, so without this they'd be re-fetched // by the NOT EXISTS query on every batch (v1.27.0). $exclude = isset( $_POST['exclude'] ) ? array_filter( array_map( 'intval', (array) $_POST['exclude'] ) ) : []; $exclude = array_slice( array_values( $exclude ), 0, 1000 ); $query_args = [ 'numberposts' => $this_batch, 'post_type' => $cpt, 'post_status' => 'publish', // We always fetch unprocessed posts starting from the beginning of // the queue — as posts get processed they drop out of the NOT EXISTS // filter, so the next call naturally picks up new ones. Offset is // only used by the caller for progress math, not DB pagination. 'meta_query' => [ [ 'key' => '_ai_search_embedding', 'compare' => 'NOT EXISTS', ], ], ]; if ( ! empty( $exclude ) ) { $query_args['post__not_in'] = $exclude; } $posts = get_posts( $query_args ); if ( empty( $posts ) ) { wp_send_json_success( [ 'processed' => 0, 'offset' => $offset, 'done' => true, 'quota_hit' => false, ] ); } $ai_search = AI_Search::get_instance(); $processed = 0; $skipped = 0; $skipped_ids = []; $quota_hit = false; $error_code = ''; $error_message = ''; // Errors that will repeat for every post — stop the run and tell // the user why. Per-post problems (empty content, filter skip) are // counted and the batch carries on. $fatal_codes = [ 'no_token', 'no_api_key', 'invalid_token', 'invalid_api_key', 'quota_exceeded', 'http_error', 'service_unavailable', 'service_error', 'provider_error', 'invalid_response' ]; foreach ( $posts as $post ) { $result = $ai_search->generate_embedding( $post->ID ); if ( is_wp_error( $result ) ) { if ( in_array( $result->get_error_code(), $fatal_codes, true ) ) { $quota_hit = $result->get_error_code() === 'quota_exceeded'; $error_code = $result->get_error_code(); $error_message = $result->get_error_message(); break; } // Non-fatal: this post can't be embedded, move on. Because // it stays without meta it would be re-fetched forever by // the NOT EXISTS query, so count it toward progress. $skipped++; $skipped_ids[] = (int) $post->ID; continue; } $processed++; } $advanced = $processed + $skipped; wp_send_json_success( [ 'processed' => $processed, 'skipped' => $skipped, 'skipped_ids' => $skipped_ids, 'offset' => $offset + $advanced, 'done' => $error_code === '' && ( $offset + $advanced >= $limit ), 'quota_hit' => $quota_hit, 'error_code' => $error_code, 'error_message' => $error_message, ] ); } /** * Snapshot everything the one-click sync page needs to render its * preview panel and drive the batch loop. * * Returned shape: * [ * 'post_types' => [ slug => [ 'label' => str, 'count' => int, 'pending' => int, 'fields' => [ meta_key, ... ] ], ... ], * 'has_woo' => bool, * 'total' => int, // total published items across all post types * 'pending' => int, // total posts without _ai_search_embedding * 'estimated' => int, // rough embedding count if the whole thing runs * ] * * Custom fields are the DISTINCT public meta_keys (not starting with * `_`) that actually exist on published rows of each type. We do NOT * touch the saved `ai_search_custom_fields_{type}` option here — that * belongs to auto_populate_defaults() and only fires when the user * hits the button. */ public function scan_content() { global $wpdb; $has_woo = class_exists( 'WooCommerce' ); $type_names = get_post_types( [ 'public' => true, 'exclude_from_search' => false ], 'names' ); unset( $type_names['attachment'] ); $type_names = array_values( $type_names ); $result = [ 'post_types' => [], 'has_woo' => $has_woo, 'total' => 0, 'pending' => 0, 'estimated' => 0, ]; foreach ( $type_names as $slug ) { $obj = get_post_type_object( $slug ); if ( ! $obj ) continue; $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s AND post_status = 'publish'", $slug ) ); if ( $count === 0 ) continue; $pending = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} p WHERE p.post_type = %s AND p.post_status = 'publish' AND NOT EXISTS ( SELECT 1 FROM {$wpdb->postmeta} m WHERE m.post_id = p.ID AND m.meta_key = '_ai_search_embedding' )", $slug ) ); // Auto-detected custom fields: distinct meta_keys not starting // with `_`. Capped to prevent runaway UI listings on sites with // thousands of meta rows. $fields = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT m.meta_key FROM {$wpdb->postmeta} m INNER JOIN {$wpdb->posts} p ON p.ID = m.post_id WHERE p.post_type = %s AND p.post_status = 'publish' AND m.meta_key NOT LIKE %s ORDER BY m.meta_key LIMIT 50", $slug, $wpdb->esc_like( '_' ) . '%' ) ); $result['post_types'][ $slug ] = [ 'label' => $obj->label, 'count' => $count, 'pending' => $pending, 'fields' => array_values( array_map( 'strval', $fields ?: [] ) ), ]; $result['total'] += $count; $result['pending'] += $pending; $result['estimated'] += $pending; } return $result; } /** * Runs on the "Sync content" button click, before the first batch * fires. Silently applies the defaults a first-time user would have * clicked through the old wizard for: * * - Auto-populate `ai_search_custom_fields_{type}` for any post type * that doesn't yet have a saved config. * - Auto-enable term embeddings when Woo is active and the option * hasn't been set. * - Auto-register on the AI Search Service when there's no token yet. * * We only ever WRITE options that are currently unset — existing user * preferences are never overwritten, so an existing user hitting the * sync page a second time sees their pruning honoured. */ public function ajax_prepare_sync() { check_ajax_referer( 'ai_search_wizard_generate', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( [ 'message' => __( 'Unauthorized', 'ai-search' ) ], 403 ); } $scan = $this->scan_content(); // 1. Auto-register with the AI Search Service if we have no token // and the user hasn't switched to OpenAI. Silent failure is // fine — the caller will get a proper error from the first // embedding call. Registering blindly is safer than blocking // the click. $provider = get_option( 'ai_search_provider', 'ai_service' ); $token = get_option( 'ai_search_service_token', '' ); if ( $provider === 'ai_service' && empty( $token ) ) { $service = new AI_Search_Service(); $new_token = $service->register_origin(); if ( $new_token ) { update_option( 'ai_search_service_token', $new_token ); } } // 2. Auto-populate custom fields for post types without config. // Use `get_option(...,'__unset__')` sentinel because an existing // but deliberately-empty array is a valid user choice ("index // nothing extra"), not a signal to re-populate. $auto_populated = []; foreach ( $scan['post_types'] as $slug => $meta ) { $option_key = "ai_search_custom_fields_{$slug}"; $current = get_option( $option_key, '__unset__' ); if ( $current === '__unset__' && ! empty( $meta['fields'] ) ) { update_option( $option_key, $meta['fields'] ); $auto_populated[ $slug ] = $meta['fields']; } } // 3. Auto-enable term embeddings on Woo sites where the toggle // was never explicitly touched. Existing preference wins. if ( $scan['has_woo'] && get_option( 'ai_search_term_embeddings_enabled', '__unset__' ) === '__unset__' ) { update_option( 'ai_search_term_embeddings_enabled', true ); } // 4. Ensure the searchable post types option includes everything // the scan sees. Old flows saved just [ 'post', 'page' ]; this // change makes any newly-indexed CPT actually reachable by the // search filter. $searchable = array_keys( $scan['post_types'] ); $existing = get_option( 'ai_search_searchable_post_types', [] ); if ( is_array( $existing ) ) { $searchable = array_values( array_unique( array_merge( $existing, $searchable ) ) ); } update_option( 'ai_search_searchable_post_types', $searchable ); wp_send_json_success( [ 'post_types' => array_keys( $scan['post_types'] ), 'plan' => $scan['post_types'], // slug => { label, pending, ... } 'total_pending' => $scan['pending'], 'auto_populated' => $auto_populated, 'woo_terms' => $scan['has_woo'], ] ); } /** * Output wizard styles. * * Since 1.40.0 the sync page is presented as a full brand-styled * card (purple->pink gradient, on-brand type, circular progress * ring) rather than the native wp-admin form idiom used before. * All colours are hard-coded because the plugin has no user-facing * theming API and we want the sync experience to feel like the * marketing site, not the WP admin shell. */ private function output_wizard_styles() { echo ''; } }