'GUEST' ); foreach ( wp_roles()->roles as $slug => $role ) { $choices[ $slug ] = $role['name']; } return $choices; } public static function build( $role = '__guest__' ) { $user = wp_get_current_user(); if ( ! current_user_can( 'manage_options' ) || ! $user->exists() ) { return new WP_Error( 'acpw_test_permission', __( 'You do not have permission to send a test.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } if ( ! is_email( $user->user_email ) ) { return new WP_Error( 'acpw_test_email', __( 'Your logged-in account needs a valid email address.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $roles = self::roles(); if ( ! isset( $roles[ $role ] ) ) { return new WP_Error( 'acpw_test_choice', __( 'Choose a valid customer type.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } // admin-post does not load frontend cart helpers. Load functions without creating a cart/session. if ( ! function_exists( 'wc_get_cart_item_data_hash' ) ) { require_once WC_ABSPATH . 'includes/wc-cart-functions.php'; } // Read the catalogue only. Do not reuse customer snapshots or mutate the administrator's cart. $products = array(); foreach ( wc_get_products( array( 'status' => 'publish', 'type' => array( 'simple', 'variable' ), 'limit' => 20, 'orderby' => 'ID', 'order' => 'DESC' ) ) as $product ) { if ( $product->is_type( 'variable' ) ) { $variation = false; foreach ( $product->get_children() as $child_id ) { $child = wc_get_product( $child_id ); if ( $child && 'publish' === $child->get_status() && $child->is_purchasable() && $child->is_in_stock() && ! in_array( '', $child->get_attributes(), true ) ) { $variation = $child; break; } } if ( ! $variation ) { continue; } $product = $variation; } if ( $product->is_purchasable() && $product->is_in_stock() ) { $products[] = $product; } if ( count( $products ) >= 2 ) { break; } } if ( ! $products ) { return new WP_Error( 'acpw_test_products', __( 'No purchasable, in-stock simple product or explicit variation was found in the latest 20 published products. Add or make one available, then retry.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $cart = array(); $items = array(); $subtotal = 0.0; $tax_total = 0.0; $all_taxes = array(); foreach ( $products as $product ) { $vid = $product->is_type( 'variation' ) ? $product->get_id() : 0; $pid = $vid ? $product->get_parent_id() : $product->get_id(); $variation = $vid ? $product->get_variation_attributes() : array(); $key = md5( wp_json_encode( array( $pid, $vid, $variation ) ) ); $price = (float) wc_get_price_excluding_tax( $product, array( 'qty' => 1 ) ); $taxes = $product->is_taxable() ? WC_Tax::calc_tax( $price, WC_Tax::get_rates( $product->get_tax_class() ), false ) : array(); $tax = (float) array_sum( $taxes ); $line = array( 'key' => $key, 'product_id' => $pid, 'variation_id' => $vid, 'variation' => $variation, 'quantity' => 1, 'data_hash' => wc_get_cart_item_data_hash( $product ), 'line_tax_data' => array( 'subtotal' => $taxes, 'total' => $taxes ), 'line_subtotal' => $price, 'line_subtotal_tax' => $tax, 'line_total' => $price, 'line_tax' => $tax, 'data' => new stdClass(), ); $cart[ $key ] = $line; $items[] = array_merge( $line, array( 'product_name' => $product->get_name(), 'sku' => $product->get_sku(), 'product_url' => $product->get_permalink(), 'image_url' => wp_get_attachment_image_url( $product->get_image_id(), 'woocommerce_thumbnail' ) ?: '', ) ); $subtotal += $price; $tax_total += $tax; foreach ( $taxes as $tax_id => $amount ) { $all_taxes[ $tax_id ] = ( $all_taxes[ $tax_id ] ?? 0 ) + $amount; } } $address = array_fill_keys( array( 'first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'email', 'phone' ), '' ); $address['first_name'] = $user->first_name ?: $user->display_name; $address['last_name'] = $user->last_name; $address['email'] = $user->user_email; $address['country'] = WC()->countries->get_base_country(); $address['state'] = WC()->countries->get_base_state(); $settings = ACPW_Store::settings(); $now = time(); $entry = ACPW_Payload::augment( array( 'user_id' => '__guest__' === $role ? null : $user->ID, 'email' => $user->user_email, 'phone' => '', 'cart' => $cart, 'billing_address' => $address, 'shipping_address' => $address, 'timestamp' => $now, 'cart_items' => $items, 'currency' => get_woocommerce_currency(), 'coupons' => array(), 'totals' => array( 'subtotal' => $subtotal, 'subtotal_tax' => $tax_total, 'shipping_total' => 0, 'shipping_tax' => 0, 'shipping_taxes' => array(), 'discount_total' => 0, 'discount_tax' => 0, 'cart_contents_total' => $subtotal, 'cart_contents_tax' => $tax_total, 'cart_contents_taxes' => $all_taxes, 'fee_total' => 0, 'fee_tax' => 0, 'fee_taxes' => array(), 'total' => wc_format_decimal( $subtotal + $tax_total, wc_get_price_decimals() ), 'total_tax' => $tax_total, ), 'schema_version' => '1.0', 'event' => 'cart.abandoned', 'event_id' => wp_generate_uuid4(), 'cart_id' => wp_generate_uuid4(), 'created_at' => gmdate( 'c', $now ), 'last_activity_at' => gmdate( 'c', $now ), 'abandoned_at' => gmdate( 'c', $now ), 'checkout_url_expires_at' => ! empty( $settings['recovery_enabled'] ) ? gmdate( 'c', $now + (int) $settings['link_days'] * DAY_IN_SECONDS ) : '', 'recovery_enabled' => ! empty( $settings['recovery_enabled'] ), 'checkout_url' => '', 'is_test' => true, ) ); // Explicit simulation affects the test only. Never change the administrator's account roles. $entry['user_role'] = $roles[ $role ]; $entry['user_role_slug'] = '__guest__' === $role ? 'guest' : $role; $entry['user_roles'] = '__guest__' === $role ? array() : array( $roles[ $role ] ); return $entry; } public static function send( $role = '__guest__' ) { global $wpdb; $entry = self::build( $role ); if ( is_wp_error( $entry ) ) { return $entry; } $now = time(); // 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 -- Write plugin-owned transactional state through the WordPress database API; cached state would invalidate queue/privacy guarantees. $ok = $wpdb->insert( ACPW_Store::carts(), array( 'cart_uuid' => $entry['cart_id'], 'session_hash' => hash( 'sha256', 'admin-test:' . $entry['event_id'] ), 'user_id' => (int) $entry['user_id'], 'email' => $entry['email'], 'snapshot' => wp_json_encode( $entry ), 'content_hash' => ACPW_Payload::hash( $entry ), 'status' => 'test', 'created_at' => $now, 'updated_at' => $now, 'last_sent_at' => $now, ) ); if ( false !== $ok ) { // 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( ACPW_Store::events(), array( 'event_uuid' => $entry['event_id'], 'cart_uuid' => $entry['cart_id'], 'revision' => 1, 'payload' => wp_json_encode( $entry ), 'token_hash' => hash( 'sha256', ACPW_Delivery::token( $entry['event_id'] ) ), 'expires_at' => $now + (int) ACPW_Store::settings()['link_days'] * DAY_IN_SECONDS, 'status' => 'test_pending', 'next_attempt' => $now, 'created_at' => $now, ) ); } // 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. $committed = ( false === $ok ? $wpdb->query( 'ROLLBACK' ) : $wpdb->query( 'COMMIT' ) ); if ( false === $ok || false === $committed ) { return new WP_Error( 'acpw_test_storage', __( 'The test recovery link could not be saved. No webhook was sent.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $entry['checkout_url'] = ACPW_Delivery::recovery_url( $entry['event_id'] ); try { $response = ACPW_Delivery::post( $entry ); } catch ( Throwable $error ) { $response = new WP_Error( 'acpw_test_transport', __( 'The test webhook request could not be completed.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); $accepted = $code >= 200 && $code < 300; // 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. $wpdb->update( ACPW_Store::events(), array( 'status' => $accepted ? 'test_delivered' : 'test_failed', 'attempts' => 1, 'http_code' => $code, 'delivered_at' => $accepted ? time() : 0, 'last_error' => $accepted ? '' : ( $code ? 'HTTP ' . $code : __( 'Transport error', 'abandoned-cart-webhooks-for-woocommerce' ) ), ), array( 'event_uuid' => $entry['event_id'] ) ); ACPW_Store::trim_history(); return array( 'response' => $response, 'email' => $entry['email'], 'payload' => $entry ); } }