success = false; $result->errors = array( 'Empty response from AI' ); return $result; } $response = trim( $response ); $result->looksLikeJson = 1 === preg_match( '/^(?:```[ \t]*[a-z]*\s*)?\{|\{\s*"/i', $response ); $parsed = self::tryDirectJsonParse( $response ); if ( null !== $parsed ) { $result->strategy = 'direct_json'; return self::extractContent( $parsed, $expectedTypes, $result, $options ); } $parsed = self::tryExtractFromCodeBlock( $response ); if ( null !== $parsed ) { $result->strategy = 'code_block_extraction'; return self::extractContent( $parsed, $expectedTypes, $result, $options ); } $parsed = self::tryExtractJsonObject( $response ); if ( null !== $parsed ) { $result->strategy = 'json_object_extraction'; return self::extractContent( $parsed, $expectedTypes, $result, $options ); } $result->success = false; $result->errors = array( 'Failed to parse AI response in any format' ); return $result; } private static function tryDirectJsonParse( string $response ): ?array { if ( strlen( $response ) === 0 || $response[0] !== '{' ) { return null; } return self::decodeObject( $response ); } private static function tryExtractFromCodeBlock( string $response ): ?array { $cleaned = preg_replace( '/^```json?\s*\n?/i', '', $response ); $cleaned = preg_replace( '/\n?```\s*$/i', '', $cleaned ); $cleaned = trim( $cleaned ); if ( $cleaned === $response ) { return null; } return self::decodeObject( $cleaned ); } /** * Decodes a JSON object, tolerating raw control characters inside string values. * * Models often put a literal newline inside a value (the description prompt * asks for one after each block tag), which strict JSON rejects. Escaping * every raw C0 control character (0x00-0x1F) inside strings changes no * meaning, so it is retried once. */ private static function decodeObject( string $json ): ?array { $decoded = json_decode( $json, true ); if ( JSON_ERROR_CTRL_CHAR === json_last_error() ) { $decoded = json_decode( self::escapeControlCharsInStrings( $json ), true ); } if ( JSON_ERROR_NONE === json_last_error() && is_array( $decoded ) ) { return $decoded; } return null; } private static function escapeControlCharsInStrings( string $json ): string { $length = strlen( $json ); $out = ''; $inString = false; $escaped = false; $short = array( "\x08" => '\\b', "\t" => '\\t', "\n" => '\\n', "\x0c" => '\\f', "\r" => '\\r', ); for ( $i = 0; $i < $length; $i++ ) { $char = $json[ $i ]; if ( $inString ) { if ( $escaped ) { $escaped = false; } elseif ( '\\' === $char ) { $escaped = true; } elseif ( '"' === $char ) { $inString = false; } elseif ( ord( $char ) < 0x20 ) { $char = $short[ $char ] ?? sprintf( '\\u%04x', ord( $char ) ); } } elseif ( '"' === $char ) { $inString = true; } $out .= $char; } return $out; } /** * Decodes the first balanced top-level JSON object found in prose. * * The scan is string-aware, so braces and escaped quotes inside string * values do not count. A `{` whose object never closes means the answer * was cut off, and nothing nested inside it is trusted, so the scan * stops there. A balanced `{...}` that is not a usable object (an empty * `{}` in the prose, say) is skipped. */ private static function tryExtractJsonObject( string $response ): ?array { $length = strlen( $response ); $offset = 0; while ( $offset < $length ) { $start = strpos( $response, '{', $offset ); if ( false === $start ) { return null; } $end = self::findObjectEnd( $response, $start ); if ( null === $end ) { return null; } $decoded = self::decodeObject( substr( $response, $start, $end - $start + 1 ) ); if ( null !== $decoded && ! empty( $decoded ) ) { return $decoded; } $offset = $end + 1; } return null; } /** * Returns the offset of the brace that closes the object opened at $start, or null when it never closes. */ private static function findObjectEnd( string $text, int $start ): ?int { $length = strlen( $text ); $depth = 0; $inString = false; $escaped = false; for ( $i = $start; $i < $length; $i++ ) { $char = $text[ $i ]; if ( $inString ) { if ( $escaped ) { $escaped = false; } elseif ( '\\' === $char ) { $escaped = true; } elseif ( '"' === $char ) { $inString = false; } continue; } if ( '"' === $char ) { $inString = true; } elseif ( '{' === $char ) { ++$depth; } elseif ( '}' === $char ) { --$depth; if ( 0 === $depth ) { return $i; } } } return null; } private static function extractContent( array $parsed, array $expectedTypes, ParseResult $result, array $options = array() ): ParseResult { $keyMappings = array( 'short_description' => array( 'short_description', 'short', 'summary' ), 'description' => array( 'description', 'long_description', 'full_description', 'full' ), 'tags' => array( 'tags', 'tag_list', 'keywords' ), ); foreach ( $expectedTypes as $type ) { $keys = $keyMappings[ $type ] ?? array( $type ); $normalized = self::findNormalizedValue( $parsed, $keys, $type, $options ); if ( '' !== $normalized ) { $result->content[ $type ] = $normalized; } else { $result->errors[] = "Missing content for: {$type}"; } } $result->success = ! empty( $expectedTypes ) && empty( $result->errors ); return $result; } /** * Returns the first alias key whose value is still non-empty after normalisation, or ''. * * Selecting before normalising would stop at a value such as "[]" that * normalises to nothing and never try the next alias. */ private static function findNormalizedValue( array $data, array $keys, string $type, array $options ): string { foreach ( $keys as $key ) { if ( ! array_key_exists( $key, $data ) ) { continue; } $value = $data[ $key ]; if ( is_array( $value ) ) { $value = implode( ', ', array_map( 'trim', $value ) ); } $value = trim( (string) $value ); if ( empty( $value ) ) { continue; } $normalized = self::normalizeContent( $value, $type, $options ); if ( '' !== $normalized ) { return $normalized; } } return ''; } public static function normalizeContent( string $content, string $type, array $options = array() ): string { $content = trim( $content ); if ( $type === 'tags' ) { return self::normalizeTags( $content ); } return self::normalizeDescription( $content, $options ); } private static function normalizeDescription( string $content, array $options = array() ): string { $content = preg_replace( '/^\s*```[a-zA-Z]*\s*\n?/', '', $content ); $content = preg_replace( '/\n?\s*```\s*$/', '', $content ); if ( self::isPlainOutput( $options ) ) { return PlainTextSanitizer::sanitize( $content ); } $content = PromptFormatter::formatAiResponseForWordPress( $content ); return trim( $content ); } private static function isPlainOutput( array $options ): bool { return ( $options['outputFormat'] ?? 'html' ) === 'plain'; } private static function normalizeTags( string $content ): string { $content = trim( $content ); $content = trim( $content, '[]' ); $content = str_replace( array( '"', "'" ), '', $content ); $content = wp_strip_all_tags( $content ); $content = str_replace( array( "\r\n", "\r", "\n", ';' ), ',', $content ); $parts = array_filter( array_map( 'trim', explode( ',', $content ) ) ); $cleanParts = array(); foreach ( $parts as $part ) { $part = preg_replace( '/[#*_`]/', '', $part ); $part = preg_replace( '/^tags:\s*/i', '', $part ); $part = trim( $part ); if ( ! empty( $part ) && strlen( $part ) <= 100 ) { $cleanParts[] = $part; } } return implode( ', ', $cleanParts ); } public static function parseTags( string $rawTags, int $maxCount = 5 ): array { $normalized = self::normalizeTags( $rawTags ); $tags = array_filter( array_map( 'trim', explode( ',', $normalized ) ) ); $validTags = array(); foreach ( $tags as $tag ) { if ( ! preg_match( '/[<>{}()\[\]\/\\\\]/', $tag ) && strlen( $tag ) <= 100 ) { $validTags[] = $tag; } } return array_slice( $validTags, 0, $maxCount ); } } class ParseResult { public bool $success = false; public array $content = array(); public array $errors = array(); public string $strategy = ''; /** * True when the answer was shaped like a JSON object, whether or not it * decoded: it starts with "{", alone or right after a code fence, or it * holds a quoted key after a "{" anywhere, as an object cut off after a * preamble does. A fenced answer with no object in it is not. A * single-type caller may keep an answer as plain text only when this is * false. */ public bool $looksLikeJson = false; }