default = $config['default_language']; $this->current = $this->default; $this->original_uri = self::request_uri(); self::drop_fetch_arg(); if ( ! $this->is_frontend_request() || ! Settings::is_active() ) { return; } if ( 'subdirectory' === $config['url_mode'] ) { $this->detect_from_path( $config ); } else { $this->detect_from_host( $config ); } if ( $this->pending_redirect ) { add_action( 'init', array( $this, 'do_pending_redirect' ), 0 ); } if ( $this->changed_request_uri() ) { self::keep_out_of_page_caches(); } } /** * Whether REQUEST_URI now names a different address from the one the visitor asked for * ("/es/about/" is served as "/about/", a translated slug as its original, or the worker's * throwaway argument dropped). */ public function changed_request_uri() { return self::request_uri() !== $this->original_uri; } /** * The address asked for (REQUEST_URI), the one place the plugin reads it. It is sanitized as a * URL with esc_url_raw(), which removes quotes, angle brackets, line breaks (also as %0d/%0a) and * other characters a URL can't hold. Percent-encoded characters stay, so translated slugs in any * script still match; sanitize_text_field() would remove them. It is then validated as a path: * anything else (missing, empty, "http://…", "javascript:…") counts as the home page. */ private static function request_uri() { $uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; return '' !== $uri && '/' === $uri[0] ? $uri : '/'; } /** * The request's own FETCH_ARG value, from the address as it was asked for, when it has the worker's * signed shape (Fetch_Signature::SHAPE), else ''. The argument given twice or as an array * ("langferry_fetch[]=…") is no value. The value is read as it was sent, never decoded. */ public function fetch_value(): string { $qpos = strpos( $this->original_uri, '?' ); if ( false === $qpos ) { return ''; } $found = array(); foreach ( explode( '&', substr( $this->original_uri, $qpos + 1 ) ) as $pair ) { $parts = explode( '=', $pair, 2 ); if ( self::FETCH_ARG === $parts[0] ) { $found[] = $parts[1] ?? ''; } } if ( 1 !== count( $found ) || strlen( $found[0] ) > Fetch_Signature::MAX_LENGTH ) { return ''; } return 1 === preg_match( Fetch_Signature::SHAPE, $found[0] ) ? $found[0] : ''; } /** * Drop the worker's throwaway argument (FETCH_ARG) from the request, before WordPress or any other * plugin builds an address from it: REQUEST_URI, QUERY_STRING, $_GET and $_REQUEST, in either form * (the signed value, or 2.8.0's 12 hex digits alone). Only its own key is touched. Its value is * read only to verify the worker's signature, by fetch_value() from the address as it was asked for. */ private static function drop_fetch_arg() { $uri = self::request_uri(); $clean = self::without_fetch_arg( $uri ); if ( $clean === $uri ) { return; } $query = (string) wp_parse_url( $clean, PHP_URL_QUERY ); $_SERVER['REQUEST_URI'] = $clean; $_SERVER['QUERY_STRING'] = $query; unset( $_GET[ self::FETCH_ARG ], $_REQUEST[ self::FETCH_ARG ] ); } /** * An address without the worker's throwaway argument: "/es/about/?langferry_fetch=…" is * "/es/about/", "/?p=5&langferry_fetch=…" is "/?p=5". Every other part stays as it is. */ private static function without_fetch_arg( $uri ) { $qpos = strpos( $uri, '?' ); if ( false === $qpos ) { return $uri; } $kept = array(); foreach ( explode( '&', substr( $uri, $qpos + 1 ) ) as $pair ) { if ( '' !== $pair && self::FETCH_ARG !== explode( '=', $pair, 2 )[0] ) { $kept[] = $pair; } } return substr( $uri, 0, $qpos ) . ( $kept ? '?' . implode( '&', $kept ) : '' ); } /** * Page caches that run inside WordPress and file the finished page under REQUEST_URI * (SiteGround Optimizer's file cache, among others) would store this translated page as the * original-language one and serve it to everyone at that address: a home page shown in * Chinese to every visitor. DONOTCACHEPAGE is the signal those caches share. Caches in front of PHP file pages under the address the visitor asked for, so they * keep caching translated pages. */ private static function keep_out_of_page_caches() { if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- The page caches' shared flag. } } private function is_frontend_request() { if ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) || wp_doing_cron() || ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) ) { return false; } $path = $this->relative_path( strtok( $this->original_uri, '?' ) ); return null !== $path && 0 !== strpos( $path, '/wp-json/' ) && 0 !== strpos( $path, '/wp-login.php' ); } private function detect_from_path( array $config ) { $uri = self::without_fetch_arg( $this->original_uri ); $qpos = strpos( $uri, '?' ); $path = false === $qpos ? $uri : substr( $uri, 0, $qpos ); $query = false === $qpos ? '' : substr( $uri, $qpos ); $rel = $this->relative_path( $path ); if ( null === $rel ) { return; } $parts = explode( '/', ltrim( $rel, '/' ), 2 ); $lang = Languages::from_url_slug( rawurldecode( $parts[0] ), Settings::all_languages() ); if ( null === $lang ) { return; } $rest = '/' . ( $parts[1] ?? '' ); // "/es/sitemap_index.xml" (a common pattern on translated sites, often already // submitted in Search Console) → this language's Langferry sitemap. if ( $lang !== $this->default && preg_match( '#^/(sitemap_index|sitemap|wp-sitemap)\.xml$#', $rest ) ) { $this->pending_redirect = $this->home_path() . '/langferry-sitemap-' . Languages::url_slug( $lang ) . '-1.xml'; return; } // Files, feeds and APIs exist once, without a language prefix. if ( $this->is_resource_path( $rest ) ) { $this->pending_redirect = $this->home_path() . $rest . $query; return; } if ( $lang === $this->default ) { // "/en/about/" duplicates "/about/" — send it to the canonical URL. $this->pending_redirect = $this->home_path() . $rest . $query; return; } if ( ! isset( $parts[1] ) ) { // "/es" → "/es/" so every translated URL has exactly one form. $this->pending_redirect = $this->home_path() . '/' . Languages::url_slug( $lang ) . '/' . $query; return; } if ( $config['seo']['translate_slugs'] ) { $source = Slugs::to_source( $rest, $lang ); $canonical = Slugs::to_translated( $source, $lang ); if ( $canonical !== Slugs::normalize( $rest ) ) { // "/es/about/" when "/es/acerca-de/" exists: one URL per page. $this->pending_redirect = $this->home_path() . '/' . Languages::url_slug( $lang ) . $canonical . $query; return; } $rest = $source; } $this->current = $lang; $_SERVER['REQUEST_URI'] = $this->home_path() . $rest . $query; } private function detect_from_host( array $config ) { $host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : ''; $lang = $this->language_for_host( $host ); if ( $lang === $config['default_language'] ) { return; } $this->current = $lang; if ( $config['seo']['translate_slugs'] ) { $uri = self::without_fetch_arg( $this->original_uri ); $qpos = strpos( $uri, '?' ); $path = false === $qpos ? $uri : substr( $uri, 0, $qpos ); $rel = $this->relative_path( $path ); if ( null !== $rel ) { $_SERVER['REQUEST_URI'] = $this->home_path() . Slugs::to_source( $rel, $lang ) . ( false === $qpos ? '' : substr( $uri, $qpos ) ); } } } /** * The language served at a host in sub-domain / custom-domain mode. */ public function language_for_host( $host ) { $host = strtolower( (string) $host ); $config = Settings::effective(); // The site's own address always serves the original language; in sub-directory mode the path decides. if ( 'subdirectory' === $config['url_mode'] || self::without_www( $host ) === self::without_www( $this->home_host() ) ) { return $config['default_language']; } foreach ( $config['languages'] as $lang ) { if ( $host === $this->lang_host( $lang ) ) { return $lang; } } return $config['default_language']; } public function do_pending_redirect() { $scheme = is_ssl() ? 'https://' : 'http://'; $host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : wp_parse_url( home_url(), PHP_URL_HOST ); wp_safe_redirect( $scheme . $host . $this->pending_redirect, 301, 'Langferry' ); exit; } /* ------------------------------------------------------------------ */ /* State */ /* ------------------------------------------------------------------ */ public function current() { return $this->current ? $this->current : Settings::effective()['default_language']; } public function default_language() { return Settings::effective()['default_language']; } public function is_default() { return $this->current() === $this->default_language(); } /** * Override the current language (e-mails, CLI). Returns the previous one. */ public function switch_to( $lang ) { $previous = $this->current(); $this->current = $lang; return $previous; } /* ------------------------------------------------------------------ */ /* URLs */ /* ------------------------------------------------------------------ */ /** * Path of the WordPress home URL without trailing slash ("" or "/blog"). */ public function home_path() { $path = (string) wp_parse_url( home_url(), PHP_URL_PATH ); return rtrim( $path, '/' ); } public function home_host() { $parts = wp_parse_url( home_url() ); return strtolower( ( $parts['host'] ?? '' ) . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ) ); } /** * Host serving a language in subdomain / custom-domain mode. */ public function lang_host( $lang ) { $config = Settings::effective(); if ( $lang === $config['default_language'] || 'subdirectory' === $config['url_mode'] ) { return $this->home_host(); } $site = self::without_www( $this->home_host() ); $domain = (string) ( $config['custom_domains'][ $lang ] ?? '' ); // The site's own address is never a translation's: it would replace the original language // for every visitor, and the switcher couldn't get back to it. if ( '' !== $domain && self::without_www( $domain ) !== $site ) { return $domain; } // Sub-domain mode, and a custom domain left empty ("Leave empty to use es.yourdomain"). return Languages::url_slug( $lang ) . '.' . $site; } private static function without_www( $host ) { return (string) preg_replace( '/^www\./', '', strtolower( (string) $host ) ); } private function is_own_host( $host ) { $host = strtolower( $host ); $home = $this->home_host(); if ( $host === $home || 'www.' . $host === $home || $host === 'www.' . $home ) { return true; } foreach ( Settings::effective()['languages'] as $lang ) { if ( $host === $this->lang_host( $lang ) ) { return true; } } return false; } /** * Path relative to the home path, or null when outside WordPress. */ private function relative_path( $path ) { $home = $this->home_path(); $path = '' === $path ? '/' : $path; if ( '' === $home ) { return $path; } if ( $path === $home ) { return '/'; } if ( 0 === strpos( $path, $home . '/' ) ) { return substr( $path, strlen( $home ) ); } return null; } /** * Paths that are files, feeds, APIs or admin — never language-prefixed. */ public function is_resource_path( $rel ) { if ( preg_match( '#^/(wp-admin|wp-content|wp-includes|wp-json)(/|$)|^/(wp-login|xmlrpc|wp-cron|wp-signup|wp-activate|wp-trackback)\.php#', $rel ) ) { return true; } if ( preg_match( '#/(feed|rdf|rss|rss2|atom)/?$#', $rel ) ) { return true; } if ( preg_match( '#\.([a-z0-9]{2,5})$#i', $rel, $m ) && ! in_array( strtolower( $m[1] ), array( 'html', 'htm', 'php' ), true ) ) { return true; } return false; } public function is_excluded_path( $rel ) { foreach ( Settings::effective()['exclusions']['paths'] as $prefix ) { if ( '' !== $prefix && 0 === strpos( $rel, rtrim( $prefix, '*' ) ) ) { return true; } } return false; } /** * Request path as WordPress sees it (language prefix removed). */ public function request_path() { $uri = self::request_uri(); $rel = $this->relative_path( (string) strtok( $uri, '?' ) ); return null === $rel ? '/' : $rel; } /** * Convert any URL to its equivalent in $lang. External, resource and * excluded URLs are returned unchanged (or in the default language). * Idempotent: an already-translated URL can be converted to any language. */ public function translate_url( $url, $lang ) { $url = (string) $url; if ( '' === $url || '#' === $url[0] || '?' === $url[0] ) { return $url; } $parts = wp_parse_url( $url ); if ( false === $parts || ( isset( $parts['scheme'] ) && ! in_array( strtolower( $parts['scheme'] ), array( 'http', 'https' ), true ) ) ) { return $url; } $has_host = isset( $parts['host'] ); if ( $has_host ) { $host = $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); if ( ! $this->is_own_host( $host ) ) { return $url; } } elseif ( ! isset( $parts['path'] ) || '' === $parts['path'] || '/' !== $parts['path'][0] ) { return $url; // Document-relative links resolve against the (already translated) page URL. } $rel = $this->relative_path( isset( $parts['path'] ) && '' !== $parts['path'] ? $parts['path'] : '/' ); if ( null === $rel ) { return $url; } $config = Settings::effective(); // Strip an existing language prefix. if ( 'subdirectory' === $config['url_mode'] ) { $seg = explode( '/', ltrim( $rel, '/' ), 2 ); $from = Languages::from_url_slug( rawurldecode( $seg[0] ), Settings::all_languages() ); if ( null !== $from ) { $rel = '/' . ( $seg[1] ?? '' ); if ( $config['seo']['translate_slugs'] && $from !== $config['default_language'] ) { $rel = Slugs::to_source( $rel, $from ); } } } elseif ( $has_host && $config['seo']['translate_slugs'] ) { foreach ( $config['languages'] as $l ) { if ( strtolower( $host ) === $this->lang_host( $l ) ) { $rel = Slugs::to_source( $rel, $l ); break; } } } if ( $this->is_resource_path( $rel ) || $this->is_excluded_path( $rel ) ) { $lang = $config['default_language']; } if ( $lang !== $config['default_language'] && $config['seo']['translate_slugs'] ) { $rel = Slugs::to_translated( $rel, $lang ); } $suffix = ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' ) . ( isset( $parts['fragment'] ) ? '#' . $parts['fragment'] : '' ); if ( 'subdirectory' === $config['url_mode'] ) { $path = $this->home_path() . ( $lang === $config['default_language'] ? '' : '/' . Languages::url_slug( $lang ) ) . $rel; if ( ! $has_host ) { return $path . $suffix; } $host = $this->is_lang_host_of_other( $host ) ? $this->home_host() : $host; return ( isset( $parts['scheme'] ) ? $parts['scheme'] . ':' : '' ) . '//' . $host . $path . $suffix; } $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : wp_parse_url( home_url(), PHP_URL_SCHEME ); return $scheme . '://' . $this->lang_host( $lang ) . $this->home_path() . $rel . $suffix; } private function is_lang_host_of_other( $host ) { return strtolower( $host ) !== $this->home_host() && $this->is_own_host( $host ); } /** * The current page in another language (keeps the query string). */ public function current_url_in( $lang ) { $scheme = is_ssl() ? 'https' : wp_parse_url( home_url(), PHP_URL_SCHEME ); $uri = self::request_uri(); return $this->translate_url( $scheme . '://' . $this->home_host() . $uri, $lang ); } /** * Canonical form of the current page in another language (no tracking * parameters), used for hreflang and sitemaps. */ public function canonical_url_in( $lang ) { $url = $this->current_url_in( $lang ); if ( '' !== (string) get_option( 'permalink_structure' ) ) { $url = (string) strtok( $url, '?' ); } return $url; } /** * Keep WordPress's own redirects inside the visitor's language. */ public function filter_redirect_canonical( $redirect_url, $requested_url ) { if ( $this->is_default() || ! $redirect_url ) { return $redirect_url; } $translated = $this->translate_url( $redirect_url, $this->current() ); $scheme = is_ssl() ? 'https://' : 'http://'; $host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : ''; if ( untrailingslashit( $translated ) === untrailingslashit( $scheme . $host . self::without_fetch_arg( $this->original_uri ) ) ) { return false; } return $translated; } public function filter_wp_redirect( $location ) { if ( is_admin() || $this->is_default() || ! is_string( $location ) ) { return $location; } return $this->translate_url( $location, $this->current() ); } }