ui = $ui; $this->ai_providers = $ai_providers; $this->ai_settings = $ai_settings; } public function slug(): string { return 'ai'; } public function label(): string { return __( 'AI Providers', 'acez-seo' ); } public function icon(): string { return 'ai'; } public function enqueue(): void { wp_enqueue_script( 'acez-seo-ai-providers', ACEZ_SEO_URL . 'assets/js/ai-providers.js', array(), ACEZ_SEO_VERSION, true ); wp_localize_script( 'acez-seo-ai-providers', 'AcezSeoAiProviders', array( 'restUrl' => esc_url_raw( rest_url( 'acez-seo/v1/test-provider' ) ), 'nonce' => wp_create_nonce( 'wp_rest' ), 'testing' => __( 'Testing…', 'acez-seo' ), 'error' => __( 'Failed to test the connection.', 'acez-seo' ), ) ); } public function handles_form_key( string $raw_tab ): bool { if ( str_starts_with( $raw_tab, 'ai:' ) || str_starts_with( $raw_tab, 'ai_disconnect:' ) ) { return true; } return in_array( sanitize_key( $raw_tab ), array( 'ai_active', 'ai_tasks', 'ai_usage', 'ai_clear_usage', 'ai_clear_log' ), true ); } /** @return array */ public function save( string $raw_tab ): array { // Defence in depth: SettingsPage::handle_save() verifies this nonce // before dispatch; re-checking keeps every entry point independently safe. check_admin_referer( FormControls::NONCE_ACTION ); if ( str_starts_with( $raw_tab, 'ai:' ) ) { $provider_id = sanitize_key( substr( $raw_tab, strlen( 'ai:' ) ) ); $this->save_provider( $provider_id ); // Card visibility is normally driven by "Aktywny dostawca" (the // generation-facing setting), NOT by which card was just edited — // so saving a key/model for a provider that ISN'T (yet) the active // one leaves its card hidden on reload, looking exactly like the // save silently failed. Carry the just-saved provider through the // redirect so render() can show ITS card this one time, without // touching the actual active_provider value. return array( 'tab' => 'ai', 'ai_provider' => $provider_id, ); } if ( str_starts_with( $raw_tab, 'ai_disconnect:' ) ) { $provider_id = sanitize_key( substr( $raw_tab, strlen( 'ai_disconnect:' ) ) ); $this->ai_settings->disconnect_provider( $provider_id ); delete_transient( self::auto_test_cache_key( $provider_id ) ); return array( 'tab' => 'ai', 'ai_provider' => $provider_id, ); } $tab_key = sanitize_key( $raw_tab ); if ( 'ai_active' === $tab_key ) { $this->ai_settings->set_active_provider( isset( $_POST['active_provider'] ) ? sanitize_key( wp_unslash( $_POST['active_provider'] ) ) : '' ); } elseif ( 'ai_tasks' === $tab_key ) { $map = array(); // Only the tasks the card actually renders — a task without a // field (e.g. an add-on's task while the add-on is inactive) keeps // its stored model instead of being blanked by this save. foreach ( array_keys( $this->ai_task_labels() ) as $task ) { $map[ $task ] = isset( $_POST[ 'task_model_' . $task ] ) ? sanitize_text_field( wp_unslash( $_POST[ 'task_model_' . $task ] ) ) : ''; } $this->ai_settings->update_task_models( $map ); } elseif ( 'ai_usage' === $tab_key ) { $this->ai_settings->set_monthly_limit( isset( $_POST['ai_monthly_limit'] ) ? absint( $_POST['ai_monthly_limit'] ) : 0 ); } elseif ( 'ai_clear_usage' === $tab_key ) { \AcezSeo\Ai\AiUsageLog::clear_current_month(); } elseif ( 'ai_clear_log' === $tab_key ) { \AcezSeo\Ai\AiUsageLog::clear_log(); } return array( 'tab' => 'ai' ); } private function save_provider( string $provider_id ): void { // Defence in depth: SettingsPage::handle_save() verifies this nonce // before dispatch; re-checking keeps every entry point independently safe. check_admin_referer( FormControls::NONCE_ACTION ); $field = static fn( string $base ): string => $base . '_' . $provider_id; $this->ai_settings->update_provider( $provider_id, array( 'api_key' => isset( $_POST[ $field( 'api_key' ) ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field( 'api_key' ) ] ) ) : '', 'model' => isset( $_POST[ $field( 'model' ) ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field( 'model' ) ] ) ) : '', ) ); // "1" is set by ai-providers.js after a SUCCESSFUL connection test of // exactly this form state (the Save button only appears then) — this // is what unlocks the Dashboard "Obsługa AI" toggle. The noscript // path saves without a test, so it correctly stays untested. $tested = isset( $_POST[ $field( 'provider_tested' ) ] ) && '1' === $_POST[ $field( 'provider_tested' ) ]; $this->ai_settings->mark_tested( $provider_id, $tested ); // A provider saved right after a successful test becomes the active one // automatically — without this, "Zapisz" left the separate "Aktywny // dostawca" dropdown untouched and generation kept failing with "Nie // wybrano aktywnego dostawcy AI" despite a saved, tested key. Same // behavior as the onboarding wizard's Step 3. The untested/noscript // save path deliberately does not switch the active provider. if ( $tested ) { $this->ai_settings->set_active_provider( $provider_id ); } // A just-saved key must be re-checked on the NEXT render — otherwise // a stale cached failure from the old key would still show, or a // stale cached success would mask a real problem with the new one. delete_transient( self::auto_test_cache_key( $provider_id ) ); } public function render(): void { echo '

' . esc_html__( 'Configure the AI provider used to generate titles, SEO descriptions, and image alt text (the "Generate with AI" button in the editor). API keys are encrypted in the database.', 'acez-seo' ) . wp_kses( HelpIcon::render( 'ai_providers' ), KsesTags::help_icon() ) . '

'; $this->auto_test_active_provider(); $providers = $this->ai_providers->all(); $active = $this->ai_settings->get_active_provider(); // A just-saved-or-disconnected provider (see save()) is shown here // even when it isn't (yet) the active one — otherwise its card stays // hidden after the redirect and the save looks like it silently // failed. Display-only: the real active_provider in the database is // untouched unless the "Aktywny dostawca" form below is submitted. // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display hint from our own redirect, no state change. $requested_provider = isset( $_GET['ai_provider'] ) ? sanitize_key( wp_unslash( $_GET['ai_provider'] ) ) : ''; $known_provider_ids = array_map( static fn( AiProviderInterface $p ): string => $p->get_id(), $providers ); $display_active = ( '' !== $requested_provider && in_array( $requested_provider, $known_provider_ids, true ) ) ? $requested_provider : $active; $this->ui->card_open( __( 'Active provider', 'acez-seo' ), 'ai', '', 'ai-active-provider' ); $this->ui->form_open( 'ai_active' ); echo '
' . esc_html__( 'Provider used for generation', 'acez-seo' ) . '

' . esc_html__( 'The configuration below appears for the provider selected here.', 'acez-seo' ) . '

'; submit_button(); $this->ui->form_close(); $this->ui->card_close(); foreach ( $providers as $provider ) { // Exactly one card shown at a time, matching the "Konfiguracja // poniżej pojawia się dla wybranego tu dostawcy" description above: // $display_active is either the real saved active_provider, or — // for exactly one page load right after editing/disconnecting a // DIFFERENT (not-yet-active) provider — the just-saved one via // $requested_provider, so that save doesn't look like it silently // failed. A provider that was previously configured but never made // active stays reachable by picking it in the dropdown above and // saving — that submit sets it active and reveals its card. $is_shown = $provider->get_id() === $display_active; $this->render_ai_provider_card( $provider, $is_shown ); } $this->render_ai_task_models_card(); $this->render_ai_usage_card(); } /** * Background connectivity check for the ACTIVE provider (user-requested * follow-up, 2026-07-19): trial API keys (common on 7-day test accounts) * expire silently — without this, the tab kept showing a stale "tested * OK" state from the last manual click, with no visible sign generation * had actually started failing. Cached for AUTO_TEST_CACHE_TTL so simply * reloading this tab doesn't re-spend an API call every time; the cache * is invalidated immediately on save/disconnect (see save_provider()). * Silent on success — this is a health check, not something to * congratulate the user about on every visit. */ private function auto_test_active_provider(): void { $active = $this->ai_settings->get_active_provider(); if ( '' === $active || ! $this->ai_settings->has_api_key( $active ) ) { return; } $cache_key = self::auto_test_cache_key( $active ); $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { $this->render_auto_test_notice( $cached ); return; } $provider = $this->ai_providers->get( $active ); if ( null === $provider ) { return; } try { $provider->test_connection(); $result = array( 'ok' => true, 'message' => '' ); } catch ( \AcezSeo\Ai\AiProviderException $exception ) { $result = array( 'ok' => false, 'message' => $exception->getMessage() ); } // Keeps "tested" a LIVE health signal (also gates the Dashboard "Obsługa // AI" toggle) rather than a one-time flag from the last manual click — // a silently-expired key now greys that toggle out too, not just this tab. $this->ai_settings->mark_tested( $active, $result['ok'] ); set_transient( $cache_key, $result, self::AUTO_TEST_CACHE_TTL ); $this->render_auto_test_notice( $result ); } private static function auto_test_cache_key( string $provider_id ): string { return 'acez_seo_ai_autotest_' . $provider_id; } /** @param array{ok: bool, message: string} $result */ private function render_auto_test_notice( array $result ): void { if ( $result['ok'] ) { return; } printf( '

%1$s %2$s

%3$s

', esc_html__( 'The active AI provider is not responding correctly:', 'acez-seo' ), esc_html( $result['message'] ), esc_html__( 'The key may have expired (common with trial/test keys) or been revoked. Enter a current key in the card below and click "Test connection".', 'acez-seo' ) ); } /** * Per-task model overrides (M36) — e.g. a cheap/fast model for alt texts, * a stronger one for schema nodes. */ private function render_ai_task_models_card(): void { $task_models = $this->ai_settings->get_task_models(); $this->ui->card_open( __( 'Model per task', 'acez-seo' ), 'ai', '', 'ai-task-models' ); echo '

' . esc_html__( 'Optional: a different model for each task type (e.g. a cheap, fast one for alt texts, a stronger one for schema nodes). Empty field = the model configured for the active provider. The model you enter must exist at the ACTIVE provider.', 'acez-seo' ) . wp_kses( HelpIcon::render( 'ai_task_models' ), KsesTags::help_icon() ) . '

'; $this->ui->form_open( 'ai_tasks' ); echo ''; foreach ( $this->ai_task_labels() as $task => $label ) { printf( '', esc_attr( $task ), esc_html( $label ), esc_attr( (string) ( $task_models[ $task ] ?? '' ) ), esc_attr__( 'provider\'s default model', 'acez-seo' ) ); } echo '
'; submit_button(); $this->ui->form_close(); $this->ui->card_close(); } /** * Local usage counters, the soft monthly limit and the recent-generations * log (M36). Everything is stored locally in wp_options. */ private function render_ai_usage_card(): void { $summary = \AcezSeo\Ai\AiUsageLog::current_month_summary(); $labels = $this->ai_task_labels(); $this->ui->card_open( __( 'Usage and log', 'acez-seo' ), 'ai', '', 'ai-usage' ); echo '

