AlpineConsent: a table of every script class-blocker.php * has discovered (automatically, as real visitors load real pages, or * immediately via the "Scan site now" button here) — a site owner * assigns a category per row, no hunting for a WordPress "handle" by * hand and no editing code. Deliberately the native Settings API, not * the React/@wordpress/scripts admin app docs/ARCHITECTURE.md * describes as the eventual target — that's a bigger, separate build; * this is v1. */ if ( ! defined( 'ABSPATH' ) ) { exit; } class AlpineConsent_Admin { /** * 'functional' stores identically to "no category" for blocking * purposes (see class-blocker.php's BLOCKABLE_CATEGORIES) — it * exists here only so a site owner can explicitly mark a script as * reviewed-and-essential rather than leaving it in the ambiguous * "not yet looked at" state. The other three are the plugin's real, * widget-recognized blocking categories (widget/alpineconsent.js's * own CATEGORIES list) — labels here follow the site's compliance * documentation's wording; "Statistics-Anonymous" cookies from that * doc fall under Statistics / Analytics too, since visitors control * both via the one Statistics toggle the widget exposes. */ const CATEGORY_LABELS = array( 'functional' => 'Functional (Essential)', 'preferences' => 'Preferences', 'statistics' => 'Statistics / Analytics', 'marketing' => 'Marketing / Tracking', ); // Cookies discovered via "Scan site now" reading the same // response's Set-Cookie headers (see handle_scan_request()) — a // separate option from AlpineConsent_Blocker::OPTION_NAME because // this data has a different shape and a different ceiling: it's // never per-script (a Set-Cookie header doesn't say which script // caused it), and it's purely informational — there is no // cookie-level blocking mechanism, only script/iframe-level, so a // category assigned here records "reviewed" for a site owner's own // documentation rather than controlling anything at runtime. const COOKIE_OPTION_NAME = 'alpineconsent_cookies'; // Stale-entry delete (single + bulk, scripts + cookies) — a real, // new action with no pre-existing form/nonce to reuse (unlike every // other AJAX conversion in this file), so this is localized to // settings-ajax.js directly — see enqueue_assets(). const DELETE_ENTRY_NONCE_ACTION = 'alpineconsent_delete_entry'; // AlpineConsent#260 item 1 — "Scan site now" used to only ever // fetch the homepage itself; passive discovery still happens as // real visitors load other pages, but there was no on-demand way to // check more than one page. Same shallow-crawl budget as the public // web scanner's own multi-page crawl (AlpineConsent#249, // backend/src/routes/scan.js's MAX_PAGES_TO_CRAWL) — the homepage // plus up to 4 more real pages, not a full-site crawl. const MAX_PAGES_TO_SCAN = 5; // Checked *before* AlpineConsent_Cookie_Database::lookup() in // discover_cookies_from_response() — same reasoning, and the same // list, as the backend scanner's own NECESSARY_COOKIES // (backend/src/utils/trackers.js). These are generic session/ // security infrastructure names that are essential essentially // everywhere they appear, regardless of which site set them. The // database indexes by literal cookie *name* per *platform* — at // least one real entry (Instagram's own "sessionid") reuses a // generic infra-sounding name for something that specific platform // categorizes as Marketing. Trusting the database for a name on // this list would risk suggesting an actually-essential cookie as // non-essential purely because some unrelated product happens to // reuse the same common name. const GENERIC_NECESSARY_COOKIE_NAMES = array( 'session', 'sessionid', 'phpsessid', 'csrftoken', 'xsrf-token', '__cf_bm', 'cf_clearance' ); // v0.6.20's `MENU_ICON_SVG` (a single flat mountain-glyph path, no // filled background) was itself a real fix for a real bug — WP // forces every `fill` in a base64-encoded SVG menu icon to white — // but it was the wrong fix for what the site owner actually wanted: // "the real site logo/favicon", not an abstract monochrome // silhouette (#281 — reported live as "shows two mountains", which // is literally that glyph's two peaks). WordPress core only applies // the fill-to-white rewrite to the `data:image/svg+xml;base64,` // icon_url form (confirmed directly in wp-admin/menu-header.php: a // plain image URL takes a completely different branch — a bare // ``, untouched by that CSS). So a full-color icon // was never actually impossible; it just can't be a base64 SVG. // // AlpineConsent#296 — real follow-up bug, also reported live: that plain-URL branch of // menu-header.php has NO size constraint of its own on the `` // it prints — WP's own admin-menu.css only ever sizes the SVG-icon // form (`background-size: 20px auto`) or a dashicon (font glyph); // a plain ``'s pixel dimensions are whatever the source file // actually is. Pointing icon_url at the full logo.png master // (608×632) rendered it at that full native size instead of a menu // icon. add_page() below now points at a dedicated // `assets/img/menu-icon.svg` (a real vector source, Logo/ // AlpineConsent.svg — not a base64-embedded data URI, which is the // ONLY form WP force-recolors to white; a plain .svg FILE url takes // the exact same untouched-by-that-CSS branch as a PNG) — crisp at // any size/pixel density with no pre-sizing needed, since the // browser rasterizes vector content fresh for whatever size it's // actually displayed at. print_menu_icon_size_fix() below still // adds an explicit width/height rule scoped to this one menu // item's ``, since WP itself still won't size a plain-URL icon // on its own regardless of format. private $banner_settings; private $general_settings; // Set by add_page() to add_menu_page()'s own return value (the // page's hook suffix) — enqueue_assets() needs it to load admin.css // only on this one page, not every wp-admin screen. private $page_hook; public function __construct( AlpineConsent_Banner_Settings $banner_settings, AlpineConsent_General_Settings $general_settings ) { $this->banner_settings = $banner_settings; $this->general_settings = $general_settings; } public function register() { add_action( 'admin_menu', array( $this, 'add_page' ) ); add_action( 'admin_init', array( $this, 'register_setting' ) ); add_action( 'admin_post_alpineconsent_scan', array( $this, 'handle_scan_request' ) ); // AJAX-save follow-up, raised directly: the mega-form below // (Scripts/Cookies categories + Banner + General settings, one // "Save changes" button, all four registered under the same // 'alpineconsent' Settings API group) already reaches this same // admin_init-registered sanitize_callback via options.php — see // process_save_settings_ajax()'s own docblock for why calling // update_option() here reuses that exact same validation with // zero duplicated logic. wp_ajax_* handlers run under is_admin() // too (admin-ajax.php lives in wp-admin regardless of caller), // same reasoning already established for the other AJAX actions // in this plugin (class-ai-translation.php, class-legal-backup.php). add_action( 'wp_ajax_alpineconsent_save_settings', array( $this, 'handle_save_settings_ajax' ) ); // Stale-entry delete follow-up, raised directly: no way to // remove a stale discovered script/cookie at all, single or // bulk. Same delete_entries_and_build_response() worker behind // all four — see that method's own docblock. add_action( 'wp_ajax_alpineconsent_delete_script', array( $this, 'handle_delete_script_ajax' ) ); add_action( 'wp_ajax_alpineconsent_delete_scripts', array( $this, 'handle_delete_scripts_ajax' ) ); add_action( 'wp_ajax_alpineconsent_delete_cookie', array( $this, 'handle_delete_cookie_ajax' ) ); add_action( 'wp_ajax_alpineconsent_delete_cookies', array( $this, 'handle_delete_cookies_ajax' ) ); // Deliberately NOT gated to this plugin's own page like // enqueue_assets() below — the menu ITSELF (and therefore its // icon) is visible on every wp-admin screen, so this has to run // everywhere too. add_action( 'admin_enqueue_scripts', array( $this, 'print_menu_icon_size_fix' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } /** * A top-level menu entry with the AlpineConsent mark, not a * Settings submenu — the plugin's own settings are frequent enough * to visit that hiding them a click deep under Settings was real * friction, not just cosmetic. */ public function add_page() { $this->page_hook = add_menu_page( 'AlpineConsent', 'AlpineConsent', 'manage_options', 'alpineconsent', array( $this, 'render_page' ), ALPINECONSENT_PLUGIN_URL . 'assets/img/menu-icon.svg' ); } /** * AlpineConsent#296 — real follow-up bug found live: WordPress's own menu CSS * only ever sizes a menu icon that's a dashicon (font glyph) or a * base64 SVG (`background-size: 20px auto`) — a plain `` * icon_url (what add_page() above uses — a plain .svg FILE url, to * get a real full-color logo instead of a base64-recolored one) * gets no size constraint from core at all, regardless of format. * Scoped to this one menu item's own wrapper * (`#toplevel_page_alpineconsent` — WordPress's own * "toplevel_page_{slug}" ID convention for add_menu_page()). * * WordPress.org Plugins Team review (2026-10-09): used to echo a raw * inline style block directly into admin_head — flagged, correctly, since * even a four-line admin-only rule is still expected to go through * wp_enqueue_*. `false` for $src registers a virtual handle with no * actual file — core's own documented mechanism for a handle that * exists only to carry wp_add_inline_style() content (see the Codex * on wp_register_style(), "To create a dependency...with no source * file"). * * Real gap found live, caught only by actually loading the real * rendered admin page rather than trusting a static code read: the * FIRST version of this fix registered the handle here but called * wp_add_inline_style() from a SEPARATE method hooked to admin_head * — admin_head fires AFTER WordPress has already printed every * queued style's own output (admin_print_styles runs first), * so that later addition had nowhere left to be printed and * silently never rendered at all. Register, enqueue, AND attach the * inline content all together, in the SAME admin_enqueue_scripts * callback — confirmed via a real authenticated page load (not just * wp eval in isolation, which doesn't reproduce the real print-order * gap) that the inline style now actually appears in the response. */ public function print_menu_icon_size_fix() { wp_register_style( 'alpineconsent-admin-global', false, array(), ALPINECONSENT_VERSION ); wp_enqueue_style( 'alpineconsent-admin-global' ); wp_add_inline_style( 'alpineconsent-admin-global', '#toplevel_page_alpineconsent .wp-menu-image img{width:20px;height:20px;padding:9px 0 0;}' ); } public function enqueue_assets( $hook ) { if ( $hook !== $this->page_hook ) { return; } wp_enqueue_style( 'alpineconsent-admin', ALPINECONSENT_PLUGIN_URL . 'assets/css/admin.css', array(), ALPINECONSENT_VERSION ); // WordPress.org Plugins Team review (2026-10-09): every class // that used to echo its own raw inline-script block directly into this // settings page's own output (class-admin.php itself, // class-banner-settings.php, class-managed-page.php, // class-privacy-section.php) now calls // wp_add_inline_script( 'alpineconsent-admin-inline', ... ) // instead — same virtual-handle mechanism // print_menu_icon_size_fix() above already uses for CSS. No // dependency declared: every one of those scripts is plain // vanilla DOM JS (getElementById/querySelector/addEventListener), // not one of them actually touches jQuery. Registered here, on // this one page-scoped hook, rather than globally like the // style handle above — none of this JS has any reason to load // outside this plugin's own settings page. wp_register_script( 'alpineconsent-admin-inline', false, array(), ALPINECONSENT_VERSION, true ); wp_enqueue_script( 'alpineconsent-admin-inline' ); // The banner Logo field's "Choose from Media Library" button // (class-banner-settings.php's own inline script) needs the // real wp.media JS API — WordPress doesn't load it by default on // every admin page, only where a plugin explicitly asks. wp_enqueue_media(); // AlpineConsent#325 Phase 2 — a real separate asset, unlike the // AI-translation button's inline script below: this is ~100 // lines of actual PBKDF2/AES-GCM logic, not a dozen lines of DOM // wiring, and benefits from being reviewable/loadable as its own // file rather than re-embedded as a PHP string literal. wp_enqueue_script( 'alpineconsent-legal-backup', ALPINECONSENT_PLUGIN_URL . 'assets/js/legal-backup.js', array(), ALPINECONSENT_VERSION, true ); wp_localize_script( 'alpineconsent-legal-backup', 'AlpineConsentLegalBackup', array( 'nonce' => wp_create_nonce( AlpineConsent_Legal_Backup::NONCE_ACTION ), 'fieldSelectors' => array( array( 'key' => 'company_name', 'selector' => '#alpineconsent-company-name' ), array( 'key' => 'company_address', 'selector' => '#alpineconsent-company-address' ), array( 'key' => 'company_email', 'selector' => '#alpineconsent-company-email' ), array( 'key' => 'company_phone', 'selector' => '#alpineconsent-company-phone' ), array( 'key' => 'company_managing_director', 'selector' => '#alpineconsent-company-md' ), array( 'key' => 'company_register', 'selector' => '#alpineconsent-company-register' ), array( 'key' => 'company_vat_id', 'selector' => '#alpineconsent-company-vat' ), ), 'i18nEncrypting' => __( 'Encrypting…', 'alpineconsent' ), 'i18nSuccess' => __( 'Backed up just now.', 'alpineconsent' ), 'i18nError' => __( 'Could not back up — please try again.', 'alpineconsent' ), 'i18nPassphraseRequired' => __( 'Enter a passphrase (at least 8 characters).', 'alpineconsent' ), ) ); // AJAX-save follow-up — a real separate asset, same reasoning as // legal-backup.js above: this wires up form-submit interception, // fetch(), and DOM patching for two different forms, not a // dozen lines. No nonce is localized here — both forms already // render their own `_wpnonce` field (from settings_fields()/ // wp_nonce_field()), read straight out of FormData(form). wp_enqueue_script( 'alpineconsent-settings-ajax', ALPINECONSENT_PLUGIN_URL . 'assets/js/settings-ajax.js', array(), ALPINECONSENT_VERSION, true ); wp_localize_script( 'alpineconsent-settings-ajax', 'AlpineConsentSettingsAjax', array( 'i18nSaving' => __( 'Saving…', 'alpineconsent' ), 'i18nSaved' => __( 'Saved.', 'alpineconsent' ), 'i18nError' => __( 'Could not save — please try again.', 'alpineconsent' ), // The liability-acceptance button's own label swaps // between these two depending on its current state — // same literal strings submit_button() itself uses in // render_page(), kept in sync by hand (both are short, // stable, unlikely-to-change copy). 'i18nSave' => __( 'Save', 'alpineconsent' ), 'i18nAcceptAndUnlock' => __( 'Accept & unlock per-language editing', 'alpineconsent' ), // Stale-entry delete — a real, new action with no // pre-existing form nonce to read out of FormData(), // unlike every other AJAX action this file localizes // nothing for. 'deleteNonce' => wp_create_nonce( self::DELETE_ENTRY_NONCE_ACTION ), 'i18nConfirmDelete' => __( 'Delete this? This cannot be undone.', 'alpineconsent' ), 'i18nConfirmBulkDelete' => __( 'Delete the selected entries? This cannot be undone.', 'alpineconsent' ), ) ); } public function register_setting() { register_setting( 'alpineconsent', AlpineConsent_Blocker::OPTION_NAME, array( 'type' => 'array', // Static, not array( $this, 'sanitize' ) — so that // write_discovered_handles() below can remove_filter() // this exact callback from outside any particular // AlpineConsent_Admin instance (none is stored anywhere // globally — see render_legal_editor_area()'s own // comment for the same reasoning applied elsewhere). 'sanitize_callback' => array( __CLASS__, 'sanitize' ), 'default' => array(), ) ); register_setting( 'alpineconsent', self::COOKIE_OPTION_NAME, array( 'type' => 'array', 'sanitize_callback' => array( __CLASS__, 'sanitize_cookies' ), 'default' => array(), ) ); } /** * AJAX follow-up, raised directly: saving from this page reloaded * the whole thing, and even after fixing the tab it landed back on * (see wireTabs()/syncActiveTabEverywhere() further down), the user * asked outright whether saving could just not reload at all. This * is the mega-form's own handler — the one "Save changes" button * that already submits Scripts categories, Cookies categories, * Banner settings, and General settings together in one POST (all * four registered under the same 'alpineconsent' Settings API * group above). `settings_fields( 'alpineconsent' )` already prints * a nonce for WordPress core's own well-documented, stable action * name for a settings group — "{$option_group}-options" — in a * field named `_wpnonce`; reusing it here means the existing form * markup needs zero changes to work with either this handler or the * original options.php one. */ public function handle_save_settings_ajax() { check_ajax_referer( 'alpineconsent-options', '_wpnonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'code' => 'FORBIDDEN', 'message' => __( 'Not allowed.', 'alpineconsent' ) ), 403 ); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- $_POST is handed to process_save_settings_ajax() raw and unsanitized on purpose: update_option() re-runs each option's own registered sanitize_callback on every single call (not just from an options.php submission), so real validation already happens downstream, exactly as process_save_settings_ajax()'s own docblock explains — the same "sanitize happens where update_option() is actually called, not inline here" reasoning class-legal-backup.php/class-ai-translation.php already use for their own raw $_POST reads. wp_send_json_success( $this->process_save_settings_ajax( $_POST ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified above via check_ajax_referer(). } /** * The actual save, split out from handle_save_settings_ajax() for * direct testability (same thin-wrapper/private-method split as * AlpineConsent_AI_Translation::handle_translate_request()/ * process_request()). * * Calls wp_unslash() on each option's value before handing it to * update_option() — WordPress slashes $_POST the same way for every * request, AJAX included (wp_magic_quotes() runs unconditionally at * bootstrap), and core's own options.php always unslashes each * value before its update_option() call, so sanitize()/ * sanitize_cookies()/the Banner and General settings' own sanitize() * methods have only ever run against unslashed input. Skipping this * here let backslashes from a real options.php submission creep in * un-stripped (e.g. saving "O'Brien" stored as "O\'Brien") — * WordPress.org Plugins Team review. * * update_option() re-runs each option's own registered * sanitize_callback on every call, not just from an options.php * submission (see sanitize()'s own docblock below) — so this * reuses the exact same validation as today's flow, no logic * duplicated here at all. * * @param array $post $_POST (or an equivalent array in tests). * @return array{setupScoreHtml: string, scriptsPillLabels: ?array, cookiesPillLabels: ?array} */ private function process_save_settings_ajax( $post ) { $option_names = array( AlpineConsent_Blocker::OPTION_NAME, self::COOKIE_OPTION_NAME, AlpineConsent_Banner_Settings::OPTION_NAME, AlpineConsent_General_Settings::OPTION_NAME, ); foreach ( $option_names as $option_name ) { if ( isset( $post[ $option_name ] ) ) { update_option( $option_name, wp_unslash( $post[ $option_name ] ) ); } } ob_start(); $this->render_setup_score(); $setup_score_html = ob_get_clean(); // AlpineConsent#386 — a category saved via this AJAX path used to // only refresh the setup score and the pill-count LABELS, never // the table body itself: a row's own data-category attribute and // its group membership (Other vs. Uncategorized, or a named // provider group — see render_scripts_table_body()) are both // computed once, server-side, at render time, so they went stale // until a real page reload. Reported directly: after clearing // several "Other" scripts to "—" and clicking Save, "they should // have moved to uncategorized, but stayed right there until I // refreshed the page". Returning fresh table-body HTML here lets // the JS side swap it in, so the AJAX save visually matches // exactly what a full reload would show. $scripts_pill_labels = null; $scripts_table_body_html = null; if ( isset( $post[ AlpineConsent_Blocker::OPTION_NAME ] ) ) { $discovered = get_option( AlpineConsent_Blocker::OPTION_NAME, array() ); $scripts_pill_labels = $this->toolbar_pill_labels( $this->counts_by_effective_category( $discovered ), $this->count_uncategorized( $discovered ), true ); ob_start(); $this->render_scripts_table_body( $discovered ); $scripts_table_body_html = ob_get_clean(); } $cookies_pill_labels = null; $cookies_table_body_html = null; if ( isset( $post[ self::COOKIE_OPTION_NAME ] ) ) { $discovered_cookies = get_option( self::COOKIE_OPTION_NAME, array() ); $cookies_pill_labels = $this->toolbar_pill_labels( $this->counts_by_effective_category( $discovered_cookies ), $this->count_uncategorized( $discovered_cookies ), false ); ob_start(); $this->render_cookies_table_body( $discovered_cookies ); $cookies_table_body_html = ob_get_clean(); } return array( 'setupScoreHtml' => $setup_score_html, 'scriptsPillLabels' => $scripts_pill_labels, 'cookiesPillLabels' => $cookies_pill_labels, 'scriptsTableBodyHtml' => $scripts_table_body_html, 'cookiesTableBodyHtml' => $cookies_table_body_html, ); } /** * Stale-entry cleanup, raised directly after fixing how the Cookie * Policy page groups the "Other" catch-all: fixing the DISPLAY of a * pile of never-pruned discovered scripts/cookies doesn't shrink the * pile itself — there was no delete action anywhere in this plugin * at all, single or bulk. `last_seen` (see class-blocker.php's own * maybe_discover() and this class's discover_from_html()/ * discover_cookies_from_response()/discover_cookies_from_active_plugins()) * only ever moves on an explicit "Scan site now" click, never live * traffic — so "not seen in N days" genuinely means "the last * several re-scans didn't find it," not "no visitor loaded it." * * One shared private worker for all four thin AJAX handlers below * (single/bulk × scripts/cookies) — same option-shape, same * "remove these keys, report whether anything actually changed" * logic either way. * * @param string $option_name AlpineConsent_Blocker::OPTION_NAME or self::COOKIE_OPTION_NAME. * @param array $keys_to_delete Handles or cookie names to remove. * @return array{deleted: string[], setupScoreHtml: string, pillLabels: array} */ private function delete_entries_and_build_response( $option_name, $keys_to_delete ) { $discovered = get_option( $option_name, array() ); $deleted = array(); foreach ( $keys_to_delete as $key ) { $key = (string) $key; if ( isset( $discovered[ $key ] ) ) { unset( $discovered[ $key ] ); $deleted[] = $key; } } if ( ! empty( $deleted ) ) { // $discovered here is the full {handle: {src, category, ...}} // shape, same as every other raw discovery write — same // sanitize() bypass needed, not the plain category-string // merge logic. self::write_raw_discovery_data( $option_name, $discovered ); } ob_start(); $this->render_setup_score(); $setup_score_html = ob_get_clean(); $show_uncategorized_filter = ( AlpineConsent_Blocker::OPTION_NAME === $option_name ); $pill_labels = $this->toolbar_pill_labels( $this->counts_by_effective_category( $discovered ), $this->count_uncategorized( $discovered ), $show_uncategorized_filter ); // Same staleness risk as process_save_settings_ajax() above: a // delete can shrink a collapsible provider group down to a // singleton (which must fall back into the flat Other/ // Uncategorized run) or remove a group entirely — fresh table- // body HTML lets the JS side swap it in rather than just // deleting the one row from the DOM and leaving a stale header. ob_start(); if ( AlpineConsent_Blocker::OPTION_NAME === $option_name ) { $this->render_scripts_table_body( $discovered ); } else { $this->render_cookies_table_body( $discovered ); } $table_body_html = ob_get_clean(); return array( 'deleted' => $deleted, 'setupScoreHtml' => $setup_score_html, 'pillLabels' => $pill_labels, 'tableBodyHtml' => $table_body_html, ); } public function handle_delete_script_ajax() { check_ajax_referer( self::DELETE_ENTRY_NONCE_ACTION, 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'code' => 'FORBIDDEN', 'message' => __( 'Not allowed.', 'alpineconsent' ) ), 403 ); } $handle = isset( $_POST['handle'] ) ? sanitize_text_field( wp_unslash( $_POST['handle'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified above via check_ajax_referer(). if ( '' === $handle ) { wp_send_json_error( array( 'code' => 'VALIDATION_ERROR', 'message' => __( 'No script specified.', 'alpineconsent' ) ), 400 ); } wp_send_json_success( $this->delete_entries_and_build_response( AlpineConsent_Blocker::OPTION_NAME, array( $handle ) ) ); } public function handle_delete_scripts_ajax() { check_ajax_referer( self::DELETE_ENTRY_NONCE_ACTION, 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'code' => 'FORBIDDEN', 'message' => __( 'Not allowed.', 'alpineconsent' ) ), 403 ); } $handles = isset( $_POST['handles'] ) && is_array( $_POST['handles'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['handles'] ) ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified above via check_ajax_referer(). if ( empty( $handles ) ) { wp_send_json_error( array( 'code' => 'VALIDATION_ERROR', 'message' => __( 'No scripts specified.', 'alpineconsent' ) ), 400 ); } wp_send_json_success( $this->delete_entries_and_build_response( AlpineConsent_Blocker::OPTION_NAME, $handles ) ); } public function handle_delete_cookie_ajax() { check_ajax_referer( self::DELETE_ENTRY_NONCE_ACTION, 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'code' => 'FORBIDDEN', 'message' => __( 'Not allowed.', 'alpineconsent' ) ), 403 ); } $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified above via check_ajax_referer(). if ( '' === $name ) { wp_send_json_error( array( 'code' => 'VALIDATION_ERROR', 'message' => __( 'No cookie specified.', 'alpineconsent' ) ), 400 ); } wp_send_json_success( $this->delete_entries_and_build_response( self::COOKIE_OPTION_NAME, array( $name ) ) ); } public function handle_delete_cookies_ajax() { check_ajax_referer( self::DELETE_ENTRY_NONCE_ACTION, 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'code' => 'FORBIDDEN', 'message' => __( 'Not allowed.', 'alpineconsent' ) ), 403 ); } $names = isset( $_POST['names'] ) && is_array( $_POST['names'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['names'] ) ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified above via check_ajax_referer(). if ( empty( $names ) ) { wp_send_json_error( array( 'code' => 'VALIDATION_ERROR', 'message' => __( 'No cookies specified.', 'alpineconsent' ) ), 400 ); } wp_send_json_success( $this->delete_entries_and_build_response( self::COOKIE_OPTION_NAME, $names ) ); } /** * The form only submits { handle: category }. This merges that * into the existing discovered-scripts structure rather than * replacing it wholesale, so src/suggested_category/first_seen — * none of which the form re-submits — survive a save. * * WordPress runs a registered option's sanitize_callback on *every* * update_option() call for that option, not just a Settings API * form submission — including class-blocker.php's own internal * writes from maybe_discover(), and this class's own * discover_from_html()/discover_cookies_from_response(), which all * pass the *entire* discovered array (handle => {src, category, * ...}), not {handle: category}. * * Real, live-reported regression (found by the user, reproduced * step by step against a real site): the ORIGINAL fix here * (`is_array( $value ) ? continue` — correctly avoiding casting an * array to the literal string "Array" and treating it as a * submitted category) went one step too far by then unconditionally * `return $existing;` — the option's value re-read from the DB * *inside this very callback*, i.e. the value from BEFORE this * update_option() call. For a real Settings API form submission * that's correct (nothing else changed it). But `admin_init` (where * register_setting() hooks this callback) has ALREADY fired by the * time an admin-post.php handler like handle_scan_request() runs — * so every update_option() call inside discover_from_html()/ * discover_cookies_from_response() also passes through this exact * sanitize callback, which silently discarded the caller's own * freshly-built $input (with its newly-discovered entries) and * returned the stale pre-scan value instead. "Scan site now" could * therefore never actually persist a newly-found raw script or * cookie — passive front-end discovery (class-blocker.php's own * maybe_discover(), which runs on a real visitor's page load, where * admin_init never fires) was never affected, which is exactly why * this went unnoticed: every *enqueued* script ever discovered this * way looked fine, only an admin-triggered scan's own new * discoveries silently vanished. * * Original fix: detect which shape $input actually is, and let a * raw internal write (built from the caller's OWN get_option() read, * immediately before this same update_option() call) through as-is, * skipping the merge-into-$existing logic below. * * WordPress.org Plugins Team review (2026-10-06): that shape check * (every value an array => trust it completely) was itself a real * sanitize-bypass — any options.php submission from an * authenticated admin that happens to nest one array value skips * category-whitelist validation entirely, writing arbitrary content * straight into the option. Fixed properly: sanitize() now ALWAYS * runs the real merge/validate logic below, unconditionally, and * the three legitimate internal raw-discovery call sites * (class-blocker.php's maybe_discover(), and this file's own * discover_from_html()/discover_cookies_from_response()/ * discover_cookies_from_active_plugins()) go through * write_discovered_handles()/write_discovered_cookies() instead, * which bypass this callback entirely by removing it from the * sanitize_option_* filter around their own update_option() call — * see those methods' own comments. */ public static function sanitize( $input ) { $input = is_array( $input ) ? $input : array(); $existing = get_option( AlpineConsent_Blocker::OPTION_NAME, array() ); $valid = array_keys( self::CATEGORY_LABELS ); // Iterates the *submission*, not every known handle — a handle // discovered by some other visitor between this page loading // and the admin clicking Save (rare, but real) has no field in // $input at all, and must survive untouched rather than being // silently reset to uncategorized. foreach ( $input as $handle => $value ) { if ( ! isset( $existing[ $handle ] ) ) { continue; // not a real discovered handle — ignore } // is_scalar() guard: a genuine category submission is // always a plain string, but $value can now be anything — // including an array, from a crafted options.php submission // trying to pass as a raw discovery write (see this // method's own comment above). (string) $value on an array // raises a PHP warning for no benefit — sanitize_key( '' ) // below already resolves to the same safe '' outcome. $submitted = is_scalar( $value ) ? sanitize_key( (string) $value ) : ''; // Real bug reported directly: explicitly choosing "—" and // saving looked like it silently did nothing whenever a // real suggestion existed for that script (Contact Form 7, // in the report) — because this used to store `null` here, // exactly the same value a BRAND NEW, never-reviewed handle // already starts with (discover_from_html()/maybe_discover() // both set 'category' => null on first discovery). Since // render_category_select() falls back to showing the // suggestion pre-selected whenever `category` is that same // `null`, a real, explicit "no category" choice was // visually indistinguishable from "never looked at yet" — // the dropdown re-selected the suggestion on the very next // page load, looking exactly like the save had failed, even // though the stored value was already correct for every // other purpose (blocking, category counts/filters — see // effective_category()/category_for_handle(), both already // treat '' exactly like null). Storing '' here instead of // null marks a real, INTENTIONAL "no category" choice in // the DB, distinct from "untouched" — giving // render_category_select() something real to tell them // apart by. See its own updated comment. $existing[ $handle ]['category'] = in_array( $submitted, $valid, true ) ? $submitted : ''; } return $existing; } /** * Same shape and same bug-avoidance reasoning as sanitize() above — * a separate method (not a shared one parameterized by option name) * only because the two options' entry shapes have already started * to differ (a cookie entry has no `src`) and are likely to keep * diverging, e.g. once a scan actually records the matched * database platform/description alongside suggested_category. */ public static function sanitize_cookies( $input ) { $input = is_array( $input ) ? $input : array(); $existing = get_option( self::COOKIE_OPTION_NAME, array() ); $valid = array_keys( self::CATEGORY_LABELS ); foreach ( $input as $name => $value ) { if ( ! isset( $existing[ $name ] ) ) { continue; } $submitted = is_scalar( $value ) ? sanitize_key( (string) $value ) : ''; // Same real bug/fix as sanitize() above — '' marks an // explicit, intentional "no category" choice, distinct // from a brand-new cookie's own initial `null`. $existing[ $name ]['category'] = in_array( $submitted, $valid, true ) ? $submitted : ''; } return $existing; } /** * The internal discovery writers' own entry point — bypasses * sanitize() entirely rather than relying on it to recognize a raw * write by shape (the exact thing a crafted options.php submission * could spoof; see sanitize()'s own comment on the WordPress.org * review that caught it). Safe to call from a request where * admin_init never fired (class-blocker.php's own front-end * maybe_discover()) — remove_filter() on a tag nothing is hooked to * yet is simply a no-op. */ public static function write_discovered_handles( array $discovered ) { self::write_raw_discovery_data( AlpineConsent_Blocker::OPTION_NAME, $discovered ); } public static function write_discovered_cookies( array $discovered ) { self::write_raw_discovery_data( self::COOKIE_OPTION_NAME, $discovered ); } /** * Shared by the two wrappers above AND delete_entries_and_build_ * response() below — a delete is also a write of the full, * already-correct {handle: {src, category, ...}} shape (just with * some keys removed), the same shape every other raw discovery * write uses, and needs the exact same bypass. */ private static function write_raw_discovery_data( $option_name, array $value ) { $sanitize_method = ( AlpineConsent_Blocker::OPTION_NAME === $option_name ) ? 'sanitize' : 'sanitize_cookies'; self::update_option_bypassing_sanitize( $option_name, $value, $sanitize_method ); } /** * register_setting() attaches sanitize()/sanitize_cookies() to the * sanitize_option_{$option_name} filter, and WordPress core runs * that filter on EVERY update_option() for a registered option, not * just a real form submission — there's no call-path signal that * distinguishes "this plugin's own trusted internal write" from * "something coming through options.php." Removing the exact same * static callback around just this one write, then re-adding it * immediately after, is what lets this plugin keep treating its own * writes as pre-validated without ever having to guess from $input's * shape again. */ private static function update_option_bypassing_sanitize( $option_name, $value, $sanitize_method ) { $callback = array( __CLASS__, $sanitize_method ); remove_filter( "sanitize_option_{$option_name}", $callback ); update_option( $option_name, $value ); add_filter( "sanitize_option_{$option_name}", $callback ); } public function handle_scan_request() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Not allowed.', 'alpineconsent' ) ); } check_admin_referer( 'alpineconsent_scan' ); // AlpineConsent#260 item 1 — each page gets its own request (and // its own Set-Cookie headers read separately) since different // pages can load different scripts/cookies; one page failing to // fetch (is_wp_error()) just means that one page contributes // nothing, not that the whole scan aborts. foreach ( $this->pages_to_scan() as $url ) { $response = wp_remote_get( $url, array( 'timeout' => 10 ) ); if ( is_wp_error( $response ) ) { continue; } $this->discover_from_html( wp_remote_retrieve_body( $response ) ); $this->discover_cookies_from_response( $response ); } // Independent of the responses above: a known plugin's own // well-documented cookies (AlpineConsent#272) — most are set by // JavaScript in the visitor's browser, never in this response's // headers, so the scan above alone would never find them. $this->discover_cookies_from_active_plugins(); wp_safe_redirect( add_query_arg( array( 'page' => 'alpineconsent', 'scanned' => '1', 'tab' => 'scripts', ), // A top-level menu page (add_menu_page(), not // add_options_page()) lives under admin.php, not // options-general.php. admin_url( 'admin.php' ) ) ); exit; } /** * Real URLs to scan: the homepage first, then up to * self::MAX_PAGES_TO_SCAN - 1 more of the site's own published * pages/posts. AlpineConsent#260 item 1. Enumerated directly via * get_posts() rather than scraping out of the homepage's * own HTML the way the public web scanner's own multi-page crawl * does (AlpineConsent#249) — running *inside* WordPress means this * plugin already has a complete, reliable list of every published * page/post, no guessing at what's linked from the homepage (which * a nav menu might not even fully cover) required. */ private function pages_to_scan() { $urls = array( home_url( '/' ) ); $posts = get_posts( array( 'post_type' => array( 'page', 'post' ), 'post_status' => 'publish', 'posts_per_page' => self::MAX_PAGES_TO_SCAN - 1, 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids', ) ); foreach ( $posts as $post_id ) { $permalink = get_permalink( $post_id ); // A static front page (show_on_front = 'page') resolves its // own get_permalink() to home_url('/') too — already in // $urls from above, so this skips it rather than scanning // the homepage twice and wasting a page out of the budget. if ( $permalink && ! in_array( $permalink, $urls, true ) ) { $urls[] = $permalink; } } return $urls; } /** * Looks for WordPress's own id="{handle}-js" convention on rendered * script tags first — the same convention class-blocker.php * itself writes and relies on, so anything found that way is * guaranteed to be something that filter can actually act on (hold * until consent, via the script_loader_tag filter, which only ever * fires for a script WordPress itself enqueued and is printing). * * AlpineConsent#260 — real gap found live against a real Divi * install (gamasiabco.com): a hand-authored script tag (src="...") * directly into a shortcode/page-builder module's own output (Divi * renders every page through its own shortcode system — this isn't * one special module, it's how the whole site is built) never gets * a WordPress handle at all, so it used to be silently skipped here * entirely — invisible to the site owner, with no way to even see * it exists, let alone categorize it. A script like that now still * gets discovered, under a synthetic "raw:" handle derived from its * own URL (stable across repeat scans, namespaced so it can never * collide with a real WordPress handle) — so it's visible, gets a * real category suggestion the same as any other script, and an * admin can manually flag it as tracking. What this does NOT do — * a real, separate limitation, not solved here — is actually BLOCK * it: script_loader_tag never fires for a raw tag WordPress didn't * print itself, so a "raw:" entry can be categorized but not yet * held before it executes. That needs a different mechanism (a * full-page output buffer rewriting every real script tag, not * just enqueued ones) — filed as its own follow-up rather than * bolted on here, since it's a materially bigger, riskier change to * class-blocker.php than this discovery fix. */ private function discover_from_html( $html ) { if ( ! preg_match_all( '/]*>/i', $html, $tag_matches ) ) { return; } $discovered = get_option( AlpineConsent_Blocker::OPTION_NAME, array() ); $changed = false; // One timestamp for this whole scan, not one gmdate() call per // script — every handle "Scan site now" sees this run was // equally confirmed present at the same moment. $alpineconsent_now = gmdate( 'c' ); foreach ( $tag_matches[0] as $tag ) { if ( ! preg_match( '/\bsrc=["\']([^"\']+)["\']/i', $tag, $src_match ) ) { continue; } // Real bug found reviewing a live scan report: a raw regex // capture of an HTML attribute is still HTML-ENCODED text, // not a real URL — WordPress's own esc_url() (used // everywhere a theme/page-builder prints a src="...") HTML- // entity-encodes every "&" as "&", so a multi-param // URL (e.g. a Google Maps embed with ?key=...&callback=...) // got stored with a literal "&" still inside it. That // silently corrupts the URL the moment anything treats "#" // as a fragment separator (or the query string) — visibly, // this is exactly what turned one real report's Google Maps // URL into "...js?key&&ver=3#038;callback=initMap" instead // of the real, working URL. $src = html_entity_decode( $src_match[1], ENT_QUOTES | ENT_HTML5 ); if ( preg_match( '/\bid=["\']([^"\']+)-js["\']/i', $tag, $id_match ) ) { $handle = $id_match[1]; } else { $handle = self::synthetic_handle_for_src( $src ); } if ( isset( $discovered[ $handle ] ) ) { // Real gap, found live: "Scan site now" used to only // ever ADD brand-new handles here, never refresh an // already-known one's suggestion — so a script scanned // before AlpineConsent_Suggestions::suggest() learned to // recognize it (this exact classifier grew a lot in // v0.6.4 — see class-suggestions.php's own top comment) // kept a stale/null suggestion forever, no matter how // many times the site owner clicked scan again. Re-runs // the suggestion against the CURRENT classifier on every // scan; deliberately never touches `category` (the site // owner's own manual choice, if any) or `first_seen`. // // `last_seen`, though, IS always bumped here — this is // the one place that's true, deliberately never on // class-blocker.php's own live, per-page-load // maybe_discover() (see that method's own comment on // why). An explicit "Scan site now" click seeing this // handle again is exactly the staleness signal the // per-row/bulk delete tools below read. $fresh = AlpineConsent_Suggestions::suggest( $handle, $discovered[ $handle ]['src'] ); if ( $fresh !== $discovered[ $handle ]['suggested_category'] ) { $discovered[ $handle ]['suggested_category'] = $fresh; } $discovered[ $handle ]['last_seen'] = $alpineconsent_now; $changed = true; continue; } $discovered[ $handle ] = array( 'src' => $src, 'category' => null, 'suggested_category' => AlpineConsent_Suggestions::suggest( $handle, $src ), 'first_seen' => $alpineconsent_now, 'last_seen' => $alpineconsent_now, ); $changed = true; } if ( $changed ) { self::write_discovered_handles( $discovered ); } } /** * A stable, readable synthetic handle for a raw script tag (src="...") * with no WordPress-enqueued id="{handle}-js" — namespaced with a * "raw:" prefix that a real wp_enqueue_script() handle can never * collide with (WordPress handles are plain slugs, never containing * a colon), and deterministic (same URL -> same handle every scan) * so a repeat "Scan site now" refreshes the same entry instead * of creating a duplicate every time. */ private static function synthetic_handle_for_src( $src ) { $host = wp_parse_url( $src, PHP_URL_HOST ); $host = $host ? $host : 'unknown-host'; return 'raw:' . $host . '-' . substr( md5( $src ), 0, 8 ); } /** * Reads Set-Cookie header(s) off the same wp_remote_get() response * discover_from_html() already used — no second network call — and * records each cookie *name* against AlpineConsent_Cookie_Database. * Page-level only: a Set-Cookie header says a cookie was set on * this response, never which script (if any) caused it, so there's * no `src` to store here the way discover_from_html() stores one * per script. */ private function discover_cookies_from_response( $response ) { $names = self::extract_set_cookie_names( $response ); if ( empty( $names ) ) { return; } $discovered = get_option( self::COOKIE_OPTION_NAME, array() ); $changed = false; $alpineconsent_now = gmdate( 'c' ); foreach ( $names as $name ) { // Deliberately no database lookup at all for a generic name — // even a real match would be a *different* platform's data // than the one that actually decided this category, exactly // the mismatch GENERIC_NECESSARY_COOKIE_NAMES' own docblock // explains. This branch's suggestion is a fixed constant, so // there's nothing for a rescan to ever refresh here. if ( in_array( strtolower( $name ), self::GENERIC_NECESSARY_COOKIE_NAMES, true ) ) { $fresh_suggestion = 'functional'; $fresh_match = null; } else { $fresh_match = AlpineConsent_Cookie_Database::lookup( $name ); $fresh_suggestion = $fresh_match ? $fresh_match['category'] : null; } if ( isset( $discovered[ $name ] ) ) { // Same real gap/fix as discover_from_html() above — a // rescan now refreshes an already-known cookie's own // suggestion too (the cookie database itself can grow — // see bin/sync-cookie-database.sh — independently of // when this cookie was first seen). Never touches // `category` or `first_seen`. `last_seen` IS always // bumped, though — same reasoning as discover_from_html()'s // own comment: this only ever runs from an explicit // "Scan site now" click, never live traffic. if ( $fresh_suggestion !== $discovered[ $name ]['suggested_category'] || $fresh_match !== $discovered[ $name ]['db_match'] ) { $discovered[ $name ]['suggested_category'] = $fresh_suggestion; $discovered[ $name ]['db_match'] = $fresh_match; } $discovered[ $name ]['last_seen'] = $alpineconsent_now; $changed = true; continue; } $discovered[ $name ] = array( 'category' => null, 'suggested_category' => $fresh_suggestion, 'db_match' => $fresh_match, 'first_seen' => $alpineconsent_now, 'last_seen' => $alpineconsent_now, ); $changed = true; } if ( $changed ) { self::write_discovered_cookies( $discovered ); } } /** * AlpineConsent#272 — pre-populates the cookies a currently-active, * well-known plugin (Polylang, WPML, WooCommerce, ...) is documented * to set, exactly as if "Scan site now" had observed them. * Necessary because most of these are set by JavaScript in the * visitor's browser, never in the homepage response's headers * discover_cookies_from_response() reads — confirmed live scanning a * real Polylang site with a real browser-based scanner, which found * `pll_language`, a cookie this plugin's header-only scan could never * see. Same non-destructive merge as the two discover_*() methods * above: never touches an already-assigned `category` or the first * `first_seen` timestamp, only refreshes `suggested_category`/ * `db_match` in case AlpineConsent_Plugin_Cookies::KNOWN itself * changes in a future release. * * $known is injectable (defaults to the real * AlpineConsent_Plugin_Cookies::active_plugin_cookies()) purely so * tests can exercise the merge logic without needing a real Polylang/ * WPML/WooCommerce active in the test environment. */ private function discover_cookies_from_active_plugins( $known = null ) { if ( null === $known ) { $known = AlpineConsent_Plugin_Cookies::active_plugin_cookies(); } if ( empty( $known ) ) { return; } $discovered = get_option( self::COOKIE_OPTION_NAME, array() ); $changed = false; $alpineconsent_now = gmdate( 'c' ); foreach ( $known as $cookie ) { $name = $cookie['name']; $suggestion = $cookie['category']; $match = $cookie['db_match']; if ( isset( $discovered[ $name ] ) ) { if ( $suggestion !== $discovered[ $name ]['suggested_category'] || $match !== $discovered[ $name ]['db_match'] ) { $discovered[ $name ]['suggested_category'] = $suggestion; $discovered[ $name ]['db_match'] = $match; } // last_seen always bumped — same "explicit scan, not // live traffic" reasoning as the two discover_*() // methods above. $discovered[ $name ]['last_seen'] = $alpineconsent_now; $changed = true; continue; } $discovered[ $name ] = array( 'category' => null, 'suggested_category' => $suggestion, 'db_match' => $match, 'first_seen' => $alpineconsent_now, 'last_seen' => $alpineconsent_now, ); $changed = true; } if ( $changed ) { self::write_discovered_cookies( $discovered ); } } /** * WordPress's own header dictionary * (Requests_Utility_CaseInsensitiveDictionary, or its * WpOrg\Requests-namespaced equivalent on newer WP/PHP) collapses * multiple same-name headers into one comma-joined string when * accessed the plain way — wp_remote_retrieve_header() included. * That's unsafe for Set-Cookie specifically: a real cookie value * can itself contain a comma (e.g. an Expires date, * "Expires=Wed, 21 Oct 2026..."), so blindly splitting a * comma-joined blob back apart is ambiguous. Its getValues() * method returns the original, un-joined array instead — used here * when available, with a same-shape fallback for anything that * somehow lacks it, so a header this can't safely parse is skipped * rather than mis-split. */ private static function extract_set_cookie_names( $response ) { $headers = wp_remote_retrieve_headers( $response ); $raw = array(); if ( is_object( $headers ) && method_exists( $headers, 'getValues' ) ) { $raw = (array) $headers->getValues( 'set-cookie' ); } else { $single = wp_remote_retrieve_header( $response, 'set-cookie' ); if ( $single ) { $raw = is_array( $single ) ? $single : array( $single ); } } $names = array(); foreach ( $raw as $line ) { if ( preg_match( '/^\s*([^=;\s]+)\s*=/', (string) $line, $match ) ) { $names[] = $match[1]; } } return array_unique( $names ); } /** * The text for every filter pill, keyed by the same value its own * `data-category` attribute uses ('' for "All", '__uncategorized__' * for that sentinel, else a real CATEGORY_LABELS key). Pulled out of * render_table_toolbar() so the AJAX settings-save handler can * recompute fresh, already-translated pill text after a save * without a page reload — see process_save_settings_ajax() — while * render_table_toolbar() itself keeps rendering the exact same * markup it always has. */ private function toolbar_pill_labels( $counts_by_category, $uncategorized_count = 0, $show_uncategorized_filter = false ) { // AlpineConsent#364 — $uncategorized_count folds into the "All" // total too: $counts_by_category only ever counts entries with a // real, known category (see counts_by_effective_category()), so // without this an uncategorized entry was silently missing from // "All (%d)" itself, not just from having nowhere else to filter // to. $total = array_sum( $counts_by_category ) + $uncategorized_count; $labels = array( /* translators: %d: total row count */ '' => sprintf( __( 'All (%d)', 'alpineconsent' ), $total ), ); foreach ( self::CATEGORY_LABELS as $key => $label ) { $labels[ $key ] = $label . ' (' . (int) ( isset( $counts_by_category[ $key ] ) ? $counts_by_category[ $key ] : 0 ) . ')'; } if ( $show_uncategorized_filter ) { /* translators: %d: uncategorized row count */ $labels['__uncategorized__'] = sprintf( __( 'Uncategorized (%d)', 'alpineconsent' ), $uncategorized_count ); } return $labels; } /** * Search box + category filter pills, shared markup for both the * Scripts and Cookies tables (initTable() in render_page()'s own * inline script wires up whichever table it's rendered next to, scoped * by the shared [data-alpineconsent-table] wrapper — no per-table * JS needed here, one generic initializer handles both). Filter * pill counts reflect each row's *effective* category (assigned, * falling back to suggested) computed once at page render — they * don't live-update if a select is changed client-side before * saving (except after an AJAX settings save, see * toolbar_pill_labels()'s own docblock above). */ private function render_table_toolbar( $counts_by_category, $uncategorized_count = 0, $show_uncategorized_filter = false ) { $pill_labels = $this->toolbar_pill_labels( $counts_by_category, $uncategorized_count, $show_uncategorized_filter ); ?>
$label ) : ?>
, shared by both tables. * Defaults to the *suggested* category when nothing's been * assigned yet — previously defaulted to "—" even with a real * suggestion sitting right next to it in the Suggested column, * so confirming a correct suggestion meant re-picking it from the * dropdown by hand instead of just hitting Save. An admin who * disagrees still overrides it exactly as before; this only * changes what happens when they do nothing. * * Real bug reported directly, fixed alongside sanitize()/ * sanitize_cookies() above: `null` here means "never touched by * an admin at all" (discover_from_html()/maybe_discover()'s own * initial value) and still falls back to the suggestion below — * but `''` (an empty string, distinct from null) now means "an * admin explicitly chose '—' and saved," and must NOT fall back * to the suggestion, or a deliberate "no category" choice for a * script that happens to have a real suggestion (Contact Form 7, * in the report) would re-select that suggestion on every reload — * indistinguishable from the save having silently failed. */ private function render_category_select( $option_name, $key, $entry ) { $category = isset( $entry['category'] ) ? $entry['category'] : null; if ( '' === $category ) { $effective = ''; } elseif ( ! empty( $category ) ) { $effective = $category; } else { $effective = empty( $entry['suggested_category'] ) ? '' : $entry['suggested_category']; } ?> , extracted so it can be rendered identically whether * a script is nested under a provider group's header row, shown on * its own as a singleton provider (see the $in_group callers below * — a provider with only one script gets no collapsible header at * all, so it needs its own real identity right here), or shown as a * provider-less script (see * AlpineConsent_Suggestions::group_by_provider()). Same per-row * category is_raw_script_handle( $handle ) ) : ?>


— render_category_select( AlpineConsent_Blocker::OPTION_NAME, $handle, $entry ); ?> —
above the WHOLE table, describing content most of which * starts collapsed and out of view — the same gap the website's own * scan report already solved for (ColumnHeaderRow in * ScanReportView.tsx). Rendered instead right where it's actually * relevant: once above the flat/"Uncategorized"/"Other" block's own * rows, and once inside each collapsible group's own children — * never disconnected from the rows it describes. above now * carries only the "select all" checkbox; this is the table's one * real set of column s. $in_group mirrors render_script_row()'s * own param exactly, since this row needs to collapse/expand in * lockstep with its own group's other children. */ private function render_column_header_row( $in_group = false ) { ?> data-provider-child data-collapsed="1" hidden > content — the provider * groups, the flat Other/Uncategorized split, and every row in * between. Extracted out of render_page() (AlpineConsent#385) so * process_save_settings_ajax() can re-render the exact same markup * after a category is saved via AJAX: a row's data-category * attribute and its group membership (Other vs. Uncategorized, or a * named provider group) are only ever computed here, at render * time — without this, an AJAX save left both stale until a real * page reload, which is exactly the bug reported directly: "now * these should have moved to uncategorized, but stayed right there * until I refreshed the page." */ private function render_scripts_table_body( $discovered ) { $alpineconsent_block_raw_scripts_on = ! empty( AlpineConsent_General_Settings::get()['block_raw_scripts'] ); ?> 1 ) { $alpineconsent_collapsible_groups[] = $alpineconsent_group; } else { $alpineconsent_flat_handles[] = $alpineconsent_group['handles'][0]; } } $alpineconsent_flat_handles = array_merge( $alpineconsent_flat_handles, $alpineconsent_grouped['ungrouped'] ); // AlpineConsent#364 follow-up — raised directly: the flat/ // "Other" block mixed scripts that already have a real // category assigned (or suggested) with ones that have // NONE at all, with nothing telling those two apart — // exactly the distinction the "Uncategorized" filter pill // above already draws. Split into two real groups instead // of one, so a script still needing a category decision is // never sitting unmarked next to one that's already done. $alpineconsent_flat_uncategorized = array(); $alpineconsent_flat_other = array(); foreach ( $alpineconsent_flat_handles as $alpineconsent_flat_handle ) { if ( '' === $this->effective_category( $discovered[ $alpineconsent_flat_handle ] ) ) { $alpineconsent_flat_uncategorized[] = $alpineconsent_flat_handle; } else { $alpineconsent_flat_other[] = $alpineconsent_flat_handle; } } ?> render_provider_header_row( $alpineconsent_group['provider'], $alpineconsent_group['description'], count( $alpineconsent_group['handles'] ) ); $this->render_column_header_row( true ); ?> render_script_row( $handle, $discovered[ $handle ], $alpineconsent_block_raw_scripts_on, true ); ?> render_provider_header_row( $alpineconsent_flat_label, '', count( $alpineconsent_flat_group_handles ), false ); $this->render_column_header_row( true ); ?> render_script_row( $handle, $discovered[ $handle ], $alpineconsent_block_raw_scripts_on, true, true ); ?> $entry ) : ?>
— render_category_select( self::COOKIE_OPTION_NAME, $name, $entry ); ?>

