int, 'body' => array )`. * * @return array|\WP_Error */ public static function request( $method, $path, $body = null, $args = array() ) { $conn = Settings::connection(); $api_key = $args['api_key'] ?? ( $conn['api_key'] ?? '' ); $auth = $args['auth'] ?? true; if ( $auth && '' === $api_key ) { return new \WP_Error( 'langferry_not_connected', __( 'This site is not connected to Langferry.', 'langferry' ), array( 'status' => 0 ) ); } if ( ! Settings::is_allowed_cloud_url( Settings::cloud_url() ) ) { return new \WP_Error( 'langferry_insecure_cloud_url', __( 'The Langferry Cloud URL must use HTTPS.', 'langferry' ), array( 'status' => 0 ) ); } $headers = array( 'Accept' => 'application/json', 'X-LF-Plugin-Version' => LANGFERRY_VERSION, 'X-LF-Site-Url' => home_url(), ); if ( $auth ) { $headers['Authorization'] = 'Bearer ' . $api_key; } if ( null !== $body ) { $headers['Content-Type'] = 'application/json'; } $response = wp_remote_request( Settings::cloud_url() . '/api/v1' . $path, array( 'method' => $method, 'headers' => $headers, 'body' => null === $body ? null : wp_json_encode( $body ), 'timeout' => $args['timeout'] ?? 15, 'redirection' => 0, 'user-agent' => 'Langferry/' . LANGFERRY_VERSION . '; ' . home_url(), ) ); if ( is_wp_error( $response ) ) { set_transient( 'langferry_cloud_backoff', time(), self::BACKOFF_SECONDS ); Settings::update_connection( array( 'last_error' => $response->get_error_message() ) ); return new \WP_Error( 'langferry_network', $response->get_error_message(), array( 'status' => 0 ) ); } $status = (int) wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); $data = '' === $raw ? array() : json_decode( $raw, true ); if ( $status >= 200 && $status < 300 ) { return is_array( $data ) ? $data : array(); } $code = is_array( $data ) && isset( $data['error']['code'] ) ? $data['error']['code'] : 'http_' . $status; $message = is_array( $data ) && isset( $data['error']['message'] ) ? $data['error']['message'] : sprintf( 'Langferry Cloud returned HTTP %d.', $status ); if ( 401 === $status && $auth ) { // Key revoked or rotated elsewhere: stop translating until reconnected. Settings::update_connection( array( 'api_key_invalid' => true ) ); } if ( $status >= 500 ) { set_transient( 'langferry_cloud_backoff', time(), self::BACKOFF_SECONDS ); } return new \WP_Error( 'langferry_' . $code, $message, array( 'status' => $status, 'body' => is_array( $data ) ? $data : array() ) ); } public static function in_backoff() { return false !== get_transient( 'langferry_cloud_backoff' ); } /** * Pull site info, plan, entitlements and (if newer) config from the cloud. * * @return true|\WP_Error */ public static function sync() { $data = self::request( 'GET', '/site', null, array( 'timeout' => 10 ) ); if ( is_wp_error( $data ) ) { return $data; } $conn = Settings::connection(); Settings::update_connection( array( 'site_id' => $data['site']['id'] ?? '', 'site_name' => $data['site']['name'] ?? '', 'plan' => $data['plan'] ?? array(), 'entitlements' => $data['entitlements'] ?? array(), 'usage' => $data['usage'] ?? array(), 'push_secret' => $data['push_secret'] ?? '', 'dashboard_url' => $data['dashboard_url'] ?? '', 'last_sync' => time(), 'last_error' => '', 'api_key_invalid' => false, ) ); $remote_version = (int) ( $data['config_version'] ?? 0 ); $local_version = (int) ( $conn['config_version'] ?? 0 ); $remote_config = is_array( $data['config'] ?? null ) ? $data['config'] : array(); $local_config = Settings::config(); if ( 0 === $local_version && empty( $remote_config['languages'] ) && ! empty( $local_config['languages'] ) ) { // Freshly connected site that was configured before connecting: keep local choices. $pushed = self::push_config( $local_config, $remote_version ); return is_wp_error( $pushed ) ? $pushed : true; } if ( $remote_version > $local_version || empty( $conn['config_version'] ) ) { Settings::save_config( $remote_config, $remote_version ); do_action( 'langferry_config_updated', 'cloud' ); } return true; } /** * Save config to the cloud. On a version conflict the cloud copy wins and is * stored locally (the caller should tell the user). * * @return array|\WP_Error Normalized config on success. */ public static function push_config( array $config, $base_version = null ) { $base_version = null === $base_version ? Settings::config_version() : (int) $base_version; // PHP encodes an empty array as JSON [] — the API expects an object. $config['custom_domains'] = (object) $config['custom_domains']; $config['switcher']['flags'] = (object) ( $config['switcher']['flags'] ?? array() ); $data = self::request( 'PUT', '/site/config', array( 'config' => $config, 'base_version' => $base_version, ) ); if ( is_wp_error( $data ) ) { $err = $data->get_error_data(); if ( 409 === ( $err['status'] ?? 0 ) && ! empty( $err['body']['config'] ) ) { Settings::save_config( $err['body']['config'], (int) $err['body']['config_version'] ); } return $data; } Settings::save_config( $data['config'], (int) $data['config_version'] ); do_action( 'langferry_config_updated', 'local' ); return $data['config']; } /** * Translate HTML segments. Returns an array aligned with $segments; untranslated * entries are null. Never throws; failures just leave entries null. * * @param string[] $segments * @return array{translations: array, error: \WP_Error|null} */ /** * Send text to Langferry Cloud for translation, in batches. * * @param string $purpose page | slug | email. Langferry Cloud translates slugs and email text * only on the plans that include them (402 not_in_plan otherwise). * @param bool $private Text with personal data (see Privacy). * @param string $requester Who asked (Traffic): person | search_engine | pretranslate. The cloud keeps * part of the site's budget for people. * @param bool $main Pre-translation of a main page (ruling R66): sent as "main": true, which * lets the cloud use that part for it, only with the requester * pretranslate. No main key otherwise. * @return array{translations: array, error: \WP_Error|null, paced: int|null} paced: seconds to wait * when the cloud said the site's budget doesn't allow more yet. */ public static function translate( array $segments, $source, $target, $purpose = 'page', $private = false, $requester = 'person', $main = false ) { $result = array_fill( 0, count( $segments ), null ); $error = null; $paced = null; if ( empty( $segments ) ) { return array( 'translations' => $result, 'error' => null, 'paced' => null, ); } if ( self::in_backoff() ) { return array( 'translations' => $result, 'error' => new \WP_Error( 'langferry_backoff', 'Cloud temporarily unavailable.' ), 'paced' => null, ); } $batches = array(); $batch = array(); $chars = 0; foreach ( $segments as $i => $segment ) { $len = strlen( $segment ); if ( $batch && ( count( $batch ) >= self::BATCH_SEGMENTS || $chars + $len > self::BATCH_CHARS ) ) { $batches[] = $batch; $batch = array(); $chars = 0; } $batch[ $i ] = $segment; $chars += $len; } if ( $batch ) { $batches[] = $batch; } foreach ( $batches as $batch ) { $body = array( 'source_lang' => $source, 'target_lang' => $target, 'format' => 'html', 'segments' => array_values( $batch ), 'purpose' => $purpose, 'private' => (bool) $private, // the cloud doesn't keep it in its shared cache 'requester' => in_array( $requester, array( 'person', 'search_engine', 'pretranslate' ), true ) ? $requester : 'person', ); if ( true === $main && 'pretranslate' === $body['requester'] ) { $body['main'] = true; // Only JSON true counts (ruling R66). } $data = self::request( 'POST', '/translate', $body, array( 'timeout' => 30 ) ); if ( is_wp_error( $data ) ) { $error = $data; $refusal = $data->get_error_data()['body'] ?? array(); // 402 still carries cached translations (misses are null). if ( 402 !== (int) ( $data->get_error_data()['status'] ?? 0 ) || empty( $refusal['translations'] ) ) { break; // Auth or network problems won't fix themselves mid-page. } $data = $refusal; } $keys = array_keys( $batch ); foreach ( (array) ( $data['translations'] ?? array() ) as $j => $translation ) { if ( isset( $keys[ $j ] ) && is_string( $translation ) ) { $result[ $keys[ $j ] ] = $translation; } } if ( ! empty( $data['usage'] ) ) { Settings::update_connection( array( 'usage' => $data['usage'] ) ); } if ( ! empty( $data['paced'] ) ) { // The rest of the page would get the same answer: stop here, the misses stay pending. $paced = isset( $data['retry_after'] ) ? (int) $data['retry_after'] : 300; break; } } return array( 'translations' => $result, 'error' => $error, 'paced' => $paced, ); } }