800, 'medium' => 1600, 'long' => 3200, ); private const RATE_LIMIT_MAX = 10; private const RATE_LIMIT_WINDOW = MINUTE_IN_SECONDS; private AiProviderRegistry $providers; private ?AiSettingsRepositoryInterface $settings; public function __construct( AiProviderRegistry $providers, ?AiSettingsRepositoryInterface $settings = null ) { $this->providers = $providers; $this->settings = $settings; } public static function task_for_field( string $field ): string { if ( in_array( $field, self::SCHEMA_NODE_FIELDS, true ) ) { return 'schema_node'; } if ( str_starts_with( $field, 'translate_' ) ) { return 'translation'; } return in_array( $field, self::TASKS, true ) ? $field : 'description'; } /** * @throws AiProviderException */ public function generate_for_post_field( string $field, \WP_Post $post, bool $confirmed = false ): string { $prompt = PromptBuilder::for_field( $field, $post ); return $this->run( self::task_for_field( $field ), $confirmed, $prompt, static fn( AiProviderInterface $provider ): string => $provider->generate_text( $prompt ) ); } /** * Generic entry point for AI fields whose context isn't a `\WP_Post` * (e.g. Pro's 404-redirect-target suggestion, where the context is a * URL path). The base plugin builds NO default prompt here — the entire * prompt must come from an `acez_seo_ai_prompt` filter listener, which * keeps this class ignorant of any addon-specific concept. An empty * result means no listener claimed the field, so we fail loudly instead * of sending a blank prompt to the provider. * * @param mixed $context Whatever the field's `acez_seo_ai_prompt` listener expects. * * @throws AiProviderException */ public function generate_for_filtered_field( string $task, string $field, $context, bool $confirmed = false ): string { $prompt = (string) apply_filters( 'acez_seo_ai_prompt', '', $field, $context ); if ( '' === trim( $prompt ) ) { throw new AiProviderException( __( 'No prompt registered for this field.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return $this->run( $task, $confirmed, $prompt, static fn( AiProviderInterface $provider ): string => $provider->generate_text( $prompt ) ); } /** * Generates a full article body in Markdown (M62), which the caller then * converts to the target editor's format (HTML for Classic, blocks for * Gutenberg — see Support\MarkdownConverter). Two input modes: 'page' * (the post's own existing title/content/meta as context) or 'brief' (a * short user-supplied description IS the topic, page content is only * secondary context). The brief is a one-off request parameter, never * persisted — unlike the AI_CONTEXT_* meta fields, which shape every * future generation for that post. * * @param string $mode 'page' or 'brief' * @param string $brief Required (non-empty) when $mode === 'brief', ignored otherwise. * @param string $length 'short', 'medium' or 'long' — controls the output token budget. * * @throws AiProviderException */ public function generate_article( \WP_Post $post, string $mode, string $brief, string $length, bool $confirmed = false ): string { if ( ! isset( self::ARTICLE_MAX_TOKENS[ $length ] ) ) { $length = 'medium'; } if ( 'brief' === $mode && '' === trim( $brief ) ) { throw new AiProviderException( __( 'Provide a short description for the AI to write the article from.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $prompt = PromptBuilder::for_article( $post, 'brief' === $mode ? 'brief' : 'page', trim( $brief ), $length ); $max_tokens = self::ARTICLE_MAX_TOKENS[ $length ]; return $this->run( 'article', $confirmed, $prompt, static fn( AiProviderInterface $provider ): string => trim( $provider->generate_text( $prompt, $max_tokens ) ) ); } /** * Generates a complete schema.org node (M33): the model must return raw * JSON; markdown fences are tolerated and stripped, anything else that * fails to decode into an object with @type is rejected — an invalid * node must never reach the repeater field. * * @throws AiProviderException */ public function generate_schema_node( string $field, \WP_Post $post, bool $confirmed = false ): string { $prompt = PromptBuilder::for_field( $field, $post ); $raw = $this->run( 'schema_node', $confirmed, $prompt, static fn( AiProviderInterface $provider ): string => trim( $provider->generate_text( $prompt ) ) ); // Models often wrap JSON in ```json … ``` despite instructions. $raw = trim( (string) preg_replace( '/^```(?:json)?\s*|\s*```$/', '', $raw ) ); $node = json_decode( $raw, true ); if ( ! is_array( $node ) || ! isset( $node['@type'] ) || ! is_string( $node['@type'] ) ) { throw new AiProviderException( __( 'The AI did not return a valid schema.org JSON node — please try again.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return (string) wp_json_encode( $node, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } /** * Vision-first (M34): when the active provider supports image input, the * alt text comes from ANALYZING the image. Image-preparation failures * (unsupported format, unreadable file) fall back to the legacy * filename/caption-based prompt; real API errors still propagate. * * Unlocked for everyone in M69 Etap 6 (2026-08-26), reversing the M53 * decision to sell it. The reason is structural, not commercial: every * `generate_from_image()` is welded into its provider's own auth, model * and response handling here in the base plugin, so the only way to make * this a genuinely Pro-side feature would be to fork all four providers * into the addon. Anything cheaper leaves the vision code shipping in the * WordPress.org package with a licence switching it on — exactly what * Guideline 5 forbids and what the reviewer flagged by name. The user * calls the shot to leave no room for argument, so the gate is gone and * the capability is simply part of the free plugin. * * @throws AiProviderException */ public function generate_alt_text( int $attachment_id, bool $confirmed = false ): string { $vision_used = false; $callable = function ( AiProviderInterface $provider ) use ( $attachment_id, &$vision_used ): string { // No licence check (M69 Etap 6): if the active provider can read // images, it reads the image. The filename/caption prompt below // stays as the fallback for providers that cannot, and for images // that fail preparation. if ( $provider instanceof AiVisionProviderInterface ) { try { $payload = ImagePayload::from_attachment( $attachment_id ); $vision_used = true; return $provider->generate_from_image( PromptBuilder::for_alt_text_vision( $attachment_id ), $payload ); } catch ( AiImageException $exception ) { $vision_used = false; // Fall through to the filename-based prompt below. } } return $provider->generate_text( PromptBuilder::for_alt_text( $attachment_id ) ); }; return $this->run( 'alt_text', $confirmed, PromptBuilder::for_alt_text( $attachment_id ), $callable, $vision_used ); } /** * Shared pipeline: limits → task model context → provider call → local * usage/log accounting (success and failure alike). * * @param callable(AiProviderInterface): string $call * * @throws AiProviderException */ private function run( string $task, bool $confirmed, string $prompt, callable $call, bool &$vision_used = false ): string { $this->enforce_rate_limit(); $this->enforce_monthly_limit( $confirmed ); $provider = $this->active_provider(); if ( null !== $this->settings ) { $this->settings->set_task_context( $task ); } $model = null !== $this->settings ? $this->settings->get_model( $provider->get_id() ) : ''; $start = microtime( true ); try { $text = $call( $provider ); AiUsageLog::record( $task, $provider->get_id(), $model, true, '', AiUsageLog::estimate_tokens( $prompt, $text, $vision_used ), (int) round( ( microtime( true ) - $start ) * 1000 ) ); return $text; } catch ( AiProviderException $exception ) { AiUsageLog::record( $task, $provider->get_id(), $model, false, $exception->getMessage(), 0, (int) round( ( microtime( true ) - $start ) * 1000 ) ); throw $exception; } finally { if ( null !== $this->settings ) { $this->settings->set_task_context( null ); } } } /** * @throws AiProviderException */ private function active_provider(): AiProviderInterface { $provider = $this->providers->get_active(); if ( null === $provider ) { throw new AiProviderException( __( 'No active AI provider selected. Configure one in Acez SEO AI → AI Providers.', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return $provider; } /** * @throws AiProviderException */ private function enforce_rate_limit(): void { $key = 'acez_seo_ai_rate_' . get_current_user_id(); $count = (int) get_transient( $key ); if ( $count >= self::RATE_LIMIT_MAX ) { throw AiProviderException::rate_limited(); } set_transient( $key, $count + 1, self::RATE_LIMIT_WINDOW ); } /** * SOFT monthly budget (M36): reaching the user-configured limit requires * an explicit confirmation per request — it warns, it never hard-blocks. * * @throws AiLimitException */ private function enforce_monthly_limit( bool $confirmed ): void { if ( $confirmed || null === $this->settings ) { return; } $limit = $this->settings->get_monthly_limit(); if ( $limit <= 0 ) { return; } $calls = AiUsageLog::calls_this_month(); if ( $calls >= $limit ) { throw new AiLimitException( sprintf( /* translators: 1: calls made this month, 2: configured monthly limit */ __( 'The monthly AI generation limit has been reached (%1$d of %2$d). You can continue past the limit — further calls will increase your provider costs.', 'acez-seo' ), // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). $calls, // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). $limit // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). ) ); } } }