*/ private static array $hooks = array(); /** * What the widget or statement screen will show, worked out on its `load-` * hook, before any output: see `prepare_site_admin()`. * * @var array|null */ private static ?array $site_admin = null; /** * Register the admin hooks. */ public static function init(): void { add_action( 'admin_menu', array( __CLASS__, 'menu' ) ); add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) ); // The dashboard sends the administrator back here with the one-time // code. On `admin_init` rather than on our own screen's render, because // it has to run BEFORE anything is output: the handler finishes with a // redirect that takes the code out of the address bar, and a redirect // after output is a "headers already sent" warning and a code left in // the browser history. add_action( 'admin_init', array( __CLASS__, 'maybe_handle_connect_return' ) ); add_action( 'admin_post_accessibit_connect', array( __CLASS__, 'handle_connect' ) ); add_action( 'admin_post_accessibit_toggle_widget', array( __CLASS__, 'handle_toggle_widget' ) ); add_action( 'admin_post_accessibit_recheck', array( __CLASS__, 'handle_recheck' ) ); add_action( 'admin_post_accessibit_disconnect', array( __CLASS__, 'handle_disconnect' ) ); } /** * Register the AccessiBit menu and its two screens. */ public static function menu(): void { self::$hooks['setup'] = add_menu_page( __( 'AccessiBit', 'accessibit' ), 'AccessiBit', 'manage_options', 'accessibit', array( __CLASS__, 'render_setup' ), 'dashicons-universal-access' ); add_submenu_page( 'accessibit', __( 'Setup', 'accessibit' ), __( 'Setup', 'accessibit' ), 'manage_options', 'accessibit', array( __CLASS__, 'render_setup' ) ); self::$hooks['accessibility'] = add_submenu_page( 'accessibit', __( 'Accessibility', 'accessibit' ), __( 'Accessibility', 'accessibit' ), 'manage_options', 'accessibit-accessibility', array( __CLASS__, 'render_accessibility' ) ); self::$hooks['widget'] = add_submenu_page( 'accessibit', __( 'Widget', 'accessibit' ), __( 'Widget', 'accessibit' ), 'manage_options', self::WIDGET_PAGE, array( __CLASS__, 'render_widget' ) ); self::$hooks['statement'] = add_submenu_page( 'accessibit', __( 'Accessibility statement', 'accessibit' ), __( 'Statement', 'accessibit' ), 'manage_options', self::STATEMENT_PAGE, array( __CLASS__, 'render_statement' ) ); // Only while AccessiBit offers it (ACC-412): the server's // `TRACKER_IN_PLUGIN`, learned from `/account`'s capabilities whenever // the plugin reads it. if ( Accessibit_Settings::is_site_linked() && Accessibit_Settings::is_tracker_available() ) { self::$hooks['tracker'] = add_submenu_page( 'accessibit', __( 'Tracker', 'accessibit' ), __( 'Tracker', 'accessibit' ), 'manage_options', self::TRACKER_PAGE, array( __CLASS__, 'render_tracker' ) ); } foreach ( array( 'widget', 'statement', 'tracker' ) as $page ) { if ( ! empty( self::$hooks[ $page ] ) ) { add_action( 'load-' . self::$hooks[ $page ], static function () use ( $page ) { Accessibit_Admin::prepare_site_admin( $page ); } ); } } } /** * Load the scan script on our Accessibility screen only — never on the rest * of wp-admin, and not before the site is connected (the view renders no * scan UI until then). * * @param string $hook Current screen's hook suffix. */ public static function enqueue_assets( $hook ): void { $ours = array_filter( self::$hooks ); if ( ! in_array( $hook, $ours, true ) ) { return; } // The stylesheet goes on both of our screens and does not depend on // being connected: it only puts back what wp-admin's own stylesheet // takes away (the free scan's list markers, above all). wp_enqueue_style( self::STYLE_HANDLE, ACCESSIBIT_PLUGIN_URL . 'admin/css/admin.css', array(), ACCESSIBIT_VERSION ); if ( null !== self::$site_admin && 'ready' === self::$site_admin['status'] ) { self::enqueue_bundle( self::$site_admin['config'] ); return; } if ( empty( self::$hooks['accessibility'] ) || $hook !== self::$hooks['accessibility'] ) { return; } // A copy of another site's database renders no scan panels: they would // read the original site's figures (ACC-411). if ( ! Accessibit_Settings::is_site_linked() || Accessibit_Settings::is_binding_stale() ) { return; } wp_enqueue_script( self::SCAN_HANDLE, ACCESSIBIT_PLUGIN_URL . 'admin/js/accessibility.js', array(), ACCESSIBIT_VERSION, true ); wp_localize_script( self::SCAN_HANDLE, 'accessibitScan', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'accessibit_scan' ), 'locale' => self::js_locale(), // Four strings, where this used to carry twenty-odd. // // Everything else here belonged to the paid "Scan my homepage" // button: `confirmRun` (which named the credit it was about to // spend), the progress and failure sentences, `errorCodes` with // `plan_inactive` / `insufficient_credits` / `scan_in_progress`, // `unknownError`, and `buyUrl` for the "See plans" link the // refusals offered. That button came out of v1 because credits // are retired at launch, so the strings went with it rather than // being translated into every locale to render for nobody. // // What is left describes a read-only panel: the site's latest // full audit, or a line saying there is not one yet. 'i18n' => array( 'complianceScore' => __( 'Compliance score', 'accessibit' ), 'errors' => __( 'Errors', 'accessibit' ), 'neverScanned' => __( 'No full audit yet. Run one from your AccessiBit dashboard.', 'accessibit' ), /* translators: %s: date of the most recent full audit. */ 'lastAudit' => __( 'Last full audit: %s', 'accessibit' ), ), ) ); wp_enqueue_script( self::FREE_SCAN_HANDLE, ACCESSIBIT_PLUGIN_URL . 'admin/js/free-scan.js', array(), ACCESSIBIT_VERSION, true ); wp_localize_script( self::FREE_SCAN_HANDLE, 'accessibitFreeScan', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'accessibit_scan' ), 'buyUrl' => Accessibit_Links::buy(), 'locale' => self::js_locale(), 'i18n' => array( 'starting' => __( 'Starting the free scan of your homepage…', 'accessibit' ), 'scanning' => __( 'Scanning your homepage…', 'accessibit' ), // A failure is told apart from the things that are NOT a // failed scan: a revoked key, a deleted site, a rate limit, a // 5xx, a blocked outbound request and an expired nonce all // used to render "we could not scan your homepage this time", // in several of which the scan had in fact completed // perfectly well. // // Three of those were still landing here when this comment // already claimed otherwise, which is why each now has a // string of its own below: `site_not_found` (a deleted site — // `RECONNECT_CODES`), `network_error` (`blocked`), and the // bare `-1`/`0` that `check_ajax_referer()` and a logged-out // admin-ajax request answer with (`session`). The last was // the one the comment named outright: both bodies parse as a // JSON number, so `res.success` is `undefined` and the old // code could not tell them from a refusal payload. 'failed' => __( 'We could not scan your homepage this time.', 'accessibit' ), 'network' => __( 'Could not reach AccessiBit. Check your connection and reload this page.', 'accessibit' ), // The request never left this site: a security plugin, a // firewall or a proxy refused the outbound call. Waiting does // not fix it, so this does not say "try again in a minute" — // it names the thing the administrator can actually change. 'blocked' => __( 'Could not reach AccessiBit. A security plugin or firewall on this site may be blocking outgoing requests.', 'accessibit' ), // The browser still has the screen but WordPress no longer // accepts the request: the nonce has expired, or the session // ended, usually because the tab sat open. Nothing is wrong // with the scan and nothing is lost. 'session' => __( 'This page has been open too long for WordPress to accept the request. Reload it — your scan is not affected.', 'accessibit' ), 'reconnect' => __( 'AccessiBit no longer recognises this site’s connection, so we cannot read your scan. Reconnect on the Setup screen.', 'accessibit' ), 'notVerified' => __( 'We cannot scan this site until its domain is verified in AccessiBit. See the note above.', 'accessibit' ), 'busy' => __( 'AccessiBit is busy just now. Your scan is not lost — reload this page in a minute.', 'accessibit' ), 'slow' => __( 'This is taking longer than expected. The scan is still running — reload this page to see the result.', 'accessibit' ), 'exhausted' => __( 'We tried this homepage several times without success. Contact support and we will look into it.', 'accessibit' ), 'clean' => __( 'We found no issues on your homepage. Scan more pages in AccessiBit to check the rest of your site.', 'accessibit' ), // Deliberately plural-FREE, where this was two `__()` strings // picked by `total === 1` in JavaScript. A plugin's // localized strings live in PHP and are handed to the script // already translated, so the script cannot call `_n()` and // cannot know the locale's plural rule — which made the // one/many pair wrong for every language with more than two // forms, and there will be such languages the moment // translate.wordpress.org picks the plugin up. // // A label-and-count construction has no plural to get wrong, // in any language, and needs no JSON catalogs or wp-i18n // plumbing to say so. /* translators: %s: number of accessibility issues found on the homepage. */ 'issuesFound' => __( 'Accessibility issues found on your homepage: %s.', 'accessibit' ), // Two strings where there was one, because the number listed // and the number found count different things: `totalIssues` // counts instances, the list is one line per distinct rule. // "Showing the first 3" of 37 described neither — see the // note in free-scan.js. /* translators: %s: how many distinct problems are listed below. */ 'showingSome' => __( 'Showing %s of the different problems found:', 'accessibit' ), // Deliberately countless, where this read "All 1 of the // different problems found are listed below:" whenever the // homepage had exactly one. The number it carried was the // length of a list the reader can see, and the total is // already stated by `issuesFound` above it. 'showingAll' => __( 'Every different problem found is listed below:', 'accessibit' ), /* translators: %s: date the homepage was scanned. */ 'scannedOn' => __( 'Scanned on %s.', 'accessibit' ), // Not "See all issues…" any more. The dashboard deliberately // lists no free scan, so there was nowhere to go and see // them — the link opened the purchase wizard. 'cta' => __( 'See plans on AccessiBit', 'accessibit' ), 'retry' => __( 'Try again', 'accessibit' ), 'newTab' => __( '(opens in a new tab)', 'accessibit' ), // Said beside the retry button once it can no longer do anything. The // button stays on screen, disabled: it used to be removed, so the only // thing that changed at the moment the last attempt was spent was that // the control the user had been clicking silently vanished — and the // purchase link beside it became the only button left (ACC-406 review). 'retrySpent' => __( 'No attempts left for this domain.', 'accessibit' ), // The retry backoff, in words, wherever the server sent its // length — on the 429 and on the failed state alike. It used // to be shown as "AccessiBit is busy just now. Your scan is // not lost — reload this page in a minute", which was about // the wrong thing and understated a ten-minute wait by nine. /* translators: %s: whole minutes until the scan can be retried. Always two or more. */ 'retryAfter' => __( 'You can try again in about %s minutes.', 'accessibit' ), // Its own string rather than `retryAfter` with a 1 in it, // which read "You can try again in about 1 minutes." — // `waitMinutes()` rounds a wait of any length under a minute // up to one, so this is the state a retry lands in most // often, not an edge case. The script cannot call `_n()`: // these arrive already translated and it does not know the // locale's plural rule. 'retryAfterOne' => __( 'You can try again in about a minute.', 'accessibit' ), // Said when the wait has elapsed and the button is usable // again. The waiting state used to end only on a reload, so // nothing ever announced that it had ended — the one state // whose entire content is "come back shortly" was the one // state that never came back. 'retryReady' => __( 'You can try again now.', 'accessibit' ), // Same state, no number: the server refused but sent no // wait. Deliberately not the "busy" sentence — it must not // fall back into the message this replaced. 'retryLater' => __( 'That was too soon after the last attempt. Try again shortly.', 'accessibit' ), // Beside the retry button while the backoff has not elapsed. // Distinct from `retrySpent`, which is final: this one ends // in a wait, not in "contact support". 'retryWaiting' => __( 'Not ready to try again yet.', 'accessibit' ), // Why it failed, in words. The engine distinguishes these and the row // carries the code, so a site whose firewall refuses us can be told that // instead of "this time". // // The keys are `AUDIT_JOB_ERROR_CODES` from `@accessibit/types` — the // vocabulary audit-api actually writes, which `PluginFreeScan.failureCode` // stores verbatim (`job.errorCode ?? 'UNKNOWN'`). They were invented names // before (`BLOCKED`, `PRIVATE_HOST`, `DNS_NO_RECORD`, …) that the engine has // never emitted, so every real failure except the last three fell through // to the bare "we could not scan your homepage this time" — the behaviour // ACC-482 was opened to remove. The e2e mock returned one of the invented // names, which is why the suite proved the mechanism while no real code // ever matched a key. // // Keep this in step with `AUDIT_JOB_ERROR_CODES`. A code with no entry is // not a crash — it degrades to the lead sentence plus `supportHint` — but // it is a silent loss of the only explanation the customer gets. 'failureCodes' => array( // Neither the apex nor `www.` resolves. 'DOMAIN_UNRESOLVABLE' => __( 'We could not look up your domain, so we never reached your homepage.', 'accessibit' ), // We refused the target: it resolves to an internal address. 'TARGET_BLOCKED' => __( 'The address registered for this site is not reachable from the internet, so we cannot scan it.', 'accessibit' ), // The target refused us — 403/405, or a WAF challenge. 'REFUSED_BY_TARGET' => __( 'Your homepage refused our scanner — usually a firewall, a bot filter or a security plugin. Allow our scanner and try again.', 'accessibit' ), // 429 or 5xx, after one retry of our own. 'TARGET_UNAVAILABLE' => __( 'Your homepage returned an error or was too busy to answer our scanner.', 'accessibit' ), 'PAGE_NOT_FOUND' => __( 'Your homepage returned "not found". Check the address registered for this site in AccessiBit.', 'accessibit' ), // Reached, but the check itself never completed. 'ALL_SCANS_FAILED' => __( 'We reached your homepage but could not finish checking it.', 'accessibit' ), 'JOB_CRASHED' => __( 'Something went wrong on our side while we were scanning.', 'accessibit' ), 'STALE_TIMEOUT' => __( 'The scan was interrupted on our side.', 'accessibit' ), 'SCANNER_BUSY' => __( 'Our scanner was at capacity. Nothing was used up — try again.', 'accessibit' ), 'ORPHANED' => __( 'The site this scan was running for was removed from your AccessiBit account while it ran.', 'accessibit' ), // `UNKNOWN` is deliberately absent: the server stores it when the job // recorded no code at all, and a sentence for "we did not record why" // would say less than the lead and the support hint already do. ), 'supportHint' => __( 'Contact support if it keeps happening.', 'accessibit' ), ), ) ); } /** * Render the Setup screen. */ public static function render_setup(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } require ACCESSIBIT_PLUGIN_DIR . 'admin/views/setup.php'; } /** * Render the Accessibility screen. */ public static function render_accessibility(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } require ACCESSIBIT_PLUGIN_DIR . 'admin/views/accessibility.php'; } /** * Render the Widget screen. */ public static function render_widget(): void { self::render_site_admin( 'widget' ); } /** * Render the Statement screen. */ public static function render_statement(): void { self::render_site_admin( 'statement' ); } /** * Render the Tracker screen (ACC-412). */ public static function render_tracker(): void { self::render_site_admin( 'tracker' ); } /** * Print a site-admin screen: its notices, and the bundle's root when it * mounts. * * @param string $page `widget`, `statement` or `tracker`. */ private static function render_site_admin( string $page ): void { if ( ! current_user_can( 'manage_options' ) ) { return; } $accessibit_page = $page; $accessibit_state = self::$site_admin ?? array( 'status' => 'not_connected' ); require ACCESSIBIT_PLUGIN_DIR . 'admin/views/site-admin.php'; } /** * `load-` hook of the Widget and Statement screens: decide what they show. * * Re-reads `/account` on every visit, because both screens depend on what * the plan includes right now — a licence bought or ended in the dashboard * must not wait for a "Check again" — and the bundle needs the site's * address and the company's name. The widget licence and verification it * reads are stored, so the Accessibility screen's notices are refreshed * with them; the statement licence is only ever needed here. * * The bundle is mounted only for a bound install whose binding is current * (a database clone holding the original site's key must not be able to * change that site), that AccessiBit still recognises, and whose plan * includes what the screen changes. Everything else is a notice. * * The Tracker screen also mounts on a company-wide key, which reads it; * the bundle explains a refused pause or resume itself (ACC-412). * * @param string $page `widget`, `statement` or `tracker`. */ public static function prepare_site_admin( string $page ): void { if ( ! current_user_can( 'manage_options' ) ) { return; } if ( ! Accessibit_Settings::is_site_linked() ) { self::$site_admin = array( 'status' => 'not_connected' ); return; } if ( Accessibit_Settings::is_binding_stale() ) { self::$site_admin = array( 'status' => 'stale' ); return; } if ( ! is_readable( ACCESSIBIT_PLUGIN_DIR . self::BUNDLE_DIR . 'accessibit-admin.js' ) ) { self::$site_admin = array( 'status' => 'bundle_missing' ); return; } // A shorter wait than the client's 20 s: the screen is blank until this // answers, and a host whose firewall drops our requests would otherwise // sit on every visit for the whole timeout before saying so. $account = Accessibit_Api_Client::from_settings()->account( self::ACCOUNT_TIMEOUT ); $site_id = Accessibit_Settings::get_site_id(); $state = self::site_admin_state( $page, $account, $site_id, Accessibit_Settings::is_statement_published() ); // The plugin learns of a publication only from statements passing // through it, so one published from the dashboard, or before a v1 // install upgraded, is unknown here. Without the licence, that decides // between the read-only statement and the "not in your plan" notice: // ask, and only then — a licensed site mounts either way (ACC-613). if ( 'statement' === $page && 'unlicensed' === $state['status'] ) { Accessibit_Statement::look_up(); if ( Accessibit_Settings::is_statement_published() ) { $state = self::site_admin_state( $page, $account, $site_id, true ); } } if ( isset( $state['flags'] ) ) { Accessibit_Settings::update( $state['flags'] ); } // Every `/account` read refreshes the Tracker capability, so a flip of // the server's flag reaches the menu on the next visit to any of these // screens (ACC-412). if ( ! empty( $account['ok'] ) && is_array( $account['data'] ?? null ) ) { Accessibit_Settings::update( Accessibit_Settings::capability_flags( $account['data'] ) ); } if ( 'ready' === $state['status'] ) { $user = wp_get_current_user(); $state['config'] = array( 'page' => $page, 'restRoot' => esc_url_raw( rest_url( Accessibit_Rest::NAMESPACE_V1 ) ), 'nonce' => wp_create_nonce( 'wp_rest' ), // Core's own endpoint for a fresh `wp_rest` nonce (WordPress // 5.3+). An admin who signs in again with the screen open has a // new session, and the nonce above died with the old one: the // bundle asks here and retries instead of losing the edits // (ACC-411). 'nonceUrl' => admin_url( 'admin-ajax.php?action=rest-nonce' ), // `determine_locale()`, as `js_locale()` explains: the locale // the screen's own strings were loaded in, which WPML or // Polylang may move without touching the user's profile. 'locale' => determine_locale(), // Whether this plugin's strings are in that locale (a catalog it // ships, or a language pack): the bundle follows, so an es_MX // screen is not Spanish inside an English wp-admin page (ACC-411). 'stringsTranslated' => is_textdomain_loaded( 'accessibit' ), 'site' => $state['site'], 'canEdit' => $state['can_edit'], 'apiOrigin' => Accessibit_Links::api_origin_for( ACCESSIBIT_API_BASE_URL ), // Where the statement page sends a site with no audit results // yet: the plugin cannot tell the Audit page from the Tracker, // which depends on a tier it does not know (ACC-411). 'auditsUrl' => Accessibit_Links::site(), 'companyName' => $state['company_name'], 'userName' => $user->exists() ? $user->display_name : null, 'userEmail' => $user->exists() ? $user->user_email : null, ); if ( 'tracker' === $page ) { $state['config']['trackerLinks'] = Accessibit_Links::tracker_links(); } if ( 'widget' === $page ) { // The Tools tab's live preview: the homepage, framed, with the // widget in its preview mode (`Accessibit_Widget`). $state['config']['previewUrl'] = Accessibit_Widget::preview_url(); } } self::$site_admin = $state; } /** * What a site-admin screen shows, from the `/account` result. * * - `reconnect`: the key was refused, or the bound site is not among the * key's sites any more (deleted, or moved to another account). * - `unreachable`: no answer we can use; `code` says why. * - `unlicensed`: the plan does not include what this screen changes. * - `tracker_unavailable`: the Tracker screen, while AccessiBit does not * offer the Tracker to the plugin (`/account` lists no `tracker` * capability, ACC-412). A site without a Tracker licence is not this: * it mounts, and the bundle offers to activate it. * - `site_key_required`: licensed, but the key is a legacy company-wide * one, which audit-api lets read and scan but not write (ACC-615): * reconnecting swaps it for a key bound to this site. * - `ready`: mount, with `site` and `company_name` for the bundle, and * `can_edit`. A statement published before the plan lapsed is still * read — audit-api lets the reads through — but not changed; the * bundle's read-only notice says why. * * The widget screen has no read-only form: audit-api would serve its * settings, but a site without the widget has nothing on it to customize. * * `flags` are the bound site's licence and verification, to store, on any * answer that names the site. * * Pure, for the unit suite. * * @param string $page `widget`, `statement` or `tracker`. * @param array $result An `Accessibit_Api_Client::account()` result. * @param string $site_id The bound site. * @param bool $published Whether the site's statement was published. * @return array */ public static function site_admin_state( string $page, array $result, string $site_id, bool $published = false ): array { if ( empty( $result['ok'] ) ) { $code = (string) ( $result['code'] ?? '' ); return in_array( $code, array( 'invalid_api_key', 'account_not_found' ), true ) ? array( 'status' => 'reconnect' ) : array( 'status' => 'unreachable', 'code' => $code, ); } $data = is_array( $result['data'] ?? null ) ? $result['data'] : array(); $sites = isset( $data['sites'] ) && is_array( $data['sites'] ) ? $data['sites'] : array(); $site = null; foreach ( $sites as $candidate ) { $raw_id = is_array( $candidate ) ? ( $candidate['id'] ?? null ) : null; if ( ( is_string( $raw_id ) || is_int( $raw_id ) ) && (string) $raw_id === $site_id ) { $site = $candidate; break; } } if ( null === $site ) { return array( 'status' => 'reconnect' ); } $flags = array( 'widget_licensed' => ! empty( $site['isPro'] ) || ! empty( $site['isTrial'] ), 'site_verified' => ! array_key_exists( 'verified', $site ) || ! empty( $site['verified'] ), ); // The Tracker screen (ACC-412) has no licence to check here: a site // without the Tracker gets the screen's own "activate" state. It needs // only the server to offer it, and reads with any key the site has. if ( 'tracker' === $page ) { if ( ! Accessibit_Settings::capability_flags( $data )['tracker_available'] ) { return array( 'status' => 'tracker_unavailable', 'flags' => $flags, ); } $licensed = true; } elseif ( 'widget' === $page ) { $licensed = $flags['widget_licensed']; } else { $licensed = ! empty( $site['hasStatementLicense'] ); } $lapsed = ! $licensed && 'statement' === $page && $published; if ( ! $licensed && ! $lapsed ) { return array( 'status' => 'unlicensed', 'flags' => $flags, ); } // A lapsed statement only reads, which the key still may; so does the // Tracker screen, whose one write the bundle explains when refused. if ( $licensed && 'tracker' !== $page && 'company' === ( $data['scope']['kind'] ?? null ) ) { return array( 'status' => 'site_key_required', 'flags' => $flags, ); } $url = isset( $site['url'] ) && is_string( $site['url'] ) ? $site['url'] : ''; $company = $data['company']['name'] ?? null; return array( 'status' => 'ready', 'flags' => $flags, // A site has no name of its own in AccessiBit: the dashboard shows // its address, and the statement prints it. 'site' => array( 'id' => $site_id, 'name' => $url, 'url' => $url, ), 'company_name' => is_string( $company ) && '' !== $company ? $company : null, 'can_edit' => $licensed, ); } /** * Enqueue the admin bundle with its config. * * React is inside the bundle, so it depends on nothing of WordPress's. * `JSON_HEX_TAG` because the config carries free text (the company's and * the user's names): a `` in one would otherwise end the inline * script early. * * @param array $config `WpAdminConfig` (`packages/site-admin/src/wp/config.ts`). */ private static function enqueue_bundle( array $config ): void { $url = ACCESSIBIT_PLUGIN_URL . self::BUNDLE_DIR; wp_enqueue_style( self::BUNDLE_HANDLE, $url . 'accessibit-admin.css', array(), ACCESSIBIT_VERSION ); wp_enqueue_script( self::BUNDLE_HANDLE, $url . 'accessibit-admin.js', array(), ACCESSIBIT_VERSION, true ); wp_add_inline_script( self::BUNDLE_HANDLE, 'window.accessibitAdminConfig = ' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' ); } /** * Let `wp_safe_redirect` reach the AccessiBit dashboard, and nothing else. * * Starting a connection means leaving this site, which `wp_safe_redirect` * exists to prevent. The alternative is `wp_redirect`, which checks nothing * at all — so this adds the ONE host the plugin is ever allowed to send an * administrator to, and leaves the guard in place for every other redirect * in WordPress. * * @param array $hosts Hosts WordPress already considers safe. * @return array */ public static function allow_dashboard_host( $hosts ): array { // The guard comes first: WordPress always passes an array, but appending // to something that is not one is a fatal, and a filter on a core hook is // reachable by every other plugin on the site. $allowed = is_array( $hosts ) ? $hosts : array(); $host = wp_parse_url( ACCESSIBIT_DASHBOARD_URL, PHP_URL_HOST ); if ( is_string( $host ) && '' !== $host ) { $allowed[] = $host; } return $allowed; } /** * The wp-admin address the dashboard sends the administrator back to. * * Carries a nonce, because the return is a GET this site did not issue. It * survives the round trip untouched: the dashboard adds its two parameters * with the URL API, which appends rather than rewrites. * * Built from `admin_url()` so it is the WordPress address, which is what * the administrator's browser can actually reach — on an install where that * differs from the public address, `connect_origin_matches()` below refuses * the whole flow rather than producing a return URL the dashboard will * reject. * * @return string */ public static function connect_return_url(): string { return add_query_arg( array( 'page' => 'accessibit', '_wpnonce' => wp_create_nonce( self::CONNECT_RETURN_ACTION ), ), admin_url( 'admin.php' ) ); } /** * Whether this install's public address and its admin share an origin. * * The dashboard refuses a connection whose `return_url` is not on the same * origin as the `site_url` being connected — that rule is what lets its * approval screen promise the key can reach no other host. An install with * WP_HOME and WP_SITEURL on different hosts cannot satisfy it, so the * plugin says so here instead of sending the administrator to a screen that * will refuse them with no idea why. * * Path differences are fine and common (WordPress in a subdirectory): * origin is scheme, host and port. * * @return bool */ public static function connect_origin_matches(): bool { return self::origin_of( home_url() ) === self::origin_of( admin_url() ) && '' !== self::origin_of( home_url() ); } /** * Print the notice for an install whose public and admin addresses diverge. * * Here rather than in a view because BOTH admin screens need it: Setup, * where the Connect button would be, and Accessibility, which otherwise * tells such an install to connect an account with nothing on the page to * say why it cannot (ACC-568). Two copies of this sentence is how the two * screens come to disagree about what is wrong with the install. * * @return void */ public static function print_origin_mismatch_notice(): void { echo '

