Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (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:

- No `<prefix>_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`)
Expand Down
34 changes: 28 additions & 6 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 =

"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.

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 =

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 ==

Expand Down Expand Up @@ -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
Expand All @@ -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 ==
Expand Down Expand Up @@ -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: 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 (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.
* 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.
Expand Down Expand Up @@ -208,6 +227,9 @@ You are responsible for telling your visitors what you collect and for obtaining

== Upgrade Notice ==

= 0.10.0 =
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.

Expand Down
144 changes: 144 additions & 0 deletions src/Core/Events/ErrorFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php
/**
* Server-side PHP error filter for PostHog error tracking.
*
* The posthog-php error handler turns every PHP notice and warning into an
* `$exception` event and has no hook to drop the harmless ones. This filter sits
* in front of that handler: errors it calls benign skip PostHog and go to PHP's
* normal handling (the error log), and everything else is passed on.
*
* Benign means either a low severity (notices, deprecations; filtered by
* default) or a message matching a known-benign pattern, such as the
* parse_str() nesting warning that bots trigger with deeply nested query strings.
*
* Platform-agnostic: native PHP only, no WordPress functions.
*
* @package Tagbridge\Core
*/

namespace Tagbridge\Core\Events;

/**
* Decides which PHP errors are worth sending to PostHog, and installs itself as
* the error handler in front of PostHog's.
*/
final class ErrorFilter {

/**
* Severities dropped by default: they never break a page.
*
* @var int
*/
const DEFAULT_IGNORED_LEVELS = E_NOTICE | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED;

/**
* Message fragments that are always benign, whatever the site.
*
* @var string[]
*/
const DEFAULT_IGNORED_MESSAGES = array(
// Bots send query strings nested deeper than max_input_nesting_level; PHP
// truncates the input and nothing else happens.
'Input variable nesting level exceeded',
);

/**
* Bitmask of severities to drop.
*
* @var int
*/
private $ignored_levels;

/**
* Case-sensitive message fragments to drop.
*
* @var string[]
*/
private $ignored_messages;

/**
* The handler errors are passed to when they are not benign (PostHog's).
*
* @var callable|null
*/
private $next = null;

/**
* Constructor.
*
* @param int $ignored_levels Bitmask of severities to drop.
* @param string[] $ignored_messages Message fragments to drop.
*/
public function __construct( $ignored_levels = self::DEFAULT_IGNORED_LEVELS, array $ignored_messages = self::DEFAULT_IGNORED_MESSAGES ) {
$this->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 );
}
}
10 changes: 10 additions & 0 deletions src/Core/Events/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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,
Expand Down
101 changes: 101 additions & 0 deletions src/Modules/PostHog/Consent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php
/**
* Consent for PostHog's browser storage, through the WordPress Consent API.
*
* The browser decides when posthog-js may use cookies (see
* Frontend\Enqueue::consent_init_call()). The server must follow the same rule
* when it reads the posthog-js cookie to stitch server-side events: a cookie
* left over from before consent was required, or from before consent was
* withdrawn, must not be read.
*
* @package Tagbridge\Modules\PostHog
*/

namespace Tagbridge\Modules\PostHog;

/**
* Consent checks shared by the browser snippet and server-side identity.
*/
final class Consent {

/**
* The WP Consent API category that unlocks PostHog cookies and replay.
*
* @return string
*/
public static function 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' );
}

/**
* The WP Consent API cookie holding the visitor's choice for the category.
*
* @return string
*/
public static function cookie_name() {
/** 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.

return $prefix . '_' . self::category();
}

/**
* Whether the browser waits for consent before using PostHog storage.
*
* Off in cookieless mode, where there is never any storage to wait for.
*
* @param array<string,mixed> $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<string,mixed> $client Client settings.
* @param array<string,mixed> $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 ];
}
}
Loading
Loading