maybe_upgrade_tables(); $this->init_wp_consent_api_support(); add_filter('cron_schedules', array($this, 'add_cron_schedules')); add_action(self::CRON_HOOK, array($this, 'run_scheduled_scan')); add_action(self::POLL_HOOK, array($this, 'run_scan_result_poll')); add_action('init', array($this, 'register_cookie_policy_block')); add_action('init', array($this, 'register_wp_consent_api_cookie_info'), 20); add_shortcode('acookies_preferences_link', array($this, 'render_preferences_link_shortcode')); add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets')); add_action('admin_init', array($this, 'register_settings')); add_action('admin_init', array($this, 'maybe_schedule_pending_scan_poll')); add_action('admin_init', array($this, 'maybe_redirect_to_onboarding')); add_action('admin_init', array($this, 'redirect_legacy_admin_slug')); add_action('admin_post_accomplice_cookies_run_scan', array($this, 'handle_manual_scan')); add_action('admin_post_acookies_disable_managed_scanner', array($this, 'handle_disable_managed_scanner')); add_action('admin_post_accomplice_cookies_refresh_scans', array($this, 'handle_refresh_scans')); add_action('admin_post_accomplice_cookies_review_cookie', array($this, 'handle_review_cookie')); add_action('admin_post_acookies_save_onboarding', array($this, 'handle_save_onboarding')); add_action('wp_ajax_accomplice_cookies_refresh_scans', array($this, 'handle_ajax_refresh_scans')); add_action('rest_api_init', array($this, 'register_rest_routes')); $settings = self::get_settings(); if (!empty($settings['banner_enabled'])) { add_action('wp_enqueue_scripts', array($this, 'print_consent_mode_defaults'), 0); add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets')); add_action('wp_body_open', array($this, 'render_server_banner_fallback'), 100); add_action('wp_footer', array($this, 'render_server_banner_fallback'), 5); add_filter('script_loader_tag', array($this, 'filter_managed_script_tag'), 10, 3); } add_action('update_option_' . self::OPTION_KEY, array($this, 'reschedule_after_settings_update'), 10, 2); if (function_exists('aco_fs') && is_object(aco_fs())) { foreach (array('after_license_activation', 'after_license_deactivation', 'after_license_change', 'after_account_plan_sync', 'after_account_delete') as $event) { aco_fs()->add_action($event, array($this, 'refresh_scanner_entitlement'), 10, 0); } } } public function refresh_scanner_entitlement() { // License and trial events also cover changes with the same license ID. // Keep the last token and all preferences until renewal succeeds. delete_option(ACookies_Scanner_Entitlement::CACHE_KEY); $settings = self::get_settings(); if (self::managed_scanner_is_enabled($settings)) { $this->ensure_managed_scanner_token(); } } private function init_wp_consent_api_support() { add_filter('wp_consent_api_registered_' . plugin_basename(ACCOMPLICE_COOKIES_FILE), '__return_true'); add_filter('wp_get_consent_type', array($this, 'wp_consent_api_consent_type')); } public function wp_consent_api_consent_type($consent_type) { return 'optin'; } public static function default_settings() { return array( 'scanner_url' => '', 'scanner_api_key' => '', 'managed_scanner_enabled' => false, 'scanner_terms_accepted_at' => '', 'installation_id' => '', 'scanner_access_token' => '', 'scanner_token_expires_at' => '', 'scan_recurrence' => 'manual', 'scan_sample_size' => ACookies_Scanner_Entitlement::resolve()['sample_default'], 'onboarding_complete' => false, 'banner_enabled' => false, 'consent_retention_days' => 30, 'script_rules' => array( array('match_type' => 'src_contains', 'match_value' => 'connect.facebook.net', 'category' => 'marketing'), array('match_type' => 'src_contains', 'match_value' => 'facebook.com/tr', 'category' => 'marketing'), ), 'default_language' => 'en_US', 'enabled_languages' => array_keys(accomplice_cookies_language_catalog()['locales']), 'translations' => array(), // Activation can call this method before WordPress loads plugin // translations. Keep persisted defaults language-neutral here. 'banner_title' => 'We use cookies', 'banner_text' => 'We use necessary cookies to run this site and optional cookies to improve analytics and marketing. Choose your preferences below.', 'banner_position' => 'bottom-right', 'banner_background_color' => '#ffffff', 'banner_text_color' => '#141414', 'banner_border_color' => '#d6d6d6', 'banner_border_width' => 0, 'banner_border_radius' => 8, 'button_style_mode' => function_exists('wp_is_block_theme') && wp_is_block_theme() ? 'theme' : 'custom', 'button_primary_background' => '#1f1f1f', 'button_primary_text' => '#ffffff', 'button_primary_border_color' => '#1f1f1f', 'button_primary_border_width' => 1, 'button_primary_hover_background' => '#333333', 'button_primary_hover_text' => '#ffffff', 'button_primary_hover_border_color' => '#333333', 'button_secondary_background' => '#ffffff', 'button_secondary_text' => '#1f1f1f', 'button_secondary_border_color' => '#1f1f1f', 'button_secondary_border_width' => 1, 'button_secondary_hover_background' => '#f2f2f2', 'button_secondary_hover_text' => '#1f1f1f', 'button_secondary_hover_border_color' => '#1f1f1f', 'button_border_color' => '#1f1f1f', 'button_border_radius' => 6, 'privacy_url' => '', 'policy_version' => '1', 'ga_measurement_id' => '', 'gtm_id' => '', 'google_consent_integration' => 'gtag', 'google_consent_debug' => false, 'google_banner_template' => false, 'google_allow_pre_consent' => false, 'label_required' => 'Required', 'label_analytics' => 'Analytics', 'label_marketing' => 'Marketing', 'label_preferences' => 'Preferences', ); } public function add_cron_schedules($schedules) { if (!isset($schedules['weekly'])) { $schedules['weekly'] = array( 'interval' => WEEK_IN_SECONDS, 'display' => __('Once Weekly', 'acookies'), ); } return $schedules; } public static function create_tables() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $charset = $wpdb->get_charset_collate(); $scans = self::table_name('scans'); $detected = self::table_name('detected'); $consents = self::table_name('consents'); dbDelta("CREATE TABLE {$scans} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, scanner_id varchar(191) DEFAULT '', status varchar(32) NOT NULL DEFAULT 'pending', site_url text NOT NULL, urls longtext NOT NULL, result longtext NULL, error text NULL, started_at datetime NOT NULL, completed_at datetime NULL, PRIMARY KEY (id), KEY scanner_id (scanner_id), KEY status (status) ) {$charset};"); dbDelta("CREATE TABLE {$detected} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, scan_id bigint(20) unsigned NOT NULL, name varchar(191) NOT NULL, domain varchar(191) NOT NULL DEFAULT '', path varchar(191) NOT NULL DEFAULT '', category varchar(32) NOT NULL DEFAULT 'unclassified', provider varchar(191) NOT NULL DEFAULT '', source_url text NOT NULL, script_src text NULL, descriptions longtext NULL, description_overrides longtext NULL, classification longtext NULL, superseded tinyint(1) NOT NULL DEFAULT 0, expires bigint(20) NULL, http_only tinyint(1) NOT NULL DEFAULT 0, secure tinyint(1) NOT NULL DEFAULT 0, same_site varchar(32) NOT NULL DEFAULT '', first_party tinyint(1) NOT NULL DEFAULT 0, reviewed tinyint(1) NOT NULL DEFAULT 0, created_at datetime NOT NULL, PRIMARY KEY (id), KEY scan_id (scan_id), KEY reviewed (reviewed), KEY category (category) ) {$charset};"); dbDelta("CREATE TABLE {$consents} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, consent_id varchar(64) NOT NULL, categories longtext NOT NULL, policy_version varchar(64) NOT NULL DEFAULT '', language_code varchar(16) NOT NULL DEFAULT '', ip_hash varchar(64) NOT NULL DEFAULT '', user_agent_hash varchar(64) NOT NULL DEFAULT '', created_at datetime NOT NULL, PRIMARY KEY (id), KEY consent_id (consent_id), KEY created_at (created_at) ) {$charset};"); } public static function table_name($suffix) { global $wpdb; return $wpdb->prefix . 'ac_cookies_' . $suffix; } public function maybe_upgrade_tables() { if (get_option(self::DB_VERSION_KEY) === self::DB_VERSION) { return; } self::create_tables(); global $wpdb; foreach ($this->get_policy_cookies() as $cookie) { $wpdb->update( self::table_name('detected'), array('category' => $cookie->category, 'provider' => $cookie->provider, 'classification' => $cookie->classification), array('id' => $cookie->id), array('%s', '%s', '%s'), array('%d') ); } update_option(self::DB_VERSION_KEY, self::DB_VERSION); } public static function schedule_scan() { if (!wp_next_scheduled(self::CRON_HOOK)) { $settings = self::get_settings(); if ( !self::managed_scanner_is_enabled($settings) || empty($settings['scanner_access_token']) || !ACookies_Scanner_Entitlement::resolve()['eligible'] || !in_array($settings['scan_recurrence'], array('daily', 'weekly'), true) ) { return; } $recurrence = in_array($settings['scan_recurrence'], array('hourly', 'twicedaily', 'daily', 'weekly'), true) ? $settings['scan_recurrence'] : 'weekly'; wp_schedule_event(time() + MINUTE_IN_SECONDS, $recurrence, self::CRON_HOOK); } } private static function schedule_scan_result_poll($delay = MINUTE_IN_SECONDS) { if (!wp_next_scheduled(self::POLL_HOOK)) { wp_schedule_single_event(time() + max(MINUTE_IN_SECONDS, absint($delay)), self::POLL_HOOK); } } public function reschedule_after_settings_update($old_value, $value) { $old_recurrence = isset($old_value['scan_recurrence']) ? $old_value['scan_recurrence'] : ''; $new_recurrence = isset($value['scan_recurrence']) ? $value['scan_recurrence'] : 'manual'; if ($old_recurrence === $new_recurrence) { return; } self::deactivate(); self::schedule_scan(); } public static function get_settings() { $options = get_option(self::OPTION_KEY, array()); $options = is_array($options) ? $options : array(); // Before 0.2.0 all existing installations displayed the banner. Missing // activation flags must not turn those live installations into setup. if (!empty($options)) { if (!array_key_exists('banner_enabled', $options)) { $options['banner_enabled'] = true; } if (!array_key_exists('onboarding_complete', $options)) { $options['onboarding_complete'] = true; } } $settings = wp_parse_args($options, self::default_settings()); if (isset($options['button_border_color'])) { foreach (array('button_primary_border_color', 'button_secondary_border_color') as $key) { if (!isset($options[$key])) { $settings[$key] = $options['button_border_color']; } } } $scanner_config = self::managed_scanner_config(); if ($scanner_config['url'] !== '') { $settings['scanner_url'] = $scanner_config['url']; } return $settings; } private static function managed_scanner_config() { $url = defined('ACOOKIES_MANAGED_API_URL') ? trim((string) ACOOKIES_MANAGED_API_URL) : ''; return array( 'url' => $url !== '' ? esc_url_raw($url) : '', 'api_key' => '', ); } private static function has_managed_scanner_config() { $config = self::managed_scanner_config(); return $config['url'] !== ''; } private static function managed_scanner_is_enabled($settings) { return !empty($settings['managed_scanner_enabled']) && !empty($settings['scanner_terms_accepted_at']); } private function accept_scanner_terms() { if (self::managed_scanner_is_enabled(self::get_settings())) { return; } $settings = get_option(self::OPTION_KEY, array()); $settings['managed_scanner_enabled'] = true; $settings['scanner_terms_accepted_at'] = current_time('mysql', true); update_option(self::OPTION_KEY, $settings, false); } private function is_wp_consent_api_available() { return function_exists('wp_set_consent') && function_exists('wp_has_consent') && function_exists('wp_add_cookie_info'); } public function register_wp_consent_api_cookie_info() { if (!$this->is_wp_consent_api_available()) { return; } wp_add_cookie_info( 'accomplice_cookie_consent', 'ACookies', 'functional', __('1 year', 'acookies'), __('Stores the visitor cookie consent choices for ACookies.', 'acookies'), '', false, false, 'HTTP', (string) wp_parse_url(home_url(), PHP_URL_HOST) ); foreach ($this->get_wp_consent_api_cookies() as $cookie) { $category = $this->wp_consent_api_category_for_cookie($cookie->category); if ($category === '') { continue; } $service = !empty($cookie->provider) ? $cookie->provider : $this->service_name_from_cookie($cookie); $purpose = $this->wp_consent_api_cookie_purpose($cookie); wp_add_cookie_info( (string) $cookie->name, (string) $service, $category, $this->wp_consent_api_expiration_label($cookie->expires), $purpose, '', false, false, 'HTTP', (string) $cookie->domain ); } } private function get_wp_consent_api_cookies() { return array_values(array_filter($this->get_policy_cookies(), function ($cookie) { return ACookies_Cookie_Catalogue::review_state($cookie) !== 'needs_review' && in_array($cookie->category, array('required', 'preferences', 'analytics', 'marketing'), true); })); } private function wp_consent_api_category_for_cookie($category) { $map = array( 'required' => 'functional', 'analytics' => 'statistics', 'preferences' => 'preferences', 'marketing' => 'marketing', ); return isset($map[$category]) ? $map[$category] : ''; } private function wp_consent_api_expiration_label($expires) { $expires = is_numeric($expires) ? (int) $expires : 0; if ($expires <= 0) { return __('Session', 'acookies'); } if ($expires <= time()) { return __('Expired', 'acookies'); } return human_time_diff(time(), $expires); } private function wp_consent_api_cookie_purpose($cookie) { $settings = self::get_settings(); $language = $this->normalize_language_code($settings['default_language']); $texts = $this->language_texts($language); $purpose = $this->policy_cookie_purpose($cookie, $texts, $language); return $purpose !== '' ? $purpose : __('Cookie detected by the ACookies scanner.', 'acookies'); } private function service_name_from_cookie($cookie) { if (!empty($cookie->script_src)) { $host = wp_parse_url($cookie->script_src, PHP_URL_HOST); if (!empty($host)) { return $host; } } if (!empty($cookie->domain)) { return $cookie->domain; } return 'ACookies'; } private function catalog() { return accomplice_cookies_language_catalog(); } private function supported_languages() { $catalog = $this->catalog(); $languages = array(); foreach ($catalog['locales'] as $code => $data) { $languages[$code] = array( 'name' => $data[0], 'dir' => $data[1], ); } return $languages; } private function editable_translation_keys() { return array( 'banner_title' => __('Banner title', 'acookies'), 'banner_text' => __('Banner text', 'acookies'), 'label_required' => __('Required label', 'acookies'), 'label_analytics' => __('Analytics label', 'acookies'), 'label_marketing' => __('Marketing label', 'acookies'), 'label_preferences' => __('Preferences label', 'acookies'), 'accept_all' => __('Accept all button', 'acookies'), 'reject_optional' => __('Reject optional button', 'acookies'), 'customize' => __('Customize button', 'acookies'), 'save_choices' => __('Save choices button', 'acookies'), 'privacy_policy' => __('Cookie policy link', 'acookies'), 'cookie_settings' => __('Cookie settings link', 'acookies'), 'preferences_title' => __('Preferences panel title', 'acookies'), 'required_help' => __('Required cookies help text', 'acookies'), 'choices_saved' => __('Choices saved status', 'acookies'), 'policy_intro' => __('Policy introduction', 'acookies'), 'fallback_body' => __('General policy fallback', 'acookies'), 'managing_body' => __('Managing choices text', 'acookies'), 'third_party_body' => __('Third-party cookies text', 'acookies'), ); } private function normalize_language_code($code) { $code = str_replace('-', '_', trim((string) $code)); $languages = $this->supported_languages(); if (isset($languages[$code])) { return $code; } $prefix = strtolower(substr($code, 0, 2)); if ($prefix === 'no') { $prefix = 'nb'; } foreach (array_keys($languages) as $supported) { if (strtolower(substr($supported, 0, 2)) === $prefix) { return $supported; } } return 'en_US'; } private function is_supported_language($code) { $languages = $this->supported_languages(); return isset($languages[$code]); } private function enabled_languages($settings = null) { $settings = $settings ? $settings : self::get_settings(); $enabled = isset($settings['enabled_languages']) && is_array($settings['enabled_languages']) ? $settings['enabled_languages'] : array('en_US'); $enabled[] = isset($settings['default_language']) ? $this->normalize_language_code($settings['default_language']) : 'en_US'; return array_values(array_unique(array_filter(array_map(array($this, 'normalize_language_code'), $enabled)))); } private function current_language() { $settings = self::get_settings(); $default = $this->normalize_language_code($settings['default_language']); $wpml_language = $this->wpml_current_language_code(); if ($wpml_language !== '') { return $this->normalize_language_code($wpml_language); } return $default; } private function has_explicit_site_language() { return $this->wpml_current_language_code() !== ''; } private function wpml_current_language_code() { $language = ''; if (has_filter('wpml_current_language')) { $language = apply_filters('wpml_current_language', null); } if (!$language && defined('ICL_LANGUAGE_CODE')) { $language = ICL_LANGUAGE_CODE; } $language = is_string($language) ? trim($language) : ''; if ($language === '' || $language === 'all') { return ''; } return sanitize_text_field($language); } private function language_texts($language, $use_wpml = true) { $settings = self::get_settings(); $language = $this->normalize_language_code($language); $catalog = $this->catalog(); $texts = isset($catalog['strings'][$language]) ? $catalog['strings'][$language] : $catalog['strings']['en_US']; $default_language = isset($settings['default_language']) ? $this->normalize_language_code($settings['default_language']) : 'en_US'; if ($language === 'en_US' && $default_language === 'en_US') { $legacy_map = array( 'banner_title' => 'banner_title', 'banner_text' => 'banner_text', 'label_required' => 'label_required', 'label_analytics' => 'label_analytics', 'label_marketing' => 'label_marketing', 'label_preferences' => 'label_preferences', ); foreach ($legacy_map as $setting_key => $text_key) { if (!empty($settings[$setting_key])) { $texts[$text_key] = $settings[$setting_key]; } } } if (!empty($settings['translations'][$language]) && is_array($settings['translations'][$language])) { foreach ($settings['translations'][$language] as $key => $value) { if ($value !== '') { $texts[$key] = $value; } } } if ($use_wpml && has_filter('wpml_translate_single_string')) { foreach ($texts as $key => $value) { $texts[$key] = apply_filters('wpml_translate_single_string', $value, 'ACookies', $language . ':' . $key); } } return $texts; } private function translation_override($settings, $language, $key) { return isset($settings['translations'][$language][$key]) ? $settings['translations'][$language][$key] : ''; } private function sanitize_translation_overrides($input) { $current = self::get_settings(); $output = isset($current['translations']) && is_array($current['translations']) ? $current['translations'] : array(); $allowed = array_keys($this->catalog()['strings']['en_US']); foreach ($input as $language => $values) { $language = $this->normalize_language_code($language); if (!is_array($values)) { continue; } if (!isset($output[$language])) { $output[$language] = array(); } foreach ($values as $key => $value) { if (!in_array($key, $allowed, true)) { continue; } $output[$language][$key] = sanitize_textarea_field($value); } } return $output; } private function register_wpml_strings($settings) { if (!has_action('wpml_register_single_string')) { return; } foreach ($this->enabled_languages($settings) as $language) { $texts = $this->language_texts($language, false); foreach ($texts as $key => $value) { do_action('wpml_register_single_string', 'ACookies', $language . ':' . $key, $value); } } } public function register_settings() { register_setting('accomplice_cookies_settings', self::OPTION_KEY, array( 'sanitize_callback' => array($this, 'sanitize_settings'), )); } public function sanitize_settings($input) { $defaults = self::default_settings(); $current = self::get_settings(); $output = $current; if (!is_array($input)) { return $output; } $managed_scanner_config = self::managed_scanner_config(); $entitlement = ACookies_Scanner_Entitlement::resolve(); if ($managed_scanner_config['url'] !== '') { $output['scanner_url'] = $managed_scanner_config['url']; } elseif (array_key_exists('scanner_url', $input)) { $output['scanner_url'] = esc_url_raw(trim($input['scanner_url'])); } if (!$this->has_managed_scanner_config() && array_key_exists('scanner_api_key', $input)) { $output['scanner_api_key'] = sanitize_text_field($input['scanner_api_key']); } if (array_key_exists('scan_recurrence', $input)) { $recurrence = sanitize_key($input['scan_recurrence']); if (in_array($recurrence, $entitlement['schedules'], true)) { $output['scan_recurrence'] = $recurrence; } } if (array_key_exists('scan_sample_size', $input)) { // A lost verification/eligibility state must not truncate a saved // Premium preference merely because another settings field is saved. $sample = absint($input['scan_sample_size']); if ($sample === absint($current['scan_sample_size']) || $sample <= $entitlement['pages']) { $output['scan_sample_size'] = max(1, min(ACookies_Scanner_Entitlement::PREMIUM_PAGES, $sample)); } } if (array_key_exists('default_language', $input)) { $output['default_language'] = $this->normalize_language_code(sanitize_text_field($input['default_language'])); } if (array_key_exists('enabled_languages', $input) && is_array($input['enabled_languages'])) { $enabled = array(); foreach ($input['enabled_languages'] as $language) { $normalized = $this->normalize_language_code(sanitize_text_field($language)); if ($this->is_supported_language($normalized)) { $enabled[] = $normalized; } } $enabled[] = isset($output['default_language']) ? $output['default_language'] : 'en_US'; $output['enabled_languages'] = array_values(array_unique($enabled)); } if (array_key_exists('translations', $input) && is_array($input['translations'])) { $output['translations'] = $this->sanitize_translation_overrides($input['translations']); $this->register_wpml_strings($output); } if (array_key_exists('banner_title', $input)) { $output['banner_title'] = sanitize_text_field($input['banner_title']); } if (array_key_exists('banner_text', $input)) { $output['banner_text'] = sanitize_textarea_field($input['banner_text']); } if (array_key_exists('banner_position', $input)) { $output['banner_position'] = in_array($input['banner_position'], array('bottom-right', 'bottom-left', 'top-right', 'top-left', 'bottom-center'), true) ? $input['banner_position'] : $defaults['banner_position']; } if (array_key_exists('button_style_mode', $input)) { $output['button_style_mode'] = in_array($input['button_style_mode'], array('theme', 'custom'), true) ? $input['button_style_mode'] : $defaults['button_style_mode']; } foreach (array( 'banner_background_color', 'banner_text_color', 'banner_border_color', 'button_primary_background', 'button_primary_text', 'button_primary_border_color', 'button_primary_hover_background', 'button_primary_hover_text', 'button_primary_hover_border_color', 'button_secondary_background', 'button_secondary_text', 'button_secondary_border_color', 'button_secondary_hover_background', 'button_secondary_hover_text', 'button_secondary_hover_border_color', 'button_border_color', ) as $key) { if (array_key_exists($key, $input)) { $color = sanitize_hex_color($input[$key]); $output[$key] = $color ? $color : $defaults[$key]; } } if (array_key_exists('button_border_radius', $input)) { $output['button_border_radius'] = max(0, min(40, absint($input['button_border_radius']))); } if (array_key_exists('banner_border_radius', $input)) { $output['banner_border_radius'] = max(0, min(40, absint($input['banner_border_radius']))); } if (array_key_exists('banner_border_width', $input)) { $output['banner_border_width'] = max(0, min(8, absint($input['banner_border_width']))); } foreach (array('button_primary_border_width', 'button_secondary_border_width') as $key) { if (array_key_exists($key, $input)) { $output[$key] = max(0, min(8, absint($input[$key]))); } } // Legacy CSS options are retained in storage but cannot be edited or executed. if (array_key_exists('privacy_url', $input)) { $output['privacy_url'] = esc_url_raw(trim($input['privacy_url'])); } if (array_key_exists('policy_version', $input)) { $output['policy_version'] = sanitize_text_field($input['policy_version']); } if (array_key_exists('ga_measurement_id', $input)) { $output['ga_measurement_id'] = sanitize_text_field($input['ga_measurement_id']); } if (array_key_exists('gtm_id', $input)) { $output['gtm_id'] = sanitize_text_field($input['gtm_id']); } if (array_key_exists('google_allow_pre_consent', $input)) { $output['google_allow_pre_consent'] = !empty($input['google_allow_pre_consent']); } if (array_key_exists('google_consent_integration', $input)) { $output['google_consent_integration'] = $input['google_consent_integration'] === 'gtm' ? 'gtm' : 'gtag'; } foreach (array('google_consent_debug', 'google_banner_template') as $key) { if (array_key_exists($key, $input)) { $output[$key] = !empty($input[$key]); } } if (array_key_exists('banner_enabled', $input)) { $output['banner_enabled'] = !empty($input['banner_enabled']); } // WordPress also runs this registered sanitizer for update_option() // calls from setup and scanner renewal, not only the Settings form. foreach (array('onboarding_complete', 'managed_scanner_enabled') as $key) { if (array_key_exists($key, $input)) { $output[$key] = !empty($input[$key]); } } foreach (array('scanner_terms_accepted_at', 'installation_id', 'scanner_access_token', 'scanner_token_expires_at') as $key) { if (array_key_exists($key, $input)) { $output[$key] = sanitize_text_field($input[$key]); } } if (array_key_exists('consent_retention_days', $input)) { $output['consent_retention_days'] = max(1, min(30, absint($input['consent_retention_days']))); } if (array_key_exists('script_rules_text', $input)) { $output['script_rules'] = $this->sanitize_script_rules_text($input['script_rules_text']); } foreach (array('label_required', 'label_analytics', 'label_marketing', 'label_preferences') as $key) { if (array_key_exists($key, $input)) { $output[$key] = sanitize_text_field($input[$key]); } } return $output; } private function sanitize_script_rules_text($value) { $rules = array(); $lines = preg_split('/\r\n|\r|\n/', (string) $value); foreach ($lines as $line) { $parts = array_map('trim', explode('|', $line, 2)); if (count($parts) !== 2 || !in_array($parts[1], array('analytics', 'marketing', 'preferences'), true)) { continue; } $match = explode(':', $parts[0], 2); if (count($match) !== 2 || !in_array($match[0], array('handle', 'src'), true)) { continue; } $match_value = sanitize_text_field($match[1]); if ($match_value === '') { continue; } $rules[] = array( 'match_type' => $match[0] === 'handle' ? 'handle' : 'src_contains', 'match_value' => $match_value, 'category' => $parts[1], ); } return array_slice($rules, 0, 100); } private function script_rules_text($rules) { $lines = array(); foreach (is_array($rules) ? $rules : array() as $rule) { if (empty($rule['match_value']) || empty($rule['category'])) { continue; } $prefix = isset($rule['match_type']) && $rule['match_type'] === 'handle' ? 'handle' : 'src'; $lines[] = $prefix . ':' . $rule['match_value'] . '|' . $rule['category']; } return implode("\n", $lines); } public function add_admin_menu() { add_options_page( __('ACookies', 'acookies'), __('ACookies', 'acookies'), 'manage_options', self::ADMIN_SLUG, array($this, 'render_admin_page') ); } public function redirect_legacy_admin_slug() { if (!is_admin() || !current_user_can('manage_options')) { return; } $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; if ($page !== self::LEGACY_ADMIN_SLUG) { return; } $args = array('page' => self::ADMIN_SLUG); if (isset($_GET['tab'])) { $args['tab'] = sanitize_key(wp_unslash($_GET['tab'])); } if (isset($_GET['edit_lang'])) { $args['edit_lang'] = sanitize_key(wp_unslash($_GET['edit_lang'])); } if (isset($_GET['preview_lang'])) { $args['preview_lang'] = sanitize_key(wp_unslash($_GET['preview_lang'])); } wp_safe_redirect(add_query_arg($args, admin_url('options-general.php'))); exit; } public function maybe_redirect_to_onboarding() { if ( !is_admin() || !current_user_can('manage_options') || wp_doing_ajax() || is_network_admin() || get_option(self::ONBOARDING_REDIRECT_KEY) !== '1' ) { return; } delete_option(self::ONBOARDING_REDIRECT_KEY); $settings = self::get_settings(); if (!empty($settings['onboarding_complete']) || !empty($settings['banner_enabled'])) { return; } $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; if ($page === self::ADMIN_SLUG) { return; } wp_safe_redirect(add_query_arg(array('page' => self::ADMIN_SLUG, 'tab' => 'setup', 'step' => 1), admin_url('options-general.php'))); exit; } public function handle_save_onboarding() { if (!current_user_can('manage_options') || !check_admin_referer('acookies_save_onboarding')) { wp_die(esc_html__('Not allowed.', 'acookies')); } $step = isset($_POST['onboarding_step']) ? max(1, min(5, absint($_POST['onboarding_step']))) : 1; $settings = get_option(self::OPTION_KEY, array()); $next_step = min(5, $step + 1); $result = true; if ($step === 1) { $language = isset($_POST['default_language']) ? $this->normalize_language_code(sanitize_text_field(wp_unslash($_POST['default_language']))) : 'en_US'; if (!$this->is_supported_language($language)) { $language = 'en_US'; } $settings['default_language'] = $language; $settings['enabled_languages'] = array_values(array_unique(array('en_US', 'sv_SE', $language))); update_option(self::OPTION_KEY, $settings, false); } elseif ($step === 2) { if (isset($_POST['scanner_terms_accepted']) && $_POST['scanner_terms_accepted'] === '1') { $this->accept_scanner_terms(); $result = $this->ensure_managed_scanner_token(); if (is_wp_error($result)) { $next_step = 2; } } } elseif ($step === 3) { $import_code = isset($_POST['generator_import_code']) ? sanitize_text_field(wp_unslash($_POST['generator_import_code'])) : ''; if ($import_code !== '') { $result = $this->import_generator_scan($import_code); if (is_wp_error($result)) { $next_step = 3; } } elseif (!empty($_POST['run_first_scan'])) { $result = $this->start_scan(); if (is_wp_error($result)) { $next_step = 3; } } } elseif ($step === 5) { $policy_published = false; if (!empty($_POST['create_policy_page'])) { $policy_page_id = wp_insert_post(array( 'post_title' => __('Cookie Policy', 'acookies'), 'post_status' => 'publish', 'post_type' => 'page', 'post_content' => '', ), true); if (!is_wp_error($policy_page_id)) { $settings['privacy_url'] = get_permalink($policy_page_id); $policy_published = true; } } $settings['banner_enabled'] = true; $settings['onboarding_complete'] = true; update_option(self::OPTION_KEY, $settings, false); $this->record_managed_event('onboarding_complete'); if ($policy_published) { $this->record_managed_event('policy_published'); } $next_step = 5; } $args = array('page' => self::ADMIN_SLUG, 'tab' => $step === 5 && !is_wp_error($result) ? 'stats' : 'setup', 'step' => $next_step); if (is_wp_error($result)) { $args['ac_error'] = rawurlencode($result->get_error_message()); } elseif ($step === 5) { $args['ac_notice'] = rawurlencode(__('ACookies is configured and the banner is active.', 'acookies')); } wp_safe_redirect(add_query_arg($args, admin_url('options-general.php'))); exit; } public function render_admin_page() { if (!current_user_can('manage_options')) { return; } $settings = self::get_settings(); $active_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : (empty($settings['onboarding_complete']) && empty($settings['banner_enabled']) ? 'setup' : 'stats'); if ($active_tab === 'findings') { $active_tab = 'cookie-list'; } $tabs = array('setup', 'stats', 'settings', 'languages', 'design', 'cookie-policy', 'scans', 'cookie-list', 'consent-log', 'documentation'); if (!in_array($active_tab, $tabs, true)) { $active_tab = 'stats'; } ?>

render_admin_tabs($active_tab); ?>
render_onboarding_tab($settings); } elseif ($active_tab === 'stats') { $this->render_stats_tab(); } elseif ($active_tab === 'settings') { $this->render_settings_tab($settings); } elseif ($active_tab === 'languages') { $this->render_languages_tab($settings); } elseif ($active_tab === 'design') { $this->render_design_tab($settings); } elseif ($active_tab === 'cookie-policy') { $this->render_cookie_policy_tab(); } elseif ($active_tab === 'scans') { $this->render_scans_tab(); } elseif ($active_tab === 'cookie-list') { $this->render_cookie_list_tab(); } elseif ($active_tab === 'consent-log') { $this->render_consent_log_tab(); } elseif ($active_tab === 'documentation') { $this->render_documentation_tab(); } ?>
__('Setup', 'acookies'), 'stats' => __('Stats', 'acookies'), 'settings' => __('Settings', 'acookies'), 'languages' => __('Languages', 'acookies'), 'design' => __('Design', 'acookies'), 'cookie-policy' => __('Cookie Policy', 'acookies'), 'scans' => __('Scans', 'acookies'), 'cookie-list' => __('Cookie List', 'acookies'), 'consent-log' => __('Consent Log', 'acookies'), 'documentation' => __('Documentation', 'acookies'), ); ?>

