Commit 96fe93d46f0 for woocommerce
commit 96fe93d46f093b75a3ec339a549288651b3c28fb
Author: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
Date: Fri Nov 27 14:35:08 2026 +0800
Keep plugin-added event props on analytics speed module events (#71531)
* Keep event props filter additions on events the analytics speed module records
* Keep MU-plugin event props live and skip unsafe records in the analytics speed module
* Record analytics speed module event props hourly and keep the last record on any failure
* Document that event-dependent props must skip the analytics speed module record
* Note that a failed analytics speed module record keeps the last one
* Hide cookies from event props callbacks while recording them for the analytics speed module
diff --git a/packages/php/woocommerce-analytics/README.md b/packages/php/woocommerce-analytics/README.md
index b25a5bb4394..9cbd290c8cc 100644
--- a/packages/php/woocommerce-analytics/README.md
+++ b/packages/php/woocommerce-analytics/README.md
@@ -99,7 +99,7 @@ request-derived values and the session cookie.
Invalid event names and oversized pixel URLs return an error. Events beyond the
batch limit are ignored.
-Two options carry this state, because the speed module runs before plugins
+Three options carry this state, because the speed module runs before plugins
register filters and cannot read them:
- `woocommerce_analytics_proxy_tracking_ever_enabled` is sticky and decides
@@ -111,6 +111,10 @@ register filters and cannot read them:
`init` for the speed module (see "Server-Side Optimizations"). Only an explicit
`yes` lets it serve; otherwise it falls through to the REST route rather than
answering itself, so the `403` always comes from one place.
+- `woocommerce_analytics_speed_module_event_props` holds the scalar properties
+ that `jetpack_woocommerce_analytics_event_props` callbacks added at the last
+ hourly cron run, for the speed module to replay. It is deleted once proxy
+ tracking is off.
**The filter must resolve to the same value for every request on a site, and must
be registered before `init` priority 20.** A value that varies by cohort,
@@ -309,6 +313,8 @@ Called from an MU-plugin, it serves on `muplugins_loaded`, when a `wp_consent_co
The module serves only while proxy tracking was on at the last `init`, and otherwise leaves the request to the REST route. A request from a shopper whose statistics consent cookie stores a deny is left to the REST route too, which applies the consent check.
+Plugin callbacks on `jetpack_woocommerce_analytics_event_props` have not registered when the module serves, so it adds the scalar properties they returned at the last hourly `woocommerce_analytics_record_speed_module_event_props` cron run, which has no user logged in and no cookies. A new or changed callback, or a value it returns, reaches these events after the next run that records, normally within the hour. A run where a callback throws or returns a non-array keeps the last record, and logs why. With `ALTERNATE_WP_CRON`, cron runs inside a visitor's request, so only a run from WP-CLI records. Whatever a callback returns for that run's empty event name is added to every one of these events, so a property meant only for some events, visitors or requests must be left out when the event name is empty. MU-plugin callbacks still run on each event and see its real name.
+
`woocommerce_analytics_auto_install_proxy_speed_module` is deprecated and has no effect.
### Debugging
diff --git a/packages/php/woocommerce-analytics/changelog/fix-woocommerce-analytics-speed-module-event-props b/packages/php/woocommerce-analytics/changelog/fix-woocommerce-analytics-speed-module-event-props
new file mode 100644
index 00000000000..fef3f2f3e86
--- /dev/null
+++ b/packages/php/woocommerce-analytics/changelog/fix-woocommerce-analytics-speed-module-event-props
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fixed
+
+Keep the properties that plugins add through `jetpack_woocommerce_analytics_event_props` on events the proxy speed module records.
diff --git a/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php b/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php
index 85ee58446e0..368e1eb4dc7 100644
--- a/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php
+++ b/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php
@@ -167,6 +167,8 @@ class Proxy_Speed_Module {
return self::error_response( 'Invalid JSON' );
}
+ self::replay_recorded_event_props();
+
$data = WC_Analytics_Tracking::record_client_events( $events );
$data['is_proxy_speed_module'] = true;
@@ -237,6 +239,32 @@ class Proxy_Speed_Module {
return isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
}
+ /**
+ * Add what plugin callbacks on the event props filter returned at the last cron record, since they have not registered yet.
+ *
+ * @return void
+ */
+ private static function replay_recorded_event_props() {
+ // Mid-deploy, an older Woocommerce_Analytics may lack it.
+ if ( ! defined( Woocommerce_Analytics::class . '::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION' ) ) {
+ return;
+ }
+
+ $recorded = get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
+ if ( ! is_array( $recorded ) || array() === $recorded ) {
+ return;
+ }
+
+ // First, so a client value is replaced but an MU-plugin callback, which runs here, still sets its own live value.
+ add_filter(
+ 'jetpack_woocommerce_analytics_event_props',
+ static function ( $props ) use ( $recorded ) {
+ return array_merge( $props, $recorded );
+ },
+ PHP_INT_MIN
+ );
+ }
+
/**
* Whether proxy tracking was on at the last `init`.
*
diff --git a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
index 0f9df512f6c..673df2d90b7 100644
--- a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
+++ b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
@@ -560,6 +560,10 @@ class WC_Analytics_Tracking {
* is discarded, because the server re-asserts its own value below. Names a
* callback introduces are not reserved and are kept.
*
+ * It also runs hourly from cron with an empty `$event_name`, and the scalar properties it adds
+ * then are replayed on every event the proxy speed module records, for all visitors.
+ * So for an empty `$event_name`, leave out any property meant only for some events or visitors.
+ *
* @module woocommerce-analytics
*
* @since 12.5
diff --git a/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php b/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
index 4dcd35d12c0..cce9f447729 100644
--- a/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
+++ b/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
@@ -57,6 +57,25 @@ class Woocommerce_Analytics {
*/
const PROXY_TRACKING_ENABLED_OPTION = 'woocommerce_analytics_proxy_tracking_enabled';
+ /**
+ * What `jetpack_woocommerce_analytics_event_props` callbacks add to every event, recorded hourly for the
+ * speed module, which answers before they register.
+ *
+ * @since 0.19.1
+ *
+ * @var string
+ */
+ const PROXY_SPEED_MODULE_EVENT_PROPS_OPTION = 'woocommerce_analytics_speed_module_event_props';
+
+ /**
+ * Hourly cron hook that records the event props the speed module replays.
+ *
+ * @since 0.19.1
+ *
+ * @var string
+ */
+ const PROXY_SPEED_MODULE_EVENT_PROPS_HOOK = 'woocommerce_analytics_record_speed_module_event_props';
+
/**
* Whether proxy tracking has ever been enabled on this site.
*
@@ -120,6 +139,7 @@ class Woocommerce_Analytics {
public static function should_track_store() {
// Register before early returns so the speed module does not keep stale state.
add_action( 'init', array( __CLASS__, 'sync_proxy_tracking_state' ), 20 );
+ add_action( self::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK, array( __CLASS__, 'record_speed_module_event_props' ) );
// Ensure this is available, even with mu-plugins.
if ( ! function_exists( 'is_plugin_active' ) ) {
@@ -269,7 +289,7 @@ class Woocommerce_Analytics {
public static function sync_proxy_tracking_state() {
// One query covers both, so sites without these rows do not pay a query each.
if ( function_exists( 'wp_prime_option_caches' ) ) {
- wp_prime_option_caches( array( self::PROXY_TRACKING_ENABLED_OPTION, self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
+ wp_prime_option_caches( array( self::PROXY_TRACKING_ENABLED_OPTION, self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, self::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
}
// A leftover MU-plugin keeps answering while this is yes, even after proxy tracking is turned off.
@@ -283,6 +303,8 @@ class Woocommerce_Analytics {
update_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION, 'yes' );
}
+ self::schedule_speed_module_event_props( $enabled );
+
$value = $enabled ? 'yes' : 'no';
$current = get_option( self::PROXY_TRACKING_ENABLED_OPTION );
@@ -298,6 +320,105 @@ class Woocommerce_Analytics {
update_option( self::PROXY_TRACKING_ENABLED_OPTION, $value );
}
+ /**
+ * Keep the hourly record of the speed module's event props scheduled while proxy tracking is on.
+ *
+ * @since 0.19.1
+ *
+ * @param bool $proxy_tracking_enabled Whether proxy tracking is on.
+ * @return void
+ */
+ private static function schedule_speed_module_event_props( $proxy_tracking_enabled ) {
+ if ( ! $proxy_tracking_enabled ) {
+ self::clear_speed_module_event_props();
+ return;
+ }
+
+ if ( false === wp_next_scheduled( self::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK ) ) {
+ wp_schedule_event( time(), 'hourly', self::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK );
+ }
+ }
+
+ /**
+ * Stop recording the speed module's event props and drop the last record.
+ *
+ * @since 0.19.1
+ *
+ * @return void
+ */
+ private static function clear_speed_module_event_props() {
+ wp_clear_scheduled_hook( self::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK );
+
+ // This runs on every `init` while proxy tracking is off, and deleting a missing option still queries.
+ if ( false !== get_option( self::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) ) {
+ delete_option( self::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
+ }
+ }
+
+ /**
+ * Record what `jetpack_woocommerce_analytics_event_props` callbacks add to every event, for the speed module to replay.
+ *
+ * Runs only from a cron request or WP-CLI, with no user logged in and no cookies, so nothing a visitor sent is
+ * replayed onto other visitors' events. Only scalar properties within the client bounds are kept.
+ *
+ * @since 0.19.1
+ *
+ * @return void
+ */
+ public static function record_speed_module_event_props() {
+ $in_cli = defined( 'WP_CLI' ) && WP_CLI;
+
+ // Anywhere else, ALTERNATE_WP_CRON included, runs inside a visitor's page view, with their session already loaded.
+ if ( ! $in_cli && ( ! wp_doing_cron() || ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) ) ) {
+ return;
+ }
+
+ $props = array();
+
+ if ( 'yes' === get_option( self::PROXY_TRACKING_ENABLED_OPTION ) ) {
+ $user_id = get_current_user_id();
+ $cookies = $_COOKIE;
+ $error = null;
+ wp_set_current_user( 0 );
+ // Anyone can request wp-cron.php, with cookies a callback could read.
+ $_COOKIE = array();
+
+ try {
+ $base = \Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::get_page_common_properties();
+
+ /** This filter is documented in src/class-wc-analytics-tracking.php */
+ $filtered = apply_filters( 'jetpack_woocommerce_analytics_event_props', $base, '', true );
+ } catch ( \Throwable $e ) {
+ $error = $e->getMessage();
+ }
+
+ $_COOKIE = $cookies;
+ wp_set_current_user( $user_id );
+
+ if ( null === $error && ! is_array( $filtered ) ) {
+ $error = 'a callback returned ' . gettype( $filtered ) . ' instead of an array';
+ }
+
+ if ( null !== $error ) {
+ // Keep the last record, and let the rest of the cron run continue.
+ error_log( 'WooCommerce Analytics: Could not record the event props for the proxy speed module: ' . $error ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
+ return;
+ }
+
+ // Sanitizing strips the common properties, which are all reserved, and bounds what is left.
+ $props = \Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::sanitize_client_properties(
+ array_filter( $filtered, 'is_scalar' )
+ );
+ }
+
+ if ( array() === $props ) {
+ delete_option( self::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
+ return;
+ }
+
+ update_option( self::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, $props );
+ }
+
/**
* Forget that proxy tracking was enabled, so the REST route is unregistered.
*
@@ -311,6 +432,7 @@ class Woocommerce_Analytics {
delete_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION );
delete_option( self::PROXY_TRACKING_ENABLED_OPTION );
delete_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
+ self::clear_speed_module_event_props();
}
/**
@@ -348,6 +470,7 @@ class Woocommerce_Analytics {
*/
public static function maybe_remove_proxy_speed_module() {
delete_option( self::PROXY_TRACKING_ENABLED_OPTION );
+ self::clear_speed_module_event_props();
self::remove_legacy_proxy_speed_module();
}
diff --git a/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php b/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php
index 75d303cca0c..16f9da6146b 100644
--- a/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php
@@ -48,7 +48,9 @@ class Proxy_Speed_Module_Test extends BaseTestCase {
* Restore the request globals.
*/
public function tear_down(): void {
- unset( $_COOKIE['wp_consent_statistics'], $_COOKIE['custom_statistics'] );
+ unset( $_COOKIE['wp_consent_statistics'], $_COOKIE['custom_statistics'], $_COOKIE['tk_ai'] );
+ remove_all_filters( 'jetpack_woocommerce_analytics_event_props' );
+ delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
$_SERVER = $this->previous_server;
$GLOBALS['wp_actions'] = $this->previous_wp_actions;
remove_action( 'muplugins_loaded', array( Proxy_Speed_Module::class, 'maybe_serve' ) );
@@ -353,6 +355,65 @@ class Proxy_Speed_Module_Test extends BaseTestCase {
}
}
+ /**
+ * Plugin callbacks on the event props filter have not registered here, so what cron last recorded is replayed.
+ */
+ public function test_replays_the_recorded_event_props_over_the_client_value(): void {
+ $_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'host' => 'ecommplan' ) );
+ $method = new \ReflectionMethod( Proxy_Speed_Module::class, 'handle_events' );
+ $method->setAccessible( true );
+
+ $method->invoke( null, '{"event_name":"product_view","properties":{"host":"forged"}}' );
+
+ $this->assertSame( 'ecommplan', $this->get_queued_pixel_props()['host'] ?? null );
+ }
+
+ /**
+ * An MU-plugin callback still runs here, so its live value wins over what cron recorded from it.
+ */
+ public function test_an_mu_plugin_callback_keeps_its_live_value_over_the_record(): void {
+ $_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+ update_option(
+ Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION,
+ array(
+ 'host' => 'ecommplan',
+ 'mu_event' => 'recorded',
+ )
+ );
+ add_filter(
+ 'jetpack_woocommerce_analytics_event_props',
+ function ( $props, $event_name ) {
+ return array_merge( $props, array( 'mu_event' => $event_name ) );
+ },
+ 10,
+ 2
+ );
+ $method = new \ReflectionMethod( Proxy_Speed_Module::class, 'handle_events' );
+ $method->setAccessible( true );
+
+ $method->invoke( null, '{"event_name":"product_view","properties":{"host":"forged"}}' );
+
+ $props = $this->get_queued_pixel_props();
+ $this->assertSame( 'woocommerceanalytics_product_view', $props['mu_event'] ?? null );
+ $this->assertSame( 'ecommplan', $props['host'] ?? null );
+ }
+
+ /**
+ * Read the properties of the one queued pixel.
+ *
+ * @return array
+ */
+ private function get_queued_pixel_props(): array {
+ $queue = ( new \ReflectionClass( WC_Analytics_Tracking::class ) )->getProperty( 'pixel_batch_queue' );
+ $queue->setAccessible( true );
+ $pixels = $queue->getValue();
+ $this->assertCount( 1, $pixels );
+ parse_str( (string) wp_parse_url( $pixels[0], PHP_URL_QUERY ), $props );
+
+ return $props;
+ }
+
/**
* Make the current request look like the given request.
*
diff --git a/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php b/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php
index dcd266bf2d7..687810e6c69 100644
--- a/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php
@@ -9,6 +9,8 @@ namespace Automattic\Woocommerce_Analytics;
use Automattic\Woocommerce_Analytics;
use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\PreserveGlobalState;
+use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use WorDBless\BaseTestCase;
/**
@@ -37,7 +39,9 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
// Remove any filters that might interfere.
delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
+ delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
+ remove_all_filters( 'jetpack_woocommerce_analytics_event_props' );
}
/**
@@ -51,6 +55,11 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
delete_transient( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT );
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
+ delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION );
+ remove_all_filters( 'jetpack_woocommerce_analytics_event_props' );
+ wp_clear_scheduled_hook( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK );
+ remove_all_filters( 'wp_doing_cron' );
+ wp_set_current_user( 0 );
parent::tear_down();
}
@@ -382,6 +391,19 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
$this->assertFalse( get_transient( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT ) );
}
+ /**
+ * Deactivation is the only cleanup a host runs, so it also stops what the speed module would replay on reactivation.
+ */
+ public function test_maybe_remove_proxy_speed_module_stops_the_event_props_record(): void {
+ wp_schedule_event( time(), 'hourly', Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK );
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'host' => 'ecommplan' ) );
+
+ Woocommerce_Analytics::maybe_remove_proxy_speed_module();
+
+ $this->assertFalse( wp_next_scheduled( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK ) );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ }
+
/**
* The speed module runs at MU-plugin stage, where no plugin has registered a
* callback on the proxy tracking filter yet, so it cannot ask `Features` and
@@ -405,6 +427,203 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
);
}
+ /**
+ * The speed module answers before callbacks on the event props filter register, so cron records what they add.
+ *
+ * @dataProvider provide_event_props_callbacks
+ *
+ * @param string $proxy_tracking The stored proxy tracking state.
+ * @param array $added Properties the callback adds or changes.
+ * @param array|bool $expected The expected recorded properties, or false for no row.
+ */
+ #[DataProvider( 'provide_event_props_callbacks' )]
+ public function test_cron_records_what_the_event_props_filter_adds( $proxy_tracking, $added, $expected ): void {
+ add_filter( 'wp_doing_cron', '__return_true' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, $proxy_tracking );
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'stale' => 1 ) );
+ add_filter(
+ 'jetpack_woocommerce_analytics_event_props',
+ function ( $props ) use ( $added ) {
+ return array_merge( $props, $added );
+ }
+ );
+
+ Woocommerce_Analytics::record_speed_module_event_props();
+
+ $this->assertSame( $expected, get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ }
+
+ /**
+ * Event props callbacks and what cron records for them.
+ *
+ * @return array
+ */
+ public static function provide_event_props_callbacks(): array {
+ return array(
+ 'a scalar addition' => array( 'yes', array( 'host' => 'ecommplan' ), array( 'host' => 'ecommplan' ) ),
+ 'a non-scalar value' => array( 'yes', array( 'host' => 'ecommplan', 'list' => array( 1 ) ), array( 'host' => 'ecommplan' ) ),
+ 'a changed common property' => array( 'yes', array( 'store_currency' => 'XXX' ), false ),
+ 'nothing added' => array( 'yes', array(), false ),
+ 'proxy tracking off' => array( 'no', array( 'host' => 'ecommplan' ), false ),
+ );
+ }
+
+ /**
+ * A visitor's request or session must not be what gets replayed onto every other visitor's events.
+ *
+ * @dataProvider provide_record_contexts
+ *
+ * @param bool $in_cron Whether the record runs as cron.
+ * @param array|bool $expected The expected recorded properties, or false for no row.
+ */
+ #[DataProvider( 'provide_record_contexts' )]
+ public function test_the_record_holds_no_visitor( $in_cron, $expected ): void {
+ if ( $in_cron ) {
+ add_filter( 'wp_doing_cron', '__return_true' );
+ }
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ $user_id = wp_insert_user(
+ array(
+ 'user_login' => 'wca-record-visitor',
+ 'user_pass' => 'password',
+ 'role' => 'administrator',
+ )
+ );
+ wp_set_current_user( $user_id );
+ $_COOKIE['wca_visitor'] = 'shopper';
+ add_filter(
+ 'jetpack_woocommerce_analytics_event_props',
+ function ( $props ) {
+ return array_merge(
+ $props,
+ array(
+ 'recorded_user' => get_current_user_id(),
+ 'recorded_cookie' => $_COOKIE['wca_visitor'] ?? 'none',
+ )
+ );
+ }
+ );
+
+ Woocommerce_Analytics::record_speed_module_event_props();
+ $cookie = $_COOKIE['wca_visitor'] ?? null;
+ unset( $_COOKIE['wca_visitor'] );
+
+ $this->assertSame( $expected, get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ $this->assertSame( $user_id, get_current_user_id(), 'The current user must be restored.' );
+ $this->assertSame( 'shopper', $cookie, 'The cookies must be restored.' );
+ }
+
+ /**
+ * Contexts the record can run in.
+ *
+ * @return array
+ */
+ public static function provide_record_contexts(): array {
+ return array(
+ 'cron' => array(
+ true,
+ array(
+ 'recorded_user' => 0,
+ 'recorded_cookie' => 'none',
+ ),
+ ),
+ 'a page view' => array( false, false ),
+ );
+ }
+
+ /**
+ * A callback that fails in cron, where there is no cart or session, keeps the last record and the current user.
+ *
+ * @dataProvider provide_failing_event_props_callbacks
+ *
+ * @param callable $callback The failing callback.
+ */
+ #[DataProvider( 'provide_failing_event_props_callbacks' )]
+ public function test_a_failing_event_props_callback_keeps_the_last_record( $callback ): void {
+ add_filter( 'wp_doing_cron', '__return_true' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'host' => 'ecommplan' ) );
+ $user_id = wp_insert_user(
+ array(
+ 'user_login' => 'wca-record-failure',
+ 'user_pass' => 'password',
+ )
+ );
+ wp_set_current_user( $user_id );
+ add_filter( 'jetpack_woocommerce_analytics_event_props', $callback );
+ $error_log = ini_set( 'error_log', '/dev/null' ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+
+ try {
+ Woocommerce_Analytics::record_speed_module_event_props();
+ } finally {
+ ini_set( 'error_log', (string) $error_log ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+ }
+
+ $this->assertSame( array( 'host' => 'ecommplan' ), get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ $this->assertSame( $user_id, get_current_user_id() );
+ }
+
+ /**
+ * Ways an event props callback fails.
+ *
+ * @return array
+ */
+ public static function provide_failing_event_props_callbacks(): array {
+ return array(
+ 'a throw' => array(
+ function () {
+ throw new \RuntimeException( 'No session in cron.' );
+ },
+ ),
+ 'a non-array value' => array( '__return_null' ),
+ );
+ }
+
+ /**
+ * With ALTERNATE_WP_CRON, cron runs inside a visitor's request, so that visitor's cookie must not be recorded.
+ *
+ * The constant cannot be undefined, so this runs in its own process.
+ *
+ * @runInSeparateProcess
+ * @preserveGlobalState disabled
+ */
+ #[RunInSeparateProcess]
+ #[PreserveGlobalState( false )]
+ public function test_alternate_wp_cron_does_not_record(): void {
+ define( 'ALTERNATE_WP_CRON', true );
+ add_filter( 'wp_doing_cron', '__return_true' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'host' => 'ecommplan' ) );
+ $_COOKIE['visitor'] = 'shopper-a';
+ add_filter(
+ 'jetpack_woocommerce_analytics_event_props',
+ function ( $props ) {
+ return array_merge( $props, array( 'visitor' => $_COOKIE['visitor'] ?? '' ) );
+ }
+ );
+
+ Woocommerce_Analytics::record_speed_module_event_props();
+
+ $this->assertSame( array( 'host' => 'ecommplan' ), get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ }
+
+ /**
+ * Test that the hourly record is scheduled while proxy tracking is on, and cleared with its row once it is off.
+ */
+ public function test_sync_schedules_the_event_props_record_while_proxy_tracking_is_on(): void {
+ add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
+ Woocommerce_Analytics::sync_proxy_tracking_state();
+
+ $this->assertSame( 'hourly', wp_get_schedule( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK ) );
+
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION, array( 'host' => 'ecommplan' ) );
+ remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
+ Woocommerce_Analytics::sync_proxy_tracking_state();
+
+ $this->assertFalse( wp_next_scheduled( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_HOOK ) );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_EVENT_PROPS_OPTION ) );
+ }
+
/**
* The mirror runs on every front-end and admin request, so it must not write
* to the options table when nothing changed.