Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/weglot/bootstrap.php
+++ b/weglot/bootstrap.php
@@ -60,12 +60,15 @@
'WeglotWPServicesMenu_Options_Service_Weglot',
'WeglotWPServicesVersion_Service_Weglot',
'WeglotWPServicesWebhook_Service_Weglot',
+ 'WeglotWPServicesSlug_Translation_V2_Service_Weglot',
'WeglotWPThirdAmpAmp_Service_Weglot',
'WeglotWPThirdCalderaformsCaldera_Active',
'WeglotWPThirdEddEdd_Active',
'WeglotWPThirdGravityformsGf_Active',
'WeglotWPThirdFibosearchFibosearch_Active',
+ 'WeglotWPThirdDiviDivi_Active',
+ 'WeglotWPThirdDoofinderDoofinder_Active',
'WeglotWPThirdNinjaFormsNinja_Active',
'WeglotWPThirdWoocommerceWc_Active',
'WeglotWPThirdWoocommercepdfWcpdf_Active',
@@ -119,6 +122,8 @@
'WeglotWPThirdEddEdd_Filter_Urls',
'WeglotWPThirdGravityformsGF_Filter_Urls',
'WeglotWPThirdFibosearchFibosearch_Service',
+ 'WeglotWPThirdDiviDivi_Multi_View_Weglot',
+ 'WeglotWPThirdDoofinderDoofinder_Service',
'WeglotWPThirdWoocommerceWC_Filter_Urls_Weglot',
'WeglotWPThirdWoocommerceWC_Cart_Reload_Weglot',
'WeglotWPThirdWoocommerceWC_Mail_Weglot',
--- a/weglot/src/actions/admin/class-admin-enqueue-weglot.php
+++ b/weglot/src/actions/admin/class-admin-enqueue-weglot.php
@@ -95,13 +95,14 @@
$limit = $user_info['languages_limit'];
}
+ $original_language = $this->language_services->get_original_language();
wp_localize_script(
'weglot-admin',
'weglot_languages',
array(
'available' => $this->language_services->get_all_languages(),
'limit' => $limit,
- 'original' => $this->language_services->get_original_language()->getInternalCode(),
+ 'original' => null !== $original_language ? $original_language->getInternalCode() : '',
'selected' => array_map(function($lang) {
return $lang->getInternalCode();
}, $this->language_services->get_destination_languages(true))
@@ -117,6 +118,21 @@
'get_project_settings' => wp_create_nonce( 'weglot_get_project_settings' ),
'get_workspace_info' => wp_create_nonce( 'weglot_get_workspace_info' ),
),
+ // Plain __() and not esc_html__(): wp_localize_script() only decodes entities on
+ // top-level values, so an escaped apostrophe here would reach the page as '.
+ // The scripts write these strings as text, never as HTML.
+ 'i18n' => array(
+ 'changes_saved' => __( 'Changes saved!', 'weglot' ),
+ 'settings_not_saved' => __( 'Settings could not be saved.', 'weglot' ),
+ 'copied' => __( 'Copied!', 'weglot' ),
+ 'checking' => __( 'Checking...', 'weglot' ),
+ 'connect' => __( 'Connect Weglot', 'weglot' ),
+ 'invalid_api_key' => __( 'Invalid API Key', 'weglot' ),
+ 'error_try_again' => __( 'Error - Please try again', 'weglot' ),
+ 'activating' => __( 'Activating...', 'weglot' ),
+ /* translators: %s: name of the Weglot subscription plan, e.g. Starter. */
+ 'plan' => __( 'Plan %s', 'weglot' ),
+ ),
)
);
--- a/weglot/src/actions/admin/class-ajax-projects-settings.php
+++ b/weglot/src/actions/admin/class-ajax-projects-settings.php
@@ -7,7 +7,6 @@
exit;
}
-use WeglotWPHelpersHelper_Is_Admin;
use WeglotWPModelsHooks_Interface_Weglot;
use WeglotWPServicesOption_Service_Weglot;
use WeglotWPServicesVersion_Service_Weglot;
@@ -44,10 +43,12 @@
*
*/
public function hooks() {
- if ( ! Helper_Is_Admin::is_wp_admin() ) {
- return;
- }
-
+ // Registered unconditionally on purpose. The previous is_wp_admin() guard required the
+ // referer to contain "wp-admin", which a site sending Referrer-Policy: origin (or
+ // same-origin, strict-origin, no-referrer) truncates to the bare origin: the action was
+ // then never registered and admin-ajax answered "0" with a 400. A wp_ajax_ hook is only
+ // reachable through admin-ajax.php by a logged-in user, and the callback already checks
+ // manage_options and the nonce, so the guard added no protection.
add_action( 'wp_ajax_get_project_settings', array( $this, 'get_project_settings' ) );
}
@@ -69,6 +70,7 @@
}
$api_key = sanitize_text_field( wp_unslash( $_POST['api_key'] ) ); //phpcs:ignore
+ $api_key = $this->option_services->resolve_submitted_api_key_private( $api_key );
if ( $this->version_service_weglot->get_version_from_api_key_private( $api_key ) === 2 ) {
$response = $this->option_services->get_options_from_api_with_api_key( $api_key, true, true );
@@ -77,7 +79,13 @@
}
$success = isset( $response['success'] ) && $response['success'] === true;
- $has_error = isset( $response['result'] ) && is_array( $response['result'] ) && isset( $response['result']['error'] ) && null !== $response['result']['error'];
+ $has_error = isset( $response['result'] ) && is_array( $response['result'] ) && isset( $response['result']['error'] );
+
+ // get_options_from_api_with_api_key() adds the private key to the result; the screens
+ // never read it back, and it must not reach the browser.
+ if ( isset( $response['result'] ) && is_array( $response['result'] ) ) {
+ unset( $response['result']['api_key_private'] );
+ }
if ( ! $success || $has_error ) {
wp_send_json_error( array(
--- a/weglot/src/actions/admin/class-customize-menu-weglot.php
+++ b/weglot/src/actions/admin/class-customize-menu-weglot.php
@@ -94,7 +94,7 @@
public function nav_admin_enqueue_scripts() {
$screen = get_current_screen();
- if ( 'nav-menus' !== $screen->base ) {
+ if ( null === $screen || 'nav-menus' !== $screen->base ) {
return;
}
--- a/weglot/src/actions/admin/class-deactivation-feedback-weglot.php
+++ b/weglot/src/actions/admin/class-deactivation-feedback-weglot.php
@@ -108,7 +108,6 @@
);
// Send email
- // @phpstan-ignore-next-line -- WordPress stubs not resolved in current PHPStan config
$sent = wp_mail( 'help@weglot.com', $email_subject, $email_body, $headers ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.wp_mail_wp_mail -- single transactional email, not bulk
if ( $sent ) {
--- a/weglot/src/actions/admin/class-metabox-url-translate-weglot.php
+++ b/weglot/src/actions/admin/class-metabox-url-translate-weglot.php
@@ -9,6 +9,7 @@
use WeglotWPModelsHooks_Interface_Weglot;
use WeglotWPHelpersHelper_Post_Meta_Weglot;
use WeglotWPServicesOption_Service_Weglot;
+use WeglotWPServicesVersion_Service_Weglot;
/**
*
@@ -22,10 +23,16 @@
private $option_services;
/**
+ * @var Version_Service_Weglot
+ */
+ private $version_services;
+
+ /**
* @since 2.1.0
*/
public function __construct() {
$this->option_services = weglot_get_service( Option_Service_Weglot::class );
+ $this->version_services = weglot_get_service( Version_Service_Weglot::class );
}
/**
@@ -48,6 +55,11 @@
return;
}
+ // Its only content is a link to a v1 dashboard route, which Weglot 2 does not have.
+ if ( 2 === $this->version_services->get_onboarding_version() ) {
+ return;
+ }
+
$post_type = get_post_type();
$exclude_post_type_metabox = apply_filters(
--- a/weglot/src/actions/admin/class-metabox-visual-editor-weglot.php
+++ b/weglot/src/actions/admin/class-metabox-visual-editor-weglot.php
@@ -213,22 +213,17 @@
public function get_weglot_path_status( $path, $list ): void {
$wg_path = $this->request_url_services->create_url_object( $path );
$project_slug = $this->option_services->get_option( 'project_slug' );
- if ( '' === (string) $project_slug ) {
- $this->user_api_services->get_workspace_info();
- $project_slug = $this->option_services->get_option('slug');
- }
-
$is_v2 = $this->version_services->get_onboarding_version() === 2;
if ( $is_v2 ) {
- $workspace_slug = (string) $this->option_services->get_option( 'workspace_slug' );
- if ( '' === $workspace_slug ) {
- return;
- }
- $base = rtrim( Helper_API::get_dashboard_url(), '/' ) . '/' . rawurlencode( $workspace_slug ) . '/' . rawurlencode( (string) $project_slug );
- $visual_editor = $base . '/languages';
- $url_exclusion = $base . '/exclusions';
+ $workspace_slug = $this->user_api_services->get_workspace_slug();
+ $visual_editor = Helper_API::build_dashboard_project_url( $workspace_slug, (string) $project_slug, 'languages' );
+ $url_exclusion = Helper_API::build_dashboard_project_url( $workspace_slug, (string) $project_slug, 'exclusions' );
} else {
+ if ( '' === (string) $project_slug ) {
+ $this->user_api_services->get_workspace_info();
+ $project_slug = $this->option_services->get_option('slug');
+ }
$organization_slug = $this->option_services->get_option( 'organization_slug' );
$dashboard_base = rtrim( Helper_API::get_dashboard_url(), '/' );
$visual_editor = $dashboard_base . '/workspaces/' . $organization_slug . '/projects/' . $project_slug . '/translations/visual-editor/launch?mode=translations&url=' . $wg_path->getUrl();
--- a/weglot/src/actions/admin/class-options-weglot.php
+++ b/weglot/src/actions/admin/class-options-weglot.php
@@ -103,6 +103,7 @@
$api_key_private = isset( $_POST['api_key_private'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key_private'] ) ) : '';
+ $api_key_private = $this->option_services->resolve_submitted_api_key_private( $api_key_private );
if ( '' === $api_key_private || strlen( $api_key_private ) < 10 ) {
wp_send_json_error( array( 'message' => 'Invalid API key.' ) );
@@ -188,10 +189,29 @@
}
$tab = $_GET[ 'tab' ]; //phpcs:ignore
- $options = $_POST[ WEGLOT_SLUG ]; //phpcs:ignore
+ $options = isset( $_POST[ WEGLOT_SLUG ] ) && is_array( $_POST[ WEGLOT_SLUG ] ) ? $_POST[ WEGLOT_SLUG ] : array(); //phpcs:ignore
$keep_api_key_private = "";
$api_key_private = isset( $options['api_key_private'] ) ? (string) $options['api_key_private'] : '';
+ if ( $this->option_services->has_api_key_private_constant() ) {
+ // The form only carries a masked copy of the constant, and save_options_to_weglot()
+ // builds its request URL from $options['api_key_private'].
+ $api_key_private = $this->option_services->resolve_submitted_api_key_private( $api_key_private );
+ $options['api_key_private'] = $api_key_private;
+ }
+
+ // Only the Settings tab renders the API key field, so an empty value here means "not
+ // submitted", never "cleared on purpose". Without this fallback, saving any other tab
+ // wrote an empty key to the database and forced the stored API version back to 1, which
+ // locked the site on the legacy settings screen and made it happen again on the next save.
+ if ( '' === trim( $api_key_private ) ) {
+ $stored_api_key_private = get_option( sprintf( '%s-%s', WEGLOT_SLUG, 'api_key_private' ) );
+
+ if ( is_string( $stored_api_key_private ) && '' !== trim( $stored_api_key_private ) ) {
+ $api_key_private = $stored_api_key_private;
+ }
+ }
+
$api_version = $this->version_services->get_version_from_api_key_private($api_key_private);
update_option( $this->version_services::API_VERSION_OPTION_NAME, $api_version );
if($api_version === 2){
@@ -352,7 +372,7 @@
* @param array<string|int,mixed> $options
* @param mixed $has_first_settings
* @param int $version_api
- * @return array<string,mixed>
+ * @return array<int|string,mixed>
*/
public function sanitize_options_settings( $options, $has_first_settings = false, $version_api = 1 ) {
--- a/weglot/src/actions/admin/class-pages-weglot.php
+++ b/weglot/src/actions/admin/class-pages-weglot.php
@@ -74,8 +74,10 @@
$email = $current_user->user_email;
$organization_slug = $this->option_services->get_option('organization_slug');
$project_slug = $this->option_services->get_option('project_slug');
+ $onboarding_version = $this->version_services ? (int) $this->version_services->get_onboarding_version() : 1;
- if (empty($organization_slug) || empty($project_slug)) {
+ // Weglot 2 settings carry no organization_slug: this v1 refresh would call the API on every render.
+ if ( 2 !== $onboarding_version && ( '' === (string) $organization_slug || '' === (string) $project_slug ) ) {
$this->user_api_services->get_workspace_info();
$organization_slug = $this->option_services->get_option('organization_slug');
$project_slug = $this->option_services->get_option('project_slug');
@@ -118,35 +120,11 @@
)
);
- $dashboard_href = '';
- $dashboard_base = WeglotWPHelpersHelper_API::get_dashboard_url();
- $version_service = weglot_get_service( WeglotWPServicesVersion_Service_Weglot::class );
- $onboarding_version = $version_service ? (int) $version_service->get_onboarding_version() : 1;
-
- // v2: /{workspace_slug}/{project_slug}/languages
if ( 2 === $onboarding_version ) {
- $workspace_slug = get_option( 'weglot-translate-workspace-slug' );
- if ( ! is_string( $workspace_slug ) || trim( $workspace_slug ) === '' ) {
- $throttle_key = 'weglot_workspace_slug_fetch_throttle';
- if ( false === get_transient( $throttle_key ) ) {
- set_transient( $throttle_key, 1, MINUTE_IN_SECONDS * 5 );
-
- $user_api = weglot_get_service( User_Api_Service_Weglot::class );
- if ( $user_api ) {
- $user_api->get_workspace_info();
- $workspace_slug = get_option( 'weglot-translate-workspace-slug' );
- }
- }
-
- if ( ! is_string( $workspace_slug ) || trim( $workspace_slug ) === '' ) {
- $workspace_slug = '';
- }
- }
- $project_slug = $this->option_services->get_option('slug');
- $dashboard_href = rtrim( $dashboard_base, '/' ) . '/' . rawurlencode( (string) $workspace_slug ) . '/' . rawurlencode( (string) $project_slug ) . '/languages';
+ $dashboard_href = WeglotWPHelpersHelper_API::build_dashboard_project_url( $this->user_api_services->get_workspace_slug(), (string) $project_slug, 'languages' );
} else {
// v1: /workspaces/{org}/projects/{project}/translations/languages/
- $dashboard_href = rtrim( $dashboard_base, '/' ) . '/workspaces/' . rawurlencode( (string) $organization_slug ) . '/projects/' . rawurlencode( (string) $project_slug ) . '/translations/languages/';
+ $dashboard_href = rtrim( WeglotWPHelpersHelper_API::get_dashboard_url(), '/' ) . '/workspaces/' . rawurlencode( (string) $organization_slug ) . '/projects/' . rawurlencode( (string) $project_slug ) . '/translations/languages/';
}
$wp_admin_bar->add_menu(
@@ -161,12 +139,19 @@
)
);
+ if ( 2 === $onboarding_version ) {
+ // No lang parameter: the visitor picks the language in the editor.
+ $visual_editor_href = WeglotWPHelpersHelper_API::build_dashboard_project_url( $this->user_api_services->get_workspace_slug(), (string) $project_slug, 'visual-editor', array( 'url' => $url_to_edit ) );
+ } else {
+ $visual_editor_href = 'https://dashboard.weglot.com/workspaces/' . $organization_slug . '/projects/'. $project_slug .'/translations/visual-editor/launch?url='.$url_to_edit.'&mode=translations';
+ }
+
$wp_admin_bar->add_menu(
array(
'id' => 'weglot-visual-editor',
'parent' => 'weglot',
'title' => __( 'Edit with visual editor', 'weglot' ),
- 'href' => esc_url( 'https://dashboard.weglot.com/workspaces/' . $organization_slug . '/projects/'. $project_slug .'/translations/visual-editor/launch?url='.$url_to_edit.'&mode=translations' ),
+ 'href' => esc_url( $visual_editor_href ),
'meta' => array(
'target' => '_blank',
),
--- a/weglot/src/actions/class-register-widget-weglot.php
+++ b/weglot/src/actions/class-register-widget-weglot.php
@@ -140,6 +140,11 @@
];
foreach ($patterns as $pattern) {
$button_html = preg_replace($pattern, '', $button_html);
+ // These patterns sanitize the button: on a PCRE failure, render nothing rather than
+ // unsanitized markup (wp_kses() on the old null result also produced '').
+ if ( null === $button_html ) {
+ return '';
+ }
}
return wp_kses( $button_html, $allowed_html );
--- a/weglot/src/actions/front/class-search-weglot.php
+++ b/weglot/src/actions/front/class-search-weglot.php
@@ -87,11 +87,17 @@
}
$query_vars_check = apply_filters( 'weglot_query_vars_check', 's' );
- if ( empty( $query->query_vars[ $query_vars_check ] ) ) {
+ $search = $query->get( $query_vars_check );
+ if ( ! is_string( $search ) || '' === trim( $search ) ) {
return;
}
- $original_language = $this->language_services->get_original_language()->getInternalCode();
+ $original_language_entry = $this->language_services->get_original_language();
+ if ( null === $original_language_entry ) {
+ return;
+ }
+
+ $original_language = $original_language_entry->getInternalCode();
$current_language = $this->request_url_services->get_current_language()->getInternalCode();
$prevent_translation = apply_filters( 'weglot_prevent_search_translation', false, $current_language, $query );
@@ -101,12 +107,17 @@
try {
$api_key_private = $this->option_services->get_api_key_private();
- $this->new_search = $this->translate_services->reverseTranslate($api_key_private, $current_language, $original_language, home_url('/'), $query->query_vars[ $query_vars_check ], 1);
+ if ( ! is_string( $api_key_private ) || '' === $api_key_private ) {
+ return;
+ }
- if ( empty( $this->new_search ) ) {
+ $reversed = $this->translate_services->reverse_translate_term( $api_key_private, $current_language, $original_language, home_url( '/' ), $search );
+ if ( ! is_string( $reversed ) || '' === $reversed ) {
return;
}
+ $this->new_search = $reversed;
+
$query->set( $query_vars_check, $this->new_search ); //phpcs:ignore
if ( isset( $query->query[ $query_vars_check ] ) ) {
$query->query[ $query_vars_check ] = $this->new_search;
--- a/weglot/src/actions/front/class-translate-page-weglot.php
+++ b/weglot/src/actions/front/class-translate-page-weglot.php
@@ -19,6 +19,7 @@
use WeglotWPServicesOption_Service_Weglot;
use WeglotWPServicesRedirect_Service_Weglot;
use WeglotWPServicesRequest_Url_Service_Weglot;
+use WeglotWPServicesSlug_Translation_V2_Service_Weglot;
use WeglotWPServicesTranslate_Service_Weglot;
use WeglotWPServicesFeature_Flags_Service_Weglot;
use WeglotWPServicesVersion_Service_Weglot;
@@ -32,6 +33,11 @@
*/
class Translate_Page_Weglot implements Hooks_Interface_Weglot {
/**
+ * Transient value remembering that versions.json could not provide a template.
+ */
+ const TEMPLATE_HASH_NOT_FOUND = 'not_found';
+
+ /**
* @var Option_Service_Weglot
*/
private $option_services;
@@ -280,8 +286,9 @@
$file_content = file_get_contents( $file ); // phpcs:ignore WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown
}
- if ( is_string( $file_content ) ) {
- $this->translate_services->set_original_language( $this->language_services->get_original_language() );
+ $original_language = $this->language_services->get_original_language();
+ if ( is_string( $file_content ) && null !== $original_language ) {
+ $this->translate_services->set_original_language( $original_language );
$this->translate_services->set_current_language( $this->request_url_services->get_current_language() );
echo $this->translate_services->weglot_treat_page( $file_content ); //phpcs:ignore
die;
@@ -341,7 +348,8 @@
$replacement = '/' . $language . '/';
$updated_url = preg_replace($pattern, $replacement, $current_url, 1); // Replace only the first occurrence
- return $updated_url; // Return the updated URL
+ // Never fall back to $current_url: the caller would 301 to the page being requested.
+ return null === $updated_url ? false : $updated_url;
}
}
@@ -390,8 +398,8 @@
return;
}
- if ( $redirect ) {
- $original_language_url = $this->request_url_services->get_weglot_url()->getForLanguage( $this->language_services->get_original_language() );
+ if ( $redirect && null !== $original_language ) {
+ $original_language_url = $this->request_url_services->get_weglot_url()->getForLanguage( $original_language );
if (
! $this->request_url_services->get_weglot_url()->getForLanguage( $this->current_language ) &&
is_string( $original_language_url ) &&
@@ -404,9 +412,12 @@
}
// If we receive a not translated slug we return a 301. For example if we have /fr/products but should have /fr/produits we should redirect to /fr/produits.
- if ( $this->request_url_services->get_weglot_url()->getRedirect() !== null ) {
- $redirect_to = $this->request_url_services->get_weglot_url()->getRedirect();
- wp_safe_redirect( '/' . $this->current_language->getExternalCode() . $redirect_to, 301 );
+ $redirect_path = $this->request_url_services->get_weglot_url()->getRedirect();
+ if ( null === $redirect_path ) {
+ $redirect_path = $this->find_slug_history_redirect_path();
+ }
+ if ( null !== $redirect_path ) {
+ wp_safe_redirect( $this->build_slug_redirect_url( $redirect_path ), 301 );
exit;
}
$_SERVER['REQUEST_URI'] = sanitize_url( $this->request_url_services->get_weglot_url()->getPathPrefix() .
@@ -415,6 +426,76 @@
}
/**
+ * A former translated slug of a Weglot 2 project (/fr/livre-d-or after the page was renamed
+ * /fr/livre-de-bronze) is sent to the current one.
+ *
+ * @return string|null Path to redirect to, without the language segment.
+ * @since 6.5
+ */
+ private function find_slug_history_redirect_path() {
+ $slug_translation_v2 = weglot_get_service( Slug_Translation_V2_Service_Weglot::class );
+ if ( ! $slug_translation_v2 instanceof Slug_Translation_V2_Service_Weglot ) {
+ return null;
+ }
+
+ $path = $this->get_requested_translated_path();
+ if ( null === $path ) {
+ return null;
+ }
+
+ $language = $this->current_language->getInternalCode();
+ $custom_urls = $this->option_services->get_option( 'custom_urls' );
+ $custom_urls = is_array( $custom_urls ) && isset( $custom_urls[ $language ] ) && is_array( $custom_urls[ $language ] )
+ ? $custom_urls[ $language ]
+ : array();
+
+ return $slug_translation_v2->find_redirect_path( $path, $language, $custom_urls );
+ }
+
+ /**
+ * The request path as the visitor typed it, without the install directory nor the language
+ * segment: WeglotUtilUrl::getPath() has already mapped translated slugs back to original ones.
+ *
+ * @return string|null
+ * @since 6.5
+ */
+ private function get_requested_translated_path() {
+ $path = wp_parse_url( $this->request_url_services->get_full_url(), PHP_URL_PATH );
+ if ( ! is_string( $path ) ) {
+ return null;
+ }
+
+ // Decoded like WeglotUtilUrl does, so non-ASCII slugs match the API values.
+ $path = urldecode( $path );
+ $prefix = $this->request_url_services->get_weglot_url()->getPathPrefix() . '/' . $this->current_language->getExternalCode();
+
+ if ( $path !== $prefix && 0 !== strpos( $path, $prefix . '/' ) ) {
+ return null;
+ }
+
+ $path = (string) substr( $path, strlen( $prefix ) );
+
+ return '' === $path ? '/' : $path;
+ }
+
+ /**
+ * The redirect runs on plugins_loaded, before Redirect_Wp_Weglot filters wp_redirect: the target
+ * is complete here, with the directory WordPress is installed in and the query string.
+ *
+ * @param string $path Path in the current language, without the language segment.
+ *
+ * @return string
+ * @since 6.5
+ */
+ private function build_slug_redirect_url( $path ) {
+ $weglot_url = $this->request_url_services->get_weglot_url();
+ $query = $weglot_url->getQuery();
+
+ return $weglot_url->getPathPrefix() . '/' . $this->current_language->getExternalCode() . $path
+ . ( null !== $query && '' !== $query ? '?' . $query : '' );
+ }
+
+ /**
* @return void
* @since 2.0
*/
@@ -604,7 +685,9 @@
}
echo '<script type="application/json" id="weglot-data">';
- echo wp_json_encode( $settings );
+ // The request URL ends up in switcher_links: escape < and > so it can neither close the
+ // block (</script>) nor turn the parser's escape state on (<!--<script>).
+ echo wp_json_encode( $settings, JSON_HEX_TAG );
echo '</script>';
}
@@ -670,8 +753,13 @@
$filename_esc_js = esc_attr( 'weglot-switcher-default-js' );
$filename_esc_css = esc_attr( 'weglot-switcher-default-css' );
$template_default = $this->get_template_hash('default');
+ $default_hash = is_array( $template_default ) && isset( $template_default['hash'] ) ? $template_default['hash'] : '';
$css_to_load = esc_url( Helper_API::get_root_cdn_base() ) . '/weglot.min.css';
- $file_to_load = esc_url( Helper_API::get_tpl_switchers_url() . $template_default['name'] . '.' . $template_default['hash'] ) . '.min.js';
+ if ( '' !== $default_hash ) {
+ $file_to_load = esc_url( Helper_API::get_tpl_switchers_url() . 'default.' . $default_hash ) . '.min.js';
+ } else {
+ $file_to_load = esc_url( Helper_API::get_tpl_switchers_url() . 'default' ) . '.min.js';
+ }
wp_enqueue_style(
$filename_esc_css, // Handle name
@@ -689,11 +777,7 @@
true // Load in the footer
);
- $this->set_switcher_integrity(
- $filename_esc_js,
- $template_default['name'] ?? '',
- $template_default['hash'] ?? ''
- );
+ $this->set_switcher_integrity( $filename_esc_js, 'default', $default_hash );
}
}
}
@@ -770,48 +854,60 @@
* The method fetches template version data from a remote JSON file,
* and caches the retrieved data in a transient for a week.
*
+ * Failures are cached too, for a few minutes: this runs on every page view, and an
+ * unreachable versions.json would otherwise block each one on the HTTP timeout.
+ *
* @param string $template_name The name of the template to fetch the hash for.
*
* @return array<string,mixed>|null An array containing the template data if found, or null if the template is not found or if an error occurs.
*/
- public function get_template_hash($template_name) {
- // Transient key based on the template name
- $transient_key = 'template_hash_' . sanitize_key($template_name);
+ public function get_template_hash( $template_name ) {
+ $transient_key = 'template_hash_' . sanitize_key( $template_name );
- // Check if the data exists in the transient
- $template_data = get_transient($transient_key);
- if ($template_data !== false) {
- // Return the data if found in transient
- return $template_data;
+ $template_data = get_transient( $transient_key );
+ if ( self::TEMPLATE_HASH_NOT_FOUND === $template_data ) {
+ return null;
+ }
+ if ( false !== $template_data ) {
+ return is_array( $template_data ) ? $template_data : null;
}
- // Fetch JSON data from the URL
- $url = esc_url(Helper_API::get_tpl_switchers_url() . 'versions.json');
-
- $response = Helper_API::vip_safe_wp_remote_get( $url );
- // Check if the request was successful
- if (is_wp_error($response)) {
- return null; // Return null on failure
+ $template = $this->fetch_template_hash( $template_name );
+ if ( null === $template ) {
+ set_transient( $transient_key, self::TEMPLATE_HASH_NOT_FOUND, 5 * MINUTE_IN_SECONDS );
+ return null;
}
- $body = wp_remote_retrieve_body($response);
- $data = json_decode($body, true);
+ set_transient( $transient_key, $template, WEEK_IN_SECONDS );
+ return $template;
+ }
+
+ /**
+ * Look a template up in the remote versions.json.
+ *
+ * @param string $template_name The name of the template to fetch the hash for.
+ *
+ * @return array<string,mixed>|null The template data, or null on any failure.
+ */
+ private function fetch_template_hash( $template_name ) {
+ $url = esc_url( Helper_API::get_tpl_switchers_url() . 'versions.json' );
+
+ $response = Helper_API::vip_safe_wp_remote_get( $url, array( 'timeout' => 3 ) );
+ if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
+ return null;
+ }
- // Check if templates exist and are an array
- if (!isset($data['templates']) || !is_array($data['templates'])) {
+ $data = json_decode( wp_remote_retrieve_body( $response ), true );
+ if ( ! is_array( $data ) || ! isset( $data['templates'] ) || ! is_array( $data['templates'] ) ) {
return null;
}
- // Search for the template by name
- foreach ($data['templates'] as $template) {
- if ($template['name'] === $template_name) {
- // Save the result in a transient for 1 week (7 days)
- set_transient($transient_key, $template, WEEK_IN_SECONDS);
+ foreach ( $data['templates'] as $template ) {
+ if ( is_array( $template ) && isset( $template['name'] ) && $template['name'] === $template_name ) {
return $template;
}
}
- // Return null if not found
return null;
}
--- a/weglot/src/actions/rest/class-cache-purge-rest-weglot.php
+++ b/weglot/src/actions/rest/class-cache-purge-rest-weglot.php
@@ -8,6 +8,7 @@
use WeglotWPModelsHooks_Interface_Weglot;
use WeglotWPServicesOption_Service_Weglot;
+use WeglotWPServicesSlug_Translation_V2_Service_Weglot;
use WP_REST_Server;
use WP_REST_Request;
@@ -170,6 +171,13 @@
delete_transient( 'weglot_cache_cdn' );
delete_transient( 'weglot_slugs_cache' );
+ // Marked outdated rather than deleted: the next request refreshes the slugs while the
+ // current ones are still served, instead of every visitor waiting on the API.
+ $slug_translation_v2 = weglot_get_service( Slug_Translation_V2_Service_Weglot::class );
+ if ( $slug_translation_v2 instanceof Slug_Translation_V2_Service_Weglot ) {
+ $slug_translation_v2->mark_stale();
+ }
+
return new WP_REST_Response( array(
'code' => 'success',
'message' => 'Weglot cache purged.',
--- a/weglot/src/helpers/class-helper-api.php
+++ b/weglot/src/helpers/class-helper-api.php
@@ -202,6 +202,45 @@
}
/**
+ * Weglot 2 dashboard URL of a project page: {dashboard}/{workspace}/{project}/{path}.
+ *
+ * Falls back to the dashboard home when a slug is unknown: concatenating an empty slug built
+ * {dashboard}//… and the dashboard answered 404.
+ *
+ * @param string $workspace_slug
+ * @param string $project_slug
+ * @param string $path Dashboard page, e.g. 'languages' or 'visual-editor'.
+ * @param array<string,string> $query
+ * @return string
+ */
+ public static function build_dashboard_project_url( $workspace_slug, $project_slug, $path, $query = array() ) {
+ if ( '' === trim( (string) $project_slug ) ) {
+ return self::get_dashboard_url();
+ }
+
+ return self::build_dashboard_workspace_url( $workspace_slug, rawurlencode( (string) $project_slug ) . '/' . $path, $query );
+ }
+
+ /**
+ * Weglot 2 dashboard URL of a workspace page: {dashboard}/{workspace}/{path}.
+ *
+ * @param string $workspace_slug
+ * @param string $path
+ * @param array<string,string> $query
+ * @return string
+ */
+ public static function build_dashboard_workspace_url( $workspace_slug, $path, $query = array() ) {
+ $dashboard_url = self::get_dashboard_url();
+ if ( '' === trim( (string) $workspace_slug ) ) {
+ return $dashboard_url;
+ }
+
+ $url = untrailingslashit( $dashboard_url ) . '/' . rawurlencode( (string) $workspace_slug ) . '/' . ltrim( $path, '/' );
+
+ return array() === $query ? $url : add_query_arg( array_map( 'rawurlencode', $query ), $url );
+ }
+
+ /**
* Generates the registration URL based on the environment, onboarding version, and randomization settings.
*
* @param bool $random Whether to use a random onboarding version. Defaults to false.
--- a/weglot/src/helpers/class-helper-filter-url-weglot.php
+++ b/weglot/src/helpers/class-helper-filter-url-weglot.php
@@ -34,7 +34,7 @@
/**
* Prefix the language on wp_redirect targets, unless disabled via filter.
* @since 6.0
- * @param string $url
+ * @param string|false $url
* @return string|bool
*/
public static function filter_wp_redirect( $url ) {
@@ -44,17 +44,50 @@
if ( ! apply_filters( 'weglot_active_wp_redirect', true ) ) {
return $url;
}
+ // A falsy target means "no redirect" to wp_redirect(); rewriting it would send the visitor home.
+ if ( ! is_string( $url ) || '' === $url ) {
+ return $url;
+ }
+ // A relative reference (?query, #fragment, path) resolves in the browser against the current,
+ // already prefixed URL; the URL parser would read it as "/" and redirect to the homepage.
+ $target_host = wp_parse_url( $url, PHP_URL_HOST );
+ $is_root_relative = '/' === $url[0] && '//' !== substr( $url, 0, 2 );
+ if ( ! $is_root_relative && ! is_string( $target_host ) ) {
+ return $url;
+ }
// Only prefix internal redirects; an absolute URL pointing to another host must be left untouched.
// Host is case-insensitive (RFC 3986 §3.2.2) and wp_parse_url() does not normalise it.
- $target_host = wp_parse_url( $url, PHP_URL_HOST );
- $home_host = wp_parse_url( home_url(), PHP_URL_HOST );
+ $home_host = wp_parse_url( home_url(), PHP_URL_HOST );
if ( is_string( $target_host ) && 0 !== strcasecmp( $target_host, (string) $home_host ) ) {
return $url;
}
+ if ( self::is_admin_target( $url ) ) {
+ return $url;
+ }
return self::filter_url_lambda( $url );
}
/**
+ * A redirect to the admin must never take a language prefix: /fr/wp-admin/ is served as a front
+ * request, so core's wp_redirect_admin_locations() or a forced-login plugin sends the visitor to
+ * admin_url() again, prefixed again, in an infinite loop.
+ *
+ * @param string $url
+ * @return bool
+ */
+ private static function is_admin_target( $url ) {
+ $target_path = trailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) );
+ foreach ( array( admin_url(), network_admin_url() ) as $admin_url ) {
+ $admin_path = trailingslashit( (string) wp_parse_url( $admin_url, PHP_URL_PATH ) );
+ if ( 0 === strpos( $target_path, $admin_path ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
* Filter URL log redirection
* @since 2.0
* @version 2.0.2
--- a/weglot/src/services/class-button-service-weglot.php
+++ b/weglot/src/services/class-button-service-weglot.php
@@ -158,6 +158,9 @@
$amp_regex = $this->amp_services->get_regex( true );
$current_language = $this->request_url_services->get_current_language();
$original_language = $this->language_services->get_original_language();
+ if ( null === $original_language ) {
+ return apply_filters( 'weglot_button_html', '', $add_class );
+ }
$is_dropdown = $this->option_services->get_option_button( 'is_dropdown' );
$display_original_language = $this->request_url_services->get_weglot_url()->getExcludeOption( $original_language, 'language_button_displayed' );
$language_button_displayed = $this->request_url_services->get_weglot_url()->getExcludeOption( $weglot_url->getCurrentLanguage(), 'language_button_displayed' );
@@ -229,7 +232,7 @@
}
if ( ! $language_button_displayed ) {
- if ( ! $is_dropdown && $this->language_services->get_original_language()->getInternalCode() === $language->getInternalCode() && $display_first ) {
+ if ( ! $is_dropdown && $original_language->getInternalCode() === $language->getInternalCode() && $display_first ) {
$link_button = $this->request_url_services->get_weglot_url()->getForLanguage( $language, true );
} else {
$link_button = $this->request_url_services->get_weglot_url()->getForLanguage( $language, false );
--- a/weglot/src/services/class-dom-checkers-service-weglot.php
+++ b/weglot/src/services/class-dom-checkers-service-weglot.php
@@ -22,8 +22,7 @@
* @return array<int, string>
*/
public function get_dom_checkers() {
- $scanned_directory = scandir( __DIR__ . '/../domcheckers' );
- $files = is_array( $scanned_directory ) ? array_diff( $scanned_directory, array( '..', '.' ) ) : [];
+ $files = self::get_checker_filenames( __DIR__ . '/../domcheckers' );
$checkers = array_map(
function ( $filename ) {
// Thanks WPCS :)
@@ -37,4 +36,24 @@
return apply_filters( 'weglot_get_dom_checkers', $checkers );
}
+
+ /**
+ * Class files of a checker directory. A stray file there (.DS_Store, a macOS "._" copy,
+ * an editor backup) would be mapped to a class that does not exist and fatal every
+ * translated page. Keys are preserved, as callers and filters have always received them.
+ *
+ * @since 6.5
+ * @param string $directory Absolute path of the directory to scan.
+ * @return array<int, string>
+ */
+ public static function get_checker_filenames( string $directory ): array {
+ $filenames = is_dir( $directory ) ? scandir( $directory ) : false;
+ if ( ! is_array( $filenames ) ) {
+ return array();
+ }
+
+ $class_files = preg_grep( '/^class-[a-z0-9-]+.php$/', $filenames );
+
+ return is_array( $class_files ) ? $class_files : array();
+ }
}
--- a/weglot/src/services/class-email-translate-service-weglot.php
+++ b/weglot/src/services/class-email-translate-service-weglot.php
@@ -54,12 +54,13 @@
$api_version = $this->version_services->get_version_from_api_key_private( $api_key_private );
$api_key = ( 2 === $api_version ) ? $api_key_private : $this->option_services->get_api_key( true );
- if ( ! $api_key ) {
+ $original_language_entry = $this->language_services->get_original_language();
+ if ( ! $api_key || null === $original_language_entry ) {
return $args;
}
try {
- $original_language = $this->language_services->get_original_language()->getInternalCode();
+ $original_language = $original_language_entry->getInternalCode();
$exclude_blocks = $this->option_services->get_exclude_blocks();
$config = new ServerConfigProvider();
--- a/weglot/src/services/class-language-service-weglot.php
+++ b/weglot/src/services/class-language-service-weglot.php
@@ -62,17 +62,15 @@
$languages = new LanguagesList( $client );
- $this->languages = $languages->handle();
-
// We add the weglot_language_code_replace filter for custom code
- $this->languages = $this->languages->jsonSerialize();
+ $languages_data = $languages->handle()->jsonSerialize();
if ( isset( $params['sort'] ) && $params['sort'] ) {
- usort( $this->languages, array( $this, 'compare_language' ) );
+ usort( $languages_data, array( $this, 'compare_language' ) );
}
$language_collection = new LanguageCollection();
- foreach ( $this->languages as $language ) {
+ foreach ( $languages_data as $language ) {
$language_code_rewrited = apply_filters( 'weglot_language_code_replace', array() );
$external_code = array_key_exists( $language['internal_code'], $language_code_rewrited ) ? $language_code_rewrited[ $language['internal_code'] ] : $language['external_code'];
$entry = new LanguageEntry( $language['internal_code'], $external_code, $language['english'], $language['local'], $language['rtl'] );
@@ -92,7 +90,7 @@
* @param LanguageEntry|string $local_name
* @param bool $is_rtl
*
- * @return LanguageCollection|null
+ * @return LanguageCollection
*/
public function add_language( $internal_code, $external_code, $english_name, $local_name, $is_rtl = false ) {
if ($english_name instanceof LanguageEntry) {
@@ -103,16 +101,17 @@
$local_name = $local_name->getLocalName();
}
- $entry = new LanguageEntry( $internal_code, $external_code, $english_name, $local_name, $is_rtl );
- $this->languages->addOne( $entry );
+ $entry = new LanguageEntry( $internal_code, $external_code, $english_name, $local_name, $is_rtl );
+ $languages = $this->get_languages_available();
+ $languages->addOne( $entry );
- return $this->languages;
+ return $languages;
}
/**
* Get all languages : list of 109 default languages merged with custom languages taken from options
*
- * @return LanguageCollection|null
+ * @return LanguageCollection
* @throws Exception
*/
@@ -135,7 +134,7 @@
foreach ( $destination_languages as $d ) {
/** @var LanguageEntry|null $language_data */
- $language_data = $this->languages->getCode( $d['language_to'] );
+ $language_data = $this->get_languages_available()->getCode( $d['language_to'] );
if ( ! $language_data ) {
$this->languages = $this->add_language( $d['language_to'], $d['custom_code'], $d['custom_name'], $d['custom_local_name'] );
} else {
@@ -265,8 +264,11 @@
* @return LanguageEntry[]
*/
public function get_original_and_destination_languages( $allowed_private = false, $excluded_languages = array() ) {
- $languages = $this->get_destination_languages( $allowed_private, $excluded_languages );
- array_unshift( $languages, $this->get_original_language() );
+ $languages = $this->get_destination_languages( $allowed_private, $excluded_languages );
+ $original_language = $this->get_original_language();
+ if ( null !== $original_language ) {
+ array_unshift( $languages, $original_language );
+ }
return $languages;
}
--- a/weglot/src/services/class-menu-options-service-weglot.php
+++ b/weglot/src/services/class-menu-options-service-weglot.php
@@ -66,7 +66,7 @@
}
/**
- * @return string|null.
+ * @return string|null
*/
function weglot_get_widgets_admin_url() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
--- a/weglot/src/services/class-noindex-service-weglot.php
+++ b/weglot/src/services/class-noindex-service-weglot.php
@@ -125,7 +125,7 @@
return false;
}
- $path = $this->request_url_services->get_weglot_url()->getPath();
+ $path = $this->request_url_services->get_weglot_url()->getPath() ?? '';
foreach ( $this->get_noindex_urls() as $rule ) {
if ( null !== $rule[1] && ! $this->has_language( $rule[1], $language ) ) {
--- a/weglot/src/services/class-option-service-weglot.php
+++ b/weglot/src/services/class-option-service-weglot.php
@@ -140,7 +140,7 @@
*
* @param string $api_key
* @return void
- * @since 6.4
+ * @since 6.4.1
*/
private function purge_options_cache_if_key_changed( $api_key ) {
$fingerprint = hash( 'sha256', $api_key );
@@ -352,7 +352,7 @@
$active_slugs = apply_filters( 'weglot_active_slugs', true );
if ( $this->slugs_from_api || ! $active_slugs ) {
- return $this->slugs_from_api;
+ return $this->slugs_from_api ?? array();
}
// Prevent infinite recursion: get_options() below can call back into slug loading.
@@ -473,11 +473,16 @@
*/
public function get_version() {
$options = $this->get_options();
- if ( ! isset( $options['versions']['translation'] ) ) {
+ // Weglot 2 project settings name the field in the plural, the Weglot 1 CDN in the singular.
+ $field = 2 === $this->version_service_weglot->get_version_from_api_key_private( $this->get_api_key_private() )
+ ? 'translations'
+ : 'translation';
+
+ if ( ! isset( $options['versions'][ $field ] ) ) {
return apply_filters( 'weglot_get_version', 1 );
}
- return apply_filters( 'weglot_get_version', $options['versions']['translation'] );
+ return apply_filters( 'weglot_get_version', $options['versions'][ $field ] );
}
/**
@@ -534,7 +539,7 @@
$response = $this->get_options_from_cdn_with_api_key( $api_key_private );
if(
! $response['success'] ||
- ( isset( $response['result']['error'] ) && null !== $response['result']['error'] ) ||
+ isset( $response['result']['error'] ) ||
( isset( $response['result']['status'] ) && 200 !== (int) $response['result']['status'] )
){
return $this->get_options_from_v2();
@@ -599,7 +604,14 @@
$destinations_languages = array_column( $options['destination_language'], 'language_to' );
- if ( Helper_Is_Admin::is_wp_admin() && $api_key_private && $is_weglot_settings_page ) {
+ if ( $is_v2 ) {
+ // Exclusive: a site moved from Weglot 1 keeps its public key and a weglot_slugs_cache
+ // that never expires, whose slugs must not be mixed with the Weglot 2 ones.
+ $slug_translation_v2 = weglot_get_service( Slug_Translation_V2_Service_Weglot::class );
+ if ( $slug_translation_v2 instanceof Slug_Translation_V2_Service_Weglot ) {
+ $slugs = $slug_translation_v2->get_slugs( $options, $api_key_private, array_map( 'strval', $destinations_languages ) );
+ }
+ } elseif ( Helper_Is_Admin::is_wp_admin() && $api_key_private && $is_weglot_settings_page ) {
$slugs = $this->get_slugs_from_api_with_api_key( $api_key_private, $destinations_languages );
} else {
if ( ( ! Helper_Is_Admin::is_wp_admin() && $api_key ) || ( Helper_Is_Admin::is_wp_admin() && ! $is_weglot_settings_page ) ) {
@@ -617,7 +629,7 @@
* @param array<int|string,mixed> $array1
* @param array<int|string,mixed> $array2
*
- * @return array<string,mixed>
+ * @return array<int|string,mixed>
* @throws Exception
* @since 2.0
* @version 3.0.0
@@ -697,6 +709,53 @@
}
/**
+ * Masks an API key down to its last 4 characters, keeping the "wg_" version prefix.
+ *
+ * The mask has the same length as the key: the v2 onboarding script rejects shorter values
+ * before asking the server to validate them.
+ *
+ * @param string $api_key
+ * @return string
+ * @since 6.5
+ */
+ public function mask_api_key( $api_key ) {
+ $prefix = 0 === strpos( $api_key, 'wg_' ) ? 'wg_' : '';
+ $secret = (string) substr( $api_key, strlen( $prefix ) );
+
+ if ( strlen( $secret ) <= 4 ) {
+ return $prefix . str_repeat( '•', strlen( $secret ) );
+ }
+
+ return $prefix . str_repeat( '•', strlen( $secret ) - 4 ) . substr( $secret, -4 );
+ }
+
+ /**
+ * The API key as the settings screens display it: masked when it comes from the constant.
+ *
+ * @return string
+ * @since 6.5
+ */
+ public function get_displayed_api_key_private() {
+ $api_key_private = (string) $this->get_api_key_private();
+
+ return $this->has_api_key_private_constant() ? $this->mask_api_key( $api_key_private ) : $api_key_private;
+ }
+
+ /**
+ * The API key a settings form submitted, or the constant when one is defined.
+ *
+ * The screens only display a masked copy of the constant, so whatever the browser sends back
+ * must never be used in its place.
+ *
+ * @param string $submitted_api_key
+ * @return string
+ * @since 6.5
+ */
+ public function resolve_submitted_api_key_private( $submitted_api_key ) {
+ return $this->has_api_key_private_constant() ? $this->get_api_key_private() : $submitted_api_key;
+ }
+
+ /**
* Persists the API key, unless it is supplied by the WEGLOT_API_KEY_PRIVATE constant.
*
* @param string $api_key_private
@@ -713,7 +772,7 @@
/**
- * @param array<string,mixed> $options
+ * @param array<int|string,mixed> $options
*
* @return array<string,mixed>
* @since 3.0.0
@@ -760,7 +819,7 @@
}
/**
- * @param array<string,mixed> $options
+ * @param array<int|string,mixed> $options
*
* @return array<string,mixed>
* @since 3.0.0
--- a/weglot/src/services/class-parser-service-weglot.php
+++ b/weglot/src/services/class-parser-service-weglot.php
@@ -187,12 +187,17 @@
*/
public function escape_vue_attributes( $content ) {
// Escape attributes that start with "v-" (e.g. v-for, v-bind:src, etc.)
- $content = preg_replace( '/bv-([w-]+)=/', 'data-vue-v-$1=', $content );
+ $escaped = preg_replace( '/bv-([w-]+)=/', 'data-vue-v-$1=', $content );
+ if ( null !== $escaped ) {
+ $content = $escaped;
+ }
// Escape shorthand Vue.js directives starting with ":" by ensuring we match the start of the attribute.
// This regex looks for either the beginning of the string (^) or any whitespace (s)
// followed by ":" and then the attribute name.
- return preg_replace( '/(^|s):([w-]+)=/', '$1data-vue-bind-$2=', $content );
+ $escaped = preg_replace( '/(^|s):([w-]+)=/', '$1data-vue-bind-$2=', $content );
+
+ return null === $escaped ? $content : $escaped;
}
/**
@@ -203,10 +208,15 @@
*/
public function restore_vue_attributes( $content ) {
// Restore attributes replaced for "v-" directives.
- $content = preg_replace( '/bdata-vue-v-([w-]+)=/', 'v-$1=', $content );
+ $restored = preg_replace( '/bdata-vue-v-([w-]+)=/', 'v-$1=', $content );
+ if ( null !== $restored ) {
+ $content = $restored;
+ }
// Restore the shorthand directives for attributes starting with a colon.
- return preg_replace( '/(^|s)data-vue-bind-([w-]+)=/', '$1:$2=', $content );
+ $restored = preg_replace( '/(^|s)data-vue-bind-([w-]+)=/', '$1:$2=', $content );
+
+ return null === $restored ? $content : $restored;
}
@@ -303,7 +313,7 @@
$list = implode( '|', array_map( 'preg_quote', $attrs ) );
- return preg_replace_callback(
+ $preserved = preg_replace_callback(
'/b(' . $list . ')=(\\?)(['"])(.*?)23/s',
function( $m ) {
static $i = 0;
@@ -325,6 +335,8 @@
},
$html
);
+
+ return null === $preserved ? $html : $preserved;
}
@@ -337,13 +349,16 @@
*/
public function restore_preserved_attributes( string $html ): string {
foreach ( $this->preserved as $token => $original ) {
- $html = preg_replace_callback(
+ $restored = preg_replace_callback(
'/(\\?)(['"])' . preg_quote( $token, '/' ) . '12/',
function( $m ) use ( $original ) {
return $m[1] . $m[2] . $original . $m[1] . $m[2];
},
$html
);
+ if ( null !== $restored ) {
+ $html = $restored;
+ }
}
$this->preserved = [];
return $html;
--- a/weglot/src/services/class-pdf-translate-service-weglot.php
+++ b/weglot/src/services/class-pdf-translate-service-weglot.php
@@ -57,12 +57,13 @@
$api_version = $this->version_services->get_version_from_api_key_private( $api_key_private );
$api_key = ( 2 === $api_version ) ? $api_key_private : $this->option_services->get_api_key( true );
- if ( ! $api_key ) {
+ $original_language_entry = $this->language_services->get_original_language();
+ if ( ! $api_key || null === $original_language_entry ) {
return $content;
}
try {
- $original_language = $this->language_services->get_original_language()->getInternalCode();
+ $original_language = $original_language_entry->getInternalCode();
$exclude_blocks = $this->option_services->get_exclude_blocks();
$config = new ServerConfigProvider();
--- a/weglot/src/services/class-redirect-service-weglot.php
+++ b/weglot/src/services/class-redirect-service-weglot.php
@@ -115,7 +115,10 @@
public function get_best_available_language( $navigator_languages, $available_languages ) {
// We add the original in the list of available languages.
- $available_languages[] = $this->language_services->get_original_language()->getExternalCode();
+ $original_language = $this->language_services->get_original_language();
+ if ( null !== $original_language ) {
+ $available_languages[] = $original_language->getExternalCode();
+ }
// We check if user add a custom languages code
$navigator_languages = apply_filters('weglot_navigator_language', $navigator_languages);
@@ -164,7 +167,7 @@
$navigator_languages = $this->get_navigator_languages();
$destination_languages_external = $this->language_services->get_destination_languages_external( $this->request_url_services->is_allowed_private(), $this->request_url_services->get_excluded_languages_for_current_url() );
$best_external_language = $this->get_best_available_language( $navigator_languages, $destination_languages_external );
- $best_language = $this->language_services->get_language_from_external( $best_external_language );
+ $best_language = null !== $best_external_language ? $this->language_services->get_language_from_external( $best_external_language ) : null;
// Redirect using the best language.
@@ -183,12 +186,16 @@
}
// If there is no best language, we redirect using the auto switch fallback if there is one in the options.
- if ( empty($best_language) || ( ! in_array( $this->language_services->get_original_language()->getExternalCode(), $navigator_languages ) &&
+ $original_language = $this->language_services->get_original_language();
+ if ( null === $original_language ) {
+ return;
+ }
+ if ( empty($best_language) || ( ! in_array( $original_language->getExternalCode(), $navigator_languages ) &&
$this->option_services->get_option( 'autoswitch_fallback' ) !== null )
) {
$fallback_language = $this->language_services->get_language_from_internal( $this->option_services->get_option( 'autoswitch_fallback' ) );
//Cancel redirect if excluded page.
- if ( ! $this->request_url_services->get_weglot_url()->getForLanguage( $fallback_language, false ) ){
+ if ( null === $fallback_language || ! $this->request_url_services->get_weglot_url()->getForLanguage( $fallback_language, false ) ){
return;
}
$url_auto_redirect = apply_filters( 'weglot_url_auto_redirect', $this->request_url_services->get_weglot_url()->getForLanguage( $fallback_language, true ) );
@@ -222,11 +229,19 @@
// Remove the 'wg-choose-original' parameter from the query string
$request_uri = preg_replace( '/([&?])wg-choose-original=[^&]*(&|$)/', '$1', $request_uri );
+ // Redirecting with the parameter still in the URL would set the cookie and redirect again, forever.
+ if ( null === $request_uri ) {
+ return;
+ }
+
// Remove any trailing '&' or '?' left in the query string
$request_uri = rtrim( $request_uri, '&?' );
// Ensure the URL doesn't end with a '?' if no other query parameters are present
- $request_uri = preg_replace( '/?$/', '', $request_uri );
+ $without_question_mark = preg_replace( '/?$/', '', $request_uri );
+ if ( null !== $without_question_mark ) {
+ $request_uri = $without_question_mark;
+ }
$_SERVER['REQUEST_URI'] = $request_uri;
--- a/weglot/src/services/class-regex-checkers-service-weglot.php
+++ b/weglot/src/services/class-regex-checkers-service-weglot.php
@@ -54,11 +54,7 @@
continue;
}
- $scandir_files = scandir( $third_path );
- if ( false === $scandir_files ) {
- $scandir_files = [];
- }
- $files = array_diff( $scandir_files, array( '..', '.' ) );
+ $files = Dom_Checkers_Service_Weglot::get_checker_filenames( $third_path );
foreach ( $files as $file ) {
if ( strpos( $file, 'active.php' ) !== false ) {
@@ -79,19 +75,13 @@
$active = $service->is_active();
if ( $active ) {
- $regex_dir = WEGLOT_DIR . '/src/third/' . $third . '/regexcheckers/';
- if ( is_dir( $regex_dir ) ) {
- $files = scandir( WEGLOT_DIR . '/src/third/' . $third . '/regexcheckers/' );
- if(is_array($files)){
- $regex_files = array_diff( $files, array( '..', '.' ) );
- foreach ( $regex_files as $regex_file ) {
- $filename = Text::removeFileExtension( $regex_file );
- $filename = str_replace( 'class-', '', $filename );
- $filename = implode( '_', array_map( 'ucfirst', explode( '-', $filename ) ) );
- $class = '\WeglotWP\Third\' . implode( '', array_map( 'ucfirst', explode( '-', $third ) ) ) . '\Regexcheckers\' . $filename;
- $checkers[] = new RegexChecker( $class::REGEX, $class::TYPE, $class::VAR_NUMBER, $class::$KEYS );
- }
- }
+ $regex_files = Dom_Checkers_Service_Weglot::get_checker_filenames( WEGLOT_DIR . '/src/third/' . $third . '/regexcheckers/' );
+ foreach ( $regex_files as $regex_file ) {
+ $filename = Text::removeFileExtension( $regex_file );
+ $filename = str_replace( 'class-', '', $filename );
+ $filename = implode( '_', array_map( 'ucfirst', explode( '-', $filename ) ) );
+ $class = '\WeglotWP\Third\' . implode( '', array_map( 'ucfirst', explode( '-', $third ) ) ) . '\Regexcheckers\' . $filename;
+ $checkers[] = new RegexChecker( $class::REGEX, $class::TYPE, $class::VAR_NUMBER, $class::$KEYS );
}
}
}
--- a/weglot/src/services/class-replace-link-service-weglot.php
+++ b/weglot/src/services/class-replace-link-service-weglot.php
@@ -24,7 +24,7 @@
private $request_url_services;
/**
- * @var array<int|string,mixed>|null
+ * @var array<int|string,mixed>
*/
private $multisite_other_paths;
@@ -34,7 +34,7 @@
public function __construct() {
$this->multisite_service = weglot_get_service( Multisite_Service_Weglot::class );
$this->request_url_services = weglot_get_service( Request_Url_Service_Weglot::class );
- $this->multisite_other_paths = null;
+ $this->multisite_other_paths = array();
if ( is_multisite() ) {
$this->multisite_other_paths = array_filter(
$this->multisite_service->get_list_of_network_path(),
@@ -136,8 +136,9 @@
* @version 2.0.4
* @since 2.0
*/
- public function replace_a( $translated_page, $current_url, $quote1, $quote2, $sometags = null, $sometags2 = null ) {
+ public function replace_a( $translated_page, $current_url, $quote1, $quote2, $sometags = '', $sometags2 = '' ) {
$current_language = $this->request_url_services->get_current_language();
+ $replaced = null;
$no_replace_condition = apply_filters( 'weglot_no_replace_a_href', 'wp-content/uploads' );
if ( strpos( $current_url, $no_replace_condition ) !== false ) {
@@ -173,19 +174,19 @@
$paths = explode( '/', $parsed_url['path'] );
$other_site = in_array( '/' . $paths[1] . '/', $this->multisite_other_paths );
if ( $other_site ) {
- $replace_url_other_site = preg_replace( '#(?<!https:)//+#', '/', 'wg-' . esc_url( $replace_url_other_site ) );
- $translated_page = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', 'a' . $sometags . 'href=' . $quote1 . $this->esc_preg_replacement( $replace_url_other_site ) . $quote2 . $sometags2 . '>', $translated_page );
+ $replace_url_other_site = (string) preg_replace( '#(?<!https:)//+#', '/', 'wg-' . esc_url( $replace_url_other_site ) );
+ $replaced = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', 'a' . $sometags . 'href=' . $quote1 . $this->esc_preg_replacement( $replace_url_other_site ) . $quote2 . $sometags2 . '>', $translated_page );
} else {
- $translated_page = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', '<a' . $sometags . 'href=' . $quote1 . $this->esc_replacement( $this->replace_url( $current_url, $current_language ) ) . $quote2 . $sometags2 . '>', $translated_page );
+ $replaced = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', '<a' . $sometags . 'href=' . $quote1 . $this->esc_replacement( $this->replace_url( $current_url, $current_language ) ) . $quote2 . $sometags2 . '>', $translated_page );
}
}
} else {
- $translated_page = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', '<a' . $sometags . 'href=' . $quote1 . $this->esc_replacement( $this->replace_url( $current_url, $current_language ) ) . $quote2 . $sometags2 . '>', $translated_page );
+ $replaced = preg_replace( '/<a' . preg_quote( $sometags, '/' ) . 'href=' . preg_quote( $quote1 . $current_url . $quote2, '/' ) . preg_quote( $sometags2, '/' ) . '>/', '<a' . $sometags . 'href=' . $quote1 . $this->esc_replacement( $this->replace_url( $current_url, $current_language ) ) . $quote2 . $sometags2 . '>', $translated_page );
}
- return $translated_page;
+ return null === $replaced ? $translated_page : $replaced;
}
/**
@@ -201,8 +202,9 @@
* @return string
* @since 2.0
*/
- public function replace_datalink( $translated_page, $current_url, $quote1, $quote2, $sometags = null, $sometags2 = null ) {
+ public func