Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/gptranslate/ajax-handler.php
+++ b/gptranslate/ajax-handler.php
@@ -83,6 +83,10 @@
$task = preg_replace('/[^a-zA-Z]/', '', $params['task'] ?? '');
$pageLink = filter_var($params['pagelink'] ?? '', FILTER_SANITIZE_URL);
+// Parameters that never identify a page (tracking...) do not make another page
+$pageLink = gpt_remove_ignored_query_params($pageLink);
+// A fragment ignored by the "Ignored URL fragments" setting is not part of the page link
+$pageLink = gpt_remove_ignored_url_fragment($pageLink);
$languageOriginal = preg_replace('/[^a-zA-Z-]/', '', $params['language_original'] ?? '');
$languageTranslated = preg_replace('/[^a-zA-Z-]/', '', $params['language_translated'] ?? '');
$retriggerTranslation = (int)($params['retrigger'] ?? 0);
@@ -90,6 +94,158 @@
$table = $wpdb->prefix . 'gptranslate';
$response = ['result' => false];
+/**
+ * Whether a query string parameter never identifies a page: campaign, click and referral tracking (utm_*, gclid, fbclid...), cache busting
+ * of Cloudflare, Joomla Smart Search highlight. The names are case insensitive. Pages that differ only by these parameters are the same page:
+ * they share the same translation record
+ *
+ * @param string $name Parameter name
+ * @return bool
+ */
+function gpt_is_ignored_query_param($name) {
+ static $names = array('highlight', 'gclid', 'gbraid', 'wbraid', 'dclid', 'msclkid', 'fbclid', 'yclid', 'ttclid', 'twclid', 'igshid',
+ 'li_fat_id', 'mc_cid', 'mc_eid', '_ga', '_gl', '_hsenc', '_hsmi', 'srsltid', 'gad_source', 'gad_campaignid');
+ static $prefixes = array('utm_', 'fb_', 'x-wblr-', '__cf_chl_');
+ $name = strtolower((string) $name);
+ if (in_array($name, $names, true)) {
+ return true;
+ }
+ foreach ($prefixes as $prefix) {
+ if (strpos($name, $prefix) === 0) {
+ return true;
+ }
+ }
+
+ static $configuredNames = null;
+ static $configuredPrefixes = array();
+ if ($configuredNames === null) {
+ $configuredNames = array();
+ global $wpdb;
+ $optionsRaw = $wpdb->get_var("SELECT option_value FROM {$wpdb->options} WHERE option_name = 'gptranslate_options' LIMIT 1");
+ $options = $optionsRaw ? @unserialize($optionsRaw) : array();
+ $list = is_array($options) && isset($options['ignored_query_params']) ? (string) $options['ignored_query_params'] : '';
+ foreach (explode(',', strtolower($list)) as $configuredName) {
+ $configuredName = trim($configuredName);
+ if ($configuredName === '') {
+ continue;
+ }
+ if (substr($configuredName, -1) === '*') {
+ if (strlen($configuredName) > 1) {
+ $configuredPrefixes[] = substr($configuredName, 0, -1);
+ }
+ } else {
+ $configuredNames[] = $configuredName;
+ }
+ }
+ }
+ if (in_array($name, $configuredNames, true)) {
+ return true;
+ }
+ foreach ($configuredPrefixes as $configuredPrefix) {
+ if (strpos($name, $configuredPrefix) === 0) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Remove from a URL the query string parameters that never identify a page (see gpt_is_ignored_query_param()). Only when one is present
+ * the query string is rewritten: the other parameters, their order and their encoding are kept, and so is the fragment
+ *
+ * @param string $url
+ * @return string
+ */
+function gpt_remove_ignored_query_params($url) {
+ $url = (string) $url;
+ $queryPos = strpos($url, '?');
+ if ($queryPos === false) {
+ return $url;
+ }
+ $hashPos = strpos($url, '#', $queryPos);
+ $fragment = $hashPos !== false ? substr($url, $hashPos) : '';
+ $query = $hashPos !== false ? substr($url, $queryPos + 1, $hashPos - $queryPos - 1) : substr($url, $queryPos + 1);
+ $kept = array();
+ $changed = false;
+ foreach (explode('&', $query) as $pair) {
+ $name = preg_replace('~[.*$~', '', urldecode((string) strtok($pair, '=')));
+ if ($pair !== '' && gpt_is_ignored_query_param($name)) {
+ $changed = true;
+ continue;
+ }
+ $kept[] = $pair;
+ }
+ if (!$changed) {
+ return $url;
+ }
+ $kept = array_filter($kept, 'strlen');
+
+ return substr($url, 0, $queryPos) . ($kept ? '?' . implode('&', $kept) : '') . $fragment;
+}
+
+/**
+ * Remove from a URL the fragment (#...) ignored by the "Ignored URL fragments" setting: comma-separated names, case insensitive; a name ending
+ * with * matches all the fragments starting with it and * alone matches every fragment. The other fragments are kept
+ *
+ * @param string $url
+ * @return string
+ */
+function gpt_remove_ignored_url_fragment($url) {
+ $url = (string) $url;
+ $hashPos = strpos($url, '#');
+ if ($hashPos === false) {
+ return $url;
+ }
+ static $names = null;
+ static $prefixes = array();
+ static $all = false;
+ if ($names === null) {
+ $names = array();
+ $list = gpt_ignored_url_fragments_option();
+ foreach (explode(',', strtolower($list)) as $configuredName) {
+ $configuredName = trim($configuredName);
+ if ($configuredName === '') {
+ continue;
+ }
+ if ($configuredName === '*') {
+ $all = true;
+ } elseif (substr($configuredName, -1) === '*') {
+ $prefixes[] = substr($configuredName, 0, -1);
+ } else {
+ $names[] = $configuredName;
+ }
+ }
+ }
+ if (!$all && !$names && !$prefixes) {
+ return $url;
+ }
+ $fragment = strtolower(urldecode(substr($url, $hashPos + 1)));
+ if ($all || in_array($fragment, $names, true)) {
+ return substr($url, 0, $hashPos);
+ }
+ foreach ($prefixes as $prefix) {
+ if (strpos($fragment, $prefix) === 0) {
+ return substr($url, 0, $hashPos);
+ }
+ }
+
+ return $url;
+}
+
+/**
+ * The "Ignored URL fragments" setting (the options API is not loaded here: the option is read from the database)
+ *
+ * @return string
+ */
+function gpt_ignored_url_fragments_option() {
+ global $wpdb;
+ $optionsRaw = $wpdb->get_var("SELECT option_value FROM {$wpdb->options} WHERE option_name = 'gptranslate_options' LIMIT 1");
+ $options = $optionsRaw ? @unserialize($optionsRaw) : array();
+
+ return is_array($options) && isset($options['ignored_url_fragments']) ? (string) $options['ignored_url_fragments'] : '';
+}
+
// Lightweight replacement for WP trailingslashit + untrailingslashit + wp_parse_url
function gpt_light_trailingslashit($url) {
$parsed = parse_url($url);
--- a/gptranslate/gptranslate.php
+++ b/gptranslate/gptranslate.php
@@ -4,7 +4,7 @@
Plugin URI: https://gptranslate.storejextensions.org/
Description: GPTranslate for Wordpress is the revolutionary multilanguage solution to automatically translate your Wordpress website thanks to the power of Artificial Intelligence like ChatGPT, Deepseek, Gemini, Claude, DeepL and more. GPTranslate FREE installed. GPTranslate Free: ready to translate.
Author: JExtensions Store
- Version: 2.34.17
+ Version: 2.35
Author URI: https://storejextensions.org
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -72,7 +72,7 @@
return $reverse;
}
- public static $pluginVersion = '2.34.17';
+ public static $pluginVersion = '2.35';
/**
* Class constructor and settings inizializer with register_setting it's the main entry point
@@ -83,7 +83,7 @@
global $wpdb;
$this->table_name = $wpdb->prefix . 'gptranslate';
- $this->version = '2.34.17';
+ $this->version = '2.35';
$settings = get_option ( 'gptranslate_options', [ ] );
@@ -541,6 +541,9 @@
'serverside_translations_language_switching_mode' => 'url',
'serverside_translations_ignore_querystring' => '0',
'serverside_translations_strip_querystring_params' => '',
+ 'ignored_query_params' => '',
+ 'ignored_url_fragments' => '',
+ 'hreflang_keep_query' => '0',
'serverside_translations_urlencode_space' => '0',
'serverside_translations_selfheal_seconds' => '900',
'css_selector_serverside_leafnodes_excluded' => '',
@@ -602,6 +605,7 @@
'realtime_translations_retrigger_scope_selector' => '',
'translations_export_format' => '.csv',
'ignore_querystring' => '0',
+ 'page_cache_compat' => '0',
'enable_indexer' => '0',
'lightweight_ajax_endpoint' => '0',
'storage_type' => 'session',
@@ -637,6 +641,8 @@
'enable_modal' => '0',
'equal_widths' => '0',
'reader_button_position' => 'top',
+ 'reader_widget_position' => 'same',
+ 'reader_show_label' => '1',
'widget_max_height' => '260',
'wrapper_selector' => '.gptranslate_wrapper',
'draggable_widget' => '0',
@@ -874,7 +880,12 @@
<option value="gpt-5.6-terra" <?php selected($currentModel, 'gpt-5.6-terra'); ?>>GPT-5.6 Terra</option>
<option value="gpt-5.6-luna" <?php selected($currentModel, 'gpt-5.6-luna'); ?>>GPT-5.6 Luna</option>
<option value="gpt-6-astra" <?php selected($currentModel, 'gpt-6-astra'); ?>>GPT-6 Astra</option>
+ <option value="gpt-6-luna" <?php selected($currentModel, 'gpt-6-luna'); ?>>GPT-6 Luna</option>
+ <option value="gpt-6.1-sol" <?php selected($currentModel, 'gpt-6.1-sol'); ?>>GPT-6.1 Sol</option>
+ <option value="gpt-6.1-terra" <?php selected($currentModel, 'gpt-6.1-terra'); ?>>GPT-6.1 Terra</option>
<option value="deepseek-chat" <?php selected($currentModel, 'deepseek-chat'); ?>>DeepSeek Chat</option>
+ <option value="deepseek-flash" <?php selected($currentModel, 'deepseek-flash'); ?>>DeepSeek Flash</option>
+ <option value="deepseek-v4-pro" <?php selected($currentModel, 'deepseek-v4-pro'); ?>>DeepSeek V4 Pro</option>
<option value="gemini-2.5-flash" <?php selected($currentModel, 'gemini-2.5-flash'); ?>>Gemini 2.5 Flash</option>
<option value="gemini-2.5-pro" <?php selected($currentModel, 'gemini-2.5-pro'); ?>>Gemini 2.5 Pro</option>
<option value="gemini-2.5-flash-lite" <?php selected($currentModel, 'gemini-2.5-flash-lite'); ?>>Gemini 2.5 Flash Lite</option>
@@ -886,20 +897,27 @@
<option value="gemini-3.6-flash" <?php selected($currentModel, 'gemini-3.6-flash'); ?>>Gemini 3.6 Flash</option>
<option value="gemini-3.7-flash" <?php selected($currentModel, 'gemini-3.7-flash'); ?>>Gemini 3.7 Flash</option>
<option value="gemini-3.8-flash" <?php selected($currentModel, 'gemini-3.8-flash'); ?>>Gemini 3.8 Flash</option>
+ <option value="gemini-4-hydrogen" <?php selected($currentModel, 'gemini-4-hydrogen'); ?>>Gemini 4 Hydrogen</option>
+ <option value="gemini-4-argon" <?php selected($currentModel, 'gemini-4-argon'); ?>>Gemini 4 Argon</option>
+ <option value="gemini-4-carbon" <?php selected($currentModel, 'gemini-4-carbon'); ?>>Gemini 4 Carbon</option>
<option value="claude-sonnet-4-5" <?php selected($currentModel, 'claude-sonnet-4-5'); ?>>Claude Sonnet 4.5</option>
<option value="claude-sonnet-4-6" <?php selected($currentModel, 'claude-sonnet-4-6'); ?>>Claude Sonnet 4.6</option>
<option value="claude-sonnet-5" <?php selected($currentModel, 'claude-sonnet-5'); ?>>Claude Sonnet 5</option>
<option value="claude-haiku-4-5" <?php selected($currentModel, 'claude-haiku-4-5'); ?>>Claude Haiku 4.5</option>
+ <option value="claude-haiku-5-5" <?php selected($currentModel, 'claude-haiku-5-5'); ?>>Claude Haiku 5.5</option>
<option value="claude-opus-4-6" <?php selected($currentModel, 'claude-opus-4-6'); ?>>Claude Opus 4.6</option>
<option value="claude-opus-4-7" <?php selected($currentModel, 'claude-opus-4-7'); ?>>Claude Opus 4.7</option>
<option value="claude-opus-4-8" <?php selected($currentModel, 'claude-opus-4-8'); ?>>Claude Opus 4.8</option>
<option value="claude-opus-5" <?php selected($currentModel, 'claude-opus-5'); ?>>Claude Opus 5</option>
<option value="claude-opus-5-5" <?php selected($currentModel, 'claude-opus-5-5'); ?>>Claude Opus 5.5</option>
<option value="claude-fable-5" <?php selected($currentModel, 'claude-fable-5'); ?>>Claude Fable 5</option>
+ <option value="claude-fable-5-1" <?php selected($currentModel, 'claude-fable-5-1'); ?>>Claude Fable 5.1</option>
+ <option value="claude-fable-5-2" <?php selected($currentModel, 'claude-fable-5-2'); ?>>Claude Fable 5.2</option>
<option value="grok-3" <?php selected($currentModel, 'grok-3'); ?>>Grok 3</option>
<option value="grok-3-mini" <?php selected($currentModel, 'grok-3-mini'); ?>>Grok 3 Mini</option>
<option value="grok-4.5" <?php selected($currentModel, 'grok-4.5'); ?>>Grok 4.5</option>
<option value="grok-4.6" <?php selected($currentModel, 'grok-4.6'); ?>>Grok 4.6</option>
+ <option value="grok-4.7" <?php selected($currentModel, 'grok-4.7'); ?>>Grok 4.7</option>
<option value="google-cloud-translation-api" <?php selected($currentModel, 'google-cloud-translation-api'); ?>>Google Cloud Translation API</option>
<option value="deepl-api" <?php selected($currentModel, 'deepl-api'); ?>>DeepL API</option>
</select>
@@ -1105,9 +1123,9 @@
// Alternative flags check for edit view
$altFlagsOpts = isset($opts['alt_flags']) && is_array($opts['alt_flags']) ? $opts['alt_flags'] : [];
$altFlagMap = [
- 'en' => ['usa' => 'en-us', 'canada' => 'en-ca', 'ireland' => 'en-ie'],
+ 'en' => ['usa' => 'en-us', 'canada' => 'en-ca', 'ireland' => 'en-ie', 'usa_uk' => 'en-us-gb'],
'pt' => ['brazil' => 'pt-br'],
- 'es' => ['mexico' => 'es-mx', 'argentina' => 'es-ar', 'colombia' => 'es-co'],
+ 'es' => ['mexico' => 'es-mx', 'argentina' => 'es-ar', 'colombia' => 'es-co', 'spain_mexico' => 'es-es-mx'],
'fr' => ['quebec' => 'fr-qc'],
'zh' => ['taiwan' => 'zh-TW'],
'zt' => ['hongkong' => 'zh-HK'],
@@ -1447,7 +1465,7 @@
var gptranslateSitemapUrl = "' . esc_js( rest_url( 'gptranslate/v1/sitemap.xml' ) ) . '";
var gptranslateDefaultLanguage = "' . $opts['language'] . '";
var gptranslateCrawlerTimeout = "' . (isset($opts['crawler_timeout']) ? $opts['crawler_timeout'] : '60') . '";
- var gptranslateCrawlerExclusions = "' . esc_js(trim(preg_replace('/,+/', ',', str_ireplace(["r", "n"], ",", (isset($opts['crawler_exclusions']) ? $opts['crawler_exclusions'] : ''))), ',')) . '";
+ var gptranslateCrawlerExclusions = "' . esc_js(gpt_crawler_exclusions_list($opts)) . '";
var gptranslateCrawlerSkipTranslated = ' . (int)($opts['crawler_skip_translated'] ?? 0) . ';
var gptSubfolderInstallation = ' . (int)($opts['subfolder_installation'] ?? 0) . ';
var gptranslateRewriteLanguageUrl = ' . (int)$opts['rewrite_language_url'] . ';
@@ -1625,9 +1643,9 @@
// Alternative flags check for list view
$altFlagsOpts = isset($opts['alt_flags']) && is_array($opts['alt_flags']) ? $opts['alt_flags'] : [];
$altFlagMap = [
- 'en' => ['usa' => 'en-us', 'canada' => 'en-ca', 'ireland' => 'en-ie'],
+ 'en' => ['usa' => 'en-us', 'canada' => 'en-ca', 'ireland' => 'en-ie', 'usa_uk' => 'en-us-gb'],
'pt' => ['brazil' => 'pt-br'],
- 'es' => ['mexico' => 'es-mx', 'argentina' => 'es-ar', 'colombia' => 'es-co'],
+ 'es' => ['mexico' => 'es-mx', 'argentina' => 'es-ar', 'colombia' => 'es-co', 'spain_mexico' => 'es-es-mx'],
'fr' => ['quebec' => 'fr-qc'],
'zh' => ['taiwan' => 'zh-TW'],
'zt' => ['hongkong' => 'zh-HK'],
@@ -1886,6 +1904,11 @@
* @access public
*/
public function enqueue_frontend_scripts() {
+ // Pages excluded from translation ("Exclude links from rewriting" patterns) get no language switcher and no translation script
+ if ( ! empty( $GLOBALS['gptranslate_page_excluded'] ) ) {
+ return;
+ }
+
// Skip loading the translation script entirely on 404 pages, unless the admin
// explicitly opted in to also translate them via the "Translate 404 pages" setting.
if ( is_404() ) {
@@ -2071,19 +2094,19 @@
$alt_flags = array ();
$raw_alt_flags = isset($settings ['alt_flags']) ? $settings ['alt_flags'] : [];
foreach ( $raw_alt_flags as $country ) {
- if ($country == 'usa' || $country == 'canada' || $country == 'ireland')
+ if ($country == 'usa' || $country == 'canada' || $country == 'ireland' || $country == 'usa_uk')
$alt_flags ['en'] = $country;
- elseif ($country == 'brazil')
+ elseif ($country == 'brazil')
$alt_flags ['pt'] = $country;
- elseif ($country == 'mexico' or $country == 'argentina' or $country == 'colombia')
+ elseif ($country == 'mexico' or $country == 'argentina' or $country == 'colombia' or $country == 'spain_mexico')
$alt_flags ['es'] = $country;
- elseif ($country == 'quebec')
+ elseif ($country == 'quebec')
$alt_flags ['fr'] = $country;
- elseif ($country == 'taiwan')
+ elseif ($country == 'taiwan')
$alt_flags ['zh'] = $country;
- elseif ($country == 'hongkong')
+ elseif ($country == 'hongkong')
$alt_flags ['zt'] = $country;
- elseif ($country == 'austria')
+ elseif ($country == 'austria')
$alt_flags ['de'] = $country;
}
@@ -2170,7 +2193,15 @@
$ajaxEndpoint = esc_url_raw(rest_url('gptranslate/v1/request'));
+ // Language URL rewriting: URLs of the page in each language (the ones of the hreflang tags, translated aliases included),
+ // used as real links by the language switcher
+ $gptLanguageUrls = array();
+ if (!empty($settings['rewrite_language_url']) && !defined('POLYLANG_VERSION') && function_exists('gpt_get_alternate_language_urls')) {
+ $gptLanguageUrls = (array) gpt_get_alternate_language_urls($settings, (array) (isset($settings['languages']) ? $settings['languages'] : array()));
+ }
+
$inlineScript = 'var gptServerSideLink = "' . esc_js($ajaxEndpoint) . '";';
+ $inlineScript .= 'var gptLanguageUrls = ' . wp_json_encode((object) $gptLanguageUrls, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';';
if (!empty($settings['lightweight_ajax_endpoint'])) {
$lightweightEndpoint = esc_url_raw(plugin_dir_url(__FILE__) . 'ajax-handler.php');
$inlineScript .= '
@@ -2180,6 +2211,7 @@
var gptRestSecret = "' . esc_js(gptranslate_get_api_secret()) . '";
var gptAjaxSecret = "' . esc_js(gptranslate_get_api_secret()) . '";
var gptRestNonce = "' . esc_js(wp_create_nonce('wp_rest')) . '";
+ var gptPageCacheCompat = ' . (int)($settings['page_cache_compat'] ?? 0) . ';
var gptLiveSite = "' . esc_js(get_site_url()) . '";
var gptStorage = ' . ($settings['storage_type'] === 'session' ? 'window.sessionStorage' : 'window.localStorage') . ';
var gptMaxTranslationsPerRequest = ' . (int)$settings['max_translations_per_request'] . ';
@@ -2232,7 +2264,8 @@
var chatgptCssSelectorLeafnodesExcluded = "' . esc_js(trim(preg_replace('/,+/', ',', str_ireplace(["r", "n"], ",", $settings['css_selector_leafnodes_excluded'])), ',')) . '";
var chatgptWordsLeafnodesExcluded = "' . esc_js(trim(preg_replace('/,+/', ',', str_ireplace(["r", "n"], ",", $settings['words_leafnodes_excluded'])), ', ')) . '";
var chatgptWordsMinLength = "' . (int)$settings['words_min_length'] . '";
- var chatgptFlattenInnerFormattingTags = ' . (int)($settings['flatten_inner_formatting_tags'] ?? 0) . ';
+ var chatgptFlattenInnerFormattingTags = ' . ((int)($settings['flatten_inner_formatting_tags'] ?? 0) === 1 ? 1 : 0) . ';
+ var gptInlinePlaceholdersEnabled = ' . (gpt_inline_placeholders_mode($settings) ? 1 : 0) . ';
var chatgptFlattenInnerFormattingTagsToRemove = "' . esc_js(str_ireplace('"', '', trim(trim(preg_replace('/,+/', ',', str_ireplace(["r", "n"], ",", ($settings['flatten_inner_formatting_tags_to_remove'] ?? 'strong,em,u,b,i'))), ',')))) . '";
var chatgptWrapExcludedWords = ' . (int)$settings['wrap_excluded_words'] . ';
var gptApplyDictionaryToAliases = ' . (int)($settings['apply_dictionary_to_aliases'] ?? 0) . ';
@@ -2295,6 +2328,14 @@
"enable_modal": ' . (int)($settings['enable_modal'] ?? 0) . ',
"equal_widths": ' . (int)$settings['equal_widths'] . ',
"reader_button_position": "' . $settings['reader_button_position'] . '",
+ "float_position": "' . esc_js($settings['float_position']) . '",
+ "reader_widget_position": "' . esc_js($settings['reader_widget_position'] ?? 'same') . '",
+ "reader_show_label": ' . (int)($settings['reader_show_label'] ?? 1) . ',
+ "reader_labels": ' . wp_json_encode(array('listen' => $this->loadTranslations('PLG_GPTRANSLATE_READER_LISTEN'), 'stop' => $this->loadTranslations('PLG_GPTRANSLATE_READER_STOP'))) . ',
+ "widget_background_color": "' . esc_js($settings['widget_background_color']) . '",
+ "popup_border_radius": ' . (int)$settings['popup_border_radius'] . ',
+ "popup_fontsize": ' . (int)$settings['popup_fontsize'] . ',
+ "popup_iconsize": ' . (int)$settings['popup_iconsize'] . ',
"custom_css": "' . addslashes(preg_replace('/s+/', ' ', str_replace(["r", "n"], ' ', (string) $settings['custom_css']))) . '",
"alt_flags": ' . json_encode($alt_flags). ',
"realtime_translations_retrigger_events": ' . json_encode($settings['realtime_translations_retrigger_events']) . ',
@@ -2712,12 +2753,12 @@
var gptranslateSitemapUrl = "' . esc_js(rest_url('gptranslate/v1/sitemap.xml')) . '";
var gptranslateDefaultLanguage = "' . esc_js($settings['language'] ?? 'en') . '";
var gptranslateCrawlerTimeout = "' . (isset($settings['crawler_timeout']) ? (int)$settings['crawler_timeout'] : '60') . '";
- var gptranslateCrawlerExclusions = "' . esc_js(trim(preg_replace('/,+/', ',', str_ireplace(["r", "n"], ",", ($settings['crawler_exclusions'] ?? ''))), ',')) . '";
+ var gptranslateCrawlerExclusions = "' . esc_js(gpt_crawler_exclusions_list($settings)) . '";
var gptranslateCrawlerSkipTranslated = ' . (int)($settings['crawler_skip_translated'] ?? 0) . ';
var gptSubfolderInstallation = ' . (int)($settings['subfolder_installation'] ?? 0) . ';
var gptranslateRewriteLanguageUrl = ' . (int)($settings['rewrite_language_url'] ?? 0) . ';
var gptranslateOmitPrefixOriginalLanguage = ' . (isset($settings['omit_prefix_original_language']) ? (int)$settings['omit_prefix_original_language'] : 0) . ';
- var gptVersionNumeric = 1;
+ var gptVersionNumeric = 0;
var gptranslateSitemapAvailableLanguages = ' . wp_json_encode(gptranslate_get_available_languages()) . ';
', 'before');
@@ -3598,6 +3639,88 @@
}
add_action( 'admin_post_gptranslate_import_settings', 'gptranslate_import_settings' );
+/**
+ * The exclusion patterns of the crawler: "Crawler exclusions" plus the pages that are never translated: the "Exclude links from rewriting"
+ * patterns (when the language URL rewriting is on) and the "Page exclusions" patterns. The "home" and "/" entries of "Page exclusions" are
+ * left out: the crawler matches a substring of the URL, so they would exclude every page
+ *
+ * @param array $settings Options of the plugin
+ * @return string Patterns separated by commas
+ */
+function gpt_crawler_exclusions_list( $settings ) {
+ $raw = (string) ( $settings['crawler_exclusions'] ?? '' );
+ if ( ! empty( $settings['rewrite_language_url'] ) ) {
+ $raw .= "n" . (string) ( $settings['rewrite_page_links_exclusions'] ?? '' );
+ }
+ foreach ( preg_split( '/[rn,]+/', (string) ( $settings['page_exclusions'] ?? '' ) ) as $pattern ) {
+ $pattern = trim( $pattern );
+ if ( $pattern !== '' && $pattern !== '/' && strtolower( $pattern ) !== 'home' ) {
+ $raw .= "n" . $pattern;
+ }
+ }
+ return trim( preg_replace( '/,+/', ',', str_ireplace( array( "r", "n" ), ',', $raw ) ), ',' );
+}
+
+/**
+ * Links to the page in the other languages (the URLs of the hreflang tags), printed hidden inside the wrapper of the language
+ * switcher so that they can be followed without running the script. The script removes them when it builds the switcher.
+ * The data-gpt-ssr-link attribute keeps them out of the rewriting of the links of the page
+ *
+ * @return string
+ */
+function gpt_language_links_html() {
+ $settings = get_option( 'gptranslate_options', array() );
+ if ( empty( $settings['rewrite_language_url'] ) || defined( 'POLYLANG_VERSION' ) || ! function_exists( 'gpt_get_alternate_language_urls' ) ) {
+ return '';
+ }
+ // Pages excluded from translation ("Exclude links from rewriting" patterns) have no other language
+ if ( ! empty( $GLOBALS['gptranslate_page_excluded'] ) ) {
+ return '';
+ }
+ $urls = gpt_get_alternate_language_urls( $settings, (array) ( isset( $settings['languages'] ) ? $settings['languages'] : array() ) );
+ if ( empty( $urls ) ) {
+ return '';
+ }
+
+ static $names = null;
+ if ( $names === null ) {
+ $names = array();
+ $language_file = plugin_dir_path( __FILE__ ) . 'language/en-GB/gptranslate.ini';
+ if ( file_exists( $language_file ) ) {
+ $parsed = parse_ini_file( $language_file, false, INI_SCANNER_NORMAL );
+ $names = is_array( $parsed ) ? $parsed : array();
+ }
+ }
+
+ $items = '';
+ foreach ( $urls as $lang => $url ) {
+ $lang = (string) $lang;
+ // A URL with the language code before index.php (site without URL rewriting) is not a valid URL of the page
+ if ( preg_match( '#/([a-z]{2,3}(?:-[a-z0-9]{2,8})?)/index.php(?:/|$)#i', (string) wp_parse_url( $url, PHP_URL_PATH ), $match ) && isset( $urls[ strtolower( $match[1] ) ] ) ) {
+ continue;
+ }
+ $name_key = 'PLG_GPTRANSLATE_LANGUAGE_NAME_' . strtoupper( str_replace( '-', '_', $lang ) );
+ $name = isset( $names[ $name_key ] ) ? $names[ $name_key ] : strtoupper( $lang );
+ // zt (Traditional Chinese) is zh-Hant for the hreflang attribute, as in the hreflang tags
+ $hreflang = ( $lang === 'zt' ) ? 'zh-Hant' : $lang;
+ $items .= '<a data-gpt-ssr-link="1" href="' . esc_url( $url ) . '" hreflang="' . esc_attr( $hreflang ) . '" lang="' . esc_attr( $hreflang ) . '">' . esc_html( $name ) . '</a>';
+ }
+ if ( $items === '' ) {
+ return '';
+ }
+
+ $title = isset( $names['PLG_GPTRANSLATE_CHOOSE_LANGUAGE'] ) ? $names['PLG_GPTRANSLATE_CHOOSE_LANGUAGE'] : 'Choose your language';
+ $html = '<nav class="gpt-ssr-links notranslate" aria-label="' . esc_attr( $title ) . '" style="display:none">' . $items . '</nav>';
+
+ return wp_kses(
+ $html,
+ array(
+ 'nav' => array( 'class' => true, 'aria-label' => true, 'style' => true ),
+ 'a' => array( 'href' => true, 'hreflang' => true, 'lang' => true, 'data-gpt-ssr-link' => true ),
+ )
+ );
+}
+
// ============================================================================
// Shortcode [gptranslate] - Renders the language switcher at the shortcode position
// ============================================================================
@@ -3622,7 +3745,7 @@
define('GPTRANSLATE_SHORTCODE_RENDERED', true);
}
- return '<div class="' . esc_attr($wrapper_class) . '"></div>';
+ return '<div class="' . esc_attr($wrapper_class) . '">' . gpt_language_links_html() . '</div>';
});
add_action('wp_footer', function () {
@@ -3640,10 +3763,24 @@
}
if ($settings ['wrapper_selector'] == '.gptranslate_wrapper') {
- echo '<div class="gptranslate_wrapper" id="gpt-wrapper"></div>';
+ // The links to the other languages are already escaped and filtered in gpt_language_links_html()
+ echo '<div class="gptranslate_wrapper" id="gpt-wrapper">' . gpt_language_links_html() . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
});
+// Labels of the separate reader widget (Listen / Stop) as text of the page, out of the screen: the texts of the page are translated by
+// GPTranslate (server side with the stored translations, client side at the first translation), so the labels follow the language of the
+// page also when the plugin has no language file for it. The script reads them and prefers the language file when it has a translation
+add_action('wp_footer', function () {
+ $settings = get_option('gptranslate_options');
+ if (empty($settings['enable_reader']) || empty($settings['reader_widget_position']) || $settings['reader_widget_position'] === 'same' || !empty($settings['disable_control'])) {
+ return;
+ }
+ $style = 'position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden';
+ echo '<span class="gpt-reader-label-source" data-gpt-label="listen" style="' . esc_attr($style) . '">Listen</span>';
+ echo '<span class="gpt-reader-label-source" data-gpt-label="stop" style="' . esc_attr($style) . '">Stop</span>';
+}, 20);
+
// Get available (enabled) languages for sitemap filtering (excluding original language)
function gptranslate_get_available_languages() {
$opts = get_option('gptranslate_options', array());
@@ -3900,6 +4037,47 @@
}
/**
+ * LiteSpeed Cache: purge the URL of a page in a language at its original path (the page link, e.g. /fr/page/) when its translated alias
+ * (e.g. /fr/translated-page/) is stored, so that the page is not served from the cache anymore and the next request is redirected to the
+ * translated alias. Only with the translation of the aliases enabled and on a LiteSpeed server: the X-LiteSpeed-Purge response header is
+ * processed by the server; the action of the LiteSpeed Cache plugin is also called when it is active
+ *
+ * @param string $pageLink
+ * @param string $translatedAlias
+ * @param array $opts Options of the plugin
+ * @return void
+ */
+function gpt_purge_litespeed_original_url( $pageLink, $translatedAlias, $opts ) {
+ if ( empty( $opts['rewrite_language_url'] ) || empty( $opts['rewrite_language_alias'] ) || (string) $translatedAlias === '' || (string) $pageLink === '' ) {
+ return;
+ }
+ $serverSoftware = isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '';
+ if ( stripos( $serverSoftware, 'litespeed' ) === false && empty( $_SERVER['X-LSCACHE'] ) && empty( $_SERVER['HTTP_X_LSCACHE'] ) ) {
+ return;
+ }
+ $pagePath = (string) wp_parse_url( urldecode( $pageLink ), PHP_URL_PATH );
+ $aliasPath = (string) wp_parse_url( urldecode( $translatedAlias ), PHP_URL_PATH );
+ if ( $pagePath === '' || rtrim( $pagePath, '/' ) === rtrim( $aliasPath, '/' ) ) {
+ return;
+ }
+ $paths = array();
+ foreach ( array( rtrim( $pagePath, '/' ), rtrim( $pagePath, '/' ) . '/' ) as $path ) {
+ // Encoded as the requested URLs (e.g. accented characters), without commas (the header separator)
+ $path = str_replace( array( '%2F', ',' ), array( '/', '%2C' ), rawurlencode( $path ) );
+ if ( $path !== '' && $path !== '/' ) {
+ $paths[] = $path;
+ }
+ }
+ if ( $paths && ! headers_sent() ) {
+ header( 'X-LiteSpeed-Purge: ' . implode( ', ', array_unique( $paths ) ), false );
+ }
+ if ( has_action( 'litespeed_purge_url' ) ) {
+ do_action( 'litespeed_purge_url', rtrim( $pageLink, '/' ) );
+ do_action( 'litespeed_purge_url', rtrim( $pageLink, '/' ) . '/' );
+ }
+}
+
+/**
* Permission callback public API
* @param WP_REST_Request $request
* @return bool|WP_Error
@@ -3936,6 +4114,444 @@
}
/**
+ * Whether a text is blank: only whitespace, including , non-breaking and zero-width spaces.
+ * A blank translation key would match everywhere in the page (an empty pattern matches at every position),
+ * so it is never stored nor used.
+ *
+ * @param string $text
+ * @return bool
+ */
+if ( ! function_exists( 'gpt_is_blank_translation_text' ) ) {
+ function gpt_is_blank_translation_text( $text ) {
+ return preg_match( '/^(?:[sx{00A0}x{1680}x{2000}-x{200D}x{2028}x{2029}x{202F}x{205F}x{2060}x{3000}x{FEFF}]| | | )*$/iu', (string) $text ) === 1;
+ }
+}
+
+/**
+ * Remove from a list of translations (original text => translated text) the entries with a blank key
+ *
+ * @param array $translations
+ * @return array
+ */
+if ( ! function_exists( 'gpt_remove_blank_translation_keys' ) ) {
+ function gpt_remove_blank_translation_keys( $translations ) {
+ if ( ! is_array( $translations ) ) {
+ return $translations;
+ }
+ foreach ( $translations as $key => $value ) {
+ if ( gpt_is_blank_translation_text( (string) $key ) ) {
+ unset( $translations[ $key ] );
+ }
+ }
+ return $translations;
+ }
+}
+
+/**
+ * Whether the "Remove inner formatting tags" option uses the "placeholders" mode (value 2): the inline formatting tags are kept and represented by
+ * numbered markers ([[1]]...[[/1]]) in the translation keys. Only with the regex method of the server side translations (or without it).
+ *
+ * @param array $settings
+ *
+ * @return boolean
+ */
+if ( ! function_exists( 'gpt_inline_placeholders_mode' ) ) {
+ function gpt_inline_placeholders_mode( $settings ) {
+ if ( ! is_array( $settings ) || (int) ( isset( $settings['flatten_inner_formatting_tags'] ) ? $settings['flatten_inner_formatting_tags'] : 0 ) !== 2 ) {
+ return false;
+ }
+ return empty( $settings['serverside_translations'] ) || ( isset( $settings['serverside_translations_method'] ) ? $settings['serverside_translations_method'] : 'regex' ) === 'regex';
+ }
+}
+
+if ( ! function_exists( 'gpt_inline_lower' ) ) {
+ function gpt_inline_lower( $text ) {
+ return function_exists( 'mb_strtolower' ) ? mb_strtolower( (string) $text, 'UTF-8' ) : strtolower( (string) $text );
+ }
+}
+
+/**
+ * Whether the markers of a translation are valid for its original text: every marker of the original appears exactly once in the
+ * translation, opened and closed, never nested, and no other marker is present. A translation that is not valid is never applied or
+ * stored: applying it would drop a link or a formatting tag of the page.
+ *
+ * @param string $original
+ * @param mixed $value
+ *
+ * @return boolean
+ */
+if ( ! function_exists( 'gpt_inline_markers_valid' ) ) {
+ function gpt_inline_markers_valid($original, $value) {
+ if (!is_string($original) || !is_string($value)) {
+ return true;
+ }
+ $expected = array();
+ if (preg_match_all('~[[(d+)]]~', $original, $found)) {
+ $expected = array_map('intval', $found[1]);
+ }
+ sort($expected);
+ $opened = array();
+ $stripped = preg_replace_callback('~[[(d+)]]((?:(?![[/?d+]]).)*)[[/1]]~su', function ($matches) use (&$opened) {
+ $opened[] = (int) $matches[1];
+ return $matches[2];
+ }, $value);
+ if ($stripped === null || preg_match('~[[/?d+]]~', $stripped)) {
+ return false;
+ }
+ sort($opened);
+
+ return $opened === $expected;
+ }
+}
+
+/**
+ * Translations of the placeholders mode, before they are stored: the entries with markers that are not valid are removed and the
+ * edges of the others are repaired. A list without markers is returned as it is.
+ *
+ * @param string $rawJson
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_prepare_translations_json' ) ) {
+ function gpt_inline_prepare_translations_json($rawJson) {
+ if (!is_string($rawJson) || strpos($rawJson, '[[') === false) {
+ return $rawJson;
+ }
+ $translations = json_decode($rawJson, true);
+ if (!is_array($translations)) {
+ return $rawJson;
+ }
+ foreach ($translations as $original => $translation) {
+ if (strpos((string) $original, '[[') === false && (!is_string($translation) || strpos($translation, '[[') === false)) {
+ continue;
+ }
+ if (!gpt_inline_markers_valid((string) $original, $translation)) {
+ unset($translations[$original]);
+ }
+ }
+ $translations = gpt_fix_translations_edges($translations);
+
+ return json_encode($translations, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+ }
+}
+
+/**
+ * Placeholders mode: convert the markers of a translated text segment back to the tokens of the tags, see localizeInlineTokens().
+ * The markers have already been checked with areInlineMarkersValid(), so every marker has its token.
+ *
+ * @param string $text
+ * @param array $localMap Marker number => token number
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_globalize_markers' ) ) {
+ function gpt_inline_globalize_markers($text, array $localMap) {
+ if (!$localMap) {
+ return $text;
+ }
+ $result = preg_replace_callback('~[[(/?)(d+)]]~', function ($matches) use ($localMap) {
+ $number = (int) $matches[2];
+ if (!isset($localMap[$number])) {
+ return '';
+ }
+ return ($matches[1] === '/' ? "xEEx80x82" : "xEEx80x80") . $localMap[$number] . "xEEx80x81";
+ }, $text);
+
+ return $result === null ? $text : $result;
+ }
+}
+
+/**
+ * Repair what the translation engines often drop at the edges of a translation, comparing it with its original
+ * text (same rules of gptInlinePlaceholders.fixEdges() on the client side):
+ * - the space at the start or at the end INSIDE a marker ("like[[1]] Farewell" => "come[[1]] Addio");
+ * - the punctuation right after a closing marker ("[[/1]]. It" => "[[/1]]. È"), when the marker is followed
+ * directly by a word, or by a space and a capital letter after a period, ! or ?;
+ * - the punctuation at the start of a text followed by a space (". It's" => ". È"), when the translation starts
+ * with a letter or a digit;
+ * - the punctuation at the end of a text ("Read more:"), when the translation ends with a letter or a digit.
+ *
+ * @param string $original
+ * @param mixed $value
+ *
+ * @return mixed
+ */
+if ( ! function_exists( 'gpt_fix_translation_edges' ) ) {
+ function gpt_fix_translation_edges($original, $value) {
+ if (!is_string($original) || !is_string($value) || $value === '' || $original === $value || strpos($original, '[[') === false) {
+ return $value;
+ }
+ if (preg_match_all('~[[(d+)]](.*?)[[/1]]~su', $original, $markers, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
+ foreach ($markers as $marker) {
+ $open = '[[' . $marker[1][0] . ']]';
+ $close = '[[/' . $marker[1][0] . ']]';
+ $inner = $marker[2][0];
+ $afterMarker = substr($original, $marker[0][1] + strlen($marker[0][0]));
+ if (preg_match('~^s~u', $inner) && ($at = strpos($value, $open)) !== false) {
+ $after = substr($value, $at + strlen($open), 1);
+ $before = $at > 0 ? substr($value, $at - 1, 1) : '';
+ if ($after !== '' && !ctype_space($after) && $before !== '' && !ctype_space($before)) {
+ $value = substr($value, 0, $at + strlen($open)) . ' ' . substr($value, $at + strlen($open));
+ }
+ }
+ if (preg_match('~^([.,;:!?x{2026}]+)(s+)~u', $afterMarker, $punctuation) && ($at = strpos($value, $close)) !== false) {
+ $rest = substr($value, $at + strlen($close));
+ if (preg_match('~^[p{L}p{N}]~u', $rest) || (preg_match('~[.!?x{2026}]~u', $punctuation[1]) && preg_match('~^s+p{Lu}~u', $rest))) {
+ $value = substr($value, 0, $at + strlen($close)) . $punctuation[1] . ' ' . ltrim($rest);
+ }
+ }
+ if (preg_match('~s$~u', $inner) && ($at = strpos($value, $close)) !== false) {
+ $prev = $at > 0 ? substr($value, $at - 1, 1) : '';
+ $next = substr($value, $at + strlen($close), 1);
+ if ($prev !== '' && !ctype_space($prev) && $next !== '' && !ctype_space($next)) {
+ $value = substr($value, 0, $at) . ' ' . substr($value, $at);
+ }
+ }
+ }
+ }
+ $plainOriginal = preg_replace('~[[/?d+]]~', '', $original);
+ $plainValue = preg_replace('~[[/?d+]]~', '', $value);
+ if (preg_match('~^(s*)([.,;:!?x{2026})]}x{00bb}]+)(s+)~u', $plainOriginal, $lead) && preg_match('~^s*[p{L}p{N}]~u', $plainValue)) {
+ preg_match('~^s*~u', $value, $ws);
+ $value = $ws[0] . $lead[2] . ' ' . substr($value, strlen($ws[0]));
+ }
+ if (preg_match('~([^s.,;:!?x{2026}([{x{00ab}])([.,;:!?x{2026}]+|s[([{x{00ab}]+)(s*)$~u', $plainOriginal, $trail) && preg_match('~[p{L}p{N}]s*$~u', $plainValue)) {
+ preg_match('~s*$~u', $value, $tws);
+ $value = substr($value, 0, strlen($value) - strlen($tws[0])) . $trail[2] . $tws[0];
+ }
+
+ return $value;
+ }
+}
+
+/**
+ * fixTranslationEdges() on every translation of a list (original text => translation)
+ *
+ * @param mixed $translations
+ *
+ * @return mixed
+ */
+if ( ! function_exists( 'gpt_fix_translations_edges' ) ) {
+ function gpt_fix_translations_edges($translations) {
+ if (!is_array($translations)) {
+ return $translations;
+ }
+ foreach ($translations as $original => $translation) {
+ $translations[$original] = gpt_fix_translation_edges((string) $original, $translation);
+ }
+
+ return $translations;
+ }
+}
+
+/**
+ * Placeholders mode: replace the inline formatting elements of the HTML with tokens that are plain text,
+ * so that the sentence becomes a single text segment, storing the original tags to restore them later.
+ * Same rules of the client side: a tag of the list, containing only text (no nested tags), not empty,
+ * without the nogptranslate class. Single pass, so an element containing a tokenized one is not tokenized.
+ * Tokens: U+E000 n U+E001 (opening tag n) and U+E002 n U+E001 (closing tag n), UTF-8 private use characters.
+ *
+ * @param string $html
+ * @param array $tags
+ * @param array $store Original tags, by token number
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_tokenize_tags' ) ) {
+ function gpt_inline_tokenize_tags($html, array $tags, array &$store) {
+ $tags = array_values(array_filter(array_map(function ($tag) {
+ return strtolower(trim($tag));
+ }, $tags), 'strlen'));
+ if (!$tags) {
+ return $html;
+ }
+
+ $alternation = implode('|', array_map(function ($tag) {
+ return preg_quote($tag, '~');
+ }, $tags));
+ // A tag containing only text, or containing only another tag of the list containing only text (e.g.
+ // <a href="..."><strong>text</strong></a>): the marker wraps both, only the text is translated
+ $result = preg_replace_callback('~<(' . $alternation . ')(s[^>]*)?>(?:<(' . $alternation . ')(s[^>]*)?>([^<]*)</3s*>|([^<]*))</1s*>~i', function ($matches) use (&$store) {
+ $nested = isset($matches[3]) && $matches[3] !== '';
+ $text = $nested ? $matches[5] : (isset($matches[6]) ? $matches[6] : '');
+ // Empty elements (e.g. icon fonts <i class="fa ..."></i>) are kept as they are
+ if (trim(str_replace([' ', "xc2xa0"], '', $text)) === '') {
+ return $matches[0];
+ }
+ foreach (array(2, 4) as $attributesGroup) {
+ if (!empty($matches[$attributesGroup]) && preg_match('~bclasss*=s*(["'])[^"']*bnogptranslateb~i', $matches[$attributesGroup])) {
+ return $matches[0];
+ }
+ }
+ $number = count($store);
+ $store[$number] = [
+ 'open' => '<' . $matches[1] . (isset($matches[2]) ? $matches[2] : '') . '>' . ($nested ? '<' . $matches[3] . $matches[4] . '>' : ''),
+ 'close' => ($nested ? '</' . $matches[3] . '>' : '') . '</' . $matches[1] . '>'
+ ];
+ return "xEEx80x80" . $number . "xEEx80x81" . $text . "xEEx80x82" . $number . "xEEx80x81";
+ }, $html);
+
+ return $result === null ? $html : $result;
+ }
+}
+
+/**
+ * Placeholders mode: convert the tokens of a text segment to the markers numbered from 1 in the segment,
+ * as the client side builds the translation keys: "Read the [[1]]full guide[[/1]] first"
+ *
+ * @param string $text
+ * @param array $localMap Marker number => token number
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_localize_tokens' ) ) {
+ function gpt_inline_localize_tokens($text, array &$localMap) {
+ $localMap = [];
+ if (strpos($text, "xEEx80") === false) {
+ return $text;
+ }
+
+ $result = preg_replace_callback('~xEEx80x80(d+)xEEx80x81|xEEx80x82(d+)xEEx80x81~', function ($matches) use (&$localMap) {
+ if (isset($matches[2]) && $matches[2] !== '') {
+ $number = array_search((int) $matches[2], $localMap, true);
+ return '[[/' . ($number === false ? 0 : $number) . ']]';
+ }
+ $number = count($localMap) + 1;
+ $localMap[$number] = (int) $matches[1];
+ return '[[' . $number . ']]';
+ }, $text);
+
+ return $result === null ? $text : $result;
+ }
+}
+
+/**
+ * Placeholders mode: restore the original tags in place of the tokens
+ *
+ * @param string $html
+ * @param array $store Original tags, by token number
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_restore_tokens' ) ) {
+ function gpt_inline_restore_tokens($html, array $store) {
+ if (!$store) {
+ return $html;
+ }
+
+ $result = preg_replace_callback('~xEEx80x80(d+)xEEx80x81|xEEx80x82(d+)xEEx80x81~', function ($matches) use ($store) {
+ if (isset($matches[2]) && $matches[2] !== '') {
+ return isset($store[(int) $matches[2]]) ? $store[(int) $matches[2]]['close'] : '';
+ }
+ return isset($store[(int) $matches[1]]) ? $store[(int) $matches[1]]['open'] : '';
+ }, $html);
+
+ return $result === null ? $html : $result;
+ }
+}
+
+/**
+ * Placeholders mode: normalized form of a text with markers, to find its translation as a whole
+ * (same normalization of the client side keys: collapsed whitespace, trimmed)
+ *
+ * @param string $text
+ * @param boolean $caseInsensitive
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_inline_normalize_key' ) ) {
+ function gpt_inline_normalize_key($text, $caseInsensitive, $matchQuotes = true) {
+ // The client side keys come from textContent: HTML entities decoded (’ – " '...)
+ $text = html_entity_decode((string) $text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
+ $text = trim(preg_replace('~(?:s|xC2xA0)+~', ' ', $text));
+ if ($matchQuotes) {
+ $text = str_replace('"', "'", $text);
+ }
+ return $caseInsensitive ? gpt_inline_lower($text) : $text;
+ }
+}
+
+/**
+ * URL to store as page link or as translated alias (rotta REST di salvataggio). The parameters that never identify a page (campaign, click and
+ * referral tracking, cache busting: same rules of gpt_is_ignored_query_param() of the server side translations, plus the names set in the
+ * "Ignored query string parameters" option) are removed, the other parameters are kept. A page link keeps the fragment unless the "Ignored URL
+ * fragments" option ignores it; a translated alias never has the fragment, and with "Ignore query string" it has no query string at all.
+ *
+ * @param string $url
+ * @param boolean $isAlias
+ *
+ * @return string
+ */
+if ( ! function_exists( 'gpt_clean_url_to_store' ) ) {
+ function gpt_clean_url_to_store( $url, $isAlias ) {
+ $url = (string) $url;
+ if ( $url === '' ) {
+ return $url;
+ }
+ $options = (array) get_option( 'gptranslate_options', array() );
+ $names = array( 'highlight', 'gclid', 'gbraid', 'wbraid', 'dclid', 'msclkid', 'fbclid', 'yclid', 'ttclid', 'twclid', 'igshid',
+ 'li_fat_id', 'mc_cid', 'mc_eid', '_ga', '_gl', '_hsenc', '_hsmi', 'srsltid', 'gad_source', 'gad_campaignid' );
+ $prefixes = array( 'utm_', 'fb_', 'x-wblr-', '__cf_chl_' );
+ foreach ( explode( ',', strtolower( (string) ( isset( $options['ignored_query_params'] ) ? $options['ignored_query_params'] : '' ) ) ) as $configured ) {
+ $configured = trim( $configured );
+ if ( $configured === '' ) {
+ continue;
+ }
+ if ( substr( $configured, -1 ) === '*' ) {
+ if ( strlen( $configured ) > 1 ) {
+ $prefixes[] = substr( $configured, 0, -1 );
+ }
+ } else {
+ $names[] = $configured;
+ }
+ }
+ $fragment = '';
+ $hashPos = strpos( $url, '#' );
+ if ( $hashPos !== false ) {
+ $fragment = substr( $url, $hashPos );
+ $url = substr( $url, 0, $hashPos );
+ }
+ $queryPos = strpos( $url, '?' );
+ if ( $queryPos !== false ) {
+ $base = substr( $url, 0, $queryPos );
+ $kept = array();
+ foreach ( explode( '&', substr( $url, $queryPos + 1 ) ) as $pair ) {
+ $name = strtolower( preg_replace( '~[.*$~', '', urldecode( (string) strtok( $pair, '=' ) ) ) );
+ $ignored = in_array( $name, $names, true );
+ foreach ( $prefixes as $prefix ) {
+ if ( $ignored ) {
+ break;
+ }
+ $ignored = strpos( $name, $prefix ) === 0;
+ }
+ if ( $pair !== '' && ! $ignored ) {
+ $kept[] = $pair;
+ }
+ }
+ $url = $base . ( $kept ? '?' . implode( '&', $kept ) : '' );
+ }
+ if ( $isAlias ) {
+ if ( ! empty( $options['ignore_querystring'] ) && ( $queryPos = strpos( $url, '?' ) ) !== false ) {
+ $url = substr( $url, 0, $queryPos );
+ }
+ return $url;
+ }
+ if ( $fragment !== '' ) {
+ $ignoredFragments = array_filter( array_map( 'trim', explode( ',', strtolower( (string) ( isset( $options['ignored_url_fragments'] ) ? $options['ignored_url_fragments'] : '' ) ) ) ), 'strlen' );
+ $fragmentName = strtolower( urldecode( substr( $fragment, 1 ) ) );
+ foreach ( $ignoredFragments as $ignoredFragment ) {
+ if ( $ignoredFragment === '*' || $ignoredFragment === $fragmentName || ( substr( $ignoredFragment, -1 ) === '*' && strpos( $fragmentName, substr( $ignoredFragment, 0, -1 ) ) === 0 ) ) {
+ $fragment = '';
+ break;
+ }
+ }
+ }
+
+ return $url . $fragment;
+ }
+}
+
+/**
* Normalize WP URL
* @param string $url
* @return string
@@ -4096,6 +4712,9 @@
$task = sanitize_text_field( $params['task'] ?? '' );
$pageLink = esc_url_raw( $params['pagelink'] ?? '' );
$translatedAlias = esc_url_raw( $params['translated_alias'] ?? '' );
+ // Parameters that never identify a page (tracking...) and the fragment are not part of the stored URLs
+ $pageLink = gpt_clean_url_to_store( $pageLink, false );
+ $translatedAlias = gpt_clean_url_to_store( $translatedAlias, true );
$languageOriginal = sanitize_text_field( $params['language_original'] ?? '' );
$languageTranslated = sanitize_text_field( $params['language_translated'] ?? '' );
$translationEngine = sanitize_text_field( $params['translation_engine'] ?? '' );
@@ -4132,15 +4751,20 @@
}
// Strip HTML tags from translation values before storing to prevent stored XSS
+ // Entries with a blank key (only whitespace, nbsp, zero-width) are dropped: they would match everywhere in the page
$_decodedFull = json_decode( $fullTranslations, true );
if ( is_array( $_decodedFull ) ) {
- $fullTranslations = wp_json_encode( array_map( 'wp_strip_all_tags', $_decodedFull ) );
+ $fullTranslations = wp_json_encode( array_map( 'wp_strip_all_tags', gpt_remove_blank_translation_keys( $_decodedFull ) ) );
}
$_decodedAlt = json_decode( $altTranslations, true );
if ( is_array( $_decodedAlt ) ) {
- $altTranslations = wp_json_encode( array_map( 'wp_strip_all_tags', $_decodedAlt ) );
+ $altTranslations = wp_json_encode( array_map( 'wp_strip_all_tags', gpt_remove_blank_translation_keys( $_decodedAlt ) ) );
}
unset( $_decodedFull, $_decodedAlt );
+ // Placeholders mode: translations with invalid markers are never stored, the edges of the others are repaired
+ if ( gpt_inline_placeholders_mode( (array) get_option( 'gptranslate_options', array() ) ) ) {
+ $fullTranslations = gpt_inline_prepare_translations_json( $fullTranslations );
+ }
// If the translation service failed, timed out or was rate-limited, the client can end up
// calling storetranslations with an effectively empty payload. Saving that as a real record
@@ -4260,10 +4884,22 @@
[ '%s','%s','%s','%s','%s','%s','%d','%s','%s' ]
);
$response['result'] = ( $inserted !== false );
+
+ // New translation with a translated alias: the page in this language at its original URL (e.g. /fr/page/) may be stored by
+ // LiteSpeed Cache from before, so that it keeps being served instead of redirecting to the translated alias: purge it
+ if ( $inserted !== false && $retriggerTranslation !== 1 ) {
+ gpt_purge_litespeed_original_url( $pageLink, $translatedAlias, $opts );
+ }
}
} else {
$response['result'] = true;
}
+ } elseif ($task === 'gettoken') {
+ // Fresh nonce for storetranslations: the one printed in the page is wrong when the page is served by a page cache (LiteSpeed...)
+ // for longer than the life of the nonce. Used with the "Page cache compatibility" option, never cached
+ $response['result'] = true;
+ $response['token'] = wp_create_nonce( 'wp_rest' );
+ nocache_headers();
} elseif ($task === 'gettranslations') {
$opts = get_option('gptranslate_options', []);
if (!empty($opts['realtime_translations']) || $retriggerTranslation === 1) {
--- a/gptranslate/multilang-routing.php
+++ b/gptranslate/multilang-routing.php
@@ -197,7 +197,20 @@
$rawUri = rtrim(home_url() . $requestUri, '/');
$rawUriWithSlash = $rawUri . '/';
- $uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
+ // The same URL without its query string: a translated alias is matched with its query string first (a variant of a page with its own
+ // translation), then by its path only, so that the parameters of a visit (tracking, filters) do not turn the alias into a 404
+ $requestQueryString = '';
+ $requestPath = $requestUri;
+ if (($requestQueryPos = strpos($requestUri, '?')) !== false) {
+ $requestQueryString = substr($requestUri, $requestQueryPos + 1);
+ $requestPath = substr($requestUri, 0, $requestQueryPos);
+ }
+ $rawUriPath = rtrim(home_url() . $requestPath, '/');
+ $rawUriPathWithSlash = $rawUriPath . '/';
+ // The query string as the browser sent it (encoded), for the redirect and for the rewritten request
+ $requestQueryRaw = isset($_SERVER['REQUEST_URI']) ? (string) wp_parse_url(wp_unslash($_SERVER['REQUEST_URI']), PHP_URL_QUERY) : '';
+
+ $uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
// Only languages actually enabled on this site are recognized as a routable prefix -
// see $gpt_routable_languages definition above.
$pattern = '#^/(' . implode ( '|', array_map ( 'preg_quote', $gpt_routable_languages ) ) . ')(/.*)?$#i';
@@ -231,6 +244,21 @@
$originalPageLink = $wpdb->get_var($query);
+ // Not found with the query string: the alias with the query string without the parameters that never identify a page (tracking...), then
+ // by its path only
+ if (! $originalPageLink && $requestQueryString !== '') {
+ $rawUriCleaned = function_exists('gpt_clean_url_to_store') ? rtrim(gpt_clean_url_to_store($rawUri, true), '/') : $rawUriPath;
+ foreach (array_unique(array($rawUriCleaned, $rawUriPath)) as $aliasCandidate) {
+ $originalPageLink = $wpdb->get_var($wpdb->prepare(
+ "SELECT pagelink FROM $table WHERE published = 1 AND languagetranslated = %s AND (
+ translated_alias = %s OR translated_alias = %s)",
+ $currentLang, $aliasCandidate, $aliasCandidate . '/' ));
+ if ($originalPageLink) {
+ break;
+ }
+ }
+ }
+
if (! $originalPageLink) {
// The request didn't match a translated alias, so it may be the original-language
// slug accessed directly under a translated language prefix (e.g. /hu/original-slug
@@ -243,8 +271,21 @@
$currentLang, $rawUri, $rawUriWithSlash );
$translatedAlias = $wpdb->get_var($redirectQuery);
+ $redirectKeepsQuery = false;
+
+ // The original slug requested with parameters: its translated alias by the path only, with the same parameters
+ if (! $translatedAlias && $requestQueryString !== '') {
+ $translatedAlias = $wpdb->get_var($wpdb->prepare(
+ "SELECT translated_alias FROM $table WHERE published = 1 AND languagetranslated = %s AND (
+ pagelink = %s OR pagelink = %s) AND translated_alias IS NOT NULL AND translated_alias != ''",
+ $currentLang, $rawUriPath, $rawUriPathWithSlash ));
+ $redirectKeepsQuery = true;
+ }
if ($translatedAlias) {
+ if ($redirectKeepsQuery) {
+ $translatedAlias .= (strpos($translatedAlias, '?') === false ? '?' : '&') . $requestQueryRaw;
+ }
wp_safe_redirect($translatedAlias, 301);
exit;
}
@@ -272,7 +313,7 @@
}
// Rewrite the request
- $_SERVER['REQUEST_URI'] = $originalPath;
+ $_SERVER['REQUEST_URI'] = $originalPath . ($requestQueryRaw !== '' ? '?' . $requestQueryRaw : '');
}, 1);
/**
@@ -319,7 +360,39 @@
}
}
}, 2);
-
+
+ /**
+ * Pages excluded from translation by the "Exclude links from rewriting" patterns are only served in the original language: no server
+ * side or client side translation, no hreflang tags, and /fr/excluded-page/ is redirected to /excluded-page/. The path matched is the
+ * one without the language code (already stripped at priority 2), with the query string, as for the links. The home page is never excluded
+ */
+ add_action('init', function () use ($settings, $polylangActive) {
+ if (is_admin() || $polylangActive || empty($settings['rewrite_language_url'])) return;
+ $exclusions = trim((string) ($settings['rewrite_page_links_exclusions'] ?? ''));
+ if ($exclusions === '') return;
+
+ $uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
+ $homePath = rtrim((string) wp_parse_url(home_url(), PHP_URL_PATH), '/');
+ // The request path without the subfolder of the installation (the alias lookup may already have removed it)
+ $restUri = ($homePath !== '' && strpos($uri, $homePath . '/') === 0) ? substr($uri, strlen($homePath)) : $uri;
+ $parts = explode('?', $restUri, 2);
+ $restPath = '/' . ltrim($parts[0], '/');
+ if (trim($restPath, '/') === '' || $restPath === '/index.php') return;
+ $suffix = isset($parts[1]) && $parts[1] !== '' ? '?' . $parts[1] : '';
+
+ if (!gptranslate_should_exclude_link($restPath . $suffix, $exclusions) && !gptranslate_should_exclude_link(rtrim($restPath, '/') . '/' . $suffix, $exclusions)) return;
+
+ $GLOBALS['gptranslate_page_excluded'] = true;
+
+ // A language code other than the original one: back to the same page without it
+ $originalLang = strtolower((string) ($settings['language'] ?? 'en'));
+ $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))) : 'GET';
+ if (defined('GPTRANSLATE_CURRENT_LANG') && strtolower(GPTRANSLATE_CURRENT_LANG) !== $originalLang && in_array($method, ['GET', 'HEAD'], true)) {
+ wp_safe_redirect($homePath . $restPath . $suffix, 301);
+ exit;
+ }
+ }, 3);
+
/**
* Replace and manage the lang attribute of the html tag
*/
@@ -554,11 +627,24 @@
}, 99);
/**
- * Inject alternate hreflang links in <head>
+ * URL of the current page in each language (the original language and the enabled ones), as advertised by the hreflang tags:
+ * the translated alias when a published translation exists, otherwise the URL with the language code.
+ * Computed once per request, in the order of the enabled languages
+ *
+ * @param array $settings GPTranslate options
+ * @param array $enabledLanguages
+ * @return array Language code => URL
*/
- add_action('wp_head', function () use ($enabledLanguages, $polylangActive, $settings) {
- if (!$settings['add_alternate'] || $polylangActive) {
- return;
+ function gpt_get_alternate_language_urls($settings, $enabledLanguages) {
+ static $urls = null;
+ if ($urls !== null) {
+ return $urls;
+ }
+ $urls = array();
+
+ // Error pages (404, 500, ...) have no URLs in the other languages
+ if (is_404() || (function_exists('http_response_code') && (int) http_response_code() >= 400)) {
+ return $urls;
}
global $wpdb;
@@ -573,7 +659,7 @@
$original_lang = $settings['language']; // x-default language
$omit_prefix = !empty($settings['omit_prefix_original_language']); // Check if prefix should be omitted
- $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
+ $request_uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
$request_path = sanitize_text_field(wp_unslash($request_uri));
// Remove query string
@@ -606,38 +692,8 @@
$original_url_no_lang = gpt_trailingslashit_url(rtrim($site_url, '/') . $current_path_no_lang);
}
- // STEP 2: Per ogni lingua, cerca translated_alias nel DB
$table_name = $wpdb->prefix . 'gptranslate';
- $altflags_a