effective_category( $entry ); if ( isset( $counts[ $category ] ) ) { ++$counts[ $category ]; } } return $counts; } // AlpineConsent#364 — counts_by_effective_category() above only // counts entries whose effective category is a real, known // CATEGORY_LABELS key, so an uncategorized entry (effective_category() // returns '') was never counted anywhere at all — needed both for // the "Uncategorized" filter pill's own count and to fix "All (%d)" // itself, which was silently undercounting whenever any script had // no assigned or suggested category. public function count_uncategorized( $discovered ) { $count = 0; foreach ( $discovered as $entry ) { if ( '' === $this->effective_category( $entry ) ) { ++$count; } } return $count; } // The "raw:" prefix synthetic_handle_for_src() gives a hardcoded, // non-enqueued script — see discover_from_html()'s own docblock for // why such an entry is discoverable/categorizable but not yet // blockable. Public for the same direct-unit-testability reason as // effective_category() above. public function is_raw_script_handle( $handle ) { return 0 === strpos( (string) $handle, 'raw:' ); } public function has_raw_script_entries( $discovered ) { foreach ( array_keys( $discovered ) as $handle ) { if ( $this->is_raw_script_handle( $handle ) ) { return true; } } return false; } /** * AlpineConsent#291/#292 follow-up — real gap raised directly by * the user ("if it can never detect anything, why do we have it?"): * this plugin only ever discovers a cookie via a Set-Cookie HTTP * response header (class-cookie-database.php's own top comment) — * most analytics/marketing cookies are set by client-side * JavaScript instead, invisible to a plain wp_remote_get(). This * gives the Cookies tab real value even then: for every already- * discovered SCRIPT with a resolved provider * (AlpineConsent_Suggestions::describe()), look up the cookies that * provider is publicly documented to use * (AlpineConsent_Cookie_Database::lookup_by_platform()) — the same * "known for this provider, not necessarily observed" signal * backend/src/utils/scan.js's own buildPredictedCookies() already * gives the website's scanner. * * Public for direct unit-testability, same reasoning as * effective_category()/is_raw_script_handle() above. * * @param array $discovered AlpineConsent_Blocker::OPTION_NAME shape. * @param array $discovered_cookies AlpineConsent_Admin::COOKIE_OPTION_NAME shape — already-observed names are excluded, same as buildPredictedCookies()'s own observedNames exclusion. * @return array[] Each: { cookie, platform, category, description, retention_period, data_controller, privacy_link, predicted_for }. */ public function predicted_cookies_for_scripts( $discovered, $discovered_cookies = array() ) { return AlpineConsent_Cookie_Database::predicted_cookies_for_scripts( $discovered, $discovered_cookies ); } /** * AlpineConsent#328 — shown above the tabs (not inside one of * them), since it's meant to be the first thing an admin sees * regardless of which tab they land on, with each unfinished item * linking straight to the tab that fixes it. Deliberately not a * per-tab widget — see AlpineConsent_Setup_Score's own docblock * for the full "not a compliance score" framing this depends on. */ private function render_setup_score() { $result = AlpineConsent_Setup_Score::compute_for_site(); $score = $result['score']; $band = $result['band']; $breakdown = $result['breakdown']; $settings_url = add_query_arg( array( 'page' => 'alpineconsent', 'tab' => 'settings' ), admin_url( 'admin.php' ) ); $scripts_url = add_query_arg( array( 'page' => 'alpineconsent', 'tab' => 'scripts' ), admin_url( 'admin.php' ) ); $legal_url = add_query_arg( array( 'page' => 'alpineconsent', 'tab' => 'legal' ), admin_url( 'admin.php' ) ); $items = array( array( 'done' => $breakdown['banner'] >= AlpineConsent_Setup_Score::WEIGHT_BANNER, 'text' => __( 'Enable the consent banner', 'alpineconsent' ), // Real bug, reported directly: this used to point at the // Banner tab (layout/text styling) — the actual "Show the // consent banner to visitors" checkbox this item is about // lives in render_behavior_fields(), under Settings. 'url' => $settings_url, ), array( 'done' => $breakdown['categorization'] >= AlpineConsent_Setup_Score::WEIGHT_CATEGORIZATION, 'text' => __( 'Categorize every detected script and cookie', 'alpineconsent' ), 'url' => $scripts_url, ), array( 'done' => $breakdown['company_info'] >= AlpineConsent_Setup_Score::WEIGHT_COMPANY_INFO, 'text' => __( 'Fill in your company & legal details', 'alpineconsent' ), 'url' => $settings_url, ), array( 'done' => $breakdown['policy_page'] >= AlpineConsent_Setup_Score::WEIGHT_PER_LEGAL_PAGE, 'text' => __( 'Publish your Cookie Policy page', 'alpineconsent' ), 'url' => $legal_url, ), array( 'done' => $breakdown['legal_notice_page'] >= AlpineConsent_Setup_Score::WEIGHT_PER_LEGAL_PAGE, 'text' => __( 'Publish your Legal Notice page', 'alpineconsent' ), 'url' => $legal_url, ), ); ?>
/100

