get_col( $wpdb->prepare( "SELECT cart_uuid FROM %i WHERE status = 'active' AND eligible_after <= UNIX_TIMESTAMP() AND updated_at <= %d AND (last_sent_at = 0 OR (%d > 0 AND last_sent_at <= %d)) ORDER BY updated_at ASC LIMIT 50", $carts, $now - (int) $settings['cutoff_minutes'] * MINUTE_IN_SECONDS, $repeat, $now - $repeat * HOUR_IN_SECONDS) ); foreach ( $eligible as $uuid ) { self::enqueue_cart( $uuid ); } // Recover a process killed after claiming an event. The stable ID makes ambiguous retries deduplicable. // 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( $wpdb->prepare( "UPDATE %i SET status = 'pending', lock_token = '', locked_until = 0 WHERE status = 'sending' AND locked_until < %d", $events, $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. $pending = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE status = 'pending' AND next_attempt <= %d ORDER BY next_attempt ASC LIMIT 50", $events, $now) ); foreach ( $pending as $id ) { if ( function_exists( 'as_has_scheduled_action' ) && ! as_has_scheduled_action( 'acpw_deliver', array( (int) $id ), self::GROUP ) ) { as_enqueue_async_action( 'acpw_deliver', array( (int) $id ), self::GROUP, true ); } } update_option( 'acpw_last_sweep', $now, false ); } public static function enqueue_cart( $uuid ) { global $wpdb; $settings = ACPW_Store::settings(); $carts = ACPW_Store::carts(); // 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", $carts, $uuid) ); if ( ! $row || 'active' !== $row->status || (int) $row->updated_at > time() - (int) $settings['cutoff_minutes'] * 60 || ( $row->last_sent_at && ( ! $settings['repeat_hours'] || (int) $row->last_sent_at > time() - (int) $settings['repeat_hours'] * 3600 ) ) ) { // 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; } $entry = ACPW_Payload::decode( $row->snapshot ); if ( ! is_array( $entry ) || empty( $entry['cart'] ) || ( ! empty( $settings['require_email'] ) && ! ACPW_Payload::email( $entry ) ) ) { // 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( $carts, array( 'status' => 'no_email' ), array( 'id' => $row->id ) ); // 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; } $email = strtolower( ACPW_Payload::email( $entry ) ); // Reservations share the event transaction: parallel carts cannot bypass recipient/global limits. // 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. $recent = $email ? $wpdb->get_var( $wpdb->prepare( "SELECT MAX(last_sent_at) FROM %i WHERE email = %s AND last_sent_at > %d", $carts, $email, time() - (int) $settings['email_cooldown_hours'] * HOUR_IN_SECONDS) ) : 0; if ( ( $email && ( $recent || ! ACPW_Store::allow( 'recipient', $email, 1, (int) $settings['email_cooldown_hours'] * HOUR_IN_SECONDS ) ) ) || ( (int) $settings['hourly_event_limit'] > 0 && ! ACPW_Store::allow( 'events', 'store', (int) $settings['hourly_event_limit'], HOUR_IN_SECONDS ) ) ) { // 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' ); $wait = max( time() + 60, $recent ? (int) $recent + (int) $settings['email_cooldown_hours'] * HOUR_IN_SECONDS : 0, ( $email ? ACPW_Store::window_end( 'recipient', $email ) : 0 ), ACPW_Store::window_end( 'events', 'store' ) ); // 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( $carts, array( 'eligible_after' => $wait ), array( 'id' => $row->id, 'status' => 'active', 'revision' => $row->revision ) ); return; } $entry = ACPW_Payload::augment( $entry ); $event_uuid = wp_generate_uuid4(); $entry['schema_version'] = '1.0'; $entry['event'] = 'cart.abandoned'; $entry['event_id'] = $event_uuid; $entry['cart_id'] = $uuid; $entry['timestamp'] = (int) $row->updated_at; $entry['created_at'] = gmdate( 'c', (int) $row->created_at ); $entry['last_activity_at'] = gmdate( 'c', (int) $row->updated_at ); $entry['abandoned_at'] = gmdate( 'c', (int) $row->updated_at + (int) $settings['cutoff_minutes'] * 60 ); $entry['recovery_enabled'] = ! empty( $settings['recovery_enabled'] ); $entry['checkout_url'] = ''; // Reconstructed only for delivery. No usable token in stored payloads/logs. $expires = time() + (int) $settings['link_days'] * DAY_IN_SECONDS; $entry['checkout_url_expires_at'] = $entry['recovery_enabled'] ? gmdate( 'c', $expires ) : ''; // 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' => $event_uuid, 'cart_uuid' => $uuid, 'revision' => (int) $row->revision, 'payload' => wp_json_encode( $entry ), 'token_hash' => hash( 'sha256', self::token( $event_uuid ) ), 'expires_at' => $expires, 'next_attempt' => time(), 'created_at' => time(), ) ); 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->update( $carts, array( 'status' => 'queued' ), array( 'id' => $row->id ) ); } // 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' ) ); } public static function headers( $event_uuid, $body ) { $headers = array( 'Content-Type' => 'application/json', 'X-ACPW-Event-ID' => $event_uuid ); $secret = ACPW_Store::settings()['signing_secret']; if ( $secret ) { // Keep v1 intact for existing The receiver filters; v2 binds the request time as well. $headers['X-ACPW-Signature'] = 'sha256=' . hash_hmac( 'sha256', $body, $secret ); $headers['X-ACPW-Timestamp'] = (string) time(); $headers['X-ACPW-Signature-V2'] = 'sha256=' . hash_hmac( 'sha256', $headers['X-ACPW-Timestamp'] . '.' . $body, $secret ); } return $headers; } public static function post( $entry ) { $settings = ACPW_Store::settings(); $url = $settings['webhook_url']; if ( ! $url || 'https' !== wp_parse_url( $url, PHP_URL_SCHEME ) || ! wp_http_validate_url( $url ) ) { return new WP_Error( 'acpw_invalid_url', __( 'A public HTTPS webhook URL is required.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $body = wp_json_encode( array( $entry ), JSON_UNESCAPED_SLASHES ); if ( false === $body ) { return new WP_Error( 'acpw_json_error', __( 'Payload encoding failed.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } return wp_safe_remote_post( $url, array( 'headers' => self::headers( $entry['event_id'], $body ), 'body' => $body, 'timeout' => 20, 'redirection' => 0, 'limit_response_size' => 1024, 'data_format' => 'body', ) ); } public static function deliver( $id ) { global $wpdb; if ( ! ACPW_Store::enabled() || ! ACPW_Store::settings()['webhook_url'] ) { return; } $table = ACPW_Store::events(); $carts = ACPW_Store::carts(); $lock = wp_generate_uuid4(); // 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. $claimed = $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'sending', lock_token = %s, locked_until = %d WHERE id = %d AND status = 'pending' AND next_attempt <= %d", $table, $lock, time() + 300, $id, time()) ); if ( 1 !== $claimed ) { 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 * FROM %i WHERE id = %d", $table, $id) ); $cart = ACPW_Store::cart( $event->cart_uuid ); $entry = ACPW_Payload::decode( $event->payload ); $settings = ACPW_Store::settings(); if ( ! $cart || 'queued' !== $cart->status || (int) $cart->revision !== (int) $event->revision || (int) $cart->updated_at > time() - (int) $settings['cutoff_minutes'] * 60 || ! is_array( $entry ) || ( ! empty( $settings['require_email'] ) && ! ACPW_Payload::email( $entry ) ) ) { // 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( $table, array( 'status' => 'cancelled', 'lock_token' => '', 'locked_until' => 0 ), array( 'id' => $id, 'lock_token' => $lock ) ); // A longer cutoff may have been saved after this event was queued. // 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( $wpdb->prepare( "UPDATE %i SET status = 'active', revision = revision + 1 WHERE cart_uuid = %s AND revision = %d AND status = 'queued'", $carts, $event->cart_uuid, $event->revision) ); return; } if ( (int) $event->expires_at <= time() || (int) $event->attempts >= self::MAX_ATTEMPTS ) { self::finish_failure( $event, $lock, __( 'Delivery limit or recovery-link expiry reached.', 'abandoned-cart-webhooks-for-woocommerce' ), 0, false ); return; } // Previously queued events may have been created with an older token derivation. // Re-key only at delivery, ensuring the transmitted recovery URL matches storage. // Already delivered links retain their original stored hashes and remain usable. $new_hash = hash( 'sha256', self::token( $event->event_uuid ) ); if ( ! hash_equals( (string) $event->token_hash, $new_hash ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Re-key only this claimed plugin-owned event before delivering its recovery URL. if ( false === $wpdb->update( $table, array( 'token_hash' => $new_hash ), array( 'id' => $id, 'lock_token' => $lock ) ) ) { self::finish_failure( $event, $lock, __( 'Could not update recovery token.', 'abandoned-cart-webhooks-for-woocommerce' ), 0, true ); return; } } $entry['recovery_enabled'] = ! empty( $settings['recovery_enabled'] ) && ( ! array_key_exists( 'recovery_enabled', $entry ) || ! empty( $entry['recovery_enabled'] ) ); $entry['checkout_url'] = $entry['recovery_enabled'] ? self::recovery_url( $event->event_uuid ) : wc_get_checkout_url(); if ( ! $entry['recovery_enabled'] ) { $entry['checkout_url_expires_at'] = ''; } $response = self::post( $entry ); $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); if ( $code >= 200 && $code < 300 ) { // 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' ); // Match capture's cart-before-event lock order. // 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->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE cart_uuid = %s FOR UPDATE", $carts, $event->cart_uuid) ); // 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, array( 'status' => 'delivered', 'attempts' => (int) $event->attempts + 1, 'http_code' => $code, 'last_error' => '', 'delivered_at' => time(), 'lock_token' => '', 'locked_until' => 0 ), array( 'id' => $id, 'lock_token' => $lock ) ); if ( $ok ) { // 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. $ok = $wpdb->query( $wpdb->prepare( "UPDATE %i SET last_sent_at = %d, status = CASE WHEN status IN ('queued','active','no_email','failed') AND (%d = 0 OR revision = %d) THEN 'sent' ELSE status END WHERE cart_uuid = %s", $carts, time(), (int) $settings['repeat_hours'], (int) $event->revision, $event->cart_uuid) ); } // 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' ) ); ACPW_Store::trim_history(); return; } $retry = 0 === $code || in_array( $code, array( 408, 425, 429 ), true ) || $code >= 500; $error = is_wp_error( $response ) ? 'Transport: ' . sanitize_key( $response->get_error_code() ) : 'HTTP ' . $code; self::finish_failure( $event, $lock, $error, $code, $retry ); } private static function finish_failure( $event, $lock, $error, $code, $retry ) { global $wpdb; // 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. $cart = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE cart_uuid = %s FOR UPDATE", ACPW_Store::carts(), $event->cart_uuid) ); $current = $cart && 'queued' === $cart->status && (int) $cart->revision === (int) $event->revision; $attempts = (int) $event->attempts + 1; $retry = $retry && $current && $attempts < self::MAX_ATTEMPTS && (int) $event->expires_at > time(); $delays = array( 60, 300, 900, 3600, 10800 ); // 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( ACPW_Store::events(), array( 'status' => ! $current ? 'cancelled' : ( $retry ? 'pending' : 'failed' ), 'attempts' => $attempts, 'next_attempt' => time() + $delays[ min( $attempts - 1, 4 ) ], 'http_code' => $code, 'last_error' => $error, 'lock_token' => '', 'locked_until' => 0, ), array( 'id' => $event->id, 'lock_token' => $lock ) ); if ( $ok && ! $retry && $current ) { // 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. $ok = $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'failed' WHERE cart_uuid = %s AND revision = %d AND status = 'queued'", ACPW_Store::carts(), $event->cart_uuid, $event->revision) ); } // 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' ) ); ACPW_Store::trim_history(); } }