Connectors.
*
* Generation runs asynchronously via wp_schedule_single_event() to avoid
* blocking the save_post response — the AI provider call can take 5-30s.
*
* @package AiShareSummarize
* @since 2.0.0
*/
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class to handle AI summary generation, storage and rendering
*/
class AyudaWP_AISS_AI_Summary {
const META_SUMMARY = '_ayudawp_aiss_summary';
const META_PROVIDER = '_ayudawp_aiss_summary_provider';
const META_HASH = '_ayudawp_aiss_summary_hash';
const CRON_HOOK = 'ayudawp_aiss_generate_summary_async';
const LOCK_PREFIX = '_ayudawp_aiss_generating_';
const LAST_ERROR_OPT = 'ayudawp_aiss_last_ai_error';
/**
* Constructor: register hooks
*/
public function __construct() {
add_action( 'init', array( $this, 'register_meta' ) );
add_action( 'wp_after_insert_post', array( $this, 'on_save_post' ), 20, 4 );
add_action( self::CRON_HOOK, array( __CLASS__, 'run' ), 10, 1 );
}
/**
* Register the three summary meta keys for REST exposure
*
* Only registers on the post types selected in auto_insert_content_types
* so the block editor sidebar gets the meta in its data store for those
* types only.
*/
public function register_meta() {
$post_types = ayudawp_aiss_get_summary_post_types();
if ( empty( $post_types ) ) {
$post_types = array( 'post' );
}
$auth_callback = function ( $allowed, $meta_key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
};
foreach ( $post_types as $post_type ) {
register_post_meta(
$post_type,
self::META_SUMMARY,
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'default' => '',
'auth_callback' => $auth_callback,
)
);
register_post_meta(
$post_type,
self::META_PROVIDER,
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'default' => '',
'auth_callback' => $auth_callback,
)
);
register_post_meta(
$post_type,
self::META_HASH,
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'default' => '',
'auth_callback' => $auth_callback,
)
);
}
}
/**
* Fire on every post save — decide whether to schedule async generation
*
* Uses wp_after_insert_post (WP 5.6+) which fires after both the post
* row and its meta are committed, so the manual-edit provider flag is
* already in place when this runs.
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated.
* @param mixed $post_before The previous version of the post or null on insert.
*/
public function on_save_post( $post_id, $post, $update, $post_before ) {
if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
return;
}
if ( ! ayudawp_aiss_is_summary_active() ) {
return;
}
if ( 'publish' !== $post->post_status ) {
return;
}
if ( ! ayudawp_aiss_should_apply_summary( $post_id ) ) {
return;
}
// Respect manual edits — user override always wins.
if ( 'manual' === get_post_meta( $post_id, self::META_PROVIDER, true ) ) {
return;
}
if ( ! $this->should_regenerate( $post_id, $post ) ) {
return;
}
// Re-entrancy lock: avoid duplicate cron events for the same post.
$lock_key = self::LOCK_PREFIX . $post_id;
if ( get_transient( $lock_key ) ) {
return;
}
set_transient( $lock_key, 1, 5 * MINUTE_IN_SECONDS );
wp_schedule_single_event( time() + 1, self::CRON_HOOK, array( (int) $post_id ) );
}
/**
* Check whether the stored summary is still valid for the current content
*
* Compares the current content+title hash against the stored hash.
*
* @param int $post_id Post ID.
* @param WP_Post|null $post Optional post object to avoid an extra fetch.
* @return bool True when the summary should be regenerated.
*/
public function should_regenerate( $post_id, $post = null ) {
if ( null === $post ) {
$post = get_post( $post_id );
}
if ( ! $post ) {
return false;
}
$current_hash = self::compute_hash( $post->post_content, $post->post_title );
$stored_hash = get_post_meta( $post_id, self::META_HASH, true );
return $current_hash !== $stored_hash;
}
/**
* Compute the content hash used to detect significant content changes
*
* @param string $content Post content.
* @param string $title Post title.
* @return string SHA1 hash.
*/
public static function compute_hash( $content, $title ) {
return sha1( wp_strip_all_tags( (string) $content ) . '|' . (string) $title );
}
/**
* Orchestrate the provider cascade: A (WP AI Client) → C (extractive)
*
* Called by:
* - the cron hook (async, after save_post)
* - the REST endpoint (sync, when the editor user clicks "Regenerate now")
*
* Always releases the lock transient on exit so a future save can
* schedule a new generation even when the call errored.
*
* @param int $post_id Post ID to summarize.
* @param bool $force When true, regenerate even if the hash matches.
* @param bool $force_extractive When true, skip Level A (AI) and go straight to extractive.
* Used by the public frontend endpoint when the admin has
* opted out of letting visitors trigger paid API calls.
* @return string|WP_Error Summary text on success, WP_Error on failure.
*/
public static function run( $post_id, $force = false, $force_extractive = false ) {
$post_id = (int) $post_id;
$lock_key = self::LOCK_PREFIX . $post_id;
try {
$post = get_post( $post_id );
if ( ! $post ) {
return new WP_Error( 'no_post', __( 'Post not found.', 'ai-share-summarize' ) );
}
$content = $post->post_content;
$title = $post->post_title;
$hash = self::compute_hash( $content, $title );
if ( ! $force ) {
$stored_hash = get_post_meta( $post_id, self::META_HASH, true );
if ( $hash === $stored_hash ) {
return get_post_meta( $post_id, self::META_SUMMARY, true );
}
}
$options = get_option( 'ayudawp_aiss_options', array() );
// Resolve the admin's generation mode (v2.2.0). "extractive_only"
// behaves like a forced-extractive call; "ai_only" disables the
// fallback; "ai_fallback" keeps the A->C cascade. A caller that
// forces extractive (public frontend) always allows the fallback.
$mode = ayudawp_aiss_get_summary_mode();
$force_extractive_effective = $force_extractive || 'extractive_only' === $mode;
$allow_fallback = $force_extractive || 'ai_fallback' === $mode;
if ( $force_extractive_effective ) {
// Skip Level A entirely — caller wants zero-cost generation
// (typically the public frontend endpoint, or extractive_only mode).
$summary = '';
$provider = '';
} else {
// Level A — WP AI Client (WordPress 7.0+).
$summary = self::generate_with_wp_ai_client( $content, $title );
$provider = 'wp_ai_client';
}
if ( is_wp_error( $summary ) || '' === $summary ) {
$ai_error = is_wp_error( $summary ) ? $summary : null;
// Persist the last AI error for diagnostics (visible from the
// sidebar, the meta box and an admin notice — much more useful
// than relying on error_log + WP_DEBUG). Skip when the caller
// forced extractive — it isn't a real failure.
if ( ! $force_extractive_effective ) {
self::store_last_ai_error( $ai_error );
}
// Whether to run the extractive fallback is driven by the mode
// ("ai_fallback"), or by a caller that explicitly forced extractive.
if ( ! $force_extractive_effective && ! $allow_fallback ) {
if ( $ai_error ) {
// Surface the real error code/message so the user sees
// what really happened, not a generic "AI failed".
return new WP_Error(
'no_fallback',
sprintf(
/* translators: %s is the underlying error message from the AI client. */
__( 'AI generation failed and extractive fallback is disabled: %s', 'ai-share-summarize' ),
$ai_error->get_error_message()
)
);
}
return new WP_Error( 'no_fallback', __( 'AI generation failed and extractive fallback is disabled.', 'ai-share-summarize' ) );
}
// Level C — PHP extractive fallback.
$n_sentences = isset( $options['ai_summary_sentences'] ) ? (int) $options['ai_summary_sentences'] : 3;
$summary = ayudawp_aiss_extractive_summary( $content, $title, $n_sentences );
$provider = 'extractive';
} else {
// Successful AI run — clear any stale error.
self::store_last_ai_error( null );
}
if ( '' === $summary ) {
return new WP_Error( 'empty_summary', __( 'Could not generate a summary for this content.', 'ai-share-summarize' ) );
}
update_post_meta( $post_id, self::META_SUMMARY, wp_kses_post( $summary ) );
update_post_meta( $post_id, self::META_PROVIDER, $provider );
update_post_meta( $post_id, self::META_HASH, $hash );
return $summary;
} finally {
delete_transient( $lock_key );
}
}
/**
* Generate the summary via the WordPress 7.0 AI Client
*
* Returns WP_Error when wp_ai_client_prompt() is unavailable, when
* the configured Connector cannot handle text generation, or when
* the call itself fails.
*
* When running inside WP-Cron (the async path scheduled after save),
* transient provider errors are retried with a short backoff (2s, 5s)
* before giving up — retry count filterable via
* 'ayudawp_aiss_ai_retry_attempts' (default 2). Sync callers are never
* retried so the editor and the public endpoint keep failing fast.
*
* The builder chain is wrapped in try/catch \Throwable to survive
* any future signature drift in the WP AI Client API.
*
* Note: the builder uses PHP __call() magic to proxy snake_case to
* camelCase methods, so `method_exists()` cannot reliably detect
* support-check methods like `is_supported_for_text_generation`.
* We skip that check and just let `generate_text()` fail loudly
* if the provider can't handle the request — its WP_Error already
* carries the precise reason (no provider configured, model lacks
* text capability, etc.).
*
* @param string $content Post content.
* @param string $title Post title.
* @return string|WP_Error Summary text on success.
*/
public static function generate_with_wp_ai_client( $content, $title ) {
if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
return new WP_Error( 'no_wp_ai_client', __( 'WP AI Client is not available (requires WordPress 7.0+).', 'ai-share-summarize' ) );
}
$options = get_option( 'ayudawp_aiss_options', array() );
$n_sentences = isset( $options['ai_summary_sentences'] ) ? max( 1, min( 5, (int) $options['ai_summary_sentences'] ) ) : 3;
$system = 'You are a content summarizer. Return ONLY the summary in plain text, no markdown, no quotes, no preamble. Match the language of the input.';
$clean = ayudawp_aiss_clean_html_for_summary( (string) $content );
$excerpt = function_exists( 'mb_substr' )
? mb_substr( $clean, 0, 3000 )
: substr( $clean, 0, 3000 );
$prompt = sprintf(
"Summarize the following content in exactly %d sentences:\n\n%s\n\n%s",
$n_sentences,
$title,
$excerpt
);
// Resolve which model to use. The plugin exposes a model selector in
// Settings; when it is left on "Automatic" (or points at a model that no
// longer exists) we bias toward a sensible, cheaper model per provider so
// generation never lands on the newest flagship. That is what broke when
// Claude Fable 5 shipped and became the first Anthropic candidate while
// being unavailable to most accounts. See
// ayudawp_aiss_resolve_default_model_preference().
$available = ayudawp_aiss_get_available_models();
$selected = isset( $options['ai_summary_model'] ) ? (string) $options['ai_summary_model'] : '';
$pin_provider = '';
$pin_models = array();
if ( '' !== $selected && false !== strpos( $selected, ':' ) ) {
list( $sel_provider, $sel_model ) = explode( ':', $selected, 2 );
// Honor the explicit choice only if it still exists in the live list.
if ( isset( $available[ $sel_provider ]['models'] ) ) {
foreach ( $available[ $sel_provider ]['models'] as $candidate ) {
if ( $candidate['id'] === $sel_model ) {
$pin_provider = $sel_provider;
$pin_models = array( $sel_model );
break;
}
}
}
}
if ( empty( $pin_models ) ) {
// Automatic, or a stale stored selection: bias toward the cheaper default.
$pin_models = ayudawp_aiss_resolve_default_model_preference( $available );
}
// Transient provider errors (e.g. "Unexpected API response: Missing
// the 'content' key") resolve on a quick retry. Only the async cron
// path retries — sync calls (editor "Regenerate now", public frontend
// endpoint) fail fast because a user is actively waiting.
$retries = wp_doing_cron() ? (int) apply_filters( 'ayudawp_aiss_ai_retry_attempts', 2 ) : 0;
$max_attempts = 1 + min( 5, max( 0, $retries ) );
$error = null;
for ( $attempt = 1; $attempt <= $max_attempts; $attempt++ ) {
if ( $attempt > 1 ) {
sleep( 2 === $attempt ? 2 : 5 );
}
try {
$builder = wp_ai_client_prompt( $prompt )->using_system_instruction( $system );
if ( '' !== $pin_provider ) {
$builder = $builder->using_provider( $pin_provider );
}
if ( ! empty( $pin_models ) ) {
$builder = $builder->using_model_preference( ...$pin_models );
}
$result = $builder->generate_text();
} catch ( \Throwable $e ) {
$error = new WP_Error(
'wp_ai_client_exception',
sprintf( '%s (%s)', $e->getMessage(), get_class( $e ) )
);
continue;
}
if ( is_wp_error( $result ) ) {
$error = $result;
continue;
}
$text = trim( wp_strip_all_tags( (string) $result ) );
if ( '' === $text ) {
$error = new WP_Error( 'wp_ai_client_empty', __( 'WP AI Client returned an empty response.', 'ai-share-summarize' ) );
continue;
}
return $text;
}
// Every attempt failed. Surface the attempt count in the error so the
// admin can tell a persistent failure from a single transient hiccup.
if ( $max_attempts > 1 && $error instanceof WP_Error ) {
return new WP_Error(
$error->get_error_code(),
sprintf(
/* translators: 1: error message from the AI client, 2: number of attempts. */
__( '%1$s (failed after %2$d attempts)', 'ai-share-summarize' ),
$error->get_error_message(),
$max_attempts
)
);
}
return $error;
}
/**
* Persist (or clear) the last AI Client error for diagnostics
*
* The option holds the most recent failure only — successful generations
* clear it. Surfaced in the editor sidebar, the classic meta box and an
* admin notice so the admin can act on the actual error without enabling
* WP_DEBUG to read PHP logs.
*
* @param WP_Error|null $error Error to store, or null to clear.
*/
public static function store_last_ai_error( $error ) {
if ( null === $error ) {
delete_option( self::LAST_ERROR_OPT );
return;
}
update_option( self::LAST_ERROR_OPT, array(
'code' => $error->get_error_code(),
'message' => $error->get_error_message(),
'time' => time(),
), false );
}
/**
* Read the last AI Client error
*
* Auto-expires after 7 days so a long-resolved transient failure does
* not stick to the settings page forever — sites running on extractive
* only would never clear it otherwise, because the clear-on-success
* path requires a successful AI generation to fire.
*
* @return array|null Array with code/message/time, or null when no error is stored.
*/
public static function get_last_ai_error() {
$stored = get_option( self::LAST_ERROR_OPT );
if ( ! is_array( $stored ) || empty( $stored['message'] ) ) {
return null;
}
$age = isset( $stored['time'] ) ? ( time() - (int) $stored['time'] ) : 0;
if ( $age > 7 * DAY_IN_SECONDS ) {
delete_option( self::LAST_ERROR_OPT );
return null;
}
return $stored;
}
/**
* Critical inline CSS for the summary block (v2.0.0)
*
* Printed once per page right before the first summary or placeholder
* is rendered. Performance plugins (wpo-tweaks, WP Rocket, LiteSpeed,
* etc.) often defer the main stylesheet with `rel="preload"`, which
* can leave the block visually broken until the deferred CSS finishes
* loading — or fail entirely on browsers/CSPs that block onload
* handlers. These few rules guarantee the summary looks acceptable
* even when the external stylesheet never applies.
*
* The full stylesheet still wins because it ships richer rules
* (dark-mode adaptation, caret rotation, attribution color), but the
* baseline survives without it.
*
* Echoes directly (rather than returning a string the caller would echo)
* so the output is a plain literal-string echo with no escaping concerns —
* `echo helper()` of pre-built markup is a wordpress.org review red flag.
* Idempotent: the static guard prints at most once per request, whether
* the first call comes from wp_head (auto-insert) or from the summary
* renderer (late shortcode fallback after wp_head has fired).
*
* @return void
*/
public static function print_critical_inline_style() {
static $printed = false;
if ( $printed ) {
return;
}
$printed = true;
// All-literal CSS; echoing string literals needs no output escaping.
// phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact -- one-liner CSS for minimal payload.
echo '';
// phpcs:enable
}
/**
* Build the CSS class string for the summary