`, and deletes each batch once accepted.
* A batch that fails is sent again byte for byte, so aeoora Cloud, which
* reads a webhook body once by its hash, never counts it twice.
*
* Connected with a tracking code: aeoora Cloud's tracking snippet
* (`{api}/t.js` with `data-t`) is added to the front end.
*
* Disconnecting deletes the secret, the tracking code, the queue table and the
* cron job.
*
* @package aeoora
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* aeoora Cloud connection.
*/
class Aeoora_Cloud {
const DEFAULT_API = 'https://api.aeoora.com';
const APP_URL = 'https://app.aeoora.com';
const SIGNUP_URL = 'https://app.aeoora.com/sign-up';
const SECRET_OPTION = 'aeoora_cloud_secret';
const STATE_OPTION = 'aeoora_cloud_state';
const LOCK_OPTION = 'aeoora_cloud_lock';
const TABLE = 'aeoora_cloud_queue';
const CRON_HOOK = 'aeoora_cloud_send';
const SCHEDULE = 'aeoora_cloud_10min';
const SNIPPET = 'aeoora-cloud';
/** Lines per request (aeoora Cloud reads up to 20,000). */
const BATCH = 500;
/** Requests per cron run: 2,500 crawler visits every ten minutes. */
const MAX_BATCHES = 5;
/** Queue rows kept at most while aeoora Cloud can't be reached. */
const MAX_QUEUE = 50000;
/** aeoora Cloud ignores visits older than 7 days; older rows are dropped here first. */
const MAX_AGE_DAYS = 6;
/**
* Hook in. Cheap when not connected: one cron hook and one schedule.
*/
public static function init() {
add_filter( 'cron_schedules', array( __CLASS__, 'schedules' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval -- ten minutes, used only while connected.
add_action( self::CRON_HOOK, array( __CLASS__, 'cron' ) );
if ( self::has_secret() ) {
add_action( 'aeoora_crawler_hit', array( __CLASS__, 'queue' ), 10, 2 );
add_action( 'init', array( __CLASS__, 'ensure_cron' ) );
}
if ( '' !== self::tracking_code() ) {
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'snippet' ) );
}
// The browser coming back from aeoora Cloud's connect screen.
add_action( 'admin_init', array( __CLASS__, 'handle_return' ) );
}
/* ------------------------------------------------- one-click connect */
const TOKEN_OPTION = 'aeoora_cloud_site_token';
const BRAND_OPTION = 'aeoora_cloud_brand';
const CONNECT_PREFIX = 'aeoora_cloud_connect_';
const NOTICE_PREFIX = 'aeoora_cloud_notice_';
/** Option: the plan's AI credits as last reported. */
const AI_CREDITS_OPTION = 'aeoora_cloud_ai_credits';
/**
* The aeoora Cloud app origin: https://app.aeoora.com, or
* `define( 'AEOORA_CLOUD_APP', 'https://app.example.com' );` in wp-config.php.
*
* @return string Origin without a trailing slash.
*/
public static function app_url() {
$app = defined( 'AEOORA_CLOUD_APP' ) && '' !== trim( (string) AEOORA_CLOUD_APP ) ? self::parse_api( (string) AEOORA_CLOUD_APP ) : '';
return '' === $app ? self::APP_URL : $app;
}
/**
* base64url without padding.
*
* @param string $bytes Bytes.
* @return string
*/
private static function b64url( $bytes ) {
return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions -- PKCE code challenge, not obfuscation.
}
/**
* Start the one-click connection: ask aeoora Cloud whether it offers it,
* then return the address of its connect screen. The browser goes there,
* the person signs in and picks a brand, and aeoora Cloud sends them back
* here with a one-time code (handle_return()).
*
* @param int $user_id WordPress user.
* @return string|WP_Error URL to open.
*/
public static function start_connect( $user_id ) {
$res = wp_remote_get(
self::app_url() . '/api/plugin/v1/connect',
array(
'timeout' => 10,
'redirection' => 0,
'user-agent' => 'aeoora-wordpress/' . AEOORA_VERSION . ' (+https://aeoora.com)',
)
);
$data = is_wp_error( $res ) ? null : json_decode( (string) wp_remote_retrieve_body( $res ), true );
if ( is_wp_error( $res ) || 200 !== (int) wp_remote_retrieve_response_code( $res ) || ! is_array( $data ) || empty( $data['ok'] ) ) {
return new WP_Error( 'aeoora_cloud_no_oneclick', __( 'aeoora Cloud can’t be reached for one-click connect right now. Try again in a few minutes, or connect manually below.', 'aeoora' ), array( 'status' => 502 ) );
}
// The connect screen must live on the app's own address.
$authorize = isset( $data['authorize_url'] ) ? esc_url_raw( (string) $data['authorize_url'] ) : self::app_url() . '/connect/wordpress';
if ( 0 !== strpos( $authorize, self::app_url() . '/' ) ) {
$authorize = self::app_url() . '/connect/wordpress';
}
$state = self::b64url( random_bytes( 32 ) );
$verifier = self::b64url( random_bytes( 48 ) );
set_transient(
self::CONNECT_PREFIX . (int) $user_id,
array(
'state' => $state,
'verifier' => $verifier,
),
30 * MINUTE_IN_SECONDS
);
$return = add_query_arg(
array(
'page' => 'aeoora-cloud',
'aeoora_connect' => 1,
'_wpnonce' => wp_create_nonce( 'aeoora_cloud_return' ),
),
admin_url( 'admin.php' )
);
return add_query_arg(
rawurlencode_deep(
array(
'site' => untrailingslashit( home_url() ),
'name' => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
'return' => $return,
'state' => $state,
'challenge' => self::b64url( hash( 'sha256', $verifier, true ) ),
'challenge_method' => 'S256',
'wp_authorize' => admin_url( 'authorize-application.php' ),
'plugin' => AEOORA_VERSION,
)
),
$authorize
);
}
/**
* admin_init: the browser came back from aeoora Cloud. Checks the user,
* the nonce and the state, trades the one-time code for the connection's
* credentials, then redirects to the clean screen with a notice.
*/
public static function handle_return() {
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- the nonce is verified below, before anything is done.
if ( ! isset( $_GET['page'], $_GET['aeoora_connect'] ) || 'aeoora-cloud' !== sanitize_key( wp_unslash( $_GET['page'] ) ) ) {
return;
}
$user = get_current_user_id();
$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
$state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : '';
$code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : '';
$error = isset( $_GET['error'] ) ? sanitize_key( wp_unslash( $_GET['error'] ) ) : '';
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( $nonce, 'aeoora_cloud_return' ) ) {
wp_die( esc_html__( 'This connection link has expired. Start again from aeoora → aeoora Cloud.', 'aeoora' ), '', array( 'response' => 403 ) );
}
$pending = get_transient( self::CONNECT_PREFIX . $user );
delete_transient( self::CONNECT_PREFIX . $user );
if ( '' !== $error ) {
$result = new WP_Error( 'aeoora_cloud_cancelled', 'access_denied' === $error ? __( 'The connection was cancelled in aeoora Cloud. Nothing was changed.', 'aeoora' ) : __( 'aeoora Cloud could not complete the connection. Try again.', 'aeoora' ) );
} elseif ( ! is_array( $pending ) || '' === $state || ! hash_equals( (string) $pending['state'], $state ) || '' === $code ) {
$result = new WP_Error( 'aeoora_cloud_state', __( 'This connection attempt doesn’t match the one started here (it may have expired). Start again.', 'aeoora' ) );
} else {
$result = self::finish_connect( $code, (string) $pending['verifier'] );
}
set_transient(
self::NOTICE_PREFIX . $user,
is_wp_error( $result ) ? array(
'type' => 'error',
'message' => $result->get_error_message(),
) : array(
'type' => 'ok',
'message' => __( 'Connected to aeoora Cloud.', 'aeoora' ),
),
5 * MINUTE_IN_SECONDS
);
wp_safe_redirect( admin_url( 'admin.php?page=aeoora-cloud' ) );
exit;
}
/**
* Trade the one-time code (and the PKCE verifier) for the connection's
* credentials, then connect with them as the manual form would.
*
* @param string $code One-time code.
* @param string $verifier PKCE verifier.
* @return array|WP_Error Status.
*/
public static function finish_connect( $code, $verifier ) {
$res = wp_remote_post(
self::app_url() . '/api/plugin/v1/connect/exchange',
array(
'timeout' => 20,
'redirection' => 0,
'user-agent' => 'aeoora-wordpress/' . AEOORA_VERSION . ' (+https://aeoora.com)',
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode(
array(
'code' => $code,
'code_verifier' => $verifier,
'site' => untrailingslashit( home_url() ),
)
),
)
);
if ( is_wp_error( $res ) ) {
/* translators: %s: error message. */
return new WP_Error( 'aeoora_cloud_unreachable', sprintf( __( 'Couldn’t reach aeoora Cloud to finish connecting: %s', 'aeoora' ), $res->get_error_message() ) );
}
$data = json_decode( (string) wp_remote_retrieve_body( $res ), true );
if ( 200 !== (int) wp_remote_retrieve_response_code( $res ) || ! is_array( $data ) || empty( $data['ok'] ) ) {
return new WP_Error( 'aeoora_cloud_exchange', __( 'aeoora Cloud didn’t accept the connection code (it may have expired). Start again.', 'aeoora' ) );
}
$secret = isset( $data['ingest_secret'] ) && is_string( $data['ingest_secret'] ) ? self::parse_secret( $data['ingest_secret'] ) : '';
$tcode = isset( $data['tracking_code'] ) && is_string( $data['tracking_code'] ) ? self::parse_code( $data['tracking_code'] ) : '';
$token = isset( $data['site_token'] ) && is_string( $data['site_token'] ) && preg_match( '/^aeo_wp_[A-Za-z0-9_-]{20,200}$/', $data['site_token'] ) ? $data['site_token'] : '';
if ( '' === $secret && ( false === $tcode || '' === $tcode ) ) {
return new WP_Error( 'aeoora_cloud_exchange', __( 'aeoora Cloud sent nothing to connect with. Check the brand’s plan in aeoora Cloud, then try again.', 'aeoora' ) );
}
$status = self::connect( $secret, false === $tcode ? '' : $tcode );
if ( is_wp_error( $status ) ) {
return $status;
}
if ( '' !== $token ) {
update_option( self::TOKEN_OPTION, Aeoora_Ai::seal( $token ), false );
}
if ( 'site_revoked' === self::state()['error'] ) {
self::save_state(
array(
'error' => '',
'message' => '',
)
);
}
self::save_brand( $data );
// No AI set up yet: use aeoora Cloud's, so AI Studio works right away.
$other_ai = false;
foreach ( array_keys( Aeoora_Ai::providers() ) as $id ) {
if ( 'cloud' !== $id && Aeoora_Ai::is_ready( $id ) ) {
$other_ai = true;
break;
}
}
if ( self::ai_available() && ! $other_ai ) {
Aeoora_Settings::update( array( 'ai' => array( 'provider' => 'cloud' ) ), false );
}
return self::status();
}
/**
* Keep what aeoora Cloud says about the brand and plan (display only).
*
* @param array $data Exchange or status answer.
*/
private static function save_brand( array $data ) {
$brand = isset( $data['brand'] ) && is_array( $data['brand'] ) ? $data['brand'] : array();
$plan = isset( $data['plan'] ) && is_array( $data['plan'] ) ? $data['plan'] : array();
update_option(
self::BRAND_OPTION,
array(
'name' => isset( $brand['name'] ) ? sanitize_text_field( (string) $brand['name'] ) : '',
'domain' => isset( $brand['domain'] ) ? sanitize_text_field( (string) $brand['domain'] ) : '',
'plan' => isset( $plan['name'] ) ? sanitize_text_field( (string) $plan['name'] ) : '',
'bot_report' => ! empty( $plan['bot_report'] ),
'ai' => isset( $plan['ai'] ) ? (bool) $plan['ai'] : null,
'dashboard' => isset( $data['dashboard_url'] ) && 0 === strpos( (string) $data['dashboard_url'], self::app_url() . '/' ) ? esc_url_raw( (string) $data['dashboard_url'] ) : '',
'checked_at' => time(),
),
false
);
}
/**
* The site token from a one-click connection, or ''.
*
* @return string
*/
private static function site_token() {
$stored = (string) get_option( self::TOKEN_OPTION, '' );
return '' === $stored ? '' : Aeoora_Ai::unseal( $stored );
}
/**
* Refresh brand and plan from aeoora Cloud, at most every 10 minutes.
*/
private static function refresh_brand() {
$token = self::site_token();
$brand = get_option( self::BRAND_OPTION, array() );
if ( '' === $token || ( is_array( $brand ) && ! empty( $brand['checked_at'] ) && time() - (int) $brand['checked_at'] < 10 * MINUTE_IN_SECONDS ) ) {
return;
}
$res = wp_remote_get(
self::app_url() . '/api/plugin/v1/site',
array(
'timeout' => 8,
'user-agent' => 'aeoora-wordpress/' . AEOORA_VERSION . ' (+https://aeoora.com)',
'headers' => array( 'Authorization' => 'Bearer ' . $token ),
)
);
$code = is_wp_error( $res ) ? 0 : (int) wp_remote_retrieve_response_code( $res );
$data = 200 === $code ? json_decode( (string) wp_remote_retrieve_body( $res ), true ) : null;
if ( is_array( $data ) && ! empty( $data['ok'] ) ) {
self::save_brand( $data );
} elseif ( 401 === $code ) {
self::site_revoked();
} elseif ( is_array( $brand ) ) {
$brand['checked_at'] = time(); // Try again later, keep what we know.
update_option( self::BRAND_OPTION, $brand, false );
}
}
/**
* aeoora Cloud answered 401 to the site token: the site was disconnected
* there. The ingest secret stays until ingest refuses it too (then sending
* stops on its own), so a one-off 401 loses nothing.
*/
private static function site_revoked() {
delete_option( self::TOKEN_OPTION );
delete_option( self::BRAND_OPTION );
delete_option( self::AI_CREDITS_OPTION );
if ( 'cloud' === Aeoora_Settings::get( 'ai', 'provider', '' ) ) {
Aeoora_Settings::update( array( 'ai' => array( 'provider' => 'wordpress' ) ), false );
}
self::save_state(
array(
'error' => 'site_revoked',
'message' => '',
)
);
}
/* ------------------------------------------------------------------ AI */
/**
* Can this site use aeoora Cloud's AI? Connected with one click, and
* aeoora Cloud said the plan includes AI (`plan.ai: true`). An answer
* without the flag comes from an aeoora Cloud that has no AI endpoint yet.
*
* @return bool
*/
public static function ai_available() {
if ( '' === (string) get_option( self::TOKEN_OPTION, '' ) ) {
return false;
}
$brand = get_option( self::BRAND_OPTION, array() );
return is_array( $brand ) && isset( $brand['ai'] ) && true === $brand['ai'];
}
/**
* One completion from aeoora Cloud's AI, on the brand's plan.
*
* @param array $args system, prompt, json, max_tokens, temperature, context.
* @return array|WP_Error { text, model, truncated, usage }
*/
public static function ai_complete( array $args ) {
$token = self::site_token();
if ( '' === $token ) {
return new WP_Error( 'aeoora_cloud_ai', __( 'This site is no longer connected to aeoora Cloud. Reconnect it under aeoora → aeoora Cloud, or pick another AI service in aeoora → Settings → AI.', 'aeoora' ) );
}
// aeoora Cloud allows 30 requests a minute per site: after a 429, wait
// instead of sending (a background batch would otherwise keep knocking).
if ( get_transient( 'aeoora_cloud_ai_wait' ) ) {
return new WP_Error( 'aeoora_cloud_ai_busy', __( 'aeoora Cloud’s AI is busy. Try again in a minute.', 'aeoora' ), array( 'status' => 429 ) );
}
// Its limit for instructions plus text is 120,000 characters.
if ( self::length( (string) $args['system'] ) + self::length( (string) $args['prompt'] ) > 120000 ) {
return new WP_Error( 'aeoora_cloud_ai_size', __( 'This text is too long for aeoora Cloud’s AI (over 120,000 characters). Try it on a shorter page or section.', 'aeoora' ), array( 'status' => 413 ) );
}
$res = wp_remote_post(
self::app_url() . '/api/plugin/v1/ai/complete',
array(
'timeout' => (int) apply_filters( 'aeoora_ai_timeout', wp_doing_cron() ? 60 : 180 ),
'redirection' => 0,
'user-agent' => 'aeoora-wordpress/' . AEOORA_VERSION . ' (+https://aeoora.com)',
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
),
'body' => wp_json_encode(
array(
'system' => (string) $args['system'],
'prompt' => (string) $args['prompt'],
'json' => ! empty( $args['json'] ),
'max_tokens' => max( 16, min( 8192, (int) $args['max_tokens'] ) ), // aeoora Cloud's range.
'temperature' => (float) $args['temperature'],
'context' => sanitize_key( (string) ( isset( $args['context'] ) ? $args['context'] : 'manual' ) ),
)
),
)
);
if ( is_wp_error( $res ) ) {
/* translators: %s: error message. */
return new WP_Error( 'aeoora_ai_http', sprintf( __( 'Could not reach aeoora Cloud’s AI: %s', 'aeoora' ), $res->get_error_message() ) );
}
$code = (int) wp_remote_retrieve_response_code( $res );
$data = json_decode( (string) wp_remote_retrieve_body( $res ), true );
$data = is_array( $data ) ? $data : array();
if ( isset( $data['credits'] ) && is_array( $data['credits'] ) ) {
self::save_credits( $data['credits'] );
}
$message = isset( $data['error']['message'] ) && is_string( $data['error']['message'] ) ? sanitize_text_field( $data['error']['message'] ) : '';
if ( 401 === $code ) {
self::site_revoked();
return new WP_Error( 'aeoora_cloud_ai', __( 'This site was disconnected in aeoora Cloud, so its AI can’t be used. Reconnect it under aeoora → aeoora Cloud.', 'aeoora' ), array( 'status' => 401 ) );
}
if ( 402 === $code || 403 === $code ) {
return new WP_Error( 'aeoora_cloud_ai_plan', '' !== $message ? $message : __( 'Your aeoora Cloud plan has no AI credits left for now. Upgrade in aeoora Cloud, wait for the monthly reset, or pick another AI service in aeoora → Settings → AI.', 'aeoora' ), array( 'status' => 402 ) );
}
if ( 429 === $code ) {
$retry = (int) wp_remote_retrieve_header( $res, 'retry-after' );
set_transient( 'aeoora_cloud_ai_wait', 1, max( 10, min( 300, $retry ? $retry : 60 ) ) );
return new WP_Error( 'aeoora_cloud_ai_busy', __( 'aeoora Cloud’s AI is busy. Try again in a minute.', 'aeoora' ), array( 'status' => 429 ) );
}
if ( 413 === $code ) {
return new WP_Error( 'aeoora_cloud_ai_size', __( 'This text is too long for aeoora Cloud’s AI (over 120,000 characters). Try it on a shorter page or section.', 'aeoora' ), array( 'status' => 413 ) );
}
if ( 504 === $code ) {
return new WP_Error( 'aeoora_cloud_ai_timeout', __( 'aeoora Cloud’s AI took too long to answer. Try again, or ask for something shorter.', 'aeoora' ), array( 'status' => 504 ) );
}
if ( 200 !== $code || empty( $data['ok'] ) || ! isset( $data['text'] ) || ! is_string( $data['text'] ) ) {
/* translators: 1: HTTP status code, 2: message. */
return new WP_Error( 'aeoora_ai_api', sprintf( __( 'aeoora Cloud’s AI returned an error (HTTP %1$d). %2$s', 'aeoora' ), $code, $message ), array( 'status' => 502 ) );
}
$usage = isset( $data['usage'] ) && is_array( $data['usage'] ) ? $data['usage'] : array();
return array(
'text' => trim( (string) preg_replace( '~.*?~is', '', $data['text'] ) ),
'model' => isset( $data['model'] ) ? 'aeoora Cloud / ' . sanitize_text_field( (string) $data['model'] ) : 'aeoora Cloud',
'truncated' => isset( $data['finish_reason'] ) && 'length' === $data['finish_reason'],
'usage' => array(
'in' => isset( $usage['in'] ) ? (int) $usage['in'] : 0,
'out' => isset( $usage['out'] ) ? (int) $usage['out'] : 0,
),
);
}
/**
* Characters in a string (multibyte-aware when mbstring is there).
*
* @param string $s Text.
* @return int
*/
private static function length( $s ) {
return function_exists( 'mb_strlen' ) ? (int) mb_strlen( $s, 'UTF-8' ) : strlen( $s );
}
/**
* Keep the plan's AI credits as aeoora Cloud last reported them.
*
* @param array $c used, limit, remaining, resets_at.
*/
private static function save_credits( array $c ) {
update_option(
self::AI_CREDITS_OPTION,
array(
'used' => isset( $c['used'] ) ? (int) $c['used'] : null,
'limit' => isset( $c['limit'] ) ? (int) $c['limit'] : null,
'remaining' => isset( $c['remaining'] ) ? (int) $c['remaining'] : null,
'resets_at' => isset( $c['resets_at'] ) ? sanitize_text_field( (string) $c['resets_at'] ) : '',
'at' => time(),
),
false
);
}
/* ------------------------------------------------------------ settings */
/**
* Is a connection secret saved? (Read without decrypting.)
*
* @return bool
*/
public static function has_secret() {
return '' !== (string) get_option( self::SECRET_OPTION, '' );
}
/**
* Connected in any way (secret or tracking code)?
*
* @return bool
*/
public static function connected() {
return self::has_secret() || '' !== self::tracking_code();
}
/**
* The decrypted connection secret, or ''.
*
* @return string
*/
private static function secret() {
$stored = (string) get_option( self::SECRET_OPTION, '' );
return '' === $stored ? '' : Aeoora_Ai::unseal( $stored );
}
/**
* The secret with its middle hidden, for display.
*
* @return string
*/
private static function masked() {
$secret = self::secret();
return '' === $secret ? '' : substr( $secret, 0, 9 ) . str_repeat( '•', 8 ) . substr( $secret, -4 );
}
/**
* The aeoora Cloud API origin: always https://api.aeoora.com. Nothing in
* the admin changes it; a self-hosted copy of aeoora Cloud can set
* `define( 'AEOORA_CLOUD_API', 'https://api.example.com' );` in wp-config.php.
*
* @return string Origin without a trailing slash.
*/
public static function api_url() {
$api = defined( 'AEOORA_CLOUD_API' ) ? self::parse_api( (string) AEOORA_CLOUD_API ) : '';
return '' === $api ? self::DEFAULT_API : $api;
}
/**
* The AI-bot ingest endpoint.
*
* @return string
*/
public static function endpoint() {
return self::api_url() . '/bots/ingest';
}
/**
* The brand's tracking code, or ''.
*
* @return string
*/
public static function tracking_code() {
return (string) Aeoora_Settings::get( 'cloud', 'tracking_code', '' );
}
/**
* Read a connection secret from what was pasted: the secret itself, or the
* whole "Authorization: Bearer abot_…" header line aeoora Cloud shows.
*
* @param string $raw Pasted text.
* @return string The secret, or '' when it isn't one.
*/
public static function parse_secret( $raw ) {
$raw = trim( (string) $raw );
$raw = preg_replace( '/^authorization\s*:\s*/i', '', $raw );
$raw = preg_replace( '/^bearer\s+/i', '', (string) $raw );
$raw = preg_replace( '/\s+/', '', (string) $raw );
return preg_match( '/^abot_[A-Za-z0-9_-]{16,190}$/', (string) $raw ) ? (string) $raw : '';
}
/**
* Read a tracking code from what was pasted: the code, or the whole
* `