' . esc_html__('ACookies setup is complete.', 'acookies') . '

'; echo '

' . esc_html__('Open settings', 'acookies') . '

'; return; } $step = isset($_GET['step']) ? max(1, min(5, absint($_GET['step']))) : 1; $languages = $this->supported_languages(); ?>
__('Consent defaults', 'acookies'), 2 => __('Managed scanner', 'acookies'), 3 => __('First scan', 'acookies'), 4 => __('Review controls', 'acookies'), 5 => __('Publish', 'acookies'), ) as $number => $label) : ?>

render_scanner_data_disclosure(); ?> render_scanner_entitlement(); ?>

get_recent_scans(); $latest_scan = !empty($recent_scans) ? reset($recent_scans) : null; $unreviewed = count(array_filter($this->get_cookie_list(), function ($cookie) { return ACookies_Cookie_Catalogue::review_state($cookie) === 'needs_review'; })); $stats = $this->get_consent_stats(); $accepted_percent = $stats['total'] > 0 ? round(($stats['accepted'] / $stats['total']) * 100, 1) : 0; $pie_style = sprintf('background: conic-gradient(#227f5f 0 %1$s%%, #dcdcde %1$s%% 100%%);', esc_attr($accepted_percent)); ?>

status) : esc_html__('Not run', 'acookies'); ?>