' . esc_html__( 'The counters are approximate (≈4 characters per token) and stored only locally — nothing is sent anywhere.', 'acez-seo' ) . wp_kses( HelpIcon::render( 'ai_usage' ), KsesTags::help_icon() ) . '

'; echo '

' . esc_html__( 'Current month', 'acez-seo' ) . '

'; if ( array() === $summary ) { echo '

' . esc_html__( 'No AI calls this month.', 'acez-seo' ) . '

'; } else { echo ''; foreach ( $summary as $task => $totals ) { printf( '', esc_html( $labels[ $task ] ?? $task ), absint( $totals['calls'] ), esc_html( number_format_i18n( (int) $totals['tokens'] ) ) ); } printf( '', esc_html__( 'Total', 'acez-seo' ), absint( array_sum( array_column( $summary, 'calls' ) ) ), esc_html( number_format_i18n( (int) array_sum( array_column( $summary, 'tokens' ) ) ) ) ); echo '
' . esc_html__( 'Task', 'acez-seo' ) . '' . esc_html__( 'Calls', 'acez-seo' ) . '' . esc_html__( '~Tokens', 'acez-seo' ) . '
%1$s%2$d%3$s
%1$s%2$d%3$s
'; } $this->render_ai_cost_estimate(); $this->ui->form_open( 'ai_usage' ); echo ''; printf( '', esc_html__( 'Monthly call limit', 'acez-seo' ), absint( $this->ai_settings->get_monthly_limit() ), esc_html__( '0 = no limit. The limit is SOFT: once reached, every further generation asks for confirmation, but is never hard-blocked.', 'acez-seo' ) ); echo '