'; printf( /* translators: %1$s: this site's public address; %2$s: its WordPress admin address. */ esc_html__( 'This site is published at %1$s but administered at %2$s. AccessiBit can only connect a site whose admin is on the same address, so the connection cannot be started here. Contact support and we will help.', 'accessibit' ), '' . esc_html( self::origin_of( home_url() ) ) . '', '' . esc_html( self::origin_of( admin_url() ) ) . '' ); echo '

'; } /** * Scheme + host + port of a URL, or '' when it has no host. * * Pure, so the unit suite can pin the subdirectory and port cases without * standing up an install for each. * * @param string $url Any absolute URL. * @return string */ public static function origin_of( string $url ): string { $parts = wp_parse_url( $url ); if ( ! is_array( $parts ) || empty( $parts['host'] ) || empty( $parts['scheme'] ) ) { return ''; } $origin = strtolower( $parts['scheme'] ) . '://' . strtolower( $parts['host'] ); return isset( $parts['port'] ) ? $origin . ':' . (int) $parts['port'] : $origin; } /** * `admin_post` handler for the Setup screen's Connect button. * * Starts the flow; it does not finish it. The administrator is sent to the * dashboard to sign in (or sign up) and approve, and comes back to * `maybe_handle_connect_return()` with a one-time code. * * Nothing about an API key happens on this site any more. The key is minted * by AccessiBit when this server redeems the code, and the only copy of it * arrives in the body of a response to a request this server made — never * through a browser, a form field, or the administrator's clipboard. */ public static function handle_connect(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Forbidden', 'accessibit' ), '', 403 ); } // Named nonce fields, hence the second argument here and in the three // handlers below. `wp_nonce_field()` uses the field name as the input's // `id` as well, so the default `_wpnonce` put three inputs with // `id="_wpnonce"` on Setup and two on Accessibility — the same duplicate // the `submit` ids were, from the other core helper these screens lean on. check_admin_referer( 'accessibit_connect', 'accessibit_connect_nonce' ); if ( ! self::connect_origin_matches() ) { self::redirect_setup( array( 'connected' => '0', 'reason' => 'origin_mismatch', ) ); return; } // `wp_safe_redirect` refuses a host that is not this site's. Connecting // deliberately leaves the site, so the dashboard is allowed for this one // redirect — not on every request, where it made the dashboard a safe // destination for any redirect on the site, `wp-login.php`'s // `redirect_to` included (ACC-411). Not the unchecked `wp_redirect`. add_filter( 'allowed_redirect_hosts', array( __CLASS__, 'allow_dashboard_host' ) ); $attempt = self::issue_connect_state(); wp_safe_redirect( Accessibit_Links::connect( $attempt['state'], self::pkce_challenge( $attempt['verifier'] ) ) ); exit; } /** * Mint and store the `state` for one connection attempt. * * Per user, not per site: two administrators connecting at once would * otherwise overwrite each other's token and both fail. The transient is * the only record of it — this site never tells AccessiBit what the state * is beyond putting it in the redirect, so a returning code can be matched * against an attempt that really started here. * * Alphanumeric only (`wp_generate_password`'s third argument off), because * it travels in a query string and the dashboard validates its shape. * * Stored with it, the attempt's PKCE verifier (PR #1162 review): only its * challenge goes to the dashboard, and the exchange needs the verifier, so * a code that leaks from the return URL cannot be redeemed anywhere else. * * @return array{ state: string, verifier: string } */ private static function issue_connect_state(): array { $attempt = array( 'state' => wp_generate_password( 32, false, false ), 'verifier' => self::new_pkce_verifier(), ); set_transient( self::CONNECT_STATE_PREFIX . get_current_user_id(), $attempt, self::CONNECT_STATE_TTL ); return $attempt; } /** * A fresh PKCE verifier: 32 random bytes, base64url, 43 characters * (RFC 7636 §4.1). * * @return string */ public static function new_pkce_verifier(): string { return rtrim( strtr( base64_encode( random_bytes( 32 ) ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url of random bytes, RFC 7636. } /** * The PKCE challenge of a verifier: base64url SHA-256 (RFC 7636 `S256`). * * @param string $verifier The verifier this install keeps. * @return string */ public static function pkce_challenge( string $verifier ): string { return rtrim( strtr( base64_encode( hash( 'sha256', $verifier, true ) ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url of a hash, RFC 7636. } /** * Finish a connection the administrator approved in the dashboard. * * Runs on every admin page load, so it leaves immediately unless the two * parameters are present. The checks, in order, are: the capability, the * nonce (this is a logged-in administrator of this site), and the `state` * (this is the attempt this install started). Only then is the code * redeemed, server to server. * * Every path ends in a redirect, including the failures, because the code * is in the URL: leaving it there would put a credential in the browser * history, in the referrer of anything the next page loads, and in any * server log that records query strings. * * A request that fails the CAPABILITY check is left ALONE rather than * redirected or killed — at that point there is no evidence it has anything * to do with us, and `admin_init` fires on every screen in wp-admin. A * nonce failure is past that point: it is our two parameters, from an * administrator of this site, so it redirects like every other failure. */ public static function maybe_handle_connect_return(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- presence check only; the nonce is verified below before anything is read or written. if ( ! isset( $_GET['accessibit_code'], $_GET['accessibit_state'] ) ) { return; } if ( ! current_user_can( 'manage_options' ) ) { return; } if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), self::CONNECT_RETURN_ACTION ) ) { // Redirected rather than returned, because the code is in the URL and // this is reachable without anything being wrong: a nonce is bound to // the user AND the session token, so returning as a second // administrator, or after a re-login, fails here while the capability // check passes. `state_mismatch` is the accurate reason — this page no // longer matches the attempt that started it. self::redirect_setup( array( 'connected' => '0', 'reason' => 'state_mismatch', ) ); return; } $code = sanitize_text_field( wp_unslash( $_GET['accessibit_code'] ) ); $state = sanitize_text_field( wp_unslash( $_GET['accessibit_state'] ) ); // Read and deleted in one breath, whatever happens next: a state is one // attempt. Leaving it in place on a failure would let the same code — // or a different one — be replayed against it. $transient = self::CONNECT_STATE_PREFIX . get_current_user_id(); $attempt = get_transient( $transient ); delete_transient( $transient ); $expected = is_array( $attempt ) && isset( $attempt['state'] ) && is_string( $attempt['state'] ) ? $attempt['state'] : ''; $verifier = is_array( $attempt ) && isset( $attempt['verifier'] ) && is_string( $attempt['verifier'] ) ? $attempt['verifier'] : ''; if ( '' === $expected || '' === $verifier || ! hash_equals( $expected, $state ) ) { self::redirect_setup( array( 'connected' => '0', 'reason' => 'state_mismatch', ) ); return; } $result = Accessibit_Api_Client::exchange_code( ACCESSIBIT_API_BASE_URL, $code, home_url(), $verifier, ACCESSIBIT_VERSION ); if ( ! $result['ok'] ) { self::redirect_setup( array( 'connected' => '0', 'reason' => $result['code'] ?? 'error', ) ); return; } $data = is_array( $result['data'] ?? null ) ? $result['data'] : array(); $api_key = isset( $data['apiKey'] ) && is_string( $data['apiKey'] ) ? $data['apiKey'] : ''; $slug = $data['company']['slug'] ?? ''; $site = is_array( $data['site'] ?? null ) ? $data['site'] : array(); $site_id = isset( $site['id'] ) && ( is_string( $site['id'] ) || is_int( $site['id'] ) ) ? (string) $site['id'] : ''; // A 2xx whose body is not our JSON is NOT a successful connect. A // captive portal or a misconfigured proxy answering 200 with an HTML // page used to land here with an empty slug and no site, which was then // stored — wiping a working connection and, with it, the company slug // the public widget tag is built from. if ( '' === $api_key || ! is_string( $slug ) || '' === $slug || '' === $site_id ) { self::redirect_setup( array( 'connected' => '0', 'reason' => 'unexpected_response', ) ); return; } Accessibit_Settings::set_account( $api_key, $slug, $site_id, ! empty( $site['isPro'] ) || ! empty( $site['isTrial'] ), // Absent on an older API than this plugin: treat it as verified // rather than warning about something we cannot know. ! array_key_exists( 'verified', $site ) || ! empty( $site['verified'] ) ); // The exchange reports what `/account` would (ACC-412), so the Tracker // menu is there from the first screen after connecting. Accessibit_Settings::update( Accessibit_Settings::capability_flags( $data ) ); // Straight to where the free homepage scan reports (ACC-409) — the // script there starts it on load. The site is always matched now: a // connect-flow key IS a site, so the "connected but no site" state the // pasted key could land in cannot happen. wp_safe_redirect( admin_url( 'admin.php?page=accessibit-accessibility' ) ); exit; } /** * The notice for a failed connect, by the reason code the flow stored. * * `network_error` is the one that must not blame anything the administrator * typed: the request never left the site. A security plugin or firewall * blocking outgoing requests is the usual cause, and the most likely * support case we have (ACC-482). * * The raw code is appended only to the fallback, where it is support's only * clue. The codes we recognise say it in words instead. * * @param string $reason The code the connect flow put on the redirect. * @return string The notice to show, already translated. */ public static function connect_error_notice( string $reason ): string { switch ( $reason ) { case 'network_error': return __( 'Could not reach AccessiBit, so the connection was not completed. A security plugin or firewall on this site may be blocking outgoing requests.', 'accessibit' ); case 'origin_mismatch': // WP_HOME and WP_SITEURL are on different hosts. Caught before // leaving the site, because the dashboard would refuse the // request and the administrator would have no way to know why. return __( 'Could not start the connection. This site\'s address and its WordPress admin address are on different hosts, which AccessiBit cannot connect safely. Contact support and we will help.', 'accessibit' ); case 'state_mismatch': // The returning request did not belong to an attempt started // here: a stale tab, a bookmarked return link, or a second // connection started in another tab since. return __( 'Could not complete the connection — this page no longer matches the attempt that started it. Press Connect again to start over.', 'accessibit' ); case 'invalid_code': return __( 'Could not complete the connection. The approval had already been used or had expired. Press Connect again to start over.', 'accessibit' ); case 'site_url_mismatch': return __( 'Could not complete the connection. The approval was for a different site address than this one. Press Connect again from this site.', 'accessibit' ); case 'site_not_found': return __( 'Could not complete the connection. The site you approved no longer exists in your AccessiBit account.', 'accessibit' ); case 'invalid_api_key': // Reached by Check again with a stored key that has since been // revoked — the dashboard's API keys page can revoke one, and a // deleted site takes its key with it. return __( 'Could not connect. This site\'s AccessiBit key is no longer valid — it may have been revoked, or the site removed from your account. Press Connect to reconnect.', 'accessibit' ); case 'account_not_found': return __( 'Could not connect. This site\'s key is no longer tied to an AccessiBit account. Press Connect to reconnect, or contact support.', 'accessibit' ); case 'rate_limited': return __( 'Could not connect. Too many attempts — wait a minute and try again.', 'accessibit' ); case 'service_unavailable': return __( 'Could not connect. AccessiBit could not answer just now — this is on our side, so try again in a minute.', 'accessibit' ); case 'request_failed': case 'internal_error': // A 5xx, or any non-2xx with no code of ours in the body. // Nothing the administrator did caused it, which is why // `internal_error` is named here rather than left to the // fallback — it used to read "check your API key and try // again", sending the admin to re-create a key that had just // been accepted, over a fault on our side. return __( 'Could not connect. AccessiBit answered with an error, so the connection was not completed. Try again in a minute.', 'accessibit' ); case 'unexpected_response': return __( 'Could not connect. Something on your network answered instead of AccessiBit — check for a proxy, a captive portal or a security plugin intercepting outgoing requests. Your saved connection was left untouched.', 'accessibit' ); } $generic = __( 'Could not connect. Try again.', 'accessibit' ); // Only a code-shaped value is echoed back. The reason rides in on the URL // of our own redirect, so a crafted link would otherwise put an arbitrary // sentence inside a notice that looks like it came from AccessiBit. Every // code the API returns is lowercase_snake, so nothing real is lost. if ( ! preg_match( '/^[a-z0-9_]{1,64}$/', $reason ) ) { return $generic; } // The parentheses stay out of the catalog: a bare "%1$s (%2$s)" msgid is // nothing a translator can act on. return $generic . ' (' . $reason . ')'; } /** * `admin_post` handler for the Accessibility screen's widget switch. * * Redirects with `saved=1` so the screen can confirm the save. Without it * the form posted, the page came back looking identical, and nothing said * anything had happened. */ public static function handle_toggle_widget(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Forbidden', 'accessibit' ), '', 403 ); } check_admin_referer( 'accessibit_toggle_widget', 'accessibit_toggle_widget_nonce' ); $enabled = sanitize_text_field( wp_unslash( $_POST['accessibit_widget_enabled'] ?? '' ) ) === '1'; Accessibit_Settings::update( array( 'widget_enabled' => $enabled ) ); wp_safe_redirect( admin_url( 'admin.php?page=accessibit-accessibility&saved=1' ) ); exit; } /** * `admin_post` handler for Setup's "Check again". * * Re-reads `/account` with the key already stored, so an admin who has just * bought a licence or verified their domain can tell this plugin about it * without going through the whole connect flow again. */ public static function handle_recheck(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Forbidden', 'accessibit' ), '', 403 ); } check_admin_referer( 'accessibit_recheck', 'accessibit_recheck_nonce' ); // A copy of another site's database holds that site's key, whose scope // names that site. Re-reading it would re-bind this copy to the // original and switch the stale-binding guard off, letting it edit the // original's widget and statement (ACC-411). Only Connect, which checks // this address on the server, may re-bind. Setup says why. if ( Accessibit_Settings::is_binding_stale() ) { self::redirect_setup( array() ); return; } $api_key = Accessibit_Settings::get_api_key(); if ( '' === $api_key ) { self::redirect_setup( array( 'connected' => '0', 'reason' => 'invalid_api_key', ) ); return; } $result = ( new Accessibit_Api_Client( ACCESSIBIT_API_BASE_URL, $api_key, ACCESSIBIT_VERSION ) )->account(); if ( ! $result['ok'] ) { self::redirect_setup( array( 'connected' => '0', 'reason' => $result['code'] ?? 'error', ) ); return; } $slug = $result['data']['company']['slug'] ?? ''; if ( ! is_string( $slug ) || '' === $slug ) { self::redirect_setup( array( 'connected' => '0', 'reason' => 'unexpected_response', ) ); return; } $matched = self::resolve_site( is_array( $result['data'] ) ? $result['data'] : array(), home_url() ); $site_id = null === $matched ? '' : $matched['id']; Accessibit_Settings::set_account( $api_key, $slug, $site_id, null !== $matched && $matched['licensed'], null !== $matched && $matched['verified'] ); Accessibit_Settings::update( Accessibit_Settings::capability_flags( is_array( $result['data'] ) ? $result['data'] : array() ) ); if ( '' !== $site_id ) { // `rechecked=1` for the same reason the widget switch redirects with // `saved=1`: without it the admin pressed a button, the screen came // back byte-identical, and nothing said whether anything had been // re-read — which is the one question this control exists to answer. wp_safe_redirect( admin_url( 'admin.php?page=accessibit-accessibility&rechecked=1' ) ); exit; } self::redirect_setup( array( 'connected' => '1', 'site' => '0', ) ); } /** * `admin_post` handler for Setup's "Disconnect this site". * * There was no way to undo a connection short of uninstalling the plugin: * the key stayed in the options table, and reconnecting to an account that * did not have this site left the widget enabled with no switch on screen to * turn it off. * * The widget is turned off in the same write, so disconnecting can never * leave a public page loading a bundle this site can no longer configure. * * `bound_domain` goes too. It is the address this install connected as, and * the stale-binding notice compares it with the current one — so a staging * clone that followed that notice's own advice and disconnected was still * told, in red, on both screens, that it was "connected under a different * address" and should disconnect. There was nothing left to disconnect, and * no way to clear it short of reconnecting or uninstalling. * * The key is now revoked SERVER-side first (ACC-402). A key this site has * stopped using but AccessiBit still honours is a live credential for the * site, sitting in a database nobody is looking at — and until the connect * flow there was no way for the plugin to retire one, because a pasted key * might belong to something else as well. A connect-flow key belongs to * this install and nothing else, so disconnecting can end it — except on a * copy whose binding is stale, which holds the original site's key. * * Best effort, and deliberately not a gate: the local state is cleared * whether or not the call succeeded. An administrator disconnecting a site * whose network cannot reach us must still end up disconnected — the * alternative is a plugin that refuses to let go, and the key is bound to * one site and revocable from the dashboard anyway. The outcome still rides * the redirect, so the notice only claims a revocation that happened * (ACC-583). */ public static function handle_disconnect(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Forbidden', 'accessibit' ), '', 403 ); } check_admin_referer( 'accessibit_disconnect', 'accessibit_disconnect_nonce' ); $outcome = 'none'; if ( Accessibit_Settings::is_binding_stale() ) { // A copy of another site's database (a staging clone) holds that // site's key, and revoking it would cut the original site off. // Forgetting it here is all this copy may do (ACC-411). $outcome = 'copy'; } elseif ( '' !== Accessibit_Settings::get_api_key() ) { $outcome = self::disconnect_outcome( Accessibit_Api_Client::from_settings()->disconnect() ); } Accessibit_Settings::update( array( 'api_key' => '', 'company_slug' => '', 'site_id' => '', 'widget_enabled' => false, 'widget_licensed' => false, 'site_verified' => false, 'bound_domain' => '', 'statement_id' => '', 'statement_published' => false, 'tracker_available' => false, ) ); // The literal, not `Accessibit_Scan::RUNNING_JOB_OPTION`: that constant // went with the paid scan, and referencing one that no longer exists is // a fatal on every supported PHP — which took Disconnect down with it, // silently, because `php -l` does not resolve constants and no unit test // covers this handler. `uninstall.php` spells the same key out for the // same reason. // // Still deleted rather than ignored: an install that ran an earlier // build may hold the row, and disconnecting is where this plugin's // stored state is meant to go away completely. delete_option( 'accessibit_running_job' ); self::redirect_setup( array( 'disconnected' => $outcome ) ); } /** * What became of the key, from the `DELETE /connection` result. * * - `revoked`: the server revoked it, or already refused it as invalid — * either way it no longer works. * - `kept`: a legacy company-wide key, which the server deliberately * leaves alone because it may be in use elsewhere. * - `unconfirmed`: anything else, a network failure included; the key may * still be live. * * Pure, and public, for the same reason `match_site` is. * * @param array $result An `Accessibit_Api_Client::disconnect()` result. * @return string `revoked`, `kept` or `unconfirmed`. */ public static function disconnect_outcome( array $result ): string { if ( ! empty( $result['ok'] ) ) { return true === ( $result['data']['revoked'] ?? null ) ? 'revoked' : 'kept'; } return 'invalid_api_key' === ( $result['code'] ?? '' ) ? 'revoked' : 'unconfirmed'; } /** * The site this install is bound to, from an `/account` response. * * A connect-flow key IS a site, and `/account` says so in `scope.siteId` * (ACC-402). Reading that rather than matching addresses is what makes * "Check again" survive a site whose registered URL was edited in the * dashboard, a `www.` added or removed, or a move to a new domain — all of * which used to silently unbind the install, because the only thing tying * it to a site was a string comparison between two addresses. * * `match_site` remains the answer for a LEGACY pasted key, which reaches * every site of the company and therefore has to be matched by address. * Those installs exist in the directory, so the path is not dead code. * * Pure, and public, for the same reason `match_site` is. * * @param array $data The decoded `/api/v1/account` body. * @param string $home_url This install's own `home_url()`. * @return array{id: string, licensed: bool, verified: bool}|null */ public static function resolve_site( array $data, string $home_url ): ?array { $sites = isset( $data['sites'] ) && is_array( $data['sites'] ) ? $data['sites'] : array(); $scoped = $data['scope']['siteId'] ?? null; $site_id = is_string( $scoped ) || is_int( $scoped ) ? (string) $scoped : ''; if ( '' !== $site_id ) { foreach ( $sites as $site ) { $raw_id = $site['id'] ?? null; $id = is_string( $raw_id ) || is_int( $raw_id ) ? (string) $raw_id : ''; if ( $id !== $site_id ) { continue; } return array( 'id' => $id, 'licensed' => ! empty( $site['isPro'] ) || ! empty( $site['isTrial'] ), 'verified' => ! array_key_exists( 'verified', $site ) || ! empty( $site['verified'] ), ); } // A scope naming a site that is not in the list is a response we do // not understand; fall through to matching rather than inventing an // entry with no licence or verification state. } return self::match_site( $sites, $home_url ); } /** * Which of the account's sites this WordPress install is, or '' for none. * * This is the whole of the connect flow's site binding: the `www` vs bare * domain, scheme and trailing-path cases all collapse in `sanitize_domain`, * and anything that does not collapse to the same string — a staging * subdomain, a sibling site, a domain not on the account — is correctly no * match. An install whose own url does not reduce to a domain matches * nothing, rather than matching every site whose url the server could not * reduce either — which is what the early return is for. * * First usable match wins: an entry that matches but carries no id is not a * site this install can bind to, so it is skipped rather than allowed to * shadow a later entry that is. Duplicate rows for one domain are not * something the plugin can adjudicate. * * Pure, and public so the unit suite can exercise it without standing up * WordPress for `handle_connect`'s nonce, capability and redirect calls. * * @param array> $sites `sites` from /api/v1/account. * @param string $home_url This install's own `home_url()`. * @return string The matching site's id, or '' when none matches. */ public static function match_site_id( array $sites, string $home_url ): string { $matched = self::match_site( $sites, $home_url ); return null === $matched ? '' : (string) $matched['id']; } /** * The whole matched entry, not just its id. * * `match_site_id` is kept as the thin wrapper it always was, because the * connect flow needs more than the id from the same match: `isPro` / * `isTrial` decide whether the widget switch can do anything, and `verified` * decides whether a scan will be accepted at all. Both were being read off * `/account` and discarded. * * @param array> $sites `sites` from /api/v1/account. * @param string $home_url This install's own `home_url()`. * @return array{id: string, licensed: bool, verified: bool}|null */ public static function match_site( array $sites, string $home_url ): ?array { $host = self::sanitize_domain( $home_url ); if ( '' === $host ) { return null; } foreach ( $sites as $site ) { $url = isset( $site['url'] ) && is_string( $site['url'] ) ? $site['url'] : ''; if ( self::sanitize_domain( $url ) !== $host ) { continue; } // string|int: ids are cuids today, but the old code coerced whatever // it got, so don't start refusing a numeric one. $raw_id = $site['id'] ?? null; $id = is_string( $raw_id ) || is_int( $raw_id ) ? (string) $raw_id : ''; if ( '' !== $id ) { return array( 'id' => $id, 'licensed' => ! empty( $site['isPro'] ) || ! empty( $site['isTrial'] ), // Absent on an older API than this plugin: treat it as // verified rather than warning about something we cannot // know, so a stale server never blocks the screen. 'verified' => ! array_key_exists( 'verified', $site ) || ! empty( $site['verified'] ), ); } } return null; } /** * The domain a site is identified by, as the platform spells it. * * This is a PHP mirror of `sanitizeDomain` in `@accessibit/utils` — the * function the dashboard ran before storing `Website.url`, and therefore the * exact string `/api/v1/account` hands back. Matching has to compute the same * value or it is comparing against a spelling the server never stores, so * keep the two in step: lowercase, drop the scheme, drop a leading `www.`, * and cut at the first `/`, `?` or `#`. * * The port is deliberately kept, because `sanitizeDomain` keeps it: a site * registered as `example.com:8080` is a different `Website` row from * `example.com`, and a plugin that dropped the port would bind this install * to the wrong one. Production sites are on 80/443 and never carry a port, * so the only place this is observable is local development — where the dev * compose file and `dev/seed.mjs` both use `localhost:8090` and so agree * (ACC-483). * * The mirror is exact for ASCII, which is almost all it is ever asked to * compare: `strtolower` only folds ASCII where JS `toLowerCase` folds all of * Unicode (so `CAFÉ.fr` becomes `cafÉ.fr` here and `café.fr` there). That * never mattered on its own, because the dashboard sanitizes the *output* of * `normalizeAndValidateUrl`, which punycodes IDNs — so a stored `Website.url` * is always ASCII, and an IDN install failed to match on the punycode rather * than on the case. * * `punycode_host()` below is what closes that, by converting to the same * ASCII form the dashboard stores — which also disposes of the case question, * since UTS-46 case-folds all of Unicode on the way. ASCII hosts never reach * it, so nothing about the common path changes. * * Deliberately WordPress-free: no `wp_parse_url`, so it is a pure function * the unit suite can call directly. * * @param string $url Any URL, or a bare domain. * @return string The domain as the platform stores it, or '' if there is none. */ public static function sanitize_domain( string $url ): string { $value = strtolower( trim( $url ) ); $value = preg_replace( '~^https?://~', '', $value ); $value = preg_replace( '~^www\.~', '', $value ); $host = preg_split( '~[/?#]~', $value )[0]; return self::punycode_host( $host ); } /** * An internationalized host in the form the platform stores it. * * The dashboard sanitizes the OUTPUT of `normalizeAndValidateUrl`, which * resolves through the WHATWG URL parser and therefore punycodes — so a * stored `Website.url` for an IDN is always ASCII (`xn--caf-dma.com`), while * `home_url()` on such a site is usually the Unicode form (`café.com`). The * two could never match, so connecting an IDN install reported "this site is * not registered in AccessiBit" with the two addresses printed side by side * looking, to the administrator, identical. * * Converted only when there is something to convert, and only when ext-intl * is present: * * - An all-ASCII host is returned untouched rather than round-tripped. UTS-46 * would also return it unchanged, but not calling at all is what makes this * provably a no-op for every install that is not an IDN — which is nearly * all of them, and the behaviour the unit suite already pins. * - `idn_to_ascii()` lives in ext-intl, which is very common but NOT part of * the PHP the plugin claims to support. Without it the Unicode form is * returned as before: no better than today, and no worse. Making the result * depend on an extension is a real cost, which is why it buys an outcome * that is otherwise impossible rather than tidying one that works. * - A conversion that fails returns `false`; the original is kept, because a * mismatch an administrator can read is better than an empty string that * turns the Setup screen's comparison into nonsense. * * @param string $host A bare host, already lowercased and path-stripped. * @return string The host, punycoded where that is possible and needed. */ private static function punycode_host( string $host ): string { if ( '' === $host || ! preg_match( '~[^\x20-\x7e]~', $host ) ) { return $host; } if ( ! function_exists( 'idn_to_ascii' ) ) { return $host; } $ascii = idn_to_ascii( $host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46 ); return is_string( $ascii ) && '' !== $ascii ? $ascii : $host; } /** * This admin user's locale as a BCP-47 tag, for `toLocaleDateString`. * * Both admin scripts rendered dates with `toLocaleDateString()` and no * argument, which uses the BROWSER's locale: an administrator running * wp-admin in Italian on an English-configured browser read every date in * US order, in a screen whose every other word was Italian. `9/29/2026` is * not merely foreign there, it is ambiguous — `29/9` and `9/29` are the same * glyphs in a different order. * * `determine_locale()` rather than `get_user_locale()`, though in ordinary * wp-admin they are the same value: it is the locale core resolves when it * loads the plugin's language pack just in time, so it is by definition the * locale the strings beside this date were loaded in. Reading the user's setting * directly can disagree with that — anything filtering `determine_locale` * (WPML, Polylang, and this repo's own e2e locale switch) moves the strings * and not the user's profile, which would put an Italian sentence and a US * date in the same line. Both prefer the per-user language over the site's, * which is the property that matters here. * * Underscores become hyphens because WordPress spells locales `it_IT` and * `Intl` wants `it-IT`; a bare `it` passes through unchanged. Anything the * browser then rejects is handled on the JavaScript side, which falls back * to its own default rather than throwing. * * @return string A BCP-47 language tag. */ private static function js_locale(): string { return str_replace( '_', '-', determine_locale() ); } /** * Redirect back to the Setup screen, carrying the outcome in the query string. * * @param array $args Query args the Setup view reads to pick its notice. */ private static function redirect_setup( array $args ): void { wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php?page=accessibit' ) ) ); exit; } }