From b9e5f15841d134f78dc7f735fa868d545df81c56 Mon Sep 17 00:00:00 2001 From: Davide Bortolami Date: Fri, 20 Nov 2026 14:18:59 +0000 Subject: [PATCH 1/3] Consent API, checkout_started, ecommerce-spec properties, PHP error filter (0.10.0) - WP Consent API: posthog-js runs cookieless with replay off until the visitor gives statistics consent, decided in the browser so cached pages work. New "Wait for cookie consent" setting, on by default. - checkout_started fires once per cart at the first checkout view; checkout_viewed is unchanged. - Ecommerce-spec properties (category, price, value, revenue, shipping, tax, discount, coupon, products) on product, cart and order events. - ErrorFilter in front of posthog-php's error handler drops notices, deprecations and the parse_str nesting warning from PostHog. - Sanitize forwarded IP headers (fixes PHPCS on main). Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +++ readme.txt | 34 ++- src/Core/Events/ErrorFilter.php | 144 +++++++++++++ src/Core/Events/Schema.php | 10 + src/Modules/PostHog/Events/Dispatcher.php | 41 +++- src/Modules/PostHog/Frontend/Enqueue.php | 108 +++++++++- src/Modules/PostHog/Listeners/WooEvents.php | 193 +++++++++++++++--- src/Modules/PostHog/ProductMeta.php | 22 ++ src/Modules/PostHog/Settings.php | 3 + src/Modules/PostHog/SettingsPanel.php | 14 ++ tagbridge.php | 4 +- tests/phpunit/Unit/Events/ErrorFilterTest.php | 109 ++++++++++ tests/phpunit/Unit/Events/SchemaTest.php | 4 +- .../Unit/Frontend/ConsentSnippetTest.php | 160 +++++++++++++++ 14 files changed, 828 insertions(+), 41 deletions(-) create mode 100644 src/Core/Events/ErrorFilter.php create mode 100644 tests/phpunit/Unit/Events/ErrorFilterTest.php create mode 100644 tests/phpunit/Unit/Frontend/ConsentSnippetTest.php diff --git a/README.md b/README.md index 690d794..6dfad70 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,29 @@ Three layers, with a hard line between them: not linger in the browser. - The full event and property list is in `readme.txt`. +## Consent + +With `client.require_consent` on (default), `Frontend/Enqueue::consent_init_call()` +prints an init wrapper that decides in the browser, so it is safe with full-page +caching: + +- No `_statistics=allow` cookie from the WP Consent API: `posthog.init` + with `persistence: 'memory'` and `disable_session_recording: true`. +- Cookie present: the normal config, so a returning visitor keeps their stored id. +- `wp_listen_for_consent_change` (and `wp_has_consent()` once the page has loaded) + switch between the two with `set_config({persistence})` and + `start/stopSessionRecording()`. + +Server-side events never set cookies. Without consent there is no posthog cookie, +so they resolve identity from the logged-in user or the WooCommerce session. + +## PHP error tracking filter + +posthog-php has no hook to drop errors, so `Core/Events/ErrorFilter` installs +itself in front of its error handler. Notices, deprecations and known-benign +warnings (`tagbridge_posthog_ignored_php_errors`) return `false`, which hands them +to PHP's normal logging; everything else goes on to PostHog. + ## Server-side request context Server-side events are stamped with the visitor's user agent (`$raw_user_agent`) diff --git a/readme.txt b/readme.txt index 9446b87..02fa819 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: analytics, posthog, tracking, events, statistics Requires at least: 5.8 Tested up to: 7.0 Requires PHP: 8.2 -Stable tag: 0.9.5 +Stable tag: 0.10.0 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -38,18 +38,25 @@ Server-side (posthog-php), each individually toggleable: * product_viewed, product_list_viewed, products_searched * product_added_to_cart, product_removed_from_cart, cart_viewed * coupon_applied, coupon_removed -* checkout_viewed, checkout_started, order_completed, product_purchased, payment_failed, order_refunded, order_cancelled +* checkout_viewed, checkout_started, order_placed, order_completed, product_purchased, payment_failed, order_refunded, order_cancelled * product_review_submitted WooCommerce events are registered only when WooCommerce is active. Order events include value and currency and resolve to the same person as the checkout session. +Event properties follow PostHog's ecommerce spec where they apply: product events carry product_id, sku, name, category, price, quantity and currency; cart_viewed, checkout_viewed, checkout_started, order_placed and order_completed carry value, revenue, shipping, tax, discount, coupon, currency and a products list; orders also carry order_id. checkout_viewed fires on every checkout page load; checkout_started fires once per cart, the first time that cart reaches checkout. + += Cookie consent = + +With "Wait for cookie consent" on (the default), posthog-js starts cookieless (in-memory only, nothing stored on the device) with session replay off. Pageviews and autocapture still run. When the visitor gives "statistics" consent through the WordPress Consent API, PostHog switches to its normal cookie storage and starts session replay if you enabled it; withdrawing consent switches back. The decision is made in the browser from the Consent API cookie, so it works with full-page caching. + +This needs a consent banner that supports the WP Consent API (for example Complianz, CookieYes or Cookiebot with the WP Consent API plugin). Without one, visitors are never asked, so PostHog stays cookieless. Server-side events (orders, payments, refunds) are sent from your server and set no cookies, so they are sent whatever the visitor chose. + = On the roadmap = Planned for future releases: * A no-flicker feature-flag block and shortcode evaluated on the server. * Optional starter dashboards created in your PostHog project. -* WordPress Consent API support. == Installation == @@ -97,11 +104,12 @@ By default PostHog uses its normal storage. Turn on "Privacy-first cookieless mo * wp_head: print the posthog-js snippet * wp_enqueue_scripts: load the WooCommerce variant-tracking script on product pages * wp_login, user_register, wp_logout: the user_logged_in / user_registered / user_logged_out events (and identity on login/register) -* template_redirect: product_viewed, product_list_viewed, products_searched, cart_viewed, checkout_viewed +* template_redirect: product_viewed, product_list_viewed, products_searched, cart_viewed, checkout_viewed, checkout_started * woocommerce_add_to_cart, woocommerce_cart_item_removed * woocommerce_applied_coupon, woocommerce_removed_coupon * comment_post: product_review_submitted -* woocommerce_checkout_order_processed, woocommerce_order_status_completed +* woocommerce_checkout_order_processed: order_placed +* woocommerce_payment_complete and the paid order statuses: order_completed, product_purchased * woocommerce_order_status_failed, woocommerce_order_refunded, woocommerce_order_status_cancelled * shutdown: flush queued server-side events * admin_menu, admin_init, admin_enqueue_scripts, admin_notices, admin_post_*: the settings screen @@ -111,6 +119,10 @@ By default PostHog uses its normal storage. Turn on "Privacy-first cookieless mo * tagbridge_posthog_js_config: the posthog-js init config array, before it is printed. * tagbridge_posthog_mask_text_selector: the session-replay text-masking CSS selector (empty disables it). * tagbridge_server_event_ip: the resolved visitor IP stamped on server-side events; return a non-empty string to override detection for an unusual proxy chain. +* tagbridge_posthog_consent_category: the WP Consent API category PostHog waits for (default "statistics"). +* tagbridge_posthog_ignored_php_errors: message fragments of PHP errors kept out of PostHog error tracking (default: the parse_str() input-nesting warning that bots trigger). +* tagbridge_posthog_ignored_php_error_levels: PHP error severities kept out of PostHog error tracking (default: notices and deprecations). +* tagbridge_purchase_order_statuses: the order statuses treated as a purchase. * tagbridge_module_manifest: the list of registered integration modules. == External services == @@ -138,10 +150,17 @@ No analytics are sent until you enter a PostHog project token and connect. You c Server-side events include the visitor's IP address (resolved from your CDN / proxy's forwarded headers) so PostHog can determine approximate location and filter bot traffic. PostHog can be configured to discard the raw IP after geolocation. -You are responsible for telling your visitors what you collect and for obtaining any consent your jurisdiction requires. Support for the WordPress Consent API is planned for a future release. +You are responsible for telling your visitors what you collect and for obtaining any consent your jurisdiction requires. Tagbridge supports the WordPress Consent API: by default PostHog stays cookieless, with session replay off, until the visitor gives statistics consent (see Cookie consent above). == Changelog == += 0.10.0 = +* Cookie consent: WordPress Consent API support. With the new "Wait for cookie consent" setting (on by default), posthog-js runs cookieless with session replay off until the visitor gives statistics consent, then switches to cookies and starts replay; withdrawing consent switches back. The check runs in the browser, so cached pages work. Tagbridge registers with the Consent API and describes its cookie. Server-side events are unchanged and set no cookies. +* New checkout_started event (PostHog ecommerce spec "Checkout Started"): fires once per cart, the first time that cart reaches checkout. checkout_viewed still fires on every checkout page load. Note that checkout_started meant "order created" before 0.9.0; that event is order_placed. +* Ecommerce-spec properties: category and price on product events, price and value on add to cart, sku/category/price on remove from cart; value, revenue, shipping, tax, discount, coupon and a products list on cart_viewed, checkout_viewed, checkout_started, order_placed and order_completed; category, price, value and coupon on product_purchased; coupon on coupon_applied. +* PHP error tracking no longer sends benign errors: notices and deprecations are dropped, and so is the parse_str() input-nesting warning that bots trigger. They still go to the PHP error log. Both lists are filterable. +* Coding standards: sanitize forwarded IP headers before validating them. + = 0.9.5 = * Person profiles now honor the "identified-only" setting on the server side. posthog-php (like every backend SDK) creates a PostHog person for each event by default and ignores the browser's person-profile mode, so anonymous server events (a posthog cookie id, a WooCommerce session id, or a per-order fallback) were minting a person each — inflating unique-person counts and costing several times more than an anonymous event. When the site is set to identified-only, those events now send $process_person_profile = false, matching what posthog-js does for the same visitor; only logged-in users create a profile. Sites set to "everyone" are unchanged. * Logout now resets the browser identity. The plugin flags a one-shot posthog.reset() on the next page load after logout, so the logged-out user's identified id no longer lingers in the browser — preventing a later visitor on a shared device from being tracked as that user, and avoiding a refused merge of two already-identified people on a subsequent different login. @@ -208,6 +227,9 @@ You are responsible for telling your visitors what you collect and for obtaining == Upgrade Notice == += 0.10.0 = +PostHog now waits for cookie consent through the WordPress Consent API: until a visitor consents it runs cookieless with session replay off. Without a Consent API banner, PostHog stays cookieless. Adds checkout_started and ecommerce-spec properties, and stops sending PHP notices to error tracking. + = 0.9.5 = Server-side events now respect your person-profile setting (no more phantom people from anonymous events when set to identified-only), and logout resets the browser identity so shared-device visitors are not tracked as the previous user. diff --git a/src/Core/Events/ErrorFilter.php b/src/Core/Events/ErrorFilter.php new file mode 100644 index 0000000..52a8898 --- /dev/null +++ b/src/Core/Events/ErrorFilter.php @@ -0,0 +1,144 @@ +ignored_levels = (int) $ignored_levels; + $this->ignored_messages = array_values( + array_filter( + array_map( 'strval', $ignored_messages ), + static function ( $fragment ) { + return '' !== $fragment; + } + ) + ); + } + + /** + * Whether an error should be kept out of PostHog. + * + * @param int $errno PHP error severity. + * @param string $message Error message. + * @return bool + */ + public function is_benign( $errno, $message ) { + if ( 0 !== ( (int) $errno & $this->ignored_levels ) ) { + return true; + } + + foreach ( $this->ignored_messages as $fragment ) { + if ( false !== strpos( (string) $message, $fragment ) ) { + return true; + } + } + + return false; + } + + /** + * Install this filter as the PHP error handler, in front of the current one. + * + * Call it right after posthog-php installed its handler, so the handler + * replaced here is PostHog's. Returns false when there was no handler to + * wrap (error capture is off), leaving PHP's handler state unchanged. + * + * @return bool Whether the filter was installed. + */ + public function install() { + $current = set_error_handler( array( $this, 'handle' ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler -- Wraps PostHog's handler on purpose. + if ( ! is_callable( $current ) ) { + restore_error_handler(); + return false; + } + + $this->next = $current; + return true; + } + + /** + * PHP error handler: drop benign errors from PostHog, pass the rest on. + * + * Returning false hands the error to PHP's standard handler, so benign + * errors are still logged exactly as they were before PostHog was installed. + * + * @param int $errno PHP error severity. + * @param string $message Error message. + * @param string $file Source file. + * @param int $line Source line. + * @return bool + */ + public function handle( $errno, $message, $file = '', $line = 0 ) { + if ( null === $this->next || $this->is_benign( $errno, $message ) ) { + return false; + } + + return (bool) call_user_func( $this->next, $errno, $message, $file, $line ); + } +} diff --git a/src/Core/Events/Schema.php b/src/Core/Events/Schema.php index 98d1749..84fa10d 100644 --- a/src/Core/Events/Schema.php +++ b/src/Core/Events/Schema.php @@ -135,6 +135,15 @@ final class Schema { */ const CHECKOUT_VIEWED = 'checkout_viewed'; + /** + * A visitor began checkout: the first checkout view for the current cart. + * Matches "Checkout Started" in PostHog's ecommerce spec. (Before 0.9.0 this + * name meant "order created"; that event is now order_placed.) + * + * @var string + */ + const CHECKOUT_STARTED = 'checkout_started'; + /** * A visitor submitted a WooCommerce product review. * @@ -178,6 +187,7 @@ public static function woo_events() { 'coupon_applied' => self::COUPON_APPLIED, 'coupon_removed' => self::COUPON_REMOVED, 'checkout_viewed' => self::CHECKOUT_VIEWED, + 'checkout_started' => self::CHECKOUT_STARTED, 'order_placed' => self::ORDER_PLACED, 'order_completed' => self::ORDER_COMPLETED, 'product_purchased' => self::PRODUCT_PURCHASED, diff --git a/src/Modules/PostHog/Events/Dispatcher.php b/src/Modules/PostHog/Events/Dispatcher.php index adf91b8..9cfe088 100644 --- a/src/Modules/PostHog/Events/Dispatcher.php +++ b/src/Modules/PostHog/Events/Dispatcher.php @@ -11,6 +11,7 @@ namespace Tagbridge\Modules\PostHog\Events; +use Tagbridge\Core\Events\ErrorFilter; use Tagbridge\Core\Events\Schema; use Tagbridge\Core\Events\ServerClient; use Tagbridge\Core\Identity\Resolver; @@ -73,12 +74,44 @@ private function client() { $this->client = $client; + if ( ! empty( $error_opts ) ) { + $this->install_error_filter(); + } + // Deliver queued events at the end of the request without blocking it. add_action( 'shutdown', array( $this, 'flush' ), 100 ); return $this->client; } + /** + * Put the benign-error filter in front of posthog-php's error handler, so PHP + * notices, deprecations and known-harmless warnings stay in the PHP error log + * instead of becoming PostHog `$exception` events. + * + * @return void + */ + private function install_error_filter() { + /** + * Filter the PHP error severities kept out of PostHog error tracking. + * + * @param int $levels Bitmask of E_* constants. Default: notices and deprecations. + */ + $levels = (int) apply_filters( 'tagbridge_posthog_ignored_php_error_levels', ErrorFilter::DEFAULT_IGNORED_LEVELS ); + + /** + * Filter the PHP error message fragments kept out of PostHog error tracking. + * + * Add a fragment of a known-harmless warning that comes from code you do + * not control. Matching is case-sensitive. + * + * @param string[] $messages Message fragments. + */ + $messages = (array) apply_filters( 'tagbridge_posthog_ignored_php_errors', ErrorFilter::DEFAULT_IGNORED_MESSAGES ); + + ( new ErrorFilter( $levels, $messages ) )->install(); + } + /** * Eagerly initialize the client. When server-side error tracking is on this * installs PostHog's PHP error handlers early, before errors can occur. @@ -227,7 +260,7 @@ private function client_ip() { // Cloudflare sets the original visitor IP here; no other front end does. if ( ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) { - $cf = trim( (string) wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); + $cf = trim( sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) ); if ( false !== filter_var( $cf, FILTER_VALIDATE_IP ) ) { return $cf; } @@ -235,14 +268,14 @@ private function client_ip() { // nginx / load balancer / CDN single client-IP header. if ( ! empty( $_SERVER['HTTP_X_REAL_IP'] ) ) { - $real = trim( (string) wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ); + $real = trim( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ) ); if ( false !== filter_var( $real, FILTER_VALIDATE_IP ) ) { return $real; } } if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { - $parts = array_map( 'trim', explode( ',', (string) wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ); + $parts = array_map( 'trim', explode( ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ); $count = count( $parts ); // Two or more hops: a load balancer appended its own IP last, so the // visitor is the second-to-last entry. A single hop is the visitor. @@ -253,7 +286,7 @@ private function client_ip() { } if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) { - $remote = trim( (string) wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); + $remote = trim( sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) ); if ( false !== filter_var( $remote, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { return $remote; } diff --git a/src/Modules/PostHog/Frontend/Enqueue.php b/src/Modules/PostHog/Frontend/Enqueue.php index 366d830..2794d9e 100644 --- a/src/Modules/PostHog/Frontend/Enqueue.php +++ b/src/Modules/PostHog/Frontend/Enqueue.php @@ -41,6 +41,45 @@ public function register() { add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_side_cart_tracking' ) ); // Flag a browser reset() on the next page load after the user logs out. add_action( 'wp_logout', array( $this, 'flag_reset_on_logout' ) ); + + // WP Consent API: declare that Tagbridge waits for consent, and describe + // the PostHog cookie for consent banners that list cookies. + add_filter( 'wp_consent_api_registered_' . plugin_basename( TAGBRIDGE_FILE ), '__return_true' ); + add_action( 'init', array( $this, 'register_cookie_info' ) ); + } + + /** + * Describe the posthog-js cookie to the WP Consent API, when it is installed. + * + * @return void + */ + public function register_cookie_info() { + if ( ! function_exists( 'wp_add_cookie_info' ) || ! Settings::is_configured() ) { + return; + } + + wp_add_cookie_info( + 'ph_' . Settings::project_api_key() . '_posthog', + 'PostHog', + self::consent_category(), + __( '1 year', 'tagbridge' ), + __( 'Remembers an anonymous visitor ID and session for site analytics and session replay.', 'tagbridge' ), + __( 'Anonymous ID, session ID', 'tagbridge' ) + ); + } + + /** + * The WP Consent API category that unlocks PostHog cookies and replay. + * + * @return string + */ + private static function consent_category() { + /** + * Filter the WP Consent API category PostHog waits for. + * + * @param string $category One of the WP Consent API categories. Default 'statistics'. + */ + return (string) apply_filters( 'tagbridge_posthog_consent_category', 'statistics' ); } /** @@ -141,8 +180,11 @@ public function print_snippet() { return; } - $key = Settings::project_api_key(); - $js = $this->loader() . "\n" . $this->init_call( $key, $this->build_config() ); + $key = Settings::project_api_key(); + $config = $this->build_config(); + $js = $this->loader() . "\n" . ( $this->consent_required() + ? $this->consent_init_call( $key, $config ) + : $this->init_call( $key, $config ) ); // After logout, tell posthog-js to reset() so the previous user's // identified id does not linger in the browser. Mutually exclusive with @@ -304,6 +346,68 @@ private function mask_text_selector() { return (string) apply_filters( 'tagbridge_posthog_mask_text_selector', $default ); } + /** + * Whether posthog-js must wait for consent before using cookies and replay. + * + * Off when the site already runs cookieless (nothing to wait for). + * + * @return bool + */ + private function consent_required() { + $client = Settings::client(); + return ! empty( $client['require_consent'] ) && empty( $client['cookieless'] ); + } + + /** + * Build a consent-aware posthog.init call as a JS string. + * + * The page HTML is cached, so the consent decision is made in the browser, + * never in PHP. Without consent posthog-js starts cookieless (persistence + * 'memory') with session replay off; pageviews and autocapture still run, + * with nothing stored on the device. With consent it starts normally. + * + * Consent is read synchronously from the WP Consent API cookie + * (_=allow) so a returning visitor who already consented + * starts with cookies straight away: switching persistence after init would + * replace their stored ID with a fresh one. Later changes arrive through the + * Consent API's wp_listen_for_consent_change event; wp_has_consent() is also + * checked once the page has loaded, since the Consent API script loads after + * this snippet and can apply region rules (opt-out regions). + * + * @param string $key Project API key. + * @param array $config Full init configuration (as with consent). + * @return string + */ + private function consent_init_call( $key, array $config ) { + /** This filter is documented in the WP Consent API (wp-consent-api). */ + $prefix = (string) apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- The WP Consent API's own hook. + + $consent = array( + 'category' => self::consent_category(), + 'cookie' => $prefix . '_' . self::consent_category(), + 'persistence' => isset( $config['persistence'] ) ? $config['persistence'] : 'localStorage+cookie', + 'replay' => empty( $config['disable_session_recording'] ), + ); + + $js = <<<'JS' +(function(k,c,o){ +function cookie(){var m=document.cookie.match(new RegExp('(?:^|; )'+o.cookie+'=([^;]*)'));return !!m&&decodeURIComponent(m[1])==='allow';} +function has(){return typeof window.wp_has_consent==='function'?!!window.wp_has_consent(o.category):cookie();} +var on=cookie(); +if(!on){c.persistence='memory';c.disable_session_recording=true;} +posthog.init(k,c); +function apply(v){if(v===on){return;}on=v; +if(v){posthog.set_config({persistence:o.persistence});if(o.replay){posthog.startSessionRecording();}} +else{posthog.stopSessionRecording();posthog.set_config({persistence:'memory'});}} +document.addEventListener('wp_listen_for_consent_change',function(e){var d=e&&e.detail||{};if(d[o.category]==='allow'){apply(true);}else if(d[o.category]==='deny'){apply(false);}}); +function check(){if(typeof window.wp_has_consent==='function'){apply(has());}} +if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',check);}else{check();} +})(%s,%s,%s); +JS; + + return sprintf( $js, wp_json_encode( $key ), wp_json_encode( $config ), wp_json_encode( $consent ) ); + } + /** * Build the posthog.init( token, config ) call as a JS string. * diff --git a/src/Modules/PostHog/Listeners/WooEvents.php b/src/Modules/PostHog/Listeners/WooEvents.php index 1ded9cd..9e99943 100644 --- a/src/Modules/PostHog/Listeners/WooEvents.php +++ b/src/Modules/PostHog/Listeners/WooEvents.php @@ -36,6 +36,13 @@ final class WooEvents { */ const ORDER_PURCHASE_SENT_META = '_tagbridge_purchase_sent'; + /** + * WooCommerce session key holding the cart hash checkout_started last fired for. + * + * @var string + */ + const SESSION_CHECKOUT_STARTED = 'tagbridge_checkout_started'; + /** * The event dispatcher. * @@ -118,6 +125,7 @@ public function on_product_view() { 'product_id' => $product->get_id(), 'name' => $product->get_name(), 'sku' => $product->get_sku(), + 'category' => ProductMeta::primary_category( $product ), 'price' => (float) $product->get_price(), 'currency' => get_woocommerce_currency(), ) + ProductMeta::collect( $product ) @@ -154,8 +162,15 @@ public function on_add_to_cart( $cart_item_key, $product_id, $quantity, $variati $props['sku'] = $product->get_sku(); } + $priced = $variation_id ? wc_get_product( $variation_id ) : $product; + if ( $priced ) { + $props['price'] = (float) $priced->get_price(); + $props['value'] = round( (float) $priced->get_price() * (int) $quantity, 2 ); + } + if ( $product ) { - $props += ProductMeta::collect( $product ); + $props['category'] = ProductMeta::primary_category( $product ); + $props += ProductMeta::collect( $product ); } $this->dispatcher->capture( 'product_added_to_cart', $this->visitor_distinct_id(), $props ); @@ -211,12 +226,7 @@ public function on_order_placed( $order_id, $posted_data, $order = null ) { $this->dispatcher->capture( 'order_placed', $distinct_id, - array( - 'order_id' => $order->get_id(), - 'value' => (float) $order->get_total(), - 'currency' => $order->get_currency(), - 'item_count' => $order->get_item_count(), - ) + $this->order_props( $order ) ); } @@ -244,12 +254,7 @@ public function on_order_paid( $order_id ) { $this->dispatcher->capture( 'order_completed', $distinct_id, - array( - 'order_id' => $order->get_id(), - 'value' => (float) $order->get_total(), - 'currency' => $order->get_currency(), - 'item_count' => $order->get_item_count(), - ) + $this->order_props( $order ) ); // One product_purchased per line item, so sales break down by SKU, variant, @@ -270,7 +275,11 @@ public function on_order_paid( $order_id ) { 'name' => $item->get_name(), 'sku' => $product ? $product->get_sku() : null, 'quantity' => (int) $item->get_quantity(), + 'category' => ProductMeta::primary_category( $parent ), + 'price' => $item->get_quantity() ? round( (float) $item->get_subtotal() / (int) $item->get_quantity(), 2 ) : null, 'line_total' => (float) $item->get_total(), + 'value' => (float) $item->get_total(), + 'coupon' => $this->order_coupon( $order ), 'currency' => $order->get_currency(), 'variant' => $is_variant ? $this->readable_variation( $product->get_variation_attributes() ) : null, ) + ProductMeta::collect( $parent ); @@ -349,11 +358,7 @@ public function on_cart_view() { $this->dispatcher->capture( 'cart_viewed', $this->visitor_distinct_id(), - array( - 'item_count' => $cart ? (int) $cart->get_cart_contents_count() : null, - 'value' => $cart ? (float) $cart->get_cart_contents_total() : null, - 'currency' => get_woocommerce_currency(), - ) + $this->cart_props( $cart ) ); } @@ -377,7 +382,10 @@ public function on_remove_from_cart( $cart_item_key, $cart = null ) { $this->visitor_distinct_id(), array( 'product_id' => $product_id, + 'sku' => $product ? $product->get_sku() : null, 'name' => $product ? $product->get_name() : '', + 'category' => ProductMeta::primary_category( $product ), + 'price' => $product ? (float) $product->get_price() : null, 'quantity' => isset( $removed['quantity'] ) ? (int) $removed['quantity'] : null, 'currency' => get_woocommerce_currency(), ) @@ -398,6 +406,7 @@ public function on_coupon_applied( $coupon_code ) { $this->visitor_distinct_id(), array( 'coupon_code' => (string) $coupon_code, + 'coupon' => (string) $coupon_code, 'cart_value' => $cart ? (float) $cart->get_cart_contents_total() : null, 'discount_total' => $cart ? (float) $cart->get_discount_total() : null, 'currency' => get_woocommerce_currency(), @@ -521,19 +530,151 @@ public function on_checkout_view() { return; } - $cart = function_exists( 'WC' ) ? WC()->cart : null; + $cart = function_exists( 'WC' ) ? WC()->cart : null; + $distinct_id = $this->visitor_distinct_id(); + $props = $this->cart_props( $cart ); - $this->dispatcher->capture( - 'checkout_viewed', - $this->visitor_distinct_id(), - array( - 'item_count' => $cart ? (int) $cart->get_cart_contents_count() : null, - 'value' => $cart ? (float) $cart->get_cart_contents_total() : null, + // Every checkout page load, reloads and step changes included. + $this->dispatcher->capture( 'checkout_viewed', $distinct_id, $props ); + + // Once per cart: the shopper began checkout (PostHog spec "Checkout Started"). + if ( $this->is_new_checkout( $cart ) ) { + $this->dispatcher->capture( 'checkout_started', $distinct_id, $props ); + } + } + + /** + * Whether this checkout view starts a new checkout: the first view for the + * current cart contents in this WooCommerce session. Reloads and returning + * to checkout with the same cart do not count again; changing the cart does. + * Marks the cart as started as a side effect. + * + * @param \WC_Cart|null $cart The cart. + * @return bool + */ + private function is_new_checkout( $cart ) { + if ( ! $cart instanceof \WC_Cart || $cart->is_empty() ) { + return false; + } + + $session = function_exists( 'WC' ) ? WC()->session : null; + if ( ! $session || ! method_exists( $session, 'get' ) ) { + // No session to remember it in: count every view rather than none. + return true; + } + + $hash = (string) $cart->get_cart_hash(); + if ( (string) $session->get( self::SESSION_CHECKOUT_STARTED ) === $hash ) { + return false; + } + + $session->set( self::SESSION_CHECKOUT_STARTED, $hash ); + return true; + } + + /** + * Cart properties shared by cart_viewed, checkout_viewed and checkout_started, + * named as in PostHog's ecommerce spec (value, coupon, shipping, tax, + * discount, products). + * + * @param \WC_Cart|null $cart The cart. + * @return array + */ + private function cart_props( $cart ) { + if ( ! $cart instanceof \WC_Cart ) { + return array( + 'item_count' => null, + 'value' => null, 'currency' => get_woocommerce_currency(), - ) + ); + } + + $products = array(); + foreach ( $cart->get_cart() as $item ) { + $product = isset( $item['data'] ) && $item['data'] instanceof \WC_Product ? $item['data'] : null; + if ( ! $product ) { + continue; + } + $parent = $product->is_type( 'variation' ) ? wc_get_product( $product->get_parent_id() ) : $product; + $products[] = array( + 'product_id' => isset( $item['product_id'] ) ? (int) $item['product_id'] : $product->get_id(), + 'variation_id' => isset( $item['variation_id'] ) ? (int) $item['variation_id'] : 0, + 'sku' => $product->get_sku(), + 'name' => $product->get_name(), + 'category' => ProductMeta::primary_category( $parent ), + 'price' => (float) $product->get_price(), + 'quantity' => isset( $item['quantity'] ) ? (int) $item['quantity'] : 1, + ); + } + + $coupons = $cart->get_applied_coupons(); + + return array( + 'item_count' => (int) $cart->get_cart_contents_count(), + 'value' => (float) $cart->get_cart_contents_total(), + 'revenue' => (float) $cart->get_total( 'edit' ), + 'shipping' => (float) $cart->get_shipping_total(), + 'tax' => (float) $cart->get_total_tax(), + 'discount' => (float) $cart->get_discount_total(), + 'coupon' => $coupons ? implode( ',', $coupons ) : null, + 'currency' => get_woocommerce_currency(), + 'products' => $products, ); } + /** + * Order properties shared by order_placed and order_completed, named as in + * PostHog's ecommerce spec. value stays the order total (gross) as before, + * so existing revenue insights keep their meaning. + * + * @param \WC_Order $order The order. + * @return array + */ + private function order_props( \WC_Order $order ) { + $products = array(); + foreach ( $order->get_items() as $item ) { + if ( ! $item instanceof \WC_Order_Item_Product ) { + continue; + } + $product = $item->get_product(); + $parent = $product && $product->is_type( 'variation' ) ? wc_get_product( $product->get_parent_id() ) : $product; + $quantity = (int) $item->get_quantity(); + $products[] = array( + 'product_id' => (int) $item->get_product_id(), + 'variation_id' => (int) $item->get_variation_id(), + 'sku' => $product ? $product->get_sku() : null, + 'name' => $item->get_name(), + 'category' => ProductMeta::primary_category( $parent ), + 'price' => $quantity ? round( (float) $item->get_subtotal() / $quantity, 2 ) : null, + 'quantity' => $quantity, + ); + } + + return array( + 'order_id' => $order->get_id(), + 'value' => (float) $order->get_total(), + 'revenue' => (float) $order->get_total(), + 'shipping' => (float) $order->get_shipping_total(), + 'tax' => (float) $order->get_total_tax(), + 'discount' => (float) $order->get_discount_total(), + 'coupon' => $this->order_coupon( $order ), + 'currency' => $order->get_currency(), + 'item_count' => $order->get_item_count(), + 'products' => $products, + ); + } + + /** + * The coupon codes used on an order, comma-separated, or null. + * + * @param \WC_Order $order The order. + * @return string|null + */ + private function order_coupon( \WC_Order $order ) { + $codes = $order->get_coupon_codes(); + return $codes ? implode( ',', $codes ) : null; + } + /** * Capture a WooCommerce product review submission. * diff --git a/src/Modules/PostHog/ProductMeta.php b/src/Modules/PostHog/ProductMeta.php index 0005cdb..9cce761 100644 --- a/src/Modules/PostHog/ProductMeta.php +++ b/src/Modules/PostHog/ProductMeta.php @@ -51,4 +51,26 @@ public static function collect( $product ) { 'attributes' => $attributes, ); } + + /** + * The product's primary category name (PostHog spec "category"), or null. + * + * Uses the first assigned product category. Pass the parent for a variation: + * variations carry no categories of their own. + * + * @param \WC_Product|null $product The product. + * @return string|null + */ + public static function primary_category( $product ) { + if ( ! $product instanceof \WC_Product ) { + return null; + } + + $names = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'names' ) ); + if ( is_wp_error( $names ) || empty( $names ) ) { + return null; + } + + return (string) reset( $names ); + } } diff --git a/src/Modules/PostHog/Settings.php b/src/Modules/PostHog/Settings.php index 30bfafb..40bf797 100644 --- a/src/Modules/PostHog/Settings.php +++ b/src/Modules/PostHog/Settings.php @@ -44,6 +44,7 @@ public static function defaults() { 'session_recording' => false, 'person_profiles' => 'identified_only', 'cookieless' => false, + 'require_consent' => true, ), 'identity' => array( 'identify_logged_in' => true, @@ -69,6 +70,7 @@ public static function defaults() { 'coupon_applied' => true, 'coupon_removed' => true, 'checkout_viewed' => true, + 'checkout_started' => true, 'order_placed' => true, 'order_completed' => true, 'product_purchased' => true, @@ -258,6 +260,7 @@ public static function sanitize( array $input ) { $client['pageviews'] = ! empty( $raw_client['pageviews'] ); $client['session_recording'] = ! empty( $raw_client['session_recording'] ); $client['cookieless'] = ! empty( $raw_client['cookieless'] ); + $client['require_consent'] = ! empty( $raw_client['require_consent'] ); $profiles = isset( $raw_client['person_profiles'] ) ? sanitize_text_field( $raw_client['person_profiles'] ) diff --git a/src/Modules/PostHog/SettingsPanel.php b/src/Modules/PostHog/SettingsPanel.php index 5d30a2b..daae071 100644 --- a/src/Modules/PostHog/SettingsPanel.php +++ b/src/Modules/PostHog/SettingsPanel.php @@ -215,6 +215,13 @@ class="tagbridge-input tagbridge-input--mono regular-text" __( 'Keep visitor state in memory; no PostHog cookie.', 'tagbridge' ), ! empty( $client['cookieless'] ) ); + $this->row( + 'client', + 'require_consent', + __( 'Wait for cookie consent', 'tagbridge' ), + __( 'Run cookieless with session replay off until the visitor gives statistics consent through the WP Consent API (your cookie banner). Cookies and replay start after consent. Server-side order events are unaffected.', 'tagbridge' ), + ! empty( $client['require_consent'] ) + ); $this->row( 'error_tracking', 'javascript', @@ -396,6 +403,13 @@ class="tagbridge-input tagbridge-input--mono regular-text" __( 'WooCommerce: the checkout page was loaded.', 'tagbridge' ), ! empty( $server['checkout_viewed'] ) ); + $this->row( + 'server_events', + 'checkout_started', + __( 'Checkout started', 'tagbridge' ), + __( 'WooCommerce: a shopper began checkout (first checkout view for the current cart; PostHog ecommerce spec).', 'tagbridge' ), + ! empty( $server['checkout_started'] ) + ); $this->row( 'server_events', 'order_placed', diff --git a/tagbridge.php b/tagbridge.php index c9dd7fd..225bbd5 100644 --- a/tagbridge.php +++ b/tagbridge.php @@ -3,7 +3,7 @@ * Plugin Name: Tagbridge – Deep Integration for PostHog * Plugin URI: https://github.com/0xdidi/tagbridge * Description: Independent PostHog integration for WordPress. Connect your project, configure tracking, and send pageviews and events to PostHog. Not affiliated with PostHog. - * Version: 0.9.5 + * Version: 0.10.0 * Requires at least: 5.8 * Requires PHP: 8.2 * Author: Great Anthony @@ -22,7 +22,7 @@ } // Single source of truth for plugin metadata. Prefixed per coding standards. -define( 'TAGBRIDGE_VERSION', '0.9.5' ); +define( 'TAGBRIDGE_VERSION', '0.10.0' ); define( 'TAGBRIDGE_FILE', __FILE__ ); define( 'TAGBRIDGE_DIR', plugin_dir_path( __FILE__ ) ); define( 'TAGBRIDGE_URL', plugin_dir_url( __FILE__ ) ); diff --git a/tests/phpunit/Unit/Events/ErrorFilterTest.php b/tests/phpunit/Unit/Events/ErrorFilterTest.php new file mode 100644 index 0000000..5be5482 --- /dev/null +++ b/tests/phpunit/Unit/Events/ErrorFilterTest.php @@ -0,0 +1,109 @@ + + */ + private $received = array(); + + /** + * How many error handlers this test pushed, to pop in tearDown. + * + * @var int + */ + private $pushed = 0; + + protected function tearDown(): void { + for ( ; $this->pushed > 0; $this->pushed-- ) { + restore_error_handler(); + } + parent::tearDown(); + } + + private function install_fake_posthog_and_filter( ErrorFilter $filter ) { + $this->received = array(); + set_error_handler( + function ( $errno, $message ) { + $this->received[] = array( $errno, $message ); + return true; + } + ); + $this->assertTrue( $filter->install() ); + $this->pushed = 2; + } + + public function test_default_drops_notices_and_deprecations() { + $filter = new ErrorFilter(); + $this->assertTrue( $filter->is_benign( E_NOTICE, 'x' ) ); + $this->assertTrue( $filter->is_benign( E_USER_NOTICE, 'x' ) ); + $this->assertTrue( $filter->is_benign( E_DEPRECATED, 'x' ) ); + $this->assertTrue( $filter->is_benign( E_USER_DEPRECATED, 'x' ) ); + } + + public function test_default_keeps_real_warnings() { + $filter = new ErrorFilter(); + $this->assertFalse( $filter->is_benign( E_WARNING, 'Undefined variable $order' ) ); + $this->assertFalse( $filter->is_benign( E_USER_ERROR, 'boom' ) ); + } + + public function test_default_drops_parse_str_nesting_warning() { + $filter = new ErrorFilter(); + $this->assertTrue( + $filter->is_benign( + E_WARNING, + 'parse_str(): Input variable nesting level exceeded 64. To increase the limit change max_input_nesting_level in php.ini.' + ) + ); + } + + public function test_custom_messages_and_levels() { + $filter = new ErrorFilter( 0, array( 'Undefined array key "flatsome-js"', '' ) ); + $this->assertTrue( $filter->is_benign( E_WARNING, 'Undefined array key "flatsome-js"' ) ); + $this->assertFalse( $filter->is_benign( E_NOTICE, 'something else' ), 'Level 0 keeps notices.' ); + $this->assertFalse( $filter->is_benign( E_WARNING, '' ), 'An empty fragment must not match everything.' ); + } + + public function test_handle_passes_real_errors_to_the_wrapped_handler() { + $this->install_fake_posthog_and_filter( new ErrorFilter() ); + + trigger_error( 'real problem', E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error + + $this->assertSame( array( array( E_USER_WARNING, 'real problem' ) ), $this->received ); + } + + public function test_handle_keeps_benign_errors_away_from_the_wrapped_handler() { + $filter = new ErrorFilter(); + $this->install_fake_posthog_and_filter( $filter ); + + // Call the handler directly: triggering a real notice would reach PHPUnit's output. + $this->assertFalse( $filter->handle( E_USER_NOTICE, 'noise' ) ); + $this->assertFalse( $filter->handle( E_WARNING, 'parse_str(): Input variable nesting level exceeded 64.' ) ); + $this->assertSame( array(), $this->received ); + } + + public function test_install_without_a_handler_leaves_state_unchanged() { + set_error_handler( null ); + $filter = new ErrorFilter(); + $this->assertFalse( $filter->install() ); + // The current handler is still null: setting one returns it. + $this->assertNull( set_error_handler( null ) ); + $this->pushed = 2; + } +} diff --git a/tests/phpunit/Unit/Events/SchemaTest.php b/tests/phpunit/Unit/Events/SchemaTest.php index 86a424e..b7ca8c4 100644 --- a/tests/phpunit/Unit/Events/SchemaTest.php +++ b/tests/phpunit/Unit/Events/SchemaTest.php @@ -21,6 +21,7 @@ public function test_event_names_are_stable() { $this->assertSame( 'product_viewed', Schema::PRODUCT_VIEWED ); $this->assertSame( 'product_added_to_cart', Schema::PRODUCT_ADDED_TO_CART ); $this->assertSame( 'checkout_viewed', Schema::CHECKOUT_VIEWED ); + $this->assertSame( 'checkout_started', Schema::CHECKOUT_STARTED ); $this->assertSame( 'order_placed', Schema::ORDER_PLACED ); $this->assertSame( 'order_completed', Schema::ORDER_COMPLETED ); $this->assertSame( 'product_purchased', Schema::PRODUCT_PURCHASED ); @@ -42,7 +43,7 @@ public function test_core_and_woo_events_partition_all_events() { array_merge( Schema::core_events(), Schema::woo_events() ), $all ); - $this->assertCount( 19, $all ); + $this->assertCount( 20, $all ); } public function test_keys_map_to_their_event_name() { @@ -55,6 +56,7 @@ public function test_is_woo_identifies_commerce_events() { $this->assertTrue( Schema::is_woo( 'order_completed' ) ); $this->assertTrue( Schema::is_woo( 'product_viewed' ) ); $this->assertTrue( Schema::is_woo( 'checkout_viewed' ) ); + $this->assertTrue( Schema::is_woo( 'checkout_started' ) ); $this->assertTrue( Schema::is_woo( 'product_review_submitted' ) ); $this->assertFalse( Schema::is_woo( 'user_logged_in' ) ); $this->assertFalse( Schema::is_woo( 'user_logged_out' ) ); diff --git a/tests/phpunit/Unit/Frontend/ConsentSnippetTest.php b/tests/phpunit/Unit/Frontend/ConsentSnippetTest.php new file mode 100644 index 0000000..389128a --- /dev/null +++ b/tests/phpunit/Unit/Frontend/ConsentSnippetTest.php @@ -0,0 +1,160 @@ +alias( 'json_encode' ); + } + + protected function tearDown(): void { + Monkey\tearDown(); + parent::tearDown(); + } + + /** + * Build the snippet for a config. + * + * @param array $config Init config. + * @return string + */ + private function snippet( array $config ) { + $method = new \ReflectionMethod( Enqueue::class, 'consent_init_call' ); + return $method->invoke( new Enqueue(), 'phc_test', $config ); + } + + /** + * Run a snippet in Node with a fake browser; return the recorded posthog calls. + * + * @param string $snippet The snippet. + * @param string $cookie document.cookie value. + * @param string $after JS run after the snippet (e.g. fire a consent event). + * @return array + */ + private function run_in_node( $snippet, $cookie, $after = '' ) { + $node = trim( (string) shell_exec( 'command -v node 2>/dev/null' ) ); + if ( '' === $node ) { + $this->markTestSkipped( 'Node is not available.' ); + } + + $harness = 'var calls=[],listeners={};' + . 'var document={cookie:' . json_encode( $cookie ) . ',readyState:"complete",' + . 'addEventListener:function(n,f){(listeners[n]=listeners[n]||[]).push(f);}};' + . 'var window={};' + . 'var posthog={};["init","set_config","startSessionRecording","stopSessionRecording"].forEach(function(m){posthog[m]=function(){calls.push([m,JSON.parse(JSON.stringify(Array.prototype.slice.call(arguments)))]);};});' + . 'function fire(d){(listeners.wp_listen_for_consent_change||[]).forEach(function(f){f({detail:d});});}' + . $snippet . "\n" . $after + . ';process.stdout.write(JSON.stringify(calls));'; + + $file = tempnam( sys_get_temp_dir(), 'tbjs' ); + file_put_contents( $file, $harness ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents + $out = shell_exec( escapeshellarg( $node ) . ' ' . escapeshellarg( $file ) . ' 2>&1' ); + unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink + + $calls = json_decode( (string) $out, true ); + $this->assertIsArray( $calls, 'Snippet failed in Node: ' . $out ); + return $calls; + } + + public function test_without_consent_starts_cookieless_with_replay_off() { + $calls = $this->run_in_node( + $this->snippet( + array( + 'api_host' => 'https://eu.i.posthog.com', + 'disable_session_recording' => false, + ) + ), + '' + ); + + $this->assertSame( 'init', $calls[0][0] ); + $this->assertSame( 'phc_test', $calls[0][1][0] ); + $this->assertSame( 'memory', $calls[0][1][1]['persistence'] ); + $this->assertTrue( $calls[0][1][1]['disable_session_recording'] ); + $this->assertCount( 1, $calls, 'Nothing else runs until consent.' ); + } + + public function test_returning_visitor_with_consent_cookie_starts_normally() { + $calls = $this->run_in_node( + $this->snippet( array( 'disable_session_recording' => false ) ), + 'foo=bar; wp_consent_statistics=allow' + ); + + $this->assertArrayNotHasKey( 'persistence', $calls[0][1][1] ); + $this->assertFalse( $calls[0][1][1]['disable_session_recording'] ); + $this->assertCount( 1, $calls ); + } + + public function test_consent_given_later_enables_cookies_and_replay() { + $calls = $this->run_in_node( + $this->snippet( array( 'disable_session_recording' => false ) ), + '', + 'fire({statistics:"allow"});fire({statistics:"allow"});' + ); + + $this->assertSame( + array( + array( 'set_config', array( array( 'persistence' => 'localStorage+cookie' ) ) ), + array( 'startSessionRecording', array() ), + ), + array_slice( $calls, 1 ), + 'Upgrades once, even if the event repeats.' + ); + } + + public function test_consent_given_later_keeps_replay_off_when_site_disabled_it() { + $calls = $this->run_in_node( + $this->snippet( array( 'disable_session_recording' => true ) ), + '', + 'fire({statistics:"allow"});' + ); + + $this->assertSame( array( 'set_config' ), array_column( array_slice( $calls, 1 ), 0 ) ); + } + + public function test_consent_withdrawn_goes_back_to_cookieless() { + $calls = $this->run_in_node( + $this->snippet( array( 'disable_session_recording' => false ) ), + 'wp_consent_statistics=allow', + 'fire({statistics:"deny"});' + ); + + $this->assertSame( + array( + array( 'stopSessionRecording', array() ), + array( 'set_config', array( array( 'persistence' => 'memory' ) ) ), + ), + array_slice( $calls, 1 ) + ); + } + + public function test_other_categories_are_ignored() { + $calls = $this->run_in_node( + $this->snippet( array( 'disable_session_recording' => false ) ), + 'wp_consent_marketing=allow', + 'fire({marketing:"allow"});' + ); + + $this->assertSame( 'memory', $calls[0][1][1]['persistence'] ); + $this->assertCount( 1, $calls ); + } +} From ff5a5b88e3940dd9af9349cb2a736a0bf6b051f5 Mon Sep 17 00:00:00 2001 From: Davide Bortolami Date: Fri, 20 Nov 2026 14:24:50 +0000 Subject: [PATCH 2/3] Read the posthog-js cookie server-side only with consent When "Wait for cookie consent" is on, Identity no longer reads the ph__posthog cookie unless the WP Consent API (or, without it, an explicit allow cookie) grants the statistics category. A cookie left over from before consent was required is not read, so server and browser events don't split one visitor. Order events are unaffected: they use the WooCommerce session id or the id saved on the order. Co-Authored-By: Claude Opus 5.5 --- src/Modules/PostHog/Consent.php | 101 ++++++++++++++++++++ src/Modules/PostHog/Frontend/Enqueue.php | 26 +---- src/Modules/PostHog/Identity.php | 7 +- tests/phpunit/Unit/Identity/ConsentTest.php | 53 ++++++++++ 4 files changed, 163 insertions(+), 24 deletions(-) create mode 100644 src/Modules/PostHog/Consent.php create mode 100644 tests/phpunit/Unit/Identity/ConsentTest.php diff --git a/src/Modules/PostHog/Consent.php b/src/Modules/PostHog/Consent.php new file mode 100644 index 0000000..c4883a1 --- /dev/null +++ b/src/Modules/PostHog/Consent.php @@ -0,0 +1,101 @@ + $client Client settings. + * @return bool + */ + public static function required( array $client ) { + return ! empty( $client['require_consent'] ) && empty( $client['cookieless'] ); + } + + /** + * Whether the server may read the posthog-js cookie for this request. + * + * @return bool + */ + public static function may_read_posthog_cookie() { + $has_consent = function_exists( 'wp_has_consent' ) ? 'wp_has_consent' : null; + + return self::cookie_read_allowed( + Settings::client(), + $_COOKIE, // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Only compared with a fixed string. + $has_consent, + self::cookie_name(), + self::category() + ); + } + + /** + * The rule behind may_read_posthog_cookie(), without WordPress state. + * + * Allowed when consent is not required. Otherwise the WP Consent API decides + * when it is active (it also applies region rules), and without it only an + * explicit "allow" in the consent cookie counts. + * + * @param array $client Client settings. + * @param array $cookies Request cookies. + * @param callable|null $has_consent wp_has_consent, when the Consent API is active. + * @param string $cookie_name The consent cookie name. + * @param string $category The consent category. + * @return bool + */ + public static function cookie_read_allowed( array $client, array $cookies, $has_consent, $cookie_name, $category ) { + if ( ! self::required( $client ) ) { + return true; + } + + if ( is_callable( $has_consent ) ) { + return (bool) call_user_func( $has_consent, $category ); + } + + return isset( $cookies[ $cookie_name ] ) && 'allow' === $cookies[ $cookie_name ]; + } +} diff --git a/src/Modules/PostHog/Frontend/Enqueue.php b/src/Modules/PostHog/Frontend/Enqueue.php index 2794d9e..e39c21b 100644 --- a/src/Modules/PostHog/Frontend/Enqueue.php +++ b/src/Modules/PostHog/Frontend/Enqueue.php @@ -11,6 +11,7 @@ namespace Tagbridge\Modules\PostHog\Frontend; +use Tagbridge\Modules\PostHog\Consent; use Tagbridge\Modules\PostHog\Identity; use Tagbridge\Modules\PostHog\ProductMeta; use Tagbridge\Modules\PostHog\Settings; @@ -61,26 +62,13 @@ public function register_cookie_info() { wp_add_cookie_info( 'ph_' . Settings::project_api_key() . '_posthog', 'PostHog', - self::consent_category(), + Consent::category(), __( '1 year', 'tagbridge' ), __( 'Remembers an anonymous visitor ID and session for site analytics and session replay.', 'tagbridge' ), __( 'Anonymous ID, session ID', 'tagbridge' ) ); } - /** - * The WP Consent API category that unlocks PostHog cookies and replay. - * - * @return string - */ - private static function consent_category() { - /** - * Filter the WP Consent API category PostHog waits for. - * - * @param string $category One of the WP Consent API categories. Default 'statistics'. - */ - return (string) apply_filters( 'tagbridge_posthog_consent_category', 'statistics' ); - } /** * Enqueue the variant-tracking script on single product pages. @@ -354,8 +342,7 @@ private function mask_text_selector() { * @return bool */ private function consent_required() { - $client = Settings::client(); - return ! empty( $client['require_consent'] ) && empty( $client['cookieless'] ); + return Consent::required( Settings::client() ); } /** @@ -379,12 +366,9 @@ private function consent_required() { * @return string */ private function consent_init_call( $key, array $config ) { - /** This filter is documented in the WP Consent API (wp-consent-api). */ - $prefix = (string) apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- The WP Consent API's own hook. - $consent = array( - 'category' => self::consent_category(), - 'cookie' => $prefix . '_' . self::consent_category(), + 'category' => Consent::category(), + 'cookie' => Consent::cookie_name(), 'persistence' => isset( $config['persistence'] ) ? $config['persistence'] : 'localStorage+cookie', 'replay' => empty( $config['disable_session_recording'] ), ); diff --git a/src/Modules/PostHog/Identity.php b/src/Modules/PostHog/Identity.php index b29af65..d570351 100644 --- a/src/Modules/PostHog/Identity.php +++ b/src/Modules/PostHog/Identity.php @@ -21,13 +21,14 @@ final class Identity { /** - * The distinct id stored by posthog-js in its cookie, if present. + * The distinct id stored by posthog-js in its cookie, if present and the + * visitor has consented to it (see Consent::may_read_posthog_cookie()). * * @return string|null */ public static function cookie_distinct_id() { $key = Settings::project_api_key(); - if ( '' === $key ) { + if ( '' === $key || ! Consent::may_read_posthog_cookie() ) { return null; } @@ -59,7 +60,7 @@ public static function cookie_distinct_id() { */ public static function cookie_session_id() { $key = Settings::project_api_key(); - if ( '' === $key ) { + if ( '' === $key || ! Consent::may_read_posthog_cookie() ) { return null; } diff --git a/tests/phpunit/Unit/Identity/ConsentTest.php b/tests/phpunit/Unit/Identity/ConsentTest.php new file mode 100644 index 0000000..dd66928 --- /dev/null +++ b/tests/phpunit/Unit/Identity/ConsentTest.php @@ -0,0 +1,53 @@ +assertTrue( $this->allowed( array( 'require_consent' => false ), array() ) ); + } + + public function test_cookieless_mode_never_waits_for_consent() { + $this->assertFalse( Consent::required( array( 'require_consent' => true, 'cookieless' => true ) ) ); // phpcs:ignore WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound + $this->assertTrue( Consent::required( array( 'require_consent' => true ) ) ); + } + + public function test_without_consent_api_needs_an_explicit_allow_cookie() { + $client = array( 'require_consent' => true ); + $this->assertFalse( $this->allowed( $client, array() ), 'No banner, no choice: a leftover posthog cookie is not read.' ); + $this->assertFalse( $this->allowed( $client, array( self::COOKIE => 'deny' ) ) ); + $this->assertFalse( $this->allowed( $client, array( 'wp_consent_marketing' => 'allow' ) ) ); + $this->assertTrue( $this->allowed( $client, array( self::COOKIE => 'allow' ) ) ); + } + + public function test_consent_api_decides_when_active() { + $client = array( 'require_consent' => true ); + $asked = array(); + $yes = function ( $category ) use ( &$asked ) { + $asked[] = $category; + return true; + }; + $no = function () { + return false; + }; + + $this->assertTrue( $this->allowed( $client, array(), $yes ), 'Opt-out regions: the Consent API may allow without a cookie.' ); + $this->assertSame( array( 'statistics' ), $asked ); + $this->assertFalse( $this->allowed( $client, array( self::COOKIE => 'allow' ), $no ) ); + } +} From 81815a3994644634fab3b99b48b2a993cc01070e Mon Sep 17 00:00:00 2001 From: Davide Bortolami Date: Fri, 20 Nov 2026 14:39:45 +0000 Subject: [PATCH 3/3] Make consent gating opt-in ("Wait for cookie consent" off by default) The shop runs without a consent banner, so 0.10.0 keeps today's behaviour by default: cookies, session replay and cookie-stitched server events for anonymous visitors. The Consent API support stays behind the setting, and Tagbridge only registers with the Consent API when the setting is on. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- readme.txt | 10 +++++----- src/Modules/PostHog/Frontend/Enqueue.php | 12 +++++++++--- src/Modules/PostHog/Settings.php | 2 +- src/Modules/PostHog/SettingsPanel.php | 2 +- tests/phpunit/Unit/Identity/ConsentTest.php | 6 ++++++ 6 files changed, 23 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 6dfad70..62508e3 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ Three layers, with a hard line between them: ## Consent -With `client.require_consent` on (default), `Frontend/Enqueue::consent_init_call()` +With `client.require_consent` on (off by default; for sites with a Consent API banner), `Frontend/Enqueue::consent_init_call()` prints an init wrapper that decides in the browser, so it is safe with full-page caching: diff --git a/readme.txt b/readme.txt index 02fa819..470b990 100644 --- a/readme.txt +++ b/readme.txt @@ -47,9 +47,9 @@ Event properties follow PostHog's ecommerce spec where they apply: product event = Cookie consent = -With "Wait for cookie consent" on (the default), posthog-js starts cookieless (in-memory only, nothing stored on the device) with session replay off. Pageviews and autocapture still run. When the visitor gives "statistics" consent through the WordPress Consent API, PostHog switches to its normal cookie storage and starts session replay if you enabled it; withdrawing consent switches back. The decision is made in the browser from the Consent API cookie, so it works with full-page caching. +"Wait for cookie consent" is off by default, so PostHog behaves as before: cookies, session replay (if enabled) and server-side events for anonymous visitors. Turn it on only once the site has a consent banner that supports the WP Consent API. With it on, posthog-js starts cookieless (in-memory only, nothing stored on the device) with session replay off. Pageviews and autocapture still run. When the visitor gives "statistics" consent through the WordPress Consent API, PostHog switches to its normal cookie storage and starts session replay if you enabled it; withdrawing consent switches back. The decision is made in the browser from the Consent API cookie, so it works with full-page caching. -This needs a consent banner that supports the WP Consent API (for example Complianz, CookieYes or Cookiebot with the WP Consent API plugin). Without one, visitors are never asked, so PostHog stays cookieless. Server-side events (orders, payments, refunds) are sent from your server and set no cookies, so they are sent whatever the visitor chose. +It needs a consent banner that supports the WP Consent API (for example Complianz, CookieYes or Cookiebot with the WP Consent API plugin). With the setting on and no such banner, visitors are never asked, so PostHog stays cookieless. Server-side events (orders, payments, refunds) are sent from your server and set no cookies, so they are sent whatever the visitor chose. = On the roadmap = @@ -150,12 +150,12 @@ No analytics are sent until you enter a PostHog project token and connect. You c Server-side events include the visitor's IP address (resolved from your CDN / proxy's forwarded headers) so PostHog can determine approximate location and filter bot traffic. PostHog can be configured to discard the raw IP after geolocation. -You are responsible for telling your visitors what you collect and for obtaining any consent your jurisdiction requires. Tagbridge supports the WordPress Consent API: by default PostHog stays cookieless, with session replay off, until the visitor gives statistics consent (see Cookie consent above). +You are responsible for telling your visitors what you collect and for obtaining any consent your jurisdiction requires. Tagbridge supports the WordPress Consent API: with "Wait for cookie consent" on (off by default), PostHog stays cookieless, with session replay off, until the visitor gives statistics consent (see Cookie consent above). == Changelog == = 0.10.0 = -* Cookie consent: WordPress Consent API support. With the new "Wait for cookie consent" setting (on by default), posthog-js runs cookieless with session replay off until the visitor gives statistics consent, then switches to cookies and starts replay; withdrawing consent switches back. The check runs in the browser, so cached pages work. Tagbridge registers with the Consent API and describes its cookie. Server-side events are unchanged and set no cookies. +* Cookie consent: WordPress Consent API support. With the new "Wait for cookie consent" setting (off by default, so existing sites keep cookies and replay), posthog-js runs cookieless with session replay off until the visitor gives statistics consent, then switches to cookies and starts replay; withdrawing consent switches back. The check runs in the browser, so cached pages work. When it is on, Tagbridge registers with the Consent API, and the server reads the PostHog cookie only with consent. Server-side events set no cookies. * New checkout_started event (PostHog ecommerce spec "Checkout Started"): fires once per cart, the first time that cart reaches checkout. checkout_viewed still fires on every checkout page load. Note that checkout_started meant "order created" before 0.9.0; that event is order_placed. * Ecommerce-spec properties: category and price on product events, price and value on add to cart, sku/category/price on remove from cart; value, revenue, shipping, tax, discount, coupon and a products list on cart_viewed, checkout_viewed, checkout_started, order_placed and order_completed; category, price, value and coupon on product_purchased; coupon on coupon_applied. * PHP error tracking no longer sends benign errors: notices and deprecations are dropped, and so is the parse_str() input-nesting warning that bots trigger. They still go to the PHP error log. Both lists are filterable. @@ -228,7 +228,7 @@ You are responsible for telling your visitors what you collect and for obtaining == Upgrade Notice == = 0.10.0 = -PostHog now waits for cookie consent through the WordPress Consent API: until a visitor consents it runs cookieless with session replay off. Without a Consent API banner, PostHog stays cookieless. Adds checkout_started and ecommerce-spec properties, and stops sending PHP notices to error tracking. +Adds optional WordPress Consent API support ("Wait for cookie consent", off by default, so tracking is unchanged on upgrade). Adds checkout_started and ecommerce-spec properties, and stops sending PHP notices to error tracking. = 0.9.5 = Server-side events now respect your person-profile setting (no more phantom people from anonymous events when set to identified-only), and logout resets the browser identity so shared-device visitors are not tracked as the previous user. diff --git a/src/Modules/PostHog/Frontend/Enqueue.php b/src/Modules/PostHog/Frontend/Enqueue.php index e39c21b..2025704 100644 --- a/src/Modules/PostHog/Frontend/Enqueue.php +++ b/src/Modules/PostHog/Frontend/Enqueue.php @@ -43,9 +43,15 @@ public function register() { // Flag a browser reset() on the next page load after the user logs out. add_action( 'wp_logout', array( $this, 'flag_reset_on_logout' ) ); - // WP Consent API: declare that Tagbridge waits for consent, and describe - // the PostHog cookie for consent banners that list cookies. - add_filter( 'wp_consent_api_registered_' . plugin_basename( TAGBRIDGE_FILE ), '__return_true' ); + // WP Consent API: declare that Tagbridge waits for consent (only when the + // "Wait for cookie consent" setting is on), and describe the PostHog + // cookie for consent banners that list cookies. + add_filter( + 'wp_consent_api_registered_' . plugin_basename( TAGBRIDGE_FILE ), + static function () { + return Consent::required( Settings::client() ); + } + ); add_action( 'init', array( $this, 'register_cookie_info' ) ); } diff --git a/src/Modules/PostHog/Settings.php b/src/Modules/PostHog/Settings.php index 40bf797..b4f242c 100644 --- a/src/Modules/PostHog/Settings.php +++ b/src/Modules/PostHog/Settings.php @@ -44,7 +44,7 @@ public static function defaults() { 'session_recording' => false, 'person_profiles' => 'identified_only', 'cookieless' => false, - 'require_consent' => true, + 'require_consent' => false, ), 'identity' => array( 'identify_logged_in' => true, diff --git a/src/Modules/PostHog/SettingsPanel.php b/src/Modules/PostHog/SettingsPanel.php index daae071..62af8d7 100644 --- a/src/Modules/PostHog/SettingsPanel.php +++ b/src/Modules/PostHog/SettingsPanel.php @@ -219,7 +219,7 @@ class="tagbridge-input tagbridge-input--mono regular-text" 'client', 'require_consent', __( 'Wait for cookie consent', 'tagbridge' ), - __( 'Run cookieless with session replay off until the visitor gives statistics consent through the WP Consent API (your cookie banner). Cookies and replay start after consent. Server-side order events are unaffected.', 'tagbridge' ), + __( 'Off by default. When on: run cookieless with session replay off until the visitor gives statistics consent through the WP Consent API, so it needs a Consent API cookie banner. Cookies and replay start after consent. Server-side order events are unaffected.', 'tagbridge' ), ! empty( $client['require_consent'] ) ); $this->row( diff --git a/tests/phpunit/Unit/Identity/ConsentTest.php b/tests/phpunit/Unit/Identity/ConsentTest.php index dd66928..74cf05b 100644 --- a/tests/phpunit/Unit/Identity/ConsentTest.php +++ b/tests/phpunit/Unit/Identity/ConsentTest.php @@ -18,6 +18,12 @@ private function allowed( array $client, array $cookies, $has_consent = null ) { return Consent::cookie_read_allowed( $client, $cookies, $has_consent, self::COOKIE, 'statistics' ); } + public function test_consent_gating_is_off_by_default() { + $defaults = \Tagbridge\Modules\PostHog\Settings::defaults(); + $this->assertFalse( $defaults['client']['require_consent'] ); + $this->assertFalse( Consent::required( $defaults['client'] ), 'Default install keeps cookies, replay and cookie-stitched server events.' ); + } + public function test_reads_cookie_when_consent_not_required() { $this->assertTrue( $this->allowed( array( 'require_consent' => false ), array() ) ); }