%3$s

'; submit_button(); $this->ui->form_close(); if ( array() !== $summary ) { $total_calls = absint( array_sum( array_column( $summary, 'calls' ) ) ); $this->ui->form_open( 'ai_clear_usage' ); printf( '

', esc_attr( sprintf( /* translators: %d: number of AI calls counted this month */ __( 'Reset this month\'s counters (%d calls)? This action is irreversible — previous months (up to 3) stay untouched.', 'acez-seo' ), $total_calls ) ), esc_html__( 'Reset this month\'s counters', 'acez-seo' ) ); $this->ui->form_close(); } $recent = \AcezSeo\Ai\AiUsageLog::recent(); echo '

' . esc_html__( 'Recent generations', 'acez-seo' ) . '

'; if ( array() === $recent ) { echo '

' . esc_html__( 'The log is empty.', 'acez-seo' ) . '

'; } else { echo ''; foreach ( $recent as $entry ) { printf( '', esc_html( wp_date( 'Y-m-d H:i:s', (int) ( $entry['time'] ?? 0 ) ) ), esc_html( $labels[ (string) ( $entry['task'] ?? '' ) ] ?? (string) ( $entry['task'] ?? '' ) ), esc_html( trim( (string) ( $entry['provider'] ?? '' ) . ' / ' . ( '' !== (string) ( $entry['model'] ?? '' ) ? (string) $entry['model'] : '—' ) ) ), ( $entry['ok'] ?? false ) ? 'acez-seo-badge--on' : 'acez-seo-badge--off', ( $entry['ok'] ?? false ) ? esc_html__( 'OK', 'acez-seo' ) : esc_html__( 'Error', 'acez-seo' ), ( $entry['ok'] ?? false ) ? '' : '
' . esc_html( (string) ( $entry['note'] ?? '' ) ) . '', esc_html( sprintf( '%d ms', (int) ( $entry['duration_ms'] ?? 0 ) ) ) ); } echo '
' . esc_html__( 'When', 'acez-seo' ) . '' . esc_html__( 'Task', 'acez-seo' ) . '' . esc_html__( 'Provider / model', 'acez-seo' ) . '' . esc_html__( 'Status', 'acez-seo' ) . '' . esc_html__( 'Duration', 'acez-seo' ) . '
%1$s%2$s%3$s%5$s%6$s%7$s
'; $this->ui->form_open( 'ai_clear_log' ); printf( '

