init = $init; $this->options_cache = $options_cache; } /** * Build metabox localization data * * @return array Localization data array. */ public function buildMetaboxData(): array { $provider = $this->options_cache->get( 'aipt_api_provider', Activator::get_default_value( 'api_provider' ) ); $model = $this->options_cache->get( 'aipt_model', Activator::get_default_value( 'model' ) ); $aipt_data = array( 'productId' => get_the_ID(), 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'provider' => $provider, 'model' => $model, 'settingsUrl' => admin_url( 'admin.php?page=aipt-settings&tab=content-settings' ), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'fs' => $this->buildFsBlock(), 'screen' => $this->buildScreenBlock( (int) get_the_ID() ), 'contentStructure' => $this->buildContentStructureBlock(), ); return $this->init->getPremiumFeatureManager()->extendAiptData( $aipt_data ); } /** * Build the AI content panel's product-screen block: the product's own * images, page-builder/SEO-plugin detection, the capabilities and * provider-key presence the panel gates on, and the deep links it opens. * * @since 2.8.0 * @param int $product_id Product id (0 off the product edit screen, e.g. "Add new"). * @return array Screen block, see `buildMetaboxData()`'s `screen` key. */ private function buildScreenBlock( int $product_id ): array { $product = $product_id > 0 && function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : false; return array( 'productImages' => $product instanceof \WC_Product ? $this->buildScreenProductImages( $product ) : array(), 'pageBuilder' => $this->detectScreenPageBuilder( $product_id ), 'seoPlugin' => $this->detectScreenSeoPlugin(), 'focusKeyword' => $this->readScreenFocusKeyword( $product_id ), 'permalink' => $product_id > 0 ? (string) get_permalink( $product_id ) : '', 'canUseBlueprint' => current_user_can( RestConstants::CAP_USE ), 'canManage' => current_user_can( RestConstants::CAP_MANAGE ), 'hasUsableKey' => CredentialResolver::instance()->hasAnyUsableKey(), 'connectionUrl' => admin_url( 'admin.php?page=aipt-settings&tab=api' ), 'generatorUrls' => $this->buildScreenGeneratorUrls(), 'contentTemplatesUrl' => admin_url( 'admin.php?page=aipt-content-templates' ), 'contentBankUrl' => admin_url( 'admin.php?page=aipt-history' ), 'historyEnabled' => SnapshotStore::historyCaptureEnabled(), ); } /** * @param \WC_Product $product Resolved product. * @return array */ private function buildScreenProductImages( \WC_Product $product ): array { $images = array(); foreach ( ( new AttachmentContextBuilder() )->imagesForProduct( $product ) as $image ) { $attachment_id = (int) $image['attachmentId']; $thumb_url = wp_get_attachment_image_url( $attachment_id, 'thumbnail' ); $images[] = array( 'id' => $attachment_id, 'thumbUrl' => is_string( $thumb_url ) ? $thumb_url : '', 'alt' => (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'isFeatured' => (bool) $image['isFeatured'], ); } return $images; } /** * @param int $product_id Product id. * @return array{slug:string,name:string}|null */ private function detectScreenPageBuilder( int $product_id ): ?array { if ( 'builder' === get_post_meta( $product_id, '_elementor_edit_mode', true ) ) { return array( 'slug' => 'elementor', 'name' => 'Elementor' ); } if ( 'on' === get_post_meta( $product_id, '_et_pb_use_builder', true ) ) { return array( 'slug' => 'divi', 'name' => 'Divi' ); } return null; } /** * @return array{slug:string,name:string}|null */ private function detectScreenSeoPlugin(): ?array { $plugin = SeoPluginDetector::detect(); return is_array( $plugin ) ? array( 'slug' => (string) $plugin['plugin_slug'], 'name' => (string) $plugin['plugin_name'] ) : null; } /** * The product's stored focus keyword in the detected SEO plugin, '' when there is none. * * @param int $product_id Product id (0 off the product edit screen). * @return string */ private function readScreenFocusKeyword( int $product_id ): string { if ( $product_id <= 0 || null === SeoPluginDetector::detect() ) { return ''; } $info = SeoPluginDetector::get_seo_info( $product_id, null, false ); return is_array( $info ) ? trim( (string) ( $info['focus_keyword'] ?? '' ) ) : ''; } /** * @return array Generator key => its generator page's admin URL. */ private function buildScreenGeneratorUrls(): array { $urls = array(); foreach ( array( Generators::DESCRIPTION, Generators::TITLE, Generators::SEO_META, Generators::FAQ, Generators::IMAGE_ALT ) as $generator ) { $urls[ $generator ] = admin_url( 'admin.php?page=' . Generators::adminSlug( $generator ) ); } return $urls; } /** * Build settings page localization data * * @return array Localization data array. */ public function buildSettingsData(): array { $settings = $this->maskSettingsApiKeys( $this->init->get_cached_settings_array() ); $resolver = CredentialResolver::instance(); foreach ( array( 'openai', 'gemini', 'openrouter', 'claude' ) as $provider ) { $settings[ $provider . '_api_key_is_set' ] = $resolver->isConfigured( $provider ); } $premium_manager = $this->init->getPremiumFeatureManager(); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'settings' => $settings, 'onboarding' => $this->init->get_onboarding_status_fast(), 'fs' => $this->buildFsBlock(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'shopManagerAccess' => array( 'isAdmin' => current_user_can( 'manage_options' ), 'enabled' => (bool) get_option( 'aipt_allow_shop_manager_settings', false ), ), 'mcpAgentsSummary' => McpSettingsPresenter::summary(), ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); $aipt_data = array_merge( $aipt_data, $this->buildConnectorsBlock() ); return $aipt_data; } /** * Build toolkit page localization data * * @return array Localization data array. */ public function buildToolkitData(): array { $current_user = wp_get_current_user(); $wc_stats = $this->buildWooCommerceStats(); $toolkit_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'siteTimezone' => wp_timezone_string(), 'onboarding' => $this->init->get_onboarding_status_fast(), 'user' => array( 'display_name' => $current_user->display_name, 'user_login' => $current_user->user_login, 'first_name' => $current_user->first_name, ), 'woocommerce' => $wc_stats, 'fs' => $this->buildFsBlock(), 'uiPrefs' => $this->buildUiPrefsData(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'widgetOrder' => \AIPT\Api\Dashboard\DashboardController::get_user_widget_order( (int) $current_user->ID ), 'mcpAgentsSummary' => current_user_can( 'manage_woocommerce' ) ? McpSettingsPresenter::summary() : null, ); $toolkit_data = $this->init->getPremiumFeatureManager()->extendAiptData( $toolkit_data ); return array_merge( $toolkit_data, $this->buildConnectorsBlock() ); } /** * Build WooCommerce statistics * * @return array WooCommerce statistics. */ private function buildWooCommerceStats(): array { $wc_stats = array( 'total_products' => 0, 'published_products' => 0, 'draft_products' => 0, 'missing_description' => 0, 'ai_generated' => 0, 'recent_products' => 0, 'out_of_stock' => 0, 'no_tags' => 0, ); if ( class_exists( 'WooCommerce' ) ) { global $wpdb; try { $total_products = wp_count_posts( 'product' ); if ( $total_products ) { $wc_stats['total_products'] = intval( $total_products->publish ?? 0 ) + intval( $total_products->draft ?? 0 ) + intval( $total_products->pending ?? 0 ) + intval( $total_products->private ?? 0 ); $wc_stats['published_products'] = intval( $total_products->publish ?? 0 ); $wc_stats['draft_products'] = intval( $total_products->draft ?? 0 ); } } catch ( Exception $e ) { } $stats_cache_key = 'aipt_toolkit_stats'; $cached_stats = get_transient( $stats_cache_key ); if ( is_array( $cached_stats ) ) { $wc_stats['missing_description'] = intval( $cached_stats['missing_description'] ?? 0 ); $wc_stats['ai_generated'] = intval( $cached_stats['ai_generated'] ?? 0 ); $wc_stats['recent_products'] = intval( $cached_stats['recent_products'] ?? 0 ); $wc_stats['out_of_stock'] = intval( $cached_stats['out_of_stock'] ?? 0 ); $wc_stats['no_tags'] = intval( $cached_stats['no_tags'] ?? 0 ); } else { $fresh_stats = array( 'missing_description' => 0, 'ai_generated' => 0, 'recent_products' => 0, 'out_of_stock' => 0, 'no_tags' => 0, ); $stats_complete = true; $missing_desc = ( new ProductFilterBuilder() )->contentFilters( array( 'without_full' ) )->countProducts(); if ( null !== $missing_desc ) { $fresh_stats['missing_description'] = $missing_desc; } else { $stats_complete = false; } try { $ai_generated = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT post_id) FROM {$wpdb->postmeta} WHERE meta_key = %s", MetaKeys::ROLLUP ) ); if ( null !== $ai_generated ) { $fresh_stats['ai_generated'] = intval( $ai_generated ); } else { $stats_complete = false; } } catch ( Exception $e ) { $stats_complete = false; } try { $seven_days_ago = gmdate( 'Y-m-d H:i:s', strtotime( '-7 days' ) ); $recent = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status IN ('publish', 'draft') AND post_date >= %s", $seven_days_ago ) ); if ( null !== $recent ) { $fresh_stats['recent_products'] = intval( $recent ); } else { $stats_complete = false; } } catch ( Exception $e ) { $stats_complete = false; } try { $out_of_stock = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'product' AND p.post_status = 'publish' AND pm.meta_key = '_stock_status' AND pm.meta_value = 'outofstock'" ); if ( null !== $out_of_stock ) { $fresh_stats['out_of_stock'] = intval( $out_of_stock ); } else { $stats_complete = false; } } catch ( Exception $e ) { $stats_complete = false; } try { $no_tags = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} p WHERE p.post_type = 'product' AND p.post_status IN ('publish', 'draft') AND p.ID NOT IN ( SELECT DISTINCT tr.object_id FROM {$wpdb->term_relationships} tr INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'product_tag' )" ); if ( null !== $no_tags ) { $fresh_stats['no_tags'] = intval( $no_tags ); } else { $stats_complete = false; } } catch ( Exception $e ) { $stats_complete = false; } set_transient( $stats_cache_key, $fresh_stats, $stats_complete ? 15 * MINUTE_IN_SECONDS : MINUTE_IN_SECONDS ); $wc_stats['missing_description'] = $fresh_stats['missing_description']; $wc_stats['ai_generated'] = $fresh_stats['ai_generated']; $wc_stats['recent_products'] = $fresh_stats['recent_products']; $wc_stats['out_of_stock'] = $fresh_stats['out_of_stock']; $wc_stats['no_tags'] = $fresh_stats['no_tags']; } } return $wc_stats; } /** * Build description generator localization data * * @return array Localization data array. */ public function buildDescriptionGeneratorData(): array { $settings = $this->maskSettingsApiKeys( $this->init->get_cached_advanced_settings_array() ); $premium_manager = $this->init->getPremiumFeatureManager(); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'settings' => $settings, 'locale' => $this->init->convert_locale_format( get_locale() ), 'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD', 'fs' => $this->buildFsBlock(), 'bulk_terms_accepted' => $this->options_cache->get( 'aipt_bulk_terms_accepted', '0' ), 'uiPrefs' => $this->buildUiPrefsData(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentStructure' => $this->buildContentStructureBlock(), ); $aipt_data = array_merge( $aipt_data, $this->buildConnectorsBlock() ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * Build FAQ generator localization data * * @return array Localization data array. */ public function buildFAQGeneratorData(): array { $settings = $this->maskSettingsApiKeys( $this->init->get_cached_settings_array() ); $premium_manager = $this->init->getPremiumFeatureManager(); $faq_defaults = array( 'faqCount' => FAQGeneratorService::DEFAULT_FAQ_COUNT, 'faqFormat' => Init::get_default_faq_format(), 'faqMode' => Init::get_default_faq_mode(), 'writeMode' => 'append', ); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'restNonce' => wp_create_nonce( 'wp_rest' ), 'version' => AIPT_VERSION, 'settings' => $settings, 'locale' => $this->init->convert_locale_format( get_locale() ), 'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD', 'faqDefaults' => $faq_defaults, 'maxFaqCount' => FAQGeneratorService::MAX_FAQ_COUNT, 'faqDisplaySettingsEndpoint' => esc_url_raw( rest_url( 'aipt/v1/faq-display-settings' ) ), 'customFieldsEndpoint' => esc_url_raw( rest_url( 'aipt/v1/custom-fields' ) ), 'fs' => $this->buildFsBlock(), 'uiPrefs' => $this->buildUiPrefsData(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentStructure' => $this->buildContentStructureBlock(), ); $aipt_data = array_merge( $aipt_data, $this->buildConnectorsBlock() ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * Build title generator localization data * * @return array Localization data array. */ public function buildTitleGeneratorData(): array { return $this->buildSharedGeneratorDataImpl(); } /** * Build SEO Meta Generator localization data * * @return array Localization data array. */ public function buildSeoMetaGeneratorData(): array { return $this->buildSharedGeneratorDataImpl(); } /** * Build taxonomy generator localization data * * @return array Localization data array. */ public function buildTaxonomyGeneratorData(): array { return $this->buildSharedGeneratorDataImpl(); } public function buildImageAltGeneratorData(): array { return $this->buildSharedGeneratorDataImpl(); } /** * Build Content History localization data * * @return array Localization data array. */ public function buildContentHistoryData(): array { return $this->buildSharedGeneratorDataImpl(); } /** * Build content structure localization data * * The feature-specific block lives in the extracted * {@see ContentStructureDataBuilder} (same split-candidate pattern as * `buildMigrationNoticeBlock()`) — this method only assembles the shared * envelope every build*Data() method carries and delegates the rest. * * @since 2.8.0 * @return array Localization data array. */ public function buildContentStructureData(): array { $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'locale' => $this->init->convert_locale_format( get_locale() ), 'fs' => $this->buildFsBlock(), 'uiPrefs' => $this->buildUiPrefsData(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentHistory' => array( 'enabled' => SnapshotStore::historyCaptureEnabled() ), ); $aipt_data['contentStructure'] = $this->buildContentStructureBlock(); return $this->init->getPremiumFeatureManager()->extendAiptData( $aipt_data ); } /** * Build AI Agents page localization data. * * The `mcpAgents` block is the admin REST contract's own shape * (`window.aiptData.mcpAgents`, see `docs/mcp-admin-rest-contract-2026-11.md`); * `settings` inside it is built by the exact same {@see McpSettingsPresenter} * the `GET aipt/v1/mcp-admin/settings` route answers with, so the page never * renders a localized settings object that could drift from its own first * REST read. * * @since 2.8.2 * @return array Localization data array. */ public function buildMcpAgentsData(): array { $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'siteTimezone' => wp_timezone_string(), 'locale' => $this->init->convert_locale_format( get_locale() ), 'fs' => $this->buildFsBlock(), ); $aipt_data['mcpAgents'] = array( 'rest_namespace' => 'aipt/v1/mcp-admin', 'settings' => McpSettingsPresenter::present(), 'site_name' => (string) get_bloginfo( 'name' ), 'upgrade_url' => $this->mcpUpgradeUrl(), 'docs_url' => 'https://aiforwoo.com/docs/ai-agents-mcp-server/', 'current_user_id' => get_current_user_id(), ); return $this->init->getPremiumFeatureManager()->extendAiptData( $aipt_data ); } /** * @return string */ private function mcpUpgradeUrl(): string { try { return \AIPT\Core\FsManager::getInstance()->getUpgradeUrl(); } catch ( \Throwable $exception ) { return ''; } } /** * Build AI Bulk Product Editor localization data * * @return array Localization data array. */ public function buildProductEditorData(): array { $content_defaults = ( new \AIPT\Api\ProductEditor\ContentDefaultsService() )->get(); $premium_manager = $this->init->getPremiumFeatureManager(); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'locale' => $this->init->convert_locale_format( get_locale() ), 'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD', 'fs' => $this->buildFsBlock(), 'uiPrefs' => $this->buildUiPrefsData(), 'contentDefaults' => array( 'provider' => $content_defaults['provider'], 'model' => $content_defaults['model'], 'language' => $content_defaults['language'], 'writing_style' => $content_defaults['writing_style'], 'brand_context' => $content_defaults['brand_context'], 'preserveContentImages' => $content_defaults['preserveContentImages'], 'canUpdate' => (bool) current_user_can( 'manage_aipt_settings' ), ), 'wpCron' => array( 'enabled' => ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ), 'alternate' => ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ), ), 'productEditor' => array( 'perPageDefault' => 25, 'maxBatch' => 50, 'decimalSeparator' => function_exists( 'wc_get_price_decimal_separator' ) && ',' === wc_get_price_decimal_separator() ? ',' : '.', 'clearAiMarkOnManualEdit' => (bool) rest_sanitize_boolean( get_option( 'aipt_editor_clear_ai_mark_on_manual_edit', false ) ), ), 'productExportUrl' => ( current_user_can( 'edit_products' ) && current_user_can( 'export' ) ) ? admin_url( 'edit.php?post_type=product&page=product_exporter' ) . '&_wpnonce=' . wp_create_nonce( 'export-selected-products' ) : '', 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentStructure' => $this->buildContentStructureBlock(), ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * Build shared generator data. * * Used by title, SEO meta, taxonomy, and image-alt generator pages. * * @return array Localization data array. */ private function buildSharedGeneratorDataImpl(): array { $settings = $this->maskSettingsApiKeys( $this->init->get_cached_settings_array() ); $premium_manager = $this->init->getPremiumFeatureManager(); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'version' => AIPT_VERSION, 'siteTimezone' => wp_timezone_string(), 'settings' => $settings, 'locale' => $this->init->convert_locale_format( get_locale() ), 'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD', 'fs' => $this->buildFsBlock(), 'uiPrefs' => $this->buildUiPrefsData(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentStructure' => $this->buildContentStructureBlock(), ); $aipt_data = array_merge( $aipt_data, $this->buildConnectorsBlock() ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * The Content templates editor's localized block, for every page that can * open a Blueprint's rules in place: the "Adjust rule" dialog on the * generator pages, Category descriptions and the product edit screen hosts * the same editor as the Content templates page and reads its capability * and plan data (who may save, which Business fields unlock) from here. * * @return array */ private function buildContentStructureBlock(): array { return ( new ContentStructureDataBuilder( $this->options_cache ) )->build(); } /** * Replace API key values with masked previews before serializing settings to JS. * * @param array $settings Settings array from OptionsCache. * @return array Settings with API key fields masked. */ private function maskSettingsApiKeys( array $settings ): array { $resolver = CredentialResolver::instance(); $generic_mask = str_repeat( "\u{2022}", 12 ); $key_fields = array( 'openai' => 'openai_api_key', 'gemini' => 'gemini_api_key', 'openrouter' => 'openrouter_api_key', 'claude' => 'claude_api_key', ); foreach ( $key_fields as $provider => $key_field ) { $value = isset( $settings[ $key_field ] ) ? (string) $settings[ $key_field ] : ''; $source = $resolver->getSource( $provider ); if ( CredentialSource::DATABASE_LOCAL === $source && '' !== $value ) { $settings[ $key_field ] = ApiKeyManager::mask_key_string( $value ); } elseif ( in_array( $source, array( CredentialSource::ENV, CredentialSource::CONSTANT, CredentialSource::DATABASE_CONNECTORS ), true ) ) { $settings[ $key_field ] = $generic_mask; } else { $settings[ $key_field ] = ''; } } foreach ( $settings as $field => $field_value ) { if ( in_array( $field, $key_fields, true ) ) { continue; } if ( is_string( $field_value ) && '' !== $field_value && '_api_key' === substr( (string) $field, -8 ) ) { $settings[ $field ] = ApiKeyManager::mask_key_string( $field_value ); } } return $settings; } /** * Build UI preferences localization data for the Phase 1 provider-cost chip. * * Exposed as `window.aiptData.uiPrefs` so ProviderCostChip can honor the * `aipt_show_provider_cost_usd` opt-in without a REST round-trip on first * paint. Matches the `UiPrefsLocalizedData` type in `src/Types/uiNext.ts`. * * @since 2.6.1 * @return array{showProviderCostUsd:bool} */ /** * "Pause between requests": the one Connection setting every admin page * reads so a bulk run paces its AI requests the same way regardless of * which build*Data() composed that page's payload. Mirrors * SettingsService::clampRequestInterval()'s bounds so a page that never * fetches the full `settings` array still sees the same clamped number. * * @since 2.8.0 * @return int Seconds, clamped to [0, 60]. */ /** * The plugin-wide content mode (`blueprint` = Content Template Mode, * `advanced` = Custom Prompt Mode), on every admin page so a screen can * show or hide mode-specific controls on first paint without a request. * * @return string */ private function buildContentModeValue(): string { return ExecutionModeRegistry::globalMode(); } private function buildRequestIntervalValue(): int { $raw = get_option( 'aipt_request_interval', 0 ); $seconds = is_numeric( $raw ) ? (int) $raw : 0; return max( 0, min( 60, $seconds ) ); } private function buildUiPrefsData(): array { $default = array( 'showProviderCostUsd' => false ); if ( ! function_exists( 'is_user_logged_in' ) || ! is_user_logged_in() ) { return $default; } $value = get_user_meta( (int) get_current_user_id(), 'aipt_show_provider_cost_usd', true ); return array( 'showProviderCostUsd' => ( '1' === (string) $value ), ); } /** * Build AI Store Index localization data * * Preloads all Store Index data to eliminate initial API calls. * This includes profiles, status, settings, filter options, and available fields. * * @return array Localization data array. */ public function buildStoreIndexData(): array { $fs_manager = $this->init->getFsManager(); $premium_manager = $this->init->getPremiumFeatureManager(); $profile_manager = new \AIPT\Api\StoreIndex\ProfileManager(); $profile_manager->ensureDefaultExists(); $profiles = $profile_manager->getAll(); $active_profile = null; $active_profile_id = null; foreach ( $profiles as $profile ) { if ( ! empty( $profile['is_active'] ) ) { $active_profile = $profile; $active_profile_id = (int) $profile['id']; break; } } if ( ! $active_profile_id ) { $default_profile = $profile_manager->getDefault(); if ( $default_profile ) { $active_profile_id = (int) $default_profile['id']; $active_profile = $default_profile; } } $index_settings = new \AIPT\Api\StoreIndex\IndexSettings( $active_profile_id ); $status = $index_settings->getStatus(); $settings = $index_settings->getAll(); if ( ( $status['status'] ?? '' ) === 'building' ) { $job_id = (int) ( $status['build_job_id'] ?? 0 ); $progress = (int) ( $status['progress_percent'] ?? 0 ); $status['needs_manual_process'] = $job_id > 0 && $progress < 100; } $global_settings = $profile_manager->getGlobalSettings(); $global_building_status = $profile_manager->getGlobalBuildingStatus(); $available_fields = $this->getAvailableFieldsData(); $filter_options = $this->getFilterOptionsData(); $next_scheduled_run = null; if ( $fs_manager->isUsingPremiumFiles() && class_exists( '\AIPT\Premium\StoreIndex\ScheduledRebuildService' ) ) { $next_scheduled_run = \AIPT\Premium\StoreIndex\ScheduledRebuildService::getNextScheduledRun(); } $scheduled_skip = $this->options_cache->get( 'aipt_store_index_scheduled_rebuild_skipped', null ); $scheduled_skip_reason = ( is_array( $scheduled_skip ) && isset( $scheduled_skip['reason'] ) && is_string( $scheduled_skip['reason'] ) && '' !== $scheduled_skip['reason'] ) ? $scheduled_skip['reason'] : null; $index_premium = array(); if ( $fs_manager->isUsingPremiumFiles() && class_exists( '\AIPT\Premium\StoreIndex\PremiumIndexCapability' ) ) { $index_premium = \AIPT\Premium\StoreIndex\PremiumIndexCapability::getIndexPremiumData(); } $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'locale' => $this->init->convert_locale_format( get_locale() ), 'wpCron' => array( 'enabled' => ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ), 'alternate' => ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ), ), 'fs' => $this->buildFsBlock(), 'initialSettings' => array( 'enabled' => $global_settings['enabled'] ?? false, 'scheduledEnabled' => (bool) ( $global_settings['scheduled_enabled'] ?? false ), 'scheduleFrequency' => $global_settings['schedule_frequency'] ?? 'daily', 'nextScheduledRun' => $next_scheduled_run, 'scheduledRebuildSkipReason' => $scheduled_skip_reason, ), 'preload' => array( 'profiles' => $profiles, 'activeProfileId' => $active_profile_id, 'status' => $status, 'settings' => $settings, 'globalSettings' => $global_settings, 'globalBuildingStatus' => $global_building_status, 'availableFields' => $available_fields['fields'], 'fieldGroups' => $available_fields['groups'], 'defaultFields' => $available_fields['default_fields'], 'filterOptions' => $filter_options, ), 'premium' => $index_premium, 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * Get available fields data for Store Index. * * This is static data that rarely changes. * Premium field information is dynamically determined via filter hooks. * * @return array Fields, groups, and default fields. */ private function getAvailableFieldsData(): array { $mandatory_fields = ProfileManager::getMandatoryFields(); $premium_only_fields = ProfileManager::getPremiumOnlyFields(); return array( 'fields' => array( array( 'key' => 'sku', 'label' => __( 'SKU', 'ai-product-tools' ), 'description' => __( 'Product stock keeping unit.', 'ai-product-tools' ), 'group' => 'basic', 'mandatory' => in_array( 'sku', $mandatory_fields, true ), 'is_premium' => in_array( 'sku', $premium_only_fields, true ), ), array( 'key' => 'title', 'label' => __( 'Title', 'ai-product-tools' ), 'description' => __( 'Product name/title. Required for product identification.', 'ai-product-tools' ), 'group' => 'basic', 'mandatory' => in_array( 'title', $mandatory_fields, true ), 'is_premium' => in_array( 'title', $premium_only_fields, true ), ), array( 'key' => 'short_description', 'label' => __( 'Short Description', 'ai-product-tools' ), 'description' => __( 'Product excerpt/short description. Recommended for better AI context.', 'ai-product-tools' ), 'group' => 'content', 'mandatory' => in_array( 'short_description', $mandatory_fields, true ), 'is_premium' => in_array( 'short_description', $premium_only_fields, true ), ), array( 'key' => 'description', 'label' => __( 'Full Description', 'ai-product-tools' ), 'description' => __( 'Complete product description.', 'ai-product-tools' ), 'group' => 'content', 'mandatory' => in_array( 'description', $mandatory_fields, true ), 'is_premium' => in_array( 'description', $premium_only_fields, true ), ), array( 'key' => 'price', 'label' => __( 'Price', 'ai-product-tools' ), 'description' => __( 'Regular and sale prices. Required for product recommendations.', 'ai-product-tools' ), 'group' => 'basic', 'mandatory' => in_array( 'price', $mandatory_fields, true ), 'is_premium' => in_array( 'price', $premium_only_fields, true ), ), array( 'key' => 'stock_status', 'label' => __( 'Stock Status', 'ai-product-tools' ), 'description' => __( 'In stock, out of stock, on backorder.', 'ai-product-tools' ), 'group' => 'inventory', 'mandatory' => in_array( 'stock_status', $mandatory_fields, true ), 'is_premium' => in_array( 'stock_status', $premium_only_fields, true ), ), array( 'key' => 'stock_quantity', 'label' => __( 'Stock Quantity', 'ai-product-tools' ), 'description' => __( 'Number of items in stock.', 'ai-product-tools' ), 'group' => 'inventory', 'mandatory' => in_array( 'stock_quantity', $mandatory_fields, true ), 'is_premium' => in_array( 'stock_quantity', $premium_only_fields, true ), ), array( 'key' => 'categories', 'label' => __( 'Categories', 'ai-product-tools' ), 'description' => __( 'Product category assignments. Required for filtering.', 'ai-product-tools' ), 'group' => 'taxonomy', 'mandatory' => in_array( 'categories', $mandatory_fields, true ), 'is_premium' => in_array( 'categories', $premium_only_fields, true ), ), array( 'key' => 'tags', 'label' => __( 'Tags', 'ai-product-tools' ), 'description' => __( 'Product tag assignments.', 'ai-product-tools' ), 'group' => 'taxonomy', 'mandatory' => in_array( 'tags', $mandatory_fields, true ), 'is_premium' => in_array( 'tags', $premium_only_fields, true ), ), array( 'key' => 'attributes', 'label' => __( 'Attributes', 'ai-product-tools' ), 'description' => __( 'Product attributes (color, size, etc.).', 'ai-product-tools' ), 'group' => 'taxonomy', 'mandatory' => in_array( 'attributes', $mandatory_fields, true ), 'is_premium' => in_array( 'attributes', $premium_only_fields, true ), ), ), 'groups' => array( array( 'key' => 'basic', 'label' => __( 'Basic Info', 'ai-product-tools' ), ), array( 'key' => 'content', 'label' => __( 'Content', 'ai-product-tools' ), ), array( 'key' => 'inventory', 'label' => __( 'Inventory', 'ai-product-tools' ), ), array( 'key' => 'taxonomy', 'label' => __( 'Taxonomy', 'ai-product-tools' ), ), ), 'default_fields' => \AIPT\Api\StoreIndex\ProfileManager::getDefaultIncludedFieldsForDisplay(), ); } /** * Get filter options data for Store Index. * * Uses smart limits to handle large product catalogs: * - Max 100 categories (ordered by product count) * - Max 50 tags (ordered by product count) * * @return array Filter options with categories, tags, and total products. */ private function getFilterOptionsData(): array { $categories = array(); $cat_terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 100, ) ); if ( ! is_wp_error( $cat_terms ) ) { foreach ( $cat_terms as $term ) { $categories[] = array( 'id' => (int) $term->term_id, 'name' => $term->name, 'count' => (int) $term->count, ); } } $tags = array(); $tag_terms = get_terms( array( 'taxonomy' => 'product_tag', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 50, ) ); if ( ! is_wp_error( $tag_terms ) ) { foreach ( $tag_terms as $term ) { $tags[] = array( 'id' => (int) $term->term_id, 'name' => $term->name, 'count' => (int) $term->count, ); } } $counts = wp_count_posts( 'product' ); $total_products = isset( $counts->publish ) ? (int) $counts->publish : 0; return array( 'categories' => $categories, 'tags' => $tags, 'total_products' => $total_products, ); } /** * Build automation jobs localization data * * @return array Localization data array. */ public function buildAutomationJobsData(): array { $settings = $this->maskSettingsApiKeys( $this->init->get_cached_settings_array() ); $premium_manager = $this->init->getPremiumFeatureManager(); $onboarding = $this->init->get_onboarding_status_fast(); $aipt_data = array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'siteTimezone' => wp_timezone_string(), 'settings' => $settings, 'locale' => $this->init->convert_locale_format( get_locale() ), 'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD', 'currency_symbol' => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '$', 'onboarding' => $onboarding, 'aipt_setup_completed' => $onboarding['setupCompleted'] ? '1' : '0', 'aipt_needs_setup' => $onboarding['setupCompleted'] ? '0' : '1', 'aipt_site_registered' => ( get_option( 'aipt_site_registered', '0' ) === '1' || get_option( 'aipt_credit_registered', false ) ) ? '1' : '0', 'aipt_bulk_terms_accepted' => $this->options_cache->get( 'aipt_bulk_terms_accepted', '0' ), 'bulk_terms_accepted' => $this->options_cache->get( 'aipt_bulk_terms_accepted', '0' ), 'wpCron' => array( 'enabled' => ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ), 'alternate' => ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ), ), 'fs' => $this->buildFsBlock(), 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), 'contentStructure' => $this->buildContentStructureBlock(), 'automation' => array( 'showTriggerNow' => (bool) apply_filters( 'aipt_automation_show_trigger_now', defined( 'WP_DEBUG' ) && WP_DEBUG ), ), ); $aipt_data = $premium_manager->extendAiptData( $aipt_data ); return $aipt_data; } /** * IDs of the WooCommerce cart, checkout and account pages. * * @return int[] Page IDs, without the "no page" value. */ private function get_woocommerce_system_page_ids(): array { if ( ! function_exists( 'wc_get_page_id' ) ) { return array(); } $ids = array(); foreach ( array( 'cart', 'checkout', 'myaccount' ) as $page ) { $id = (int) wc_get_page_id( $page ); if ( $id > 0 ) { $ids[] = $id; } } return $ids; } /** * Build chatbot admin localization data * * @return array Localization data array. */ public function buildChatbotAdminData(): array { $chatbot_settings = new \AIPT\Api\Chatbot\ChatbotSettings(); $providers = array( 'openai', 'gemini', 'openrouter', 'claude' ); $available_providers = array(); foreach ( $providers as $provider ) { $api_key_getter = array( '\AIPT\Utils\ApiKeyManager', 'get_' . $provider . '_key' ); $available_providers[ $provider ] = is_callable( $api_key_getter ) && ! empty( call_user_func( $api_key_getter ) ); } $profile_manager = new \AIPT\Api\StoreIndex\ProfileManager(); $profile_manager->ensureDefaultExists(); $all_profiles = $profile_manager->getAll(); $index_profiles = array_map( function ( $profile ) { $profile_id = isset( $profile['id'] ) ? (string) $profile['id'] : ''; $profile_name = isset( $profile['name'] ) ? (string) $profile['name'] : ''; $product_count = 0; $index_status = 'idle'; if ( isset( $profile['status']['product_count'] ) ) { $product_count = max( 0, (int) $profile['status']['product_count'] ); } $valid_statuses = array( 'idle', 'building', 'completed' ); if ( isset( $profile['status']['status'] ) && in_array( $profile['status']['status'], $valid_statuses, true ) ) { $index_status = (string) $profile['status']['status']; } return array( 'id' => $profile_id, 'name' => $profile_name, 'product_count' => $product_count, 'status' => $index_status, ); }, $all_profiles ); array_unshift( $index_profiles, array( 'id' => '0', 'name' => __( 'Auto (Active Profile)', 'ai-product-tools' ), 'product_count' => 0, 'status' => 'idle', ) ); $chatbot_premium = array(); if ( class_exists( '\\AIPT\\Premium\\PremiumFeatureManager', false ) && class_exists( '\AIPT\Premium\Chatbot\PremiumChatbotCapability' ) ) { $chatbot_premium = \AIPT\Premium\Chatbot\PremiumChatbotCapability::getChatbotPremiumData(); } return array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'adminUrl' => admin_url(), 'restUrl' => esc_url_raw( rest_url() ), 'version' => AIPT_VERSION, 'siteTimezone' => wp_timezone_string(), 'locale' => $this->init->convert_locale_format( get_locale() ), 'settings' => $chatbot_settings->getAll(), 'defaults' => \AIPT\Api\Chatbot\ChatbotSettings::getDefaults(), 'availableProviders' => $available_providers, 'wpPrivacyPolicyLinked' => null !== \AIPT\Api\Chatbot\ChatbotSettings::wpPrivacyPolicyUrl(), 'wpPrivacyPolicyPageId' => (int) $this->options_cache->get( 'wp_page_for_privacy_policy', 0 ), 'systemPageIds' => $this->get_woocommerce_system_page_ids(), 'homeUrl' => esc_url_raw( home_url( '/' ) ), 'indexProfiles' => $index_profiles, 'endpoints' => array( 'settings' => rest_url( 'aipt/v1/chatbot/settings' ), 'settingsFull' => rest_url( 'aipt/v1/chatbot/settings/full' ), 'messages' => rest_url( 'aipt/v1/chatbot/messages' ), 'detectColors' => rest_url( 'aipt/v1/chatbot/detect-brand-colors' ), ), 'fs' => $this->init->getPremiumFeatureManager()->extendAiptData( array( 'fs' => $this->buildFsBlock() ) )['fs'], 'premium' => $chatbot_premium, 'requestInterval' => $this->buildRequestIntervalValue(), 'contentMode' => $this->buildContentModeValue(), 'multilingual' => ContentStructureDataBuilder::detectMultilingual(), ); } /** * Build chatbot widget localization data for frontend * * @since 2.5.0 * @return array Localization data array. */ public function buildChatbotWidgetData(): array { $chatbot_settings = new \AIPT\Api\Chatbot\ChatbotSettings(); $settings = \AIPT\Api\Chatbot\ChatbotSettings::projectForStorefront( $chatbot_settings->getAll() ); $defaults = \AIPT\Api\Chatbot\ChatbotSettings::getDefaults(); $terms_url = \AIPT\Api\Chatbot\ChatbotSettings::publicPageUrl( $settings['general']['terms_page_id'] ?? null ); $privacy_url = \AIPT\Api\Chatbot\ChatbotSettings::privacyLinkUrl( $settings['general']['privacy_page_id'] ?? null ); return array( 'nonce' => wp_create_nonce( 'wp_rest' ), 'restUrl' => trailingslashit( rest_url() ), 'asyncEnabled' => (bool) apply_filters( ChatbotConstants::ASYNC_ENABLED_FILTER, false ), 'maxMessageLength' => ChatbotConstants::maxMessageLength(), 'is_rtl' => is_rtl(), 'dir' => is_rtl() ? 'rtl' : 'ltr', 'locale' => function_exists( 'determine_locale' ) ? determine_locale() : get_locale(), 'settings' => array( 'enabled' => $settings['general']['enabled'] ?? $defaults['general']['enabled'], 'bot_name' => $settings['general']['bot_name'] ?? $defaults['general']['bot_name'], 'greeting_message' => $settings['general']['greeting_message'] ?? $defaults['general']['greeting_message'], 'language' => $settings['general']['language'] ?? $defaults['general']['language'], 'pre_chat_form_enabled' => $settings['general']['pre_chat_form_enabled'] ?? $defaults['general']['pre_chat_form_enabled'], 'starter_messages_enabled' => $settings['general']['starter_messages_enabled'] ?? $defaults['general']['starter_messages_enabled'], 'starter_messages' => $settings['general']['starter_messages'] ?? $defaults['general']['starter_messages'], 'terms_url' => $terms_url, 'privacy_url' => $privacy_url, 'whatsapp_number' => $settings['general']['whatsapp_number'] ?? '', 'fallback_contact_url' => esc_url_raw( $settings['general']['fallback_contact_url'] ?? '' ), 'placement' => array( 'position' => $settings['placement']['position'] ?? $defaults['placement']['position'], 'offset_x' => $settings['placement']['offset_x'] ?? $defaults['placement']['offset_x'], 'offset_y' => $settings['placement']['offset_y'] ?? $defaults['placement']['offset_y'], 'device' => $settings['placement']['device'] ?? $defaults['placement']['device'], ), 'appearance' => array( 'colors' => array( 'primary' => $settings['appearance']['colors']['primary'] ?? $defaults['appearance']['colors']['primary'], 'secondary' => $settings['appearance']['colors']['secondary'] ?? $defaults['appearance']['colors']['secondary'], 'background' => $settings['appearance']['colors']['background'] ?? $defaults['appearance']['colors']['background'], 'text' => $settings['appearance']['colors']['text'] ?? $defaults['appearance']['colors']['text'], 'user_bubble' => $settings['appearance']['colors']['user_bubble'] ?? $defaults['appearance']['colors']['user_bubble'], 'bot_bubble' => $settings['appearance']['colors']['bot_bubble'] ?? $defaults['appearance']['colors']['bot_bubble'], 'header_bg' => $settings['appearance']['colors']['header_bg'] ?? $defaults['appearance']['colors']['header_bg'], 'footer_bg' => $settings['appearance']['colors']['footer_bg'] ?? $defaults['appearance']['colors']['footer_bg'], 'button_hover' => $settings['appearance']['colors']['button_hover'] ?? $defaults['appearance']['colors']['button_hover'], 'online_indicator' => $settings['appearance']['colors']['online_indicator'] ?? $defaults['appearance']['colors']['online_indicator'], 'launcher_bg' => $settings['appearance']['colors']['launcher_bg'] ?? $defaults['appearance']['colors']['launcher_bg'], 'launcher_icon_color' => $settings['appearance']['colors']['launcher_icon_color'] ?? $defaults['appearance']['colors']['launcher_icon_color'], 'attention_bubble_bg' => $settings['appearance']['colors']['attention_bubble_bg'] ?? $defaults['appearance']['colors']['attention_bubble_bg'], 'attention_bubble_text' => $settings['appearance']['colors']['attention_bubble_text'] ?? $defaults['appearance']['colors']['attention_bubble_text'], 'attention_badge_bg' => $settings['appearance']['colors']['attention_badge_bg'] ?? $defaults['appearance']['colors']['attention_badge_bg'], 'attention_badge_text' => $settings['appearance']['colors']['attention_badge_text'] ?? $defaults['appearance']['colors']['attention_badge_text'], 'hero_bg' => $settings['appearance']['colors']['hero_bg'] ?? $defaults['appearance']['colors']['hero_bg'], ), 'font_family' => $settings['appearance']['font_family'] ?? $defaults['appearance']['font_family'], 'border_radius' => $settings['appearance']['border_radius'] ?? $defaults['appearance']['border_radius'], 'custom_css' => $settings['appearance']['custom_css'] ?? $defaults['appearance']['custom_css'], 'launcher_icon' => $settings['appearance']['launcher_icon'] ?? $defaults['appearance']['launcher_icon'], 'custom_launcher_icon_url' => $settings['appearance']['custom_launcher_icon_url'] ?? $defaults['appearance']['custom_launcher_icon_url'], 'profile_picture_url' => $settings['appearance']['profile_picture_url'] ?? $defaults['appearance']['profile_picture_url'], 'hero_image_url' => $settings['appearance']['hero_image_url'] ?? $defaults['appearance']['hero_image_url'], 'launcher_animation' => $settings['appearance']['launcher_animation'] ?? $defaults['appearance']['launcher_animation'], 'attention_bubble_enabled' => $settings['appearance']['attention_bubble_enabled'] ?? $defaults['appearance']['attention_bubble_enabled'], 'attention_bubble_text' => $settings['appearance']['attention_bubble_text'] ?? $defaults['appearance']['attention_bubble_text'], 'attention_badge_enabled' => $settings['appearance']['attention_badge_enabled'] ?? $defaults['appearance']['attention_badge_enabled'], 'attention_badge_text' => $settings['appearance']['attention_badge_text'] ?? $defaults['appearance']['attention_badge_text'], ), 'behavior' => array( 'max_products' => $settings['behavior']['max_products'] ?? $defaults['behavior']['max_products'], 'show_view_product' => $settings['behavior']['show_view_product'] ?? $defaults['behavior']['show_view_product'], 'show_add_to_cart' => $settings['behavior']['show_add_to_cart'] ?? $defaults['behavior']['show_add_to_cart'], 'show_stock_status' => $settings['behavior']['show_stock_status'] ?? $defaults['behavior']['show_stock_status'], ), 'labels' => \AIPT\Api\Chatbot\ChatbotSettings::getLabelsForLanguage( (string) ( $settings['general']['language'] ?? $defaults['general']['language'] ), (array) ( $settings['localization']['custom_labels'] ?? array() ) ), 'localization' => $this->buildLocalizationConfig( $chatbot_settings, $settings, $defaults ), ), ); } /** * Build the connectors block for localization data. * * Returns connector state, WP AI support flag, WP version, Connectors API * availability, and admin URL for the Connectors settings page. No raw API * key values, encrypted blobs, or option names are included in the output. * * @since 2.6.0 * @return array Connectors block array. */ private function buildConnectorsBlock(): array { $resolver = CredentialResolver::instance(); $providers_state = $resolver->getStatus(); $managed_count = count( array_filter( $providers_state, function ( $s ) { return ! empty( $s['isConnectorsManaged'] ); } ) ); $connectors_status = array( 'hasAnyConfigured' => $resolver->hasAnyConfiguredProvider(), 'hasAnyUsableKey' => $resolver->hasAnyUsableKey(), 'hasAnyConnectorsManaged' => $managed_count > 0, 'connectorsManagedCount' => $managed_count, 'providers' => $providers_state, ); return array( 'connectors' => $connectors_status, 'wpSupportsAi' => WordPressRuntimeDetector::supportsAi(), 'wpVersion' => get_bloginfo( 'version' ), 'connectorsApiAvailable' => WordPressRuntimeDetector::supportsConnectorsApi(), 'connectorsAdminUrl' => admin_url( 'options-connectors.php' ), 'migrationNotice' => $this->buildMigrationNoticeBlock( $providers_state ), ); } /** * Compute eligibility for the one-click "Move local keys into Connectors" * admin notice. Candidates are providers whose key is currently sourced * locally AND whose Connectors DB option is empty. * * Notice is hidden when (a) Connectors API is not available, * (b) the site-wide snooze transient is active, (c) the current user has * permanently dismissed the notice via user meta, or (d) no candidates exist. * * @since 2.6.0 * * @param array> $providers_state Output of CredentialResolver::getStatus(). * @return array{eligible: bool, candidates: array, snoozedUntil: int, permanentlyDismissed: bool} */ private function buildMigrationNoticeBlock( array $providers_state ): array { $connectors_available = WordPressRuntimeDetector::supportsConnectorsApi(); $user_id = get_current_user_id(); $snoozed_until = (int) get_user_meta( $user_id, 'aipt_migration_notice_snoozed_until', true ); $permanently_dismissed = (bool) get_user_meta( $user_id, 'aipt_connectors_migration_dismissed', true ); $candidates = array(); foreach ( $providers_state as $provider_id => $state ) { if ( 'openrouter' === $provider_id ) { continue; } $source = isset( $state['source'] ) ? (string) $state['source'] : ''; if ( CredentialSource::DATABASE_LOCAL !== $source ) { continue; } try { $connector_id = \AIPT\Utils\ProviderNameMapper::toConnectorId( (string) $provider_id ); } catch ( \InvalidArgumentException $e ) { continue; } $existing = get_option( 'connectors_ai_' . $connector_id . '_api_key', '' ); if ( empty( $existing ) ) { $candidates[] = (string) $provider_id; } } $is_snoozed = $snoozed_until > time(); $eligible = $connectors_available && ! $is_snoozed && ! $permanently_dismissed && ! empty( $candidates ); return array( 'eligible' => $eligible, 'candidates' => $candidates, 'snoozedUntil' => $snoozed_until, 'permanentlyDismissed' => $permanently_dismissed, ); } /** * Build the complete 'fs' block for localization data. * * Centralizes all Freemius plan, registration, and SDK conflict data into a * single reusable block consumed by every build*Data() method. * * @return array Complete 'fs' block array. */ private function buildFsBlock(): array { $fs_manager = \AIPT\Core\FsManager::getInstance(); $sdk_conflict = $fs_manager->detectSdkConflict(); $has_conflict = (bool) ( $sdk_conflict['has_conflict'] ?? false ); $can_see_paths = (bool) current_user_can( 'manage_options' ); return array( 'is_premium' => $fs_manager->isUsingPremiumFiles(), 'is_registered' => $fs_manager->is_registered(), 'plan' => $fs_manager->getPlanType(), 'siteId' => $fs_manager->getSiteId(), 'pluginId' => $fs_manager->getPluginId(), 'licenseId' => $fs_manager->getLicenseId(), 'upgradeUrl' => $fs_manager->getUpgradeUrl(), 'checkout' => $fs_manager->getCheckoutLinks(), 'accountUrl' => $fs_manager->getAccountUrl(), 'connectUrl' => $fs_manager->getConnectUrl(), 'premiumActivateUrl' => $fs_manager->getPremiumActivateUrl(), 'licenseSyncUrl' => $fs_manager->getLicenseSyncUrl(), 'license' => current_user_can( 'manage_aipt_settings' ) ? $fs_manager->getLicenseSummary() : null, 'pricing' => $fs_manager->getBusinessPlanPricing(), 'canManageSettings' => (bool) current_user_can( 'manage_aipt_settings' ), 'can_review' => apply_filters( 'aipt_content_review_enabled_cache_only', false ), 'can_draft_review' => apply_filters( 'aipt_draft_review_enabled_cache_only', false ), 'sdkConflict' => $has_conflict, 'sdkConflictDetail' => array( 'hasConflict' => $has_conflict, 'pluginName' => $sdk_conflict['conflicting_plugin_name'] ?? '', 'sdkVersion' => $sdk_conflict['active_version'] ?? '', 'sdkFile' => $can_see_paths ? ( $sdk_conflict['conflicting_sdk_file'] ?? '' ) : '', 'pluginFile' => $can_see_paths ? ( $sdk_conflict['conflicting_plugin_file'] ?? '' ) : '', 'dismissNonce' => \wp_create_nonce( 'aipt_dismiss_sdk_conflict' ), 'reverifyNonce' => \wp_create_nonce( 'aipt_force_license_reverify' ), 'reverifyUrl' => \admin_url( 'admin-ajax.php' ), 'canReverify' => (bool) current_user_can( 'manage_options' ) && (bool) apply_filters( 'aipt_license_reverify_available', false ), 'pluginsAdminUrl' => \admin_url( 'plugins.php' ), ), ); } /** * Build localization configuration for auto-detect feature. * * This data is printed into storefront HTML that page caches serve to * every visitor, so it never depends on the request. The widget detects * the visitor's language in the browser and fetches that language's * labels from the public labels route. * * @since 2.5.3 * @param \AIPT\Api\Chatbot\ChatbotSettings $chatbot_settings ChatbotSettings instance. * @param array $settings Current settings. * @param array $defaults Default settings. * @return array Localization configuration. */ private function buildLocalizationConfig( \AIPT\Api\Chatbot\ChatbotSettings $chatbot_settings, array $settings, array $defaults ): array { return array( 'auto_detect_enabled' => $settings['localization']['auto_detect_enabled'] ?? $defaults['localization']['auto_detect_enabled'], 'default_language' => $settings['general']['language'] ?? $defaults['general']['language'], 'fallback_language' => $settings['localization']['fallback_language'] ?? $defaults['localization']['fallback_language'], 'supported_languages' => \AIPT\Api\Chatbot\ChatbotSettings::getSupportedLanguages(), ); } }