%

render_scanner_entitlement(); ?> render_input('scanner_url', __('Scanner service URL', 'acookies'), 'url', $settings['scanner_url'], 'https://scanner.example.com'); ?> render_input('scanner_api_key', __('Scanner API key', 'acookies'), 'password', $settings['scanner_api_key'], ''); ?> render_input('scan_sample_size', __('Public page sample size', 'acookies'), 'number', absint($settings['scan_sample_size']), (string) $entitlement['sample_default']); ?>

render_input('ga_measurement_id', __('GA4 measurement ID', 'acookies'), 'text', $settings['ga_measurement_id'], 'G-XXXXXXXXXX'); ?> render_input('gtm_id', __('Google Tag Manager ID', 'acookies'), 'text', $settings['gtm_id'], 'GTM-XXXXXXX'); ?>

handle:my-analytics|analytics
src:connect.facebook.net|marketing

render_wp_consent_api_status(); ?>

render_input('banner_title', __('Title', 'acookies'), 'text', $settings['banner_title'], ''); ?> render_input('privacy_url', __('Cookie policy URL', 'acookies'), 'url', $settings['privacy_url'], home_url('/cookie-policy/')); ?> render_input('policy_version', __('Policy version', 'acookies'), 'text', $settings['policy_version'], '1'); ?> render_input('consent_retention_days', __('Consent log retention (days, Free max 30)', 'acookies'), 'number', $settings['consent_retention_days'], '30'); ?> render_input('label_required', __('Required label', 'acookies'), 'text', $settings['label_required'], ''); ?> render_input('label_analytics', __('Analytics label', 'acookies'), 'text', $settings['label_analytics'], ''); ?> render_input('label_marketing', __('Marketing label', 'acookies'), 'text', $settings['label_marketing'], ''); ?> render_input('label_preferences', __('Preferences label', 'acookies'), 'text', $settings['label_preferences'], ''); ?>

