'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, ?OnboardingService $onboarding_service = null, ?ApiKeyTestService $api_key_test_service = 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->onboarding_service = $onboarding_service ?? new OnboardingService(); $this->api_key_test_service = $api_key_test_service ?? new ApiKeyTestService(); } public function register_routes(): void { 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_write'], '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', ], 'monthly_spend_limit' => [ '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_write'] ]); register_rest_route($this->namespace, '/test-api-key', [ 'methods' => 'POST', 'callback' => [$this, 'test_api_key'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'provider' => [ 'required' => true, 'type' => 'string', 'enum' => \AIPT\Utils\ProviderNameMapper::aiptProviders(), ], ], ]); 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_write'] ]); 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_write'] ]); register_rest_route($this->namespace, '/skip-setup', [ 'methods' => 'POST', 'callback' => [$this, 'skip_setup'], 'permission_callback' => [$this, 'check_permissions_write'] ]); register_rest_route($this->namespace, '/quickstart-progress', [ 'methods' => 'POST', 'callback' => [$this, 'update_quickstart_progress'], 'permission_callback' => [$this, 'check_permissions_write'] ]); 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(); \AIPT\Api\AutomationJobs\JobBlueprintScopeController::register_routes(); } catch (\Exception $e) { Logger::error('automation', 'Automation routes could not be registered', array('error' => $e->getMessage())); } } public function check_permissions() { return current_user_can('manage_aipt_settings'); } /** * Tool-level write permission: the `wp_rest` nonce for a request that * was authenticated by the login cookie, then use_aipt_tools * (administrators and shop managers). * * Used by the two tool routes of this class: the OpenRouter model check * (aipt/v1/openrouter-models/validate) and the upgrade prompt record * (aipt/v1/upgrade-prompt-shown). The check asks a cookie request only * ({@see \AIPT\Utils\RestNonceGuard}), so an Application Password client * still reaches the capability check without a nonce it has no way to get. * * @since 2.6.4 * * @param \WP_REST_Request $request Incoming request. * @return bool|\WP_Error */ 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' ); } /** * 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' ); } 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 ); } 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; } /** * Test the saved key of a provider with one short real request. * * Rate-limited to 10 requests per 60 seconds per user: each test is a * request the provider bills. * * @param \WP_REST_Request $request Incoming request. * @return array|\WP_Error */ public function test_api_key( \WP_REST_Request $request ) { $rate_check = $this->checkRateLimit( get_current_user_id(), 'test_api_key', 10, 60 ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } return $this->api_key_test_service->test( (string) $request->get_param( 'provider' ) ); } 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(); } /** * 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 ] ); } }