Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,178 @@
<?php
/**
* Base REST API controller.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\AI_Visibility\Api
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\AI_Visibility\Api;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Controller;
use RankMath\Rest\Rest_Helper;
use RankMath\Admin\Admin_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Abstract base.
*/
abstract class Base_Controller extends WP_REST_Controller {
/**
* Constructor.
*/
public function __construct() {
$this->namespace = Rest_Helper::BASE . '/ai-visibility';
}
/**
* Permission check — user must have `manage_options`.
*
* @param WP_REST_Request $request Request.
*
* @return true|WP_Error
*/
public function check_admin_permission( $request ) {
return Rest_Helper::can_manage_options();
}
/**
* Build a success response envelope.
*
* @param mixed $data Payload to return under `data`.
* @param string $message Optional human-readable status message.
*
* @return WP_REST_Response
*/
protected function success( $data, $message = '' ) {
$response = [
'success' => true,
'data' => $data,
];
if ( ! empty( $message ) ) {
$response['message'] = $message;
}
return rest_ensure_response( $response );
}
/**
* Build an error response.
*
* @param string $code Error code slug.
* @param string $message Human-readable message.
* @param int $status HTTP status code.
*
* @return WP_Error
*/
protected function error( $code, $message, $status = 400 ) {
return new WP_Error( $code, $message, [ 'status' => $status ] );
}
/**
* Send a request to the AI Visibility backend.
*
* Centralises all `wp_remote_*` calls so every controller method only has
* to supply the HTTP verb, the path, and an optional payload.
*
* Return value
* ------------
* Returns the decoded JSON array on success. Returns a `WP_Error` on:
* - Missing / invalid registration data (not connected to Rank Math).
* - `wp_remote_request()` transport error (timeout, DNS, TLS, …).
* - Non-2xx HTTP status from the backend (code mapped to a slug).
* - Response body that cannot be decoded as JSON.
*
* @param string $method HTTP verb — 'GET', 'POST', 'PATCH', 'PUT', 'DELETE'.
* @param string $path Backend path, e.g. '/api/v1/brands'.
* @param array $body Request payload (JSON-encoded automatically).
*
* @return array|WP_Error Decoded response array, or WP_Error on failure.
*/
protected function remote_request( $method, $path, $body = [] ) {
$data = Admin_Helper::get_registration_data();
if ( ! $data || empty( $data['api_key'] ) ) {
return new WP_Error(
'aiv_unauthorized',
__( 'Rank Math account not connected. Please connect your account and try again.', 'seo-by-rank-math' ),
[ 'status' => 401 ]
);
}
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'x-username' => $data['username'] ?? '',
'x-site-url' => $data['site_url'] ?? '',
'x-cai-api-key' => $data['api_key'],
];
$args = [
'method' => strtoupper( $method ),
'timeout' => 30,
'headers' => $headers,
];
if ( ! empty( $body ) ) {
$args['body'] = wp_json_encode( $body );
}
$url = RANK_MATH_AIV_URL . '/' . ltrim( $path, '/' );
$response = wp_remote_request( $url, $args );
if ( is_wp_error( $response ) ) {
return new WP_Error(
'aiv_request_failed',
$response->get_error_message(),
[ 'status' => 502 ]
);
}
$http_code = (int) wp_remote_retrieve_response_code( $response );
$raw_body = wp_remote_retrieve_body( $response );
$decoded = json_decode( $raw_body, true );
$backend_msg = isset( $decoded['message'] ) ? $decoded['message'] : '';
if ( $http_code < 200 || $http_code >= 300 ) {
$error_map = [
400 => 'aiv_bad_request',
401 => 'aiv_unauthorized',
402 => 'aiv_insufficient_credits',
403 => 'aiv_plan_limit',
404 => 'aiv_not_found',
409 => 'aiv_conflict',
422 => 'aiv_invalid_credentials',
];
if ( $http_code >= 500 ) {
$code = 'aiv_server_error';
} else {
$code = isset( $error_map[ $http_code ] ) ? $error_map[ $http_code ] : 'aiv_request_failed';
}
$message = ! empty( $backend_msg )
? $backend_msg
/* translators: %d: HTTP status code returned by the backend. */
: sprintf( __( 'AI Visibility API returned an unexpected status: %d', 'seo-by-rank-math' ), $http_code );
return new WP_Error( $code, $message, [ 'status' => $http_code ] );
}
if ( null === $decoded ) {
return new WP_Error(
'aiv_bad_response',
__( 'AI Visibility API returned an invalid response.', 'seo-by-rank-math' ),
[ 'status' => 502 ]
);
}
return $decoded;
}
}
@@ -0,0 +1,903 @@
<?php
/**
* Brands REST API controller.
*
* Cache-backed proxy for the AI Visibility backend with SWR caching.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\AI_Visibility\Api
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\AI_Visibility\Api;
use WP_REST_Server;
use WP_REST_Request;
use RankMath\Helper;
use RankMath\AI_Visibility\Cache;
use RankMath\AI_Visibility\Platforms;
defined( 'ABSPATH' ) || exit;
/**
* Brands_Controller class.
*/
class Brands_Controller extends Base_Controller {
/**
* Regex segment that matches a brand UUID.
*/
const BRAND_ID_PATTERN = '(?P<id>[a-zA-Z0-9\-]+)';
/**
* Allowed values for the `language` request param.
*
* @param bool $allow_empty Whether '' (no value) is a valid choice.
*
* @return array
*/
public static function get_language_choices( bool $allow_empty = true ): array {
$names = wp_list_pluck( Helper::get_content_ai_languages(), 'name' );
return $allow_empty ? array_merge( [ '' ], $names ) : $names;
}
/**
* Allowed values for the `interval` request param.
*
* @return array
*/
public static function get_interval_choices(): array {
return [ 'daily', 'weekly', 'monthly' ];
}
/**
* Cadences allowed for a given AI Visibility plan.
*
* @param string|null $plan Plan slug. Defaults to the current account's plan.
*
* @return array
*/
public static function get_allowed_intervals( ?string $plan = null ): array {
$plan = $plan ?? Helper::get_content_ai_plan();
return 'expert' === $plan
? [ 'daily', 'weekly', 'monthly' ]
: [ 'weekly', 'monthly' ];
}
/**
* Reject an `interval` value the caller's plan does not allow.
*
* @param string $interval Requested cadence value.
*
* @return \WP_Error|true
*/
private function check_interval_allowed( string $interval ) {
$allowed = self::get_allowed_intervals();
if ( in_array( $interval, $allowed, true ) ) {
return true;
}
return $this->error(
'aiv_frequency_not_allowed',
sprintf(
/* translators: %s: comma-separated list of allowed cadences. */
__( 'The selected analysis frequency is not available on your plan. Allowed frequencies: %s. Upgrade your plan to unlock more frequency options.', 'seo-by-rank-math' ),
implode( ', ', $allowed )
),
403
);
}
/**
* Register routes.
*/
public function register_routes() {
$id_arg = [
'id' => [
'description' => esc_html__( 'Brand UUID.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
];
// GET /overview — dashboard payload: summary + per-brand rollup rows.
register_rest_route(
$this->namespace,
'/overview',
[
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_overview' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => [
'refresh' => [
'description' => esc_html__( 'Force a refresh from the AI Visibility API.', 'seo-by-rank-math' ),
'type' => 'boolean',
'required' => false,
'default' => false,
'sanitize_callback' => 'rest_sanitize_boolean',
],
'search' => [
'description' => esc_html__( 'Filter brands by name or URL.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => false,
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
],
],
]
);
// GET /brands/{id} — single brand identity (incl. description).
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN,
[
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_brand' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => $id_arg,
]
);
// POST /brands — create a new brand.
register_rest_route(
$this->namespace,
'/brands',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [ $this, 'create_brand' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => [
'name' => [
'description' => esc_html__( 'Brand name.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
],
'url' => [
'description' => esc_html__( 'Brand website URL or domain.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'esc_url_raw',
],
'description' => [
'description' => esc_html__( 'Short description of the brand or product.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_textarea_field',
],
'locale' => [
'description' => esc_html__( 'ISO 3166-1 alpha-2 country code (e.g. "US", "HU").', 'seo-by-rank-math' ),
'type' => 'string',
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
],
'language' => [
'description' => esc_html__( 'Output language to use when analyzing/generating content for this brand. Independent of `locale` (target country). Required; immutable after creation.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'enum' => self::get_language_choices( false ),
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
'interval' => [
'description' => esc_html__( 'Analysis refresh cadence. Omitted → backend applies the account plan\'s default.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => false,
'enum' => self::get_interval_choices(),
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
'platforms' => Platforms::rest_arg( true ),
],
]
);
// PUT/PATCH /brands/{id} — update brand fields and/or status.
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN,
[
'methods' => WP_REST_Server::EDITABLE,
'callback' => [ $this, 'update_brand' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => array_merge(
$id_arg,
[
'name' => [
'type' => 'string',
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
],
'url' => [
'type' => 'string',
'required' => false,
'sanitize_callback' => 'esc_url_raw',
],
'description' => [
'type' => 'string',
'required' => false,
'sanitize_callback' => 'sanitize_textarea_field',
],
'locale' => [
'type' => 'string',
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
],
'language' => [
'type' => 'string',
'required' => false,
'enum' => self::get_language_choices(),
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
'status' => [
'type' => 'string',
'required' => false,
'enum' => [ 'active', 'inactive' ],
'sanitize_callback' => 'sanitize_text_field',
],
'interval' => [
'type' => 'string',
'required' => false,
'enum' => self::get_interval_choices(),
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
'platforms' => Platforms::rest_arg( false ),
]
),
]
);
// GET /brands/{id}/insights — full latest-analysis payload (competitors + transcripts).
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN . '/insights',
[
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_insights' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => $id_arg,
]
);
// GET /brands/{id}/queries — list queries for a brand.
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN . '/queries',
[
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_queries' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => $id_arg,
]
);
// PUT /brands/{id}/queries/{qid} — enable/disable a query.
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN . '/queries/(?P<qid>[a-zA-Z0-9\-]+)',
[
'methods' => WP_REST_Server::EDITABLE,
'callback' => [ $this, 'update_query' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => array_merge(
$id_arg,
[
'qid' => [
'description' => esc_html__( 'Query UUID.', 'seo-by-rank-math' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'rest_validate_request_arg',
],
'enabled' => [
'description' => esc_html__( 'Whether the query is enabled for analysis.', 'seo-by-rank-math' ),
'type' => 'boolean',
'required' => true,
],
]
),
]
);
// POST /brands/{id}/generate-queries — regenerate baseline queries.
register_rest_route(
$this->namespace,
'/brands/' . self::BRAND_ID_PATTERN . '/generate-queries',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [ $this, 'generate_queries' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
'args' => $id_arg,
]
);
}
/**
* Dashboard payload (summary + rollup rows) — cache-first with SWR.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function get_overview( $request ) {
$force = (bool) $request->get_param( 'refresh' );
$search = (string) $request->get_param( 'search' );
$cached = Cache::get_dashboard();
if ( null !== $cached && ! $force ) {
if ( Cache::is_dashboard_fresh() ) {
return $this->overview_response( $cached, false, $search );
}
return $this->overview_response( $cached, true, $search );
}
$result = $this->remote_request( 'GET', '/api/v1/overview' );
if ( is_wp_error( $result ) ) {
if ( null !== $cached ) {
return $this->overview_response( $cached, true, $search );
}
return $result;
}
$summary = isset( $result['summary'] ) ? (array) $result['summary'] : [];
$brands = [];
$raw_brands = isset( $result['brands']['data'] ) ? (array) $result['brands']['data'] : [];
foreach ( $raw_brands as $brand ) {
$brands[] = $this->map_overview_brand( $brand );
}
Cache::set_dashboard( $summary, $brands );
return $this->overview_response( Cache::get_dashboard(), false, $search );
}
/**
* Map an /overview brand item (API shape) to the UI row shape.
*
* @param array $brand Raw brand item.
*
* @return array
*/
private function map_overview_brand( $brand ) {
return [
'id' => $brand['uuid'] ?? '',
'name' => $brand['name'] ?? '',
'url' => $brand['url'] ?? '',
'locale' => $brand['country_code'] ?? null,
'language' => $brand['language'] ?? null,
'status' => ! empty( $brand['active'] ) ? 'active' : 'inactive',
'interval' => $brand['analysis_frequency'] ?? null,
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
'score' => $brand['ai_visibility_score'] ?? null,
'rank' => $brand['rank'] ?? null,
'avg_sentiment' => $brand['avg_sentiment'] ?? null,
'mentions' => $brand['mentions'] ?? null,
'citations' => $brand['citations'] ?? null,
'last_analyzed' => $brand['last_analyzed_at'] ?? null,
'created_at' => $brand['created_at'] ?? null,
'analysis_status' => $brand['last_analysis_status'] ?? null,
'next_scheduled' => $brand['next_scheduled_at'] ?? null,
];
}
/**
* Build the dashboard response envelope, applying the optional search filter.
*
* @param array $data Cached dashboard payload.
* @param bool $is_stale Whether the payload is past its TTL.
* @param string $search Optional name/URL filter.
*
* @return \WP_REST_Response
*/
private function overview_response( $data, $is_stale, $search = '' ) {
$brands = isset( $data['brands'] ) ? $data['brands'] : [];
if ( '' !== $search ) {
$brands = array_values(
array_filter(
$brands,
function ( $row ) use ( $search ) {
return false !== stripos( $row['name'] ?? '', $search )
|| false !== stripos( $row['url'] ?? '', $search );
}
)
);
}
return $this->success(
[
'summary' => isset( $data['summary'] ) ? $data['summary'] : [],
'brands' => $brands,
'is_stale' => (bool) $is_stale,
]
);
}
/**
* Get single brand identity (incl. description) — cache-first.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function get_brand( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$cached = Cache::get_brand( $uuid );
if ( false !== $cached ) {
return $this->success( [ 'brand' => $cached ] );
}
// /overview omits `description`; fetch full identity once and cache it.
$result = $this->remote_request( 'GET', '/api/v1/brands/' . $uuid );
if ( is_wp_error( $result ) ) {
return $result;
}
$brand = $this->map_brand( isset( $result['data'] ) ? $result['data'] : $result );
Cache::set_brand( $uuid, $brand );
return $this->success( [ 'brand' => $brand ] );
}
/**
* Create a brand — the 201 response primes the dashboard row, identity
* transient, and queries cache (no follow-up reads).
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function create_brand( $request ) {
$locale = $request->get_param( 'locale' );
$language = $request->get_param( 'language' );
$interval = $request->get_param( 'interval' );
$platforms = $request->get_param( 'platforms' );
// Re-validate: the create-brand ability bypasses the REST arg constraints.
$valid = Platforms::validate( $platforms );
if ( is_wp_error( $valid ) ) {
return $valid;
}
$platforms = Platforms::sanitize( $platforms );
if ( ! $language ) {
return $this->error(
'aiv_bad_request',
__( 'Please select a language for this brand.', 'seo-by-rank-math' ),
400
);
}
$body = [
'name' => sanitize_text_field( (string) $request->get_param( 'name' ) ),
'url' => esc_url_raw( (string) $request->get_param( 'url' ) ),
'description' => sanitize_textarea_field( (string) $request->get_param( 'description' ) ),
'language' => (string) $language,
'platforms' => $platforms,
];
// Omit rather than send '' — the backend rejects an explicit empty string.
if ( $locale ) {
$body['country_code'] = strtoupper( (string) $locale );
}
if ( $interval ) {
$allowed = $this->check_interval_allowed( $interval );
if ( is_wp_error( $allowed ) ) {
return $allowed;
}
$body['analysis_frequency'] = (string) $interval;
}
$result = $this->remote_request( 'POST', '/api/v1/brands', $body );
if ( is_wp_error( $result ) ) {
return $result;
}
$brand = $this->map_brand( $result );
$uuid = $brand['id'];
// Row starts as `pending` — creation atomically seeds the first analysis.
Cache::append_brand_row(
array_merge(
$brand,
[
'score' => null,
'rank' => null,
'avg_sentiment' => null,
'mentions' => null,
'citations' => null,
'analysis_status' => 'pending',
'next_scheduled' => null,
]
)
);
Cache::set_brand( $uuid, $brand );
if ( ! empty( $result['queries'] ) ) {
Cache::set_queries( $uuid, $this->map_queries( $result['queries'] ) );
}
rank_math()->tracking->track_ability_executed(
'AI Visibility Brand Created',
[
'locale' => $brand['locale'] ?? null,
'language' => $brand['language'] ?? null,
'interval' => $brand['interval'] ?? null,
'platforms' => $platforms,
]
);
return $this->success( [ 'brand' => $brand ] );
}
/**
* Update brand fields/status — patches the cached row in place
* (analysis and queries caches are intentionally kept).
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function update_brand( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$body = [];
$fields = [
'name' => 'sanitize_text_field',
'url' => 'esc_url_raw',
'description' => 'sanitize_textarea_field',
'status' => 'sanitize_text_field',
];
foreach ( $fields as $field => $sanitizer ) {
$value = $request->get_param( $field );
if ( null !== $value ) {
$body[ $field ] = call_user_func( $sanitizer, $value );
}
}
$locale = $request->get_param( 'locale' );
if ( null !== $locale ) {
$body['country_code'] = strtoupper( sanitize_text_field( $locale ) );
}
// Omit blank values — the backend rejects an explicit empty string.
$language = $request->get_param( 'language' );
if ( $language ) {
$body['language'] = sanitize_text_field( $language );
}
$interval = $request->get_param( 'interval' );
if ( null !== $interval ) {
$allowed = $this->check_interval_allowed( $interval );
if ( is_wp_error( $allowed ) ) {
return $allowed;
}
$body['analysis_frequency'] = sanitize_text_field( $interval );
}
$platforms = $request->get_param( 'platforms' );
if ( null !== $platforms ) {
$valid = Platforms::validate( $platforms );
if ( is_wp_error( $valid ) ) {
return $valid;
}
$body['platforms'] = Platforms::sanitize( $platforms );
}
if ( empty( $body ) ) {
return $this->error( 'aiv_bad_request', __( 'No fields to update.', 'seo-by-rank-math' ), 400 );
}
$result = $this->remote_request( 'PATCH', '/api/v1/brands/' . $uuid, $body );
if ( is_wp_error( $result ) ) {
return $result;
}
$brand = $this->map_brand( isset( $result['data'] ) ? $result['data'] : $result );
Cache::patch_brand_row(
$uuid,
[
'name' => $brand['name'],
'url' => $brand['url'],
'description' => $brand['description'],
'locale' => $brand['locale'],
'language' => $brand['language'],
'status' => $brand['status'],
'interval' => $brand['interval'],
'platforms' => $brand['platforms'],
]
);
Cache::set_brand( $uuid, $brand );
$status_changed = isset( $body['status'] );
rank_math()->tracking->track_event(
'AI Visibility Brand Updated',
[
'fields_changed' => array_keys( $body ),
'status_changed' => $status_changed,
'new_status' => $status_changed ? $brand['status'] : null,
'platforms' => $brand['platforms'],
'language' => $brand['language'] ?? null,
]
);
return $this->success( [ 'brand' => $brand ] );
}
/**
* Map an upstream brand object to the UI shape.
*
* @param array $brand Raw brand object.
*
* @return array
*/
private function map_brand( $brand ) {
return [
'id' => $brand['uuid'] ?? '',
'name' => $brand['name'] ?? '',
'url' => $brand['url'] ?? '',
'description' => $brand['description'] ?? '',
'locale' => $brand['country_code'] ?? null,
'language' => $brand['language'] ?? null,
'status' => $brand['status'] ?? 'active',
'interval' => $brand['analysis_frequency'] ?? null,
'last_analyzed' => $brand['last_analyzed_at'] ?? null,
'created_at' => $brand['created_at'] ?? null,
'platforms' => Platforms::sanitize( $brand['platforms'] ?? [] ),
];
}
/**
* Full latest-analysis payload — cache-first; upstream only on miss or
* stale flag. Upstream 404 (no completed analysis) → `{ pending: true }`.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function get_insights( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$cached = Cache::get_analysis( $uuid );
if ( false !== $cached && ! Cache::is_brand_stale( $uuid ) ) {
return $this->success( [ 'insights' => $cached ] );
}
$result = $this->remote_request( 'GET', '/api/v1/brands/' . $uuid . '/analyses/results' );
if ( is_wp_error( $result ) ) {
// No completed analysis yet — pending state, never cached.
if ( 'aiv_not_found' === $result->get_error_code() ) {
return $this->success( [ 'pending' => true ] );
}
// Serve the superseded payload on upstream failure.
if ( false !== $cached ) {
return $this->success( [ 'insights' => $cached ] );
}
return $result;
}
$insights = $this->map_insights( $result );
Cache::set_analysis( $uuid, $insights );
rank_math()->tracking->track_event(
'AI Visibility Insights Fetched',
[
'score' => $insights['score'],
'rank' => $insights['rank'],
'avg_sentiment' => $insights['avg_sentiment'],
'mentions' => $insights['mentions'],
'citations' => $insights['citations'],
'has_competitors' => ! empty( $insights['competitors'] ),
'query_result_count' => count( $insights['query_results'] ),
]
);
// Keep the dashboard row's summary in sync (poller success path).
$finished_ats = array_filter( array_column( $insights['analyses'], 'finished_at' ) );
// Resolve status here rather than relying on /overview, which can lag.
$analysis_statuses = array_column( $insights['analyses'], 'status' );
$analysis_status = in_array( 'error', $analysis_statuses, true ) ? 'error' : 'success';
Cache::patch_brand_row(
$uuid,
[
'score' => $insights['score'],
'rank' => $insights['rank'],
'avg_sentiment' => $insights['avg_sentiment'],
'mentions' => $insights['mentions'],
'citations' => $insights['citations'],
'last_analyzed' => $finished_ats ? max( $finished_ats ) : null,
'analysis_status' => $analysis_status,
]
);
return $this->success( [ 'insights' => $insights ] );
}
/**
* Map the upstream analyses/results payload to the UI shape.
*
* @param array $result Raw payload.
*
* @return array
*/
private function map_insights( $result ) {
$analyses = isset( $result['analyses'] ) ? (array) $result['analyses'] : [];
return [
'score' => $result['ai_visibility_score'] ?? null,
'rank' => $result['rank'] ?? null,
'avg_sentiment' => $result['avg_sentiment'] ?? null,
'mentions' => $result['mentions'] ?? null,
'citations' => $result['citations'] ?? null,
'analyses' => array_map(
function ( $analysis ) {
return [
'id' => $analysis['uuid'] ?? null,
'platform' => $analysis['platform'] ?? null,
'status' => isset( $analysis['status'] ) && 'success' === $analysis['status'] ? 'done' : ( $analysis['status'] ?? null ),
'started_at' => $analysis['started_at'] ?? null,
'finished_at' => $analysis['finished_at'] ?? null,
'duration_seconds' => $analysis['duration_seconds'] ?? null,
];
},
$analyses
),
'competitors' => array_map(
function ( $competitor ) {
return [
'name' => $competitor['name'] ?? '',
'url' => $competitor['url'] ?? null,
'mentions' => $competitor['mentions'] ?? null,
'avg_sentiment' => $competitor['avg_sentiment'] ?? null,
];
},
isset( $result['competitors'] ) ? (array) $result['competitors'] : []
),
'query_results' => array_map(
function ( $query_result ) {
return [
'query_id' => $query_result['query_uuid'] ?? null,
'query_text' => $query_result['query_text'] ?? '',
'platform' => $query_result['platform'] ?? null,
'found' => ! empty( $query_result['found'] ),
'rank' => $query_result['rank_among_competitors'] ?? null,
'sentiment' => $query_result['sentiment_score'] ?? null,
'citations' => $query_result['citations_count'] ?? null,
'response' => $query_result['model_response'] ?? '',
'extraction_data' => $query_result['extraction_data_raw'] ?? '',
];
},
isset( $result['query_results'] ) ? (array) $result['query_results'] : []
),
];
}
/**
* List queries for a brand — cache-first (24h TTL).
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function get_queries( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$cached = Cache::get_queries( $uuid );
if ( null !== $cached ) {
return $this->success( [ 'queries' => $cached['queries'] ] );
}
$result = $this->remote_request( 'GET', '/api/v1/brands/' . $uuid . '/queries?enabled=true' );
if ( is_wp_error( $result ) ) {
return $result;
}
$queries = $this->map_queries( isset( $result['queries'] ) ? $result['queries'] : [] );
Cache::set_queries( $uuid, $queries );
return $this->success( [ 'queries' => $queries ] );
}
/**
* Enable or disable a query.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function update_query( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$qid = sanitize_text_field( $request->get_param( 'qid' ) );
$enabled = (bool) $request->get_param( 'enabled' );
$result = $this->remote_request( 'PATCH', '/api/v1/queries/' . $qid, [ 'enabled' => $enabled ] );
if ( is_wp_error( $result ) ) {
return $result;
}
Cache::patch_query( $uuid, $qid, [ 'enabled' => $enabled ] );
rank_math()->tracking->track_event(
'AI Visibility Query Toggled',
[ 'enabled' => $enabled ]
);
return $this->success( [ 'updated' => true ] );
}
/**
* Regenerate baseline queries — response replaces the cached list.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function generate_queries( $request ) {
$uuid = sanitize_text_field( $request->get_param( 'id' ) );
$result = $this->remote_request( 'POST', '/api/v1/brands/' . $uuid . '/generate-queries' );
if ( is_wp_error( $result ) ) {
return $result;
}
$queries = $this->map_queries( isset( $result['queries'] ) ? $result['queries'] : [] );
Cache::set_queries( $uuid, $queries );
rank_math()->tracking->track_event(
'AI Visibility Queries Regenerated',
[ 'query_count' => count( $queries ) ]
);
return $this->success( [ 'queries' => $queries ] );
}
/**
* Map upstream query objects to the UI shape.
*
* @param array $queries Raw query objects.
*
* @return array
*/
private function map_queries( $queries ) {
return array_map(
function ( $query ) {
return [
'id' => $query['uuid'] ?? '',
'text' => $query['text'] ?? '',
'enabled' => $query['enabled'] ?? true,
'is_baseline' => ! empty( $query['is_baseline'] ),
'created_at' => $query['created_at'] ?? null,
'updated_at' => $query['updated_at'] ?? null,
];
},
(array) $queries
);
}
}
@@ -0,0 +1,119 @@
<?php
/**
* Content AI checkout REST API controller.
*
* @since 1.0.273
* @package RankMath
* @subpackage RankMath\AI_Visibility\Api
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\AI_Visibility\Api;
use WP_Error;
use WP_REST_Server;
use WP_REST_Request;
use RankMath\Traits\Hooker;
use RankMath\Admin\Admin_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Checkout_Controller class.
*/
class Checkout_Controller extends Base_Controller {
use Hooker;
/**
* Register routes.
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/checkout-url',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [ $this, 'get_checkout_url' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
]
);
}
/**
* POST /checkout-url — build an authenticated Content AI checkout iframe URL.
*
* Fetches a fresh single-use token (15-min, consumed on first iframe load)
* and returns the full iframe `src`. A new URL must be requested per
* iframe session — never reload the iframe with the same URL.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|WP_Error
*/
public function get_checkout_url( $request ) {
$token = $this->get_checkout_token();
if ( is_wp_error( $token ) ) {
return $token;
}
$url = add_query_arg(
[
'site_checkout' => 1,
'rm_token' => $token,
],
RANK_MATH_SITE_URL . '/site-checkout-cai',
);
return $this->success( [ 'url' => $url ] );
}
/**
* Fetch a single-use checkout token from the Rank Math account API.
*
* @return string|WP_Error Token string, or WP_Error on failure.
*/
private function get_checkout_token() {
$registered = Admin_Helper::get_registration_data();
if ( empty( $registered['api_key'] ) || empty( $registered['username'] ) ) {
return new WP_Error(
'aiv_unauthorized',
__( 'Rank Math account not connected. Please connect your account and try again.', 'seo-by-rank-math' ),
[ 'status' => 401 ]
);
}
$response = wp_remote_post(
RANK_MATH_SITE_URL . '/wp-json/rankmath/v1/checkoutToken',
[
'timeout' => 60,
'headers' => [ 'Content-Type' => 'application/json' ],
'body' => wp_json_encode(
[
'username' => $registered['username'],
'api_key' => $registered['api_key'],
]
),
]
);
if ( is_wp_error( $response ) ) {
return new WP_Error( 'aiv_request_failed', $response->get_error_message(), [ 'status' => 502 ] );
}
$http_code = (int) wp_remote_retrieve_response_code( $response );
$decoded = json_decode( wp_remote_retrieve_body( $response ), true );
if ( $http_code < 200 || $http_code >= 300 || empty( $decoded['token'] ) ) {
$message = ! empty( $decoded['message'] )
? $decoded['message']
: __( 'Could not start the checkout session. Please try again.', 'seo-by-rank-math' );
return new WP_Error( 'aiv_checkout_token_failed', $message, [ 'status' => $http_code ? $http_code : 502 ] );
}
return $decoded['token'];
}
}
@@ -0,0 +1,132 @@
<?php
/**
* Trial activation REST API controller.
*
* @since 1.0.281
* @package RankMath
* @subpackage RankMath\AI_Visibility\Api
* @author Rank Math <support@rankmath.com>
*/
namespace RankMath\AI_Visibility\Api;
use WP_Error;
use WP_REST_Server;
use WP_REST_Request;
use RankMath\Helper;
use RankMath\Traits\Hooker;
use RankMath\Admin\Admin_Helper;
defined( 'ABSPATH' ) || exit;
/**
* Trial_Controller class.
*/
class Trial_Controller extends Base_Controller {
use Hooker;
/**
* Plan slug requested when activating the AI Visibility free trial.
*/
const TRIAL_PLAN = 'content-ai-creator-trial';
/**
* Register routes.
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/trial/activate',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [ $this, 'activate_trial' ],
'permission_callback' => [ $this, 'check_admin_permission' ],
]
);
}
/**
* Activate 15-day AI Visibility free trial.
*
* @param WP_REST_Request $request Request.
*
* @return \WP_REST_Response|\WP_Error
*/
public function activate_trial( $request ) {
unset( $request );
$result = $this->request_trial_activation();
if ( is_wp_error( $result ) ) {
return $result;
}
// Refresh the cached Content AI plan & credits so the UI unlocks on reload.
Helper::get_content_ai_credits( true );
rank_math()->tracking->track_event(
'AI Visibility Trial Activated',
[ 'plan' => Helper::get_content_ai_plan() ]
);
return $this->success(
$result,
__( 'Your AI Visibility trial has been activated.', 'seo-by-rank-math' )
);
}
/**
* Request trial activation from the Rank Math account API.
*
* Hits the `planUpgrade` endpoint with the connected account's
* credentials. The base URL defaults to the test host and can be pointed
* at production via the `rank_math/ai_visibility/plan_upgrade_url` filter.
*
* @return array|WP_Error Decoded response array, or WP_Error on failure.
*/
private function request_trial_activation() {
$registered = Admin_Helper::get_registration_data();
if ( empty( $registered['api_key'] ) || empty( $registered['username'] ) ) {
return new WP_Error(
'aiv_unauthorized',
__( 'Rank Math account not connected. Please connect your account and try again.', 'seo-by-rank-math' ),
[ 'status' => 401 ]
);
}
$response = wp_remote_post(
RANK_MATH_SITE_URL . '/wp-json/rankmath/v1/planUpgrade',
[
'timeout' => 60,
'body' => [
'api_key' => $registered['api_key'],
'username' => $registered['username'],
'plan' => self::TRIAL_PLAN,
],
]
);
if ( is_wp_error( $response ) ) {
return new WP_Error(
'aiv_request_failed',
$response->get_error_message(),
[ 'status' => 502 ]
);
}
$http_code = (int) wp_remote_retrieve_response_code( $response );
$decoded = json_decode( wp_remote_retrieve_body( $response ), true );
if ( $http_code < 200 || $http_code >= 300 ) {
$message = ! empty( $decoded['message'] )
? $decoded['message']
: __( 'We could not activate your trial. Please try again.', 'seo-by-rank-math' );
return new WP_Error( 'aiv_trial_activation_failed', $message, [ 'status' => $http_code ] );
}
return is_array( $decoded ) ? $decoded : [ 'activated' => true ];
}
}