Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/easy-form-builder/emsfb.php
+++ b/easy-form-builder/emsfb.php
@@ -3,7 +3,7 @@
* Plugin Name: Easy Form Builder
* Plugin URI: https://whitestudio.team
* Description: Create multi-step WordPress forms with drag and drop, confirmation codes, notification emails, and free custom email notification templates with a built-in visual editor. Build professional contact, survey, payment, login, and registration forms without coding.
- * Version: 4.2.0
+ * Version: 4.3.0
* Author: WhiteStudio
* Author URI: https://whitestudio.team
* Text Domain: easy-form-builder
@@ -24,7 +24,7 @@
define("EMSFB_PLUGIN_DIRECTORY", plugin_dir_path(__FILE__));
}
if (!defined("EMSFB_PLUGIN_VERSION")) {
- define("EMSFB_PLUGIN_VERSION", "4.2.0");
+ define("EMSFB_PLUGIN_VERSION", "4.3.0");
}
if (!defined("EMSFB_DB_VERSION")) {
// 1.2 adds the emsfb_stts_ indexes (sid, lookup, date). Bumping this is what
--- a/easy-form-builder/includes/admin/class-Emsfb-addon.php
+++ b/easy-form-builder/includes/admin/class-Emsfb-addon.php
@@ -52,9 +52,9 @@
$ac = get_setting_Emsfb('decoded');
$php_addon_issues = emsfb_get_incompatible_addons_efb( $ac );
- // After a plugin update, block the Add-ons page until missing add-on files
- // are reinstalled. The Recover button on the blocking screen performs the
- // reinstall, then offers an Activate (reload) button.
+ // Missing add-on files never lock this page, not even right after a plugin
+ // update: it is where an add-on that cannot be restored is reinstalled or
+ // switched off. The recovery card is shown above the catalogue instead.
$efb_recovery_fn = get_efbFunction();
$addon_recovery = $efb_recovery_fn->recover_missing_addons_efb( null, 'addons' );
if ( ! empty( $addon_recovery['recovered'] ) ) {
@@ -62,10 +62,9 @@
return;
}
$addon_recovery_state = $efb_recovery_fn->addon_recovery_state_efb();
- if ( 'block' === $addon_recovery_state ) {
- echo $efb_recovery_fn->render_addon_recovery_ui_efb( 'block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
- return;
- }
+ // A locale now in use may lack an add-on language file pruned at install.
+ // Runtime scope above: translations never lock or banner this page.
+ $efb_recovery_fn->process_addon_i18n_refetch_efb();
$server_name = str_replace("www.", "", isset($_SERVER['HTTP_HOST']) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '');
/*
* The shared helper is the single source of truth for catalogue requests.
@@ -188,7 +187,7 @@
<div id="alert_efb" class="efb mx-5"></div>
- <?php if ( 'inline' === $addon_recovery_state ) : ?>
+ <?php if ( 'none' !== $addon_recovery_state ) : ?>
<?php echo $efb_recovery_fn->render_addon_recovery_ui_efb( 'inline' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php endif; ?>
--- a/easy-form-builder/includes/admin/class-Emsfb-admin.php
+++ b/easy-form-builder/includes/admin/class-Emsfb-admin.php
@@ -43,6 +43,7 @@
add_action('wp_ajax_check_email_server_efb', [$this, 'check_email_server_admin']);
add_action('wp_ajax_efb_save_onboarding_email', [$this, 'efb_save_onboarding_email']);
add_action('wp_ajax_efb_complete_onboarding', [$this, 'efb_complete_onboarding']);
+ add_action('wp_ajax_efb_dismiss_onboarding', [$this, 'efb_dismiss_onboarding']);
add_action('wp_ajax_add_addons_Emsfb', [$this, 'add_addons_Emsfb']);
add_action('wp_ajax_remove_addons_Emsfb', [$this, 'remove_addons_Emsfb']);
add_action('wp_ajax_update_file_Emsfb', array( $this,'file_upload_public'));
@@ -300,6 +301,7 @@
unset($valp[0]['sms_msg_new_noti']);
unset($valp[0]['sms_msg_responsed_noti']);
unset($valp[0]['sms_msg_recived_user']);
+ unset($valp[0]['sms_msg_recived_usr']);
if(isset($valp[0]['sms_admins_phone_no'])){unset($valp[0]['sms_admins_phone_no']);}
}
@@ -313,6 +315,7 @@
unset($valp[0]['telegram_msg_new_noti']);
unset($valp[0]['telegram_msg_responsed_noti']);
unset($valp[0]['telegram_msg_recived_user']);
+ unset($valp[0]['telegram_msg_recived_usr']);
unset($valp[0]['telegram_bot_token']);
unset($valp[0]['telegram_admin_chat_ids']);
}
@@ -533,6 +536,29 @@
wp_send_json_success($response, 200);
}
+ /*
+ * The plan gate, decided here rather than by the licensing server.
+ * That server only refuses add-ons it actually sells, so it approves
+ * Conditional Logic for every site and approves everything for
+ * localhost - the Add-ons page drew a lock that the install never
+ * honoured, and clicking it installed the add-on anyway.
+ */
+ if (!$efbFunction->addon_plan_allows_install_efb($post_value)) {
+ $required_package = $efbFunction->addon_required_package_efb($post_value);
+ $this->addon_install_log_efb('request_blocked_local_plan', [
+ 'requested_addon' => $post_value,
+ 'required_package' => $required_package,
+ 'local_package' => (int) get_option('emsfb_pro', 2),
+ ]);
+ wp_send_json_error([
+ 'success' => false,
+ 'm' => 3 === $required_package ? $lang['thisFeatureAvailableFreePlusPro'] : $lang['proUnlockMsg'],
+ 'code' => 'addon_plan_required',
+ 'required_package' => $required_package,
+ ], 200);
+ return;
+ }
+
// Block script injection attempts and make it visible in the logs.
if ($this->isScript($post_value)) {
$this->addon_install_log_efb('request_blocked_script_value', [
@@ -544,9 +570,6 @@
return;
}
- // Form Security & Spam Protection ships inside the plugin. The
- // licensing endpoint still verifies its package before local files are
- // enabled.
// File access problems are common on shared hosts, so log the full
// preflight status before any network requests are attempted.
$status = emsfb_get_file_access_status_efb();
@@ -839,8 +862,21 @@
'response_data' => $data,
]);
$remote_reason = isset($data->reason) ? sanitize_key($data->reason) : '';
+ /*
+ * The server states a refusal as {"status":false,"error":"You do
+ * not have permission"} - no `reason` at all. Read only as a
+ * reason, that is an unrecognised failure, so a site on the
+ * wrong plan was told "the server responded with an invalid
+ * request" instead of being offered the upgrade.
+ */
+ $remote_error = isset($data->error) && is_scalar($data->error) ? trim((string) $data->error) : '';
+ if ('' === $remote_reason && '' !== $remote_error && false !== stripos($remote_error, 'permission')) {
+ $remote_reason = 'plan_required';
+ }
if (in_array($remote_reason, ['plan_required', 'package_required', 'premium_required'], true)) {
- $required_package = isset($data->required_package) ? (int) $data->required_package : 1;
+ $required_package = isset($data->required_package)
+ ? (int) $data->required_package
+ : $efbFunction->addon_required_package_efb($post_value);
$entitlement = $this->addon_local_entitlement_efb($required_package);
$this->addon_install_log_efb('remote_response_plan_required', [
@@ -1912,6 +1948,32 @@
wp_send_json_success(array('completed' => true));
}
+ /**
+ * The admin closed the email step (x or Escape) without running the
+ * delivery test. That is a deliberate "not now", and the step used to
+ * reopen on every Panel and Create load until a test was run. The test
+ * stays available in General Settings, and the builder keeps warning while
+ * email sending is off.
+ *
+ * Kept apart from completion: emsfb_onboarding_completed_at still means a
+ * test actually ran. A plan that was never saved is not affected - the
+ * plan chooser keeps coming back on its own until one is.
+ */
+ public function efb_dismiss_onboarding() {
+ $efbFunction = get_efbFunction();
+ if (!check_ajax_referer('wp_rest', 'nonce', false) || !$efbFunction->user_permission_efb_admin_dashboard()) {
+ wp_send_json_error(array('message' => esc_html__('You do not have permission to complete setup.', 'easy-form-builder')), 403);
+ }
+
+ $dismissed = false;
+ if ((bool) get_option('emsfb_onboarding_pending', false)) {
+ update_option('emsfb_onboarding_pending', 0, false);
+ update_option('emsfb_onboarding_dismissed_at', current_time('mysql'), false);
+ $dismissed = true;
+ }
+ wp_send_json_success(array('dismissed' => $dismissed));
+ }
+
private function start_email_tester_efb($efbFunction, $ac) {
$admin_email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
if (!is_email($admin_email)) {
@@ -3026,6 +3088,15 @@
. ' (' . $r->get_error_message() . ')'
);
}
+ // Keep only the add-on language files of locales this site uses. A global
+ // function (this class does not extend efbFunction); it never throws and
+ // never changes the install result.
+ if ( ! function_exists( 'emsfb_prune_addon_languages_efb' ) && function_exists( 'get_efbFunction' ) ) {
+ get_efbFunction();
+ }
+ if ( function_exists( 'emsfb_prune_addon_languages_efb' ) ) {
+ emsfb_prune_addon_languages_efb();
+ }
return true;
}
public function file_upload_public(){
@@ -3642,9 +3713,21 @@
if (!in_array($current_package_type, [0, 1, 2, 3], true)) {
$current_package_type = 2;
}
+ /*
+ * Until a plan is chosen, emsfb_pro holds -1 (a fresh install), the
+ * legacy 10, or nothing at all. The coercion above reads those as Free
+ * for the downgrade checks, but they are not a saved choice: letting
+ * them short-cut as "unchanged" meant "Start with Free" never wrote
+ * anything, and the plan chooser reopened on every Panel and Create
+ * load. Only a stored 1, 2 or 3 - the values getSelectedPlan_efb()
+ * recognises - can be unchanged.
+ */
+ $stored_package_type = get_option('emsfb_pro', null);
+ $has_saved_plan = is_numeric($stored_package_type)
+ && in_array((int) $stored_package_type, [1, 2, 3], true);
$onboarding_pending = emsfb_onboarding_pending_efb();
$target_package_type = $selected_plan === 'free_plus' ? 3 : ($selected_plan === 'free' ? 2 : 1);
- if ($target_package_type === $current_package_type) {
+ if ($has_saved_plan && $target_package_type === $current_package_type) {
wp_send_json_success(array(
'success' => true,
'plan' => $selected_plan,
@@ -3724,11 +3807,12 @@
*/
$disabled_addons = array();
if ($is_downgrade) {
- $addon_keys = $efbFunction->get_all_addon_keys_efb();
- if ($package_type_efb === 3) {
- // Offline Forms and Conditional Logic are available in Free Plus.
- $addon_keys = array_diff($addon_keys, array('AdnOF', 'AdnSMF'));
- }
+ // Which add-ons the new plan keeps is the same question the install
+ // gate answers, so both read one table (addon_required_package_efb).
+ $addon_keys = array_diff(
+ $efbFunction->get_all_addon_keys_efb(),
+ $efbFunction->addon_keys_allowed_by_package_efb($package_type_efb)
+ );
foreach ($addon_keys as $addon_key) {
if (isset($settings->{$addon_key}) && (int) $settings->{$addon_key} !== 0) {
$disabled_addons[] = $addon_key;
--- a/easy-form-builder/includes/admin/class-Emsfb-create.php
+++ b/easy-form-builder/includes/admin/class-Emsfb-create.php
@@ -75,16 +75,20 @@
echo $efbFunction->render_addon_recovery_reload_ui_efb(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
return;
}
- $addon_health = $efbFunction->get_addon_local_health_efb( $settings );
+ // Scope 'admin': a package from before the add-on shipped its own translations
+ // counts as missing here (and only here and on Panel), so recovery replaces it.
+ $addon_health = $efbFunction->get_addon_local_health_efb( $settings, 'admin' );
$download_addons = ! empty( $addon_health['missing'] );
// After a plugin update, do not load the builder until missing add-on
// files have been reinstalled — show a blocking recovery screen instead.
- $addon_recovery_state = $efbFunction->addon_recovery_state_efb( $settings );
+ $addon_recovery_state = $efbFunction->addon_recovery_state_efb( $settings, 'admin' );
if ( 'block' === $addon_recovery_state ) {
- echo $efbFunction->render_addon_recovery_ui_efb( 'block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
+ echo $efbFunction->render_addon_recovery_ui_efb( 'block', 'admin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
return;
}
+ // A locale now in use may lack an add-on language file pruned at install.
+ $efbFunction->process_addon_i18n_refetch_efb();
if(isset($settings->AdnPAP) && $settings->AdnPAP==1){
if(!file_exists(EMSFB_PLUGIN_DIRECTORY."/vendor/paypal/paypalefb.php")) {
@@ -176,7 +180,7 @@
<?php echo $noti_pro; ?>
<div id="alert_efb" class="efb mx-5"></div>
<?php if ( 'inline' === $addon_recovery_state ) : ?>
- <?php echo $efbFunction->render_addon_recovery_ui_efb( 'inline' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
+ <?php echo $efbFunction->render_addon_recovery_ui_efb( 'inline', 'admin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php endif; ?>
<div class="efb modal fade " id="settingModalEfb" aria-hidden="true" aria-labelledby="settingModalEfb" role="dialog" tabindex="-1" data-backdrop="static" >
<div class="efb modal-dialog modal-dialog-centered " id="settingModalEfb_" >
@@ -412,6 +416,7 @@
unset($valp[0]['sms_msg_new_noti']);
unset($valp[0]['sms_msg_responsed_noti']);
unset($valp[0]['sms_msg_recived_user']);
+ unset($valp[0]['sms_msg_recived_usr']);
if(isset($valp[0]['sms_admins_phone_no'])){unset($valp[0]['sms_admins_phone_no']);}
}
$valx =json_encode($valp,JSON_UNESCAPED_UNICODE);
--- a/easy-form-builder/includes/admin/class-Emsfb-panel.php
+++ b/easy-form-builder/includes/admin/class-Emsfb-panel.php
@@ -68,16 +68,20 @@
echo $efbFunction->render_addon_recovery_reload_ui_efb(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
return;
}
- $addon_health = $efbFunction->get_addon_local_health_efb( $ac );
+ // Scope 'admin': a package from before the add-on shipped its own translations
+ // counts as missing here (and only here and on Create), so recovery replaces it.
+ $addon_health = $efbFunction->get_addon_local_health_efb( $ac, 'admin' );
$download_addons = ! empty( $addon_health['missing'] );
// After a plugin update, block the panel until missing add-on files are
// reinstalled; show the recovery screen instead of the panel contents.
- $addon_recovery_state = $efbFunction->addon_recovery_state_efb( $ac );
+ $addon_recovery_state = $efbFunction->addon_recovery_state_efb( $ac, 'admin' );
if ( 'block' === $addon_recovery_state ) {
- echo $efbFunction->render_addon_recovery_ui_efb( 'block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
+ echo $efbFunction->render_addon_recovery_ui_efb( 'block', 'admin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
return;
}
+ // A locale now in use may lack an add-on language file pruned at install.
+ $efbFunction->process_addon_i18n_refetch_efb();
if(isset($ac->AdnPAP) && $ac->AdnPAP==1){
if(!file_exists(EMSFB_PLUGIN_DIRECTORY."/vendor/paypal/paypalefb.php")) {
@@ -204,7 +208,7 @@
</nav>
<div id="alert_efb" class="efb mx-5"></div>
<?php if ( 'inline' === $addon_recovery_state ) : ?>
- <?php echo $efbFunction->render_addon_recovery_ui_efb( 'inline' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
+ <?php echo $efbFunction->render_addon_recovery_ui_efb( 'inline', 'admin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php endif; ?>
<!-- end new nav -->
<div class="efb modal fade " id="settingModalEfb" aria-hidden="true" aria-labelledby="settingModalEfb" role="dialog" tabindex="-1" data-backdrop="static" >
--- a/easy-form-builder/includes/class-Emsfb-install.php
+++ b/easy-form-builder/includes/class-Emsfb-install.php
@@ -207,6 +207,7 @@
update_option('emsfb_onboarding_pending', 1, false);
update_option('emsfb_onboarding_initial_install', 1, false);
delete_option('emsfb_onboarding_completed_at');
+ delete_option('emsfb_onboarding_dismissed_at');
}
// Activation runs on every activate, not only the first one, and
--- a/easy-form-builder/includes/class-Emsfb-language-packs.php
+++ b/easy-form-builder/includes/class-Emsfb-language-packs.php
@@ -0,0 +1,2854 @@
+<?php
+/**
+ * Language packs downloaded at runtime: WhiteStudio first, wordpress.org second.
+ *
+ * The plugin ships a few languages itself (the "bundled" ones). Every other
+ * language the site uses - the site language, each user's language, every
+ * language of a multilingual plugin, every site of a network - is downloaded
+ * after activation and kept up to date: from the WhiteStudio language server
+ * (the ws-language-plugins-handler plugin), and from wordpress.org when
+ * WhiteStudio has no pack for that language or cannot be reached.
+ *
+ * Nothing in this file depends on the plugin that ships it, so it can be
+ * copied into another plugin. See docs/language-packs/README.md, "Porting".
+ *
+ * Rules this class keeps:
+ *
+ * 1. It never breaks the plugin. Every entry point is wrapped, the network is
+ * only used from WP-Cron, and a failure leaves the translations that were
+ * already installed exactly as they were.
+ * 2. WhiteStudio first, wordpress.org second, nothing third.
+ * 3. It never installs executable code from the network. WordPress includes
+ * .l10n.php files as PHP, so that file is generated here from the .mo,
+ * never taken from a download.
+ * 4. It only replaces translation files that came from WhiteStudio or
+ * wordpress.org. A translation someone made by hand is left alone.
+ * 5. It emails the admin once per outage, and only after this site's server
+ * has been unable to reach WhiteStudio for days. An error answered by the
+ * WhiteStudio server itself proves the connection works, so it never
+ * triggers an email.
+ */
+
+namespace Emsfb;
+
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
+class Language_Packs {
+
+ /** Written into the X-Generator header of every pack from WhiteStudio. */
+ const MARKER = 'WhiteStudio Language Packs';
+
+ const CLIENT_VERSION = '1.0.0';
+
+ /** Sent by the WhiteStudio language server on every response it produces. */
+ const SERVER_HEADER = 'x-ws-language-handler';
+
+ const CATALOG_TIMEOUT = 10;
+ const DOWNLOAD_TIMEOUT = 25;
+
+ /** Stop starting new installs after this many seconds; the rest continue in a follow-up event. */
+ const TIME_BUDGET = 20;
+
+ const LOCK_TTL = 600;
+ const MAX_PACKAGE_BYTES = 20971520;
+ const MAX_FILE_BYTES = 20971520;
+ const MAX_ZIP_ENTRIES = 500;
+ const MAX_SITES_SCANNED = 200;
+
+ /** Unreachable for at least this long (72 hours) and this many attempts before the admin is emailed. */
+ const NOTIFY_AFTER = 259200;
+ const NOTIFY_MIN_FAILURES = 3;
+
+ /** At most one email per 30 days, whatever happens. */
+ const NOTIFY_COOLDOWN = 2592000;
+
+ const NOTIFY_MAX_SEND_ATTEMPTS = 3;
+
+ /** How often an admin page load checks whether the site started using a new language. */
+ const WATCH_INTERVAL = 600;
+
+ /** Page views start at most one background run per hour. */
+ const BACKGROUND_THROTTLE = 3600;
+
+ /** No completed run for two days: WP-Cron is not running here, so a page view starts one. */
+ const DUE_AFTER = 172800;
+
+ /** The front-end trigger inside a cached page stops firing 30 minutes after the page was built. */
+ const TRIGGER_TTL = 1800;
+
+ /** Seconds the admin screen waits for an installation before offering to continue in English. */
+ const UI_TIMEOUT = 90;
+
+ /** Same kind of installation failure: one email per 30 days. */
+ const INSTALL_MAIL_COOLDOWN = 2592000;
+
+ /** WordPress's own locale format (see wp_get_installed_translations()). */
+ const LOCALE_PATTERN = '/^[a-z]{2,3}(?:_[A-Z]{2})?(?:_[a-z0-9]+)?$/';
+
+ /** @var array<string, Language_Packs> */
+ private static $instances = array();
+
+ /** @var array */
+ private $config;
+
+ /** @var array<string, array> Per-request cache of inspect_installed(). */
+ private $installed_cache = array();
+
+ /** @var array<string, bool> Per-request cache of bundled_file_exists(). */
+ private $bundled_cache = array();
+
+ /**
+ * Create the instance and hook it into WordPress. Never throws: a broken
+ * configuration only means there are no language packs.
+ *
+ * @param array $config See normalize_config().
+ * @return Language_Packs|null
+ */
+ public static function boot( array $config ) {
+ try {
+ $instance = new self( $config );
+ $prefix = $instance->config['prefix'];
+ if ( isset( self::$instances[ $prefix ] ) ) {
+ return self::$instances[ $prefix ];
+ }
+ self::$instances[ $prefix ] = $instance;
+ $instance->register_hooks();
+ return $instance;
+ } catch ( Throwable $e ) {
+ return null;
+ }
+ }
+
+ /**
+ * @param string $prefix The prefix the instance was booted with.
+ * @return Language_Packs|null
+ */
+ public static function instance( $prefix ) {
+ return isset( self::$instances[ $prefix ] ) ? self::$instances[ $prefix ] : null;
+ }
+
+ /**
+ * @param array $config See normalize_config().
+ * @throws InvalidArgumentException When a required value is missing.
+ */
+ public function __construct( array $config ) {
+ $this->config = self::normalize_config( $config );
+ }
+
+ /**
+ * @return array
+ */
+ public function get_config() {
+ return $this->config;
+ }
+
+ /**
+ * Configuration keys:
+ *
+ * - product Required. Product slug on the WhiteStudio language server.
+ * - text_domain Required. The plugin's text domain.
+ * - version Required. The plugin's version.
+ * - plugin_file Required. Main plugin file (activation/deactivation hooks).
+ * - prefix Required. Prefix of every option, event and filter ([a-z0-9_]).
+ * - servers Required. Base URLs of the WhiteStudio server, tried in order.
+ * - plugin_name Name used in the email.
+ * - wporg_slug Slug on wordpress.org; '' turns the wordpress.org fallback off.
+ * - bundled_locales Exact locales the plugin ships itself; never downloaded. en_US is always one.
+ * - bundled_dir Folder of the shipped translation files; those win over downloaded ones.
+ * - guide_url Manual installation guide linked from the email.
+ * - languages_dir Where packs are installed. Default WP_LANG_DIR/plugins/.
+ * - extra_locales Callable returning more locales the site uses.
+ * - enabled false turns every download off.
+ * - notify false turns the email off.
+ * - debug true writes a line to the PHP error log for each run.
+ * - inline false turns the first-visit installer off (then only WP-Cron installs packs).
+ * - capability Who sees the "installing language files" screen and may start it. Default install_languages.
+ * - blocking_screens Admin page slugs (?page=) where that screen blocks the page and reloads it when done.
+ * Every other admin screen gets a notice that never reloads.
+ * - front_script_handles Front-end script handles; a page that enqueues one of them can start a background install.
+ *
+ * @param array $config Raw configuration.
+ * @return array
+ * @throws InvalidArgumentException When a required value is missing.
+ */
+ private static function normalize_config( array $config ) {
+ $defaults = array(
+ 'product' => '',
+ 'text_domain' => '',
+ 'version' => '',
+ 'plugin_file' => '',
+ 'prefix' => '',
+ 'servers' => array(),
+ 'plugin_name' => '',
+ 'wporg_slug' => '',
+ 'bundled_locales' => array( 'en_US' ),
+ 'bundled_dir' => '',
+ 'guide_url' => '',
+ 'languages_dir' => '',
+ 'extra_locales' => null,
+ 'enabled' => true,
+ 'notify' => true,
+ 'debug' => false,
+ 'inline' => true,
+ 'capability' => 'install_languages',
+ 'blocking_screens' => array(),
+ 'front_script_handles' => array(),
+ );
+ $c = array_merge( $defaults, $config );
+
+ foreach ( array( 'product', 'text_domain', 'version', 'plugin_file', 'prefix' ) as $required ) {
+ $c[ $required ] = trim( (string) $c[ $required ] );
+ if ( '' === $c[ $required ] ) {
+ throw new InvalidArgumentException( 'Language_Packs: missing ' . $required );
+ }
+ }
+ if ( ! preg_match( '/^[a-z0-9_-]+$/', $c['product'] ) || ! preg_match( '/^[a-z0-9_]+$/', $c['prefix'] ) ) {
+ throw new InvalidArgumentException( 'Language_Packs: invalid product or prefix' );
+ }
+
+ $servers = array();
+ foreach ( (array) $c['servers'] as $server ) {
+ $server = untrailingslashit( trim( (string) $server ) );
+ if ( preg_match( '#^https?://[^/s]+#i', $server ) ) {
+ $servers[] = $server;
+ }
+ }
+ if ( empty( $servers ) ) {
+ throw new InvalidArgumentException( 'Language_Packs: no server' );
+ }
+ $c['servers'] = $servers;
+
+ $c['plugin_name'] = '' !== trim( (string) $c['plugin_name'] ) ? (string) $c['plugin_name'] : $c['text_domain'];
+ $c['wporg_slug'] = preg_replace( '/[^a-z0-9_-]/', '', strtolower( (string) $c['wporg_slug'] ) );
+ $bundled = array( 'en_US' );
+ foreach ( (array) $c['bundled_locales'] as $locale ) {
+ if ( preg_match( self::LOCALE_PATTERN, (string) $locale ) ) {
+ $bundled[] = (string) $locale;
+ }
+ }
+ $c['bundled_locales'] = array_values( array_unique( $bundled ) );
+ $c['bundled_dir'] = '' === (string) $c['bundled_dir'] ? '' : trailingslashit( (string) $c['bundled_dir'] );
+ $c['guide_url'] = (string) $c['guide_url'];
+
+ $languages_dir = (string) $c['languages_dir'];
+ if ( '' === $languages_dir ) {
+ $languages_dir = WP_LANG_DIR . '/plugins/';
+ }
+ $c['languages_dir'] = trailingslashit( $languages_dir );
+
+ $c['extra_locales'] = is_callable( $c['extra_locales'] ) || is_string( $c['extra_locales'] ) ? $c['extra_locales'] : null;
+ $c['enabled'] = (bool) $c['enabled'];
+ $c['notify'] = (bool) $c['notify'];
+ $c['debug'] = (bool) $c['debug'];
+ $c['inline'] = (bool) $c['inline'];
+ $c['capability'] = '' !== (string) $c['capability'] ? (string) $c['capability'] : 'install_languages';
+ $c['blocking_screens'] = array_values( array_map( 'strval', (array) $c['blocking_screens'] ) );
+ $c['front_script_handles'] = array_values( array_map( 'strval', (array) $c['front_script_handles'] ) );
+
+ return $c;
+ }
+
+ /**
+ * @return void
+ */
+ public function register_hooks() {
+ $file = $this->config['plugin_file'];
+
+ register_activation_hook( $file, array( $this, 'on_activation' ) );
+ register_deactivation_hook( $file, array( $this, 'on_deactivation' ) );
+
+ add_action( $this->key( 'sync' ), array( $this, 'run_sync' ), 10, 1 );
+ add_action( $this->key( 'daily' ), array( $this, 'run_daily' ) );
+ add_action( 'init', array( $this, 'maybe_schedule' ), 20 );
+ add_action( 'admin_init', array( $this, 'watch' ) );
+ add_action( 'update_option_WPLANG', array( $this, 'on_site_language_changed' ) );
+ add_action( 'update_site_option_WPLANG', array( $this, 'on_site_language_changed' ) );
+ add_action( 'upgrader_process_complete', array( $this, 'on_upgrade' ), 10, 2 );
+
+ add_filter( 'site_transient_update_plugins', array( $this, 'filter_update_offers' ) );
+ add_filter( 'lang_dir_for_domain', array( $this, 'filter_lang_dir' ), 10, 3 );
+
+ // The first visit installs a missing pack itself: some servers never run WP-Cron.
+ add_action( 'admin_notices', array( $this, 'admin_notice' ) );
+ add_action( 'admin_footer', array( $this, 'admin_footer' ) );
+ add_action( 'wp_footer', array( $this, 'front_footer' ), 100 );
+ add_action( 'wp_ajax_' . $this->key( 'install' ), array( $this, 'ajax_install' ) );
+ add_action( 'wp_ajax_' . $this->key( 'background' ), array( $this, 'ajax_background' ) );
+ add_action( 'wp_ajax_nopriv_' . $this->key( 'background' ), array( $this, 'ajax_background' ) );
+ }
+
+ /*
+ * ---------------------------------------------------------------------
+ * Scheduling
+ * ---------------------------------------------------------------------
+ */
+
+ /**
+ * Activation only schedules; the download happens in WP-Cron shortly after,
+ * never inside the activation request.
+ *
+ * @return void
+ */
+ public function on_activation() {
+ $this->guard(
+ function () {
+ $this->schedule_sync( 30, 'activation' );
+ }
+ );
+ }
+
+ /**
+ * Drops the schedule. Installed packs and the state stay: a reactivation
+ * should not download everything again.
+ *
+ * @return void
+ */
+ public function on_deactivation() {
+ $this->guard(
+ function () {
+ wp_clear_scheduled_hook( $this->key( 'daily' ) );
+ foreach ( array( 'activation', 'version', 'locales', 'retry', 'continue', 'manual' ) as $reason ) {
+ wp_clear_scheduled_hook( $this->key( 'sync' ), array( $reason ) );
+ }
+ $this->release_lock();
+ }
+ );
+ }
+
+ /**
+ * init: keep the daily event scheduled, or remove it when the feature is off.
+ *
+ * @return void
+ */
+ public function maybe_schedule() {
+ $this->guard(
+ function () {
+ $hook = $this->key( 'daily' );
+ if ( ! $this->is_enabled() ) {
+ if ( wp_next_scheduled( $hook ) ) {
+ wp_clear_scheduled_hook( $hook );
+ }
+ return;
+ }
+ if ( ! wp_next_scheduled( $hook ) ) {
+ // Spread the first run so a release does not bring every site to the server at once.
+ wp_schedule_event( time() + wp_rand( HOUR_IN_SECONDS, 12 * HOUR_IN_SECONDS ), 'daily', $hook );
+ }
+ }
+ );
+ }
+
+ /**
+ * admin_init, at most every WATCH_INTERVAL: sync soon when the plugin was
+ * updated (by any route, FTP included) or the site started using a language
+ * it has no pack for yet.
+ *
+ * @return void
+ */
+ public function watch() {
+ $this->guard(
+ function () {
+ if ( ! $this->is_enabled() || ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) ) {
+ return;
+ }
+ $throttle = $this->key( 'watched' );
+ if ( get_site_transient( $throttle ) ) {
+ return;
+ }
+ set_site_transient( $throttle, 1, self::WATCH_INTERVAL );
+
+ $state = $this->get_state();
+ if ( $state['synced_version'] !== $this->config['version'] ) {
+ $this->schedule_sync( 60, 'version' );
+ return;
+ }
+ $new = array_diff( $this->target_locales( true ), (array) $state['locales'] );
+ if ( ! empty( $new ) ) {
+ $this->schedule_sync( 30, 'locales' );
+ }
+ }
+ );
+ }
+
+ /**
+ * @return void
+ */
+ public function on_site_language_changed() {
+ $this->guard(
+ function () {
+ $this->schedule_sync( 30, 'locales' );
+ }
+ );
+ }
+
+ /**
+ * @param object $upgrader Unused.
+ * @param array $options Upgrade details.
+ * @return void
+ */
+ public function on_upgrade( $upgrader, $options ) {
+ $this->guard(
+ function () use ( $options ) {
+ if ( ! is_array( $options ) || ! isset( $options['type'], $options['action'] ) || 'plugin' !== $options['type'] || 'update' !== $options['action'] ) {
+ return;
+ }
+ $plugins = isset( $options['plugins'] ) ? (array) $options['plugins'] : ( isset( $options['plugin'] ) ? array( $options['plugin'] ) : array() );
+ if ( in_array( plugin_basename( $this->config['plugin_file'] ), $plugins, true ) ) {
+ $this->schedule_sync( 60, 'version' );
+ }
+ }
+ );
+ }
+
+ /**
+ * @param int $delay Seconds from now.
+ * @param string $reason activation|version|locales|retry|continue|manual.
+ * @return bool
+ */
+ private function schedule_sync( $delay, $reason ) {
+ if ( ! $this->is_enabled() ) {
+ return false;
+ }
+ $hook = $this->key( 'sync' );
+ $args = array( (string) $reason );
+ if ( wp_next_scheduled( $hook, $args ) ) {
+ return true;
+ }
+ return (bool) wp_schedule_single_event( time() + max( 0, (int) $delay ), $hook, $args );
+ }
+
+ /**
+ * @param string $reason Why the event was scheduled.
+ * @return void
+ */
+ public function run_sync( $reason = 'manual' ) {
+ $this->guard(
+ function () use ( $reason ) {
+ $this->sync( (string) $reason );
+ }
+ );
+ }
+
+ /**
+ * @return void
+ */
+ public function run_daily() {
+ $this->run_sync( 'daily' );
+ }
+
+ /*
+ * ---------------------------------------------------------------------
+ * The sync
+ * ---------------------------------------------------------------------
+ */
+
+ /**
+ * Bring the pack of every language this site uses up to date.
+ *
+ * @param string $reason Why it runs (daily, activation, version, locales, retry, continue, manual, inline, background).
+ * @param array $options first: a locale to handle before the others.
+ * @return array Summary: status, ws, wporg, results (locale => outcome), errors (locale => kind, detail),
+ * ws_error, blocker, pending, installed, notified.
+ */
+ public function sync( $reason = 'manual', array $options = array() ) {
+ $summary = array(
+ 'status' => '',
+ 'ws' => '',
+ 'wporg' => '',
+ 'results' => array(),
+ 'errors' => array(),
+ 'ws_error' => null,
+ 'blocker' => '',
+ 'pending' => array(),
+ 'installed' => array(),
+ 'notified' => false,
+ );
+
+ if ( ! $this->is_enabled() ) {
+ $summary['status'] = 'disabled';
+ return $summary;
+ }
+
+ $state = $this->get_state();
+
+ // On a network every site runs this event, but the language folder is shared: one daily run is enough.
+ if ( 'daily' === $reason && is_multisite() && 'complete' === $state['last_run']['status']
+ && $state['synced_version'] === $this->config['version']
+ && ( time() - (int) $state['last_run']['at'] ) < 20 * HOUR_IN_SECONDS ) {
+ $summary['status'] = 'recent';
+ return $summary;
+ }
+
+ if ( ! $this->acquire_lock() ) {
+ $summary['status'] = 'locked';
+ return $summary;
+ }
+
+ try {
+ if ( function_exists( 'set_time_limit' ) ) {
+ @set_time_limit( 120 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+
+ $started = time();
+ $locales = $this->target_locales();
+ if ( ! empty( $options['first'] ) && in_array( $options['first'], $locales, true ) ) {
+ $locales = array_values( array_unique( array_merge( array( (string) $options['first'] ), $locales ) ) );
+ }
+
+ $state['locales'] = $locales;
+ $state['synced_version'] = $this->config['version'];
+ $state['last_run'] = array(
+ 'at' => $started,
+ 'reason' => (string) $reason,
+ 'status' => '',
+ 'results' => array(),
+ );
+
+ if ( empty( $locales ) ) {
+ $state['last_run']['status'] = 'complete';
+ $summary['status'] = 'no_locales';
+ $this->save_state( $state );
+ $this->record_completed_sync();
+ return $summary;
+ }
+
+ $blocker = $this->write_blocker();
+ if ( '' !== $blocker ) {
+ $state['last_run']['status'] = $blocker;
+ $summary['status'] = $blocker;
+ $summary['blocker'] = $blocker;
+ $this->save_state( $state );
+ $this->record_completed_sync();
+ $this->log( 'not installing anything: ' . $blocker );
+ return $summary;
+ }
+
+ $ws = $this->fetch_ws_catalog( $locales );
+ $ws_ok = 'ok' === $ws['status'];
+ $results = array();
+ $errors = array();
+ $pending = array();
+ if ( ! $ws_ok ) {
+ $summary['ws_error'] = array(
+ 'kind' => 'unreachable' === $ws['status'] ? 'unreachable' : 'server',
+ 'detail' => (string) $ws['error'],
+ );
+ }
+ $wporg_candidates = array();
+ $ws_download_blocked = false;
+ $ws_download_worked = false;
+
+ foreach ( $locales as $locale ) {
+ $installed = $this->inspect_installed( $locale );
+
+ if ( $ws_ok && isset( $ws['translations'][ $locale ] ) ) {
+ if ( 'other' === $installed['source'] ) {
+ $results[ $locale ] = 'kept_custom';
+ continue;
+ }
+ $entry = $ws['translations'][ $locale ];
+ if ( ! $this->needs_install( $locale, $entry, $installed, true, $state['packs'] ) ) {
+ $results[ $locale ] = 'up_to_date_ws';
+ continue;
+ }
+ if ( ( time() - $started ) > self::TIME_BUDGET ) {
+ $pending[] = $locale;
+ continue;
+ }
+ $outcome = $this->install( $entry, $locale );
+ if ( $outcome['ok'] ) {
+ $results[ $locale ] = 'installed_ws';
+ $ws_download_worked = true;
+ $state['packs'][ $locale ] = $outcome['record'];
+ $summary['installed'][] = $locale;
+ continue;
+ }
+ $results[ $locale ] = 'failed_ws:' . $outcome['error'];
+ $errors[ $locale ] = array(
+ 'kind' => $outcome['kind'],
+ 'detail' => $outcome['detail'],
+ );
+ if ( 'unreachable' === $outcome['kind'] ) {
+ $ws_download_blocked = true;
+ $ws['error'] = $outcome['detail'];
+ }
+ // What is installed stays. Only a language with nothing at all goes to wordpress.org.
+ if ( ! $installed['exists'] ) {
+ $wporg_candidates[] = $locale;
+ }
+ continue;
+ }
+
+ if ( ! $ws_ok && 'ws' === $installed['source'] ) {
+ $results[ $locale ] = 'kept_ws';
+ continue;
+ }
+ if ( 'other' === $installed['source'] ) {
+ $results[ $locale ] = 'kept_custom';
+ continue;
+ }
+ $wporg_candidates[] = $locale;
+ }
+
+ $wporg_status = 'not_needed';
+ if ( ! empty( $wporg_candidates ) && '' === $this->config['wporg_slug'] ) {
+ $wporg_status = 'off';
+ foreach ( $wporg_candidates as $locale ) {
+ $results[ $locale ] = 'not_available';
+ }
+ } elseif ( ! empty( $wporg_candidates ) ) {
+ $wporg = $this->fetch_wporg_catalog( $wporg_candidates );
+ $wporg_status = $wporg['status'];
+ $state['wporg'] = array(
+ 'status' => $wporg['status'],
+ 'last_attempt_at' => time(),
+ 'last_error' => $wporg['error'],
+ );
+ foreach ( $wporg_candidates as $locale ) {
+ if ( 'ok' !== $wporg['status'] ) {
+ $results[ $locale ] = 'wporg_' . $wporg['status'];
+ if ( ! isset( $errors[ $locale ] ) ) {
+ $errors[ $locale ] = array(
+ 'kind' => 'unreachable' === $wporg['status'] ? 'unreachable' : 'server',
+ 'detail' => 'wordpress.org: ' . $wporg['error'],
+ );
+ }
+ continue;
+ }
+ if ( ! isset( $wporg['translations'][ $locale ] ) ) {
+ $results[ $locale ] = isset( $results[ $locale ] ) ? $results[ $locale ] : 'not_available';
+ continue;
+ }
+ $installed = $this->inspect_installed( $locale );
+ $entry = $wporg['translations'][ $locale ];
+ if ( ! $this->needs_install( $locale, $entry, $installed, $ws_ok, $state['packs'] ) ) {
+ $results[ $locale ] = 'up_to_date_wporg';
+ continue;
+ }
+ if ( ( time() - $started ) > self::TIME_BUDGET ) {
+ $pending[] = $locale;
+ continue;
+ }
+ $outcome = $this->install( $entry, $locale );
+ $results[ $locale ] = $outcome['ok'] ? 'installed_wporg' : 'failed_wporg:' . $outcome['error'];
+ if ( $outcome['ok'] ) {
+ $state['packs'][ $locale ] = $outcome['record'];
+ $summary['installed'][] = $locale;
+ unset( $errors[ $locale ] );
+ } else {
+ $errors[ $locale ] = array(
+ 'kind' => $outcome['kind'],
+ 'detail' => $outcome['detail'],
+ );
+ }
+ }
+ }
+
+ // A catalog that loads while every package download is intercepted is still "cannot connect".
+ $ws_status = $ws['status'];
+ if ( $ws_ok && $ws_download_blocked && ! $ws_download_worked ) {
+ $ws_status = 'unreachable';
+ }
+ $this->record_ws_health( $state, $ws_status, $ws['error'], $ws['server'] );
+
+ $state['last_run']['status'] = empty( $pending ) ? 'complete' : 'partial';
+ $state['last_run']['results'] = $results;
+
+ $summary['status'] = $state['last_run']['status'];
+ $summary['ws'] = $ws_status;
+ $summary['wporg'] = $wporg_status;
+ $summary['results'] = $results;
+ $summary['errors'] = $errors;
+ $summary['pending'] = $pending;
+ if ( 'unreachable' === $ws_status && null === $summary['ws_error'] ) {
+ $summary['ws_error'] = array(
+ 'kind' => 'unreachable',
+ 'detail' => (string) $ws['error'],
+ );
+ }
+
+ if ( 'unreachable' === $ws_status ) {
+ $this->schedule_retry( (int) $state['ws']['failures'] );
+ $summary['notified'] = $this->maybe_notify( $state, $locales, $wporg_status );
+ }
+ if ( ! empty( $pending ) ) {
+ $this->schedule_sync( 60, 'continue' );
+ }
+
+ $this->save_state( $state );
+ $this->record_completed_sync();
+ $this->log( 'run ' . $reason . ': ws=' . $ws_status . ' wporg=' . $wporg_status . ' ' . wp_json_encode( $results ) );
+ } finally {
+ $this->release_lock();
+ }
+
+ if ( ! empty( $summary['installed'] ) ) {
+ /**
+ * Fires after language packs were installed, so the plugin can drop caches built with the old strings.
+ *
+ * @param string[] $locales Locales that received a pack.
+ */
+ do_action( $this->key( 'installed' ), $summary['installed'] );
+ }
+
+ return $summary;
+ }
+
+ /**
+ * @param string $locale Locale.
+ * @param array $entry Catalog entry (source ws or wporg).
+ * @param array $installed inspect_installed() result.
+ * @param bool $ws_ok Whether the WhiteStudio catalog loaded in this run.
+ * @param array $packs Install records by locale.
+ * @return bool
+ */
+ private function needs_install( $locale, array $entry, array $installed, $ws_ok, array $packs ) {
+ if ( ! $installed['exists'] ) {
+ return true;
+ }
+ if ( 'other' === $installed['source'] ) {
+ return false;
+ }
+
+ $remote_updated = $this->timestamp( $entry['updated'] );
+
+ if ( 'ws' === $entry['source'] ) {
+ if ( 'ws' !== $installed['source'] ) {
+ return true;
+ }
+ $record = isset( $packs[ $locale ] ) && is_array( $packs[ $locale ] ) ? $packs[ $locale ] : null;
+ if ( $record && ! empty( $record['sha256'] ) && 'ws' === $record['source'] ) {
+ return $record['sha256'] !== $entry['sha256'];
+ }
+ return $remote_updated > $installed['updated'];
+ }
+
+ // wordpress.org. A WhiteStudio pack is only handed back when WhiteStudio answered and no longer has it.
+ if ( 'ws' === $installed['source'] ) {
+ return (bool) $ws_ok;
+ }
+ return $remote_updated > $installed['updated'];
+ }
+
+ /**
+ * @param array $state State, updated in place.
+ * @param string $status ok|unreachable|server_error.
+ * @param string $error Error detail.
+ * @param string $server Server that answered or failed.
+ * @return void
+ */
+ private function record_ws_health( array &$state, $status, $error, $server ) {
+ $now = time();
+ $ws = $state['ws'];
+
+ $ws['last_attempt_at'] = $now;
+ $ws['server'] = (string) $server;
+
+ if ( 'unreachable' === $status ) {
+ $ws['status'] = 'unreachable';
+ $ws['failures'] = (int) $ws['failures'] + 1;
+ $ws['first_failure_at'] = (int) $ws['first_failure_at'] > 0 ? (int) $ws['first_failure_at'] : $now;
+ $ws['last_error'] = (string) $error;
+ } else {
+ // Any answer from the WhiteStudio server - an error included - proves this site can reach it.
+ $ws['status'] = $status;
+ $ws['failures'] = 0;
+ $ws['first_failure_at'] = 0;
+ $ws['last_error'] = 'ok' === $status ? '' : (string) $error;
+ if ( 'ok' === $status ) {
+ $ws['last_success_at'] = $now;
+ }
+ $state['notice']['episode_sent_at'] = 0;
+ $state['notice']['episode_attempts'] = 0;
+ }
+
+ $state['ws'] = $ws;
+ }
+
+ /**
+ * @param int $failures Consecutive failures so far.
+ * @return void
+ */
+ private function schedule_retry( $failures ) {
+ $delays = array(
+ 1 => HOUR_IN_SECONDS,
+ 2 => 3 * HOUR_IN_SECONDS,
+ 3 => 6 * HOUR_IN_SECONDS,
+ 4 => 12 * HOUR_IN_SECONDS,
+ );
+ $this->schedule_sync( isset( $delays[ $failures ] ) ? $delays[ $failures ] : DAY_IN_SECONDS, 'retry' );
+ }
+
+ /*
+ * ---------------------------------------------------------------------
+ * Which languages
+ * ---------------------------------------------------------------------
+ */
+
+ /**
+ * Every locale the site uses, minus English and the bundled languages.
+ *
+ * @param bool $light Skip the per-user and per-site lookups (used on admin page loads).
+ * @return string[]
+ */
+ public function target_locales( $light = false ) {
+ $found = array( get_locale(), (string) get_option( 'WPLANG', '' ) );
+
+ if ( function_exists( 'get_available_languages' ) ) {
+ $found = array_merge( $found, (array) get_available_languages() );
+ }
+
+ if ( ! $light ) {
+ global $wpdb;
+ if ( isset( $wpdb ) && is_object( $wpdb ) && ! empty( $wpdb->usermeta ) ) {
+ $user_locales = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT meta_value FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value <> ''", 'locale' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
+ $found = array_merge( $found, (array) $user_locales );
+ }
+ if ( is_multisite() ) {
+ $found[] = (string) get_site_option( 'WPLANG', '' );
+ if ( function_exists( 'get_sites' ) ) {
+ $site_ids = get_sites(
+ array(
+ 'fields' => 'ids',
+ 'number' => self::MAX_SITES_SCANNED,
+ )
+ );
+ foreach ( (array) $site_ids as $site_id ) {
+ $found[] = (string) get_blog_option( $site_id, 'WPLANG', '' );
+ }
+ }
+ }
+ }
+
+ // Polylang.
+ if ( function_exists( 'pll_languages_list' ) ) {
+ $found = array_merge( $found, (array) pll_languages_list( array( 'fields' => 'locale' ) ) );
+ }
+
+ // WPML.
+ if ( defined( 'ICL_SITEPRESS_VERSION' ) || has_filter( 'wpml_active_languages' ) ) {
+ $wpml = apply_filters( 'wpml_active_languages', null, array( 'skip_missing' => 0 ) );
+ foreach ( is_array( $wpml ) ? $wpml : array() as $language ) {
+ if ( is_array( $language ) && ! empty( $language['default_locale'] ) ) {
+ $found[] = (string) $language['default_locale'];
+ }
+ }
+ }
+
+ // TranslatePress.
+ $trp = get_option( 'trp_settings' );
+ if ( is_array( $trp ) ) {
+ if ( ! empty( $trp['translation-languages'] ) && is_array( $trp['translation-languages'] ) ) {
+ $found = array_merge( $found, $trp['translation-languages'] );
+ }
+ if ( ! empty( $trp['default-language'] ) ) {
+ $found[] = (string) $trp['default-language'];
+ }
+ }
+
+ if ( ! $light && null !== $this->config['extra_locales'] && is_callable( $this->config['extra_locales'] ) ) {
+ $found = array_merge( $found, (array) call_user_func( $this->config['extra_locales'] ) );
+ }
+
+ /**
+ * Filters the locales whose language packs are kept up to date.
+ *
+ * @param string[] $found All locales found, before English and bundled languages are removed.
+ * @param bool $light Whether the per-user and per-site lookups were skipped.
+ */
+ $found = (array) apply_filters( $this->key( 'locales' ), $found, $light );
+
+ $locales = array();
+ foreach ( $found as $locale ) {
+ $locale = trim( (string) $locale );
+ if ( 'en_US' === $locale || ! preg_match( self::LOCALE_PATTERN, $locale ) || $this->is_bundled_locale( $locale ) ) {
+ continue;
+ }
+ $locales[ $locale ] = true;
+ }
+ $locales = array_keys( $locales );
+ sort( $locales );
+
+ return $locales;
+ }
+
+ /**
+ * Whether the plugin ships this exact locale itself. Exact on purpose: shipping
+ * fa_IR says nothing about fa_AF, and de_DE nothing about de_AT or de_DE_formal.
+ *
+ * @param string $locale Locale.
+ * @return bool
+ */
+ public function is_bundled_locale( $locale ) {
+ return in_array( (string) $locale, $this->config['bundled_locales'], true );
+ }
+
+ /*
+ * ---------------------------------------------------------------------
+ * What is installed
+ * ---------------------------------------------------------------------
+ */
+
+ /**
+ * Where the installed translation for a locale came from, read from the
+ * files themselves so a manual install is recognised too.
+ *
+ * @param string $locale Locale.
+ * @return array{exists: bool, source: string, updated: int} source is ws, wporg, other or ''.
+ */
+ public function inspect_installed( $locale ) {
+ if ( isset( $this->installed_cache[ $locale ] ) ) {
+ return $this->installed_cache[ $locale ];
+ }
+
+ $base = $this->config['languages_dir'] . $this->config['text_domain'] . '-' . $locale;
+ $has_mo = is_file( $base . '.mo' );
+ $has_php = is_file( $base . '.l10n.php' );
+ $info = array(
+ 'exists' => $has_mo || $has_php,
+ 'source' => '',
+ 'updated' => 0,
+ );
+
+ if ( $info['exists'] ) {
+ $headers = array();
+ try {
+ if ( is_file( $base . '.po' ) && function_exists( 'wp_get_pomo_file_data' ) ) {
+ $headers = wp_get_pomo_file_data( $base . '.po' );
+ } elseif ( $has_php && function_exists( 'wp_get_l10n_php_file_data' ) ) {
+ $headers = wp_get_l10n_php_file_data( $base . '.l10n.php' );
+ }
+ } catch ( Throwable $e ) {
+ // A file that cannot be read is treated as someone else's: it is never replaced.
+ $headers = array();
+ }
+ $generator = isset( $headers['X-Generator'] ) ? trim( (string) $headers['X-Generator'] ) : '';
+ if ( 0 === strpos( $generator, self::MARKER ) ) {
+ $info['source'] = 'ws';
+ } elseif ( 0 === stripos( $generator, 'GlotPress' ) ) {
+ $info['source'] = 'wporg';
+ } else {
+ $info['source'] = 'other';
+ }
+ $info['updated'] = ! empty( $headers['PO-Revision-Date'] ) ? $this->timestamp( $headers['PO-Revision-Date'] ) : 0;
+ }
+
+ $this->installed_cache[ $locale ] = $info;
+ return $info;
+ }
+
+ /**
+ * Empty string when packs can be written, otherwise the reason they cannot.
+ * Mirrors what WordPress itself requires before it installs a language pack.
+ *
+ * @return string
+ */
+ private function write_blocker() {
+ if ( function_exists( 'wp_is_file_mod_allowed' ) && ! wp_is_file_mod_allowed( 'download_language_pack' ) ) {
+ return 'file_mods_disallowed';
+ }
+ $dir = $this->config['languages_dir'];
+ if ( ! wp_mkdir_p( $dir ) ) {
+ return 'languages_dir_missing';
+ }
+ if ( ! wp_is_writable( $dir ) ) {
+ return 'languages_dir_not_writable';
+ }
+ if ( ! function_exists( 'get_filesystem_method' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ }
+ // Files written by PHP would belong to the wrong user on a host that needs FTP credentials.
+ if ( 'direct' !== get_filesystem_method( array(), $dir ) ) {
+ return 'filesystem_not_direct';
+ }
+ return '';
+ }
+
+ /*
+ * ---------------------------------------------------------------------
+ * Catalogs
+ * ---------------------------------------------------------------------
+ */
+
+ /**
+ * GET {server}/wp-json/wl/v1/translations/{product}
+ *
+ * @param string[] $locales Locales wanted.
+ * @return array{status: string, error: string, server: string, translations: array}
+ */
+ public function fetch_ws_catalog( array $locales ) {
+ $result = array(
+ 'status' => 'unreachable',
+ 'error' => '',
+ 'server' => '',
+ 'translations' => array(),
+ );
+
+ foreach ( $this->servers() as $server ) {
+ $url = $server . '/wp-json/wl/v1/translations/' . rawurlencode( $this->config['product'] )
+ . '?version=' . rawurlencode( $this->config['version'] )
+ . '&locales=' . rawurlencode( implode( ',', $locales ) )
+ . '&client=' . rawurlencode( self::CLIENT_VERSION );
+
+ $response = wp_remote_get(
+ $url,
+ array(
+ 'timeout' => self::CATALOG_TIMEOUT,
+ 'redirection' => 0,
+ 'sslverify' => $this->sslverify( $url ),
+ 'headers' => array( 'Accept' => 'application/json' ),
+ )
+ );
+
+ $attempt = $this->classify_ws_response( $response );
+ if ( 'ok' === $attempt['status'] ) {
+ return array(
+ 'status' => 'ok',
+ 'error' => '',
+ 'server' => $server,
+ 'translations' => $this->parse_catalog( $attempt['body'], $locales, 'ws', array( $this->host( $server ) ), 0 === stripos( $server, 'http://' ) ),
+ );
+ }
+
+ // A server that answered with an error outranks one that could not be reached at all.
+ if ( 'unreachable' === $result['status'] || '' === $result['server'] ) {
+ $result['status'] = $attempt['status'];
+ $result['error'] = $attempt['error'];
+ $result['server'] = $server;
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Tells "this site cannot connect" apart from "WhiteStudio answered with an error".
+ * Only a response carrying SERVER_HEADER came from the language server; anything
+ * else (a firewall page, a bot challenge, a proxy error) means it was not reached.
+ *
+ * @param array|WP_Error $response wp_remote_get() result.
+ * @return array{status: string, error: string, body: array}
+ */
+ private function classify_ws_response( $response ) {
+ if ( is_wp_error( $response ) ) {
+ return array(
+ 'status' => 'unreachable',
+ 'error' => $this->http_error_text( $response ),
+ 'body' => array(),
+ );
+ }
+
+ $code = (int) wp_remote_retrieve_response_code( $response );
+ if ( '' === (string) wp_remote_retrieve_header( $response, self::SERVER_HEADER ) ) {
+ $rest_error = $this->wordpress_rest_error( $response );
+ if ( '' !== $rest_error ) {
+ // WordPress on the server answered (e.g. the handler plugin is not deployed yet): the connection works.
+ return array(
+ 'status' => 'server_error',
+ 'error' => sprintf( 'HTTP %d %s', $code, $rest_error ),
+ 'body' => array(),
+ );
+ }
+ return array(
+ 'status' => 'unreachable',
+ 'error' => sprintf( 'HTTP %d from something other than the language server (firewall, proxy or bot protection)', $code ),
+ 'body' => array(),
+ );
+ }
+ if ( 200 !== $code ) {
+ return array(
+ 'status' => 'server_error',
+ 'error' => sprintf( 'HTTP %d', $code ),
+ 'body' => array(),
+ );
+ }
+
+ $body = json_decode( (string) wp_remote_retrieve_body( $response ), true );
+ if ( ! is_array( $body ) || ! isset( $body['translations'] ) || ! is_array( $body['translations'] ) ) {
+ return array(
+ 'status' => 'server_error',
+ 'error' => 'invalid catalog',
+ 'body' => array(),
+ );
+ }
+
+ return array(
+ 'status' => 'ok',
+ 'error' => '',
+ 'body' => $body,
+ );
+ }
+
+ /**
+ * The error code when the body is a WordPress REST API error ({"code":"rest_…"}),
+ * which only WordPress itself produces - a firewall or proxy page never does.
+ *
+ * @param array $response wp_remote_get() result.
+ * @param string $body_file When the response was streamed to a file, that file.
+ * @return string '' when it is not one.
+ */
+ private function wordpress_rest_error( $response, $body_file = '' ) {
+ $body = (string) wp_remote_retrieve_body( $response );
+ if ( '' === $body && '' !== $body_file && is_file( $body_file ) && (int) @filesize( $body_file ) < 65536 ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ $body = (string) @file_get_contents( $body_file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions
+ }
+ $decoded = json_decode( $body, true );
+ if ( is_array( $decoded ) && isset( $decoded['code'] ) && is_string( $decoded['code'] ) && 0 === strpos( $decoded['code'], 'rest_' ) ) {
+ return $decoded['code'];
+ }
+ return '';
+ }
+
+ /**
+ * The text of a failed wp_remote_get(), for the email and the message on screen.
+ *
+ * WordPress translates its own error messages into the site language, and this plugin only runs for
+ * a site whose language is not shipped with it, so a phrase in the message cannot be recognised
+ * afterwards ("User has blocked requests through HTTP" arrives in Swedish on a Swedish site).
+ * The error code never changes: a request WordPress refused to send (WP_HTTP_BLOCK_EXTERNAL) is marked with it.
+ *
+ * @param WP_Error $error Error from wp_remote_get().
+ * @return string
+ */
+ private function http_error_text( WP_Error $error ) {
+ $text = (string) $error->get_error_message();
+ if ( 'http_request_not_executed' === $error->get_error_code() ) {
+ $text .= ' [http_request_not_executed]';
+ }
+ return $text;
+ }
+
+ /**
+ * GET https://api.wordpress.org/translations/plugins/1.0/
+ *
+ * @param string[] $locales Locales wanted.
+ * @return array{status: string, error: string, translations: array}
+ */
+ public function fetch_wporg_catalog( array $locales ) {
+ $url = 'https://api.wordpress.org/translations/plugins/1.0/?slug=' . rawurlencode( $this->config['wporg_slug'] )
+ . '&version=' . rawurlencode( $this->config['version'] );
+
+ $response = wp_remote_get(
+ $url,
+ array(
+ 'timeout' => self::CATALOG_TIMEOUT,
+ 'headers' => array( 'Accept' => 'application/json' ),
+ )
+ );
+
+ if ( is_wp_error( $response ) ) {
+ return array(
+ 'status' => 'unreachable',
+ 'error' => $this->http_error_text( $response ),
+ 'translations' => array(),
+ );
+ }
+ $code = (int) wp_remote_retrieve_response_code( $response );
+ $body = json_decode( (string) wp_remote_retrieve_body( $response ), true );
+ if ( 200 !== $code || ! is_array( $body ) || ! isset( $body['translations'] ) || ! is_array( $body['translations'] ) ) {
+ return array(
+ 'status' => 'server_error',
+ 'error' => sprintf( 'HTTP %d', $code ),
+ 'translations' => array(),
+ );
+ }
+
+ return array(
+ 'status' => 'ok',
+ 'error' => '',
+ 'translations' => $this->parse_catalog( $body, $locales, 'wporg', array( 'downloads.wordpress.org' ), false ),
+ );
+ }
+
+ /**
+ * Keep only well-formed entries for wanted locales whose package lives on
+ * the expected host. WhiteStudio entries must carry a checksum.
+ *
+ * @param array $body Decoded catalog.
+ * @param string[] $locales Wanted locales.
+ * @param string $source ws|wporg.
+ * @param string[] $hosts Hosts packages may be downloaded from.
+ * @param bool $allow_http Whether a plain http package URL is acceptable (local servers only).
+ * @return array<string, array>
+ */
+ private function parse_catalog( array $body, array $locales, $source, array $hosts, $all