Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/review-schema/app/AI/AIClient.php
+++ b/review-schema/app/AI/AIClient.php
@@ -500,6 +500,7 @@
}
$response = wp_remote_post(
+ // phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration -- Bring-your-own-key: the site admin enters the provider key; the WordPress AI Client is not available on the plugin's WP 6.0 minimum.
'https://api.openai.com/v1/chat/completions',
[
'timeout' => $this->timeout,
@@ -526,6 +527,7 @@
*/
private function call_anthropic( $system_prompt, $user_prompt ) {
$response = wp_remote_post(
+ // phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration -- Bring-your-own-key: the site admin enters the provider key; the WordPress AI Client is not available on the plugin's WP 6.0 minimum.
'https://api.anthropic.com/v1/messages',
[
'timeout' => $this->timeout,
@@ -709,6 +711,7 @@
// The key goes in a header, never the URL: request URLs surface in
// Query Monitor, server access logs and error messages.
$url = sprintf(
+ // phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration -- Bring-your-own-key: the site admin enters the provider key; the WordPress AI Client is not available on the plugin's WP 6.0 minimum.
'https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent',
rawurlencode( $this->model )
);
--- a/review-schema/app/AI/AIInit.php
+++ b/review-schema/app/AI/AIInit.php
@@ -387,6 +387,7 @@
private function initComponents() {
( new RestApi() )->register_hooks();
( new SchemaRenderer() )->register_hooks();
+ ( new ArticleBodySync() )->register_hooks();
}
/**
@@ -777,16 +778,21 @@
// Geo coordinates.
$geo = [];
if ( ! empty( $settings['latitude'] ) || ! empty( $settings['longitude'] ) ) {
- $geo = [
- '@type' => 'GeoCircle',
- '@id' => $entity_id . '-geocircle',
- 'geoMidpoint' => [
- '@type' => 'GeoCoordinates',
- 'latitude' => $settings['latitude'] ?? '',
- 'longitude' => $settings['longitude'] ?? '',
- ],
- 'geoRadius' => ! empty( $settings['radius'] ) ? absint( $settings['radius'] ) : 50,
+ $geo_coordinates = [
+ '@type' => 'GeoCoordinates',
+ 'latitude' => $settings['latitude'] ?? '',
+ 'longitude' => $settings['longitude'] ?? '',
];
+ $geo_radius = Functions::getGeoRadius( $settings['radius'] ?? '' );
+
+ $geo = $geo_radius > 0
+ ? [
+ '@type' => 'GeoCircle',
+ '@id' => $entity_id . '-geocircle',
+ 'geoMidpoint' => $geo_coordinates,
+ 'geoRadius' => $geo_radius,
+ ]
+ : $geo_coordinates;
}
// Opening hours.
@@ -942,6 +948,11 @@
}
/**
+ * SoftwareApplication and its subtypes (Pro-only AI extraction).
+ */
+ const SOFTWARE_APPLICATION_TYPES = [ 'SoftwareApplication', 'WebApplication', 'MobileApplication' ];
+
+ /**
* Get pro-only schema type values derived from rich_snippet_cats().
*
* Identifies types whose label contains [Pro] and maps them to
@@ -967,6 +978,11 @@
}
}
+ // SoftwareApplication subtypes share its Pro-only extraction.
+ if ( in_array( 'SoftwareApplication', $pro, true ) ) {
+ $pro = array_merge( $pro, self::SOFTWARE_APPLICATION_TYPES );
+ }
+
return $pro;
}
@@ -1239,9 +1255,9 @@
'logoUrl' => rtrs()->get_assets_uri( 'imgs/icon-128x128.gif' ),
'validation' => $initial_validation,
'evaluation' => $initial_evaluation,
- 'seo' => AiVerifyStore::restore( 'seo', $post_id, SeoAnalyzer::analyze( $post_id ) ),
- 'aeo' => AiVerifyStore::restore( 'aeo', $post_id, RtrsModulesAeoAnalyzersAeoAnalyzer::analyze( $post_id ) ),
- 'geo' => AiVerifyStore::restore( 'geo', $post_id, RtrsModulesGeoAnalyzersGeoAnalyzer::analyze( $post_id ) ),
+ 'seo' => apply_filters( 'rtrs_ai_verify_restore', SeoAnalyzer::analyze( $post_id ), 'seo', $post_id ),
+ 'aeo' => apply_filters( 'rtrs_ai_verify_restore', RtrsModulesAeoAnalyzersAeoAnalyzer::analyze( $post_id ), 'aeo', $post_id ),
+ 'geo' => apply_filters( 'rtrs_ai_verify_restore', RtrsModulesGeoAnalyzersGeoAnalyzer::analyze( $post_id ), 'geo', $post_id ),
'schemaTypes' => array_merge(
[
[
--- a/review-schema/app/AI/AiVerifyStore.php
+++ b/review-schema/app/AI/AiVerifyStore.php
@@ -1,211 +0,0 @@
-<?php
-/**
- * Persistence for "Verify with AI" channel results.
- *
- * A channel verification (bounded AI re-score) is produced on demand by the Pro
- * ChannelAiVerifier and is otherwise ephemeral. This store persists the verified
- * score/grade/notes to post meta, keyed by a signature of the deterministic
- * channel. On a later render the verified result is re-applied only while the
- * signature still matches — i.e. until the post content (or any input that moves
- * the channel score) changes, after which the deterministic score is shown again
- * and the channel can be re-verified.
- *
- * @package RtrsAI
- * @since 1.0.0
- */
-
-namespace RtrsAI;
-
-use RtrsModulesSeoAnalysisGrade;
-
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
-
-/**
- * Class AiVerifyStore
- */
-class AiVerifyStore {
-
- /**
- * Post-meta key prefix; the channel key ('seo'|'aeo'|'geo') is appended.
- */
- const META_PREFIX = '_rtrs_ai_verify_';
-
- /**
- * Fingerprint of a deterministic channel.
- *
- * Combines the aggregate score with each criterion's key => value so the
- * signature changes whenever any scored input changes (content, links,
- * headings, SEO title/meta, …). Optional criteria are intentionally ignored
- * since they never affect the score.
- *
- * @param array $channel Channel object.
- * @return string
- */
- public static function signature( array $channel ) {
- $parts = [
- 'score' => isset( $channel['score'] ) ? (int) $channel['score'] : 0,
- 'criteria' => [],
- ];
-
- if ( ! empty( $channel['criteria'] ) && is_array( $channel['criteria'] ) ) {
- foreach ( $channel['criteria'] as $criterion ) {
- $key = isset( $criterion['key'] ) ? (string) $criterion['key'] : '';
- $parts['criteria'][ $key ] = isset( $criterion['value'] ) ? (int) $criterion['value'] : 0;
- }
- }
-
- return md5( (string) wp_json_encode( $parts ) );
- }
-
- /**
- * Persist a verified channel, fingerprinted against its deterministic form.
- *
- * @param string $key Channel key ('seo'|'aeo'|'geo').
- * @param int $post_id Post ID.
- * @param array $deterministic The channel before AI verification.
- * @param array $verified The channel after AI verification.
- * @return void
- */
- public static function save( $key, $post_id, array $deterministic, array $verified ) {
- $post_id = (int) $post_id;
- if ( $post_id <= 0 || empty( $verified['scored_by'] ) || 'ai' !== $verified['scored_by'] ) {
- return;
- }
-
- update_post_meta(
- $post_id,
- self::META_PREFIX . $key,
- [
- 'score' => isset( $verified['score'] ) ? (int) $verified['score'] : 0,
- 'grade' => isset( $verified['grade'] ) ? (string) $verified['grade'] : '',
- 'notes' => self::collect_criteria_notes( $verified ),
- 'values' => self::collect_criteria_values( $verified ),
- 'sig' => self::signature( $deterministic ),
- 'time' => time(),
- ]
- );
- }
-
- /**
- * Build a `criterion key => notes[]` map from a verified channel.
- *
- * @param array $verified The channel after AI verification.
- * @return array<string, array>
- */
- private static function collect_criteria_notes( array $verified ) {
- $map = [];
-
- if ( empty( $verified['criteria'] ) || ! is_array( $verified['criteria'] ) ) {
- return $map;
- }
-
- foreach ( $verified['criteria'] as $criterion ) {
- $key = isset( $criterion['key'] ) ? (string) $criterion['key'] : '';
- if ( '' === $key || empty( $criterion['ai_notes'] ) || ! is_array( $criterion['ai_notes'] ) ) {
- continue;
- }
- $map[ $key ] = $criterion['ai_notes'];
- }
-
- return $map;
- }
-
- /**
- * Build a `criterion key => AI-adjusted value` map from a verified channel.
- *
- * Persists the per-criterion percentages the AI shifted so a restored
- * verification shows the same numbers (and derived status) it did when the
- * review ran, not the deterministic values.
- *
- * @param array $verified The channel after AI verification.
- * @return array<string, int>
- */
- private static function collect_criteria_values( array $verified ) {
- $map = [];
-
- if ( empty( $verified['criteria'] ) || ! is_array( $verified['criteria'] ) ) {
- return $map;
- }
-
- foreach ( $verified['criteria'] as $criterion ) {
- $key = isset( $criterion['key'] ) ? (string) $criterion['key'] : '';
- if ( '' === $key || ! empty( $criterion['locked'] ) ) {
- continue;
- }
- $map[ $key ] = max( 0, min( 100, isset( $criterion['value'] ) ? (int) $criterion['value'] : 0 ) );
- }
-
- return $map;
- }
-
- /**
- * Delete a saved AI verification so the channel reverts to its deterministic
- * score. Used by the editor's "Remove AI review" action.
- *
- * @param string $key Channel key ('seo'|'aeo'|'geo').
- * @param int $post_id Post ID.
- * @return void
- */
- public static function clear( $key, $post_id ) {
- $post_id = (int) $post_id;
- if ( $post_id <= 0 ) {
- return;
- }
-
- delete_post_meta( $post_id, self::META_PREFIX . $key );
- }
-
- /**
- * Re-apply a saved verification onto a freshly built deterministic channel.
- *
- * Returns the channel unchanged when there is no saved result or the saved
- * signature no longer matches (the content changed) — so the deterministic
- * score is shown and the channel can be re-verified.
- *
- * @param string $key Channel key ('seo'|'aeo'|'geo').
- * @param int $post_id Post ID.
- * @param array $channel Freshly built deterministic channel.
- * @return array
- */
- public static function restore( $key, $post_id, array $channel ) {
- $post_id = (int) $post_id;
- if ( $post_id <= 0 ) {
- return $channel;
- }
-
- $saved = get_post_meta( $post_id, self::META_PREFIX . $key, true );
- if ( ! is_array( $saved ) || empty( $saved['sig'] ) ) {
- return $channel;
- }
-
- if ( $saved['sig'] !== self::signature( $channel ) ) {
- return $channel; // Content changed — fall back to the deterministic score.
- }
-
- $channel['score'] = max( 0, min( 100, isset( $saved['score'] ) ? (int) $saved['score'] : 0 ) );
- $channel['grade'] = isset( $saved['grade'] ) ? (string) $saved['grade'] : ( isset( $channel['grade'] ) ? $channel['grade'] : '' );
- $channel['scored_by'] = 'ai';
-
- // Re-apply the saved per-criterion adjusted values (and derived status)
- // plus notes, keyed by criterion key.
- $notes_map = isset( $saved['notes'] ) && is_array( $saved['notes'] ) ? $saved['notes'] : [];
- $values_map = isset( $saved['values'] ) && is_array( $saved['values'] ) ? $saved['values'] : [];
- if ( ! empty( $channel['criteria'] ) && is_array( $channel['criteria'] ) ) {
- foreach ( $channel['criteria'] as $index => $criterion ) {
- $ckey = isset( $criterion['key'] ) ? (string) $criterion['key'] : '';
-
- $channel['criteria'][ $index ]['ai_notes'] = ( '' !== $ckey && isset( $notes_map[ $ckey ] ) && is_array( $notes_map[ $ckey ] ) ) ? $notes_map[ $ckey ] : [];
-
- if ( '' !== $ckey && empty( $criterion['locked'] ) && isset( $values_map[ $ckey ] ) ) {
- $value = max( 0, min( 100, (int) $values_map[ $ckey ] ) );
- $channel['criteria'][ $index ]['value'] = $value;
- $channel['criteria'][ $index ]['status'] = Grade::status( $value );
- }
- }
- }
-
- return $channel;
- }
-}
--- a/review-schema/app/AI/ArticleBodySync.php
+++ b/review-schema/app/AI/ArticleBodySync.php
@@ -0,0 +1,572 @@
+<?php
+/**
+ * Article Body Sync - keeps generated articleBody / wordCount in step with the post.
+ *
+ * articleBody is the current post content as plain text, capped at
+ * MAX_CHARS; wordCount is the word count of the full post. Both are set when
+ * schema is generated and refreshed on save_post — but only for fields the
+ * plugin itself wrote. Provenance lives in a per-post marker
+ * (MARKER_META_KEY): a hash of each generated field value. A field whose
+ * saved value no longer matches its hash was edited by the user and is never
+ * overwritten; records without a marker (saved before this class existed)
+ * are left untouched. Password-protected posts never get articleBody: it is
+ * omitted at generation and save, and removed on save_post when a post
+ * becomes protected (regardless of provenance). Nothing here runs at
+ * render time.
+ *
+ * @package RtrsAI
+ * @since 3.1.4
+ */
+
+namespace RtrsAI;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Generates and synchronizes article-family articleBody / wordCount values.
+ */
+class ArticleBodySync {
+
+ /**
+ * Maximum articleBody length, in characters.
+ *
+ * @var int
+ */
+ const MAX_CHARS = 2000;
+
+ /**
+ * Post meta holding the generated-value provenance marker.
+ *
+ * Shape: [ 'content' => md5( post_content ), 'nodes' => [ node_key => [ field => hash ] ] ].
+ *
+ * @var string
+ */
+ const MARKER_META_KEY = '_aise_article_sync';
+
+ /**
+ * Schema types whose articleBody / wordCount are managed.
+ *
+ * @var string[]
+ */
+ const ARTICLE_TYPES = [ 'Article', 'BlogPosting', 'NewsArticle', 'TechArticle' ];
+
+ /**
+ * Fields managed per article node.
+ *
+ * @var string[]
+ */
+ const FIELDS = [ 'articleBody', 'wordCount' ];
+
+ /**
+ * Plain-text cache for the latest post: post ID => [ content hash, text ].
+ *
+ * @var array
+ */
+ private static $text_cache = [];
+
+ /**
+ * Re-entrancy guard for the_content rendering.
+ *
+ * @var bool
+ */
+ private static $rendering = false;
+
+ /**
+ * Register hooks.
+ *
+ * @return void
+ */
+ public function register_hooks() {
+ // After SchemaRenderer::clear_schema_cache (priority 10).
+ add_action( 'save_post', [ $this, 'sync_post' ], 20, 2 );
+ }
+
+ /**
+ * Current post content as plain text (blocks rendered).
+ *
+ * Same steps ContentExtractor has always used for the AI body (before its
+ * word cap), plus a space after block-level closing tags so stripping
+ * does not glue words from adjacent blocks together. With
+ * $strip_shortcodes, shortcodes are removed before rendering, so their
+ * output (which may depend on the saving user) never reaches articleBody.
+ * Cached for the latest post and mode; returns '' when re-entered from
+ * inside the_content.
+ *
+ * @param WP_Post $post Post.
+ * @param bool $strip_shortcodes Remove shortcodes instead of rendering them.
+ *
+ * @return string
+ */
+ public static function get_plain_text( $post, $strip_shortcodes = false ) {
+ if ( ! $post instanceof WP_Post && ! ( is_object( $post ) && isset( $post->ID, $post->post_content ) ) ) {
+ return '';
+ }
+
+ $key = $post->ID . ( $strip_shortcodes ? ':s' : ':r' );
+ $hash = md5( (string) $post->post_content );
+ if ( isset( self::$text_cache[ $key ] ) && self::$text_cache[ $key ][0] === $hash ) {
+ return self::$text_cache[ $key ][1];
+ }
+
+ if ( self::$rendering ) {
+ return '';
+ }
+
+ $source = $strip_shortcodes ? strip_shortcodes( (string) $post->post_content ) : $post->post_content;
+
+ self::$rendering = true;
+ try {
+ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- "the_content" is a WP core filter; we apply it to render post content.
+ $content = apply_filters( 'the_content', $source );
+ } finally {
+ self::$rendering = false;
+ }
+
+ // Block-aware strip, entity decode and whitespace collapse (shared helper).
+ $content = RtrsHelpersFunctions::html_to_text( $content );
+
+ // Keep only the latest post: bounded memory during batch generation.
+ self::$text_cache = [ $key => [ $hash, $content ] ];
+
+ return $content;
+ }
+
+ /**
+ * Truncate text to a character limit, Unicode-safe.
+ *
+ * Cuts at the last whitespace when it falls within the final 20% of the
+ * limit; otherwise cuts hard, never separating a combining mark or
+ * zero-width joiner from the preceding character. Never exceeds $limit.
+ *
+ * @param string $text Plain text.
+ * @param int $limit Maximum characters.
+ *
+ * @return string
+ */
+ public static function truncate( $text, $limit = self::MAX_CHARS ) {
+ $text = (string) $text;
+ if ( mb_strlen( $text, 'UTF-8' ) <= $limit ) {
+ return $text;
+ }
+
+ $cut = mb_substr( $text, 0, $limit, 'UTF-8' );
+ $next = mb_substr( $text, $limit, 1, 'UTF-8' );
+
+ if ( preg_match( '/^[sp{Z}]/u', $next ) ) {
+ return rtrim( $cut );
+ }
+
+ if ( preg_match( '/^(.*)[sp{Z}]/su', $cut, $m ) && mb_strlen( $m[1], 'UTF-8' ) >= (int) floor( $limit * 0.8 ) ) {
+ return rtrim( $m[1] );
+ }
+
+ while ( '' !== $cut && ( preg_match( '/^[p{M}x{200C}x{200D}]/u', $next ) || preg_match( '/[x{200C}x{200D}]$/u', $cut ) ) ) {
+ $next = mb_substr( $cut, -1, 1, 'UTF-8' );
+ $cut = mb_substr( $cut, 0, -1, 'UTF-8' );
+ }
+
+ return $cut;
+ }
+
+ /**
+ * Count words, Unicode-aware.
+ *
+ * Splits on Unicode whitespace and counts tokens holding at least one
+ * letter or number, so punctuation-only tokens (—, ।) are not words and
+ * Bengali combining marks stay inside their word. Scripts written without
+ * spaces (e.g. CJK) count one word per unbroken run.
+ *
+ * @param string $text Plain text.
+ *
+ * @return int
+ */
+ public static function count_words( $text ) {
+ $tokens = preg_split( '/[sp{Z}]+/u', (string) $text, -1, PREG_SPLIT_NO_EMPTY );
+ if ( ! is_array( $tokens ) ) {
+ return 0;
+ }
+
+ $count = 0;
+ foreach ( $tokens as $token ) {
+ if ( preg_match( '/[p{L}p{N}]/u', $token ) ) {
+ ++$count;
+ }
+ }
+
+ return $count;
+ }
+
+ /**
+ * Set articleBody / wordCount on article nodes from the current post.
+ *
+ * Used at generation time. Leaves the schemas unchanged when the post
+ * has no renderable text.
+ *
+ * @param array $schemas Schema node list.
+ * @param int $post_id Post ID.
+ *
+ * @return array
+ */
+ public static function apply_to_schemas( $schemas, $post_id ) {
+ if ( ! is_array( $schemas ) ) {
+ return $schemas;
+ }
+
+ $post = get_post( absint( $post_id ) );
+ if ( self::is_protected( $post ) ) {
+ return self::omit_protected_body( $schemas );
+ }
+
+ $values = null;
+ foreach ( $schemas as $index => $schema ) {
+ if ( ! self::is_article( $schema ) ) {
+ continue;
+ }
+
+ $values = $values ?? self::build_values( $post );
+ if ( null === $values ) {
+ return $schemas;
+ }
+
+ $schemas[ $index ]['articleBody'] = $values['articleBody'];
+ $schemas[ $index ]['wordCount'] = $values['wordCount'];
+ }
+
+ return $schemas;
+ }
+
+ /**
+ * Record the article fields of just-saved generated schemas as generated.
+ *
+ * @param int $post_id Post ID.
+ * @param array $schemas Content schemas exactly as saved.
+ *
+ * @return void
+ */
+ public static function mark_generated( $post_id, $schemas ) {
+ $post_id = absint( $post_id );
+ $post = get_post( $post_id );
+ $nodes = [];
+
+ foreach ( (array) $schemas as $index => $schema ) {
+ if ( ! self::is_article( $schema ) ) {
+ continue;
+ }
+
+ $entry = [];
+ foreach ( self::FIELDS as $field ) {
+ if ( array_key_exists( $field, $schema ) ) {
+ $entry[ $field ] = self::hash( $schema[ $field ] );
+ }
+ }
+ if ( $entry ) {
+ $nodes[ self::node_key( $schema, $index ) ] = $entry;
+ }
+ }
+
+ self::save_marker( $post_id, $post ? md5( (string) $post->post_content ) : '', $nodes );
+ }
+
+ /**
+ * After an explicit edit, stop tracking every field the user changed.
+ *
+ * Fields still equal to their generated value stay tracked, so editing
+ * one property does not freeze the others.
+ *
+ * @param int $post_id Post ID.
+ * @param array $schemas Content schemas exactly as saved.
+ *
+ * @return void
+ */
+ public static function reconcile_after_edit( $post_id, $schemas ) {
+ $post_id = absint( $post_id );
+ $marker = self::get_marker( $post_id );
+ if ( ! $marker ) {
+ return;
+ }
+
+ $nodes = [];
+ foreach ( (array) $schemas as $index => $schema ) {
+ if ( ! self::is_article( $schema ) ) {
+ continue;
+ }
+
+ $key = self::node_key( $schema, $index );
+ $entry = [];
+ foreach ( $marker['nodes'][ $key ] ?? [] as $field => $hash ) {
+ if ( array_key_exists( $field, $schema ) && self::hash( $schema[ $field ] ) === $hash ) {
+ $entry[ $field ] = $hash;
+ }
+ }
+ if ( $entry ) {
+ $nodes[ $key ] = $entry;
+ }
+ }
+
+ self::save_marker( $post_id, $marker['content'], $nodes );
+ }
+
+ /**
+ * Forget the provenance marker (schema deleted).
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return void
+ */
+ public static function forget( $post_id ) {
+ delete_post_meta( absint( $post_id ), self::MARKER_META_KEY );
+ }
+
+ /**
+ * save_post callback: refresh generated fields when the content changed.
+ *
+ * @param int $post_id Post ID.
+ * @param WP_Post $post Post.
+ *
+ * @return void
+ */
+ public function sync_post( $post_id, $post = null ) {
+ $post_id = absint( $post_id );
+ if ( ! $post_id || wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
+ return;
+ }
+
+ $post = $post instanceof WP_Post ? $post : get_post( $post_id );
+ if ( self::is_protected( $post ) ) {
+ self::clear_protected_body( $post_id );
+ return;
+ }
+
+ $marker = self::get_marker( $post_id );
+ if ( ! $marker || empty( $marker['nodes'] ) ) {
+ return; // Nothing generated to refresh, or unknown provenance.
+ }
+
+ if ( ! $post ) {
+ return;
+ }
+
+ $content_hash = md5( (string) $post->post_content );
+ if ( $content_hash === $marker['content'] ) {
+ return;
+ }
+
+ $schemas = AIInit::normalizeSchemaData( get_post_meta( $post_id, AIInit::META_KEY, true ) );
+ if ( empty( $schemas ) ) {
+ self::forget( $post_id );
+ return;
+ }
+
+ $values = self::build_values( $post );
+ if ( null === $values ) {
+ return; // No renderable text (or re-entered); retry on the next save.
+ }
+
+ $changed = false;
+ $nodes = [];
+ foreach ( $schemas as $index => $schema ) {
+ if ( ! self::is_article( $schema ) ) {
+ continue;
+ }
+
+ $key = self::node_key( $schema, $index );
+ $entry = [];
+ foreach ( $marker['nodes'][ $key ] ?? [] as $field => $hash ) {
+ if ( ! array_key_exists( $field, $schema ) || self::hash( $schema[ $field ] ) !== $hash ) {
+ continue; // Edited outside the tracked flows — the user's value now.
+ }
+
+ if ( $schema[ $field ] !== $values[ $field ] ) {
+ $schemas[ $index ][ $field ] = $values[ $field ];
+ $changed = true;
+ }
+ $entry[ $field ] = self::hash( $values[ $field ] );
+ }
+ if ( $entry ) {
+ $nodes[ $key ] = $entry;
+ }
+ }
+
+ if ( $changed ) {
+ // wp_slash() counteracts the wp_unslash() inside update_post_meta().
+ update_post_meta( $post_id, AIInit::META_KEY, wp_slash( wp_json_encode( $schemas, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ) );
+ wp_cache_delete( "rtrs_ai_schemas_{$post_id}", 'rtrs_ai' );
+ }
+
+ self::save_marker( $post_id, $content_hash, $nodes );
+ }
+
+ /**
+ * Build the articleBody / wordCount values for a post.
+ *
+ * @param WP_Post|null $post Post.
+ *
+ * @return array|null [ 'articleBody' => string, 'wordCount' => int ], or null without
+ * text or for a password-protected post.
+ */
+ private static function build_values( $post ) {
+ // Never copy a password-protected post's text into public JSON-LD.
+ if ( ! $post || self::is_protected( $post ) ) {
+ return null;
+ }
+
+ // Shortcodes stripped: their output can depend on the saving user.
+ $text = self::get_plain_text( $post, true );
+ if ( '' === $text ) {
+ return null;
+ }
+
+ return [
+ 'articleBody' => self::truncate( $text ),
+ 'wordCount' => self::count_words( $text ),
+ ];
+ }
+
+ /**
+ * Whether a post is password-protected.
+ *
+ * Same rule as all public schema output: Functions::is_schema_protected().
+ *
+ * @param WP_Post|null $post Post.
+ *
+ * @return bool
+ */
+ public static function is_protected( $post ) {
+ return is_object( $post ) && RtrsHelpersFunctions::is_schema_protected( $post );
+ }
+
+ /**
+ * Drop articleBody from every article node.
+ *
+ * Applies regardless of provenance: a protected post's text — generated or
+ * hand-written — must not stay in public JSON-LD.
+ *
+ * @param array $schemas Schema node list.
+ *
+ * @return array
+ */
+ public static function omit_protected_body( $schemas ) {
+ if ( ! is_array( $schemas ) ) {
+ return $schemas;
+ }
+
+ foreach ( $schemas as $index => $schema ) {
+ if ( self::is_article( $schema ) && array_key_exists( 'articleBody', $schema ) ) {
+ unset( $schemas[ $index ]['articleBody'] );
+ }
+ }
+
+ return $schemas;
+ }
+
+ /**
+ * Remove articleBody from a password-protected post's saved AI schema.
+ *
+ * Runs whether or not a provenance marker exists, and stops tracking
+ * articleBody so a later unprotected save does not resurrect old text.
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return void
+ */
+ private static function clear_protected_body( $post_id ) {
+ $schemas = AIInit::normalizeSchemaData( get_post_meta( $post_id, AIInit::META_KEY, true ) );
+ if ( empty( $schemas ) ) {
+ return;
+ }
+
+ $cleaned = self::omit_protected_body( $schemas );
+ if ( $cleaned !== $schemas ) {
+ // wp_slash() counteracts the wp_unslash() inside update_post_meta().
+ update_post_meta( $post_id, AIInit::META_KEY, wp_slash( wp_json_encode( $cleaned, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ) );
+ wp_cache_delete( "rtrs_ai_schemas_{$post_id}", 'rtrs_ai' );
+ }
+
+ $marker = self::get_marker( $post_id );
+ if ( $marker ) {
+ $nodes = [];
+ foreach ( $marker['nodes'] as $key => $entry ) {
+ unset( $entry['articleBody'] );
+ if ( $entry ) {
+ $nodes[ $key ] = $entry;
+ }
+ }
+ self::save_marker( $post_id, $marker['content'], $nodes );
+ }
+ }
+
+ /**
+ * Whether a schema node is a managed article type.
+ *
+ * @param mixed $schema Schema node.
+ *
+ * @return bool
+ */
+ private static function is_article( $schema ) {
+ return is_array( $schema ) && (bool) array_intersect( (array) ( $schema['@type'] ?? [] ), self::ARTICLE_TYPES );
+ }
+
+ /**
+ * Stable key for a node: its @id, else its list position.
+ *
+ * @param array $schema Schema node.
+ * @param int|string $index List index.
+ *
+ * @return string
+ */
+ private static function node_key( $schema, $index ) {
+ return ( isset( $schema['@id'] ) && is_string( $schema['@id'] ) && '' !== $schema['@id'] ) ? 'id:' . $schema['@id'] : 'i:' . $index;
+ }
+
+ /**
+ * Type-sensitive value hash.
+ *
+ * @param mixed $value Field value.
+ *
+ * @return string
+ */
+ private static function hash( $value ) {
+ return md5( (string) wp_json_encode( $value ) );
+ }
+
+ /**
+ * Read a well-formed marker.
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return array|null
+ */
+ private static function get_marker( $post_id ) {
+ $marker = get_post_meta( $post_id, self::MARKER_META_KEY, true );
+ if ( ! is_array( $marker ) || ! isset( $marker['content'] ) || ! is_string( $marker['content'] ) || ! isset( $marker['nodes'] ) || ! is_array( $marker['nodes'] ) ) {
+ return null;
+ }
+
+ return $marker;
+ }
+
+ /**
+ * Store the marker, or delete it when nothing is tracked.
+ *
+ * @param int $post_id Post ID.
+ * @param string $content_hash md5 of the post content the values came from.
+ * @param array $nodes Tracked nodes.
+ *
+ * @return void
+ */
+ private static function save_marker( $post_id, $content_hash, $nodes ) {
+ if ( empty( $nodes ) ) {
+ self::forget( $post_id );
+ return;
+ }
+
+ update_post_meta(
+ $post_id,
+ self::MARKER_META_KEY,
+ [
+ 'content' => (string) $content_hash,
+ 'nodes' => $nodes,
+ ]
+ );
+ }
+}
--- a/review-schema/app/AI/ContentExtractor.php
+++ b/review-schema/app/AI/ContentExtractor.php
@@ -14,6 +14,7 @@
use RtrsHelpersFunctions;
use RtrsModulesReviewHelpersReviewFns;
+use RtrsModulesSchemaHelpersSchemaFns;
defined( 'ABSPATH' ) || exit;
@@ -43,7 +44,8 @@
* @return void
*/
public function set_post( $post ) {
- $this->post = $post;
+ // Password-protected: title and SEO meta only, never the body.
+ $this->post = Functions::schema_safe_post( $post );
}
/**
@@ -56,7 +58,8 @@
* @return array|WP_Error Structured payload array or WP_Error on failure.
*/
public function extract( $post_id ) {
- $this->post = get_post( $post_id );
+ // Password-protected: title and SEO meta only, never the body (see Functions::schema_safe_post()).
+ $this->post = Functions::schema_safe_post( get_post( $post_id ) );
if ( ! $this->post ) {
return new WP_Error( 'invalid_post', __( 'Post not found.', 'review-schema' ) );
@@ -96,11 +99,12 @@
'body' => $this->get_clean_body(),
'excerpt' => $this->get_excerpt(),
'post_type' => $this->post->post_type,
+ // Privacy-safe author: no login-revealing name or archive url, and
+ // no Gravatar URL (an email hash the schema does not need).
'author' => [
- 'name' => get_the_author_meta( 'display_name', $author_id ),
- 'bio' => get_the_author_meta( 'description', $author_id ),
- 'url' => get_author_posts_url( $author_id ),
- 'avatar' => get_avatar_url( $author_id, [ 'size' => 96 ] ),
+ 'name' => SchemaFns::get_author_schema_name( $author_id ),
+ 'bio' => get_the_author_meta( 'description', $author_id ),
+ 'url' => SchemaFns::get_author_schema_url( $author_id ),
],
'publish_date' => get_the_date( 'c', $this->post ),
'modified_date' => get_the_modified_date( 'c', $this->post ),
@@ -134,13 +138,17 @@
* Delegated via filter so Pro can provide full product data.
* Free version defaults to null (no product data extraction).
*/
- $product_data = apply_filters( 'rtrs_ai_extract_wc_product_data', null, $this->post );
+ // An installed Pro older than the paired version still calls extraction
+ // methods that now live in Pro; skip its product/course hooks.
+ $pro_outdated = RtrsControllersAdminProCompatibilityNotice::is_pro_outdated();
+
+ $product_data = $pro_outdated ? null : apply_filters( 'rtrs_ai_extract_wc_product_data', null, $this->post );
if ( $product_data ) {
$signals['wc_product'] = $product_data;
}
- $edd_data = apply_filters( 'rtrs_ai_extract_edd_product_data', null, $this->post );
+ $edd_data = $pro_outdated ? null : apply_filters( 'rtrs_ai_extract_edd_product_data', null, $this->post );
if ( $edd_data ) {
$signals['edd_product'] = $edd_data;
@@ -155,7 +163,7 @@
}
// Course data extraction — delegated to Pro via filter.
- $course_data = apply_filters( 'rtrs_ai_extract_course_data', null, $this->post );
+ $course_data = $pro_outdated ? null : apply_filters( 'rtrs_ai_extract_course_data', null, $this->post );
if ( $course_data ) {
$signals['tutor_course'] = $course_data;
@@ -240,7 +248,7 @@
'site_name' => get_bloginfo( 'name' ),
'site_url' => home_url( '/' ),
'site_logo' => $custom_logo_id ? wp_get_attachment_image_url( $custom_logo_id, 'full' ) : '',
- 'language' => get_locale(),
+ 'language' => SchemaFns::sanitize_bcp47_language( get_locale() ), // BCP 47, so the AI copies de-DE, not de_DE.
'breadcrumbs' => $this->build_breadcrumbs(),
'page_template' => get_page_template_slug( $this->post ) ?: 'default',
'is_front_page' => ( (int) get_option( 'page_on_front' ) === $this->post->ID ),
@@ -255,12 +263,13 @@
* @return string Cleaned body text.
*/
private function get_clean_body() {
- // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- "the_content" is a WP core filter; we apply it to render post content.
- $content = apply_filters( 'the_content', $this->post->post_content );
- $content = wp_strip_all_tags( $content );
- $content = html_entity_decode( $content, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
- $content = preg_replace( '/s+/', ' ', $content );
- $content = trim( $content );
+ // Password-protected: never render the body (builder filters may ignore the emptied copy).
+ if ( Functions::is_schema_protected( $this->post ) ) {
+ return '';
+ }
+
+ // Shared with ArticleBodySync so the_content renders once per request.
+ $content = ArticleBodySync::get_plain_text( $this->post );
$words = explode( ' ', $content );
@@ -280,14 +289,12 @@
* @return string Post excerpt.
*/
private function get_excerpt() {
- $excerpt = $this->post->post_excerpt
- ? $this->post->post_excerpt
- : wp_trim_words( wp_strip_all_tags( $this->post->post_content ), 55 );
-
- $excerpt = html_entity_decode( $excerpt, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
- $excerpt = preg_replace( '/s+/', ' ', $excerpt );
+ // Decode once, then strip tags (an encoded tag never survives as markup).
+ if ( $this->post->post_excerpt ) {
+ return Functions::schema_plain_text( $this->post->post_excerpt );
+ }
- return trim( $excerpt );
+ return wp_trim_words( Functions::schema_plain_text( $this->post->post_content ), 55, "u{2026}" );
}
/**
@@ -472,215 +479,6 @@
return null;
}
- /**
- * Extract Tutor LMS course data for schema generation.
- *
- * @return array|null Course data or null if not a Tutor course.
- */
- public function extract_tutor_course_data() {
- if ( ! function_exists( 'tutor_utils' ) ) {
- return null;
- }
-
- $post_id = $this->post->ID;
- $utils = tutor_utils();
-
- // Duration.
- $duration = get_post_meta( $post_id, '_course_duration', true );
-
- // Level.
- $level = get_post_meta( $post_id, '_tutor_course_level', true );
-
- // Price.
- $price_type = get_post_meta( $post_id, '_tutor_course_price_type', true );
- $price = '';
- $currency = '';
-
- if ( 'paid' === $price_type ) {
- $product_id = get_post_meta( $post_id, '_tutor_course_product_id', true );
-
- if ( $product_id && function_exists( 'wc_get_product' ) ) {
- $product = wc_get_product( $product_id );
- $price = $product ? $product->get_price() : '';
- $currency = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD';
- }
-
- if ( ! $price ) {
- $price = get_post_meta( $post_id, 'tutor_course_price', true );
- }
- }
-
- // Instructor.
- $instructors = $utils->get_instructors_by_course( $post_id );
- $instructor = [];
-
- if ( ! empty( $instructors ) && is_array( $instructors ) ) {
- $inst = is_object( $instructors[0] ) ? $instructors[0] : null;
-
- if ( $inst ) {
- $instructor = [
- 'name' => $inst->display_name ?? '',
- 'url' => get_author_posts_url( $inst->ID ?? 0 ),
- ];
- }
- }
-
- // Rating — check review-schema's own ratings first, then Tutor native.
- $rating = [];
-
- if ( Functions::isEnableReviewByPostType( $this->post->post_type ) ) {
- $avg = ReviewFns::getAvgRatings( $post_id, true );
- $total = ReviewFns::getTotalRatings( $post_id );
-
- if ( $avg && $total ) {
- $rating = [
- 'average_rating' => (float) $avg,
- 'review_count' => (int) $total,
- 'rating_count' => (int) $total,
- ];
- }
- } else {
- $rating_data = $utils->get_course_rating( $post_id );
-
- if ( $rating_data && ! empty( $rating_data->rating_avg ) && $rating_data->rating_avg > 0 ) {
- $rating = [
- 'average_rating' => (float) $rating_data->rating_avg,
- 'rating_count' => (int) ( $rating_data->rating_count ?? 0 ),
- ];
- }
- }
-
- // Enrolled students.
- $enrolled = method_exists( $utils, 'count_enrolled_users_by_course' )
- ? (int) $utils->count_enrolled_users_by_course( $post_id )
- : 0;
-
- // Course benefits / requirements.
- $benefits = get_post_meta( $post_id, '_tutor_course_benefits', true );
- $requirements = get_post_meta( $post_id, '_tutor_course_requirements', true );
-
- return array_filter(
- [
- 'duration' => $duration,
- 'level' => $level,
- 'price_type' => $price_type,
- 'price' => $price,
- 'currency' => $currency,
- 'instructor' => $instructor,
- 'rating' => $rating,
- 'enrolled' => $enrolled,
- 'benefits' => $benefits,
- 'requirements' => $requirements,
- ]
- );
- }
-
- /**
- * Extract LearnPress course data for schema generation.
- *
- * @return array|null Course data or null if not a LearnPress course.
- */
- public function extract_learnpress_course_data() {
- if ( ! function_exists( 'learn_press_get_course' ) ) {
- return null;
- }
-
- $post_id = $this->post->ID;
-
- // Price.
- $price = '';
- $currency = '';
-
- $lp_course = learn_press_get_course( $post_id );
-
- if ( $lp_course && method_exists( $lp_course, 'get_price' ) ) {
- $price = $lp_course->get_price();
- }
-
- if ( ! $price ) {
- $price = get_post_meta( $post_id, '_lp_regular_price', true )
- ?: get_post_meta( $post_id, '_lp_price', true );
- }
-
- $price_type = ( $price && (float) $price > 0 ) ? 'paid' : 'free';
-
- if ( 'paid' === $price_type ) {
- $currency = function_exists( 'learn_press_get_currency' ) ? learn_press_get_currency() : 'USD';
- }
-
- $sale_price = get_post_meta( $post_id, '_lp_sale_price', true );
-
- // Level.
- $level = get_post_meta( $post_id, '_lp_level', true );
-
- // Duration.
- $duration = get_post_meta( $post_id, '_lp_duration', true );
-
- // Instructor.
- $author_id = $this->post->post_author;
- $instructor = [];
-
- if ( $author_id ) {
- $instructor = [
- 'name' => get_the_author_meta( 'display_name', $author_id ),
- 'url' => get_author_posts_url( $author_id ),
- ];
- }
-
- // Rating — check review-schema's own ratings first, then LearnPress native.
- $rating = [];
-
- if ( Functions::isEnableReviewByPostType( $this->post->post_type ) ) {
- $avg = ReviewFns::getAvgRatings( $post_id, true );
- $total = ReviewFns::getTotalRatings( $post_id );
-
- if ( $avg && $total ) {
- $rating = [
- 'average_rating' => (float) $avg,
- 'review_count' => (int) $total,
- 'rating_count' => (int) $total,
- ];
- }
- } else {
- // Fallback to LearnPress native ratings (learnpress-course-review plugin).
- global $wpdb;
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Aggregating native ratings via JOIN; caching is not applicable per-request.
- $result = $wpdb->get_row(
- $wpdb->prepare(
- "SELECT COUNT(cm.meta_value) AS rating_count, AVG(cm.meta_value) AS rating_avg
- FROM {$wpdb->comments} c
- INNER JOIN {$wpdb->commentmeta} cm ON c.comment_ID = cm.comment_id
- WHERE c.comment_post_ID = %d
- AND c.comment_approved = 1
- AND cm.meta_key = '_lpr_rating'",
- $post_id
- )
- );
-
- if ( $result && $result->rating_count > 0 && (float) $result->rating_avg > 0 ) {
- $rating = [
- 'average_rating' => round( (float) $result->rating_avg, 2 ),
- 'review_count' => (int) $result->rating_count,
- 'rating_count' => (int) $result->rating_count,
- ];
- }
- }
-
- return array_filter(
- [
- 'duration' => $duration,
- 'level' => $level,
- 'price_type' => $price_type,
- 'price' => $price,
- 'sale_price' => $sale_price,
- 'currency' => $currency,
- 'instructor' => $instructor,
- 'rating' => $rating,
- ]
- );
- }
-
private function extract_embedded_media() {
$content = $this->post->post_content;
$media = [];
@@ -937,398 +735,6 @@
return $count;
}
- public function extract_woocommerce_product_data() {
- if ( ! function_exists( 'wc_get_product' ) ) {
- return null;
- }
-
- $product = wc_get_product( $this->post->ID );
-
- if ( ! $product ) {
- return null;
- }
-
- $currency = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD';
-
- $pricing = array_filter(
- [
- 'currency' => $currency,
- 'price' => $product->get_price(),
- 'regular_price' => $product->get_regular_price(),
- 'sale_price' => $product->get_sale_price(),
- 'on_sale' => $product->is_on_sale(),
- ]
- );
-
- $sale_to = $product->get_date_on_sale_to();
-
- if ( $sale_to ) {
- $pricing['sale_date_to'] = $sale_to->date( 'c' );
- }
-
- $variation_count = 0;
-
- if ( $product->is_type( 'variable' ) && method_exists( $product, 'get_variation_prices' ) ) {
- $prices = $product->get_variation_prices( true );
-
- if ( ! empty( $prices['price'] ) ) {
- $pricing['min_price'] = min( $prices['price'] );
- $pricing['max_price'] = max( $prices['price'] );
- }
-
- $variation_count = count( $product->get_children() );
- }
-
- $stock_status = $product->get_stock_status();
- $availability_map = [
- 'instock' => 'https://schema.org/InStock',
- 'outofstock' => 'https://schema.org/OutOfStock',
- 'onbackorder' => 'https://schema.org/BackOrder',
- ];
-
- $sku = $product->get_sku();
- // Fallback to product ID if SKU is not set.
- if ( empty( $sku ) ) {
- $sku = (string) $product->get_id();
- }
- $gtin = method_exists( $product, 'get_global_unique_id' ) ? $product->get_global_unique_id() : '';
-
- $brand = '';
- $brand_taxonomies = [ 'product_brand', 'pwb-brand', 'pa_brand' ];
-
- foreach ( $brand_taxonomies as $tax ) {
- if ( taxonomy_exists( $tax ) ) {
- $terms = get_the_terms( $this->post->ID, $tax );
-
- if ( $terms && ! is_wp_error( $terms ) ) {
- $brand = $terms[0]->name;
- break;
- }
- }
- }
-
- $attributes = [];
-
- foreach ( $product->get_attributes() as $attr ) {
- if ( is_object( $attr ) && method_exists( $attr, 'get_name' ) ) {
- $name = wc_attribute_label( $attr->get_name() );
- $values = $attr->is_taxonomy()
- ? wc_get_product_terms( $this->post->ID, $attr->get_name(), [ 'fields' => 'names' ] )
- : $attr->get_options();
-
- $attributes[ $name ] = is_array( $values ) ? implode( ', ', $values ) : (string) $values;
- }
- }
-
- $categories = [];
- $cat_terms = get_the_terms( $this->post->ID, 'product_cat' );
-
- if ( $cat_terms && ! is_wp_error( $cat_terms ) ) {
- foreach ( $cat_terms as $term ) {
- $categories[] = $term->name;
- }
- }
-
- $reviews = [];
-
- if ( $product->get_reviews_allowed() ) {
- $reviews = [
- 'average_rating' => (float) $product->get_average_rating(),
- 'review_count' => (int) $product->get_review_count(),
- 'rating_counts' => $product->get_rating_counts(),
- ];
-
- $review_comments = get_comments(
- [
- 'post_id' => $this->post->ID,
- 'type' => 'review',
- 'status' => 'approve',
- 'number' => 2,
- // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Necessary meta query for plugin feature.
- 'meta_key' => 'rating',
- 'orderby' => 'meta_value_num',
- 'order' => 'DESC',
- ]
- );
-
- $review_items = [];
-
- foreach ( $review_comments as $comment ) {
- $rating = (int) get_comment_meta( $comment->comment_ID, 'rating', true );
-
- $review_items[] = array_filter(
- [
- 'author' => $comment->comment_author,
- 'date' => get_comment_date( 'c', $comment ),
- 'rating' => $rating ?: null,
- 'text' => wp_strip_all_tags( $comment->comment_content ),
- ]
- );
- }
-
- if ( ! empty( $review_items ) ) {
- $reviews['items'] = $review_items;
- }
- }
-
- $gallery = [];
-
- foreach ( $product->get_gallery_image_ids() as $img_id ) {
- $src = wp_get_attachment_image_src( $img_id, 'full' );
-
- if ( $src ) {
- $gallery[] = [
- 'url' => $src[0],
- 'width' => $src[1],
- 'height' => $src[2],
- ];
- }
- }
-
- $weight = $product->get_weight();
- $dimensions = array_filter(
- [
- 'length' => $product->get_length(),
- 'width' => $product->get_width(),
- 'height' => $product->get_height(),
- ]
- );
-
- $weight_unit = function_exists( 'get_option' ) ? get_option( 'woocommerce_weight_unit', 'kg' ) : 'kg';
- $dim_unit = function_exists( 'get_option' ) ? get_option( 'woocommerce_dimension_unit', 'cm' ) : 'cm';
-
- $prices_include_tax = 'yes' === get_option( 'woocommerce_prices_include_tax', 'no' );
-
- return array_filter(
- [
- 'product_type' => $product->get_type(),
- 'pricing' => $pricing,
- 'stock_status' => $stock_status,
- 'availability' => $availability_map[ $stock_status ] ?? '',
- 'sku' => $sku,
- 'gtin' => $gtin,
- 'brand' => $brand,
- 'categories' => $categories,
- 'attributes' => $attributes,
- 'reviews' => $reviews,
- 'gallery' => $gallery,
- 'weight' => $weight ? $weight . ' ' . $weight_unit : '',
- 'dimensions' => ! empty( $dimensions ) ? $dimensions : null,
- 'dimension_unit' => ! empty( $dimensions ) ? $dim_unit : '',
- 'is_virtual' => $product->is_virtual(),
- 'is_downloadable' => $product->is_downloadable(),
- 'total_sales' => (int) $product->get_total_sales(),
- 'variation_count' => $variation_count,
- 'variations' => $this->extract_wc_variations( $product, $currency, $availability_map ),
- 'prices_include_tax' => $prices_include_tax,
- ]
- );
- }
-
- /**
- * Extract WooCommerce product variation details for ProductGroup schema.
- *
- * Only extracts when review-schema-pro is active.
- *
- * @since 1.0.0
- *
- * @param WC_Product $product The parent product.
- * @param string $currency Store currency code.
- * @param array $availability_map Stock status to schema.org URL map.
- *
- * @return array|null Variation data or null.
- */
- public function extract_wc_variations( $product, $currency, $availability_map ) {
- if ( ! $product->is_type( 'variable' ) ) {
- return null;
- }
-
- $children = $product->get_children();
- $varies_by = [];
- $variants = [];
-
- foreach ( $children as $variation_id ) {
- $variation = wc_get_product( $variation_id );
-
- if ( ! $variation || ! $variation->exists() ) {
- continue;
- }
-
- $attrs = $variation->get_variation_attributes();
- $variant_attrs = [];
-
- foreach ( $attrs as $attr_key => $attr_value ) {
- $taxonomy = str_replace( 'attribute_', '', $attr_key );
- $label = wc_attribute_label( $taxonomy, $product );
-
- if ( $attr_value && taxonomy_exists( $taxonomy ) ) {
- $term = get_term_by( 'slug', $attr_value, $taxonomy );
- $attr_value = $term ? $term->name : $attr_value;
- }
-
- $variant_attrs[ $label ] = $attr_value ?: __( 'Any', 'review-schema' );
-
- if ( ! in_array( $label, $varies_by, true ) ) {
- $varies_by[] = $label;
- }
- }
-
- $stock = $variation->get_stock_status();
- $img_id = $variation->get_image_id();
- $image = $img_id ? wp_get_attachment_image_url( $img_id, 'full' ) : '';
-
- $variants[] = array_filter(
- [
- 'variation_id' => $variation_id,
- 'sku' => $variation->get_sku(),
- 'name' => $variation->get_name(),
- 'description' => $variation->get_description(),
- 'attributes' => $variant_attrs,
- 'price' => $variation->get_price(),
- 'regular_price' => $variation->get_regular_price(),
- 'sale_price' => $variation->get_sale_price(),
- 'currency' => $currency,
- 'stock_status' => $stock,
- 'availability' => $availability_map[ $stock ] ?? '',
- 'image' => $image,
- ]
- );
- }
-
- if ( empty( $variants ) ) {
- return null;
- }
-
- return [
- 'varies_by' => $varies_by,
- 'items' => $variants,
- ];
- }
-
- /**
- * Extract Easy Digital Downloads product data.
- *
- * @since 1.0.0
- *
- * @return array|null EDD product data or null.
- */
- public function extract_edd_product_data() {
- if ( ! function_exists( 'edd_get_download' ) ) {
- return null;
- }
-
- if ( 'download' !== $this->post->post_type ) {
- return null;
- }
-
- $download = edd_get_download( $this->post->ID );
-
- if ( ! $download ) {
- return null;
- }
-
- $currency = function_exists( 'edd_get_currency' )
- ? edd_get_currency()
- : ( function_exists( 'edd_get_option' ) ? edd_get_option( 'currency', 'USD' ) : 'USD' );
- $price = $download->get_price();
-
- $categories = [];
- $cat_terms = get_the_terms( $this->post->ID, 'download_category' );
-
- if ( $cat_terms && ! is_wp_error( $cat_terms ) ) {
- foreach ( $cat_terms as $term ) {
- $categories[] = $term->name;
- }
- }
-
- $tags = [];
- $tag_terms = get_the_terms( $this->post->ID, 'download_tag' );
-
- if ( $tag_terms && ! is_wp_error( $tag_terms ) ) {
- foreach ( $tag_terms as $term ) {
- $tags[] = $term->name;
- }
- }
-
- $sku = $download->get_sku();
- // Fallback to download ID if SKU is not set.
- if ( empty( $sku ) ) {
- $sku = (string) $download->get_ID();
- }
-
- $data = [
- 'product_type' => $download->has_variable_prices() ? 'variable' : 'simple',
- 'pricing' => [
- 'currency' => $currency,
- 'price' => $price,
- ],
- 'sku' => $sku,
- 'categories' => $categories,
- 'tags' => $tags,
- 'sales' => (int) $download->get_sales(),
- 'is_free' => ! (bool) $price,
- 'is_bundled' => $download->is_bundled_download(),
- ];
-
- /** Include variable pricing details when pro is active. */
- $variations = $this->extract_edd_variations( $download, $currency );
-
- if ( $variations ) {
- $data['variations'] = $variations;
- }
-
- return array_filter( $data );
- }
-
- /**
- * Extract EDD variable pricing tiers for product offers schema.
- *
- * EDD "variations" are pricing tiers (e.g. Personal, Business, Developer),
- * not actual product variants — they become multiple Offer objects.
- *
- * @since 1.0.0
- *
- * @param EDD_Download $download The EDD download object.
- * @param string $currency Store currency code.
- *
- * @return array|null Variable pricing data or null.
- */
- public function extract_edd_variations( $download, $currency ) {
- if ( ! $download->has_variable_prices() ) {
- return null;
- }
-
- $prices = $download->get_prices();
- $variants = [];
-
- if ( empty( $prices ) || ! is_array( $prices ) ) {
- return null;
- }
-
- foreach ( $prices as $price_id => $price_option ) {
- $name = $price_option['name'] ?? '';
- $amount = isset( $price_option['amount'] ) ? $price_option['amount'] : 0;
-
- $variants[] = array_filter(
- [
- 'price_id' => $price_id,
- 'name' => $name,
- 'price' => $amount,
- 'currency' => $currency,
- ]
- );
- }
-
- if ( empty( $variants ) ) {
- return null;
- }
-
- return [
- 'varies_by' => [ 'price_option' ],
- 'items' => $variants,
- ];
- }
-
private function build_breadcrumbs() {
$crumbs = [
[
@@ -1557,7 +963,8 @@
* @return array|WP_Error Compact payload or WP_Error.
*/
public function extract_for_classification( $post_id ) {
- $this->post = get_post( $post_id );
+ // Password-protected: title and SEO meta only, never the body (see Functions::schema_safe_post()).
+ $this->post = Functions::schema_safe_post( get_post( $post_id ) );
if ( ! $this->post ) {
return new WP_Error( 'invalid_post', __( 'Post not found.', 'review-schema' ) );
--- a/review-schema/app/AI/RestApi.php
+++ b/review-schema/app/AI/RestApi.php
@@ -299,6 +299,23 @@
);
}
+ // An installed Pro older than the paired version lacks the Product, Course and
+ // SoftwareApplication extraction that moved to Pro: ask for a Pro update.
+ $moved_types = array_merge( AIInit::SOFTWARE_APPLICATION_TYPES, [ 'Product', 'ProductGroup', 'Course' ] );
+ if ( in_array( $classification['primary_type'], $moved_types, true ) && function_exists( 'rtrsp' )
+ && ( RtrsControllersAdminProCompatibilityNotice::is_pro_outdated() || ( in_array( $classification['primary_type'], AIInit::SOFTWARE_APPLICATION_TYPES, true ) && ! has_filter( 'rtrs_ai_fill_software_application_schema' ) ) ) ) {
+ return new WP_Error(
+ 'pro_update_required',
+ sprintf(
+ /* translators: 1: schema type, 2: minimum SchemaEngine AI Pro version */
+ __( '%1$s schema generation requires SchemaEngine AI Pro %2$s or later. Please update the Pro plugin.', 'review-schema' ),
+ $classification['primary_type'],
+ RtrsControllersAdminProCompatibilityNotice::MIN_PRO_VERSION
+ ),
+ [ 'status' => 403 ]
+ );
+ }
+
// Filter out pro-gated secondary types when free.
if ( ! function_exists( 'rtrsp' ) ) {
$classification['secondary_types'] = array_values(
@@ -349,7 +366,7 @@
&& ! in_array( 'FAQPage', $classification['secondary_types'], true );
$schema_extractor = new SchemaExtractor();
- $extract_options = [];
+ $extract_options = [ 'post_id' => $post_id ];
$faq_count = $request->get_param( 'faq_count' );
if ( $faq_count ) {
$extract_options['faq_count'] = (int) $faq_count;
@@ -635,7 +652,7 @@
}
return rest_ensure_response(
- self::persist_content_schemas( $post_id, $schemas, $body['schema_type'] ?? '', $body['schema_types'] ?? [], $body['confidence'] ?? 0 )
+ self::persist_content_schemas( $post_id, $schemas, $body['schema_type'] ?? '', $body['schema_types'] ?? [], $body['confidence'] ?? 0, true )
);
}
@@ -654,9 +671,11 @@
* @param string $schema_type Primary schema type.
* @param array|string $schema_types All schema types.
* @param int|string $confidence Classification confidence.
+ * @param bool $is_generated True only for the unmodified generated payload;
+ * false (edits) keeps user-changed article fields untracked.
* @return array Response data.
*/
- public static function persist_content_schemas( $post_id, array $schemas, $schema_type = '', $schema_types = [], $confidence = 0 ) {
+ public static function persist_content_schemas( $post_id, array $schemas, $schema_type = '', $schema_types = [], $confidence = 0, $is_generated = false ) {
$post_id = absint( $post_id );
// Filter out global node types before saving (safety net).
@@ -701,12 +720,24 @@
)
);
+ // A password-protected post's text never goes into public JSON-LD.
+ if ( ArticleBodySync::is_protected( get_post( $post_id ) ) ) {
+ $content_schemas = ArticleBodySync::omit_protected_body( $content_schemas );
+ }
+
// Save content-only schemas as JSON string to post meta.
// wp_slash() counteracts the wp_unslash() inside update_post_meta(),
// which would otherwise strip JSON escape backslashes (e.g. " → ") and corrupt the JSON.
update_post_meta( $post_id, AIInit::META_KEY, wp_slash( wp_json_encode( $content_schemas, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ) );
wp_cache_delete( "rtrs_ai_schemas_{$post_id}", 'rtrs_ai' );
+ // Provenance for articleBody / wordCount refresh on later post updates.
+ if ( $is_generated ) {
+ ArticleBodySync::mark_generated( $post_id, $content_schemas );
+ } else {
+ ArticleBodySync::reconcile_after_edit( $post_id, $content_schemas );
+ }
+
// Sync FAQPage data: for Elementor pages append widget only,
// for other editors save to dedicated meta for frontend rendering.
if ( $faq_main_entity ) {
@@ -950,6 +981,7 @@
$post_id = $request->get_param( 'post_id' );
delete_post_meta( $post_id, AIInit::META_KEY );
+ ArticleBodySync::forget( $post_id );
delete_post_meta( $post_id, AIInit::TYPE_META_KEY );
delete_post_meta( $post_id, AIInit::CONFIDENCE_META_KEY );
delete_post_meta( $post_id, '_rtrs_faqpage_data' );
--- a/review-schema/app/AI/SchemaClassifier.php
+++ b/review-schema/app/AI/SchemaClassifier.php
@@ -1,151 +1,43 @@
<?php
/**
- * Schema Classifier - Step 1 of the two-step AI approach.
+ * Deprecated stub: the AI schema classifier moved to SchemaEngine AI Pro.
+ *
+ * The free plugin ships no classifier. Auto-detect is provided by Pro through
+ * the `rtrs_ai_auto_classify` filter (RtrspAISchemaClassifier). This empty
+ * class only exists so an older Pro that still calls `new RtrsAISchemaClassifier()`
+ * gets an "update Pro" error instead of a fatal; it makes no AI request.
*
* @package RtrsAI
- * @since 1.0.0
+ * @deprecated 3.1.4 Use RtrspAISchemaClassifier (Pro).
*/
namespace RtrsAI;
defined( 'ABSPATH' ) || exit;
+/**
+ * Class SchemaClassifier
+ *
+ * @deprecated 3.1.4
+ */
class SchemaClassifier {
/**
- * @var AIClient
- */
- private $ai_client;
-
- const SUPPORTED_TYPES = [
- 'Article',
- 'TechArticle',
- 'NewsArticle',
- 'BlogPosting',
- 'FAQPage',
- 'HowTo',
- 'Product',
- 'Recipe',
- 'Event',
- 'LocalBusiness',
- 'Restaurant',
- 'VideoObject',
- 'AudioObject',
- 'Person',
- 'Course',
- 'Service',
- 'QAPage',
- 'AboutPage',
- 'ContactPage',
- 'Movie',
- 'Mosque',
- 'Church',
- 'HinduTemple',
- 'BuddhistTemple',
- 'TouristAttraction',
- 'ProfilePage',
- 'MedicalWebPage',
- 'Book',
- 'RealEstateListing',
- 'JobPosting',
- 'SoftwareApplication',
- 'ImageObject',
- 'SpecialAnnouncement',
- 'VacationRental',
- 'Vehicle',
- 'TVSeries',
- 'PodcastEpisode',
- 'DiscussionForumPosting',
- 'Dataset',
- 'TaxiService',
- 'WebPage',
- ];
-
- public function __construct() {
- $this->ai_client = new AIClient();
- }
-
- /**
- * @param $compact_payload
- *
- * @return array|WP_Error
- */
- public function classify( $compact_payload ) {
- $system_prompt = $this->build_system_prompt();
- $user_prompt = $this->build_user_prompt( $compact_payload );
-
- $result = $this->ai_client->complete( $system_prompt, $user_prompt );
-
- if ( is_wp_error( $result ) ) {
- return $result;
- }
-
- return $this->normalize_result( $result );
- }
-
- /**
- * @return string
- */
- private function build_system_prompt() {
- $types = implode( ', ', self::SUPPORTED_TYPES );
-
- return "You are a structured data (Schema.org) expert. Your job is to analyze content signals and determine the most appropriate schema type(s) for a web page.nn"
- . "Supported schema types: {$types}nn"
- . "Rules:n"
- . "1. Return a JSON object with "primary_type", "secondary_types" (array), and "confidence" (0-100).n"
- . "2. "primary_type" is the single best schema type.n"
- . "3. "secondary_types" are additional schemas that should also be applied.n"
- . "4. "confidence" reflects how certain you are about the primary type (0-100).n"
- . "5. Do NOT include BreadcrumbList, WebPage, WebSite, or Organization in secondary_types — these are generated separately as global schemas.n"
- . "6. If the content is a standard blog post, use "BlogPosting" (not "Article").n"
- . "7. If FAQ patterns are detected, include "FAQPage" (as primary or secondary).n"
- . "8. If unsure, default to "WebPage" with lower confidence.nn"
- . "Respond ONLY with valid JSON. No explanations.nn"
- . "Example output:n"
- . "{n"
- . " "primary_type": "BlogPosting",n"
- . " "secondary_types": ["FAQPage"],n"
- . " "confidence": 85,n"
- . " "reasoning": "Blog post with FAQ section detected"n"
- . "}";
- }
-
- /**
- * @param $payload
+ * Always refuse: classification is a Pro feature that needs an updated Pro.
*
- * @return string
- */
- private function build_user_prompt( $payload ) {
- $data = wp_json_encode( $payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
-
- return "Analyze this content and classify the schema type: