From 55cf80f81435dfb4bc1b60c09a2c2316168418a8 Mon Sep 17 00:00:00 2001 From: castellon Date: Tue, 29 Sep 2026 08:50:55 +0200 Subject: [PATCH 1/9] Add generic script/iframe blocking until consent (#5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce ScriptBlocker, a new Frontend module that holds back arbitrary third-party '; + $rules = array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + // A leading space, not a bare substring check: 'data-frcn-src="..."' + // itself contains the substring 'src="...."' too, which would make a + // naive check pass even if the *live* src attribute were still there. + $this->assertStringNotContainsString( ' src="https://www.youtube.com/embed/abc123"', $result ); + $this->assertStringContainsString( 'type="text/plain"', $result ); + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + $this->assertStringContainsString( 'data-frcn-src="https://www.youtube.com/embed/abc123"', $result ); + $this->assertStringContainsString( '', $result ); + } + + /** + * A matching '; + $rules = array( array( 'pattern' => 'google.com/maps', 'category' => 'marketing' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'src="about:blank"', $result ); + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + $this->assertStringContainsString( 'data-frcn-src="https://www.google.com/maps/embed?pb=123"', $result ); + // Unrelated attributes must survive the rewrite untouched. + $this->assertStringContainsString( 'width="600"', $result ); + $this->assertStringContainsString( 'height="450"', $result ); + } + + /** + * A self-closing ' + . ''; + + $rules = array( + array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ), + array( 'pattern' => 'google.com/maps', 'category' => 'marketing' ), + ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-src="https://www.youtube.com/embed/one"', $result ); + $this->assertStringContainsString( 'data-frcn-src="https://www.google.com/maps/embed?pb=2"', $result ); + $this->assertStringContainsString( 'src="https://example.com/app.js"', $result ); + $this->assertStringContainsString( 'src="https://example.com/other-embed"', $result ); + $this->assertStringNotContainsString( 'data-frcn-src="https://example.com/app.js"', $result ); + $this->assertStringNotContainsString( 'data-frcn-src="https://example.com/other-embed"', $result ); + } + + /** + * A rule with an unrecognized/missing category falls back to + * 'marketing', matching Settings::parse_rules_text()'s own fallback. + */ + public function test_rule_with_missing_category_falls_back_to_marketing() { + $html = ''; + $rules = array( array( 'pattern' => 'tracker.example.com' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + } + + /** + * Matching is case-insensitive, both for the pattern against the src, + * and regardless of the tag name's own casing. + */ + public function test_matching_is_case_insensitive() { + $html = ''; + $rules = array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-src="https://www.YouTube.com/Embed/abc"', $result ); + } + + /** + * ScriptBlocker::parse_rules_text() and rules_to_text() round-trip the + * settings screen's one-rule-per-line textarea format. + */ + public function test_parse_rules_text_round_trips_with_rules_to_text() { + $text = "youtube.com/embed|marketing\ntracker.example.com|analytics"; + + $rules = ScriptBlocker::parse_rules_text( $text ); + + $this->assertSame( + array( + array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ), + array( 'pattern' => 'tracker.example.com', 'category' => 'analytics' ), + ), + $rules + ); + $this->assertSame( $text, ScriptBlocker::rules_to_text( $rules ) ); + } + + /** + * Blank lines and a missing/unrecognized category in the textarea + * format are handled gracefully rather than producing a broken rule. + */ + public function test_parse_rules_text_handles_blank_lines_and_unknown_category() { + $rules = ScriptBlocker::parse_rules_text( "\nyoutube.com/embed|not-a-real-category\n\n \n" ); + + $this->assertSame( + array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ), + $rules + ); + } +} diff --git a/tests/js/script-blocker.test.js b/tests/js/script-blocker.test.js new file mode 100644 index 0000000..19f8bf1 --- /dev/null +++ b/tests/js/script-blocker.test.js @@ -0,0 +1,245 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const scriptPath = path.resolve(__dirname, '../../assets/cookie-notice/frontconsent-script-blocker.js'); +const scriptBlockerScript = fs.readFileSync(scriptPath, 'utf8'); + +function makeParent() { + const inserted = []; + const removed = []; + + return { + inserted, + removed, + insertBefore(newNode, referenceNode) { + inserted.push({ newNode, referenceNode }); + }, + removeChild(node) { + removed.push(node); + } + }; +} + +function makeElement(tagName, attrs) { + const values = Object.assign({}, attrs); + + const element = { + tagName: tagName.toUpperCase(), + parentNode: null, + src: undefined, + get attributes() { + return Object.keys(values).map(function (name) { + return { name: name, value: values[name] }; + }); + }, + getAttribute(name) { + return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null; + }, + setAttribute(name, value) { + values[name] = String(value); + }, + removeAttribute(name) { + delete values[name]; + } + }; + + // Mimic the real DOM's src attribute/property reflection: an element + // created from markup with a src="..." attribute also has a matching + // .src property, which is what reviveIframe() reads/writes directly. + if (Object.prototype.hasOwnProperty.call(values, 'src')) { + element.src = values.src; + } + + return element; +} + +function createEnvironment(options) { + options = options || {}; + + const placeholders = options.placeholders || []; + const createdScripts = []; + const listeners = {}; + + const document = { + cookie: options.cookie || '', + readyState: 'loading', + addEventListener(event, callback) { + listeners[event] = callback; + }, + querySelectorAll(selector) { + assert.equal(selector, 'script[data-frcn-category], iframe[data-frcn-category]'); + return placeholders; + }, + createElement(tagName) { + const script = makeElement(tagName, {}); + createdScripts.push(script); + return script; + } + }; + + const context = { Array, document, window: {} }; + + if (Object.prototype.hasOwnProperty.call(options, 'frcnCookieNotice')) { + context.frcnCookieNotice = options.frcnCookieNotice; + } + + if (options.isCategoryAllowed) { + context.window.frcnCookieNoticeIsCategoryAllowed = options.isCategoryAllowed; + } + + vm.createContext(context); + vm.runInContext(scriptBlockerScript, context); + listeners.DOMContentLoaded(); + + return { context, createdScripts, listeners, placeholders }; +} + +test('a placeholder script for an accepted category is revived into a real, freshly-created script', () => { + const parent = makeParent(); + const placeholder = makeElement('script', { + type: 'text/plain', + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://tracker.example.com/pixel.js', + id: 'my-tracker', + async: '' + }); + placeholder.parentNode = parent; + + const environment = createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(environment.createdScripts.length, 1); + + const revived = environment.createdScripts[0]; + assert.equal(revived.src, 'https://tracker.example.com/pixel.js'); + assert.equal(revived.getAttribute('id'), 'my-tracker'); + assert.equal(revived.getAttribute('async'), ''); + // The 'type' attribute (and the data-frcn-* bookkeeping attributes) must + // NOT be copied onto the new element — a text/plain script would still + // never execute, even freshly created. + assert.equal(revived.getAttribute('type'), null); + assert.equal(revived.getAttribute('data-frcn-category'), null); + assert.equal(revived.getAttribute('data-frcn-src'), null); + + assert.equal(parent.inserted.length, 1); + assert.equal(parent.inserted[0].newNode, revived); + assert.equal(parent.inserted[0].referenceNode, placeholder); + assert.equal(parent.removed.length, 1); + assert.equal(parent.removed[0], placeholder); +}); + +test("an accepted iframe's src is restored from data-frcn-src and its bookkeeping attributes are cleaned up", () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank', + width: '600' + }); + placeholder.parentNode = makeParent(); + + createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'https://www.google.com/maps/embed?pb=1'); + assert.equal(placeholder.getAttribute('data-frcn-src'), null); + assert.equal(placeholder.getAttribute('data-frcn-category'), null); + assert.equal(placeholder.getAttribute('width'), '600'); +}); + +test('a placeholder for a still-rejected category is left completely alone', () => { + const parent = makeParent(); + const placeholder = makeElement('script', { + type: 'text/plain', + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://tracker.example.com/pixel.js' + }); + placeholder.parentNode = parent; + + const environment = createEnvironment({ + cookie: 'frcn_cookie_consent=rejected', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(environment.createdScripts.length, 0); + assert.equal(parent.inserted.length, 0); + assert.equal(parent.removed.length, 0); + assert.equal(placeholder.getAttribute('data-frcn-src'), 'https://tracker.example.com/pixel.js'); +}); + +test('an undecided visitor (no consent cookie yet) leaves placeholders alone', () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + placeholder.parentNode = makeParent(); + + createEnvironment({ + cookie: '', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'about:blank'); +}); + +test('a per-category override (window.frcnCookieNoticeIsCategoryAllowed) is consulted instead of the binary cookie', () => { + const marketingPlaceholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + marketingPlaceholder.parentNode = makeParent(); + + const analyticsPlaceholder = makeElement('iframe', { + 'data-frcn-category': 'analytics', + 'data-frcn-src': 'https://tracker.example.com/embed', + src: 'about:blank' + }); + analyticsPlaceholder.parentNode = makeParent(); + + createEnvironment({ + // The binary cookie says 'rejected' — without the override, nothing + // would be revived; the override says 'analytics' is allowed anyway. + cookie: 'frcn_cookie_consent=rejected', + isCategoryAllowed: (category) => category === 'analytics', + placeholders: [marketingPlaceholder, analyticsPlaceholder] + }); + + assert.equal(marketingPlaceholder.src, 'about:blank'); + assert.equal(analyticsPlaceholder.src, 'https://tracker.example.com/embed'); +}); + +test('revives newly-accepted placeholders on the frcnCookieConsent event', () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + placeholder.parentNode = makeParent(); + + const environment = createEnvironment({ + cookie: '', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'about:blank'); + + // A visitor decides to accept: frontconsent-cookie-notice.js sets the + // cookie first, then dispatches this same event. + environment.context.document.cookie = 'frcn_cookie_consent=accepted'; + environment.listeners.frcnCookieConsent({ detail: { consent: 'accepted' } }); + + assert.equal(placeholder.src, 'https://www.google.com/maps/embed?pb=1'); +}); From a000dd8bfd2ed7772b076e1c98eb4eb2b071e7d0 Mon Sep 17 00:00:00 2001 From: castellon Date: Wed, 30 Sep 2026 09:43:42 +0200 Subject: [PATCH 2/9] fix: icon-only reopen trigger, policy-page-title link, hover contrast The persistent "Cookie preferences" reopen trigger rendered as a text pill ("Preferencias de cookies" in Spanish) instead of reusing the same cookie icon already shown inside the banner. Reported live on a production site. Now icon-only (the same .frcn-cookie-notice__icon glyph, sized to its own 44x44px circular button), with the accessible name carried entirely by aria-label instead of visible text. Also fixes the same "Learn more" link accessibility issue already fixed in FrontBlocks (closemarketing/frontblocks#316): the link now uses the policy page's own title instead of a generic label (WCAG 2.4.4), and gets explicit hover/focus colors so a theme's global a:hover style can't make the text unreadable against its background. Co-Authored-By: Claude Sonnet 5 --- .../frontconsent-cookie-notice.css | 50 +++++++++++++++---- includes/Frontend/CookieNotice.php | 25 ++++++++-- tests/Unit/CookieNoticeAccessibilityTest.php | 18 +++++++ tests/Unit/CookieNoticePolicyPageTest.php | 45 +++++++++++++++++ 4 files changed, 124 insertions(+), 14 deletions(-) diff --git a/assets/cookie-notice/frontconsent-cookie-notice.css b/assets/cookie-notice/frontconsent-cookie-notice.css index ec09591..7529a1d 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.css +++ b/assets/cookie-notice/frontconsent-cookie-notice.css @@ -78,8 +78,24 @@ .frcn-cookie-notice__link { color: var(--frcn-cookie-accent-on-light); + background-color: transparent; text-decoration: underline; - white-space: nowrap; +} + +/* + * Explicit hover/focus color so a theme's own global `a:hover` style (some + * themes swap the text to white, expecting a colored background underneath) + * can't make this link's text unreadable against the notice's own background. + */ +.frcn-cookie-notice__link:hover, +.frcn-cookie-notice__link:focus { + color: var(--frcn-cookie-accent-on-light); + background-color: transparent; +} + +.frcn-cookie-notice__link:focus-visible { + outline: 2px solid var(--frcn-cookie-accent-on-light); + outline-offset: 2px; } .frcn-cookie-notice__actions { @@ -330,24 +346,36 @@ body.frcn-cookie-notice-lock-scroll { z-index: 999998; left: 16px; bottom: 16px; + display: flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; appearance: none; - border: 1px solid #d1d5db; - border-radius: 999px; - background-color: #ffffff; - color: #1f2937; - font-size: 12px; - font-weight: 600; - line-height: 1.2; - padding: 8px 14px; + border: none; + border-radius: 50%; + background-color: var(--frcn-cookie-accent); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); cursor: pointer; } +.frcn-cookie-reopen .frcn-cookie-notice__icon { + width: 100%; + height: 100%; + background-color: transparent; +} + +.frcn-cookie-reopen .frcn-cookie-notice__icon::before { + width: 22px; + height: 22px; + background-color: var(--frcn-cookie-accent-contrast); +} + .frcn-cookie-reopen:hover { - filter: brightness(0.97); + filter: brightness(0.92); } .frcn-cookie-reopen:focus-visible { - outline: 2px solid #687df9; + outline: 2px solid var(--frcn-cookie-accent); outline-offset: 2px; } diff --git a/includes/Frontend/CookieNotice.php b/includes/Frontend/CookieNotice.php index 846616b..e34b019 100644 --- a/includes/Frontend/CookieNotice.php +++ b/includes/Frontend/CookieNotice.php @@ -488,7 +488,7 @@ class="frcn-cookie-notice-sr-only" } /** - * Render the persistent "Cookie preferences" trigger that lets a visitor + * Render the persistent cookie-preferences trigger that lets a visitor * who already decided open the banner again to change their mind — the * only way to withdraw acceptance or replace a rejection without deleting * the consent cookie by hand. Always printed (including on the policy @@ -496,17 +496,33 @@ class="frcn-cookie-notice-sr-only" * only once a decision cookie actually exists, the same cache-neutral * approach render_banner_markup() itself uses. * + * Icon-only by design: it reuses the exact same cookie glyph shown inside + * the banner itself (.frcn-cookie-notice__icon), rather than a text label, + * so it reads as a small recognizable affordance rather than a chunk of + * text competing for attention on every page. The accessible name comes + * entirely from aria-label. + * * @return void */ private function render_reopen_trigger() { + $options = get_option( 'frontconsent_settings', array() ); + $color = (string) ( $options['cookie_notice_color'] ?? '#687df9' ); + $style = sprintf( + '--frcn-cookie-accent: %1$s; --frcn-cookie-accent-contrast: %2$s; --frcn-cookie-icon-url: url(%3$s);', + esc_attr( $color ), + esc_attr( $this->get_readable_text_color( $color ) ), + esc_attr( FRCN_PLUGIN_URL . 'assets/cookie-notice/cookie-icon.svg' ) + ); ?> " echo esc_html( $message ); if ( $policy_url ) { - echo ' ' . esc_html__( 'Learn more', 'frontconsent' ) . ''; + $policy_title = $policy_page_id ? get_the_title( $policy_page_id ) : ''; + $link_text = '' !== $policy_title ? $policy_title : __( 'Learn more', 'frontconsent' ); + + echo ' ' . esc_html( $link_text ) . ''; } ?>

diff --git a/tests/Unit/CookieNoticeAccessibilityTest.php b/tests/Unit/CookieNoticeAccessibilityTest.php index b8ccaed..48f3d47 100644 --- a/tests/Unit/CookieNoticeAccessibilityTest.php +++ b/tests/Unit/CookieNoticeAccessibilityTest.php @@ -177,4 +177,22 @@ public function test_status_announcer_is_present_even_on_the_policy_page() { $this->assertStringNotContainsString( 'id="frcn-cookie-notice"', $html ); $this->assertStringContainsString( 'id="frcn-cookie-notice-announcer"', $html ); } + + /** + * The reopen trigger is icon-only by design (a small recognizable + * affordance, not a text pill competing for attention on every page), so + * its accessible name must come entirely from aria-label — it must not + * also carry visible text content. + */ + public function test_reopen_trigger_is_icon_only_with_an_aria_label() { + update_option( 'frontconsent_settings', array( 'enable_cookie_notice' => true ) ); + + $html = $this->render_banner_html(); + + $this->assertMatchesRegularExpression( + '/]*id="frcn-cookie-reopen"[^>]*aria-label="Cookie preferences"[^>]*>\s*]*aria-hidden="true"[^>]*><\/span>\s*<\/button>/', + $html + ); + $this->assertStringNotContainsString( '>Cookie preferences<', $html ); + } } diff --git a/tests/Unit/CookieNoticePolicyPageTest.php b/tests/Unit/CookieNoticePolicyPageTest.php index ffe33b9..fc71a0e 100644 --- a/tests/Unit/CookieNoticePolicyPageTest.php +++ b/tests/Unit/CookieNoticePolicyPageTest.php @@ -154,6 +154,51 @@ public function test_learn_more_link_resolves_to_the_policy_page_permalink() { ); } + /** + * The link's visible text must name its actual destination (the policy + * page's own title) rather than a generic "Learn more" — out of context + * (e.g. a screen reader's "list all links"), "Learn more" gives no + * indication of where the link leads (WCAG 2.4.4). + */ + public function test_link_text_uses_the_policy_page_title() { + $other_page_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); + $this->go_to( get_permalink( $other_page_id ) ); + + $html = $this->render_banner_html(); + + $this->assertStringContainsString( '>Cookie Policy', $html ); + $this->assertStringNotContainsString( 'Learn more', $html ); + } + + /** + * A policy page with no title falls back to the generic label rather + * than rendering an empty link. + */ + public function test_link_text_falls_back_to_learn_more_when_the_page_has_no_title() { + $untitled_page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => '', + 'post_status' => 'publish', + ) + ); + + update_option( + 'frontconsent_settings', + array( + 'enable_cookie_notice' => true, + 'cookie_notice_policy_page_id' => $untitled_page_id, + ) + ); + + $other_page_id = self::factory()->post->create( array( 'post_type' => 'page' ) ); + $this->go_to( get_permalink( $other_page_id ) ); + + $html = $this->render_banner_html(); + + $this->assertStringContainsString( 'Learn more', $html ); + } + /** * On the configured policy page, the reopen trigger must localize * isPolicyPage=true and the home URL — otherwise clicking it there would From 7c0b8d34821fb697715af3c63e7c766e02bcc003 Mon Sep 17 00:00:00 2001 From: castellon Date: Wed, 30 Sep 2026 13:12:13 +0200 Subject: [PATCH 3/9] Add "Customize cookie settings" button and preferences panel (#11) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a real + get_readable_text_color( $color ); + $accent_link = $this->get_readable_on_white_color( $color, $bg_color ); + $panel_text = $this->get_readable_text_color( $bg_color ); + $style = sprintf( + '--frcn-cookie-accent: %1$s; --frcn-cookie-accent-contrast: %2$s; --frcn-cookie-accent-on-light: %3$s; --frcn-cookie-bg: %4$s; --frcn-cookie-text: %5$s; --frcn-cookie-radius: %6$s; --frcn-cookie-icon-url: url(%7$s);', + esc_attr( $color ), + esc_attr( $accent_text ), + esc_attr( $accent_link ), + esc_attr( $bg_color ), + esc_attr( $panel_text ), + esc_attr( $this->get_radius_value( $radius ) ), + esc_attr( FRCN_PLUGIN_URL . 'assets/cookie-notice/cookie-icon.svg' ) + ); + ?> + + fallback above. + $noscript_css .= ' .frcn-cookie-notice__button--customize { display: none; }'; + $this->print_noscript_style( $noscript_css ); /** @@ -1292,7 +1505,55 @@ public function log_consent_callback() { $this->maybe_increment_stat( $decision ); - wp_send_json_success(); + wp_send_json_success( array( 'categories' => $this->get_consent_categories_payload( $decision ) ) ); + } + + /** + * Build the (optional, additive) per-category consent map for the current + * request, applying the frcn_cookie_consent_categories filter around it. + * + * The Free tier never populates this itself — the stored binary + * accepted/rejected cookie stays the single source of truth for Free, and + * this method only exists so FrontConsent PRO's per-category consent + * (Analytics, Marketing, etc.) has a single, well-defined place to read + * the raw category selection submitted by the preferences panel (see + * render_preferences_panel()'s frcn_cookie_preferences_categories action) + * and to persist/return its own per-category decision alongside the + * binary one. Never required for the binary flow to keep working. + * + * @param string $decision 'accepted' or 'rejected'. + * @return array Category slug => state, empty unless something extends it. + */ + private function get_consent_categories_payload( $decision ) { + $categories = array(); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the surrounding log_consent_callback() already verified the nonce above. + if ( isset( $_POST['categories'] ) ) { + // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- raw JSON can't be run through a string sanitizer without corrupting it; every decoded key/value is sanitized individually below (sanitize_key()/rest_sanitize_boolean()) before it's ever used. + $decoded = json_decode( (string) wp_unslash( $_POST['categories'] ), true ); + + if ( is_array( $decoded ) ) { + foreach ( $decoded as $key => $value ) { + $categories[ sanitize_key( (string) $key ) ] = rest_sanitize_boolean( $value ); + } + } + } + + /** + * Filters the per-category consent map recorded alongside a binary + * accept/reject decision. + * + * FrontConsent PRO hooks here to persist (e.g. in its own cookie/option) + * and/or normalize the category selection a visitor made in the + * preferences panel (see frcn_cookie_preferences_categories), and to + * read back any category state it needs when this fires again on a + * later request. The Free tier's own stored consent format never + * depends on this value — it is optional and purely additive. + * + * @param array $categories Category slug => state, decoded from the request. + * @param string $decision The binary decision being recorded ('accepted' or 'rejected'). + */ + return apply_filters( 'frcn_cookie_consent_categories', $categories, $decision ); } /** diff --git a/readme.md b/readme.md index 00b2d69..b64d40e 100644 --- a/readme.md +++ b/readme.md @@ -5,6 +5,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli ## Functionalities - **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. +- **Cookie preferences panel** — a "Customize cookie settings" button (left of Reject/Accept) and the persistent reopen trigger both open a dialog with Accept all / Reject all / Save changes and a static "Strictly necessary" section, all recording the exact same consent cookie/Consent Mode update/logging as the binary Accept/Reject buttons. Extensible via the `frcn_cookie_preferences_categories` action and `frcn_cookie_consent_categories` filter so FrontConsent PRO can add per-category consent (Analytics, Marketing, etc.) without forking markup — see [docs/preferences-panel-hooks.md](docs/preferences-panel-hooks.md). - **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. - **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). diff --git a/readme.txt b/readme.txt index bb36a33..712df5c 100644 --- a/readme.txt +++ b/readme.txt @@ -68,6 +68,10 @@ Service provided by OpenAI: [Terms of Use](https://openai.com/policies/terms-of- == Changelog == += Unreleased = +* Added a "Customize cookie settings" button (left of Reject/Accept, showing the cookie icon) that opens a cookie preferences dialog with Accept all / Reject all / Save changes actions and a static "Strictly necessary" section, also reachable from the persistent "Cookie preferences" reopen trigger. Every action records the exact same consent cookie, Consent Mode update and logging as the existing Accept/Reject buttons. +* Added PRO-ready extension points so a future FrontConsent PRO add-on can render per-category consent (Analytics, Marketing, etc.) into the same panel without forking markup: the `frcn_cookie_preferences_categories` action, the `frcn_cookie_consent_categories` filter, and the `frcn_cookie_customize_button_label`/`frcn_cookie_customize_button_enabled` filters. Documented in `docs/preferences-panel-hooks.md`. + = 1.0.1 = * Settings page now uses tabs, so a companion plugin can add its own tab via the new `frontconsent_settings_tabs` filter, rendering its panel on either `frontconsent_settings_form_tab_panels` (fields saved through the main settings form) or `frontconsent_settings_tab_panels` (a panel with its own form, e.g. FrontConsent PRO's License tab). * Added a FrontConsent PRO upsell tab and an inline promo link on the Cookie Notice tab, shown only when FrontConsent PRO isn't installed. diff --git a/tests/Unit/CookieNoticeAccessibilityTest.php b/tests/Unit/CookieNoticeAccessibilityTest.php index 48f3d47..0b510de 100644 --- a/tests/Unit/CookieNoticeAccessibilityTest.php +++ b/tests/Unit/CookieNoticeAccessibilityTest.php @@ -59,9 +59,17 @@ public function test_bar_layout_uses_region_role_not_dialog() { $html = $this->render_banner_html(); - $this->assertStringContainsString( 'role="region"', $html ); - $this->assertStringNotContainsString( 'role="dialog"', $html ); - $this->assertStringNotContainsString( 'aria-modal', $html ); + // Scoped to the banner element itself: the cookie preferences panel + // (a separate, always-present dialog — see + // CookieNotice::render_preferences_panel()) legitimately carries + // role="dialog"/aria-modal regardless of the banner's own layout, so + // asserting over the whole wp_footer output would wrongly fail here. + $banner_end = strpos( $html, 'id="frcn-cookie-reopen"' ); + $banner_html = substr( $html, 0, $banner_end ); + + $this->assertStringContainsString( 'role="region"', $banner_html ); + $this->assertStringNotContainsString( 'role="dialog"', $banner_html ); + $this->assertStringNotContainsString( 'aria-modal', $banner_html ); } /** diff --git a/tests/Unit/CookieNoticeConsentCategoriesTest.php b/tests/Unit/CookieNoticeConsentCategoriesTest.php new file mode 100644 index 0000000..7fe5ecd --- /dev/null +++ b/tests/Unit/CookieNoticeConsentCategoriesTest.php @@ -0,0 +1,156 @@ +cookie_notice = new CookieNotice(); + + update_option( 'frontconsent_settings', array( 'enable_cookie_notice' => true ) ); + + // wp_send_json_success() only routes through the interceptable + // wp_die() below when the request is treated as an Ajax one. + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( 'wp_die_ajax_handler', array( $this, 'get_die_handler' ) ); + + $_POST['nonce'] = wp_create_nonce( CookieNotice::NONCE_ACTION ); + } + + public function tear_down() { + remove_filter( 'wp_die_ajax_handler', array( $this, 'get_die_handler' ) ); + remove_filter( 'wp_doing_ajax', '__return_true' ); + unset( $_POST['nonce'], $_POST['decision'], $_POST['categories'] ); + delete_option( 'frontconsent_settings' ); + parent::tear_down(); + } + + /** + * @return callable + */ + public function get_die_handler() { + return static function ( $message ) { + throw new Exception( is_scalar( $message ) ? (string) $message : 'die' ); + }; + } + + /** + * Invoke log_consent_callback() and decode its JSON response. + * + * @return array + */ + private function log_consent() { + ob_start(); + + try { + $this->cookie_notice->log_consent_callback(); + } catch ( Exception $e ) { + unset( $e ); + } + + $output = ob_get_clean(); + + return json_decode( $output, true ); + } + + /** + * With nothing hooked in, the response still carries an (empty) array — + * the binary decision itself never depends on this. + */ + public function test_categories_default_to_an_empty_array() { + $_POST['decision'] = 'accepted'; + + $response = $this->log_consent(); + + $this->assertTrue( $response['success'] ); + $this->assertSame( array(), $response['data']['categories'] ); + } + + /** + * A submitted categories JSON payload is decoded, sanitized to booleans + * keyed by a sanitized slug, and handed to the filter. + */ + public function test_submitted_categories_are_decoded_and_sanitized() { + $_POST['decision'] = 'accepted'; + $_POST['categories'] = wp_json_encode( + array( + 'Analytics!' => true, + 'marketing' => false, + ) + ); + + $response = $this->log_consent(); + + $this->assertSame( + array( + 'analytics' => true, + 'marketing' => false, + ), + $response['data']['categories'] + ); + } + + /** + * The frcn_cookie_consent_categories filter must actually run around the + * categories payload, receiving the decision alongside it, and its + * return value must be what reaches the response — this is the concrete + * extension point a PRO-like add-on uses to persist/read its own + * per-category state. + */ + public function test_consent_categories_filter_is_applied_and_observable_in_the_response() { + $_POST['decision'] = 'rejected'; + + $captured_decision = null; + + add_filter( + 'frcn_cookie_consent_categories', + static function ( $categories, $decision ) use ( &$captured_decision ) { + $captured_decision = $decision; + $categories['marketing'] = false; + $categories['analytics'] = true; + return $categories; + }, + 10, + 2 + ); + + $response = $this->log_consent(); + + $this->assertSame( 'rejected', $captured_decision ); + $this->assertSame( + array( + 'marketing' => false, + 'analytics' => true, + ), + $response['data']['categories'] + ); + } + + /** + * The binary accepted/rejected cookie/logging flow must keep working + * completely unmodified when no categories are submitted at all — the + * category map is purely additive. + */ + public function test_binary_decision_is_recorded_without_any_categories_payload() { + $_POST['decision'] = 'accepted'; + + $response = $this->log_consent(); + + $this->assertTrue( $response['success'] ); + } +} diff --git a/tests/Unit/CookieNoticePreferencesPanelTest.php b/tests/Unit/CookieNoticePreferencesPanelTest.php new file mode 100644 index 0000000..4444253 --- /dev/null +++ b/tests/Unit/CookieNoticePreferencesPanelTest.php @@ -0,0 +1,296 @@ +cookie_notice = new CookieNotice(); + } + + public function tear_down() { + delete_option( 'frontconsent_settings' ); + remove_all_actions( 'frcn_cookie_preferences_categories' ); + remove_all_filters( 'frcn_cookie_consent_categories' ); + remove_all_filters( 'frcn_cookie_customize_button_label' ); + remove_all_filters( 'frcn_cookie_customize_button_enabled' ); + parent::tear_down(); + } + + /** + * Render the full wp_footer output (banner markup + reopen trigger + + * preferences panel + status announcer), the same way WordPress itself + * would for a request. + * + * @return string + */ + private function render_banner_html() { + ob_start(); + $this->cookie_notice->render_banner(); + return ob_get_clean(); + } + + /** + * The button must render as a real, keyboard-focusable