text, the apply pass swaps in translations by key. * * @package TranslatePlus */ namespace TranslatePlus\Translation; defined( 'ABSPATH' ) || exit; final class Segmenter { /** Block attributes that hold visible text. */ const TEXT_ATTRS = array( 'content', 'text', 'caption', 'alt', 'title', 'label', 'placeholder', 'buttonText', 'submitButtonText', 'submitButtonLabel', 'description', 'heading', 'subheading', 'linkText', 'citation', 'value', 'prefix', 'suffix', 'tooltip', 'emptyText', 'readMoreText', 'moreText', 'buttonLabel', 'question', 'answer', 'name', 'subtitle', 'excerpt', 'message', 'html' ); /** Shortcode attributes that hold visible text (Divi, WPBakery, common plugins). */ const SHORTCODE_ATTRS = array( 'title', 'heading', 'subhead', 'subtitle', 'text', 'button_text', 'button_one_text', 'button_two_text', 'alt', 'title_text', 'caption', 'label', 'content', 'description', 'name', 'position', 'company_name', 'author', 'job_title', 'placeholder', 'submit_button_text', 'success_message', 'more_text', 'read_more_text', 'prefix', 'suffix', 'tab_title', 'header', 'footer', 'quote', 'btn_title', 'link_text', 'el_title' ); /** * Collect segments. * * @return array key => source text. */ public static function collect( string $content, string $prefix = 'content' ): array { $found = array(); self::walk( $content, $prefix, static function ( $key, $text ) use ( &$found ) { $found[ $key ] = $text; return $text; } ); return $found; } /** * Rebuild content with translations. * * @param array $translations key => translation. */ public static function apply( string $content, array $translations, string $prefix = 'content' ): string { return self::walk( $content, $prefix, static function ( $key, $text ) use ( $translations ) { return array_key_exists( $key, $translations ) ? $translations[ $key ] : $text; } ); } /** * @param callable $fn function( string $key, string $text ): string. */ public static function walk( string $content, string $prefix, callable $fn ): string { if ( '' === trim( $content ) ) { return $content; } if ( function_exists( 'has_blocks' ) && has_blocks( $content ) ) { $blocks = parse_blocks( $content ); $blocks = self::walk_blocks( $blocks, $prefix, $fn ); return serialize_blocks( $blocks ); } return self::walk_html( $content, $prefix, $fn ); } private static function walk_blocks( array $blocks, string $path, callable $fn ): array { foreach ( $blocks as $i => $block ) { $key = $path . '.' . $i; if ( null === $block['blockName'] ) { // Freeform HTML between blocks (also classic content inside a block document). $html = self::walk_html( (string) $block['innerHTML'], $key, $fn ); $blocks[ $i ]['innerHTML'] = $html; $blocks[ $i ]['innerContent'] = array( $html ); continue; } if ( ! empty( $block['attrs'] ) ) { $blocks[ $i ]['attrs'] = self::walk_attrs( $block['attrs'], $key . '.a', $fn ); } $inner_html = ''; foreach ( $block['innerContent'] as $j => $chunk ) { if ( ! is_string( $chunk ) ) { continue; } $new = self::walk_fragment( $chunk, $key . '.c' . $j, $fn, $block['blockName'] ); $blocks[ $i ]['innerContent'][ $j ] = $new; $inner_html .= $new; } if ( ! empty( $block['innerBlocks'] ) ) { $blocks[ $i ]['innerBlocks'] = self::walk_blocks( $block['innerBlocks'], $key, $fn ); } $blocks[ $i ]['innerHTML'] = $inner_html; } return $blocks; } /** * One block HTML fragment. Fragments without text (wrappers) are skipped. */ private static function walk_fragment( string $html, string $key, callable $fn, string $block_name ): string { if ( ! Translator::is_translatable( $html ) ) { return $html; } // Raw code must never be translated. if ( in_array( $block_name, array( 'core/code', 'core/preformatted' ), true ) ) { return $html; } if ( in_array( $block_name, array( 'core/html', 'core/shortcode', 'core/freeform' ), true ) ) { return self::walk_html( $html, $key, $fn ); } // Keep the outer whitespace and the block's own wrapper element out of the // segment, so translators edit text and inline markup only. list( $before, $inner, $after ) = self::unwrap( $html ); if ( ! Translator::is_translatable( $inner ) ) { return $html; } return $before . $fn( $key, $inner ) . $after; } /** * Split "

Text bold

" into wrapper start, inner HTML and wrapper end. * Only a single, balanced outer element is unwrapped. * * @return array{0:string, 1:string, 2:string} */ public static function unwrap( string $html ): array { if ( ! preg_match( '/^(\s*)(.*?)(\s*)$/s', $html, $ws ) ) { return array( '', $html, '' ); } $body = $ws[2]; if ( preg_match( '#^(<([a-z][a-z0-9]*)\b[^>]*>)(.*)()$#is', $body, $m ) && ! preg_match( '#^(img|br|hr|input)$#i', $m[2] ) ) { $tag = strtolower( $m[2] ); $inner = $m[3]; // The outer element must enclose everything: depth may never drop below zero. $depth = 0; $ok = true; if ( preg_match_all( '#<(/?)' . preg_quote( $tag, '#' ) . '\b[^>]*>#i', $inner, $tags, PREG_SET_ORDER ) ) { foreach ( $tags as $t ) { $depth += '/' === $t[1] ? -1 : 1; if ( $depth < 0 ) { $ok = false; break; } } } if ( $ok && 0 === $depth && '' !== trim( $inner ) ) { return array( $ws[1] . $m[1], $inner, $m[4] . $ws[3] ); } } return array( $ws[1], $body, $ws[3] ); } /** * @param array $attrs Block attributes. */ private static function walk_attrs( array $attrs, string $key, callable $fn ): array { foreach ( $attrs as $name => $value ) { $k = $key . '.' . $name; if ( is_array( $value ) ) { $attrs[ $name ] = self::walk_attrs( $value, $k, $fn ); } elseif ( is_string( $value ) && ( is_int( $name ) || in_array( (string) $name, self::TEXT_ATTRS, true ) ) && self::looks_like_text( $value ) ) { $attrs[ $name ] = $fn( $k, $value ); } } return $attrs; } /** * Classic HTML / shortcode content: paragraphs and shortcode text. */ private static function walk_html( string $html, string $key, callable $fn ): string { $tokens = preg_split( '/(\[\/?[a-zA-Z0-9_\-]+(?:\s[^\]]*)?\/?\])/', $html, -1, PREG_SPLIT_DELIM_CAPTURE ); $out = ''; foreach ( $tokens as $t => $token ) { if ( '' === $token ) { continue; } if ( '[' === $token[0] && preg_match( '/^\[\/?[a-zA-Z0-9_\-]+/', $token ) ) { $out .= self::walk_shortcode_tag( $token, $key . '.s' . $t, $fn ); continue; } $out .= self::walk_paragraphs( $token, $key . '.t' . $t, $fn ); } return $out; } private static function walk_paragraphs( string $html, string $key, callable $fn ): string { $parts = preg_split( '/(\n\s*\n)/', $html, -1, PREG_SPLIT_DELIM_CAPTURE ); foreach ( $parts as $p => $part ) { if ( 1 === $p % 2 || ! Translator::is_translatable( $part ) ) { continue; } list( $before, $inner, $after ) = self::unwrap( $part ); if ( Translator::is_translatable( $inner ) ) { $parts[ $p ] = $before . $fn( $key . '.p' . ( $p / 2 ), $inner ) . $after; } } return implode( '', $parts ); } private static function walk_shortcode_tag( string $tag, string $key, callable $fn ): string { return (string) preg_replace_callback( '/\b([a-zA-Z0-9_\-]+)=("|\')(.*?)\2/s', static function ( $m ) use ( $key, $fn ) { if ( ! in_array( strtolower( $m[1] ), self::SHORTCODE_ATTRS, true ) || ! self::looks_like_text( $m[3] ) ) { return $m[0]; } $tr = $fn( $key . '.' . $m[1], $m[3] ); return $m[1] . '=' . $m[2] . str_replace( $m[2], '"' === $m[2] ? '"' : ''', $tr ) . $m[2]; }, $tag ); } /** * Heuristic: human-readable text rather than an ID, URL, colour or slug. */ public static function looks_like_text( string $value ): bool { $value = trim( $value ); if ( '' === $value || ! preg_match( '/\p{L}/u', $value ) ) { return false; } if ( preg_match( '#^(https?:|mailto:|tel:|/|\#|var:|rgba?\(|hsla?\(|[a-z0-9]+(-[a-z0-9]+)+$|[a-z]+_[a-z0-9_]+$|\d+(\.\d+)?(px|em|rem|%|vh|vw)?$)#i', $value ) ) { return false; } // Single lowercase token without spaces is usually a machine value ("left", "large"). if ( ! preg_match( '/\s/', $value ) && preg_match( '/^[a-z0-9_\-]+$/', $value ) ) { return false; } return true; } }