prefix . 'ai_app_onsite_rag_reference_sources'; $excluded_table = $wpdb->prefix . 'ai_app_onsite_rag_excluded_posts'; $excluded_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $excluded_table ) ) === $excluded_table; // Parse reference_sources JSON $raw = isset( $_POST['reference_sources'] ) ? wp_unslash( $_POST['reference_sources'] ) : ''; $sources = json_decode( $raw, true ); if ( ! is_array( $sources ) ) { $sources = []; } // Delete existing sources for this app $wpdb->delete( $table, [ 'app_id' => $app_selector ], [ '%d' ] ); if ( $excluded_table_exists ) { $wpdb->delete( $excluded_table, [ 'app_id' => $app_selector ], [ '%d' ] ); } $now = current_time( 'mysql' ); $inserted = 0; foreach ( [ 'posts', 'categories', 'tags' ] as $type ) { if ( empty( $sources[ $type ] ) || ! is_array( $sources[ $type ] ) ) { continue; } foreach ( $sources[ $type ] as $source_id ) { $source_id = $this->normalize_source_id( $source_id ); if ( $source_id < 1 ) { continue; } $wpdb->insert( $table, [ 'app_id' => $app_selector, 'source_type' => $type, 'source_id' => $source_id, 'created_at' => $now, 'updated_at' => $now, ], [ '%d', '%s', '%d', '%s', '%s' ] ); $inserted++; } } if ( $excluded_table_exists && ! empty( $sources['excluded_posts'] ) && is_array( $sources['excluded_posts'] ) ) { foreach ( $sources['excluded_posts'] as $post_id ) { $post_id = $this->normalize_source_id( $post_id ); if ( $post_id < 1 ) { continue; } $wpdb->insert( $excluded_table, [ 'app_id' => $app_selector, 'post_id' => $post_id, 'created_at' => $now, 'updated_at' => $now, ], [ '%d', '%d', '%s', '%s' ] ); } } // Save token budget if provided if ( isset( $_POST['rag_max_tokens'] ) ) { $this->save_token_settings( (int) $app_selector, absint( $_POST['rag_max_tokens'] ) ); } // Clear transient cache delete_transient( 'ai_app_rag_' . $app_selector ); wp_send_json_success( [ 'message' => "Reference sources saved. {$inserted} source(s) configured.", ] ); } /* ========================================================== * Load saved reference sources * ========================================================*/ public function get_rag_references(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized.' ); } $app_selector = ai_app_onsite_get_app_selector(); if ( ! $app_selector ) { wp_send_json_error( 'App not found. Please create an app first.' ); } global $wpdb; $table = $wpdb->prefix . 'ai_app_onsite_rag_reference_sources'; $excluded_table = $wpdb->prefix . 'ai_app_onsite_rag_excluded_posts'; $excluded_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $excluded_table ) ) === $excluded_table; // Check if table exists if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { wp_send_json_success( [ 'reference_sources' => [ 'posts' => [], 'categories' => [], 'tags' => [], 'excluded_posts' => [] ], 'rag_max_tokens' => 2000, ] ); return; } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT source_type, source_id FROM {$table} WHERE app_id = %d", $app_selector ), ARRAY_A ); $sources = [ 'posts' => [], 'categories' => [], 'tags' => [] ]; foreach ( $rows as $row ) { if ( isset( $sources[ $row['source_type'] ] ) ) { $sources[ $row['source_type'] ][] = (int) $row['source_id']; } } // Enrich with labels for the UI $enriched = [ 'posts' => $this->enrich_posts( $sources['posts'] ), 'categories' => $this->enrich_terms( $sources['categories'], 'category' ), 'tags' => $this->enrich_terms( $sources['tags'], 'post_tag' ), 'excluded_posts' => [], ]; if ( $excluded_table_exists ) { $excluded_rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM {$excluded_table} WHERE app_id = %d", $app_selector ), ARRAY_A ); foreach ( $excluded_rows as $row ) { $enriched['excluded_posts'][] = (int) $row['post_id']; } } // Get token settings $token_table = $wpdb->prefix . 'ai_app_onsite_rag_token_settings'; $rag_max = 2000; if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $token_table ) ) === $token_table ) { $token_row = $wpdb->get_row( $wpdb->prepare( "SELECT rag_max_tokens FROM {$token_table} WHERE app_id = %d", $app_selector ), ARRAY_A ); if ( $token_row ) { $rag_max = (int) $token_row['rag_max_tokens']; } } wp_send_json_success( [ 'reference_sources' => $enriched, 'rag_max_tokens' => $rag_max, ] ); } /* ========================================================== * Search posts * ========================================================*/ public function search_posts(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized.' ); } $search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : ''; $page = isset( $_POST['page'] ) ? max( 1, absint( $_POST['page'] ) ) : 1; $per_page = 20; $args = [ 'post_type' => 'post', 'post_status' => [ 'publish', 'draft', 'pending', 'private' ], 'posts_per_page' => $per_page, 'paged' => $page, 'orderby' => 'date', 'order' => 'DESC', ]; if ( ! empty( $search ) ) { $args['s'] = $search; } $query = new WP_Query( $args ); $posts = []; foreach ( $query->posts as $post ) { $posts[] = [ 'id' => $post->ID, 'title' => get_the_title( $post->ID ) ?: "(No title – ID {$post->ID})", 'status' => $post->post_status, 'date' => get_the_date( 'Y-m-d', $post->ID ), ]; } wp_send_json_success( [ 'posts' => $posts, 'total' => $query->found_posts, 'pages' => $query->max_num_pages, 'page' => $page, ] ); } /* ========================================================== * Get categories * ========================================================*/ public function get_categories(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized.' ); } $terms = get_terms( [ 'taxonomy' => 'category', 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', ] ); $categories = []; if ( ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $categories[] = [ 'id' => $term->term_id, 'name' => $term->name, 'count' => $term->count, ]; } } wp_send_json_success( [ 'categories' => $categories ] ); } /* ========================================================== * Get tags * ========================================================*/ public function get_tags(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized.' ); } $terms = get_terms( [ 'taxonomy' => 'post_tag', 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', ] ); $tags = []; if ( ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $tags[] = [ 'id' => $term->term_id, 'name' => $term->name, 'count' => $term->count, ]; } } wp_send_json_success( [ 'tags' => $tags ] ); } /* ========================================================== * Token settings helpers * ========================================================*/ private function save_token_settings( int $app_id, int $max_tokens ): void { global $wpdb; $table = $wpdb->prefix . 'ai_app_onsite_rag_token_settings'; $now = current_time( 'mysql' ); $max_tokens = max( 500, min( 10000, $max_tokens ) ); $existing = $wpdb->get_row( $wpdb->prepare( "SELECT id FROM {$table} WHERE app_id = %d", $app_id ), ARRAY_A ); if ( $existing ) { $wpdb->update( $table, [ 'rag_max_tokens' => $max_tokens, 'updated_at' => $now ], [ 'id' => (int) $existing['id'] ], [ '%d', '%s' ], [ '%d' ] ); } else { $wpdb->insert( $table, [ 'app_id' => $app_id, 'rag_max_tokens' => $max_tokens, 'created_at' => $now, 'updated_at' => $now, ], [ '%d', '%d', '%s', '%s' ] ); } } /** * Normalize a source item to an integer ID. * * Accepts raw IDs, arrays decoded from JSON, or stdClass objects. * * @param mixed $source_item * @return int */ private function normalize_source_id( $source_item ): int { if ( is_array( $source_item ) && isset( $source_item['id'] ) ) { return absint( $source_item['id'] ); } if ( is_object( $source_item ) && isset( $source_item->id ) ) { return absint( $source_item->id ); } return absint( $source_item ); } /* ========================================================== * Enrichment helpers * ========================================================*/ private function enrich_posts( array $ids ): array { $result = []; foreach ( $ids as $id ) { $post = get_post( $id ); if ( $post ) { $result[] = [ 'id' => $post->ID, 'title' => get_the_title( $post->ID ) ?: "(No title – ID {$post->ID})", 'status' => $post->post_status, ]; } } return $result; } private function enrich_terms( array $ids, string $taxonomy ): array { $result = []; foreach ( $ids as $id ) { $term = get_term( $id, $taxonomy ); if ( $term && ! is_wp_error( $term ) ) { $result[] = [ 'id' => $term->term_id, 'name' => $term->name, 'count' => $term->count, ]; } } return $result; } /* ========================================================== * C3: Full post data for client-side word count * ========================================================*/ public function get_posts_full_data(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorised.' ); } $raw_ids = isset( $_POST['post_ids'] ) ? wp_unslash( $_POST['post_ids'] ) : []; if ( ! is_array( $raw_ids ) ) { $raw_ids = json_decode( stripslashes( (string) $raw_ids ), true ) ?: []; } $ids = array_map( 'absint', (array) $raw_ids ); $ids = array_filter( $ids ); if ( empty( $ids ) ) { wp_send_json_success( [ 'posts' => [] ] ); } $posts = []; foreach ( $ids as $post_id ) { $post = get_post( $post_id ); if ( ! $post ) { continue; } // Categories (names) $category_terms = get_the_terms( $post_id, 'category' ); $categories = []; if ( $category_terms && ! is_wp_error( $category_terms ) ) { foreach ( $category_terms as $term ) { $categories[] = $term->name; } } // Tags (names) $tag_terms = get_the_terms( $post_id, 'post_tag' ); $tags = []; if ( $tag_terms && ! is_wp_error( $tag_terms ) ) { foreach ( $tag_terms as $term ) { $tags[] = $term->name; } } $meta_description = $this->clean_text( $this->get_meta_description( $post_id ) ); // Body – first 2000 chars of clean plain text $body = wp_strip_all_tags( apply_filters( 'the_content', $post->post_content ) ); $body = preg_replace( '/\s+/', ' ', $body ); $body = trim( substr( $body, 0, 2000 ) ); $posts[] = [ 'id' => $post->ID, 'title' => get_the_title( $post->ID ), 'status' => $post->post_status, 'url' => get_permalink( $post->ID ), 'categories' => $categories, 'tags' => $tags, 'meta_description' => $meta_description, 'body' => $body, ]; } wp_send_json_success( [ 'posts' => $posts ] ); } /* ========================================================== * Fetch all posts belonging to a category or tag (for chip display). * Returns the same full-data shape as get_posts_full_data. * ========================================================*/ public function get_posts_by_term(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorised.' ); } $term_id = isset( $_POST['term_id'] ) ? absint( $_POST['term_id'] ) : 0; $taxonomy = isset( $_POST['taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['taxonomy'] ) ) : ''; if ( ! $term_id || ! in_array( $taxonomy, [ 'category', 'post_tag' ], true ) ) { wp_send_json_error( 'Invalid term or taxonomy.' ); } $query = new WP_Query( [ 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 200, 'tax_query' => [ [ 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $term_id, ] ], 'no_found_rows' => true, ] ); $posts = []; foreach ( $query->posts as $post ) { $category_terms = get_the_terms( $post->ID, 'category' ); $categories = []; if ( $category_terms && ! is_wp_error( $category_terms ) ) { foreach ( $category_terms as $term ) { $categories[] = $term->name; } } $tag_terms = get_the_terms( $post->ID, 'post_tag' ); $tags = []; if ( $tag_terms && ! is_wp_error( $tag_terms ) ) { foreach ( $tag_terms as $term ) { $tags[] = $term->name; } } $meta_description = $this->clean_text( $this->get_meta_description( $post->ID ) ); $body = wp_strip_all_tags( apply_filters( 'the_content', $post->post_content ) ); $body = preg_replace( '/\s+/', ' ', $body ); $body = trim( substr( $body, 0, 2000 ) ); $posts[] = [ 'id' => $post->ID, 'title' => get_the_title( $post->ID ), 'status' => $post->post_status, 'url' => get_permalink( $post->ID ), 'categories' => $categories, 'tags' => $tags, 'meta_description' => $meta_description, 'body' => $body, ]; } wp_send_json_success( [ 'posts' => $posts ] ); } /** * 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 ''; } } new AI_APP_ONSITE_RAG_Reference_Handler(); }