AlpineConsent_Legal_Content_Format::html_to_editable( AlpineConsent_Policy_Page::build_html( $discovered, $discovered_cookies, $alpineconsent_legal_company, true ) ), 'legal' => AlpineConsent_Legal_Content_Format::html_to_editable( AlpineConsent_Legal_Notice_Page::build_html( $alpineconsent_legal_company ) ), 'privacy_section' => AlpineConsent_Legal_Content_Format::html_to_editable( AlpineConsent_Privacy_Section::build_html( $discovered, $discovered_cookies, $alpineconsent_legal_company, true ) ), ); $alpineconsent_legal_field_labels = array( 'policy' => __( 'Cookie Policy', 'alpineconsent' ), 'legal' => __( 'Legal Notice', 'alpineconsent' ), 'privacy_section' => __( 'Privacy Policy — cookies section', 'alpineconsent' ), ); $alpineconsent_legal_shortcodes = array( 'policy' => AlpineConsent_Policy_Page::SHORTCODE, 'legal' => AlpineConsent_Legal_Notice_Page::SHORTCODE, 'privacy_section' => AlpineConsent_Privacy_Section::SHORTCODE, ); $alpineconsent_legal_overrides = AlpineConsent_Legal_Content_Overrides::get(); ?>

Installed Plugins. ?> v
render_setup_score(); ?>