scanner data processing terms.', 'acookies'), esc_url('https://acookies.com/external-services'))); ?>

' . esc_html($message) . '

'; if ($entitlement['error'] !== '') { echo '

' . esc_html($entitlement['error']) . '

'; } } private function render_wp_consent_api_status() { $available = $this->is_wp_consent_api_available(); ?>

supported_languages(); $enabled = $this->enabled_languages($settings); $default_language = $this->normalize_language_code($settings['default_language']); $edit_language = isset($_GET['edit_lang']) ? $this->normalize_language_code(sanitize_text_field(wp_unslash($_GET['edit_lang']))) : $default_language; if (!$this->is_supported_language($edit_language)) { $edit_language = $default_language; } $texts = $this->language_texts($edit_language, false); $editable = $this->editable_translation_keys(); ?>

$label) : ?>

get_policy_cookies())) : ?>

supported_languages(); $preview_language = isset($_GET['preview_lang']) ? $this->normalize_language_code(sanitize_text_field(wp_unslash($_GET['preview_lang']))) : $this->current_language(); foreach ($this->enabled_languages($settings) as $code) : ?>

render_cookie_policy_block_content(array('language' => $preview_language))); ?>

render_scanner_data_disclosure(); ?> render_scanner_entitlement(); ?>
render_scans_table($this->get_recent_scans()); ?>
get_cookie_list(); $states = array( 'all' => __('All cookies', 'acookies'), 'automatic' => __('Automatically resolved', 'acookies'), 'reviewed' => __('Manually reviewed', 'acookies'), 'needs_review' => __('Needs attention', 'acookies'), ); $state = isset($_GET['review_state']) ? sanitize_key(wp_unslash($_GET['review_state'])) : 'all'; if (!isset($states[$state])) { $state = 'all'; } $page = max(1, isset($_GET['cookie_page']) ? absint($_GET['cookie_page']) : 1); $filtered = array_values(array_filter($cookies, function ($cookie) use ($state) { return $state === 'all' || ACookies_Cookie_Catalogue::review_state($cookie) === $state; })); $page_count = max(1, (int) ceil(count($filtered) / 50)); $page = min($page, $page_count); ?>

$label) : $count = count(array_filter($cookies, function ($cookie) use ($key) { return $key === 'all' || ACookies_Cookie_Catalogue::review_state($cookie) === $key; })); ?>

render_pending_table(array_slice($filtered, ($page - 1) * 50, 50)); ?>

render_consent_log_table($this->get_recent_consents()); ?>

#acookies-preferences
<a href="#acookies-preferences" data-acookies-open-preferences>Cookie settings</a>
[acookies_preferences_link]
[acookies_preferences_link text="Cookie settings"]

