Commit c1553b109f9 for woocommerce
commit c1553b109f974513de87b5fe8c275a14b7b6b704
Author: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
Date: Fri Nov 27 10:43:21 2026 +0800
Let sites enable the analytics speed module instead of auto-installing it (#71301)
* Let hosts run the analytics proxy speed module from their own platform code
* Share the proxy event loop and let the speed module exit after answering
* Stop writing the analytics speed module MU-plugin and let hosts provide it
* Fix a comment that still called the speed module an MU-plugin
* Replace the host-provided speed module filter with Proxy_Speed_Module::enable()
* Note which consent prefix filters the speed module sees from a plugin file
* Retry an undeletable speed module file and keep the IP visitor fallback on the fast path
* Store only the proxy tracking state for the speed module, and keep enable() per request
* Generate the analytics daily salt without a pluggable function
* Trim the speed module README now that nothing installs it
* Stop a leftover speed module answering once proxy tracking is off or the plugin is deactivated
* Fall back to REST on a package version mismatch and cover the early-boot salt
* Refresh speed module docs now that hosts call enable() instead of an MU-plugin
* Keep the Jetpack autoloader plugin cache when the speed module answers
* Keep the autoloader handler when the speed module hits an error
* Skip option cache priming on WordPress versions without wp_prime_option_caches()
diff --git a/packages/php/woocommerce-analytics/README.md b/packages/php/woocommerce-analytics/README.md
index 7942942dc9d..b25a5bb4394 100644
--- a/packages/php/woocommerce-analytics/README.md
+++ b/packages/php/woocommerce-analytics/README.md
@@ -99,25 +99,23 @@ 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 optional MU-plugin speed module loads
-before plugins register filters and cannot read them:
+Two 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
whether the route is registered at all. Nothing in the package clears it:
`Woocommerce_Analytics::reset_proxy_tracking_state()` is the only way, and it
has no caller, so a host that wants the endpoint gone has to call it from its
own deactivation or uninstall routine once the cached pages have expired.
-- `woocommerce_analytics_proxy_speed_module_authorized` records whether the speed
- module may serve. It holds `should_install_proxy_speed_module()`, which is proxy
- tracking **and** the module's own opt-in, so a revoked module is not
- reauthorized by the next request. An unauthorized module falls through to the
- REST route rather than answering itself, so the `403` always comes from one
- place.
+- `woocommerce_analytics_proxy_tracking_enabled` mirrors proxy tracking at each
+ `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.
**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,
-percentage or geo makes cached pages disagree with what `/track` decides, and makes
-the speed module install and uninstall itself on alternate runs. A callback added
+percentage or geo makes cached pages disagree with what `/track` decides, and flips
+the option the speed module reads on alternate runs. A callback added
after `init` priority 20 is never seen: the route is registered from the option,
not from the filter, and the option is written there.
@@ -299,7 +297,19 @@ When proxy tracking is enabled:
**Server-Side Optimizations:**
-The package includes an optional MU plugin (`woocommerce-analytics-proxy-speed-module.php`) that significantly improves proxy performance by only loading WooCommerce, WooCommerce Analytics, and Jetpack for proxy requests. A request from a shopper whose statistics consent cookie stores a deny is left to the REST route, which applies the consent check. The module runs before regular plugins, so it only reads the default `wp_consent` cookie prefix or one set by an earlier MU-plugin.
+`Proxy_Speed_Module` answers proxy requests before regular plugins finish loading and exits, which significantly reduces their cost. Code on the site turns it on, such as WordPress.com's platform plugin or a VIP `client-mu-plugins` file, by calling `enable()` once a Jetpack autoloader that can find this package has loaded:
+
+```php
+if ( class_exists( \Automattic\Woocommerce_Analytics\Proxy_Speed_Module::class ) ) {
+ \Automattic\Woocommerce_Analytics\Proxy_Speed_Module::enable();
+}
+```
+
+Called from an MU-plugin, it serves on `muplugins_loaded`, when a `wp_consent_cookie_prefix` filter from any MU-plugin is already registered. Called from a plugin's main file, it serves at once, so it also sees that filter from the plugins that load before it, but not from those after. A call after `plugins_loaded` is refused with a `_doing_it_wrong()` notice.
+
+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.
+
+`woocommerce_analytics_auto_install_proxy_speed_module` is deprecated and has no effect.
### Debugging
diff --git a/packages/php/woocommerce-analytics/changelog/add-wooa7s-2526-host-provided-proxy-speed-module b/packages/php/woocommerce-analytics/changelog/add-wooa7s-2526-host-provided-proxy-speed-module
new file mode 100644
index 00000000000..4124b760b68
--- /dev/null
+++ b/packages/php/woocommerce-analytics/changelog/add-wooa7s-2526-host-provided-proxy-speed-module
@@ -0,0 +1,4 @@
+Significance: minor
+Type: changed
+
+Let hosts run the proxy speed module from their own platform code, and stop writing the speed module MU-plugin into sites. The `woocommerce_analytics_auto_install_proxy_speed_module` filter is deprecated.
diff --git a/packages/php/woocommerce-analytics/src/API/class-wc-analytics-tracking-proxy.php b/packages/php/woocommerce-analytics/src/API/class-wc-analytics-tracking-proxy.php
index 6a93f4a07d9..4e0b76f0132 100644
--- a/packages/php/woocommerce-analytics/src/API/class-wc-analytics-tracking-proxy.php
+++ b/packages/php/woocommerce-analytics/src/API/class-wc-analytics-tracking-proxy.php
@@ -79,64 +79,9 @@ class WC_Analytics_Tracking_Proxy extends \WC_REST_Controller {
);
}
- $events = $request->get_json_params();
+ $response_data = WC_Analytics_Tracking::record_client_events( $request->get_json_params() );
- if ( ! is_array( $events ) || ( isset( $events['event_name'] ) ) ) {
- // If $events is a single event (associative array), wrap it in an array.
- $events = array( $events );
- }
-
- // Limit unauthenticated callers to a bounded number of pixel requests.
- if ( count( $events ) > WC_Analytics_Tracking::MAX_CLIENT_EVENTS_PER_REQUEST ) {
- $events = array_slice( $events, 0, WC_Analytics_Tracking::MAX_CLIENT_EVENTS_PER_REQUEST, true );
- }
-
- $results = array();
- $has_errors = false;
-
- foreach ( $events as $index => $event ) {
- // Validate event structure.
- if ( empty( $event ) || ! is_array( $event ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => 'Invalid event format',
- );
- $has_errors = true;
- continue;
- }
-
- // Validate event name and properties.
- $event_name = $event['event_name'] ?? null;
- $properties = $event['properties'] ?? array();
- if ( ! $event_name || ! is_string( $event_name ) || ! is_array( $properties ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => 'Missing event_name or invalid properties',
- );
- $has_errors = true;
- continue;
- }
-
- $result = WC_Analytics_Tracking::record_client_event( $event_name, $properties );
-
- if ( is_wp_error( $result ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => $result->get_error_message(),
- );
- $has_errors = true;
- continue;
- }
-
- $results[ $index ] = array( 'success' => true );
- }
-
- $response_data = array(
- 'success' => ! $has_errors,
- 'results' => $results,
- );
-
- return new \WP_REST_Response( $response_data, $has_errors ? 207 : 200 );
+ return new \WP_REST_Response( $response_data, $response_data['success'] ? 200 : 207 );
}
/**
diff --git a/packages/php/woocommerce-analytics/src/class-features.php b/packages/php/woocommerce-analytics/src/class-features.php
index f3404a631b4..3d93b189706 100644
--- a/packages/php/woocommerce-analytics/src/class-features.php
+++ b/packages/php/woocommerce-analytics/src/class-features.php
@@ -47,20 +47,27 @@ class Features {
}
/**
- * Check if auto-installation of the proxy speed module MU-plugin is enabled.
+ * Fire the deprecated auto-install filter, so its callbacks get the deprecation notice.
+ *
+ * @deprecated 0.19.0 The package no longer installs the MU-plugin. Call Proxy_Speed_Module::enable() instead.
*
* @return bool
*/
public static function is_proxy_speed_module_enabled() {
/**
- * Filter to control auto-installation of the proxy speed module mu-plugin.
- *
- * When this filter returns false, the mu-plugin file can't be added automatically.
+ * Filter that controlled auto-installation of the proxy speed module MU-plugin.
*
* @since 0.15.0
+ * @deprecated 0.19.0 The package no longer installs the MU-plugin, so this has no effect.
*
* @param bool $auto_install Whether to auto-install the mu-plugin. Default false.
*/
- return apply_filters( 'woocommerce_analytics_auto_install_proxy_speed_module', false );
+ return (bool) apply_filters_deprecated(
+ 'woocommerce_analytics_auto_install_proxy_speed_module',
+ array( false ),
+ '0.19.0',
+ '',
+ 'The package no longer installs the proxy speed module MU-plugin. Call Proxy_Speed_Module::enable() instead.'
+ );
}
}
diff --git a/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php b/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php
new file mode 100644
index 00000000000..85ee58446e0
--- /dev/null
+++ b/packages/php/woocommerce-analytics/src/class-proxy-speed-module.php
@@ -0,0 +1,255 @@
+<?php
+/**
+ * Proxy speed module for WooCommerce Analytics.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Woocommerce_Analytics;
+
+use Automattic\Woocommerce_Analytics;
+
+/**
+ * Answers proxy tracking requests before regular plugins finish loading, so they skip the full WordPress boot.
+ *
+ * @since 0.19.0
+ */
+class Proxy_Speed_Module {
+
+ /**
+ * Path of the proxy request.
+ *
+ * @var string
+ */
+ const PROXY_REQUEST_PATH = 'woocommerce-analytics/v1/track';
+
+ /**
+ * Whether code on this site called enable() in this request.
+ *
+ * @var bool
+ */
+ private static $enabled = false;
+
+ /**
+ * Serve proxy tracking requests early on this site.
+ *
+ * From an MU-plugin it serves on `muplugins_loaded`; from a plugin's main file it serves at once.
+ * A call after `plugins_loaded` is refused with a `_doing_it_wrong()` notice.
+ *
+ * @since 0.19.0
+ *
+ * @return void
+ */
+ public static function enable() {
+ // Plugins have already loaded, so serving now would save nothing.
+ if ( did_action( 'plugins_loaded' ) ) {
+ _doing_it_wrong( __METHOD__, 'Call it before plugins_loaded, from an MU-plugin or a plugin main file.', '0.19.0' );
+ return;
+ }
+
+ self::$enabled = true;
+
+ if ( did_action( 'muplugins_loaded' ) ) {
+ self::maybe_serve();
+ return;
+ }
+
+ add_action( 'muplugins_loaded', array( __CLASS__, 'maybe_serve' ) );
+ }
+
+ /**
+ * Answer the current request and exit if it is a proxy request this module may serve.
+ *
+ * Returns without output otherwise, so WordPress continues loading and the REST route answers.
+ *
+ * @since 0.19.0
+ *
+ * @return void
+ */
+ public static function maybe_serve() {
+ if ( self::respond() ) {
+ exit;
+ }
+ }
+
+ /**
+ * Send the response to a proxy request this module may serve.
+ *
+ * @return bool Whether a response was sent.
+ */
+ private static function respond() {
+ if ( ! self::$enabled || ! self::is_proxy_request() ) {
+ return false;
+ }
+
+ // The WP Consent API has not loaded yet, so let the REST route apply the stored deny.
+ if ( self::is_statistics_consent_denied() ) {
+ return false;
+ }
+
+ // Off means "do not accelerate", not "do not serve": the REST route answers, with the 403 a cached page needs.
+ if ( ! self::is_proxy_tracking_enabled() ) {
+ return false;
+ }
+
+ try {
+ // Match the superglobals the REST route sees.
+ wp_magic_quotes();
+
+ // The plugin that turns proxy tracking on has not loaded yet, but it was on at the last init.
+ add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
+
+ $response = self::handle_events( (string) file_get_contents( 'php://input' ) );
+ WC_Analytics_Tracking::send_batched_pixels();
+
+ // Only on success: after an error, the handler empties a cache that may have caused it.
+ self::keep_autoloader_cache();
+ } catch ( \Throwable $e ) {
+ error_log( 'WooCommerce Analytics Proxy Speed Module: Uncaught error while handling the request: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
+ $response = array(
+ 'status' => 500,
+ 'data' => array(
+ 'success' => false,
+ 'error' => 'Internal server error while processing analytics events.',
+ ),
+ );
+ }
+
+ if ( ! headers_sent() ) {
+ header( 'Content-Type: application/json; charset=utf-8' );
+ header( 'Cache-Control: no-cache, must-revalidate' );
+ http_response_code( $response['status'] );
+ }
+
+ echo wp_json_encode( $response['data'], JSON_UNESCAPED_SLASHES );
+
+ return true;
+ }
+
+ /**
+ * Unhook the Jetpack autoloader's shutdown handler, which reads an exit before `plugins_loaded` as a failed boot.
+ *
+ * Left hooked, it empties the autoloader's plugin cache on every answered request, and the next page rebuilds it.
+ *
+ * @return void
+ */
+ private static function keep_autoloader_cache() {
+ global $wp_filter;
+
+ if ( ! isset( $wp_filter['shutdown'] ) ) {
+ return;
+ }
+
+ foreach ( $wp_filter['shutdown']->callbacks as $priority => $callbacks ) {
+ foreach ( $callbacks as $callback ) {
+ $function = $callback['function'];
+ // The autoloader generates its classes under a per-plugin, per-version namespace.
+ if ( is_object( $function ) && preg_match( '/^Automattic\\\\Jetpack\\\\Autoloader\\\\.+\\\\Shutdown_Handler$/', get_class( $function ) ) ) {
+ remove_action( 'shutdown', $function, $priority );
+ }
+ }
+ }
+ }
+
+ /**
+ * Record the events in a proxy request body, leaving their pixels queued.
+ *
+ * @param string $body Raw request body.
+ * @return array{status: int, data: array} The response to send.
+ */
+ private static function handle_events( $body ) {
+ if ( '' === $body ) {
+ return self::error_response( 'Empty request body' );
+ }
+
+ $events = json_decode( $body, true );
+ if ( json_last_error() !== JSON_ERROR_NONE ) {
+ return self::error_response( 'Invalid JSON' );
+ }
+
+ $data = WC_Analytics_Tracking::record_client_events( $events );
+
+ $data['is_proxy_speed_module'] = true;
+
+ return array(
+ 'status' => $data['success'] ? 200 : 207,
+ 'data' => $data,
+ );
+ }
+
+ /**
+ * Build a 400 response.
+ *
+ * @param string $message Error message.
+ * @return array{status: int, data: array}
+ */
+ private static function error_response( $message ) {
+ return array(
+ 'status' => 400,
+ 'data' => array(
+ 'success' => false,
+ 'error' => $message,
+ ),
+ );
+ }
+
+ /**
+ * Whether the current request is a POST to the proxy endpoint.
+ *
+ * @return bool
+ */
+ private static function is_proxy_request() {
+ $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
+ if ( 'POST' !== $method ) {
+ return false;
+ }
+
+ $raw_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
+ $path = is_string( $raw_uri ) ? wp_parse_url( $raw_uri, PHP_URL_PATH ) : null;
+
+ if ( ! is_string( $path ) || preg_match( '/[^A-Za-z0-9\-._~\/]/', $path ) ) {
+ return false;
+ }
+
+ $normalized_path = rtrim( $path, '/' );
+ $proxy_suffix = '/' . self::PROXY_REQUEST_PATH;
+
+ return strlen( $normalized_path ) >= strlen( $proxy_suffix )
+ && substr( $normalized_path, -strlen( $proxy_suffix ) ) === $proxy_suffix;
+ }
+
+ /**
+ * Whether the WP Consent API cookie stores a statistics deny.
+ *
+ * Unlike Consent_Manager, this reads the cookie whatever the consent type, which is not known yet.
+ * Only a prefix filter registered before this runs applies, which is why enable() waits for `muplugins_loaded`.
+ *
+ * @return bool
+ */
+ private static function is_statistics_consent_denied() {
+ $prefix = apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Reads a WP Consent API filter.
+ if ( ! is_string( $prefix ) ) {
+ return false;
+ }
+
+ $cookie_name = $prefix . '_statistics';
+
+ return isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
+ }
+
+ /**
+ * Whether proxy tracking was on at the last `init`.
+ *
+ * Features cannot answer this early, because no plugin has registered its filters yet. Only an explicit yes serves.
+ *
+ * @return bool
+ */
+ private static function is_proxy_tracking_enabled() {
+ // Mid-deploy, an older Woocommerce_Analytics may lack it, and this runs outside respond()'s try.
+ if ( ! defined( Woocommerce_Analytics::class . '::PROXY_TRACKING_ENABLED_OPTION' ) ) {
+ return false;
+ }
+
+ return 'yes' === get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
+ }
+}
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 f101a91fd3f..0f9df512f6c 100644
--- a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
+++ b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
@@ -3,7 +3,7 @@
* WooCommerce Analytics Tracking for tracking frontend events
*
* This class is designed to work without WooCommerce dependencies,
- * enabling it to run at the MU-plugin stage without loading WooCommerce to optimize performance.
+ * so the proxy speed module can run it before WooCommerce loads.
*
* @package automattic/woocommerce-analytics
*/
@@ -253,9 +253,9 @@ class WC_Analytics_Tracking {
/**
* Record an event whose properties came from an untrusted client.
*
- * The entry point for the tracking proxy: the REST controller and the MU-plugin
- * speed module both come through here. A distinct method rather than a sanitizer
- * callers must remember to invoke, so a wrong choice is visible at the call site.
+ * The entry point for the tracking proxy, through record_client_events(). A distinct
+ * method rather than a sanitizer callers must remember to invoke, so a wrong choice is
+ * visible at the call site.
*
* @since 0.18.0
*
@@ -268,6 +268,69 @@ class WC_Analytics_Tracking {
return self::record_event( $event_name, $event_properties, true );
}
+ /**
+ * Record a batch of events posted to the tracking proxy, shared by the REST route and the speed module.
+ *
+ * @internal Not for use outside this package; the contract may change.
+ * @since 0.19.0
+ *
+ * @param mixed $events Decoded request body: a list of events, or a single event.
+ * @return array{success: bool, results: array} Per-event results; `success` is false when any event failed.
+ */
+ public static function record_client_events( $events ) {
+ if ( ! is_array( $events ) || isset( $events['event_name'] ) ) {
+ $events = array( $events );
+ }
+
+ // Every event becomes an outbound pixel, so bound what an unauthenticated caller can fan out.
+ if ( count( $events ) > self::MAX_CLIENT_EVENTS_PER_REQUEST ) {
+ $events = array_slice( $events, 0, self::MAX_CLIENT_EVENTS_PER_REQUEST, true );
+ }
+
+ $results = array();
+ $has_errors = false;
+
+ foreach ( $events as $index => $event ) {
+ if ( empty( $event ) || ! is_array( $event ) ) {
+ $results[ $index ] = array(
+ 'success' => false,
+ 'error' => 'Invalid event format',
+ );
+ $has_errors = true;
+ continue;
+ }
+
+ $event_name = $event['event_name'] ?? null;
+ $properties = $event['properties'] ?? array();
+ if ( ! $event_name || ! is_string( $event_name ) || ! is_array( $properties ) ) {
+ $results[ $index ] = array(
+ 'success' => false,
+ 'error' => 'Missing event_name or invalid properties',
+ );
+ $has_errors = true;
+ continue;
+ }
+
+ $result = self::record_client_event( $event_name, $properties );
+
+ if ( is_wp_error( $result ) ) {
+ $results[ $index ] = array(
+ 'success' => false,
+ 'error' => $result->get_error_message(),
+ );
+ $has_errors = true;
+ continue;
+ }
+
+ $results[ $index ] = array( 'success' => true );
+ }
+
+ return array(
+ 'success' => ! $has_errors,
+ 'results' => $results,
+ );
+ }
+
/**
* Queue an event in the event queue which will be processed on the page load in client-side analytics.
*
@@ -1093,8 +1156,8 @@ class WC_Analytics_Tracking {
return $salt_data['salt'];
}
- // Generate new salt for today
- $new_salt = wp_generate_password( 32, false );
+ // Not wp_generate_password(): the speed module can get here before pluggable.php loads.
+ $new_salt = bin2hex( random_bytes( 16 ) );
// Store salt with date (no expiration time needed)
$salt_data = array(
diff --git a/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php b/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
index d9e7715defd..4dcd35d12c0 100644
--- a/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
+++ b/packages/php/woocommerce-analytics/src/class-woocommerce-analytics.php
@@ -14,38 +14,33 @@ use Automattic\Woocommerce_Analytics\Consent_Manager;
use Automattic\Woocommerce_Analytics\My_Account;
use Automattic\Woocommerce_Analytics\Universal;
use Automattic\Woocommerce_Analytics\WC_Analytics_Tracking_Proxy;
-use Composer\InstalledVersions;
/**
* Instantiate WooCommerce Analytics
*/
class Woocommerce_Analytics {
/**
- * Package version, also the key that triggers the proxy speed module refresh. Rewritten from
- * composer.json by tasks/build-package.sh when the package is published, so bumping it here
- * does not refresh published copies. Bump the version in composer.json instead.
+ * Package version. Rewritten from composer.json by tasks/build-package.sh when the package is
+ * published, so bump the version in composer.json instead.
*/
const PACKAGE_VERSION = '0.18.0';
/**
- * Proxy speed module version option.
+ * Version of the speed module MU-plugin an earlier package installed, kept until the file is removed.
*
* @var string
*/
const PROXY_SPEED_MODULE_VERSION_OPTION = 'woocommerce_analytics_proxy_speed_module_version';
/**
- * Proxy speed module version check transient.
+ * Throttles the daily check for a leftover speed module MU-plugin.
*
* @var string
*/
const PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT = 'woocommerce_analytics_proxy_speed_module_version_check';
/**
- * Whether the MU-plugin speed module may serve requests.
- *
- * It reads this option because filters are unavailable before plugins load.
- * It tracks installation eligibility, so removal cannot reauthorize the module.
+ * Authorization read by the MU-plugin earlier package versions installed. Deleted at `init`, so that file cannot serve.
*
* @since 0.18.0
*
@@ -53,6 +48,15 @@ class Woocommerce_Analytics {
*/
const PROXY_SPEED_MODULE_AUTHORIZED_OPTION = 'woocommerce_analytics_proxy_speed_module_authorized';
+ /**
+ * Whether proxy tracking was on at the last `init`, for the speed module, which runs before plugins register the filter.
+ *
+ * @since 0.19.0
+ *
+ * @var string
+ */
+ const PROXY_TRACKING_ENABLED_OPTION = 'woocommerce_analytics_proxy_tracking_enabled';
+
/**
* Whether proxy tracking has ever been enabled on this site.
*
@@ -114,7 +118,7 @@ class Woocommerce_Analytics {
* @return bool
*/
public static function should_track_store() {
- // Register before early returns so the MU-plugin does not keep stale state.
+ // Register before early returns so the speed module does not keep stale state.
add_action( 'init', array( __CLASS__, 'sync_proxy_tracking_state' ), 20 );
// Ensure this is available, even with mu-plugins.
@@ -256,39 +260,48 @@ class Woocommerce_Analytics {
}
/**
- * Sync proxy tracking state for the REST route and MU-plugin speed module.
+ * Sync proxy tracking state for the REST route and the speed module.
*
* @since 0.18.0
*
* @return void
*/
public static function sync_proxy_tracking_state() {
- if ( \Automattic\Woocommerce_Analytics\Features::is_proxy_tracking_enabled()
- && 'yes' !== get_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION ) ) {
+ // 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 ) );
+ }
+
+ // A leftover MU-plugin keeps answering while this is yes, even after proxy tracking is turned off.
+ if ( false !== get_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) ) {
+ delete_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
+ }
+
+ $enabled = \Automattic\Woocommerce_Analytics\Features::is_proxy_tracking_enabled();
+
+ if ( $enabled && 'yes' !== get_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION ) ) {
update_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION, 'yes' );
}
- // Track module eligibility so a removed module cannot be reauthorized.
- $authorized = self::should_install_proxy_speed_module() ? 'yes' : 'no';
- $current = get_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
+ $value = $enabled ? 'yes' : 'no';
+ $current = get_option( self::PROXY_TRACKING_ENABLED_OPTION );
- if ( $current === $authorized ) {
+ if ( $current === $value ) {
return;
}
- // An absent option already means unauthorized, so most sites installing this
- // package never need a row saying so.
- if ( false === $current && 'no' === $authorized ) {
+ // An absent option already means off, so most sites installing this package never need a row saying so.
+ if ( false === $current && 'no' === $value ) {
return;
}
- update_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, $authorized );
+ update_option( self::PROXY_TRACKING_ENABLED_OPTION, $value );
}
/**
* Forget that proxy tracking was enabled, so the REST route is unregistered.
*
- * This is separate from removing the speed module because cached pages may remain.
+ * Separate from removing a leftover MU-plugin, because cached pages may still post to the route.
*
* @since 0.18.0
*
@@ -296,147 +309,54 @@ class Woocommerce_Analytics {
*/
public static function reset_proxy_tracking_state() {
delete_option( self::PROXY_TRACKING_EVER_ENABLED_OPTION );
+ delete_option( self::PROXY_TRACKING_ENABLED_OPTION );
delete_option( self::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
}
/**
- * Update the proxy speed module.
- *
- * The module must refuse itself because this periodic check can be delayed.
+ * Remove a speed module MU-plugin that an earlier package version installed.
*/
public static function maybe_update_proxy_speed_module() {
- // Skip if we've already checked recently.
if ( get_transient( self::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT ) ) {
return;
}
- $version = get_option( self::PROXY_SPEED_MODULE_VERSION_OPTION, false );
+ // Fire the deprecated filter during its deprecation window, so its callbacks get the notice.
+ \Automattic\Woocommerce_Analytics\Features::is_proxy_speed_module_enabled();
- if ( self::should_install_proxy_speed_module() ) {
- if ( $version !== self::PACKAGE_VERSION ) {
- self::maybe_add_proxy_speed_module();
- }
- } elseif ( $version !== false ) {
- self::maybe_remove_proxy_speed_module();
+ if ( false !== get_option( self::PROXY_SPEED_MODULE_VERSION_OPTION, false ) ) {
+ self::remove_legacy_proxy_speed_module();
}
- // Set the transient after the update attempt to prevent checking on every admin_init.
- // If the update failed, it will be retried after the transient expires (1 day).
+ // A failed removal keeps the version option, so it is retried once this expires.
set_transient( self::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT, 1, DAY_IN_SECONDS );
}
/**
- * Whether the proxy speed module belongs on this site.
- *
- * It requires its own opt-in and proxy tracking, so it cannot serve when
- * tracking is disabled.
+ * Formerly installed the speed module MU-plugin; the package no longer writes it.
*
- * @since 0.18.0
- *
- * @return bool
+ * @deprecated 0.19.0 Call Proxy_Speed_Module::enable() instead.
*/
- private static function should_install_proxy_speed_module() {
- return \Automattic\Woocommerce_Analytics\Features::is_proxy_speed_module_enabled()
- && \Automattic\Woocommerce_Analytics\Features::is_proxy_tracking_enabled();
+ public static function maybe_add_proxy_speed_module() {
+ // Kept as a no-op for callers such as the Jetpack activation hook.
}
/**
- * Maybe add proxy speed module.
+ * Stop the speed module serving once the plugin carrying this package is deactivated.
+ *
+ * A copy of this package in another plugin that never runs `init` would otherwise keep serving on the stored state.
*/
- public static function maybe_add_proxy_speed_module() {
- if ( ! self::should_install_proxy_speed_module() ) {
- return;
- }
-
- // Write before the module file exists because it fails closed on this option.
- self::sync_proxy_tracking_state();
-
- if ( ! self::init_filesystem() ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'WooCommerce Analytics proxy speed module not installed: filesystem unavailable.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- global $wp_filesystem;
-
- // Create the mu-plugin directory if it doesn't exist.
- if ( ! is_dir( WPMU_PLUGIN_DIR ) ) {
- wp_mkdir_p( WPMU_PLUGIN_DIR );
- }
-
- // If the mu-plugin directory doesn't exist, we can't copy the files.
- if ( ! is_dir( WPMU_PLUGIN_DIR ) ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'WooCommerce Analytics proxy speed module not installed: mu-plugins directory could not be created.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- // Check if the mu-plugin directory is writable.
- if ( ! $wp_filesystem->is_writable( WPMU_PLUGIN_DIR ) ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->debug( 'WooCommerce Analytics proxy speed module not installed: mu-plugins directory is not writable.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- if ( get_option( self::PROXY_SPEED_MODULE_VERSION_OPTION ) === self::PACKAGE_VERSION ) {
- // No need to copy the files again.
- return;
- }
-
- $mu_plugin_src_file = __DIR__ . '/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php';
- $mu_plugin_dest_file = trailingslashit( WPMU_PLUGIN_DIR ) . 'woocommerce-analytics-proxy-speed-module.php';
-
- // Verify source file exists before attempting to copy.
- if ( ! file_exists( $mu_plugin_src_file ) ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'WooCommerce Analytics proxy speed module source file not found.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- $content = $wp_filesystem->get_contents( $mu_plugin_src_file );
- if ( false === $content ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'Failed to read the WooCommerce Analytics proxy speed module source file.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- // Get the autoloader path from the current plugin location.
- $autoloader_path = self::locate_autoloader_file();
- if ( null === $autoloader_path ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'WooCommerce Analytics proxy speed module not installed: could not locate autoloader.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- // Replace placeholders with actual values.
- $content = str_replace(
- array( '{{AUTOLOADER_PATH}}', '{{VERSION}}' ),
- array( $autoloader_path, self::PACKAGE_VERSION ),
- $content
- );
-
- if ( ! $wp_filesystem->put_contents( $mu_plugin_dest_file, $content ) ) {
- if ( function_exists( 'wc_get_logger' ) ) {
- wc_get_logger()->error( 'Failed to write the WooCommerce Analytics proxy speed module file.', array( 'source' => 'woocommerce-analytics' ) );
- }
- return;
- }
-
- update_option( self::PROXY_SPEED_MODULE_VERSION_OPTION, self::PACKAGE_VERSION );
+ public static function maybe_remove_proxy_speed_module() {
+ delete_option( self::PROXY_TRACKING_ENABLED_OPTION );
+ self::remove_legacy_proxy_speed_module();
}
/**
- * Remove the proxy speed module when the plugin is deactivated.
+ * Remove a speed module MU-plugin left by an earlier package version, and the authorization it reads.
*
* Clear its authorization because an undeletable MU-plugin can still load.
*/
- public static function maybe_remove_proxy_speed_module() {
+ private static function remove_legacy_proxy_speed_module() {
// Revoked before anything can fail: WP_Filesystem() returns false outright on
// hosts that ask for credentials, and that is exactly the case where the file
// survives and keeps loading.
@@ -448,78 +368,21 @@ class Woocommerce_Analytics {
global $wp_filesystem;
- /**
- * Clean up MU plugin.
- */
$file_path = trailingslashit( WPMU_PLUGIN_DIR ) . 'woocommerce-analytics-proxy-speed-module.php';
- if ( $wp_filesystem->exists( $file_path ) && $wp_filesystem->is_writable( $file_path ) ) {
- $deleted = $wp_filesystem->delete( $file_path );
- if ( ! $deleted && function_exists( 'wc_get_logger' ) ) {
+ if ( $wp_filesystem->exists( $file_path )
+ && ( ! $wp_filesystem->is_writable( $file_path ) || ! $wp_filesystem->delete( $file_path ) ) ) {
+ if ( function_exists( 'wc_get_logger' ) ) {
wc_get_logger()->error( 'Failed to delete WooCommerce Analytics proxy speed module file. The MU-plugin may continue running.', array( 'source' => 'woocommerce-analytics' ) );
}
+ // Keep the version option, which is what schedules the next attempt.
+ return;
}
delete_option( self::PROXY_SPEED_MODULE_VERSION_OPTION );
delete_transient( self::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT );
}
- /**
- * Finds the path to the autoloader file.
- *
- * Uses multiple strategies to locate the autoloader, since this package
- * can be included in different plugins (Jetpack, WooCommerce Analytics, etc.):
- * 1. Jetpack autoloader global (if available)
- * 2. Composer's InstalledVersions API
- * 3. Directory-based guessing as a fallback
- *
- * @return string|null The path to the autoloader file, or null if not found.
- */
- private static function locate_autoloader_file() {
- global $jetpack_autoloader_loader;
-
- $autoload_file = null;
-
- // Try the Jetpack autoloader.
- if ( isset( $jetpack_autoloader_loader ) ) {
- $class_file = $jetpack_autoloader_loader->find_class_file( self::class );
- if ( $class_file ) {
- // Walk up 5 levels: src/ → woocommerce-analytics/ → automattic/ → jetpack_vendor/ → plugin root.
- $autoload_file = dirname( $class_file, 5 ) . '/vendor/autoload.php';
- }
- }
-
- // Try Composer's InstalledVersions API.
- if ( null === $autoload_file
- && is_callable( array( InstalledVersions::class, 'getInstallPath' ) )
- && InstalledVersions::isInstalled( 'automattic/woocommerce-analytics' )
- ) {
- $package_file = InstalledVersions::getInstallPath( 'automattic/woocommerce-analytics' );
- $expected_suffix = '/automattic/woocommerce-analytics';
- if ( substr( $package_file, -strlen( $expected_suffix ) ) === $expected_suffix ) {
- // Walk up 3 levels: woocommerce-analytics/ → automattic/ → jetpack_vendor/ → plugin root.
- $autoload_file = dirname( $package_file, 3 ) . '/vendor/autoload.php';
- }
- }
-
- // Guess based on directory structure.
- // First try standard vendor layout (vendor/automattic/woocommerce-analytics/src/),
- // then try standalone package with its own vendor dir.
- if ( null === $autoload_file ) {
- // Walk up 4 levels from src/: woocommerce-analytics/ → automattic/ → vendor/ → project root.
- $autoload_file = dirname( __DIR__, 4 ) . '/vendor/autoload.php';
- if ( ! file_exists( $autoload_file ) ) {
- $autoload_file = dirname( __DIR__ ) . '/vendor/autoload.php';
- }
- }
-
- if ( ! file_exists( $autoload_file ) ) {
- return null;
- }
-
- return $autoload_file;
- }
-
/**
* Initialize the WP filesystem.
*
diff --git a/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php b/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php
deleted file mode 100644
index 969195295a1..00000000000
--- a/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php
+++ /dev/null
@@ -1,368 +0,0 @@
-<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
-/**
- * Plugin Name: WooCommerce Analytics - Proxy Speed Module
- * Description: Speeds up WooCommerce Analytics' proxy by handling requests at MU-plugin stage and exiting early.
- * Plugin URI: https://woocommerce.com
- * Author: WooCommerce
- * Version: {{VERSION}}
- * Author URI: https://woocommerce.com
- *
- * Text Domain: woocommerce-analytics
- *
- * This module intercepts proxy tracking requests at the MU-plugin stage (before regular plugins load)
- * and handles them completely, then exits. This dramatically reduces response time by avoiding
- * the full WordPress plugin initialization.
- */
-
-defined( 'ABSPATH' ) || exit;
-
-/**
- * WooCommerce Analytics Proxy Speed Module
- */
-class WooCommerceAnalyticsProxySpeed {
-
- /**
- * Path of the proxy request.
- *
- * @var string
- */
- const PROXY_REQUEST_PATH = 'woocommerce-analytics/v1/track';
-
- /**
- * Autoloader path - this placeholder is replaced during installation.
- * DO NOT MODIFY - this value is injected by the parent plugin.
- *
- * @var string
- */
- const AUTOLOADER_PATH = '{{AUTOLOADER_PATH}}';
-
- /**
- * Initialize the proxy speed module.
- *
- * @return void
- */
- public function init() {
- // Only intercept POST requests to the proxy endpoint.
- if ( ! $this->is_proxy_request() ) {
- return;
- }
-
- // The WP Consent API has not loaded yet, so let the REST route apply the stored deny.
- if ( $this->is_statistics_consent_denied() ) {
- return;
- }
-
- // If autoloader failed, let WordPress continue loading
- // and fallback to the regular REST API.
- if ( ! $this->load_autoloader() ) {
- return;
- }
-
- // Unauthorized means "do not accelerate", not "do not serve". Only the REST
- // route can tell a disabled feature from a module whose authorization was
- // revoked while the feature stays on, so fall through and let it answer.
- if ( ! $this->is_authorized() ) {
- return;
- }
-
- // Handle the request completely and exit.
- $this->handle_proxy_request();
- exit;
- }
-
- /**
- * Check if current request is a proxy request.
- *
- * Self-contained on purpose: init() calls this before load_autoloader(), so no
- * package class exists yet to delegate to.
- *
- * @return bool
- */
- private function is_proxy_request() {
- if ( 'POST' !== $this->get_request_method() ) {
- return false;
- }
-
- $path = $this->get_request_path();
-
- if ( '' === $path ) {
- return false;
- }
-
- $normalized_path = rtrim( $path, '/' );
- $proxy_suffix = '/' . ltrim( self::PROXY_REQUEST_PATH, '/' );
-
- if ( strlen( $normalized_path ) < strlen( $proxy_suffix ) ) {
- return false;
- }
-
- return substr( $normalized_path, -strlen( $proxy_suffix ) ) === $proxy_suffix;
- }
-
- /**
- * Check if the shopper denied statistics consent, as recorded in the WP Consent API consent cookie.
- *
- * Unlike Consent_Manager, this reads the cookie whatever the consent type, which is not known yet. Only a prefix filter added by an earlier MU-plugin applies this early.
- *
- * @return bool
- */
- private function is_statistics_consent_denied() {
- $prefix = apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Reads a WP Consent API filter.
- if ( ! is_string( $prefix ) ) {
- return false;
- }
-
- $cookie_name = $prefix . '_statistics';
-
- return isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
- }
-
- /**
- * Load the autoloader.
- *
- * At MU-plugin stage, plugins haven't loaded yet, so we bootstrap
- * the autoloader directly using the path injected during installation.
- *
- * @return bool True if autoloader loaded and classes are available.
- */
- private function load_autoloader() {
- $autoload_path = self::AUTOLOADER_PATH;
-
- // Validate the path was properly injected (not still a placeholder).
- if ( strpos( $autoload_path, '{{' ) !== false ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: Autoloader path placeholder was not replaced during installation.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- if ( ! file_exists( $autoload_path ) ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: Autoloader file not found at: ' . $autoload_path ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- try {
- require_once $autoload_path;
- } catch ( \Throwable $e ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: Failed to load autoloader: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- if ( ! class_exists( '\Automattic\Woocommerce_Analytics\WC_Analytics_Tracking' ) ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: WC_Analytics_Tracking class not found after loading autoloader.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- // The autoloader resolves the highest version across active plugins, which can
- // be older than the one that wrote this file. Fall back rather than fatal.
- if ( ! method_exists( '\Automattic\Woocommerce_Analytics\WC_Analytics_Tracking', 'record_client_event' ) ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: the loaded WC_Analytics_Tracking predates record_client_event().' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- // Avoid a 500 when an older package lacks the bound constant.
- if ( ! defined( '\Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::MAX_CLIENT_EVENTS_PER_REQUEST' ) ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: the loaded WC_Analytics_Tracking predates the client input bounds.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- // Same skew, other class: process_proxy_request() reads this to decide whether
- // to serve, and an older package lacking it throws where nothing can fall back.
- if ( ! defined( '\Automattic\Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION' ) ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: the loaded Woocommerce_Analytics predates the speed module authorization option.' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- return false;
- }
-
- return true;
- }
-
- /**
- * Whether this module may serve the request.
- *
- * Features::is_proxy_tracking_enabled() cannot be used here: no plugin has
- * registered that filter this early, so it reads false everywhere. Only an
- * explicit yes serves, so a network-wide module file cannot answer for a site
- * that never authorized it.
- *
- * @return bool
- */
- private function is_authorized() {
- return 'yes' === get_option( \Automattic\Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
- }
-
- /**
- * Handle the proxy request completely.
- *
- * Processes the events and sends the response without loading
- * regular WordPress plugins.
- *
- * @return void
- */
- private function handle_proxy_request() {
- if ( ! headers_sent() ) {
- header( 'Content-Type: application/json; charset=utf-8' );
- header( 'Cache-Control: no-cache, must-revalidate' );
- }
-
- try {
- $this->process_proxy_request();
- } catch ( \Throwable $e ) {
- error_log( 'WooCommerce Analytics Proxy Speed Module: Uncaught error in handle_proxy_request: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- $this->send_json_response(
- array(
- 'success' => false,
- 'error' => 'Internal server error while processing analytics events.',
- ),
- 500
- );
- }
- }
-
- /**
- * Process the proxy request body: parse events, record them, and send the response.
- *
- * @return void
- */
- private function process_proxy_request() {
- // Apply magic quotes to superglobals ($_GET, $_POST, $_COOKIE, $_REQUEST) for compatibility with the regular API flow.
- if ( function_exists( 'wp_magic_quotes' ) ) {
- wp_magic_quotes();
- }
-
- $body = file_get_contents( 'php://input' );
- if ( empty( $body ) ) {
- $this->send_json_response(
- array(
- 'success' => false,
- 'error' => 'Empty request body',
- ),
- 400
- );
- return;
- }
-
- $events = json_decode( $body, true );
- if ( json_last_error() !== JSON_ERROR_NONE ) {
- $this->send_json_response(
- array(
- 'success' => false,
- 'error' => 'Invalid JSON',
- ),
- 400
- );
- return;
- }
-
- // Normalize: wrap a single event object or unexpected scalar in an array.
- if ( ! is_array( $events ) || isset( $events['event_name'] ) ) {
- $events = array( $events );
- }
-
- // Use the same batch limit as the REST controller.
- $max_events = \Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::MAX_CLIENT_EVENTS_PER_REQUEST;
- if ( count( $events ) > $max_events ) {
- $events = array_slice( $events, 0, $max_events, true );
- }
-
- $results = array();
- $has_errors = false;
-
- foreach ( $events as $index => $event ) {
- if ( empty( $event ) || ! is_array( $event ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => 'Invalid event format',
- );
- $has_errors = true;
- continue;
- }
-
- $event_name = $event['event_name'] ?? null;
- $properties = $event['properties'] ?? array();
-
- if ( ! $event_name || ! is_string( $event_name ) || ! is_array( $properties ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => 'Missing event_name or invalid properties',
- );
- $has_errors = true;
- continue;
- }
-
- $result = \Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::record_client_event( $event_name, $properties );
-
- if ( is_wp_error( $result ) ) {
- $results[ $index ] = array(
- 'success' => false,
- 'error' => $result->get_error_message(),
- );
- $has_errors = true;
- continue;
- }
-
- $results[ $index ] = array( 'success' => true );
- }
-
- \Automattic\Woocommerce_Analytics\WC_Analytics_Tracking::send_batched_pixels();
-
- $this->send_json_response(
- array(
- 'success' => ! $has_errors,
- 'results' => $results,
- 'is_proxy_speed_module' => true,
- ),
- $has_errors ? 207 : 200
- );
- }
-
- /**
- * Send a JSON response.
- *
- * @param array $data Response data.
- * @param int $status_code HTTP status code.
- * @return void
- */
- private function send_json_response( $data, $status_code = 200 ) {
- http_response_code( $status_code );
- echo wp_json_encode( $data, JSON_UNESCAPED_SLASHES );
- }
-
- /**
- * Helper method to retrieve the request path.
- *
- * Extracts and validates the path component from $_SERVER['REQUEST_URI']
- * for safe internal matching.
- *
- * @return string The validated path, or empty string on failure.
- */
- private function get_request_path() {
- $raw_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
-
- if ( ! is_string( $raw_uri ) ) {
- return '';
- }
-
- // Extract just the path component to avoid matching against query strings, etc.
- $path = wp_parse_url( $raw_uri, PHP_URL_PATH );
-
- if ( ! is_string( $path ) ) {
- return '';
- }
-
- // Ensure the path contains only expected URL path characters.
- if ( preg_match( '/[^A-Za-z0-9\-._~\/]/', $path ) ) {
- return '';
- }
-
- return $path;
- }
-
- /**
- * Helper method to get request method.
- *
- * @return string
- */
- private function get_request_method() {
- return isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
- }
-}
-
-( new WooCommerceAnalyticsProxySpeed() )->init();
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 51fd520620b..75d303cca0c 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
@@ -1,126 +1,415 @@
<?php
/**
- * Tests for the proxy speed module MU-plugin template.
+ * Tests for the proxy speed module.
*
* @package automattic/woocommerce-analytics
*/
namespace Automattic\Woocommerce_Analytics;
+use Automattic\Woocommerce_Analytics;
+use PHPUnit\Framework\Attributes\DataProvider;
use WorDBless\BaseTestCase;
/**
- * Tests that the speed module leaves a shopper's stored statistics deny to the REST route.
+ * Tests for Proxy_Speed_Module.
+ *
+ * maybe_serve() exits after answering, so these tests drive its private respond() instead.
*/
class Proxy_Speed_Module_Test extends BaseTestCase {
/**
- * File error_log() writes to during a test.
- *
- * @var string
- */
- private $error_log_file;
-
- /**
- * Previous error_log ini value.
+ * Request globals as they were before the test.
*
- * @var string|false
+ * @var array
*/
- private $previous_error_log;
+ private $previous_server;
/**
- * Request globals as they were before the test.
+ * Fired actions as they were before the test.
*
* @var array
*/
- private $previous_server;
+ private $previous_wp_actions;
/**
- * Load the template, whose own init() returns at load because the test request is not a proxy request.
+ * Start from an enabled module, with proxy tracking off and no queued pixels.
*/
public function set_up(): void {
parent::set_up();
- require_once dirname( __DIR__, 2 ) . '/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php';
-
- $this->previous_server = $_SERVER;
- $this->error_log_file = tempnam( sys_get_temp_dir(), 'wca-speed-module' );
- $this->previous_error_log = ini_set( 'error_log', $this->error_log_file ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+ $this->previous_server = $_SERVER;
+ $this->previous_wp_actions = $GLOBALS['wp_actions'];
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
+ $this->set_pixel_batch_queue( array() );
+ $this->set_enabled( true );
}
/**
- * Restore the request globals and error log.
+ * Restore the request globals.
*/
public function tear_down(): void {
unset( $_COOKIE['wp_consent_statistics'], $_COOKIE['custom_statistics'] );
- $_SERVER = $this->previous_server;
+ $_SERVER = $this->previous_server;
+ $GLOBALS['wp_actions'] = $this->previous_wp_actions;
+ remove_action( 'muplugins_loaded', array( Proxy_Speed_Module::class, 'maybe_serve' ) );
+ remove_all_filters( 'doing_it_wrong_trigger_error' );
+ remove_all_actions( 'doing_it_wrong_run' );
+ $this->set_enabled( false );
remove_all_filters( 'wp_consent_cookie_prefix' );
- ini_set( 'error_log', (string) $this->previous_error_log ); // phpcs:ignore WordPress.PHP.IniSet.Risky
- wp_delete_file( $this->error_log_file );
+ remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_EVER_ENABLED_OPTION );
+ $GLOBALS['wp_rest_server'] = null;
+ $this->set_pixel_batch_queue( array() );
parent::tear_down();
}
/**
- * Test that a proxy request carrying a stored deny returns before the module loads the package.
+ * @dataProvider provide_requests_left_to_the_rest_route
+ *
+ * @param string $method Request method.
+ * @param string $uri Request URI.
+ * @param string|null $proxy_tracking Stored proxy tracking state, or null when absent.
+ * @param string|null $choice Stored statistics choice, or null when none is stored.
*/
- public function test_falls_through_to_the_rest_route_when_the_shopper_denied_statistics(): void {
- $this->make_proxy_request();
- $_COOKIE['wp_consent_statistics'] = 'deny';
+ #[DataProvider( 'provide_requests_left_to_the_rest_route' )]
+ public function test_leaves_the_request_to_the_rest_route( $method, $uri, $proxy_tracking, $choice ): void {
+ $this->make_request( $method, $uri );
+ if ( null !== $proxy_tracking ) {
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, $proxy_tracking );
+ }
+ if ( null !== $choice ) {
+ $_COOKIE['wp_consent_statistics'] = $choice;
+ }
- ( new \WooCommerceAnalyticsProxySpeed() )->init();
+ list( $served, $output ) = $this->respond();
- $this->assertSame( '', file_get_contents( $this->error_log_file ) );
+ $this->assertFalse( $served );
+ $this->assertSame( '', $output, 'A request left to the REST route must not be answered here.' );
}
/**
- * Test that a proxy request without a stored deny goes on to load the package.
+ * Requests the module must not answer.
*
- * The template's autoloader placeholder is never replaced here, so loading it logs an error.
+ * @return array
+ */
+ public static function provide_requests_left_to_the_rest_route(): array {
+ $route = '/wp-json/woocommerce-analytics/v1/track';
+ return array(
+ 'not a POST' => array( 'GET', $route, 'yes', null ),
+ 'proxy tracking never on' => array( 'POST', $route, null, null ),
+ 'proxy tracking turned off' => array( 'POST', $route, 'no', null ),
+ 'shopper denied statistics' => array( 'POST', $route, 'yes', 'deny' ),
+ 'another route' => array( 'POST', '/wp-json/wp/v2/posts', 'yes', null ),
+ 'a longer route' => array( 'POST', $route . 'er', 'yes', null ),
+ 'route in the query string' => array( 'POST', '/?rest_route=' . $route, 'yes', null ),
+ 'encoded path' => array( 'POST', '/wp-json/%2e%2e' . $route, 'yes', null ),
+ );
+ }
+
+ /**
+ * A direct maybe_serve() call without enable() must not bypass the REST route's checks.
+ */
+ public function test_leaves_the_request_to_the_rest_route_without_enable(): void {
+ $this->set_enabled( false );
+ $this->make_request( 'POST', '/wp-json/woocommerce-analytics/v1/track' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+
+ list( $served ) = $this->respond();
+
+ $this->assertFalse( $served );
+ }
+
+ /**
+ * Test that the stored deny is read under a consent cookie prefix filtered by an earlier MU-plugin.
+ */
+ public function test_leaves_a_deny_under_a_filtered_cookie_prefix_to_the_rest_route(): void {
+ $this->make_request( 'POST', '/wp-json/woocommerce-analytics/v1/track' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ add_filter( 'wp_consent_cookie_prefix', fn() => 'custom' );
+ $_COOKIE['custom_statistics'] = 'deny';
+
+ list( $served ) = $this->respond();
+
+ $this->assertFalse( $served );
+ }
+
+ /**
+ * The test request has no body, so an answered request is the module's empty-body error.
*
- * @dataProvider provide_choices_the_module_still_serves
+ * @dataProvider provide_requests_the_module_answers
*
+ * @param string $uri Request URI.
* @param string|null $choice The stored statistics choice, or null when none is stored.
*/
- public function test_goes_on_to_load_the_package_without_a_stored_deny( $choice ): void {
- $this->make_proxy_request();
+ #[DataProvider( 'provide_requests_the_module_answers' )]
+ public function test_answers_a_proxy_request_while_proxy_tracking_is_on( $uri, $choice ): void {
+ $this->make_request( 'POST', $uri );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
if ( null !== $choice ) {
$_COOKIE['wp_consent_statistics'] = $choice;
}
- ( new \WooCommerceAnalyticsProxySpeed() )->init();
+ list( $served, $output ) = $this->respond();
- $this->assertStringContainsString( 'Autoloader path placeholder was not replaced', file_get_contents( $this->error_log_file ) );
+ $this->assertTrue( $served );
+ $this->assertSame(
+ array(
+ 'success' => false,
+ 'error' => 'Empty request body',
+ ),
+ json_decode( $output, true )
+ );
+ $this->assertTrue( Features::is_proxy_tracking_enabled(), 'A shopper without a tk_ai cookie needs the IP-based visitor id, which reads this.' );
}
/**
- * Stored choices that do not deny statistics.
+ * Requests the module answers.
*
* @return array
*/
- public static function provide_choices_the_module_still_serves(): array {
+ public static function provide_requests_the_module_answers(): array {
return array(
- 'no stored choice' => array( null ),
- 'stored allow' => array( 'allow' ),
+ 'no stored choice' => array( '/wp-json/woocommerce-analytics/v1/track', null ),
+ 'stored allow' => array( '/wp-json/woocommerce-analytics/v1/track', 'allow' ),
+ 'subdirectory install, trailing slash' => array( '/shop/wp-json/woocommerce-analytics/v1/track/', null ),
);
}
/**
- * Test that the stored deny is read under a consent cookie prefix filtered by an MU-plugin that loads before the module.
+ * The autoloader reads an exit before `plugins_loaded` as a failed boot and empties its cache.
*/
- public function test_falls_through_under_a_prefix_filtered_by_an_earlier_mu_plugin(): void {
- $this->make_proxy_request();
- add_filter( 'wp_consent_cookie_prefix', fn() => 'custom' );
- $_COOKIE['custom_statistics'] = 'deny';
+ public function test_answering_keeps_the_jetpack_autoloader_cache(): void {
+ require_once __DIR__ . '/mocks/class-jetpack-autoloader-shutdown-handler.php';
+ $this->make_request( 'POST', '/wp-json/woocommerce-analytics/v1/track' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ $autoloader_handler = new \Automattic\Jetpack\Autoloader\jp_test\al6_0_4\Shutdown_Handler();
+ $other_handler = static function () {};
+ add_action( 'shutdown', $autoloader_handler );
+ add_action( 'shutdown', $other_handler );
+
+ $this->respond();
+
+ $this->assertFalse( has_action( 'shutdown', $autoloader_handler ) );
+ $this->assertSame( 10, has_action( 'shutdown', $other_handler ) );
+ remove_action( 'shutdown', $autoloader_handler );
+ remove_action( 'shutdown', $other_handler );
+ }
+
+ /**
+ * After an error the autoloader handler stays hooked, so it can empty a cache that caused the error.
+ */
+ public function test_an_error_keeps_the_jetpack_autoloader_handler(): void {
+ require_once __DIR__ . '/mocks/class-jetpack-autoloader-shutdown-handler.php';
+ $this->make_request( 'POST', '/wp-json/woocommerce-analytics/v1/track' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ // A pixel that cannot be converted to a string makes sending throw.
+ $this->set_pixel_batch_queue( array( new \stdClass() ) );
+ $autoloader_handler = new \Automattic\Jetpack\Autoloader\jp_test\al6_0_4\Shutdown_Handler();
+ add_action( 'shutdown', $autoloader_handler );
+ $previous_error_log = ini_set( 'error_log', '/dev/null' ); // phpcs:ignore WordPress.PHP.IniSet.Risky
- ( new \WooCommerceAnalyticsProxySpeed() )->init();
+ list( , $output ) = $this->respond();
- $this->assertSame( '', file_get_contents( $this->error_log_file ) );
+ ini_set( 'error_log', (string) $previous_error_log ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+ $this->assertSame( 'Internal server error while processing analytics events.', json_decode( $output, true )['error'] );
+ $this->assertSame( 10, has_action( 'shutdown', $autoloader_handler ) );
+ remove_action( 'shutdown', $autoloader_handler );
}
/**
- * Make the current request look like a proxy tracking request.
+ * Test that answering sends the pixels queued while handling the request.
+ */
+ public function test_sends_the_queued_pixels_after_answering(): void {
+ $this->make_request( 'POST', '/wp-json/woocommerce-analytics/v1/track' );
+ update_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, 'yes' );
+ // A closed loopback port, so the non-blocking send fails fast without leaving the machine.
+ $this->set_pixel_batch_queue( array( 'http://127.0.0.1:9/t.gif' ) );
+
+ $this->respond();
+
+ $property = ( new \ReflectionClass( WC_Analytics_Tracking::class ) )->getProperty( 'pixel_batch_queue' );
+ $property->setAccessible( true );
+ $this->assertSame( array(), $property->getValue() );
+ }
+
+ /**
+ * @dataProvider provide_request_bodies
+ *
+ * @param string $body Raw request body.
+ * @param int $expected_status Expected status code.
+ * @param array $expected_data Expected subset of the response data.
+ */
+ #[DataProvider( 'provide_request_bodies' )]
+ public function test_responds_to_the_request_body( $body, $expected_status, $expected_data ): void {
+ $method = new \ReflectionMethod( Proxy_Speed_Module::class, 'handle_events' );
+ $method->setAccessible( true );
+
+ $response = $method->invoke( null, $body );
+
+ $this->assertSame( $expected_status, $response['status'] );
+ $this->assertSame( $expected_data, array_intersect_key( $response['data'], $expected_data ) );
+ }
+
+ /**
+ * Request bodies and the responses they get.
+ *
+ * @return array
+ */
+ public static function provide_request_bodies(): array {
+ return array(
+ 'invalid JSON' => array( '{', 400, array( 'error' => 'Invalid JSON' ) ),
+ 'one invalid event' => array(
+ '[{"properties":{}},{"event_name":"add_to_cart"}]',
+ 207,
+ array(
+ 'success' => false,
+ 'is_proxy_speed_module' => true,
+ ),
+ ),
+ 'valid events' => array(
+ '{"event_name":"add_to_cart"}',
+ 200,
+ array(
+ 'success' => true,
+ 'is_proxy_speed_module' => true,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * A renamed route must rename the module's path too, or the module silently never serves.
+ */
+ public function test_the_rest_route_matches_the_module_path(): void {
+ add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
+ Woocommerce_Analytics::sync_proxy_tracking_state();
+ $GLOBALS['wp_rest_server'] = null;
+ Woocommerce_Analytics::register_rest_routes();
+
+ $this->assertArrayHasKey( '/' . Proxy_Speed_Module::PROXY_REQUEST_PATH, rest_get_server()->get_routes() );
+ }
+
+ /**
+ * Test that an MU-plugin's call waits for every MU-plugin, so their consent cookie prefix applies.
+ */
+ public function test_enable_from_an_mu_plugin_serves_on_muplugins_loaded(): void {
+ $this->set_enabled( false );
+ $this->set_load_stage( 'mu-plugins' );
+
+ Proxy_Speed_Module::enable();
+
+ $this->assertTrue( $this->is_enabled() );
+ $this->assertSame( 10, has_action( 'muplugins_loaded', array( Proxy_Speed_Module::class, 'maybe_serve' ) ) );
+ }
+
+ /**
+ * Test that a plugin file's call serves at once, since `muplugins_loaded` has already fired.
+ */
+ public function test_enable_from_a_plugin_file_serves_at_once(): void {
+ $this->set_enabled( false );
+ $this->set_load_stage( 'plugins' );
+ $this->make_request( 'GET', '/' );
+
+ Proxy_Speed_Module::enable();
+
+ $this->assertTrue( $this->is_enabled() );
+ $this->assertFalse( has_action( 'muplugins_loaded', array( Proxy_Speed_Module::class, 'maybe_serve' ) ) );
+ }
+
+ /**
+ * A call once plugins have loaded is too late to save anything, so it is refused.
+ */
+ public function test_enable_after_plugins_loaded_is_refused(): void {
+ $this->set_enabled( false );
+ $this->set_load_stage( 'loaded' );
+ $wrong = 0;
+ add_action(
+ 'doing_it_wrong_run',
+ function () use ( &$wrong ) {
+ ++$wrong;
+ }
+ );
+ add_filter( 'doing_it_wrong_trigger_error', '__return_false' );
+
+ Proxy_Speed_Module::enable();
+
+ $this->assertFalse( $this->is_enabled() );
+ $this->assertSame( 1, $wrong );
+ }
+
+ /**
+ * Make the load-stage actions look fired up to the given stage.
+ *
+ * @param string $stage `mu-plugins` (loading MU-plugins), `plugins` (loading plugins) or `loaded`.
+ */
+ private function set_load_stage( $stage ): void {
+ unset( $GLOBALS['wp_actions']['muplugins_loaded'], $GLOBALS['wp_actions']['plugins_loaded'] );
+ if ( 'mu-plugins' !== $stage ) {
+ $GLOBALS['wp_actions']['muplugins_loaded'] = 1;
+ }
+ if ( 'loaded' === $stage ) {
+ $GLOBALS['wp_actions']['plugins_loaded'] = 1;
+ }
+ }
+
+ /**
+ * Make the current request look like the given request.
+ *
+ * @param string $method Request method.
+ * @param string $uri Request URI.
+ */
+ private function make_request( $method, $uri ): void {
+ $_SERVER['REQUEST_METHOD'] = $method;
+ $_SERVER['REQUEST_URI'] = $uri;
+ }
+
+ /**
+ * Run the module's respond step and capture its output.
+ *
+ * @return array{0: bool, 1: string} Whether it answered, and what it printed.
+ */
+ private function respond(): array {
+ $method = new \ReflectionMethod( Proxy_Speed_Module::class, 'respond' );
+ $method->setAccessible( true );
+
+ ob_start();
+ $served = $method->invoke( null );
+ $output = (string) ob_get_clean();
+
+ return array( $served, $output );
+ }
+
+ /**
+ * Replace the queued pixel URLs.
+ *
+ * @param array $queue Pixel URLs.
+ */
+ private function set_pixel_batch_queue( array $queue ): void {
+ $property = ( new \ReflectionClass( WC_Analytics_Tracking::class ) )->getProperty( 'pixel_batch_queue' );
+ $property->setAccessible( true );
+ $property->setValue( null, $queue );
+ }
+
+ /**
+ * Set what enable() records.
+ *
+ * @param bool $enabled Whether the module is enabled.
+ */
+ private function set_enabled( bool $enabled ): void {
+ $property = ( new \ReflectionClass( Proxy_Speed_Module::class ) )->getProperty( 'enabled' );
+ $property->setAccessible( true );
+ $property->setValue( null, $enabled );
+ }
+
+ /**
+ * Read what enable() recorded.
+ *
+ * @return bool
*/
- private function make_proxy_request(): void {
- $_SERVER['REQUEST_METHOD'] = 'POST';
- $_SERVER['REQUEST_URI'] = '/wp-json/woocommerce-analytics/v1/track';
+ private function is_enabled(): bool {
+ $property = ( new \ReflectionClass( Proxy_Speed_Module::class ) )->getProperty( 'enabled' );
+ $property->setAccessible( true );
+ return $property->getValue();
}
}
diff --git a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Proxy_Test.php b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Proxy_Test.php
index d248477a7d3..0d3bc575619 100644
--- a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Proxy_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Proxy_Test.php
@@ -42,7 +42,7 @@ class WC_Analytics_Tracking_Proxy_Test extends BaseTestCase {
parent::set_up();
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
delete_option( Woocommerce_Analytics::PROXY_TRACKING_EVER_ENABLED_OPTION );
- delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
$GLOBALS['wp_rest_server'] = null;
$this->server_snapshot = $_SERVER;
$this->reset_pixel_batch_queue();
@@ -57,7 +57,7 @@ class WC_Analytics_Tracking_Proxy_Test extends BaseTestCase {
public function tear_down(): void {
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
delete_option( Woocommerce_Analytics::PROXY_TRACKING_EVER_ENABLED_OPTION );
- delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
$GLOBALS['wp_rest_server'] = null;
$_SERVER = $this->server_snapshot;
unset( $_COOKIE['tk_ai'] );
diff --git a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
index 423198d7804..f44017d673c 100644
--- a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
@@ -939,75 +939,6 @@ class WC_Analytics_Tracking_Reserved_Props_Test extends BaseTestCase {
$this->assertStringEndsWith( '…', $sanitized['pn'] );
}
- /**
- * Keep the MU-plugin template aligned with the package API.
- */
- public function test_mu_plugin_template_stays_in_step_with_the_package(): void {
- $template = file_get_contents(
- dirname( __DIR__, 2 ) . '/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php'
- );
-
- $this->assertStringContainsString(
- '::record_client_event(',
- $template,
- 'The template must record through the untrusted-client entry point.'
- );
- $this->assertStringNotContainsString(
- '::record_event(',
- $template,
- 'The template must not call the trusted entry point.'
- );
-
- // Nothing executes the template, so the direction of the comparison has to be
- // asserted literally: inverting it serves exactly the requests it is there to
- // refuse, and every other test stays green.
- $this->assertStringContainsString(
- "return 'yes' === get_option( \\Automattic\\Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );",
- $template,
- 'Only an explicit yes may authorize the module; an absent option must not serve.'
- );
- // Position, not presence: a check that runs after the events are recorded is
- // not a check, and a string match alone cannot tell the two apart.
- $this->assertLessThan(
- strpos( $template, '$this->handle_proxy_request();' ),
- strpos( $template, 'if ( ! $this->is_authorized() ) {' ),
- 'The authorization check must run before the request is handled.'
- );
- // Falling through is what lets the REST route separate a disabled feature from
- // a module whose authorization was revoked while the feature stays on.
- $this->assertStringNotContainsString(
- 'proxy_tracking_disabled',
- $template,
- 'Refusing is the REST route\'s job; an unauthorized module returns so the route can answer.'
- );
-
- $this->assertStringContainsString(
- 'MAX_CLIENT_EVENTS_PER_REQUEST',
- $template,
- 'The template must cap the batch with the same constant as the REST controller.'
- );
- // The autoloader resolves the highest version across active plugins, which can
- // predate this file, so every package constant it reads needs a defined() guard
- // in load_autoloader(). Collected rather than listed: a constant added to the
- // template without a guard is a 500 nothing can fall back from.
- preg_match_all( '/\\\\Automattic\\\\[A-Za-z_\\\\]*::[A-Z][A-Z0-9_]*/', $template, $reads );
- preg_match_all( '/defined\\( \'([^\']+)\' \)/', $template, $guards );
-
- $this->assertNotEmpty( $reads[0], 'The template is expected to read package constants.' );
-
- foreach ( array_unique( $reads[0] ) as $constant ) {
- $this->assertContains(
- $constant,
- $guards[1],
- "load_autoloader() must check {$constant} exists before process_proxy_request() reads it."
- );
- $this->assertTrue(
- defined( $constant ),
- "The guarded name must resolve, or load_autoloader() always returns false and the module never serves. Reviewers read the leading backslash in {$constant} as breaking defined(); it does not, on any PHP this package supports."
- );
- }
- }
-
/**
* Keep the documented bounds in sync with their constants.
*/
diff --git a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Test.php b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Test.php
index ea52fae124c..f4648bb5c96 100644
--- a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Test.php
@@ -210,4 +210,28 @@ class WC_Analytics_Tracking_Test extends BaseTestCase {
$this->assertSame( 'test-visitor-id-1234567890ab', $visitor_id, 'Cookie value should be returned verbatim when present.' );
}
+
+ /**
+ * The speed module can mint a salt before pluggable.php loads, where wp_generate_password() is undefined.
+ */
+ public function test_get_daily_salt_does_not_need_pluggable_functions(): void {
+ delete_option( WC_Analytics_Tracking::DAILY_SALT_OPTION );
+
+ $pluggable_calls = 0;
+ $spy = function ( $password ) use ( &$pluggable_calls ) {
+ ++$pluggable_calls;
+ return $password;
+ };
+ add_filter( 'random_password', $spy );
+
+ $method = new \ReflectionMethod( WC_Analytics_Tracking::class, 'get_daily_salt' );
+ $method->setAccessible( true );
+ $salt = $method->invoke( null );
+
+ remove_filter( 'random_password', $spy );
+
+ $this->assertSame( 0, $pluggable_calls );
+ $this->assertMatchesRegularExpression( '/^[0-9a-f]{32}$/', $salt );
+ $this->assertSame( $salt, get_option( WC_Analytics_Tracking::DAILY_SALT_OPTION )['salt'] );
+ }
}
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 fa7a8c7d3d6..dcd266bf2d7 100644
--- a/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/Woocommerce_Analytics_Test.php
@@ -8,6 +8,7 @@
namespace Automattic\Woocommerce_Analytics;
use Automattic\Woocommerce_Analytics;
+use PHPUnit\Framework\Attributes\DataProvider;
use WorDBless\BaseTestCase;
/**
@@ -18,27 +19,16 @@ class WooCommerce_Test_Double {}
/**
* Tests for the Woocommerce_Analytics class.
*
- * Focuses on testing the MU-plugin auto-update mechanism.
+ * Focuses on the proxy tracking state the speed module reads, and the leftover MU-plugin cleanup.
*/
class Woocommerce_Analytics_Test extends BaseTestCase {
- /**
- * Temporary directory for MU-plugins during tests.
- *
- * @var string
- */
- private $temp_mu_plugin_dir;
-
/**
* Set up test environment.
*/
public function set_up(): void {
parent::set_up();
- // Create a temporary directory for MU-plugins.
- $this->temp_mu_plugin_dir = sys_get_temp_dir() . '/wc-analytics-test-mu-plugins-' . uniqid();
- mkdir( $this->temp_mu_plugin_dir, 0755, true );
-
// Clean up any existing options/transients.
delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION );
delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
@@ -46,7 +36,7 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
delete_transient( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT );
// Remove any filters that might interfere.
- remove_all_filters( 'woocommerce_analytics_auto_install_proxy_speed_module' );
+ delete_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION );
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
}
@@ -54,43 +44,17 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
* Tear down test environment.
*/
public function tear_down(): void {
- // Clean up temporary directory.
- if ( is_dir( $this->temp_mu_plugin_dir ) ) {
- $this->recursive_rmdir( $this->temp_mu_plugin_dir );
- }
-
// Clean up options and transients.
delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION );
delete_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION );
delete_option( Woocommerce_Analytics::PROXY_TRACKING_EVER_ENABLED_OPTION );
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 );
parent::tear_down();
}
- /**
- * Recursively remove a directory.
- *
- * @param string $dir Directory path.
- */
- private function recursive_rmdir( $dir ): void {
- if ( is_dir( $dir ) ) {
- $objects = scandir( $dir );
- foreach ( $objects as $object ) {
- if ( $object !== '.' && $object !== '..' ) {
- $path = $dir . '/' . $object;
- if ( is_dir( $path ) ) {
- $this->recursive_rmdir( $path );
- } else {
- unlink( $path );
- }
- }
- }
- rmdir( $dir );
- }
- }
-
/**
* Test that transient throttling prevents frequent checks.
*/
@@ -151,134 +115,139 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
}
/**
- * Test that update is skipped when version matches current package version.
+ * Jetpack still calls this on activation, so it must stay callable and write nothing.
*/
- public function test_maybe_update_proxy_speed_module_skips_when_version_matches(): void {
- // Enable both flags: the module is only installed where the feature it
- // accelerates is also on.
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
+ public function test_maybe_add_proxy_speed_module_installs_nothing(): void {
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- // Set version to match current.
- update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, Woocommerce_Analytics::PACKAGE_VERSION );
-
- // Call the method.
- Woocommerce_Analytics::maybe_update_proxy_speed_module();
-
- // Version should remain the same (no update needed).
- $this->assertSame( Woocommerce_Analytics::PACKAGE_VERSION, get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ) );
+ Woocommerce_Analytics::maybe_add_proxy_speed_module();
- remove_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
- remove_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ) );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
}
/**
- * Turning proxy tracking off must uninstall the speed module, not just leave
- * the REST route unregistered. Otherwise the module keeps intercepting POSTs
- * at MU-plugin stage on a site whose operator believes the endpoint is gone.
+ * A file an earlier version installed runs stale code, so the daily check removes it, and retries if it cannot.
+ *
+ * @dataProvider provide_leftover_module_files
+ *
+ * @param bool $deletable Whether the file can be deleted.
*/
- public function test_maybe_update_proxy_speed_module_removes_when_proxy_tracking_disabled(): void {
- // The module's own flag stays on; only proxy tracking is off.
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
+ #[DataProvider( 'provide_leftover_module_files' )]
+ public function test_maybe_update_proxy_speed_module_removes_a_leftover_module( $deletable ): void {
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, '0.18.1' );
+ // Not wp_mkdir_p(): it refuses the `..` in the test bootstrap's WPMU_PLUGIN_DIR.
+ $created_dir = ! is_dir( WPMU_PLUGIN_DIR ) && mkdir( WPMU_PLUGIN_DIR, 0755, true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
+ $file = trailingslashit( WPMU_PLUGIN_DIR ) . 'woocommerce-analytics-proxy-speed-module.php';
+ file_put_contents( $file, '<?php' );
+ if ( ! $deletable ) {
+ chmod( $file, 0444 );
+ }
- update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, Woocommerce_Analytics::PACKAGE_VERSION );
+ try {
+ Woocommerce_Analytics::maybe_update_proxy_speed_module();
+
+ $this->assertSame( ! $deletable, file_exists( $file ) );
+ $this->assertSame(
+ $deletable ? false : '0.18.1',
+ get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ),
+ 'The version option schedules the retry, so only a removed file may clear it.'
+ );
+ } finally {
+ if ( file_exists( $file ) ) {
+ chmod( $file, 0644 );
+ unlink( $file );
+ }
+ if ( $created_dir ) {
+ rmdir( WPMU_PLUGIN_DIR );
+ }
+ }
+ }
- Woocommerce_Analytics::maybe_update_proxy_speed_module();
+ /**
+ * Leftover module files.
+ *
+ * @return array
+ */
+ public static function provide_leftover_module_files(): array {
+ return array(
+ 'deletable' => array( true ),
+ 'undeletable' => array( false ),
+ );
+ }
- $this->assertFalse(
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ),
- 'The speed module must be uninstalled when proxy tracking is disabled.'
+ /**
+ * A callback on the deprecated filter still runs during its deprecation window, and is told so.
+ */
+ public function test_the_daily_check_still_fires_the_deprecated_auto_install_filter(): void {
+ $notices = 0;
+ add_action(
+ 'deprecated_hook_run',
+ function () use ( &$notices ) {
+ ++$notices;
+ }
);
+ add_filter( 'deprecated_hook_trigger_error', '__return_false' );
+ add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
- remove_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
+ try {
+ Woocommerce_Analytics::maybe_update_proxy_speed_module();
+
+ $this->assertSame( 1, $notices );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ), 'The deprecated filter must not install anything.' );
+ } finally {
+ remove_all_actions( 'deprecated_hook_run' );
+ remove_all_filters( 'deprecated_hook_trigger_error' );
+ remove_all_filters( 'woocommerce_analytics_auto_install_proxy_speed_module' );
+ }
}
/**
- * The install path needs both flags, so that an operator cannot end up with a
- * module installed for a feature that is switched off.
+ * Proxy tracking is off here, the case where a leftover MU-plugin answering would be wrong.
*/
- public function test_maybe_add_proxy_speed_module_requires_proxy_tracking_too(): void {
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
+ public function test_the_sync_revokes_a_leftover_module_authorization(): void {
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, 'yes' );
- Woocommerce_Analytics::maybe_add_proxy_speed_module();
+ Woocommerce_Analytics::sync_proxy_tracking_state();
- // Asserted on the options the install path writes, not on a temp directory:
- // WPMU_PLUGIN_DIR is already defined by the test bootstrap, so a path
- // assertion here would pass whether or not the guard exists.
- $this->assertFalse(
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ),
- 'No module may be installed while proxy tracking is disabled.'
- );
$this->assertFalse(
get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
- 'An uninstalled module must not be authorized to serve.'
+ 'The leftover MU-plugin serves while this is yes, so the first sync after an update must drop it.'
);
-
- remove_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
}
/**
- * The module fails closed on the authorization option, so it has to be written
- * before the file can exist. Asserted on an install that fails after that point,
- * because the ordering is not observable once both have succeeded.
+ * Deactivation has to stop the module even if another plugin's copy of the package never runs `init`.
*/
- public function test_the_install_path_authorizes_before_it_writes_the_file(): void {
+ public function test_deactivation_clears_the_proxy_tracking_state(): void {
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
- add_filter( 'filesystem_method', array( $this, 'force_unusable_filesystem' ) );
+ Woocommerce_Analytics::sync_proxy_tracking_state();
- Woocommerce_Analytics::maybe_add_proxy_speed_module();
+ $this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ) );
- remove_filter( 'filesystem_method', array( $this, 'force_unusable_filesystem' ) );
+ Woocommerce_Analytics::maybe_remove_proxy_speed_module();
- $this->assertSame(
- 'yes',
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
- 'A module written before this option exists refuses every request until the next init.'
- );
- $this->assertFalse(
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ),
- 'No version may be recorded for a module that was never written.'
- );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ) );
}
/**
* The sync runs on `init` for every request on every site carrying this package,
- * and the module already treats an absent option as unauthorized. Writing `no`
+ * and the module already treats an absent option as off. Writing `no`
* anyway puts an autoloaded row on the overwhelming majority of installs that
* will never turn proxy tracking on.
*/
- public function test_a_site_that_never_authorized_the_module_gets_no_row(): void {
+ public function test_a_site_that_never_enabled_proxy_tracking_gets_no_row(): void {
Woocommerce_Analytics::sync_proxy_tracking_state();
Woocommerce_Analytics::sync_proxy_tracking_state();
$this->assertFalse(
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
- 'An absent option already means unauthorized; the row buys nothing.'
- );
- }
-
- /**
- * Revoking still has to leave a value behind, since the module reads the option
- * and an absent one is only safe while no module was ever authorized.
- */
- public function test_revoking_an_authorized_module_writes_no(): void {
- add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
- Woocommerce_Analytics::sync_proxy_tracking_state();
-
- remove_all_filters( 'woocommerce_analytics_auto_install_proxy_speed_module' );
- Woocommerce_Analytics::sync_proxy_tracking_state();
-
- $this->assertSame(
- 'no',
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
- 'A module already on disk must be told to stop, not merely left unmentioned.'
+ get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ),
+ 'An absent option already means off; the row buys nothing.'
);
}
/**
- * The MU-plugin reads what this writes, and the conditions the early returns in
+ * The speed module reads what this writes, and the conditions the early returns in
* should_track_store() test say nothing about whether the feature is on. Losing
* the registration, or moving it below one of them, leaves the module serving on
* a stale value with the whole suite green.
@@ -314,83 +283,6 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
);
}
- /**
- * Test that MU-plugin is removed when feature flag is disabled and version exists.
- */
- public function test_maybe_update_proxy_speed_module_removes_when_flag_disabled(): void {
- // Set a version to simulate existing installation.
- update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, Woocommerce_Analytics::PACKAGE_VERSION );
-
- // Feature flag is off by default — no filter needed.
- Woocommerce_Analytics::maybe_update_proxy_speed_module();
-
- // Version option should be deleted (MU-plugin removal cleans it up).
- $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ) );
- }
-
- /**
- * Test that auto-installation is disabled by default.
- */
- public function test_maybe_add_proxy_speed_module_disabled_by_default(): void {
- // Call the method without any filter (default is false).
- Woocommerce_Analytics::maybe_add_proxy_speed_module();
-
- // Version option should not be set since auto-install is disabled by default.
- $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION ) );
- }
-
- /**
- * Test that filter can enable auto-installation.
- */
- public function test_maybe_add_proxy_speed_module_respects_filter(): void {
- $filter_called = false;
- $filter_cb = function () use ( &$filter_called ) {
- $filter_called = true;
- return true;
- };
-
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', $filter_cb );
-
- // Call the method - it will proceed past the filter check but may stop at other checks
- // (e.g., filesystem init, WPMU_PLUGIN_DIR). The point is the filter is respected.
- Woocommerce_Analytics::maybe_add_proxy_speed_module();
-
- $this->assertTrue( $filter_called, 'The auto_install_proxy_speed_module filter should be checked.' );
-
- remove_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', $filter_cb );
- }
-
- /**
- * Test that maybe_add_proxy_speed_module skips when version already matches.
- */
- public function test_maybe_add_proxy_speed_module_skips_when_version_matches(): void {
- // Both flags, or the method returns at its eligibility guard and the file
- // assertion below holds whatever the version check does.
- add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
-
- // Set version to match current.
- update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, Woocommerce_Analytics::PACKAGE_VERSION );
-
- // Define WPMU_PLUGIN_DIR if not defined.
- if ( ! defined( 'WPMU_PLUGIN_DIR' ) ) {
- define( 'WPMU_PLUGIN_DIR', $this->temp_mu_plugin_dir );
- }
-
- // Call the method.
- Woocommerce_Analytics::maybe_add_proxy_speed_module();
-
- $this->assertSame(
- 'yes',
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
- 'The eligibility guard returned first, so the version check was never reached.'
- );
-
- // No file should be created since version matches.
- $mu_plugin_file = $this->temp_mu_plugin_dir . '/woocommerce-analytics-proxy-speed-module.php';
- $this->assertFileDoesNotExist( $mu_plugin_file );
- }
-
/**
* MU-plugins load whether or not the plugin carrying this package is active,
* so a module file that outlives a deactivation must not be left holding a
@@ -398,14 +290,13 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
*/
public function test_removing_the_module_drops_its_authorization(): void {
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
Woocommerce_Analytics::sync_proxy_tracking_state();
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, 'yes' );
$this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
- // Both filters stay on, so a later sync cannot be what clears the option: the
- // removal itself has to, or a module file that outlives a deactivation keeps
- // serving on the last value written.
+ // No sync runs once the plugin is deactivated, so the removal itself has to
+ // clear it, or a module file that outlives a deactivation keeps serving.
Woocommerce_Analytics::maybe_remove_proxy_speed_module();
$this->assertNotSame(
@@ -427,8 +318,8 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
*/
public function test_removal_revokes_even_when_the_filesystem_is_unavailable(): void {
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
Woocommerce_Analytics::sync_proxy_tracking_state();
+ update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, 'yes' );
update_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_OPTION, Woocommerce_Analytics::PACKAGE_VERSION );
$this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
@@ -462,18 +353,17 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
* carries the endpoint for good with no supported way back.
*/
public function test_reset_proxy_tracking_state_clears_both_options(): void {
- // Both flags, or the sync leaves the authorization option absent and the
- // second assertion below is true without anything having been cleared.
+ // Proxy tracking on, or the sync leaves the option absent and the second
+ // assertion below is true without anything having been cleared.
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
Woocommerce_Analytics::sync_proxy_tracking_state();
- $this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
+ $this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ) );
Woocommerce_Analytics::reset_proxy_tracking_state();
$this->assertFalse( get_option( Woocommerce_Analytics::PROXY_TRACKING_EVER_ENABLED_OPTION ) );
- $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
+ $this->assertFalse( get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ) );
}
/**
@@ -499,11 +389,10 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
*/
public function test_sync_proxy_tracking_state_records_the_resolved_value(): void {
add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
- add_filter( 'woocommerce_analytics_auto_install_proxy_speed_module', '__return_true' );
Woocommerce_Analytics::sync_proxy_tracking_state();
- $this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ) );
+ $this->assertSame( 'yes', get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ) );
remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
@@ -511,7 +400,7 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
$this->assertSame(
'no',
- get_option( Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION ),
+ get_option( Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION ),
'Turning the feature off must be mirrored too, or the module never stops answering.'
);
}
@@ -528,11 +417,11 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
++$writes;
return $value;
};
- add_filter( 'pre_update_option_' . Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, $spy );
+ add_filter( 'pre_update_option_' . Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, $spy );
Woocommerce_Analytics::sync_proxy_tracking_state();
- remove_filter( 'pre_update_option_' . Woocommerce_Analytics::PROXY_SPEED_MODULE_AUTHORIZED_OPTION, $spy );
+ remove_filter( 'pre_update_option_' . Woocommerce_Analytics::PROXY_TRACKING_ENABLED_OPTION, $spy );
$this->assertSame( 0, $writes );
}
@@ -576,4 +465,5 @@ class Woocommerce_Analytics_Test extends BaseTestCase {
Woocommerce_Analytics::PROXY_SPEED_MODULE_VERSION_CHECK_TRANSIENT
);
}
+
}
diff --git a/packages/php/woocommerce-analytics/tests/php/mocks/class-jetpack-autoloader-shutdown-handler.php b/packages/php/woocommerce-analytics/tests/php/mocks/class-jetpack-autoloader-shutdown-handler.php
new file mode 100644
index 00000000000..fb605049407
--- /dev/null
+++ b/packages/php/woocommerce-analytics/tests/php/mocks/class-jetpack-autoloader-shutdown-handler.php
@@ -0,0 +1,19 @@
+<?php
+/**
+ * Stand-in for the shutdown handler the Jetpack autoloader generates, under the namespace it generates.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Jetpack\Autoloader\jp_test\al6_0_4;
+
+/**
+ * Empties the autoloader's plugin cache when a request ends before `plugins_loaded`.
+ */
+class Shutdown_Handler {
+
+ /**
+ * Run on shutdown.
+ */
+ public function __invoke() {}
+}