setup_encryption_system(); $this->options_cache_service = new Services\OptionsCache(); $this->localization_data_builder = new Services\LocalizationDataBuilder( $this, $this->options_cache_service ); $this->asset_enqueuer = new Services\AssetEnqueuer( $this, $this->localization_data_builder ); $this->admin_menu_manager = new Services\AdminMenuManager( $this ); $this->capability_manager = new Services\CapabilityManager(); $this->cron_scheduler = new Services\CronScheduler( $this ); $this->ability_registrar = new Services\AbilityRegistrar( new RestAPIClientFactory() ); $this->ability_registrar->register(); $this->fsManager = FsManager::getInstance(); $this->premiumFeatureManager = PremiumFeatureManager::getInstance(); \AIPT\Core\ContentSnapshots\SnapshotStore::init(); \AIPT\Core\ContentSnapshots\SnapshotReadController::init(); \AIPT\Core\ContentSnapshots\TermEditorRevisionHook::init(); \AIPT\Core\ContentReview\ContentReviewController::init(); \AIPT\Core\Services\GrandfatherResolver::init(); \AIPT\Core\ContentStructure\Rest\BlueprintController::init(); \AIPT\Core\ContentStructure\Rest\BrandProfileController::init(); \AIPT\Core\ContentStructure\Rest\AssignmentController::init(); \AIPT\Core\ContentStructure\Rest\StructureController::init(); \AIPT\Core\ContentStructure\Rest\SettingsController::init(); \AIPT\Core\ContentStructure\Rest\CompareNoticeController::init(); \AIPT\Api\ContentStructure\Rest\BlueprintRunController::init(); \AIPT\Api\ContentStructure\Rest\SourceController::init(); \AIPT\Api\ContentStructure\Rest\BrandAssistController::init(); \AIPT\Api\ContentStructure\Apply\ProductScreenSeoGuard::init(); \AIPT\Core\ProductForm\StaleProductFormGuard::init(); if ( class_exists( 'WooCommerce' ) ) { \AIPT\Core\ProductCsv\InternalMetaGuard::init(); \AIPT\Core\ProductCsv\ProductCsvColumns::init(); \AIPT\Core\ProductCsv\ProductCsvImport::init(); \AIPT\Core\ProductCsv\ProductCsvReport::init(); } if ( wp_next_scheduled( 'aipt_credit_sync' ) ) { wp_clear_scheduled_hook( 'aipt_credit_sync' ); } foreach ( array( 'aipt_run_history_migration', 'aipt_clean_history_records' ) as $hook ) { if ( wp_next_scheduled( $hook ) ) { wp_clear_scheduled_hook( $hook ); } } $this->init_hooks(); } /** * Memory optimization: Clear options cache when needed */ public static function clear_options_cache() { $instance = self::get_instance(); $instance->options_cache_service->clear(); } /** * MEMORY OPTIMIZATION: Get cached settings array for Advanced Bulk Generator * Prevents repeated option calls and creates settings array once * * @internal Used by LocalizationDataBuilder service */ public function get_cached_advanced_settings_array() { return $this->options_cache_service->getSettingsArray( 'advanced' ); } /** * MEMORY OPTIMIZATION: Get cached settings array for general use (Settings page, etc.) * Includes all settings for compatibility * * @internal Used by LocalizationDataBuilder service */ public function get_cached_settings_array() { return $this->options_cache_service->getSettingsArray( 'general' ); } private function getGenerationController() { if ( null === $this->generation_controller ) { $this->generation_controller = new NewGenerationController(); } return $this->generation_controller; } private function getContentController() { if ( null === $this->content_controller ) { $this->content_controller = new ContentController(); } return $this->content_controller; } private function getTitleGeneratorController() { if ($this->title_generator_controller === null) { $this->title_generator_controller = new TitleGeneratorController(); } return $this->title_generator_controller; } private function getFaqGeneratorController() { if ($this->faq_generator_controller === null) { $this->faq_generator_controller = new FAQGeneratorController(); } return $this->faq_generator_controller; } private function getSeoMetaGeneratorController() { if ($this->seo_meta_generator_controller === null) { $this->seo_meta_generator_controller = new SeoMetaGeneratorController(); } return $this->seo_meta_generator_controller; } private function getTaxonomyGeneratorController() { if ($this->taxonomy_generator_controller === null) { $this->taxonomy_generator_controller = new TaxonomyGeneratorController(); } return $this->taxonomy_generator_controller; } private function getProductEditorController() { if ($this->product_editor_controller === null) { $this->product_editor_controller = new ProductEditorController(); } return $this->product_editor_controller; } private function getContentDefaultsController() { if ($this->content_defaults_controller === null) { $this->content_defaults_controller = new ContentDefaultsController(); } return $this->content_defaults_controller; } /** * Get Freemius Manager instance * * @internal Used by LocalizationDataBuilder service * @return FsManager Freemius Manager instance */ public function getFsManager() { return $this->fsManager; } /** * Get Premium Feature Manager instance * * @internal Used by LocalizationDataBuilder service * @return PremiumFeatureManager Premium Feature Manager instance */ public function getPremiumFeatureManager() { return $this->premiumFeatureManager; } private function getCustomFields() { if ($this->custom_fields === null) { $this->custom_fields = new CustomFields(); } return $this->custom_fields; } private function getStoreIndexController() { if ($this->store_index_controller === null) { $this->store_index_controller = new StoreIndexController(); } return $this->store_index_controller; } /** * Get ChatbotController instance. * * @return ChatbotController */ private function getChatbotController() { if ($this->chatbot_controller === null) { $this->chatbot_controller = new ChatbotController(); } return $this->chatbot_controller; } private function getPromptTemplateController() { if ($this->prompt_template_controller === null) { $this->prompt_template_controller = new PromptTemplateController(); } return $this->prompt_template_controller; } private function getDashboardController() { if ($this->dashboard_controller === null) { $this->dashboard_controller = new DashboardController(); } return $this->dashboard_controller; } private function getImageAltController() { if ( $this->image_alt_controller === null ) { $this->image_alt_controller = new ImageAltController(); } return $this->image_alt_controller; } private function getUiPrefsController() { if ( $this->ui_prefs_controller === null ) { $this->ui_prefs_controller = new UiPrefsController(); } return $this->ui_prefs_controller; } private function getPricingPreviewController() { if ( $this->pricing_preview_controller === null ) { $this->pricing_preview_controller = new PricingPreviewController(); } return $this->pricing_preview_controller; } private function init_hooks() { add_action('admin_init', [$this, 'handle_activation_redirect']); add_action('init', [\AIPT\Admin\Notification\LegacyHistoryReleaseNotice::class, 'register']); add_action('init', [\AIPT\Admin\Notices\ContentModeUpdateNotice::class, 'register']); add_action('init', [\AIPT\Core\CatalogScan\NewProductsGap::class, 'register']); add_action('init', [\AIPT\Admin\Notices\NewProductsNotice::class, 'register']); add_action('init', [\AIPT\Admin\Dashboard\GapDashboardWidget::class, 'register']); add_action('rest_api_init', [$this, 'register_rest_routes']); add_filter('rest_post_dispatch', [$this, 'add_rest_no_cache_headers'], 10, 3); add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_Assets']); add_action('add_meta_boxes_product', [$this, 'add_product_metabox']); add_action('admin_menu', [$this, 'add_admin_menu'], 10); add_action('admin_menu', [$this, 'add_product_editor_products_menu'], 99); add_action('admin_bar_menu', [$this, 'add_product_editor_admin_bar_node'], 90); add_action('admin_head', [$this, 'hide_generator_menu_items']); add_filter('submenu_file', [$this, 'filter_generator_submenu_file']); add_action('admin_head', [$this, 'add_editor_styles']); add_filter('admin_body_class', [$this, 'filter_admin_body_class']); add_action('admin_head', [$this, 'print_theme_init_script'], 99); add_action( 'update_option_aipt_openai_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'add_option_aipt_openai_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'update_option_aipt_gemini_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'add_option_aipt_gemini_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'update_option_aipt_openrouter_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'add_option_aipt_openrouter_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'update_option_aipt_claude_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'add_option_aipt_claude_api_key', [ \AIPT\Utils\ApiKeyManager::class, 'flush_credential_caches' ] ); add_action( 'update_option_aipt_allow_shop_manager_settings', [ $this->capability_manager, 'syncShopManagerSettingsCap' ] ); add_action( 'add_option_aipt_allow_shop_manager_settings', [ $this->capability_manager, 'syncShopManagerSettingsCap' ] ); add_action('init', [$this, 'load_textdomain'], 1); add_action('init', [$this, 'add_capabilities'], 20); add_action('init', ['\AIPT\Utils\ProductFilter\ProductFilterMapper', 'registerCacheInvalidationHooks'], 20); add_action('init', ['\AIPT\Core\ContentMarking\MetaRegistrar', 'register'], 20); add_action('init', [CustomFields::class, 'register_cache_invalidation_hooks'], 20); if ( class_exists( '\AIPT\Core\CatalogScan\CatalogScanService' ) && method_exists( '\AIPT\Core\CatalogScan\CatalogScanService', 'register_invalidation_hooks' ) ) { \AIPT\Core\CatalogScan\CatalogScanService::register_invalidation_hooks(); } \AIPT\Core\Funnel\FunnelDebugInfo::register(); add_filter('manage_product_posts_columns', ['\AIPT\Core\ContentMarking\ProductListColumn', 'add_column']); add_action('manage_product_posts_custom_column', ['\AIPT\Core\ContentMarking\ProductListColumn', 'render_column'], 10, 2); add_action('admin_enqueue_scripts', ['\AIPT\Core\ContentMarking\ProductListColumn', 'enqueue_styles']); add_action('aipt_clean_job_logs', ['\AIPT\Core\Database\JobLogCleaner', 'cron_callback']); add_action('aipt_clean_content_review', ['\AIPT\Core\Database\ContentReviewCleaner', 'cron_callback']); add_action('admin_init', ['\AIPT\Core\Database\JobLogCleaner', 'ensure_scheduled']); add_action('admin_init', ['\AIPT\Core\Database\ContentReviewCleaner', 'ensure_scheduled']); add_action('aipt_content_structure_cleanup', ['\AIPT\Core\ContentStructure\Cleanup\BlueprintCleanup', 'cron_callback']); add_action('admin_init', ['\AIPT\Core\ContentStructure\Cleanup\BlueprintCleanup', 'ensure_scheduled']); add_action('admin_init', [$this, 'ensure_retention_crons_scheduled']); add_action('aipt_cleanup_rate_limits', ['\AIPT\Core\Database\RateLimiterCleaner', 'cron_callback']); add_action('aipt_cleanup_request_claims', ['\AIPT\Core\Database\RequestClaimCleaner', 'cron_callback']); add_action( 'aipt_mcp_audit_log_cleanup', [ McpAuditLogCleaner::class, 'cron_callback' ] ); add_action( 'aipt_mcp_credential_cleanup', [ McpCredentialCleaner::class, 'cron_callback' ] ); add_action( 'aipt_mcp_oauth_client_gc', [ McpOAuthClientGc::class, 'cron_callback' ] ); add_action( 'aipt_mcp_capability_sweep', [ McpConnectionCapabilitySweeper::class, 'cron_callback' ] ); add_action( 'admin_init', [ McpAuditLogCleaner::class, 'ensure_scheduled' ] ); add_action( 'admin_init', [ McpCredentialCleaner::class, 'ensure_scheduled' ] ); add_action( 'admin_init', [ McpOAuthClientGc::class, 'ensure_scheduled' ] ); add_action( 'admin_init', [ McpConnectionCapabilitySweeper::class, 'ensure_scheduled' ] ); McpConnectionLifecycle::register(); add_action( 'admin_init', [ McpPrivacyPolicyContent::class, 'register' ] ); \AIPT\Api\Mcp\McpServerBootstrap::register(); McpUserAuthResolver::register(); OAuthRestRoutes::register(); McpAdminController::register(); add_action( \AIPT\Core\Services\PricingFeedManager::CRON_HOOK, ['\AIPT\Core\Services\PricingFeedManager', 'cron_callback'] ); add_action( \AIPT\Core\Services\UsageTracker::CRON_HOOK, ['\AIPT\Core\Services\UsageTracker', 'cron_callback'] ); add_action( 'aipt_upgrade_prompt_shown', ['\AIPT\Core\Services\UsageTracker', 'on_upgrade_prompt_shown'], 10, 1 ); \AIPT\Core\Database\OrphanCleaner::register(); add_action('aipt_chatbot_queue_cleanup', [$this, 'cleanup_chatbot_message_queue']); add_action('admin_init', [$this, 'schedule_chatbot_queue_cleanup']); add_action( ChatbotConstants::ACTION_SCHEDULER_HOOK, [ ChatbotJobWorker::class, 'processJob' ], 10, 1 ); add_action( ChatbotConstants::STALE_RECOVERY_HOOK, [ ChatbotJobWorker::class, 'reclaimStaleClaims' ], 10, 0 ); add_action( 'admin_init', [ ChatbotJobWorker::class, 'ensureStaleRecoveryScheduled' ] ); ChatbotPrivacy::register(); NoticeManager::get_instance(); add_filter('pre_reschedule_event', [$this, 'prevent_noop_reschedule_race'], 10, 2); add_action('aipt_process_automation_jobs', [$this, 'process_automation_jobs']); add_action('aipt_monitor_automation_jobs', [$this, 'monitor_automation_jobs']); \AIPT\Api\AutomationJobs\JobExecutionHandler::init(); \AIPT\Api\AutomationJobs\AutoPublishDispatcher::register(); \AIPT\Api\AutomationJobs\AutoDeltaDispatcher::register(); add_action('wp_loaded', [$this, 'setup_automation_cron_schedules'], 10); add_action('aipt_build_store_index', [$this, 'process_store_index_batch'], 10, 5); add_action('aipt_scheduled_index_rebuild', [$this, 'trigger_scheduled_index_rebuild'], 10, 1); add_action('aipt_store_index_build_complete', [$this, 'clear_store_index_consumer_cache'], 10, 1); add_action('wp_enqueue_scripts', [$this, 'enqueue_chatbot_widget_assets']); add_action('wp_footer', [$this, 'render_chatbot_widget_container'], 10); add_action( 'wp_enqueue_scripts', [ FAQFrontendRenderer::class, 'enqueue_styles' ] ); add_action( 'wp_head', [ FAQFrontendRenderer::class, 'render_dynamic_css' ], 5 ); add_action( 'woocommerce_after_single_product_summary', [ FAQFrontendRenderer::class, 'render_accordion_content' ], 15 ); add_action( 'init', [ FAQGeneratorController::class, 'register_meta' ], 20 ); FAQShortcode::register(); /** * WP 7.0 AI Connectors integration. * * Activated only when wp_get_connector() exists (WP 7.0+). Warms the * credential resolver for the three core providers (openai/claude/gemini). * The default credential chain (Connectors-first, Local-fallback) can be * customized via the `aipt_credential_provider_chain` filter. * * NOTE: OpenRouter is intentionally NOT registered as a Connector. It * was previously self-registered via OpenRouterConnectorRegistrar but * the registration was removed in 2.6.x because the WP Connectors UI * mis-detected the locally-stored OpenRouter key as Connectors-managed. * OpenRouter now uses the plugin's local AES-256-GCM storage exclusively * (the option key remains `aipt_openrouter_api_key`). * * @since 2.6.0 */ if ( WordPressRuntimeDetector::supportsConnectorsApi() ) { CredentialResolver::instance(); } } public function add_capabilities() { $this->capability_manager->registerCapabilities(); } public function register_rest_routes() { $endpoints = new RestEndpoints(); $endpoints->register_routes(); $this->getGenerationController()->register_routes(); $this->getContentController()->register_routes(); $this->getTitleGeneratorController()->register_routes(); $this->getFaqGeneratorController()->register_routes(); $this->getSeoMetaGeneratorController()->register_routes(); $this->getTaxonomyGeneratorController()->register_routes(); $this->getProductEditorController()->register_routes(); $this->getContentDefaultsController()->register_routes(); $this->getCustomFields()->register_routes(); $this->getStoreIndexController()->register_routes(); $this->getChatbotController()->register_routes(); $this->getPromptTemplateController()->register_routes(); $this->getDashboardController()->register_routes(); $this->getImageAltController()->register_routes(); $this->getUiPrefsController()->register_routes(); $this->getPricingPreviewController()->register_routes(); ( new FAQDisplaySettingsController() )->register_routes(); ( new ContentMarkingController() )->register_routes(); ( new \AIPT\Api\FirstRun\FirstRunController() )->register_routes(); } /** * Add no-cache headers to all AIPT REST API responses. * * Prevents server-level caching (LiteSpeed, Cloudflare, reverse proxies) * from returning stale data for dynamic plugin endpoints. * This fixes issues on some hosting environments where GET responses * are cached, causing stale job lists and stuck build progress. * * @param \WP_REST_Response $response The response object. * @param \WP_REST_Server $server The REST server instance. * @param \WP_REST_Request $request The request object. * @return \WP_REST_Response Modified response with cache-busting headers. */ public function add_rest_no_cache_headers($response, $server, $request) { $route = $request->get_route(); $is_aipt_route = strpos($route, '/aipt/') !== false; if ($is_aipt_route) { $response->header('Cache-Control', 'no-cache, no-store, must-revalidate'); $response->header('Pragma', 'no-cache'); $response->header('Expires', '0'); } return $response; } /** * Convert WordPress locale format to standard format * * @internal Used by LocalizationDataBuilder service * @param string $wp_locale WordPress locale (e.g., 'en_US') * @return string Standard locale format (e.g., 'en-US') */ public function convert_locale_format($wp_locale) { return str_replace('_', '-', $wp_locale); } public function enqueue_admin_Assets($hook) { $this->asset_enqueuer->enqueueForHook( $hook ); } private function get_faq_localized_data(): array { $defaults = [ 'faqCount' => FAQGeneratorService::DEFAULT_FAQ_COUNT, 'faqFormat' => self::get_default_faq_format(), 'faqMode' => self::get_default_faq_mode(), 'writeMode' => 'append', 'targetField' => 'post_content', ]; return [ 'restUrl' => esc_url_raw(rest_url()), 'restNonce' => wp_create_nonce('wp_rest'), 'adminUrl' => admin_url(), 'faqDefaults' => $defaults, 'maxFaqCount' => FAQGeneratorService::MAX_FAQ_COUNT, 'customFieldsEndpoint' => esc_url_raw(rest_url('aipt/v1/custom-fields')), ]; } public static function get_default_faq_format(): string { return 'text'; } public static function get_default_faq_mode(): string { return 'both'; } /** * Get asset path with dist prefix * * @internal Used by AssetEnqueuer service * @param string $path Asset yolu (örn: 'css/commons.css') * @return string Tam asset yolu (örn: 'dist/css/commons.css') */ public function get_asset_path($path) { return 'dist/' . $path; } /** * Cache-busting version for a built asset under dist/. * * The webpack build writes dist/js/.asset.php with a content hash * of that entry's JS and extracted CSS, so a rebuilt bundle gets a new * `ver` even when AIPT_VERSION is unchanged and a stale cached bundle is * not reused. * * @internal Used by AssetEnqueuer service * @param string $path Asset path relative to dist/ (e.g. 'css/product-editor.css'). * @return string Build hash, else the file mtime, else AIPT_VERSION. */ public function get_asset_version( string $path ): string { $entry = pathinfo( $path, PATHINFO_FILENAME ); return self::resolve_asset_version( AIPT_PLUGIN_DIR . $this->get_asset_path( 'js/' . $entry . '.asset.php' ), AIPT_PLUGIN_DIR . $this->get_asset_path( $path ) ); } /** * Resolve an asset version from its build manifest and file. * * @internal Used by get_asset_version(); public for unit tests. * @param string $manifest_file Absolute path of the entry's .asset.php manifest. * @param string $asset_file Absolute path of the enqueued asset. * @return string */ public static function resolve_asset_version( string $manifest_file, string $asset_file ): string { if ( is_readable( $manifest_file ) ) { $manifest = include $manifest_file; if ( is_array( $manifest ) && isset( $manifest['version'] ) && is_string( $manifest['version'] ) && '' !== $manifest['version'] ) { return $manifest['version']; } } $mtime = is_readable( $asset_file ) ? filemtime( $asset_file ) : false; return false !== $mtime ? (string) $mtime : AIPT_VERSION; } /** * @param \WP_Post|object|null $post The product post WordPress's own * `add_meta_boxes_product` hook passes in. Untyped * because a lower-privilege caller below only ever * reads its `ID` property, and tests pass a plain * stdClass stand-in. */ public function add_product_metabox( $post = null ) { $metabox_hidden = get_option( 'aipt_metabox_hidden', Activator::get_default_value( 'metabox_hidden' ) ); if ( $metabox_hidden ) { return; } if ( current_user_can( 'use_aipt_tools' ) ) { add_meta_box( 'aipt_product_metabox', __('AI Product Tools', 'ai-product-tools'), [$this, 'render_product_metabox'], 'product', 'side', 'high' ); return; } } public function render_product_metabox($post) { $ai_note = (string) get_post_meta( $post->ID, MetaKeys::AI_NOTE, true ); echo '
'; } /** * Get onboarding status quickly without API call * This is optimized for fast loading * * @internal Used by LocalizationDataBuilder service * @return array Onboarding status data */ public function get_onboarding_status_fast(): array { try { $has_api_key = false; if (class_exists('\AIPT\Utils\ApiKeyManager')) { $has_api_key = \AIPT\Utils\ApiKeyManager::has_any_api_key(); } $resolver = CredentialResolver::instance(); $setup_completed = get_option('aipt_setup_completed', false); $setup_fields = SetupState::statusFields($resolver); $onboarding_dismissed = get_option('aipt_onboarding_dismissed', false); $snooze_until = get_option('aipt_onboarding_snoozed_until', 0); $is_snoozed = $snooze_until > time(); $should_show = current_user_can( 'manage_aipt_settings' ) && ! $setup_completed && ! $onboarding_dismissed && ! $is_snoozed && ! $resolver->hasAnyLocalUsableKey(); $first_run = $setup_fields['firstRun']; $gap_map_is_active = $first_run['eligible'] && ! $first_run['hidden'] && ! $first_run['firstValueReached']; $qs_completed_steps = get_option( 'aipt_quickstart_completed_steps', '[]' ); if ( is_string( $qs_completed_steps ) ) { $qs_completed_steps = json_decode( $qs_completed_steps, true ); if ( ! is_array( $qs_completed_steps ) ) { $qs_completed_steps = []; } } return [ 'shouldShow' => $should_show, 'isFirstTime' => !get_option('aipt_first_run_completed', false), 'hasApiKey' => $has_api_key, 'setupCompleted' => $setup_fields['setupCompleted'], 'hasAnyUsableKey' => $setup_fields['hasAnyUsableKey'], 'mcpReachable' => $setup_fields['mcpReachable'], 'firstRun' => $setup_fields['firstRun'], 'onboardingDismissed' => $onboarding_dismissed, 'connectorsManaged' => $resolver->connectorsManagedProviders(), 'connectorsAvailable' => WordPressRuntimeDetector::supportsConnectorsApi(), 'isSnoozed' => $is_snoozed, 'snoozeUntil' => $snooze_until, 'firstProductEditUrl' => ( $should_show || $gap_map_is_active ) ? $this->first_product_edit_url() : null, 'newProductUrl' => admin_url( 'post-new.php?post_type=product' ), 'quickstart' => [ 'completedSteps' => array_values( array_intersect( $qs_completed_steps, \AIPT\Api\Services\OnboardingService::QUICKSTART_STEPS ) ), 'dismissed' => (bool) get_option( 'aipt_quickstart_dismissed', false ), 'completed' => (bool) get_option( 'aipt_quickstart_completed', false ), 'totalSteps' => count( \AIPT\Api\Services\OnboardingService::QUICKSTART_STEPS ), ], ]; } catch (\Exception $e) { return [ 'shouldShow' => false, 'isFirstTime' => false, 'hasApiKey' => true, 'setupCompleted' => true, 'onboardingDismissed' => true, 'hasAnyUsableKey' => false, 'mcpReachable' => false, 'firstRun' => [ 'eligible' => false, 'hidden' => false, 'firstValueReached' => false, 'businessDismissed' => false, 'installedVersion' => '', ], ]; } } /** * Completion's "Preview on your first product" link: the newest product's * edit screen with its Description drawer open, or null with no products. * * @return string|null */ protected function first_product_edit_url(): ?string { return ( new \AIPT\Api\Services\OnboardingService() )->firstProductEditUrl(); } public function add_admin_menu() { $this->admin_menu_manager->registerMenus(); } /** * Hide the six generator pages' rows from the WP admin left nav. */ public function hide_generator_menu_items() { $this->admin_menu_manager->hideGeneratorMenuItems(); } /** * Keep the "AI Toolkit" submenu row highlighted while a hidden * generator page is open. * * @param string $submenu_file The submenu slug WordPress would otherwise highlight. * @return string */ public function filter_generator_submenu_file( $submenu_file ) { return $this->admin_menu_manager->mapGeneratorPagesToSubmenuFile( $submenu_file ); } /** * Surface the AI Bulk Product Editor under the WooCommerce Products menu. */ public function add_product_editor_products_menu() { $this->admin_menu_manager->registerProductsSubmenu(); } /** * Add the AI Bulk Product Editor shortcut to the top admin bar. * * @param \WP_Admin_Bar $wp_admin_bar The admin bar instance. */ public function add_product_editor_admin_bar_node( $wp_admin_bar ) { $this->admin_menu_manager->registerAdminBarNode( $wp_admin_bar ); } /** * Setup encryption system for new installations * Ensures API keys are stored encrypted from first use */ private function setup_encryption_system() { static $setup_attempted = false; if (!$setup_attempted) { $setup_attempted = true; try { Encryption::setup_new_installation(); \AIPT\Utils\ApiKeyManager::migrate_keys_if_needed(); } catch (\Exception $e) { } } } private function hasApiKeys(): bool { return \AIPT\Utils\ApiKeyManager::has_any_api_key(); } public function render_toolkit_page() { $this->admin_menu_manager->renderToolkitPage(); } public function render_settings_page() { $this->admin_menu_manager->renderSettingsPage(); } public function render_bulk_generator_page() { $this->admin_menu_manager->renderBulkGeneratorPage(); } public function render_standard_bulk_generator_page() { $this->admin_menu_manager->redirectStandardBulkGeneratorPage(); } public function render_faq_generator_page() { $this->admin_menu_manager->renderFaqGeneratorPage(); } public function render_title_generator_page() { $this->admin_menu_manager->renderTitleGeneratorPage(); } public function render_automation_jobs_page() { $this->admin_menu_manager->renderAutomationJobsPage(); } public function add_editor_styles() { if (!function_exists('get_current_screen')) { return; } $screen = get_current_screen(); if (!$screen || 'toplevel_page_ai-product-tools' !== $screen->id) { return; } } /** * Add scoped Tailwind wrapper classes to admin body on plugin pages * * @param string $classes Existing admin body classes. * @return string */ public function filter_admin_body_class($classes) { if (!function_exists('get_current_screen')) { return $classes; } $screen = get_current_screen(); if (!$screen) { return $classes; } $is_product_editor = ( isset($screen->post_type) && 'product' === $screen->post_type && isset($screen->base) && in_array($screen->base, ['post', 'post-new'], true) ); if ($is_product_editor) { return $classes; } $screen_id = isset($screen->id) ? (string) $screen->id : ''; $is_aipt_admin_page = ( $screen_id !== '' && (strpos($screen_id, 'ai-product-tools') !== false || strpos($screen_id, 'aipt-') !== false) ); if ($is_aipt_admin_page) { $classes .= ' aipt-ui-shell'; } return $classes; } /** * Print inline script in admin for zero-flash theme detection. * * Reads the user's explicit theme choice from localStorage and sets * a data attribute on before renders. This ensures CSS * selectors (html[data-aipt-theme="dark"]) are active before first paint. * If no explicit choice exists, CSS @media (prefers-color-scheme) handles it. */ public function print_theme_init_script() { if (!function_exists('get_current_screen')) { return; } $screen = get_current_screen(); if (!$screen) { return; } $screen_id = isset($screen->id) ? (string) $screen->id : ''; $is_aipt_page = ( $screen_id !== '' && (strpos($screen_id, 'ai-product-tools') !== false || strpos($screen_id, 'aipt-') !== false) ); $is_product_editor = ( isset($screen->post_type) && 'product' === $screen->post_type && isset($screen->base) && in_array($screen->base, ['post', 'post-new'], true) ); if (!$is_aipt_page && !$is_product_editor) { return; } echo ''; } /** * Load plugin text domain for translations. * * @since 2.5.12 * @return void */ public function load_textdomain() { load_plugin_textdomain( 'ai-product-tools', false, basename( AIPT_PLUGIN_DIR ) . '/languages' ); } public function handle_activation_redirect() { if (!is_admin() || !current_user_can('manage_options')) { return; } if (get_transient('aipt_activation_redirect')) { delete_transient('aipt_activation_redirect'); if (isset($_GET['activate-multi'])) { return; } if (!headers_sent()) { wp_safe_redirect(admin_url('admin.php?page=ai-product-tools')); exit; } } } /** * pre_reschedule_event filter callback (@since 2.6.2). * * Thin delegation to CronScheduler — see preventNoopRescheduleRace() there * for the full rationale (suppress could_not_set noise from no-op * reschedule races for our two recurring hooks). * * @param null|bool|\WP_Error $pre Prior filter result. * @param object $event WP cron event object. * @return null|bool|\WP_Error Filter result. */ public function prevent_noop_reschedule_race($pre, $event) { return $this->cron_scheduler->preventNoopRescheduleRace( $pre, $event ); } public function process_automation_jobs() { $this->cron_scheduler->processAutomationJobs(); } public function monitor_automation_jobs() { $this->cron_scheduler->monitorAutomationJobs(); } public function setup_automation_cron_schedules() { $this->cron_scheduler->setupAutomationSchedules(); } /** * Register and enqueue a virtual style handle that depends on shared assets. * * @internal Used by LocalizationDataBuilder service * @param string $handle Style handle to register. * @param array $dependencies Optional dependency handles. */ public function enqueue_virtual_style( string $handle, array $dependencies = [] ) : void { if ( ! wp_style_is( $handle, 'registered' ) ) { wp_register_style( $handle, false, array_unique( $dependencies ), AIPT_VERSION ); } wp_enqueue_style( $handle ); } /** * Process a batch of products for the AI Store Index. * * Callback for Action Scheduler hook 'aipt_build_store_index'. * * @param int $profile_id Profile ID for multi-profile support. * @param int $job_id Job identifier. * @param int $last_id Last processed product ID (keyset pagination). * @param int $batch_size Number of products per batch. * @param int $processed_count Total products processed so far. */ public function process_store_index_batch(int $profile_id, int $job_id, int $last_id, int $batch_size, int $processed_count = 0): void { $builder = new IndexBuilder($profile_id); $builder->processBatch($job_id, $last_id, $batch_size, $processed_count); } /** * Trigger scheduled index rebuild. * * Callback for Action Scheduler hook 'aipt_scheduled_index_rebuild'. * * Scheduled rebuilds are a paid feature owned by the premium * ScheduledRebuildService, which registers its own executor on this hook * (scheduled_enabled and entitlement checks) together with the * 'aipt_index_scheduled_updates_enabled' bridge. This always-shipped * callback therefore never builds: in the premium build it leaves the run * to that executor, and without the premium code (no bridge registrant) it * removes the recurring action a removed premium plugin left behind. * * That removal cannot happen inside this callback: the executing action is * in-progress, as_unschedule_all_actions() cancels pending actions only, and * the queue runner stores the next recurring instance after this callback * returns. It therefore runs on shutdown, once the runner has rescheduled. * * @param int $profile_id Profile ID for multi-profile support (defaults to active profile). */ public function trigger_scheduled_index_rebuild(int $profile_id = 0): void { if (has_filter('aipt_index_scheduled_updates_enabled')) { return; } add_action('shutdown', [$this, 'unschedule_orphaned_index_rebuild']); } /** * Cancel the pending recurring index rebuilds left without a premium executor. * * Registered on shutdown by trigger_scheduled_index_rebuild() in the free build. */ public function unschedule_orphaned_index_rebuild(): void { if (function_exists('as_unschedule_all_actions')) { as_unschedule_all_actions(IndexBuilder::getScheduledHook(), [], IndexBuilder::getGroup()); } } /** * Clear IndexConsumer cache when build completes. * * Ensures consumers get fresh data after rebuild. * * @param array $meta Build metadata containing profile_id. */ public function clear_store_index_consumer_cache( array $meta = array() ): void { $profile_id = isset( $meta['profile_id'] ) ? (int) $meta['profile_id'] : 1; $consumer = new \AIPT\Api\StoreIndex\IndexConsumer( $profile_id ); $consumer->clearCache(); } /** * Re-arm retention cron schedules that can be missed during plugin updates. * * @return void */ public function ensure_retention_crons_scheduled(): void { if ( ! \wp_next_scheduled( \AIPT\Core\ContentSnapshots\SnapshotStore::CRON_HOOK ) ) { \AIPT\Core\ContentSnapshots\SnapshotStore::schedule(); } if ( ! \wp_next_scheduled( \AIPT\Core\Services\UsageTracker::CRON_HOOK ) ) { \AIPT\Core\Services\UsageTracker::schedule(); } if ( ! \wp_next_scheduled( \AIPT\Core\Database\RateLimiterCleaner::CRON_HOOK ) ) { ( new \AIPT\Core\Database\RateLimiterCleaner() )->schedule(); } if ( ! \wp_next_scheduled( \AIPT\Core\Database\RequestClaimCleaner::CRON_HOOK ) ) { ( new \AIPT\Core\Database\RequestClaimCleaner() )->schedule(); } if ( ! \wp_next_scheduled( McpAuditLogCleaner::CRON_HOOK ) ) { ( new McpAuditLogCleaner() )->schedule(); } if ( ! \wp_next_scheduled( McpCredentialCleaner::CRON_HOOK ) ) { ( new McpCredentialCleaner() )->schedule(); } if ( ! \wp_next_scheduled( McpOAuthClientGc::CRON_HOOK ) ) { ( new McpOAuthClientGc() )->schedule(); } if ( ! \wp_next_scheduled( McpConnectionCapabilitySweeper::CRON_HOOK ) ) { ( new McpConnectionCapabilitySweeper() )->schedule(); } } /** * Schedule chatbot message queue cleanup cron. * * Uses a transient guard to prevent repeated wp_next_scheduled() checks * on every admin page load, improving performance. * * @since 2.5.0 */ public function schedule_chatbot_queue_cleanup(): void { if ( get_transient( 'aipt_chatbot_cron_checked' ) ) { return; } set_transient( 'aipt_chatbot_cron_checked', true, HOUR_IN_SECONDS ); if ( ! wp_next_scheduled( 'aipt_chatbot_queue_cleanup' ) ) { wp_schedule_event( time(), 'daily', 'aipt_chatbot_queue_cleanup' ); } } /** * Clean up old chatbot message queue records. * * Called by cron to remove messages older than 30 days and finished * async chat jobs older than the job retention window. * * @since 2.5.0 */ public function cleanup_chatbot_message_queue(): void { $message_queue = new \AIPT\Api\Chatbot\MessageQueue(); $deleted = $message_queue->cleanup(30); if ($deleted > 0) { } $deleted_jobs = ( new ChatbotJobRepository() )->purgeFinished( ChatbotConstants::JOB_RETENTION_DAYS ); if ($deleted_jobs > 0) { } } /** * Enqueue chatbot widget assets on frontend. * * @since 2.5.0 */ public function enqueue_chatbot_widget_assets(): void { if (is_admin()) { return; } $asset_enqueuer = $this->asset_enqueuer; if ( null === $asset_enqueuer ) { $options_cache = $this->options_cache_service ?? new Services\OptionsCache(); $data_builder = $this->localization_data_builder ?? new Services\LocalizationDataBuilder( $this, $options_cache ); $asset_enqueuer = new Services\AssetEnqueuer( $this, $data_builder ); } $asset_enqueuer->enqueueChatbotWidgetAssets(); } /** * Render chatbot widget container. * * Registered on wp_footer only. * * @since 2.5.0 */ public function render_chatbot_widget_container(): void { if ($this->chatbot_container_rendered) { return; } if (is_admin()) { return; } $settings = get_option('aipt_chatbot_settings', []); $is_enabled = isset($settings['general']['enabled']) ? (bool) $settings['general']['enabled'] : false; if (!$is_enabled) { return; } if (!$this->should_show_chatbot_on_page($settings)) { return; } echo '
'; $this->chatbot_container_rendered = true; } /** * Check if chatbot should be shown on current page. * * @since 2.5.0 * @param array $settings Chatbot settings. * @return bool True if should show. */ public function should_show_chatbot_on_page(array $settings): bool { $placement = $settings['placement'] ?? []; $excluded_types = $placement['excluded_page_types'] ?? []; if (in_array('checkout', $excluded_types, true) && function_exists('is_checkout') && is_checkout()) { return false; } if (in_array('cart', $excluded_types, true) && function_exists('is_cart') && is_cart()) { return false; } if (in_array('my-account', $excluded_types, true) && function_exists('is_account_page') && is_account_page()) { return false; } $visibility_mode = $placement['visibility_mode'] ?? 'all'; $current_page_id = get_queried_object_id(); if ($visibility_mode === 'specific') { $specific_pages = $placement['specific_pages'] ?? []; $specific_pages_int = array_map( 'intval', $specific_pages ); if (!empty($specific_pages_int) && !in_array($current_page_id, $specific_pages_int, true)) { return false; } } elseif ($visibility_mode === 'exclude') { $excluded_pages = $placement['excluded_pages'] ?? []; $excluded_pages_int = array_map( 'intval', $excluded_pages ); if (!empty($excluded_pages_int) && in_array($current_page_id, $excluded_pages_int, true)) { return false; } } return true; } }