diff --git a/assets/admin/scanner.css b/assets/admin/scanner.css new file mode 100644 index 0000000..f0202bf --- /dev/null +++ b/assets/admin/scanner.css @@ -0,0 +1,108 @@ +/* FrontConsent Scanner: settings tab and dashboard widget. */ + +.frcn-scanner__summary { + display: flex; + gap: 16px; + align-items: center; + margin: 16px 0; +} + +.frcn-scanner--widget .frcn-scanner__summary { + margin: 0 0 8px; +} + +.frcn-scanner__grade { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-width: 72px; + height: 72px; + border-radius: 8px; + color: #fff; + background: #646970; +} + +.frcn-scanner__grade--a { background: #00a32a; } +.frcn-scanner__grade--b { background: #4f8a10; } +.frcn-scanner__grade--c { background: #996800; } +.frcn-scanner__grade--d { background: #c9480a; } +.frcn-scanner__grade--e, +.frcn-scanner__grade--f { background: #d63638; } + +.frcn-scanner__grade-letter { + font-size: 32px; + font-weight: 700; + line-height: 1; +} + +.frcn-scanner__score { + font-size: 12px; +} + +.frcn-scanner__headline { + margin: 0 0 4px; + font-size: 14px; + font-weight: 600; +} + +.frcn-scanner__counts, +.frcn-scanner__date { + margin: 0 0 4px; + color: #50575e; +} + +.frcn-scanner__count { + margin-right: 12px; + white-space: nowrap; +} + +.frcn-scanner__checks { + max-width: 760px; + margin: 0; + padding: 0; + list-style: none; +} + +.frcn-scanner__check { + display: flex; + gap: 10px; + padding: 10px 0; + border-top: 1px solid #dcdcde; +} + +.frcn-scanner__check p { + margin: 4px 0 0; +} + +.frcn-scanner__check-status { + color: #50575e; +} + +/* Status is never conveyed by colour alone: icon + text label. */ +.frcn-scanner__icon::before { + display: inline-block; + width: 1.4em; + font-weight: 700; + text-align: center; +} + +.frcn-scanner__status--pass .frcn-scanner__icon::before { content: "\2713"; color: #00a32a; } +.frcn-scanner__status--warn .frcn-scanner__icon::before { content: "!"; color: #996800; } +.frcn-scanner__status--fail .frcn-scanner__icon::before { content: "\2715"; color: #d63638; } +.frcn-scanner__status--not_applicable .frcn-scanner__icon::before, +.frcn-scanner__status--in_report .frcn-scanner__icon::before { content: "\2013"; color: #646970; } + +.frcn-scanner__pending .spinner { + float: none; + margin: 0 8px 0 0; +} + +.frcn-scanner__message--error, +.frcn-scanner__error { + color: #d63638; +} + +.frcn-scanner__widget-link { + margin-bottom: 0; +} diff --git a/assets/admin/scanner.js b/assets/admin/scanner.js new file mode 100644 index 0000000..bf0863d --- /dev/null +++ b/assets/admin/scanner.js @@ -0,0 +1,97 @@ +/** + * FrontConsent Scanner: starts a scan and follows it until it finishes. + * Used by the Scanner settings tab and the dashboard widget. + * + * @package FrontConsent + */ + +(function () { + 'use strict'; + + var config = window.frcnScanner; + + if (!config) { + return; + } + + function post(action) { + var body = new FormData(); + body.append('action', action); + body.append('nonce', config.nonce); + + return fetch(config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body }).then(function (response) { + return response.json().then(function (json) { + if (!json || !json.success) { + throw new Error(json && json.data && json.data.message ? json.data.message : config.i18n.error); + } + return json.data; + }, function () { + throw new Error(config.i18n.error); + }); + }); + } + + function initScanner(root) { + var button = root.querySelector('[data-frcn-scanner-start]'); + var result = root.querySelector('[data-frcn-scanner-result]'); + var message = root.querySelector('[data-frcn-scanner-message]'); + var compact = root.classList.contains('frcn-scanner--widget'); + var polls = 0; + + function setMessage(text, isError) { + if (!message) { + return; + } + message.textContent = text || ''; + message.classList.toggle('frcn-scanner__message--error', !!isError); + } + + function render(data) { + if (result) { + result.innerHTML = compact ? data.compactHtml : data.html; + } + if (button) { + button.disabled = !!data.pending; + } + // The rendered result shows its own "Analyzing…" line while pending. + setMessage(''); + if (!data.pending) { + return; + } + if (polls >= config.maxPolls) { + setMessage(config.i18n.timeout, true); + return; + } + window.setTimeout(poll, Math.max(3, data.pollAfterSeconds || 5) * 1000); + } + + function fail(error) { + if (button) { + button.disabled = false; + } + setMessage(error.message, true); + } + + function poll() { + polls++; + post('frcn_scanner_status').then(render, fail); + } + + if (button) { + button.addEventListener('click', function () { + button.disabled = true; + polls = 0; + setMessage(config.i18n.running); + post('frcn_scanner_start').then(render, fail); + }); + } + + if (result && result.hasAttribute('data-frcn-scanner-pending')) { + poll(); + } + } + + document.addEventListener('DOMContentLoaded', function () { + Array.prototype.forEach.call(document.querySelectorAll('[data-frcn-scanner]'), initScanner); + }); +})(); diff --git a/bin/build-assets.js b/bin/build-assets.js index 229941e..edb8dc9 100644 --- a/bin/build-assets.js +++ b/bin/build-assets.js @@ -29,14 +29,16 @@ const CleanCSS = require( 'clean-css' ); /** * Plugin-relative paths of every plain asset this script knows how to - * minify. Keep in sync with the enqueue calls in includes/Frontend/CookieNotice.php - * and includes/Admin/Settings.php. + * minify. Keep in sync with the enqueue calls in includes/Frontend/CookieNotice.php, + * includes/Admin/Settings.php and includes/Admin/Scanner.php. */ const ASSETS = [ { relativePath: 'assets/cookie-notice/frontconsent-cookie-notice.js', type: 'js' }, { relativePath: 'assets/cookie-notice/frontconsent-cookie-notice.css', type: 'css' }, { relativePath: 'assets/admin/settings.js', type: 'js' }, { relativePath: 'assets/admin/settings.css', type: 'css' }, + { relativePath: 'assets/admin/scanner.js', type: 'js' }, + { relativePath: 'assets/admin/scanner.css', type: 'css' }, ]; /** diff --git a/includes/Admin/Scanner.php b/includes/Admin/Scanner.php new file mode 100644 index 0000000..60ffce1 --- /dev/null +++ b/includes/Admin/Scanner.php @@ -0,0 +1,559 @@ + + */ + private static function status_labels() { + return array( + 'pass' => __( 'Pass', 'frontconsent' ), + 'warn' => __( 'Warning', 'frontconsent' ), + 'fail' => __( 'Fail', 'frontconsent' ), + 'not_applicable' => __( 'Not applicable', 'frontconsent' ), + 'in_report' => __( 'In the full report', 'frontconsent' ), + ); + } + + /** + * Constructor. + */ + public function __construct() { + add_filter( 'frontconsent_settings_tabs', array( $this, 'add_tab' ) ); + add_action( 'frontconsent_settings_tab_panels', array( $this, 'render_tab_panel' ) ); + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + add_action( 'wp_dashboard_setup', array( $this, 'register_dashboard_widget' ) ); + add_action( 'wp_ajax_frcn_scanner_start', array( $this, 'ajax_start' ) ); + add_action( 'wp_ajax_frcn_scanner_status', array( $this, 'ajax_status' ) ); + } + + /** + * Add the "Scanner" tab right after "Settings". + * + * @param array $tabs Settings tabs. + * @return array + */ + public function add_tab( $tabs ) { + array_splice( + $tabs, + 1, + 0, + array( + array( + 'id' => 'scanner', + 'label' => __( 'Scanner', 'frontconsent' ), + ), + ) + ); + + return $tabs; + } + + /** + * Enqueue the scanner script on the settings page and the dashboard. + * + * @param string $hook_suffix Current admin page hook suffix. + * @return void + */ + public function enqueue_assets( $hook_suffix ) { + if ( ! in_array( $hook_suffix, array( 'settings_page_' . self::PAGE_SLUG, 'index.php' ), true ) || ! current_user_can( 'manage_options' ) ) { + return; + } + + $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min'; + + foreach ( array( 'css', 'js' ) as $type ) { + $path = 'assets/admin/scanner' . $suffix . '.' . $type; + if ( ! file_exists( FRCN_PLUGIN_PATH . $path ) ) { + $path = 'assets/admin/scanner.' . $type; + } + + if ( 'css' === $type ) { + wp_enqueue_style( 'frontconsent-scanner', FRCN_PLUGIN_URL . $path, array(), FRCN_VERSION ); + } else { + wp_enqueue_script( 'frontconsent-scanner', FRCN_PLUGIN_URL . $path, array(), FRCN_VERSION, true ); + } + } + + wp_localize_script( + 'frontconsent-scanner', + 'frcnScanner', + array( + 'ajaxUrl' => admin_url( 'admin-ajax.php' ), + 'nonce' => wp_create_nonce( self::NONCE_ACTION ), + 'maxPolls' => 40, + 'i18n' => array( + 'running' => __( 'Analyzing your site… this usually takes under a minute.', 'frontconsent' ), + 'error' => __( 'The scan could not be completed. Please try again later.', 'frontconsent' ), + 'timeout' => __( 'The scan is taking longer than expected. Reload this page in a few minutes to see the result.', 'frontconsent' ), + ), + ) + ); + } + + /** + * Render the Scanner tab panel (outside the settings form). + * + * @return void + */ + public function render_tab_panel() { + $scan = self::get_stored_scan(); + ?> + + +
+
> + ' . esc_html__( 'Your site has not been scanned yet. Check whether your cookie banner complies with the GDPR and the AEPD guide.', 'frontconsent' ) . '

'; + } + ?> +
+ +
+ 0 ) { + wp_send_json_error( + array( + 'message' => sprintf( + /* translators: %d: minutes to wait. */ + _n( 'Your site was scanned a moment ago. You can scan it again in %d minute.', 'Your site was scanned a moment ago. You can scan it again in %d minutes.', (int) ceil( $remaining / 60 ), 'frontconsent' ), + (int) ceil( $remaining / 60 ) + ), + ), + 429 + ); + } + + $response = self::request( + 'POST', + 'scans', + array( 'url' => self::get_site_url() ) + ); + + if ( is_wp_error( $response ) ) { + wp_send_json_error( array( 'message' => $response->get_error_message() ), (int) $response->get_error_data() ); + } + + set_transient( self::COOLDOWN_TRANSIENT, time() + self::COOLDOWN_SECONDS, self::COOLDOWN_SECONDS ); + self::send_scan( self::store_scan( $response ) ); + } + + /** + * AJAX: refresh the stored scan while it is in progress. + * + * Only ever asks about the scan this site started, never a uuid sent by + * the browser. + * + * @return void + */ + public function ajax_status() { + self::check_ajax_request(); + + $stored = self::get_stored_scan(); + if ( ! self::is_pending( $stored ) ) { + self::send_scan( $stored ); + } + + $response = self::request( 'GET', 'scans/' . rawurlencode( $stored['uuid'] ) ); + + if ( is_wp_error( $response ) ) { + wp_send_json_error( array( 'message' => $response->get_error_message() ), (int) $response->get_error_data() ); + } + + self::send_scan( self::store_scan( $response ) ); + } + + /** + * Render a scan as HTML: status while pending, error when failed, and + * grade, headline, counts and checks when done. + * + * @param array|null $scan Stored scan. + * @param bool $compact Dashboard widget layout (no check list). + * @return string + */ + public static function render_result( $scan, $compact = false ) { + if ( ! $scan ) { + return ''; + } + + if ( self::is_pending( $scan ) ) { + return '

' . esc_html__( 'Analyzing your site… this usually takes under a minute.', 'frontconsent' ) . '

'; + } + + if ( 'failed' === $scan['status'] ) { + return '

' . esc_html__( 'The last scan could not be completed: the site could not be reached or did not load in time.', 'frontconsent' ) . '

'; + } + + $labels = self::status_labels(); + $grade = strtoupper( substr( (string) $scan['grade'], 0, 1 ) ); + + ob_start(); + ?> +
+
+ + + + +
+
+

+

+ %2$s: %3$d ', + esc_attr( $status ), + esc_html( $labels[ $status ] ), + (int) ( isset( $scan['counts'][ $status ] ) ? $scan['counts'][ $status ] : 0 ) + ); + } + ?> +

+ +

+ +

+ +
+
+ + + + +

+ + → + +

+ + sanitize_text_field( isset( $check['id'] ) ? (string) $check['id'] : '' ), + 'status' => sanitize_key( isset( $check['status'] ) ? (string) $check['status'] : '' ), + 'label' => sanitize_text_field( isset( $check['label'] ) ? (string) $check['label'] : '' ), + 'summary' => sanitize_text_field( isset( $check['summary'] ) ? (string) $check['summary'] : '' ), + ); + } + } + + $counts = array(); + foreach ( array( 'pass', 'warn', 'fail', 'not_applicable', 'reviewed' ) as $key ) { + $counts[ $key ] = isset( $data['counts'][ $key ] ) ? absint( $data['counts'][ $key ] ) : 0; + } + + $scan = array( + 'uuid' => sanitize_text_field( isset( $data['uuid'] ) ? (string) $data['uuid'] : '' ), + 'status' => sanitize_key( isset( $data['status'] ) ? (string) $data['status'] : 'failed' ), + 'url' => esc_url_raw( isset( $data['url'] ) ? (string) $data['url'] : '' ), + 'result_url' => esc_url_raw( isset( $data['result_url'] ) ? (string) $data['result_url'] : '' ), + 'analyzed_at' => sanitize_text_field( isset( $data['analyzed_at'] ) ? (string) $data['analyzed_at'] : '' ), + 'score' => isset( $data['score'] ) ? absint( $data['score'] ) : 0, + 'grade' => sanitize_text_field( isset( $data['grade'] ) ? (string) $data['grade'] : '' ), + 'headline' => sanitize_text_field( isset( $data['headline'] ) ? (string) $data['headline'] : '' ), + 'counts' => $counts, + 'checks' => $checks, + 'poll_after_seconds' => isset( $data['poll_after_seconds'] ) ? max( 3, absint( $data['poll_after_seconds'] ) ) : 5, + ); + + update_option( self::OPTION_NAME, $scan, false ); + + return $scan; + } + + /** + * Call the API. + * + * @param string $method HTTP method. + * @param string $path Path relative to the API base URL. + * @param array $body Request body, sent as JSON. + * @return array|\WP_Error The response's `data` object, or an error whose data is the HTTP status to answer with. + */ + private static function request( $method, $path, array $body = array() ) { + /** + * Filters the base URL of the tuwebcumple.es scan API. + * + * @since 1.1.0 + * @param string $url API base URL, ending in a slash. + */ + $base = trailingslashit( (string) apply_filters( 'frontconsent_scanner_api_url', self::API_URL ) ); + + $args = array( + 'method' => $method, + 'timeout' => 15, + 'headers' => array( 'Accept' => 'application/json' ), + ); + if ( $body ) { + $args['headers']['Content-Type'] = 'application/json'; + $args['body'] = wp_json_encode( $body ); + } + + $response = wp_remote_request( $base . $path, $args ); + + if ( is_wp_error( $response ) ) { + return new \WP_Error( 'frcn_scanner_unreachable', __( 'Could not connect to the scanning service. Please try again later.', 'frontconsent' ), 502 ); + } + + $code = (int) wp_remote_retrieve_response_code( $response ); + $decoded = json_decode( wp_remote_retrieve_body( $response ), true ); + + if ( 429 === $code ) { + return new \WP_Error( 'frcn_scanner_rate_limited', __( 'The scanning service has received too many requests. Please try again in a while.', 'frontconsent' ), 429 ); + } + + if ( 422 === $code ) { + $message = isset( $decoded['errors']['url'][0] ) ? sanitize_text_field( (string) $decoded['errors']['url'][0] ) : ''; + + return new \WP_Error( + 'frcn_scanner_invalid_url', + '' !== $message ? $message : __( 'This site cannot be scanned. It must be publicly reachable on the internet.', 'frontconsent' ), + 422 + ); + } + + if ( $code < 200 || $code >= 300 || ! isset( $decoded['data'] ) || ! is_array( $decoded['data'] ) || empty( $decoded['data']['uuid'] ) ) { + return new \WP_Error( 'frcn_scanner_bad_response', __( 'The scanning service returned an unexpected response. Please try again later.', 'frontconsent' ), 502 ); + } + + return $decoded['data']; + } + + /** + * Verify capability and nonce of an AJAX request. + * + * @return void + */ + private static function check_ajax_request() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'frontconsent' ) ), 403 ); + } + + check_ajax_referer( self::NONCE_ACTION, 'nonce' ); + } + + /** + * Send a scan to the browser with its rendered HTML. + * + * @param array|null $scan Stored scan. + * @return void + */ + private static function send_scan( $scan ) { + wp_send_json_success( + array( + 'status' => $scan ? $scan['status'] : '', + 'pending' => self::is_pending( $scan ), + 'pollAfterSeconds' => isset( $scan['poll_after_seconds'] ) ? (int) $scan['poll_after_seconds'] : 5, + 'html' => self::render_result( $scan ), + 'compactHtml' => self::render_result( $scan, true ), + ) + ); + } +} diff --git a/includes/Plugin_Main.php b/includes/Plugin_Main.php index 6da14c0..18c413b 100644 --- a/includes/Plugin_Main.php +++ b/includes/Plugin_Main.php @@ -92,10 +92,14 @@ private function load_modules() { if ( ! class_exists( 'FrontConsent\Admin\Settings' ) ) { require_once FRCN_PLUGIN_PATH . 'includes/Admin/Settings.php'; } + if ( ! class_exists( 'FrontConsent\Admin\Scanner' ) ) { + require_once FRCN_PLUGIN_PATH . 'includes/Admin/Scanner.php'; + } if ( ! class_exists( 'FrontConsent\GDPR_Cookie_Compliance_Migration' ) ) { require_once FRCN_PLUGIN_PATH . 'includes/GDPR_Cookie_Compliance_Migration.php'; } new Admin\Settings(); + new Admin\Scanner(); } } } diff --git a/readme.md b/readme.md index 1a79610..36a2290 100644 --- a/readme.md +++ b/readme.md @@ -10,6 +10,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli - **Import from GDPR Cookie Compliance** — explicit "Import settings" action that maps its Integrations tab (GA4, GTM, and the container configured in GTM4WP) and banner texts/expiration/position into FrontConsent without overwriting existing values; unsupported integrations (Google Ads, Meta Pixel, Microsoft UET/Clarity, reCAPTCHA) are reported, not imported. See `includes/GDPR_Cookie_Compliance_Migration.php`. - **Consent-gated attribution cookies** — WooCommerce order attribution scripts (`sbjs_*` cookies) stay inert until the visitor accepts (filter `frcn_cookie_notice_gated_script_handles`), and GTM4WP's own Consent Mode default is suppressed so FrontConsent's denied default is the only one (filter `frcn_cookie_notice_suppress_gtm4wp_consent_default`). - **Tracking cookies deleted on rejection** — rejecting, withdrawing an earlier acceptance, or returning after a rejection deletes known analytics/marketing cookies (`_ga`, `_ga_*`, `_gid`, `_gcl_*`, `_fbp`, `sbjs_*`…) on the host and its parent domains, so nothing set while consent was granted stays behind (filter `frcn_cookie_notice_purge_cookies`). +- **Compliance scanner** — a Scanner tab that, on an administrator's click, sends the site's home URL to the tuwebcumple.es API (`https://tuwebcumple.es/api/v1/`, filter `frontconsent_scanner_api_url`), follows the scan until it finishes and shows the grade, headline and per-requirement results; a dashboard widget shows the last grade. Results are stored in the `frontconsent_scan_result` option. One scan every 10 minutes per site, on top of the API's own rate limits. See `includes/Admin/Scanner.php`. - **Extensible settings tabs** — the settings page renders as a tab shell (Settings, plus a PRO upsell tab by default). A companion plugin such as FrontConsent PRO can add its own tab via the `frontconsent_settings_tabs` filter and render its panel on the `frontconsent_settings_form_tab_panels` action (fields saved through the main form) or `frontconsent_settings_tab_panels` action (a panel with its own form, e.g. a License tab). See [docs/plan.md](docs/plan.md) for the product plan (market, Free/Pro split, roadmap) and [AGENTS.md](AGENTS.md) for guidelines for AI coding agents working on this plugin. diff --git a/readme.txt b/readme.txt index 7252679..677ee6f 100644 --- a/readme.txt +++ b/readme.txt @@ -64,7 +64,11 @@ FrontConsent already sends a denied default first. To avoid a second, conflictin == External services == -This plugin only connects to external services that the site owner explicitly configures — none are contacted by default. All connections below happen entirely in the visitor's own browser, after that visitor has accepted the relevant cookie category; no data is ever sent from the server. +This plugin only connects to external services that the site owner explicitly configures or requests — none are contacted by default. The tracking services below are loaded entirely in the visitor's own browser, after that visitor has accepted the relevant cookie category. The only request made from the server is the compliance scan, and only when an administrator clicks "Scan my site". + +**tuwebcumple.es (compliance scanner)** +When an administrator clicks "Scan my site" in the Scanner tab, the site's public home URL is sent from the server to the tuwebcumple.es API (`https://tuwebcumple.es/api/v1/scans`), which visits the site like a first-time visitor and returns the result; the plugin then asks the same API for the result until the scan finishes. No visitor or personal data is sent. The last result is stored in the site's database and shown in the Scanner tab and a dashboard widget. +Service provided by CLOSE Marketing: [Terms and privacy](https://tuwebcumple.es/). **Google Tag Manager / Google Analytics 4 (GA4)** If a site administrator enters a Google Tag Manager container ID or a GA4 Measurement ID in the plugin settings, the visitor's browser loads the corresponding Google script (`https://www.googletagmanager.com/gtm.js` or `https://www.googletagmanager.com/gtag/js`) once the visitor accepts. This sends standard Google Tag Manager/Analytics data (e.g. page views, and any events the site's own tag configuration adds) to Google. @@ -84,6 +88,9 @@ Service provided by OpenAI: [Terms of Use](https://openai.com/policies/terms-of- == Changelog == += Unreleased = +* Added a Scanner tab that checks the site's cookie compliance through tuwebcumple.es and lists the result per requirement, plus a dashboard widget with the last grade. + = 1.0.2 = * Added an importer for GDPR Cookie Compliance settings in a new Integrations tab: migrates banner texts, layout, position, policy link and tracking IDs (GTM, GA4, GT-/AW-), enables the banner and reports any integration it couldn't map. * The "Cookie preferences" reopen trigger is now an icon-only cookie button (accessible name via `aria-label`), and stays hidden until the visitor has made a consent decision. diff --git a/tests/Unit/ScannerTest.php b/tests/Unit/ScannerTest.php new file mode 100644 index 0000000..3f88762 --- /dev/null +++ b/tests/Unit/ScannerTest.php @@ -0,0 +1,272 @@ +user->create( array( 'role' => 'administrator' ) ) ); + $this->requests = array(); + add_filter( 'pre_http_request', array( $this, 'mock_api' ), 10, 3 ); + add_filter( 'wp_doing_ajax', '__return_true' ); + add_filter( 'wp_die_ajax_handler', array( $this, 'die_handler' ) ); + } + + public function tear_down() { + remove_filter( 'pre_http_request', array( $this, 'mock_api' ), 10 ); + remove_filter( 'wp_doing_ajax', '__return_true' ); + remove_filter( 'wp_die_ajax_handler', array( $this, 'die_handler' ) ); + delete_option( Scanner::OPTION_NAME ); + delete_transient( Scanner::COOLDOWN_TRANSIENT ); + unset( $_REQUEST['nonce'] ); + parent::tear_down(); + } + + public function mock_api( $pre, $args, $url ) { + $this->requests[] = array( + 'method' => $args['method'], + 'url' => $url, + 'body' => isset( $args['body'] ) ? json_decode( $args['body'], true ) : null, + ); + + return array( + 'headers' => array(), + 'body' => wp_json_encode( $this->next_response['body'] ), + 'response' => array( + 'code' => $this->next_response['code'], + 'message' => '', + ), + 'cookies' => array(), + ); + } + + public function die_handler() { + return function () { + throw new WPDieException( 'die' ); + }; + } + + /** + * Run an AJAX method and return the decoded JSON it sent. + */ + private function call_ajax( $method ) { + $_REQUEST['nonce'] = wp_create_nonce( Scanner::NONCE_ACTION ); + $scanner = new Scanner(); + + ob_start(); + try { + $scanner->$method(); + } catch ( WPDieException $e ) { + unset( $e ); + } + + return json_decode( ob_get_clean(), true ); + } + + private function done_scan( array $overrides = array() ) { + return array_merge( + array( + 'uuid' => 'abc-123', + 'url' => 'https://example.org/', + 'status' => 'done', + 'analyzed_at' => '2026-11-03T10:00:00+00:00', + 'result_url' => 'https://tuwebcumple.es/resultado/abc-123', + 'score' => 41, + 'grade' => 'D', + 'headline' => 'Tu web instala 2 cookies antes del consentimiento', + 'counts' => array( + 'pass' => 4, + 'warn' => 1, + 'fail' => 2, + ), + 'checks' => array( + array( + 'id' => 'C01', + 'status' => 'fail', + 'label' => 'Cookies antes del consentimiento', + 'summary' => 'Se instalan cookies', + ), + ), + ), + $overrides + ); + } + + public function test_scanner_tab_is_added_after_settings() { + $tabs = ( new Scanner() )->add_tab( + array( + array( + 'id' => 'settings', + 'label' => 'Settings', + ), + array( + 'id' => 'license', + 'label' => 'PRO', + ), + ) + ); + + $this->assertSame( array( 'settings', 'scanner', 'license' ), wp_list_pluck( $tabs, 'id' ) ); + } + + public function test_starting_a_scan_posts_the_home_url_and_stores_the_pending_scan() { + $this->next_response = array( + 'code' => 202, + 'body' => array( + 'data' => array( + 'uuid' => 'abc-123', + 'status' => 'queued', + 'poll_after_seconds' => 5, + ), + ), + ); + + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertTrue( $json['success'] ); + $this->assertTrue( $json['data']['pending'] ); + $this->assertSame( 'POST', $this->requests[0]['method'] ); + $this->assertSame( 'https://tuwebcumple.es/api/v1/scans', $this->requests[0]['url'] ); + $this->assertSame( home_url( '/' ), $this->requests[0]['body']['url'] ); + $this->assertSame( 'queued', Scanner::get_stored_scan()['status'] ); + $this->assertGreaterThan( 0, Scanner::cooldown_remaining() ); + } + + public function test_a_second_scan_within_the_cooldown_does_not_call_the_api() { + update_option( Scanner::OPTION_NAME, $this->done_scan() ); + set_transient( Scanner::COOLDOWN_TRANSIENT, time() + 300, 300 ); + + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertFalse( $json['success'] ); + $this->assertStringContainsString( '5 minutes', $json['data']['message'] ); + $this->assertCount( 0, $this->requests ); + } + + public function test_starting_while_a_scan_is_pending_returns_it_without_calling_the_api() { + update_option( Scanner::OPTION_NAME, $this->done_scan( array( 'status' => 'running' ) ) ); + + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertTrue( $json['data']['pending'] ); + $this->assertCount( 0, $this->requests ); + } + + public function test_status_polls_only_the_stored_scan_and_stores_the_result() { + update_option( Scanner::OPTION_NAME, $this->done_scan( array( 'status' => 'running' ) ) ); + $this->next_response = array( + 'code' => 200, + 'body' => array( 'data' => $this->done_scan() ), + ); + + $json = $this->call_ajax( 'ajax_status' ); + + $this->assertSame( 'GET', $this->requests[0]['method'] ); + $this->assertSame( 'https://tuwebcumple.es/api/v1/scans/abc-123', $this->requests[0]['url'] ); + $this->assertFalse( $json['data']['pending'] ); + $this->assertSame( 'D', Scanner::get_stored_scan()['grade'] ); + $this->assertStringContainsString( 'frcn-scanner__grade--d', $json['data']['html'] ); + } + + public function test_status_of_a_finished_scan_does_not_call_the_api() { + update_option( Scanner::OPTION_NAME, $this->done_scan() ); + + $this->call_ajax( 'ajax_status' ); + + $this->assertCount( 0, $this->requests ); + } + + public function test_api_errors_are_reported_and_do_not_start_the_cooldown() { + $this->next_response = array( + 'code' => 422, + 'body' => array( 'errors' => array( 'url' => array( 'No podemos analizar esa dirección.' ) ) ), + ); + + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertFalse( $json['success'] ); + $this->assertSame( 'No podemos analizar esa dirección.', $json['data']['message'] ); + $this->assertSame( 0, Scanner::cooldown_remaining() ); + + $this->next_response = array( + 'code' => 429, + 'body' => array( 'message' => 'Too Many Attempts.' ), + ); + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertStringContainsString( 'too many requests', $json['data']['message'] ); + } + + public function test_users_without_manage_options_cannot_start_scans() { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + + $json = $this->call_ajax( 'ajax_start' ); + + $this->assertFalse( $json['success'] ); + $this->assertCount( 0, $this->requests ); + } + + public function test_result_html_escapes_api_text() { + $html = Scanner::render_result( Scanner::store_scan( $this->done_scan() ) ); + + $this->assertStringNotContainsString( '