query_vars['blogpage'] ?? ($_GET['blogpage'] ?? null); if (is_admin() || !is_scalar($page)) { return; } $posts_page_id = (int) get_option('page_for_posts'); if ($posts_page_id <= 0) { return; } $page_path = (string) ($wp->query_vars['pagename'] ?? ''); $page_id = (int) ($wp->query_vars['page_id'] ?? 0); if ($page_id !== $posts_page_id && $page_path !== (string) get_page_uri($posts_page_id)) { return; } $wp->query_vars['paged'] = max(1, absint(wp_unslash($page))); } /** * Rewrite internal links based on current language. * * @param string $html * @param string $lang * @return string */ public static function rewrite($html, $lang) { if (is_admin()) { return $html; } $default = AI_Lang::default(); if ($lang === null || $default === null) { return $html; } $doc = new \DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $flags = LIBXML_HTML_NODEFDTD; $doc->loadHTML($html, $flags); libxml_clear_errors(); libxml_use_internal_errors($internalErrors); self::rewrite_dom($doc, $lang); $result = $doc->saveHTML(); // Remove XML declaration added by loadHTML (causes quirks mode) $result = preg_replace('/<\?xml[^?]*\?>\s*/i', '', $result); // Preserve DOCTYPE from original HTML to avoid quirks mode if (preg_match('/^(]*>)/i', (string) $html, $docMatch)) { // Ensure we don't duplicate if saveHTML already includes it if (stripos($result, ']*>([\s\S]*?)<\/body>/i', (string) $result, $bodyNew) && preg_match('/
]*>([\s\S]*?)<\/body>/i', (string) $html, $bodyOrig)) { $newBodyInner = (string) $bodyNew[1]; // Only replace body inner content (URLs have been rewritten), keep everything else from original $result = (string) preg_replace('/(]*>)[\s\S]*?(<\/body>)/i', '$1' . $newBodyInner . '$2', (string) $html, 1); } return $result; } /** * Rewrite internal links in an already-parsed DOMDocument. * Modifies the document in place. Used by combined DOM pass in AI_OB. * * @param \DOMDocument $doc Parsed HTML document. * @param string $lang Target language code. * @return void */ public static function rewrite_dom(\DOMDocument $doc, string $lang): void { $default = AI_Lang::default(); if ($default === null) { return; } $xpath = new \DOMXPath($doc); $links = $xpath->query('//a[@href]'); if ($links) { foreach ($links as $a) { /** @var \DOMElement $a */ if (self::hasSkipFlag($a)) { continue; } $href = (string) $a->getAttribute('href'); if ($href === '' || self::isSkippableHref($href)) { continue; } $isLogo = self::isLogoLink($a); $new = self::rewriteHref($href, $lang, $default, $isLogo); if ($new !== null) { $a->setAttribute('href', self::addSitePrefix($new)); } } } // Second pass: translate slugs via slug map + handle blog pagination rewrites. // Reuses the same DOMNodeList (live, reflects href changes made in the first pass). if ($links) { foreach ($links as $a) { /** @var \DOMElement $a */ if (self::hasSkipFlag($a)) { continue; } $href = (string) $a->getAttribute('href'); if ($href === '' || self::isSkippableHref($href)) continue; $hrefParts = wp_parse_url($href); $path = isset($hrefParts['path']) ? (string) $hrefParts['path'] : ''; if ($path !== '' && preg_match('#/page/([0-9]+)/?$#', $path, $mm)) { $postsPageId = (int) get_option('page_for_posts'); if ($postsPageId > 0) { $postsSlug = (string) get_page_uri($postsPageId); $translatedSlug = \AITranslate\AI_Slugs::get_or_generate($postsPageId, $lang); if (!is_string($translatedSlug) || $translatedSlug === '') { $translatedSlug = $postsSlug; } $base = (strtolower($lang) === strtolower($default)) ? ('/' . trim($postsSlug, '/') . '/') : ('/' . $lang . '/' . trim($translatedSlug, '/') . '/'); $n = max(1, (int) $mm[1]); $params = array(); if (isset($hrefParts['query']) && $hrefParts['query'] !== '') { parse_str((string)$hrefParts['query'], $params); } $params['blogpage'] = $n; $q = '?' . http_build_query($params); $frag = isset($hrefParts['fragment']) ? ('#' . $hrefParts['fragment']) : ''; $a->setAttribute('href', self::addSitePrefix($base . $q . $frag)); continue; } } $translated = self::rewriteSingularWithSlugMap($href, $lang, $default); if ($translated) { $a->setAttribute('href', self::addSitePrefix($translated)); } } } } /** * Rewrite a single URL (relative or absolute) to the target language path. * Returns a site-relative path with query/fragment when internal; null when external or not rewritable. * * @param string $href * @param string $lang * @param string|null $default * @return string|null */ public static function rewrite_single_href($href, $lang, $default = null) { if ($default === null) { $default = AI_Lang::default(); } if ($lang === null || $default === null) { return null; } return self::rewriteHref($href, $lang, $default); } /** * Return true when a href value should never be rewritten. * Skips anchors, mailto/tel/javascript schemes, and WordPress system paths * such as /wp-admin/, /wp-content/, wp-login.php, /wp-json/, and admin-ajax.php. * * @param string $href * @return bool */ private static function isSkippableHref($href) { $href = ltrim($href); if ($href === '' || $href[0] === '#') return true; $lower = strtolower($href); if (str_starts_with($lower, 'mailto:')) return true; if (str_starts_with($lower, 'tel:')) return true; if (str_starts_with($lower, 'javascript:')) return true; // Never rewrite admin/auth/REST endpoints or static asset paths if (strpos($lower, '/wp-admin/') !== false) return true; if (strpos($lower, '/wp-content/') !== false) return true; if (strpos($lower, 'wp-login.php') !== false) return true; if (strpos($lower, '/wp-json/') !== false) return true; if (strpos($lower, 'admin-ajax.php') !== false) return true; if (strpos($lower, 'rest_route=') !== false) return true; if (strpos($lower, 'switch_lang=') !== false || strpos($lower, '_lang_switch=') !== false) return true; return false; } /** * Check if element or any ancestor is marked to skip rewriting. * * @param \DOMElement $el * @return bool */ private static function hasSkipFlag(\DOMElement $el) { $node = $el; while ($node && $node instanceof \DOMElement) { $id = strtolower((string) $node->getAttribute('id')); if ($id === 'ai-trans' || $id === 'ai-trans-menu') { return true; } if ($node->hasAttribute('data-ai-trans-skip')) { return true; } $classAttr = ' ' . strtolower((string) $node->getAttribute('class')) . ' '; if (strpos($classAttr, ' ai-trans-item ') !== false) { return true; } $node = $node->parentNode instanceof \DOMElement ? $node->parentNode : null; } return false; } /** * Check if a link element is likely a logo link (homepage link with logo image or logo class/id). * * @param \DOMElement $a * @return bool */ private static function isLogoLink(\DOMElement $a) { $href = (string) $a->getAttribute('href'); if ($href === '') { return false; } $hrefParts = wp_parse_url($href); $pathOnly = isset($hrefParts['path']) ? (string) $hrefParts['path'] : '/'; // Check if link points to homepage (root path) $isHomepage = ($pathOnly === '' || $pathOnly === '/' || preg_match('#^/([a-z]{2})/?$#i', $pathOnly)); if (!$isHomepage) { return false; } // Check if link contains an image (common for logo links) $images = $a->getElementsByTagName('img'); if ($images && $images->length > 0) { // Check if any image has logo-related attributes foreach ($images as $img) { $alt = strtolower((string) $img->getAttribute('alt')); $src = strtolower((string) $img->getAttribute('src')); $classAttr = ' ' . strtolower((string) $img->getAttribute('class')) . ' '; if (strpos($alt, 'logo') !== false || strpos($src, 'logo') !== false || strpos($classAttr, ' logo ') !== false || strpos($classAttr, ' custom-logo ') !== false) { return true; } } // If link contains image and points to homepage, assume it's a logo return true; } // Check if link or parent has logo-related class/id $node = $a; while ($node && $node instanceof \DOMElement) { $id = strtolower((string) $node->getAttribute('id')); $classAttr = ' ' . strtolower((string) $node->getAttribute('class')) . ' '; if (strpos($id, 'logo') !== false || strpos($classAttr, ' logo ') !== false || strpos($classAttr, ' site-logo ') !== false || strpos($classAttr, ' custom-logo ') !== false) { return true; } $node = $node->parentNode instanceof \DOMElement ? $node->parentNode : null; } return false; } private static function rewriteHref($href, $lang, $default, $isLogo = false) { // Use unfiltered home URL to avoid language-prefix injection from the home_url filter. $home = trailingslashit((string) get_option('home', get_option('siteurl', ''))); $homeParts = wp_parse_url($home); $hrefParts = wp_parse_url($href); // Hard skip when switcher params are present if (isset($hrefParts['query']) && $hrefParts['query'] !== '') { $params = []; parse_str((string) $hrefParts['query'], $params); if (isset($params['switch_lang']) || isset($params['_lang_switch'])) { return $href; // leave untouched } } // Skip pure root or pure /xx/ language-home links to avoid rewriting the switcher // Exception: logo links should be rewritten to include language prefix $pathOnly = isset($hrefParts['path']) ? (string) $hrefParts['path'] : '/'; if (!$isLogo) { if ($pathOnly === '' || $pathOnly === '/') { return $href; } if (preg_match('#^/([a-z]{2})/?$#i', $pathOnly)) { return $href; } } // Determine if internal $isRelative = !isset($hrefParts['host']) && !isset($hrefParts['scheme']); $isInternal = $isRelative; if (!$isInternal && isset($hrefParts['host']) && isset($homeParts['host'])) { $isInternal = strtolower($hrefParts['host']) === strtolower($homeParts['host']); } if (!$isInternal) { return null; // leave external links unchanged } // Build path $path = isset($hrefParts['path']) ? $hrefParts['path'] : '/'; $path = self::normalizePath($path, $homeParts); // Wanneer de href al expliciet een taalprefix heeft die AFWIJKT van de huidige $lang, // laat de link ongemoeid (language switcher moet niet naar huidige taal herschreven worden). // Exception: logo links should always use current language if (!$isLogo && preg_match('#^/([a-z]{2})(/|$)#i', $path, $pm)) { $hrefLang = strtolower($pm[1]); if ($hrefLang !== strtolower($lang)) { $query = isset($hrefParts['query']) ? ('?' . $hrefParts['query']) : ''; $frag = isset($hrefParts['fragment']) ? ('#' . $hrefParts['fragment']) : ''; return $path . $query . $frag; } } // Do not attempt to split arbitrary two-letter prefixes; rely on proper rewrite rules // Special handling for blog pagination links and posts index: // - Theme may use '/?blogpage=N' without a path → rewrite to '/{lang}/{translated-posts-slug}/page/N/' // - Path '/{posts-slug}/page/N/' → rewrite to '/{lang}/{translated-posts-slug}/page/N/' $postsPageId = (int) get_option('page_for_posts'); if ($postsPageId > 0) { $postsSlug = (string) get_page_uri($postsPageId); // source slug, e.g., 'nieuws' $translatedSlug = \AITranslate\AI_Slugs::get_or_generate($postsPageId, $lang); if (!is_string($translatedSlug) || $translatedSlug === '') { $translatedSlug = $postsSlug; } $query = isset($hrefParts['query']) ? (string) $hrefParts['query'] : ''; $params = array(); if ($query !== '') { parse_str($query, $params); } $hasBlogPage = isset($params['blogpage']) && (int) $params['blogpage'] > 0; // Case A: '/?blogpage=N' or '/{lang}/?blogpage=N' (path is root) $pathNoLang = preg_replace('#^/([a-z]{2})(?=/|$)#i', '', $path); if ($pathNoLang === '') { $pathNoLang = '/'; } if (($path === '/' || $pathNoLang === '/') && $hasBlogPage) { $n = max(1, (int) $params['blogpage']); // Build language-aware path to posts index with blogpage query if (strtolower($lang) === strtolower($default)) { $newPath = '/' . trim($postsSlug, '/') . '/'; } else { $newPath = '/' . $lang . '/' . trim($translatedSlug, '/') . '/'; } $frag = isset($hrefParts['fragment']) ? ('#' . $hrefParts['fragment']) : ''; // Ensure blogpage stays in querystring if (!isset($params['blogpage'])) { $params['blogpage'] = $n; } $q = '?' . http_build_query($params); return $newPath . $q . $frag; } // Case B: '/{postsSlug}/page/N/' or '/{lang}/{translatedSlug}/page/N/' $segments = array_values(array_filter(explode('/', ltrim($pathNoLang, '/')))); if (!empty($segments)) { $first = isset($segments[0]) ? (string) $segments[0] : ''; $hasPageSeg = false; $n = 0; for ($i = 0; $i < count($segments) - 1; $i++) { if ($segments[$i] === 'page' && ctype_digit((string) $segments[$i+1])) { $hasPageSeg = true; $n = (int) $segments[$i+1]; break; } } if ($hasPageSeg && ($first === $postsSlug || $first === $translatedSlug)) { if (strtolower($lang) === strtolower($default)) { $newPath = '/' . trim($postsSlug, '/') . '/'; } else { $newPath = '/' . $lang . '/' . trim($translatedSlug, '/') . '/'; } // Convert page/N to blogpage=N query $params = array(); if (isset($hrefParts['query']) && $hrefParts['query'] !== '') { parse_str((string)$hrefParts['query'], $params); } $params['blogpage'] = max(1, $n); $q = '?' . http_build_query($params); $frag = isset($hrefParts['fragment']) ? ('#' . $hrefParts['fragment']) : ''; return $newPath . $q . $frag; } } } // If current lang is default: strip any leading /xx/ prefix if (strtolower($lang) === strtolower($default)) { $path = preg_replace('#^/[a-z]{2}(?=/|$)#i', '', $path); if ($path === '') { $path = '/'; } } else { // Always ensure prefix /{lang}/ and avoid double language $pathNoLang = preg_replace('#^/([a-z]{2})(?=/|$)#i', '', $path); $path = '/' . $lang . '/' . ltrim($pathNoLang, '/'); } $query = isset($hrefParts['query']) ? ('?' . $hrefParts['query']) : ''; $frag = isset($hrefParts['fragment']) ? ('#' . $hrefParts['fragment']) : ''; return $path . $query . $frag; // relative site-path keeps site portable } /** * Normalize a URL path to a site-relative path. * Ensures a leading slash and strips the WordPress installation subdirectory prefix when present. * * @param string $path * @param array