> lang => hash => translation. */ private $maps = array(); /** @var array Newly discovered strings this request. */ private $buffer = array(); /** @var array Strings seen on this page (for the visual editor). */ private $seen = array(); /** @var bool */ private $track_seen = false; /** @var bool */ private $active = false; public function __construct( Settings $settings, Translator $translator ) { $this->settings = $settings; $this->translator = $translator; } private static function table(): string { global $wpdb; return $wpdb->prefix . 'tp_strings'; } public static function hash( string $domain, string $context, string $text ): string { return md5( $domain . "\x04" . $context . "\x04" . $text ); } public function register(): void { add_action( self::AUTO_HOOK, array( $this, 'auto_translate_all' ) ); add_action( 'init', array( $this, 'schedule' ) ); // Hooks are added at 'init' so that the current language is known and the // thousands of gettext calls made while plugins load are not affected. add_action( 'init', array( $this, 'activate' ), 1 ); add_action( 'shutdown', array( $this, 'flush' ) ); } public function schedule(): void { if ( ! function_exists( 'as_has_scheduled_action' ) || ! $this->settings->get( 'auto_translate' ) ) { return; } if ( ! as_has_scheduled_action( self::AUTO_HOOK, array(), 'translateplus' ) ) { as_schedule_recurring_action( time() + 300, 15 * MINUTE_IN_SECONDS, self::AUTO_HOOK, array(), 'translateplus' ); } } public function activate(): void { $router = \TranslatePlus\Core\Router::instance(); if ( ! $router || ! $router->is_frontend() || Languages::is_source_current() ) { return; } $this->active = true; // Read the final page HTML (WordPress 6.9 template output buffer) so only // strings that are actually visible get registered. The output is not modified. add_action( 'wp_finalized_template_enhancement_output_buffer', array( $this, 'capture_output' ) ); add_filter( 'gettext', array( $this, 'gettext' ), 99, 3 ); add_filter( 'gettext_with_context', array( $this, 'gettext_with_context' ), 99, 4 ); add_filter( 'ngettext', array( $this, 'ngettext' ), 99, 5 ); add_filter( 'ngettext_with_context', array( $this, 'ngettext_with_context' ), 99, 6 ); foreach ( array( 'blogname', 'blogdescription' ) as $option ) { add_filter( 'option_' . $option, function ( $value ) use ( $option ) { return $this->get( 'site', $option, (string) $value ); } ); } add_filter( 'widget_title', function ( $title ) { return '' === (string) $title ? $title : $this->get( 'widgets', 'title', (string) $title ); } ); add_filter( 'widget_text', function ( $text ) { return $this->get( 'widgets', 'text', (string) $text ); } ); add_filter( 'widget_block_content', function ( $content ) { return Segmenter::walk( (string) $content, 'widget', function ( $key, $text ) { return $this->get( 'widgets', 'block', $text ); } ); } ); } public function is_active(): bool { return $this->active; } public function track_seen( bool $on = true ): void { $this->track_seen = $on; } /** @return array */ public function seen(): array { return $this->seen; } // ------------------------------------------------------------------ // gettext filters // ------------------------------------------------------------------ public function gettext( $translation, $text, $domain ) { return $this->filter( $translation, (string) $text, (string) $domain, '' ); } public function gettext_with_context( $translation, $text, $context, $domain ) { return $this->filter( $translation, (string) $text, (string) $domain, (string) $context ); } public function ngettext( $translation, $single, $plural, $number, $domain ) { return $this->filter( $translation, 1 === (int) $number ? (string) $single : (string) $plural, (string) $domain, '' ); } public function ngettext_with_context( $translation, $single, $plural, $number, $context, $domain ) { return $this->filter( $translation, 1 === (int) $number ? (string) $single : (string) $plural, (string) $domain, (string) $context ); } /** * @param mixed $translation Current translation (from .mo files). */ private function filter( $translation, string $text, string $domain, string $context ) { // A real language pack already translated it. if ( $translation !== $text || in_array( $domain, self::SKIP_DOMAINS, true ) ) { return $translation; } return $this->get( $domain, $context, $text ); } /** * Translation of a registered string in the current language (registers it if new). */ public function get( string $domain, string $context, string $text, string $lang = '' ): string { $lang = $lang ?: Languages::current(); if ( $lang === Languages::source() || '' === trim( $text ) ) { return $text; } $hash = self::hash( $domain, $context, $text ); $map = $this->map( $lang ); $tr = $map[ $hash ] ?? null; if ( $this->track_seen && Translator::is_translatable( $text ) ) { $this->seen[ $hash ] = array( 'hash' => $hash, 'domain' => $domain, 'context' => $context, 'source' => $text, 'translation' => (string) $tr, ); } if ( null !== $tr && '' !== $tr ) { return $tr; } if ( null === $tr && $this->settings->get( 'capture_strings', true ) && count( $this->buffer ) < self::MAX_BUFFER && mb_strlen( $text ) <= 5000 && Translator::is_translatable( $text ) ) { $this->buffer[ $hash ] = array( $domain, $context, $text ); } return $text; } /** * @return array hash => translation ('' when untranslated). */ private function map( string $lang ): array { if ( isset( $this->maps[ $lang ] ) ) { return $this->maps[ $lang ]; } $key = 'translateplus_strings_' . md5( $lang ); $map = wp_cache_get( $key, 'translateplus' ); if ( false === $map ) { $map = get_transient( $key ); } if ( ! is_array( $map ) ) { global $wpdb; $map = array(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT hash, translation FROM %i WHERE lang = %s", $wpdb->tp_strings, $lang ), ARRAY_A ); // phpcs:ignore WordPress.DB foreach ( $rows as $r ) { $map[ $r['hash'] ] = (string) $r['translation']; } set_transient( $key, $map, DAY_IN_SECONDS ); } wp_cache_set( $key, $map, 'translateplus' ); $this->maps[ $lang ] = $map; return $map; } public static function flush_cache( ?string $lang = null ): void { $instance = \TranslatePlus\Plugin::instance(); if ( $instance ) { $instance->strings()->forget_maps(); } foreach ( $lang ? array( $lang ) : Languages::targets() as $l ) { $key = 'translateplus_strings_' . md5( $l ); delete_transient( $key ); wp_cache_delete( $key, 'translateplus' ); } } public function forget_maps(): void { $this->maps = array(); } /** * Persist strings discovered on this request, for every target language. */ /** @var string|null Final page HTML (null when no page was rendered). */ private $page_html = null; /** * @param string $html Final page output. */ public function capture_output( $html ): void { $this->page_html = (string) $html; $this->flush(); } /** * Persist strings discovered on this request that appear in the output. * Strings registered for menus, widgets and site options are always kept. * Runs when the page output is finalized, and again at shutdown for requests * without HTML output (only the always-kept strings are saved then). */ public function flush(): void { if ( ! $this->buffer ) { return; } $html = null === $this->page_html ? '' : self::visible_text( $this->page_html ); $items = array(); foreach ( $this->buffer as $item ) { list( $domain, , $text ) = $item; $always = in_array( $domain, array( 'menus', 'site', 'widgets', 'acf-options', 'woocommerce-attributes' ), true ); if ( $always || ( '' !== $html && self::appears_in( $text, $html ) ) ) { $items[] = $item; } } $this->buffer = array(); if ( $items ) { $this->register_many( $items ); } } /** * Visible text of a page: text nodes plus user-facing attributes. */ public static function visible_text( string $html ): string { $start = stripos( $html, '#is', ' ', $html ); $attrs = array(); if ( preg_match_all( '#\s(?:alt|title|placeholder|aria-label|value|data-label)\s*=\s*(["\'])(.*?)\1#is', $html, $m ) ) { $attrs = $m[2]; } $text = wp_strip_all_tags( $html ) . "\n" . implode( "\n", $attrs ); $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); return (string) preg_replace( '/\s+/u', ' ', $text ); } /** * Whether a string (possibly containing placeholders) is visible on the page. * * @param string $visible Output of visible_text(). */ public static function appears_in( string $text, string $visible ): bool { // Use the longest literal chunk between placeholders such as %s / %1$d. $chunks = preg_split( '/%(?:\d+\$)?[sdfu]|\{[a-z_]+\}/i', html_entity_decode( wp_strip_all_tags( $text ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ); usort( $chunks, static function ( $a, $b ) { return strlen( $b ) - strlen( $a ); } ); $needle = trim( (string) preg_replace( '/\s+/u', ' ', (string) ( $chunks[0] ?? '' ) ) ); if ( mb_strlen( $needle ) < 2 ) { return false; } foreach ( array( $needle, html_entity_decode( wptexturize( $needle ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) as $candidate ) { if ( preg_match( '/(? $items domain, context, text. */ public function register_many( array $items ): int { global $wpdb; $now = current_time( 'mysql', true ); $n = 0; foreach ( $items as list( $domain, $context, $text ) ) { foreach ( Languages::targets() as $lang ) { $n += (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->prepare( "INSERT IGNORE INTO %i (hash, domain, context, lang, source, translation, status, updated_at) VALUES (%s, %s, %s, %s, %s, '', 'untranslated', %s)", $wpdb->tp_strings, self::hash( $domain, $context, $text ), substr( $domain, 0, 100 ), substr( $context, 0, 191 ), $lang, $text, $now ) ); } } if ( $n ) { self::flush_cache(); } return $n; } // ------------------------------------------------------------------ // Management (REST / CLI) // ------------------------------------------------------------------ /** * @param array $q lang, domain, status, search, page, per_page. */ public function query( array $q ): array { global $wpdb; $lang = (string) ( $q['lang'] ?? '' ); $domain = (string) ( $q['domain'] ?? '' ); $status = (string) ( $q['status'] ?? '' ); $like = empty( $q['search'] ) ? '' : '%' . $wpdb->esc_like( (string) $q['search'] ) . '%'; $per_page = min( 200, max( 1, (int) ( $q['per_page'] ?? 50 ) ) ); $page = max( 1, (int) ( $q['page'] ?? 1 ) ); $offset = ( $page - 1 ) * $per_page; // phpcs:disable WordPress.DB.DirectDatabaseQuery $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE lang = %s AND ( %s = '' OR domain = %s ) AND ( %s = '' OR status = %s ) AND ( %s = '' OR source LIKE %s OR translation LIKE %s )", $wpdb->tp_strings, $lang, $domain, $domain, $status, $status, $like, $like, $like ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, hash, domain, context, source, translation, status, updated_at FROM %i WHERE lang = %s AND ( %s = '' OR domain = %s ) AND ( %s = '' OR status = %s ) AND ( %s = '' OR source LIKE %s OR translation LIKE %s ) ORDER BY domain ASC, id ASC LIMIT %d OFFSET %d", $wpdb->tp_strings, $lang, $domain, $domain, $status, $status, $like, $like, $like, $per_page, $offset ), ARRAY_A ); // phpcs:enable $domains = $wpdb->get_results( $wpdb->prepare( "SELECT domain, COUNT(*) total, SUM(status <> %s) translated FROM %i WHERE lang = %s GROUP BY domain ORDER BY domain", 'untranslated', $wpdb->tp_strings, $lang ), ARRAY_A ); // phpcs:ignore WordPress.DB return array( 'items' => array_map( static function ( $r ) { $r['id'] = (int) $r['id']; return $r; }, $rows ), 'total' => $total, 'pages' => (int) ceil( $total / $per_page ), 'domains' => array_map( static function ( $d ) { return array( 'domain' => $d['domain'], 'total' => (int) $d['total'], 'translated' => (int) $d['translated'], ); }, $domains ), ); } /** * @param array $edits Edits. */ public function save( array $edits, string $status = 'manual' ): int { global $wpdb; $n = 0; $langs = array(); foreach ( $edits as $e ) { $id = (int) ( $e['id'] ?? 0 ); if ( ! $id && ! empty( $e['hash'] ) && ! empty( $e['lang'] ) ) { $id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE hash = %s AND lang = %s", $wpdb->tp_strings, $e['hash'], $e['lang'] ) ); // phpcs:ignore WordPress.DB } if ( ! $id ) { continue; } $tr = (string) ( $e['translation'] ?? '' ); $n += (int) $wpdb->update( // phpcs:ignore WordPress.DB self::table(), array( 'translation' => $tr, 'status' => '' === $tr ? 'untranslated' : $status, 'updated_at' => current_time( 'mysql', true ), ), array( 'id' => $id ) ); $langs[ (string) $wpdb->get_var( $wpdb->prepare( "SELECT lang FROM %i WHERE id = %d", $wpdb->tp_strings, $id ) ) ] = true; // phpcs:ignore WordPress.DB } foreach ( array_keys( $langs ) as $l ) { self::flush_cache( $l ); } return $n; } /** * Import translations for (domain, context, source) triples, e.g. from a translated PO file. * * @param array $rows domain, context, source, translation. */ public function import( array $rows, string $lang, string $status = 'auto' ): int { $this->register_many( array_map( static function ( $r ) { return array( $r[0], $r[1], $r[2] ); }, $rows ) ); global $wpdb; $n = 0; foreach ( $rows as list( $domain, $context, $source, $translation ) ) { if ( '' === (string) $translation ) { continue; } $n += (int) $wpdb->query( // phpcs:ignore WordPress.DB $wpdb->prepare( "UPDATE %i SET translation = %s, status = %s, updated_at = %s WHERE hash = %s AND lang = %s AND status <> 'manual'", $wpdb->tp_strings, $translation, $status, current_time( 'mysql', true ), self::hash( $domain, $context, $source ), $lang ) ); } self::flush_cache( $lang ); return $n; } /** * Machine-translate untranslated strings for a language. * * @param int[] $ids Restrict to these row IDs (optional). * @return array{translated:int, remaining:int} * @throws ApiException On API failure. */ public function auto_translate( string $lang, int $limit = 200, array $ids = array(), string $domain = '' ): array { global $wpdb; $id_list = implode( ',', array_filter( array_map( 'intval', $ids ) ) ); // Explicit IDs select those rows; otherwise every untranslated string. Optional domain filter. $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->prepare( "SELECT id, source FROM %i WHERE lang = %s AND ( ( %s <> '' AND INSTR( CONCAT( ',', %s, ',' ), CONCAT( ',', id, ',' ) ) > 0 ) OR ( %s = '' AND status = 'untranslated' ) ) AND ( %s = '' OR domain = %s ) LIMIT %d", $wpdb->tp_strings, $lang, $id_list, $id_list, $id_list, $domain, $domain, $limit ), ARRAY_A ); if ( $rows ) { $segments = array(); foreach ( $rows as $r ) { $segments[ (string) $r['id'] ] = $r['source']; } $out = $this->translator->translate( $segments, Languages::source(), $lang ); foreach ( $out as $id => $tr ) { $wpdb->update( self::table(), array( 'translation' => $tr, 'status' => 'auto', 'updated_at' => current_time( 'mysql', true ) ), array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB } self::flush_cache( $lang ); } $remaining = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE lang = %s AND status = 'untranslated'" . ( $domain ? ' AND domain = %s' : '' ), array_merge( array( $wpdb->tp_strings ), $domain ? array( $lang, $domain ) : array( $lang ) ) ) ); // phpcs:ignore WordPress.DB return array( 'translated' => count( $rows ), 'remaining' => $remaining, ); } /** * Background: translate newly discovered strings for every language. */ public function auto_translate_all(): void { if ( ! $this->settings->get( 'auto_translate' ) ) { return; } foreach ( Languages::targets() as $lang ) { try { $this->auto_translate( $lang, 500 ); } catch ( ApiException $e ) { Logger::error( 'String auto-translation failed: ' . $e->getMessage() ); return; } } } /** * Language of a string row ('' when it does not exist). */ public function lang_of( int $id ): string { global $wpdb; return (string) $wpdb->get_var( $wpdb->prepare( 'SELECT lang FROM %i WHERE id = %d', $wpdb->tp_strings, $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } public function delete( array $ids ): int { global $wpdb; $ids = array_filter( array_map( 'intval', $ids ) ); if ( ! $ids ) { return 0; } // Delete the string in every language, not only the row passed. $id_placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery $hashes = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT hash FROM %i WHERE id IN ($id_placeholders)", array_merge( array( $wpdb->tp_strings ), array_values( $ids ) ) ) ); if ( ! $hashes ) { return 0; } $hash_placeholders = implode( ',', array_fill( 0, count( $hashes ), '%s' ) ); $n = (int) $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE hash IN ($hash_placeholders)", array_merge( array( $wpdb->tp_strings ), $hashes ) ) ); // phpcs:enable self::flush_cache(); return $n; } }