array( __CLASS__, 'sanitize' ) ) ); } ); add_filter( 'option_page_capability_acpw_group', static function () { return 'manage_options'; } ); add_action( 'admin_post_acpw_test', array( __CLASS__, 'test' ) ); add_action( 'admin_post_acpw_retry', array( __CLASS__, 'retry' ) ); add_action( 'admin_post_acpw_clear_history', array( __CLASS__, 'clear_history' ) ); add_action( 'update_option_acpw_settings', array( 'ACPW_Store', 'trim_history' ), 10, 0 ); add_action( 'admin_notices', array( __CLASS__, 'notices' ) ); add_filter( 'plugin_action_links_' . plugin_basename( ACPW_FILE ), static function ( $links ) { array_unshift( $links, '' . esc_html__( 'Settings', 'abandoned-cart-webhooks-for-woocommerce' ) . '' ); return $links; } ); } public static function sanitize( $input ) { $old = ACPW_Store::settings(); if ( ACPW_Compat::previous_active() || get_option( 'acpw_db_version' ) !== ACPW_VERSION ) { add_settings_error( 'acpw_settings', 'upgrade', __( 'Deactivate the previous build and complete storage migration before saving settings.', 'abandoned-cart-webhooks-for-woocommerce' ) ); return $old; } $input = is_array( $input ) ? $input : array(); $value = $old; // Each checkbox has an explicit zero-value form field. A partial or unrelated // options update must never enable an opt-in feature by accident. foreach ( array( 'enabled', 'recovery_enabled', 'delete_data', 'require_email' ) as $flag ) { if ( array_key_exists( $flag, $input ) ) { $value[ $flag ] = ( '1' === (string) $input[ $flag ] ) ? 1 : 0; } } // Recovery is a separate opt-in, not a consequence of enabling capture. // A previously disabled installation requires positive confirmation of // this sensitive feature before it can transition to enabled. if ( empty( $old['recovery_enabled'] ) && ! empty( $value['recovery_enabled'] ) ) { if ( ! isset( $input['recovery_confirm'] ) || '1' !== (string) $input['recovery_confirm'] ) { $value['recovery_enabled'] = 0; add_settings_error( 'acpw_settings', 'recovery_confirmation', __( 'Cart recovery was kept off. To enable it, check both the recovery option and its separate confirmation, then save again.', 'abandoned-cart-webhooks-for-woocommerce' ), 'error' ); } } $url = isset( $input['webhook_url'] ) && is_string( $input['webhook_url'] ) ? esc_url_raw( trim( $input['webhook_url'] ) ) : ''; if ( $url && ( 'https' !== wp_parse_url( $url, PHP_URL_SCHEME ) || ! wp_http_validate_url( $url ) ) ) { add_settings_error( 'acpw_settings', 'url', __( 'Enter a public HTTPS webhook URL. The previous URL has been retained.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } elseif ( ! empty( $input['clear_url'] ) ) { $value['webhook_url'] = ''; } elseif ( $url ) { $value['webhook_url'] = $url; } foreach ( array( 'cutoff_minutes' => array( 1, 43200 ), 'repeat_hours' => array( 0, 8760 ), 'link_days' => array( 1, 90 ), 'retention_days' => array( 2, 365 ), 'history_limit' => array( 0, 100000 ), 'email_cooldown_hours' => array( 1, 8760 ), 'hourly_event_limit' => array( 0, 1000000 ) ) as $key => list( $min, $max ) ) { $number = isset( $input[ $key ] ) && is_scalar( $input[ $key ] ) ? (int) $input[ $key ] : (int) $old[ $key ]; $value[ $key ] = max( $min, min( $max, $number ) ); } $value['item_metadata'] = isset( $input['item_metadata'] ) && in_array( $input['item_metadata'], array( 'full', 'minimal' ), true ) ? $input['item_metadata'] : $old['item_metadata']; $value['retention_days'] = max( $value['retention_days'], $value['link_days'] + 1 ); if ( ! empty( $input['clear_secret'] ) ) { $value['signing_secret'] = ''; } elseif ( ! empty( $input['signing_secret'] ) && is_string( $input['signing_secret'] ) ) { $value['signing_secret'] = substr( trim( $input['signing_secret'] ), 0, 254 ); } if ( $value['enabled'] && ! $value['webhook_url'] ) { $value['enabled'] = 0; add_settings_error( 'acpw_settings', 'missing_url', 'Set a webhook URL before enabling delivery.' ); } if ( $value['enabled'] !== $old['enabled'] ) { add_settings_error( 'acpw_settings', 'tracking_state', $value['enabled'] ? __( 'Tracking and eligible webhook delivery enabled.', 'abandoned-cart-webhooks-for-woocommerce' ) : __( 'Tracking and eligible webhook delivery disabled.', 'abandoned-cart-webhooks-for-woocommerce' ), 'updated' ); } if ( $value['recovery_enabled'] !== $old['recovery_enabled'] ) { add_settings_error( 'acpw_settings', 'recovery_state', $value['recovery_enabled'] ? __( 'Saved-cart recovery explicitly enabled.', 'abandoned-cart-webhooks-for-woocommerce' ) : __( 'Saved-cart recovery disabled.', 'abandoned-cart-webhooks-for-woocommerce' ), 'updated' ); } if ( ! empty( $old['require_email'] ) && empty( $value['require_email'] ) ) { // Carts excluded under the former email requirement can now join the normal queue. global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Plugin-owned cart state; requalification is intentionally performed only when this setting changes. $wpdb->update( ACPW_Store::carts(), array( 'status' => 'active' ), array( 'status' => 'no_email' ) ); } delete_option( 'acpw_upgrade_notice' ); return $value; } public static function notices() { if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'activate_plugins' ) ) { return; } if ( get_option( 'acpw_install_error' ) ) { echo '

' . esc_html__( 'Cart Webhooks storage initialization did not complete. Confirm database table permissions and retry activation or reload the plugin. Tracking and deliveries remain paused until installation succeeds.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } if ( get_option( 'acpw_migration_error' ) ) { echo '

' . esc_html( ACPW_Compat::migration_error_message() ) . '

'; } if ( get_option( 'acpw_upgrade_notice' ) ) { echo '

' . esc_html__( 'Previous settings and stored carts were migrated. Tracking is paused and cart recovery is off. Review settings and explicitly enable the features you want.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } if ( ! class_exists( 'WooCommerce' ) ) { echo '

' . esc_html__( 'Abandoned Cart Webhooks for WooCommerce requires WooCommerce to be active.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } elseif ( ACPW_Compat::previous_active() ) { echo '

' . esc_html__( 'Tracking and delivery are paused while the previous build is active. Deactivate the previous build before using this plugin.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } } public static function page() { global $wpdb; if ( ! current_user_can( 'manage_options' ) ) { return; } if ( ACPW_Compat::previous_active() || get_option( 'acpw_db_version' ) !== ACPW_VERSION ) { echo '

' . esc_html__( 'Abandoned Cart Webhooks for WooCommerce', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Deactivate the previous build and complete storage migration before using these controls.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; return; } $settings = ACPW_Store::settings(); echo '

' . esc_html__( 'Abandoned Cart Webhooks for WooCommerce', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Complete cart data to your webhook. Customer role labels come from this store’s registered WordPress roles; shoppers without an account are identified as guests.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; settings_errors( 'acpw_settings' ); $result = get_transient( 'acpw_admin_result_' . get_current_user_id() ); if ( $result ) { delete_transient( 'acpw_admin_result_' . get_current_user_id() ); echo '

' . esc_html( $result ) . '

'; } if ( ! function_exists( 'as_schedule_recurring_action' ) ) { echo '

' . esc_html__( 'Action Scheduler is unavailable. Delivery cannot run. Check WooCommerce activation.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { echo '

' . esc_html__( 'WP-Cron is disabled. A working hosting/server cron must run WordPress scheduled tasks.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; } $last = (int) get_option( 'acpw_last_sweep', 0 ); echo '

' . esc_html__( 'Last queue check:', 'abandoned-cart-webhooks-for-woocommerce' ) . ' ' . ( $last ? esc_html( wp_date( 'm/d/y H:i:s', $last ) ) : esc_html__( 'Not run yet', 'abandoned-cart-webhooks-for-woocommerce' ) ) . '. ' . esc_html__( 'Due carts are checked approximately once per minute when scheduled tasks run.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; self::test_controls(); echo '

' . esc_html__( 'Settings', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; echo '
'; settings_fields( 'acpw_group' ); echo ''; echo ''; echo ''; self::number( 'cutoff_minutes', __( 'Inactivity cutoff (minutes)', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 1, 43200, __( '1440 = one day. Cart and checkout changes reset the timer; ordinary page views do not.', 'abandoned-cart-webhooks-for-woocommerce' ) ); self::number( 'repeat_hours', __( 'Repeat interval (hours)', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 0, 8760, __( '0 = one successful abandonment webhook per cart. A positive value permits a new episode only after further activity and this interval.', 'abandoned-cart-webhooks-for-woocommerce' ) ); self::number( 'email_cooldown_hours', __( 'Recipient cooldown (hours)', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 1, 8760, __( 'Default 24. At most one new normal event per email in this interval, across carts. Failed delivery still reserves the interval; retries retain the same event. Manual admin tests are excluded.', 'abandoned-cart-webhooks-for-woocommerce' ) ); self::number( 'hourly_event_limit', __( 'New events per hour', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 0, 1000000, __( 'Default 100; 0 = no hourly cap. Store-wide limit on new normal events in an hour-long window. Excess carts wait for a later sweep; existing retries and manual tests are excluded.', 'abandoned-cart-webhooks-for-woocommerce' ) ); echo ''; echo ''; self::number( 'link_days', __( 'Recovery-link lifetime (days)', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 1, 90, __( 'Links remain reusable until expiry or checkout. The customer confirms restoration before anything changes.', 'abandoned-cart-webhooks-for-woocommerce' ) ); self::number( 'retention_days', __( 'Data retention (days)', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 2, 365, __( 'Automatically increased when needed to outlast recovery links. Old records are removed in bounded batches on every scheduled queue check, even while paused.', 'abandoned-cart-webhooks-for-woocommerce' ) ); self::number( 'history_limit', __( 'Completed history limit', 'abandoned-cart-webhooks-for-woocommerce' ), $settings, 0, 100000, __( 'Target number of completed delivery records to retain. 0 = age retention only. Oldest removable records go first. Pending deliveries and unexpired customer recovery links are protected, so the total may exceed this target. Old test links may be removed early.', 'abandoned-cart-webhooks-for-woocommerce' ) ); echo ''; echo '
' . esc_html__( 'Enable', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . ( $settings['webhook_url'] ? esc_html__( 'A URL is saved. Leave blank to retain it.', 'abandoned-cart-webhooks-for-woocommerce' ) : esc_html__( 'No URL saved.', 'abandoned-cart-webhooks-for-woocommerce' ) ) . ' ' . esc_html__( 'Enter a public HTTPS destination. Email-less carts can be included using the optional setting below.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Customer email requirement', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Enabled by default. Uncheck to deliver otherwise eligible carts without an email. Missing emails are sent as empty strings; these events have a cart ID but no email recipient. Recipient cooldowns apply only to carts with valid emails. Store-wide delivery limits still apply.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Cart item metadata', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Full includes JSON-safe extension metadata. Minimal excludes arbitrary extension fields from new snapshots. Existing snapshots/events are unchanged.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Cart recovery', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . ( empty( $settings['recovery_enabled'] ) ? '

' : '' ) . '

' . esc_html__( 'Off by default, including upgrades. When off, checkout_url is the ordinary checkout page and saved-cart recovery links do not work. When enabled, anyone holding the emailed link can restore its items, including guests on another device. A forwarded link also works. Email ownership is not verified; no verification emails or codes are sent. A final confirmation restores items at current prices, with merge/replace choices. No sign-in or address transfer occurs. Review your privacy notice and local requirements before enabling.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . ( $settings['signing_secret'] ? esc_html__( 'A secret is set. Leave blank to retain it.', 'abandoned-cart-webhooks-for-woocommerce' ) : esc_html__( 'No secret set.', 'abandoned-cart-webhooks-for-woocommerce' ) ) . ' ' . esc_html__( 'X-ACPW-Signature retains HMAC(body). X-ACPW-Signature-V2 signs timestamp.body using X-ACPW-Timestamp. The receiver must verify the signature, reject timestamps older than 5 minutes and deduplicate event_id. Leaving the secret unset disables both signatures.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Uninstall', 'abandoned-cart-webhooks-for-woocommerce' ) . '
'; submit_button( __( 'Save settings', 'abandoned-cart-webhooks-for-woocommerce' ) ); echo '

' . esc_html__( 'Cart status', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; // 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. $counts = $wpdb->get_results( $wpdb->prepare( "SELECT status, COUNT(*) AS total FROM %i GROUP BY status", ACPW_Store::carts() )); foreach ( $counts as $count ) { echo '' . esc_html( $count->status ) . ': ' . esc_html( $count->total ) . '   '; } if ( ! $counts ) { echo esc_html__( 'No carts captured yet. Tracking begins after activation and enablement.', 'abandoned-cart-webhooks-for-woocommerce' ); } // 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_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i", 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. $event_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i", ACPW_Store::events() )); echo '

' . esc_html__( 'Stored cart records:', 'abandoned-cart-webhooks-for-woocommerce' ) . ' ' . esc_html( $cart_count ) . '   ' . esc_html__( 'Stored delivery records:', 'abandoned-cart-webhooks-for-woocommerce' ) . ' ' . esc_html( $event_count ) . '   ' . esc_html__( 'Completed delivery records:', 'abandoned-cart-webhooks-for-woocommerce' ) . ' ' . esc_html( ACPW_Store::history_count() ) . '

'; self::pending_carts( $settings ); self::history_controls(); /* translators: 1: displayed delivery count, 2: total stored delivery count. */ $history_summary = sprintf( __( 'Showing the newest %1$d of %2$d stored delivery records (display limit: 50). No email addresses, webhook secrets, full payloads or usable recovery tokens are shown here. A delivered status confirms endpoint acceptance, not completion of downstream receiver steps.', 'abandoned-cart-webhooks-for-woocommerce' ), min( 50, $event_count ), $event_count ); echo '

' . esc_html__( 'Recent deliveries', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html( $history_summary ) . '

'; // 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. $events = $wpdb->get_results( $wpdb->prepare( "SELECT id,event_uuid,cart_uuid,revision,status,attempts,http_code,last_error,created_at,expires_at FROM %i ORDER BY id DESC LIMIT 50", ACPW_Store::events() )); foreach ( $events as $event ) { echo ''; } if ( ! $events ) { echo ''; } echo '
' . esc_html__( 'Created', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'Event ID', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'Status', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'Attempts', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'HTTP', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'Result', 'abandoned-cart-webhooks-for-woocommerce' ) . '' . esc_html__( 'Action', 'abandoned-cart-webhooks-for-woocommerce' ) . '
' . esc_html( wp_date( 'm/d/y H:i', (int) $event->created_at ) ) . '' . esc_html( $event->event_uuid ) . '' . esc_html( $event->status ) . '' . esc_html( $event->attempts ) . '' . esc_html( $event->http_code ?: '-' ) . '' . esc_html( $event->last_error ) . ''; if ( 'failed' === $event->status && (int) $event->expires_at > time() ) { echo '
'; wp_nonce_field( 'acpw_retry_' . $event->id ); echo '
'; } echo '
' . esc_html__( 'No abandonment deliveries yet.', 'abandoned-cart-webhooks-for-woocommerce' ) . '
'; } /** Read-only inspection of saved carts. No cart or event is modified. */ private static function pending_carts( $settings ) { global $wpdb; $statuses = array( 'active', 'queued', 'failed', 'sent', 'all' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameters affect display only. $filter = isset( $_GET['acpw_cart_status'] ) && is_string( $_GET['acpw_cart_status'] ) ? sanitize_key( wp_unslash( $_GET['acpw_cart_status'] ) ) : 'active'; $filter = in_array( $filter, $statuses, true ) ? $filter : 'active'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only pagination. $page = isset( $_GET['acpw_cart_page'] ) ? max( 1, absint( $_GET['acpw_cart_page'] ) ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only sorting. $order = isset( $_GET['acpw_cart_order'] ) && is_string( $_GET['acpw_cart_order'] ) ? sanitize_key( wp_unslash( $_GET['acpw_cart_order'] ) ) : 'eligible'; $order = in_array( $order, array( 'eligible', 'activity' ), true ) ? $order : 'eligible'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only email filter. $with_email = isset( $_GET['acpw_with_email'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['acpw_with_email'] ) ); $limit = 25; $table = ACPW_Store::carts(); // All filter values are validated against allowlists above. The queries // use placeholders for the table name and every variable value. // This plugin-owned, frequently updated table is read live in an admin-only // view; caching here would require invalidation on every cart update. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Live admin view of the plugin-owned, frequently updated cart table. $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE status IN ('active', 'queued', 'failed', 'sent') AND (%s = 'all' OR status = %s) AND (%d = 0 OR (email IS NOT NULL AND TRIM(email) <> ''))", $table, $filter, $filter, $with_email ? 1 : 0 ) ); $pages = max( 1, (int) ceil( $total / $limit ) ); $page = min( $page, $pages ); $offset = ( $page - 1 ) * $limit; $cutoff_seconds = (int) $settings['cutoff_minutes'] * MINUTE_IN_SECONDS; if ( 'activity' === $order ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Live paginated admin view of the plugin-owned cart table. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, cart_uuid, email, snapshot, status, updated_at, eligible_after, last_sent_at FROM %i WHERE status IN ('active', 'queued', 'failed', 'sent') AND (%s = 'all' OR status = %s) AND (%d = 0 OR (email IS NOT NULL AND TRIM(email) <> '')) ORDER BY updated_at DESC, id DESC LIMIT %d OFFSET %d", $table, $filter, $filter, $with_email ? 1 : 0, $limit, $offset ) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Live paginated admin view of the plugin-owned cart table. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, cart_uuid, email, snapshot, status, updated_at, eligible_after, last_sent_at FROM %i WHERE status IN ('active', 'queued', 'failed', 'sent') AND (%s = 'all' OR status = %s) AND (%d = 0 OR (email IS NOT NULL AND TRIM(email) <> '')) ORDER BY GREATEST(updated_at + %d, eligible_after) ASC, id ASC LIMIT %d OFFSET %d", $table, $filter, $filter, $with_email ? 1 : 0, $cutoff_seconds, $limit, $offset ) ); } $base = admin_url( 'admin.php?page=' . self::PAGE ); echo '

' . esc_html__( 'Pending carts', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; echo '

' . esc_html__( 'Read-only view of stored carts. Active carts have not yet been queued; queued and failed carts have delivery events. Eligibility times describe inactivity, not email qualification. Scheduled tasks, email validity and delivery limits may affect actual sending.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; echo '
'; echo '

' . esc_html( sprintf( /* translators: 1: first visible cart, 2: last visible cart, 3: total carts. */ __( 'Showing %1$d–%2$d of %3$d carts', 'abandoned-cart-webhooks-for-woocommerce' ), $total ? $offset + 1 : 0, min( $offset + $limit, $total ), $total ) ) . '

'; echo '
'; foreach ( array( __( 'Cart ID', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Last activity', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Customer email', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Cart total', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Items', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Customer type', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Status', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Eligible at', 'abandoned-cart-webhooks-for-woocommerce' ), __( 'Time remaining', 'abandoned-cart-webhooks-for-woocommerce' ) ) as $heading ) { echo ''; } echo ''; $now = time(); foreach ( $rows as $row ) { $entry = json_decode( $row->snapshot, true ); $entry = is_array( $entry ) ? $entry : array(); $items = 0; foreach ( (array) ( $entry['cart'] ?? array() ) as $line ) { if ( is_array( $line ) ) { $items += (float) ( $line['quantity'] ?? 0 ); } } $amount = $entry['totals']['total'] ?? null; $currency = isset( $entry['currency'] ) && is_string( $entry['currency'] ) ? $entry['currency'] : ''; $total_text = is_numeric( $amount ) ? number_format_i18n( (float) $amount, wc_get_price_decimals() ) . ' ' . $currency : '—'; $eligible_at = max( (int) $row->updated_at + $cutoff_seconds, (int) $row->eligible_after ); $waiting = 'active' === $row->status; $time_remaining = $waiting ? max( 0, $eligible_at - $now ) : 0; $remaining_text = ! $waiting ? __( 'Not applicable', 'abandoned-cart-webhooks-for-woocommerce' ) : ( $time_remaining ? sprintf( /* translators: 1: hours, 2: minutes */ __( '%1$dh %2$dm', 'abandoned-cart-webhooks-for-woocommerce' ), (int) floor( $time_remaining / HOUR_IN_SECONDS ), (int) ceil( ( $time_remaining % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS ) ) : __( 'Due for queue check', 'abandoned-cart-webhooks-for-woocommerce' ) ); echo ''; } if ( ! $rows ) { echo ''; } echo '
' . esc_html( $heading ) . '
' . esc_html( substr( (string) $row->cart_uuid, 0, 8 ) ) . '' . esc_html( wp_date( 'm/d/y H:i', (int) $row->updated_at ) ) . '' . esc_html( $row->email ?: '—' ) . '' . esc_html( $total_text ) . '' . esc_html( number_format_i18n( $items ) ) . '' . esc_html( (string) ( $entry['user_role'] ?? ( empty( $entry['user_id'] ) ? 'GUEST' : __( 'Registered user', 'abandoned-cart-webhooks-for-woocommerce' ) ) ) ) . '' . esc_html( $row->status ) . '' . ( $waiting ? esc_html( wp_date( 'm/d/y H:i', $eligible_at ) ) : '—' ) . '' . esc_html( $remaining_text ) . '
' . esc_html__( 'No stored carts match this filter.', 'abandoned-cart-webhooks-for-woocommerce' ) . '
'; if ( $pages > 1 ) { echo '

'; // Show every page for short lists. For larger lists, retain the first, // last, and nearby pages while indicating omissions explicitly. $visible_pages = array(); for ( $i = 1; $i <= $pages; $i++ ) { if ( $pages <= 7 || 1 === $i || $pages === $i || abs( $i - $page ) <= 2 ) { $visible_pages[] = $i; } } $previous_page = 0; foreach ( $visible_pages as $i ) { if ( $previous_page && $i > $previous_page + 1 ) { if ( $i === $previous_page + 2 ) { $missing = $previous_page + 1; $missing_url = add_query_arg( array( 'acpw_cart_status' => $filter, 'acpw_cart_order' => $order, 'acpw_with_email' => $with_email ? '1' : '0', 'acpw_cart_page' => $missing ), $base ) . '#acpw-pending-carts'; echo '' . esc_html( $missing ) . ' '; } else { echo ' '; } } $url = add_query_arg( array( 'acpw_cart_status' => $filter, 'acpw_cart_order' => $order, 'acpw_with_email' => $with_email ? '1' : '0', 'acpw_cart_page' => $i ), $base ) . '#acpw-pending-carts'; echo $i === $page ? '' . esc_html( $i ) . ' ' : '' . esc_html( $i ) . ' '; $previous_page = $i; } echo '

'; } } private static function history_controls() { echo '

' . esc_html__( 'Clear stored history', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; wp_nonce_field( 'acpw_clear_history' ); echo '


' . esc_html__( 'Clearing test records also removes their standalone test snapshots and invalidates their test links. Pending/in-flight deliveries are protected. Real cart tracking and send-once markers remain until their normal age-based cleanup.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Clears up to 500 eligible delivery records per click. Repeat for a larger backlog. Settings, queued deliveries and existing receiver workflows are not reset.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; submit_button( __( 'Clear selected records', 'abandoned-cart-webhooks-for-woocommerce' ), 'secondary' ); echo '
'; } public static function clear_history() { self::permission( 'acpw_clear_history' ); check_admin_referer( 'acpw_clear_history' ); if ( 'POST' !== ( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) ) { wp_die( esc_html__( 'Clearing history requires a POST request.', 'abandoned-cart-webhooks-for-woocommerce' ), '', array( 'response' => 405 ) ); } $scope = isset( $_POST['clear_scope'] ) && is_string( $_POST['clear_scope'] ) ? sanitize_key( wp_unslash( $_POST['clear_scope'] ) ) : ''; $removed = ACPW_Store::clear_history( $scope, isset( $_POST['invalidate_links'] ) && '1' === $_POST['invalidate_links'] ); /* translators: %d: number of removed delivery records. */ self::result( is_wp_error( $removed ) ? $removed->get_error_message() : sprintf( __( 'Cleared %d delivery records. Unreferenced standalone test snapshots were also removed. Pending deliveries and real-cart tracking were retained.', 'abandoned-cart-webhooks-for-woocommerce' ), $removed ) ); } private static function test_controls() { $email = wp_get_current_user()->user_email; echo '

' . esc_html__( 'Test webhook', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Uses up to two current catalogue products. Recovery links are included only when cart recovery is enabled. Every recipient email field uses', 'abandoned-cart-webhooks-for-woocommerce' ) . ' ' . '' . esc_html( $email ) . '' . esc_html__( '. No customer cart is copied and your current cart is not changed.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

' . esc_html__( 'Works while tracking is paused. Save your webhook URL first. Configure your receiver to accept a sample request, then send this test.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; echo '
'; wp_nonce_field( 'acpw_test' ); echo '


' . esc_html__( 'Sends the full payload using your account email and selected customer type. The event is cart.abandoned with is_test=true. Your receiver decides whether to send an email or perform other actions. A receiver filter excluding is_test=true also excludes this test.', 'abandoned-cart-webhooks-for-woocommerce' ) . '

'; submit_button( __( 'Send test payload', 'abandoned-cart-webhooks-for-woocommerce' ), 'secondary' ); echo '
'; } private static function number( $key, $label, $settings, $min, $max, $help ) { echo '

' . esc_html( $help ) . '

'; } private static function permission( $action ) { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'abandoned-cart-webhooks-for-woocommerce' ), '', array( 'response' => 403 ) ); } if ( ! class_exists( 'WooCommerce' ) || ACPW_Compat::previous_active() || get_option( 'acpw_db_version' ) !== ACPW_VERSION ) { wp_die( esc_html__( 'Complete plugin activation and storage migration before using these controls.', 'abandoned-cart-webhooks-for-woocommerce' ), '', array( 'response' => 409 ) ); } if ( 'POST' !== sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) { wp_die( esc_html__( 'This action requires a POST request.', 'abandoned-cart-webhooks-for-woocommerce' ), '', array( 'response' => 405 ) ); } } private static function result( $message ) { set_transient( 'acpw_admin_result_' . get_current_user_id(), $message, 120 ); wp_safe_redirect( admin_url( 'admin.php?page=' . self::PAGE ) ); exit; } public static function test() { self::permission( 'acpw_test' ); check_admin_referer( 'acpw_test' ); if ( ! class_exists( 'WooCommerce' ) ) { self::result( __( 'WooCommerce is unavailable.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } $role = isset( $_POST['test_role'] ) && is_string( $_POST['test_role'] ) ? sanitize_key( wp_unslash( $_POST['test_role'] ) ) : '__guest__'; $sent = ACPW_Test::send( $role ); if ( is_wp_error( $sent ) ) { self::result( $sent->get_error_message() ); } $response = $sent['response']; $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); /* translators: 1: HTTP status code, 2: administrator email address. */ $accepted_message = sprintf( __( 'Full test payload accepted (HTTP %1$d) with recipient %2$s. Check your receiver for processing and any resulting email.', 'abandoned-cart-webhooks-for-woocommerce' ), $code, $sent['email'] ); /* translators: %d: HTTP status code. */ $failed_message = $code ? sprintf( __( 'Test failed: HTTP %d.', 'abandoned-cart-webhooks-for-woocommerce' ), $code ) : __( 'Test failed: transport or webhook URL error.', 'abandoned-cart-webhooks-for-woocommerce' ); self::result( $code >= 200 && $code < 300 ? $accepted_message : $failed_message ); } public static function retry() { global $wpdb; $id = isset( $_POST['event_id'] ) && is_scalar( $_POST['event_id'] ) ? absint( wp_unslash( $_POST['event_id'] ) ) : 0; self::permission( 'acpw_retry_' . $id ); check_admin_referer( 'acpw_retry_' . $id ); $table = ACPW_Store::events(); // 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 = $event ? ACPW_Store::cart( $event->cart_uuid ) : false; if ( ! $event || ! $cart || 'failed' !== $event->status || (int) $event->expires_at <= time() || 'failed' !== $cart->status || (int) $cart->revision !== (int) $event->revision ) { self::result( __( 'This event is no longer eligible for retry.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } // 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. $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE cart_uuid = %s FOR UPDATE", ACPW_Store::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. $updated_event = $wpdb->update( $table, array( 'status' => 'pending', 'attempts' => 0, 'next_attempt' => time(), 'last_error' => '', 'http_code' => 0 ), array( 'id' => $id, 'status' => 'failed' ) ); // 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. $updated_cart = 1 === $updated_event ? $wpdb->update( ACPW_Store::carts(), array( 'status' => 'queued' ), array( 'cart_uuid' => $event->cart_uuid, 'revision' => $event->revision, 'status' => 'failed' ) ) : 0; if ( 1 !== $updated_event || 1 !== $updated_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( 'ROLLBACK' ); self::result( __( 'This event changed or was cleared before it could be retried.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } // 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' ); self::result( __( 'Retry queued with the same event ID.', 'abandoned-cart-webhooks-for-woocommerce' ) ); } }