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( '/