,
, etc.)
* we trust it's pure HTML. Otherwise, we look for the first HTML start tag
* and strip everything before it when the prefix looks like reasoning.
*
* @param string $raw Raw AI HTML response.
* @return string Cleaned HTML.
*/
function aime_strip_thinking_from_html( string $raw ): string {
$raw = trim( $raw );
if ( '' === $raw ) {
return $raw;
}
// First, apply the JSON-aware stripper (handles think tags,
// safety lines, preambles, JSON-prefix cleanup).
$raw = aime_strip_thinking_text( $raw );
if ( '' === $raw ) {
return $raw;
}
// If the response starts with an HTML tag or placeholder tag, it's already clean HTML.
$first_char = $raw[0];
if ( '<' === $first_char || '[' === $first_char ) {
return $raw;
}
// Otherwise, look for the first HTML opening tag or placeholder. If found and the prefix
// looks like natural-language reasoning, drop the prefix.
$html_start = preg_match( '/(?:<\s*(?:p|h[1-6]|div|section|article|ul|ol|li|blockquote|figure|table|nav|header|footer|main|aside|strong|em|br|!--)\b|\[\[AIME_)/i', $raw, $m, PREG_OFFSET_CAPTURE );
if ( $html_start && isset( $m[0][1] ) && $m[0][1] > 0 ) {
$prefix = substr( $raw, 0, $m[0][1] );
// Only strip if the prefix contains natural-language reasoning
// (at least 20 chars of word characters — avoids stripping short
// legitimate prefixes).
$letters = preg_replace( '/[^a-zA-Z]/', '', $prefix );
if ( strlen( $letters ) >= 20 ) {
$raw = substr( $raw, $m[0][1] );
$raw = ltrim( $raw );
}
}
// Strip safety-classification lines from HTML output (e.g. trailing
// "User Safety: safe" line, or ones embedded anywhere in the body).
$raw = preg_replace( '/^[ \t]*(?:User\s+Safety|Safety|Harm\s+Category|Harm_Policy|Category|Severity)[ \t]*:[ \t]*[^\n\r]*[\n\r]?/im', '', $raw );
$raw = preg_replace( '/(?:\n|\r)[ \t]*(?:User\s+Safety|Safety|Harm\s+Category|Harm_Policy|Category|Severity)[ \t]*:[ \t]*[^\n\r]*/i', '', $raw );
$raw = preg_replace( '/[\s\n\r]*(?:User\s+Safety|Safety|Harm\s+Category|Harm_Policy|Category|Severity)[ \t]*:[ \t]*[^\n\r<]*$/i', '', $raw );
$raw = trim( $raw );
return $raw;
}
/**
* Per-IP rate limiting for public endpoints.
*
* Uses a transient counter keyed on a hash of the visitor IP and the action
* name. Returns true while the caller is within the limit, false once the
* limit for the current window is exceeded.
*
* @param string $action Unique action key (e.g. 'subscribe').
* @param int $limit Max requests allowed per window.
* @param int $window Window length in seconds.
* @return bool True if allowed, false if rate-limited.
*/
function aime_check_ip_rate_limit( string $action, int $limit, int $window ): bool {
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
if ( '' === $ip ) {
// No IP available (CLI/cron context) — do not rate-limit.
return true;
}
/**
* Filter the rate limit for a public action.
*
* @param int $limit Max requests per window.
* @param string $action Action key.
* @param int $window Window in seconds.
*/
$limit = (int) apply_filters( 'aime_ip_rate_limit', $limit, $action, $window );
if ( $limit <= 0 ) {
// A non-positive limit disables rate limiting for this action.
return true;
}
$key = 'aime_rl_' . md5( $action . '|' . $ip );
$count = (int) get_transient( $key );
if ( $count >= $limit ) {
return false;
}
if ( 0 === $count ) {
set_transient( $key, 1, max( 1, $window ) );
} else {
// Increment without resetting the window (transient TTL persists).
$count++;
$updated = false;
if ( wp_using_ext_object_cache() ) {
$updated = wp_cache_set( $key, $count, 'transient', max( 1, $window ) );
} else {
$updated = update_option( '_transient_' . $key, $count, false );
}
if ( ! $updated ) {
set_transient( $key, $count, max( 1, $window ) );
}
}
return true;
}
/**
* Extra tags article bodies need on top of $allowedposttags.
*
* kses still enforces wp_allowed_protocols() on src/srcset, so javascript:
* and data: URLs are rejected; srcdoc and every on* handler stay disallowed.
*
* @return array Tag => attribute map.
*/
function aime_embed_kses_tags(): array {
$common = array(
'class' => true,
'id' => true,
'style' => true,
'title' => true,
);
return array(
'iframe' => array_merge(
$common,
array(
'src' => true,
'width' => true,
'height' => true,
'name' => true,
'allow' => true,
'allowfullscreen' => true,
'frameborder' => true,
'scrolling' => true,
'loading' => true,
'referrerpolicy' => true,
'sandbox' => true,
)
),
'video' => array_merge(
$common,
array(
'src' => true,
'poster' => true,
'width' => true,
'height' => true,
'controls' => true,
'preload' => true,
'autoplay' => true,
'loop' => true,
'muted' => true,
'playsinline' => true,
)
),
'audio' => array_merge(
$common,
array(
'src' => true,
'controls' => true,
'preload' => true,
'autoplay' => true,
'loop' => true,
'muted' => true,
)
),
'source' => array(
'src' => true,
'srcset' => true,
'type' => true,
'media' => true,
'sizes' => true,
),
'track' => array(
'src' => true,
'kind' => true,
'srclang' => true,
'label' => true,
'default' => true,
),
'picture' => $common,
);
}
/**
* Allowed HTML for article bodies.
*
* wp_kses_post()'s $allowedposttags has no iframe/video/audio/picture, so
* oEmbed players and self-hosted media are destroyed on every save and on
* every AI round trip. This adds them back.
*
* @return array Tag => attribute map for wp_kses().
*/
function aime_allowed_article_html(): array {
$tags = array_merge( wp_kses_allowed_html( 'post' ), aime_embed_kses_tags() );
/**
* Filter the allowed HTML for AI Marketing Expert article bodies.
*
* @param array $tags Tag => attribute map.
*/
return apply_filters( 'aime_allowed_article_html', $tags );
}
/**
* Sanitize article HTML without destroying embedded media.
*
* Drop-in replacement for wp_kses_post() on article bodies. Applies kses
* unconditionally — no unfiltered_html bypass — because this content passes
* through AI models and must not be trusted even when an administrator
* submits it.
*
* @param string $content Raw HTML.
*/
function aime_kses_article( $content ): string {
if ( ! is_string( $content ) || '' === $content ) {
return '';
}
return wp_kses( $content, aime_allowed_article_html() );
}
/**
* Widen the core post allowlist while our own content is being saved.
*
* Hooked only around wp_insert_post()/wp_update_post() calls that write an
* already-sanitized article body — see aime_allow_embeds_during_save(). Without
* it, core's content_save_pre kses pass (active for any user or cron run
* without unfiltered_html) strips the embeds back out.
*
* @param array $tags Allowed tags.
* @param string $context Allowlist context.
* @return array
*/
function aime_filter_kses_allowed_html( $tags, $context ): array {
if ( 'post' !== $context || ! is_array( $tags ) ) {
return (array) $tags;
}
return array_merge( $tags, aime_embed_kses_tags() );
}
/**
* Run a post-writing callback with embeds allowed through core kses.
*
* @param callable $callback Receives no arguments.
* @return mixed Callback return value.
*/
function aime_allow_embeds_during_save( callable $callback ) {
add_filter( 'wp_kses_allowed_html', 'aime_filter_kses_allowed_html', 10, 2 );
try {
return $callback();
} finally {
remove_filter( 'wp_kses_allowed_html', 'aime_filter_kses_allowed_html', 10 );
}
}
function aime_parse_ai_json( string $raw ): ?array {
$raw = trim( $raw );
// Stage 0 — Strip thinking / reasoning prefix text.
// Many models output chain-of-thought reasoning before JSON.
// Remove everything before the first plausible JSON start.
$raw = aime_strip_thinking_text( $raw );
// Stage 1 — Direct decode.
$decoded = json_decode( $raw, true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
return $decoded;
}
// Stage 2 — Extract from fenced code block.
if ( preg_match( '/```(?:json)?\s*([\s\S]*?)```/', $raw, $m ) ) {
$decoded = json_decode( trim( $m[1] ), true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
return $decoded;
}
}
// Stage 2.5 — GLOBAL FALLBACK: Find first valid JSON by scanning for
// { or [ and attempting parse from every position. This catches ANY
// reasoning model output pattern without needing to know specific prefixes.
// Works for unknown future models and custom reasoning formats.
$first_brace = strpos( $raw, '{' );
$first_bracket = strpos( $raw, '[' );
if ( false !== $first_brace || false !== $first_bracket ) {
// Try every position where JSON might start, earliest first.
$positions = array_filter( array( $first_brace, $first_bracket ), function ( $pos ) {
return false !== $pos;
} );
sort( $positions );
foreach ( $positions as $try_pos ) {
$candidate = substr( $raw, $try_pos );
$decoded = json_decode( $candidate, true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) && ! empty( $decoded ) ) {
return $decoded;
}
}
}
// Stage 3 — Brace / bracket matching.
$openers = array(
array( '{', '}' ),
array( '[', ']' ),
);
foreach ( $openers as list( $open, $close ) ) {
$start = strpos( $raw, $open );
while ( $start !== false ) {
$depth = 0;
$in_string = false;
$escape = false;
$len = strlen( $raw );
for ( $i = $start; $i < $len; $i++ ) {
$ch = $raw[ $i ];
if ( $escape ) {
$escape = false;
continue;
}
if ( '\\' === $ch && $in_string ) {
$escape = true;
continue;
}
if ( '"' === $ch ) {
$in_string = ! $in_string;
continue;
}
if ( $in_string ) {
continue;
}
if ( $ch === $open ) {
$depth++;
} elseif ( $ch === $close ) {
$depth--;
if ( 0 === $depth ) {
$candidate = substr( $raw, $start, $i - $start + 1 );
$decoded = json_decode( $candidate, true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
return $decoded;
}
// Stage 3b — Repair: thinking models may inject reasoning
// text inside the JSON object before actual key-value pairs.
// Find each valid-looking JSON key and try building JSON from there.
if ( '{' === $open && preg_match_all( '/"([a-z_][a-z0-9_]{0,30})"\s*:/i', $candidate, $keys, PREG_OFFSET_CAPTURE ) ) {
foreach ( $keys[0] as $km ) {
$repair_pos = $km[1];
if ( $repair_pos <= 1 ) {
continue; // Already tried the full candidate.
}
$repaired = '{ ' . substr( $candidate, $repair_pos );
$decoded = json_decode( $repaired, true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
return $decoded;
}
}
}
break;
}
}
}
$start = strpos( $raw, $open, $start + 1 );
}
}
// Stage 4 — Fix unescaped newlines inside JSON string values.
if ( preg_match( '/[\[{][\s\S]*[\]}]/', $raw, $m ) ) {
$fixed = preg_replace_callback(
'/"((?:[^"\\\\]|\\\\.)*?)"/',
function ( $match ) {
$inner = $match[1];
$inner = str_replace(
array( "\r\n", "\r", "\n", "\t" ),
array( '\\n', '\\n', '\\n', '\\t' ),
$inner
);
return '"' . $inner . '"';
},
$m[0]
);
if ( $fixed ) {
$decoded = json_decode( $fixed, true );
if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) {
return $decoded;
}
}
}
return null;
}
/**
* UTF-8 and multibyte-aware word counter.
*
* str_word_count() in PHP only understands ASCII/Latin characters, returning 0
* for non-Latin languages (Bengali, Hindi, Arabic, Cyrillic, Greek, CJK, etc.).
* This helper calculates the accurate word count across all languages while
* preserving full compatibility with English/Latin text.
*
* @param string $text Source text (HTML will be stripped).
* @return int Word count.
*/
function aime_count_words( string $text ): int {
$text = trim( wp_strip_all_tags( $text ) );
if ( '' === $text ) {
return 0;
}
$ascii_count = str_word_count( $text );
$words = preg_split( '/[\s\p{Z}\p{P}]+/u', $text, -1, PREG_SPLIT_NO_EMPTY );
$unicode_count = is_array( $words ) ? count( $words ) : 0;
return max( $ascii_count, $unicode_count );
}