'', 'class' => '', ), $attributes, 'acookies_preferences_link' ); $texts = $this->language_texts($this->current_language()); $text = trim((string) $attributes['text']); if ($text === '') { $text = isset($texts['cookie_settings']) ? $texts['cookie_settings'] : __('Cookie settings', 'acookies'); } $class = trim((string) $attributes['class']); return sprintf( '%2$s', $class !== '' ? ' class="' . esc_attr($class) . '"' : '', esc_html($text) ); } public function register_cookie_policy_block() { $asset_file = ACCOMPLICE_COOKIES_DIR . 'build/cookie-policy/index.asset.php'; $script_file = ACCOMPLICE_COOKIES_DIR . 'build/cookie-policy/index.js'; if (file_exists($asset_file) && file_exists($script_file)) { $asset = include $asset_file; wp_register_script( 'accomplice-cookies-policy-block', ACCOMPLICE_COOKIES_URL . 'build/cookie-policy/index.js', isset($asset['dependencies']) ? $asset['dependencies'] : array(), isset($asset['version']) ? $asset['version'] : ACCOMPLICE_COOKIES_VERSION, true ); wp_set_script_translations('accomplice-cookies-policy-block', 'acookies'); } if (file_exists(ACCOMPLICE_COOKIES_DIR . 'build/cookie-policy/style-index.css')) { wp_register_style( 'accomplice-cookies-policy-block', ACCOMPLICE_COOKIES_URL . 'build/cookie-policy/style-index.css', array(), ACCOMPLICE_COOKIES_VERSION ); } $block_args = array( 'api_version' => 3, 'title' => __('ACookies Cookie Policy', 'acookies'), 'category' => 'widgets', 'icon' => 'privacy', 'description' => __('Displays the generated cookie policy from ACookies scan results.', 'acookies'), 'render_callback' => array($this, 'render_cookie_policy_block_content'), 'supports' => array( 'html' => false, ), ); if (wp_script_is('accomplice-cookies-policy-block', 'registered')) { $block_args['editor_script'] = 'accomplice-cookies-policy-block'; } if (wp_style_is('accomplice-cookies-policy-block', 'registered')) { $block_args['style'] = 'accomplice-cookies-policy-block'; } register_block_type('accomplice-cookies/cookie-policy', $block_args); } public function render_cookie_policy_block_content($attributes = array()) { $cookies = $this->get_policy_cookies(); $language = isset($attributes['language']) ? $this->normalize_language_code($attributes['language']) : $this->current_language(); $texts = $this->language_texts($language); $languages = $this->supported_languages(); $dir = isset($languages[$language]['dir']) ? $languages[$language]['dir'] : 'ltr'; ob_start(); ?> get_results( $wpdb->prepare( "SELECT d.* FROM %i d INNER JOIN ( SELECT name, domain, path, MAX(id) AS id FROM %i GROUP BY name, domain, path ) latest ON latest.id = d.id WHERE d.superseded = 0 ORDER BY d.name ASC", self::table_name('detected'), self::table_name('detected') ) ); return array_map(array('ACookies_Cookie_Catalogue', 'resolve'), $cookies); } private function group_policy_cookies($cookies) { $groups = array(); foreach ($cookies as $cookie) { $category = $this->public_policy_category($cookie); if (!isset($groups[$category])) { $groups[$category] = array(); } $groups[$category][] = $cookie; } return $groups; } private function frontend_cookie_details_for_language($language, $policy_cookies = null) { $language = $this->normalize_language_code($language); $texts = $this->language_texts($language); $groups = $this->group_policy_cookies(is_array($policy_cookies) ? $policy_cookies : $this->get_policy_cookies()); $details = array(); $category_order = array('required', 'security', 'preferences', 'analytics', 'marketing', 'unclassified'); foreach ($category_order as $category) { $items = isset($groups[$category]) ? $groups[$category] : array(); $cookies = array(); foreach ($items as $cookie) { $privacy = $this->policy_cookie_privacy_data($cookie); $cookies[] = array( 'name' => isset($cookie->name) ? (string) $cookie->name : '', 'provider' => $this->policy_cookie_provider($cookie), 'purpose' => $this->policy_cookie_purpose($cookie, $texts, $language), 'duration' => $this->policy_cookie_duration($cookie, $texts, $language), 'type' => !empty($cookie->first_party) ? $texts['first_party'] : $texts['third_party'], 'privacy' => !empty($privacy) ? $privacy : null, ); } $details[$category] = array( 'category' => $category, 'label' => $this->policy_category_label($category, $texts), 'purpose' => $this->policy_category_purpose($category, $texts), 'required' => in_array($category, array('required', 'security'), true), 'cookies' => $cookies, ); } return $details; } private function policy_category_label($category, $texts) { $labels = array( 'required' => $texts['required_cookies'], 'security' => $texts['security_cookies'], 'preferences' => $texts['preferences_cookies'], 'analytics' => $texts['analytics_cookies'], 'marketing' => $texts['marketing_cookies'], 'unclassified' => $texts['unclassified_cookies'], ); return isset($labels[$category]) ? $labels[$category] : $labels['unclassified']; } private function policy_category_purpose($category, $texts) { $purposes = array( 'required' => $texts['required_purpose'], 'security' => $texts['security_purpose'], 'preferences' => $texts['preferences_purpose'], 'analytics' => $texts['analytics_purpose'], 'marketing' => $texts['marketing_purpose'], 'unclassified' => $texts['unclassified_purpose'], ); return isset($purposes[$category]) ? $purposes[$category] : $purposes['unclassified']; } private function policy_cookie_purpose($cookie, $texts, $language) { $description = $this->cookie_description_override_for_language($cookie, $language); if ($description !== '') { return $description; } $known_purpose = $this->known_cookie_public_purpose($cookie, $language); if ($known_purpose !== '') { return $known_purpose; } if ($this->public_policy_category($cookie) === 'unclassified') { return $texts['unclassified_purpose']; } $description = $this->cookie_description_for_language($cookie, $language); if ($description !== '') { return $description; } $category = $this->public_policy_category($cookie); if ($category === 'required') { return $texts['required_purpose']; } if ($category === 'security') { return $texts['security_purpose']; } if ($category === 'preferences') { return $texts['preferences_purpose']; } if ($category === 'analytics') { return $texts['analytics_purpose']; } if ($category === 'marketing') { return $texts['marketing_purpose']; } return $texts['unclassified_purpose']; } private function public_policy_category($cookie) { $resolved = ACookies_Cookie_Catalogue::resolve($cookie); return $resolved->display_category; } private function cookie_description_override_for_language($cookie, $language) { $language = $this->normalize_language_code($language); $map = isset($cookie->description_overrides) ? json_decode($cookie->description_overrides, true) : null; if (!is_array($map)) { return ''; } return $this->description_from_language_map($map, $language); } private function cookie_description_for_language($cookie, $language) { $language = $this->normalize_language_code($language); $maps = array( isset($cookie->description_overrides) ? json_decode($cookie->description_overrides, true) : null, isset($cookie->descriptions) ? json_decode($cookie->descriptions, true) : null, ); foreach ($maps as $map) { if (!is_array($map)) { continue; } $description = $this->description_from_language_map($map, $language); if ($description !== '') { return $description; } } return ''; } private function description_from_language_map($map, $language) { if (!empty($map[$language])) { return sanitize_textarea_field($map[$language]); } $prefix = strtolower(substr($language, 0, 2)); foreach ($map as $candidate => $value) { if (strtolower(substr((string) $candidate, 0, 2)) === $prefix && !empty($value)) { return sanitize_textarea_field($value); } } if (!empty($map['en_US'])) { return sanitize_textarea_field($map['en_US']); } return ''; } private function known_cookie_public_purpose($cookie, $language) { return ACookies_Cookie_Catalogue::description(ACookies_Cookie_Catalogue::resolve($cookie), $language); } private function policy_cookie_provider($cookie) { if (!empty($cookie->provider) && strtolower((string) $cookie->provider) !== 'unknown') { return $cookie->provider; } if (!empty($cookie->domain)) { return ltrim((string) $cookie->domain, '.'); } return get_bloginfo('name'); } private function policy_cookie_duration($cookie, $texts, $language) { $is_swedish = strtolower(substr($this->normalize_language_code($language), 0, 2)) === 'sv'; $expires = is_numeric($cookie->expires) ? (int) $cookie->expires : 0; if ($expires > 0) { return $this->format_cookie_duration($expires, $texts); } $name = strtolower((string) $cookie->name); if ($name === '_ga' || strpos($name, '_ga_') === 0) { if ($is_swedish) { return 'Vanligtvis 2 år'; } return __('Usually 2 years', 'acookies'); } if ($name === '_gid') { if ($is_swedish) { return 'Vanligtvis 24 timmar'; } return __('Usually 24 hours', 'acookies'); } if (strpos($name, '_gat') === 0) { if ($is_swedish) { return 'Vanligtvis 1 minut'; } return __('Usually 1 minute', 'acookies'); } if ($name === '_fbp' || $name === '_fbc') { if ($is_swedish) { return 'Vanligtvis 3 månader'; } return __('Usually 3 months', 'acookies'); } if ($name === 'bcookie') { if ($is_swedish) { return 'Vanligtvis 1 år'; } return __('Usually 1 year', 'acookies'); } if ($name === 'lidc') { if ($is_swedish) { return 'Vanligtvis 1 dag'; } return __('Usually 1 day', 'acookies'); } if ($name === 'li_gc' || $name === '_grecaptcha') { if ($is_swedish) { return 'Vanligtvis 6 månader'; } return __('Usually 6 months', 'acookies'); } if ($name === '__cf_bm') { if ($is_swedish) { return 'Vanligtvis 30 minuter'; } return __('Usually 30 minutes', 'acookies'); } if ($name === '_cfuvid') { return $texts['session']; } if (preg_match('/cookieyes|cookielawinfo|viewed_cookie_policy|cookie_consent/i', $name)) { if ($is_swedish) { return 'Beror på samtyckesinställningarna'; } return __('Depends on consent settings', 'acookies'); } if ($is_swedish) { return 'Session eller anges av leverantören'; } return __('Session or set by provider', 'acookies'); } private function policy_cookie_privacy_information($cookie) { $provider = $this->policy_cookie_privacy_data($cookie); if (empty($provider)) { return '-'; } return sprintf( '%s', esc_url($provider['url']), esc_html($provider['label']) ); } private function policy_cookie_privacy_data($cookie) { $provider = $this->known_provider_privacy_information($cookie); if (empty($provider)) { return array(); } return array( 'label' => $provider['label'], 'url' => $provider['url'], ); } private function known_provider_privacy_information($cookie) { $resolved = ACookies_Cookie_Catalogue::resolve($cookie); $metadata = ACookies_Cookie_Catalogue::metadata($resolved); if (empty($metadata['evidence'])) { return array(); } return array('label' => sprintf(/* translators: %s: cookie provider name. */ __('%s cookie information', 'acookies'), $resolved->provider), 'url' => $metadata['evidence'][0]['url']); } private function format_cookie_duration($expires, $texts) { $expires = is_numeric($expires) ? (int) $expires : 0; if ($expires <= 0) { return $texts['session']; } $seconds = $expires - time(); if ($seconds <= 0) { return $texts['expired']; } if ($seconds < DAY_IN_SECONDS) { return $texts['less_than_day']; } if ($seconds < MONTH_IN_SECONDS) { $count = (int) ceil($seconds / DAY_IN_SECONDS); return number_format_i18n($count) . ' ' . ($count === 1 ? $texts['day'] : $texts['days']); } if ($seconds < YEAR_IN_SECONDS) { $count = (int) ceil($seconds / MONTH_IN_SECONDS); return number_format_i18n($count) . ' ' . ($count === 1 ? $texts['month'] : $texts['months']); } $count = (int) ceil($seconds / YEAR_IN_SECONDS); return number_format_i18n($count) . ' ' . ($count === 1 ? $texts['year'] : $texts['years']); } private function get_consent_stats() { global $wpdb; $rows = $wpdb->get_col($wpdb->prepare("SELECT categories FROM %i ORDER BY id DESC LIMIT 10000", self::table_name('consents'))); $stats = array( 'total' => 0, 'accepted' => 0, 'rejected' => 0, 'analytics' => 0, 'marketing' => 0, 'preferences' => 0, ); foreach ($rows as $raw) { $categories = json_decode($raw, true); if (!is_array($categories)) { continue; } $stats['total']++; $has_optional = false; foreach (array('analytics', 'marketing', 'preferences') as $category) { if (!empty($categories[$category])) { $stats[$category]++; $has_optional = true; } } if ($has_optional) { $stats['accepted']++; } else { $stats['rejected']++; } } return $stats; } public function enqueue_admin_assets($hook_suffix) { if ($hook_suffix !== 'settings_page_' . self::ADMIN_SLUG || !current_user_can('manage_options')) { return; } wp_enqueue_style('acookies-admin', ACCOMPLICE_COOKIES_URL . 'assets/admin.css', array(), ACCOMPLICE_COOKIES_VERSION); wp_enqueue_script('acookies-admin', ACCOMPLICE_COOKIES_URL . 'assets/admin.js', array(), ACCOMPLICE_COOKIES_VERSION, true); $strings = array( 'message0' => __('AA pass', 'acookies'), 'message1' => __('Review contrast', 'acookies'), 'message2' => __('Theme controlled', 'acookies'), 'message3' => __('Refreshing scan results...', 'acookies'), 'message4' => __('Refreshing...', 'acookies'), 'message5' => __('Could not refresh scan results.', 'acookies'), 'message6' => __('Waiting for scan results...', 'acookies'), ); wp_add_inline_script('acookies-admin', 'window.AcookiesAdminStrings = ' . wp_json_encode($strings, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';', 'before'); } private function render_input($key, $label, $type, $value, $placeholder) { ?>

render_color_input('banner_background_color', __('Background', 'acookies'), $settings['banner_background_color'], '--ac-banner-background'); ?> render_color_input('banner_text_color', __('Text', 'acookies'), $settings['banner_text_color'], '--ac-banner-text-color'); ?> render_color_input('banner_border_color', __('Border', 'acookies'), $settings['banner_border_color'], '--ac-banner-border-color'); ?> render_number_input('banner_border_width', __('Border width', 'acookies'), $settings['banner_border_width'], 0, 8, '--ac-banner-border-size'); ?> render_number_input('banner_border_radius', __('Border radius', 'acookies'), $settings['banner_border_radius'], 0, 40, '--ac-banner-border-radius'); ?>

render_color_input($prefix . '_background', __('Background', 'acookies'), $settings[$prefix . '_background'], $css_prefix . '-background'); ?> render_color_input($prefix . '_text', __('Text', 'acookies'), $settings[$prefix . '_text'], $css_prefix . '-text'); ?> render_color_input($prefix . '_border_color', __('Border', 'acookies'), $settings[$prefix . '_border_color'], $css_prefix . '-border'); ?> render_number_input($prefix . '_border_width', __('Border width', 'acookies'), $settings[$prefix . '_border_width'], 0, 8, $css_prefix . '-border-size'); ?>

render_color_input($prefix . '_hover_background', __('Background', 'acookies'), $settings[$prefix . '_hover_background'], $css_prefix . '-hover-background'); ?> render_color_input($prefix . '_hover_text', __('Text', 'acookies'), $settings[$prefix . '_hover_text'], $css_prefix . '-hover-text'); ?> render_color_input($prefix . '_hover_border_color', __('Border', 'acookies'), $settings[$prefix . '_hover_border_color'], $css_prefix . '-hover-border'); ?>
language_texts($this->current_language()); $labels = array( 'acceptAll' => $texts['accept_all'], 'rejectAll' => $texts['reject_optional'], 'customize' => $texts['customize'], 'privacy' => $texts['privacy_policy'], ); $position = in_array($settings['banner_position'], array('bottom-right', 'bottom-left', 'bottom-center', 'top-right', 'top-left'), true) ? $settings['banner_position'] : 'bottom-right'; $style = sprintf( '--ac-banner-background:%1$s;--ac-banner-text-color:%2$s;--ac-banner-border-color:%3$s;--ac-banner-border-size:%4$dpx;--ac-banner-border-radius:%5$dpx;--ac-button-primary-background:%6$s;--ac-button-primary-text:%7$s;--ac-button-primary-border:%8$s;--ac-button-primary-border-size:%9$dpx;--ac-button-primary-hover-background:%10$s;--ac-button-primary-hover-text:%11$s;--ac-button-primary-hover-border:%12$s;--ac-button-secondary-background:%13$s;--ac-button-secondary-text:%14$s;--ac-button-secondary-border:%15$s;--ac-button-secondary-border-size:%16$dpx;--ac-button-secondary-hover-background:%17$s;--ac-button-secondary-hover-text:%18$s;--ac-button-secondary-hover-border:%19$s;--ac-button-border-radius:%20$dpx;', esc_attr($settings['banner_background_color']), esc_attr($settings['banner_text_color']), esc_attr($settings['banner_border_color']), absint($settings['banner_border_width']), absint($settings['banner_border_radius']), esc_attr($settings['button_primary_background']), esc_attr($settings['button_primary_text']), esc_attr($settings['button_primary_border_color']), absint($settings['button_primary_border_width']), esc_attr($settings['button_primary_hover_background']), esc_attr($settings['button_primary_hover_text']), esc_attr($settings['button_primary_hover_border_color']), esc_attr($settings['button_secondary_background']), esc_attr($settings['button_secondary_text']), esc_attr($settings['button_secondary_border_color']), absint($settings['button_secondary_border_width']), esc_attr($settings['button_secondary_hover_background']), esc_attr($settings['button_secondary_hover_text']), esc_attr($settings['button_secondary_hover_border_color']), absint($settings['button_border_radius']) ); ?>

id); ?> status); ?> scanner_id); ?> started_at); ?> completed_at); ?> urls, true) ?: array())); ?> error)) : ?> error, 140, '...')); ?> —
categories, true); ?>
created_at); ?> consent_id, 18, '...')); ?> language_code); ?> consent_choice_badge($categories, 'required')); ?> consent_choice_badge($categories, 'analytics')); ?> consent_choice_badge($categories, 'marketing')); ?> consent_choice_badge($categories, 'preferences')); ?> policy_version); ?> ip_hash, 12, '...')); ?> user_agent_hash, 12, '...')); ?>
%2$s', esc_attr($class), esc_html($label) ); } private function render_pending_table($pending) { $settings = self::get_settings(); $languages = $this->supported_languages(); $enabled = $this->enabled_languages($settings); ?>
name); ?> domain); ?> provider) ? $cookie->provider : ''); ?> category); ?>