', esc_attr( sprintf( /* translators: %d: number of log entries that will be deleted */ __( 'Clear the generation log (%d entries)? This action is irreversible.', 'acez-seo' ), count( $recent ) ) ), esc_html__( 'Clear generation log', 'acez-seo' ) ); $this->ui->form_close(); } $this->ui->card_close(); } /** * Tasks shown on the "Model per task" card — the SAME list drives the * card's render and its save, so a task can never be saved without being * shown (the old split between this list and AiGenerationService::TASKS * left "article" with no field at all). * * @return array Ordered like AiGenerationService::TASKS. */ private function ai_task_labels(): array { $labels = array( 'title' => __( 'SEO titles', 'acez-seo' ), 'description' => __( 'Meta descriptions', 'acez-seo' ), 'product_description' => __( 'Product descriptions', 'acez-seo' ), 'keyword' => __( 'Focus keyphrases', 'acez-seo' ), 'alt_text' => __( 'Image alt text', 'acez-seo' ), 'schema_node' => __( 'Schema nodes (FAQ/HowTo)', 'acez-seo' ), 'translation' => __( 'Meta translations', 'acez-seo' ), 'article' => __( 'Full articles', 'acez-seo' ), 'llms' => __( 'llms.txt content', 'acez-seo' ), ); /** * Filters the AI tasks listed on the "Model per task" card. An add-on * that runs its own task (one of AiGenerationService::TASKS) adds its * label here; keys outside TASKS are ignored. * * @param array $labels Task key => human-readable label. */ $labels = (array) apply_filters( 'acez_seo_ai_task_labels', $labels ); $ordered = array(); foreach ( \AcezSeo\Ai\AiGenerationService::TASKS as $task ) { if ( isset( $labels[ $task ] ) && is_string( $labels[ $task ] ) ) { $ordered[ $task ] = $labels[ $task ]; } } return $ordered; } /** Estimated month-to-date cost per model (M45) — an estimate, never a balance. */ private function render_ai_cost_estimate(): void { $models = \AcezSeo\Ai\AiUsageLog::current_month_models(); if ( array() === $models ) { return; } echo '

' . esc_html__( 'Estimated cost (current month)', 'acez-seo' ) . '

'; echo ''; $total = 0.0; foreach ( $models as $key => $tokens ) { list( $provider_id, $model ) = array_pad( explode( '|', (string) $key, 2 ), 2, '' ); $cost = \AcezSeo\Ai\ModelPricing::estimate_cost( $provider_id, $model, (int) $tokens ); $total += $cost; printf( '', esc_html( '' !== $model ? $model /* translators: %s: AI provider id */ : sprintf( __( 'default (%s)', 'acez-seo' ), $provider_id ) ), esc_html( number_format_i18n( (int) $tokens ) ), esc_html( '$' . number_format( $cost, $cost < 0.01 ? 4 : 2 ) ) ); } printf( '', esc_html__( 'Total', 'acez-seo' ), esc_html( '$' . number_format( $total, $total < 0.01 ? 4 : 2 ) ) ); echo '
' . esc_html__( 'Model', 'acez-seo' ) . '' . esc_html__( '~Tokens', 'acez-seo' ) . '' . esc_html__( '~Cost (USD)', 'acez-seo' ) . '
%1$s%2$s%3$s
%1$s%2$s
'; echo '

' . esc_html__( 'An estimate based on a built-in, averaged price table per 1M tokens (editable via the acez_seo_ai_model_prices filter) — this is NOT your account balance at the provider.', 'acez-seo' ) . '

'; } /** Provider billing/usage dashboards (M45) — where the REAL numbers live. */ private function ai_usage_dashboard_url( string $provider_id ): string { $urls = apply_filters( 'acez_seo_ai_usage_urls', array( 'openai' => 'https://platform.openai.com/usage', 'anthropic' => 'https://console.anthropic.com/settings/usage', 'gemini' => 'https://aistudio.google.com/usage', 'openrouter' => 'https://openrouter.ai/activity', // phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration -- plain usage-dashboard URL (see AiProviderException docblock and M67), not an API call. ) ); return is_array( $urls ) ? (string) ( $urls[ $provider_id ] ?? '' ) : ''; } private function render_ai_provider_card( AiProviderInterface $provider, bool $is_active ): void { $provider_id = $provider->get_id(); $model = $this->ai_settings->get_model( $provider_id ); $has_key = $this->ai_settings->has_api_key( $provider_id ); printf( '
', esc_attr( $provider_id ), $is_active ? '' : ' hidden' ); printf( '
%1$s%2$s
', wp_kses( $this->ui->tab_icon_svg( 'ai' ), KsesTags::svg() ), esc_html( $provider->get_label() ) ); $this->ui->form_open( 'ai:' . $provider_id ); echo ''; printf( '', esc_attr( $provider_id ), esc_html__( 'API key', 'acez-seo' ), $has_key ? esc_attr__( '•••••••• (saved, leave blank to keep it unchanged)', 'acez-seo' ) : esc_attr__( 'not set', 'acez-seo' ), esc_html__( 'The key is encrypted before saving and is never displayed again.', 'acez-seo' ) ); // name/id are both namespaced per provider ($provider_id) — they used // to share a bare name="model"/"api_key" across all provider cards // (kept identical "for the shared save handler", which never actually // needed it: only one card's posts at a time). That let // browser form-autofill, which keys by `name` rather than by , // silently overwrite one provider's rendered value with another // provider's previously-typed one on page load — e.g. Anthropic's // model showing up in the OpenRouter card. autocomplete="off" alone // does not reliably suppress this in every browser, so the fix is to // make the names unique instead of fighting autofill. printf( '', esc_attr( $provider_id ), esc_html__( 'Model', 'acez-seo' ), esc_attr( $model ), esc_attr__( 'leave blank to use the default', 'acez-seo' ), wp_kses( HelpIcon::render( 'ai_model' ), KsesTags::help_icon() ) ); // Populated by ai-providers.js after a successful "Testuj połączenie" // with up to 10 of the provider's most recent models — picking one // fills the "Model" field above, which is what actually gets saved. printf( '', esc_attr( $provider_id ), esc_html__( 'Suggested models', 'acez-seo' ), esc_html__( '— choose a model —', 'acez-seo' ), esc_html__( 'List fetched from the provider after a successful connection test. Selecting one fills the "Model" field above.', 'acez-seo' ) ); echo '

