wrappers -> /v2/translate/html.
* 5. Restore protected spans, save to memory.
*
* @package TranslatePlus
*/
namespace TranslatePlus\Translation;
use TranslatePlus\Api\ApiException;
use TranslatePlus\Api\Client;
defined( 'ABSPATH' ) || exit;
class Translator {
/** Max characters per packed HTML request (well under the 200k API limit for latency). */
const HTML_PACK_CHARS = 40000;
/** Max characters of a single plain segment sent through the batch endpoint. */
const PLAIN_MAX_CHARS = 4500;
/** Placeholders that must survive translation untouched. */
const PLACEHOLDERS = array(
'/%%[a-z0-9_]+%%/i', // Yoast variables.
'/%[a-z_]+(?:\([^)]*\))?%/i', // Rank Math variables.
'/%(?:\d+\$)?[sdfu]/', // sprintf.
'/\{\{?[a-z0-9_.\-]+\}?\}/i', // {name} / {{name}}.
'/\[[a-z0-9_\-]+(?:\s[^\]]*)?\/?\]|\[\/[a-z0-9_\-]+\]/i', // Shortcodes.
);
/** @var Client */
private $api;
/** @var array{api_chars:int, memory_chars:int, segments:int} */
private $stats = array(
'api_chars' => 0,
'memory_chars' => 0,
'segments' => 0,
);
public function __construct( Client $api ) {
$this->api = $api;
}
/** @var string[] Keys left untranslated by the last offline call. */
private $missing = array();
public function stats(): array {
return $this->stats;
}
/** @return string[] */
public function missing(): array {
return $this->missing;
}
/**
* Whether a segment contains something worth translating.
*/
public static function is_translatable( string $text ): bool {
$plain = trim( html_entity_decode( wp_strip_all_tags( $text ), ENT_QUOTES, 'UTF-8' ) );
return '' !== $plain && (bool) preg_match( '/\p{L}/u', $plain ) && ! preg_match( '#^(https?:)?//\S+$#i', $plain );
}
public static function is_html( string $text ): bool {
return (bool) preg_match( '/<[a-z!\/][^>]*>/i', $text );
}
/**
* Translate keyed segments.
*
* @param array
$segments key => source text.
* @param array $opts memory (bool, default true); offline (bool): never call the API,
* untranslated segments keep the source text and are reported by missing().
* @return array key => translation (untranslatable segments returned as-is).
* @throws ApiException When the API fails in a non-recoverable way.
*/
public function translate( array $segments, string $source, string $target, array $opts = array() ): array {
$use_memory = $opts['memory'] ?? true;
$out = array();
$todo = array(); // unique source text => true.
foreach ( $segments as $key => $text ) {
$text = (string) $text;
if ( ! self::is_translatable( $text ) ) {
$out[ $key ] = $text;
continue;
}
$todo[ $text ] = true;
}
$this->stats['segments'] += count( $todo );
$found = $use_memory ? Memory::lookup( array_keys( $todo ), $source, $target ) : array();
foreach ( $found as $text => $tr ) {
$this->stats['memory_chars'] += mb_strlen( $text );
unset( $todo[ $text ] );
}
$this->missing = array();
$offline = ! empty( $opts['offline'] );
$fresh = $todo && ! $offline ? $this->translate_uncached( array_keys( $todo ), $source, $target ) : array();
if ( $fresh ) {
Memory::save( $fresh, $source, $target );
}
$all = $found + $fresh;
foreach ( $segments as $key => $text ) {
if ( ! array_key_exists( $key, $out ) ) {
if ( ! isset( $all[ (string) $text ] ) ) {
$this->missing[] = (string) $key;
}
$out[ $key ] = $all[ (string) $text ] ?? (string) $text;
}
}
return $out;
}
/**
* Characters that would be sent to the API (memory hits excluded).
*
* @param string[] $texts Source texts.
*/
public static function estimate( array $texts, string $source, string $target ): int {
$unique = array();
foreach ( $texts as $t ) {
if ( self::is_translatable( (string) $t ) ) {
$unique[ (string) $t ] = true;
}
}
$hits = Memory::lookup( array_keys( $unique ), $source, $target );
$chars = 0;
foreach ( array_keys( $unique ) as $t ) {
if ( ! isset( $hits[ $t ] ) ) {
$chars += mb_strlen( wp_strip_all_tags( $t ) );
}
}
return $chars;
}
/**
* @param string[] $texts Unique source texts.
* @return array source => translation.
*/
private function translate_uncached( array $texts, string $source, string $target ): array {
$plain = array();
$html = array();
$prep = array(); // source => tokenised text.
$maps = array(); // source => token values.
foreach ( $texts as $t ) {
list( $p, $maps[ $t ] ) = self::tokenize( $t, $target );
$prep[ $t ] = $p;
if ( self::is_html( $p ) || mb_strlen( $p ) > self::PLAIN_MAX_CHARS ) {
$html[] = $t;
} else {
$plain[] = $t;
}
}
$out = array();
if ( $plain ) {
$inputs = array_map(
static function ( $t ) use ( $prep ) {
return $prep[ $t ];
},
$plain
);
$this->stats['api_chars'] += array_sum( array_map( 'mb_strlen', $inputs ) );
$results = $this->api->translate_batch( $inputs, $source, $target );
foreach ( $plain as $i => $t ) {
if ( isset( $results[ $i ] ) && '' !== $results[ $i ] ) {
$out[ $t ] = self::detokenize( $results[ $i ], $maps[ $t ] );
}
}
}
foreach ( $this->pack( $html, $prep ) as $pack ) {
foreach ( $this->translate_pack( $pack, $prep, $source, $target ) as $t => $tr ) {
$out[ $t ] = self::detokenize( $tr, $maps[ $t ] );
}
}
return $out;
}
/**
* Group HTML segments into request-sized packs.
*
* @return array
*/
private function pack( array $texts, array $prep ): array {
$packs = array();
$cur = array();
$size = 0;
foreach ( $texts as $t ) {
$len = mb_strlen( $prep[ $t ] ) + 32;
if ( $cur && $size + $len > self::HTML_PACK_CHARS ) {
$packs[] = $cur;
$cur = array();
$size = 0;
}
$cur[] = $t;
$size += $len;
}
if ( $cur ) {
$packs[] = $cur;
}
return $packs;
}
/**
* @param string[] $pack Source texts.
* @return array
*/
private function translate_pack( array $pack, array $prep, string $source, string $target ): array {
$html = '';
foreach ( $pack as $i => $t ) {
$html .= '' . $prep[ $t ] . '
';
}
if ( mb_strlen( $html ) > Client::MAX_HTML_CHARS ) {
return $this->translate_oversized( $pack, $prep, $source, $target );
}
$this->stats['api_chars'] += mb_strlen( $html );
$result = $this->api->translate_html( $html, $source, $target );
$parsed = self::unpack( $result, count( $pack ) );
if ( null === $parsed ) {
// Markers were not preserved; fall back to one request per segment.
if ( count( $pack ) === 1 ) {
return array( $pack[0] => $result );
}
$out = array();
foreach ( $pack as $t ) {
$out += $this->translate_pack( array( $t ), $prep, $source, $target );
}
return $out;
}
$out = array();
foreach ( $pack as $i => $t ) {
$out[ $t ] = $parsed[ $i ];
}
return $out;
}
/**
* A single segment larger than the API limit: split on block-level boundaries.
*/
private function translate_oversized( array $pack, array $prep, string $source, string $target ): array {
$out = array();
foreach ( $pack as $t ) {
$chunks = preg_split( '#(?<=| |||||\n\n)#i', $prep[ $t ] );
$buf = '';
$parts = array();
foreach ( $chunks as $c ) {
if ( mb_strlen( $buf . $c ) > Client::MAX_HTML_CHARS - 1000 && '' !== $buf ) {
$parts[] = $buf;
$buf = '';
}
$buf .= $c;
}
$parts[] = $buf;
$tr = '';
foreach ( $parts as $p ) {
$this->stats['api_chars'] += mb_strlen( $p );
$tr .= $this->api->translate_html( $p, $source, $target );
}
$out[ $t ] = $tr;
}
return $out;
}
/**
* Split packed output back into segments. Returns null when markers are broken.
*
* @return string[]|null
*/
public static function unpack( string $html, int $count ): ?array {
$pieces = preg_split( '//', $html, -1, PREG_SPLIT_DELIM_CAPTURE );
if ( ! $pieces || count( $pieces ) !== 1 + 2 * $count ) {
return null;
}
$out = array();
for ( $i = 1; $i < count( $pieces ); $i += 2 ) {
$idx = (int) $pieces[ $i ];
$body = $pieces[ $i + 1 ];
$body = preg_replace( '#
\s*$#', '', rtrim( $body ), 1 );
if ( $idx !== ( $i - 1 ) / 2 ) {
return null;
}
$out[ $idx ] = $body;
}
return $out;
}
/**
* Replace glossary terms and placeholders with empty marker elements.
*
* @return array{0:string, 1:string[]} Tokenised text and the token values.
*/
public static function tokenize( string $text, string $target, ?array $glossary = null ): array {
$map = array();
$wrap = static function ( string $value ) use ( &$map ): string {
$map[] = $value;
return '