*/ private $cache = array(); public function __construct( Router $router ) { $this->router = $router; } public function register(): void { if ( ! $this->router->is_frontend() ) { return; } add_filter( 'the_content', array( $this, 'filter' ), 100 ); add_filter( 'widget_block_content', array( $this, 'filter' ), 100 ); add_filter( 'widget_text', array( $this, 'filter' ), 100 ); add_filter( 'term_description', array( $this, 'filter' ), 100 ); add_filter( 'woocommerce_short_description', array( $this, 'filter' ), 100 ); } public function filter( $html ) { if ( Languages::is_source_current() || ! is_string( $html ) || false === stripos( $html, 'href' ) ) { return $html; } return (string) preg_replace_callback( '#(]*?\bhref\s*=\s*)(["\'])([^"\']*)\2#i', function ( $m ) { return $m[1] . $m[2] . esc_url( $this->localize( html_entity_decode( $m[3] ) ) ) . $m[2]; }, $html ); } public function localize( string $url, string $lang = '' ): string { $lang = $lang ?: Languages::current(); if ( '' === $url || preg_match( '#^(\#|mailto:|tel:|javascript:|data:)#i', $url ) ) { return $url; } $abs = $url; if ( '/' === $url[0] && '/' !== ( $url[1] ?? '' ) ) { $abs = rtrim( $this->router->raw_home(), '/' ) . $url; } if ( ! $this->router->is_internal( $abs ) ) { return $url; } $key = $lang . '|' . $abs; if ( isset( $this->cache[ $key ] ) ) { return $this->cache[ $key ]; } $cached = wp_cache_get( md5( $key ), 'translateplus_links' ); if ( false !== $cached ) { return $this->cache[ $key ] = $cached; } $stripped = $this->router->strip( $abs ); $post_id = $this->router->without_filters( static function () use ( $stripped ) { return url_to_postid( $stripped ); } ); $out = ''; if ( $post_id ) { $tr = Groups::translation( 'post', Groups::source_id( 'post', (int) $post_id ), $lang ); if ( $tr && 'publish' === get_post_status( $tr ) ) { $out = (string) get_permalink( $tr ); // Keep query string and fragment from the original link. $q = wp_parse_url( $abs, PHP_URL_QUERY ); $f = wp_parse_url( $abs, PHP_URL_FRAGMENT ); $out .= ( $q ? '?' . $q : '' ) . ( $f ? '#' . $f : '' ); } } if ( '' === $out ) { $out = $this->router->convert( $stripped, $lang ); } wp_cache_set( md5( $key ), $out, 'translateplus_links', HOUR_IN_SECONDS ); return $this->cache[ $key ] = $out; } }