From 2fc8b7553acf6a388a6c2a909ccfe0c6e4da6bc5 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 10:44:49 +0200 Subject: [PATCH 1/9] Add settings importer from GDPR Cookie Compliance Closes #14 Co-Authored-By: Claude Sonnet 5.5 --- includes/Admin/Settings.php | 78 +++++ includes/GDPR_Cookie_Compliance_Migration.php | 307 ++++++++++++++++++ includes/Plugin_Main.php | 3 + 3 files changed, 388 insertions(+) create mode 100644 includes/GDPR_Cookie_Compliance_Migration.php diff --git a/includes/Admin/Settings.php b/includes/Admin/Settings.php index 1c90015..b636825 100644 --- a/includes/Admin/Settings.php +++ b/includes/Admin/Settings.php @@ -11,6 +11,7 @@ namespace FrontConsent\Admin; use FrontConsent\Frontend\CookieNotice; +use FrontConsent\GDPR_Cookie_Compliance_Migration; defined( 'ABSPATH' ) || exit; @@ -56,6 +57,82 @@ public function __construct() { add_action( 'admin_menu', array( $this, 'register_menu' ) ); add_action( 'admin_init', array( $this, 'register_settings' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + add_action( 'admin_post_frcn_import_gdpr_cookie_compliance', array( $this, 'handle_gdpr_cookie_compliance_import' ) ); + } + + /** + * Run the GDPR Cookie Compliance importer from its admin-post form. + * + * @return void + */ + public function handle_gdpr_cookie_compliance_import() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do this.', 'frontconsent' ), '', array( 'response' => 403 ) ); + } + + check_admin_referer( 'frcn_import_gdpr_cookie_compliance' ); + + $report = GDPR_Cookie_Compliance_Migration::run(); + if ( null !== $report ) { + set_transient( 'frcn_gdpr_import_report_' . get_current_user_id(), $report, 5 * MINUTE_IN_SECONDS ); + } + + wp_safe_redirect( admin_url( 'options-general.php?page=' . $this->page_slug ) ); + exit; + } + + /** + * Render the GDPR Cookie Compliance import prompt, or the report of the + * import the current user just ran. + * + * @return void + */ + private function render_gdpr_import_notice() { + $report_key = 'frcn_gdpr_import_report_' . get_current_user_id(); + $report = get_transient( $report_key ); + + if ( is_array( $report ) ) { + delete_transient( $report_key ); + $labels = array( + GDPR_Cookie_Compliance_Migration::STATUS_MIGRATED => __( 'Imported', 'frontconsent' ), + GDPR_Cookie_Compliance_Migration::STATUS_EXISTING => __( 'Kept existing', 'frontconsent' ), + GDPR_Cookie_Compliance_Migration::STATUS_UNSUPPORTED => __( 'Not supported', 'frontconsent' ), + GDPR_Cookie_Compliance_Migration::STATUS_REVIEW => __( 'Needs review', 'frontconsent' ), + ); + ?> +
+

+ +
    + +
  • + + +
  • + +
+ +

+ +

+
+ +
+

+
+ + +