%2$s

', esc_attr( $alpineconsent_page_notice[0] ), esc_html( $alpineconsent_page_notice[1] ) ); } } } ?> — nesting it inside the settings form below is invalid HTML, and it posts to a different handler (admin-post.php) entirely. */ ?>

banner_settings->render_fields(); ?>

has_raw_script_entries( $discovered ) ) : ?>

array( 'href' => array() ) ) ), '' . esc_html__( 'Settings', 'alpineconsent' ) . '' ); ?>

render_table_toolbar( $this->counts_by_effective_category( $discovered ), $this->count_uncategorized( $discovered ), true ); ?> now carries only the "select all" checkbox so the table keeps a real column count without repeating labels most of the table starts collapsed under. ?> render_scripts_table_body( $discovered ); ?>

render_table_toolbar( $this->counts_by_effective_category( $discovered_cookies ), $this->count_uncategorized( $discovered_cookies ) ); ?> render_cookies_table_body( $discovered_cookies ); ?>
predicted_cookies_for_scripts( $discovered, $discovered_cookies ); if ( ! empty( $alpineconsent_predicted_cookies ) ) : ?>

general_settings->render_behavior_fields(); ?>

general_settings->render_company_fields(); ?>
. Encryption happens entirely in // legal-backup.js, in this browser; nothing plaintext is // ever sent here. ?>
render_legal_backup_fields(); ?>
(posts to // admin-post.php, same reasoning as the "Scan site now" // form above), placed last on this tab and visually set // apart with its own note: license activation has nothing // to do with any of the settings above it — it only tells // this site which plan it's on, and never touches the // Behavior toggles or the Company & legal details above. ?>

' . esc_html( $connection['account_email'] ) . '', '' . esc_html( ucfirst( $connection['plan'] ) ) . '' // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- both operands already esc_html()'d above ); ?>