first_party ? esc_html__('Yes', 'acookies') : esc_html__('No', 'acookies'); ?> source_url); ?> script_src); ?>
id); ?>
server_has_category_consent($category)) { return $tag; } $blocked_src = esc_url($src); if ($blocked_src === '') { return $tag; } $tag = preg_replace('/\s+type=("|\')[^"\']*\1/i', '', $tag, 1); $tag = preg_replace('/\s+src=("|\')[^"\']*\1/i', '', $tag, 1); $attributes = sprintf( ' type="text/plain" data-acookies-managed="true" data-acookies-category="%s" data-acookies-src="%s"', esc_attr($category), esc_url($blocked_src) ); return preg_replace('/ $settings['google_consent_integration'] === 'gtm' ? 'gtm' : 'gtag', 'developerId' => defined('ACOOKIES_GOOGLE_DEVELOPER_ID') ? ACOOKIES_GOOGLE_DEVELOPER_ID : '', 'debug' => !empty($settings['google_consent_debug']), ); // Queue the default/restore bridge first, in the head, before optional tags. wp_enqueue_script('acookies-consent-bridge', ACCOMPLICE_COOKIES_URL . 'assets/consent-bridge.js', array(), ACCOMPLICE_COOKIES_VERSION, false); wp_add_inline_script('acookies-consent-bridge', 'window.AcookiesConsentConfig = ' . wp_json_encode($bridge_config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';', 'before'); wp_add_inline_script('acookies-consent-bridge', 'if (window.AcookiesConsent && window.AcookiesConsent.getConsent()) { document.documentElement.classList.add("acookies-consent-stored"); }', 'after'); wp_enqueue_style('acookies-consent-bridge', ACCOMPLICE_COOKIES_URL . 'assets/consent-bridge.css', array(), ACCOMPLICE_COOKIES_VERSION); } public function enqueue_frontend_assets() { $settings = self::get_settings(); $asset_file = ACCOMPLICE_COOKIES_DIR . 'build/banner/index.asset.php'; $script_file = ACCOMPLICE_COOKIES_DIR . 'build/banner/index.js'; $style_file = ACCOMPLICE_COOKIES_DIR . 'build/banner/style-index.css'; if (!file_exists($asset_file) || !file_exists($script_file)) { if (current_user_can('manage_options')) { wp_register_script('accomplice-cookies-build-missing', '', array(), ACCOMPLICE_COOKIES_VERSION, true); wp_enqueue_script('accomplice-cookies-build-missing'); wp_add_inline_script( 'accomplice-cookies-build-missing', 'console.warn("ACookies banner assets are missing. Run npm install && npm run build in the plugin directory.");' ); } return; } $asset = include $asset_file; $dependencies = isset($asset['dependencies']) && is_array($asset['dependencies']) ? $asset['dependencies'] : array(); $dependencies[] = 'acookies-consent-bridge'; $version = isset($asset['version']) ? $asset['version'] : ACCOMPLICE_COOKIES_VERSION; if (file_exists($style_file)) { wp_enqueue_style( 'accomplice-cookies-banner', ACCOMPLICE_COOKIES_URL . 'build/banner/style-index.css', array(), $version ); } wp_enqueue_script( 'accomplice-cookies-banner', ACCOMPLICE_COOKIES_URL . 'build/banner/index.js', $dependencies, $version, true ); wp_localize_script('accomplice-cookies-banner', 'AccompliceCookies', $this->frontend_banner_config($settings)); } public function render_server_banner_fallback() { $script_file = ACCOMPLICE_COOKIES_DIR . 'build/banner/index.js'; if ($this->server_banner_rendered || !file_exists($script_file)) { return; } $this->server_banner_rendered = true; $config = $this->frontend_banner_config(); $language = $this->server_banner_language($config); $translation = isset($config['translations'][$language]) ? $config['translations'][$language] : array(); $labels = isset($translation['labels']) && is_array($translation['labels']) ? $translation['labels'] : array(); $direction = isset($translation['dir']) ? $translation['dir'] : 'ltr'; $position = in_array($config['bannerPosition'], array('bottom-right', 'bottom-left', 'bottom-center', 'top-right', 'top-left'), true) ? $config['bannerPosition'] : 'bottom-right'; $use_theme_buttons = isset($config['buttonStyleMode']) && $config['buttonStyleMode'] === 'theme'; $banner_classes = array( 'ac-cookie-banner', 'cookie-consent-banner', 'ac-cookie-banner--' . $position, $use_theme_buttons ? 'ac-cookie-banner--theme-buttons' : 'ac-cookie-banner--custom-buttons', ); $secondary_button_classes = array('ac-cookie-button', 'ac-cookie-button-secondary'); $primary_button_classes = array('ac-cookie-button', 'ac-cookie-button-primary'); if ($use_theme_buttons) { $secondary_button_classes[] = 'wp-element-button'; $primary_button_classes[] = 'wp-element-button'; } ?> enabled_languages($settings); $current_language = $this->current_language(); $languages = $this->supported_languages(); $banner_translations = array(); $cookie_details = array(); $policy_cookies = $this->get_policy_cookies(); foreach ($enabled_languages as $language) { $texts = $this->language_texts($language); $banner_translations[$language] = array( 'dir' => isset($languages[$language]['dir']) ? $languages[$language]['dir'] : 'ltr', 'bannerTitle' => $texts['banner_title'], 'bannerText' => $texts['banner_text'], 'labels' => array( 'required' => $texts['label_required'], 'analytics' => $texts['label_analytics'], 'marketing' => $texts['label_marketing'], 'preferences' => $texts['label_preferences'], 'acceptAll' => $texts['accept_all'], 'rejectAll' => $texts['reject_optional'], 'customize' => $texts['customize'], 'save' => $texts['save_choices'], 'back' => $texts['back_to_banner'], 'privacy' => $texts['privacy_policy'], 'cookieSettings' => isset($texts['cookie_settings']) ? $texts['cookie_settings'] : __('Cookie settings', 'acookies'), 'preferencesTitle' => isset($texts['preferences_title']) ? $texts['preferences_title'] : $texts['customize'], 'requiredHelp' => isset($texts['required_help']) ? $texts['required_help'] : __('Required cookies are always active because they are needed for the website to work.', 'acookies'), 'saved' => isset($texts['choices_saved']) ? $texts['choices_saved'] : __('Cookie choices saved.', 'acookies'), 'cookieSingular' => $texts['cookie_singular'], 'cookiePlural' => $texts['cookie_plural'], 'showDetails' => $texts['show_details'], 'hideDetails' => $texts['hide_details'], 'noCookiesListed' => $texts['no_cookies_listed'], 'provider' => $texts['table_provider'], 'purpose' => $texts['table_purpose'], 'duration' => $texts['table_duration'], 'type' => $texts['table_type'], 'privacyInfo' => $texts['table_privacy_info'], 'alwaysActive' => $texts['always_active'], 'optional' => $texts['optional'], ), ); $cookie_details[$language] = $this->frontend_cookie_details_for_language($language, $policy_cookies); } $privacy_url = !empty($settings['privacy_url']) ? $settings['privacy_url'] : $this->default_cookie_policy_url(); return array( 'restUrl' => esc_url_raw(rest_url(self::REST_NAMESPACE . '/consent')), 'nonce' => wp_create_nonce('wp_rest'), 'policyVersion' => $settings['policy_version'], 'defaultLanguage' => $this->normalize_language_code($settings['default_language']), 'currentLanguage' => $current_language, 'hasExplicitSiteLanguage' => $this->has_explicit_site_language(), 'enabledLanguages' => $enabled_languages, 'translations' => $banner_translations, 'cookieDetails' => $cookie_details, 'wpConsentApiEnabled' => $this->is_wp_consent_api_available(), 'gaMeasurementId' => $settings['ga_measurement_id'], 'gtmId' => $settings['gtm_id'], 'googleConsentIntegration' => $settings['google_consent_integration'], 'googleBannerTemplate' => !empty($settings['google_banner_template']), 'googleConsentDisclosure' => __('With your consent, Google tags can collect data for analytics and advertising personalization.', 'acookies'), 'googlePrivacyLabel' => __('How Google uses data', 'acookies'), 'googleAllowPreConsent' => !empty($settings['google_allow_pre_consent']), 'bannerPosition' => $settings['banner_position'], 'privacyUrl' => $privacy_url, 'bannerStyles' => array( 'background' => $settings['banner_background_color'], 'textColor' => $settings['banner_text_color'], 'borderColor' => $settings['banner_border_color'], 'borderWidth' => absint($settings['banner_border_width']), 'borderRadius' => absint($settings['banner_border_radius']), ), 'buttonStyleMode' => $settings['button_style_mode'], 'buttonStyles' => array( 'primaryBackground' => $settings['button_primary_background'], 'primaryText' => $settings['button_primary_text'], 'primaryBorder' => $settings['button_primary_border_color'], 'primaryBorderWidth' => absint($settings['button_primary_border_width']), 'primaryHoverBackground' => $settings['button_primary_hover_background'], 'primaryHoverText' => $settings['button_primary_hover_text'], 'primaryHoverBorder' => $settings['button_primary_hover_border_color'], 'secondaryBackground' => $settings['button_secondary_background'], 'secondaryText' => $settings['button_secondary_text'], 'secondaryBorder' => $settings['button_secondary_border_color'], 'secondaryBorderWidth' => absint($settings['button_secondary_border_width']), 'secondaryHoverBackground' => $settings['button_secondary_hover_background'], 'secondaryHoverText' => $settings['button_secondary_hover_text'], 'secondaryHoverBorder' => $settings['button_secondary_hover_border_color'], 'borderColor' => $settings['button_border_color'], 'borderRadius' => absint($settings['button_border_radius']), ), ); } private function server_banner_language($config) { if (isset($config['translations'][$config['currentLanguage']])) { return $config['currentLanguage']; } if (isset($config['translations'][$config['defaultLanguage']])) { return $config['defaultLanguage']; } $languages = array_keys($config['translations']); return !empty($languages) ? reset($languages) : 'en_US'; } private function banner_style_attribute($config) { $banner_styles = isset($config['bannerStyles']) && is_array($config['bannerStyles']) ? $config['bannerStyles'] : array(); $button_styles = isset($config['buttonStyles']) && is_array($config['buttonStyles']) ? $config['buttonStyles'] : array(); $styles = array( '--ac-banner-background:' . (isset($banner_styles['background']) ? $banner_styles['background'] : '#ffffff'), '--ac-banner-text-color:' . (isset($banner_styles['textColor']) ? $banner_styles['textColor'] : '#141414'), '--ac-banner-border-color:' . (isset($banner_styles['borderColor']) ? $banner_styles['borderColor'] : '#d6d6d6'), '--ac-banner-border-size:' . absint(isset($banner_styles['borderWidth']) ? $banner_styles['borderWidth'] : 0) . 'px', '--ac-banner-border-radius:' . absint(isset($banner_styles['borderRadius']) ? $banner_styles['borderRadius'] : 8) . 'px', ); if (!isset($config['buttonStyleMode']) || $config['buttonStyleMode'] !== 'theme') { $styles = array_merge($styles, array( '--ac-button-primary-background:' . (isset($button_styles['primaryBackground']) ? $button_styles['primaryBackground'] : '#1f1f1f'), '--ac-button-primary-text:' . (isset($button_styles['primaryText']) ? $button_styles['primaryText'] : '#ffffff'), '--ac-button-primary-border:' . (isset($button_styles['primaryBorder']) ? $button_styles['primaryBorder'] : '#1f1f1f'), '--ac-button-primary-border-size:' . absint(isset($button_styles['primaryBorderWidth']) ? $button_styles['primaryBorderWidth'] : 1) . 'px', '--ac-button-primary-hover-background:' . (isset($button_styles['primaryHoverBackground']) ? $button_styles['primaryHoverBackground'] : '#333333'), '--ac-button-primary-hover-text:' . (isset($button_styles['primaryHoverText']) ? $button_styles['primaryHoverText'] : '#ffffff'), '--ac-button-primary-hover-border:' . (isset($button_styles['primaryHoverBorder']) ? $button_styles['primaryHoverBorder'] : '#333333'), '--ac-button-secondary-background:' . (isset($button_styles['secondaryBackground']) ? $button_styles['secondaryBackground'] : '#ffffff'), '--ac-button-secondary-text:' . (isset($button_styles['secondaryText']) ? $button_styles['secondaryText'] : '#1f1f1f'), '--ac-button-secondary-border:' . (isset($button_styles['secondaryBorder']) ? $button_styles['secondaryBorder'] : '#1f1f1f'), '--ac-button-secondary-border-size:' . absint(isset($button_styles['secondaryBorderWidth']) ? $button_styles['secondaryBorderWidth'] : 1) . 'px', '--ac-button-secondary-hover-background:' . (isset($button_styles['secondaryHoverBackground']) ? $button_styles['secondaryHoverBackground'] : '#f2f2f2'), '--ac-button-secondary-hover-text:' . (isset($button_styles['secondaryHoverText']) ? $button_styles['secondaryHoverText'] : '#1f1f1f'), '--ac-button-secondary-hover-border:' . (isset($button_styles['secondaryHoverBorder']) ? $button_styles['secondaryHoverBorder'] : '#1f1f1f'), '--ac-button-border-radius:' . absint(isset($button_styles['borderRadius']) ? $button_styles['borderRadius'] : 6) . 'px', )); } return implode(';', $styles) . ';'; } public function register_rest_routes() { register_rest_route(self::REST_NAMESPACE, '/consent', array( 'methods' => 'POST', 'callback' => array($this, 'record_consent'), 'permission_callback' => '__return_true', 'args' => array( 'consentId' => array('type' => 'string', 'required' => true), 'categories' => array('type' => 'object', 'required' => true), 'policyVersion' => array('type' => 'string', 'required' => true), 'languageCode' => array('type' => 'string', 'required' => false), ), )); } public function record_consent(WP_REST_Request $request) { global $wpdb; $categories = $request->get_param('categories'); $allowed = array('required', 'analytics', 'marketing', 'preferences'); $clean = array(); foreach ($allowed as $category) { $clean[$category] = !empty($categories[$category]); } $clean['required'] = true; $consent_id = sanitize_text_field($request->get_param('consentId')); $policy_version = sanitize_text_field($request->get_param('policyVersion')); $language_code = $this->normalize_language_code(sanitize_text_field((string) $request->get_param('languageCode'))); $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''; $ua = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : ''; $inserted = $wpdb->insert( self::table_name('consents'), array( 'consent_id' => $consent_id, 'categories' => wp_json_encode($clean), 'policy_version' => $policy_version, 'language_code' => $language_code, 'ip_hash' => hash_hmac('sha256', $this->truncate_ip($ip), wp_salt('auth')), 'user_agent_hash' => hash_hmac('sha256', $ua, wp_salt('auth')), 'created_at' => current_time('mysql'), ), array('%s', '%s', '%s', '%s', '%s', '%s', '%s') ); if (!$inserted) { return new WP_Error('accomplice_cookies_log_failed', __('Could not record consent.', 'acookies'), array('status' => 500)); } $settings = self::get_settings(); $retention_days = max(1, min(30, absint($settings['consent_retention_days']))); $cutoff = wp_date('Y-m-d H:i:s', current_time('timestamp') - ($retention_days * DAY_IN_SECONDS)); $wpdb->query($wpdb->prepare( "DELETE FROM %i WHERE created_at < %s", self::table_name('consents'), $cutoff )); $oldest_retained_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM %i ORDER BY id DESC LIMIT 1 OFFSET 999", self::table_name('consents'))); if ($oldest_retained_id) { $wpdb->query($wpdb->prepare( "DELETE FROM %i WHERE id < %d", self::table_name('consents'), absint($oldest_retained_id) )); } return rest_ensure_response(array('ok' => true)); } private function truncate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return preg_replace('/\.\d+$/', '.0', $ip); } if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $parts = explode(':', $ip); return implode(':', array_slice($parts, 0, 4)) . '::'; } return ''; } public function run_scheduled_scan() { $settings = self::get_settings(); $entitlement = ACookies_Scanner_Entitlement::resolve(); if (!self::managed_scanner_is_enabled($settings) || !$entitlement['eligible'] || !in_array($settings['scan_recurrence'], array('daily', 'weekly'), true)) { return; } $this->start_scan(); $this->refresh_pending_scans(); } public function run_scan_result_poll() { $result = $this->refresh_pending_scans(); if (!is_wp_error($result) && $this->has_pending_scans()) { self::schedule_scan_result_poll(2 * MINUTE_IN_SECONDS); } } public function maybe_schedule_pending_scan_poll() { if (self::managed_scanner_is_enabled(self::get_settings()) && $this->has_pending_scans()) { self::schedule_scan_result_poll(); } } public function handle_manual_scan() { if (!current_user_can('manage_options') || !check_admin_referer('accomplice_cookies_run_scan')) { wp_die(esc_html__('Not allowed.', 'acookies')); } if (isset($_POST['scanner_terms_accepted']) && $_POST['scanner_terms_accepted'] === '1') { $this->accept_scanner_terms(); } $result = $this->start_scan(); $this->redirect_after_action($result, 'scans', __('Scan submitted.', 'acookies')); } public function handle_disable_managed_scanner() { if (!current_user_can('manage_options') || !check_admin_referer('acookies_disable_managed_scanner')) { wp_die(esc_html__('Not allowed.', 'acookies')); } $settings = get_option(self::OPTION_KEY, array()); $settings['managed_scanner_enabled'] = false; $settings['scanner_terms_accepted_at'] = ''; $settings['scanner_access_token'] = ''; $settings['scanner_token_expires_at'] = ''; update_option(self::OPTION_KEY, $settings, false); delete_option(ACookies_Scanner_Entitlement::CACHE_KEY); self::deactivate(); $this->redirect_after_action(true, 'scans', __('Managed scanning is off.', 'acookies')); } public function handle_refresh_scans() { if (!current_user_can('manage_options') || !check_admin_referer('accomplice_cookies_refresh_scans')) { wp_die(esc_html__('Not allowed.', 'acookies')); } $result = $this->refresh_pending_scans(); $this->redirect_after_action($result, 'scans'); } public function handle_ajax_refresh_scans() { if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Not allowed.', 'acookies')), 403); } check_ajax_referer('accomplice_cookies_refresh_scans'); $result = $this->refresh_pending_scans(); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message()), 400); } ob_start(); $this->render_scans_table($this->get_recent_scans()); $table = ob_get_clean(); wp_send_json_success(array( 'message' => __('Scan results refreshed.', 'acookies'), 'table' => $table, 'hasPending' => $this->has_pending_scans(), )); } public function handle_review_cookie() { global $wpdb; $cookie_id = isset($_POST['cookie_id']) ? absint($_POST['cookie_id']) : 0; if (!current_user_can('manage_options') || !$cookie_id || !check_admin_referer('accomplice_cookies_review_cookie_' . $cookie_id)) { wp_die(esc_html__('Not allowed.', 'acookies')); } $category = isset($_POST['category']) ? sanitize_key(wp_unslash($_POST['category'])) : 'unclassified'; if (!in_array($category, array('required', 'analytics', 'marketing', 'preferences', 'unclassified'), true)) { $category = 'unclassified'; } $descriptions = isset($_POST['descriptions']) && is_array($_POST['descriptions']) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitize_description_map validates locale keys and sanitizes every description. ? $this->sanitize_description_map(wp_unslash($_POST['descriptions'])) : array(); $saved_cookie = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", self::table_name('detected'), $cookie_id)); if (!$saved_cookie) { wp_die(esc_html__('Cookie not found.', 'acookies')); } $resolved_cookie = ACookies_Cookie_Catalogue::resolve($saved_cookie); $classification = ACookies_Cookie_Catalogue::metadata($resolved_cookie); $classification['approval'] = array('category' => $classification['category'], 'provider' => $classification['provider'], 'evidenceSignature' => $classification['evidenceSignature']); unset($classification['approvalConflict'], $classification['identityConflict']); $wpdb->update( self::table_name('detected'), array( 'category' => $category, 'description_overrides' => wp_json_encode($descriptions), 'classification' => wp_json_encode($classification), 'reviewed' => 1, ), array('id' => $cookie_id), array('%s', '%s', '%s', '%d'), array('%d') ); $this->redirect_after_action(true, 'cookie-list'); } private function sanitize_description_map($values) { $output = array(); if (!is_array($values)) { return $output; } foreach ($values as $language => $description) { $language = $this->normalize_language_code(sanitize_text_field($language)); $description = sanitize_textarea_field($description); if ($description !== '') { $output[$language] = $description; } } return $output; } private function redirect_after_action($result, $tab = 'stats', $notice = '') { $args = array( 'page' => self::ADMIN_SLUG, 'tab' => sanitize_key($tab), ); if (is_wp_error($result)) { $args['ac_error'] = rawurlencode($result->get_error_message()); } else { $args['ac_notice'] = rawurlencode($notice !== '' ? $notice : __('Action completed.', 'acookies')); } wp_safe_redirect(add_query_arg($args, admin_url('options-general.php'))); exit; } private function start_scan() { global $wpdb; $settings = self::get_settings(); if (!self::managed_scanner_is_enabled($settings)) { return new WP_Error('accomplice_cookies_scanner_not_enabled', __('To start scanning, choose Agree and run scan on the Scans tab.', 'acookies')); } $token_result = $this->ensure_managed_scanner_token(); if (is_wp_error($token_result)) { return $token_result; } $settings = self::get_settings(); $urls = $this->build_scan_urls($settings); $default_language = $this->normalize_language_code($settings['default_language']); $enabled_languages = $this->enabled_languages($settings); $wpdb->insert( self::table_name('scans'), array( 'status' => 'pending', 'site_url' => home_url('/'), 'urls' => wp_json_encode($urls), 'started_at' => current_time('mysql'), ), array('%s', '%s', '%s', '%s') ); $scan_id = $wpdb->insert_id; $response = wp_remote_post(trailingslashit($settings['scanner_url']) . 'scans', array( 'timeout' => 20, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $settings['scanner_access_token'], ), 'body' => wp_json_encode(array( 'siteUrl' => home_url('/'), 'urls' => $urls, 'defaultLanguage' => $default_language, 'enabledLanguages' => $enabled_languages, 'options' => array( 'maxPages' => count($urls), 'timeoutMs' => 30000, ), )), )); if (is_wp_error($response)) { $this->mark_scan_failed($scan_id, $response->get_error_message()); return $response; } $status = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($status < 200 || $status >= 300 || empty($body['id'])) { $message = isset($body['error']) ? $body['error'] : __('Scanner rejected the scan request.', 'acookies'); $this->mark_scan_failed($scan_id, $message); return new WP_Error('accomplice_cookies_scanner_error', $message); } $wpdb->update( self::table_name('scans'), array( 'scanner_id' => sanitize_text_field($body['id']), 'status' => sanitize_text_field($body['status']), ), array('id' => $scan_id), array('%s', '%s'), array('%d') ); self::schedule_scan_result_poll(); return true; } private function refresh_pending_scans() { global $wpdb; $settings = self::get_settings(); $token_result = $this->ensure_managed_scanner_token(); if (is_wp_error($token_result)) { return $token_result; } $settings = self::get_settings(); $scans = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE scanner_id <> '' AND status IN ('queued', 'running', 'pending') ORDER BY id DESC LIMIT 10", self::table_name('scans'))); foreach ($scans as $scan) { $response = wp_remote_get(trailingslashit($settings['scanner_url']) . 'scans/' . rawurlencode($scan->scanner_id), array( 'timeout' => 20, 'headers' => array( 'Authorization' => 'Bearer ' . $settings['scanner_access_token'], ), )); if (is_wp_error($response)) { continue; } $status = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($status < 200 || $status >= 300 || empty($body['status'])) { continue; } $this->store_scan_result((int) $scan->id, $body); } if ($this->has_pending_scans()) { self::schedule_scan_result_poll(2 * MINUTE_IN_SECONDS); } return true; } private function ensure_managed_scanner_token() { $settings = self::get_settings(); if (!self::managed_scanner_is_enabled($settings)) { return new WP_Error('accomplice_cookies_scanner_not_enabled', __('The managed scanner has not been enabled.', 'acookies')); } $expires_at = !empty($settings['scanner_token_expires_at']) ? strtotime($settings['scanner_token_expires_at']) : 0; $entitlement = ACookies_Scanner_Entitlement::resolve(); if (!empty($settings['scanner_access_token']) && $expires_at > time() + MINUTE_IN_SECONDS && $entitlement['verified']) { return true; } $installation_id = !empty($settings['installation_id']) ? sanitize_text_field($settings['installation_id']) : wp_generate_uuid4(); $registration = array( 'installationId' => $installation_id, 'siteUrl' => home_url('/'), 'pluginVersion' => ACCOMPLICE_COOKIES_VERSION, 'dataProcessingAccepted' => true, 'scannerProtocol' => ACookies_Scanner_Entitlement::SCANNER_PROTOCOL, ); if ($entitlement['eligible']) { $proof = ACookies_Scanner_Entitlement::sign_registration($registration, $entitlement['site']); if (is_wp_error($proof)) { return $proof; } $registration['freemius'] = $proof; } $response = wp_remote_post(trailingslashit($settings['scanner_url']) . 'installations', array( 'timeout' => 20, 'headers' => array('Content-Type' => 'application/json'), 'body' => wp_json_encode($registration), )); if (is_wp_error($response)) { $this->remember_scanner_verification_error($entitlement, $response->get_error_message()); return $response; } $status = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($status < 200 || $status >= 300 || empty($body['token']) || empty($body['expiresAt'])) { $message = !empty($body['error']) ? sanitize_text_field($body['error']) : __('Could not register this site with the managed scanner.', 'acookies'); $this->remember_scanner_verification_error($entitlement, $message); return new WP_Error('accomplice_cookies_scanner_registration_failed', $message); } $plan = isset($body['plan']) ? $body['plan'] : 'free'; $token_expires = strtotime($body['expiresAt']); if ($plan !== $entitlement['plan'] || !$token_expires || $token_expires <= time() || ($plan === 'pro' && ($token_expires > time() + (15 * MINUTE_IN_SECONDS) + 10 || empty($body['limits']['pagesPerScan']) || (int) $body['limits']['pagesPerScan'] !== $entitlement['pages'] || empty($body['limits']['scansPerDay']) || (int) $body['limits']['scansPerDay'] < 2))) { $message = __('The scanner service has not verified this site’s Premium access. Your saved preferences are preserved. Retry after the managed API is updated or check ACookies Account.', 'acookies'); $this->remember_scanner_verification_error($entitlement, $message); return new WP_Error('acookies_scanner_entitlement_mismatch', $message); } $options = get_option(self::OPTION_KEY, array()); $options['installation_id'] = $installation_id; $options['scanner_access_token'] = sanitize_text_field($body['token']); $options['scanner_token_expires_at'] = sanitize_text_field($body['expiresAt']); update_option(self::OPTION_KEY, $options, false); update_option(ACookies_Scanner_Entitlement::CACHE_KEY, array( 'fingerprint' => $entitlement['fingerprint'], 'plan' => $plan, 'expires_at' => $token_expires, 'error' => '', ), false); self::schedule_scan(); if (empty($settings['installation_id'])) { $this->record_managed_event('activation'); } return true; } private function remember_scanner_verification_error($entitlement, $message) { $cache = get_option(ACookies_Scanner_Entitlement::CACHE_KEY, array()); $cache = is_array($cache) ? $cache : array(); $cache['error'] = sanitize_text_field($message); update_option(ACookies_Scanner_Entitlement::CACHE_KEY, $cache, false); } private function import_generator_scan($code) { global $wpdb; $code = sanitize_text_field($code); if (!preg_match('/^AC-[A-Za-z0-9_-]{16,32}$/', $code)) { return new WP_Error('acookies_import_code_invalid', __('Enter a valid ACookies generator import code.', 'acookies')); } $token_result = $this->ensure_managed_scanner_token(); if (is_wp_error($token_result)) { return $token_result; } $settings = self::get_settings(); $response = wp_remote_post(trailingslashit($settings['scanner_url']) . 'imports/' . rawurlencode($code), array( 'timeout' => 20, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $settings['scanner_access_token'], ), 'body' => '{}', )); if (is_wp_error($response)) { return $response; } $status = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($status < 200 || $status >= 300 || empty($body['status']) || $body['status'] !== 'completed') { $message = !empty($body['error']) ? sanitize_text_field($body['error']) : __('The generator scan could not be imported.', 'acookies'); return new WP_Error('acookies_import_failed', $message); } $wpdb->insert( self::table_name('scans'), array( 'scanner_id' => sanitize_text_field(isset($body['id']) ? $body['id'] : 'generator-import'), 'status' => 'pending', 'site_url' => esc_url_raw(isset($body['siteUrl']) ? $body['siteUrl'] : home_url('/')), 'urls' => wp_json_encode(array(home_url('/'))), 'started_at' => current_time('mysql'), ), array('%s', '%s', '%s', '%s', '%s') ); $this->store_scan_result((int) $wpdb->insert_id, $body); return true; } private function record_managed_event($event) { if (!in_array($event, array('activation', 'onboarding_complete', 'first_scan', 'policy_published'), true)) { return; } $settings = self::get_settings(); if ( !self::managed_scanner_is_enabled($settings) || empty($settings['scanner_access_token']) || empty($settings['scanner_url']) ) { return; } wp_remote_post(trailingslashit($settings['scanner_url']) . 'events', array( 'timeout' => 5, 'blocking' => false, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $settings['scanner_access_token'], ), 'body' => wp_json_encode(array( 'event' => $event, 'pluginVersion' => ACCOMPLICE_COOKIES_VERSION, )), )); } private function has_pending_scans() { global $wpdb; return (bool) $wpdb->get_var( $wpdb->prepare("SELECT id FROM %i WHERE scanner_id <> '' AND status IN ('queued', 'running', 'pending') LIMIT 1", self::table_name('scans')) ); } private function store_scan_result($scan_id, $body) { global $wpdb; $data = array( 'status' => sanitize_text_field($body['status']), 'result' => wp_json_encode($body), ); $format = array('%s', '%s'); if (in_array($body['status'], array('completed', 'failed'), true)) { $data['completed_at'] = current_time('mysql'); $format[] = '%s'; } if (!empty($body['error'])) { $data['error'] = sanitize_textarea_field($body['error']); $format[] = '%s'; } $wpdb->update(self::table_name('scans'), $data, array('id' => $scan_id), $format, array('%d')); if ($body['status'] === 'completed') { $this->record_managed_event('first_scan'); } if ($body['status'] !== 'completed' || empty($body['cookies']) || !is_array($body['cookies'])) { return; } $incoming_paths = array(); $identity_conflicts = array(); $legacy_approvals = array(); $incoming_identities = array(); foreach ($body['cookies'] as $incoming) { $name = sanitize_text_field($incoming['name'] ?? ''); $domain = sanitize_text_field($incoming['domain'] ?? ''); $key = wp_json_encode(array($name, $domain)); $incoming_identities[$key] = array($name, $domain); $incoming_paths[$key][sanitize_text_field($incoming['path'] ?? '')] = true; } // Reconcile unscoped legacy rows before processing any path in the new scan. foreach ($incoming_identities as $key => $identity) { $paths = array_keys($incoming_paths[$key]); if (count($paths) === 1 && $paths[0] === '') { continue; } list($name, $domain) = $identity; $legacy = $wpdb->get_row($wpdb->prepare( "SELECT * FROM %i WHERE name = %s AND domain = %s AND path = '' AND superseded = 0 ORDER BY id DESC LIMIT 1", self::table_name('detected'), $name, $domain )); if (!$legacy) { continue; } if (count($paths) === 1) { $exact = $wpdb->get_row($wpdb->prepare( "SELECT * FROM %i WHERE name = %s AND domain = %s AND path = %s AND superseded = 0 ORDER BY id DESC LIMIT 1", self::table_name('detected'), $name, $domain, $paths[0] )); if (!$exact) { $wpdb->update(self::table_name('detected'), array('path' => $paths[0]), array('name' => $name, 'domain' => $domain, 'path' => ''), array('%s'), array('%s', '%s', '%s')); continue; } if (empty($exact->reviewed) && !empty($legacy->reviewed)) { $legacy_approvals[$key] = $legacy; } } else { $identity_conflicts[$key] = !empty($legacy->reviewed); } $wpdb->update(self::table_name('detected'), array('superseded' => 1), array('name' => $name, 'domain' => $domain, 'path' => ''), array('%d'), array('%s', '%s', '%s')); } foreach ($body['cookies'] as $cookie) { $name = sanitize_text_field(isset($cookie['name']) ? $cookie['name'] : ''); $domain = sanitize_text_field(isset($cookie['domain']) ? $cookie['domain'] : ''); $path = sanitize_text_field(isset($cookie['path']) ? $cookie['path'] : ''); $source_url = isset($cookie['sourceUrl']) ? $cookie['sourceUrl'] : ''; if ($source_url === '' && !empty($cookie['sourceUrls']) && is_array($cookie['sourceUrls'])) { $source_url = reset($cookie['sourceUrls']); } $script_src = isset($cookie['scriptSrc']) ? $cookie['scriptSrc'] : ''; if ($script_src === '' && !empty($cookie['scriptEvidence']) && is_array($cookie['scriptEvidence'])) { $script_src = reset($cookie['scriptEvidence']); } $descriptions = isset($cookie['descriptions']) && is_array($cookie['descriptions']) ? $this->sanitize_description_map($cookie['descriptions']) : array(); $previous = $wpdb->get_row($wpdb->prepare( "SELECT * FROM %i WHERE name = %s AND domain = %s AND path = %s AND superseded = 0 ORDER BY id DESC LIMIT 1", self::table_name('detected'), $name, $domain, $path )); $identity_key = wp_json_encode(array($name, $domain)); if (!empty($legacy_approvals[$identity_key])) { $previous = $legacy_approvals[$identity_key]; } if (empty($descriptions) && !empty($cookie['purpose'])) { $descriptions['en_US'] = sanitize_textarea_field($cookie['purpose']); } $classification = isset($cookie['classification']) && is_array($cookie['classification']) ? $cookie['classification'] : array(); $previous_classification = $previous ? ACookies_Cookie_Catalogue::metadata(ACookies_Cookie_Catalogue::resolve($previous)) : array(); if (!empty($previous_classification['approval'])) { $classification['approval'] = $previous_classification['approval']; } if (!empty($identity_conflicts[$identity_key]) || !empty($previous_classification['identityConflict'])) { $classification['identityConflict'] = true; } $resolved = ACookies_Cookie_Catalogue::resolve((object) array( 'name' => $name, 'domain' => $domain, 'category' => $previous && !empty($previous->reviewed) ? $previous->category : sanitize_key($cookie['category'] ?? 'unclassified'), 'reviewed' => $previous ? (int) $previous->reviewed : 0, 'classification' => $classification, )); $category = $resolved->category; $wpdb->insert( self::table_name('detected'), array( 'scan_id' => $scan_id, 'name' => $name, 'domain' => $domain, 'path' => $path, 'category' => $category, 'provider' => sanitize_text_field($resolved->provider), 'classification' => $resolved->classification, 'source_url' => esc_url_raw($source_url), 'script_src' => esc_url_raw($script_src), 'descriptions' => wp_json_encode($descriptions), 'description_overrides' => $previous && !empty($previous->description_overrides) ? $previous->description_overrides : wp_json_encode(array()), 'expires' => isset($cookie['expires']) ? (int) $cookie['expires'] : 0, 'http_only' => !empty($cookie['httpOnly']) ? 1 : 0, 'secure' => !empty($cookie['secure']) ? 1 : 0, 'same_site' => sanitize_text_field(isset($cookie['sameSite']) ? $cookie['sameSite'] : ''), 'first_party' => !empty($cookie['firstParty']) ? 1 : 0, 'reviewed' => $previous ? (int) $previous->reviewed : 0, 'created_at' => current_time('mysql'), ), array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%d', '%s') ); } } private function mark_scan_failed($scan_id, $message) { global $wpdb; $wpdb->update( self::table_name('scans'), array( 'status' => 'failed', 'error' => sanitize_textarea_field($message), 'completed_at' => current_time('mysql'), ), array('id' => $scan_id), array('%s', '%s', '%s'), array('%d') ); } private function build_scan_urls($settings) { $urls = array(home_url('/')); $cookie_policy_url = !empty($settings['privacy_url']) ? $settings['privacy_url'] : $this->default_cookie_policy_url(); if ($cookie_policy_url) { $urls[] = $cookie_policy_url; } if (function_exists('wc_get_page_permalink')) { foreach (array('cart', 'checkout') as $page) { $url = wc_get_page_permalink($page); if ($url) { $urls[] = $url; } } } $sample_size = isset($settings['scan_sample_size']) ? absint($settings['scan_sample_size']) : 10; if ($sample_size > 0) { $posts = get_posts(array( 'post_type' => array('page', 'post'), 'post_status' => 'publish', 'numberposts' => $sample_size, 'orderby' => 'modified', 'order' => 'DESC', 'fields' => 'ids', )); foreach ($posts as $post_id) { $urls[] = get_permalink($post_id); } } $urls = array_values(array_unique(array_filter($urls))); $urls = apply_filters('accomplice_cookies_scan_urls', $urls); $entitlement = ACookies_Scanner_Entitlement::resolve(); $sample_size = max(1, min($entitlement['pages'], $sample_size)); // Apply both the configured sample and plan ceiling after filters, which // can add URLs. Never submit off-origin policy or third-party URLs. $origin = ACookies_Scanner_Entitlement::origin(home_url('/')); $urls = array_filter(is_array($urls) ? $urls : array(), function ($url) use ($origin) { return is_string($url) && ACookies_Scanner_Entitlement::origin($url) === $origin; }); return array_slice(array_values(array_unique($urls)), 0, $sample_size); } private function default_cookie_policy_url() { $page = get_page_by_path('cookie-policy'); if ($page && get_post_status($page) === 'publish') { return get_permalink($page); } return ''; } private function get_recent_scans() { global $wpdb; return $wpdb->get_results($wpdb->prepare("SELECT * FROM %i ORDER BY id DESC LIMIT 20", self::table_name('scans'))); } private function get_recent_consents() { global $wpdb; return $wpdb->get_results($wpdb->prepare("SELECT * FROM %i ORDER BY id DESC LIMIT 200", self::table_name('consents'))); } private function get_cookie_list() { return $this->get_policy_cookies(); } }