settings = $settings; self::$instance = $this; } public static function instance(): self { return self::$instance; } public function register(): void { Languages::set_current( $this->detect() ); add_filter( 'do_parse_request', array( $this, 'strip_request_uri' ), 1 ); add_action( 'parse_request', array( $this, 'restore_request_uri' ), 1 ); add_filter( 'query_vars', array( $this, 'query_vars' ) ); if ( $this->is_frontend() ) { add_filter( 'home_url', array( $this, 'filter_home_url' ), 10, 2 ); add_filter( 'locale', array( $this, 'filter_locale' ), 20 ); add_action( 'wp_loaded', array( $this, 'apply_text_direction' ) ); add_filter( 'body_class', array( $this, 'body_class' ) ); add_filter( 'redirect_canonical', array( $this, 'redirect_canonical' ), 10, 2 ); add_action( 'template_redirect', array( $this, 'enforce_post_language' ), 1 ); } foreach ( array( 'post_link', 'page_link', 'post_type_link' ) as $hook ) { add_filter( $hook, array( $this, 'filter_post_link' ), 20, 2 ); } add_filter( 'term_link', array( $this, 'filter_term_link' ), 20, 3 ); add_filter( 'wp_unique_post_slug', array( $this, 'unique_slug' ), 10, 6 ); foreach ( array( 'page_on_front', 'page_for_posts' ) as $option ) { add_filter( 'option_' . $option, array( $this, 'translate_page_option' ) ); } } public function mode(): string { return (string) $this->settings->get( 'url_mode', 'directory' ); } private function hide_default(): bool { return (bool) $this->settings->get( 'hide_default', true ); } public function is_frontend(): bool { if ( defined( 'WP_CLI' ) && WP_CLI ) { return false; } // AJAX and REST requests belong to the page that made them. if ( wp_doing_ajax() || $this->is_rest_request() ) { $referer = Request::referer(); return '' === $referer || ! preg_match( '#/wp-admin/#', $referer ); } if ( is_admin() ) { return false; } $uri = Request::uri(); return ! preg_match( '#/wp-(admin|login\.php|cron\.php)#', $uri ); } // ------------------------------------------------------------------ // Detection // ------------------------------------------------------------------ /** * Determine the language of the current request. */ public function detect(): string { $source = Languages::source(); // REST / AJAX: explicit param first, then the referring page. if ( wp_doing_ajax() || $this->is_rest_request() ) { $param = isset( $_REQUEST[ self::QUERY_VAR ] ) ? sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_VAR ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification if ( $param && Languages::is_enabled( $param ) ) { return $param; } $referer = Request::referer(); return $referer ? $this->lang_from_url( $referer ) : $source; } if ( ! $this->is_frontend() ) { return $source; } $scheme = is_ssl() ? 'https://' : 'http://'; $host = Request::host(); $uri = Request::uri(); return $this->lang_from_url( $scheme . $host . $uri ); } /** * Language encoded in a URL (source language when none). */ public function lang_from_url( string $url ): string { $parts = wp_parse_url( $url ); $host = strtolower( $parts['host'] ?? '' ); $path = $parts['path'] ?? '/'; switch ( $this->mode() ) { case 'query': parse_str( $parts['query'] ?? '', $q ); $lang = isset( $q[ self::QUERY_VAR ] ) ? Settings::sanitize_lang( $q[ self::QUERY_VAR ] ) : ''; return $lang && Languages::is_enabled( $lang ) ? $lang : Languages::source(); case 'subdomain': $base = $this->home_host(); if ( $host !== $base && substr( $host, -strlen( '.' . $base ) ) === '.' . $base ) { $lang = Languages::from_slug( substr( $host, 0, -strlen( '.' . $base ) ) ); if ( $lang ) { return $lang; } } return Languages::source(); case 'domain': foreach ( (array) $this->settings->get( 'domains', array() ) as $lang => $domain ) { if ( $domain === $host && Languages::is_enabled( $lang ) ) { return $lang; } } return Languages::source(); default: $rel = $this->relative_path( $path ); $seg = strtok( ltrim( $rel, '/' ), '/' ); $lang = $seg ? Languages::from_slug( (string) $seg ) : ''; return $lang ?: Languages::source(); } } private function is_rest_request(): bool { $uri = Request::uri(); $prefix = '/' . trim( function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : 'wp-json', '/' ) . '/'; return false !== strpos( $uri, $prefix ) || isset( $_GET['rest_route'] ); // phpcs:ignore WordPress.Security.NonceVerification } // ------------------------------------------------------------------ // Request parsing (directory mode) // ------------------------------------------------------------------ /** * Strip the language prefix only while WP parses the request. * * @param bool $do Whether to parse. */ public function strip_request_uri( $do ) { $uri = Request::uri(); if ( 'directory' !== $this->mode() || '' === $uri ) { return $do; } $path = (string) wp_parse_url( $uri, PHP_URL_PATH ); $base = $this->home_path(); $rel = $this->relative_path( $path ); $seg = strtok( ltrim( $rel, '/' ), '/' ); if ( $seg && Languages::from_slug( (string) $seg ) ) { $this->original_uri = $uri; $stripped = preg_replace( '#^' . preg_quote( $base . $seg, '#' ) . '(/|$)#i', $base, $uri, 1 ); Request::set_uri( $stripped ?: $base ); } return $do; } public function restore_request_uri(): void { if ( null !== $this->original_uri ) { Request::set_uri( $this->original_uri ); $this->original_uri = null; } } public function query_vars( array $vars ): array { $vars[] = self::QUERY_VAR; return $vars; } // ------------------------------------------------------------------ // URL conversion // ------------------------------------------------------------------ /** * Convert any internal URL to the given language. */ public function convert( string $url, string $lang ): string { if ( '' === $url || ! Languages::is_enabled( $lang ) || ! $this->is_internal( $url ) || $this->is_excluded( $url ) ) { return $url; } $url = $this->strip( $url ); $is_source = $lang === Languages::source(); if ( $is_source && $this->hide_default() ) { return $url; } $slug = Languages::slug( $lang ); switch ( $this->mode() ) { case 'query': return add_query_arg( self::QUERY_VAR, $lang, $url ); case 'subdomain': $base = $this->home_host(); return $is_source ? $url : $this->replace_host( $url, $slug . '.' . $base ); case 'domain': $domains = (array) $this->settings->get( 'domains', array() ); return ( ! $is_source && ! empty( $domains[ $lang ] ) ) ? $this->replace_host( $url, $domains[ $lang ] ) : $url; default: $base = $this->home_path(); $parts = wp_parse_url( $url ); $path = $parts['path'] ?? '/'; if ( 0 !== stripos( $path . '/', $base ) && $path !== rtrim( $base, '/' ) ) { return $url; } $rest = (string) substr( $path, strlen( rtrim( $base, '/' ) ) ); $new_path = rtrim( $base, '/' ) . '/' . $slug . ( '' === $rest ? '/' : $rest ); return $this->rebuild( $parts, $new_path ); } } /** * Remove any language marker from a URL, producing the source-language form. */ public function strip( string $url ): string { $parts = wp_parse_url( $url ); if ( ! $parts ) { return $url; } switch ( $this->mode() ) { case 'query': return remove_query_arg( self::QUERY_VAR, $url ); case 'subdomain': case 'domain': return $this->replace_host( $url, $this->home_host() ); default: $path = $parts['path'] ?? ''; $base = $this->home_path(); $rel = $this->relative_path( $path ); $seg = strtok( ltrim( $rel, '/' ), '/' ); if ( $seg && Languages::from_slug( (string) $seg ) ) { $path = preg_replace( '#^' . preg_quote( $base . $seg, '#' ) . '(/|$)#i', $base, $path, 1 ); return $this->rebuild( $parts, $path ); } return $url; } } /** * URL of the current request, in another language. */ public function current_url_in( string $lang ): string { $scheme = is_ssl() ? 'https://' : 'http://'; $host = Request::host() ?: $this->home_host(); $uri = Request::uri() ?: '/'; return $this->convert( esc_url_raw( $scheme . $host . $uri ), $lang ); } /** * Best URL for the current page in a language: its translation when one exists. */ public function language_url( string $lang ): string { if ( is_singular() ) { $id = (int) get_queried_object_id(); $tr = Groups::translation( 'post', $id, $lang ); if ( $tr && 'publish' === get_post_status( $tr ) ) { return (string) get_permalink( $tr ); } return $this->convert( $this->raw_home(), $lang ); } if ( is_category() || is_tag() || is_tax() ) { $term = get_queried_object(); if ( $term instanceof \WP_Term ) { $tr = Groups::translation( 'term', (int) $term->term_id, $lang ); if ( $tr ) { $link = get_term_link( $tr ); if ( ! is_wp_error( $link ) ) { return $link; } } } } if ( is_front_page() || is_home() ) { return $this->convert( $this->raw_home(), $lang ); } return $this->current_url_in( $lang ); } // ------------------------------------------------------------------ // Filters // ------------------------------------------------------------------ /** * @param string $url Home URL. * @param string $path Requested path. */ public function filter_home_url( $url, $path ) { if ( $this->converting || Languages::is_source_current() && $this->hide_default() ) { return $url; } $rest = trim( function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : 'wp-json', '/' ); if ( is_string( $path ) && preg_match( '#^/?(' . preg_quote( $rest, '#' ) . '|wp-)#', $path ) ) { return $url; } $this->converting = true; $out = $this->convert( (string) $url, Languages::current() ); $this->converting = false; return $out; } /** * @param string $link Permalink. * @param int|\WP_Post $post Post. */ public function filter_post_link( $link, $post ) { $post = get_post( $post ); if ( ! $post || ! PostTypes::is_translatable( $post->post_type ) ) { return $link; } $this->converting = true; $out = $this->convert( (string) $link, Groups::lang_of( 'post', (int) $post->ID ) ); $this->converting = false; return $out; } public function filter_term_link( $link, $term, $taxonomy ) { if ( ! PostTypes::is_translatable_taxonomy( (string) $taxonomy ) ) { return $link; } $this->converting = true; $out = $this->convert( (string) $link, Groups::lang_of( 'term', (int) $term->term_id ) ); $this->converting = false; return $out; } public function filter_locale( $locale ) { return Languages::is_source_current() ? $locale : Languages::locale( Languages::current() ); } public function apply_text_direction(): void { global $wp_locale; if ( $wp_locale && ! Languages::is_source_current() ) { $wp_locale->text_direction = Languages::is_rtl( Languages::current() ) ? 'rtl' : 'ltr'; } } public function body_class( array $classes ): array { $classes[] = 'tp-lang-' . sanitize_html_class( Languages::slug( Languages::current() ) ); return $classes; } /** * Prevent canonical redirects that drop the language, and loops. */ public function redirect_canonical( $redirect_url, $requested_url ) { if ( ! $redirect_url ) { return $redirect_url; } $lang = Languages::current(); $redirect = $this->convert( $this->strip( (string) $redirect_url ), $lang ); if ( untrailingslashit( $redirect ) === untrailingslashit( (string) $requested_url ) ) { return false; } // For subdomain/domain modes WP would bounce to the main host; keep ours. if ( in_array( $this->mode(), array( 'subdomain', 'domain' ), true ) && wp_parse_url( $redirect, PHP_URL_HOST ) !== wp_parse_url( (string) $redirect_url, PHP_URL_HOST ) ) { return $redirect; } return $redirect_url; } /** * A singular post requested under the wrong language prefix is redirected to * the right URL: its translation in this language, or the post's own language. */ public function enforce_post_language(): void { if ( ! is_singular() || is_front_page() || is_preview() ) { return; } $post = get_queried_object(); if ( ! $post instanceof \WP_Post || ! PostTypes::is_translatable( $post->post_type ) ) { return; } $post_lang = Groups::lang_of( 'post', (int) $post->ID ); $current = Languages::current(); if ( $post_lang === $current ) { return; } $tr = Groups::translation( 'post', (int) $post->ID, $current ); $target = ( $tr && 'publish' === get_post_status( $tr ) ) ? get_permalink( $tr ) : get_permalink( $post ); if ( $target ) { wp_safe_redirect( $target, $tr ? 301 : 302, 'TranslatePlus' ); exit; } } /** * Translated static front page / posts page. * * @param mixed $value Page ID. */ public function translate_page_option( $value ) { if ( ! $value || Languages::is_source_current() || ! $this->is_frontend() ) { return $value; } $tr = Groups::translation( 'post', (int) $value, Languages::current() ); return $tr ?: $value; } /** * Translations whose slug collides get a language suffix instead of "-2". */ public function unique_slug( $slug, $post_id, $status, $type, $parent, $original ) { if ( $slug === $original || ! $post_id || ! Groups::is_translation( 'post', (int) $post_id ) ) { return $slug; } $lang = Languages::slug( Groups::lang_of( 'post', (int) $post_id ) ); $candidate = $original . '-' . $lang; remove_filter( 'wp_unique_post_slug', array( $this, 'unique_slug' ), 10 ); $unique = wp_unique_post_slug( $candidate, $post_id, $status, $type, $parent ); add_filter( 'wp_unique_post_slug', array( $this, 'unique_slug' ), 10, 6 ); return $unique; } // ------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------ /** * Run a callback with the home_url language filter disabled * (e.g. url_to_postid(), which matches against the raw home URL). * * @return mixed */ public function without_filters( callable $fn ) { $prev = $this->converting; $this->converting = true; try { return $fn(); } finally { $this->converting = $prev; } } public function raw_home(): string { return trailingslashit( (string) get_option( 'home' ) ); } public function home_host(): string { return strtolower( (string) wp_parse_url( get_option( 'home' ), PHP_URL_HOST ) ); } /** Home path with trailing slash, e.g. "/" or "/blog/". */ public function home_path(): string { $path = (string) wp_parse_url( get_option( 'home' ), PHP_URL_PATH ); return trailingslashit( '/' . ltrim( $path, '/' ) ); } private function relative_path( string $path ): string { $base = $this->home_path(); if ( 0 === stripos( $path, $base ) ) { return '/' . substr( $path, strlen( $base ) ); } return $path; } public function is_internal( string $url ): bool { if ( '/' === ( $url[0] ?? '' ) && '/' !== ( $url[1] ?? '' ) ) { return false; // Relative URLs are left alone. } $host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) ); if ( '' === $host ) { return false; } $base = $this->home_host(); if ( $host === $base ) { return true; } if ( 'subdomain' === $this->mode() && substr( $host, -strlen( '.' . $base ) ) === '.' . $base ) { return (bool) Languages::from_slug( substr( $host, 0, -strlen( '.' . $base ) ) ); } if ( 'domain' === $this->mode() ) { return in_array( $host, (array) $this->settings->get( 'domains', array() ), true ); } return false; } private function is_excluded( string $url ): bool { $path = (string) wp_parse_url( $url, PHP_URL_PATH ); if ( preg_match( '#/(wp-admin|wp-content|wp-includes|wp-json)(/|$)|/wp-[a-z-]+\.php$|/xmlrpc\.php$|\.(xml|xsl|txt|css|js|jpe?g|png|gif|webp|svg|ico|pdf|zip|mp4|mp3|woff2?)$#i', $path ) ) { return true; } /** * Filter whether a URL must never be language-converted. * * @param bool $excluded Excluded. * @param string $url URL. */ return (bool) apply_filters( 'translateplus_url_excluded', false, $url ); } private function replace_host( string $url, string $host ): string { $parts = wp_parse_url( $url ); $parts['host'] = $host; return $this->rebuild( $parts, $parts['path'] ?? '' ); } private function rebuild( array $parts, string $path ): string { $out = ''; if ( isset( $parts['scheme'] ) ) { $out .= $parts['scheme'] . ':'; } if ( isset( $parts['host'] ) ) { $out .= '//' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); } $out .= $path; if ( isset( $parts['query'] ) && '' !== $parts['query'] ) { $out .= '?' . $parts['query']; } if ( isset( $parts['fragment'] ) ) { $out .= '#' . $parts['fragment']; } return $out; } }