, so they must sit OUTSIDE the * options.php settings form above — a nested
is invalid * HTML and the browser drops the inner tag, which would make * their buttons submit the settings form instead. All three * live together under their own "Legal pages" tab (grouped * here directly at the user's request — previously the Cookie * Policy panel sat on the Cookies tab and Legal Notice/privacy * section sat on Settings, with nothing tying the three * together for an admin trying to find them). */ ?>

__( 'Scanning… this can take several seconds.', 'alpineconsent' ), 'aiTranslateNonce' => wp_create_nonce( AlpineConsent_AI_Translation::NONCE_ACTION ), 'aiTranslateKeys' => array_merge( array( 'title', 'description' ), AlpineConsent_Banner_Settings::STRING_KEYS ), 'aiAsking' => __( 'Asking AI for a suggestion…', 'alpineconsent' ), 'aiFilled' => __( 'Suggestion filled in — review it, then click Save Changes.', 'alpineconsent' ), 'aiError' => __( 'Could not get a suggestion — please try again.', 'alpineconsent' ), 'aiNetworkError' => __( 'Could not reach the server — please try again.', 'alpineconsent' ), 'stringsDictionary' => AlpineConsent_Strings::DICTIONARY, 'noDictionaryEntry' => __( "We don't have a built-in translation for this language yet — nothing was filled in.", 'alpineconsent' ), 'dictFilled' => __( 'Empty fields filled in from our built-in dictionary — review it, then click Save Changes.', 'alpineconsent' ), 'dictNothingToFill' => __( 'Nothing to fill in — every field on this tab already has text.', 'alpineconsent' ), ) ); // WordPress.org Plugins Team review (2026-10-09): this entire // block used to be a raw inline-script block echoed directly into the // page — flagged, correctly (see class-admin.php's own // enqueue_assets() for the shared virtual handle this now // attaches to). Content is byte-for-byte the same JS as // before, with the eleven points that used to read an inline // PHP echo of wp_json_encode(...) directly now reading // AlpineConsentAdminL10n's own properties (localized just // above) instead — nothing about the JS logic itself changed. wp_add_inline_script( 'alpineconsent-admin-inline', <<<'ALPINECONSENT_ADMIN_JS_EOT' ( function () { // One small generic wiring for a set of nav-tab links + the // panels they show/hide, reused as-is for both the top-level // tabs and the Banner tab's own "Settings"/"Preview" sub-tabs // below — same click/active-class/display-toggle behavior // either way, just scoped to a different attribute pair. // `onSwitch`, when given, fires with the newly-active tab's // own value — the top-level tabs use it (see below), the // three sub-tab tiers don't need it (see each call's own // comment). function wireTabs( tabAttr, panelAttr, onSwitch ) { var tabs = document.querySelectorAll( '.nav-tab[' + tabAttr + ']' ); var panels = document.querySelectorAll( '[' + panelAttr + ']' ); tabs.forEach( function ( tab ) { tab.addEventListener( 'click', function ( e ) { e.preventDefault(); var target = tab.getAttribute( tabAttr ); tabs.forEach( function ( t ) { t.classList.toggle( 'nav-tab-active', t === tab ); } ); panels.forEach( function ( p ) { p.style.display = p.getAttribute( panelAttr ) === target ? '' : 'none'; } ); if ( onSwitch ) { onSwitch( target ); } } ); } ); } // Real bug reported directly: switching the top-level tab is // purely client-side (no page navigation) — the URL's own // "?tab=" param, and every already-rendered form's own // "_wp_http_referer" hidden field (WordPress's own // settings_fields()/wp_nonce_field() bake this in from // $_SERVER['REQUEST_URI'] AT PAGE LOAD, not at submit time), // both stay frozen at whatever tab was active when the page // was first opened. Saving from a DIFFERENT tab than that one // (a real, easy thing to do — nothing about switching tabs // looks like it should matter) redirects back to the STALE // tab once the save completes, not the one just worked in. // Keeping both in sync on every tab click fixes this for // every form on the page — the scan button, the Settings API // form, and every admin-post.php form under Legal pages — not // just one of them. function syncActiveTabEverywhere( tab ) { try { var url = new URL( window.location.href ); url.searchParams.set( 'tab', tab ); window.history.replaceState( null, '', url ); } catch ( e ) { // Unsupported/unavailable History API — the page still // works, it just won't update the address bar. } document.querySelectorAll( 'input[name="_wp_http_referer"]' ).forEach( function ( input ) { try { var referrerUrl = new URL( input.value, window.location.origin ); referrerUrl.searchParams.set( 'tab', tab ); input.value = referrerUrl.pathname + referrerUrl.search; } catch ( e ) { // A malformed/unexpected referrer value — leave it // exactly as WordPress rendered it rather than risk // breaking that form's own redirect entirely. } } ); } wireTabs( 'data-alpineconsent-tab', 'data-alpineconsent-panel', syncActiveTabEverywhere ); wireTabs( 'data-alpineconsent-subtab', 'data-alpineconsent-subpanel' ); // "Button & banner text"'s own per-language sub-tabs — a // distinct attribute pair, not the one above: wireTabs()'s // querySelectorAll matches every element with that attribute // ANYWHERE on the page, so reusing data-alpineconsent-subtab // here would make clicking a language tab also toggle the // Banner tab's unrelated Settings/Preview sub-tabs. wireTabs( 'data-alpineconsent-banner-lang-subtab', 'data-alpineconsent-banner-lang-subpanel' ); // AlpineConsent#292 — the "Legal pages" tab's own per-language // sub-tabs. A fourth, distinct attribute pair, same reasoning // as the one above. wireTabs( 'data-alpineconsent-legal-lang-subtab', 'data-alpineconsent-legal-lang-subpanel' ); // One generic initializer for both the Scripts and Cookies // tables — search, category-filter pills, and bulk-apply — // scoped per [data-alpineconsent-table] wrapper so the two // tables' controls never cross-wire. Entirely client-side: // bulk-apply just sets visible