+
+
+ render_cache_notice(); + $this->render_gdpr_import_notice(); $tabs = array( array( diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php new file mode 100644 index 0000000..46da3cd --- /dev/null +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -0,0 +1,307 @@ + 'ga4', + 'gtm' => 'gtm', + 'gtmc2' => 'gtm', + ); + + /** + * Source integrations FrontConsent has no equivalent for, with a label. + * + * @return string[] + */ + public static function get_unsupported_integrations() { + return array( + 'gadc' => __( 'Google Ads', 'frontconsent' ), + 'fbp' => __( 'Meta Pixel', 'frontconsent' ), + 'muet' => __( 'Microsoft Advertising (UET)', 'frontconsent' ), + 'clarity' => __( 'Microsoft Clarity', 'frontconsent' ), + 'recaptcha' => __( 'Google reCAPTCHA blocker', 'frontconsent' ), + ); + } + + /** + * Whether the source plugin's settings exist on this site. + * + * @return bool + */ + public static function has_source_settings() { + return is_array( get_option( self::SOURCE_OPTION, null ) ); + } + + /** + * Run the import against the live options and save the result. + * + * @return array|null Report, or null when there is nothing to import. + */ + public static function run() { + $source = get_option( self::SOURCE_OPTION, null ); + if ( ! is_array( $source ) ) { + return null; + } + + $current = get_option( 'frontconsent_settings', array() ); + $current = is_array( $current ) ? $current : array(); + + $result = self::build( $source, $current ); + + update_option( 'frontconsent_settings', $result['settings'] ); + update_option( self::DONE_FLAG, true, false ); + + return $result['report']; + } + + /** + * Build the merged FrontConsent settings from the source option value. + * Pure function (no database access) so it can be tested with fixtures. + * + * @param array $source Value of the source plugin's option. + * @param array $current Current `frontconsent_settings` value. + * @return array{settings: array, report: array} Merged settings and a report + * of `{item, status, note}` rows. + */ + public static function build( array $source, array $current ) { + $report = array(); + + self::map_integrations( $source, $current, $report ); + self::map_banner_settings( $source, $current, $report ); + + return array( + 'settings' => $current, + 'report' => $report, + ); + } + + /** + * Map the Integrations tab (`gdin_values`) into + * `cookie_notice_tracking_integrations`. + * + * @param array $source Source option value. + * @param array $current FrontConsent settings, by reference. + * @param array $report Report rows, by reference. + * @return void + */ + private static function map_integrations( array $source, array &$current, array &$report ) { + $values = array(); + if ( isset( $source['gdin_values'] ) && is_string( $source['gdin_values'] ) ) { + $decoded = json_decode( $source['gdin_values'], true ); + $values = is_array( $decoded ) ? $decoded : array(); + } + + $integrations = Frontend\CookieNotice::get_tracking_integrations( $current, true ); + $unsupported = self::get_unsupported_integrations(); + + foreach ( $values as $slug => $value ) { + // Only the plain `{slug}` keys mark an integration as enabled; + // `{slug}_id` rows hold its tracking ID. + if ( ! is_string( $slug ) || '_id' === substr( $slug, -3 ) ) { + continue; + } + + if ( isset( $unsupported[ $slug ] ) ) { + $report[] = array( + 'item' => $unsupported[ $slug ], + 'status' => self::STATUS_UNSUPPORTED, + 'note' => __( 'FrontConsent has no equivalent integration yet. Add it manually.', 'frontconsent' ), + ); + continue; + } + + if ( ! isset( self::INTEGRATION_MAP[ $slug ] ) ) { + continue; + } + + $id = strtoupper( trim( sanitize_text_field( (string) ( $values[ $slug . '_id' ] ?? '' ) ) ) ); + $type = self::INTEGRATION_MAP[ $slug ]; + + // The source plugin accepts GA4 measurement IDs in its GTM field. + if ( 'gtm' === $type && 0 === strpos( $id, 'G-' ) ) { + $type = 'ga4'; + } + + $label = 'ga4' === $type ? 'GA4' : 'Google Tag Manager'; + $valid = 'ga4' === $type ? 1 === preg_match( '/^G-[A-Z0-9]+$/', $id ) : 1 === preg_match( '/^GTM-[A-Z0-9]+$/', $id ); + + if ( ! $valid ) { + $report[] = array( + 'item' => $label, + 'status' => self::STATUS_REVIEW, + 'note' => __( 'The tracking ID is missing or has an unexpected format, so it was not imported.', 'frontconsent' ), + ); + continue; + } + + if ( self::has_integration_type( $integrations, $type ) ) { + $report[] = array( + 'item' => $label, + 'status' => self::STATUS_EXISTING, + 'note' => __( 'FrontConsent already has this integration configured.', 'frontconsent' ), + ); + continue; + } + + $integrations[] = array( + 'type' => $type, + 'id' => $id, + ); + + $note = ''; + if ( 'gtmc2' === $slug ) { + $note = __( 'Imported as Google Tag Manager. Review your Consent Mode v2 setup.', 'frontconsent' ); + } + + $report[] = array( + 'item' => $label . ' (' . $id . ')', + 'status' => 'gtmc2' === $slug ? self::STATUS_REVIEW : self::STATUS_MIGRATED, + 'note' => $note, + ); + } + + if ( $integrations ) { + $current['cookie_notice_tracking_integrations'] = array_values( $integrations ); + } + } + + /** + * Map the banner texts, consent expiration and position, filling only + * the keys FrontConsent has not configured yet. + * + * @param array $source Source option value. + * @param array $current FrontConsent settings, by reference. + * @param array $report Report rows, by reference. + * @return void + */ + private static function map_banner_settings( array $source, array &$current, array &$report ) { + $candidates = array(); + + $text_keys = array( + 'moove_gdpr_info_bar_content' => 'cookie_notice_message', + 'moove_gdpr_infobar_accept_button_label' => 'cookie_notice_accept_label', + 'moove_gdpr_infobar_reject_button_label' => 'cookie_notice_reject_label', + ); + + foreach ( $text_keys as $source_key => $target_key ) { + if ( ! isset( $source[ $source_key ] ) || ! is_string( $source[ $source_key ] ) ) { + continue; + } + $text = trim( sanitize_textarea_field( wp_strip_all_tags( $source[ $source_key ] ) ) ); + if ( '' !== $text ) { + $candidates[ $target_key ] = $text; + } + } + + if ( isset( $source['moove_gdpr_consent_expiration'] ) ) { + $days = absint( $source['moove_gdpr_consent_expiration'] ); + if ( $days > 0 ) { + $candidates['cookie_notice_expiration_days'] = min( $days, 730 ); + } + } + + if ( isset( $source['moove_gdpr_infobar_position'] ) ) { + $candidates['cookie_notice_position'] = 'left' === $source['moove_gdpr_infobar_position'] ? 'bottom-left' : 'bottom-right'; + } + + $migrated = 0; + $existing = 0; + foreach ( $candidates as $key => $value ) { + if ( array_key_exists( $key, $current ) ) { + ++$existing; + continue; + } + $current[ $key ] = $value; + ++$migrated; + } + + if ( $migrated > 0 ) { + $report[] = array( + 'item' => __( 'Banner texts and options', 'frontconsent' ), + 'status' => self::STATUS_MIGRATED, + /* translators: %d: number of imported settings. */ + 'note' => sprintf( _n( '%d setting imported.', '%d settings imported.', $migrated, 'frontconsent' ), $migrated ), + ); + } + + if ( $existing > 0 ) { + $report[] = array( + 'item' => __( 'Banner texts and options', 'frontconsent' ), + 'status' => self::STATUS_EXISTING, + /* translators: %d: number of settings left untouched. */ + 'note' => sprintf( _n( '%d setting was already configured in FrontConsent and was kept.', '%d settings were already configured in FrontConsent and were kept.', $existing, 'frontconsent' ), $existing ), + ); + } + } + + /** + * Whether an integration list already contains a type. + * + * @param array $integrations List of `{type, id}` rows. + * @param string $type Integration type. + * @return bool + */ + private static function has_integration_type( array $integrations, $type ) { + foreach ( $integrations as $integration ) { + if ( $type === $integration['type'] ) { + return true; + } + } + + return false; + } +} diff --git a/includes/Plugin_Main.php b/includes/Plugin_Main.php index ee9c4ec..6da14c0 100644 --- a/includes/Plugin_Main.php +++ b/includes/Plugin_Main.php @@ -92,6 +92,9 @@ private function load_modules() { if ( ! class_exists( 'FrontConsent\Admin\Settings' ) ) { require_once FRCN_PLUGIN_PATH . 'includes/Admin/Settings.php'; } + if ( ! class_exists( 'FrontConsent\GDPR_Cookie_Compliance_Migration' ) ) { + require_once FRCN_PLUGIN_PATH . 'includes/GDPR_Cookie_Compliance_Migration.php'; + } new Admin\Settings(); } } From cf28326cb9d23e9fff5b6930b9e9141aa55a8d50 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 10:45:11 +0200 Subject: [PATCH 2/9] Add tests for the GDPR Cookie Compliance importer Co-Authored-By: Claude Sonnet 5.5 --- .../GDPRCookieComplianceMigrationTest.php | 202 ++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 tests/Unit/GDPRCookieComplianceMigrationTest.php diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php new file mode 100644 index 0000000..7d1b279 --- /dev/null +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -0,0 +1,202 @@ + wp_json_encode( $gdin ) ), $more ); + } + + private function statuses( array $report ) { + return wp_list_pluck( $report, 'status' ); + } + + public function test_ga4_and_gtm_are_migrated() { + $result = Importer::build( + $this->source( + array( + 'ga4' => 2, + 'ga4_id' => 'G-ABC123', + 'gtm' => 3, + 'gtm_id' => 'GTM-ABCD12', + ) + ), + array() + ); + + $this->assertSame( + array( + array( + 'type' => 'ga4', + 'id' => 'G-ABC123', + ), + array( + 'type' => 'gtm', + 'id' => 'GTM-ABCD12', + ), + ), + $result['settings']['cookie_notice_tracking_integrations'] + ); + $this->assertSame( array( 'migrated', 'migrated' ), $this->statuses( $result['report'] ) ); + } + + public function test_running_twice_does_not_duplicate_integrations() { + $source = $this->source( + array( + 'ga4' => 2, + 'ga4_id' => 'G-ABC123', + ) + ); + + $first = Importer::build( $source, array() ); + $second = Importer::build( $source, $first['settings'] ); + + $this->assertCount( 1, $second['settings']['cookie_notice_tracking_integrations'] ); + $this->assertSame( array( 'skipped_existing' ), $this->statuses( $second['report'] ) ); + } + + public function test_existing_frontconsent_integration_is_not_overwritten() { + $current = array( + 'cookie_notice_tracking_integrations' => array( + array( + 'type' => 'gtm', + 'id' => 'GTM-KEEPME1', + ), + ), + ); + + $result = Importer::build( + $this->source( + array( + 'gtm' => 2, + 'gtm_id' => 'GTM-OTHER99', + ) + ), + $current + ); + + $this->assertSame( 'GTM-KEEPME1', $result['settings']['cookie_notice_tracking_integrations'][0]['id'] ); + } + + public function test_ga4_id_in_the_gtm_field_becomes_ga4() { + $result = Importer::build( + $this->source( + array( + 'gtm' => 2, + 'gtm_id' => 'G-XYZ789', + ) + ), + array() + ); + + $this->assertSame( 'ga4', $result['settings']['cookie_notice_tracking_integrations'][0]['type'] ); + } + + public function test_consent_mode_gtm_is_migrated_but_flagged_for_review() { + $result = Importer::build( + $this->source( + array( + 'gtmc2' => 2, + 'gtmc2_id' => 'GTM-CMV2AB', + ) + ), + array() + ); + + $this->assertSame( 'gtm', $result['settings']['cookie_notice_tracking_integrations'][0]['type'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); + } + + public function test_unsupported_integrations_are_reported_not_dropped_silently() { + $result = Importer::build( + $this->source( + array( + 'fbp' => 3, + 'fbp_id' => '123456789012345', + 'gadc' => 3, + 'gadc_id' => 'AW-1', + ) + ), + array() + ); + + $this->assertArrayNotHasKey( 'cookie_notice_tracking_integrations', $result['settings'] ); + $this->assertSame( array( 'unsupported', 'unsupported' ), $this->statuses( $result['report'] ) ); + } + + public function test_invalid_id_is_flagged_and_not_imported() { + $result = Importer::build( + $this->source( + array( + 'ga4' => 2, + 'ga4_id' => 'not-an-id', + ) + ), + array() + ); + + $this->assertArrayNotHasKey( 'cookie_notice_tracking_integrations', $result['settings'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); + } + + public function test_malformed_gdin_values_is_ignored() { + $result = Importer::build( array( 'gdin_values' => '{not json' ), array() ); + + $this->assertSame( array(), $result['report'] ); + $this->assertSame( array(), $result['settings'] ); + } + + public function test_banner_settings_fill_only_missing_keys() { + $result = Importer::build( + array( + 'moove_gdpr_info_bar_content' => '

We use cookies.

', + 'moove_gdpr_infobar_accept_button_label' => 'Accept all', + 'moove_gdpr_consent_expiration' => '90', + 'moove_gdpr_infobar_position' => 'left', + ), + array( 'cookie_notice_accept_label' => 'OK' ) + ); + + $this->assertSame( 'We use cookies.', $result['settings']['cookie_notice_message'] ); + $this->assertSame( 'OK', $result['settings']['cookie_notice_accept_label'] ); + $this->assertSame( 90, $result['settings']['cookie_notice_expiration_days'] ); + $this->assertSame( 'bottom-left', $result['settings']['cookie_notice_position'] ); + } + + public function test_run_returns_null_without_source_and_never_writes_source() { + delete_option( Importer::SOURCE_OPTION ); + $this->assertNull( Importer::run() ); + + $source = $this->source( + array( + 'ga4' => 2, + 'ga4_id' => 'G-ABC123', + ) + ); + update_option( Importer::SOURCE_OPTION, $source ); + delete_option( 'frontconsent_settings' ); + + Importer::run(); + + $this->assertSame( $source, get_option( Importer::SOURCE_OPTION ) ); + $this->assertSame( 'G-ABC123', get_option( 'frontconsent_settings' )['cookie_notice_tracking_integrations'][0]['id'] ); + + delete_option( Importer::SOURCE_OPTION ); + delete_option( Importer::DONE_FLAG ); + delete_option( 'frontconsent_settings' ); + } +} From c53d7431bc4f35f3cfa827878bd6769a12a800c7 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 12:38:19 +0200 Subject: [PATCH 3/9] Address review: enable banner on import, handle GT-/AW- IDs, set box layout, docs Co-Authored-By: Claude Sonnet 5.5 --- includes/Admin/Settings.php | 2 +- includes/GDPR_Cookie_Compliance_Migration.php | 26 +++++++++++++++- readme.md | 1 + readme.txt | 4 +++ .../GDPRCookieComplianceMigrationTest.php | 31 +++++++++++++++++++ 5 files changed, 62 insertions(+), 2 deletions(-) diff --git a/includes/Admin/Settings.php b/includes/Admin/Settings.php index b636825..87da31e 100644 --- a/includes/Admin/Settings.php +++ b/includes/Admin/Settings.php @@ -114,7 +114,7 @@ private function render_gdpr_import_notice() {

-

+

__( 'FrontConsent banner', 'frontconsent' ), + 'status' => self::STATUS_MIGRATED, + 'note' => __( 'Enabled, so visitors keep seeing a consent banner.', 'frontconsent' ), + ); + } + return array( 'settings' => $current, 'report' => $report, @@ -159,7 +171,7 @@ private static function map_integrations( array $source, array &$current, array $report[] = array( 'item' => $unsupported[ $slug ], 'status' => self::STATUS_UNSUPPORTED, - 'note' => __( 'FrontConsent has no equivalent integration yet. Add it manually.', 'frontconsent' ), + 'note' => __( 'FrontConsent has no equivalent integration yet and it was not imported. Do not hard-code its script (it would run before consent); load it through Google Tag Manager with consent-aware triggers instead.', 'frontconsent' ), ); continue; } @@ -176,6 +188,16 @@ private static function map_integrations( array $source, array &$current, array $type = 'ga4'; } + // Google tag IDs added in source plugin 5.2 have no FrontConsent type. + if ( 1 === preg_match( '/^(GT|AW)-[A-Z0-9]+$/', $id ) ) { + $report[] = array( + 'item' => $id, + 'status' => self::STATUS_UNSUPPORTED, + 'note' => __( 'Google tag (GT-/AW-) IDs are not supported by FrontConsent and were not imported. Load them through Google Tag Manager with consent-aware triggers instead.', 'frontconsent' ), + ); + continue; + } + $label = 'ga4' === $type ? 'GA4' : 'Google Tag Manager'; $valid = 'ga4' === $type ? 1 === preg_match( '/^G-[A-Z0-9]+$/', $id ) : 1 === preg_match( '/^GTM-[A-Z0-9]+$/', $id ); @@ -256,6 +278,8 @@ private static function map_banner_settings( array $source, array &$current, arr if ( isset( $source['moove_gdpr_infobar_position'] ) ) { $candidates['cookie_notice_position'] = 'left' === $source['moove_gdpr_infobar_position'] ? 'bottom-left' : 'bottom-right'; + // Left/right positioning only applies to the box layout. + $candidates['cookie_notice_layout'] = 'box'; } $migrated = 0; diff --git a/readme.md b/readme.md index 00b2d69..6a1320d 100644 --- a/readme.md +++ b/readme.md @@ -7,6 +7,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli - **Cookie Notice** — configurable cookie consent banner (bar/box/popup) that gates Google Tag Manager, GA4, and supported tracking integrations (Clientify, Brevo, ChatGPT Ads) behind consent, with Google Consent Mode v2 support for compatibility with Google Site Kit and other analytics plugins. - **Acceptance stats** — aggregate accepted/rejected counter on the settings page. - **Migration from FrontBlocks** — automatically imports settings and stats from FrontBlocks Site Tools' bundled Cookie Notice module, which FrontConsent replaces. +- **Import from GDPR Cookie Compliance** — explicit "Import settings" action that maps its Integrations tab (GA4, GTM) and banner texts/expiration/position into FrontConsent without overwriting existing values; unsupported integrations (Google Ads, Meta Pixel, Microsoft UET/Clarity, reCAPTCHA) are reported, not imported. See `includes/GDPR_Cookie_Compliance_Migration.php`. - **Extensible settings tabs** — the settings page renders as a tab shell (Settings, plus a PRO upsell tab by default). A companion plugin such as FrontConsent PRO can add its own tab via the `frontconsent_settings_tabs` filter and render its panel on the `frontconsent_settings_form_tab_panels` action (fields saved through the main form) or `frontconsent_settings_tab_panels` action (a panel with its own form, e.g. a License tab). See [docs/plan.md](docs/plan.md) for the product plan (market, Free/Pro split, roadmap) and [AGENTS.md](AGENTS.md) for guidelines for AI coding agents working on this plugin. diff --git a/readme.txt b/readme.txt index bb36a33..a35bfb8 100644 --- a/readme.txt +++ b/readme.txt @@ -46,6 +46,10 @@ Activating FrontConsent copies your existing Cookie Notice settings and acceptan The free version keeps a simple aggregate accepted/rejected count. Per-visitor consent logging and cookie scanning are part of the planned Pro version. += Can I import my settings from GDPR Cookie Compliance? = + +Yes. If its settings are found, FrontConsent shows an "Import settings" button on its settings page. It imports Google Analytics 4 and Google Tag Manager IDs from the Integrations tab, plus the banner text, button labels, consent expiration and position, without overwriting anything you already configured in FrontConsent. Integrations FrontConsent has no equivalent for (Google Ads, Meta Pixel, Microsoft Advertising, Microsoft Clarity, reCAPTCHA blocker) are listed as not imported. The other plugin is never modified: deactivate it yourself after checking the result. + == External services == This plugin only connects to external services that the site owner explicitly configures — none are contacted by default. All connections below happen entirely in the visitor's own browser, after that visitor has accepted the relevant cookie category; no data is ever sent from the server. diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php index 7d1b279..0b9df78 100644 --- a/tests/Unit/GDPRCookieComplianceMigrationTest.php +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -175,6 +175,37 @@ public function test_banner_settings_fill_only_missing_keys() { $this->assertSame( 'OK', $result['settings']['cookie_notice_accept_label'] ); $this->assertSame( 90, $result['settings']['cookie_notice_expiration_days'] ); $this->assertSame( 'bottom-left', $result['settings']['cookie_notice_position'] ); + $this->assertSame( 'box', $result['settings']['cookie_notice_layout'] ); + } + + public function test_banner_is_enabled_on_import_unless_already_chosen() { + $source = $this->source( + array( + 'ga4' => 2, + 'ga4_id' => 'G-ABC123', + ) + ); + + $fresh = Importer::build( $source, array() ); + $this->assertTrue( $fresh['settings']['enable_cookie_notice'] ); + + $disabled = Importer::build( $source, array( 'enable_cookie_notice' => false ) ); + $this->assertFalse( $disabled['settings']['enable_cookie_notice'] ); + } + + public function test_google_tag_ids_are_reported_as_unsupported() { + $result = Importer::build( + $this->source( + array( + 'gtm' => 2, + 'gtm_id' => 'AW-123456789', + ) + ), + array() + ); + + $this->assertArrayNotHasKey( 'cookie_notice_tracking_integrations', $result['settings'] ); + $this->assertSame( array( 'unsupported' ), $this->statuses( $result['report'] ) ); } public function test_run_returns_null_without_source_and_never_writes_source() { From e05804591d99dd6f347551e8854adecdf2906d06 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 12:40:28 +0200 Subject: [PATCH 4/9] Enable banner on import without adding a spurious report row Co-Authored-By: Claude Sonnet 5.5 --- includes/GDPR_Cookie_Compliance_Migration.php | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php index b3b768f..f4ba7aa 100644 --- a/includes/GDPR_Cookie_Compliance_Migration.php +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -124,15 +124,11 @@ public static function build( array $source, array $current ) { self::map_banner_settings( $source, $current, $report ); // A fresh FrontConsent install has the banner disabled; enable it when - // anything was imported so removing the source plugin never leaves the - // site without a consent banner. An explicit saved choice is kept. - if ( $report && ! array_key_exists( 'enable_cookie_notice', $current ) ) { + // something was actually imported so removing the source plugin never + // leaves the site without a consent banner. An explicit saved choice + // is kept. + if ( in_array( self::STATUS_MIGRATED, wp_list_pluck( $report, 'status' ), true ) && ! array_key_exists( 'enable_cookie_notice', $current ) ) { $current['enable_cookie_notice'] = true; - $report[] = array( - 'item' => __( 'FrontConsent banner', 'frontconsent' ), - 'status' => self::STATUS_MIGRATED, - 'note' => __( 'Enabled, so visitors keep seeing a consent banner.', 'frontconsent' ), - ); } return array( From d0d24d0ec000a9596760ccc5193f74c478dd3228 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 12:50:27 +0200 Subject: [PATCH 5/9] Address review: report unknown integrations, handle top position, keep separators, enable on any import Co-Authored-By: Claude Sonnet 5.5 --- includes/GDPR_Cookie_Compliance_Migration.php | 28 +++++++++++--- .../GDPRCookieComplianceMigrationTest.php | 38 +++++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php index f4ba7aa..aa66cca 100644 --- a/includes/GDPR_Cookie_Compliance_Migration.php +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -73,6 +73,7 @@ public static function get_unsupported_integrations() { 'fbp' => __( 'Meta Pixel', 'frontconsent' ), 'muet' => __( 'Microsoft Advertising (UET)', 'frontconsent' ), 'clarity' => __( 'Microsoft Clarity', 'frontconsent' ), + 'gtm4wp' => __( 'GTM4WP (Google Tag Manager for WordPress)', 'frontconsent' ), 'recaptcha' => __( 'Google reCAPTCHA blocker', 'frontconsent' ), ); } @@ -119,6 +120,7 @@ public static function run() { */ public static function build( array $source, array $current ) { $report = array(); + $before = $current; self::map_integrations( $source, $current, $report ); self::map_banner_settings( $source, $current, $report ); @@ -127,7 +129,7 @@ public static function build( array $source, array $current ) { // something was actually imported so removing the source plugin never // leaves the site without a consent banner. An explicit saved choice // is kept. - if ( in_array( self::STATUS_MIGRATED, wp_list_pluck( $report, 'status' ), true ) && ! array_key_exists( 'enable_cookie_notice', $current ) ) { + if ( $current !== $before && ! array_key_exists( 'enable_cookie_notice', $current ) ) { $current['enable_cookie_notice'] = true; } @@ -173,6 +175,13 @@ private static function map_integrations( array $source, array &$current, array } if ( ! isset( self::INTEGRATION_MAP[ $slug ] ) ) { + // Never drop an enabled integration silently: it may still be + // injecting its script once the source plugin is deactivated. + $report[] = array( + 'item' => sanitize_key( $slug ), + 'status' => self::STATUS_UNSUPPORTED, + 'note' => __( 'Unrecognized integration, not imported. Check whether it still loads on your site after deactivating GDPR Cookie Compliance.', 'frontconsent' ), + ); continue; } @@ -259,7 +268,7 @@ private static function map_banner_settings( array $source, array &$current, arr if ( ! isset( $source[ $source_key ] ) || ! is_string( $source[ $source_key ] ) ) { continue; } - $text = trim( sanitize_textarea_field( wp_strip_all_tags( $source[ $source_key ] ) ) ); + $text = trim( sanitize_textarea_field( wp_strip_all_tags( preg_replace( '#|#i', "\n", $source[ $source_key ] ) ) ) ); if ( '' !== $text ) { $candidates[ $target_key ] = $text; } @@ -273,9 +282,18 @@ private static function map_banner_settings( array $source, array &$current, arr } if ( isset( $source['moove_gdpr_infobar_position'] ) ) { - $candidates['cookie_notice_position'] = 'left' === $source['moove_gdpr_infobar_position'] ? 'bottom-left' : 'bottom-right'; - // Left/right positioning only applies to the box layout. - $candidates['cookie_notice_layout'] = 'box'; + $position = $source['moove_gdpr_infobar_position']; + if ( in_array( $position, array( 'left', 'right' ), true ) ) { + $candidates['cookie_notice_position'] = 'left' === $position ? 'bottom-left' : 'bottom-right'; + // Left/right positioning only applies to the box layout. + $candidates['cookie_notice_layout'] = 'box'; + } else { + $report[] = array( + 'item' => __( 'Banner position', 'frontconsent' ), + 'status' => self::STATUS_REVIEW, + 'note' => __( 'FrontConsent cannot reproduce this position (only bottom-left and bottom-right boxes). Choose a layout manually.', 'frontconsent' ), + ); + } } $migrated = 0; diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php index 0b9df78..474f2ae 100644 --- a/tests/Unit/GDPRCookieComplianceMigrationTest.php +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -230,4 +230,42 @@ public function test_run_returns_null_without_source_and_never_writes_source() { delete_option( Importer::DONE_FLAG ); delete_option( 'frontconsent_settings' ); } + + public function test_unknown_enabled_integration_is_reported() { + $result = Importer::build( $this->source( array( 'gtm4wp' => 2 ) ), array() ); + + $this->assertSame( array( 'unsupported' ), $this->statuses( $result['report'] ) ); + $this->assertArrayNotHasKey( 'enable_cookie_notice', $result['settings'] ); + + $result = Importer::build( $this->source( array( 'somethingnew' => 2 ) ), array() ); + $this->assertSame( array( 'unsupported' ), $this->statuses( $result['report'] ) ); + } + + public function test_consent_mode_gtm_alone_enables_the_banner() { + $result = Importer::build( + $this->source( + array( + 'gtmc2' => 2, + 'gtmc2_id' => 'GTM-CMV2AB', + ) + ), + array() + ); + + $this->assertTrue( $result['settings']['enable_cookie_notice'] ); + } + + public function test_top_position_is_reported_and_not_imported() { + $result = Importer::build( array( 'moove_gdpr_infobar_position' => 'top' ), array() ); + + $this->assertArrayNotHasKey( 'cookie_notice_position', $result['settings'] ); + $this->assertArrayNotHasKey( 'cookie_notice_layout', $result['settings'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); + } + + public function test_block_boundaries_keep_a_separator_in_the_message() { + $result = Importer::build( array( 'moove_gdpr_info_bar_content' => '

One.

Two.

' ), array() ); + + $this->assertSame( "One.\nTwo.", $result['settings']['cookie_notice_message'] ); + } } From 3ebdd12adc8d38725730980ca84d00357027360a Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 12:59:35 +0200 Subject: [PATCH 6/9] Address review: skip disabled integrations, keep policy link, allow retry on unreadable data Co-Authored-By: Claude Sonnet 5.5 --- includes/GDPR_Cookie_Compliance_Migration.php | 52 ++++++++++++++++--- .../GDPRCookieComplianceMigrationTest.php | 46 +++++++++++++++- 2 files changed, 91 insertions(+), 7 deletions(-) diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php index aa66cca..14354c2 100644 --- a/includes/GDPR_Cookie_Compliance_Migration.php +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -104,7 +104,12 @@ public static function run() { $result = self::build( $source, $current ); update_option( 'frontconsent_settings', $result['settings'] ); - update_option( self::DONE_FLAG, true, false ); + + // Leave the import available for a retry when the source data could + // not be read, so the admin can repair it and run it again. + if ( $result['complete'] ) { + update_option( self::DONE_FLAG, true, false ); + } return $result['report']; } @@ -115,14 +120,15 @@ public static function run() { * * @param array $source Value of the source plugin's option. * @param array $current Current `frontconsent_settings` value. - * @return array{settings: array, report: array} Merged settings and a report - * of `{item, status, note}` rows. + * @return array{settings: array, report: array, complete: bool} Merged settings, + * a report of `{item, status, note}` rows, and whether + * the source data was fully readable. */ public static function build( array $source, array $current ) { $report = array(); $before = $current; - self::map_integrations( $source, $current, $report ); + $complete = self::map_integrations( $source, $current, $report ); self::map_banner_settings( $source, $current, $report ); // A fresh FrontConsent install has the banner disabled; enable it when @@ -136,6 +142,7 @@ public static function build( array $source, array $current ) { return array( 'settings' => $current, 'report' => $report, + 'complete' => $complete, ); } @@ -146,13 +153,23 @@ public static function build( array $source, array $current ) { * @param array $source Source option value. * @param array $current FrontConsent settings, by reference. * @param array $report Report rows, by reference. - * @return void + * @return bool False when the integrations data could not be decoded. */ private static function map_integrations( array $source, array &$current, array &$report ) { - $values = array(); + $values = array(); + $readable = true; if ( isset( $source['gdin_values'] ) && is_string( $source['gdin_values'] ) ) { $decoded = json_decode( $source['gdin_values'], true ); $values = is_array( $decoded ) ? $decoded : array(); + + if ( ! is_array( $decoded ) && '' !== trim( $source['gdin_values'] ) ) { + $readable = false; + $report[] = array( + 'item' => __( 'Integrations', 'frontconsent' ), + 'status' => self::STATUS_REVIEW, + 'note' => __( 'The integrations data of GDPR Cookie Compliance could not be read. Re-save its settings and run the import again.', 'frontconsent' ), + ); + } } $integrations = Frontend\CookieNotice::get_tracking_integrations( $current, true ); @@ -165,6 +182,11 @@ private static function map_integrations( array $source, array &$current, array continue; } + // A falsy selector means the integration is disabled in the source. + if ( empty( $value ) ) { + continue; + } + if ( isset( $unsupported[ $slug ] ) ) { $report[] = array( 'item' => $unsupported[ $slug ], @@ -244,6 +266,8 @@ private static function map_integrations( array $source, array &$current, array if ( $integrations ) { $current['cookie_notice_tracking_integrations'] = array_values( $integrations ); } + + return $readable; } /** @@ -268,6 +292,22 @@ private static function map_banner_settings( array $source, array &$current, arr if ( ! isset( $source[ $source_key ] ) || ! is_string( $source[ $source_key ] ) ) { continue; } + + // Anchors lose their URL when flattened to plain text: keep a + // local policy page link through the policy-page setting, and + // ask for a manual review otherwise. + if ( 'cookie_notice_message' === $target_key && 1 === preg_match( '/]*href=["\']([^"\']+)["\']/i', $source[ $source_key ], $link ) ) { + $page_id = (int) url_to_postid( esc_url_raw( $link[1] ) ); + if ( $page_id > 0 ) { + $candidates['cookie_notice_policy_page_id'] = $page_id; + } else { + $report[] = array( + 'item' => __( 'Banner message link', 'frontconsent' ), + 'status' => self::STATUS_REVIEW, + 'note' => __( 'The banner message contained a link that is not a page of this site and was removed. Set the policy page in FrontConsent if needed.', 'frontconsent' ), + ); + } + } $text = trim( sanitize_textarea_field( wp_strip_all_tags( preg_replace( '#|#i', "\n", $source[ $source_key ] ) ) ) ); if ( '' !== $text ) { $candidates[ $target_key ] = $text; diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php index 474f2ae..4222263 100644 --- a/tests/Unit/GDPRCookieComplianceMigrationTest.php +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -156,8 +156,9 @@ public function test_invalid_id_is_flagged_and_not_imported() { public function test_malformed_gdin_values_is_ignored() { $result = Importer::build( array( 'gdin_values' => '{not json' ), array() ); - $this->assertSame( array(), $result['report'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); $this->assertSame( array(), $result['settings'] ); + $this->assertFalse( $result['complete'] ); } public function test_banner_settings_fill_only_missing_keys() { @@ -268,4 +269,47 @@ public function test_block_boundaries_keep_a_separator_in_the_message() { $this->assertSame( "One.\nTwo.", $result['settings']['cookie_notice_message'] ); } + + public function test_integration_disabled_in_the_source_is_skipped() { + $result = Importer::build( + $this->source( + array( + 'ga4' => 0, + 'ga4_id' => 'G-ABC123', + ) + ), + array() + ); + + $this->assertSame( array(), $result['report'] ); + $this->assertArrayNotHasKey( 'cookie_notice_tracking_integrations', $result['settings'] ); + } + + public function test_local_policy_link_sets_the_policy_page_and_foreign_link_is_reported() { + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'publish', + ) + ); + + $result = Importer::build( array( 'moove_gdpr_info_bar_content' => '

See policy.

' ), array() ); + $this->assertSame( $page_id, $result['settings']['cookie_notice_policy_page_id'] ); + + $result = Importer::build( array( 'moove_gdpr_info_bar_content' => '

See policy.

' ), array() ); + $this->assertContains( 'needs_review', $this->statuses( $result['report'] ) ); + $this->assertArrayNotHasKey( 'cookie_notice_policy_page_id', $result['settings'] ); + } + + public function test_import_stays_available_when_source_data_is_unreadable() { + update_option( Importer::SOURCE_OPTION, array( 'gdin_values' => '{not json' ) ); + delete_option( Importer::DONE_FLAG ); + + Importer::run(); + + $this->assertFalse( get_option( Importer::DONE_FLAG ) ); + + delete_option( Importer::SOURCE_OPTION ); + delete_option( 'frontconsent_settings' ); + } } From f125cd3c0dcc9cc38e40cda92a070c879186e827 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Fri, 16 Oct 2026 13:14:37 +0200 Subject: [PATCH 7/9] Address review: handle every banner link, apply position and layout atomically Co-Authored-By: Claude Sonnet 5.5 --- includes/GDPR_Cookie_Compliance_Migration.php | 49 +++++++++++++------ .../GDPRCookieComplianceMigrationTest.php | 28 +++++++++++ 2 files changed, 62 insertions(+), 15 deletions(-) diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php index 14354c2..544d546 100644 --- a/includes/GDPR_Cookie_Compliance_Migration.php +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -293,21 +293,30 @@ private static function map_banner_settings( array $source, array &$current, arr continue; } - // Anchors lose their URL when flattened to plain text: keep a - // local policy page link through the policy-page setting, and - // ask for a manual review otherwise. - if ( 'cookie_notice_message' === $target_key && 1 === preg_match( '/]*href=["\']([^"\']+)["\']/i', $source[ $source_key ], $link ) ) { - $page_id = (int) url_to_postid( esc_url_raw( $link[1] ) ); - if ( $page_id > 0 ) { - $candidates['cookie_notice_policy_page_id'] = $page_id; - } else { + // Anchors lose their URL when flattened to plain text: keep the + // first local page link through the policy-page setting, and ask + // for a manual review for every other link. + if ( 'cookie_notice_message' === $target_key && preg_match_all( '/]*href=["\']([^"\']+)["\']/i', $source[ $source_key ], $links ) ) { + $removed = 0; + foreach ( $links[1] as $href ) { + $page_id = isset( $candidates['cookie_notice_policy_page_id'] ) ? 0 : (int) url_to_postid( esc_url_raw( $href ) ); + if ( $page_id > 0 ) { + $candidates['cookie_notice_policy_page_id'] = $page_id; + } else { + ++$removed; + } + } + + if ( $removed > 0 ) { $report[] = array( - 'item' => __( 'Banner message link', 'frontconsent' ), + 'item' => __( 'Banner message links', 'frontconsent' ), 'status' => self::STATUS_REVIEW, - 'note' => __( 'The banner message contained a link that is not a page of this site and was removed. Set the policy page in FrontConsent if needed.', 'frontconsent' ), + /* translators: %d: number of links. */ + 'note' => sprintf( _n( '%d link in the banner message was removed (only one local policy page can be kept). Review the policy page in FrontConsent.', '%d links in the banner message were removed (only one local policy page can be kept). Review the policy page in FrontConsent.', $removed, 'frontconsent' ), $removed ), ); } } + $text = trim( sanitize_textarea_field( wp_strip_all_tags( preg_replace( '#|#i', "\n", $source[ $source_key ] ) ) ) ); if ( '' !== $text ) { $candidates[ $target_key ] = $text; @@ -323,16 +332,26 @@ private static function map_banner_settings( array $source, array &$current, arr if ( isset( $source['moove_gdpr_infobar_position'] ) ) { $position = $source['moove_gdpr_infobar_position']; - if ( in_array( $position, array( 'left', 'right' ), true ) ) { - $candidates['cookie_notice_position'] = 'left' === $position ? 'bottom-left' : 'bottom-right'; - // Left/right positioning only applies to the box layout. - $candidates['cookie_notice_layout'] = 'box'; - } else { + if ( ! in_array( $position, array( 'left', 'right' ), true ) ) { $report[] = array( 'item' => __( 'Banner position', 'frontconsent' ), 'status' => self::STATUS_REVIEW, 'note' => __( 'FrontConsent cannot reproduce this position (only bottom-left and bottom-right boxes). Choose a layout manually.', 'frontconsent' ), ); + } elseif ( ( $current['cookie_notice_position'] ?? '' ) === ( 'left' === $position ? 'bottom-left' : 'bottom-right' ) && 'box' === ( $current['cookie_notice_layout'] ?? '' ) ) { + // Already imported (idempotent re-run): nothing to do. + unset( $position ); + } elseif ( array_key_exists( 'cookie_notice_position', $current ) || array_key_exists( 'cookie_notice_layout', $current ) ) { + // Position and layout only work as a pair (left/right applies + // to the box layout), so never mix them with existing values. + $report[] = array( + 'item' => __( 'Banner position', 'frontconsent' ), + 'status' => self::STATUS_REVIEW, + 'note' => __( 'FrontConsent already has a layout or position configured, so the source position was not applied.', 'frontconsent' ), + ); + } else { + $candidates['cookie_notice_position'] = 'left' === $position ? 'bottom-left' : 'bottom-right'; + $candidates['cookie_notice_layout'] = 'box'; } } diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php index 4222263..6262a20 100644 --- a/tests/Unit/GDPRCookieComplianceMigrationTest.php +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -312,4 +312,32 @@ public function test_import_stays_available_when_source_data_is_unreadable() { delete_option( Importer::SOURCE_OPTION ); delete_option( 'frontconsent_settings' ); } + + public function test_every_removed_link_is_counted_in_the_report() { + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'publish', + ) + ); + + $html = 'a b c'; + $result = Importer::build( array( 'moove_gdpr_info_bar_content' => $html ), array() ); + + $this->assertSame( $page_id, $result['settings']['cookie_notice_policy_page_id'] ); + $review = array_values( array_filter( $result['report'], static function ( $row ) { + return 'needs_review' === $row['status']; + } ) ); + $this->assertCount( 1, $review ); + $this->assertStringContainsString( '2', $review[0]['note'] ); + } + + public function test_position_is_not_mixed_with_a_partially_configured_layout() { + foreach ( array( array( 'cookie_notice_layout' => 'bar' ), array( 'cookie_notice_position' => 'bottom-right' ) ) as $current ) { + $result = Importer::build( array( 'moove_gdpr_infobar_position' => 'left' ), $current ); + + $this->assertSame( $current, $result['settings'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); + } + } } From 7dcf2fc6d35561da03e4f4a396095928ded361e7 Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Thu, 29 Oct 2026 08:49:51 +0100 Subject: [PATCH 8/9] Import the GTM4WP container as a GTM integration Co-Authored-By: Claude Sonnet 5.5 --- frontconsent.php | 4 +- includes/GDPR_Cookie_Compliance_Migration.php | 93 ++++++++++++++++++- readme.md | 2 +- readme.txt | 2 +- .../GDPRCookieComplianceMigrationTest.php | 46 ++++++++- 5 files changed, 135 insertions(+), 12 deletions(-) diff --git a/frontconsent.php b/frontconsent.php index e316256..972e280 100644 --- a/frontconsent.php +++ b/frontconsent.php @@ -3,7 +3,7 @@ * Plugin Name: FrontConsent * Plugin URI: https://wordpress.org/plugins/frontconsent/ * Description: GDPR/ePrivacy-compliant cookie consent banner for WordPress, following the AEPD guide. Configurable banner, Google Consent Mode v2, and tracking integrations that only load after consent. - * Version: 1.0.1 + * Version: 1.0.2-beta.gdpr * Author: CloseTechnology * Author URI: https://close.technology * Text Domain: frontconsent @@ -26,7 +26,7 @@ defined( 'ABSPATH' ) || die( 'No script kiddies please!' ); -define( 'FRCN_VERSION', '1.0.1' ); +define( 'FRCN_VERSION', '1.0.2-beta.gdpr' ); define( 'FRCN_PLUGIN', __FILE__ ); define( 'FRCN_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); define( 'FRCN_PLUGIN_PATH', plugin_dir_path( __FILE__ ) ); diff --git a/includes/GDPR_Cookie_Compliance_Migration.php b/includes/GDPR_Cookie_Compliance_Migration.php index 544d546..4a243d2 100644 --- a/includes/GDPR_Cookie_Compliance_Migration.php +++ b/includes/GDPR_Cookie_Compliance_Migration.php @@ -73,7 +73,6 @@ public static function get_unsupported_integrations() { 'fbp' => __( 'Meta Pixel', 'frontconsent' ), 'muet' => __( 'Microsoft Advertising (UET)', 'frontconsent' ), 'clarity' => __( 'Microsoft Clarity', 'frontconsent' ), - 'gtm4wp' => __( 'GTM4WP (Google Tag Manager for WordPress)', 'frontconsent' ), 'recaptcha' => __( 'Google reCAPTCHA blocker', 'frontconsent' ), ); } @@ -101,7 +100,8 @@ public static function run() { $current = get_option( 'frontconsent_settings', array() ); $current = is_array( $current ) ? $current : array(); - $result = self::build( $source, $current ); + $gtm4wp = get_option( 'gtm4wp-options', array() ); + $result = self::build( $source, $current, is_array( $gtm4wp ) ? $gtm4wp : array() ); update_option( 'frontconsent_settings', $result['settings'] ); @@ -120,15 +120,17 @@ public static function run() { * * @param array $source Value of the source plugin's option. * @param array $current Current `frontconsent_settings` value. + * @param array $gtm4wp Value of GTM4WP's `gtm4wp-options` option, used to + * resolve the container ID behind the `gtm4wp` integration. * @return array{settings: array, report: array, complete: bool} Merged settings, * a report of `{item, status, note}` rows, and whether * the source data was fully readable. */ - public static function build( array $source, array $current ) { + public static function build( array $source, array $current, array $gtm4wp = array() ) { $report = array(); $before = $current; - $complete = self::map_integrations( $source, $current, $report ); + $complete = self::map_integrations( $source, $current, $report, $gtm4wp ); self::map_banner_settings( $source, $current, $report ); // A fresh FrontConsent install has the banner disabled; enable it when @@ -153,9 +155,10 @@ public static function build( array $source, array $current ) { * @param array $source Source option value. * @param array $current FrontConsent settings, by reference. * @param array $report Report rows, by reference. + * @param array $gtm4wp GTM4WP options. * @return bool False when the integrations data could not be decoded. */ - private static function map_integrations( array $source, array &$current, array &$report ) { + private static function map_integrations( array $source, array &$current, array &$report, array $gtm4wp = array() ) { $values = array(); $readable = true; if ( isset( $source['gdin_values'] ) && is_string( $source['gdin_values'] ) ) { @@ -196,6 +199,11 @@ private static function map_integrations( array $source, array &$current, array continue; } + if ( 'gtm4wp' === $slug ) { + self::map_gtm4wp( $gtm4wp, $integrations, $report ); + continue; + } + if ( ! isset( self::INTEGRATION_MAP[ $slug ] ) ) { // Never drop an enabled integration silently: it may still be // injecting its script once the source plugin is deactivated. @@ -385,6 +393,81 @@ private static function map_banner_settings( array $source, array &$current, arr } } + /** + * Map the `gtm4wp` integration: the source plugin gates the container that + * GTM4WP is configured with, so the container ID is read from GTM4WP's own + * options and imported as a regular GTM integration. + * + * @param array $gtm4wp GTM4WP options. + * @param array $integrations Tracking integrations, by reference. + * @param array $report Report rows, by reference. + * @return void + */ + private static function map_gtm4wp( array $gtm4wp, array &$integrations, array &$report ) { + $label = __( 'GTM4WP (Google Tag Manager for WordPress)', 'frontconsent' ); + $ids = array_map( 'trim', explode( ',', (string) ( $gtm4wp['gtm-code'] ?? '' ) ) ); + + if ( isset( $gtm4wp['gtm-containers'] ) && is_array( $gtm4wp['gtm-containers'] ) ) { + foreach ( $gtm4wp['gtm-containers'] as $container ) { + if ( is_array( $container ) && ! empty( $container['id'] ) ) { + $ids[] = (string) $container['id']; + } + } + } + + $ids = array_values( + array_unique( + array_filter( + array_map( 'strtoupper', array_map( 'sanitize_text_field', $ids ) ), + static function ( $id ) { + return 1 === preg_match( '/^GTM-[A-Z0-9]+$/', $id ); + } + ) + ) + ); + + if ( ! $ids ) { + $report[] = array( + 'item' => $label, + 'status' => self::STATUS_REVIEW, + 'note' => __( 'No GTM container ID was found in the GTM4WP settings, so nothing was imported. Add the container ID in FrontConsent manually.', 'frontconsent' ), + ); + return; + } + + if ( self::has_integration_type( $integrations, 'gtm' ) ) { + $report[] = array( + 'item' => $label, + 'status' => self::STATUS_EXISTING, + 'note' => __( 'FrontConsent already has a Google Tag Manager container configured.', 'frontconsent' ), + ); + return; + } + + $integrations[] = array( + 'type' => 'gtm', + 'id' => $ids[0], + ); + + $placement_off = defined( 'GTM4WP_PLACEMENT_OFF' ) ? (int) GTM4WP_PLACEMENT_OFF : 3; + $placement = isset( $gtm4wp['gtm-code-placement'] ) ? (int) $gtm4wp['gtm-code-placement'] : 0; + $notes = array(); + + if ( $placement_off !== $placement ) { + $notes[] = __( 'GTM4WP still places the container itself. Set its container code placement to "Off" so FrontConsent is the only one loading it, after consent.', 'frontconsent' ); + } + + if ( count( $ids ) > 1 ) { + $notes[] = __( 'GTM4WP has several containers; only the first was imported.', 'frontconsent' ); + } + + $report[] = array( + 'item' => $label . ' (' . $ids[0] . ')', + 'status' => $notes ? self::STATUS_REVIEW : self::STATUS_MIGRATED, + 'note' => implode( ' ', $notes ), + ); + } + /** * Whether an integration list already contains a type. * diff --git a/readme.md b/readme.md index 6a1320d..1ade170 100644 --- a/readme.md +++ b/readme.md @@ -7,7 +7,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli - **Cookie Notice** — configurable cookie consent banner (bar/box/popup) that gates Google Tag Manager, GA4, and supported tracking integrations (Clientify, Brevo, ChatGPT Ads) behind consent, with Google Consent Mode v2 support for compatibility with Google Site Kit and other analytics plugins. - **Acceptance stats** — aggregate accepted/rejected counter on the settings page. - **Migration from FrontBlocks** — automatically imports settings and stats from FrontBlocks Site Tools' bundled Cookie Notice module, which FrontConsent replaces. -- **Import from GDPR Cookie Compliance** — explicit "Import settings" action that maps its Integrations tab (GA4, GTM) and banner texts/expiration/position into FrontConsent without overwriting existing values; unsupported integrations (Google Ads, Meta Pixel, Microsoft UET/Clarity, reCAPTCHA) are reported, not imported. See `includes/GDPR_Cookie_Compliance_Migration.php`. +- **Import from GDPR Cookie Compliance** — explicit "Import settings" action that maps its Integrations tab (GA4, GTM, and the container configured in GTM4WP) and banner texts/expiration/position into FrontConsent without overwriting existing values; unsupported integrations (Google Ads, Meta Pixel, Microsoft UET/Clarity, reCAPTCHA) are reported, not imported. See `includes/GDPR_Cookie_Compliance_Migration.php`. - **Extensible settings tabs** — the settings page renders as a tab shell (Settings, plus a PRO upsell tab by default). A companion plugin such as FrontConsent PRO can add its own tab via the `frontconsent_settings_tabs` filter and render its panel on the `frontconsent_settings_form_tab_panels` action (fields saved through the main form) or `frontconsent_settings_tab_panels` action (a panel with its own form, e.g. a License tab). See [docs/plan.md](docs/plan.md) for the product plan (market, Free/Pro split, roadmap) and [AGENTS.md](AGENTS.md) for guidelines for AI coding agents working on this plugin. diff --git a/readme.txt b/readme.txt index a35bfb8..27cd896 100644 --- a/readme.txt +++ b/readme.txt @@ -48,7 +48,7 @@ The free version keeps a simple aggregate accepted/rejected count. Per-visitor c = Can I import my settings from GDPR Cookie Compliance? = -Yes. If its settings are found, FrontConsent shows an "Import settings" button on its settings page. It imports Google Analytics 4 and Google Tag Manager IDs from the Integrations tab, plus the banner text, button labels, consent expiration and position, without overwriting anything you already configured in FrontConsent. Integrations FrontConsent has no equivalent for (Google Ads, Meta Pixel, Microsoft Advertising, Microsoft Clarity, reCAPTCHA blocker) are listed as not imported. The other plugin is never modified: deactivate it yourself after checking the result. +Yes. If its settings are found, FrontConsent shows an "Import settings" button on its settings page. It imports Google Analytics 4 and Google Tag Manager IDs from the Integrations tab (including the GTM4WP integration, using the container ID configured in GTM4WP), plus the banner text, button labels, consent expiration and position, without overwriting anything you already configured in FrontConsent. Integrations FrontConsent has no equivalent for (Google Ads, Meta Pixel, Microsoft Advertising, Microsoft Clarity, reCAPTCHA blocker) are listed as not imported. The other plugin is never modified: deactivate it yourself after checking the result. == External services == diff --git a/tests/Unit/GDPRCookieComplianceMigrationTest.php b/tests/Unit/GDPRCookieComplianceMigrationTest.php index 6262a20..f5174f6 100644 --- a/tests/Unit/GDPRCookieComplianceMigrationTest.php +++ b/tests/Unit/GDPRCookieComplianceMigrationTest.php @@ -233,13 +233,53 @@ public function test_run_returns_null_without_source_and_never_writes_source() { } public function test_unknown_enabled_integration_is_reported() { - $result = Importer::build( $this->source( array( 'gtm4wp' => 2 ) ), array() ); + $result = Importer::build( $this->source( array( 'somethingnew' => 2 ) ), array() ); $this->assertSame( array( 'unsupported' ), $this->statuses( $result['report'] ) ); $this->assertArrayNotHasKey( 'enable_cookie_notice', $result['settings'] ); + } - $result = Importer::build( $this->source( array( 'somethingnew' => 2 ) ), array() ); - $this->assertSame( array( 'unsupported' ), $this->statuses( $result['report'] ) ); + public function test_gtm4wp_container_is_imported_as_gtm() { + $result = Importer::build( + $this->source( array( 'gtm4wp' => 2 ) ), + array(), + array( + 'gtm-code' => 'GTM-TWKQP7Z', + 'gtm-code-placement' => 3, + ) + ); + + $this->assertSame( + array( + array( + 'type' => 'gtm', + 'id' => 'GTM-TWKQP7Z', + ), + ), + $result['settings']['cookie_notice_tracking_integrations'] + ); + $this->assertSame( array( 'migrated' ), $this->statuses( $result['report'] ) ); + } + + public function test_gtm4wp_still_placing_the_container_is_flagged_for_review() { + $result = Importer::build( + $this->source( array( 'gtm4wp' => 2 ) ), + array(), + array( + 'gtm-containers' => array( array( 'id' => 'gtm-abc123' ), array( 'id' => 'GTM-OTHER1' ) ), + 'gtm-code-placement' => 0, + ) + ); + + $this->assertSame( 'GTM-ABC123', $result['settings']['cookie_notice_tracking_integrations'][0]['id'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); + } + + public function test_gtm4wp_without_a_container_id_is_reported_and_not_imported() { + $result = Importer::build( $this->source( array( 'gtm4wp' => 2 ) ), array(), array() ); + + $this->assertArrayNotHasKey( 'cookie_notice_tracking_integrations', $result['settings'] ); + $this->assertSame( array( 'needs_review' ), $this->statuses( $result['report'] ) ); } public function test_consent_mode_gtm_alone_enables_the_banner() { From 93eea4bf8d98eada25d1b05f9d934b493576ddda Mon Sep 17 00:00:00 2001 From: davidperezgar Date: Thu, 29 Oct 2026 08:58:14 +0100 Subject: [PATCH 9/9] Gate WooCommerce order attribution until consent and suppress GTM4WP consent default Co-Authored-By: Claude Sonnet 5.5 --- .../frontconsent-cookie-notice.js | 37 ++++++++ .../frontconsent-cookie-notice.min.js | 2 +- includes/Frontend/CookieNotice.php | 93 +++++++++++++++++++ readme.md | 1 + readme.txt | 8 ++ tests/Unit/CookieNoticeGatedScriptsTest.php | 56 +++++++++++ 6 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/CookieNoticeGatedScriptsTest.php diff --git a/assets/cookie-notice/frontconsent-cookie-notice.js b/assets/cookie-notice/frontconsent-cookie-notice.js index 27549ec..6db7e55 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.js @@ -43,6 +43,40 @@ } } + function defineActivateGatedHelper() { + window.frcnCookieNoticeActivateGated = window.frcnCookieNoticeActivateGated || function (allowedCategories) { + if (allowedCategories && !allowedCategories.analytics) { + return; + } + + var run = function () { + var gated = Array.prototype.slice.call(document.querySelectorAll('script[data-frcn-consent=analytics]')).filter(function (node) { + return 'text/plain' === node.type; + }); + + var next = function () { + var inert = gated.shift(); + if (!inert) { + return; + } + var live = document.createElement('script'); + live.async = false; + live.onload = next; + live.onerror = next; + live.src = inert.src; + inert.parentNode.replaceChild(live, inert); + }; + next(); + }; + + if ('loading' === document.readyState) { + document.addEventListener('DOMContentLoaded', run); + } else { + run(); + } + }; + } + function defineInjectHelper() { window.frcnCookieNoticeInject = window.frcnCookieNoticeInject || function (gtmId, ga4Id, trackingIntegrations, allowedCategories) { var allowsCategory = function (category) { @@ -133,6 +167,8 @@ window.frcnCookieNoticePendingIntegrations.push(integration); } }); + + window.frcnCookieNoticeActivateGated(allowedCategories); }; } @@ -230,6 +266,7 @@ return; } + defineActivateGatedHelper(); defineInjectHelper(); var isStale = typeof window.frcnCookieNoticeIsConsentStale === 'function' && window.frcnCookieNoticeIsConsentStale(); diff --git a/assets/cookie-notice/frontconsent-cookie-notice.min.js b/assets/cookie-notice/frontconsent-cookie-notice.min.js index e48e341..0e84215 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.min.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.min.js @@ -1 +1 @@ -!function(){"use strict";function e(e){var n=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!n)return"";try{return decodeURIComponent(n[1])}catch(e){return""}}function n(){var e=new FormData;e.append("action","frcn_get_cookie_notice_config"),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:e}).then(function(e){return e.json()}).then(function(e){e&&e.success&&e.data&&window.frcnCookieNoticeInject&&window.frcnCookieNoticeInject(e.data.gtmId,e.data.ga4Id,e.data.trackingIntegrations,e.data.allowedCategories)}).catch(function(){})}function o(){if(!window.frcnCookieNoticeBootstrapped){window.frcnCookieNoticeInject=window.frcnCookieNoticeInject||function(e,n,o,t){var i=function(e){return!t||!!t[e]};if(e&&i("analytics")){window.dataLayer=window.dataLayer||[],window.dataLayer.push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var c=document.createElement("script");c.async=!0,c.src="https://www.googletagmanager.com/gtm.js?id="+encodeURIComponent(e),document.head.appendChild(c)}if(n&&i("analytics")){var a=document.createElement("script");a.async=!0,a.src="https://www.googletagmanager.com/gtag/js?id="+encodeURIComponent(n),document.head.appendChild(a),window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("js",new Date),window.gtag("config",n)}Array.isArray(o)||(o=[]),o.forEach(function(e){var n=e&&e.type?e.type:"",o=e&&e.id?e.id:"",t=e&&e.category?e.category:"marketing";if(o&&i(t))if("clientify_analytics_plus"===n){var c=document.createElement("script");c.defer=!0,c.src="https://analyticsplusdev.clientify.net/analytics_plus/pixel/"+encodeURIComponent(o),document.head.appendChild(c)}else if("clientify_analytics_classic"===n)!function(e,n,o,t){n[t]=n[t]||function(){(n[t].q=n[t].q||[]).push(arguments)};var i=e.createElement("script"),c=e.getElementsByTagName("script")[0];i.async=1,i.src="https://analytics.clientify.net/tracker.js",c.parentNode.insertBefore(i,c)}(document,window,0,"ana"),window.ana("setTrackerUrl","https://analytics.clientify.net"),window.ana("setTrackingCode",o),window.ana("trackPageview");else if("brevo"===n){var a=document.createElement("script");a.async=!0,a.src="https://cdn.brevo.com/js/sdk-loader.js",document.head.appendChild(a),window.Brevo=window.Brevo||[],window.Brevo.push(["init",{client_key:o}])}else if("openai_chatgpt_ads"===n){if(!window.oaiq){window.oaiq=function(){window.oaiq.q.push(arguments)},window.oaiq.q=[];var d=document.createElement("script");d.async=!0,d.src="https://bzrcdn.openai.com/sdk/oaiq.min.js",document.head.appendChild(d)}window.oaiq("init",{pixelId:o,debug:!0})}else"function"==typeof window.frcnCookieNoticeInjectIntegration?window.frcnCookieNoticeInjectIntegration(e):(window.frcnCookieNoticePendingIntegrations=window.frcnCookieNoticePendingIntegrations||[],window.frcnCookieNoticePendingIntegrations.push(e))})};var o="function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale();"accepted"!==e(frcnCookieNotice.cookieName)||o||n(),window.frcnCookieNoticeBootstrapped=!0}}"undefined"!=typeof frcnCookieNotice&&function(){window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)};var n="accepted"===e(frcnCookieNotice.cookieName)?"granted":"denied",o={ad_storage:n,ad_user_data:n,ad_personalization:n,analytics_storage:n};if("function"==typeof window.frcnCookieNoticeConsentModeState){var t=window.frcnCookieNoticeConsentModeState();t&&(o=t)}"function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale()&&(o={ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied"});window.gtag("consent","default",o)}(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",c):c();var t=!1;function i(){var n=document.getElementById("frcn-cookie-reopen");if(n){var o=e(frcnCookieNotice.cookieName);"accepted"!==o&&"rejected"!==o||(n.hidden=!1,t||(t=!0,n.addEventListener("click",function(){document.cookie=frcnCookieNotice.cookieName+"=; path="+frcnCookieNotice.cookiePath+"; max-age=0; SameSite=Lax",frcnCookieNotice.isPolicyPage&&frcnCookieNotice.homeUrl?window.location.href=frcnCookieNotice.homeUrl:window.location.reload()})))}}function c(){if("undefined"!=typeof frcnCookieNotice){var t="undefined"!=typeof frcnCookieNoticeA11y?frcnCookieNoticeA11y:{bannerOpened:"Cookie consent banner opened.",accepted:"Cookies accepted.",rejected:"Cookies rejected."};o(),i();var c=document.getElementById("frcn-cookie-notice");if(c&&!function(n){var o=e(frcnCookieNotice.cookieName);return!("function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale()||!n||"accepted"!==o&&"rejected"!==o||(n.style.display="none",0))}(c)){var a,d=c.querySelector('[data-frcn-cookie-action="accept"]'),r=c.querySelector('[data-frcn-cookie-action="reject"]'),s=c.classList.contains("frcn-cookie-notice--popup"),f=document.activeElement,u=document.getElementById("frcn-cookie-notice-announcer");a=s?150:20,window.setTimeout(function(){c.classList.remove("frcn-cookie-notice--init"),p(t.bannerOpened),s&&(document.body.classList.add("frcn-cookie-notice-lock-scroll"),d&&d.focus({preventScroll:!0}),document.addEventListener("keydown",k))},a),d&&d.addEventListener("click",function(e){e.preventDefault(),g("accepted")}),r&&r.addEventListener("click",function(e){e.preventDefault(),g("rejected")});var w=c.querySelector('[data-frcn-cookie-action="customize"]');w&&w.addEventListener("click",function(){var e;try{e=new CustomEvent("frcnCookieNoticeCustomize")}catch(n){(e=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieNoticeCustomize",!0,!0,null)}document.dispatchEvent(e)});var l=!1}}function p(e){u&&(u.textContent=e)}function m(e){var n=Array.prototype.slice.call(c.querySelectorAll('a[href], button, input, [tabindex]:not([tabindex="-1"])'));if(n.length){var o=n[0],t=n[n.length-1];e.shiftKey&&document.activeElement===o?(e.preventDefault(),t.focus()):e.shiftKey||document.activeElement!==t||(e.preventDefault(),o.focus())}}function k(e){"Tab"===e.key?m(e):"Escape"!==e.key&&"Esc"!==e.key||(e.preventDefault(),g("rejected"))}function g(e){l||(l=!0,function(e){var n=24*parseInt(frcnCookieNotice.expirationDays,10)*60*60,o="https:"===window.location.protocol?"; Secure":"";document.cookie=frcnCookieNotice.cookieName+"="+e+"; path="+frcnCookieNotice.cookiePath+"; max-age="+n+"; SameSite=Lax"+o}(e),function(e){var n="accepted"===e?"granted":"denied";window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("consent","update",{ad_storage:n,ad_user_data:n,ad_personalization:n,analytics_storage:n})}(e),p("accepted"===e?t.accepted:t.rejected),function(){c.classList.add("frcn-cookie-notice--hidden"),document.body.classList.remove("frcn-cookie-notice-lock-scroll"),document.removeEventListener("keydown",k),s&&f&&"function"==typeof f.focus&&f.focus({preventScroll:!0});window.setTimeout(function(){c.parentNode&&c.parentNode.removeChild(c)},300)}(),i(),function(e){var n;try{n=new CustomEvent("frcnCookieConsent",{detail:{consent:e}})}catch(o){(n=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieConsent",!0,!0,{consent:e})}document.dispatchEvent(n)}(e),function(e){var n=new FormData;n.append("action","frcn_get_cookie_notice_log_nonce"),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:n}).then(function(e){return e.json()}).then(function(n){if(n&&n.success&&n.data){var o=new FormData;return o.append("action","frcn_log_cookie_consent"),o.append("nonce",n.data.nonce),o.append("decision",e),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:o})}}).catch(function(){})}(e),"accepted"===e&&n())}}}(); \ No newline at end of file +!function(){"use strict";function e(e){var n=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!n)return"";try{return decodeURIComponent(n[1])}catch(e){return""}}function n(){var e=new FormData;e.append("action","frcn_get_cookie_notice_config"),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:e}).then(function(e){return e.json()}).then(function(e){e&&e.success&&e.data&&window.frcnCookieNoticeInject&&window.frcnCookieNoticeInject(e.data.gtmId,e.data.ga4Id,e.data.trackingIntegrations,e.data.allowedCategories)}).catch(function(){})}function t(){if(!window.frcnCookieNoticeBootstrapped){window.frcnCookieNoticeActivateGated=window.frcnCookieNoticeActivateGated||function(e){if(!e||e.analytics){var n=function(){var e=Array.prototype.slice.call(document.querySelectorAll("script[data-frcn-consent=analytics]")).filter(function(e){return"text/plain"===e.type}),n=function(){var t=e.shift();if(t){var o=document.createElement("script");o.async=!1,o.onload=n,o.onerror=n,o.src=t.src,t.parentNode.replaceChild(o,t)}};n()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",n):n()}},window.frcnCookieNoticeInject=window.frcnCookieNoticeInject||function(e,n,t,o){var i=function(e){return!o||!!o[e]};if(e&&i("analytics")){window.dataLayer=window.dataLayer||[],window.dataLayer.push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var c=document.createElement("script");c.async=!0,c.src="https://www.googletagmanager.com/gtm.js?id="+encodeURIComponent(e),document.head.appendChild(c)}if(n&&i("analytics")){var a=document.createElement("script");a.async=!0,a.src="https://www.googletagmanager.com/gtag/js?id="+encodeURIComponent(n),document.head.appendChild(a),window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("js",new Date),window.gtag("config",n)}Array.isArray(t)||(t=[]),t.forEach(function(e){var n=e&&e.type?e.type:"",t=e&&e.id?e.id:"",o=e&&e.category?e.category:"marketing";if(t&&i(o))if("clientify_analytics_plus"===n){var c=document.createElement("script");c.defer=!0,c.src="https://analyticsplusdev.clientify.net/analytics_plus/pixel/"+encodeURIComponent(t),document.head.appendChild(c)}else if("clientify_analytics_classic"===n)!function(e,n,t,o){n[o]=n[o]||function(){(n[o].q=n[o].q||[]).push(arguments)};var i=e.createElement("script"),c=e.getElementsByTagName("script")[0];i.async=1,i.src="https://analytics.clientify.net/tracker.js",c.parentNode.insertBefore(i,c)}(document,window,0,"ana"),window.ana("setTrackerUrl","https://analytics.clientify.net"),window.ana("setTrackingCode",t),window.ana("trackPageview");else if("brevo"===n){var a=document.createElement("script");a.async=!0,a.src="https://cdn.brevo.com/js/sdk-loader.js",document.head.appendChild(a),window.Brevo=window.Brevo||[],window.Brevo.push(["init",{client_key:t}])}else if("openai_chatgpt_ads"===n){if(!window.oaiq){window.oaiq=function(){window.oaiq.q.push(arguments)},window.oaiq.q=[];var r=document.createElement("script");r.async=!0,r.src="https://bzrcdn.openai.com/sdk/oaiq.min.js",document.head.appendChild(r)}window.oaiq("init",{pixelId:t,debug:!0})}else"function"==typeof window.frcnCookieNoticeInjectIntegration?window.frcnCookieNoticeInjectIntegration(e):(window.frcnCookieNoticePendingIntegrations=window.frcnCookieNoticePendingIntegrations||[],window.frcnCookieNoticePendingIntegrations.push(e))}),window.frcnCookieNoticeActivateGated(o)};var t="function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale();"accepted"!==e(frcnCookieNotice.cookieName)||t||n(),window.frcnCookieNoticeBootstrapped=!0}}"undefined"!=typeof frcnCookieNotice&&function(){window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)};var n="accepted"===e(frcnCookieNotice.cookieName)?"granted":"denied",t={ad_storage:n,ad_user_data:n,ad_personalization:n,analytics_storage:n};if("function"==typeof window.frcnCookieNoticeConsentModeState){var o=window.frcnCookieNoticeConsentModeState();o&&(t=o)}"function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale()&&(t={ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied"});window.gtag("consent","default",t)}(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",c):c();var o=!1;function i(){var n=document.getElementById("frcn-cookie-reopen");if(n){var t=e(frcnCookieNotice.cookieName);"accepted"!==t&&"rejected"!==t||(n.hidden=!1,o||(o=!0,n.addEventListener("click",function(){document.cookie=frcnCookieNotice.cookieName+"=; path="+frcnCookieNotice.cookiePath+"; max-age=0; SameSite=Lax",frcnCookieNotice.isPolicyPage&&frcnCookieNotice.homeUrl?window.location.href=frcnCookieNotice.homeUrl:window.location.reload()})))}}function c(){if("undefined"!=typeof frcnCookieNotice){var o="undefined"!=typeof frcnCookieNoticeA11y?frcnCookieNoticeA11y:{bannerOpened:"Cookie consent banner opened.",accepted:"Cookies accepted.",rejected:"Cookies rejected."};t(),i();var c=document.getElementById("frcn-cookie-notice");if(c&&!function(n){var t=e(frcnCookieNotice.cookieName);return!("function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale()||!n||"accepted"!==t&&"rejected"!==t||(n.style.display="none",0))}(c)){var a,r=c.querySelector('[data-frcn-cookie-action="accept"]'),d=c.querySelector('[data-frcn-cookie-action="reject"]'),s=c.classList.contains("frcn-cookie-notice--popup"),f=document.activeElement,u=document.getElementById("frcn-cookie-notice-announcer");a=s?150:20,window.setTimeout(function(){c.classList.remove("frcn-cookie-notice--init"),p(o.bannerOpened),s&&(document.body.classList.add("frcn-cookie-notice-lock-scroll"),r&&r.focus({preventScroll:!0}),document.addEventListener("keydown",k))},a),r&&r.addEventListener("click",function(e){e.preventDefault(),y("accepted")}),d&&d.addEventListener("click",function(e){e.preventDefault(),y("rejected")});var w=c.querySelector('[data-frcn-cookie-action="customize"]');w&&w.addEventListener("click",function(){var e;try{e=new CustomEvent("frcnCookieNoticeCustomize")}catch(n){(e=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieNoticeCustomize",!0,!0,null)}document.dispatchEvent(e)});var l=!1}}function p(e){u&&(u.textContent=e)}function m(e){var n=Array.prototype.slice.call(c.querySelectorAll('a[href], button, input, [tabindex]:not([tabindex="-1"])'));if(n.length){var t=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===t?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),t.focus())}}function k(e){"Tab"===e.key?m(e):"Escape"!==e.key&&"Esc"!==e.key||(e.preventDefault(),y("rejected"))}function y(e){l||(l=!0,function(e){var n=24*parseInt(frcnCookieNotice.expirationDays,10)*60*60,t="https:"===window.location.protocol?"; Secure":"";document.cookie=frcnCookieNotice.cookieName+"="+e+"; path="+frcnCookieNotice.cookiePath+"; max-age="+n+"; SameSite=Lax"+t}(e),function(e){var n="accepted"===e?"granted":"denied";window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("consent","update",{ad_storage:n,ad_user_data:n,ad_personalization:n,analytics_storage:n})}(e),p("accepted"===e?o.accepted:o.rejected),function(){c.classList.add("frcn-cookie-notice--hidden"),document.body.classList.remove("frcn-cookie-notice-lock-scroll"),document.removeEventListener("keydown",k),s&&f&&"function"==typeof f.focus&&f.focus({preventScroll:!0});window.setTimeout(function(){c.parentNode&&c.parentNode.removeChild(c)},300)}(),i(),function(e){var n;try{n=new CustomEvent("frcnCookieConsent",{detail:{consent:e}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieConsent",!0,!0,{consent:e})}document.dispatchEvent(n)}(e),function(e){var n=new FormData;n.append("action","frcn_get_cookie_notice_log_nonce"),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:n}).then(function(e){return e.json()}).then(function(n){if(n&&n.success&&n.data){var t=new FormData;return t.append("action","frcn_log_cookie_consent"),t.append("nonce",n.data.nonce),t.append("decision",e),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:t})}}).catch(function(){})}(e),"accepted"===e&&n())}}}(); \ No newline at end of file diff --git a/includes/Frontend/CookieNotice.php b/includes/Frontend/CookieNotice.php index e34b019..1734f46 100644 --- a/includes/Frontend/CookieNotice.php +++ b/includes/Frontend/CookieNotice.php @@ -81,6 +81,8 @@ public function __construct() { add_action( 'wp_head', array( $this, 'render_consent_bootstrap_script' ), 2 ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'wp_footer', array( $this, 'render_banner' ) ); + add_filter( 'script_loader_tag', array( $this, 'gate_analytics_scripts' ), 10, 2 ); + add_filter( 'gtm4wp_consent_mode_default_enabled', array( $this, 'filter_gtm4wp_consent_default' ) ); } // The endpoints must stay available for logged-out and logged-in visitors alike. @@ -99,6 +101,63 @@ public function __construct() { add_action( 'admin_post_nopriv_frcn_log_cookie_decision', array( $this, 'log_consent_form_callback' ) ); } + /** + * Script handles that set analytics/attribution cookies on their own and + * must therefore wait for consent. WooCommerce's order attribution + * (sourcebuster) writes its `sbjs_*` cookies on every first page view. + * + * @return string[] + */ + public static function get_gated_script_handles() { + /** + * Filters the script handles held back until the visitor accepts. + * + * Return an empty array to stop FrontConsent from gating any script. + * + * @param string[] $handles Registered script handles. + */ + $handles = apply_filters( 'frcn_cookie_notice_gated_script_handles', array( 'sourcebuster-js', 'wc-order-attribution' ) ); + + return is_array( $handles ) ? array_map( 'strval', $handles ) : array(); + } + + /** + * Turn a gated script's tag into an inert one. The tag is always printed, + * identically for every visitor (cache-neutral, like the rest of the + * banner); JS runs it once consent is accepted. + * + * @param string $tag Script tag HTML. + * @param string $handle Script handle. + * @return string + */ + public function gate_analytics_scripts( $tag, $handle ) { + if ( ! in_array( $handle, self::get_gated_script_handles(), true ) ) { + return $tag; + } + + $tag = preg_replace( '/\stype=(["\'])[^"\']*\1/i', '', (string) $tag ); + + return preg_replace( '/^cookie_notice = new CookieNotice(); + } + + public function test_order_attribution_scripts_are_made_inert() { + $tag = "\n"; + + $gated = $this->cookie_notice->gate_analytics_scripts( $tag, 'sourcebuster-js' ); + + $this->assertStringStartsWith( '\n"; + + $this->assertSame( $tag, $this->cookie_notice->gate_analytics_scripts( $tag, 'app-js' ) ); + } + + public function test_gated_handles_can_be_emptied_by_filter() { + add_filter( 'frcn_cookie_notice_gated_script_handles', '__return_empty_array' ); + + $tag = ""; + $this->assertSame( $tag, $this->cookie_notice->gate_analytics_scripts( $tag, 'sourcebuster-js' ) ); + + remove_filter( 'frcn_cookie_notice_gated_script_handles', '__return_empty_array' ); + } + + public function test_gtm4wp_consent_default_is_suppressed_unless_opted_out() { + $this->assertFalse( $this->cookie_notice->filter_gtm4wp_consent_default( true ) ); + + add_filter( 'frcn_cookie_notice_suppress_gtm4wp_consent_default', '__return_false' ); + $this->assertTrue( $this->cookie_notice->filter_gtm4wp_consent_default( true ) ); + remove_filter( 'frcn_cookie_notice_suppress_gtm4wp_consent_default', '__return_false' ); + } +}