api = $api; $this->strings = $strings; self::$instance = $this; } public static function instance(): ?self { return self::$instance; } public function register(): void { add_action( self::POLL_HOOK, array( $this, 'poll' ) ); } public static function token(): string { $token = (string) get_option( self::TOKEN_OPT ); if ( '' === $token ) { $token = wp_generate_password( 32, false ); update_option( self::TOKEN_OPT, $token, false ); } return $token; } public static function jobs(): array { return (array) get_option( self::OPTION, array() ); } private static function put( string $job_id, array $data ): void { $jobs = self::jobs(); $jobs[ $job_id ] = array_merge( $jobs[ $job_id ] ?? array(), $data ); // Keep the 20 most recent. uasort( $jobs, static function ( $a, $b ) { return ( $b['created'] ?? 0 ) <=> ( $a['created'] ?? 0 ); } ); update_option( self::OPTION, array_slice( $jobs, 0, 20, true ), false ); } /** * Installed themes and plugins with a text domain. * * @return array */ public static function sources(): array { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $out = array(); foreach ( get_plugins() as $file => $data ) { if ( empty( $data['TextDomain'] ) || ! is_plugin_active( $file ) || 'translateplus' === $data['TextDomain'] ) { continue; } $dir = WP_PLUGIN_DIR . '/' . dirname( $file ); $out[] = array( 'domain' => $data['TextDomain'], 'name' => $data['Name'], 'type' => 'plugin', 'pot' => self::find_pot( $dir, (string) $data['DomainPath'], $data['TextDomain'] ), ); } $theme = wp_get_theme(); foreach ( array_filter( array( $theme, $theme->parent() ) ) as $t ) { $domain = (string) $t->get( 'TextDomain' ); if ( $domain ) { $out[] = array( 'domain' => $domain, 'name' => $t->get( 'Name' ), 'type' => 'theme', 'pot' => self::find_pot( $t->get_stylesheet_directory(), (string) $t->get( 'DomainPath' ), $domain ), ); } } return $out; } private static function find_pot( string $dir, string $domain_path, string $domain ): string { $candidates = array_unique( array_filter( array( $dir . '/' . trim( $domain_path, '/' ), $dir . '/languages', $dir . '/i18n/languages', $dir . '/lang', ) ) ); foreach ( $candidates as $c ) { if ( is_readable( "$c/$domain.pot" ) ) { return "$c/$domain.pot"; } $any = glob( "$c/*.pot" ); if ( $any ) { return $any[0]; } } return ''; } /** * Start a file job for a text domain. * * @param string[] $langs Target languages. * @throws ApiException|\RuntimeException On failure. */ public function start( string $domain, array $langs ): array { $langs = array_values( array_intersect( $langs ?: Languages::targets(), Languages::targets() ) ); $source = current( wp_list_filter( self::sources(), array( 'domain' => $domain ) ) ); if ( $source && $source['pot'] ) { $file = $source['pot']; $filename = basename( $file ); $format = 'po'; } else { // No .pot shipped: send the strings discovered on the site as JSON. $found = $this->strings->query( array( 'lang' => $langs[0] ?? '', 'domain' => $domain, 'per_page' => 200, ) ); if ( ! $found['total'] ) { throw new \RuntimeException( esc_html__( 'No strings found for this text domain yet. Browse your site in a translated language first, or install a version that ships a .pot file.', 'translateplus' ) ); } $pairs = array(); for ( $page = 1; $page <= $found['pages']; $page++ ) { $chunk = 1 === $page ? $found : $this->strings->query( array( 'lang' => $langs[0], 'domain' => $domain, 'per_page' => 200, 'page' => $page ) ); foreach ( $chunk['items'] as $item ) { $pairs[ $item['source'] ] = $item['source']; } } $file = wp_tempnam( $domain . '.json' ); file_put_contents( $file, wp_json_encode( $pairs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents $filename = $domain . '.json'; $format = 'json'; } $webhook = add_query_arg( 'token', self::token(), rest_url( 'translateplus/v1/webhook/i18n' ) ); $res = $this->api->create_i18n_job( $file, $filename, Languages::source(), $langs, $webhook ); if ( 'json' === $format ) { wp_delete_file( $file ); } $job_id = (string) ( $res['job_id'] ?? '' ); if ( '' === $job_id ) { throw new \RuntimeException( esc_html__( 'The translation service did not return a job ID.', 'translateplus' ) ); } self::put( $job_id, array( 'job_id' => $job_id, 'domain' => $domain, 'name' => $source['name'] ?? $domain, 'langs' => $langs, 'format' => $format, 'status' => 'processing', 'progress' => 0, 'created' => time(), 'error' => '', ) ); as_schedule_single_action( time() + 60, self::POLL_HOOK, array( $job_id ), 'translateplus' ); Logger::info( sprintf( 'File translation job %s started for %s (%s).', $job_id, $domain, implode( ', ', $langs ) ) ); return self::jobs()[ $job_id ]; } /** * Check a job; import when complete, otherwise poll again. */ public function poll( $job_id ): void { $job_id = (string) $job_id; $job = self::jobs()[ $job_id ] ?? null; if ( ! $job || 'processing' !== $job['status'] ) { return; } try { $status = $this->api->i18n_job_status( $job_id ); } catch ( ApiException $e ) { if ( $e->is_retryable() ) { as_schedule_single_action( time() + 120, self::POLL_HOOK, array( $job_id ), 'translateplus' ); } else { self::put( $job_id, array( 'status' => 'failed', 'error' => $e->getMessage() ) ); } return; } $state = strtolower( (string) ( $status['status'] ?? '' ) ); $total = max( 1, (int) ( $status['total_keys'] ?? 0 ) ); self::put( $job_id, array( 'progress' => (int) round( (int) ( $status['translated_keys'] ?? 0 ) / $total * 100 ) ) ); if ( in_array( $state, array( 'completed', 'complete', 'done', 'success', 'finished' ), true ) ) { $this->import( $job_id ); return; } if ( in_array( $state, array( 'failed', 'error', 'cancelled' ), true ) ) { self::put( $job_id, array( 'status' => 'failed', 'error' => (string) ( $status['error_message'] ?? $state ) ) ); return; } if ( time() - (int) $job['created'] > 6 * HOUR_IN_SECONDS ) { self::put( $job_id, array( 'status' => 'failed', 'error' => __( 'Timed out.', 'translateplus' ) ) ); return; } as_schedule_single_action( time() + 90, self::POLL_HOOK, array( $job_id ), 'translateplus' ); } /** * Download each language and import into the string layer. */ public function import( string $job_id ): void { $job = self::jobs()[ $job_id ] ?? null; if ( ! $job ) { return; } $imported = 0; try { foreach ( $job['langs'] as $lang ) { $body = $this->api->i18n_job_download( $job_id, $lang ); $rows = self::parse( $body, (string) $job['domain'] ); $imported += $this->strings->import( $rows, $lang ); } } catch ( \Throwable $e ) { self::put( $job_id, array( 'status' => 'failed', 'error' => $e->getMessage() ) ); Logger::error( sprintf( 'Importing file job %s failed: %s', $job_id, $e->getMessage() ) ); return; } self::put( $job_id, array( 'status' => 'completed', 'progress' => 100, 'imported' => $imported ) ); Logger::info( sprintf( 'File translation job %s imported %d strings.', $job_id, $imported ) ); } /** * Parse a translated PO or JSON file into string rows. * * @return array */ public static function parse( string $body, string $domain ): array { $rows = array(); $json = json_decode( $body, true ); if ( is_array( $json ) ) { $walk = static function ( $data, $prefix ) use ( &$walk, &$rows, $domain ) { foreach ( $data as $k => $v ) { if ( is_array( $v ) ) { $walk( $v, $prefix . $k . '.' ); } elseif ( is_string( $v ) ) { $rows[] = array( $domain, '', (string) $k, $v ); } } }; $walk( $json, '' ); return $rows; } if ( ! class_exists( 'PO' ) ) { require_once ABSPATH . WPINC . '/pomo/po.php'; } $tmp = wp_tempnam( 'translateplus.po' ); file_put_contents( $tmp, $body ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents $po = new \PO(); $po->import_from_file( $tmp ); wp_delete_file( $tmp ); foreach ( $po->entries as $entry ) { $tr = $entry->translations[0] ?? ''; if ( '' !== $entry->singular && '' !== $tr ) { $rows[] = array( $domain, (string) $entry->context, $entry->singular, $tr ); } if ( $entry->is_plural && ! empty( $entry->translations[1] ) ) { $rows[] = array( $domain, (string) $entry->context, $entry->plural, $entry->translations[1] ); } } return $rows; } }