'Use clear, concise, and formal language. Focus on features, benefits, and technical details.', 'Encouraging' => 'Use positive, motivational language that inspires confidence and action.', 'Exaggerated' => 'Use dramatic and hyperbolic language to create excitement and emphasis.', 'Friendly' => 'Use warm, conversational language that builds rapport and trust.', 'Storytelling' => 'Create a narrative that engages readers and connects emotionally.', 'Minimalist' => 'Use simple, straightforward language focusing on essential details.', 'Luxurious and Elegant' => 'Use sophisticated, refined language that conveys premium quality and exclusivity.', 'Adventurous' => 'Use dynamic, exciting language that creates a sense of exploration and discovery.', 'Educational' => 'Use informative, detailed language that explains and educates.', 'Humorous' => 'Use light-hearted, playful language with appropriate humor and wit.' ]; public function __construct( ?AIClientFactoryInterface $ai_client_factory = null, ?SettingsService $settings_service = null, ?ContentGenerationService $content_generation_service = null, ?OnboardingService $onboarding_service = null, ?UnifiedContentGenerator $unified_generator = null ) { $this->ai_client_factory = $ai_client_factory ?? new RestAPIClientFactory(); $this->settings_service = $settings_service ?? new SettingsService( $this->settings_fields, $this->style_descriptions, $this->ai_client_factory ); $this->content_generation_service = $content_generation_service ?? new ContentGenerationService( $this->ai_client_factory, $this->style_descriptions ); $this->onboarding_service = $onboarding_service ?? new OnboardingService(); $this->unified_generator = $unified_generator ?? new UnifiedContentGenerator( $this->ai_client_factory, $this->style_descriptions ); } private function get_ai_client() { return $this->ai_client_factory->create(); } private function get_default_model_for_provider(string $provider): string { return $this->ai_client_factory->getDefaultModel( $provider ); } private function normalize_model_for_provider(string $provider, ?string $model): string { return $this->ai_client_factory->normalizeModel( $provider, $model ); } public function register_routes(): void { register_rest_route($this->namespace, '/generate-description', [ 'methods' => 'POST', 'callback' => [$this, 'generate_description'], 'permission_callback' => [$this, 'check_tool_permissions'], 'args' => [ 'product_id' => [ 'required' => true, 'type' => 'integer', ], 'is_short' => [ 'required' => false, 'type' => 'boolean', 'default' => false, ], 'improveExistingDescription' => [ 'required' => false, 'type' => 'boolean', ], 'keepExistingDescription' => [ 'required' => false, 'type' => 'boolean', ], 'blueprintId' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', ], ], ]); register_rest_route($this->namespace, '/generate-title', [ 'methods' => 'POST', 'callback' => [$this, 'generate_title'], 'permission_callback' => [$this, 'check_tool_permissions'], 'args' => [ 'product_id' => [ 'required' => true, 'type' => 'integer', ], 'system_prompt' => [ 'required' => false, 'type' => 'string', ], 'user_prompt' => [ 'required' => false, 'type' => 'string', ], 'mode' => [ 'required' => false, 'type' => 'string', 'default' => 'rewrite', 'enum' => ['rewrite', 'improve'] ], 'tone' => [ 'required' => false, 'type' => 'string', 'default' => 'SEO-Focused' ], 'max_length' => [ 'required' => false, 'type' => 'integer', 'default' => 60 ], 'keywords' => [ 'required' => false, 'type' => 'string', 'default' => '' ], 'blueprintId' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', ], ], ]); register_rest_route($this->namespace, '/generate-tags', [ 'methods' => 'POST', 'callback' => [$this, 'generate_tags'], 'permission_callback' => [$this, 'check_tool_permissions'], 'args' => [ 'product_id' => [ 'required' => true, 'type' => 'integer', ], 'system_prompt' => [ 'required' => false, 'type' => 'string', ], 'user_prompt' => [ 'required' => false, 'type' => 'string', ], 'max_tags' => [ 'required' => false, 'type' => 'integer', 'default' => 5 ], 'keep_existing' => [ 'required' => false, 'type' => 'boolean', 'default' => false ], 'blueprintId' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', ], ], ]); register_rest_route($this->namespace, '/generate-unified', [ 'methods' => 'POST', 'callback' => [$this, 'generate_unified'], 'permission_callback' => [$this, 'check_generate_unified_permissions'], 'args' => [ 'product_id' => [ 'required' => true, 'type' => 'integer', ], 'content_types' => [ 'required' => true, 'type' => 'array', 'items' => ['type' => 'string'], ], 'options' => [ 'required' => false, 'type' => 'object', 'default' => [], ], ], ]); register_rest_route($this->namespace, '/apply-description', [ 'methods' => 'POST', 'callback' => [$this, 'apply_description'], 'permission_callback' => [$this, 'check_apply_description_permissions'], 'args' => [ 'product_id' => [ 'required' => true, 'type' => 'integer', ], 'description' => [ 'required' => true, 'type' => 'string', ], 'type' => [ 'required' => false, 'type' => 'string', 'enum' => [ 'full', 'short', 'title', 'tags' ], 'default' => 'full', ], 'overwrite' => [ 'required' => false, 'type' => 'string', 'enum' => [ 'replace', 'empty_only' ], 'default' => 'replace', ], ], ]); register_rest_route($this->namespace, '/settings', [ [ 'methods' => 'GET', 'callback' => [$this, 'get_settings'], 'permission_callback' => [$this, 'check_permissions'], ], [ 'methods' => 'POST', 'callback' => [$this, 'update_settings'], 'permission_callback' => [$this, 'check_permissions'], 'args' => [ 'openai_api_key' => [ 'required' => false, 'type' => 'string', ], 'gemini_api_key' => [ 'required' => false, 'type' => 'string', ], 'openrouter_api_key' => [ 'required' => false, 'type' => 'string', ], 'claude_api_key' => [ 'required' => false, 'type' => 'string', ], 'api_provider' => [ 'required' => false, 'type' => 'string', 'enum' => ['openai', 'gemini', 'openrouter', 'claude'] ], 'short_custom_prompt' => [ 'required' => false, 'type' => 'string', ], 'full_custom_prompt' => [ 'required' => false, 'type' => 'string', ], 'language' => [ 'required' => false, 'type' => 'string', ], 'writing_style' => [ 'required' => false, 'type' => 'string', ], 'content_length_preset' => [ 'required' => false, 'type' => 'string', 'enum' => ['short', 'medium', 'long', 'very_long'] ], 'short_length_preset' => [ 'required' => false, 'type' => 'string', 'enum' => ['brief', 'standard', 'detailed'] ], 'max_tags_count' => [ 'required' => false, 'type' => 'string', ], 'request_interval' => [ 'required' => false, 'type' => 'string', ], 'model' => [ 'required' => false, 'type' => 'string', ], 'enable_tooltip' => [ 'required' => false, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ], 'preserve_content_images' => [ 'required' => false, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ], 'editor_clear_ai_mark_on_manual_edit' => [ 'required' => false, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ], ], ], ]); register_rest_route($this->namespace, '/validate-api-key', [ 'methods' => 'POST', 'callback' => [$this, 'validate_api_key'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/check-api-keys', [ 'methods' => 'GET', 'callback' => [$this, 'check_api_keys'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/complete-setup', [ 'methods' => 'POST', 'callback' => [$this, 'complete_setup'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/onboarding-status', [ 'methods' => 'GET', 'callback' => [$this, 'get_onboarding_status'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/snooze-onboarding', [ 'methods' => 'POST', 'callback' => [$this, 'snooze_onboarding'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/skip-setup', [ 'methods' => 'POST', 'callback' => [$this, 'skip_setup'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/quickstart-progress', [ 'methods' => 'POST', 'callback' => [$this, 'update_quickstart_progress'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/get-available-models', [ 'methods' => 'GET', 'callback' => [$this, 'get_available_models'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route( 'aipt/v1', '/openrouter-models/validate', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [ $this, 'validate_openrouter_model' ], 'permission_callback' => [ $this, 'check_tool_permissions_write' ], 'args' => [ 'model' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => static function ( $value ): string { return trim( sanitize_text_field( (string) $value ) ); }, ], ], ] ); register_rest_route($this->namespace, '/encryption-status', [ 'methods' => 'GET', 'callback' => [$this, 'get_encryption_status'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route( 'aipt/v1', '/connectors-status', [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_connectors_status' ], 'permission_callback' => [ $this, 'check_permissions' ], ] ); register_rest_route( 'aipt/v1', '/migrate-keys-to-connectors', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [ $this, 'migrate_keys_to_connectors' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'args' => [ 'providers' => [ 'type' => 'array', 'required' => true, 'sanitize_callback' => function ( $value ) { if ( ! is_array( $value ) ) { return []; } return array_values( array_map( 'sanitize_text_field', $value ) ); }, ], ], ] ); register_rest_route( 'aipt/v1', '/migration-notice/dismiss', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [ $this, 'dismiss_migration_notice' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'args' => [ 'mode' => [ 'type' => 'string', 'required' => true, 'enum' => [ 'snooze', 'permanent' ], 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ], ], ] ); register_rest_route( 'aipt/v1', '/upgrade-prompt-shown', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [ $this, 'record_upgrade_prompt_shown' ], 'permission_callback' => [ $this, 'check_tool_permissions_write' ], 'args' => [ 'feature' => [ 'type' => 'string', 'required' => true, 'sanitize_callback' => static function ( $value ): string { return trim( sanitize_text_field( (string) $value ) ); }, 'validate_callback' => static function ( $value ): bool { return is_string( $value ) && 1 === preg_match( '/^[A-Za-z0-9_]{1,64}$/', $value ); }, ], ], ] ); register_rest_route( 'aipt/v1', '/shop-manager-access', [ [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [ $this, 'get_shop_manager_access' ], 'permission_callback' => [ $this, 'check_admin_only_permissions' ], ], [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [ $this, 'update_shop_manager_access' ], 'permission_callback' => [ $this, 'check_admin_only_permissions_write' ], 'args' => [ 'enabled' => [ 'type' => 'boolean', 'required' => true, ], ], ], ] ); $this->register_automation_jobs_routes(); ( new \AIPT\Api\AiAvailability\AiAvailabilityController() )->register_routes(); } /** * Register automation jobs REST API routes */ private function register_automation_jobs_routes() { try { $job_manager = new \AIPT\Api\AutomationJobs\AutomationJobManager(); $logger = new \AIPT\Api\AutomationJobs\JobLogger(); $executor = new \AIPT\Api\AutomationJobs\JobExecutor($job_manager, $logger); $scheduler = new \AIPT\Api\AutomationJobs\JobScheduler($job_manager, $logger); $controller = new \AIPT\Api\AutomationJobs\AutomationJobsController( $job_manager, $executor, $scheduler, $logger ); $controller->register_routes(); $draft_controller = new \AIPT\Api\AutomationJobs\DraftContentController(); $draft_controller->register_routes(); \AIPT\Api\AutomationJobs\JobBlueprintScopeController::register_routes(); } catch (\Exception $e) { } } public function check_permissions() { return current_user_can('manage_aipt_settings'); } /** * Tool-level read permission check: grants access to any user who can use * the plugin's generator tools (administrators + shop managers). * * Used by non-sensitive tool routes such as /generate-description, * /generate-title and /generate-tags. Replaces the previously-referenced * but never-implemented check_admin_permissions() callback, which silently * 403'd for every role. See native Shop Manager permissions redesign (2.6.4). * * Deliberately takes no $request and performs no nonce check of its own, * matching check_apply_description_permissions()/ * check_generate_unified_permissions()'s identical convention for this * plugin's generate/apply tool routes: a cookie-authenticated request * carrying no nonce is already demoted to an anonymous request by * WordPress core's own rest_cookie_check_errors() before any * permission_callback runs, and an * Application Password-authenticated request correctly reaches this * capability check without being asked for a cookie nonce it has no way * to supply. * * @since 2.6.4 * * @return bool */ public function check_tool_permissions() { return current_user_can( 'use_aipt_tools' ); } public function check_tool_permissions_write( \WP_REST_Request $request ) { if ( \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } $nonce = is_string( $nonce ) ? sanitize_text_field( wp_unslash( $nonce ) ) : ''; if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new \WP_Error( 'rest_forbidden_nonce', __( 'Invalid security token. Please refresh and try again.', 'ai-product-tools' ), [ 'status' => 403 ] ); } } return current_user_can( 'use_aipt_tools' ); } /** * apply-description permission: tool-level use_aipt_tools, plus * edit_post on the target product — a custom-prompts insert must still * respect WordPress's own per-post editing capability, not only "can use * the plugin's tools at all". * * @since 2.8.0 * * @param \WP_REST_Request $request Incoming request. * @return true|\WP_Error */ public function check_apply_description_permissions( \WP_REST_Request $request ) { if ( ! current_user_can( 'use_aipt_tools' ) ) { return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.', 'ai-product-tools' ), [ 'status' => 403 ] ); } $product_id = (int) $request->get_param( 'product_id' ); if ( ! current_user_can( 'edit_post', $product_id ) ) { return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to edit this product.', 'ai-product-tools' ), [ 'status' => 403 ] ); } return true; } /** * generate-unified permission: tool-level use_aipt_tools, plus edit_post * on the target product, like check_apply_description_permissions() * above — generating a product's own content is a tool action gated on * that product's own editing rights, not a sensitive-settings action. * * @since 2.8.0 * * @param \WP_REST_Request $request Incoming request. * @return true|\WP_Error */ public function check_generate_unified_permissions( \WP_REST_Request $request ) { if ( ! current_user_can( 'use_aipt_tools' ) ) { return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.', 'ai-product-tools' ), [ 'status' => 403 ] ); } $product_id = (int) $request->get_param( 'product_id' ); if ( ! current_user_can( 'edit_post', $product_id ) ) { return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to edit this product.', 'ai-product-tools' ), [ 'status' => 403 ] ); } return true; } /** * Strict administrator-only read permission (manage_options). * * Used for the Shop Manager access-policy toggle: only true administrators * may see/change WHO gets settings access. A Shop Manager who has been opted * in (manage_aipt_settings) must NOT be able to change the policy that * governs their own access. * * @since 2.6.4 * * @return bool */ public function check_admin_only_permissions() { return current_user_can( 'manage_options' ); } /** * Strict administrator-only write permission (wp_rest nonce + manage_options). * * @since 2.6.4 * * @param \WP_REST_Request $request Incoming request. * @return bool|\WP_Error */ public function check_admin_only_permissions_write( \WP_REST_Request $request ) { if ( \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } $nonce = is_string( $nonce ) ? sanitize_text_field( wp_unslash( $nonce ) ) : ''; if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new \WP_Error( 'rest_forbidden_nonce', __( 'Invalid security token. Please refresh and try again.', 'ai-product-tools' ), [ 'status' => 403 ] ); } } return current_user_can( 'manage_options' ); } /** * Write-side permission check: validates wp_rest nonce + manage_options. * * Used by mutating REST routes (e.g., /migrate-keys-to-connectors, * /migration-notice/dismiss) per project convention. Mirrors the pattern * established in ChatbotController::check_permissions_write(). * * @since 2.6.0 * * @param \WP_REST_Request $request Incoming REST request. * @return bool|\WP_Error True on success, WP_Error(403) on invalid nonce, false on capability fail. */ public function check_permissions_write( \WP_REST_Request $request ) { if ( \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } $nonce = is_string( $nonce ) ? sanitize_text_field( wp_unslash( $nonce ) ) : ''; if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new \WP_Error( 'rest_forbidden_nonce', __( 'Invalid security token. Please refresh and try again.', 'ai-product-tools' ), [ 'status' => 403 ] ); } } return current_user_can( 'manage_aipt_settings' ); } /** * Gate shared by the single-product generate routes: AI support, then the * per-user limiter that the bulk and product editor routes also use. * * @return \WP_Error|null Refusal, or null when the request may proceed. */ private function guard_generation(): ?\WP_Error { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { return $ai_gate; } $rate_check = $this->checkRateLimit( (int) get_current_user_id(), 'metabox_generate' ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } return null; } public function generate_description($request) { $refusal = $this->guard_generation(); if ( $refusal instanceof \WP_Error ) { return $refusal; } return $this->content_generation_service->generateDescription( $request->get_params() ); } public function generate_title($request) { $refusal = $this->guard_generation(); if ( $refusal instanceof \WP_Error ) { return $refusal; } return $this->content_generation_service->generateTitle( $request->get_params() ); } public function generate_tags($request) { $refusal = $this->guard_generation(); if ( $refusal instanceof \WP_Error ) { return $refusal; } return $this->content_generation_service->generateTags( $request->get_params() ); } public function generate_unified($request) { $refusal = $this->guard_generation(); if ( $refusal instanceof \WP_Error ) { return $refusal; } $params = $request->get_params(); $product_id = absint( $params['product_id'] ); $content_types = isset( $params['content_types'] ) ? (array) $params['content_types'] : []; $options = isset( $params['options'] ) ? (array) $params['options'] : []; return $this->unified_generator->generate( $product_id, $content_types, $options ); } /** * Cleans prompt content and formats variables * * @param string $content Content to format * @param array $productData Array containing product data (optional) * @return string Cleaned and formatted content */ private function clean_prompt_content(string $content, array $productData = []): string { if (!empty($productData)) { return PromptFormatter::formatProductVariables($content, $productData); } return PromptFormatter::cleanContent($content); } /** * Formats text received from AI for the WordPress editor * * @param string $text Raw text received from AI * @return string Text formatted for the WordPress editor */ private function format_ai_response_for_wordpress($text) { return PromptFormatter::formatAiResponseForWordPress($text); } public function apply_description($request) { $params = $request->get_params(); $type = isset( $params['type'] ) ? $params['type'] : 'full'; $execution_path = \AIPT\Api\ContentStructure\Integration\BlueprintIntegration::executionPath( \AIPT\Core\ContentStructure\Domain\Generators::DESCRIPTION, [] ); $context = []; if ( \AIPT\Api\ContentStructure\Integration\BlueprintIntegration::PATH_BLUEPRINT === $execution_path['path'] ) { $context = [ 'blueprint' => true, 'overwrite' => isset( $params['overwrite'] ) ? (string) $params['overwrite'] : 'replace', ]; } return $this->content_generation_service->applyContent( $params['product_id'], $params['description'], $type, $context ); } public function get_settings() { return $this->settings_service->getSettings(); } public function update_settings($request) { return $this->settings_service->updateSettings( $request->get_params() ); } /** * GET the Shop Manager settings-access policy state (administrators only). * * @since 2.6.4 * * @return \WP_REST_Response */ public function get_shop_manager_access(): \WP_REST_Response { return new \WP_REST_Response( [ 'enabled' => (bool) get_option( 'aipt_allow_shop_manager_settings', false ) ], 200 ); } /** * Set the Shop Manager settings-access policy (administrators only). * * Writing the option fires update_option_aipt_allow_shop_manager_settings, * which grants/revokes manage_aipt_settings on the shop_manager role via * CapabilityManager::syncShopManagerSettingsCap(). * * @since 2.6.4 * * @param \WP_REST_Request $request Incoming request. * @return \WP_REST_Response */ public function update_shop_manager_access( \WP_REST_Request $request ): \WP_REST_Response { $enabled = rest_sanitize_boolean( $request->get_param( 'enabled' ) ); update_option( 'aipt_allow_shop_manager_settings', $enabled ); return new \WP_REST_Response( [ 'enabled' => $enabled ], 200 ); } /** * Record the feature that caused an upgrade prompt to be shown. * * @param \WP_REST_Request $request Incoming request. * @return \WP_REST_Response */ public function record_upgrade_prompt_shown( \WP_REST_Request $request ): \WP_REST_Response { $feature = (string) $request->get_param( 'feature' ); do_action( 'aipt_upgrade_prompt_shown', $feature ); return new \WP_REST_Response( [ 'recorded' => true ], 200 ); } private function get_product_info($product) { $product_info = []; $product_info['name'] = sanitize_text_field($product->get_name()); $product_info['sku'] = sanitize_text_field($product->get_sku()); $product_info['regular_price'] = $product->get_regular_price(); $product_info['sale_price'] = $product->get_sale_price(); $product_info['price'] = $product->get_price(); $product_info['currency'] = get_woocommerce_currency(); $product_info['short_description'] = $product->get_short_description(); $categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']); if (!is_wp_error($categories) && !empty($categories)) { $product_info['categories'] = array_map(function($category) { return html_entity_decode(sanitize_text_field($category), ENT_QUOTES, 'UTF-8'); }, $categories); } else { $product_info['categories'] = []; } $tags = wp_get_post_terms($product->get_id(), 'product_tag', ['fields' => 'names']); if (!is_wp_error($tags) && !empty($tags)) { $product_info['tags'] = array_map('sanitize_text_field', $tags); } else { $product_info['tags'] = []; } $product_info['attributes'] = []; $attributes = $product->get_attributes(); if (!empty($attributes)) { foreach ($attributes as $attribute) { if ($attribute instanceof \WC_Product_Attribute && $attribute->get_visible()) { $name = sanitize_text_field(wc_attribute_label($attribute->get_name())); $values = []; if ($attribute->is_taxonomy()) { $terms = wp_get_post_terms($product->get_id(), $attribute->get_name(), ['fields' => 'names']); if (!is_wp_error($terms)) { $values = array_map('sanitize_text_field', $terms); } } else { $options = $attribute->get_options(); $values = array_map('sanitize_text_field', $options); } if (!empty($values)) { $safe_values = implode(', ', $values); $product_info['attributes'][$name] = wp_kses($safe_values, []); } } } } return $product_info; } public function validate_api_key($request) { $params = $request->get_json_params(); $api_key = sanitize_text_field( $params['api_key'] ); $api_provider = sanitize_text_field( $params['api_provider'] ?? 'openai' ); $claude_workspace_id = ( isset( $params['claude_workspace_id'] ) && is_string( $params['claude_workspace_id'] ) ) ? sanitize_text_field( $params['claude_workspace_id'] ) : (string) get_option( 'aipt_claude_workspace_id', '' ); $supported_providers = \AIPT\Utils\ProviderNameMapper::aiptProviders(); if ( ! in_array( $api_provider, $supported_providers, true ) ) { return new \WP_Error( 'aipt_invalid_provider', esc_html( sprintf( /* translators: %s: comma-separated list of supported AI provider ids. */ __( 'Unknown API provider. Must be one of: %s.', 'ai-product-tools' ), implode( ', ', $supported_providers ) ) ), [ 'status' => 400 ] ); } $source = CredentialResolver::instance()->getSource( $api_provider ); if ( ! ApiKeyManager::localWriteAllowed( $api_provider ) ) { return new \WP_Error( 'aipt_provider_immutable', esc_html( sprintf( /* translators: %s: where the credential is managed, e.g. "WordPress Connectors", "Environment variable", "PHP constant". */ __( "This provider's API key is managed by %s and cannot be edited here. Update it there instead.", 'ai-product-tools' ), CredentialSource::label( $source ) ) ), [ 'status' => 403, 'source' => $source ] ); } $result = $this->settings_service->validateApiKey( $api_key, $api_provider, $claude_workspace_id ); if ( ! is_wp_error( $result ) ) { if ( $result instanceof \WP_REST_Response ) { $data = (array) $result->get_data(); $data['source'] = $source; $result->set_data( $data ); } elseif ( is_array( $result ) ) { $result['source'] = $source; } } return $result; } public function complete_setup($request) { $params = $request->get_json_params(); if ( ! is_array( $params ) ) { $params = array(); } return $this->onboarding_service->completeSetup( $params ); } public function get_available_models($request) { try { $api_provider = get_option('aipt_api_provider', 'openai'); $source = CredentialResolver::instance()->getSource( $api_provider ); if ($api_provider === 'openai') { $client = new OpenAIClient('dummy-key'); } elseif ($api_provider === 'openrouter') { $client = new OpenRouterClient('dummy-key'); } elseif ($api_provider === 'claude') { $client = new \AIPT\Api\Claude\ClaudeClient('dummy-key'); } else { $client = new GeminiClient('dummy-key'); } return [ 'models' => $client->get_available_models(), 'source' => $source, ]; } catch (\Exception $e) { $message = $e->getMessage(); $status = ErrorHandler::extract_http_status_from_message($message, 500); return new \WP_Error('models_fetch_failed', esc_html($message), ['status' => $status]); } } public function validate_openrouter_model( \WP_REST_Request $request ) { try { $model = trim( (string) $request->get_param( 'model' ) ); $metadata = OpenRouterClient::get_model_metadata( $model ); if ( $metadata === null ) { return new \WP_Error( 'aipt_openrouter_model_not_found', __( 'This model is not currently available on OpenRouter.', 'ai-product-tools' ), [ 'status' => 404 ] ); } return rest_ensure_response( [ 'model' => [ 'id' => $metadata['id'], 'label' => $metadata['label'], ], ] ); } catch ( \RuntimeException $e ) { return new \WP_Error( 'aipt_openrouter_catalog_unavailable', __( 'OpenRouter model validation is temporarily unavailable. Please try again.', 'ai-product-tools' ), [ 'status' => 503 ] ); } } public function check_api_keys() { if (!current_user_can('manage_aipt_settings')) { return new \WP_Error( 'rest_forbidden', esc_html__('Sorry, you are not allowed to do that.', 'ai-product-tools'), ['status' => 401] ); } $resolver = CredentialResolver::instance(); $status = $resolver->getStatus(); $provider_sources = []; foreach ( $status as $provider_id => $provider_data ) { $provider_sources[ $provider_id ] = [ 'source' => $provider_data['source'], ]; } return [ 'hasApiKey' => ApiKeyManager::has_any_api_key(), 'providers' => $provider_sources, ]; } public function get_encryption_status() { if (!current_user_can('manage_options')) { return new \WP_Error( 'rest_forbidden', esc_html__('Sorry, you are not allowed to do that.', 'ai-product-tools'), ['status' => 401] ); } return ApiKeyManager::get_encryption_status(); } private function sanitize_api_key(string $key): string { return $this->settings_service->sanitizeApiKey( $key ); } private function sanitize_multiline_text($text) { if (empty($text)) { return ''; } $text = preg_replace('/^\s*```[a-zA-Z]*\s*\n/', '', $text); $text = preg_replace('/\n\s*```\s*$/', '', $text); $text = preg_replace('/```[a-zA-Z]*/', '', $text); $text = preg_replace('/```/', '', $text); $containsHtml = preg_match('/<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>/is', $text); if ($containsHtml) { $text = preg_replace('/)<[^<]*)*<\/script>/mi', '', $text); $text = preg_replace('/)<[^<]*)*<\/iframe>/mi', '', $text); $text = preg_replace('/)<[^<]*)*<\/object>/mi', '', $text); $text = preg_replace('/)<[^<]*)*<\/embed>/mi', '', $text); $text = preg_replace('/\s*on\w+\s*=\s*["\'][^"\']*["\']/i', '', $text); $text = preg_replace('/\s*javascript\s*:/i', '', $text); $text = wp_kses_post($text); $text = preg_replace('/\xE2\x80\x8B|\x{200B}/u', '', $text); $text = str_replace("\r\n", "\n", $text); $text = str_replace("\r", "\n", $text); return $text; } $text = preg_replace('/)<[^<]*)*<\/script>/mi', '', $text); $text = preg_replace('/\s*on\w+\s*=\s*["\'][^"\']*["\']/i', '', $text); $text = preg_replace('/\s*javascript\s*:/i', '', $text); $text = preg_replace('/\xE2\x80\x8B|\x{200B}/u', '', $text); $text = str_replace("\r\n", "\n", $text); $text = str_replace("\r", "\n", $text); $lines = explode("\n", $text); $clean_lines = []; foreach ($lines as $line) { $clean_lines[] = sanitize_text_field(trim($line)); } return implode("\n", $clean_lines); } /** * Get onboarding status * Determines if onboarding popup should be shown */ public function get_onboarding_status(\WP_REST_Request $request): \WP_REST_Response { try { $status = $this->onboarding_service->getStatus(); return new \WP_REST_Response( $status, 200 ); } catch ( \Exception $e ) { return new \WP_REST_Response( array( 'success' => false, 'message' => 'Failed to get onboarding status: ' . esc_html($e->getMessage()), ), 500 ); } } /** * Snooze onboarding popup for 1 hour * Sets a timestamp for when onboarding should be shown again */ public function snooze_onboarding(\WP_REST_Request $request): \WP_REST_Response { try { $result = $this->onboarding_service->snooze(); return new \WP_REST_Response( $result, 200 ); } catch ( \Exception $e ) { return new \WP_REST_Response( array( 'success' => false, 'message' => 'Failed to snooze onboarding: ' . esc_html($e->getMessage()), ), 500 ); } } /** * Skip setup process * Marks setup as skipped and completed */ public function skip_setup(\WP_REST_Request $request): \WP_REST_Response { try { $result = $this->onboarding_service->skipSetup(); return new \WP_REST_Response( $result, 200 ); } catch ( \Exception $e ) { return new \WP_REST_Response( array( 'success' => false, 'message' => 'Failed to skip setup: ' . esc_html($e->getMessage()), ), 500 ); } } /** * Update quick start guide progress * * Handles complete_step, dismiss, and reset actions via single endpoint. * * @param \WP_REST_Request $request Request with 'action' and optional 'step_id' * @return \WP_REST_Response Updated quick start state */ public function update_quickstart_progress( \WP_REST_Request $request ): \WP_REST_Response { try { $params = $request->get_json_params(); $action = isset( $params['action'] ) ? sanitize_text_field( $params['action'] ) : ''; $step_id = isset( $params['step_id'] ) ? sanitize_text_field( $params['step_id'] ) : ''; switch ( $action ) { case 'complete_step': $result = $this->onboarding_service->completeQuickStartStep( $step_id ); break; case 'dismiss': $result = $this->onboarding_service->dismissQuickStart(); break; case 'reset': $result = $this->onboarding_service->resetQuickStart(); break; default: return new \WP_REST_Response( array( 'success' => false, 'message' => 'Invalid action. Use: complete_step, dismiss, or reset.', ), 400 ); } if ( is_wp_error( $result ) ) { /** @var \WP_Error $result */ $error_data = $result->get_error_data(); $status_code = is_array( $error_data ) && isset( $error_data['status'] ) ? (int) $error_data['status'] : 400; return new \WP_REST_Response( array( 'success' => false, 'message' => $result->get_error_message(), ), $status_code ); } return new \WP_REST_Response( array( 'success' => true, 'quickstart' => $result, ), 200 ); } catch ( \Exception $e ) { return new \WP_REST_Response( array( 'success' => false, 'message' => 'Failed to update quick start progress: ' . esc_html( $e->getMessage() ), ), 500 ); } } /** * GET /aipt/v1/connectors-status — Returns aggregate connector credential status. * * Rate-limited to 30 requests per 60 seconds per user. * Requires manage_options capability (enforced by permission_callback). * * @since 2.6.0 * * @return \WP_REST_Response|\WP_Error Connector status payload or rate-limit error. */ public function get_connectors_status() { $rate_check = $this->checkRateLimit( get_current_user_id(), 'connectors_status', 30, 60 ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $resolver = CredentialResolver::instance(); $providers = $resolver->getStatus(); $connectors_managed = array_filter( $providers, static fn( $p ) => ! empty( $p['isConnectorsManaged'] ) ); $payload = [ 'connectorsApiAvailable' => WordPressRuntimeDetector::supportsConnectorsApi(), 'connectorsAdminUrl' => admin_url( 'options-connectors.php' ), 'hasAnyConfigured' => $resolver->hasAnyConfiguredProvider(), 'providers' => $providers, 'hasAnyConnectorsManaged' => ! empty( $connectors_managed ), 'connectorsManagedCount' => count( $connectors_managed ), ]; return rest_ensure_response( $payload ); } /** * POST /aipt/v1/migrate-keys-to-connectors — Copy local plaintext keys into * Connectors DB options so users can switch to Connectors-managed UX without * losing access. Never overwrites env/constant-backed keys or existing * Connectors DB entries. * * Rate-limited to 5 requests per 60 seconds per user. * * @since 2.6.0 * * @param \WP_REST_Request $request REST request carrying `providers` array. * @return \WP_REST_Response|\WP_Error Per-provider migration results or rate-limit error. */ public function migrate_keys_to_connectors( \WP_REST_Request $request ) { $rate_check = $this->checkRateLimit( get_current_user_id(), 'migrate_keys', 5, 60 ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $providers_input = (array) $request->get_param( 'providers' ); $allowed = \AIPT\Utils\ProviderNameMapper::aiptProviders(); $allowed = array_values( array_diff( $allowed, array( 'openrouter' ) ) ); $providers = array_values( array_intersect( $providers_input, $allowed ) ); if ( empty( $providers ) ) { return new \WP_Error( 'aipt_migrate_invalid_providers', esc_html__( 'No valid providers supplied for migration.', 'ai-product-tools' ), [ 'status' => 400 ] ); } $local_provider = new \AIPT\Utils\Credentials\LocalCredentialProvider(); $resolver = CredentialResolver::instance(); $results = []; $migrated_count = 0; foreach ( $providers as $aipt_provider ) { $source = $resolver->getSource( $aipt_provider ); $connector_id = \AIPT\Utils\ProviderNameMapper::toConnectorId( $aipt_provider ); $option_name = 'connectors_ai_' . $connector_id . '_api_key'; if ( CredentialSource::ENV === $source ) { $results[] = [ 'provider' => $aipt_provider, 'status' => 'skipped_env' ]; continue; } if ( CredentialSource::CONSTANT === $source ) { $results[] = [ 'provider' => $aipt_provider, 'status' => 'skipped_constant' ]; continue; } $existing_connectors_value = get_option( $option_name, '' ); if ( ! empty( $existing_connectors_value ) ) { $results[] = [ 'provider' => $aipt_provider, 'status' => 'skipped_already_set' ]; continue; } $local_key = $local_provider->getKey( $aipt_provider ); if ( null === $local_key || '' === $local_key ) { $results[] = [ 'provider' => $aipt_provider, 'status' => 'skipped_no_local' ]; continue; } $saved = update_option( $option_name, $local_key, false ); if ( $saved ) { $results[] = [ 'provider' => $aipt_provider, 'status' => 'migrated' ]; $migrated_count++; } else { $results[] = [ 'provider' => $aipt_provider, 'status' => 'failed_write' ]; } } if ( $migrated_count > 0 ) { $resolver->flushMemoization(); \AIPT\Api\AiAvailability\AiAvailabilityController::clearCache(); } return rest_ensure_response( [ 'results' => $results ] ); } /** * POST /aipt/v1/migration-notice/dismiss — Hide the migration banner. * * Both modes are stored per-user so one admin closing the banner never hides * it from a co-admin who still needs to see it. * * - 'snooze' writes a 7-day expiry timestamp to the current user's meta; * the banner resurfaces once the timestamp has passed. * - 'permanent' writes a flag that the current user never wants to see it * again. * * @since 2.6.0 * * @param \WP_REST_Request $request REST request carrying `mode`. * @return \WP_REST_Response Acknowledgement payload. */ public function dismiss_migration_notice( \WP_REST_Request $request ) { $mode = (string) $request->get_param( 'mode' ); $user_id = get_current_user_id(); if ( 'snooze' === $mode ) { update_user_meta( $user_id, 'aipt_migration_notice_snoozed_until', time() + ( 7 * DAY_IN_SECONDS ) ); } elseif ( 'permanent' === $mode ) { update_user_meta( $user_id, 'aipt_connectors_migration_dismissed', 1 ); } return rest_ensure_response( [ 'dismissed' => true, 'mode' => $mode ] ); } }