prefix . 'acpw_carts'; } public static function events() { global $wpdb; return $wpdb->prefix . 'acpw_events'; } public static function rates() { global $wpdb; return $wpdb->prefix . 'acpw_rates'; } /** Atomic fixed-duration bucket. Denied requests do not extend the window. No raw IP/email stored. */ public static function allow( $scope, $identity, $limit, $seconds ) { global $wpdb; $key = hash_hmac( 'sha256', $scope . ':' . $identity, wp_salt( 'auth' ) ); $now = time(); $table = self::rates(); // 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( "INSERT INTO %i (rate_key,hits,expires_at) VALUES (%s,1,%d) ON DUPLICATE KEY UPDATE hits = IF(expires_at <= %d,1,LEAST(hits + 1,%d)), expires_at = IF(expires_at <= %d,%d,expires_at)", $table, $key, $now + $seconds, $now, $limit + 1, $now, $now + $seconds) ); if ( false === $ok ) { return false; } // In enqueue_cart this read is protected by its transaction's write lock. // 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. $hits = $wpdb->get_var( $wpdb->prepare( "SELECT hits FROM %i WHERE rate_key = %s", $table, $key) ); return null !== $hits && (int) $hits <= $limit; } public static function forget( $scope, $identity ) { global $wpdb; $key = hash_hmac( 'sha256', $scope . ':' . $identity, wp_salt( 'auth' ) ); // 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. return false !== $wpdb->delete( self::rates(), array( 'rate_key' => $key ) ); } public static function window_end( $scope, $identity ) { global $wpdb; $key = hash_hmac( 'sha256', $scope . ':' . $identity, wp_salt( 'auth' ) ); // 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. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT expires_at FROM %i WHERE rate_key = %s", self::rates(), $key) ); } public static function settings() { return wp_parse_args( (array) get_option( 'acpw_settings', array() ), array( 'enabled' => 0, 'webhook_url' => '', 'cutoff_minutes' => 1440, 'repeat_hours' => 0, 'link_days' => 7, 'recovery_enabled' => 0, 'require_email' => 1, 'email_cooldown_hours' => 24, 'hourly_event_limit' => 100, 'item_metadata' => 'full', 'retention_days' => 30, 'history_limit' => 500, 'signing_secret' => '', 'delete_data' => 0, ) ); } /** A stable secret confined to cart recovery, independent of WordPress login salts. */ public static function recovery_secret() { $secret = get_option( 'acpw_recovery_secret', '' ); if ( is_string( $secret ) && strlen( $secret ) >= 32 ) { return $secret; } $candidate = bin2hex( random_bytes( 32 ) ); add_option( 'acpw_recovery_secret', $candidate, '', false ); $secret = get_option( 'acpw_recovery_secret', '' ); if ( ! is_string( $secret ) || strlen( $secret ) < 32 ) { throw new RuntimeException( 'Unable to initialize the cart recovery secret.' ); } return $secret; } public static function install() { global $wpdb; if ( ! ACPW_Compat::migrate() ) { return; } ACPW_Compat::retire_previous_schedule(); require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $charset = $wpdb->get_charset_collate(); $carts = self::carts(); $events = self::events(); dbDelta( "CREATE TABLE $carts ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, cart_uuid char(36) NOT NULL, session_hash char(64) NOT NULL, user_id bigint(20) unsigned NOT NULL DEFAULT 0, email varchar(254) NOT NULL DEFAULT '', snapshot longtext NOT NULL, content_hash char(64) NOT NULL, revision bigint(20) unsigned NOT NULL DEFAULT 1, status varchar(20) NOT NULL DEFAULT 'active', created_at bigint(20) unsigned NOT NULL, updated_at bigint(20) unsigned NOT NULL, eligible_after bigint(20) unsigned NOT NULL DEFAULT 0, last_sent_at bigint(20) unsigned NOT NULL DEFAULT 0, order_id bigint(20) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE KEY cart_uuid (cart_uuid), KEY status_updated (status,updated_at), KEY session_hash (session_hash), KEY email (email) ) ENGINE=InnoDB $charset;" ); dbDelta( "CREATE TABLE $events ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, event_uuid char(36) NOT NULL, cart_uuid char(36) NOT NULL, revision bigint(20) unsigned NOT NULL, payload longtext NOT NULL, token_hash char(64) NOT NULL, expires_at bigint(20) unsigned NOT NULL, status varchar(20) NOT NULL DEFAULT 'pending', attempts int(10) unsigned NOT NULL DEFAULT 0, next_attempt bigint(20) unsigned NOT NULL, locked_until bigint(20) unsigned NOT NULL DEFAULT 0, lock_token char(36) NOT NULL DEFAULT '', http_code int(10) unsigned NOT NULL DEFAULT 0, last_error varchar(190) NOT NULL DEFAULT '', created_at bigint(20) unsigned NOT NULL, delivered_at bigint(20) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE KEY event_uuid (event_uuid), UNIQUE KEY cart_revision (cart_uuid,revision), UNIQUE KEY token_hash (token_hash), KEY status_next (status,next_attempt) ) ENGINE=InnoDB $charset;" ); $rates = self::rates(); dbDelta( "CREATE TABLE $rates ( rate_key char(64) NOT NULL, hits bigint(20) unsigned NOT NULL DEFAULT 0, expires_at bigint(20) unsigned NOT NULL, PRIMARY KEY (rate_key), KEY expires_at (expires_at) ) ENGINE=InnoDB $charset;" ); // dbDelta() can return without creating every table, including when DB privileges // or the storage engine prevent installation. Do not mark incomplete installs ready. foreach ( array( $carts, $events, $rates ) as $table ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Confirm plugin-owned storage exists before allowing capture/delivery. $exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ); if ( $table !== $exists ) { update_option( 'acpw_install_error', 'missing_tables', false ); delete_option( 'acpw_db_version' ); return false; } } if ( false === get_option( 'acpw_settings', false ) ) { add_option( 'acpw_settings', self::settings(), '', false ); } // Generate the independent recovery secret before the plugin can queue events. try { self::recovery_secret(); } catch ( RuntimeException $error ) { update_option( 'acpw_install_error', 'recovery_secret', false ); delete_option( 'acpw_db_version' ); return false; } delete_option( 'acpw_install_error' ); update_option( 'acpw_db_version', ACPW_VERSION, false ); return true; } public static function cart( $uuid ) { 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. return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE cart_uuid = %s", self::carts(), $uuid) ); } public static function cancel( $uuid ) { global $wpdb; // A request already in flight must retain its claim so its actual result can be recorded. // 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 = 'cancelled', lock_token = '', locked_until = 0 WHERE cart_uuid = %s AND status = 'pending'", self::events(), $uuid) ); } public static function close( $uuid, $status, $order_id = 0 ) { global $wpdb; if ( ! $uuid ) { return; } // 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( self::carts(), array( 'status' => $status, 'order_id' => (int) $order_id, 'updated_at' => time() ), array( 'cart_uuid' => $uuid ) ); self::cancel( $uuid ); } public static function cleanup() { 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( $wpdb->prepare( "DELETE FROM %i WHERE expires_at <= %d LIMIT 500", self::rates(), time()) ); $settings = self::settings(); $cutoff = time() - (int) $settings['retention_days'] * DAY_IN_SECONDS; $events = self::events(); $carts = self::carts(); // Expired abandoned requests must not retain personal data forever when delivery is paused. // 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 = 'cancelled', lock_token = '', locked_until = 0 WHERE expires_at <= %d AND (status = 'pending' OR (status = 'sending' AND locked_until < %d)) LIMIT 500", $events, time(), 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( $wpdb->prepare( "UPDATE %i SET status = 'test_failed' WHERE status = 'test_pending' AND created_at < %d LIMIT 500", $events, time() - 300) ); // Never remove an unexpired recovery link; delete bounded batches only. // 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( "DELETE FROM %i WHERE created_at < %d AND expires_at < %d AND status NOT IN ('pending','sending') LIMIT 500", $events, $cutoff, 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( $wpdb->prepare( "DELETE FROM %i WHERE updated_at < %d AND cart_uuid NOT IN (SELECT cart_uuid FROM %i) LIMIT 500", $carts, $cutoff, $events) ); self::trim_history(); } public static function history_statuses() { return "'delivered','failed','cancelled','test_delivered','test_failed'"; } public static function history_count() { 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. return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status IN ('delivered','failed','cancelled','test_delivered','test_failed')", self::events() )); } /** Count is a target: pending requests and live CUSTOMER links always take precedence. */ public static function trim_history() { global $wpdb; $limit = max( 0, (int) self::settings()['history_limit'] ); if ( ! $limit ) { return 0; } $excess = self::history_count() - $limit; if ( $excess <= 0 ) { return 0; } // Keep the newest X records even if older protected links put storage above the target. // 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. $boundary = $wpdb->get_row( $wpdb->prepare( "SELECT id, created_at FROM %i WHERE status IN ('delivered','failed','cancelled','test_delivered','test_failed') ORDER BY created_at DESC, id DESC LIMIT 1 OFFSET %d", self::events(), $limit - 1 ) ); if ( ! $boundary ) { return 0; } // 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. $removed = $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE status IN ('delivered','failed','cancelled','test_delivered','test_failed') AND (expires_at <= %d OR status IN ('test_delivered','test_failed')) AND (created_at < %d OR (created_at = %d AND id < %d)) ORDER BY created_at ASC, id ASC LIMIT %d", self::events(), time(), $boundary->created_at, $boundary->created_at, $boundary->id, min( 500, $excess )) ); self::remove_orphan_test_carts(); return false === $removed ? 0 : (int) $removed; } private static function remove_orphan_test_carts() { global $wpdb; // Only standalone test snapshots. Real-cart rows retain send-once and order-suppression state. // 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( "DELETE FROM %i WHERE status = 'test' AND cart_uuid NOT IN (SELECT cart_uuid FROM %i) LIMIT 500", self::carts(), self::events() )); } public static function clear_history( $scope, $invalidate_links = false ) { global $wpdb; if ( ! in_array( $scope, array( 'tests', 'expired', 'completed' ), true ) ) { return new WP_Error( 'acpw_clear_scope', __( 'Choose a valid history scope.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } if ( 'completed' === $scope && ! $invalidate_links ) { return new WP_Error( 'acpw_clear_confirmation', __( 'Confirm that deleting completed history invalidates its remaining recovery links.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } // Bound each manual request. The scope selects fixed SQL, never caller-supplied SQL. if ( 'tests' === $scope ) { // 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. $removed = $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE status IN ('test_delivered','test_failed') ORDER BY created_at ASC, id ASC LIMIT 500", self::events() ) ); } elseif ( 'expired' === $scope ) { // 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. $removed = $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE status IN ('delivered','failed','cancelled','test_delivered','test_failed') AND expires_at <= %d ORDER BY created_at ASC, id ASC LIMIT 500", self::events(), time() ) ); } else { // 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. $removed = $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE status IN ('delivered','failed','cancelled','test_delivered','test_failed') ORDER BY created_at ASC, id ASC LIMIT 500", self::events() ) ); } if ( false === $removed ) { return new WP_Error( 'acpw_clear_storage', __( 'History could not be cleared. Please retry.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } self::remove_orphan_test_carts(); return (int) $removed; } }