*/
public static function prefetch_segments($html, $lang): array
{
$default = AI_Lang::default();
if ($default === null || !is_string($html) || $html === '' || strtolower((string) $lang) === strtolower((string) $default)) {
return [];
}
$texts = [];
// , meta description, og:description, og:image:alt, post title (same source as inject_dom)
try {
$doc = new \DOMDocument();
$internalErrors = libxml_use_internal_errors(true);
$doc->loadHTML('' . self::ensureUtf8($html), LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
libxml_use_internal_errors($internalErrors);
$texts = self::collectMetaTexts($doc, new \DOMXPath($doc));
} catch (\Throwable $e) {
$texts = [];
}
// Twitter Card tags (same pattern as translateTwitterCards)
$twitterNames = ['twitter:text:title', 'twitter:title', 'twitter:description', 'twitter:image:alt'];
$names = implode('|', array_map(function ($n) { return preg_quote($n, '#'); }, $twitterNames));
if (preg_match_all('#]*>#i', $html, $twitterMatches) && !empty($twitterMatches[1])) {
foreach ($twitterMatches[1] as $raw) {
$decoded = html_entity_decode($raw, ENT_QUOTES, 'UTF-8');
if (trim($decoded) !== '') {
$texts[] = $decoded;
}
}
}
// JSON-LD (same collector as translateJsonLd)
if (preg_match_all('##is', $html, $ldBlocks) && !empty($ldBlocks[1])) {
foreach ($ldBlocks[1] as $raw) {
$json = json_decode($raw, true);
if (is_array($json)) {
self::collectJsonLdTexts($json, $texts);
}
}
}
return self::buildMetaSegments($texts, $lang, 'pf');
}
private static function batchTranslateMeta(array $texts, $default, $lang): void
{
if (empty($texts) || !is_string($default) || !is_string($lang)
|| $default === '' || $lang === '' || strtolower($lang) === strtolower($default)) {
return;
}
$segments = self::buildMetaSegments($texts, $lang, 's');
if (empty($segments)) {
return;
}
$plan = ['segments' => $segments];
$ctx = ['website_context' => self::get_website_context()];
$res = AI_Batch::translate_plan($plan, $default, $lang, $ctx);
$segs = isset($res['segments']) && is_array($res['segments']) ? $res['segments'] : [];
foreach ($segments as $seg) {
$id = $seg['id'];
$origText = $seg['text'];
$translated = isset($segs[$id]) ? trim((string) $segs[$id]) : '';
if ($translated !== '') {
self::$metaTranslationCache[$lang . '|' . md5($origText)] = $translated;
}
}
}
/**
* Gather all meta/SEO texts from the DOM that may need translation.
* Used to pre-populate the translation cache in a single batch call.
*
* @param \DOMDocument $doc
* @param \DOMXPath $xpath
* @return string[]
*/
private static function collectMetaTexts(\DOMDocument $doc, \DOMXPath $xpath): array
{
$texts = [];
$titleNode = $doc->getElementsByTagName('title')->item(0);
if ($titleNode) {
$t = trim((string) $titleNode->textContent);
if ($t !== '') {
$texts[] = $t;
}
}
$desc = self::computeMetaDescription();
if ($desc !== '') {
$texts[] = $desc;
}
$metaDescNodes = $xpath->query('//head/meta[translate(@name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="description"]');
if ($metaDescNodes && $metaDescNodes->length > 0) {
$item = $metaDescNodes->item(0);
if ($item instanceof \DOMElement) {
$c = trim((string) $item->getAttribute('content'));
if ($c !== '') {
$texts[] = $c;
}
}
}
$ogDescNodes = $xpath->query('//meta[translate(@property, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="og:description"]');
if ($ogDescNodes && $ogDescNodes->length > 0) {
$item = $ogDescNodes->item(0);
if ($item instanceof \DOMElement) {
$c = trim((string) $item->getAttribute('content'));
if ($c !== '') {
$texts[] = $c;
}
}
}
$ogAltNodes = $xpath->query('//meta[translate(@property, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="og:image:alt"]');
if ($ogAltNodes && $ogAltNodes->length > 0) {
$item = $ogAltNodes->item(0);
if ($item instanceof \DOMElement) {
$c = trim((string) $item->getAttribute('content'));
if ($c !== '') {
$texts[] = $c;
}
}
}
if (function_exists('is_singular') && is_singular()) {
$postId = get_queried_object_id();
if ($postId) {
$postTitle = (string) get_the_title($postId);
if ($postTitle !== '') {
$texts[] = $postTitle;
}
}
}
return $texts;
}
/**
* Inject hreflang alternate links into .
*
* @param \DOMDocument $doc
* @param \DOMXPath $xpath
* @param \DOMElement $head
* @param string $current
* @param string $default
* @return void
*/
private static function injectHreflang($doc, $xpath, $head, $current, $default)
{
// Remove all existing hreflang alternate links to ensure clean injection
// This prevents conflicts with incorrectly generated hreflang tags from other sources
$links = $xpath->query('//head/link[@rel="alternate" and @hreflang]');
if ($links) {
foreach ($links as $lnk) {
if ($lnk instanceof \DOMElement && $lnk->parentNode) {
$lnk->parentNode->removeChild($lnk);
}
}
}
$enabled = AI_Translate_Core::enabled_languages();
$detectable = AI_Translate_Core::detectable_languages();
$langs = array_values(array_unique(array_merge($enabled, $detectable)));
if (is_string($default) && $default !== '' && !in_array($default, $langs, true)) {
$langs[] = $default;
}
$currentAbs = self::currentPageUrlAbsolute();
$defaultUrl = '';
// Determine post_id for singular pages to enable slug translation
$post_id = 0;
if (is_singular()) {
$post_id = get_queried_object_id();
}
foreach ($langs as $lc) {
$lc = sanitize_key((string) $lc);
// Build URL with translated slug if available
$href = self::buildHreflangUrl($currentAbs, $lc, $default, $post_id);
if ($href === '') {
continue;
}
if ($lc === $default) {
$defaultUrl = $href;
}
$el = $doc->createElement('link');
$el->setAttribute('rel', 'alternate');
$el->setAttribute('hreflang', $lc);
$el->setAttribute('href', esc_url($href));
$head->appendChild($doc->createTextNode("\n"));
$head->appendChild($el);
}
// x-default equals default language URL
if (is_string($default) && $default !== '' ) {
if ($defaultUrl === '') {
$defaultUrl = self::buildHreflangUrl($currentAbs, $default, $default, $post_id);
}
if ($defaultUrl !== '') {
$el = $doc->createElement('link');
$el->setAttribute('rel', 'alternate');
$el->setAttribute('hreflang', 'x-default');
$el->setAttribute('href', esc_url($defaultUrl));
$head->appendChild($doc->createTextNode("\n"));
$head->appendChild($el);
$head->appendChild($doc->createTextNode("\n"));
}
}
}
/**
* Build hreflang URL with translated slug for a given language.
*
* @param string $currentUrl
* @param string $targetLang
* @param string $default
* @param int $post_id
* @return string
*/
private static function buildHreflangUrl($currentUrl, $targetLang, $default, $post_id)
{
// For homepage
if (is_front_page() || is_home()) {
if (strtolower($targetLang) === strtolower($default)) {
return home_url('/');
}
return home_url('/' . $targetLang . '/');
}
// For singular posts/pages with slug translation
if ($post_id > 0 && function_exists('ai_translate_build_translated_path')) {
$path = ai_translate_build_translated_path((int) $post_id, $targetLang, $default, '/');
if ($path !== null && $path !== '') {
return home_url($path);
}
}
// Fallback: use basic rewrite (language prefix only)
$path = AI_URL::rewrite_single_href($currentUrl, $targetLang, $default);
if (!is_string($path) || $path === '') {
return '';
}
return home_url($path);
}
/**
* Return the translated URL for a post and language (same URL as hreflang uses).
* Use this for warm cache, crawlers, or any code that needs the canonical translated URL.
*
* @param int $post_id Post ID (0 = homepage).
* @param string $lang Language code.
* @return string Full URL or empty string on failure.
*/
public static function get_translated_url($post_id, $lang)
{
$lang = sanitize_key((string) $lang);
$default = AI_Lang::default();
if ($default === null || $default === '') {
return '';
}
$front_page_id = (int) get_option('page_on_front');
if ($front_page_id > 0 && (int) $post_id === $front_page_id) {
if (strtolower($lang) === strtolower($default)) {
return home_url('/');
}
return home_url('/' . $lang . '/');
}
if ((int) $post_id === 0) {
if (strtolower($lang) === strtolower($default)) {
return home_url('/');
}
return home_url('/' . $lang . '/');
}
// 404 page: use a non-existent path to trigger a 404 response
if ((int) $post_id === -1) {
return home_url('/' . $lang . '/ait-404-cache-warm/');
}
if (function_exists('ai_translate_build_translated_path')) {
$path = ai_translate_build_translated_path((int) $post_id, $lang, $default, '/');
if ($path !== null && $path !== '') {
return home_url($path);
}
}
$currentUrl = get_permalink((int) $post_id);
if (!$currentUrl) {
return '';
}
$path = AI_URL::rewrite_single_href($currentUrl, $lang, $default);
if (!is_string($path) || $path === '') {
return '';
}
return home_url($path);
}
/**
* Determine if a given Open Graph property is missing.
*
* @param \DOMXPath $xpath
* @param string $prop
* @return bool
*/
private static function isOgMissing($xpath, $prop)
{
// Search entire document, not just . DOMDocument may move OG tags from
// Jetpack/Yoast/RankMath to when placeholder s break structure.
$q = sprintf('//meta[translate(@property, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="%s"]', strtolower($prop));
$nodes = $xpath->query($q);
return !($nodes && $nodes->length > 0);
}
/**
* Truncate a UTF-8 string at character boundary.
*
* @param string $text
* @param int $max
* @param string $suffix
* @return string
*/
private static function truncateUtf8($text, $max, $suffix)
{
$text = (string) $text;
if ($text === '') return '';
if (mb_strlen($text) <= $max) return $text;
$tr = mb_substr($text, 0, $max);
$lastSpace = mb_strrpos($tr, ' ');
if ($lastSpace !== false) {
$tr = mb_substr($tr, 0, $lastSpace);
} else {
$tr = mb_substr($tr, 0, max(0, $max - mb_strlen($suffix)));
}
return rtrim($tr) . $suffix;
}
/**
* Delegate to centralized UTF-8 helper.
*
* @param string $html
* @return string
*/
private static function ensureUtf8($html)
{
return AI_DOM::ensureUtf8($html);
}
/**
* Compute absolute URL for the current page.
*
* @return string
*/
private static function currentPageUrlAbsolute()
{
if (is_singular()) {
$postId = get_queried_object_id();
if ($postId) {
$p = get_permalink($postId);
if (is_string($p) && $p !== '') return (string) $p;
}
}
if (is_front_page() || is_home()) {
return home_url('/');
}
$req_uri = ai_translate_request_uri('/');
$path = (string) wp_parse_url($req_uri, PHP_URL_PATH);
if ($path === '') { $path = '/'; }
return home_url($path);
}
/**
* Translate Twitter Card meta tags in final HTML.
* Runs on the fully assembled HTML (after DOMDocument + placeholder restore)
* because DOMDocument may move Jetpack meta tags out of when
* preceding script/style placeholders break the head structure.
*
* @param string $html Full HTML output.
* @param string $lang Target language code.
* @return string HTML with translated Twitter Card meta tags.
*/
public static function translateTwitterCards($html, $lang)
{
$default = AI_Lang::default();
if ($default === null || strtolower((string) $lang) === strtolower((string) $default)) {
return $html;
}
$twitterNames = ['twitter:text:title', 'twitter:title', 'twitter:description', 'twitter:image:alt'];
$names = implode('|', array_map(function ($n) { return preg_quote($n, '#'); }, $twitterNames));
$pattern = '#(]*>)#i';
if (preg_match_all($pattern, $html, $allMatches) && !empty($allMatches[2])) {
$texts = [];
foreach ($allMatches[2] as $raw) {
$decoded = html_entity_decode($raw, ENT_QUOTES, 'UTF-8');
if (trim($decoded) !== '') {
$texts[] = $decoded;
}
}
self::batchTranslateMeta($texts, $default, $lang);
}
return preg_replace_callback($pattern, function ($m) use ($default, $lang) {
$original = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8');
if (trim($original) === '') {
return $m[0];
}
$translated = self::maybeTranslateMeta($original, $default, $lang);
if (!is_string($translated) || $translated === '' || $translated === $original) {
return $m[0];
}
return $m[1] . esc_attr($translated) . $m[3];
}, $html);
}
/**
* Translate JSON-LD BreadcrumbList name fields in final HTML.
* Called after script placeholders have been restored.
*
* @param string $html Full HTML output.
* @param string $lang Target language code.
* @return string HTML with translated JSON-LD.
*/
public static function translateJsonLd($html, $lang)
{
$default = AI_Lang::default();
if ($default === null || strtolower((string) $lang) === strtolower((string) $default)) {
return $html;
}
if (preg_match_all('##is', $html, $allBlocks) && !empty($allBlocks[1])) {
$texts = [];
foreach ($allBlocks[1] as $raw) {
$json = json_decode($raw, true);
if (is_array($json)) {
self::collectJsonLdTexts($json, $texts);
}
}
if (!empty($texts)) {
self::batchTranslateMeta($texts, $default, $lang);
}
}
return preg_replace_callback(
'#()#is',
function ($m) use ($default, $lang) {
$json = json_decode($m[2], true);
if (!is_array($json)) {
return $m[0];
}
$changed = self::translateJsonLdNode($json, $default, $lang);
if (!$changed) {
return $m[0];
}
$encoded = wp_json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if (!is_string($encoded) || $encoded === '') {
return $m[0];
}
return $m[1] . $encoded . $m[3];
},
$html
);
} /**
* Recursively translate name/description fields in JSON-LD BreadcrumbList nodes.
*
* @param array &$node JSON-LD node (modified in place).
* @param string $default Default language.
* @param string $lang Target language.
* @return bool Whether any field was translated.
*/
/**
* Recursively collect translatable text values from a JSON-LD structure.
*
* @param array $node JSON-LD node.
* @param string[] &$texts Collected texts (appended in place).
*/
private static function collectJsonLdTexts(array $node, array &$texts): void
{
$type = $node['@type'] ?? '';
if ($type === 'BreadcrumbList' && isset($node['itemListElement']) && is_array($node['itemListElement'])) {
foreach ($node['itemListElement'] as $item) {
if (isset($item['name']) && is_string($item['name']) && trim($item['name']) !== '') {
$texts[] = $item['name'];
}
}
}
// WooCommerce Product schema: only name/description are user-facing prose;
// offers, sku, brand and ratings must stay untouched.
if ($type === 'Product') {
foreach (['name', 'description'] as $field) {
if (isset($node[$field]) && is_string($node[$field]) && trim($node[$field]) !== '') {
$texts[] = $node[$field];
}
}
}
if (isset($node['@graph']) && is_array($node['@graph'])) {
foreach ($node['@graph'] as $graphNode) {
if (is_array($graphNode)) {
self::collectJsonLdTexts($graphNode, $texts);
}
}
}
}
private static function translateJsonLdNode(array &$node, $default, $lang)
{
$type = $node['@type'] ?? '';
$changed = false; if ($type === 'BreadcrumbList' && isset($node['itemListElement']) && is_array($node['itemListElement'])) {
foreach ($node['itemListElement'] as &$item) {
if (isset($item['name']) && is_string($item['name']) && trim($item['name']) !== '') {
$translated = self::maybeTranslateMeta($item['name'], $default, $lang);
if (is_string($translated) && $translated !== '' && $translated !== $item['name']) {
$item['name'] = $translated;
$changed = true;
}
}
}
unset($item);
}
// WooCommerce Product schema: translate name/description only (see collector).
if ($type === 'Product') {
foreach (['name', 'description'] as $field) {
if (isset($node[$field]) && is_string($node[$field]) && trim($node[$field]) !== '') {
$translated = self::maybeTranslateMeta($node[$field], $default, $lang);
if (is_string($translated) && $translated !== '' && $translated !== $node[$field]) {
$node[$field] = $translated;
$changed = true;
}
}
}
}
// Handle @graph arrays (used by Yoast and others)
if (isset($node['@graph']) && is_array($node['@graph'])) {
foreach ($node['@graph'] as &$graphNode) {
if (is_array($graphNode)) {
if (self::translateJsonLdNode($graphNode, $default, $lang)) {
$changed = true;
}
}
}
unset($graphNode);
} return $changed;
}
}