Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/bloyal/app/controller/bloyal_resubmit_order_controller.php
+++ b/bloyal/app/controller/bloyal_resubmit_order_controller.php
@@ -98,7 +98,7 @@
);
$customFields = array();
$entity = array(
- 'Status' => 'completed',
+ 'Status' => 'Approved',
'Title' => null,
'StoreUid' => '00000000-0000-0000-0000-000000000000',
'StoreCode' => null,
@@ -143,15 +143,24 @@
bLoyalLoggerService::write_custom_log( "Resubmit Cart Request rn " . wp_json_encode( $submitCartRequest ) . "rn ===================rn", 1 );
$result = $this->bloyal_controller_obj->send_curl_request( $submitCartRequest, 'SalesOrders/Changes', 'grid', 1 );
- if ( $result->status == 'success' || $result->message == 'Cart cannot be submitted. Cart already exists in Captured state.' ) {
- $order->add_order_note( 'Order successfully submitted to bLoyal order engine', 0, true );
+ $result_status = is_object( $result ) && isset( $result->status ) ? $result->status : null;
+ $result_message = is_object( $result ) && isset( $result->message ) ? $result->message : null;
+ if ( $result_status == 'success' || $result_message == 'Cart cannot be submitted. Cart already exists in Captured state.' ) {
+ $note_message = 'Order successfully submitted to bLoyal order engine';
} else {
- $order->add_order_note( $result->message, 0, true );
+ $note_message = $result_message;
+ if ( empty( $note_message ) && is_object( $result ) && isset( $result->title ) ) {
+ $note_message = $result->title;
+ }
+ if ( empty( $note_message ) ) {
+ $note_message = 'bLoyal rejected the resubmit. See the bLoyal log for details.';
+ }
}
+ $order->add_order_note( $note_message, 0, true );
bLoyalLoggerService::write_custom_log( "Resubmit Cart Response rn" . wp_json_encode( $result ) . "rn ======================rn", 1 );
$response = wp_json_encode(
array(
- 'resubmit_message' => $result->message,
+ 'resubmit_message' => $note_message,
)
);
return $response;
@@ -243,9 +252,9 @@
'LoyaltyCardNumbers' => array(),
'ProgramMembershipUids' => array(),
'GroupMembershipUids' => array(),
- 'ClubMemberships' => $clubMemberships,
+ 'ClubMemberships' => array(),
'LoyaltyAccountUids' => array(),
- 'ExternalIds' => $externalIds,
+ 'ExternalIds' => array( $externalIds ),
'Code' => null,
'Id' => 0,
'Uid' => '00000000-0000-0000-0000-000000000000',
@@ -330,7 +339,7 @@
$taxDetails[] = array(
'ClassCode' => null,
'Code' => null,
- 'Rate' => null,
+ 'Rate' => 0,
'Amount' => number_format( floor( $shipping_tax_total * 100 ) / 100, 2 ),
);
@@ -438,6 +447,7 @@
$line_tax = $order_data_product_details[ $attribute_count ]->meta_value;
}
}
+ $line_level_discount = 0;
$line_level_discount_query = $wpdb->get_results( $wpdb->prepare( "SELECT meta_value FROM $db_table_name WHERE meta_key = %s AND order_item_id = %d ", '_bloyal_item_level_discount', $order_item_id ) );
if ( ! empty( $line_level_discount_query ) ) {
$line_level_discount = number_format( $line_level_discount_query[0]->meta_value, 2, '.', '' );
@@ -488,7 +498,7 @@
'ClassCode' => null,
'Code' => $tax_code,
- 'Rate' => null,
+ 'Rate' => 0,
'Amount' => number_format( floor( $line_tax * 100 ) / 100, 2 ),
);
$customFields = array();
--- a/bloyal/app/controller/bloyal_snippets_payment.php
+++ b/bloyal/app/controller/bloyal_snippets_payment.php
@@ -7,13 +7,17 @@
$plugin_url = BLOYAL_DIR;
$plugin_url = explode( '/plugins', $plugin_url );
-add_action( 'plugins_loaded', 'bloyal_snippets_payment_gateway' );
$plugin_list = get_option( 'active_plugins' );
$epay = false;
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
+ add_action( 'plugins_loaded', 'bloyal_snippets_payment_gateway' );
+
function bloyal_snippets_payment_gateway() {
+ if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
+ return;
+ }
class Bloyal_Snippets_Gateway extends WC_Payment_Gateway {
--- a/bloyal/app/controller/class-alertpopupcontroller.php
+++ b/bloyal/app/controller/class-alertpopupcontroller.php
@@ -44,7 +44,7 @@
$bloyal_snippet_args['PaymentRedirectToHome'] = true;
$snippets_api_url = get_option( 'web_snippets_api_url' );
$snippets_src = 'https://snippets.bloyal.io/bLoyalSnippetLoader.js?ver=1.0.0';
- $alert_snippet_div = "<div data-bloyal-snippet-code='" . $snippet_code . "' data-bloyal-login-domain='" . $loginDomain . "' data-bloyal-device-code='" . $strDeviceCode . "' data-bloyal-snippet-args='" . wp_wp_json_encode( $bloyal_snippet_args, true ) . "' id='root'></div><script> function EgiftSnippetComplete() { console.log('The Snippet is done') } </script>";
+ $alert_snippet_div = "<div data-bloyal-snippet-code='" . $snippet_code . "' data-bloyal-login-domain='" . $loginDomain . "' data-bloyal-device-code='" . $strDeviceCode . "' data-bloyal-snippet-args='" . wp_json_encode( $bloyal_snippet_args, true ) . "' id='root'></div><script> function EgiftSnippetComplete() { console.log('The Snippet is done') } </script>";
return $alert_snippet_div;
} catch ( Exception $ex ) {
--- a/bloyal/app/controller/class-bloyalcontroller.php
+++ b/bloyal/app/controller/class-bloyalcontroller.php
@@ -592,8 +592,12 @@
// Trigger cart calculation to ensure discount is applied immediately
// This will trigger woocommerce_before_calculate_totals which calls bloyal_calculate_bloyal_promotions
+ // Track whether the recalculation actually ran: on an empty cart it is skipped,
+ // which would leave a stale CalculateCart response in the session.
+ $did_recalculate = false;
if ( WC()->cart && ! WC()->cart->is_empty() ) {
WC()->cart->calculate_totals();
+ $did_recalculate = true;
}
}
}
@@ -602,8 +606,44 @@
$msg = 'Coupon ' . esc_html( $coupon_code ) . ' does not exist!';
wc_add_notice( $msg, 'error' );
} else {
- // Don't echo HTML in filter hook - WooCommerce will handle the response
- // The success is indicated by the session being set and cart calculation triggered
+ // bLoyal accepted the code, but "accepted" is not the same as "discounted":
+ // a reward coupon the customer was never awarded comes back Valid=false /
+ // Redeemed=false with no discount. Redeemed is the authoritative flag -
+ // promotion_class_controller also uses it to decide which coupons are written
+ // onto the committed order - so a non-redeemed coupon must not be reported as
+ // applied. The response of the recalculation above is already in the session.
+ // Fail safe: anything unknown (no recalculation, missing or stale response)
+ // keeps the success message; only an explicit Redeemed=false downgrades it.
+ $coupon_redeemed = true;
+ $coupon_message = '';
+ if ( ! empty( $did_recalculate ) && WC()->session ) {
+ $fresh = WC()->session->get( 'bloyal_cart_data' );
+ if ( is_object( $fresh )
+ && isset( $fresh->Cart->Uid ) && 0 === strcasecmp( $fresh->Cart->Uid, $cart_uid )
+ && isset( $fresh->LoyaltySummary->AppliedCoupons )
+ && is_array( $fresh->LoyaltySummary->AppliedCoupons ) ) {
+ // Absent from the list means bLoyal did not act on it.
+ $coupon_redeemed = false;
+ foreach ( $fresh->LoyaltySummary->AppliedCoupons as $applied ) {
+ if ( isset( $applied->Code ) && 0 === strcasecmp( $applied->Code, $coupon_code ) ) {
+ $coupon_redeemed = ! empty( $applied->Redeemed );
+ $coupon_message = isset( $applied->Message ) ? (string) $applied->Message : '';
+ break;
+ }
+ }
+ }
+ }
+ if ( $coupon_redeemed ) {
+ // Queued after wc_clear_notices() above so it survives this request.
+ wc_add_notice( 'Coupon code applied successfully', 'success' );
+ } else {
+ // Prefer bLoyal's own explanation (e.g. "Customer has not been awarded
+ // this coupon.") over a generic string when it provides one.
+ $reason = ( '' !== trim( $coupon_message ) )
+ ? $coupon_message
+ : "Coupon code '" . $coupon_code . "' is not valid for this order.";
+ wc_add_notice( esc_html( $reason ), 'error' );
+ }
}
}
} catch ( Exception $exception ) {
@@ -2421,89 +2461,6 @@
}
/**
- * Initialize verify_is_woocommerce_customer.
- *
- * @param object $customer_obj as parameter.
- * @return boolean
- */
- public function verify_is_woocommerce_customer( $customer_obj ) {
- try {
- global $wpdb;
- $customer_external_id = $customer_obj->ExternalId;
-
- $id_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->users WHERE ID = %d", $customer_external_id ) );
- if ( $id_count == 1 ) {
- $this->bloyal_customer_auto_login( $customer_external_id );
- return true;
- } else {
- $email = $customer_obj->EmailAddress;
- $email_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->users WHERE user_email = %s", $email ) );
- if ( $email_count == 1 ) {
- $user_by_email = get_user_by( 'email', $email );
- $this->bloyal_customer_auto_login( $user_by_email->ID );
- return true;
- } else {
- $customer_id = $this->create_woocommerce_customer( $customer_obj );
- $this->bloyal_customer_auto_login( $customer_id );
- return false;
- }
- }
- } catch ( Exception $e ) {
- bLoyalLoggerService::write_custom_log( $e->getMessage(), 3 );
- }
- }
-
- /**
- * Initialize bloyal_customer_auto_login.
- *
- * @param int $user_id as parameter.
- * @return void
- */
- public function bloyal_customer_auto_login( $user_id ) {
- $user_info = get_userdata( $user_id );
- $username = $user_info->user_login;
-
- if ( $user = get_user_by( 'login', $username ) ) {
- clean_user_cache( $user->ID );
- wp_clear_auth_cookie();
- wp_set_current_user( $user->ID );
- wp_set_auth_cookie( $user->ID, true, false );
- update_user_caches( $user );
- }
- }
-
- /**
- * Initialize create_woocommerce_customer.
- *
- * @param array $customer_obj as parameter.
- * @return json_object
- */
- public function create_woocommerce_customer( $customer_obj ) {
- try {
- $email = $customer_obj->EmailAddress;
- $username = $customer_obj->EmailAddress;
- $password = $customer_obj->ExternalId;
- $user_id = wc_create_new_customer( $email, $username, $password );
- update_user_meta( $user_id, 'billing_first_name', $customer_obj->FirstName );
- update_user_meta( $user_id, 'billing_last_name', $customer_obj->LastName );
- update_user_meta( $user_id, 'billing_company', $customer_obj->CompanyName );
- update_user_meta( $user_id, 'billing_address_1', $customer_obj->Address->Address1 );
- update_user_meta( $user_id, 'billing_address_2', $customer_obj->Address->Address2 );
- update_user_meta( $user_id, 'billing_city', $customer_obj->Address->City );
- update_user_meta( $user_id, 'billing_postcode', $customer_obj->Address->PostalCode );
- update_user_meta( $user_id, 'billing_country', $customer_obj->Address->Country );
- update_user_meta( $user_id, 'billing_state', $customer_obj->Address->StateName );
- update_user_meta( $user_id, 'billing_email', $customer_obj->EmailAddress );
- update_user_meta( $user_id, 'billing_phone', $customer_obj->MobilePhone );
- update_user_meta( $user_id, 'first_name', $customer_obj->FirstName );
- update_user_meta( $user_id, 'last_name', $customer_obj->LastName );
- return $user_id;
- } catch ( Exception $e ) {
- bLoyalLoggerService::write_custom_log( $e->getMessage(), 3 );
- }
- }
-
- /**
* Initialize bloyal_view_cart_in_woocommerce
*
* @param array $request as parameter
@@ -2513,11 +2470,17 @@
try {
WC()->cart->empty_cart();
- $action = 'carts?CartUid=' . $request;
+ $action = 'carts?CartUid=' . rawurlencode( $request );
WC()->session->set( 'third_party_cardId', $request );
$result = $this->send_curl_request( '', $action, 'loyaltyengine', 0 );
bLoyalLoggerService::write_custom_log( "View Cart Response rn" . wp_json_encode( $result ) . "rn ======================rn", 1 );
- $this->verify_is_woocommerce_customer( $result->data->Cart->Customer );
+ // CON-184 / CVE-2026-15001: the Customer object in this response is deliberately NOT
+ // used to identify a WordPress user. This line used to call
+ // verify_is_woocommerce_customer(), which logged the visitor in - and could create an
+ // account - from the ExternalId the API returned, so whoever controlled the configured
+ // API URL controlled who you were logged in as. The cart handoff now authenticates
+ // nobody: the visitor keeps their cart and continues as a guest, or signs in through
+ // WooCommerce's own flow.
if ( isset( $result->data->Cart->Lines ) ) {
$bloyal_unexisted_woo_products = array();
foreach ( $result->data->Cart->Lines as $line ) {
--- a/bloyal/app/controller/class-bloyalstoredpaymentmethod.php
+++ b/bloyal/app/controller/class-bloyalstoredpaymentmethod.php
@@ -10,8 +10,6 @@
-add_action( 'plugins_loaded', 'bloyal_stored_payment_gateway' );
-
require_once BLOYAL_DIR . '/app/controller/bloyal_payment_controller.php';
@@ -24,9 +22,14 @@
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
+ add_action( 'plugins_loaded', 'bloyal_stored_payment_gateway' );
+
function bloyal_stored_payment_gateway() {
+ if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
+ return;
+ }
#[AllowDynamicProperties] // we have added this code avoid create dynamic property notice in php error logs
class Bloyal_Stored_Payment_Gateway extends WC_Payment_Gateway {
@@ -265,7 +268,8 @@
var data = {
- action: 'get_stored_payment_method'
+ action: 'get_stored_payment_method',
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
};
@@ -842,7 +846,7 @@
$snippets_src = 'https://snippetsbeta.bloyal.io/bLoyalSnippetLoader.js';
- $alert_snippet_div = "<div data-bloyal-snippet-code='" . $snippet_code . "' data-bloyal-login-domain='" . $this->domain_name . "' data-bloyal-snippet-args='" . wp_json_encode( $bloyal_snippet_args, true ) . "' id='root'></div><script> function PaymentSnippetCompleteFn(paymentMethod) { jQuery.ajax( { type: 'POST', dataType : 'JSON',url: httpAdminUrl, data: { action: 'bloyal_stored_payment_method', method_uid: paymentMethod.PaymentMethod.Uid }, beforeSend: function(){ jQuery('#loading_resubmit').show(); }, success:function(responseData){ }, complete:function(responseData){jQuery('#loading_resubmit').hide(); } } );} </script>";
+ $alert_snippet_div = "<div data-bloyal-snippet-code='" . $snippet_code . "' data-bloyal-login-domain='" . $this->domain_name . "' data-bloyal-snippet-args='" . wp_json_encode( $bloyal_snippet_args, true ) . "' id='root'></div><script> function PaymentSnippetCompleteFn(paymentMethod) { jQuery.ajax( { type: 'POST', dataType : 'JSON',url: httpAdminUrl, data: { action: 'bloyal_stored_payment_method', method_uid: paymentMethod.PaymentMethod.Uid, nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '') }, beforeSend: function(){ jQuery('#loading_resubmit').show(); }, success:function(responseData){ }, complete:function(responseData){jQuery('#loading_resubmit').hide(); } } );} </script>";
return $alert_snippet_div;
--- a/bloyal/app/controller/class-paymentalertcontroller.php
+++ b/bloyal/app/controller/class-paymentalertcontroller.php
@@ -86,6 +86,19 @@
$session_key = $this->get_session_key( $user_id, $email_id );
+ if ( ! class_exists( 'Bloyal_Stored_Payment_Gateway' ) ) {
+ // CON-106: the gateway class is only defined when WooCommerce (WC_Payment_Gateway)
+ // is loaded. If it is unavailable on this request, skip the alert instead of fataling
+ // with an uncaught Error (which try/catch ( Exception ) would not catch).
+ wp_send_json( wp_json_encode( array(
+ 'title' => '',
+ 'html' => '',
+ 'is_logged_in' => $is_logged_in_user,
+ 'session_key' => $session_key,
+ ) ) );
+ die;
+ }
+
$obj_payment = new Bloyal_Stored_Payment_Gateway();
$alertHtml = $obj_payment->payment_web_snippets_callback();
--- a/bloyal/app/controller/gift_card_tender_controller.php
+++ b/bloyal/app/controller/gift_card_tender_controller.php
@@ -4,13 +4,16 @@
// If this file is called directly, abort.
defined( 'ABSPATH' ) or die( 'No script!' );
-add_action( 'plugins_loaded', 'bloyal_gift_card_payment_gateway' );
-
require_once BLOYAL_DIR . '/app/controller/bloyal_payment_controller.php';
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
+ add_action( 'plugins_loaded', 'bloyal_gift_card_payment_gateway' );
+
function bloyal_gift_card_payment_gateway() {
+ if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
+ return;
+ }
#[AllowDynamicProperties] // we have added this code avoid create dynamic property notice in php error logs
class Bloyal_Gift_Card_Gateway extends WC_Payment_Gateway {
/**
@@ -162,7 +165,8 @@
$("#giftCardMessage").text('Checking ... ');
var data = {
action: 'check_gift_card_balance',
- gift_card_number: gift_card_number
+ gift_card_number: gift_card_number,
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
};
$.post(ajaxurl, data, function(response) {
var response_obj = $.parseJSON(response);
@@ -219,7 +223,8 @@
var data = {
action: 'apply_gift_card_balance',
gift_card_number: gift_card_number,
- post_redeem_amount : selectedBalance
+ post_redeem_amount : selectedBalance,
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
};
$.post(ajaxurl, data, function(response) {
var response_obj = $.parseJSON(response);
--- a/bloyal/app/controller/loyalty_dollar_tender_controller.php
+++ b/bloyal/app/controller/loyalty_dollar_tender_controller.php
@@ -2,13 +2,16 @@
defined( 'ABSPATH' ) or die( 'No script!' );
-add_action( 'plugins_loaded', 'bloyal_loyalty_dollar_payment_gateway' );
-
require_once BLOYAL_DIR . '/app/controller/bloyal_loyalty_dollar_payment_controller.php';
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
+ add_action( 'plugins_loaded', 'bloyal_loyalty_dollar_payment_gateway' );
+
function bloyal_loyalty_dollar_payment_gateway() {
+ if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
+ return;
+ }
#[AllowDynamicProperties] // we have added this code avoid create dynamic property notice in php error logs
class Bloyal_Loyalty_Dollar_Gateway extends WC_Payment_Gateway {
/**
@@ -162,7 +165,8 @@
// stored payment snippets code
function stored_payment_snippets(selected_payment_value) {
var data = {
- action: 'get_stored_payment_method'
+ action: 'get_stored_payment_method',
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
};
$.post(ajaxurl, data, function(responseData) {
if (responseData != null && responseData != '') {
@@ -186,7 +190,8 @@
$("#storedPaymentMessage1").text('checking...');
$("#check_loyalty_balance").prop('disabled', true);
var data = {
- action: 'check_loyalty_dollar_balance'
+ action: 'check_loyalty_dollar_balance',
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
}
$.post(ajaxurl, data, function(response) {
var response_obj = $.parseJSON(response);
@@ -233,7 +238,8 @@
<?php } ?>
var data = {
action: 'apply_loyalty_dollar_balance',
- post_redeem_amount : selectedBalance
+ post_redeem_amount : selectedBalance,
+ nonce: (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
}
$.post(ajaxurl, data, function(response) {
var response_obj = $.parseJSON(response);
--- a/bloyal/bloyal.php
+++ b/bloyal/bloyal.php
@@ -4,8 +4,11 @@
* Plugin Name: bLoyal
* Plugin URI:
* Description: bLoyal provides real-time customer loyalty and omni-channel order processing to your WooCommerce web store.
- * Version: 3.1.611.78
+ * Version: 3.1.611.90
* Author: bLoyal
+ * Requires PHP: 7.4
+ * License: GPLv2 or later
+ * License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
$server = '';
@@ -31,7 +34,7 @@
define('BLOYAL_CURL_TIME', 30 * 60);
}
if (! defined('BLOYAL_VERSION')) {
- define('BLOYAL_VERSION', '3.1.611.78');
+ define('BLOYAL_VERSION', '3.1.611.90');
}
if (! defined('BLOYAL_UPLOAD_DIR_BASEPATH')) {
@@ -69,6 +72,205 @@
require_once BLOYAL_DIR . '/app/controller/class-paymentalertcontroller.php';
require_once BLOYAL_DIR . '/app/controller/bloyal_loyalty_dollar_payment_controller.php';
+/**
+ * AJAX actions that administer the plugin. They require manage_options and an
+ * admin nonce, except order resubmission which shop managers also perform.
+ *
+ * @return string[]
+ */
+function bloyal_admin_ajax_actions()
+{
+ return array(
+ 'save_bloyal_configuration_data',
+ 'save_bloyal_accesskeyverification_data',
+ 'save_bloyal_configuration_data_order_processing',
+ 'get_bloyal_configuration_details',
+ 'get_bloyal_accesskeyverification_details',
+ 'check_access_key_before_save',
+ 'test_bloyal_access_key_by_apikey',
+ 'get_bloyal_access_key_by_apikey',
+ 'bloyal_remove_bloyal_accesskey',
+ 'refresh_cached_data',
+ 'bloyal_save_bloyal_click_collect_configuration_data',
+ 'resubmit_bloyal_order_data',
+ 'bloyal_activate_provisioning_device',
+ 'bloyal_activate_provisioning_snippets_url',
+ 'bloyal_log_download',
+ 'bloyal_log_delete',
+ 'bloyal_snippets_log_download',
+ 'bloyal_snippets_log_delete',
+ 'save_configuration_data',
+ 'get_configuration_details',
+ 'save_snippets_accesskeyverification_data',
+ 'get_accesskeyverification_details',
+ 'check_snippets_access_key_before_save',
+ 'test_access_key_by_apikey_snippets',
+ 'get_access_key_by_apikey_snippets',
+ 'fetch_snippets_associated_with_device',
+ 'save_snippets_uss_css_status',
+ 'refresh_saved_data',
+ 'refresh_device_codes',
+ );
+}
+
+/**
+ * AJAX actions the storefront calls, as guest or as customer. They require the
+ * storefront nonce only.
+ *
+ * @return string[]
+ */
+function bloyal_customer_ajax_actions()
+{
+ return array(
+ 'check_loyalty_dollar_balance',
+ 'apply_loyalty_dollar_balance',
+ 'check_gift_card_balance',
+ 'apply_gift_card_balance',
+ 'shipping_address_change',
+ 'save_shipping_address',
+ 'update_shipping_method_cart',
+ 'bloyal_remove_custom_coupon',
+ 'get_bloyal_cart_items',
+ 'get_stored_payment_method',
+ 'bloyal_stored_payment_method',
+ 'bloyal_web_snippets_complete',
+ 'generate_bloyal_session_key',
+ 'carrier_name',
+ );
+}
+
+/**
+ * Register the authorization gates for the plugin's AJAX actions (CON-184).
+ * Hooking each wp_ajax_{action} at priority 0 means WordPress resolves the
+ * action, so the gate cannot disagree with the handler about which action runs.
+ *
+ * @return void
+ */
+function bloyal_register_ajax_authz_gates()
+{
+ foreach (bloyal_admin_ajax_actions() as $bloyal_action) {
+ add_action('wp_ajax_' . $bloyal_action, 'bloyal_require_admin_ajax_authz', 0);
+ }
+ foreach (bloyal_customer_ajax_actions() as $bloyal_action) {
+ add_action('wp_ajax_' . $bloyal_action, 'bloyal_require_front_ajax_authz', 0);
+ add_action('wp_ajax_nopriv_' . $bloyal_action, 'bloyal_require_front_ajax_authz', 0);
+ }
+}
+bloyal_register_ajax_authz_gates();
+
+function bloyal_require_admin_ajax_authz()
+{
+ $action = bloyal_current_ajax_action();
+ $capability = ('resubmit_bloyal_order_data' === $action) ? 'edit_shop_orders' : 'manage_options';
+ if (! current_user_can($capability)) {
+ // Anonymous callers are internet background noise and would otherwise
+ // fill the log with exceptions, so only signed-in users raise one.
+ $log_type = is_user_logged_in() ? 3 : 2;
+ bloyal_deny_ajax_request($action, 'missing capability ' . $capability, $log_type, 'bloyal_forbidden');
+ }
+ if (! check_ajax_referer('bloyal_admin', 'nonce', false)) {
+ bloyal_deny_ajax_request($action, 'invalid admin nonce', 3, 'bloyal_invalid_nonce');
+ }
+}
+
+function bloyal_require_front_ajax_authz()
+{
+ if (! check_ajax_referer('bloyal_front', 'nonce', false)) {
+ // A warning, not an exception: the storefront refreshes its nonce and
+ // retries, so an isolated rejection is expected on cached pages.
+ bloyal_deny_ajax_request(bloyal_current_ajax_action(), 'invalid storefront nonce', 2, 'bloyal_invalid_nonce');
+ }
+}
+
+/**
+ * The AJAX action currently being dispatched, taken from the hook name.
+ *
+ * @return string
+ */
+function bloyal_current_ajax_action()
+{
+ return preg_replace('/^wp_ajax_(nopriv_)?/', '', current_action());
+}
+
+/**
+ * Reject an AJAX request and log it, so a blocked integration is diagnosable.
+ * The code tells the caller whether a fresh nonce is worth trying: only
+ * bloyal_invalid_nonce is recoverable by retrying.
+ *
+ * @param string $action Action that was rejected.
+ * @param string $reason Why it was rejected.
+ * @param int $log_type Log level: 2 for warning, 3 for exception.
+ * @param string $code Machine-readable reason for the client.
+ * @return void
+ */
+function bloyal_deny_ajax_request($action, $reason, $log_type = 3, $code = 'bloyal_forbidden')
+{
+ bLoyalLoggerService::write_custom_log(
+ 'Denied AJAX action "' . $action . '": ' . $reason . ' (user ' . get_current_user_id() . ')',
+ $log_type
+ );
+ wp_send_json_error(
+ array(
+ 'message' => 'Forbidden',
+ 'code' => $code,
+ ),
+ 403
+ );
+}
+
+add_action('wp_ajax_bloyal_front_nonce', 'bloyal_send_front_nonce');
+add_action('wp_ajax_nopriv_bloyal_front_nonce', 'bloyal_send_front_nonce');
+/**
+ * Hands the storefront its AJAX nonce. Kept out of the page HTML so that a
+ * full-page cache can never serve one visitor's nonce to another, and answered
+ * over POST so no intermediary cache stores it either.
+ *
+ * @return void
+ */
+function bloyal_send_front_nonce()
+{
+ $nonce = wp_create_nonce('bloyal_front');
+ bloyal_set_front_nonce_cookie($nonce);
+ nocache_headers();
+ header('Vary: Cookie', false);
+ wp_send_json_success(array('nonce' => $nonce));
+}
+
+/**
+ * Store the storefront AJAX nonce in a JS-readable cookie, so the common case
+ * costs no extra request. Only sent when the browser has no usable nonce yet:
+ * an unconditional Set-Cookie stops some reverse proxies from caching the page.
+ *
+ * @param string|null $nonce Nonce value, or null to create one.
+ * @return void
+ */
+function bloyal_set_front_nonce_cookie($nonce = null)
+{
+ if (headers_sent()) {
+ return;
+ }
+ // Only 1 means "issued in the current tick". A nonce from the previous tick
+ // still verifies but is on its way out, so it gets replaced here rather than
+ // left to expire on the visitor.
+ if (isset($_COOKIE['bloyal_front_n']) && 1 === wp_verify_nonce($_COOKIE['bloyal_front_n'], 'bloyal_front')) {
+ return;
+ }
+ if (null === $nonce) {
+ $nonce = wp_create_nonce('bloyal_front');
+ }
+ $path = (defined('COOKIEPATH') && COOKIEPATH) ? COOKIEPATH : '/';
+ $domain = (defined('COOKIE_DOMAIN') && COOKIE_DOMAIN) ? COOKIE_DOMAIN : '';
+ setcookie('bloyal_front_n', $nonce, time() + (10 * HOUR_IN_SECONDS), $path, $domain, is_ssl(), false);
+}
+
+add_action('send_headers', 'bloyal_send_front_nonce_cookie');
+function bloyal_send_front_nonce_cookie()
+{
+ if (is_admin()) {
+ return;
+ }
+ bloyal_set_front_nonce_cookie();
+}
$bloyal_obj = new BloyalController();
$payment_alert_obj = new BLOYAL_PaymentAlertController();
@@ -96,18 +298,22 @@
function bloyal_uninstall()
{
try {
+ // CON-111: preserve the device connection (credentials + service URLs + device id)
+ // and the tender mapping on uninstall. A delete+reinstall is a common way to "update"
+ // the hand-distributed ZIP, and it must not force a reconnect or wipe tender mappings.
+ // The following options are intentionally NOT deleted:
+ // bloyal_access_key, bloyal_access_key_verification, bloyal_domain_url,
+ // bloyal_custom_grid_api_url, bloyal_custom_loyaltyengine_api_url,
+ // bloyal_custom_orderengine_api_url, bloyal_custompayment_api_url,
+ // bloyal_custom_logging_api_url, is_bloyal_custom_api_url, Device_Code,
+ // bloyal_tender_payments_mapping
+ // Caches and non-essential settings below are still cleaned up on uninstall.
delete_option('loyalty_block');
delete_option('bloyal_click_and_collect_status');
delete_option('bloyal_apply_full_balance_loyalty');
delete_option('bloyal_apply_full_balance_giftcard');
delete_option('bloyal_Tenders');
- delete_option('bloyal_access_key');
delete_option('bloyal_ShippingCarriers');
- delete_option('bloyal_custom_grid_api_url');
- delete_option('bloyal_custom_loyaltyengine_api_url');
- delete_option('bloyal_custom_orderengine_api_url');
- delete_option('bloyal_custompayment_api_url');
- delete_option('bloyal_custom_logging_api_url');
delete_option('bloyal_apply_in_increment_of_giftcard');
delete_option('bloyal_apply_in_increment_of_loyalty');
delete_option('bloyal_log_enable_disable');
@@ -115,21 +321,14 @@
delete_option('bloyal_snippet_informational_code');
delete_option('bloyal_snippet_confirmation_code');
delete_option('bloyal_snippet_problem_code');
- delete_option('bloyal_tender_payments_mapping');
- delete_option('is_bloyal_custom_api_url');
- delete_option('bloyal_access_key_verification');
- delete_option('bloyal_domain_url');
delete_option('bloyal_on_account_tender_code');
delete_option('bloyal_snippets_codes');
delete_option('bloyal_saved_device_snippets_lists');
- delete_option('Device_Code');
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
-add_action('wp_ajax_view_loyalty_block', 'bloyal_fetch_discount_summary');
-
add_filter('woocommerce_default_address_fields', 'bloyal_wdm_override_default_address_fields');
function bloyal_wdm_override_default_address_fields($address_fields)
{
@@ -1140,13 +1339,68 @@
'cart',
'/cart',
array(
- 'methods' => WP_REST_Server::READABLE,
- 'callback' => 'bloyal_view_cart_in_woocommerce',
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => 'bloyal_view_cart_in_woocommerce',
+ 'permission_callback' => 'bloyal_cart_handoff_permission_check',
+ 'args' => array(
+ 'CartId' => array(
+ 'required' => false,
+ 'sanitize_callback' => 'sanitize_text_field',
+ 'validate_callback' => 'bloyal_is_cart_uid',
+ ),
+ 'cart_uid' => array(
+ 'required' => false,
+ 'sanitize_callback' => 'sanitize_text_field',
+ 'validate_callback' => 'bloyal_is_cart_uid',
+ ),
+ ),
)
);
}
);
+/**
+ * Whether a value is shaped like a bLoyal CartUid (a GUID).
+ *
+ * @param mixed $value Value received on the request.
+ * @return bool
+ */
+function bloyal_is_cart_uid($value)
+{
+ if ('' === $value || null === $value) {
+ return true;
+ }
+ return (bool) preg_match(
+ '/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/',
+ (string) $value
+ );
+}
+
+/**
+ * Permission check for the bLoyal cart-handoff route.
+ *
+ * The route stays reachable without authentication on purpose: it exists so a shopper can open a
+ * cart link minted on bLoyal's side and land on this store's checkout. What it is allowed to do is
+ * bounded instead - it authenticates nobody, creates no WordPress user, and changes only the
+ * calling visitor's own WooCommerce session. It is refused when WooCommerce has not set up a cart
+ * and session for this request, which is the case on /wp-json/ requests: the handler calls
+ * WC()->cart->empty_cart() first and would otherwise fatal on a null cart.
+ *
+ * @return true|WP_Error
+ */
+function bloyal_cart_handoff_permission_check()
+{
+ if (! function_exists('WC') || ! WC()->cart || ! WC()->session) {
+ return new WP_Error(
+ 'bloyal_cart_unavailable',
+ __('The cart is not available for this request.', 'bloyal'),
+ array('status' => 503)
+ );
+ }
+ return true;
+}
+
+
function bloyal_fetch_orders_after_modified_date(WP_REST_Request $request)
{
try {
@@ -1240,6 +1494,9 @@
return $coupons_enabled;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
+ // Pass the original value through: returning nothing here makes this filter
+ // resolve to null, which disables coupons store-wide and hides both coupon forms.
+ return $coupons_enabled;
}
}
@@ -1289,6 +1546,14 @@
{
try {
wp_enqueue_script('bloyal_scripts', BLOYAL_URL . 'assets/js/bloyal.js', array('jquery'), BLOYAL_VERSION, true);
+ wp_localize_script(
+ 'bloyal_scripts',
+ 'bloyalAuth',
+ array(
+ 'nonce' => wp_create_nonce('bloyal_admin'),
+ 'actions' => bloyal_admin_ajax_actions(),
+ )
+ );
wp_register_style('bloyal_style_sheet', BLOYAL_URL . 'assets/css/bloyal.css', array(), '1.0');
wp_enqueue_style('bloyal_style_sheet');
} catch (Exception $ex) {
@@ -1332,12 +1597,21 @@
);
}
-add_action('wp_head', 'bloyal_myplugin_ajaxurl');
+add_action('wp_head', 'bloyal_myplugin_ajaxurl', 8);
function bloyal_myplugin_ajaxurl()
{
echo '<script type="text/javascript">
var ajaxurl = "' . esc_js(admin_url('admin-ajax.php')) . '";
var httpAdminUrl = ajaxurl;
+ window.bloyalFront = window.bloyalFront || {};
+ bloyalFront.actions = ' . wp_json_encode(bloyal_customer_ajax_actions(), JSON_HEX_TAG) . ';
+ function bloyalFrontNonce() {
+ if (bloyalFront.nonce) {
+ return bloyalFront.nonce;
+ }
+ var match = document.cookie.match(/(?:^|; )bloyal_front_n=([^;]*)/);
+ return match ? decodeURIComponent(match[1]) : "";
+ }
</script>';
}
@@ -1553,7 +1827,6 @@
function bloyal_save_configuration_data()
{
try {
-
function save_configuration_data()
{
try {
@@ -2492,7 +2765,6 @@
}
add_action('admin_enqueue_scripts', 'bloyal_snippets_enqueue_scripts');
-add_action('wp_enqueue_script', 'bloyal_snippets_enqueue_scripts');
/**
* Initialize bloyal_snippets_enqueue_scripts.
*
@@ -2500,7 +2772,8 @@
*/
function bloyal_snippets_enqueue_scripts()
{
- wp_enqueue_script('bloyal_snippets_scripts', BLOYAL_URL . '/assets/js/bloyal_snippets.js', array('jquery'), BLOYAL_VERSION, true);
+ // Depends on bloyal_scripts for the admin-ajax nonce prefilter and bloyalAuth data.
+ wp_enqueue_script('bloyal_snippets_scripts', BLOYAL_URL . '/assets/js/bloyal_snippets.js', array('jquery', 'bloyal_scripts'), BLOYAL_VERSION, true);
wp_register_style('bloyal_snippets_style_sheet', BLOYAL_URL . '/assets/css/bloyal_snippets.css', array(), '1.0');
wp_enqueue_style('bloyal_snippets_style_sheet');
}
@@ -3003,9 +3276,8 @@
add_action('wp_ajax_bloyal_activate_provisioning_snippets_url', 'bloyal_activate_provisioning_snippets_url');
function bloyal_activate_provisioning_snippets_url()
{
-
$provisioningStatus = WC()->session->get('provisioning_status');
- bLoyalLoggerService::write_custom_log('activate_provisioning_snippets_url' . $$provisioningStatus);
+ bLoyalLoggerService::write_custom_log('activate_provisioning_snippets_url' . $provisioningStatus);
if ($provisioningStatus == 'Pending') {
$provisioningResponse = WC()->session->get('provisioning_response');
wp_send_json($provisioningResponse);
@@ -3032,7 +3304,7 @@
'headers' => array(
'Content-Type' => 'application/json',
),
- 'body' => wp_wp_json_encode($apiRequestData),
+ 'body' => wp_json_encode($apiRequestData),
'method' => 'POST',
'timeout' => 45,
);
@@ -3154,7 +3426,6 @@
function bloyal_save_bloyal_click_collect_configuration_data()
{
try {
-
function save_click_collect_configuration_data()
{
try {
@@ -3280,15 +3551,13 @@
function bloyal_remove_bloyal_access_key()
{
try {
-
- $adv_access_key = sanitize_text_field(wp_unslash($_POST['post_adv_access_key']));
- update_option('bloyal_access_key', $adv_access_key);
+ $adv_access_key = isset($_POST['post_adv_access_key']) ? sanitize_text_field(wp_unslash($_POST['post_adv_access_key'])) : '';
update_option('bloyal_access_key', $adv_access_key);
$result = array(
'message' => 'Access Key succefully removed!',
'status' => 'success',
);
- wp_send_json(wp_wp_json_encode($result));
+ wp_send_json($result);
wp_die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
@@ -3470,7 +3739,8 @@
url: <?php echo esc_js($js_variable); ?>.ajax_url,
data: {
'action': 'carrier_name',
- 'value': value
+ 'value': value,
+ 'nonce': (typeof bloyalFrontNonce === 'function' ? bloyalFrontNonce() : '')
},
success: function(result) {
// console.log(result); // Only for testing (to be removed)
@@ -3663,15 +3933,13 @@
bLoyalLoggerService::write_custom_log("rn ==========Saved cart_uid to order metadata during checkout_create_order============rn" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "rn---------------rn", 1);
- // Clear CartUID from session now that it is safely stored in order metadata.
- // This prevents the next order from inheriting this CartUID if the customer navigates
- // away before the order-received page loads (which is the only place it was cleared before).
- // CommitCart falls back to _cart_uid order metadata when the session is empty.
- if (WC()->session) {
- WC()->session->__unset('bloyal_uid');
- WC()->session->__unset('bloyal_early_cart_uid');
- bLoyalLoggerService::write_custom_log("rn ========== Cleared CartUID session keys after saving to order metadata============rn" . "Order ID: " . $order_id . "rn---------------rn", 1);
- }
+ // CON-182: the CartUID session keys are deliberately NOT cleared here.
+ // Clearing them at checkout_create_order (i.e. before payment) meant that a second
+ // Place Order submission on the same session started a brand-new bLoyal cart, which
+ // never went through shipping calculation and committed with $0 shipping (see FCW
+ // orders 442609/442610). They are cleared after a successful commit in
+ // PromotionClassController::bloyal_commit_cart() and again on woocommerce_thankyou,
+ // plus on woocommerce_cart_emptied below, which ties their lifetime to the cart.
} else {
bLoyalLoggerService::write_custom_log("rn ==========WARNING: cart_uid is empty during checkout_create_order============rn" . "Order ID: " . $order->get_id() . "rn---------------rn", 2);
}
@@ -3680,6 +3948,26 @@
}
}
+// CON-182: tie the CartUID session lifetime to the cart itself. This covers the concern
+// CON-27 was addressing (a stale CartUID surviving when the order-received page never
+// loads) without destroying the CartUID for a retry of the same cart. WooCommerce empties
+// the cart on the order-received page (wc_clear_cart_after_payment) and when the shopper
+// clears it. CommitCart falls back to the _cart_uid order meta when the session is empty.
+add_action('woocommerce_cart_emptied', 'bloyal_clear_cart_uid_on_cart_emptied');
+function bloyal_clear_cart_uid_on_cart_emptied()
+{
+ try {
+ if (! WC()->session) {
+ return;
+ }
+ WC()->session->__unset('bloyal_uid');
+ WC()->session->__unset('bloyal_early_cart_uid');
+ bLoyalLoggerService::write_custom_log("rn ========== Cleared CartUID session keys on cart_emptied ============rn", 1);
+ } catch (Exception $e) {
+ bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
+ }
+}
+
// Save cart_uid to postmeta table when order is created (after order ID is available)
add_action('woocommerce_new_order', 'bloyal_save_cart_uid_on_order_created', 10, 1);
function bloyal_save_cart_uid_on_order_created($order_id)
@@ -3916,7 +4204,6 @@
// bLoyal log download function
add_action('wp_ajax_bloyal_log_download', 'bloyal_log_download'); // Log download on bLoyal admin
-add_action('wp_ajax_nopriv_bloyal_log_download', 'bloyal_log_download');
function bloyal_log_download()
{
try {
@@ -3944,7 +4231,6 @@
// bLoyal snippets log download function
add_action('wp_ajax_bloyal_snippets_log_download', 'bloyal_snippets_log_download'); // Log download on bLoyal admin
-add_action('wp_ajax_nopriv_bloyal_snippets_log_download', 'bloyal_snippets_log_download');
function bloyal_snippets_log_download()
{
try {
@@ -3971,7 +4257,6 @@
// bLoyal log delete function
add_action('wp_ajax_bloyal_log_delete', 'bloyal_log_delete');
-add_action('wp_ajax_nopriv_bloyal_log_delete', 'bloyal_log_delete');
function bloyal_log_delete()
{
try {
@@ -4001,7 +4286,6 @@
// bLoyal snippets log delete function
add_action('wp_ajax_bloyal_snippets_log_delete', 'bloyal_snippets_log_delete');
-add_action('wp_ajax_nopriv_bloyal_snippets_log_delete', 'bloyal_snippets_log_delete');
function bloyal_snippets_log_delete()
{
try {