array( summary, content_hash, indexed_at ). * * @var array|null */ private static $cache = null; /** * Get the summary for a post (from local cache only — no API calls). * * Optionally validates freshness: if the cached content_hash does not * match the sha256 of the post's current content, the summary is * considered stale and '' is returned (Synergy 3 of the plan). * * @param int $post_id Post ID. * @param string $current_content Current post_content for hash validation ('' to skip). * @return string Summary text or ''. */ public static function get_summary( $post_id, $current_content = '' ) { $post_id = (int) $post_id; $all = self::load_cache(); if ( ! isset( $all[ $post_id ] ) || ! is_array( $all[ $post_id ] ) ) { return ''; } $entry = $all[ $post_id ]; $summary = isset( $entry['summary'] ) ? (string) $entry['summary'] : ''; if ( '' === $summary ) { return ''; } // Freshness validation via content_hash (Synergy 3). if ( '' !== $current_content ) { $cached_hash = isset( $entry['content_hash'] ) ? (string) $entry['content_hash'] : ''; if ( '' !== $cached_hash && ! hash_equals( $cached_hash, self::hash_content( $current_content ) ) ) { return ''; // Stale summary — omit rather than mislead LLMs. } } return $summary; } /** * Whether a fresh (hash-matching) summary exists for a post. * * @param int $post_id Post ID. * @param string $current_content Current post_content. * @return bool */ public static function has_fresh_summary( $post_id, $current_content ) { return '' !== self::get_summary( $post_id, $current_content ); } /** * Count of cached summaries. * * @return int */ public static function count_cached() { return count( self::load_cache() ); } /** * Timestamp of the last successful sync (UTC mysql format) or ''. * * @return string */ public static function last_sync_at() { return (string) get_option( self::LAST_SYNC_OPT, '' ); } /** * Sync summaries from the SaaS server into the local cache. * * Uses pagination (limit/offset) to bound response size. Returns a * status array; never throws. * * @return array{ok:bool, synced?:int, message:string, code?:string} */ public static function sync() { if ( ! self::acquire_lock() ) { return array( 'ok' => false, 'message' => __( 'A summaries sync is already in progress.', 'ailinkmaster-internal-auto-manager' ), 'code' => 'locked', ); } $provider = self::get_provider(); if ( is_wp_error( $provider ) ) { self::release_lock(); return array( 'ok' => false, 'message' => $provider->get_error_message(), 'code' => $provider->get_error_code(), ); } $all = array(); $offset = 0; $total = 0; while ( true ) { $endpoint = add_query_arg( array( 'limit' => self::PAGE_SIZE, 'offset' => $offset, ), '/api/v1/index/summaries' ); $response = $provider->request_saas( $endpoint, 'GET' ); if ( is_wp_error( $response ) ) { self::release_lock(); $code = $response->get_error_code(); // Graceful degradation: endpoint missing or balance gate. if ( 'payment_required' === $code ) { return array( 'ok' => false, 'message' => __( 'Token balance is zero — summaries are unavailable until the balance-gate exception is deployed server-side. The module works without AI descriptions.', 'ailinkmaster-internal-auto-manager' ), 'code' => $code, ); } return array( 'ok' => false, 'message' => $response->get_error_message(), 'code' => $code, ); } $items = is_array( $response ) && isset( $response['summaries'] ) && is_array( $response['summaries'] ) ? $response['summaries'] : null; if ( null === $items ) { self::release_lock(); return array( 'ok' => false, 'message' => __( 'Unexpected response format from the summaries endpoint.', 'ailinkmaster-internal-auto-manager' ), 'code' => 'bad_response', ); } foreach ( $items as $item ) { if ( ! is_array( $item ) || ! isset( $item['post_id'] ) ) { continue; } $post_id = absint( $item['post_id'] ); if ( $post_id <= 0 ) { continue; } $all[ $post_id ] = array( 'summary' => isset( $item['summary'] ) ? self::clean_summary( (string) $item['summary'] ) : '', 'content_hash' => isset( $item['content_hash'] ) ? preg_replace( '/[^a-f0-9]/i', '', (string) $item['content_hash'] ) : '', 'indexed_at' => isset( $item['indexed_at'] ) ? sanitize_text_field( (string) $item['indexed_at'] ) : '', ); $total++; } if ( count( $items ) < self::PAGE_SIZE ) { break; // Last page. } $offset += self::PAGE_SIZE; // Hard safety cap: 10k posts = 20 pages. if ( $offset >= 10000 ) { break; } } update_option( self::CACHE_OPTION, $all, false ); update_option( self::LAST_SYNC_OPT, gmdate( 'Y-m-d H:i:s' ) ); self::$cache = $all; self::release_lock(); return array( 'ok' => true, 'synced' => $total, 'message' => sprintf( /* translators: %d: number of summaries. */ _n( '%d summary synced.', '%d summaries synced.', $total, 'ailinkmaster-internal-auto-manager' ), $total ), ); } /** * Clean a raw summary string before caching. * * Defends against "dirty" LLM output: a markdown code fence * (```json ... ``` or ``` ... ```) wrapping either plain text or a * JSON object like {"summary": "..."}. sanitize_text_field() alone * strips HTML tags but keeps the fences, so they would leak into * llms.txt / llms-full.txt. Order: * 1. Strip a leading/trailing code fence (with optional language tag). * 2. If the remainder is a JSON object with a "summary" field, use it. * 3. sanitize_text_field() for tags/whitespace/extra lines. * * @param string $raw Raw summary from the SaaS endpoint. * @return string Cleaned single-line summary (may be ''). */ private static function clean_summary( $raw ) { $text = trim( (string) $raw ); // 1. Strip a wrapping markdown code fence: ```json ... ``` or ``` ... ```. if ( preg_match( '/^`{3,}[a-zA-Z0-9_-]*\s*(.*?)\s*`{3,}$/s', $text, $m ) ) { $text = trim( $m[1] ); } // 2. If what remains is a JSON object with a summary field, unwrap it. if ( '' !== $text && '{' === substr( $text, 0, 1 ) && '}' === substr( $text, -1 ) ) { $decoded = json_decode( $text, true ); if ( is_array( $decoded ) && isset( $decoded['summary'] ) && is_string( $decoded['summary'] ) ) { $text = trim( $decoded['summary'] ); } } // 3. Standard sanitization: strips tags, line breaks, extra whitespace. return sanitize_text_field( $text ); } /** * Drop the local cache (e.g. when the module is disabled). * * @return void */ public static function clear_cache() { delete_option( self::CACHE_OPTION ); delete_option( self::LAST_SYNC_OPT ); self::$cache = null; } /** * Delete one post's document from the SaaS index (vector_chunks) and * drop it from the local summaries cache. * * Called when a post is permanently deleted in WordPress so the server * index does not keep orphaned chunks (seen live: post 20 on * test1.aicoloringpages.pro). Failures are non-fatal: the daily sync * self-heals the local cache once the server side is clean. * * @param int $post_id Post ID. * @return bool True when the server delete succeeded (or was not needed). */ public static function delete_server_document( $post_id ) { $post_id = absint( $post_id ); if ( $post_id <= 0 ) { return false; } $ok = false; $provider = self::get_provider(); if ( ! is_wp_error( $provider ) ) { $result = $provider->saas_delete_document( $post_id ); $ok = ! is_wp_error( $result ); } // Drop the local cache entry either way: if the server delete // failed the next sync() will re-add it, but a deleted WP post // must not keep a stale summary locally. self::forget_post( $post_id ); return $ok; } /** * Remove a single post from the local summaries cache. * * @param int $post_id Post ID. * @return void */ public static function forget_post( $post_id ) { $post_id = absint( $post_id ); if ( $post_id <= 0 ) { return; } $all = self::load_cache(); if ( ! isset( $all[ $post_id ] ) ) { return; } unset( $all[ $post_id ] ); update_option( self::CACHE_OPTION, $all, false ); self::$cache = $all; } /** * sha256 of raw content — matches the server-side index_hashes hash. * * @param string $content Raw content. * @return string */ public static function hash_content( $content ) { return hash( 'sha256', (string) $content ); } // ------------------------------------------------------------------------- // Internals. // ------------------------------------------------------------------------- /** * Load the cache option (once per request). * * @return array */ private static function load_cache() { if ( null === self::$cache ) { $raw = get_option( self::CACHE_OPTION, array() ); self::$cache = is_array( $raw ) ? $raw : array(); } return self::$cache; } /** * Lazy-load the SaaS provider (pattern of AILM_PageRank_Engine). * * @return AILM_OpenAI_Provider|WP_Error */ private static function get_provider() { if ( ! class_exists( 'AILM_OpenAI_Provider' ) ) { // The provider implements AILM_AI_Provider — the interface must // be loaded first or the require below fatals with // "Class 'AILM_AI_Provider' not found". $iface = dirname( dirname( __DIR__ ) ) . '/modules/ai-core/interfaces/interface-ailm-ai-provider.php'; if ( file_exists( $iface ) ) { require_once $iface; } $path = dirname( dirname( __DIR__ ) ) . '/modules/ai-core/providers/class-ailm-openai-provider.php'; if ( ! file_exists( $path ) ) { return new WP_Error( 'missing_provider', __( 'SaaS provider class is not available.', 'ailinkmaster-internal-auto-manager' ) ); } require_once $path; } return new AILM_OpenAI_Provider(); } /** * Acquire the sync lock (transient, 5-minute TTL). * * @return bool */ private static function acquire_lock() { if ( get_transient( self::SYNC_LOCK ) ) { return false; } set_transient( self::SYNC_LOCK, 1, 5 * MINUTE_IN_SECONDS ); return true; } /** * Release the sync lock. * * @return void */ private static function release_lock() { delete_transient( self::SYNC_LOCK ); } }