600, 'pending' => 300, 'alive' => 200, ); /** * Rate-limit scope identifier. * * Subclasses MUST override this constant with a unique, lowercase string * that identifies their generator type (e.g. 'title', 'faq', 'seo_meta'). * This value is passed to `RateLimitTrait::checkRateLimit()` as the scope * parameter and forms part of the transient key * (`aipt_rate_limit_{scope}_{user_id}`). * * Keeping each generator on a separate scope means a flood of title * generation requests will not consume the FAQ or SeoMeta allowances. */ protected const RATE_LIMIT_SCOPE = 'default'; /** * Register REST routes — must be implemented by each subclass. * * @return void */ abstract public function register_routes(); /** * Check read permission for GET endpoints. * * Called as `permission_callback` on read-only REST routes. Returns a * simple boolean because GET endpoints do not require nonce validation * (nonces are CSRF tokens; GET requests are safe and idempotent). * * @return bool True when the current user has `manage_woocommerce`. */ public function check_permissions(): bool { return current_user_can( 'manage_woocommerce' ); } /** * Check write permission for POST/PUT/DELETE endpoints. * * Validates authorization, and the `wp_rest` nonce for a mutating * request that was authenticated through the login cookie. Frontend * callers should send the nonce in the `X-WP-Nonce` header; `_wpnonce` * is accepted as a fallback for form-style requests. An * Application-Password/Basic-Auth (or other non-cookie) REST client is * already authenticated and has no way to ever obtain that nonce, so it * is exempt, exactly like WP core's own write routes * ({@see \AIPT\Utils\RestNonceGuard}). * * @param mixed $_request The REST request object. * @return bool|WP_Error True if authorized, WP_Error with 403 otherwise. */ public function check_permissions_write( $_request = null ) { if ( ! current_user_can( 'manage_woocommerce' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to perform this action.', 'ai-product-tools' ), array( 'status' => 403 ) ); } if ( ! \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { return true; } $nonce = ''; if ( is_object( $_request ) && method_exists( $_request, 'get_header' ) ) { $nonce = (string) $_request->get_header( 'X-WP-Nonce' ); } if ( '' === $nonce && is_object( $_request ) && method_exists( $_request, 'get_param' ) ) { $nonce = (string) $_request->get_param( '_wpnonce' ); } if ( '' === $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie check failed', 'ai-product-tools' ), array( 'status' => 403 ) ); } return true; } /** * Refuse a Product Editor bulk generation. * * Business: every generator registers its `editor-bulk-generate` route * with this callback, beside `bulk-generate` and with the same arguments * and write check, so the free build only refuses there. The Business * build registers the bulk generation on the same paths in its place * (Premium\BulkGenerator\EditorBulkGenerateController), and answers a * site without the plan with this same refusal. * * @param mixed $_request The REST request object. * @return WP_Error */ public function editor_bulk_generation_required( $_request = null ): WP_Error { return PlanDenial::error( 'editorBulkGeneration', PlanDenial::PLAN_BUSINESS, __( 'Business plan adds bulk generation in the Product Editor.', 'ai-product-tools' ) ); } /** * Check whether AI is supported on this WordPress installation. * * All AI-firing endpoints MUST call this at the top of their callback. * Returns `null` when AI is available, or a `WP_Error` (503) when the site * administrator has disabled AI via `WP_AI_SUPPORT` constant or the * `wp_supports_ai` filter. * * @return WP_Error|null Null when AI is available, WP_Error otherwise. */ protected function check_ai_support_gate(): ?WP_Error { $result = \AIPT\Core\Services\AiSupportGate::guard(); return ( $result instanceof WP_Error ) ? $result : null; } /** * Convenience wrapper around RateLimitTrait::checkRateLimit(). * * Resolves the scope from the calling subclass's `RATE_LIMIT_SCOPE` * constant via late static binding, so each generator type gets its own * isolated rate-limit window. Callers may pass an explicit `$scope` to * override the constant (useful in tests). * * @param int $user_id Authenticated user ID. * @param string|null $scope Optional scope override; defaults to static::RATE_LIMIT_SCOPE. * @return array{allowed: bool, remaining: int, reset_in: int} */ protected function check_rate_limit( int $user_id, ?string $scope = null ): array { return $this->checkRateLimit( $user_id, $scope ?? static::RATE_LIMIT_SCOPE ); } /** * Whether a saved site-level additional prompt will be left out of generation. * * The premium option filters read the stored prompt only for an entitled * site. The G9 bridge filter mirrors that gate (false by default, so the * free build reports it too), letting the response say why saved * instructions were not used instead of ignoring them silently. The stored * value is read only to report, never applied here. A run on content * templates never uses the saved prompt, on any plan, so it is not * reported there. * * @param string $generator Content structure generator key of the run. * @param string $option Option name of the saved prompt. * @param string $bridge Bridge filter that allows the saved prompt. * @return bool True when a non-empty saved prompt is not allowed. */ protected static function site_additional_prompt_skipped( string $generator, string $option, string $bridge ): bool { if ( BlueprintIntegration::usesBlueprint( $generator, BlueprintIntegration::jobTrustedFacts() ) ) { return false; } $saved = get_option( $option, '' ); return is_string( $saved ) && '' !== trim( $saved ) && ! apply_filters( $bridge, false ); } /** * Schemas of the three optional arguments every generate route declares * next to `runSize`. None has a sanitize_callback, so WordPress * enforces the schema itself. * * - `clientRequestId`: the key a page keeps for one product's request * until it has an answer. * - `replayOnly`: ask for the answer of an earlier request with that key, * and never start one. * - `runHold`: the run a bulk run armed on the server (its id) and the * product this request generates for. The free build * accepts and ignores it; the Business build reads it through the * `aipt_generate_run_hold_start` filter and `aipt_generate_run_hold_end` * action ({@see claim_generate_request()}, {@see finish_generate_claim()}). * * @return array> */ protected static function claim_args(): array { return array( 'clientRequestId' => array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{8,64}$', 'required' => false, 'description' => 'Key of one generation request. A repeat of the same request is answered from the first one instead of calling the provider again.', ), 'replayOnly' => array( 'type' => 'boolean', 'required' => false, 'description' => 'Only return the answer of an earlier request with this clientRequestId; never generate.', ), 'runHold' => array( 'type' => 'object', 'required' => false, 'additionalProperties' => false, 'properties' => array( 'id' => array( 'type' => 'string', 'pattern' => '^[a-z0-9-]{8,64}$', 'required' => true, ), 'productId' => array( 'type' => 'integer', 'minimum' => 1, 'required' => true, ), ), 'description' => 'The run hold this request belongs to and the product it generates for.', ), ); } /** * The `runHold` of a request that is not a replay, checked again because a * direct caller never went through the route's schema. * * @param WP_REST_Request $request The generate request. * @return array{id:string,productId:int}|null Null when the request carries none, is a `replayOnly` one or carries a malformed one. */ private static function run_hold_of( WP_REST_Request $request ): ?array { if ( filter_var( $request->get_param( 'replayOnly' ), FILTER_VALIDATE_BOOLEAN ) ) { return null; } $run_hold = $request->get_param( 'runHold' ); if ( ! is_array( $run_hold ) || ! isset( $run_hold['id'], $run_hold['productId'] ) || ! is_string( $run_hold['id'] ) || 1 !== preg_match( '/^[a-z0-9-]{8,64}\z/', $run_hold['id'] ) ) { return null; } $product_id = $run_hold['productId']; if ( ! is_int( $product_id ) && ! ( is_string( $product_id ) && ctype_digit( $product_id ) ) ) { return null; } if ( (int) $product_id < 1 ) { return null; } return array( 'id' => $run_hold['id'], 'productId' => (int) $product_id, ); } /** * Claim a generate request that carries a `clientRequestId`, right before * its provider call (after the AI gate, rate limit, option clean-up, mode * enforcement and per-product authorization, so a replay has passed every * check the first request passed). * * The claim key is the user, the generator, the id and a fingerprint of * what was asked (the items and the options, key order and the * `blueprintRun` pin left out): the same id with other options is a new * request. A request without an id never touches the claims table. * * The items are what was asked plus who may be generated for now (the * authorized subset), so a user who lost edit access since the first * request gets the normal path and its denial, never the cached content. * * A request that carries a `runHold` and is not `replayOnly` first asks the * `aipt_generate_run_hold_start` filter (default null, which is all the * free build ever sees; arguments: the null, the `{id, productId}` and the * generator's `RATE_LIMIT_SCOPE`). A `WP_Error` answer is returned as it * is, before any claim is made: no claim row and no provider call. The * filter also runs for a request without a key, so it comes first. * * @param WP_REST_Request $request The generate request. * @param array|\Closure $items The products or image selections the request generates * for, with the authorized subset. A closure is only called for a keyed request, for items that cost work to compute. * @return string|WP_REST_Response|WP_Error A response to return as it is: the first request's own answer replayed * (header `X-AIPT-Replayed`), the 409 while it still runs, or the 404 of a `replayOnly` request with nothing to * replay. Otherwise the claim key this request owns, to hand to {@see finish_generate_claim()} with its final * response, or '' when there is nothing to claim. */ protected function claim_generate_request( WP_REST_Request $request, $items ) { $client_request_id = $request->get_param( 'clientRequestId' ); $replay_only = filter_var( $request->get_param( 'replayOnly' ), FILTER_VALIDATE_BOOLEAN ); $run_hold = self::run_hold_of( $request ); if ( null !== $run_hold ) { $verdict = apply_filters( 'aipt_generate_run_hold_start', null, $run_hold, static::RATE_LIMIT_SCOPE ); if ( $verdict instanceof WP_Error ) { return $verdict; } } if ( ! is_string( $client_request_id ) || '' === $client_request_id ) { return $replay_only ? self::not_replayable() : ''; } if ( $items instanceof \Closure ) { $items = $items(); } $options = $request->get_param( 'options' ); $options = is_array( $options ) ? $options : array(); unset( $options['blueprintRun'] ); $fingerprint = wp_json_encode( self::canonical_for_fingerprint( array( 'items' => $items, 'options' => $options ) ) ); $claim_key = 'aipt_gen_' . static::RATE_LIMIT_SCOPE . '_' . (int) get_current_user_id() . '_' . md5( $client_request_id . '|' . $fingerprint ); $state = $replay_only ? RequestClaimStore::peek( $claim_key, self::GENERATION_CLAIM_WINDOWS ) : RequestClaimStore::claim( $claim_key, self::GENERATION_CLAIM_WINDOWS ); if ( is_array( $state ) ) { return self::replay_response( $state ); } if ( $state instanceof WP_Error ) { return $state; } return $replay_only ? self::not_replayable() : $claim_key; } /** * Keep the final response of a claimed request, so a repeat of it inside * the cache window is answered with this same status and body. Every * outcome after the claim is kept, a failure included: a replay shows * what really happened, and the provider was paid either way. * * A request that carries a `runHold` and is not `replayOnly` also fires the * `aipt_generate_run_hold_end` action (arguments: the `{id, productId}` and the * generator's `RATE_LIMIT_SCOPE`), keyed or not, whatever the response is. * * @param string $claim_key The claim {@see claim_generate_request()} granted; '' keeps nothing. * @param WP_REST_Response|WP_Error $response The response this request is about to return. * @param WP_REST_Request|null $request The generate request, so its `runHold` is seen; every call site passes it. * @return WP_REST_Response|WP_Error The same response. */ protected function finish_generate_claim( string $claim_key, $response, ?WP_REST_Request $request = null ) { $run_hold = null === $request ? null : self::run_hold_of( $request ); if ( null !== $run_hold ) { do_action( 'aipt_generate_run_hold_end', $run_hold, static::RATE_LIMIT_SCOPE ); } if ( '' === $claim_key ) { return $response; } if ( $response instanceof WP_Error ) { $error_data = $response->get_error_data(); $status = is_array( $error_data ) && isset( $error_data['status'] ) ? (int) $error_data['status'] : 500; $body = array( 'code' => $response->get_error_code(), 'message' => $response->get_error_message(), 'data' => $error_data, ); } else { $status = $response->get_status(); $body = $response->get_data(); } $json = wp_json_encode( $body ); if ( false === $json ) { RequestClaimStore::release( $claim_key ); return $response; } RequestClaimStore::complete( $claim_key, array( 'status' => $status, 'body' => $json ) ); return $response; } /** * @param array $payload What {@see finish_generate_claim()} kept. * @return WP_REST_Response */ private static function replay_response( array $payload ): WP_REST_Response { $response = new WP_REST_Response( json_decode( (string) ( $payload['body'] ?? 'null' ) ), (int) ( $payload['status'] ?? 200 ) ); $response->header( 'X-AIPT-Replayed', '1' ); return $response; } /** * @return WP_Error */ private static function not_replayable(): WP_Error { return new WP_Error( 'aipt_request_not_replayable', __( 'There is no earlier answer for this request.', 'ai-product-tools' ), array( 'status' => 404 ) ); } /** * Sort the keys of every associative array, at any depth, so the same * request fingerprints the same whatever order a client wrote it in. A * list keeps its order. * * @param mixed $value Any request value. * @return mixed */ private static function canonical_for_fingerprint( $value ) { if ( ! is_array( $value ) ) { return $value; } $value = array_map( array( self::class, 'canonical_for_fingerprint' ), $value ); if ( array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) { ksort( $value ); } return $value; } /** * Build a uniform success response envelope. * * @param array $data Response payload. * @param string $message Optional human-readable success message. * @return WP_REST_Response HTTP 200 with `{ success: true, data: ..., [message: ...] }`. */ protected function success_response( array $data, string $message = '' ): WP_REST_Response { $response = array( 'success' => true, 'data' => $data, ); if ( ! empty( $message ) ) { $response['message'] = $message; } return new WP_REST_Response( $response, 200 ); } /** * Build a uniform error WP_Error. * * @param string $code Machine-readable error code. * @param string $message Human-readable error message. * @param int $status HTTP status code (default 400). * @return WP_Error */ protected function error_response( string $code, string $message, int $status = 400 ): WP_Error { return new WP_Error( $code, $message, array( 'status' => $status ) ); } /** * Enforce the tri-state generationMode contract server-side. * * Sanitizes the incoming mode (an unknown or non-string value becomes * 'client_preview') and downgrades 'server_review' to 'client_preview' * when the content review feature is not enabled (a plan without the * review queue) or the build offers no review stager to queue the results * with. Sanitizing twice is harmless: Description already sanitized its * options, so for it only the downgrade acts. * * @param array $options Request options. * @param ReviewQueueStager|null $review_stager The review stager the build offers, or null. * @return array Options with enforced generationMode. */ protected function enforce_generation_mode( array $options, ?ReviewQueueStager $review_stager ): array { $mode = ( isset( $options['generationMode'] ) && is_string( $options['generationMode'] ) ) ? $options['generationMode'] : ''; $options['generationMode'] = in_array( $mode, array( 'immediate', 'client_preview', 'server_review' ), true ) ? $mode : 'client_preview'; if ( 'server_review' === $options['generationMode'] && ( ! apply_filters( 'aipt_content_review_enabled', false ) || null === $review_stager ) ) { $options['generationMode'] = 'client_preview'; $options['downgraded_mode'] = true; } return $options; } /** * Format an AI provider API error message with the provider name prefix. * * Delegates to `AIPT\Core\ErrorHandler` for consistent error presentation * across all controllers. * * @param string $provider Provider name (e.g. 'OpenAI', 'Gemini'). * @param string $error_message Raw error message from the provider client. * @return string Formatted error string ready for display. */ protected function format_api_error_message( string $provider, string $error_message ): string { return \AIPT\Core\ErrorHandler::format_api_error_message( $provider, $error_message ); } }