%4$s

%5$s
'; echo '

'; printf( ' ', esc_html__( 'Test connection', 'acez-seo' ) ); echo ''; echo '

'; // Set to "1" by ai-providers.js after a successful connection test — // the save handler persists it as the provider's "tested" state. printf( '', esc_attr( $provider_id ) ); printf( '

', $has_key ? '' : ' hidden' ); // Custom class via $type (not $other_attributes['class']) — get_submit_button() // emits a class="..." from BOTH sources independently, so passing 'class' // via $other_attributes here produced two class="" attributes on one // tag (the second, with our custom class, was silently dropped by every // browser's HTML parser). submit_button( __( 'Save', 'acez-seo' ), 'primary acez-seo-ai-save-button', 'save_provider', false ); echo '

'; echo ''; $this->ui->form_close(); if ( $has_key ) { $this->ui->form_open( 'ai_disconnect:' . $provider_id ); printf( '

%3$s

', esc_attr( sprintf( /* translators: %s: AI provider label, e.g. "OpenAI" */ __( 'Disconnect %s? The saved API key, model, and connection test status will be permanently deleted from the database — this cannot be undone.', 'acez-seo' ), $provider->get_label() ) ), esc_html__( 'Disconnect and delete API key', 'acez-seo' ), esc_html__( 'Removes the key without a trace — it cannot be recovered, you\'ll need to enter it again.', 'acez-seo' ) ); $this->ui->form_close(); } $usage_url = $this->ai_usage_dashboard_url( $provider_id ); if ( '' !== $usage_url ) { printf( '', esc_url( $usage_url ), esc_html__( 'Check usage at the provider ↗', 'acez-seo' ), esc_html__( 'Actual usage and account balance are in the provider\'s dashboard (login required).', 'acez-seo' ) ); } echo '
'; } }