app_id = $app_id; $this->max_tokens = max( 500, min( 10000, $max_tokens ) ); } /** * Build the RAG reference content block for prompt injection. * * @return string Formatted reference block, or empty string if nothing configured. */ public function build(): string { global $wpdb; $table = $wpdb->prefix . 'ai_app_onsite_rag_reference_sources'; // Bail if table does not exist if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { return ''; } $sources = $wpdb->get_results( $wpdb->prepare( "SELECT source_type, source_id FROM {$table} WHERE app_id = %d", $this->app_id ), ARRAY_A ); if ( empty( $sources ) ) { return ''; } // Group source IDs by type $post_ids = []; $category_ids = []; $tag_ids = []; foreach ( $sources as $source ) { $id = (int) $source['source_id']; switch ( $source['source_type'] ) { case 'posts': $post_ids[] = $id; break; case 'categories': $category_ids[] = $id; break; case 'tags': $tag_ids[] = $id; break; } } // Resolve taxonomies to post IDs $from_cats = $this->resolve_posts_from_taxonomy( $category_ids, 'category' ); $from_tags = $this->resolve_posts_from_taxonomy( $tag_ids, 'post_tag' ); $excluded_post_ids = $this->get_excluded_post_ids(); // Merge, deduplicate, cap, sort deterministically $all_post_ids = array_unique( array_merge( $post_ids, $from_cats, $from_tags ) ); if ( ! empty( $excluded_post_ids ) ) { $all_post_ids = array_values( array_filter( $all_post_ids, function ( $post_id ) use ( $excluded_post_ids ) { return ! in_array( (int) $post_id, $excluded_post_ids, true ); } ) ); } if ( empty( $all_post_ids ) ) { return ''; } $all_post_ids = array_slice( $all_post_ids, 0, $this->max_total_posts ); sort( $all_post_ids, SORT_NUMERIC ); // Extract structured content $content_blocks = $this->extract_post_content( $all_post_ids ); if ( empty( $content_blocks ) ) { return ''; } // Trim to token budget $trimmed = $this->trim_to_token_budget( $content_blocks ); if ( empty( trim( $trimmed ) ) ) { return ''; } return $trimmed; } /* ---------------------------------------------------------- * Taxonomy resolution * --------------------------------------------------------*/ /** * Resolve taxonomy term IDs to post IDs. * * @param int[] $term_ids Term IDs. * @param string $taxonomy Taxonomy name. * @return int[] */ private function resolve_posts_from_taxonomy( array $term_ids, string $taxonomy ): array { if ( empty( $term_ids ) ) { return []; } $query = new WP_Query( [ 'post_type' => 'post', 'post_status' => [ 'publish', 'draft', 'pending', 'private' ], 'posts_per_page' => $this->max_posts_per_source, 'fields' => 'ids', 'orderby' => 'ID', 'order' => 'ASC', 'tax_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query [ 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $term_ids, ], ], ] ); return $query->posts ?: []; } /** * Fetch globally excluded post IDs for the app. * * @return int[] */ private function get_excluded_post_ids(): array { global $wpdb; $table = $wpdb->prefix . 'ai_app_onsite_rag_excluded_posts'; if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { return []; } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM {$table} WHERE app_id = %d", $this->app_id ), ARRAY_A ); if ( empty( $rows ) ) { return []; } $ids = []; foreach ( $rows as $row ) { $ids[] = (int) $row['post_id']; } return $ids; } /* ---------------------------------------------------------- * Content extraction * --------------------------------------------------------*/ /** * Extract structured content from an array of post IDs. * * @param int[] $post_ids * @return string[] One formatted text block per post. */ private function extract_post_content( array $post_ids ): array { $blocks = []; foreach ( $post_ids as $post_id ) { $post = get_post( $post_id ); if ( ! $post ) { continue; } // URL if ( $post->post_status === 'publish' ) { $url = get_permalink( $post_id ); } else { $url = get_preview_post_link( $post_id ); if ( ! $url ) { $url = get_permalink( $post_id ); } } $title = get_the_title( $post_id ); $meta_description = $this->get_meta_description( $post_id ); $meta_description = $this->clean_text( $meta_description ); // Headings (H1–H3) $headings = $this->extract_headings( $post->post_content ); // Clean body text $body = $this->clean_body_text( $post->post_content ); // Metadata $author = get_the_author_meta( 'display_name', $post->post_author ); $categories = wp_get_post_categories( $post_id, [ 'fields' => 'names' ] ); $tags = wp_get_post_tags( $post_id, [ 'fields' => 'names' ] ); $block = "- Post Title: {$title}\n"; $block .= "- URL: {$url}\n"; if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) { $block .= '- Categories: ' . implode( ', ', $categories ) . "\n"; } if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) { $block .= '- Tags: ' . implode( ', ', $tags ) . "\n"; } $block .= "- Meta-Description: {$meta_description}\n"; if ( ! empty( $headings ) ) { $block .= '- Headings: ' . implode( ' | ', $headings ) . "\n"; } $block .= "\n{$body}\n"; $blocks[] = $block; } return $blocks; } /** * Extract H1–H3 headings from HTML content. * * @param string $html * @return string[] */ private function extract_headings( string $html ): array { $headings = []; if ( preg_match_all( '/]*>(.*?)<\/h[1-3]>/si', $html, $matches ) ) { foreach ( $matches[1] as $match ) { $clean = wp_strip_all_tags( $match ); if ( ! empty( trim( $clean ) ) ) { $headings[] = trim( $clean ); } } } return $headings; } /** * Strip HTML and boilerplate, return clean body text. * * @param string $html * @return string */ private function clean_body_text( string $html ): string { // Remove script and style tags completely $text = preg_replace( '/]*>.*?<\/script>/si', '', $html ); $text = preg_replace( '/]*>.*?<\/style>/si', '', $text ); // Remove nav, header, footer, aside elements $text = preg_replace( '/<(nav|header|footer|aside)[^>]*>.*?<\/\1>/si', '', $text ); // Remove WordPress block comments $text = preg_replace( '//s', '', $text ); // Strip remaining HTML $text = wp_strip_all_tags( $text ); // Normalize whitespace $text = preg_replace( '/[ \t]+/', ' ', $text ); $text = preg_replace( '/\n{3,}/', "\n\n", $text ); $text = trim( $text ); // Cap per-post body length if ( strlen( $text ) > $this->per_post_body_chars ) { $text = substr( $text, 0, $this->per_post_body_chars ) . '…'; } return $text; } /** * Clean plain text extracted from meta descriptions. * * @param string $text * @return string */ private function clean_text( string $text ): string { $text = strip_tags( $text ); $text = preg_replace( '/[ \t]+/', ' ', $text ); $text = preg_replace( '/\n{3,}/', "\n\n", $text ); return trim( (string) $text ); } /** * Resolve a post meta description from common SEO plugin keys. * * @param int $post_id * @return string */ private function get_meta_description( int $post_id ): string { $meta_keys = [ '_yoast_wpseo_metadesc', 'rank_math_description', '_aioseop_description', '_seopress_titles_desc', ]; foreach ( $meta_keys as $meta_key ) { $value = get_post_meta( $post_id, $meta_key, true ); if ( is_string( $value ) ) { $value = $this->clean_text( $value ); if ( $value !== '' ) { return $value; } } } return ''; } /* ---------------------------------------------------------- * Token trimming * --------------------------------------------------------*/ /** * Trim content blocks to fit within the RAG token budget. * Uses the ~4 chars/token heuristic for English + GPT models. * * @param string[] $blocks * @return string */ private function trim_to_token_budget( array $blocks ): string { $max_chars = $this->max_tokens * 4; $result = ''; $current_chars = 0; foreach ( $blocks as $block ) { $block_len = strlen( $block ); if ( $current_chars + $block_len <= $max_chars ) { $result .= $block . "\n"; $current_chars += $block_len + 1; } else { // Add partial block if meaningful space remains $remaining = $max_chars - $current_chars; if ( $remaining > 200 ) { $result .= substr( $block, 0, $remaining ) . "…\n"; } break; } } return $result; } } }