session ) { return ''; } $uuid = WC()->session->get( 'acpw_cart_uuid' ); if ( ! is_string( $uuid ) || ! wp_is_uuid( $uuid ) ) { $uuid = wp_generate_uuid4(); WC()->session->set( 'acpw_cart_uuid', $uuid ); } return $uuid; } public static function flush() { global $wpdb; if ( ! self::$dirty || self::$submitted || self::$restoring || ! ACPW_Store::enabled() || ! WC()->session || ! WC()->cart ) { return; } self::$dirty = false; if ( WC()->cart->is_empty() ) { ACPW_Store::close( WC()->session->get( 'acpw_cart_uuid' ), 'empty' ); WC()->session->__unset( 'acpw_cart_uuid' ); WC()->session->__unset( 'acpw_contact' ); WC()->session->__unset( 'acpw_submitted_basket' ); WC()->session->__unset( 'acpw_recovery_event' ); return; } $entry = ACPW_Payload::snapshot( (array) WC()->session->get( 'acpw_contact', array() ) ); $basket = ACPW_Payload::basket_hash( $entry ); $submitted_basket = WC()->session->get( 'acpw_submitted_basket' ); if ( $submitted_basket && hash_equals( (string) $submitted_basket, $basket ) ) { return; } WC()->session->__unset( 'acpw_submitted_basket' ); $uuid = self::uuid(); $hash = ACPW_Payload::hash( $entry ); $table = ACPW_Store::carts(); // Serialize captures and event creation for this cart. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $wpdb->query( 'START TRANSACTION' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE cart_uuid = %s FOR UPDATE", $table, $uuid) ); if ( $row && 'erased' === $row->status ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $wpdb->query( 'ROLLBACK' ); return; // Do not repopulate a cart that was anonymised by a privacy request. } if ( $row && 'ordered' === $row->status ) { $ordered_entry = ACPW_Payload::decode( $row->snapshot ); if ( is_array( $ordered_entry ) && hash_equals( ACPW_Payload::basket_hash( $ordered_entry ), $basket ) ) { WC()->session->set( 'acpw_submitted_basket', $basket ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $wpdb->query( 'COMMIT' ); return; } } if ( $row && in_array( $row->status, array( 'ordered', 'empty', 'superseded' ), true ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $wpdb->query( 'ROLLBACK' ); WC()->session->__unset( 'acpw_cart_uuid' ); self::$dirty = true; self::flush(); return; } if ( $row && hash_equals( $row->content_hash, $hash ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $wpdb->query( 'COMMIT' ); return; } $settings = ACPW_Store::settings(); $data = array( 'session_hash' => hash_hmac( 'sha256', (string) WC()->session->get_customer_id(), wp_salt( 'auth' ) ), 'user_id' => (int) $entry['user_id'], 'email' => $entry['email'], 'snapshot' => wp_json_encode( $entry ), 'content_hash' => $hash, 'eligible_after' => 0, 'updated_at' => time(), 'status' => $row && $row->last_sent_at && ! $settings['repeat_hours'] ? 'sent' : 'active', 'revision' => $row ? (int) $row->revision + 1 : 1, ); if ( $row ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Write plugin-owned transactional state through the WordPress database API; cached state would invalidate queue/privacy guarantees. $ok = $wpdb->update( $table, $data, array( 'id' => $row->id ) ); ACPW_Store::cancel( $uuid ); } else { $data['cart_uuid'] = $uuid; $data['created_at'] = time(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Write plugin-owned transactional state through the WordPress database API; cached state would invalidate queue/privacy guarantees. $ok = $wpdb->insert( $table, $data ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. ( false === $ok ? $wpdb->query( 'ROLLBACK' ) : $wpdb->query( 'COMMIT' ) ); } /** Only checkout identity/address fields; never passwords, payment fields, or arbitrary form data. */ public static function clean_contact( array $input ) { $output = array(); $fields = array( 'first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'email', 'phone' ); foreach ( array( 'billing', 'shipping' ) as $type ) { foreach ( $fields as $field ) { $key = $type . '_' . $field; if ( isset( $input[ $key ] ) && is_scalar( $input[ $key ] ) ) { $output[ $key ] = substr( sanitize_text_field( (string) $input[ $key ] ), 0, 254 ); } } } if ( isset( $input['email'] ) && is_scalar( $input['email'] ) ) { $output['email'] = substr( sanitize_text_field( (string) $input['email'] ), 0, 254 ); } return $output; } private static function save_contact( array $input ) { if ( ! ACPW_Store::enabled() || ! WC()->session || self::$submitted ) { return; } $contact = self::clean_contact( $input ); if ( $contact ) { $previous = (array) WC()->session->get( 'acpw_contact', array() ); WC()->session->set( 'acpw_contact', array_merge( $previous, $contact ) ); self::queue(); } } public static function classic_contact( $encoded ) { $data = array(); parse_str( (string) $encoded, $data ); self::save_contact( $data ); } public static function store_contact( $customer, $request ) { $data = array(); foreach ( array( 'billing', 'shipping' ) as $type ) { foreach ( (array) $request[ $type . '_address' ] as $key => $value ) { $data[ $type . '_' . $key ] = $value; } } self::save_contact( $data ); } public static function scripts() { if ( ! ACPW_Store::enabled() || ! ( is_checkout() || is_cart() ) || is_order_received_page() ) { return; } wp_enqueue_script( 'acpw-contact', plugins_url( 'assets/contact.js', ACPW_FILE ), array(), ACPW_VERSION, true ); wp_localize_script( 'acpw-contact', 'acpwContact', array( 'bootstrap' => WC_AJAX::get_endpoint( 'acpw_bootstrap' ), 'capture' => WC_AJAX::get_endpoint( 'acpw_contact' ), ) ); } private static function guard_ajax() { // Per-session bearer token from a same-origin bootstrap, safe with cached checkout pages. $origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ) : ''; $parts = wp_parse_url( home_url() ); $expected = $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); $fetch_site = sanitize_text_field( wp_unslash( $_SERVER['HTTP_SEC_FETCH_SITE'] ?? '' ) ); if ( 'POST' !== ( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) || 'XMLHttpRequest' !== ( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' ) ) ) || ( $origin && ! hash_equals( $expected, rtrim( $origin, '/' ) ) ) || 'cross-site' === $fetch_site || ! ACPW_Store::enabled() || ! WC()->session || ! WC()->cart || WC()->cart->is_empty() ) { wp_send_json_error( array( 'message' => __( 'Cart capture unavailable.', 'abandoned-cart-webhooks-for-woocommerce' ) ), 403 ); } nocache_headers(); } private static function rate_ajax( $scope, $limit ) { // Trust the direct peer only. Forwarded headers are attacker-controlled without host configuration. $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) ); $ip = filter_var( $ip, FILTER_VALIDATE_IP ) ? inet_ntop( inet_pton( $ip ) ) : 'unknown'; if ( ! ACPW_Store::allow( 'ip-' . $scope, $ip, $limit, 10 * MINUTE_IN_SECONDS ) ) { header( 'Retry-After: 600' ); wp_send_json_error( array( 'message' => __( 'Please retry later.', 'abandoned-cart-webhooks-for-woocommerce' ) ), 429 ); } } public static function bootstrap() { self::guard_ajax(); self::rate_ajax( 'bootstrap', 60 ); $token = WC()->session->get( 'acpw_capture_token' ); if ( ! $token ) { $token = bin2hex( random_bytes( 32 ) ); WC()->session->set( 'acpw_capture_token', $token ); } WC()->session->set_customer_session_cookie( true ); wp_send_json_success( array( 'token' => $token ) ); } public static function ajax_contact() { self::guard_ajax(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Read the same-origin WC session bearer token in order to verify it below; a cached-page WordPress nonce is not used. $token = isset( $_POST['token'] ) && is_string( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : ''; $stored = (string) WC()->session->get( 'acpw_capture_token', '' ); if ( ! $stored || ! hash_equals( $stored, $token ) ) { wp_send_json_error( array( 'message' => __( 'Session expired.', 'abandoned-cart-webhooks-for-woocommerce' ) ), 403 ); } self::rate_ajax( 'contact', 120 ); $last = (int) WC()->session->get( 'acpw_contact_saved_at', 0 ); if ( time() - $last < 2 ) { wp_send_json_error( array( 'message' => __( 'Please retry.', 'abandoned-cart-webhooks-for-woocommerce' ) ), 429 ); } // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The WC session token was just verified; save_contact immediately allowlists and sanitizes scalar contact fields. $contact = isset( $_POST['contact'] ) && is_array( $_POST['contact'] ) ? wp_unslash( $_POST['contact'] ) : array(); self::save_contact( $contact ); WC()->session->set( 'acpw_contact_saved_at', time() ); // Include this request's capture before WooCommerce persists its session at shutdown. self::flush(); wp_send_json_success(); } public static function tag_order( $order ) { ACPW_Compat::session(); if ( $order instanceof WC_Order && WC()->session ) { $recovery_event = WC()->session->get( 'acpw_recovery_event' ); if ( is_string( $recovery_event ) && wp_is_uuid( $recovery_event ) ) { $order->update_meta_data( '_acpw_recovery_event', $recovery_event ); } $uuid = WC()->session->get( 'acpw_cart_uuid' ); if ( $uuid ) { $order->update_meta_data( '_acpw_cart_uuid', $uuid ); } } } public static function ordered( $order ) { $order = $order instanceof WC_Order ? $order : wc_get_order( $order ); if ( ! $order || $order->has_status( array( 'checkout-draft', 'auto-draft' ) ) ) { return; } $uuid = ACPW_Compat::order_uuid( $order ); if ( ! $uuid && WC()->session ) { $uuid = WC()->session->get( 'acpw_cart_uuid' ); if ( $uuid ) { $order->update_meta_data( '_acpw_cart_uuid', $uuid ); $order->save_meta_data(); } } ACPW_Store::close( $uuid, 'ordered', $order->get_id() ); self::close_recovered_order( $order ); self::$submitted = true; if ( WC()->session ) { if ( WC()->cart && ! WC()->cart->is_empty() ) { WC()->session->set( 'acpw_submitted_basket', ACPW_Payload::basket_hash( array( 'cart' => WC()->cart->get_cart(), 'coupons' => WC()->cart->get_applied_coupons() ) ) ); } WC()->session->__unset( 'acpw_cart_uuid' ); WC()->session->__unset( 'acpw_contact' ); WC()->session->__unset( 'acpw_recovery_event' ); } } private static function close_recovered_order( $order ) { global $wpdb; $uuid = $order->get_meta( '_acpw_recovery_event', true ); if ( ! is_string( $uuid ) || ! wp_is_uuid( $uuid ) ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned queue/privacy tables and transaction locks require current uncached database state; all values/identifiers are prepared separately. $event = $wpdb->get_row( $wpdb->prepare( "SELECT cart_uuid,payload FROM %i WHERE event_uuid = %s", ACPW_Store::events(), $uuid) ); $entry = $event ? ACPW_Payload::decode( $event->payload ) : null; $recipient = is_array( $entry ) ? ACPW_Payload::email( $entry ) : ''; $billing = trim( (string) $order->get_billing_email() ); if ( $recipient && is_email( $billing ) && 0 === strcasecmp( $recipient, $billing ) ) { // Close the source only after an actual submitted order with the same email. // The recovering browser never adopts or edits the source tracking identity. ACPW_Store::close( $event->cart_uuid, 'ordered', $order->get_id() ); } } public static function order_status( $order_id, $from, $to, $order ) { if ( in_array( $to, array( 'checkout-draft', 'auto-draft' ), true ) ) { return; } self::close_recovered_order( $order ); // Status notifications may run in another shopper's request. Never use that shopper's session. $uuid = ACPW_Compat::order_uuid( $order ); if ( $uuid ) { ACPW_Store::close( $uuid, 'ordered', $order_id ); } } }