Plugin Directory

Changeset 3746021


Ignore:
Timestamp:
10/14/2026 10:29:49 AM (6 weeks ago)
Author:
clonable
Message:

Deploy clonable 2.13.6 from Git tag 2.13.6

Location:
clonable
Files:
167 added
26 edited

Legend:

Unmodified
Added
Removed
  • clonable/trunk/assets/js/clonable-search.js

    r3664836 r3746021  
    175175
    176176document.addEventListener("DOMContentLoaded", async () => {
     177    // No widget on this page: skip the (potentially large) index fetch.
     178    const searchElements = document.querySelectorAll("[data-clonable-search]");
     179    if (searchElements.length === 0) return;
     180
    177181    await initSearch();
    178182
    179     const searchElements = document.querySelectorAll("[data-clonable-search]");
    180183    searchElements.forEach(searcher => {
    181184        searcher.addEventListener("input", e => handleSearch(searcher, e));
  • clonable/trunk/clonable-wp.php

    r3736199 r3746021  
    55Description: Official plugin for improving your clones made with Clonable.
    66Plugin URI: https://kb.clonable.net/en/introduction/getting-started/wordpress#de-clonable-plug-in-downloaden
    7 Version: 2.13.5
     7Version: 2.13.6
    88Author: Clonable BV
    99Author URI: https://www.clonable.net
    … …  
    157157define('CLONABLE_NAME', 'Clonable');
    158158define('CLONABLE_PLUGIN_BASE', plugin_basename(__FILE__));
    159 define('CLONABLE_VERSION', '2.13.5');
     159define('CLONABLE_VERSION', '2.13.6');
    160160define('CLONABLE_URL', plugin_dir_url(__FILE__));
    161161
    … …  
    207207        $clonable_plugin = new Bootstrap(CLONABLE_NAME, CLONABLE_VERSION);
    208208        add_action('wp_head', array($clonable_plugin, 'verification'), 1);
    209     } catch (Exception $exception) {
     209    } catch (\Throwable $exception) {
    210210        error_log("[Clonable] Error while initializing plug-in: {$exception->getMessage()}");
    211211        return;
    … …  
    214214    try {
    215215        $allowed_hosts_service = new AllowedHostsService();
    216     } catch (Exception $exception) {
     216    } catch (\Throwable $exception) {
    217217        error_log("[Clonable] Error setting allowed hosts: {$exception->getMessage()}");
    218218    }
    … …  
    237237            }
    238238        }
    239     } catch (Exception $exception) {
     239    } catch (\Throwable $exception) {
    240240        error_log("[Clonable] Error while setting up language tags: {$exception->getMessage()}");
    241241    }
    … …  
    253253            }
    254254        }
    255     } catch (Exception $exception) {
     255    } catch (\Throwable $exception) {
    256256        error_log("[Clonable] Error while setting up LanguageSwitcherService: {$exception->getMessage()}");
    257257    }
    … …  
    260260        // Constructor automatically fixes the initialisation of the subfolders
    261261        $subfolder_service = new SubfolderService();
    262     } catch (Exception $exception) {
     262    } catch (\Throwable $exception) {
    263263        error_log("[Clonable] Error while setting up Clonable subfolders: {$exception->getMessage()}");
    264264    }
    … …  
    270270            $exclusion_module = new ExclusionModule(); // applies exclusion filters to any post type.
    271271        }
    272     } catch (Exception $exception) {
     272    } catch (\Throwable $exception) {
    273273        error_log("[Clonable] Error while setting up exclusion modules: {$exception->getMessage()}");
    274274    }
    … …  
    283283            }
    284284        });
    285     } catch (Exception $exception) {
     285    } catch (\Throwable $exception) {
    286286        error_log("[Clonable] Error while setting up WooCommerce modules: {$exception->getMessage()}");
    287287    }
    … …  
    289289    try {
    290290        $email_translations_service = new EmailTranslationsService();
    291     } catch (Exception $exception) {
     291    } catch (\Throwable $exception) {
    292292        error_log("[Clonable] Error setting up email translations: {$exception->getMessage()}");
    293293    }
    … …  
    295295    try {
    296296        $locale_service = new LocaleService();
    297     } catch (Exception $exception) {
     297    } catch (\Throwable $exception) {
    298298        error_log("[Clonable] Error setting locale: {$exception->getMessage()}");
    299299    }
    … …  
    301301    try {
    302302        $search_engine_service = new SearchEngineService();
    303     } catch (Exception $exception) {
     303    } catch (\Throwable $exception) {
    304304        error_log("[Clonable] Error setting up search engine translations: {$exception->getMessage()}");
    305305    }
    … …  
    307307    try {
    308308        $short_code_service =  new ShortCodeService();
    309     } catch (Exception $exception) {
     309    } catch (\Throwable $exception) {
    310310        error_log("[Clonable] Error setting the Clonable shortcodes: {$exception->getMessage()}");
    311311    }
    … …  
    313313    try {
    314314        $multi_currency_service = new MultiCurrencyService();
    315     } catch (Exception $exception) {
     315    } catch (\Throwable $exception) {
    316316        error_log("[Clonable] Error setting the Multi currency settings: {$exception->getMessage()}");
    317317    }
    … …  
    319319    try {
    320320        $cache_service = new CacheService();
    321     } catch (Exception $exception) {
     321    } catch (\Throwable $exception) {
    322322        error_log("[Clonable] Error handling cache service: {$exception->getMessage()}");
    323323    }
    … …  
    334334            }
    335335        }
    336     } catch (Exception $exception) {
     336    } catch (\Throwable $exception) {
    337337        error_log("Could not setup global Clonable functions: {$exception->getMessage()}");
    338338    }
    … …  
    340340    try {
    341341        $admin_ui_service = new AdminUIService();
    342     } catch (Exception $exception) {
     342    } catch (\Throwable $exception) {
    343343        error_log("[Clonable] Error handling admin UI service: {$exception->getMessage()}");
    344344    }
  • clonable/trunk/controllers/LanguageSwitcherController.php

    r3719175 r3746021  
    44
    55use Clonable\Helpers\Functions;
    6 use Clonable\Helpers\Json;
    76use Clonable\Models\LanguageSwitcher;
    87use Clonable\Traits\Validation;
    … …  
    7473        }
    7574
     75        /**
     76         * Validate switcher JSON. Unslash (magic quotes), re-encode: always valid.
     77         * Literal slashes/unicode: view esc_js() strips backslashes.
     78         *
     79         * @link https://developer.wordpress.org/reference/functions/wp_unslash/
     80         * @link https://developer.wordpress.org/reference/functions/wp_json_encode/
     81         * @link https://developer.wordpress.org/reference/functions/add_settings_error/
     82         */
    7683        public function clonable_language_switcher_items_validate($input) {
    7784                if (!$input) {
    … …  
    7986                }
    8087
    81                 // str_replace needed because of incorrect inline character escaping of php json parsing
    82                 // good explanation: https://stackoverflow.com/questions/32056940/how-to-deal-with-backslashes-in-json-strings-php/32057601#32057601
    83                 $languages = Json::handle_input($input);
     88                $languages = is_string($input) ? json_decode(wp_unslash($input)) : null;
    8489                if ($languages === null) {
    8590                        add_settings_error('clonable_langswitch_data', 'err_invalid_json', 'The supplied JSON string was invalid. Please check its syntax and try again.');
    … …  
    105110        }
    106111
    107         return Json::handle_output($input);
     112        $encoded = wp_json_encode($languages, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
     113        if ($encoded === false) {
     114            add_settings_error('clonable_langswitch_data', 'err_invalid_json', 'The supplied JSON string was invalid. Please check its syntax and try again.');
     115            return false;
     116        }
     117
     118        return $encoded;
    108119    }
    109120}
  • clonable/trunk/controllers/WoocommerceController.php

    r3719175 r3746021  
    120120                return Json::handle_output(json_encode($rows));
    121121        }
     122
     123        /**
     124         * Checkbox; checked enables the clone-based customer location.
     125         *
     126         * @param mixed $input Submitted value.
     127         * @return mixed
     128         */
     129        public function clonable_woocommerce_customer_location_enabled_validate($input) {
     130                return $this->validate_checkbox($input, ClonableWooCommerce::CUSTOMER_LOCATION_ENABLED);
     131        }
    122132}
  • clonable/trunk/helpers/Html.php

    r3719175 r3746021  
    8383         *
    8484         * @param $file string the name of the file excluding the assets/js directory, should not start with a /.
    85          * @param $options array array of additional script loading strategies
     85         * @param $options array wp_enqueue_script() $args: in_footer, strategy, fetchpriority.
     86         *                       No 'version': fixed to CLONABLE_VERSION; WP 7.0+ warns on unknown keys.
    8687         * @return void does not return, enqueues the given script
     88         * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    8789         */
    8890        public static function include_jquery_script($file, $options = array()) {
    … …  
    126128                self::include_css('fomantic-transition.css', CLONABLE_VERSION);
    127129                self::flags();
    128                 self::include_jquery_script('fomantic-dropdown.js', array('version' => CLONABLE_VERSION));
    129                 self::include_jquery_script('fomantic-transition.js', array('version' => CLONABLE_VERSION));
    130                 self::include_jquery_script(
    131                         'onload.js',
    132                         array(
    133                                 'strategy' => 'defer',
    134                                 'version'  => CLONABLE_VERSION,
    135                         )
    136                 );
     130                self::include_jquery_script('fomantic-dropdown.js');
     131                self::include_jquery_script('fomantic-transition.js');
     132                self::include_jquery_script('onload.js', array('strategy' => 'defer'));
    137133        }
    138134
    … …  
    143139         */
    144140        public static function include_alpine() {
    145                 self::include_jquery_script(
    146                         'alpine.js',
    147                         array(
    148                                 'in_footer' => false,
    149                                 'version'   => CLONABLE_VERSION,
    150                         )
    151                 );
     141                self::include_jquery_script('alpine.js', array('in_footer' => false));
    152142                self::include_cdn('Alpine-Tooltip.js', 'https://cdn.jsdelivr.net/npm/@ryangjchandler/alpine-tooltip@1.x.x/dist/cdn.min.js', false, true);
    153143                self::include_cdn('Tippy.css', 'https://unpkg.com/tippy.js@6/dist/tippy.css', true);
  • clonable/trunk/helpers/Json.php

    r3719175 r3746021  
    1313                return str_replace('\\"', '"', $input);
    1414        }
     15
     16        /**
     17         * JSON list to array, never null. Junk gives [].
     18         * Fallback strips backslashes: repairs legacy d\'Italia.
     19         *
     20         * @param mixed $raw Option value.
     21         * @return array
     22         */
     23        public static function decode_array(mixed $raw): array {
     24                if (!is_string($raw)) {
     25                        return [];
     26                }
     27
     28                $decoded = json_decode($raw);
     29                if (!is_array($decoded)) {
     30                        $decoded = self::handle_input($raw);
     31                }
     32
     33                return is_array($decoded) ? $decoded : [];
     34        }
    1535}
  • clonable/trunk/models/ClonableWooCommerce.php

    r3719175 r3746021  
    77use Clonable\Services\MultiCurrencyService;
    88
    9 class ClonableWooCommerce {
    10         const PAGE = 'woocommerce';
     9class ClonableWooCommerce
     10{
     11    public const PAGE = 'woocommerce';
    1112
    12         public static $fields = [
    13                 'clonable_woocommerce_module_enabled'    => [
    14                         'render'      => 'clonable_woocommerce_module_enabled_field',
    15                         'name'        => 'Enable WooCommerce module',
    16                         'setting'     => 'clonable_woocommerce_module_enabled',
    17                         'description' => 'This is the master setting of the WooCommerce module, turn this off if you wish to disable this module.',
    18                 ],
    19                 'clonable_woocommerce_analytics_enabled' => [
    20                         'render'      => 'clonable_woocommerce_analytics_enabled_field',
    21                         'name'        => 'Enable conversion tracking',
    22                         'setting'     => 'clonable_woocommerce_analytics_enabled',
    23                         'description' => 'Changes the redirect url of the payment provider to the domain of the last visited clone.',
    24                 ],
    25                 'clonable_woocommerce_analytics'         => [
    26                         'render'  => 'clonable_woocommerce_analytics_field',
    27                         'name'    => 'Valid redirect locations',
    28                         'setting' => 'clonable_woocommerce_allowed_origins',
    29                 ],
    30                 'clonable_default_country_by_domain'     => [
    31                         'render'  => 'clonable_default_country_by_domain_field',
    32                         'name'    => 'Default checkout country by domain',
    33                         'setting' => 'clonable_default_country_by_domain',
    34                 ],
    35         ];
     13    /** Checked = guest default location follows the clone. Default off: opt-in. */
     14    public const CUSTOMER_LOCATION_ENABLED = 'clonable_woocommerce_customer_location_enabled';
    3615
    37         public static function get_woocommerce_countries(): array {
    38                 if (!class_exists('\WC_Countries')) {
    39                         return [];
    40                 }
    41                 $wc_countries = new \WC_Countries();
    42                 return array_keys($wc_countries->get_countries());
    43         }
     16    public static $fields = [
     17        'clonable_woocommerce_module_enabled'    => [
     18            'render'      => 'clonable_woocommerce_module_enabled_field',
     19            'name'        => 'Enable WooCommerce module',
     20            'setting'     => 'clonable_woocommerce_module_enabled',
     21            'description' => 'This is the master setting of the WooCommerce module, turn this off if you wish to disable this module.',
     22        ],
     23        'clonable_woocommerce_analytics_enabled' => [
     24            'render'      => 'clonable_woocommerce_analytics_enabled_field',
     25            'name'        => 'Enable conversion tracking',
     26            'setting'     => 'clonable_woocommerce_analytics_enabled',
     27            'description' => 'Changes the redirect url of the payment provider to the domain of the last visited clone.',
     28        ],
     29        self::CUSTOMER_LOCATION_ENABLED          => [
     30            'render'      => 'clonable_woocommerce_customer_location_enabled_field',
     31            'name'        => 'Enable customer location based on clone',
     32            'setting'     => self::CUSTOMER_LOCATION_ENABLED,
     33            'description' => 'Check this to give guests the country of the clone as their default customer location, so taxes and shipping estimates match the clone until the customer enters an address. Unchecked, the WooCommerce default location is used.',
     34        ],
     35        'clonable_woocommerce_analytics'         => [
     36            'render'  => 'clonable_woocommerce_analytics_field',
     37            'name'    => 'Valid redirect locations',
     38            'setting' => 'clonable_woocommerce_allowed_origins',
     39        ],
     40        'clonable_default_country_by_domain'     => [
     41            'render'  => 'clonable_default_country_by_domain_field',
     42            'name'    => 'Default checkout country by domain',
     43            'setting' => 'clonable_default_country_by_domain',
     44        ],
     45
     46    ];
     47
     48    public static function get_woocommerce_countries(): array
     49    {
     50        if (!class_exists('\WC_Countries')) {
     51            return [];
     52        }
     53        $wc_countries = new \WC_Countries();
     54        return array_keys($wc_countries->get_countries());
     55    }
    4456}
  • clonable/trunk/models/Site.php

    r3719175 r3746021  
    3030        private $site;
    3131
     32        /**
     33         * @param mixed $site Non-array: empty site.
     34         */
    3235        public function __construct($site) {
    33                 $this->site = $site;
     36                $this->site = is_array($site) ? $site : [];
    3437        }
    3538
    … …  
    6164         */
    6265        public function get_clones() {
    63                 return $this->site['clones'];
     66                $clones = $this->site['clones'] ?? null;
     67                return is_array($clones) ? $clones : [];
    6468        }
    6569
    … …  
    7377
    7478        public function get_subfolders() {
    75                 $clones            = $this->site['clones'];
     79                $clones            = $this->get_clones();
    7680                $domain            = $this->get_domain();
    7781                $mapped_subdomains = array_map(
  • clonable/trunk/objects/ClonableConfig.php

    r3719175 r3746021  
    5656        /**
    5757         * Retrieves the Clonable site from the WordPress option.
     58         * Non-array option: no site.
    5859         *
     60         * @link https://developer.wordpress.org/reference/functions/get_option/
    5961         * @return Site|null
    6062         */
    6163        public static function get_site() {
    6264                $response = get_option('clonable_site');
    63                 if (empty($response)) {
     65                if (empty($response) || !is_array($response)) {
    6466                        return null;
    6567                }
  • clonable/trunk/readme-da_DK.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-de_DE.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-es_ES.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-fr_FR.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-it_IT.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-nb_NO.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-nl_NL.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme-sv_SE.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/readme.txt

    r3736199 r3746021  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 2.13.5
     7Stable tag: 2.13.6
    88License: GPL v2 or later
    99
    … …  
    3232
    3333== Changelog ==
     34v2.13.6
     35Optional customer location based on clone for WooCommerce, more reliable clone ID and origin on orders, and fixes for menus, product exclusions, search and WordPress 7.0.
     36
    3437v2.13.5
    3538Inclusion of the X-Forwarded-For header for subfolder proxy.
  • clonable/trunk/services/ClonableWooCommerceService.php

    r3719175 r3746021  
    55use Clonable\Helpers\Functions;
    66use Clonable\Helpers\Json;
     7use Clonable\Models\ClonableWooCommerce;
    78use Clonable\Objects\ClonableConfig;
    89use Clonable\Services\Modules\DataPanelModule;
    … …  
    2122        private const OPT_HEADERS_BY_DOMAIN      = 'clonable_email_headers_by_domain';
    2223
     24        /** WooCommerce session key: country this plugin last set for the guest. */
     25        private const SESSION_CLONE_COUNTRY = 'clonable_clone_country';
     26
    2327        public function __construct() {
    2428                $module_enabled = get_option('clonable_woocommerce_module_enabled', 'on') === 'on';
    … …  
    3034                if ($include_woocommerce_analytics) {
    3135                        // Add hidden field with the domain. Will get replaced by Clonable automagically to match actual domain.
    32                         add_action('woocommerce_after_order_notes', array($this, 'add_origin_field'));
     36                        // Billing section sits inside the checkout <form>, also when order notes are hidden.
     37                        add_action('woocommerce_checkout_billing', array($this, 'add_origin_field'), 20);
    3338                        add_action('woocommerce_checkout_update_order_meta', array($this, 'save_origin_field'), 10, 1);
     39                        // Fallback when the hidden field was not rendered (checkout builders without the billing hook).
     40                        add_action('woocommerce_checkout_create_order', array($this, 'add_missing_origin'), 10, 1);
    3441                        add_action('woocommerce_admin_order_data_after_shipping_address', array($this, 'display_order_origin'));
    3542
    … …  
    5764                        $data_panel_module       = new DataPanelModule(); // data panel on the admin product page.
    5865                        $product_importer_module = new ProductImporterModule(); // enables bulk edit via the WooCommerce product importer
     66                }
     67
     68                // Guest default location follows the clone (taxes, shipping estimates). Opt-in, default off.
     69                if (get_option(ClonableWooCommerce::CUSTOMER_LOCATION_ENABLED, 'off') === 'on') {
     70                        add_filter('woocommerce_customer_default_location_array', array($this, 'clone_default_location'), 20);
     71                        add_action('woocommerce_cart_loaded_from_session', array($this, 'sync_guest_location_to_clone'));
    5972                }
    6073
    … …  
    8194
    8295                // Add a hidden field containing the current clone ID for use in woocommerce email translations
    83                 add_action('woocommerce_after_order_notes', array($this, 'add_clone_id_field'), 10, 2);
     96                add_action('woocommerce_checkout_billing', array($this, 'add_clone_id_field'), 20);
    8497
    8598                // Add the clone ID to the order meta when saving the order
    8699                add_action('woocommerce_checkout_update_order_meta', array($this, 'save_order_clone_id'));
     100
     101                // Fallback when the hidden field was not rendered (checkout builders without the billing hook).
     102                add_action('woocommerce_checkout_create_order', array($this, 'add_missing_clone_id'), 10, 1);
    87103
    88104                // Save clone ID for WooCommerce Blocks checkout (Store API doesn't use $_POST)
    … …  
    281297        }
    282298
     299        /**
     300         * Hidden clone ID field in checkout form.
     301         *
     302         * @link https://developer.wordpress.org/reference/functions/esc_attr/
     303         * @link https://woocommerce.github.io/code-reference/hooks/hooks.html
     304         */
    283305        public function add_clone_id_field() {
    284306                $clone_id = ClonableConfig::get_clone_id_by_current_url();
    … …  
    342364         * Country from the WooCommerce "Default customer location" setting
    343365         * (woocommerce_default_customer_address: base / geolocation / none).
     366         */
     367        private function woocommerce_default_country(): string {
     368                return $this->woocommerce_default_location()['country'];
     369        }
     370
     371        /**
     372         * WooCommerce "Default customer location" as ['country' => string, 'state' => string].
     373         * Own filter clone_default_location() leaves it alone on the origin.
    344374         *
    345375         * @link https://woocommerce.github.io/code-reference/namespaces/default.html#function_wc_get_customer_default_location
    346376         */
    347         private function woocommerce_default_country(): string {
    348                 if (!function_exists('wc_get_customer_default_location')) {
     377        private function woocommerce_default_location(): array {
     378                $location = function_exists('wc_get_customer_default_location') ? wc_get_customer_default_location() : null;
     379
     380                return array(
     381                        'country' => is_array($location) ? (string) ($location['country'] ?? '') : '',
     382                        'state'   => is_array($location) ? (string) ($location['state'] ?? '') : '',
     383                );
     384        }
     385
     386        /**
     387         * Filter woocommerce_customer_default_location_array: the clone decides the default country.
     388         * Runs after geolocation, so it also wins over the "Geolocate" setting.
     389         *
     390         * @param mixed $location ['country' => string, 'state' => string].
     391         * @return mixed
     392         * @link https://woocommerce.github.io/code-reference/namespaces/default.html#function_wc_get_customer_default_location
     393         */
     394        public function clone_default_location($location) {
     395                $country = $this->resolve_clone_country();
     396
     397                // Same country: keep its state.
     398                if ('' === $country || !is_array($location) || ($location['country'] ?? '') === $country) {
     399                        return $location;
     400                }
     401
     402                return array(
     403                        'country' => $country,
     404                        'state'   => '',
     405                );
     406        }
     407
     408        /**
     409         * Action woocommerce_cart_loaded_from_session: guest session follows the clone until the customer picks a location.
     410         * WooCommerce only fills an empty country, so a session started elsewhere keeps its old one.
     411         * Fires on every cart load (page, AJAX, Store API), before WooCommerce recalculates totals.
     412         *
     413         * Only a country this plugin set is changed; one the customer picked stays (any checkout, any plugin).
     414         * Origin (or clone without allowed country) with a shared session, e.g. subfolder clones:
     415         * the country this plugin set goes back to the WooCommerce default location.
     416         *
     417         * @param mixed $cart WC_Cart.
     418         * @link https://developer.wordpress.org/reference/functions/is_user_logged_in/
     419         * @link https://woocommerce.github.io/code-reference/classes/WC-Customer.html#method_has_calculated_shipping
     420         * @link https://woocommerce.github.io/code-reference/classes/WC-Session.html#method_get
     421         * @link https://woocommerce.github.io/code-reference/classes/WC-Session.html#method_set
     422         */
     423        public function sync_guest_location_to_clone($cart): void {
     424                if (is_user_logged_in()) {
     425                        return;
     426                }
     427
     428                // WooCommerce creates the customer before the cart.
     429                $customer = WC()->customer;
     430                $session  = WC()->session;
     431                if (!$customer instanceof \WC_Customer || $session === null) {
     432                        return;
     433                }
     434
     435                $country       = $this->resolve_clone_country();
     436                $set_by_plugin = (string) $session->get(self::SESSION_CLONE_COUNTRY, '');
     437
     438                // Origin, never on a clone: nothing to undo.
     439                if ($country === '' && $set_by_plugin === '') {
     440                        return;
     441                }
     442
     443                // Entered address or shipping calculator: the customer's own choice.
     444                if ($customer->has_calculated_shipping() || $customer->get_billing_postcode() || $customer->get_billing_address_1()
     445                        || $customer->get_shipping_postcode() || $customer->get_shipping_address_1()) {
     446                        return;
     447                }
     448
     449                // Billing or shipping country no longer what we set: changed by the customer, e.g. in the checkout.
     450                if ('' !== $set_by_plugin
     451                        && ($customer->get_billing_country() !== $set_by_plugin || $customer->get_shipping_country() !== $set_by_plugin)) {
     452                        return;
     453                }
     454
     455                // Origin or clone without allowed country: back to the WooCommerce default, forget our country.
     456                if ($country === '') {
     457                        $session->set(self::SESSION_CLONE_COUNTRY, null);
     458                        $default = $this->woocommerce_default_location();
     459                        $this->apply_guest_country($customer, $cart, $default['country'], $default['state']);
     460                        return;
     461                }
     462
     463                // Also when already equal, so a later switch by the customer is recognised. No write if unchanged.
     464                $session->set(self::SESSION_CLONE_COUNTRY, $country);
     465
     466                // Country only; a state belongs to the old country.
     467                $this->apply_guest_country($customer, $cart, $country, '');
     468        }
     469
     470        /**
     471         * Set billing + shipping country (with state) on the guest; save + recalc only on change.
     472         *
     473         * @param mixed $cart WC_Cart.
     474         * @link https://woocommerce.github.io/code-reference/classes/WC-Customer.html#method_set_billing_country
     475         * @link https://woocommerce.github.io/code-reference/classes/WC-Customer.html#method_set_shipping_country
     476         * @link https://woocommerce.github.io/code-reference/classes/WC-Cart.html#method_calculate_totals
     477         */
     478        private function apply_guest_country(\WC_Customer $customer, $cart, string $country, string $state): void {
     479                if ($customer->get_billing_country() === $country && $customer->get_shipping_country() === $country) {
     480                        return;
     481                }
     482
     483                if ($customer->get_billing_country() !== $country) {
     484                        $customer->set_billing_country($country);
     485                        $customer->set_billing_state($state);
     486                }
     487                if ($customer->get_shipping_country() !== $country) {
     488                        $customer->set_shipping_country($country);
     489                        $customer->set_shipping_state($state);
     490                }
     491                $customer->save();
     492
     493                // Totals in the session were calculated for the old country (e.g. the mini cart).
     494                if ($cart instanceof \WC_Cart) {
     495                        $cart->calculate_totals();
     496                }
     497        }
     498
     499        /**
     500         * Country of the current clone: the configured checkout country first, then the proxy's region header.
     501         * '' on the origin, or when WooCommerce does not allow the country.
     502         *
     503         * @link https://developer.wordpress.org/reference/functions/wp_unslash/
     504         * @link https://developer.wordpress.org/reference/functions/sanitize_text_field/
     505         * @link https://woocommerce.github.io/code-reference/classes/WC-Countries.html#method_get_allowed_countries
     506         */
     507        private function resolve_clone_country(): string {
     508                if (!Functions::is_clone()) {
    349509                        return '';
    350510                }
    351511
    352                 $location = wc_get_customer_default_location();
    353 
    354                 return is_array($location) ? (string) ($location['country'] ?? '') : '';
    355         }
    356 
    357         public function add_origin_field($checkout) {
     512                $region     = isset($_SERVER['HTTP_CLONABLE_TARGET_REGION']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_CLONABLE_TARGET_REGION'])) : '';
     513                $candidates = array($this->resolve_clone_checkout_country('billing'), $region);
     514                $allowed    = WC()->countries->get_allowed_countries();
     515
     516                foreach ($candidates as $candidate) {
     517                        $country = strtoupper(trim($candidate));
     518                        if ('' !== $country && isset($allowed[$country])) {
     519                                return $country;
     520                        }
     521                }
     522
     523                return '';
     524        }
     525
     526        /**
     527         * Hidden origin field in checkout form. Hook passes no args.
     528         *
     529         * @link https://developer.wordpress.org/reference/functions/get_site_url/
     530         * @link https://developer.wordpress.org/reference/functions/esc_attr/
     531         * @link https://woocommerce.github.io/code-reference/hooks/hooks.html
     532         */
     533        public function add_origin_field() {
    358534                $value = parse_url(get_site_url(), PHP_URL_HOST);
    359                 echo '<input type="hidden" name="clonable_origin" value="' . esc_html($value) . '" />';
     535                echo '<input type="hidden" name="clonable_origin" value="' . esc_attr($value) . '" />';
    360536        }
    361537
    … …  
    387563
    388564        /**
     565         * Origin fallback: hidden field absent from POST means the billing hook did not render it.
     566         * Resolve from request headers. Runs before the first order save: no extra save().
     567         *
     568         * @param WC_Order|mixed $order Order being created.
     569         * @link https://woocommerce.github.io/code-reference/hooks/hooks.html
     570         */
     571        public function add_missing_origin($order): void {
     572                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked by WC_Checkout::process_checkout().
     573                if (!$order instanceof WC_Order || isset($_POST['clonable_origin']) || $order->get_meta('clonable_origin')) {
     574                        return;
     575                }
     576
     577                $this->log_checkout_fallback('clonable_origin');
     578
     579                $origin = $this->resolve_origin_from_request();
     580                if ($origin !== null) {
     581                        $order->update_meta_data('clonable_origin', $origin);
     582                }
     583        }
     584
     585        /**
     586         * Clone ID fallback: hidden field absent from POST means the billing hook did not render it.
     587         * Resolve from request headers. Runs before the first order save: no extra save().
     588         *
     589         * @param WC_Order|mixed $order Order being created.
     590         * @link https://woocommerce.github.io/code-reference/hooks/hooks.html
     591         * @link https://developer.wordpress.org/reference/functions/sanitize_text_field/
     592         */
     593        public function add_missing_clone_id($order): void {
     594                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce checked by WC_Checkout::process_checkout().
     595                if (!$order instanceof WC_Order || isset($_POST['clonable_clone_id']) || $order->get_meta('clonable_clone_id')) {
     596                        return;
     597                }
     598
     599                $this->log_checkout_fallback('clonable_clone_id');
     600
     601                $clone_id = ClonableConfig::get_clone_id_by_current_url();
     602                if ($clone_id) {
     603                        $order->update_meta_data('clonable_clone_id', sanitize_text_field($clone_id));
     604                }
     605        }
     606
     607        /**
     608         * Origin from Clonable proxy headers (domain + subfolder), else ORIGINAL_SHOP.
     609         * Null when not in the allowed origins.
     610         *
     611         * @link https://developer.wordpress.org/reference/functions/wp_unslash/
     612         * @link https://developer.wordpress.org/reference/functions/sanitize_text_field/
     613         */
     614        private function resolve_origin_from_request(): ?string {
     615                $origin = rtrim(sanitize_text_field(wp_unslash(ClonableConfig::current_clonable_domain())), '/');
     616
     617                return ($origin !== '' && $this->is_valid_origin($origin)) ? $origin : null;
     618        }
     619
     620        /**
     621         * Debug-log checkout fallback use (WP_DEBUG_LOG only): billing hook not rendered on this site.
     622         */
     623        private function log_checkout_fallback(string $field): void {
     624                if (!defined('WP_DEBUG_LOG') || !WP_DEBUG_LOG) {
     625                        return;
     626                }
     627
     628                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     629                error_log("[Clonable] Checkout field {$field} missing (woocommerce_checkout_billing not rendered); using request headers.");
     630        }
     631
     632        /**
    389633         * Save clone ID for orders placed via the WooCommerce Blocks checkout.
    390634         * The blocks checkout uses the Store API instead of $_POST, so we determine
    … …  
    419663                }
    420664
    421                 $origin = null;
    422                 // get the origin clone URL based on the current request headers (set by Clonable on the frontend)
    423                 if (isset($_SERVER['HTTP_CLONABLE_CLONE_DOMAIN'])) {
    424                         $origin = $_SERVER['HTTP_CLONABLE_CLONE_DOMAIN'];
    425                         if (isset($_SERVER['HTTP_CLONABLE_CLONE_SUBFOLDER']) && !empty($_SERVER['HTTP_CLONABLE_CLONE_SUBFOLDER'])) {
    426                                 $origin .= $_SERVER['HTTP_CLONABLE_CLONE_SUBFOLDER'];
    427                         }
    428                 } else {
    429                         // fallback to original shop domain when header not present
    430                         $origin = ClonableConfig::ORIGINAL_SHOP;
    431                 }
    432 
    433                 $origin = rtrim($origin, '/'); // remove trailing slash from origin if present
    434 
    435                 if (!$this->is_valid_origin($origin)) {
     665                $origin = $this->resolve_origin_from_request();
     666                if ($origin === null) {
    436667                        return;
    437668                }
  • clonable/trunk/services/LanguageSwitcherService.php

    r3719175 r3746021  
    88use Clonable\Helpers\UrlTranslator;
    99use Clonable\Helpers\Functions;
     10use Clonable\Helpers\Json;
    1011use stdClass;
    1112use Throwable;
    … …  
    1718 * Uses the values set by the language switcher settings.
    1819 */
    19 class LanguageSwitcherService {
    20         // Define constants for menu item classes
    21         private const MENU_ITEM_CLASS    = 'clonable-language-switcher';
    22         private const MENU_ITEM_LI_CLASS = 'menu-item clonable-menu-item-language-switcher';
    23 
    24         /**
    25          * Prints out the language switcher script tag and the corresponding JavaScript settings.
    26          *
    27          * @return void echos out the scripts.
    28          */
    29         public function __construct() {
    30                 add_shortcode('clonable_language_switcher', [$this, 'language_switcher_shortcode']);
    31 
    32                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    33 
    34                 if (!$plugin_language_switcher_settings['showFlag'] && !$plugin_language_switcher_settings['showTargetLanguage']) {
    35                         // If both flag and text are disabled, no need to render the switcher
    36                         return;
    37                 }
    38 
    39                 add_action('wp_head', [$this, 'print_language_switcher']);
    40                 add_action('wp_head', [$this, 'include_language_switcher_assets']);
    41                 add_action('admin_head', [$this, 'include_language_switcher_assets']);
    42 
    43                 // Register the meta box for Appearance → Menus
    44                 add_action('admin_head-nav-menus.php', [$this, 'register_nav_menu_meta_box']);
    45                 // Hook into menu objects to inject language items from native menu items
    46                 add_filter('wp_nav_menu_objects', [$this, 'inject_language_menu_items'], 10, 2);
    47                 // Customize the output of injected language child menu items
    48                 add_filter('walker_nav_menu_start_el', [$this, 'customize_language_menu_item_output'], 10, 4);
    49 
    50                 add_filter(
    51                         'render_block_core/navigation-submenu',
    52                         [$this, 'submenu_block_language_switcher'],
    53                         10,
    54                         2
    55                 );
    56         }
    57 
    58         /**
    59          * New entry point for hooking into wp_nav_menu_items.
    60          * Matches the signature expected by add_action/add_filter('wp_nav_menu_items', ...).
    61          *
    62          * @param string   $items The HTML list content for the menu items.
    63          * @param stdClass $args An object containing wp_nav_menu() arguments.
    64          *
    65          * @return string
    66          */
    67         public function add_language_switcher_to_menu($items, $menu_args): string {
    68                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    69                 return $this->build_language_switcher($plugin_language_switcher_settings, $items, $menu_args, 'traditional_menu');
    70         }
    71 
    72         public function include_language_switcher_assets(): void {
    73                 /*
    74                 Load assets for the language switcher preview.
    75                 If we are in admin, only load when the current page is a clonable page to avoid loading unnecessary assets in the admin.
    76                 */
    77                 $is_clonable_page = Functions::is_clonable_page();
    78                 if (is_admin() && !$is_clonable_page) {
    79                         return;
    80                 }
    81 
    82                 Html::flags();
    83                 Html::include_js('language-switcher.js', CLONABLE_VERSION);
    84 
    85                 // check if the user has disabled the default styles of the language switcher, if not include the default css.
    86                 $disable_styles = (get_option('clonable_disable_language_switcher_styles', 'on') === 'on') ? 1 : 0;
    87                 if ($disable_styles) {
    88                         return;
    89                 }
    90 
    91                 Html::include_css('clonable-language-switcher.css', CLONABLE_VERSION);
    92                 $this->add_menu_language_switcher_css();
    93         }
    94 
    95         public function add_menu_language_switcher_css(): void {
    96                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    97                 if (!$plugin_language_switcher_settings) {
    98                         return;
    99                 }
    100 
    101                 // if floating language switcher is enabled, we want to apply the background color and hover background color to the menu item in the traditional menu, to ensure a consistent design between the floating switcher and the traditional menu item.
    102                 $floating_language_switcher_enabled = (get_option('clonable_enable_language_switcher', 'off') === 'on');
    103                 if (!$floating_language_switcher_enabled) {
    104                         return;
    105                 }
    106 
    107                 $bg_color       = $plugin_language_switcher_settings['backgroundColor'] ?? '';
    108                 $bg_hover_color = $plugin_language_switcher_settings['hoverBackgroundColor'] ?? '';
    109                 ?>
     20class LanguageSwitcherService
     21{
     22    // Define constants for menu item classes
     23    private const MENU_ITEM_CLASS    = 'clonable-language-switcher';
     24    private const MENU_ITEM_LI_CLASS = 'menu-item clonable-menu-item-language-switcher';
     25
     26    /**
     27     * Prints out the language switcher script tag and the corresponding JavaScript settings.
     28     *
     29     * @return void echos out the scripts.
     30     */
     31    public function __construct()
     32    {
     33        add_shortcode('clonable_language_switcher', [$this, 'language_switcher_shortcode']);
     34
     35        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     36
     37        if (!$plugin_language_switcher_settings['showFlag'] && !$plugin_language_switcher_settings['showTargetLanguage']) {
     38            // If both flag and text are disabled, no need to render the switcher
     39            return;
     40        }
     41
     42        add_action('wp_head', [$this, 'print_language_switcher']);
     43        add_action('wp_head', [$this, 'include_language_switcher_assets']);
     44        add_action('admin_head', [$this, 'include_language_switcher_assets']);
     45
     46        // Register the meta box for Appearance → Menus
     47        add_action('admin_head-nav-menus.php', [$this, 'register_nav_menu_meta_box']);
     48        // Hook into menu objects to inject language items from native menu items
     49        add_filter('wp_nav_menu_objects', [$this, 'inject_language_menu_items'], 10, 2);
     50        // Customize the output of injected language child menu items
     51        add_filter('walker_nav_menu_start_el', [$this, 'customize_language_menu_item_output'], 10, 4);
     52
     53        add_filter(
     54            'render_block_core/navigation-submenu',
     55            [$this, 'submenu_block_language_switcher'],
     56            10,
     57            2
     58        );
     59    }
     60
     61    /**
     62     * New entry point for hooking into wp_nav_menu_items.
     63     * Matches the signature expected by add_action/add_filter('wp_nav_menu_items', ...).
     64     *
     65     * @param string   $items The HTML list content for the menu items.
     66     * @param stdClass $args An object containing wp_nav_menu() arguments.
     67     *
     68     * @return string
     69     */
     70    public function add_language_switcher_to_menu($items, $menu_args): string
     71    {
     72        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     73        return $this->build_language_switcher($plugin_language_switcher_settings, $items, $menu_args, 'traditional_menu');
     74    }
     75
     76    public function include_language_switcher_assets(): void
     77    {
     78        /*
     79        Load assets for the language switcher preview.
     80        If we are in admin, only load when the current page is a clonable page to avoid loading unnecessary assets in the admin.
     81        */
     82        $is_clonable_page = Functions::is_clonable_page();
     83        if (is_admin() && !$is_clonable_page) {
     84            return;
     85        }
     86
     87        Html::flags();
     88        Html::include_js('language-switcher.js', CLONABLE_VERSION);
     89
     90        // check if the user has disabled the default styles of the language switcher, if not include the default css.
     91        $disable_styles = (get_option('clonable_disable_language_switcher_styles', 'on') === 'on') ? 1 : 0;
     92        if ($disable_styles) {
     93            return;
     94        }
     95
     96        Html::include_css('clonable-language-switcher.css', CLONABLE_VERSION);
     97        $this->add_menu_language_switcher_css();
     98    }
     99
     100    public function add_menu_language_switcher_css(): void
     101    {
     102        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     103        if (!$plugin_language_switcher_settings) {
     104            return;
     105        }
     106
     107        // if floating language switcher is enabled, we want to apply the background color and hover background color to the menu item in the traditional menu, to ensure a consistent design between the floating switcher and the traditional menu item.
     108        $floating_language_switcher_enabled = (get_option('clonable_enable_language_switcher', 'off') === 'on');
     109        if (!$floating_language_switcher_enabled) {
     110            return;
     111        }
     112
     113        $bg_color       = $plugin_language_switcher_settings['backgroundColor'] ?? '';
     114        $bg_hover_color = $plugin_language_switcher_settings['hoverBackgroundColor'] ?? '';
     115        ?>
    110116                <style class="clonable-language-switcher-style" type="text/css">
    111117                        /* Clonable Language Switcher Menu Styles */
    … …  
    118124                </style>
    119125                <?php
    120         }
    121 
    122         /**
    123          * Appends the language switcher item to a specific menu (by menu slug).
    124          *
    125          * @param array    $plugin_language_switcher_settings Language switcher settings.
    126          * @param string   $items      The HTML list content for the menu items.
    127          * @param stdClass $menu_args  An object containing wp_nav_menu() arguments.
    128          * @param string   $context    Render context: 'traditional_menu', 'block_menu_submenu', or 'shortcode'.
    129          *
    130          * @return string
    131          */
    132         public function build_language_switcher(array $plugin_language_switcher_settings, $items, $menu_args, string $context): string {
    133                 if (empty($plugin_language_switcher_settings)) {
    134                         return $items;
    135                 }
    136 
    137                 $menu_languages = $this->build_menu_languages($plugin_language_switcher_settings);
    138 
    139                 if (empty($menu_languages)) {
    140                         return $items . $this->render_fallback_item();
    141                 }
    142 
    143                 $flag_dimensions_class = $this->get_flag_dimensions_class($plugin_language_switcher_settings);
    144 
    145                 $html = match ($context) {
    146                         'shortcode' => $this->render_traditional_menu($plugin_language_switcher_settings, $menu_languages, $flag_dimensions_class, $context),
    147                         'block_menu_submenu' => $this->render_block_submenu($plugin_language_switcher_settings, $menu_languages, $flag_dimensions_class),
    148                         default => '',
    149                 };
    150 
    151                 if ($html === '') {
    152                         $html = $this->render_fallback_item();
    153                 }
    154 
    155                 return $items . $html;
    156         }
    157 
    158         /**
    159          * Returns the CSS class for flag dimensions based on settings.
    160          *
    161          * @param array $settings Language switcher settings.
    162          * @return string
    163          */
    164         private function get_flag_dimensions_class(array $settings): string {
    165                 return !empty($settings['roundedFlag']) ? 'ff-rounded' : 'ff-rectangle';
    166         }
    167 
    168         /**
    169          * Returns the current request path.
    170          *
    171          * @return string
    172          */
    173         private function get_request_path(): string {
    174                 return parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
    175         }
    176 
    177         /**
    178          * Builds the array of menu languages with translated URLs.
    179          *
    180          * @param array $settings Language switcher settings.
    181          * @return array
    182          */
    183         private function build_menu_languages(array $settings): array {
    184                 $menu_languages = $this->get_language_switcher_languages();
    185 
    186                 // Resolve display names from settings
    187                 $languages_map = $this->parse_languages_setting($settings['languages'] ?? '[]');
    188 
    189                 foreach ($menu_languages as &$lang) {
    190                         // in case country code is enabled, we want to show the country code instead of the language name.
    191                         // We can determine the country code by taking the display region of the locale code.
    192                         // For example, if the locale code is en_US, we want to show US as the country code.
    193                         if (!empty($settings['showCountry'])) {
    194                                 $lang['display_name'] = $lang['flag_code'];
    195                                 continue;
    196                         }
    197 
    198                         $lang['display_name'] = $languages_map[$lang['lang_code']] ?? $lang['lang_code'];
    199                 }
    200 
    201                 unset($lang);
    202                 return $menu_languages;
    203         }
    204 
    205         /**
    206          * Parses the languages setting JSON into a lang_code => display_name map.
    207          *
    208          * @param mixed $languages_setting JSON string or array.
    209          * @return array<string, string>
    210          */
    211         private function parse_languages_setting($languages_setting): array {
    212                 try {
    213                         if (is_array($languages_setting)) {
    214                                 $json = json_encode($languages_setting);
    215                         } else {
    216                                 $json = (string) $languages_setting;
    217                         }
    218 
    219                         $json = str_replace('U+002E', '.', $json);
    220                         $arr  = json_decode($json, true);
    221 
    222                         if (!is_array($arr)) {
    223                                 return [];
    224                         }
    225 
    226                         $map = [];
    227                         foreach ($arr as $entry) {
    228                                 if (is_array($entry)
    229                                         && isset($entry['clonableLocaleCode'], $entry['clonableDisplayLanguage'])
    230                                 ) {
    231                                         $map[ (string) $entry['clonableLocaleCode']] = (string) $entry['clonableDisplayLanguage'];
    232                                 }
    233                         }
    234 
    235                         return $map;
    236                 } catch (Throwable) {
    237                         return [];
    238                 }
    239         }
    240 
    241         /**
    242          * Renders a single language item's flag and name HTML fragments.
    243          *
    244          * @param array  $settings             Plugin language switcher settings.
    245          * @param array  $language             Single language entry.
    246          * @param string $flag_dimensions_class CSS class for flag dimensions.
    247          * @param string $name_class           CSS class for the name span.
    248          *
    249          * @return array{flag: string, name: string}
    250          */
    251         private function render_language_parts(array $settings, array $language, string $flag_dimensions_class, string $name_class = 'cl-language-switcher-lan-name'): array {
    252                 $flag_html = '';
    253                 $name_html = '';
    254 
    255                 if (!empty($settings['showFlag'])) {
    256                         $flag_code = esc_attr(strtoupper($language['flag_code']));
    257                         $flag_html = '<i class="cl-language-switcher-lan-flag mr-2 fflag-' . $flag_code
    258                                 . ' fflag ' . esc_attr($flag_dimensions_class) . ' ff-md"></i>';
    259                 }
    260 
    261                 if (!empty($settings['showTargetLanguage'])) {
    262                         $flag_html_safe = esc_html(wp_strip_all_tags($language['display_name']));
    263                         $name_html      = '<span class="' . esc_attr($name_class) . ' notranslate">' . $flag_html_safe . '</span>';
    264                 }
    265 
    266                 return [
    267                         'flag' => $flag_html,
    268                         'name' => $name_html,
    269                 ];
    270         }
    271 
    272         /**
    273          * Renders the chevron SVG icon.
    274          *
    275          * @param string $type 'up' for traditional menu, 'down' for block/shortcode.
    276          * @return string
    277          */
    278         private function render_chevron_svg(string $type = 'up'): string {
    279                 if ($type === 'down') {
    280                         return '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true" focusable="false">'
    281                                 . '<path d="M1.50002 4L6.00002 8L10.5 4" stroke-width="1.5"></path>'
    282                                 . '</svg>';
    283                 }
    284 
    285                 return '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 1.25rem;" class="clonable-rotate">'
    286                         . '<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5"></path>'
    287                         . '</svg>';
    288         }
    289 
    290         /**
    291          * Renders the traditional/shortcode menu HTML.
    292          *
    293          * @param array  $settings             Language switcher settings.
    294          * @param array  $menu_languages       Array of language data.
    295          * @param string $flag_dimensions_class CSS class for flag shape.
    296          * @param string $context              'traditional_menu' or 'shortcode'.
    297          *
    298          * @return string
    299          */
    300         private function render_traditional_menu(array $settings, array $menu_languages, string $flag_dimensions_class, string $context): string {
    301                 $li_classes   = esc_attr(self::MENU_ITEM_LI_CLASS . ' menu-item-has-children');
    302                 $a_class      = esc_attr(self::MENU_ITEM_CLASS);
    303                 $toggle_label = 'Languages';
    304 
    305                 $html  = '<li data-loading class="' . $li_classes . '">';
    306                 $html .= '<a href="#" rel="nofollow" role="button" class="' . $a_class . '"'
    307                         . ' aria-haspopup="true" aria-expanded="false">'
    308                         . $toggle_label
    309                         . '</a>';
    310 
    311                 $html .= '<ul class="sub-menu">';
    312 
    313                 foreach ($menu_languages as $language) {
    314 
    315                         $parts = $this->render_language_parts($settings, $language, $flag_dimensions_class);
    316 
    317                         if ($parts['flag'] === '' && $parts['name'] === '') {
    318                                 continue;
    319                         }
    320 
    321                         $href         = esc_url($language['href'] ?? '#');
    322                         $hreflang     = esc_attr($language['locale']);
    323                         $href_encoded = isset($language['href']) ? esc_attr(base64_encode($language['href'])) : '';
    324 
    325                         $html .= '<li class="menu-item cl-language-switcher-menu-item">'
    326                                 . '<a class="cl-language-switcher-link" href="' . $href . '"'
    327                                 . ' hreflang="' . $hreflang . '"'
    328                                 . ' data-href-encoded="' . $href_encoded . '">'
    329                                 . '<span class="cl-language-switcher-lan-container">'
    330                                 . $parts['flag']
    331                                 . $parts['name']
    332                                 . '</span></a>'
    333                                 . '</li>';
    334                 }
    335 
    336                 $html .= '</ul>';
    337                 $html .= '</li>';
    338 
    339                 return $html;
    340         }
    341 
    342         /**
    343          * Renders the block-based navigation submenu HTML.
    344          *
    345          * @param array  $settings             Language switcher settings.
    346          * @param array  $menu_languages       Array of language data.
    347          * @param string $flag_dimensions_class CSS class for flag shape.
    348          *
    349          * @return string
    350          */
    351         private function render_block_submenu(array $settings, array $menu_languages, string $flag_dimensions_class): string {
    352                 $toggle_label = 'Languages';
    353 
    354                 $wp_context = esc_attr(
    355                         json_encode(
    356                                 [
    357                                         'submenuOpenedBy' => [
    358                                                 'click' => false,
    359                                                 'hover' => true,
    360                                                 'focus' => false,
    361                                         ],
    362                                         'type'            => 'submenu',
    363                                         'modal'           => null,
    364                                         'previousFocus'   => null,
    365                                 ],
    366                                 JSON_UNESCAPED_SLASHES
    367                         )
    368                 );
    369 
    370                 $html = '<li'
    371                         . ' data-wp-context=\'' . $wp_context . '\''
    372                         . ' data-wp-interactive="core/navigation"'
    373                         . ' data-wp-on--focusout="actions.handleMenuFocusout"'
    374                         . ' data-wp-on--keydown="actions.handleMenuKeydown"'
    375                         . ' data-wp-on--mouseenter="actions.openMenuOnHover"'
    376                         . ' data-wp-on--mouseleave="actions.closeMenuOnHover"'
    377                         . ' data-wp-watch="callbacks.initMenu"'
    378                         . ' tabindex="-1"'
    379                         . ' class="wp-block-navigation-item has-child open-on-hover-click wp-block-navigation-submenu clonable-language-switcher-block-submenu-item"'
    380                         . ' data-loading>';
    381 
    382                 $html .= '<a class="wp-block-navigation-item__content">'
    383                         . '<span class="wp-block-navigation-item__label">' . esc_html($toggle_label) . '</span>'
    384                         . '</a>';
    385 
    386                 $html .= '<button'
    387                         . ' data-wp-bind--aria-expanded="state.isMenuOpen"'
    388                         . ' data-wp-on--click="actions.toggleMenuOnClick"'
    389                         . ' aria-label="' . esc_attr($toggle_label . ' submenu') . '"'
    390                         . ' class="wp-block-navigation__submenu-icon wp-block-navigation-submenu__toggle"'
    391                         . ' aria-expanded="false">'
    392                         . $this->render_chevron_svg('down')
    393                         . '</button>';
    394 
    395                 $html .= '<ul data-wp-on--focus="actions.openMenuOnFocus"'
    396                         . ' class="wp-block-navigation__submenu-container wp-block-navigation-submenu clonable-language-switcher-block-submenu">';
    397 
    398                 foreach ($menu_languages as $language) {
    399                         $parts = $this->render_language_parts(
    400                                 $settings,
    401                                 $language,
    402                                 $flag_dimensions_class,
    403                                 'wp-block-navigation-item__label'
    404                         );
    405 
    406                         if ($parts['flag'] === '' && $parts['name'] === '') {
    407                                 continue;
    408                         }
    409 
    410                         $href         = esc_url($language['href'] ?? '#');
    411                         $hreflang     = esc_attr($language['locale']);
    412                         $href_encoded = isset($language['href']) ? esc_attr(base64_encode($language['href'])) : '';
    413 
    414                         $html .= '<li class="wp-block-navigation-item wp-block-navigation-link">'
    415                                 . '<a class="wp-block-navigation-item__content cl-language-switcher-link"'
    416                                 . ' href="' . $href . '"'
    417                                 . ' hreflang="' . $hreflang . '"'
    418                                 . ' data-href-encoded="' . $href_encoded . '">'
    419                                 . $parts['flag']
    420                                 . $parts['name']
    421                                 . '</a>'
    422                                 . '</li>';
    423                 }
    424 
    425                 $html .= '</ul>';
    426                 $html .= '</li>';
    427 
    428                 return $html;
    429         }
    430 
    431         /**
    432          * Renders a fallback empty language switcher item.
    433          *
    434          * @return string
    435          */
    436         private function render_fallback_item(): string {
    437                 return '<li class="' . esc_attr(self::MENU_ITEM_LI_CLASS) . '">'
    438                         . '<div class="' . esc_attr(self::MENU_ITEM_CLASS) . '"></div>'
    439                         . '</li>';
    440         }
    441 
    442         /**
    443          * Adds the language switcher to block-based navigation (core/navigation-submenu).
    444          *
    445          * @param string $block_content The rendered block content.
    446          * @param array  $block         The parsed block data.
    447          *
    448          * @return string
    449          */
    450         public function submenu_block_language_switcher(string $block_content, array $block): string {
    451                 if ($block['blockName'] !== 'core/navigation-submenu') {
    452                         return $block_content;
    453                 }
    454 
    455                 $attrs = $block['attrs'] ?? [];
    456 
    457                 $block_class = $attrs['className'] ?? '';
    458                 // Only render the language switcher in submenu blocks that have the 'clonable-language-switcher' class, to avoid affecting all submenu blocks and allow users to choose where to display the switcher. This also prevents potential issues with duplicate IDs or classes if multiple submenu blocks are used.
    459                 if (!$block_class || strpos($block_class, 'clonable-language-switcher') === false) {
    460                         return $block_content;
    461                 }
    462 
    463                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    464 
    465                 // Build the language switcher HTML using the same method, passing empty items and args
    466                 $output = $this->build_language_switcher($plugin_language_switcher_settings, '', new stdClass(), 'block_menu_submenu');
    467 
    468                 if (!$output) {
    469                         return $block_content;
    470                 }
    471 
    472                 // replace the whole content of the submenu block with the switcher, without worrying about the existing content, as the submenu block is meant to only contain the language switcher in this case. This also avoids issues with trying to merge the switcher with existing content and potential duplicate IDs or classes. Make sure the block still functions correctly as a submenu with the necessary classes for styling and functionality.
    473                 return $output;
    474         }
    475 
    476         /*
    477         ------------------------------------------------------------------ */
    478         /*
    479                 Native WordPress Menu Item (Appearance → Menus)                   */
    480         /*
    481         ------------------------------------------------------------------ */
    482         /*
    483          * Register a meta box on the WordPress Menus page (Appearance → Menus)
    484          * so users can add a Language Switcher as a regular, positionable menu item.
    485          */
    486         public function register_nav_menu_meta_box(): void {
    487                 add_meta_box(
    488                         'clonable-language-switcher',
    489                         'Clonable Language Switcher',
    490                         [$this, 'render_nav_menu_meta_box'],
    491                         'nav-menus',
    492                         'side',
    493                         'default'
    494                 );
    495         }
    496 
    497         /**
    498          * Render the meta box content that lets users add the language switcher to a menu.
    499          */
    500         public function render_nav_menu_meta_box(): void {
    501                 global $_nav_menu_placeholder;
    502                 $_nav_menu_placeholder = $_nav_menu_placeholder < -1 ? $_nav_menu_placeholder - 1 : -1;
    503                 ?>
     126    }
     127
     128    /**
     129     * Appends the language switcher item to a specific menu (by menu slug).
     130     *
     131     * @param array    $plugin_language_switcher_settings Language switcher settings.
     132     * @param string   $items      The HTML list content for the menu items.
     133     * @param stdClass $menu_args  An object containing wp_nav_menu() arguments.
     134     * @param string   $context    Render context: 'traditional_menu', 'block_menu_submenu', or 'shortcode'.
     135     *
     136     * @return string
     137     */
     138    public function build_language_switcher(array $plugin_language_switcher_settings, $items, $menu_args, string $context): string
     139    {
     140        if (empty($plugin_language_switcher_settings)) {
     141            return $items;
     142        }
     143
     144        $menu_languages = $this->build_menu_languages($plugin_language_switcher_settings);
     145
     146        if (empty($menu_languages)) {
     147            return $items . $this->render_fallback_item();
     148        }
     149
     150        $flag_dimensions_class = $this->get_flag_dimensions_class($plugin_language_switcher_settings);
     151
     152        $html = match ($context) {
     153            'shortcode' => $this->render_traditional_menu($plugin_language_switcher_settings, $menu_languages, $flag_dimensions_class, $context),
     154            'block_menu_submenu' => $this->render_block_submenu($plugin_language_switcher_settings, $menu_languages, $flag_dimensions_class),
     155            default => '',
     156        };
     157
     158        if ($html === '') {
     159            $html = $this->render_fallback_item();
     160        }
     161
     162        return $items . $html;
     163    }
     164
     165    /**
     166     * Returns the CSS class for flag dimensions based on settings.
     167     *
     168     * @param array $settings Language switcher settings.
     169     * @return string
     170     */
     171    private function get_flag_dimensions_class(array $settings): string
     172    {
     173        return !empty($settings['roundedFlag']) ? 'ff-rounded' : 'ff-rectangle';
     174    }
     175
     176    /**
     177     * Returns the current request path.
     178     *
     179     * @return string
     180     */
     181    private function get_request_path(): string
     182    {
     183        return parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
     184    }
     185
     186    /**
     187     * Builds the array of menu languages with translated URLs.
     188     *
     189     * @param array $settings Language switcher settings.
     190     * @return array
     191     */
     192    private function build_menu_languages(array $settings): array
     193    {
     194        $menu_languages = $this->get_language_switcher_languages();
     195
     196        // Resolve display names from settings
     197        $languages_map = $this->parse_languages_setting($settings['languages'] ?? '[]');
     198
     199        foreach ($menu_languages as &$lang) {
     200            // in case country code is enabled, we want to show the country code instead of the language name.
     201            // We can determine the country code by taking the display region of the locale code.
     202            // For example, if the locale code is en_US, we want to show US as the country code.
     203            if (!empty($settings['showCountry'])) {
     204                $lang['display_name'] = $lang['flag_code'];
     205                continue;
     206            }
     207
     208            $lang['display_name'] = $languages_map[$lang['lang_code']] ?? $lang['lang_code'];
     209        }
     210
     211        unset($lang);
     212        return $menu_languages;
     213    }
     214
     215    /**
     216     * Parses the languages setting JSON into a lang_code => display_name map.
     217     *
     218     * @param mixed $languages_setting JSON string or array.
     219     * @return array<string, string>
     220     */
     221    private function parse_languages_setting($languages_setting): array
     222    {
     223        try {
     224            if (is_array($languages_setting)) {
     225                $json = json_encode($languages_setting);
     226            } else {
     227                $json = (string) $languages_setting;
     228            }
     229
     230            $json = str_replace('U+002E', '.', $json);
     231            $arr  = json_decode($json, true);
     232
     233            if (!is_array($arr)) {
     234                return [];
     235            }
     236
     237            $map = [];
     238            foreach ($arr as $entry) {
     239                if (is_array($entry)
     240                    && isset($entry['clonableLocaleCode'], $entry['clonableDisplayLanguage'])
     241                ) {
     242                    $map[ (string) $entry['clonableLocaleCode']] = (string) $entry['clonableDisplayLanguage'];
     243                }
     244            }
     245
     246            return $map;
     247        } catch (Throwable) {
     248            return [];
     249        }
     250    }
     251
     252    /**
     253     * Renders a single language item's flag and name HTML fragments.
     254     *
     255     * @param array  $settings             Plugin language switcher settings.
     256     * @param array  $language             Single language entry.
     257     * @param string $flag_dimensions_class CSS class for flag dimensions.
     258     * @param string $name_class           CSS class for the name span.
     259     *
     260     * @return array{flag: string, name: string}
     261     */
     262    private function render_language_parts(array $settings, array $language, string $flag_dimensions_class, string $name_class = 'cl-language-switcher-lan-name'): array
     263    {
     264        $flag_html = '';
     265        $name_html = '';
     266
     267        if (!empty($settings['showFlag'])) {
     268            $flag_code = esc_attr(strtoupper($language['flag_code']));
     269            $flag_html = '<i class="cl-language-switcher-lan-flag mr-2 fflag-' . $flag_code
     270                . ' fflag ' . esc_attr($flag_dimensions_class) . ' ff-md"></i>';
     271        }
     272
     273        if (!empty($settings['showTargetLanguage'])) {
     274            $flag_html_safe = esc_html(wp_strip_all_tags($language['display_name']));
     275            $name_html      = '<span class="' . esc_attr($name_class) . ' notranslate">' . $flag_html_safe . '</span>';
     276        }
     277
     278        return [
     279            'flag' => $flag_html,
     280            'name' => $name_html,
     281        ];
     282    }
     283
     284    /**
     285     * Renders the chevron SVG icon.
     286     *
     287     * @param string $type 'up' for traditional menu, 'down' for block/shortcode.
     288     * @return string
     289     */
     290    private function render_chevron_svg(string $type = 'up'): string
     291    {
     292        if ($type === 'down') {
     293            return '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true" focusable="false">'
     294                . '<path d="M1.50002 4L6.00002 8L10.5 4" stroke-width="1.5"></path>'
     295                . '</svg>';
     296        }
     297
     298        return '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 1.25rem;" class="clonable-rotate">'
     299            . '<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5"></path>'
     300            . '</svg>';
     301    }
     302
     303    /**
     304     * Renders the traditional/shortcode menu HTML.
     305     *
     306     * @param array  $settings             Language switcher settings.
     307     * @param array  $menu_languages       Array of language data.
     308     * @param string $flag_dimensions_class CSS class for flag shape.
     309     * @param string $context              'traditional_menu' or 'shortcode'.
     310     *
     311     * @return string
     312     */
     313    private function render_traditional_menu(array $settings, array $menu_languages, string $flag_dimensions_class, string $context): string
     314    {
     315        $li_classes   = esc_attr(self::MENU_ITEM_LI_CLASS . ' menu-item-has-children');
     316        $a_class      = esc_attr(self::MENU_ITEM_CLASS);
     317        $toggle_label = 'Languages';
     318
     319        $html  = '<li data-loading class="' . $li_classes . '">';
     320        $html .= '<a href="#" rel="nofollow" role="button" class="' . $a_class . '"'
     321            . ' aria-haspopup="true" aria-expanded="false">'
     322            . $toggle_label
     323            . '</a>';
     324
     325        $html .= '<ul class="sub-menu">';
     326
     327        foreach ($menu_languages as $language) {
     328
     329            $parts = $this->render_language_parts($settings, $language, $flag_dimensions_class);
     330
     331            if ($parts['flag'] === '' && $parts['name'] === '') {
     332                continue;
     333            }
     334
     335            $href         = esc_url($language['href'] ?? '#');
     336            $hreflang     = esc_attr($language['locale']);
     337            $href_encoded = isset($language['href']) ? esc_attr(base64_encode($language['href'])) : '';
     338
     339            $html .= '<li class="menu-item cl-language-switcher-menu-item">'
     340                . '<a class="cl-language-switcher-link" href="' . $href . '"'
     341                . ' hreflang="' . $hreflang . '"'
     342                . ' data-href-encoded="' . $href_encoded . '">'
     343                . '<span class="cl-language-switcher-lan-container">'
     344                . $parts['flag']
     345                . $parts['name']
     346                . '</span></a>'
     347                . '</li>';
     348        }
     349
     350        $html .= '</ul>';
     351        $html .= '</li>';
     352
     353        return $html;
     354    }
     355
     356    /**
     357     * Renders the block-based navigation submenu HTML.
     358     *
     359     * @param array  $settings             Language switcher settings.
     360     * @param array  $menu_languages       Array of language data.
     361     * @param string $flag_dimensions_class CSS class for flag shape.
     362     *
     363     * @return string
     364     */
     365    private function render_block_submenu(array $settings, array $menu_languages, string $flag_dimensions_class): string
     366    {
     367        $toggle_label = 'Languages';
     368
     369        $wp_context = esc_attr(
     370            json_encode(
     371                [
     372                    'submenuOpenedBy' => [
     373                        'click' => false,
     374                        'hover' => true,
     375                        'focus' => false,
     376                    ],
     377                    'type'            => 'submenu',
     378                    'modal'           => null,
     379                    'previousFocus'   => null,
     380                ],
     381                JSON_UNESCAPED_SLASHES
     382            )
     383        );
     384
     385        $html = '<li'
     386            . ' data-wp-context=\'' . $wp_context . '\''
     387            . ' data-wp-interactive="core/navigation"'
     388            . ' data-wp-on--focusout="actions.handleMenuFocusout"'
     389            . ' data-wp-on--keydown="actions.handleMenuKeydown"'
     390            . ' data-wp-on--mouseenter="actions.openMenuOnHover"'
     391            . ' data-wp-on--mouseleave="actions.closeMenuOnHover"'
     392            . ' data-wp-watch="callbacks.initMenu"'
     393            . ' tabindex="-1"'
     394            . ' class="wp-block-navigation-item has-child open-on-hover-click wp-block-navigation-submenu clonable-language-switcher-block-submenu-item"'
     395            . ' data-loading>';
     396
     397        $html .= '<a class="wp-block-navigation-item__content">'
     398            . '<span class="wp-block-navigation-item__label">' . esc_html($toggle_label) . '</span>'
     399            . '</a>';
     400
     401        $html .= '<button'
     402            . ' data-wp-bind--aria-expanded="state.isMenuOpen"'
     403            . ' data-wp-on--click="actions.toggleMenuOnClick"'
     404            . ' aria-label="' . esc_attr($toggle_label . ' submenu') . '"'
     405            . ' class="wp-block-navigation__submenu-icon wp-block-navigation-submenu__toggle"'
     406            . ' aria-expanded="false">'
     407            . $this->render_chevron_svg('down')
     408            . '</button>';
     409
     410        $html .= '<ul data-wp-on--focus="actions.openMenuOnFocus"'
     411            . ' class="wp-block-navigation__submenu-container wp-block-navigation-submenu clonable-language-switcher-block-submenu">';
     412
     413        foreach ($menu_languages as $language) {
     414            $parts = $this->render_language_parts(
     415                $settings,
     416                $language,
     417                $flag_dimensions_class,
     418                'wp-block-navigation-item__label'
     419            );
     420
     421            if ($parts['flag'] === '' && $parts['name'] === '') {
     422                continue;
     423            }
     424
     425            $href         = esc_url($language['href'] ?? '#');
     426            $hreflang     = esc_attr($language['locale']);
     427            $href_encoded = isset($language['href']) ? esc_attr(base64_encode($language['href'])) : '';
     428
     429            $html .= '<li class="wp-block-navigation-item wp-block-navigation-link">'
     430                . '<a class="wp-block-navigation-item__content cl-language-switcher-link"'
     431                . ' href="' . $href . '"'
     432                . ' hreflang="' . $hreflang . '"'
     433                . ' data-href-encoded="' . $href_encoded . '">'
     434                . $parts['flag']
     435                . $parts['name']
     436                . '</a>'
     437                . '</li>';
     438        }
     439
     440        $html .= '</ul>';
     441        $html .= '</li>';
     442
     443        return $html;
     444    }
     445
     446    /**
     447     * Renders a fallback empty language switcher item.
     448     *
     449     * @return string
     450     */
     451    private function render_fallback_item(): string
     452    {
     453        return '<li class="' . esc_attr(self::MENU_ITEM_LI_CLASS) . '">'
     454            . '<div class="' . esc_attr(self::MENU_ITEM_CLASS) . '"></div>'
     455            . '</li>';
     456    }
     457
     458    /**
     459     * Adds the language switcher to block-based navigation (core/navigation-submenu).
     460     *
     461     * @param string $block_content The rendered block content.
     462     * @param array  $block         The parsed block data.
     463     *
     464     * @return string
     465     */
     466    public function submenu_block_language_switcher(string $block_content, array $block): string
     467    {
     468        if ($block['blockName'] !== 'core/navigation-submenu') {
     469            return $block_content;
     470        }
     471
     472        $attrs = $block['attrs'] ?? [];
     473
     474        $block_class = $attrs['className'] ?? '';
     475        // Only render the language switcher in submenu blocks that have the 'clonable-language-switcher' class, to avoid affecting all submenu blocks and allow users to choose where to display the switcher. This also prevents potential issues with duplicate IDs or classes if multiple submenu blocks are used.
     476        if (!$block_class || strpos($block_class, 'clonable-language-switcher') === false) {
     477            return $block_content;
     478        }
     479
     480        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     481
     482        // Build the language switcher HTML using the same method, passing empty items and args
     483        $output = $this->build_language_switcher($plugin_language_switcher_settings, '', new stdClass(), 'block_menu_submenu');
     484
     485        if (!$output) {
     486            return $block_content;
     487        }
     488
     489        // replace the whole content of the submenu block with the switcher, without worrying about the existing content, as the submenu block is meant to only contain the language switcher in this case. This also avoids issues with trying to merge the switcher with existing content and potential duplicate IDs or classes. Make sure the block still functions correctly as a submenu with the necessary classes for styling and functionality.
     490        return $output;
     491    }
     492
     493    /*
     494    ------------------------------------------------------------------ */
     495    /*
     496        Native WordPress Menu Item (Appearance → Menus)                   */
     497    /*
     498    ------------------------------------------------------------------ */
     499    /*
     500     * Register a meta box on the WordPress Menus page (Appearance → Menus)
     501     * so users can add a Language Switcher as a regular, positionable menu item.
     502     */
     503    public function register_nav_menu_meta_box(): void
     504    {
     505        add_meta_box(
     506            'clonable-language-switcher',
     507            'Clonable Language Switcher',
     508            [$this, 'render_nav_menu_meta_box'],
     509            'nav-menus',
     510            'side',
     511            'default'
     512        );
     513    }
     514
     515    /**
     516     * Render the meta box content that lets users add the language switcher to a menu.
     517     */
     518    public function render_nav_menu_meta_box(): void
     519    {
     520        global $_nav_menu_placeholder;
     521        $_nav_menu_placeholder = $_nav_menu_placeholder < -1 ? $_nav_menu_placeholder - 1 : -1;
     522        ?>
    504523                <div id="clonable-language-switcher-div" class="posttypediv">
    505524                        <div id="tabs-panel-clonable-language-switcher" class="tabs-panel tabs-panel-active">
    … …  
    537556                </div>
    538557                <?php
    539         }
    540 
    541         /**
    542          * Detect the Clonable Language Switcher placeholder in the menu and
    543          * dynamically inject child menu items for each available language.
    544          *
    545          * Hooked into wp_nav_menu_objects so the theme's walker renders
    546          * the dropdown natively (the theme controls the sub-menu styling).
    547          *
    548          * @param array    $sorted_menu_items The menu items, sorted.
    549          * @param stdClass $args              An object containing wp_nav_menu() arguments.
    550          * @return array
    551          * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu/
    552          * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
    553          * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/
    554          * @see https://developer.wordpress.org/reference/classes/walker_nav_menu/ for how the menu items are rendered after we inject our language items here.
    555          */
    556         public function inject_language_menu_items(array $sorted_menu_items, stdClass $args): array {
    557                 // this should work for all menu locations since we're looking for the placeholder item, but we can also add additional checks here based on $args to only inject into specific menus if needed (similar to the checks in build_language_switcher)
    558 
    559                 $switcher_item = null;
    560 
    561                 foreach ($sorted_menu_items as $item) {
    562                         if ($item->url === '#clonable-language-switcher' ||
    563                                 (is_array($item->classes) && in_array('clonable-language-switcher', $item->classes, true))
    564                         ) {
    565                                 $switcher_item = $item;
    566                                 break;
    567                         }
    568                 }
    569 
    570                 if ($switcher_item === null) {
    571                         return $sorted_menu_items;
    572                 }
    573 
    574                 // Mark the parent so the theme's walker renders a sub-menu container
    575                 $switcher_item->classes[] = 'menu-item-has-children';
    576                 $switcher_item->classes[] = 'clonable-menu-item-language-switcher';
    577                 $switcher_item->url       = '#';
    578 
    579                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    580 
    581                 $menu_languages = $this->build_menu_languages($plugin_language_switcher_settings);
    582 
    583                 if (empty($menu_languages)) {
    584                         return $sorted_menu_items;
    585                 }
    586 
    587                 $counter = 900000; // high ID range to avoid collisions
    588 
    589                 foreach ($menu_languages as $menu_language) {
    590                         $display_name                 = $menu_language['display_name'] ?? $menu_language['lang_code'];
    591                         $child                        = new stdClass();
    592                         $child->ID                    = $counter;
    593                         $child->db_id                 = $counter;
    594                         $child->menu_item_parent      = $switcher_item->ID;
    595                         $child->object_id             = $counter;
    596                         $child->object                = 'custom';
    597                         $child->type                  = 'custom';
    598                         $child->type_label            = ''; // can be customized if needed, it adds a label in the admin menu editor, but since this is a dynamic item we can leave it empty or set it to something like 'Language Switcher Item'
    599                         $child->title                 = $display_name;
    600                         $child->url                   = $menu_language['href'] ?? '#';
    601                         $child->target                = '_self';  // can be customized if needed, e.g. '_blank' to open in new tab
    602                         $child->attr_title            = $display_name;
    603                         $child->description           = ''; // adds a title attribute to the link with the display name, can be customized if needed
    604                         $child->classes               = ['menu-item', 'cl-language-switcher-menu-item', 'clonable-language-item'];
    605                         $child->xfn                   = ''; // can be customized if needed, it adds a rel attribute to the link, e.g. rel="alternate" for language switcher items, but some themes may use it for other purposes so leaving it empty for now
    606                         $child->current               = false;
    607                         $child->current_item_ancestor = false;
    608                         $child->current_item_parent   = $switcher_item->ID;
    609                         $child->menu_order            = $counter;
    610                         $child->post_type             = 'nav_menu_item';
    611                         $child->post_status           = 'publish'; // the menu editor only shows items with 'publish' status, but since these are dynamic items we can set it to whatever, it won't affect the menu editor since these items don't exist in the database, but setting it to 'publish' can help with debugging and compatibility with themes that check for post_status when rendering menu items, even though it's not strictly necessary since these items are not stored in the database
    612 
    613                         // Custom properties consumed by customize_language_menu_item_output()
    614 
    615                         $child->clonable_lang_code    = $menu_language['lang_code'];
    616                         $child->clonable_flag_code    = $menu_language['flag_code'];
    617                         $child->clonable_locale       = $menu_language['locale'] ?? str_replace('_', '-', $menu_language['lang_code']);
    618                         $child->clonable_href_encoded = isset($menu_language['href']) ? base64_encode($menu_language['href']) : '';
    619 
    620                         $sorted_menu_items[] = $child;
    621                         ++$counter;
    622                 }
    623 
    624                 return $sorted_menu_items;
    625         }
    626 
    627         /**
    628          * Customize the HTML output of injected language child menu items
    629          * to include flag icons, hreflang attributes, and proper styling classes.
    630          *
    631          * @param string   $item_output The menu item's starting HTML output.
    632          * @param object   $menu_item   Menu item data object.
    633          * @param int      $depth       Depth of menu item.
    634          * @param stdClass $args        An object of wp_nav_menu() arguments.
    635          * @return string
    636          */
    637         public function customize_language_menu_item_output(string $item_output, $menu_item, int $depth, $args): string {
    638                 if (!isset($menu_item->clonable_lang_code)) {
    639                         return $item_output;
    640                 }
    641 
    642                 $settings              = $this->get_language_switcher_settings();
    643                 $flag_dimensions_class = $this->get_flag_dimensions_class($settings);
    644 
    645                 $language = [
    646                         'flag_code'    => $menu_item->clonable_flag_code,
    647                         'lang_code'    => $menu_item->clonable_lang_code,
    648                         'display_name' => $menu_item->title,
    649                 ];
    650 
    651                 $parts = $this->render_language_parts($settings, $language, $flag_dimensions_class);
    652 
    653                 $link_html = '<a class="cl-language-switcher-link" href="' . esc_url($menu_item->url)
    654                         . '" hreflang="' . esc_attr($menu_item->clonable_locale)
    655                         . '" data-href-encoded="' . esc_attr($menu_item->clonable_href_encoded)
    656                         . '"><span class="cl-language-switcher-lan-container">'
    657                         . $parts['flag']
    658                         . $parts['name']
    659                         . '</span></a>';
    660 
    661                 // Preserve the existing $args->before / $args->after wrapping if available
    662                 $before = '';
    663                 $after  = '';
    664                 if (is_object($args)) {
    665                         $before = $args->before ?? '';
    666                         $after  = $args->after ?? '';
    667                 }
    668 
    669                 return $before . $link_html . $after;
    670         }
    671 
    672         /**
    673          * Build the array of available languages with translated URLs.
    674          *
    675          * @return array Each element contains lang_code, locale, flag_code, and href.
    676          */
    677         private function get_language_switcher_languages(): array {
    678                 $request_path      = $this->get_request_path();
    679                 $menu_languages    = [];
    680                 $site              = ClonableConfig::get_site();
    681                 $urls_to_translate = [];
    682 
    683                 if (!$site) {
    684                         return [];
    685                 }
    686 
    687                 $clones                = $site->get_clones();
    688                 $locally_set_languages = $this->get_locally_set_languages();
    689 
    690                 // Source URL is never translated; keep it out of the batch.
    691                 $source_match = $this->normalize_href_for_match(rtrim($site->get_url(), '/') . $request_path);
    692 
    693                 // Hide per-post excluded languages (like tags + menus).
    694                 $excluded_lang_codes = ClonableConfig::get_excluded_lang_codes_for_current_post();
    695 
    696                 if ($clones) {
    697                         foreach ($clones as $index => $clone) {
    698                                 if (in_array(strtolower(str_replace('_', '-', $clone['lang_code'])), $excluded_lang_codes, true)) {
    699                                         continue;
    700                                 }
    701 
    702                                 $href = rtrim($site->get_clone_url($index), '/') . $request_path;
    703                                 if ($this->normalize_href_for_match($href) !== $source_match) {
    704                                         $urls_to_translate[] = [
    705                                                 'o' => $href,
    706                                                 'r' => $href,
    707                                         ];
    708                                 }
    709 
    710                                 $menu_languages[$index] = [
    711                                         'lang_code' => $clone['lang_code'],
    712                                         'locale'    => str_replace('_', '-', $clone['lang_code']),
    713                                         'flag_code' => Locales::get_region($clone['lang_code']),
    714                                         'href'      => $href, // default, overwritten if translation succeeds
    715                                 ];
    716                         }
    717                 }
    718 
    719                 if ($locally_set_languages) {
    720                         foreach ($locally_set_languages as $local_lang) {
    721                                 // Avoid duplicates if the locally set language is already included from the clones (matching by lang_code)
    722                                 if (array_search($local_lang->clonableLocaleCode, array_column($menu_languages, 'lang_code')) !== false) {
    723                                         continue;
    724                                 }
    725 
    726                                 $href = rtrim($local_lang->clonableUrl, '/') . $request_path; // default to site URL + request path, translation will be attempted in bulk later
    727 
    728                                 if ($this->normalize_href_for_match($href) !== $source_match) {
    729                                         $urls_to_translate[] = [
    730                                                 'o' => $href,
    731                                                 'r' => $href,
    732                                         ];
    733                                 }
    734 
    735                                 $menu_languages[] = [
    736                                         'lang_code' => $local_lang->clonableLocaleCode,
    737                                         'locale'    => str_replace('_', '-', $local_lang->clonableLocaleCode),
    738                                         'flag_code' => Locales::get_region($local_lang->clonableLocaleCode),
    739                                         'href'      => $href, // default, overwritten if translation succeeds
    740                                 ];
    741                         }
    742                 }
    743 
    744                 // Bulk translate; skip on 404 (default hrefs stay, no scanner API calls).
    745                 // @link https://developer.wordpress.org/reference/functions/is_404/
    746                 if ($urls_to_translate && !is_404()) {
    747                         try {
    748                                 // Use clonable_translate_hrefs() so switcher URLs go through the same
    749                                 // transient cache + debounce as the language tags, instead of a
    750                                 // synchronous API call on every render.
    751                                 $translate_results = UrlTranslator::clonable_translate_hrefs($urls_to_translate);
    752 
    753                                 if ($translate_results) {
    754                                         // Match on the original URL ('o') instead of array index, so a
    755                                         // dropped or reordered API item can never assign a translation to
    756                                         // the wrong language. O(n2), but n is tiny (typically <10).
    757                                         // Compare normalised, so an API echoing the URL with a different
    758                                         // trailing slash or "www." prefix still matches.
    759                                         foreach ($translate_results as $result) {
    760                                                 if (!isset($result['o'], $result['r'])) {
    761                                                         continue;
    762                                                 }
    763                                                 $normalized_original = $this->normalize_href_for_match( (string) $result['o']);
    764                                                 foreach ($menu_languages as $key => $language) {
    765                                                         if (!isset($language['href'])) {
    766                                                                 continue;
    767                                                         }
    768                                                         if ($this->normalize_href_for_match( (string) $language['href']) === $normalized_original) {
    769                                                                 $menu_languages[$key]['href'] = $result['r'];
    770                                                                 break;
    771                                                         }
    772                                                 }
    773                                         }
    774                                 }
    775                         } catch (Throwable) {
    776                                 // Silently fail; default URLs are already set
    777                         }
    778                 }
    779 
    780                 // Append the default/source language, if not set yet in Clonable languages yet. Check based on url
    781                 $source_href            = rtrim($site->get_url(), '/') . $request_path;
    782                 $normalized_source_href = $this->normalize_href_for_match($source_href);
    783 
    784                 $source_url_exists = false;
    785                 foreach ($menu_languages as $language) {
    786                         if (!isset($language['href'])) {
    787                                 continue;
    788                         }
    789 
    790                         if ($this->normalize_href_for_match( (string) $language['href']) === $normalized_source_href) {
    791                                 $source_url_exists = true;
    792                                 break;
    793                         }
    794                 }
    795 
    796                 if (!$source_url_exists) {
    797                         $menu_languages[] = [
    798                                 'lang_code' => $site->get_locale(),
    799                                 'locale'    => str_replace('_', '-', $site->get_locale()),
    800                                 'flag_code' => Locales::get_region($site->get_locale()),
    801                                 'href'      => $source_href,
    802                         ];
    803                 }
    804 
    805                 return $menu_languages;
    806         }
    807 
    808         /**
    809          * Normalise a URL for comparison: ignore the "www." prefix and a trailing slash.
    810          */
    811         private function normalize_href_for_match(string $url): string {
    812                 return untrailingslashit(str_replace('www.', '', $url));
    813         }
    814 
    815         public function get_locally_set_languages(): array {
    816                 $languages = get_option('clonable_langswitch_data', []);
    817                 if ($languages) {
    818                         return json_decode($languages);
    819                 }
    820                 return [];
    821         }
    822 
    823         /**
    824          * Build settings passed to the front-end.
    825          * Uses menu slug instead of theme location.
    826          * Includes legacy menuLocation for backward compatibility if needed.
    827          *
    828          * @return array
    829          */
    830         private function get_language_switcher_settings(): array {
    831                 return [
    832                         'showFlag'             => (get_option('clonable_show_flag', 'on') === 'on') ? 1 : 0,
    833                         'roundedFlag'          => (get_option('clonable_rounded_flag', 'on') === 'on') ? 1 : 0,
    834                         'showTargetLanguage'   => (get_option('clonable_show_text', 'on') === 'on') ? 1 : 0,
    835                         'showCountry'          => (get_option('clonable_show_country_code', 'off') === 'on') ? 1 : 0,
    836                         'backgroundColor'      => get_option('clonable_background_color', '#ffffff'),
    837                         'hoverBackgroundColor' => get_option('clonable_hover_background_color', '#efefef'),
    838                         'languages'            => get_option('clonable_langswitch_data', []),
    839                 ];
    840         }
    841 
    842         public function print_language_switcher(): void {
    843                 $build_language_switcher = get_option('clonable_enable_language_switcher', 'off') === 'on';
    844 
    845                 if ($build_language_switcher) {
    846                         $endpoint = ClonableConfig::MODULES_ENDPOINT;
    847                         echo "<!-- Start Clonable Language Switcher -->\n";
    848                         echo "<script>\n";
    849                         $config = $this->create_clonable_config();
    850                         echo ent2ncr($config);
    851                         echo "</script>\n";
    852                         echo '<script defer src="https://' . esc_attr($endpoint) . "/language-switcher/js/init.js?v=1.2.0\"></script>\n";
    853                         echo "<!-- End Clonable Language Switcher -->\n";
    854                 }
    855         }
    856 
    857         public function language_switcher_shortcode($items = '', $menu_args = ''): string {
    858                 $plugin_language_switcher_settings = $this->get_language_switcher_settings();
    859 
    860                 if (empty($plugin_language_switcher_settings)) {
    861                         error_log('Clonable Language Switcher: Missing settings, cannot render shortcode.');
    862                         return '';
    863                 }
    864 
    865                 // if showFlags and showTargetLanguage are both disabled, don't render the switcher and return early to avoid rendering empty language switcher containers
    866                 if (! (bool) $plugin_language_switcher_settings['showFlag'] && ! (bool) $plugin_language_switcher_settings['showTargetLanguage']) {
    867                         $wp_admin_url = admin_url('admin.php?page=clonable&tab=language-switcher');
    868                         return '<small>Check your <a target="_blank" href="' . $wp_admin_url . '">Clonable Language Switcher settings</a> to display the language switcher.</small>';
    869                 }
    870 
    871                 $submenu = $this->build_language_switcher(
    872                         $plugin_language_switcher_settings,
    873                         is_array($items) ? implode('', $items) : $items,
    874                         $menu_args,
    875                         'shortcode'
    876                 );
    877 
    878                 ob_start();
    879                 ?>
     558    }
     559
     560    /**
     561     * Detect the Clonable Language Switcher placeholder in the menu and
     562     * dynamically inject child menu items for each available language.
     563     *
     564     * Hooked into wp_nav_menu_objects so the theme's walker renders
     565     * the dropdown natively (the theme controls the sub-menu styling).
     566     *
     567     * $args untyped: third-party compatibility. Core passes stdClass, but third-party menu builders
     568     * can call this filter themselves with an array.
     569     *
     570     * @param array               $sorted_menu_items The menu items, sorted.
     571     * @param stdClass|array|null $args              wp_nav_menu() arguments. Unused.
     572     * @return array
     573     * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu/
     574     * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/
     575     * @see https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/
     576     * @see https://developer.wordpress.org/reference/classes/walker_nav_menu/ for how the menu items are rendered after we inject our language items here.
     577     * @link https://developer.wordpress.org/reference/functions/sanitize_title/
     578     */
     579    public function inject_language_menu_items(array $sorted_menu_items, mixed $args = null): array
     580    {
     581        // this should work for all menu locations since we're looking for the placeholder item
     582
     583        $switcher_item = null;
     584
     585        foreach ($sorted_menu_items as $item) {
     586            if ($item->url === '#clonable-language-switcher' ||
     587                (is_array($item->classes) && in_array('clonable-language-switcher', $item->classes, true))
     588            ) {
     589                $switcher_item = $item;
     590                break;
     591            }
     592        }
     593
     594        if ($switcher_item === null) {
     595            return $sorted_menu_items;
     596        }
     597
     598        // Mark the parent so the theme's walker renders a sub-menu container
     599        $switcher_item->classes[] = 'menu-item-has-children';
     600        $switcher_item->classes[] = 'clonable-menu-item-language-switcher';
     601        $switcher_item->url       = '#';
     602
     603        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     604
     605        $menu_languages = $this->build_menu_languages($plugin_language_switcher_settings);
     606
     607        if (empty($menu_languages)) {
     608            return $sorted_menu_items;
     609        }
     610
     611        $counter = 900000; // high ID range to avoid collisions
     612
     613        foreach ($menu_languages as $menu_language) {
     614            $display_name                 = $menu_language['display_name'] ?? $menu_language['lang_code'];
     615            $child                        = new stdClass();
     616            $child->ID                    = $counter;
     617            $child->db_id                 = $counter;
     618            $child->menu_item_parent      = $switcher_item->ID;
     619            $child->object_id             = $counter;
     620            $child->object                = 'custom';
     621            $child->type                  = 'custom';
     622            $child->type_label            = ''; // can be customized if needed, it adds a label in the admin menu editor, but since this is a dynamic item we can leave it empty or set it to something like 'Language Switcher Item'
     623            $child->title                 = $display_name;
     624            $child->url                   = $menu_language['href'] ?? '#';
     625            $child->target                = '_self';  // can be customized if needed, e.g. '_blank' to open in new tab
     626            $child->attr_title            = $display_name;
     627            $child->description           = ''; // adds a title attribute to the link with the display name, can be customized if needed
     628            $child->classes               = ['menu-item', 'cl-language-switcher-menu-item', 'clonable-language-item'];
     629            $child->xfn                   = ''; // can be customized if needed, it adds a rel attribute to the link, e.g. rel="alternate" for language switcher items, but some themes may use it for other purposes so leaving it empty for now
     630            $child->current               = false;
     631            $child->current_item_ancestor = false;
     632            $child->current_item_parent   = $switcher_item->ID;
     633            $child->menu_order            = $counter;
     634            $child->post_name             = sanitize_title('clonable-language-' . $menu_language['lang_code']); // read unguarded by some builders
     635            $child->post_type             = 'nav_menu_item';
     636            $child->post_status           = 'publish'; // the menu editor only shows items with 'publish' status, but since these are dynamic items we can set it to whatever, it won't affect the menu editor since these items don't exist in the database, but setting it to 'publish' can help with debugging and compatibility with themes that check for post_status when rendering menu items, even though it's not strictly necessary since these items are not stored in the database
     637
     638            // Custom properties consumed by customize_language_menu_item_output()
     639
     640            $child->clonable_lang_code    = $menu_language['lang_code'];
     641            $child->clonable_flag_code    = $menu_language['flag_code'];
     642            $child->clonable_locale       = $menu_language['locale'] ?? str_replace('_', '-', $menu_language['lang_code']);
     643            $child->clonable_href_encoded = isset($menu_language['href']) ? base64_encode($menu_language['href']) : '';
     644
     645            $sorted_menu_items[] = $child;
     646            ++$counter;
     647        }
     648
     649        return $sorted_menu_items;
     650    }
     651
     652    /**
     653     * Customize the HTML output of injected language child menu items
     654     * to include flag icons, hreflang attributes, and proper styling classes.
     655     *
     656     * @param string   $item_output The menu item's starting HTML output.
     657     * @param object   $menu_item   Menu item data object.
     658     * @param int      $depth       Depth of menu item.
     659     * @param stdClass $args        An object of wp_nav_menu() arguments.
     660     * @return string
     661     */
     662    public function customize_language_menu_item_output(string $item_output, $menu_item, int $depth, $args): string
     663    {
     664        if (!isset($menu_item->clonable_lang_code)) {
     665            return $item_output;
     666        }
     667
     668        $settings              = $this->get_language_switcher_settings();
     669        $flag_dimensions_class = $this->get_flag_dimensions_class($settings);
     670
     671        $language = [
     672            'flag_code'    => $menu_item->clonable_flag_code,
     673            'lang_code'    => $menu_item->clonable_lang_code,
     674            'display_name' => $menu_item->title,
     675        ];
     676
     677        $parts = $this->render_language_parts($settings, $language, $flag_dimensions_class);
     678
     679        $link_html = '<a class="cl-language-switcher-link" href="' . esc_url($menu_item->url)
     680            . '" hreflang="' . esc_attr($menu_item->clonable_locale)
     681            . '" data-href-encoded="' . esc_attr($menu_item->clonable_href_encoded)
     682            . '"><span class="cl-language-switcher-lan-container">'
     683            . $parts['flag']
     684            . $parts['name']
     685            . '</span></a>';
     686
     687        // Preserve the existing $args->before / $args->after wrapping if available
     688        $before = '';
     689        $after  = '';
     690        if (is_object($args)) {
     691            $before = $args->before ?? '';
     692            $after  = $args->after ?? '';
     693        }
     694
     695        return $before . $link_html . $after;
     696    }
     697
     698    /**
     699     * Build the array of available languages with translated URLs.
     700     *
     701     * @return array Each element contains lang_code, locale, flag_code, and href.
     702     */
     703    private function get_language_switcher_languages(): array
     704    {
     705        $request_path      = $this->get_request_path();
     706        $menu_languages    = [];
     707        $site              = ClonableConfig::get_site();
     708        $urls_to_translate = [];
     709
     710        if (!$site) {
     711            return [];
     712        }
     713
     714        $clones                = $site->get_clones();
     715        $locally_set_languages = $this->get_locally_set_languages();
     716
     717        // Source URL is never translated; keep it out of the batch.
     718        $source_match = $this->normalize_href_for_match(rtrim($site->get_url(), '/') . $request_path);
     719
     720        // Hide per-post excluded languages (like tags + menus).
     721        $excluded_lang_codes = ClonableConfig::get_excluded_lang_codes_for_current_post();
     722
     723        if ($clones) {
     724            foreach ($clones as $index => $clone) {
     725                if (in_array(strtolower(str_replace('_', '-', $clone['lang_code'])), $excluded_lang_codes, true)) {
     726                    continue;
     727                }
     728
     729                $href = rtrim($site->get_clone_url($index), '/') . $request_path;
     730                if ($this->normalize_href_for_match($href) !== $source_match) {
     731                    $urls_to_translate[] = [
     732                        'o' => $href,
     733                        'r' => $href,
     734                    ];
     735                }
     736
     737                $menu_languages[$index] = [
     738                    'lang_code' => $clone['lang_code'],
     739                    'locale'    => str_replace('_', '-', $clone['lang_code']),
     740                    'flag_code' => Locales::get_region($clone['lang_code']),
     741                    'href'      => $href, // default, overwritten if translation succeeds
     742                ];
     743            }
     744        }
     745
     746        if ($locally_set_languages) {
     747            foreach ($locally_set_languages as $local_lang) {
     748                // Avoid duplicates if the locally set language is already included from the clones (matching by lang_code)
     749                if (array_search($local_lang->clonableLocaleCode, array_column($menu_languages, 'lang_code')) !== false) {
     750                    continue;
     751                }
     752
     753                $href = rtrim($local_lang->clonableUrl, '/') . $request_path; // default to site URL + request path, translation will be attempted in bulk later
     754
     755                if ($this->normalize_href_for_match($href) !== $source_match) {
     756                    $urls_to_translate[] = [
     757                        'o' => $href,
     758                        'r' => $href,
     759                    ];
     760                }
     761
     762                $menu_languages[] = [
     763                    'lang_code' => $local_lang->clonableLocaleCode,
     764                    'locale'    => str_replace('_', '-', $local_lang->clonableLocaleCode),
     765                    'flag_code' => Locales::get_region($local_lang->clonableLocaleCode),
     766                    'href'      => $href, // default, overwritten if translation succeeds
     767                ];
     768            }
     769        }
     770
     771        // Bulk translate; skip on 404 (default hrefs stay, no scanner API calls).
     772        // @link https://developer.wordpress.org/reference/functions/is_404/
     773        if ($urls_to_translate && !is_404()) {
     774            try {
     775                // Use clonable_translate_hrefs() so switcher URLs go through the same
     776                // transient cache + debounce as the language tags, instead of a
     777                // synchronous API call on every render.
     778                $translate_results = UrlTranslator::clonable_translate_hrefs($urls_to_translate);
     779
     780                if ($translate_results) {
     781                    // Match on the original URL ('o') instead of array index, so a
     782                    // dropped or reordered API item can never assign a translation to
     783                    // the wrong language. O(n2), but n is tiny (typically <10).
     784                    // Compare normalised, so an API echoing the URL with a different
     785                    // trailing slash or "www." prefix still matches.
     786                    foreach ($translate_results as $result) {
     787                        if (!isset($result['o'], $result['r'])) {
     788                            continue;
     789                        }
     790                        $normalized_original = $this->normalize_href_for_match((string) $result['o']);
     791                        foreach ($menu_languages as $key => $language) {
     792                            if (!isset($language['href'])) {
     793                                continue;
     794                            }
     795                            if ($this->normalize_href_for_match((string) $language['href']) === $normalized_original) {
     796                                $menu_languages[$key]['href'] = $result['r'];
     797                                break;
     798                            }
     799                        }
     800                    }
     801                }
     802            } catch (Throwable) {
     803                // Silently fail; default URLs are already set
     804            }
     805        }
     806
     807        // Append the default/source language, if not set yet in Clonable languages yet. Check based on url
     808        $source_href            = rtrim($site->get_url(), '/') . $request_path;
     809        $normalized_source_href = $this->normalize_href_for_match($source_href);
     810
     811        $source_url_exists = false;
     812        foreach ($menu_languages as $language) {
     813            if (!isset($language['href'])) {
     814                continue;
     815            }
     816
     817            if ($this->normalize_href_for_match((string) $language['href']) === $normalized_source_href) {
     818                $source_url_exists = true;
     819                break;
     820            }
     821        }
     822
     823        if (!$source_url_exists) {
     824            $menu_languages[] = [
     825                'lang_code' => $site->get_locale(),
     826                'locale'    => str_replace('_', '-', $site->get_locale()),
     827                'flag_code' => Locales::get_region($site->get_locale()),
     828                'href'      => $source_href,
     829            ];
     830        }
     831
     832        return $menu_languages;
     833    }
     834
     835    /**
     836     * Normalise a URL for comparison: ignore the "www." prefix and a trailing slash.
     837     */
     838    private function normalize_href_for_match(string $url): string
     839    {
     840        return untrailingslashit(str_replace('www.', '', $url));
     841    }
     842
     843    /**
     844     * Switcher table languages. Broken JSON gives [].
     845     *
     846     * @link https://developer.wordpress.org/reference/functions/get_option/
     847     */
     848    public function get_locally_set_languages(): array
     849    {
     850        return Json::decode_array(get_option('clonable_langswitch_data', []));
     851    }
     852
     853    /**
     854     * Build settings passed to the front-end.
     855     * Uses menu slug instead of theme location.
     856     * Includes legacy menuLocation for backward compatibility if needed.
     857     *
     858     * @return array
     859     */
     860    private function get_language_switcher_settings(): array
     861    {
     862        return [
     863            'showFlag'             => (get_option('clonable_show_flag', 'on') === 'on') ? 1 : 0,
     864            'roundedFlag'          => (get_option('clonable_rounded_flag', 'on') === 'on') ? 1 : 0,
     865            'showTargetLanguage'   => (get_option('clonable_show_text', 'on') === 'on') ? 1 : 0,
     866            'showCountry'          => (get_option('clonable_show_country_code', 'off') === 'on') ? 1 : 0,
     867            'backgroundColor'      => get_option('clonable_background_color', '#ffffff'),
     868            'hoverBackgroundColor' => get_option('clonable_hover_background_color', '#efefef'),
     869            'languages'            => get_option('clonable_langswitch_data', []),
     870        ];
     871    }
     872
     873    public function print_language_switcher(): void
     874    {
     875        $build_language_switcher = get_option('clonable_enable_language_switcher', 'off') === 'on';
     876
     877        if ($build_language_switcher) {
     878            $endpoint = ClonableConfig::MODULES_ENDPOINT;
     879            echo "<!-- Start Clonable Language Switcher -->\n";
     880            echo "<script>\n";
     881            $config = $this->create_clonable_config();
     882            echo ent2ncr($config);
     883            echo "</script>\n";
     884            echo '<script defer src="https://' . esc_attr($endpoint) . "/language-switcher/js/init.js?v=1.2.0\"></script>\n";
     885            echo "<!-- End Clonable Language Switcher -->\n";
     886        }
     887    }
     888
     889    public function language_switcher_shortcode($items = '', $menu_args = ''): string
     890    {
     891        $plugin_language_switcher_settings = $this->get_language_switcher_settings();
     892
     893        if (empty($plugin_language_switcher_settings)) {
     894            error_log('Clonable Language Switcher: Missing settings, cannot render shortcode.');
     895            return '';
     896        }
     897
     898        // if showFlags and showTargetLanguage are both disabled, don't render the switcher and return early to avoid rendering empty language switcher containers
     899        if (! (bool) $plugin_language_switcher_settings['showFlag'] && ! (bool) $plugin_language_switcher_settings['showTargetLanguage']) {
     900            $wp_admin_url = admin_url('admin.php?page=clonable&tab=language-switcher');
     901            return '<small>Check your <a target="_blank" href="' . $wp_admin_url . '">Clonable Language Switcher settings</a> to display the language switcher.</small>';
     902        }
     903
     904        $submenu = $this->build_language_switcher(
     905            $plugin_language_switcher_settings,
     906            is_array($items) ? implode('', $items) : $items,
     907            $menu_args,
     908            'shortcode'
     909        );
     910
     911        ob_start();
     912        ?>
    880913                <!-- Start Clonable Language Switcher -->
    881914                <div data-loading class="clonable-language-navigation clonable-language-switcher-shortcode">
    … …  
    886919                <!-- End Clonable Language Switcher -->
    887920                <?php
    888                         return ob_get_clean() ?: '';
    889         }
    890 
    891         private function create_clonable_config() {
    892                 // Display information
    893                 $show_flag            = (get_option('clonable_show_flag', 'on') === 'on') ? 1 : 0;
    894                 $rounded_flag         = (get_option('clonable_rounded_flag', 'on') === 'on') ? 1 : 0;
    895                 $show_target_language = (get_option('clonable_show_text', 'on') === 'on') ? 1 : 0;
    896                 // Colors
    897                 $background_color       = get_option('clonable_background_color', '#ffffff');
    898                 $hover_background_color = get_option('clonable_hover_background_color', '#efefef');
    899                 // Placement and size
    900                 $size      = get_option('clonable_size', 'md');
    901                 $position  = get_option('clonable_position', 'bottom-left');
    902                 $languages = get_option('clonable_langswitch_data', []);
    903                 $languages = str_replace('.', 'U+002E', $languages);
    904 
    905                 return "
     921            return ob_get_clean() ?: '';
     922    }
     923
     924    private function create_clonable_config()
     925    {
     926        // Display information
     927        $show_flag            = (get_option('clonable_show_flag', 'on') === 'on') ? 1 : 0;
     928        $rounded_flag         = (get_option('clonable_rounded_flag', 'on') === 'on') ? 1 : 0;
     929        $show_target_language = (get_option('clonable_show_text', 'on') === 'on') ? 1 : 0;
     930        // Colors
     931        $background_color       = get_option('clonable_background_color', '#ffffff');
     932        $hover_background_color = get_option('clonable_hover_background_color', '#efefef');
     933        // Placement and size
     934        $size      = get_option('clonable_size', 'md');
     935        $position  = get_option('clonable_position', 'bottom-left');
     936        $languages = get_option('clonable_langswitch_data', []);
     937        $languages = str_replace('.', 'U+002E', $languages);
     938
     939        return "
    906940            const clonableLSC = {
    907941                'backgroundColor': '$background_color',
    … …  
    922956            }
    923957        ";
    924         }
     958    }
    925959}
  • clonable/trunk/services/SearchEngineService.php

    r3698112 r3746021  
    273273    /**
    274274     * Enqueue front-end search assets (styles, fuse.js and clonable-search.js).
     275     * Skipped on the main site when the widget is clones-only: nothing to drive.
    275276     *
    276277     * @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/
    277278     * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
    278      * @link https://developer.wordpress.org/reference/functions/plugin_dir_url/
     279     * @link https://developer.wordpress.org/reference/functions/wp_localize_script/
    279280     * @link https://developer.wordpress.org/reference/functions/get_option/
    280281     */
    281282    public function clonable_include_search_assets()
    282283    {
     284        if ($this->search_only_on_clones() && !Functions::is_clone()) {
     285            return;
     286        }
    283287
    284288        if (get_option('clonable_search_widget_disable_default_styles', 'off') !== 'on') {
    … …  
    324328            'clonable-search',
    325329            CLONABLE_URL . 'assets/js/clonable-search.js',
    326             ['jquery', 'fuse'],
     330            ['fuse'],
    327331            CLONABLE_VERSION,
    328332            true
    … …  
    594598     * [clonable_search_widget] shortcode: renders the input and a row <template> that
    595599     * clonable-search.js clones per result. Visible fields follow the saved options.
    596      */
    597     public function clonable_search_widget()
    598     {
     600     *
     601     * @link https://developer.wordpress.org/reference/functions/add_shortcode/
     602     * @link https://developer.wordpress.org/reference/functions/get_option/
     603     */
     604    public function clonable_search_widget(): string
     605    {
     606        /* Don't show the search widget on the main site if the option is enabled */
     607        if ($this->search_only_on_clones() && !Functions::is_clone()) {
     608            return '';
     609        }
     610
    599611        // Which result fields to render. An empty/unsaved option means "show
    600612        // everything" so fresh installs don't render a blank search widget.
    … …  
    611623
    612624        $placeholder = (string) get_option('clonable_search_placeholder_text', 'Search...');
    613 
    614         /* Don't show the search widget on the main site if the option is enabled */
    615         if ($this->search_only_on_clones() && !Functions::is_clone()) {
    616             return;
    617         }
    618625
    619626        ob_start();
    … …  
    658665                </div>
    659666<?php
    660                 return ob_get_clean();
     667                return (string) ob_get_clean();
    661668    }
    662669
    … …  
    9981005
    9991006            if ($attribute->is_taxonomy()) {
     1007                // get_terms(): null when the pa_* taxonomy is gone.
    10001008                $attributes[$attribute->get_name()] = array_map(
    10011009                    fn ($term) => $term->name,
    1002                     $attribute->get_terms()
     1010                    $attribute->get_terms() ?? []
    10031011                );
    10041012            } else {
  • clonable/trunk/services/SearchIndexMerger.php

    r3719175 r3746021  
    7373                        }
    7474                        foreach ($index[$group] as &$term) {
     75                                // Untrusted: skip non-array. Bad client = count mismatch = null.
     76                                if (!is_array($term)) {
     77                                        continue;
     78                                }
    7579                                $this->apply_field($term, 'title', $cb);
    7680                                $this->apply_field($term, 'description', $cb);
    … …  
    8488
    8589                foreach ($index['posts'] as &$post) {
     90                        if (!is_array($post)) {
     91                                continue;
     92                        }
     93
    8694                        foreach (['title', 'short_description', 'description_excerpt'] as $field) {
    8795                                $this->apply_field($post, $field, $cb);
    … …  
    94102                                }
    95103                                foreach ($post[$group] as &$term) {
     104                                        if (!is_array($term)) {
     105                                                continue;
     106                                        }
    96107                                        $this->apply_field($term, 'title', $cb);
    97108                                }
  • clonable/trunk/services/modules/DataPanelModule.php

    r3719175 r3746021  
    1010
    1111class DataPanelModule {
     12
     13        /** Nonce in the exclusion meta box: proves the form was actually submitted. */
     14        private const NONCE_ACTION = 'clonable_exclusion_meta_box';
     15        private const NONCE_FIELD  = 'clonable_exclusion_nonce';
    1216
    1317        public function __construct() {
    … …  
    8084        }
    8185
     86        /**
     87         * Exclusion checkboxes for non-product post types, plus the save nonce.
     88         *
     89         * @link https://developer.wordpress.org/reference/functions/wp_nonce_field/
     90         * @link https://developer.wordpress.org/reference/functions/get_the_terms/
     91         */
    8292        public function clonable_render_exclusion_meta_box($post) {
     93                wp_nonce_field(self::NONCE_ACTION, self::NONCE_FIELD);
     94
    8395                $excluded_ids = get_the_terms($post->ID, ClonableConfig::EXCLUSION_TAXONOMY);
    8496                $site         = ClonableConfig::get_site();
    … …  
    95107
    96108
     109        /**
     110         * Action save_post: store the meta box exclusions.
     111         * Only when the meta box form came along (nonce). Quick Edit, block editor REST save,
     112         * imports and other plugins' saves carry no checkboxes; saving then wiped every exclusion.
     113         * Valid nonce + no checkboxes = user unchecked all: terms cleared on purpose.
     114         *
     115         * @link https://developer.wordpress.org/reference/hooks/save_post/
     116         * @link https://developer.wordpress.org/reference/functions/wp_is_post_revision/
     117         * @link https://developer.wordpress.org/reference/functions/wp_verify_nonce/
     118         * @link https://developer.wordpress.org/reference/functions/current_user_can/
     119         * @link https://developer.wordpress.org/reference/functions/wp_set_post_terms/
     120         */
    97121        public function save_exclusion_meta_box_data($post_id) {
    98                 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || !current_user_can('edit_post', $post_id)) {
    99                         return;
    100                 }
    101 
    102                 // get all the post value keys, and filter the clonable checkboxes.
    103                 $submitted_values = array_filter(
     122                if (wp_is_post_revision($post_id) || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) {
     123                        return;
     124                }
     125
     126                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- This is the nonce being read.
     127                $nonce = isset($_POST[self::NONCE_FIELD]) ? sanitize_text_field(wp_unslash($_POST[self::NONCE_FIELD])) : '';
     128                if ($nonce === '') {
     129                        return;
     130                }
     131
     132                if (!wp_verify_nonce($nonce, self::NONCE_ACTION)) {
     133                        if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
     134                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     135                                error_log("[Clonable] Exclusion meta box: invalid nonce for post {$post_id}, not saved.");
     136                        }
     137                        return;
     138                }
     139
     140                if (!current_user_can('edit_post', $post_id)) {
     141                        return;
     142                }
     143
     144                wp_set_post_terms($post_id, $this->submitted_exclusion_terms(), ClonableConfig::EXCLUSION_TAXONOMY, false);
     145        }
     146
     147        /**
     148         * Checked exclusion boxes from $_POST as comma separated term slugs. Field cb-<slug> = slug.
     149         * Callers verified the nonce (ours, or WooCommerce's for the product data panel).
     150         *
     151         * @link https://developer.wordpress.org/reference/functions/sanitize_title/
     152         */
     153        private function submitted_exclusion_terms(): string {
     154                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by the caller.
     155                $fields = array_filter(
    104156                        array_keys($_POST),
    105                         function ($field) {
    106                                 return Functions::str_starts_with($field, 'cb-clonable-excluded');
    107                         }
     157                        static fn ($field) => is_string($field) && Functions::str_starts_with($field, 'cb-clonable-excluded')
    108158                );
    109159
    110                 // strip the cb- from the checkbox keys, then the remaining value is the same as the term. then store it as a comma separated string.
    111                 $terms = implode(
    112                         ',',
    113                         array_map(
    114                                 function ($value) {
    115                                         return str_replace('cb-', '', $value);
    116                                 },
    117                                 $submitted_values
    118                         )
    119                 );
    120 
    121                 wp_set_post_terms($post_id, $terms, ClonableConfig::EXCLUSION_TAXONOMY, false);
     160                return implode(',', array_map(static fn ($field) => sanitize_title(substr($field, 3)), $fields));
    122161        }
    123162
    … …  
    136175                $flag_html         = ($item === 'product') ? "<i class='fflag-$region fflag ff-sm' style='margin-top: 2px'></i>" : "<i class='fflag-$region fflag ff-sm' style='margin-right: 10px'></i>";
    137176
    138                 // some logic for if the checkbox should be checked or not.
    139                 $value = !($excluded_ids === false) && in_array($term, array_column($excluded_ids, 'slug'));
     177                // Checked when excluded. get_the_terms(): array, false or WP_Error.
     178                $value = is_array($excluded_ids) && in_array($term, array_column($excluded_ids, 'slug'), true);
    140179                woocommerce_wp_checkbox(
    141180                        [
    … …  
    149188
    150189        /**
    151          * Parse and save the edited data from the Clonable data panel.
     190         * Action woocommerce_process_product_meta: save the Clonable product data panel.
     191         * Fires only after WooCommerce checked its own nonce and capability.
     192         *
     193         * @link https://developer.wordpress.org/reference/functions/wp_set_post_terms/
    152194         *
    153195         * @param $post_id int the id of the post
    … …  
    155197         */
    156198        public function clonable_save_data_panels($post_id) {
    157                 // get all the post value keys, and filter he clonable checkboxes.
    158                 $submitted_values = array_filter(
    159                         array_keys($_POST),
    160                         function ($field) {
    161                                 return Functions::str_starts_with($field, 'cb-clonable-excluded');
    162                         }
    163                 );
    164                 // strip the cb- from the checkbox keys, then the remaining value is the same as the term.
    165                 // then store it as a comma seperated string.
    166                 $terms = implode(
    167                         ',',
    168                         array_map(
    169                                 function ($value) {
    170                                         return str_replace('cb-', '', $value);
    171                                 },
    172                                 $submitted_values
    173                         )
    174                 );
    175 
    176                 wp_set_post_terms($post_id, $terms, ClonableConfig::EXCLUSION_TAXONOMY, false);
     199                wp_set_post_terms($post_id, $this->submitted_exclusion_terms(), ClonableConfig::EXCLUSION_TAXONOMY, false);
    177200        }
    178201}
  • clonable/trunk/services/modules/ExclusionModule.php

    r3719175 r3746021  
    323323        $term = sprintf(ClonableConfig::EXCLUSION_QUERY_ID, strtolower($current_id));
    324324        $excluded_terms = get_the_terms($post_id, ClonableConfig::EXCLUSION_TAXONOMY);
    325         return !($excluded_terms === false) && in_array($term, array_column($excluded_terms, 'slug'));
     325        // false = no terms; WP_Error = taxonomy missing or filtered by another plugin.
     326        if (!is_array($excluded_terms)) {
     327            return false;
     328        }
     329
     330        return in_array($term, array_column($excluded_terms, 'slug'), true);
    326331    }
    327332
  • clonable/trunk/services/modules/ProductImporterModule.php

    r3719175 r3746021  
    2121                                ('woocommerce_product_export_product_column_' . $term),
    2222                                function ($value, $product) use ($term) {
    23                                         $excluded_ids = wp_get_post_terms($product->id, ClonableConfig::EXCLUSION_TAXONOMY);
    24                                         $is_excluded  = in_array($term, array_column($excluded_ids, 'slug'));
     23                                        $excluded_ids = wp_get_post_terms($product->get_id(), ClonableConfig::EXCLUSION_TAXONOMY);
     24                                        // WP_Error when the taxonomy is missing.
     25                                        $is_excluded = is_array($excluded_ids) && in_array($term, array_column($excluded_ids, 'slug'), true);
    2526                                        return ($is_excluded) ? 'yes' : 'no';
    2627                                },
  • clonable/trunk/views/WoocommerceView.php

    r3719175 r3746021  
    188188                $this->render_error('clonable_default_country_by_domain');
    189189        }
     190
     191        /**
     192         * Opt-in for the clone-based customer location. Unchecked by default.
     193         */
     194        public function clonable_woocommerce_customer_location_enabled_field() {
     195                $this->create_checkbox(ClonableWooCommerce::CUSTOMER_LOCATION_ENABLED, 'off');
     196        }
    190197}
Note: See TracChangeset for help on using the changeset viewer.