From 91d50640052d91ccf5ceeae4eea24a4ef0df401a Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Wed, 23 Sep 2026 20:48:18 +0000 Subject: [PATCH 01/75] feat(connect): one button instead of copying an API key (1.8.3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Onboarding was four steps before the plugin could do anything: make an account on sendbeam.io, verify a domain, create an API key with the right permissions, paste it back. Every one of those was somewhere to stop. The Overview tab's first step is now a button. The site says who it is and what it wants to do; the person creates the account or signs in on sendbeam.io in a pop-up, with the site name and their admin email address already filled in; SendBeam hands this site a key with exactly the permissions they ticked. The plugin is the client in that exchange and never trusts the browser with the key: - the pop-up comes back with a single-use grant, not a key; - the key is fetched server-to-server, from this site's own PHP (POST /api/v1/connect/exchange); - `state` is the CSRF token, because a nonce cannot survive a redirect from another origin. It is minted here, kept in a transient belonging to one administrator, and deleted the moment it is read, in every branch — so a replayed return URL is worth nothing. - site_url must be https (http only for localhost, 127.0.0.1 and .test/.local dev boxes), and nothing is remembered for a site that fails that check. The key is written through the same sendbeam_sanitize_settings() path a pasted key goes through, rather than straight into the option: one set of validation rules instead of two, and the one that skips the validation is always the one that stores rubbish. Pasting or removing a key by hand clears the Connect marker, and Disconnect is the existing "Remove the saved key" path — it forgets this site's copy and says plainly that the key stays valid in SendBeam until revoked there. Pasting a key still works, moved to a quiet "I already have an API key" disclosure under the button. readme.txt gains a sixth external-service item covering exactly what leaves the site and what comes back. uninstall.php now sweeps sendbeam_connect_* transients for every administrator, not just the one doing the uninstalling. New includes/connect.php, 98 new smoke checks with the SendBeam end stubbed, and the cross-origin half covered by a Playwright spec in the private e2e repository. --- CHANGELOG.md | 8 + README.md | 10 +- blocks/form/block.json | 2 +- blocks/form/index.asset.php | 2 +- includes/admin-ui.php | 5 + includes/connect.php | 576 ++++++++++++++++++++++++++++++++++++ includes/helpers.php | 47 +-- includes/onboarding.php | 4 +- includes/screens.php | 91 +++++- includes/settings.php | 6 +- readme.txt | 14 +- sendbeam.php | 5 +- tests/smoke.php | 294 ++++++++++++++++++ tests/wp-stubs.php | 37 ++- uninstall.php | 41 ++- 15 files changed, 1079 insertions(+), 63 deletions(-) create mode 100644 includes/connect.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2141530..99549f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.8.3 + +- **Connect SendBeam.** Onboarding was four steps before the plugin did anything: make an account on sendbeam.io, verify a domain, create an API key with the right permissions, paste it back. Every one of those was somewhere to stop. The Overview tab's first step is now a button: tick what this site may do, create the account or sign in in a pop-up on sendbeam.io — with the site name and the administrator's email address already filled in — and the site is handed a key with exactly those permissions. +- The plugin is the client in that exchange and never trusts the browser with the key. The pop-up comes back with a single-use grant, not a key; the key is fetched server-to-server from this site's own PHP (`POST /api/v1/connect/exchange`); and `state` — minted here, kept in a transient belonging to one administrator, and deleted the moment it is read — is the CSRF token, because a nonce cannot survive a redirect from another origin. +- The key is written through the same `sendbeam_sanitize_settings()` path a pasted key goes through, so there is one set of validation rules rather than two. Pasting or removing a key by hand clears the Connect marker, and **Disconnect** is the existing "Remove the saved key" path — it forgets this site's copy, and says plainly that the key stays valid in SendBeam until revoked there. +- Pasting a key still works, moved into a quiet "I already have an API key" disclosure under the button. +- `uninstall.php` now sweeps `sendbeam_connect_*` transients for every administrator, not just the one doing the uninstalling. + ## 1.8.2 - Pop-ups come in four styles — split with image, editorial, bold colour and slide-in — with an image, an eyebrow, a button label and an optional subscriber count, set per pop-up. diff --git a/README.md b/README.md index b44934d..0ed1512 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,14 @@ git clone https://github.com/sendbeam-io/sendbeam-wordpress cd sendbeam-wordpress && bin/build-zip.sh # → build/sendbeam.zip ``` -Then Settings → SendBeam and paste an API key. Forms are picked from a dropdown of the connected workspace's -own forms — no IDs to copy. +Then Settings → SendBeam and press **Connect SendBeam**. The button opens a window on sendbeam.io where you +create your account or sign in — the site's name and your administrator email address are already filled in — +and tick what this site may do: show your forms, add people who opt in, send the site's own email, send +WooCommerce events. Approve, and this site is handed an API key with exactly those permissions. The key never +passes through the browser: the window comes back with a single-use grant bound to this site's address and to +the `state` this site minted, and your server swaps it for the key in one call. Nothing is sent to SendBeam +until you press the button. If you already have a key, "I already have an API key" on the same screen still +takes one. Forms are then picked from a dropdown of the connected workspace's own forms — no IDs to copy. ## API key permissions diff --git a/blocks/form/block.json b/blocks/form/block.json index 55e1507..2fa8c25 100644 --- a/blocks/form/block.json +++ b/blocks/form/block.json @@ -2,7 +2,7 @@ "$schema": "https://schemas.wp.org/trunk/block.json", "apiVersion": 3, "name": "sendbeam/form", - "version": "1.8.2", + "version": "1.8.3", "title": "SendBeam Form", "category": "widgets", "icon": "email-alt", diff --git a/blocks/form/index.asset.php b/blocks/form/index.asset.php index c75a57b..7a5690c 100644 --- a/blocks/form/index.asset.php +++ b/blocks/form/index.asset.php @@ -7,5 +7,5 @@ return array( 'dependencies' => array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-server-side-render', 'wp-api-fetch' ), - 'version' => '1.8.2', + 'version' => '1.8.3', ); diff --git a/includes/admin-ui.php b/includes/admin-ui.php index d8b6e27..62fa40d 100644 --- a/includes/admin-ui.php +++ b/includes/admin-ui.php @@ -129,6 +129,11 @@ function sendbeam_admin_css() { .sendbeam-app .sb-mono,.sendbeam-app .sb-label,.sendbeam-app .sb-state,.sendbeam-app .sb-chip,.sendbeam-app .sb-tab,.sendbeam-app code {font-family:"Martian Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-variant-numeric:tabular-nums} + .sb-scopes{list-style:none;margin:0;padding:0} + .sb-scopes li{margin:0 0 6px} + .sb-scopes label{display:flex;gap:8px;align-items:flex-start;line-height:1.45} + .sb-paste>summary{cursor:pointer;font-size:12px;color:var(--ink-60)} + .sb-head{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap; padding:18px 22px;background:var(--ink);color:var(--paper)} .sb-head__brand{display:flex;align-items:center;gap:10px} diff --git a/includes/connect.php b/includes/connect.php new file mode 100644 index 0000000..003ffd3 --- /dev/null +++ b/includes/connect.php @@ -0,0 +1,576 @@ + + */ +function sendbeam_connect_scopes() { + return array( + 'forms' => array( + 'label' => __( 'Show your forms on the site', 'sendbeam' ), + 'always' => true, + ), + 'contacts:write' => array( + 'label' => __( 'Add people who tick an opt-in box at registration, in comments or at checkout', 'sendbeam' ), + 'always' => false, + ), + 'transactional:send' => array( + 'label' => __( 'Send the site\'s own email (password resets, order emails, notifications) through SendBeam', 'sendbeam' ), + 'always' => false, + ), + 'ecommerce' => array( + 'label' => __( 'Send WooCommerce order, cart and product events to SendBeam', 'sendbeam' ), + 'always' => false, + ), + ); +} + +/** + * This site's origin — scheme, host and port, nothing else. + * + * SendBeam binds the grant to this exact string and refuses to hand the key to + * anything else, so it must be the origin and not a path: a site installed in + * a subdirectory would otherwise present a different value on the way out than + * on the way back. + * + * @return string + */ +function sendbeam_connect_site_origin() { + $parts = wp_parse_url( site_url() ); + if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { + return ''; + } + $origin = $parts['scheme'] . '://' . $parts['host']; + if ( ! empty( $parts['port'] ) ) { + $origin .= ':' . (int) $parts['port']; + } + return $origin; +} + +/** + * Is this origin one SendBeam will accept? + * + * Https everywhere, because the grant travels over it: http is allowed only on + * the hostnames a development machine uses, which cannot be reached from the + * internet — refusing those outright would make the feature untestable on a + * local install without weakening it anywhere that matters. + * + * @param string $origin Origin from sendbeam_connect_site_origin(). + * @return bool + */ +function sendbeam_connect_origin_ok( $origin ) { + $parts = wp_parse_url( (string) $origin ); + if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { + return false; + } + if ( 'https' === $parts['scheme'] ) { + return true; + } + if ( 'http' !== $parts['scheme'] ) { + return false; + } + $host = strtolower( $parts['host'] ); + if ( in_array( $host, array( 'localhost', '127.0.0.1', '::1', '[::1]' ), true ) ) { + return true; + } + return (bool) preg_match( '/\.(test|local)$/', $host ); +} + +/** + * Where the pop-up's state lives while the person is on sendbeam.io. + * + * Per user, not per site: two administrators connecting at once must not + * overwrite each other's state, and a state minted by one of them must not be + * usable by the other. + * + * @param int $user_id User ID. + * @return string + */ +function sendbeam_connect_transient_key( $user_id ) { + return 'sendbeam_connect_' . (int) $user_id; +} + +/** + * The pop-up URL, exactly as the contract specifies it. + * + * Nothing here is left to add_query_arg(), which does not encode: every value + * is rawurlencode()d first. A site name with a space or an ampersand would + * otherwise cut the query in half and SendBeam would read the wrong return + * address. + * + * @param string[] $scopes Approved scope names. + * @param string $state The CSRF token. + * @return string Empty when this site cannot be connected (bad origin). + */ +function sendbeam_connect_start_url( $scopes, $state ) { + $origin = sendbeam_connect_site_origin(); + if ( '' === $origin || ! sendbeam_connect_origin_ok( $origin ) ) { + return ''; + } + + $user = wp_get_current_user(); + $name = trim( (string) get_bloginfo( 'name' ) ); + if ( function_exists( 'mb_substr' ) ) { + $name = mb_substr( $name, 0, 80 ); + } else { + $name = substr( $name, 0, 80 ); + } + + return add_query_arg( + array( + 'site_url' => rawurlencode( $origin ), + 'site_name' => rawurlencode( $name ), + 'email' => rawurlencode( isset( $user->user_email ) ? (string) $user->user_email : '' ), + 'scopes' => rawurlencode( implode( ',', $scopes ) ), + 'state' => rawurlencode( $state ), + 'return_to' => rawurlencode( sendbeam_connect_return_url() ), + ), + sendbeam_app_url() . '/connect/wordpress' + ); +} + +/** + * Where SendBeam sends the pop-up back to. Always on this site's own origin. + * + * @return string + */ +function sendbeam_connect_return_url() { + return admin_url( 'admin-post.php?action=sendbeam_connect_return' ); +} + +/** + * Only the scopes we offer, and `forms` whether it was ticked or not. + * + * Nothing works without `forms` — the settings screen cannot list a single + * form — so it is presented as fixed rather than as a choice that quietly + * breaks the plugin. + * + * @param mixed $raw Posted scope list. + * @return string[] + */ +function sendbeam_connect_clean_scopes( $raw ) { + $known = sendbeam_connect_scopes(); + $out = array(); + foreach ( $known as $scope => $meta ) { + if ( $meta['always'] ) { + $out[] = $scope; + continue; + } + if ( is_array( $raw ) && in_array( $scope, array_map( 'strval', $raw ), true ) ) { + $out[] = $scope; + } + } + return $out; +} + +/** + * Step one: mint the state, remember it, and send the pop-up to SendBeam. + */ +function sendbeam_connect_start() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); + } + check_admin_referer( 'sendbeam_connect_start' ); + + $raw = array(); + if ( isset( $_POST['sendbeam_scopes'] ) && is_array( $_POST['sendbeam_scopes'] ) ) { + $raw = array_map( 'sanitize_text_field', wp_unslash( $_POST['sendbeam_scopes'] ) ); + } + $scopes = sendbeam_connect_clean_scopes( $raw ); + + // [A-Za-z0-9] only, and 43 of them: comfortably past the 32 the contract + // asks for, and safe in a query string without escaping surprises. + $state = wp_generate_password( 43, false, false ); + + // Built before anything is remembered: a site that cannot be connected at + // all should not be left holding a pending connection it can never finish. + $url = sendbeam_connect_start_url( $scopes, $state ); + if ( '' === $url ) { + wp_die( esc_html__( 'This site has no https address, so it cannot be connected to SendBeam. Add a certificate, or paste an API key instead.', 'sendbeam' ) ); + } + + set_transient( + sendbeam_connect_transient_key( get_current_user_id() ), + array( + 'state' => $state, + 'scopes' => $scopes, + ), + SENDBEAM_CONNECT_TTL + ); + + // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- deliberately off-site: this is the whole point of the button, and the destination is sendbeam_app_url(). + wp_redirect( $url, 302 ); + exit; +} + +/** + * Step two: the pop-up comes back. Swap the grant for a key, server to server. + */ +function sendbeam_connect_return() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); + } + + /* + * No nonce, by design (see the file header): this is a redirect arriving + * from sendbeam.io, and `state` is the token. It is read once and the + * transient is deleted immediately, in every branch below, so the same + * return URL cannot be replayed. + */ + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- `state`, checked below against a per-user transient, is the CSRF token for this cross-site return. + $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; + $grant = isset( $_GET['grant'] ) ? sanitize_text_field( wp_unslash( $_GET['grant'] ) ) : ''; + $error = isset( $_GET['error'] ) ? sanitize_key( wp_unslash( $_GET['error'] ) ) : ''; + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + $key = sendbeam_connect_transient_key( get_current_user_id() ); + $stored = get_transient( $key ); + delete_transient( $key ); + + $expected = is_array( $stored ) && isset( $stored['state'] ) ? (string) $stored['state'] : ''; + + if ( '' === $expected || '' === $state || ! hash_equals( $expected, $state ) ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'This window did not come back from the request this site started. Nothing was changed. Close it and press Connect SendBeam again.', 'sendbeam' ) + ); + exit; + } + + if ( '' !== $error ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'You did not approve the connection, so this site was given nothing. You can press Connect SendBeam again whenever you like.', 'sendbeam' ) + ); + exit; + } + + if ( ! preg_match( '/^[A-Za-z0-9_\-]{20,128}$/', $grant ) ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'SendBeam did not send anything this site could use. Nothing was changed.', 'sendbeam' ) + ); + exit; + } + + $result = sendbeam_connect_exchange( $grant, $state ); + if ( $result['ok'] ) { + sendbeam_connect_render_result( + true, + __( 'Connected', 'sendbeam' ), + $result['workspace'] + /* translators: %s: the SendBeam workspace name */ + ? sprintf( __( 'This site is connected to %s. You can close this window.', 'sendbeam' ), $result['workspace'] ) + : __( 'This site is connected. You can close this window.', 'sendbeam' ) + ); + exit; + } + + sendbeam_connect_render_result( false, __( 'Not connected', 'sendbeam' ), $result['error'] ); + exit; +} + +/** + * The server-to-server half: grant in, key out, once. + * + * The key never touches the browser and is never written to a log — not the + * error branch either, which is where that usually happens. + * + * @param string $grant Single-use grant ID from the redirect. + * @param string $state The state it is bound to. + * @return array{ok:bool,workspace:string,error:string} + */ +function sendbeam_connect_exchange( $grant, $state ) { + $origin = sendbeam_connect_site_origin(); + $response = wp_remote_post( + sendbeam_app_url() . '/api/v1/connect/exchange', + array( + 'timeout' => 15, + 'headers' => array( + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + 'User-Agent' => 'SendBeam-WordPress/' . SENDBEAM_VERSION . ' (' . $origin . ')', + ), + 'body' => wp_json_encode( + array( + 'grant' => $grant, + 'state' => $state, + 'site_url' => $origin, + ) + ), + ) + ); + + if ( is_wp_error( $response ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'This server could not reach sendbeam.io to finish the connection. Nothing was changed. Try again, or paste an API key instead.', 'sendbeam' ), + ); + } + + $status = (int) wp_remote_retrieve_response_code( $response ); + $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); + $data = is_array( $body ) ? $body : array(); + + if ( 410 === $status ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'That connection had already been used, or it was left too long. Nothing was changed. Press Connect SendBeam again to start a fresh one.', 'sendbeam' ), + ); + } + if ( 429 === $status ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam is rate-limiting this site. Wait a few minutes and press Connect SendBeam again.', 'sendbeam' ), + ); + } + if ( 200 !== $status || empty( $data['api_key'] ) || ! is_string( $data['api_key'] ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam refused to finish the connection. Nothing was changed. Press Connect SendBeam again, or paste an API key instead.', 'sendbeam' ), + ); + } + + $workspace = ''; + if ( isset( $data['workspace']['name'] ) && is_string( $data['workspace']['name'] ) ) { + $workspace = sanitize_text_field( $data['workspace']['name'] ); + } + + if ( ! sendbeam_connect_store_key( $data['api_key'], $workspace ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam sent something that does not look like an API key, so nothing was saved. Press Connect SendBeam again, or paste a key instead.', 'sendbeam' ), + ); + } + + return array( + 'ok' => true, + 'workspace' => $workspace, + 'error' => '', + ); +} + +/** + * Save the key the way a pasted one is saved. + * + * Through sendbeam_sanitize_settings() rather than straight into the option: + * that function is where the key is validated, where the other tabs' settings + * are preserved and where the cached workspace data is dropped. A second way + * of writing the same option is a second set of rules to keep in step, and + * the one that skips the validation is the one that stores rubbish. + * + * @param string $api_key The key SendBeam minted. + * @param string $workspace Workspace name, for the screen to show. + * @return bool False when the key did not survive validation — nothing saved. + */ +function sendbeam_connect_store_key( $api_key, $workspace ) { + $clean = sendbeam_sanitize_settings( + array( + '_tab' => 'connect', + 'api_key' => $api_key, + ) + ); + + if ( trim( (string) $api_key ) !== (string) $clean['api_key'] || '' === (string) $clean['api_key'] ) { + return false; + } + + $clean['sendbeam_connected_via'] = 'connect'; + $clean['sendbeam_connect_workspace'] = $workspace; + + update_option( 'sendbeam_settings', $clean ); + sendbeam_flush_cache(); + return true; +} + +/** + * Was this site connected through the button rather than a pasted key? + * + * @return bool + */ +function sendbeam_connected_via_connect() { + $settings = sendbeam_settings(); + return 'connect' === (string) $settings['sendbeam_connected_via'] && '' !== sendbeam_api_key(); +} + +/** + * The workspace the button connected this site to, if it was the button. + * + * @return string + */ +function sendbeam_connect_workspace_name() { + $settings = sendbeam_settings(); + return (string) $settings['sendbeam_connect_workspace']; +} + +/** + * The little page the pop-up ends on. + * + * It tells the opener what happened and closes itself. The link underneath is + * not decoration: a browser will only close a window that script opened, and + * if the person reached this through something other than the pop-up — a + * blocker, a middle-click — the window stays and the link is the way out. + * + * @param bool $connected Whether a key was stored. + * @param string $heading Heading. + * @param string $detail One sentence under it. + */ +function sendbeam_connect_render_result( $connected, $heading, $detail ) { + $overview = admin_url( 'options-general.php?page=sendbeam' ); + $origin = sendbeam_connect_site_origin(); + + nocache_headers(); + if ( ! headers_sent() ) { + header( 'Content-Type: text/html; charset=utf-8' ); + } + + echo ''; + echo ''; + echo '' . esc_html( $heading ) . ''; + echo ''; + printf( '

%s

', esc_html( $heading ) ); + printf( '

%s

', esc_html( $detail ) ); + printf( + '

%s

', + esc_url( $overview ), + esc_html__( 'Back to SendBeam settings', 'sendbeam' ) + ); + + // Only a success is announced; the opener reloads on it and would + // otherwise throw away an unsaved settings form for nothing. + if ( $connected && '' !== $origin ) { + printf( + '', + wp_json_encode( $origin, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) + ); + } else { + echo ''; + } + + echo ''; + + /** + * Fires when the Connect pop-up has rendered its outcome, immediately + * before the request ends. + * + * @param bool $connected Whether a key was stored. + * @param string $detail The sentence shown to the person. + */ + do_action( 'sendbeam_connect_result', $connected, $detail ); +} + +/** + * The Connect panel: what the site wants to do, and the button. + * + * @return void + */ +function sendbeam_connect_panel() { + $origin = sendbeam_connect_site_origin(); + + if ( ! sendbeam_connect_origin_ok( $origin ) ) { + echo '

' . esc_html__( 'This site is not served over https, so SendBeam cannot connect to it. Paste an API key below instead.', 'sendbeam' ) . '

'; + return; + } + + echo '

' . esc_html__( 'Create your SendBeam account, or sign in, and this site is connected — no key to copy.', 'sendbeam' ) . '

'; + + printf( '
', esc_url( admin_url( 'admin-post.php' ) ) ); + wp_nonce_field( 'sendbeam_connect_start' ); + echo ''; + echo '

' . esc_html__( 'This site will ask SendBeam for permission to:', 'sendbeam' ) . '

'; + echo ''; + printf( + '

', + esc_html__( 'Connect SendBeam', 'sendbeam' ) + ); + echo '
'; +} + +/** + * The two behaviours the panel needs, appended to the admin script. + * + * The window is opened in the submit handler — synchronously, inside the + * click — because a pop-up opened any later is a pop-up the browser blocks. + * If it is blocked anyway the form is left alone and simply navigates, which + * still works: the return page has a link back. + * + * @return string + */ +function sendbeam_connect_admin_js() { + $origin = wp_json_encode( sendbeam_connect_site_origin(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); + return ' + ( function () { + var origin = ' . $origin . '; + var form = document.getElementById( "sb-connect-form" ); + if ( form ) { + form.addEventListener( "submit", function () { + var win = window.open( "", "sendbeam-connect", "width=600,height=760" ); + if ( win ) { form.target = "sendbeam-connect"; } + } ); + } + window.addEventListener( "message", function ( e ) { + if ( e.origin !== origin || ! e.data || "connected" !== e.data.sendbeam ) { return; } + window.location.reload(); + } ); + }() ); + '; +} diff --git a/includes/helpers.php b/includes/helpers.php index e1b0b2f..929cb4f 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -27,27 +27,32 @@ function sendbeam_app_url() { */ function sendbeam_default_settings() { return array( - 'default_form' => '', - 'contact_form' => '', - 'popup_form' => '', - 'popup_where' => 'off', - 'popup_trigger' => 'timer', - 'popup_delay' => 5, - 'popup_once' => 'day', - 'popup_label' => '', - 'style_accent' => '', - 'style_text' => '', - 'style_field' => '', - 'style_border' => '', - 'style_radius' => '', - 'style_font' => 'inherit', - 'style_size' => '', - 'style_bare' => 1, - 'mail_enabled' => 0, - 'api_key' => '', - 'mail_from_name' => '', - 'mail_from_email' => '', - 'mail_fallback' => 1, + 'default_form' => '', + 'contact_form' => '', + 'popup_form' => '', + 'popup_where' => 'off', + 'popup_trigger' => 'timer', + 'popup_delay' => 5, + 'popup_once' => 'day', + 'popup_label' => '', + 'style_accent' => '', + 'style_text' => '', + 'style_field' => '', + 'style_border' => '', + 'style_radius' => '', + 'style_font' => 'inherit', + 'style_size' => '', + 'style_bare' => 1, + 'mail_enabled' => 0, + 'api_key' => '', + 'mail_from_name' => '', + 'mail_from_email' => '', + 'mail_fallback' => 1, + // Set only when the key arrived through Connect, so the Overview can + // name the workspace and offer Disconnect rather than a paste field. + // Cleared the moment the key is changed or removed by hand. + 'sendbeam_connected_via' => '', + 'sendbeam_connect_workspace' => '', ); } diff --git a/includes/onboarding.php b/includes/onboarding.php index 7bc6a76..f580501 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -62,7 +62,7 @@ function sendbeam_setup_steps() { 'label' => __( 'Connect your SendBeam account', 'sendbeam' ), 'detail' => $connected ? __( 'Your key works.', 'sendbeam' ) - : __( 'Paste an API key so this plugin can list your forms for you.', 'sendbeam' ), + : __( 'Press Connect SendBeam, approve what this site may do, and the key arrives on its own.', 'sendbeam' ), ), array( 'done' => $using_form || $using_popup, @@ -108,7 +108,7 @@ function sendbeam_setup_notice() {

- +

diff --git a/includes/screens.php b/includes/screens.php index 7fabb06..dc11b86 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -35,29 +35,43 @@ function sendbeam_form_close() { * Overview tab: how far through set-up the site is, what the workspace holds, and the API key. */ function sendbeam_screen_overview() { - $settings = sendbeam_settings(); - $forms = sendbeam_remote_forms(); - $lists = sendbeam_lists(); + $forms = sendbeam_remote_forms(); + $lists = sendbeam_lists(); // Asked for directly, not summed from the lists: one person on three lists // is one subscriber, and adding the lists up counted them three times. $subscribers = sendbeam_subscriber_count(); + $connected = sendbeam_is_connected(); echo '

'; sendbeam_card_open( __( 'Setup', 'sendbeam' ) ); - $steps = sendbeam_setup_steps(); - echo '
    '; + $steps = sendbeam_setup_steps(); $targets = array( sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', sendbeam_tab_url( 'forms' ), sendbeam_tab_url( 'mail' ) ); + echo '
      '; foreach ( $steps as $i => $step ) { + // Step one is not a link to a field any more when there is nothing + // connected: it is the thing itself, done here, in one button. + $is_connect_step = ( 0 === $i && ! $connected ); + printf( - '
    1. %4$s%5$s
    2. ', + '
    3. ', $step['done'] ? 'is-done' : '', - $step['done'] ? '✓' : (int) ( $i + 1 ), - esc_url( $targets[ $i ] ), - esc_html( $step['label'] ), - esc_html( $step['detail'] ) + $step['done'] ? '✓' : (int) ( $i + 1 ) ); + if ( $is_connect_step ) { + printf( '%s', esc_html( $step['label'] ) ); + sendbeam_connect_panel(); + sendbeam_connect_paste_disclosure(); + } else { + printf( + '%2$s%3$s', + esc_url( $targets[ $i ] ), + esc_html( $step['label'] ), + esc_html( $step['detail'] ) + ); + } + echo '
    4. '; } echo '
    '; sendbeam_card_close(); @@ -73,11 +87,64 @@ function sendbeam_screen_overview() { echo '
'; - sendbeam_card_open( __( 'Connect', 'sendbeam' ) ); + // When nothing is connected the key field lives in the disclosure above, + // under the Connect button — one paste field on the screen, never two. + if ( $connected ) { + sendbeam_card_open( __( 'Connect', 'sendbeam' ) ); + if ( sendbeam_connected_via_connect() ) { + sendbeam_connect_connected_panel(); + } else { + sendbeam_form_open( 'connect' ); + do_settings_sections( 'sendbeam_connect_page' ); + sendbeam_form_close(); + } + sendbeam_card_close(); + } +} + +/** + * The paste field, tucked away for the people who already have a key. + * + * Open by default would make the screen look like it still wants a key + * copied across, which is the friction Connect exists to remove. + */ +function sendbeam_connect_paste_disclosure() { + echo '
'; + echo '' . esc_html__( 'I already have an API key', 'sendbeam' ) . ''; + echo '
'; sendbeam_form_open( 'connect' ); do_settings_sections( 'sendbeam_connect_page' ); sendbeam_form_close(); - sendbeam_card_close(); + echo '
'; +} + +/** + * What the Connect card says once the button has done its work. + * + * Disconnect goes through the same "Remove the saved key" path a pasted key + * uses, so there is one way of forgetting a key rather than two. It forgets + * this site's copy and nothing else — the key itself is still live in + * SendBeam, which is where it has to be revoked, and saying so is the + * difference between a tidy uninstall and a key nobody knows is still valid. + */ +function sendbeam_connect_connected_panel() { + $workspace = sendbeam_connect_workspace_name(); + + if ( '' !== $workspace ) { + /* translators: %s: the SendBeam workspace name */ + echo '

' . esc_html( sprintf( __( 'Connected to %s', 'sendbeam' ), $workspace ) ) . '

'; + } else { + echo '

' . esc_html__( 'Connected', 'sendbeam' ) . '

'; + } + echo '

' . esc_html__( 'This site was connected through SendBeam, and holds a key with only the permissions you approved.', 'sendbeam' ) . '

'; + echo '

' . esc_html__( 'Disconnecting forgets this site\'s copy of the key. The key itself stays valid in SendBeam until you revoke it there, under Settings → API keys.', 'sendbeam' ) . '

'; + + echo '
'; + settings_fields( 'sendbeam' ); + echo ''; + echo ''; + submit_button( __( 'Disconnect', 'sendbeam' ), 'secondary', 'submit', false ); + echo '
'; } /** diff --git a/includes/settings.php b/includes/settings.php index a521ece..7a02b9e 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -228,8 +228,12 @@ function sendbeam_sanitize_settings( $input ) { // A different key means a different workspace, so anything remembered about // the old one — whether it worked, which forms it could see — is now a lie. + // That includes the Connect marker: a key pasted or removed by hand did not + // come from the Connect button, and the screen must stop claiming it did. if ( $out['api_key'] !== (string) $saved['api_key'] ) { sendbeam_flush_cache(); + $out['sendbeam_connected_via'] = ''; + $out['sendbeam_connect_workspace'] = ''; } unset( $out['_tab'] ); @@ -675,5 +679,5 @@ function flash() { '; wp_register_script( 'sendbeam-admin', '', array(), SENDBEAM_VERSION, true ); wp_enqueue_script( 'sendbeam-admin' ); - wp_add_inline_script( 'sendbeam-admin', $js ); + wp_add_inline_script( 'sendbeam-admin', $js . sendbeam_connect_admin_js() ); } diff --git a/readme.txt b/readme.txt index 78cb144..6ed403e 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: newsletter, email marketing, signup form, popup, contact form Requires at least: 6.1 Tested up to: 7.1 Requires PHP: 7.4 -Stable tag: 1.8.2 +Stable tag: 1.8.3 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -31,7 +31,7 @@ A site can listen for `sendbeam:submitted` on `document` to track a signup as an = External service = -This plugin talks to SendBeam (sendbeam.io) in five distinct ways. Nothing is sent anywhere else. +This plugin talks to SendBeam (sendbeam.io) in six distinct ways. Nothing is sent anywhere else. **1. Showing a form or pop-up.** The visitor's browser loads the form from `https://sendbeam.io/f/
` and, for the pop-up, the script `https://sendbeam.io/f//popup.js`. The URL carries the appearance you chose (colours, corner radius, text size, typeface) so the form matches your theme, and for a pop-up its headline, line underneath, style, image address, eyebrow, button label and whether to show the subscriber count; these are your settings, not anything about the visitor. Your server makes no request to show a form. @@ -43,6 +43,8 @@ This plugin talks to SendBeam (sendbeam.io) in five distinct ways. Nothing is se **5. Forms built with another form plugin** (off by default, and off for every form until you switch it on for that form). When someone submits a Contact Form 7, Elementor Pro, WPForms, Gravity Forms or Fluent Forms form you have connected, and either ticked the consent field you named or filled in a form you marked as a signup form, their email address, first and last name and the name of the form plugin are sent from your server to `/api/v1/contacts`, added to the list you chose (`/api/v1/lists//contacts`) and, if you set one, given a tag (`/api/v1/tags` and `/api/v1/contacts//tags`). Nothing else from the form is sent. +**6. Connecting this site to SendBeam** (only when you press the Connect SendBeam button). A window opens on `https://sendbeam.io/connect/wordpress` carrying this site's address, its title, your WordPress administrator email address — used only to fill in the signup or sign-in form, so you do not type it again — and the list of permissions this site is asking for. If you do not already have a SendBeam account you create one there, on sendbeam.io; account creation never happens on your site and your SendBeam password is never seen by WordPress. When you approve, your server makes one call to `https://sendbeam.io/api/v1/connect/exchange` and receives an API key for this site with exactly the permissions you ticked. The key is stored in this site's options table, the same place a pasted key goes. Press nothing and nothing is sent. + **Site email** (off by default) posts each email your site sends from your server to `https://sendbeam.io/api/v1/transactional` with your API key: the recipient addresses, subject, body and reply-to, so SendBeam can deliver it from your verified domain. Messages with attachments are left to the server's own mailer. **E-commerce events** (off by default, each of the three switched on separately, WooCommerce only) posts to `https://sendbeam.io/api/v1/ecommerce/events` with your API key: an email address, and depending on the event a name, an order total and its currency. Order placed sends when an order is completed. Product viewed sends only when the visitor is a known contact (logged in, or an email already given this visit) — never for an anonymous visitor. Cart abandoned is a best-effort heuristic: adding an item to the cart is timestamped locally on your server, and if no order has followed within a window you set (60 minutes by default) and an email became known at some point, one event is sent; nothing is sent for a cart nobody's email was ever known for. @@ -56,8 +58,9 @@ A SendBeam account (the Free plan is enough) with at least one form. Form IDs ar == Installation == 1. Install and activate the plugin. -2. Go to **Settings → SendBeam** and paste the ID of your signup form (and, if you like, a contact form and a pop-up form). -3. Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. +2. Go to **Settings → SendBeam** and click **Connect SendBeam**. Create your account or sign in in the window that opens, tick what this site may do, and the key arrives on its own — there is nothing to copy. If you already have an API key, "I already have an API key" on the same screen still takes one. +3. Pick your signup form (and, if you like, a contact form and a pop-up form) from the dropdown of your own forms. +4. Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. == Frequently Asked Questions == @@ -125,6 +128,9 @@ Yes. The form is an iframe and the pop-up is a script tag, both cache-safe. == Changelog == += 1.8.3 = +* **Connect SendBeam.** One button on the Overview tab replaces making an account, finding the API keys screen, working out which permissions to give and pasting the key back. You tick what this site may do, create your account or sign in on sendbeam.io in a pop-up, and the site is handed a key with exactly those permissions. Pasting a key by hand still works, under "I already have an API key". + = 1.8.2 = * Pop-ups come in four styles — split with image, editorial, bold colour and slide-in — with an image, an eyebrow, a button label and an optional subscriber count, set per pop-up. diff --git a/sendbeam.php b/sendbeam.php index 8c841a6..ae52163 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -3,7 +3,7 @@ * Plugin Name: SendBeam * Plugin URI: https://sendbeam.io/docs/wordpress * Description: Newsletter signup forms, pop-ups, opt-ins at registration and checkout, and your site's own email, from your SendBeam account. - * Version: 1.8.2 + * Version: 1.8.3 * Requires at least: 6.1 * Requires PHP: 7.4 * Author: SendBeam @@ -17,7 +17,7 @@ defined( 'ABSPATH' ) || exit; -define( 'SENDBEAM_VERSION', '1.8.2' ); +define( 'SENDBEAM_VERSION', '1.8.3' ); define( 'SENDBEAM_FILE', __FILE__ ); define( 'SENDBEAM_DIR', plugin_dir_path( __FILE__ ) ); @@ -33,3 +33,4 @@ require SENDBEAM_DIR . 'includes/render.php'; require SENDBEAM_DIR . 'includes/mail.php'; require SENDBEAM_DIR . 'includes/onboarding.php'; +require SENDBEAM_DIR . 'includes/connect.php'; diff --git a/tests/smoke.php b/tests/smoke.php index c95f2a8..e811999 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -606,6 +606,300 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), sendbeam_ecommerce_clear_scheduled(); ok( 1 === count( $stub['cron'] ) && 'something_else' === $stub['cron'][0]['hook'], 'deactivation: only this plugin\'s own scheduled checks are cleared' ); +// ── Connect ──────────────────────────────────────────────────────────── +// +// The plugin is the client: it mints the state, sends the person to +// sendbeam.io, and swaps a single-use grant for a key server-to-server. The +// SendBeam end is stubbed here — what is being proved is that this end builds +// exactly the URL the contract specifies, refuses anything whose state does +// not come back unchanged, and never writes a key by any path other than the +// one a pasted key goes through. + +/** + * Drive a Connect handler to the end WordPress would exit at, and return + * whatever it rendered. + * + * @param callable $fn The handler. + * @return string + */ +function sb_connect_run( $fn ) { + $GLOBALS['stub']['throw_on']['sendbeam_connect_result'] = true; + ob_start(); + try { + $fn(); + } catch ( SendBeamStubExit $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- WordPress would have exited here. + $GLOBALS['stub']['exit'] = $e->getMessage(); + } + $html = ob_get_clean(); + unset( $GLOBALS['stub']['throw_on']['sendbeam_connect_result'] ); + return $html; +} + +/** Put the world back to a signed-in administrator on an https site. */ +function sb_connect_reset() { + $GLOBALS['stub']['caps']['manage_options'] = true; + $GLOBALS['stub']['user_id'] = 7; + $GLOBALS['stub']['current_user'] = array( 'email' => 'admin@example-site.test' ); + $GLOBALS['stub']['site_url'] = 'https://www.example-site.test'; + $GLOBALS['stub']['bloginfo'] = array(); + $GLOBALS['stub']['remote'] = array(); + $GLOBALS['stub']['remote_reply'] = null; + $GLOBALS['stub']['redirect'] = null; + $GLOBALS['stub']['exit'] = ''; + $_GET = array(); + $_POST = array(); + $_REQUEST = array(); + delete_transient( 'sendbeam_connect_7' ); + delete_transient( 'sendbeam_connect_9' ); +} + +// Only the scopes we offer survive, and `forms` is not optional. +ok( sendbeam_connect_clean_scopes( array( 'transactional:send', 'sudo' ) ) === array( 'forms', 'transactional:send' ), 'connect: unknown scopes are dropped and forms is always asked for' ); +ok( sendbeam_connect_clean_scopes( null ) === array( 'forms' ), 'connect: ticking nothing still asks for forms' ); +ok( array_keys( sendbeam_connect_scopes() ) === array( 'forms', 'contacts:write', 'transactional:send', 'ecommerce' ), 'connect: the four scopes, in the order the consent page shows them' ); + +// https everywhere, with a hole only for machines that cannot be reached +// from the internet. An http origin on a real domain must be refused, or the +// grant travels in clear. +ok( sendbeam_connect_origin_ok( 'https://example.com' ), 'connect: https is allowed' ); +ok( sendbeam_connect_origin_ok( 'http://localhost:8080' ), 'connect: http on localhost is allowed for dev boxes' ); +ok( sendbeam_connect_origin_ok( 'http://127.0.0.1' ), 'connect: http on 127.0.0.1 is allowed' ); +ok( sendbeam_connect_origin_ok( 'http://wp.test' ), 'connect: http on a .test host is allowed' ); +ok( sendbeam_connect_origin_ok( 'http://site.local' ), 'connect: http on a .local host is allowed' ); +ok( ! sendbeam_connect_origin_ok( 'http://example.com' ), 'connect: plain http on a real domain is refused' ); +ok( ! sendbeam_connect_origin_ok( 'ftp://example.com' ), 'connect: a non-http scheme is refused' ); +ok( ! sendbeam_connect_origin_ok( 'nonsense' ), 'connect: a value that is not a URL is refused' ); + +// Starting: the exact URL from the contract, every parameter. +sb_connect_reset(); +$GLOBALS['stub']['bloginfo']['name'] = str_repeat( 'Ä', 100 ); // over the 80 the contract allows. +$_POST = array( + 'sendbeam_scopes' => array( 'transactional:send', 'not-a-scope' ), + '_wpnonce' => 'nonce:sendbeam_connect_start', +); +$_REQUEST = $_POST; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +ok( 'wp_redirect' === $GLOBALS['stub']['exit'], 'connect: start redirects the pop-up' ); +$sendbeam_start = (string) $GLOBALS['stub']['redirect']['url']; +ok( 302 === $GLOBALS['stub']['redirect']['status'], 'connect: start redirects with a 302' ); +ok( 0 === strpos( $sendbeam_start, 'https://sendbeam.io/connect/wordpress?' ), "connect: start goes to the contract's page — got $sendbeam_start" ); +parse_str( (string) wp_parse_url( $sendbeam_start, PHP_URL_QUERY ), $sendbeam_q ); +ok( 'https://www.example-site.test' === ( $sendbeam_q['site_url'] ?? '' ), 'connect: site_url is the origin, with no path' ); +ok( mb_strlen( $sendbeam_q['site_name'] ?? '' ) === 80, 'connect: site_name is clipped to 80 characters' ); +ok( 'admin@example-site.test' === ( $sendbeam_q['email'] ?? '' ), "connect: the admin's address is sent to prefill signup" ); +ok( 'forms,transactional:send' === ( $sendbeam_q['scopes'] ?? '' ), 'connect: scopes is the approved csv, forms first' ); +ok( 'https://www.example-site.test/wp-admin/admin-post.php?action=sendbeam_connect_return' === ( $sendbeam_q['return_to'] ?? '' ), 'connect: return_to is this site, on the site_url origin' ); +ok( 1 === preg_match( '/^[A-Za-z0-9_\-]{32,}$/', $sendbeam_q['state'] ?? '' ), 'connect: state is 32+ characters of [A-Za-z0-9_-]' ); +ok( 43 === strlen( $sendbeam_q['state'] ), 'connect: state is 43 characters' ); + +$sendbeam_state = $sendbeam_q['state']; +$sendbeam_stored = get_transient( 'sendbeam_connect_7' ); +ok( is_array( $sendbeam_stored ) && $sendbeam_stored['state'] === $sendbeam_state, 'connect: the state is remembered against the admin who started it' ); +ok( $sendbeam_stored['scopes'] === array( 'forms', 'transactional:send' ), 'connect: the approved scopes are remembered too' ); + +// Two admins connecting at once must not share a state. +$GLOBALS['stub']['user_id'] = 9; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +ok( get_transient( 'sendbeam_connect_9' )['state'] !== $sendbeam_state, 'connect: a second administrator gets their own state, not the first one\'s' ); +delete_transient( 'sendbeam_connect_9' ); + +// A site with no https address cannot be connected at all. +sb_connect_reset(); +$GLOBALS['stub']['site_url'] = 'http://insecure.example.com'; +$_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start' ); +$_REQUEST = $_POST; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'connect: an http-only site is refused rather than sent off insecurely' ); +ok( null === $GLOBALS['stub']['redirect'], 'connect: nothing is sent to SendBeam from an http-only site' ); +ok( false === get_transient( 'sendbeam_connect_7' ), 'connect: an http-only site is not left holding a connection it can never finish' ); + +// Without the nonce, nothing starts. +sb_connect_reset(); +$_POST = array(); +$_REQUEST = array(); +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'connect: start refuses a request with no nonce' ); +ok( false === get_transient( 'sendbeam_connect_7' ), 'connect: a refused start stores no state' ); + +// ── Coming back ──────────────────────────────────────────────────────── +$sendbeam_good_state = str_repeat( 'a', 43 ); +$sendbeam_good_grant = str_repeat( 'g', 43 ); +$sendbeam_new_key = 'sb_live_' . str_repeat( 'k', 32 ); + +/** Arm a pending connection for user 7. */ +function sb_connect_pending( $state ) { + set_transient( 'sendbeam_connect_7', array( 'state' => $state, 'scopes' => array( 'forms' ) ), 900 ); +} + +// A state that is not the one we minted: no request, nothing changed. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_existingexistingexisting' ) ); +sb_connect_pending( $sendbeam_good_state ); +$_GET = array( 'state' => str_repeat( 'b', 43 ), 'grant' => $sendbeam_good_grant ); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $sendbeam_html, 'Not connected', 'connect: a mismatched state is not connected' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'connect: a mismatched state makes no request to SendBeam' ); +ok( false === get_transient( 'sendbeam_connect_7' ), 'connect: the state is spent even when it did not match' ); +ok( 'sb_live_existingexistingexisting' === sendbeam_settings()['api_key'], 'connect: a mismatched state leaves the saved key alone' ); +lacks( $sendbeam_html, 'postMessage', 'connect: a failure does not tell the opener it succeeded' ); + +// No state at all — a bare visit to the return URL. +sb_connect_reset(); +sb_connect_pending( $sendbeam_good_state ); +$_GET = array(); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $sendbeam_html, 'Not connected', 'connect: a bare visit to the return URL is not connected' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'connect: a bare visit makes no request' ); + +// Refused on the consent page. +sb_connect_reset(); +sb_connect_pending( $sendbeam_good_state ); +$_GET = array( 'state' => $sendbeam_good_state, 'error' => 'denied' ); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $sendbeam_html, 'Not connected', 'connect: refusing on the consent page is not connected' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'connect: refusing makes no request to exchange anything' ); +ok( false === get_transient( 'sendbeam_connect_7' ), 'connect: the state is spent after a refusal' ); +ok( 'sb_live_existingexistingexisting' === sendbeam_settings()['api_key'], 'connect: refusing leaves the saved key alone' ); + +// The happy path: the grant is exchanged, server to server, exactly once. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_existingexistingexisting', 'default_form' => $form ) ); +sb_connect_pending( $sendbeam_good_state ); +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 200 ), + 'body' => json_encode( + array( + 'api_key' => $sendbeam_new_key, + 'key_prefix' => 'sb_live_kkkk', + 'workspace' => array( 'id' => 'ws_1', 'name' => 'Example Site' ), + 'scopes' => array( 'forms' ), + ) + ), +); +$_GET = array( 'state' => $sendbeam_good_state, 'grant' => $sendbeam_good_grant ); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); + +ok( 1 === count( $GLOBALS['stub']['remote'] ), 'connect: exactly one call is made to exchange the grant' ); +$sendbeam_req = $GLOBALS['stub']['remote'][0]; +ok( 'POST' === $sendbeam_req['method'], 'connect: the exchange is a POST' ); +ok( 'https://sendbeam.io/api/v1/connect/exchange' === $sendbeam_req['url'], 'connect: the exchange goes to the contract URL' ); +ok( 'application/json' === $sendbeam_req['args']['headers']['Content-Type'], 'connect: the exchange sends JSON' ); +ok( ! isset( $sendbeam_req['args']['headers']['x-api-key'] ), 'connect: the exchange carries no API key — the grant is the credential' ); +ok( ! isset( $sendbeam_req['args']['sslverify'] ), 'connect: certificate verification is left at the WordPress default' ); +ok( 15 === $sendbeam_req['args']['timeout'], 'connect: the exchange has a bounded timeout' ); +$sendbeam_body = json_decode( $sendbeam_req['args']['body'], true ); +ok( + $sendbeam_body === array( 'grant' => $sendbeam_good_grant, 'state' => $sendbeam_good_state, 'site_url' => 'https://www.example-site.test' ), + 'connect: the exchange body is exactly grant, state and site_url — got ' . $sendbeam_req['args']['body'] +); + +ok( $sendbeam_new_key === sendbeam_settings()['api_key'], 'connect: the key SendBeam minted is saved' ); +ok( 'connect' === sendbeam_settings()['sendbeam_connected_via'], 'connect: the connection is marked as made through Connect' ); +ok( 'Example Site' === sendbeam_settings()['sendbeam_connect_workspace'], 'connect: the workspace name is remembered for the screen' ); +ok( $form === sendbeam_settings()['default_form'], 'connect: storing the key leaves the other tabs\' settings alone' ); +ok( sendbeam_connected_via_connect(), 'connect: the screen can tell this was the button' ); +ok( false === get_transient( 'sendbeam_connect_7' ), 'connect: the state is spent after a success' ); +ok( false === get_transient( SENDBEAM_CACHE_CONN ), 'connect: the cached connection state is dropped, so the screen re-checks' ); + +has( $sendbeam_html, 'Connected', 'connect: the pop-up says it worked' ); +has( $sendbeam_html, 'postMessage', 'connect: the pop-up tells the opener to reload' ); +has( $sendbeam_html, '"https:\/\/www.example-site.test"', 'connect: the message is addressed to this site\'s origin, not "*"' ); +has( $sendbeam_html, 'window.close()', 'connect: the pop-up closes itself' ); +lacks( $sendbeam_html, $sendbeam_new_key, 'connect: the key is never rendered into the pop-up' ); + +// A replay of the same return URL: the grant is gone, so nothing happens. +$GLOBALS['stub']['remote'] = array(); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $sendbeam_html, 'Not connected', 'connect: replaying the return URL is not connected' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'connect: a replayed return URL makes no request' ); + +// Pasting a key by hand afterwards must stop the screen claiming it was the button. +$sendbeam_pasted = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => 'sb_live_pastedpastedpastedpasted' ) ); +ok( '' === $sendbeam_pasted['sendbeam_connected_via'], 'connect: a key pasted by hand clears the Connect marker' ); +ok( '' === $sendbeam_pasted['sendbeam_connect_workspace'], 'connect: a key pasted by hand clears the workspace name' ); +$sendbeam_removed = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key_remove' => '1' ) ); +ok( '' === $sendbeam_removed['api_key'] && '' === $sendbeam_removed['sendbeam_connected_via'], 'connect: Disconnect forgets the key and the marker together' ); + +// SendBeam says the grant is spent or expired. +foreach ( array( + 410 => array( '{"error":"grant_expired_or_used"}', 'already been used' ), + 400 => array( '{"error":"invalid"}', 'refused' ), + 429 => array( '{"error":"rate_limited"}', 'rate-limiting' ), + 500 => array( 'not json at all', 'refused' ), +) as $sendbeam_code => $sendbeam_case ) { + sb_connect_reset(); + update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_existingexistingexisting' ) ); + sb_connect_pending( $sendbeam_good_state ); + $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => $sendbeam_code ), 'body' => $sendbeam_case[0] ); + $_GET = array( 'state' => $sendbeam_good_state, 'grant' => $sendbeam_good_grant ); + $sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); + + has( $sendbeam_html, 'Not connected', "connect: HTTP $sendbeam_code is not connected" ); + has( $sendbeam_html, $sendbeam_case[1], "connect: HTTP $sendbeam_code says why in plain words" ); + ok( 'sb_live_existingexistingexisting' === sendbeam_settings()['api_key'], "connect: HTTP $sendbeam_code leaves the saved key untouched" ); + ok( '' === sendbeam_settings()['sendbeam_connected_via'], "connect: HTTP $sendbeam_code does not mark the site as connected" ); + ok( false === get_transient( 'sendbeam_connect_7' ), "connect: HTTP $sendbeam_code spends the state" ); + lacks( $sendbeam_html, 'postMessage', "connect: HTTP $sendbeam_code does not tell the opener it succeeded" ); +} + +// The server could not be reached at all. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_existingexistingexisting' ) ); +sb_connect_pending( $sendbeam_good_state ); +$GLOBALS['stub']['remote_reply'] = new WP_Error( 'http_request_failed', 'cURL error 28' ); +$_GET = array( 'state' => $sendbeam_good_state, 'grant' => $sendbeam_good_grant ); +$sendbeam_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $sendbeam_html, 'could not reach sendbeam.io', 'connect: an unreachable server is reported plainly' ); +ok( 'sb_live_existingexistingexisting' === sendbeam_settings()['api_key'], 'connect: an unreachable server leaves the saved key untouched' ); + +// Something that is not a key must never be written to the option. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_existingexistingexisting' ) ); +sb_connect_pending( $sendbeam_good_state ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{"api_key":"nope nope ', - wp_json_encode( $origin, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) - ); - } else { - echo ''; + /* + * Nothing is closed when this is not the pop-up. A blocked pop-up turns + * the whole flow into an ordinary navigation, and window.close() on a + * window script did not open does nothing in every current browser — so + * the person would be left on a dead-end page with no way back but the + * link. It is the link they get. + */ + if ( $is_popup ) { + // Only a success is announced; the opener reloads on it and would + // otherwise throw away an unsaved settings form for nothing. + if ( $connected && '' !== $origin ) { + printf( + '', + wp_json_encode( $origin, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) + ); + } else { + echo ''; + } } echo ''; @@ -522,6 +709,15 @@ function sendbeam_connect_panel() { printf( '', esc_url( admin_url( 'admin-post.php' ) ) ); wp_nonce_field( 'sendbeam_connect_start' ); echo ''; + + /* + * Flipped to 1 by the submit handler when window.open() actually returned + * a window. Left at 0 when the pop-up was blocked, when the browser has + * no script at all, or when someone submitted this form some other way — + * all three of which mean the flow is happening in this very tab, and the + * page it lands on must offer a way back instead of trying to close. + */ + echo ''; echo '

' . esc_html__( 'This site will ask SendBeam for permission to:', 'sendbeam' ) . '

'; echo '
    '; foreach ( sendbeam_connect_scopes() as $scope => $meta ) { @@ -563,8 +759,15 @@ function sendbeam_connect_admin_js() { var form = document.getElementById( "sb-connect-form" ); if ( form ) { form.addEventListener( "submit", function () { - var win = window.open( "", "sendbeam-connect", "width=600,height=760" ); - if ( win ) { form.target = "sendbeam-connect"; } + var flag = document.getElementById( "sb-connect-popup" ); + var win = window.open( "", "sendbeam-connect", "width=600,height=760" ); + if ( win ) { + form.target = "sendbeam-connect"; + if ( flag ) { flag.value = "1"; } + } else { + form.removeAttribute( "target" ); + if ( flag ) { flag.value = "0"; } + } } ); } window.addEventListener( "message", function ( e ) { diff --git a/includes/helpers.php b/includes/helpers.php index 929cb4f..90d6283 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -53,6 +53,17 @@ function sendbeam_default_settings() { // Cleared the moment the key is changed or removed by hand. 'sendbeam_connected_via' => '', 'sendbeam_connect_workspace' => '', + // The permissions SendBeam actually granted this key, as a csv. What + // was *asked* for is not the same thing — the person can untick a box + // on the consent page — and the Overview has to say "you did not give + // this site that permission" rather than guess. + 'sendbeam_connect_granted' => '', + // Site email was approved at consent time but held back because the + // sending domain was not verified yet. The domain check switches it + // on and clears this; turning site email off by hand clears it too, + // so a later check never re-enables something deliberately switched + // off. + 'sendbeam_mail_deferred' => 0, ); } diff --git a/includes/onboarding.php b/includes/onboarding.php index f580501..6444e22 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -42,41 +42,154 @@ function sendbeam_is_connected() { return in_array( $connection['state'], array( 'ok', 'no_scope' ), true ); } +/** + * Is a SendBeam form actually on the site? + * + * "A form is chosen in the settings" and "a visitor can see a form" are not + * the same claim, and the checklist was making the first one while sounding + * like the second. This looks for the block or either shortcode in published + * content — one indexed-free LIKE, answered once and then cached for half a + * day, because it drives one tick on one settings screen and is not worth a + * query per page load. + * + * A live pop-up counts: it is a form on the site by any reading. + * + * @param bool $force Skip the cache. + * @return bool + */ +function sendbeam_form_is_placed( $force = false ) { + if ( sendbeam_popups() ) { + return true; + } + + if ( ! $force ) { + $cached = get_transient( 'sendbeam_form_placed' ); + if ( '1' === $cached || '0' === $cached ) { + return '1' === $cached; + } + } + + global $wpdb; + if ( ! isset( $wpdb ) || ! is_object( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) ) { + // No database to ask (the smoke tests, WP-CLI oddities): fall back to + // what the settings say rather than claiming the step is unfinished. + $settings = sendbeam_settings(); + return '' !== $settings['default_form'] || '' !== $settings['contact_form']; + } + + $block = '%' . $wpdb->esc_like( 'wp:sendbeam/form' ) . '%'; + $shortcode = '%' . $wpdb->esc_like( '[sendbeam_form' ) . '%'; + $contact = '%' . $wpdb->esc_like( '[sendbeam_contact' ) . '%'; + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- cached in a transient immediately below; there is no WP API for "is this block used anywhere". + $found = $wpdb->get_var( + $wpdb->prepare( + "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND ( post_content LIKE %s OR post_content LIKE %s OR post_content LIKE %s ) LIMIT 1", + $block, + $shortcode, + $contact + ) + ); + + set_transient( 'sendbeam_form_placed', $found ? '1' : '0', 12 * HOUR_IN_SECONDS ); + return (bool) $found; +} + /** * How far through setup are they? Drives the checklist on the settings page. * - * @return array + * Four steps now, not three, and the new one is second on purpose. Verifying + * the sending domain is the step every other step quietly depends on — a form + * that cannot send a confirmation email is a form that collects nothing, and + * site email through an unverified domain is worse than no site email at all + * — and it is the step a site owner cannot even start without the DNS records + * Connect has just fetched. Burying it under "optional" was the gap the owner + * found on the test site. + * + * Each step carries a `key`, and the Overview renders a panel per key. The + * old version relied on position, which meant inserting a step in the middle + * silently pointed every link after it at the wrong tab. + * + * @return array */ function sendbeam_setup_steps() { $settings = sendbeam_settings(); $connection = sendbeam_connection(); $connected = in_array( $connection['state'], array( 'ok', 'no_scope' ), true ); + $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); $using_form = '' !== $settings['default_form'] || '' !== $settings['contact_form']; $using_popup = (bool) sendbeam_popups(); $using_mail = ! empty( $settings['mail_enabled'] ); + $domain = $status['domain']; + $verified = ! empty( $domain['verified'] ); + + if ( ! $connected ) { + $domain_detail = __( 'Connect the site first and SendBeam will set the domain up and show you the records.', 'sendbeam' ); + } elseif ( ! sendbeam_connect_granted( 'domain' ) ) { + $domain_detail = __( 'This site\'s key was not given permission to read your sending domain. Add the domain under Sending in SendBeam, or reconnect and tick the domain box.', 'sendbeam' ); + } elseif ( $verified ) { + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + $domain_detail = sprintf( __( '%s is verified. Email from this site will be sent from your own domain.', 'sendbeam' ), $domain['name'] ); + } elseif ( '' !== $domain['name'] ) { + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + $domain_detail = sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $domain['name'] ); + } else { + $domain_detail = __( 'No sending domain yet. Add one under Sending in SendBeam.', 'sendbeam' ); + } + + $placed = ( $using_form || $using_popup ) ? sendbeam_form_is_placed() : false; + + if ( $placed ) { + $form_detail = __( 'A SendBeam form is on the site.', 'sendbeam' ); + } elseif ( $using_form || $using_popup ) { + $form_name = '' !== $status['default_form']['name'] ? $status['default_form']['name'] : __( 'Your form', 'sendbeam' ); + /* translators: %s: the form name, e.g. Newsletter signup */ + $form_detail = sprintf( __( '%s is ready — add the SendBeam Form block to a page. In the editor press the + button and search for "SendBeam", or type /sendbeam on a new line. The shortcode [sendbeam_form] does the same anywhere shortcodes work.', 'sendbeam' ), $form_name ); + } else { + $form_detail = __( 'Choose a signup, contact or pop-up form below.', 'sendbeam' ); + } + + if ( $using_mail ) { + $mail_detail = __( 'On. Send yourself a test to be sure.', 'sendbeam' ); + } elseif ( $connected && ! sendbeam_connect_granted( 'transactional:send' ) ) { + $mail_detail = __( 'This site\'s key was not given permission to send your site\'s email. Reconnect and tick that box to use it.', 'sendbeam' ); + } elseif ( ! $verified ) { + $mail_detail = __( 'Waiting on step 2: this site\'s email can only go out once the sending domain is verified.', 'sendbeam' ); + } else { + $mail_detail = __( 'Ready. Switch it on and password resets, receipts and notifications go out through your own domain.', 'sendbeam' ); + } + return array( array( + 'key' => 'connect', 'done' => $connected, 'label' => __( 'Connect your SendBeam account', 'sendbeam' ), 'detail' => $connected ? __( 'Your key works.', 'sendbeam' ) : __( 'Press Connect SendBeam, approve what this site may do, and the key arrives on its own.', 'sendbeam' ), + 'target' => sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', + ), + array( + 'key' => 'domain', + 'done' => $verified, + 'label' => __( 'Verify your sending domain', 'sendbeam' ), + 'detail' => $domain_detail, + 'target' => sendbeam_app_url() . '/settings/sending', ), array( - 'done' => $using_form || $using_popup, + 'key' => 'form', + 'done' => $placed, 'label' => __( 'Put a form on the site', 'sendbeam' ), - 'detail' => ( $using_form || $using_popup ) - ? __( 'A form is chosen. Add the SendBeam block to any page, or use the pop-up.', 'sendbeam' ) - : __( 'Choose a signup, contact or pop-up form below.', 'sendbeam' ), + 'detail' => $form_detail, + 'target' => sendbeam_tab_url( 'forms' ), ), array( + 'key' => 'mail', 'done' => $using_mail, 'label' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), - 'detail' => $using_mail - ? __( 'On. Send yourself a test to be sure.', 'sendbeam' ) - : __( 'Optional. Routes password resets, receipts and notifications through your verified domain.', 'sendbeam' ), + 'detail' => $mail_detail, + 'target' => sendbeam_tab_url( 'mail' ), ), ); } diff --git a/includes/screens.php b/includes/screens.php index dc11b86..840ef70 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -42,36 +42,34 @@ function sendbeam_screen_overview() { // is one subscriber, and adding the lists up counted them three times. $subscribers = sendbeam_subscriber_count(); $connected = sendbeam_is_connected(); + $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + + sendbeam_overview_notices(); echo '
    '; sendbeam_card_open( __( 'Setup', 'sendbeam' ) ); - $steps = sendbeam_setup_steps(); - $targets = array( sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', sendbeam_tab_url( 'forms' ), sendbeam_tab_url( 'mail' ) ); echo '
      '; - foreach ( $steps as $i => $step ) { - // Step one is not a link to a field any more when there is nothing - // connected: it is the thing itself, done here, in one button. - $is_connect_step = ( 0 === $i && ! $connected ); - + foreach ( sendbeam_setup_steps() as $i => $step ) { printf( - '
    1. ', + '
    2. ', $step['done'] ? 'is-done' : '', $step['done'] ? '✓' : (int) ( $i + 1 ) ); - if ( $is_connect_step ) { - printf( '%s', esc_html( $step['label'] ) ); - sendbeam_connect_panel(); - sendbeam_connect_paste_disclosure(); + + // The connect step is not a link to a field any more when there is + // nothing connected: it is the thing itself, done here, in one button. + $linked = ! ( 'connect' === $step['key'] && ! $connected ); + if ( $linked ) { + printf( '%2$s', esc_url( $step['target'] ), esc_html( $step['label'] ) ); } else { - printf( - '%2$s%3$s', - esc_url( $targets[ $i ] ), - esc_html( $step['label'] ), - esc_html( $step['detail'] ) - ); + printf( '%s', esc_html( $step['label'] ) ); } - echo '
    3. '; + printf( '%s', esc_html( $step['detail'] ) ); + + sendbeam_overview_step_panel( $step, $status, $connected ); + + echo '
    '; } echo ''; sendbeam_card_close(); @@ -87,21 +85,282 @@ function sendbeam_screen_overview() { echo '
'; - // When nothing is connected the key field lives in the disclosure above, - // under the Connect button — one paste field on the screen, never two. - if ( $connected ) { - sendbeam_card_open( __( 'Connect', 'sendbeam' ) ); - if ( sendbeam_connected_via_connect() ) { - sendbeam_connect_connected_panel(); - } else { - sendbeam_form_open( 'connect' ); - do_settings_sections( 'sendbeam_connect_page' ); - sendbeam_form_close(); - } + // A pasted key still gets its own card: there is a field to edit. A key + // that arrived through Connect has nothing to edit, and its Disconnect + // button lives in step 1 where someone looking at the connection will + // actually find it — the old card was below the fold and titled + // "Connect", which read as an invitation to connect something. + if ( $connected && ! sendbeam_connected_via_connect() ) { + sendbeam_card_open( __( 'API key', 'sendbeam' ) ); + sendbeam_form_open( 'connect' ); + do_settings_sections( 'sendbeam_connect_page' ); + sendbeam_form_close(); sendbeam_card_close(); } } +/** + * Whatever the last button did, said in one line at the top of the screen. + * + * Every one of these arrives as a query argument on a redirect this plugin + * issued itself, so the only thing read out of the URL is which of a fixed + * list of sentences to print. + */ +function sendbeam_overview_notices() { + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- notice text only, chosen from a fixed list, set by our own redirect. + $domain = isset( $_GET['sendbeam_domain'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_domain'] ) ) : ''; + $mail = isset( $_GET['sendbeam_mail'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_mail'] ) ) : ''; + $gone = isset( $_GET['sendbeam_disconnected'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_disconnected'] ) ) : ''; + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + $messages = array( + 'domain' => array( + 'verified' => array( 'ok', __( 'Verified. SendBeam can now send email as your domain.', 'sendbeam' ) ), + 'verified_mail' => array( 'ok', __( 'Verified, and this site\'s email has been switched on — it was waiting on exactly this. Send yourself a test below.', 'sendbeam' ) ), + 'pending' => array( 'warn', __( 'Not verified yet. DNS changes can take anything from a few minutes to a day to spread; the records are below, unchanged.', 'sendbeam' ) ), + 'nodomain' => array( 'warn', __( 'There is no sending domain on this workspace yet. Add one under Sending in SendBeam.', 'sendbeam' ) ), + 'unreachable' => array( 'bad', __( 'Could not ask SendBeam to check just now. Nothing was changed.', 'sendbeam' ) ), + ), + 'mail' => array( + 'on' => array( 'ok', __( 'Site email is on. Password resets, receipts and notifications now go out through SendBeam.', 'sendbeam' ) ), + 'noscope' => array( 'bad', __( 'This site\'s key was not given permission to send your site\'s email, so it was not switched on. Reconnect and tick that box.', 'sendbeam' ) ), + 'unverified' => array( 'bad', __( 'The sending domain is not verified, so site email was not switched on. Finish step 2 first.', 'sendbeam' ) ), + ), + 'gone' => array( + 'ok' => array( 'ok', __( 'Disconnected. The key was revoked in SendBeam.', 'sendbeam' ) ), + 'unreachable' => array( 'warn', __( 'Disconnected, but this server could not reach SendBeam; revoke it under Settings → API keys.', 'sendbeam' ) ), + ), + ); + + foreach ( array( + 'domain' => $domain, + 'mail' => $mail, + 'gone' => $gone, + ) as $group => $value ) { + if ( '' === $value || ! isset( $messages[ $group ][ $value ] ) ) { + continue; + } + list( $tone, $text ) = $messages[ $group ][ $value ]; + echo '

' . esc_html( $text ) . '

'; + } +} + +/** + * The working part of a checklist step, under its sentence. + * + * Four steps, four panels, and nothing shared between them but the wrapper — + * a step whose panel is a button and a step whose panel is a table of DNS + * records have nothing in common except that they both sit in an
  • . + * + * @param array $step One entry from sendbeam_setup_steps(). + * @param array $status Normalised Connect status. + * @param bool $connected Whether the key works. + */ +function sendbeam_overview_step_panel( $step, $status, $connected ) { + switch ( $step['key'] ) { + case 'connect': + if ( ! $connected ) { + sendbeam_connect_panel(); + sendbeam_connect_paste_disclosure(); + } elseif ( sendbeam_connected_via_connect() ) { + sendbeam_connect_connected_panel( $status ); + } + break; + case 'domain': + sendbeam_overview_domain_panel( $status, $connected ); + break; + case 'form': + sendbeam_overview_form_panel( $step, $connected ); + break; + case 'mail': + sendbeam_overview_mail_panel( $status, $connected ); + break; + } +} + +/** + * Step 2: the sending domain, its records, and the two ways to finish it. + * + * The records are the whole point of this step existing. A site owner is + * being asked to go and edit DNS — the least forgiving thing in this entire + * product — so every value is one click to the clipboard rather than + * something to retype, and **Check now** is right there so they can find out + * whether it worked without leaving wp-admin. + * + * @param array $status Normalised Connect status. + * @param bool $connected Whether the key works. + */ +function sendbeam_overview_domain_panel( $status, $connected ) { + if ( ! $connected || '' === $status['domain']['name'] ) { + return; + } + + $domain = $status['domain']; + $verified = ! empty( $domain['verified'] ); + + echo '
    '; + + if ( $verified ) { + echo '

    '; + printf( + /* translators: %s: the sending domain */ + esc_html__( 'Verified — %s', 'sendbeam' ), + esc_html( $domain['name'] ) + ); + echo '

    '; + } + + if ( $domain['records'] ) { + if ( $verified ) { + echo '
    ' . esc_html__( 'The records SendBeam is using', 'sendbeam' ) . '
    '; + } + sendbeam_domain_records_table( $domain['records'] ); + if ( $verified ) { + echo '
    '; + } + } elseif ( ! $verified ) { + echo '

    ' . esc_html__( 'SendBeam has not sent the DNS records for this domain. Open Sending in SendBeam to see them.', 'sendbeam' ) . '

    '; + } + + echo '
    '; + echo ''; + wp_nonce_field( 'sendbeam_domain_check' ); + echo ''; + printf( + '', + esc_html( $verified ? __( 'Check again', 'sendbeam' ) : __( 'Check now', 'sendbeam' ) ) + ); + echo ''; + + if ( ! $verified && '' !== $domain['domain_connect_url'] ) { + printf( + '%s', + esc_url( $domain['domain_connect_url'] ), + esc_html__( 'Set up DNS automatically', 'sendbeam' ) + ); + } + echo '
    '; + + if ( ! $verified && '' !== $domain['domain_connect_url'] ) { + echo '

    ' . esc_html__( 'Your registrar supports one-click set-up: that button signs you in there and adds the records for you. It opens in a new tab.', 'sendbeam' ) . '

    '; + } + + if ( '' !== $domain['checked_at'] ) { + echo '

    ' . esc_html( + sprintf( + /* translators: %s: an ISO timestamp of the last DNS check */ + __( 'Last checked %s.', 'sendbeam' ), + $domain['checked_at'] + ) + ) . '

    '; + } + + echo '
    '; +} + +/** + * The DNS records, one row each, every value one click from the clipboard. + * + * @param array $records Records. + */ +function sendbeam_domain_records_table( $records ) { + echo '
    '; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + foreach ( $records as $record ) { + echo ''; + echo ''; + echo ''; + echo ''; + printf( + '', + esc_attr( $record['value'] ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_attr( + sprintf( + /* translators: %s: a DNS record type, e.g. TXT */ + __( 'Copy the %s record value', 'sendbeam' ), + $record['type'] + ) + ), + esc_html__( 'Copy', 'sendbeam' ) + ); + echo ''; + } + echo '
    ' . esc_html__( 'Type', 'sendbeam' ) . '' . esc_html__( 'Name', 'sendbeam' ) . '' . esc_html__( 'Value', 'sendbeam' ) . '' . esc_html__( 'Copy', 'sendbeam' ) . '
    ' . esc_html( $record['type'] ) . '' . esc_html( '' !== $record['name'] ? $record['name'] : '@' ) . '' . esc_html( $record['value'] ) . '
    '; +} + +/** + * Step 3: the shortcode, for people who are not using the block editor. + * + * @param array $step The step. + * @param bool $connected Whether the key works. + */ +function sendbeam_overview_form_panel( $step, $connected ) { + if ( ! $connected || $step['done'] ) { + return; + } + $settings = sendbeam_settings(); + if ( '' === (string) $settings['default_form'] && '' === (string) $settings['contact_form'] ) { + return; + } + + echo '
    [sendbeam_form]'; + printf( + '', + esc_attr( '[sendbeam_form]' ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy', 'sendbeam' ) + ); + echo '
    '; +} + +/** + * Step 4: one button when everything is in place, and why not when it is not. + * + * @param array $status Normalised Connect status. + * @param bool $connected Whether the key works. + */ +function sendbeam_overview_mail_panel( $status, $connected ) { + if ( ! $connected ) { + return; + } + $settings = sendbeam_settings(); + + if ( ! empty( $settings['mail_enabled'] ) ) { + echo '
    '; + echo '
    '; + wp_nonce_field( 'sendbeam_test_mail' ); + echo ''; + printf( '', esc_html__( 'Send a test email', 'sendbeam' ) ); + echo '
    '; + echo '
    '; + return; + } + + if ( ! sendbeam_connect_granted( 'transactional:send' ) || empty( $status['domain']['verified'] ) ) { + return; // The step's own sentence already says which one is missing. + } + + echo '
    '; + echo '
    '; + wp_nonce_field( 'sendbeam_mail_switch_on' ); + echo ''; + printf( '', esc_html__( 'Switch on', 'sendbeam' ) ); + echo '
    '; + echo '
    '; + echo '

    ' . esc_html( + sprintf( + /* translators: %s: the From address site email will use */ + __( 'Email will be sent as %s. You can change that on the Site email tab.', 'sendbeam' ), + '' !== $status['sender']['from_email'] ? $status['sender']['from_email'] : __( 'your workspace sender', 'sendbeam' ) + ) + ) . '

    '; +} + /** * The paste field, tucked away for the people who already have a key. * @@ -119,32 +378,71 @@ function sendbeam_connect_paste_disclosure() { } /** - * What the Connect card says once the button has done its work. + * What step 1 says once the button has done its work. + * + * Disconnect no longer goes through the settings form's "Remove the saved + * key" checkbox. That only ever forgot this site's copy, and left a live key + * in the workspace for the owner to go and revoke by hand — which is exactly + * what nobody does. It now calls SendBeam and revokes the key first. * - * Disconnect goes through the same "Remove the saved key" path a pasted key - * uses, so there is one way of forgetting a key rather than two. It forgets - * this site's copy and nothing else — the key itself is still live in - * SendBeam, which is where it has to be revoked, and saying so is the - * difference between a tidy uninstall and a key nobody knows is still valid. + * The confirmation is inline rather than window.confirm(): a browser dialog + * cannot say what disconnecting costs, and half of them are suppressed after + * the first one on a page. With scripts off the confirmation box is simply + * already open, so the button still works. + * + * @param array $status Normalised Connect status, for the workspace name. */ -function sendbeam_connect_connected_panel() { +function sendbeam_connect_connected_panel( $status = null ) { $workspace = sendbeam_connect_workspace_name(); + if ( '' === $workspace && is_array( $status ) ) { + $workspace = (string) $status['workspace']['name']; + } + + echo '
    '; if ( '' !== $workspace ) { /* translators: %s: the SendBeam workspace name */ echo '

    ' . esc_html( sprintf( __( 'Connected to %s', 'sendbeam' ), $workspace ) ) . '

    '; - } else { - echo '

    ' . esc_html__( 'Connected', 'sendbeam' ) . '

    '; } - echo '

    ' . esc_html__( 'This site was connected through SendBeam, and holds a key with only the permissions you approved.', 'sendbeam' ) . '

    '; - echo '

    ' . esc_html__( 'Disconnecting forgets this site\'s copy of the key. The key itself stays valid in SendBeam until you revoke it there, under Settings → API keys.', 'sendbeam' ) . '

    '; - echo '
    '; - settings_fields( 'sendbeam' ); - echo ''; - echo ''; - submit_button( __( 'Disconnect', 'sendbeam' ), 'secondary', 'submit', false ); - echo '
    '; + $granted = sendbeam_connect_granted_list(); + if ( $granted ) { + echo '
      '; + foreach ( $granted as $label ) { + echo '
    • ' . esc_html( $label ) . '
    • '; + } + echo '
    '; + } + + echo '
    '; + wp_nonce_field( 'sendbeam_disconnect' ); + echo ''; + printf( + '', + esc_html__( 'Disconnect', 'sendbeam' ) + ); + echo '
    '; + echo '

    ' . esc_html__( 'Disconnect this site? The key is revoked in SendBeam and forgotten here. Forms already on your pages stop loading until you connect again.', 'sendbeam' ) . '

    '; + printf( ' ', esc_html__( 'Yes, disconnect', 'sendbeam' ) ); + printf( '', esc_html__( 'Cancel', 'sendbeam' ) ); + echo '
    '; + + echo '
    '; +} + +/** + * The permissions this site's key holds, in the consent page's own words. + * + * @return string[] + */ +function sendbeam_connect_granted_list() { + $out = array(); + foreach ( sendbeam_connect_scopes() as $scope => $meta ) { + if ( sendbeam_connect_granted( $scope ) ) { + $out[] = $meta['label']; + } + } + return $out; } /** diff --git a/includes/settings.php b/includes/settings.php index 7a02b9e..77d5312 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -202,7 +202,16 @@ function sendbeam_sanitize_settings( $input ) { } if ( isset( $touch['mail_enabled'] ) ) { - $out['mail_enabled'] = empty( $input['mail_enabled'] ) ? 0 : 1; + $out['mail_enabled'] = empty( $input['mail_enabled'] ) ? 0 : 1; + + /* + * Turning site email off by hand is a decision, and it cancels the + * one Connect made on the site owner's behalf. Without this, the next + * domain check would helpfully switch it straight back on. + */ + if ( empty( $out['mail_enabled'] ) ) { + $out['sendbeam_mail_deferred'] = 0; + } $out['mail_from_name'] = isset( $input['mail_from_name'] ) ? sanitize_text_field( wp_unslash( $input['mail_from_name'] ) ) : ''; $from_email = isset( $input['mail_from_email'] ) ? sanitize_email( wp_unslash( $input['mail_from_email'] ) ) : ''; $out['mail_from_email'] = $from_email && is_email( $from_email ) ? $from_email : ''; @@ -234,6 +243,17 @@ function sendbeam_sanitize_settings( $input ) { sendbeam_flush_cache(); $out['sendbeam_connected_via'] = ''; $out['sendbeam_connect_workspace'] = ''; + // The permissions and the held-back site email belonged to the old + // key. A pasted key's permissions are unknown, and claiming the old + // ones would offer buttons that cannot work. + $out['sendbeam_connect_granted'] = ''; + $out['sendbeam_mail_deferred'] = 0; + } + + // A form chosen or cleared changes what the checklist should be looking + // for on the site, so the cached answer is no longer about this site. + if ( isset( $touch['default_form'] ) ) { + delete_transient( 'sendbeam_form_placed' ); } unset( $out['_tab'] ); @@ -656,6 +676,29 @@ function syncRule( rule ) { frame.open(); } ); + /* + * Inline confirmation, in place of window.confirm(): a browser dialog + * cannot explain what Disconnect costs, and Chrome suppresses repeat + * dialogs on a page anyway. The markup ships with the confirmation + * open and the plain button hidden, so a page with no JavaScript is + * still usable — this swaps them round the moment script runs. + */ + document.querySelectorAll( ".sb-confirm" ).forEach( function ( form ) { + var ask = form.querySelector( ".sb-confirm__ask" ); + var box = form.querySelector( ".sb-confirm__box" ); + var no = form.querySelector( ".sb-confirm__cancel" ); + if ( ! ask || ! box ) { return; } + function shut() { box.hidden = true; ask.hidden = false; } + shut(); + ask.addEventListener( "click", function () { + ask.hidden = true; + box.hidden = false; + var yes = box.querySelector( "button[type=submit]" ); + if ( yes ) { yes.focus(); } + } ); + if ( no ) { no.addEventListener( "click", function () { shut(); ask.focus(); } ); } + } ); + document.addEventListener( "click", function ( e ) { var btn = e.target.closest( ".sb-copy" ); if ( ! btn ) { return; } diff --git a/sendbeam.php b/sendbeam.php index ae52163..5dde57a 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -34,3 +34,4 @@ require SENDBEAM_DIR . 'includes/mail.php'; require SENDBEAM_DIR . 'includes/onboarding.php'; require SENDBEAM_DIR . 'includes/connect.php'; +require SENDBEAM_DIR . 'includes/connect-status.php'; diff --git a/uninstall.php b/uninstall.php index ecf439b..d61f425 100644 --- a/uninstall.php +++ b/uninstall.php @@ -34,6 +34,7 @@ 'sendbeam_remote_forms', 'sendbeam_remote_lists', 'sendbeam_subscriber_count', + 'sendbeam_form_placed', ); foreach ( $sendbeam_transients as $sendbeam_transient ) { delete_transient( $sendbeam_transient ); From 19144435898321085c780dd474bec4e97fb5bbcd Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Wed, 23 Sep 2026 22:08:19 +0000 Subject: [PATCH 04/75] Cover Connect v2, and the Overview screen itself MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new checks split three ways. What the exchange sets up: the form becomes the default only when the site has not chosen one, the sender fills only empty fields, site email stays off behind an unverified domain and goes on behind a verified one, and a domain-connect link pointing anywhere but sendbeam.io is dropped rather than rendered as a button. What the status endpoint does: one request a minute, a check that bypasses the cache, and a failure — including a 200 carrying something that is not JSON — that returns the full shape so no template indexes into a missing key. What the buttons do: Check now and Switch on both re-read the permission and the domain rather than trusting the page that drew them, and Disconnect revokes the key, forgets everything, and still forgets it when sendbeam.io cannot be reached. The Overview is now rendered by the smoke test and read back. No test could see a settings screen before — the layer where a permission check, a nonce or a whole form can drift without anything noticing — and four stubs of the Settings API are all it took. --- tests/smoke.php | 502 ++++++++++++++++++++++++++++++++++++++++++++- tests/wp-stubs.php | 15 ++ 2 files changed, 516 insertions(+), 1 deletion(-) diff --git a/tests/smoke.php b/tests/smoke.php index e811999..728b619 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -656,7 +656,18 @@ function sb_connect_reset() { // Only the scopes we offer survive, and `forms` is not optional. ok( sendbeam_connect_clean_scopes( array( 'transactional:send', 'sudo' ) ) === array( 'forms', 'transactional:send' ), 'connect: unknown scopes are dropped and forms is always asked for' ); ok( sendbeam_connect_clean_scopes( null ) === array( 'forms' ), 'connect: ticking nothing still asks for forms' ); -ok( array_keys( sendbeam_connect_scopes() ) === array( 'forms', 'contacts:write', 'transactional:send', 'ecommerce' ), 'connect: the four scopes, in the order the consent page shows them' ); +ok( array_keys( sendbeam_connect_scopes() ) === array( 'forms', 'contacts:write', 'transactional:send', 'ecommerce', 'domain' ), 'connect: the five scopes, in the order the consent page shows them' ); + +// The domain scope names the domain, not "your domain": a site owner has to +// recognise it to decide whether to tick it. +$GLOBALS['stub']['site_url'] = 'https://www.example-site.test'; +ok( 'example-site.test' === sendbeam_connect_site_host(), 'connect: the sending domain is the site host with www. stripped' ); +has( sendbeam_connect_scopes()['domain']['label'], 'example-site.test', 'connect: the domain scope says which domain it means' ); +ok( ! sendbeam_connect_scopes()['domain']['always'], 'connect: the domain scope can be unticked' ); +ok( sendbeam_connect_clean_scopes( array( 'domain' ) ) === array( 'forms', 'domain' ), 'connect: domain survives the scope clean-up' ); +$GLOBALS['stub']['site_url'] = 'https://shop.example.co.uk'; +ok( 'shop.example.co.uk' === sendbeam_connect_site_host(), 'connect: a host with no www. is left alone' ); +unset( $GLOBALS['stub']['site_url'] ); // https everywhere, with a hole only for machines that cannot be reached // from the internet. An http origin on a real domain must be refused, or the @@ -897,7 +908,496 @@ function sb_connect_pending( $state ) { ok( is_array( get_transient( 'sendbeam_connect_7' ) ), 'connect: a refused caller does not spend somebody else\'s state' ); delete_transient( 'sendbeam_connect_7' ); +// ── Connect v2: what the exchange sets up, and what it refuses to ────── +/** + * The v2 exchange body, with the parts each test wants overridden. + * + * @param array $over Keys to replace. + * @return string JSON. + */ +function sb_v2_body( $over = array() ) { + global $sendbeam_new_key, $form; + $body = array( + 'api_key' => $sendbeam_new_key, + 'key_prefix' => 'sb_live_kkkk', + 'workspace' => array( 'id' => 'ws_1', 'name' => 'Harbour Lane' ), + 'scopes' => array( 'forms', 'contacts:write', 'transactional:send', 'domain' ), + 'default_form' => array( 'id' => $form, 'name' => 'Newsletter signup' ), + 'domain' => array( + 'name' => 'harbourlane.co.uk', + 'verified' => false, + 'records' => array( + array( 'type' => 'TXT', 'name' => '_sendbeam', 'value' => 'v=sb1 k=abc' ), + array( 'type' => 'cname', 'name' => 'sb1._domainkey', 'value' => 'sb1.dkim.sendbeam.io' ), + ), + 'domain_connect_url' => 'https://sendbeam.io/domain-connect/xyz', + 'checked_at' => null, + ), + 'sender' => array( 'from_name' => 'Harbour Lane Roasters', 'from_email' => 'hello@harbourlane.co.uk' ), + ); + foreach ( $over as $k => $v ) { + $body[ $k ] = $v; + } + return json_encode( $body ); +} + +/** Drive the return handler with one exchange reply. */ +function sb_v2_exchange( $body, $settings = array() ) { + global $sendbeam_good_state, $sendbeam_good_grant; + sb_connect_reset(); + delete_transient( 'sendbeam_connect_status' ); + update_option( 'sendbeam_settings', $settings ); + sb_connect_pending( $sendbeam_good_state ); + $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => $body ); + $_GET = array( 'state' => $sendbeam_good_state, 'grant' => $sendbeam_good_grant ); + return sb_connect_run( 'sendbeam_connect_return' ); +} + +// An unverified domain: everything is stored, and site email stays off. +sb_v2_exchange( sb_v2_body() ); +$v2 = sendbeam_settings(); +ok( $form === $v2['default_form'], 'connect v2: the form SendBeam made becomes this site\'s default' ); +ok( 'Harbour Lane Roasters' === $v2['mail_from_name'], 'connect v2: the workspace sender name fills the empty From name' ); +ok( 'hello@harbourlane.co.uk' === $v2['mail_from_email'], 'connect v2: the workspace sender address fills the empty From address' ); +ok( empty( $v2['mail_enabled'] ), 'connect v2: site email is NOT switched on while the domain is unverified' ); +ok( ! empty( $v2['sendbeam_mail_deferred'] ), 'connect v2: site email is remembered as held back, not forgotten' ); +ok( 'forms,contacts:write,transactional:send,domain' === $v2['sendbeam_connect_granted'], 'connect v2: the granted permissions are stored as the key actually carries them' ); +ok( sendbeam_connect_granted( 'domain' ), 'connect v2: the screen can ask whether a permission was granted' ); +ok( ! sendbeam_connect_granted( 'ecommerce' ), 'connect v2: a permission that was not granted reads false' ); + +$v2_status = get_transient( 'sendbeam_connect_status' ); +ok( is_array( $v2_status ), 'connect v2: the status is cached for the Overview instead of being fetched again' ); +ok( 'harbourlane.co.uk' === $v2_status['domain']['name'], 'connect v2: the sending domain is cached' ); +ok( 2 === count( $v2_status['domain']['records'] ), 'connect v2: the DNS records are cached' ); +ok( 'CNAME' === $v2_status['domain']['records'][1]['type'], 'connect v2: a record type is upper-cased for display' ); +ok( 'https://sendbeam.io/domain-connect/xyz' === $v2_status['domain']['domain_connect_url'], 'connect v2: the registrar one-click link is kept' ); +ok( 'Newsletter signup' === $v2_status['default_form']['name'], 'connect v2: the form name is cached for the checklist' ); + +// A domain-connect link pointing anywhere but SendBeam is a phishing link +// wearing the plugin's chrome. It never becomes a button. +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array(), 'domain_connect_url' => 'https://evil.example.com/dns' ) ) ) ); +ok( '' === get_transient( 'sendbeam_connect_status' )['domain']['domain_connect_url'], 'connect v2: a domain-connect link on another host is dropped' ); +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array(), 'domain_connect_url' => 'http://sendbeam.io/dns' ) ) ) ); +ok( '' === get_transient( 'sendbeam_connect_status' )['domain']['domain_connect_url'], 'connect v2: an http domain-connect link is dropped' ); + +// A form ID that is not a form ID never becomes this site's default. +sb_v2_exchange( sb_v2_body( array( 'default_form' => array( 'id' => 'nonsense', 'name' => 'X' ) ) ) ); +ok( '' === sendbeam_settings()['default_form'], 'connect v2: a malformed default form ID is dropped, not stored' ); + +// A verified domain: site email goes on, because consent asked for it. +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array(), 'checked_at' => '2026-09-23T15:04:05Z' ) ) ) ); +$v2 = sendbeam_settings(); +ok( ! empty( $v2['mail_enabled'] ), 'connect v2: site email IS switched on when the domain is already verified' ); +ok( empty( $v2['sendbeam_mail_deferred'] ), 'connect v2: nothing is held back once it is on' ); + +// Without the transactional scope, nothing about site email is touched at all. +sb_v2_exchange( sb_v2_body( array( 'scopes' => array( 'forms', 'domain' ), 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ) ) ) ); +$v2 = sendbeam_settings(); +ok( empty( $v2['mail_enabled'] ), 'connect v2: a verified domain does not switch on site email the key cannot send' ); +ok( '' === $v2['mail_from_name'], 'connect v2: the sender is not filled in for a key that cannot send' ); + +// A form the site already chose is never repointed: an embed may be live on a page. +sb_v2_exchange( sb_v2_body(), array( 'default_form' => $other ) ); +ok( $other === sendbeam_settings()['default_form'], 'connect v2: reconnecting does not repoint a form the site already chose' ); + +// A From address the owner typed is theirs, not SendBeam's to overwrite. +sb_v2_exchange( sb_v2_body(), array( 'mail_from_email' => 'orders@harbourlane.co.uk', 'mail_from_name' => 'Orders' ) ); +$v2 = sendbeam_settings(); +ok( 'orders@harbourlane.co.uk' === $v2['mail_from_email'] && 'Orders' === $v2['mail_from_name'], 'connect v2: a sender the owner set is left alone' ); + +// ── /api/v1/connect/status ───────────────────────────────────────────── +sb_connect_reset(); +delete_transient( 'sendbeam_connect_status' ); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_statusstatusstatus' ) ); +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 200 ), + 'body' => json_encode( + array( + 'workspace' => array( 'id' => 'ws_1', 'name' => 'Harbour Lane' ), + 'default_form' => array( 'id' => $form, 'name' => 'Newsletter signup' ), + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array( array( 'type' => 'TXT', 'name' => '_sendbeam', 'value' => 'v=sb1' ) ), 'checked_at' => '2026-09-23T15:04:05Z' ), + 'sender' => array( 'from_name' => 'Harbour Lane Roasters', 'from_email' => 'hello@harbourlane.co.uk' ), + ) + ), +); +$st = sendbeam_connect_status(); +ok( 1 === count( $GLOBALS['stub']['remote'] ), 'status: one request the first time' ); +ok( 'GET' === $GLOBALS['stub']['remote'][0]['method'], 'status: a plain read is a GET' ); +ok( 'https://sendbeam.io/api/v1/connect/status' === $GLOBALS['stub']['remote'][0]['url'], 'status: goes to the contract URL' ); +// SENDBEAM_API_KEY is defined earlier in this file, and a key in wp-config.php +// deliberately beats the saved one — so that, not the option, is what travels. +ok( SENDBEAM_API_KEY === $GLOBALS['stub']['remote'][0]['args']['headers']['x-api-key'], 'status: authenticates with the site\'s own key' ); +ok( $st['ok'] && 'harbourlane.co.uk' === $st['domain']['name'], 'status: the domain comes back' ); + +sendbeam_connect_status(); +ok( 1 === count( $GLOBALS['stub']['remote'] ), 'status: the second read inside a minute is served from the cache' ); + +$checked = sendbeam_connect_status( true ); +ok( 2 === count( $GLOBALS['stub']['remote'] ), 'status: a check bypasses the cache' ); +ok( 'POST' === $GLOBALS['stub']['remote'][1]['method'], 'status: a check is a POST' ); +ok( array( 'check_domain' => true ) === json_decode( $GLOBALS['stub']['remote'][1]['args']['body'], true ), 'status: a check asks for check_domain' ); + +// The Overview renders for a site that was never connected: every key a +// template reads is present, and nothing claims to be true. +$st = sendbeam_connect_empty_status(); +ok( ! $st['ok'] && '' === $st['domain']['name'] && array() === $st['domain']['records'], 'status: an unconnected site gets the empty shape, not a missing key' ); +ok( '' === $st['workspace']['name'] && '' === $st['default_form']['id'] && '' === $st['sender']['from_email'], 'status: the empty shape has every key the Overview indexes into' ); +ok( array() === sendbeam_connect_normalise_status( 'not json' )['domain']['records'], 'status: a reply that is not an object normalises to empties rather than warning' ); + +// A rejected key is reported, cached, and never crashes a template. +sb_connect_reset(); +delete_transient( 'sendbeam_connect_status' ); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_revokedrevokedrevoked' ) ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 401 ), 'body' => '{"error":"unauthorised"}' ); +$st = sendbeam_connect_status(); +ok( ! $st['ok'] && '' !== $st['error'], 'status: a rejected key is reported in plain words' ); +ok( '' === $st['sender']['from_name'] && '' === $st['default_form']['id'], 'status: a failure still returns every key a template reads' ); +sendbeam_connect_status(); +ok( 1 === count( $GLOBALS['stub']['remote'] ), 'status: a failure is cached too, so a revoked key is not retried on every page load' ); + +// A 200 carrying nothing usable is a failure, not an answer: caching it as +// one would blank the DNS records somebody is halfway through copying. +sb_connect_reset(); +delete_transient( 'sendbeam_connect_status' ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => 'proxy error' ); +$st = sendbeam_connect_status(); +ok( ! $st['ok'] && '' !== $st['error'], 'status: a 200 that is not JSON is treated as a failure, not as an empty workspace' ); + +// ── Check now ────────────────────────────────────────────────────────── +/** Drive an admin-post handler that ends in a redirect. */ +function sb_run_admin_post( $fn ) { + try { + $fn(); + } catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); + } + return isset( $GLOBALS['stub']['redirect']['url'] ) ? (string) $GLOBALS['stub']['redirect']['url'] : ''; +} + +/** A connected site with site email approved but held back. */ +function sb_deferred_site() { + sb_connect_reset(); + delete_transient( 'sendbeam_connect_status' ); + update_option( + 'sendbeam_settings', + array( + 'api_key' => 'sb_live_connectedconnectedxx', + 'sendbeam_connected_via' => 'connect', + 'sendbeam_connect_granted' => 'forms,transactional:send,domain', + 'sendbeam_mail_deferred' => 1, + 'mail_enabled' => 0, + ) + ); + $_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check' ); + $_REQUEST = $_POST; +} + +/** A status reply body with the domain verified or not. */ +function sb_status_body( $verified ) { + return json_encode( + array( + 'workspace' => array( 'id' => 'ws_1', 'name' => 'Harbour Lane' ), + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => $verified, 'records' => array(), 'checked_at' => '2026-09-23T15:04:05Z' ), + 'sender' => array( 'from_name' => 'Harbour Lane Roasters', 'from_email' => 'hello@harbourlane.co.uk' ), + ) + ); +} + +sb_deferred_site(); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) ); +$url = sb_run_admin_post( 'sendbeam_handle_domain_check' ); +has( $url, 'sendbeam_domain=pending', 'check: a domain that is still unverified says so' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'check: an unverified domain never switches site email on' ); +ok( ! empty( sendbeam_settings()['sendbeam_mail_deferred'] ), 'check: site email stays held back' ); + +sb_deferred_site(); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +$url = sb_run_admin_post( 'sendbeam_handle_domain_check' ); +has( $url, 'sendbeam_domain=verified_mail', 'check: a verified domain finishes the job consent started' ); +$v2 = sendbeam_settings(); +ok( ! empty( $v2['mail_enabled'] ), 'check: site email goes on once the domain is verified' ); +ok( empty( $v2['sendbeam_mail_deferred'] ), 'check: nothing is left held back' ); +ok( 'hello@harbourlane.co.uk' === $v2['mail_from_email'], 'check: the workspace sender fills the empty From address' ); + +// Site email switched off by hand is a decision. A later check must not undo it. +sb_deferred_site(); +$off = sendbeam_sanitize_settings( array( '_tab' => 'mail' ) ); +update_option( 'sendbeam_settings', $off ); +ok( empty( $off['sendbeam_mail_deferred'] ), 'check: turning site email off by hand cancels the held-back switch-on' ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check' ); +$_REQUEST = $_POST; +delete_transient( 'sendbeam_connect_status' ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +$url = sb_run_admin_post( 'sendbeam_handle_domain_check' ); +has( $url, 'sendbeam_domain=verified', 'check: a verified domain is still reported' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'check: a verified domain does NOT re-enable site email the owner switched off' ); + +// Nonce and capability. +sb_deferred_site(); +$_POST = array(); +$_REQUEST = array(); +sb_run_admin_post( 'sendbeam_handle_domain_check' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'check: no nonce, no check' ); +sb_deferred_site(); +$GLOBALS['stub']['caps']['manage_options'] = false; +sb_run_admin_post( 'sendbeam_handle_domain_check' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'check: the capability is required' ); + +// ── Switch on ────────────────────────────────────────────────────────── +sb_deferred_site(); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_mail_switch_on' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) ); +$url = sb_run_admin_post( 'sendbeam_handle_mail_switch_on' ); +has( $url, 'sendbeam_mail=unverified', 'switch on: refuses while the domain is unverified' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'switch on: nothing is enabled while the domain is unverified' ); + +sb_deferred_site(); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_mail_switch_on' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +$url = sb_run_admin_post( 'sendbeam_handle_mail_switch_on' ); +has( $url, 'sendbeam_mail=on', 'switch on: turns site email on once the domain is verified' ); +ok( ! empty( sendbeam_settings()['mail_enabled'] ), 'switch on: site email is on' ); + +// A key without the scope cannot be talked into it by a replayed form. +sb_deferred_site(); +$noscope = sendbeam_settings(); +$noscope['sendbeam_connect_granted'] = 'forms'; +update_option( 'sendbeam_settings', $noscope ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_mail_switch_on' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +$url = sb_run_admin_post( 'sendbeam_handle_mail_switch_on' ); +has( $url, 'sendbeam_mail=noscope', 'switch on: refuses a key that was never given the permission' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'switch on: nothing is enabled without the permission' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'switch on: a key without the permission is not even asked about' ); + +// ── Disconnect ───────────────────────────────────────────────────────── +/** A connected site, armed for a disconnect. */ +function sb_connected_site() { + sb_connect_reset(); + update_option( + 'sendbeam_settings', + array( + 'api_key' => 'sb_live_connectedconnectedxx', + 'sendbeam_connected_via' => 'connect', + 'sendbeam_connect_workspace' => 'Harbour Lane', + 'sendbeam_connect_granted' => 'forms,transactional:send,domain', + 'sendbeam_mail_deferred' => 1, + ) + ); + set_transient( 'sendbeam_connect_status', sendbeam_connect_empty_status(), 60 ); + $_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); + $_REQUEST = $_POST; +} + +sb_connected_site(); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' ); +$url = sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( 1 === count( $GLOBALS['stub']['remote'] ), 'disconnect: SendBeam is asked to revoke the key' ); +ok( 'https://sendbeam.io/api/v1/connect/disconnect' === $GLOBALS['stub']['remote'][0]['url'], 'disconnect: the revoke goes to the contract URL' ); +ok( 'POST' === $GLOBALS['stub']['remote'][0]['method'], 'disconnect: the revoke is a POST' ); +ok( SENDBEAM_API_KEY === $GLOBALS['stub']['remote'][0]['args']['headers']['x-api-key'], 'disconnect: the key revokes itself' ); +ok( 10 === $GLOBALS['stub']['remote'][0]['args']['timeout'], 'disconnect: the revoke has the short timeout the contract asks for' ); +$v2 = sendbeam_settings(); +ok( '' === $v2['api_key'], 'disconnect: the key is forgotten' ); +ok( '' === $v2['sendbeam_connected_via'] && '' === $v2['sendbeam_connect_workspace'], 'disconnect: the Connect marker and workspace name go with it' ); +ok( '' === $v2['sendbeam_connect_granted'] && empty( $v2['sendbeam_mail_deferred'] ), 'disconnect: the permissions and the held-back switch-on are forgotten' ); +ok( false === get_transient( 'sendbeam_connect_status' ), 'disconnect: the cached status is dropped' ); +has( $url, 'sendbeam_disconnected=ok', 'disconnect: the notice says the key was revoked' ); + +// SendBeam unreachable: the site still forgets the key, and says so. +sb_connected_site(); +$GLOBALS['stub']['remote_reply'] = new WP_Error( 'http_request_failed', 'cURL error 28' ); +$url = sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( '' === sendbeam_settings()['api_key'], 'disconnect: an unreachable SendBeam still forgets the key here' ); +has( $url, 'sendbeam_disconnected=unreachable', 'disconnect: an unreachable SendBeam is reported so the key can be revoked by hand' ); + +// A key SendBeam has already forgotten is not a live key. +sb_connected_site(); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 401 ), 'body' => '{"error":"unauthorised"}' ); +$url = sb_run_admin_post( 'sendbeam_connect_disconnect' ); +has( $url, 'sendbeam_disconnected=ok', 'disconnect: a key SendBeam already rejects counts as revoked' ); + +// Nonce and capability. +sb_connected_site(); +$_POST = array(); +$_REQUEST = array(); +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'disconnect: no nonce, no disconnect' ); +ok( 'sb_live_connectedconnectedxx' === sendbeam_settings()['api_key'], 'disconnect: a request with no nonce keeps the key' ); +sb_connected_site(); +$GLOBALS['stub']['caps']['manage_options'] = false; +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'disconnect: the capability is required' ); +ok( 'sb_live_connectedconnectedxx' === sendbeam_settings()['api_key'], 'disconnect: a caller without the capability changes nothing' ); + +// ── A blocked pop-up ─────────────────────────────────────────────────── +sb_connect_reset(); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start', 'sendbeam_popup' => '0' ); +$_REQUEST = $_POST; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +$blocked_state = get_transient( 'sendbeam_connect_7' ); +ok( isset( $blocked_state['popup'] ) && 0 === $blocked_state['popup'], 'pop-up blocked: the flow remembers it is happening in this tab' ); + +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_v2_body() ); +$_GET = array( 'state' => $blocked_state['state'], 'grant' => $sendbeam_good_grant ); +$blocked_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $blocked_html, 'Connected', 'pop-up blocked: the connection still completes' ); +has( $blocked_html, 'Back to the site', 'pop-up blocked: the page offers a way back instead of a dead end' ); +lacks( $blocked_html, 'window.close()', 'pop-up blocked: nothing tries to close the tab the person is using' ); +lacks( $blocked_html, 'postMessage', 'pop-up blocked: there is no opener to message' ); + +// The pop-up path is unchanged. +sb_connect_reset(); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start', 'sendbeam_popup' => '1' ); +$_REQUEST = $_POST; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +$popup_state = get_transient( 'sendbeam_connect_7' ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_v2_body() ); +$_GET = array( 'state' => $popup_state['state'], 'grant' => $sendbeam_good_grant ); +$popup_html = sb_connect_run( 'sendbeam_connect_return' ); +has( $popup_html, 'window.close()', 'pop-up: a real pop-up still closes itself' ); +has( $popup_html, 'Back to SendBeam settings', 'pop-up: the link underneath still points at the settings screen' ); + +// The form carries the flag the script flips, and the script flips it. +sb_connect_reset(); +ob_start(); +sendbeam_connect_panel(); +$panel_html = ob_get_clean(); +has( $panel_html, 'name="sendbeam_popup" value="0"', 'pop-up: the form defaults to "this tab" until the script says otherwise' ); +has( $panel_html, 'example-site.test', 'pop-up: the domain permission names this site\'s domain' ); +has( sendbeam_connect_admin_js(), 'sb-connect-popup', 'pop-up: the script sets the flag it was given' ); + +// ── The Overview itself ──────────────────────────────────────────────── +// No test could see a settings screen before, which is how a permission +// check or a form could drift on the page layer without anything noticing. +// These render the real function and read the real HTML. + +/** + * Render the Overview for a site in a given state. + * + * @param array $settings Saved settings. + * @param array $status Status payload, as the API would send it. + * @param array $get Query arguments on the screen. + * @return string + */ +function sb_overview( $settings, $status, $get = array() ) { + $GLOBALS['stub']['caps']['manage_options'] = true; + $GLOBALS['stub']['user_id'] = 7; + $GLOBALS['stub']['current_user'] = array( 'email' => 'admin@example-site.test' ); + $GLOBALS['stub']['remote'] = array(); + $_GET = $get; + update_option( 'sendbeam_settings', $settings ); + set_transient( 'sendbeam_connection', array( 'state' => '' === (string) ( $settings['api_key'] ?? '' ) ? 'none' : 'ok', 'message' => '', 'count' => 1 ) ); + set_transient( 'sendbeam_remote_forms', array() ); + set_transient( 'sendbeam_remote_lists', array() ); + set_transient( 'sendbeam_subscriber_count', 0 ); + set_transient( 'sendbeam_connect_status', sendbeam_connect_normalise_status( $status ), 60 ); + ob_start(); + sendbeam_screen_overview(); + return ob_get_clean(); +} + +$sb_connected = array( + 'api_key' => 'sb_live_connectedconnectedxx', + 'sendbeam_connected_via' => 'connect', + 'sendbeam_connect_workspace' => 'Harbour Lane', + 'sendbeam_connect_granted' => 'forms,transactional:send,domain', + 'sendbeam_mail_deferred' => 1, +); +$sb_unverified = array( + 'workspace' => array( 'id' => 'ws_1', 'name' => 'Harbour Lane' ), + 'default_form' => array( 'id' => $form, 'name' => 'Newsletter signup' ), + 'domain' => array( + 'name' => 'harbourlane.co.uk', + 'verified' => false, + 'records' => array( + array( 'type' => 'TXT', 'name' => '_sendbeam', 'value' => 'v=sb1 k=abc' ), + array( 'type' => 'MX', 'name' => 'send', 'value' => '10 feedback-smtp.eu-west-1.amazonses.com' ), + ), + 'domain_connect_url' => 'https://sendbeam.io/dc/1', + 'checked_at' => '2026-09-23T15:04:05Z', + ), + 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'hello@harbourlane.co.uk' ), +); + +$ov = sb_overview( $sb_connected, $sb_unverified ); +has( $ov, 'Verify your sending domain', 'overview: the domain step is on the checklist' ); +has( $ov, 'Put a form on the site', 'overview: the form step is on the checklist' ); +has( $ov, 'Send this site's email through SendBeam', 'overview: the site email step is on the checklist' ); +has( $ov, 'v=sb1 k=abc', 'overview: the DNS records are shown, not linked to' ); +has( $ov, '10 feedback-smtp.eu-west-1.amazonses.com', 'overview: every record is shown' ); +has( $ov, 'data-copy="10 feedback-smtp.eu-west-1.amazonses.com"', 'overview: each record value has its own Copy button' ); +has( $ov, 'Check now', 'overview: the domain can be re-checked without leaving wp-admin' ); +has( $ov, 'value="sendbeam_domain_check"', 'overview: Check now posts to the check handler' ); +has( $ov, 'nonce:sendbeam_domain_check', 'overview: Check now carries a nonce' ); +has( $ov, 'Set up DNS automatically', 'overview: the registrar one-click button is offered' ); +has( $ov, 'https://sendbeam.io/dc/1', 'overview: the one-click button points at the link SendBeam sent' ); +has( $ov, 'target="_blank"', 'overview: the one-click button opens in a new tab' ); +has( $ov, 'Disconnect', 'overview: Disconnect is visible on the connected card' ); +has( $ov, 'value="sendbeam_disconnect"', 'overview: Disconnect posts to the disconnect handler' ); +has( $ov, 'nonce:sendbeam_disconnect', 'overview: Disconnect carries a nonce' ); +has( $ov, 'sb-confirm', 'overview: Disconnect is confirmed before it runs' ); +lacks( $ov, 'confirm(', 'overview: the confirmation is the plugin\'s own, not a browser dialog' ); +lacks( $ov, 'Switch on', 'overview: site email cannot be switched on while the domain is unverified' ); +has( $ov, 'Waiting on step 2', 'overview: the site email step says what it is waiting for' ); +lacks( $ov, 'sb_live_connectedconnectedxx', 'overview: the key is never printed on the screen' ); + +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sendbeam_domain' => 'pending' ) ); +has( $ov, 'Not verified yet', 'overview: a check that found nothing says so at the top' ); +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sendbeam_disconnected' => 'unreachable' ) ); +has( $ov, 'revoke it under Settings', 'overview: a disconnect SendBeam never heard about says where to finish the job' ); +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sendbeam_domain' => '' ) ); +lacks( $ov, 'alert(1)', 'overview: a notice name from the URL is not a message to print' ); + +// Verified, site email approved but not yet on: one button. +$sb_verified = $sb_unverified; +$sb_verified['domain']['verified'] = true; +$ov = sb_overview( $sb_connected, $sb_verified ); +has( $ov, 'Verified', 'overview: a verified domain is ticked off' ); +has( $ov, 'Switch on', 'overview: site email offers one button once the domain is verified' ); +has( $ov, 'value="sendbeam_mail_switch_on"', 'overview: Switch on posts to the switch-on handler' ); +has( $ov, 'nonce:sendbeam_mail_switch_on', 'overview: Switch on carries a nonce' ); +has( $ov, 'hello@harbourlane.co.uk', 'overview: Switch on says which address email will come from' ); + +// Verified, but the key was never given the permission. +$sb_noscope = $sb_connected; +$sb_noscope['sendbeam_connect_granted'] = 'forms,domain'; +$ov = sb_overview( $sb_noscope, $sb_verified ); +lacks( $ov, 'Switch on', 'overview: no Switch on button for a key that cannot send' ); +has( $ov, 'not given permission to send', 'overview: the screen says the permission is what is missing' ); + +// Site email already on: the test send is right there. +$sb_on = $sb_connected; +$sb_on['mail_enabled'] = 1; +$ov = sb_overview( $sb_on, $sb_verified ); +has( $ov, 'Send a test email', 'overview: site email that is on offers the test send' ); +has( $ov, 'nonce:sendbeam_test_mail', 'overview: the test send carries a nonce' ); + +// Never connected: the Connect button, and no checklist that pretends to know anything. +$ov = sb_overview( array(), array() ); +has( $ov, 'Connect SendBeam', 'overview: an unconnected site gets the button' ); +has( $ov, 'I already have an API key', 'overview: pasting a key is still possible' ); +lacks( $ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); +lacks( $ov, 'value="sendbeam_disconnect"', 'overview: nothing offers to disconnect what is not connected' ); +has( $ov, 'Connect the site first', 'overview: the domain step says to connect first' ); + sb_connect_reset(); +delete_transient( 'sendbeam_connect_status' ); +delete_transient( 'sendbeam_connection' ); +delete_transient( 'sendbeam_remote_forms' ); +delete_transient( 'sendbeam_remote_lists' ); +delete_transient( 'sendbeam_subscriber_count' ); update_option( 'sendbeam_settings', array() ); // One version number, five files. 1.6.2 shipped with the block's asset diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 7e9b484..0627d3d 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -184,6 +184,21 @@ function wp_unschedule_hook( $hook ) { if ( ! defined( 'MINUTE_IN_SECONDS' ) ) { define( 'MINUTE_IN_SECONDS', 60 ); } +if ( ! defined( 'HOUR_IN_SECONDS' ) ) { + define( 'HOUR_IN_SECONDS', 3600 ); +} +function esc_attr__( $s, $d = null ) { return esc_attr( $s ); } + +/** + * Enough of the Settings API to render a tab. The fields themselves are + * exercised elsewhere; what these let the smoke test see is the *screen* — + * which is the one layer no test could reach before, and the one where a + * missing function is a fatal error on a live wp-admin page. + */ +function do_settings_sections( $page ) { echo ''; } +function settings_fields( $group ) { echo ''; } +function submit_button( $text = '', $type = 'primary', $name = 'submit', $wrap = true ) { echo ''; } +function number_format_i18n( $n, $decimals = 0 ) { return number_format( (float) $n, (int) $decimals ); } function is_user_logged_in() { return ! empty( $GLOBALS['stub']['current_user'] ); } function get_the_ID() { return isset( $GLOBALS['stub']['post_id'] ) ? $GLOBALS['stub']['post_id'] : 0; } function wp_get_current_user() { From 3e7bc9feb0466ea2a3e181243b386bee9153b486 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Wed, 23 Sep 2026 22:08:19 +0000 Subject: [PATCH 05/75] Document what connecting now does for you readme.txt's external-service entry 6 says what SendBeam changes in the workspace at consent time, that the settings screen reads /api/v1/connect/status while it is open, and that Disconnect revokes the key rather than merely forgetting it. Installation gains the sending-domain step in second place, which is where it is on the screen. --- CHANGELOG.md | 6 ++++++ README.md | 20 +++++++++++++++----- readme.txt | 12 ++++++++++-- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99549f1..628780a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ - The key is written through the same `sendbeam_sanitize_settings()` path a pasted key goes through, so there is one set of validation rules rather than two. Pasting or removing a key by hand clears the Connect marker, and **Disconnect** is the existing "Remove the saved key" path — it forgets this site's copy, and says plainly that the key stays valid in SendBeam until revoked there. - Pasting a key still works, moved into a quiet "I already have an API key" disclosure under the button. - `uninstall.php` now sweeps `sendbeam_connect_*` transients for every administrator, not just the one doing the uninstalling. +- **The sending domain, in the plugin.** A fifth permission — "Set up this site's sending domain (yourdomain.com) in SendBeam", ticked by default — lets consent add this site's domain to the workspace. The Overview then shows its DNS records as a table with a Copy button on every value, a **Check now** button that asks SendBeam to look the DNS up again without leaving wp-admin, and a **Set up DNS automatically** button where the registrar supports one-click set-up. This was the gap: a site owner who has just connected needs the domain next, and had to go and find it on sendbeam.io. +- The set-up checklist is four steps, with the sending domain second. It used to say "optional" about the one thing every other step depends on, and step three now ticks off only when a block or shortcode is actually on the site rather than when a form has been chosen in the settings. +- Site email fills its From name and address from the workspace sender, but switches on **only** when the sending domain is verified — at consent time, from the **Check now** button, or from a one-click **Switch on**. A site whose password resets silently stop arriving is worse off than one that never turned the feature on. Turning site email off by hand cancels that held-back switch-on, so a later check never quietly undoes the decision. +- **Disconnect** is a visible button on the connected card, confirmed inline rather than with `window.confirm()`, and it revokes the key at SendBeam (`POST /api/v1/connect/disconnect`) before forgetting it here. The old path was a "Remove the saved key" checkbox that left a live key in the workspace and told you to go and revoke it yourself. +- A blocked pop-up is no longer a dead end: the Connect form falls back to navigating the current tab, and the page it lands on offers **Back to the site** instead of trying to close a window nothing opened. +- The Overview screen itself is now covered by the smoke tests. No test could see a settings screen before, which is how a permission check or a form on the page layer could drift without anything noticing. ## 1.8.2 diff --git a/README.md b/README.md index 0ed1512..11f7709 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,20 @@ cd sendbeam-wordpress && bin/build-zip.sh # → build/sendbeam.zip Then Settings → SendBeam and press **Connect SendBeam**. The button opens a window on sendbeam.io where you create your account or sign in — the site's name and your administrator email address are already filled in — and tick what this site may do: show your forms, add people who opt in, send the site's own email, send -WooCommerce events. Approve, and this site is handed an API key with exactly those permissions. The key never -passes through the browser: the window comes back with a single-use grant bound to this site's address and to -the `state` this site minted, and your server swaps it for the key in one call. Nothing is sent to SendBeam -until you press the button. If you already have a key, "I already have an API key" on the same screen still -takes one. Forms are then picked from a dropdown of the connected workspace's own forms — no IDs to copy. +WooCommerce events, set up this site's sending domain. Approve, and this site is handed an API key with +exactly those permissions. The key never passes through the browser: the window comes back with a single-use +grant bound to this site's address and to the `state` this site minted, and your server swaps it for the key +in one call. Nothing is sent to SendBeam until you press the button. If you already have a key, "I already +have an API key" on the same screen still takes one. Forms are then picked from a dropdown of the connected +workspace's own forms — no IDs to copy. + +Leaving the sending-domain box ticked does the next piece of setting up for you. SendBeam adds this site's +domain to the workspace, and the Overview's second step shows its DNS records with a Copy button on every +value, a **Check now** button that re-runs the check without leaving wp-admin, and a **Set up DNS +automatically** button where your registrar supports one-click set-up. Site email fills in its sender from the +workspace but only switches on once that domain is verified — a site should never have its password resets +quietly routed through a domain nothing has set up yet. **Disconnect**, on the connected card, revokes the key +in SendBeam first and then forgets it here. ## API key permissions @@ -49,6 +58,7 @@ Only what you use. Placing a form or a pop-up needs no key at all. | `lists:read` | The Audience tab and its subscriber counts | | `contacts:read`, `contacts:write`, `lists:write` | The opt-in box at registration, comments or checkout | | `transactional:send` | Site email | +| `domains:read` | The sending-domain step: its DNS records, and **Check now** | Paste the key in the settings, or define `SENDBEAM_API_KEY` in `wp-config.php` to keep it out of the database. diff --git a/readme.txt b/readme.txt index 6ed403e..c2cb9f2 100644 --- a/readme.txt +++ b/readme.txt @@ -45,6 +45,8 @@ This plugin talks to SendBeam (sendbeam.io) in six distinct ways. Nothing is sen **6. Connecting this site to SendBeam** (only when you press the Connect SendBeam button). A window opens on `https://sendbeam.io/connect/wordpress` carrying this site's address, its title, your WordPress administrator email address — used only to fill in the signup or sign-in form, so you do not type it again — and the list of permissions this site is asking for. If you do not already have a SendBeam account you create one there, on sendbeam.io; account creation never happens on your site and your SendBeam password is never seen by WordPress. When you approve, your server makes one call to `https://sendbeam.io/api/v1/connect/exchange` and receives an API key for this site with exactly the permissions you ticked. The key is stored in this site's options table, the same place a pasted key goes. Press nothing and nothing is sent. +What SendBeam does at that moment, in your workspace, is decided by the boxes you tick: if you leave the sending-domain box ticked it adds this site's domain as a sending domain so its DNS records exist for you to copy, and if the workspace has no signup form yet it creates a list called Subscribers and a form called Newsletter signup on it. Afterwards, while a site administrator has the SendBeam settings page open, your server reads `https://sendbeam.io/api/v1/connect/status` with this site's key to show the domain's records and whether it is verified; the answer is cached for a minute. Pressing **Check now** posts to the same address to ask for the DNS to be looked up again. Pressing **Disconnect** posts to `https://sendbeam.io/api/v1/connect/disconnect`, which revokes this site's key in SendBeam, and then the key is deleted from this site. + **Site email** (off by default) posts each email your site sends from your server to `https://sendbeam.io/api/v1/transactional` with your API key: the recipient addresses, subject, body and reply-to, so SendBeam can deliver it from your verified domain. Messages with attachments are left to the server's own mailer. **E-commerce events** (off by default, each of the three switched on separately, WooCommerce only) posts to `https://sendbeam.io/api/v1/ecommerce/events` with your API key: an email address, and depending on the event a name, an order total and its currency. Order placed sends when an order is completed. Product viewed sends only when the visitor is a known contact (logged in, or an email already given this visit) — never for an anonymous visitor. Cart abandoned is a best-effort heuristic: adding an item to the cart is timestamped locally on your server, and if no order has followed within a window you set (60 minutes by default) and an email became known at some point, one event is sent; nothing is sent for a cart nobody's email was ever known for. @@ -59,8 +61,9 @@ A SendBeam account (the Free plan is enough) with at least one form. Form IDs ar 1. Install and activate the plugin. 2. Go to **Settings → SendBeam** and click **Connect SendBeam**. Create your account or sign in in the window that opens, tick what this site may do, and the key arrives on its own — there is nothing to copy. If you already have an API key, "I already have an API key" on the same screen still takes one. -3. Pick your signup form (and, if you like, a contact form and a pop-up form) from the dropdown of your own forms. -4. Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. +3. Verify your sending domain — the plugin shows the records, or sets them up for you where your registrar supports it. Copy each value into your DNS, press **Check now**, and the step ticks itself off. Nothing SendBeam sends for you leaves your own domain until this is done. +4. Pick your signup form (and, if you like, a contact form and a pop-up form) from the dropdown of your own forms. +5. Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. == Frequently Asked Questions == @@ -130,6 +133,11 @@ Yes. The form is an iframe and the pop-up is a script tag, both cache-safe. = 1.8.3 = * **Connect SendBeam.** One button on the Overview tab replaces making an account, finding the API keys screen, working out which permissions to give and pasting the key back. You tick what this site may do, create your account or sign in on sendbeam.io in a pop-up, and the site is handed a key with exactly those permissions. Pasting a key by hand still works, under "I already have an API key". +* Connecting can now set up your sending domain as well: tick the box and SendBeam adds this site's domain, and the Overview shows you the DNS records with a Copy button on every value, a **Check now** button, and a **Set up DNS automatically** button where your registrar supports it. +* The set-up checklist has four steps rather than three, with verifying your sending domain second — it is what everything else depends on, and it used to be buried under "optional". +* Site email can be switched on from the Overview in one click, but only once the sending domain is verified. A site's password resets should never start going out through a domain that has not been set up. +* **Disconnect** is now a visible button on the Overview, and it revokes the key in SendBeam before forgetting it here. Before, it only forgot this site's copy and left the key live in your account. +* If your browser blocks the pop-up, connecting now carries on in the same tab and offers a link back instead of a blank window. = 1.8.2 = * Pop-ups come in four styles — split with image, editorial, bold colour and slide-in — with an image, an eyebrow, a button label and an optional subscriber count, set per pop-up. From cb4c7879c12a4260b2265dab7fc3a74940217ef1 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Wed, 23 Sep 2026 22:10:48 +0000 Subject: [PATCH 06/75] Never revoke a key this site did not issue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SENDBEAM_API_KEY in wp-config.php beats the saved key everywhere, and that includes the revoke call Disconnect now makes. On a site that defines it, pressing Disconnect would have revoked the wp-config key — one Connect never issued, held outside the database on purpose, and very likely shared with something else. A key this site does not store is not this site's to revoke. The stored key is forgotten as before, nothing is revoked, and the notice says where the live one is and how to take it out of service. --- CHANGELOG.md | 1 + includes/connect.php | 21 +++++++++++++++++---- includes/screens.php | 1 + tests/smoke.php | 28 ++++++++++++++++++++++++---- 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 628780a..1700f19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - The set-up checklist is four steps, with the sending domain second. It used to say "optional" about the one thing every other step depends on, and step three now ticks off only when a block or shortcode is actually on the site rather than when a form has been chosen in the settings. - Site email fills its From name and address from the workspace sender, but switches on **only** when the sending domain is verified — at consent time, from the **Check now** button, or from a one-click **Switch on**. A site whose password resets silently stop arriving is worse off than one that never turned the feature on. Turning site email off by hand cancels that held-back switch-on, so a later check never quietly undoes the decision. - **Disconnect** is a visible button on the connected card, confirmed inline rather than with `window.confirm()`, and it revokes the key at SendBeam (`POST /api/v1/connect/disconnect`) before forgetting it here. The old path was a "Remove the saved key" checkbox that left a live key in the workspace and told you to go and revoke it yourself. +- Disconnect will not revoke a key defined as `SENDBEAM_API_KEY` in `wp-config.php`. That key beats the saved one everywhere, including in the revoke call, so pressing the button on such a site would have taken down a key Connect never issued and something else is probably using. The stored key is forgotten, nothing is revoked, and the screen says where the live one is. - A blocked pop-up is no longer a dead end: the Connect form falls back to navigating the current tab, and the page it lands on offers **Back to the site** instead of trying to close a window nothing opened. - The Overview screen itself is now covered by the smoke tests. No test could see a settings screen before, which is how a permission check or a form on the page layer could drift without anything noticing. diff --git a/includes/connect.php b/includes/connect.php index 59a1670..b9f360a 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -578,12 +578,25 @@ function sendbeam_connect_disconnect() { } check_admin_referer( 'sendbeam_disconnect' ); - $revoked = false; - if ( '' !== sendbeam_api_key() ) { + /* + * SENDBEAM_API_KEY in wp-config.php beats the stored key everywhere, + * including here — so on a site that defines it, POST /connect/disconnect + * would revoke *that* key, which this button never issued and which is + * very likely shared with something else. A key this site does not store + * is not this site's to revoke: it is left alone, the stored one is + * forgotten, and the screen says where the live one is. + */ + $stored = (string) sendbeam_settings()['api_key']; + $constant = ( defined( 'SENDBEAM_API_KEY' ) && SENDBEAM_API_KEY ) ? (string) SENDBEAM_API_KEY : ''; + $note = 'unreachable'; + + if ( '' !== $constant && $constant !== $stored ) { + $note = 'constant'; + } elseif ( '' !== sendbeam_api_key() ) { $result = sendbeam_api_post( '/api/v1/connect/disconnect', array(), 10 ); // A key SendBeam has already forgotten is a key that is not live, so // 401 counts as revoked rather than as a failure to report. - $revoked = $result['ok'] || 401 === $result['status']; + $note = ( $result['ok'] || 401 === $result['status'] ) ? 'ok' : 'unreachable'; } $settings = sendbeam_settings(); @@ -597,7 +610,7 @@ function sendbeam_connect_disconnect() { sendbeam_flush_cache(); sendbeam_connect_forget_status(); - wp_safe_redirect( add_query_arg( 'sendbeam_disconnected', $revoked ? 'ok' : 'unreachable', sendbeam_tab_url( 'overview' ) ) ); + wp_safe_redirect( add_query_arg( 'sendbeam_disconnected', $note, sendbeam_tab_url( 'overview' ) ) ); exit; } diff --git a/includes/screens.php b/includes/screens.php index 840ef70..b7f34af 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -129,6 +129,7 @@ function sendbeam_overview_notices() { 'gone' => array( 'ok' => array( 'ok', __( 'Disconnected. The key was revoked in SendBeam.', 'sendbeam' ) ), 'unreachable' => array( 'warn', __( 'Disconnected, but this server could not reach SendBeam; revoke it under Settings → API keys.', 'sendbeam' ) ), + 'constant' => array( 'warn', __( 'Disconnected here, and nothing was revoked: this site sends with the key defined as SENDBEAM_API_KEY in wp-config.php, which is not the one this button issued. Remove it there, and revoke it under Settings → API keys.', 'sendbeam' ) ), ), ); diff --git a/tests/smoke.php b/tests/smoke.php index 728b619..d378fcb 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1174,13 +1174,20 @@ function sb_status_body( $verified ) { ok( empty( $GLOBALS['stub']['remote'] ), 'switch on: a key without the permission is not even asked about' ); // ── Disconnect ───────────────────────────────────────────────────────── -/** A connected site, armed for a disconnect. */ +/** + * A connected site, armed for a disconnect. + * + * The saved key is SENDBEAM_API_KEY's value on purpose. This file defines + * that constant earlier, and a key in wp-config.php beats the saved one — so + * a site where the two differ is a site whose live key Connect never issued, + * which has its own test below. + */ function sb_connected_site() { sb_connect_reset(); update_option( 'sendbeam_settings', array( - 'api_key' => 'sb_live_connectedconnectedxx', + 'api_key' => SENDBEAM_API_KEY, 'sendbeam_connected_via' => 'connect', 'sendbeam_connect_workspace' => 'Harbour Lane', 'sendbeam_connect_granted' => 'forms,transactional:send,domain', @@ -1220,18 +1227,31 @@ function sb_connected_site() { $url = sb_run_admin_post( 'sendbeam_connect_disconnect' ); has( $url, 'sendbeam_disconnected=ok', 'disconnect: a key SendBeam already rejects counts as revoked' ); +// A key defined in wp-config.php is not this button's to revoke: it beats the +// saved key everywhere, so revoking it would take down something Connect +// never issued and something else is probably using. +sb_connected_site(); +$const_site = sendbeam_settings(); +$const_site['api_key'] = 'sb_live_storedbutnotusedxxx'; +update_option( 'sendbeam_settings', $const_site ); +$GLOBALS['stub']['remote'] = array(); +$url = sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'disconnect: a key from wp-config.php is never revoked by this button' ); +ok( '' === sendbeam_settings()['api_key'], 'disconnect: the stored key is still forgotten' ); +has( $url, 'sendbeam_disconnected=constant', 'disconnect: the screen is told the live key is in wp-config.php' ); + // Nonce and capability. sb_connected_site(); $_POST = array(); $_REQUEST = array(); sb_run_admin_post( 'sendbeam_connect_disconnect' ); ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'disconnect: no nonce, no disconnect' ); -ok( 'sb_live_connectedconnectedxx' === sendbeam_settings()['api_key'], 'disconnect: a request with no nonce keeps the key' ); +ok( SENDBEAM_API_KEY === sendbeam_settings()['api_key'], 'disconnect: a request with no nonce keeps the key' ); sb_connected_site(); $GLOBALS['stub']['caps']['manage_options'] = false; sb_run_admin_post( 'sendbeam_connect_disconnect' ); ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'disconnect: the capability is required' ); -ok( 'sb_live_connectedconnectedxx' === sendbeam_settings()['api_key'], 'disconnect: a caller without the capability changes nothing' ); +ok( SENDBEAM_API_KEY === sendbeam_settings()['api_key'], 'disconnect: a caller without the capability changes nothing' ); // ── A blocked pop-up ─────────────────────────────────────────────────── sb_connect_reset(); From 270cb45596816686a705e25c205c1b30f6932bf8 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Wed, 23 Sep 2026 22:47:26 +0000 Subject: [PATCH 07/75] Say why the sending domain could not be set up --- includes/connect-status.php | 10 ++++++++++ includes/connect.php | 2 ++ includes/onboarding.php | 6 +++++- includes/settings.php | 1 + 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index 822907a..2d71f6e 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -105,6 +105,16 @@ function sendbeam_connect_normalise_status( $data ) { $out['workspace']['name'] = isset( $data['workspace']['name'] ) ? sanitize_text_field( (string) $data['workspace']['name'] ) : ''; } + // What SendBeam could not set up, in its words, so step 2 can say why. + $out['notes'] = array(); + if ( isset( $data['notes'] ) && is_array( $data['notes'] ) ) { + foreach ( array_slice( $data['notes'], 0, 3 ) as $note ) { + if ( is_string( $note ) && '' !== trim( $note ) ) { + $out['notes'][] = mb_substr( sanitize_text_field( $note ), 0, 200 ); + } + } + } + // A form ID that is not a form ID is dropped rather than stored: it would // become this site's default form and every embed would 404. if ( isset( $data['default_form'] ) && is_array( $data['default_form'] ) && sendbeam_is_form_id( isset( $data['default_form']['id'] ) ? $data['default_form']['id'] : null ) ) { diff --git a/includes/connect.php b/includes/connect.php index b9f360a..cfda09e 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -481,6 +481,7 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { // The form SendBeam made during consent becomes this site's default, but // only when the site has not already chosen one: a reconnect must not // quietly repoint an embed that is already live on a page. + $clean['sendbeam_connect_notes'] = isset( $status['notes'] ) && is_array( $status['notes'] ) ? array_values( $status['notes'] ) : array(); if ( '' === trim( (string) $clean['default_form'] ) && sendbeam_is_form_id( $status['default_form']['id'] ) ) { $clean['default_form'] = strtolower( $status['default_form']['id'] ); } @@ -603,6 +604,7 @@ function sendbeam_connect_disconnect() { $settings['api_key'] = ''; $settings['sendbeam_connected_via'] = ''; $settings['sendbeam_connect_workspace'] = ''; + $settings['sendbeam_connect_notes'] = array(); $settings['sendbeam_connect_granted'] = ''; $settings['sendbeam_mail_deferred'] = 0; update_option( 'sendbeam_settings', $settings ); diff --git a/includes/onboarding.php b/includes/onboarding.php index 6444e22..27bbc61 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -135,7 +135,11 @@ function sendbeam_setup_steps() { /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ $domain_detail = sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $domain['name'] ); } else { - $domain_detail = __( 'No sending domain yet. Add one under Sending in SendBeam.', 'sendbeam' ); + $notes = isset( $settings['sendbeam_connect_notes'] ) && is_array( $settings['sendbeam_connect_notes'] ) ? $settings['sendbeam_connect_notes'] : array(); + $domain_detail = $notes + /* translators: %s: SendBeam's own explanation, e.g. a plan cap on sending domains */ + ? sprintf( __( 'SendBeam could not set the domain up: %s Add it under Sending in SendBeam, then press Check now.', 'sendbeam' ), rtrim( (string) $notes[0], '.' ) . '.' ) + : __( 'No sending domain yet. Add one under Sending in SendBeam.', 'sendbeam' ); } $placed = ( $using_form || $using_popup ) ? sendbeam_form_is_placed() : false; diff --git a/includes/settings.php b/includes/settings.php index 77d5312..afb1733 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -243,6 +243,7 @@ function sendbeam_sanitize_settings( $input ) { sendbeam_flush_cache(); $out['sendbeam_connected_via'] = ''; $out['sendbeam_connect_workspace'] = ''; + $out['sendbeam_connect_notes'] = array(); // The permissions and the held-back site email belonged to the old // key. A pasted key's permissions are unknown, and claiming the old // ones would offer buttons that cannot work. From b7d181afb6ffce18a67504e7d8f210585a9dee97 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 05:54:11 +0000 Subject: [PATCH 08/75] Say which DNS records are live, one row at a time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two records right out of three looked exactly like none: the table showed what SendBeam wants and nothing about what is already there. The check already annotates each record, so the answer is carried through and shown per row — with never-checked kept apart from not-found, because telling someone their DNS is wrong when nothing has looked is its own bug. Every record is a CNAME under sendbeam.io, so the table still says nothing about priority: an always-empty Priority column is a box a site owner goes hunting for in their registrar. --- includes/connect-status.php | 13 ++++++++++++- includes/onboarding.php | 2 +- includes/screens.php | 28 +++++++++++++++++++++++++++- tests/smoke.php | 31 +++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index 2d71f6e..9fe144e 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -177,8 +177,14 @@ function sendbeam_connect_is_app_url( $url ) { * every field is plain text. Twenty is far more than any sending domain needs * and stops a malformed reply filling the screen. * + * `found` is the check's verdict for that one record, and it has three + * values rather than two: true, false, and never-checked. They are three + * different sentences to a site owner — "this one is live", "this one is not + * there yet", "nobody has looked" — and collapsing the last two into false + * tells someone their DNS is wrong when in fact nothing has been asked. + * * @param mixed $raw Records from the API. - * @return array + * @return array */ function sendbeam_connect_clean_records( $raw ) { if ( ! is_array( $raw ) ) { @@ -195,10 +201,15 @@ function sendbeam_connect_clean_records( $raw ) { if ( '' === $type || '' === $val ) { continue; } + $found = null; + if ( array_key_exists( 'found', $record ) && null !== $record['found'] ) { + $found = (bool) $record['found']; + } $out[] = array( 'type' => substr( $type, 0, 10 ), 'name' => $name, 'value' => $val, + 'found' => $found, ); } return $out; diff --git a/includes/onboarding.php b/includes/onboarding.php index 27bbc61..dfb7676 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -135,7 +135,7 @@ function sendbeam_setup_steps() { /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ $domain_detail = sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $domain['name'] ); } else { - $notes = isset( $settings['sendbeam_connect_notes'] ) && is_array( $settings['sendbeam_connect_notes'] ) ? $settings['sendbeam_connect_notes'] : array(); + $notes = isset( $settings['sendbeam_connect_notes'] ) && is_array( $settings['sendbeam_connect_notes'] ) ? $settings['sendbeam_connect_notes'] : array(); $domain_detail = $notes /* translators: %s: SendBeam's own explanation, e.g. a plan cap on sending domains */ ? sprintf( __( 'SendBeam could not set the domain up: %s Add it under Sending in SendBeam, then press Check now.', 'sendbeam' ), rtrim( (string) $notes[0], '.' ) . '.' ) diff --git a/includes/screens.php b/includes/screens.php index b7f34af..d5166f2 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -262,13 +262,21 @@ function sendbeam_overview_domain_panel( $status, $connected ) { /** * The DNS records, one row each, every value one click from the clipboard. * - * @param array $records Records. + * Every record is a CNAME under sendbeam.io, so there is no priority to enter + * anywhere and the table says nothing about one: a Priority column that is + * always empty is a box a site owner goes looking for in their registrar. + * + * The last column is the check's verdict for that row. Two records right out + * of three looks exactly like none until something says which is which. + * + * @param array $records Records. */ function sendbeam_domain_records_table( $records ) { echo '
    '; echo ''; echo ''; echo ''; + echo ''; echo ''; echo ''; foreach ( $records as $record ) { @@ -276,6 +284,7 @@ function sendbeam_domain_records_table( $records ) { echo ''; echo ''; echo ''; + echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped inside sendbeam_record_verdict(). printf( '', esc_attr( $record['value'] ), @@ -294,6 +303,23 @@ function sendbeam_domain_records_table( $records ) { echo '
    ' . esc_html__( 'Type', 'sendbeam' ) . '' . esc_html__( 'Name', 'sendbeam' ) . '' . esc_html__( 'Value', 'sendbeam' ) . '' . esc_html__( 'Found', 'sendbeam' ) . '' . esc_html__( 'Copy', 'sendbeam' ) . '
    ' . esc_html( $record['type'] ) . '' . esc_html( '' !== $record['name'] ? $record['name'] : '@' ) . '' . esc_html( $record['value'] ) . '' . sendbeam_record_verdict( isset( $record['found'] ) ? $record['found'] : null ) . '
    '; } +/** + * One record's verdict, in the three states the check actually has. + * + * @param bool|null $found True when the record is live, false when it is not + * there, null when nothing has looked yet. + * @return string Escaped HTML. + */ +function sendbeam_record_verdict( $found ) { + if ( null === $found ) { + return '' . esc_html__( 'Not checked yet', 'sendbeam' ) . ''; + } + if ( $found ) { + return '' . esc_html__( 'Found', 'sendbeam' ) . ''; + } + return '' . esc_html__( 'Not found yet', 'sendbeam' ) . ''; +} + /** * Step 3: the shortcode, for people who are not using the block editor. * diff --git a/tests/smoke.php b/tests/smoke.php index d378fcb..ea7a6ea 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1063,6 +1063,37 @@ function sb_v2_exchange( $body, $settings = array() ) { $st = sendbeam_connect_status(); ok( ! $st['ok'] && '' !== $st['error'], 'status: a 200 that is not JSON is treated as a failure, not as an empty workspace' ); +// ── Per-record verdict ───────────────────────────────────────────────── +// Every record SendBeam asks for is a CNAME under sendbeam.io, so there is no +// priority to enter and the table must not invent a column for one. What the +// table does need is the check's answer per row: two records right out of +// three looks exactly like none without it. +$v3_records = sendbeam_connect_normalise_status( + array( + 'domain' => array( + 'name' => 'harbourlane.co.uk', + 'records' => array( + array( 'type' => 'CNAME', 'name' => 'sb1._domainkey', 'value' => 'sb1.dkim.sendbeam.io', 'found' => true ), + array( 'type' => 'CNAME', 'name' => 'sb2._domainkey', 'value' => 'sb2.dkim.sendbeam.io', 'found' => false ), + array( 'type' => 'CNAME', 'name' => 'sbmail', 'value' => 'mail.sendbeam.io' ), + ), + ), + ) +)['domain']['records']; +ok( true === $v3_records[0]['found'], 'records: a record the check found reads true' ); +ok( false === $v3_records[1]['found'], 'records: a record the check did not find reads false, not missing' ); +ok( null === $v3_records[2]['found'], 'records: a record nothing has looked at reads null, not false' ); + +ob_start(); +sendbeam_domain_records_table( $v3_records ); +$v3_table = ob_get_clean(); +has( $v3_table, '>Found<', 'records: the table has a verdict column' ); +has( $v3_table, 'Not found yet', 'records: a record that is not in DNS says so on its own row' ); +has( $v3_table, 'Not checked yet', 'records: a record nothing has checked is not reported as wrong' ); +has( $v3_table, 'sb-tick', 'records: a record that is live is ticked' ); +lacks( $v3_table, 'Priority', 'records: there is no Priority column — every record is a CNAME' ); +lacks( $v3_table, 'priority', 'records: nothing on the table mentions priority' ); + // ── Check now ────────────────────────────────────────────────────────── /** Drive an admin-post handler that ends in a redirect. */ function sb_run_admin_post( $fn ) { From 90479d2df24321d048f7a1def4ba3fdd15c114e5 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 05:55:10 +0000 Subject: [PATCH 09/75] Say when the domain was last checked in the site's own words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The step printed the API's own timestamp — 2026-09-24T05:49:24.291+00:00 — which is not a time anybody reads and is not even the right hour for most of the people reading it. WordPress already knows the site's timezone and the formats its owner picked, so it does the rendering. Anything that will not parse is still shown as it arrived: an odd-looking date beats a step that quietly stops saying when it last ran. --- includes/connect-status.php | 28 ++++++++++++++++++++++++++++ includes/screens.php | 4 ++-- tests/smoke.php | 16 ++++++++++++++++ tests/wp-stubs.php | 8 ++++++++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index 9fe144e..bfc95c2 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -215,6 +215,34 @@ function sendbeam_connect_clean_records( $raw ) { return $out; } +/** + * A timestamp from the API, in the site's own words. + * + * SendBeam answers in ISO 8601 UTC, which is the right thing to send and the + * wrong thing to show: "2026-09-24T05:49:24.291+00:00" is not a time anybody + * reads, and it is not even the right hour for most of the people reading it. + * WordPress already knows the site's timezone and the formats its owner + * chose, so it does the rendering. + * + * Anything that will not parse is handed back untouched rather than dropped — + * a strange-looking date is better than a step that silently stops saying + * when it last ran. + * + * @param string $iso A timestamp from the API. + * @return string + */ +function sendbeam_connect_when( $iso ) { + $iso = trim( (string) $iso ); + if ( '' === $iso ) { + return ''; + } + $stamp = strtotime( $iso ); + if ( ! $stamp ) { + return $iso; + } + return wp_date( get_option( 'date_format', 'j F Y' ) . ', ' . get_option( 'time_format', 'g:i a' ), $stamp ); +} + /** * Remember a status for a minute. * diff --git a/includes/screens.php b/includes/screens.php index d5166f2..d348ee4 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -249,9 +249,9 @@ function sendbeam_overview_domain_panel( $status, $connected ) { if ( '' !== $domain['checked_at'] ) { echo '

    ' . esc_html( sprintf( - /* translators: %s: an ISO timestamp of the last DNS check */ + /* translators: %s: when the DNS was last checked, in the site's own date and time format */ __( 'Last checked %s.', 'sendbeam' ), - $domain['checked_at'] + sendbeam_connect_when( $domain['checked_at'] ) ) ) . '

    '; } diff --git a/tests/smoke.php b/tests/smoke.php index ea7a6ea..e7fc0f6 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1094,6 +1094,20 @@ function sb_v2_exchange( $body, $settings = array() ) { lacks( $v3_table, 'Priority', 'records: there is no Priority column — every record is a CNAME' ); lacks( $v3_table, 'priority', 'records: nothing on the table mentions priority' ); +// ── When the check last ran ──────────────────────────────────────────── +// The API answers in ISO 8601 UTC. That is the right thing to send and the +// wrong thing to print at somebody: it is not a time anybody reads, and it is +// not their hour either. +ok( '23 September 2026, 3:04 pm' === sendbeam_connect_when( '2026-09-23T15:04:05Z' ), 'checked at: an ISO timestamp is rendered in the site\'s own date and time format' ); +ok( '24 September 2026, 5:49 am' === sendbeam_connect_when( '2026-09-24T05:49:24.291+00:00' ), 'checked at: fractional seconds and an offset are understood too' ); +ok( '' === sendbeam_connect_when( '' ), 'checked at: nothing in, nothing out' ); +ok( 'whenever' === sendbeam_connect_when( 'whenever' ), 'checked at: something that will not parse is shown as it came rather than dropped' ); +update_option( 'date_format', 'Y/m/d' ); +update_option( 'time_format', 'H:i' ); +ok( '2026/09/23, 15:04' === sendbeam_connect_when( '2026-09-23T15:04:05Z' ), 'checked at: the formats the site owner chose are the ones used' ); +delete_option( 'date_format' ); +delete_option( 'time_format' ); + // ── Check now ────────────────────────────────────────────────────────── /** Drive an admin-post handler that ends in a redirect. */ function sb_run_admin_post( $fn ) { @@ -1390,6 +1404,8 @@ function sb_overview( $settings, $status, $get = array() ) { has( $ov, '10 feedback-smtp.eu-west-1.amazonses.com', 'overview: every record is shown' ); has( $ov, 'data-copy="10 feedback-smtp.eu-west-1.amazonses.com"', 'overview: each record value has its own Copy button' ); has( $ov, 'Check now', 'overview: the domain can be re-checked without leaving wp-admin' ); +has( $ov, 'Last checked 23 September 2026, 3:04 pm', 'overview: the last check is a time the site owner can read, in their own format' ); +lacks( $ov, '2026-09-23T15:04:05Z', 'overview: the raw ISO timestamp is never printed at anybody' ); has( $ov, 'value="sendbeam_domain_check"', 'overview: Check now posts to the check handler' ); has( $ov, 'nonce:sendbeam_domain_check', 'overview: Check now carries a nonce' ); has( $ov, 'Set up DNS automatically', 'overview: the registrar one-click button is offered' ); diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 0627d3d..ca6369c 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -189,6 +189,14 @@ function wp_unschedule_hook( $hook ) { } function esc_attr__( $s, $d = null ) { return esc_attr( $s ); } +/** + * Dates. The real wp_date() renders in the site's timezone; the stub uses + * UTC, which is what the tests assert against, and the plugin's job is only + * to hand WordPress a format and a timestamp rather than print the raw ISO + * string it got from the API. + */ +function wp_date( $format, $timestamp = null, $timezone = null ) { return gmdate( (string) $format, null === $timestamp ? time() : (int) $timestamp ); } + /** * Enough of the Settings API to render a tab. The fields themselves are * exercised elsewhere; what these let the smoke test see is the *screen* — From 6574c3d593ea6a0e3fd702599c90e82ea47c8e34 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 05:58:05 +0000 Subject: [PATCH 10/75] Say why there is no sending domain, in SendBeam's own words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A null domain meant four different things — the box was never ticked, the key predates domains being readable, the key has no site host, the row was removed by hand — and step 2 could only answer "not set up" to all four. The answer now carries a state and a sentence, and every word step 2 says comes from it. That also fixes what the owner found on the test site: the step read what this site remembered granting, and a key pasted by hand records nothing, so it announced a missing permission while printing that very domain's DNS records directly underneath. What the key can do is whatever the answer says it did. The domain shown is always the one in the answer. The sending host is the owner's choice at consent time and is often not this site's domain at all. --- includes/connect-status.php | 52 ++++++++++++++++++++ includes/onboarding.php | 97 ++++++++++++++++++++++++++++--------- includes/screens.php | 21 +++++++- tests/smoke.php | 96 ++++++++++++++++++++++++++++++++++++ 4 files changed, 241 insertions(+), 25 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index bfc95c2..757aa45 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -59,6 +59,15 @@ function sendbeam_connect_empty_status() { return array( 'ok' => false, 'error' => '', + 'notes' => array(), + // Why there is no sending domain, when there is none. `domain` being + // null meant four different things before this — the box was never + // ticked, the key is too old to read domains, the key has no site + // host, the row was deleted by hand — and the screen could only say + // "not set up" to all four, which is the one answer that helps + // nobody. + 'domain_state' => '', + 'domain_note' => '', 'workspace' => array( 'id' => '', 'name' => '', @@ -122,6 +131,16 @@ function sendbeam_connect_normalise_status( $data ) { $out['default_form']['name'] = isset( $data['default_form']['name'] ) ? sanitize_text_field( (string) $data['default_form']['name'] ) : ''; } + $out['domain_state'] = sendbeam_connect_clean_domain_state( isset( $data['domain_state'] ) ? $data['domain_state'] : '' ); + if ( isset( $data['domain_note'] ) && is_string( $data['domain_note'] ) ) { + $out['domain_note'] = mb_substr( sanitize_text_field( $data['domain_note'] ), 0, 200 ); + } + // v2 said the same thing in an array called `notes`. A site talking to a + // SendBeam that predates `domain_note` still gets its sentence. + if ( '' === $out['domain_note'] && $out['notes'] ) { + $out['domain_note'] = (string) $out['notes'][0]; + } + if ( isset( $data['domain'] ) && is_array( $data['domain'] ) && ! empty( $data['domain']['name'] ) ) { $out['domain']['name'] = sanitize_text_field( (string) $data['domain']['name'] ); $out['domain']['verified'] = ! empty( $data['domain']['verified'] ); @@ -147,9 +166,42 @@ function sendbeam_connect_normalise_status( $data ) { $out['sender']['from_email'] = ( $email && is_email( $email ) ) ? $email : ''; } + $out['domain_state'] = sendbeam_connect_domain_state( $out ); + return $out; } +/** + * The states the contract defines, and nothing else. + * + * @param mixed $raw Value from the API. + * @return string Empty when it is not one of them. + */ +function sendbeam_connect_clean_domain_state( $raw ) { + $known = array( 'ok', 'not_granted', 'no_permission', 'no_site', 'not_found', 'managed_host', 'unavailable' ); + $raw = is_string( $raw ) ? strtolower( trim( $raw ) ) : ''; + return in_array( $raw, $known, true ) ? $raw : ''; +} + +/** + * A status's domain state, worked out when the answer did not carry one. + * + * A cached body written before this field existed, or an older SendBeam, + * would otherwise leave every sentence on step 2 blank. A domain that came + * back is `ok`; no domain and no reason is `not_found`, which is both the + * commonest case and the one whose sentence is safe to show for any of them. + * + * @param array $status Normalised status. + * @return string + */ +function sendbeam_connect_domain_state( $status ) { + $state = isset( $status['domain_state'] ) ? sendbeam_connect_clean_domain_state( $status['domain_state'] ) : ''; + if ( '' !== $state ) { + return $state; + } + return ( isset( $status['domain']['name'] ) && '' !== $status['domain']['name'] ) ? 'ok' : 'not_found'; +} + /** * Is this an https URL on the SendBeam app's own host? * diff --git a/includes/onboarding.php b/includes/onboarding.php index dfb7676..38961f4 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -94,6 +94,29 @@ function sendbeam_form_is_placed( $force = false ) { return (bool) $found; } +/** + * What step 2 says once there really is a sending domain. + * + * The name is always the one the answer carried, never one derived from + * site_url: the owner chooses the sending host at consent time and it is + * often not this site's domain at all. + * + * @param string $name The sending domain, from the response. + * @param bool $verified Whether SendBeam has seen its records. + * @return string + */ +function sendbeam_domain_sentence( $name, $verified ) { + if ( '' === (string) $name ) { + return __( 'No sending domain is set up for this site. Add one under Settings → Domains in SendBeam.', 'sendbeam' ); + } + if ( $verified ) { + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + return sprintf( __( '%s is verified. Email from this site will be sent from your own domain.', 'sendbeam' ), $name ); + } + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + return sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $name ); +} + /** * How far through setup are they? Drives the checklist on the settings page. * @@ -124,22 +147,43 @@ function sendbeam_setup_steps() { $domain = $status['domain']; $verified = ! empty( $domain['verified'] ); + /* + * Everything step 2 says comes out of the answer SendBeam just gave, and + * nothing out of what this site remembers granting. The two disagree more + * often than they look like they would — a key pasted by hand has no + * recorded permissions at all, and the step used to tell those sites they + * had no permission to read a domain while printing that domain's DNS + * records directly underneath. + */ + $state = $connected ? sendbeam_connect_domain_state( $status ) : ''; + $note = isset( $status['domain_note'] ) ? trim( (string) $status['domain_note'] ) : ''; + $domain_reconnect = false; + if ( ! $connected ) { $domain_detail = __( 'Connect the site first and SendBeam will set the domain up and show you the records.', 'sendbeam' ); - } elseif ( ! sendbeam_connect_granted( 'domain' ) ) { - $domain_detail = __( 'This site\'s key was not given permission to read your sending domain. Add the domain under Sending in SendBeam, or reconnect and tick the domain box.', 'sendbeam' ); - } elseif ( $verified ) { - /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ - $domain_detail = sprintf( __( '%s is verified. Email from this site will be sent from your own domain.', 'sendbeam' ), $domain['name'] ); - } elseif ( '' !== $domain['name'] ) { - /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ - $domain_detail = sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $domain['name'] ); + } elseif ( 'not_granted' === $state ) { + $domain_detail = __( 'You did not allow SendBeam to set up a sending domain, so this site has none.', 'sendbeam' ); + $domain_reconnect = true; + } elseif ( 'no_permission' === $state ) { + $domain_detail = __( 'This connection was made before domains could be read, so this site cannot see its sending domain.', 'sendbeam' ); + $domain_reconnect = true; + } elseif ( 'managed_host' === $state ) { + $domain_detail = '' !== $note + ? $note + : __( 'This site runs on a hosting company\'s own domain, so mail cannot be sent from it. Add a domain you own under Settings → Domains in SendBeam.', 'sendbeam' ); + } elseif ( 'unavailable' === $state ) { + $domain_detail = __( 'SendBeam could not be reached; showing the last known state.', 'sendbeam' ); + if ( '' !== $domain['name'] ) { + $domain_detail .= ' ' . sendbeam_domain_sentence( $domain['name'], $verified ); + } + } elseif ( 'no_site' === $state || 'not_found' === $state ) { + $domain_detail = __( 'No sending domain is set up for this site.', 'sendbeam' ); + if ( '' !== $note ) { + $domain_detail .= ' ' . rtrim( $note, '.' ) . '.'; + } + $domain_detail .= ' ' . __( 'Add one under Settings → Domains in SendBeam.', 'sendbeam' ); } else { - $notes = isset( $settings['sendbeam_connect_notes'] ) && is_array( $settings['sendbeam_connect_notes'] ) ? $settings['sendbeam_connect_notes'] : array(); - $domain_detail = $notes - /* translators: %s: SendBeam's own explanation, e.g. a plan cap on sending domains */ - ? sprintf( __( 'SendBeam could not set the domain up: %s Add it under Sending in SendBeam, then press Check now.', 'sendbeam' ), rtrim( (string) $notes[0], '.' ) . '.' ) - : __( 'No sending domain yet. Add one under Sending in SendBeam.', 'sendbeam' ); + $domain_detail = sendbeam_domain_sentence( $domain['name'], $verified ); } $placed = ( $using_form || $using_popup ) ? sendbeam_form_is_placed() : false; @@ -154,10 +198,13 @@ function sendbeam_setup_steps() { $form_detail = __( 'Choose a signup, contact or pop-up form below.', 'sendbeam' ); } + $mail_reconnect = false; + if ( $using_mail ) { $mail_detail = __( 'On. Send yourself a test to be sure.', 'sendbeam' ); } elseif ( $connected && ! sendbeam_connect_granted( 'transactional:send' ) ) { - $mail_detail = __( 'This site\'s key was not given permission to send your site\'s email. Reconnect and tick that box to use it.', 'sendbeam' ); + $mail_detail = __( 'This site\'s key was not given permission to send your site\'s email. Reconnect and tick that box to use it.', 'sendbeam' ); + $mail_reconnect = true; } elseif ( ! $verified ) { $mail_detail = __( 'Waiting on step 2: this site\'s email can only go out once the sending domain is verified.', 'sendbeam' ); } else { @@ -175,11 +222,12 @@ function sendbeam_setup_steps() { 'target' => sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', ), array( - 'key' => 'domain', - 'done' => $verified, - 'label' => __( 'Verify your sending domain', 'sendbeam' ), - 'detail' => $domain_detail, - 'target' => sendbeam_app_url() . '/settings/sending', + 'key' => 'domain', + 'done' => $verified, + 'label' => __( 'Verify your sending domain', 'sendbeam' ), + 'detail' => $domain_detail, + 'target' => sendbeam_app_url() . '/settings/domains', + 'reconnect' => $domain_reconnect, ), array( 'key' => 'form', @@ -189,11 +237,12 @@ function sendbeam_setup_steps() { 'target' => sendbeam_tab_url( 'forms' ), ), array( - 'key' => 'mail', - 'done' => $using_mail, - 'label' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), - 'detail' => $mail_detail, - 'target' => sendbeam_tab_url( 'mail' ), + 'key' => 'mail', + 'done' => $using_mail, + 'label' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), + 'detail' => $mail_detail, + 'target' => sendbeam_tab_url( 'mail' ), + 'reconnect' => $mail_reconnect, ), ); } diff --git a/includes/screens.php b/includes/screens.php index d348ee4..eef3ff2 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -192,12 +192,31 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { * @param bool $connected Whether the key works. */ function sendbeam_overview_domain_panel( $status, $connected ) { - if ( ! $connected || '' === $status['domain']['name'] ) { + if ( ! $connected ) { return; } $domain = $status['domain']; $verified = ! empty( $domain['verified'] ); + $state = sendbeam_connect_domain_state( $status ); + + /* + * No domain, so no records and nothing to check — the step's own sentence + * has already said why. What it cannot do is hand over the page where the + * owner fixes it, so that is all this panel is in that case. + */ + if ( '' === $domain['name'] ) { + if ( in_array( $state, array( 'no_site', 'not_found', 'managed_host' ), true ) ) { + echo '
    '; + printf( + '%s', + esc_url( sendbeam_app_url() . '/settings/domains' ), + esc_html__( 'Open Settings → Domains', 'sendbeam' ) + ); + echo '
    '; + } + return; + } echo '
    '; diff --git a/tests/smoke.php b/tests/smoke.php index e7fc0f6..d02669b 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1108,6 +1108,87 @@ function sb_v2_exchange( $body, $settings = array() ) { delete_option( 'date_format' ); delete_option( 'time_format' ); +// ── Why there is no sending domain ───────────────────────────────────── +// `domain: null` meant four different things and the screen could only say +// "not set up" to all four. The state says which, and every sentence on step +// 2 now comes out of the answer rather than out of what this site remembers +// granting — the two disagree on any site whose key was pasted by hand. +ok( 'not_granted' === sendbeam_connect_normalise_status( array( 'domain_state' => 'not_granted' ) )['domain_state'], 'domain state: the state comes back as SendBeam sent it' ); +ok( '' === sendbeam_connect_clean_domain_state( 'made_up' ), 'domain state: a state that is not in the contract is dropped' ); +ok( 'ok' === sendbeam_connect_domain_state( sendbeam_connect_normalise_status( array( 'domain' => array( 'name' => 'harbourlane.co.uk' ) ) ) ), 'domain state: an answer with a domain and no state reads as ok' ); +ok( 'not_found' === sendbeam_connect_domain_state( sendbeam_connect_normalise_status( array( 'workspace' => array( 'id' => 'ws_1' ) ) ) ), 'domain state: an answer with neither falls back to not_found rather than to nothing' ); +ok( 'The domain is on another workspace.' === sendbeam_connect_normalise_status( array( 'domain_state' => 'not_found', 'domain_note' => 'The domain is on another workspace.' ) )['domain_note'], 'domain state: the note is one sentence for the owner' ); +ok( 'Your plan allows one sending domain.' === sendbeam_connect_normalise_status( array( 'domain_state' => 'not_found', 'notes' => array( 'Your plan allows one sending domain.' ) ) )['domain_note'], 'domain state: a SendBeam that predates domain_note still gets its sentence across' ); + +/** + * The checklist sentences for one status body, keyed by step. + * + * @param array $status Status payload as the API would send it. + * @param array $settings Saved settings. + * @return array + */ +function sb_step_details( $status, $settings = null ) { + $GLOBALS['stub']['caps']['manage_options'] = true; + update_option( 'sendbeam_settings', null === $settings ? array( 'api_key' => 'sb_live_connectedconnectedxx', 'sendbeam_connected_via' => 'connect', 'sendbeam_connect_granted' => 'forms,transactional:send,domain' ) : $settings ); + set_transient( 'sendbeam_connection', array( 'state' => '' === (string) ( sendbeam_settings()['api_key'] ) ? 'none' : 'ok', 'message' => '', 'count' => 1 ) ); + sendbeam_connect_cache_status( sendbeam_connect_normalise_status( $status ) ); + $out = array(); + foreach ( sendbeam_setup_steps() as $step ) { + $out[ $step['key'] ] = $step['detail']; + $out[ $step['key'] . ':reconnect' ] = ! empty( $step['reconnect'] ) ? '1' : ''; + } + return $out; +} + +$sb_dom = sb_step_details( array( 'domain_state' => 'not_granted' ) ); +has( $sb_dom['domain'], 'You did not allow SendBeam to set up a sending domain', 'domain state: not_granted says the box was never ticked' ); +ok( '1' === $sb_dom['domain:reconnect'], 'domain state: not_granted offers a way to reconnect' ); + +$sb_dom = sb_step_details( array( 'domain_state' => 'no_permission' ) ); +has( $sb_dom['domain'], 'made before domains could be read', 'domain state: no_permission says the key is too old' ); +ok( '1' === $sb_dom['domain:reconnect'], 'domain state: no_permission offers a way to reconnect' ); + +$sb_dom = sb_step_details( array( 'domain_state' => 'no_site' ) ); +has( $sb_dom['domain'], 'No sending domain is set up for this site', 'domain state: no_site says there is no domain' ); +has( $sb_dom['domain'], 'Settings → Domains', 'domain state: no_site says where to add one' ); + +$sb_dom = sb_step_details( array( 'domain_state' => 'not_found', 'domain_note' => 'It was removed from the workspace.' ) ); +has( $sb_dom['domain'], 'It was removed from the workspace.', 'domain state: not_found carries SendBeam\'s own reason' ); + +$sb_dom = sb_step_details( array( 'domain_state' => 'managed_host', 'domain_note' => 'example.wordpress.com is run by a hosting company; mail cannot be sent from it.' ) ); +has( $sb_dom['domain'], 'run by a hosting company', 'domain state: managed_host is the note, in SendBeam\'s words' ); + +$sb_dom = sb_step_details( array( 'domain_state' => 'unavailable', 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true ) ) ); +has( $sb_dom['domain'], 'showing the last known state', 'domain state: unavailable says the answer is old' ); +has( $sb_dom['domain'], 'harbourlane.co.uk is verified', 'domain state: unavailable still shows what was last known' ); +$sb_dom = sb_step_details( array( 'domain_state' => 'unavailable' ) ); +has( $sb_dom['domain'], 'showing the last known state', 'domain state: unavailable with nothing cached is the sentence on its own' ); +lacks( $sb_dom['domain'], 'is verified', 'domain state: unavailable claims nothing it does not know' ); + +// The defect this replaced: a key pasted by hand records no permissions, so +// the step told those sites they had no permission to read a domain — while +// the records for that very domain rendered underneath. +$sb_pasted = array( 'api_key' => 'sb_live_pastedpastedpasted' ); +$sb_dom = sb_step_details( + array( + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array( array( 'type' => 'CNAME', 'name' => 'sb1._domainkey', 'value' => 'sb1.dkim.sendbeam.io', 'found' => false ) ) ), + ), + $sb_pasted +); +has( $sb_dom['domain'], 'Add these records to the DNS for harbourlane.co.uk', 'domain state: a pasted key that can read the domain is simply ok' ); +lacks( $sb_dom['domain'], 'not given permission', 'domain state: nothing claims a permission is missing while the domain is on screen' ); + +// The sending host is the owner's choice at consent time and need not be +// this site's domain at all. Whatever the answer says is what is shown. +$GLOBALS['stub']['site_url'] = 'https://www.example-site.test'; +$sb_dom = sb_step_details( array( 'domain' => array( 'name' => 'mail.brand.co.uk', 'verified' => true ) ) ); +has( $sb_dom['domain'], 'mail.brand.co.uk is verified', 'domain state: the domain shown is the one SendBeam reported' ); +lacks( $sb_dom['domain'], 'example-site.test', 'domain state: the step never derives the host from site_url' ); +unset( $GLOBALS['stub']['site_url'] ); +update_option( 'sendbeam_settings', array() ); +sendbeam_connect_forget_status(); +delete_transient( 'sendbeam_connection' ); + // ── Check now ────────────────────────────────────────────────────────── /** Drive an admin-post handler that ends in a redirect. */ function sb_run_admin_post( $fn ) { @@ -1451,6 +1532,21 @@ function sb_overview( $settings, $status, $get = array() ) { has( $ov, 'Send a test email', 'overview: site email that is on offers the test send' ); has( $ov, 'nonce:sendbeam_test_mail', 'overview: the test send carries a nonce' ); +// A site connected with a key pasted by hand: no recorded permissions, but a +// domain it can plainly read. The screen must not print a table of records +// under a sentence saying it has no permission to read them. +$ov = sb_overview( array( 'api_key' => 'sb_live_pastedpastedpasted' ), $sb_unverified ); +has( $ov, 'v=sb1 k=abc', 'overview: a pasted key still gets its DNS records' ); +lacks( $ov, 'not given permission to read', 'overview: nothing claims a missing permission while the records are on screen' ); + +// No domain at all: no table, no Check now, and the page where it is fixed. +$sb_nodomain = array( 'workspace' => array( 'id' => 'ws_1', 'name' => 'Harbour Lane' ), 'domain_state' => 'no_site' ); +$ov = sb_overview( $sb_connected, $sb_nodomain ); +has( $ov, 'No sending domain is set up for this site', 'overview: a site with no domain is told so once' ); +has( $ov, '/settings/domains', 'overview: and handed the page where it is added' ); +lacks( $ov, 'table class="sb-table sb-dns"', 'overview: no records table for a domain that does not exist' ); +lacks( $ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); + // Never connected: the Connect button, and no checklist that pretends to know anything. $ov = sb_overview( array(), array() ); has( $ov, 'Connect SendBeam', 'overview: an unconnected site gets the button' ); From b44197e87094bdc82eb2b57374e24c9ddc81e74c Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 05:59:53 +0000 Subject: [PATCH 11/75] Offer a way back into consent that is not "disconnect first" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un-ticking a permission at the consent page, or leaving the sending domain box alone, could only be undone by disconnecting and connecting again — a frightening instruction to give someone whose site is already working, and one that revokes a key for no reason. Any step whose sentence names a permission this site was never given now ends in a link that starts the same Connect flow with every box preselected, and the connected card carries a plain Reconnect beside Disconnect, asking for exactly what the key already holds. The key that comes back replaces the one this site has, by the ordinary return path. A link cannot post an array, so the scopes travel as a csv and are cleaned by the same function the panel's checkboxes go through. Asking for a permission is still not being given it: the consent page decides. --- includes/connect.php | 60 ++++++++++++++++++++++++++++++++++++++++---- includes/screens.php | 28 +++++++++++++++++++++ tests/smoke.php | 40 +++++++++++++++++++++++++++++ tests/wp-stubs.php | 1 + 4 files changed, 124 insertions(+), 5 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index cfda09e..e34ee81 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -152,7 +152,7 @@ function sendbeam_connect_transient_key( $user_id ) { } /** - * The pop-up URL, exactly as the contract specifies it. + * The consent page's URL on sendbeam.io, exactly as the contract specifies it. * * Nothing here is left to add_query_arg(), which does not encode: every value * is rawurlencode()d first. A site name with a space or an ampersand would @@ -163,7 +163,7 @@ function sendbeam_connect_transient_key( $user_id ) { * @param string $state The CSRF token. * @return string Empty when this site cannot be connected (bad origin). */ -function sendbeam_connect_start_url( $scopes, $state ) { +function sendbeam_connect_consent_url( $scopes, $state ) { $origin = sendbeam_connect_site_origin(); if ( '' === $origin || ! sendbeam_connect_origin_ok( $origin ) ) { return ''; @@ -190,6 +190,47 @@ function sendbeam_connect_start_url( $scopes, $state ) { ); } +/** + * The URL that starts the Connect flow from a link rather than the panel. + * + * Reconnecting is the answer to more than one dead end — a permission + * un-ticked at consent, a sending domain nobody was allowed to set up, a key + * that predates a permission existing — and every one of them used to end in + * "disconnect and connect again", which is a frightening instruction to give + * someone whose site is already working. A link is not a form, so the scopes + * it asks for are decided here: everything, or exactly what this site's key + * already carries. + * + * @param bool $all_scopes True to preselect every permission. False asks for + * the ones the key already holds, which is what a + * plain Reconnect means; a key pasted by hand records + * none, so that falls back to everything too. + * @return string + */ +function sendbeam_connect_start_url( $all_scopes = false ) { + $scopes = array_keys( sendbeam_connect_scopes() ); + + if ( ! $all_scopes ) { + $settings = sendbeam_settings(); + $granted = array_filter( array_map( 'trim', explode( ',', (string) $settings['sendbeam_connect_granted'] ) ) ); + $known = array_values( array_intersect( $scopes, $granted ) ); + if ( $known ) { + $scopes = $known; + } + } + + return wp_nonce_url( + add_query_arg( + array( + 'action' => 'sendbeam_connect_start', + 'sendbeam_scopes' => rawurlencode( implode( ',', $scopes ) ), + ), + admin_url( 'admin-post.php' ) + ), + 'sendbeam_connect_start' + ); +} + /** * Where SendBeam sends the pop-up back to. Always on this site's own origin. * @@ -233,9 +274,18 @@ function sendbeam_connect_start() { } check_admin_referer( 'sendbeam_connect_start' ); + /* + * The panel posts a checkbox per scope; a Reconnect link carries the same + * list as a csv, because a link cannot post an array. Both are cleaned by + * the same function, and the consent page is the real gate either way — + * asking for a permission is not being given it. + */ $raw = array(); - if ( isset( $_POST['sendbeam_scopes'] ) && is_array( $_POST['sendbeam_scopes'] ) ) { - $raw = array_map( 'sanitize_text_field', wp_unslash( $_POST['sendbeam_scopes'] ) ); + if ( isset( $_REQUEST['sendbeam_scopes'] ) ) { + $asked = wp_unslash( $_REQUEST['sendbeam_scopes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitised on the next two lines, as an array or as a string. + $raw = is_array( $asked ) + ? array_map( 'sanitize_text_field', $asked ) + : array_map( 'trim', explode( ',', sanitize_text_field( $asked ) ) ); } $scopes = sendbeam_connect_clean_scopes( $raw ); @@ -245,7 +295,7 @@ function sendbeam_connect_start() { // Built before anything is remembered: a site that cannot be connected at // all should not be left holding a pending connection it can never finish. - $url = sendbeam_connect_start_url( $scopes, $state ); + $url = sendbeam_connect_consent_url( $scopes, $state ); if ( '' === $url ) { wp_die( esc_html__( 'This site has no https address, so it cannot be connected to SendBeam. Add a certificate, or paste an API key instead.', 'sendbeam' ) ); } diff --git a/includes/screens.php b/includes/screens.php index eef3ff2..5780a4a 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -177,6 +177,22 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { sendbeam_overview_mail_panel( $status, $connected ); break; } + + /* + * A step whose sentence names a permission this site was never given ends + * in the same place: the consent page, with that box ticked. The link + * starts the ordinary Connect flow with everything preselected, and the + * key that comes back replaces the one this site holds. + */ + if ( $connected && ! empty( $step['reconnect'] ) ) { + echo '
    '; + printf( + '%s', + esc_url( sendbeam_connect_start_url( true ) ), + esc_html__( 'Reconnect with more permissions', 'sendbeam' ) + ); + echo '
    '; + } } /** @@ -463,6 +479,18 @@ function sendbeam_connect_connected_panel( $status = null ) { echo '
    '; wp_nonce_field( 'sendbeam_disconnect' ); echo ''; + + /* + * Reconnect sits beside Disconnect because it is what people reach for + * Disconnect to do: change workspace, pick a different sending host, + * re-approve something. It asks for the permissions this site already + * has, so the consent page comes up saying what is already true. + */ + printf( + '%s ', + esc_url( sendbeam_connect_start_url() ), + esc_html__( 'Reconnect', 'sendbeam' ) + ); printf( '', esc_html__( 'Disconnect', 'sendbeam' ) diff --git a/tests/smoke.php b/tests/smoke.php index d02669b..39e2e3c 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1189,6 +1189,36 @@ function sb_step_details( $status, $settings = null ) { sendbeam_connect_forget_status(); delete_transient( 'sendbeam_connection' ); +// ── Reconnecting ─────────────────────────────────────────────────────── +// Un-ticking a permission at consent used to be fixable only by disconnect +// and connect again, which is a frightening thing to tell someone whose site +// is working. A link starts the same flow with the boxes already ticked. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_connectedconnectedxx', 'sendbeam_connect_granted' => 'forms,contacts:write' ) ); +$sb_all = sendbeam_connect_start_url( true ); +has( $sb_all, 'action=sendbeam_connect_start', 'reconnect: the link starts the ordinary Connect flow' ); +has( $sb_all, 'nonce:sendbeam_connect_start', 'reconnect: the link carries the same nonce the panel does' ); +has( rawurldecode( $sb_all ), 'forms,contacts:write,transactional:send,ecommerce,domain', 'reconnect: with more permissions preselects every scope' ); +$sb_same = sendbeam_connect_start_url(); +has( rawurldecode( $sb_same ), 'sendbeam_scopes=forms,contacts:write', 'reconnect: a plain Reconnect asks for what the key already has' ); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_pastedpastedpasted' ) ); +has( rawurldecode( sendbeam_connect_start_url() ), 'ecommerce', 'reconnect: a key that recorded no permissions falls back to asking for all of them' ); + +// The link's csv reaches the consent page as the panel's checkboxes would. +sb_connect_reset(); +$_GET = array( 'sendbeam_scopes' => 'forms,domain,not-a-scope', '_wpnonce' => 'nonce:sendbeam_connect_start' ); +$_REQUEST = $_GET; +try { + sendbeam_connect_start(); +} catch ( SendBeamStubExit $e ) { + $GLOBALS['stub']['exit'] = $e->getMessage(); +} +parse_str( (string) wp_parse_url( (string) $GLOBALS['stub']['redirect']['url'], PHP_URL_QUERY ), $sb_rq ); +ok( 'forms,domain' === ( $sb_rq['scopes'] ?? '' ), 'reconnect: the link\'s scopes are cleaned exactly as the panel\'s are' ); +ok( 0 === get_transient( 'sendbeam_connect_7' )['popup'], 'reconnect: a link is not a pop-up, so the return page offers a way back' ); +sb_connect_reset(); +update_option( 'sendbeam_settings', array() ); + // ── Check now ────────────────────────────────────────────────────────── /** Drive an admin-post handler that ends in a redirect. */ function sb_run_admin_post( $fn ) { @@ -1532,6 +1562,16 @@ function sb_overview( $settings, $status, $get = array() ) { has( $ov, 'Send a test email', 'overview: site email that is on offers the test send' ); has( $ov, 'nonce:sendbeam_test_mail', 'overview: the test send carries a nonce' ); +// The steps that name a missing permission offer the way out of it. +$sb_nodomain_scope = $sb_connected; +$sb_nodomain_scope['sendbeam_connect_granted'] = 'forms,transactional:send'; +$ov = sb_overview( $sb_nodomain_scope, array( 'workspace' => array( 'id' => 'ws_1' ), 'domain_state' => 'not_granted' ) ); +has( $ov, 'Reconnect with more permissions', 'overview: a step that names a missing permission offers to reconnect' ); +has( $ov, 'action=sendbeam_connect_start', 'overview: the reconnect link starts the Connect flow' ); +$ov = sb_overview( $sb_connected, $sb_verified ); +lacks( $ov, 'Reconnect with more permissions', 'overview: a step with nothing missing does not offer it' ); +has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); + // A site connected with a key pasted by hand: no recorded permissions, but a // domain it can plainly read. The screen must not print a table of records // under a sentence saying it has no permission to read them. diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index ca6369c..270b637 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -217,6 +217,7 @@ function wp_get_current_user() { function did_action( $tag ) { return empty( $GLOBALS['stub']['did'][ $tag ] ) ? 0 : 1; } function wp_doing_ajax() { return ! empty( $GLOBALS['stub']['ajax'] ); } function wp_verify_nonce( $nonce, $action = -1 ) { return 'nonce:' . $action === $nonce ? 1 : false; } +function wp_nonce_url( $url, $action = -1, $name = '_wpnonce' ) { return add_query_arg( $name, 'nonce:' . $action, $url ); } function wp_nonce_field( $action = -1, $name = '_wpnonce' ) { echo ''; } function get_post_meta( $id, $key = '', $single = false ) { return isset( $GLOBALS['stub']['postmeta'][ $id ][ $key ] ) ? $GLOBALS['stub']['postmeta'][ $id ][ $key ] : ( $single ? '' : array() ); } function update_post_meta( $id, $key, $value ) { $GLOBALS['stub']['postmeta'][ $id ][ $key ] = $value; return true; } From a55c3d19df75cec820c628e40608929f65a06584 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:02:08 +0000 Subject: [PATCH 12/75] Put back what Connect filled in, and nothing else Disconnecting forgot the key and left the rest of Connect's work sitting in the site: a default form belonging to a workspace this site no longer has a key for, so every embed 404s without a word, and a From address on a domain it can no longer send from. Each setting Connect fills is now recorded as it is filled, and Disconnect puts back exactly that list. A form or a sender the owner chose is theirs and is left alone; saving the tab by hand takes those settings off the list for good, and so does pasting a different key. The workspace side is untouched on purpose, and the confirmation now says so: disconnecting one site is not a reason to dismantle a workspace other sites may be sending from. --- includes/connect-status.php | 19 +++++++++++++ includes/connect.php | 41 ++++++++++++++++++++++++++- includes/helpers.php | 5 ++++ includes/screens.php | 2 +- includes/settings.php | 19 +++++++++++++ tests/smoke.php | 55 +++++++++++++++++++++++++++++++++++++ 6 files changed, 139 insertions(+), 2 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index 757aa45..ad8e8de 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -449,14 +449,33 @@ function sendbeam_handle_mail_switch_on() { function sendbeam_connect_enable_mail( $status ) { $settings = sendbeam_settings(); + /* + * A held-back switch-on is Connect finishing the job consent started, so + * what it fills goes on the same list the exchange writes and Disconnect + * puts back. Pressing **Switch on** by hand is the owner's own decision + * and is recorded as nobody's but theirs. + */ + $connects = ! empty( $settings['sendbeam_mail_deferred'] ); + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + + if ( empty( $settings['mail_enabled'] ) && $connects ) { + $filled[] = 'mail_enabled'; + } $settings['mail_enabled'] = 1; $settings['sendbeam_mail_deferred'] = 0; if ( '' === trim( (string) $settings['mail_from_name'] ) && '' !== $status['sender']['from_name'] ) { $settings['mail_from_name'] = $status['sender']['from_name']; + if ( $connects ) { + $filled[] = 'mail_from_name'; + } } if ( '' === trim( (string) $settings['mail_from_email'] ) && '' !== $status['sender']['from_email'] ) { $settings['mail_from_email'] = $status['sender']['from_email']; + if ( $connects ) { + $filled[] = 'mail_from_email'; + } } + $settings['sendbeam_connect_filled'] = array_values( array_unique( $filled ) ); update_option( 'sendbeam_settings', $settings ); } diff --git a/includes/connect.php b/includes/connect.php index e34ee81..3247056 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -524,6 +524,17 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { $granted = sendbeam_connect_granted_from_response( $data ); $status = sendbeam_connect_normalise_status( $data ); + /* + * Everything below fills a setting the site had left empty, and Disconnect + * has to be able to put those back without touching anything the owner + * chose. So each one is recorded as it is filled. A reconnect adds to the + * list rather than replacing it — the first connection's work is still + * this plugin's to undo — and saving the tab by hand takes a setting off + * it again, in sendbeam_sanitize_settings(). + */ + $before = sendbeam_settings(); + $filled = isset( $before['sendbeam_connect_filled'] ) && is_array( $before['sendbeam_connect_filled'] ) ? $before['sendbeam_connect_filled'] : array(); + $clean['sendbeam_connected_via'] = 'connect'; $clean['sendbeam_connect_workspace'] = $workspace; $clean['sendbeam_connect_granted'] = implode( ',', $granted ); @@ -534,14 +545,17 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { $clean['sendbeam_connect_notes'] = isset( $status['notes'] ) && is_array( $status['notes'] ) ? array_values( $status['notes'] ) : array(); if ( '' === trim( (string) $clean['default_form'] ) && sendbeam_is_form_id( $status['default_form']['id'] ) ) { $clean['default_form'] = strtolower( $status['default_form']['id'] ); + $filled[] = 'default_form'; } if ( in_array( 'transactional:send', $granted, true ) ) { if ( '' === trim( (string) $clean['mail_from_name'] ) && '' !== $status['sender']['from_name'] ) { $clean['mail_from_name'] = $status['sender']['from_name']; + $filled[] = 'mail_from_name'; } if ( '' === trim( (string) $clean['mail_from_email'] ) && '' !== $status['sender']['from_email'] ) { $clean['mail_from_email'] = $status['sender']['from_email']; + $filled[] = 'mail_from_email'; } /* @@ -557,12 +571,15 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { if ( ! empty( $status['domain']['verified'] ) ) { $clean['mail_enabled'] = 1; $clean['sendbeam_mail_deferred'] = 0; + $filled[] = 'mail_enabled'; } else { $clean['sendbeam_mail_deferred'] = 1; } } } + $clean['sendbeam_connect_filled'] = array_values( array_unique( $filled ) ); + update_option( 'sendbeam_settings', $clean ); sendbeam_flush_cache(); sendbeam_connect_cache_status( $status ); @@ -650,17 +667,39 @@ function sendbeam_connect_disconnect() { $note = ( $result['ok'] || 401 === $result['status'] ) ? 'ok' : 'unreachable'; } - $settings = sendbeam_settings(); + $settings = sendbeam_settings(); + + /* + * The workspace keeps its list, its form, its sending domain and its + * sender — disconnecting one site is not a reason to dismantle a + * workspace other sites may be sending from. What this site puts back is + * what Connect filled in here, and only that: a form ID belonging to a + * workspace this site no longer has a key for makes every embed 404 + * silently, and a From address pointing at a domain it can no longer send + * from is worse than an empty field. + */ + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + foreach ( array( 'default_form', 'mail_from_name', 'mail_from_email' ) as $key ) { + if ( in_array( $key, $filled, true ) ) { + $settings[ $key ] = ''; + } + } + if ( in_array( 'mail_enabled', $filled, true ) ) { + $settings['mail_enabled'] = 0; + } + $settings['api_key'] = ''; $settings['sendbeam_connected_via'] = ''; $settings['sendbeam_connect_workspace'] = ''; $settings['sendbeam_connect_notes'] = array(); $settings['sendbeam_connect_granted'] = ''; + $settings['sendbeam_connect_filled'] = array(); $settings['sendbeam_mail_deferred'] = 0; update_option( 'sendbeam_settings', $settings ); sendbeam_flush_cache(); sendbeam_connect_forget_status(); + delete_transient( 'sendbeam_form_placed' ); wp_safe_redirect( add_query_arg( 'sendbeam_disconnected', $note, sendbeam_tab_url( 'overview' ) ) ); exit; diff --git a/includes/helpers.php b/includes/helpers.php index 90d6283..036b150 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -58,6 +58,11 @@ function sendbeam_default_settings() { // on the consent page — and the Overview has to say "you did not give // this site that permission" rather than guess. 'sendbeam_connect_granted' => '', + // Which of this site's settings Connect filled in for the owner, so + // that disconnecting can put back exactly what it changed and not one + // thing more. Anything the owner has since saved by hand comes off + // the list: it is theirs now. + 'sendbeam_connect_filled' => array(), // Site email was approved at consent time but held back because the // sending domain was not verified yet. The domain check switches it // on and clears this; turning site email off by hand clears it too, diff --git a/includes/screens.php b/includes/screens.php index 5780a4a..b70b668 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -496,7 +496,7 @@ function sendbeam_connect_connected_panel( $status = null ) { esc_html__( 'Disconnect', 'sendbeam' ) ); echo '
    '; - echo '

    ' . esc_html__( 'Disconnect this site? The key is revoked in SendBeam and forgotten here. Forms already on your pages stop loading until you connect again.', 'sendbeam' ) . '

    '; + echo '

    ' . esc_html__( 'Disconnect this site? Its key is revoked. Your list, form and sending domain stay in SendBeam. Forms already on your pages stop loading until you connect again.', 'sendbeam' ) . '

    '; printf( ' ', esc_html__( 'Yes, disconnect', 'sendbeam' ) ); printf( '', esc_html__( 'Cancel', 'sendbeam' ) ); echo '
    '; diff --git a/includes/settings.php b/includes/settings.php index afb1733..3e5be51 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -235,6 +235,23 @@ function sendbeam_sanitize_settings( $input ) { } } + /* + * Saving a tab by hand is the owner taking those settings back. They come + * off the list of things Connect filled, so disconnecting later puts back + * only what the plugin actually put there — a From address somebody typed + * is not Connect's to clear, whoever typed it first. + */ + $out['sendbeam_connect_filled'] = isset( $out['sendbeam_connect_filled'] ) && is_array( $out['sendbeam_connect_filled'] ) ? $out['sendbeam_connect_filled'] : array(); + $owned = array(); + if ( isset( $touch['mail_enabled'] ) ) { + $owned = array( 'mail_enabled', 'mail_from_name', 'mail_from_email' ); + } elseif ( isset( $touch['default_form'] ) ) { + $owned = array( 'default_form' ); + } + if ( $owned ) { + $out['sendbeam_connect_filled'] = array_values( array_diff( $out['sendbeam_connect_filled'], $owned ) ); + } + // A different key means a different workspace, so anything remembered about // the old one — whether it worked, which forms it could see — is now a lie. // That includes the Connect marker: a key pasted or removed by hand did not @@ -249,6 +266,8 @@ function sendbeam_sanitize_settings( $input ) { // ones would offer buttons that cannot work. $out['sendbeam_connect_granted'] = ''; $out['sendbeam_mail_deferred'] = 0; + // Nor is anything this site's settings hold still Connect's doing. + $out['sendbeam_connect_filled'] = array(); } // A form chosen or cleared changes what the checklist should be looking diff --git a/tests/smoke.php b/tests/smoke.php index 39e2e3c..274df7b 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1409,6 +1409,60 @@ function sb_connected_site() { ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'disconnect: the capability is required' ); ok( SENDBEAM_API_KEY === sendbeam_settings()['api_key'], 'disconnect: a caller without the capability changes nothing' ); +// ── What Disconnect puts back ────────────────────────────────────────── +// The workspace keeps its list, form, domain and sender. What this site puts +// back is what Connect filled in here — and only that, because a form ID +// belonging to a workspace this site no longer has a key for makes every +// embed 404 without a word. +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ) ) ) ); +$sb_filled = sendbeam_settings()['sendbeam_connect_filled']; +ok( in_array( 'default_form', $sb_filled, true ), 'filled: the form Connect chose is recorded as Connect\'s' ); +ok( in_array( 'mail_from_name', $sb_filled, true ) && in_array( 'mail_from_email', $sb_filled, true ), 'filled: the sender Connect filled is recorded' ); +ok( in_array( 'mail_enabled', $sb_filled, true ), 'filled: site email switched on at consent is recorded' ); + +$_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' ); +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +$sb_after = sendbeam_settings(); +ok( '' === $sb_after['default_form'], 'disconnect: the form Connect chose is let go' ); +ok( '' === $sb_after['mail_from_name'] && '' === $sb_after['mail_from_email'], 'disconnect: the sender Connect filled is let go' ); +ok( empty( $sb_after['mail_enabled'] ), 'disconnect: site email Connect switched on goes off with it' ); +ok( array() === $sb_after['sendbeam_connect_filled'], 'disconnect: the list of what was filled is emptied too' ); + +// The same site, but the owner chose the form and the From address. Those are +// theirs: Disconnect leaves both exactly where they are. +sb_v2_exchange( sb_v2_body(), array( 'default_form' => $other, 'mail_from_email' => 'orders@harbourlane.co.uk', 'mail_from_name' => 'Orders' ) ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' ); +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +$sb_after = sendbeam_settings(); +ok( $other === $sb_after['default_form'], 'disconnect: a form the owner chose is left alone' ); +ok( 'orders@harbourlane.co.uk' === $sb_after['mail_from_email'] && 'Orders' === $sb_after['mail_from_name'], 'disconnect: a sender the owner typed is left alone' ); + +// Saving the Site email tab by hand is the owner taking those settings back. +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ) ) ) ); +update_option( 'sendbeam_settings', sendbeam_sanitize_settings( array( '_tab' => 'mail', 'mail_enabled' => '1', 'mail_from_name' => 'Harbour Lane', 'mail_from_email' => 'hello@harbourlane.co.uk' ) ) ); +$sb_filled = sendbeam_settings()['sendbeam_connect_filled']; +ok( ! in_array( 'mail_from_email', $sb_filled, true ) && ! in_array( 'mail_enabled', $sb_filled, true ), 'filled: saving Site email by hand takes those settings off Connect\'s list' ); +ok( in_array( 'default_form', $sb_filled, true ), 'filled: saving one tab does not release the settings on another' ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' ); +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +$sb_after = sendbeam_settings(); +ok( ! empty( $sb_after['mail_enabled'] ), 'disconnect: site email the owner switched on themselves stays on' ); +ok( 'hello@harbourlane.co.uk' === $sb_after['mail_from_email'], 'disconnect: and the sender they typed stays with it' ); + +// A key pasted over the top of a connection leaves nothing of Connect's behind. +sb_v2_exchange( sb_v2_body() ); +update_option( 'sendbeam_settings', sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => 'sb_live_pastedoverthetopxxxx' ) ) ); +ok( array() === sendbeam_settings()['sendbeam_connect_filled'], 'filled: a key changed by hand ends Connect\'s claim on anything' ); + +sb_connect_reset(); +update_option( 'sendbeam_settings', array() ); + // ── A blocked pop-up ─────────────────────────────────────────────────── sb_connect_reset(); $_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start', 'sendbeam_popup' => '0' ); @@ -1526,6 +1580,7 @@ function sb_overview( $settings, $status, $get = array() ) { has( $ov, 'value="sendbeam_disconnect"', 'overview: Disconnect posts to the disconnect handler' ); has( $ov, 'nonce:sendbeam_disconnect', 'overview: Disconnect carries a nonce' ); has( $ov, 'sb-confirm', 'overview: Disconnect is confirmed before it runs' ); +has( $ov, 'Your list, form and sending domain stay in SendBeam', 'overview: the confirmation says what disconnecting does not take away' ); lacks( $ov, 'confirm(', 'overview: the confirmation is the plugin\'s own, not a browser dialog' ); lacks( $ov, 'Switch on', 'overview: site email cannot be switched on while the domain is unverified' ); has( $ov, 'Waiting on step 2', 'overview: the site email step says what it is waiting for' ); From 0ef4e10818285a73b0612fdb90bbf05b9965c2fb Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:04:22 +0000 Subject: [PATCH 13/75] Check the DNS again on the site's own, for a day MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records almost never spread while somebody is sitting in wp-admin: they are entered at the registrar and the tab is closed. Step 2 then stayed unticked and the site's email stayed held back until a human came back and pressed Check now — the plugin waiting for the one thing it had just told the owner they would not have to do. An hourly event now does exactly what that button does, including finishing the switch-on consent already approved, and stops the moment there is nothing left to find out: verified, no domain any more, disconnected, or a full day of asking. A request that fails is retried rather than counted; sendbeam.io being down for an hour is not the same as the record not being there. One an hour sits well inside the check's own rate limit. Deactivating the plugin clears it, which the plugin had no hook for at all until now: a switched-off plugin still making requests is one nobody can see or stop from the screen they switched it off on. --- includes/connect-status.php | 96 +++++++++++++++++++++++++++++++++++++ includes/connect.php | 2 + includes/onboarding.php | 12 +++++ tests/smoke.php | 93 +++++++++++++++++++++++++++++++++++ tests/wp-stubs.php | 5 +- uninstall.php | 3 ++ 6 files changed, 210 insertions(+), 1 deletion(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index ad8e8de..4f2f918 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -35,6 +35,21 @@ /** Where the status lives between renders. */ const SENDBEAM_CACHE_STATUS = 'sendbeam_connect_status'; +/** The hourly DNS re-check, and where its tally lives. */ +const SENDBEAM_RECHECK_HOOK = 'sendbeam_connect_recheck'; +const SENDBEAM_RECHECK_COUNT = 'sendbeam_connect_recheck_runs'; + +/** + * A day of hourly re-checks, and then it gives up. + * + * DNS that has not spread in twenty-four hours has not been entered, and a + * site quietly asking SendBeam about it every hour for the rest of its life + * is a request nobody is waiting for. + */ +const SENDBEAM_RECHECK_MAX = 24; + +add_action( SENDBEAM_RECHECK_HOOK, 'sendbeam_connect_run_recheck' ); + /** * One minute. * @@ -400,6 +415,7 @@ function sendbeam_handle_domain_check() { sendbeam_connect_enable_mail( $status ); $note = 'verified_mail'; } + sendbeam_connect_unschedule_recheck(); } else { $note = 'pending'; } @@ -479,3 +495,83 @@ function sendbeam_connect_enable_mail( $status ) { update_option( 'sendbeam_settings', $settings ); } + +/** + * Start re-checking the DNS on this site's own, for a day. + * + * Records almost never propagate while somebody is sitting in wp-admin: they + * enter them at the registrar, close the tab, and come back tomorrow. Until + * now that meant step 2 stayed unticked and the site's email stayed held back + * until a human pressed **Check now** — the plugin was waiting for the one + * thing it had just told the owner they did not need to do. + * + * One request an hour is well inside the check's own rate limit, and it stops + * the moment there is nothing left to find out. + * + * @param array $status The status that decided there was something to wait for. + */ +function sendbeam_connect_schedule_recheck( $status ) { + if ( '' === sendbeam_api_key() || ! sendbeam_connect_granted( 'domain' ) ) { + return; + } + // Nothing to wait for: no domain to check, or one that is already done. + if ( '' === $status['domain']['name'] || ! empty( $status['domain']['verified'] ) ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + update_option( SENDBEAM_RECHECK_COUNT, 0, false ); + if ( ! wp_next_scheduled( SENDBEAM_RECHECK_HOOK ) ) { + wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', SENDBEAM_RECHECK_HOOK ); + } +} + +/** Stop re-checking: verified, disconnected, deactivated, or out of tries. */ +function sendbeam_connect_unschedule_recheck() { + wp_clear_scheduled_hook( SENDBEAM_RECHECK_HOOK ); + delete_option( SENDBEAM_RECHECK_COUNT ); +} + +/** + * One hourly re-check. + * + * It does exactly what **Check now** does, including finishing the held-back + * switch-on, and then decides whether there is any reason to run again. A + * request that fails is not counted against the site — sendbeam.io being down + * for an hour is not the same as the DNS not being there — but the tally is, + * so a site cannot ask forever. + */ +function sendbeam_connect_run_recheck() { + if ( '' === sendbeam_api_key() ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + $runs = (int) get_option( SENDBEAM_RECHECK_COUNT, 0 ) + 1; + update_option( SENDBEAM_RECHECK_COUNT, $runs, false ); + if ( $runs > SENDBEAM_RECHECK_MAX ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + $status = sendbeam_connect_status( true ); + if ( ! $status['ok'] ) { + return; // Ask again next hour. + } + if ( '' === $status['domain']['name'] ) { + sendbeam_connect_unschedule_recheck(); + return; + } + if ( empty( $status['domain']['verified'] ) ) { + return; + } + + $settings = sendbeam_settings(); + if ( ! empty( $settings['sendbeam_mail_deferred'] ) + && empty( $settings['mail_enabled'] ) + && sendbeam_connect_granted( 'transactional:send' ) ) { + sendbeam_connect_enable_mail( $status ); + } + + sendbeam_connect_unschedule_recheck(); +} diff --git a/includes/connect.php b/includes/connect.php index 3247056..365980b 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -583,6 +583,7 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { update_option( 'sendbeam_settings', $clean ); sendbeam_flush_cache(); sendbeam_connect_cache_status( $status ); + sendbeam_connect_schedule_recheck( $status ); return true; } @@ -699,6 +700,7 @@ function sendbeam_connect_disconnect() { sendbeam_flush_cache(); sendbeam_connect_forget_status(); + sendbeam_connect_unschedule_recheck(); delete_transient( 'sendbeam_form_placed' ); wp_safe_redirect( add_query_arg( 'sendbeam_disconnected', $note, sendbeam_tab_url( 'overview' ) ) ); diff --git a/includes/onboarding.php b/includes/onboarding.php index 38961f4..7b6da4b 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -19,6 +19,7 @@ defined( 'ABSPATH' ) || exit; register_activation_hook( SENDBEAM_FILE, 'sendbeam_on_activate' ); +register_deactivation_hook( SENDBEAM_FILE, 'sendbeam_on_deactivate' ); add_action( 'admin_notices', 'sendbeam_setup_notice' ); add_action( 'admin_post_sendbeam_dismiss_setup', 'sendbeam_dismiss_setup' ); @@ -32,6 +33,17 @@ function sendbeam_on_activate() { sendbeam_flush_cache(); } +/** + * Switched off: stop the clock. + * + * A deactivated plugin that leaves a scheduled event behind is a site making + * requests nobody can see, explain or stop from the screen they turned it off + * on. The hourly DNS re-check is the only one Connect owns. + */ +function sendbeam_on_deactivate() { + sendbeam_connect_unschedule_recheck(); +} + /** * Has the user finished the one step that unlocks everything else? * diff --git a/tests/smoke.php b/tests/smoke.php index 274df7b..fbbc50c 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1463,6 +1463,99 @@ function sb_connected_site() { sb_connect_reset(); update_option( 'sendbeam_settings', array() ); +// ── The hourly re-check ──────────────────────────────────────────────── +// Records almost never spread while somebody is sitting in wp-admin: they are +// entered at the registrar and the tab is closed. Without this the step +// stayed unticked and the site's email stayed held back until a human pressed +// Check now — waiting for the one thing the plugin had just said was unneeded. +$GLOBALS['stub']['cron'] = array(); +sb_v2_exchange( sb_v2_body() ); +ok( false !== wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: connecting with an unverified domain starts the hourly check' ); +ok( 'hourly' === $GLOBALS['stub']['cron'][0]['recurrence'], 'recheck: it runs hourly' ); + +$GLOBALS['stub']['cron'] = array(); +sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ) ) ) ); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: nothing is scheduled for a domain that is already verified' ); + +$GLOBALS['stub']['cron'] = array(); +sb_v2_exchange( sb_v2_body( array( 'scopes' => array( 'forms' ), 'domain' => null ) ) ); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: nothing is scheduled when there is no domain to wait for' ); + +/** A connected site mid-wait, with one reply armed for the re-check. */ +function sb_recheck_site( $verified ) { + sb_connect_reset(); + sendbeam_connect_forget_status(); + update_option( + 'sendbeam_settings', + array( + 'api_key' => 'sb_live_connectedconnectedxx', + 'sendbeam_connected_via' => 'connect', + 'sendbeam_connect_granted' => 'forms,transactional:send,domain', + 'sendbeam_mail_deferred' => 1, + 'mail_enabled' => 0, + ) + ); + $GLOBALS['stub']['cron'] = array( array( 'hook' => 'sendbeam_connect_recheck', 'args' => array(), 'recurrence' => 'hourly' ) ); + update_option( 'sendbeam_connect_recheck_runs', 0 ); + $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( $verified ) ); +} + +sb_recheck_site( false ); +sendbeam_connect_run_recheck(); +ok( 'POST' === $GLOBALS['stub']['remote'][0]['method'], 'recheck: a run asks SendBeam to look the DNS up now' ); +ok( false !== wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: an unverified domain is worth asking about again' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'recheck: nothing is switched on while the domain is unverified' ); +ok( 1 === (int) get_option( 'sendbeam_connect_recheck_runs' ), 'recheck: the run is counted' ); + +sb_recheck_site( true ); +sendbeam_connect_run_recheck(); +ok( ! empty( sendbeam_settings()['mail_enabled'] ), 'recheck: a verified domain finishes the held-back switch-on with nobody watching' ); +ok( empty( sendbeam_settings()['sendbeam_mail_deferred'] ), 'recheck: nothing is left held back' ); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: it unschedules itself once there is nothing left to find out' ); + +// A day of trying is enough: DNS that has not spread in 24 hours was not entered. +sb_recheck_site( false ); +update_option( 'sendbeam_connect_recheck_runs', 24 ); +sendbeam_connect_run_recheck(); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: it gives up after a day rather than asking forever' ); +ok( empty( $GLOBALS['stub']['remote'] ), 'recheck: the run that gives up does not make the request first' ); + +// SendBeam being down for an hour is not the same as the DNS not being there. +sb_recheck_site( false ); +$GLOBALS['stub']['remote_reply'] = new WP_Error( 'http_request_failed', 'cURL error 28' ); +sendbeam_connect_run_recheck(); +ok( false !== wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: a failed request is tried again next hour' ); + +// A domain that has gone from the workspace is not one to keep asking about. +sb_recheck_site( false ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => json_encode( array( 'workspace' => array( 'id' => 'ws_1' ), 'domain' => null, 'domain_state' => 'not_found' ) ) ); +sendbeam_connect_run_recheck(); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: a domain that is no longer there stops it asking' ); + +// Pressing Check now, disconnecting, or switching the plugin off all stop it. +sb_recheck_site( true ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check' ); +$_REQUEST = $_POST; +sb_run_admin_post( 'sendbeam_handle_domain_check' ); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: a verified domain found by hand stops it too' ); + +sb_recheck_site( false ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); +$_REQUEST = $_POST; +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' ); +sb_run_admin_post( 'sendbeam_connect_disconnect' ); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: disconnecting stops it' ); +ok( false === get_option( 'sendbeam_connect_recheck_runs' ), 'recheck: and forgets the tally' ); + +sb_recheck_site( false ); +sendbeam_on_deactivate(); +ok( false === wp_next_scheduled( 'sendbeam_connect_recheck' ), 'recheck: deactivating the plugin stops it' ); +ok( in_array( 'sendbeam_on_deactivate', $GLOBALS['stub']['deactivation'], true ), 'recheck: and WordPress is told to call that on deactivation' ); + +sb_connect_reset(); +update_option( 'sendbeam_settings', array() ); +$GLOBALS['stub']['cron'] = array(); + // ── A blocked pop-up ─────────────────────────────────────────────────── sb_connect_reset(); $_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start', 'sendbeam_popup' => '0' ); diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 270b637..baef738 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -5,7 +5,7 @@ * for the inputs the plugin passes it. */ define( 'ABSPATH', '/stub/' ); -$GLOBALS['stub'] = array( 'remote' => array(), 'remote_reply' => null, 'actions' => array(), 'options' => array(), 'hooks' => array(), 'shortcodes' => array(), 'scripts' => array(), 'inline' => array(), 'printed' => '', 'caps' => array(), 'query' => array(), 'errors' => array() ); +$GLOBALS['stub'] = array( 'remote' => array(), 'remote_reply' => null, 'actions' => array(), 'options' => array(), 'hooks' => array(), 'shortcodes' => array(), 'cron' => array(), 'scripts' => array(), 'inline' => array(), 'printed' => '', 'caps' => array(), 'query' => array(), 'errors' => array() ); function plugin_dir_path( $f ) { return dirname( $f ) . '/'; } function plugin_basename( $f ) { return 'sendbeam/sendbeam.php'; } @@ -169,6 +169,9 @@ function nocache_headers() {} // ── Form plugin bridges ──────────────────────────────────────────────── function wp_schedule_single_event( $timestamp, $hook, $args = array() ) { $GLOBALS['stub']['cron'][] = array( 'hook' => $hook, 'args' => $args ); return true; } +/** The recurring counterpart: the DNS re-check runs hourly for a day. */ +function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array() ) { $GLOBALS['stub']['cron'][] = array( 'hook' => $hook, 'args' => $args, 'recurrence' => $recurrence ); return true; } +function wp_clear_scheduled_hook( $hook, $args = array() ) { wp_unschedule_hook( $hook ); } /** Whether the same hook+args is already queued — cart-abandonment tracking dedupes on this. */ function wp_next_scheduled( $hook, $args = array() ) { foreach ( $GLOBALS['stub']['cron'] as $c ) { diff --git a/uninstall.php b/uninstall.php index d61f425..d3eb2a8 100644 --- a/uninstall.php +++ b/uninstall.php @@ -24,6 +24,7 @@ 'sendbeam_activated_at', 'sendbeam_ecommerce', 'sendbeam_ecommerce_log', + 'sendbeam_connect_recheck_runs', ); foreach ( $sendbeam_options as $sendbeam_option ) { delete_option( $sendbeam_option ); @@ -50,6 +51,7 @@ wp_unschedule_hook( 'sendbeam_bridge_subscribe' ); wp_unschedule_hook( 'sendbeam_ecommerce_send_event' ); wp_unschedule_hook( 'sendbeam_check_cart_abandonment' ); +wp_unschedule_hook( 'sendbeam_connect_recheck' ); // Two families of transient are named after something this file cannot list // up front — a shopper's session (sendbeam_cart_) and an administrator's @@ -98,6 +100,7 @@ function sendbeam_uninstall_sweep_transients( $prefixes ) { wp_unschedule_hook( 'sendbeam_bridge_subscribe' ); wp_unschedule_hook( 'sendbeam_ecommerce_send_event' ); wp_unschedule_hook( 'sendbeam_check_cart_abandonment' ); + wp_unschedule_hook( 'sendbeam_connect_recheck' ); sendbeam_uninstall_sweep_transients( $sendbeam_transient_prefixes ); restore_current_blog(); } From 9a82678ba5cd124efbcf2e509f160e5fdd9ee150 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:07:17 +0000 Subject: [PATCH 14/75] Look everywhere a form actually ends up, and believe the owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 3 read published post_content and nothing else, which is one of about six places a form goes. A block theme keeps the footer in a template part; a classic theme keeps it in a block widget; every page builder worth the name keeps its layout in post meta. All three ticked nothing, leaving an unfinished checklist beside a working form. All of them are looked at now, across every public post type, and the form's own hosted URL joins the block and the shortcodes as something to look for — that is what a builder pastes in. A text widget only counts when a sidebar actually holds it: one sitting in the inactive pile is a leftover, not a form on the site. No list of six will ever be seven, so "I've placed it elsewhere" ticks the step on the owner's word, and the step says plainly that this is what is holding the tick — with a way to take it back. --- includes/onboarding.php | 241 +++++++++++++++++++++++++++++++++++----- includes/screens.php | 29 ++++- tests/smoke.php | 97 ++++++++++++++++ tests/wp-stubs.php | 34 ++++++ uninstall.php | 1 + 5 files changed, 375 insertions(+), 27 deletions(-) diff --git a/includes/onboarding.php b/includes/onboarding.php index 7b6da4b..991932b 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -22,6 +22,7 @@ register_deactivation_hook( SENDBEAM_FILE, 'sendbeam_on_deactivate' ); add_action( 'admin_notices', 'sendbeam_setup_notice' ); add_action( 'admin_post_sendbeam_dismiss_setup', 'sendbeam_dismiss_setup' ); +add_action( 'admin_post_sendbeam_form_placed', 'sendbeam_handle_form_placed' ); /** * Remember when we were switched on, so the notice can be new-install-only. @@ -59,51 +60,182 @@ function sendbeam_is_connected() { * * "A form is chosen in the settings" and "a visitor can see a form" are not * the same claim, and the checklist was making the first one while sounding - * like the second. This looks for the block or either shortcode in published - * content — one indexed-free LIKE, answered once and then cached for half a - * day, because it drives one tick on one settings screen and is not worth a - * query per page load. - * - * A live pop-up counts: it is a form on the site by any reading. + * like the second. * * @param bool $force Skip the cache. * @return bool */ function sendbeam_form_is_placed( $force = false ) { + return '' !== sendbeam_form_placement( $force ); +} + +/** + * Where the form was found, or an empty string when it was not. + * + * The first version of this read published `post_content` and nothing else, + * which is one of perhaps six places a form actually ends up. A site running + * a block theme keeps its footer in `wp_template_part`; a classic theme keeps + * it in a block widget; every page builder worth the name stores its layout + * in post meta rather than in the post. All three tick nothing, and the owner + * is left looking at an unfinished checklist beside a working form. + * + * So all of them are looked at — and, because no list of six will ever be + * seven, the owner can simply say so and be believed. + * + * One query family, answered once and cached for half a day: this drives one + * tick on one settings screen and is not worth a query per page load. + * + * @param bool $force Skip the cache. + * @return string One of manual, popup, content, template, widget, meta; empty + * when no form could be found anywhere. + */ +function sendbeam_form_placement( $force = false ) { + if ( get_option( 'sendbeam_form_placed' ) ) { + return 'manual'; + } if ( sendbeam_popups() ) { - return true; + return 'popup'; } if ( ! $force ) { $cached = get_transient( 'sendbeam_form_placed' ); - if ( '1' === $cached || '0' === $cached ) { - return '1' === $cached; + if ( is_string( $cached ) && '' !== $cached ) { + return 'no' === $cached ? '' : $cached; } } + $found = sendbeam_find_form_placement(); + set_transient( 'sendbeam_form_placed', '' === $found ? 'no' : $found, 12 * HOUR_IN_SECONDS ); + return $found; +} + +/** + * The needles: the block, both shortcodes, and the form's own hosted URL. + * + * The URL is what a page builder or an HTML block holding an iframe contains, + * and it is the only one of the four that names a particular form. + * + * @return string[] + */ +function sendbeam_form_needles() { + $needles = array( 'wp:sendbeam/form', '[sendbeam_form', '[sendbeam_contact' ); + $settings = sendbeam_settings(); + foreach ( array( 'default_form', 'contact_form' ) as $key ) { + $id = (string) $settings[ $key ]; + if ( sendbeam_is_form_id( $id ) ) { + $needles[] = sendbeam_app_url() . '/f/' . strtolower( $id ); + } + } + return $needles; +} + +/** + * Look in all six places, cheapest first. + * + * @return string + */ +function sendbeam_find_form_placement() { + $needles = sendbeam_form_needles(); + + $widget = sendbeam_form_in_widgets( $needles ); + if ( '' !== $widget ) { + return $widget; + } + global $wpdb; if ( ! isset( $wpdb ) || ! is_object( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) ) { // No database to ask (the smoke tests, WP-CLI oddities): fall back to // what the settings say rather than claiming the step is unfinished. $settings = sendbeam_settings(); - return '' !== $settings['default_form'] || '' !== $settings['contact_form']; + return ( '' !== $settings['default_form'] || '' !== $settings['contact_form'] ) ? 'content' : ''; } - $block = '%' . $wpdb->esc_like( 'wp:sendbeam/form' ) . '%'; - $shortcode = '%' . $wpdb->esc_like( '[sendbeam_form' ) . '%'; - $contact = '%' . $wpdb->esc_like( '[sendbeam_contact' ) . '%'; - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- cached in a transient immediately below; there is no WP API for "is this block used anywhere". - $found = $wpdb->get_var( - $wpdb->prepare( - "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND ( post_content LIKE %s OR post_content LIKE %s OR post_content LIKE %s ) LIMIT 1", - $block, - $shortcode, - $contact - ) - ); + $like = array(); + foreach ( $needles as $needle ) { + $like[] = '%' . $wpdb->esc_like( $needle ) . '%'; + } + $content_or = implode( ' OR ', array_fill( 0, count( $like ), 'post_content LIKE %s' ) ); + + // Published content, in post types a visitor can actually reach. + $types = get_post_types( array( 'public' => true ), 'names' ); + $types = array_values( array_filter( array_map( 'strval', (array) $types ) ) ); + if ( ! $types ) { + $types = array( 'post', 'page' ); + } + $type_in = implode( ', ', array_fill( 0, count( $types ), '%s' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- cached in a transient by the caller; the two interpolated fragments are runs of %s placeholders built here, and every value goes through prepare(). + if ( $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ( $type_in ) AND ( $content_or ) LIMIT 1", array_merge( $types, $like ) ) ) ) { + return 'content'; + } + + // A block theme keeps the header, the footer and every page layout here. + // Templates are not "published" in the way a page is, so status is not + // part of the question. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- as above. + if ( $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'wp_template', 'wp_template_part' ) AND post_status != 'trash' AND ( $content_or ) LIMIT 1", $like ) ) ) { + return 'template'; + } + + // Page builders keep their layout beside the post, not in it. + $meta_or = implode( ' OR ', array_fill( 0, count( $like ), 'meta_value LIKE %s' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- as above. + if ( $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->postmeta} WHERE $meta_or LIMIT 1", $like ) ) ) { + return 'meta'; + } - set_transient( 'sendbeam_form_placed', $found ? '1' : '0', 12 * HOUR_IN_SECONDS ); - return (bool) $found; + return ''; +} + +/** + * Block widgets, and the text widgets a sidebar actually holds. + * + * Widgets live in options rather than in posts, so no amount of looking at + * `post_content` will ever find one. A text widget that is in `widget_text` + * but in no sidebar is not on the site — it is a leftover — so the sidebars + * decide which of them count. + * + * @param string[] $needles What a placed form looks like. + * @return string 'widget', or empty. + */ +function sendbeam_form_in_widgets( $needles ) { + $haystacks = array(); + + $blocks = get_option( 'widget_block' ); + if ( is_array( $blocks ) ) { + foreach ( $blocks as $block ) { + if ( is_array( $block ) && isset( $block['content'] ) ) { + $haystacks[] = (string) $block['content']; + } + } + } + + $sidebars = get_option( 'sidebars_widgets' ); + $text = get_option( 'widget_text' ); + if ( is_array( $sidebars ) && is_array( $text ) ) { + foreach ( $sidebars as $key => $ids ) { + if ( 'wp_inactive_widgets' === $key || ! is_array( $ids ) ) { + continue; + } + foreach ( $ids as $id ) { + if ( ! is_string( $id ) || 0 !== strpos( $id, 'text-' ) ) { + continue; + } + $number = (int) substr( $id, 5 ); + if ( isset( $text[ $number ]['text'] ) ) { + $haystacks[] = (string) $text[ $number ]['text']; + } + } + } + } + + foreach ( $haystacks as $haystack ) { + foreach ( $needles as $needle ) { + if ( false !== strpos( $haystack, $needle ) ) { + return 'widget'; + } + } + } + return ''; } /** @@ -198,10 +330,19 @@ function sendbeam_setup_steps() { $domain_detail = sendbeam_domain_sentence( $domain['name'], $verified ); } - $placed = ( $using_form || $using_popup ) ? sendbeam_form_is_placed() : false; + $where = ( $using_form || $using_popup ) ? sendbeam_form_placement() : ''; + $placed = '' !== $where; if ( $placed ) { - $form_detail = __( 'A SendBeam form is on the site.', 'sendbeam' ); + $found = array( + 'manual' => __( 'You said a SendBeam form is on the site.', 'sendbeam' ), + 'popup' => __( 'A SendBeam pop-up is live on the site.', 'sendbeam' ), + 'content' => __( 'A SendBeam form is on a published page or post.', 'sendbeam' ), + 'template' => __( 'A SendBeam form is in one of the theme\'s block templates.', 'sendbeam' ), + 'widget' => __( 'A SendBeam form is in a widget.', 'sendbeam' ), + 'meta' => __( 'A SendBeam form is in a layout stored with a page — a page builder, most likely.', 'sendbeam' ), + ); + $form_detail = isset( $found[ $where ] ) ? $found[ $where ] : __( 'A SendBeam form is on the site.', 'sendbeam' ); } elseif ( $using_form || $using_popup ) { $form_name = '' !== $status['default_form']['name'] ? $status['default_form']['name'] : __( 'Your form', 'sendbeam' ); /* translators: %s: the form name, e.g. Newsletter signup */ @@ -247,6 +388,7 @@ function sendbeam_setup_steps() { 'label' => __( 'Put a form on the site', 'sendbeam' ), 'detail' => $form_detail, 'target' => sendbeam_tab_url( 'forms' ), + 'where' => $where, ), array( 'key' => 'mail', @@ -308,3 +450,50 @@ function sendbeam_dismiss_setup() { wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() ); exit; } + +/** + * "I've placed it elsewhere" — and the way back from it. + * + * No list of places a form can be will ever be complete: a theme that renders + * the shortcode in PHP, a form in a plugin this one has never heard of, a + * cached page. The owner can see their own site, so they get the last word, + * and the step says plainly that this is what is holding the tick. + */ +function sendbeam_handle_form_placed() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); + } + check_admin_referer( 'sendbeam_form_placed' ); + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- checked immediately above. + $on = ! isset( $_GET['state'] ) || '0' !== sanitize_text_field( wp_unslash( $_GET['state'] ) ); + + if ( $on ) { + update_option( 'sendbeam_form_placed', 1, false ); + } else { + delete_option( 'sendbeam_form_placed' ); + } + delete_transient( 'sendbeam_form_placed' ); + + wp_safe_redirect( add_query_arg( 'sendbeam_form', $on ? 'placed' : 'unplaced', sendbeam_tab_url( 'overview' ) ) ); + exit; +} + +/** + * The URL behind that link. + * + * @param bool $on True to say the form is placed, false to take it back. + * @return string + */ +function sendbeam_form_placed_url( $on = true ) { + return wp_nonce_url( + add_query_arg( + array( + 'action' => 'sendbeam_form_placed', + 'state' => $on ? '1' : '0', + ), + admin_url( 'admin-post.php' ) + ), + 'sendbeam_form_placed' + ); +} diff --git a/includes/screens.php b/includes/screens.php index b70b668..94aa0aa 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -110,6 +110,7 @@ function sendbeam_overview_notices() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- notice text only, chosen from a fixed list, set by our own redirect. $domain = isset( $_GET['sendbeam_domain'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_domain'] ) ) : ''; $mail = isset( $_GET['sendbeam_mail'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_mail'] ) ) : ''; + $placed = isset( $_GET['sendbeam_form'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_form'] ) ) : ''; $gone = isset( $_GET['sendbeam_disconnected'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_disconnected'] ) ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended @@ -121,6 +122,10 @@ function sendbeam_overview_notices() { 'nodomain' => array( 'warn', __( 'There is no sending domain on this workspace yet. Add one under Sending in SendBeam.', 'sendbeam' ) ), 'unreachable' => array( 'bad', __( 'Could not ask SendBeam to check just now. Nothing was changed.', 'sendbeam' ) ), ), + 'form' => array( + 'placed' => array( 'ok', __( 'Noted — the form step is ticked. Say so again if you take the form off the site.', 'sendbeam' ) ), + 'unplaced' => array( 'ok', __( 'The form step will look for itself again.', 'sendbeam' ) ), + ), 'mail' => array( 'on' => array( 'ok', __( 'Site email is on. Password resets, receipts and notifications now go out through SendBeam.', 'sendbeam' ) ), 'noscope' => array( 'bad', __( 'This site\'s key was not given permission to send your site\'s email, so it was not switched on. Reconnect and tick that box.', 'sendbeam' ) ), @@ -135,6 +140,7 @@ function sendbeam_overview_notices() { foreach ( array( 'domain' => $domain, + 'form' => $placed, 'mail' => $mail, 'gone' => $gone, ) as $group => $value ) { @@ -362,9 +368,25 @@ function sendbeam_record_verdict( $found ) { * @param bool $connected Whether the key works. */ function sendbeam_overview_form_panel( $step, $connected ) { - if ( ! $connected || $step['done'] ) { + if ( ! $connected ) { return; } + + // Ticked because the owner said so, not because anything was found. The + // step says which, and offers to stop believing it. + if ( $step['done'] ) { + if ( 'manual' === ( isset( $step['where'] ) ? $step['where'] : '' ) ) { + echo '
    '; + printf( + '%s', + esc_url( sendbeam_form_placed_url( false ) ), + esc_html__( 'Actually, it is not', 'sendbeam' ) + ); + echo '
    '; + } + return; + } + $settings = sendbeam_settings(); if ( '' === (string) $settings['default_form'] && '' === (string) $settings['contact_form'] ) { return; @@ -377,6 +399,11 @@ function sendbeam_overview_form_panel( $step, $connected ) { esc_attr__( 'Copied', 'sendbeam' ), esc_html__( 'Copy', 'sendbeam' ) ); + printf( + '%s', + esc_url( sendbeam_form_placed_url() ), + esc_html__( 'I\'ve placed it elsewhere', 'sendbeam' ) + ); echo '
    '; } diff --git a/tests/smoke.php b/tests/smoke.php index fbbc50c..58f27a5 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1556,6 +1556,103 @@ function sb_recheck_site( $verified ) { update_option( 'sendbeam_settings', array() ); $GLOBALS['stub']['cron'] = array(); +// ── Where a form can actually be ─────────────────────────────────────── +// Published post_content is one of perhaps six places a form ends up. A block +// theme keeps the footer in wp_template_part; a classic theme keeps it in a +// block widget; a page builder keeps its layout in post meta. All three used +// to tick nothing, leaving the owner with an unfinished checklist beside a +// working form. +/** A site using a form, with a database that answers as the test says. */ +function sb_placement( $db, $options = array() ) { + delete_transient( 'sendbeam_form_placed' ); + delete_option( 'sendbeam_form_placed' ); + delete_option( 'widget_block' ); + delete_option( 'sidebars_widgets' ); + delete_option( 'widget_text' ); + foreach ( $options as $name => $value ) { + update_option( $name, $value ); + } + update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_connectedconnectedxx', 'default_form' => $GLOBALS['form'] ) ); + update_option( 'sendbeam_popups', array() ); + $GLOBALS['stub']['db'] = $db; + $GLOBALS['wpdb'] = new SendBeam_Stub_Db(); + $where = sendbeam_form_placement( true ); + $sql = implode( ' ', $GLOBALS['wpdb']->queries ); + unset( $GLOBALS['wpdb'] ); + return array( $where, $sql ); +} + +list( $sb_where, $sb_sql ) = sb_placement( array( 'posts' => true ) ); +ok( 'content' === $sb_where, 'placed: a form on a published page is found' ); +has( $sb_sql, 'wp:sendbeam/form', 'placed: the block is one of the things looked for' ); +has( $sb_sql, '[sendbeam\\_form', 'placed: so is the shortcode, with the underscore escaped for LIKE' ); +has( $sb_sql, 'https://sendbeam.io/f/' . $form, 'placed: and the form\'s own hosted URL, for an iframe a builder pasted in' ); +has( $sb_sql, "post_type IN ( 'post', 'page', 'attachment' )", 'placed: every public post type is searched, not only posts and pages' ); + +list( $sb_where ) = sb_placement( array( 'templates' => true ) ); +ok( 'template' === $sb_where, 'placed: a form in a block theme\'s template part is found' ); + +list( $sb_where ) = sb_placement( array( 'meta' => true ) ); +ok( 'meta' === $sb_where, 'placed: a form a page builder stored beside the post is found' ); + +list( $sb_where, $sb_sql ) = sb_placement( array(), array( 'widget_block' => array( 2 => array( 'content' => '' ) ) ) ); +ok( 'widget' === $sb_where, 'placed: a form in a block widget is found' ); +ok( '' === $sb_sql, 'placed: and found without asking the database at all' ); + +list( $sb_where ) = sb_placement( + array(), + array( + 'sidebars_widgets' => array( 'sidebar-1' => array( 'text-3' ) ), + 'widget_text' => array( 3 => array( 'text' => 'Join us [sendbeam_form]' ) ), + ) +); +ok( 'widget' === $sb_where, 'placed: a text widget a sidebar actually holds is found' ); + +list( $sb_where ) = sb_placement( + array(), + array( + 'sidebars_widgets' => array( 'wp_inactive_widgets' => array( 'text-3' ) ), + 'widget_text' => array( 3 => array( 'text' => 'Join us [sendbeam_form]' ) ), + ) +); +ok( '' === $sb_where, 'placed: a widget nobody has put in a sidebar is a leftover, not a form on the site' ); + +list( $sb_where ) = sb_placement( array() ); +ok( '' === $sb_where, 'placed: a site with the form nowhere is not ticked off' ); + +// No list of six will ever be seven, so the owner gets the last word. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_connectedconnectedxx', 'default_form' => $form ) ); +delete_option( 'sendbeam_form_placed' ); +delete_transient( 'sendbeam_form_placed' ); +$_GET = array( '_wpnonce' => 'nonce:sendbeam_form_placed' ); +$_REQUEST = $_GET; +$url = sb_run_admin_post( 'sendbeam_handle_form_placed' ); +has( $url, 'sendbeam_form=placed', 'placed: saying so is confirmed on the screen' ); +ok( 'manual' === sendbeam_form_placement(), 'placed: and the step is ticked, without a database in sight' ); + +$_GET = array( '_wpnonce' => 'nonce:sendbeam_form_placed', 'state' => '0' ); +$_REQUEST = $_GET; +$url = sb_run_admin_post( 'sendbeam_handle_form_placed' ); +has( $url, 'sendbeam_form=unplaced', 'placed: and taking it back is possible' ); +ok( 'manual' !== sendbeam_form_placement( true ), 'placed: the override really is gone' ); + +$_GET = array(); +$_REQUEST = array(); +sb_run_admin_post( 'sendbeam_handle_form_placed' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'placed: no nonce, no override' ); +$GLOBALS['stub']['caps']['manage_options'] = false; +$_GET = array( '_wpnonce' => 'nonce:sendbeam_form_placed' ); +$_REQUEST = $_GET; +sb_run_admin_post( 'sendbeam_handle_form_placed' ); +ok( 0 === strpos( $GLOBALS['stub']['exit'], 'wp_die' ), 'placed: the capability is required' ); + +sb_connect_reset(); +delete_option( 'sendbeam_form_placed' ); +delete_transient( 'sendbeam_form_placed' ); +update_option( 'sendbeam_settings', array() ); +$GLOBALS['stub']['db'] = array(); + // ── A blocked pop-up ─────────────────────────────────────────────────── sb_connect_reset(); $_POST = array( '_wpnonce' => 'nonce:sendbeam_connect_start', 'sendbeam_popup' => '0' ); diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index baef738..349407a 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -225,3 +225,37 @@ function wp_nonce_field( $action = -1, $name = '_wpnonce' ) { echo 'queries[] = $sql; + $db = isset( $GLOBALS['stub']['db'] ) ? $GLOBALS['stub']['db'] : array(); + if ( false !== strpos( $sql, 'wp_postmeta' ) ) { return empty( $db['meta'] ) ? null : 1; } + if ( false !== strpos( $sql, 'wp_template' ) ) { return empty( $db['templates'] ) ? null : 1; } + return empty( $db['posts'] ) ? null : 1; + } +} diff --git a/uninstall.php b/uninstall.php index d3eb2a8..5e1865b 100644 --- a/uninstall.php +++ b/uninstall.php @@ -25,6 +25,7 @@ 'sendbeam_ecommerce', 'sendbeam_ecommerce_log', 'sendbeam_connect_recheck_runs', + 'sendbeam_form_placed', // The owner's "I've placed it elsewhere", which is an option; the transient of the same name is swept below. ); foreach ( $sendbeam_options as $sendbeam_option ) { delete_option( $sendbeam_option ); From 32ce3424d2178ecebbb25e9c2b5b2dae307ba3ff Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:09:26 +0000 Subject: [PATCH 15/75] Never make wp-admin wait ten seconds for a panel The Overview asked for the connection's status on a cold cache with the timeout meant for a button somebody pressed, so the first load of every minute could sit there for ten seconds, and a failed request blanked the panel of DNS records the owner was halfway through copying. Screen renders now wait four seconds and fall back to the last answer they had, marked as old, with the domain state saying SendBeam could not be reached. The answer is kept for half a day rather than the minute it is trusted for; the hourly re-check and the next load refresh it. The cache is also per key now, hashed. Two administrators signed in to different workspaces shared one transient, so for up to a minute each was shown the other's sending domain and told to put its records into their own DNS. The hash rather than the key because a transient name ends up in the options table, in backups and in logs. --- includes/api.php | 13 +++-- includes/connect-status.php | 104 +++++++++++++++++++++++++++++------- includes/connect.php | 6 ++- includes/settings.php | 3 ++ tests/smoke.php | 73 ++++++++++++++++++++----- 5 files changed, 164 insertions(+), 35 deletions(-) diff --git a/includes/api.php b/includes/api.php index 8eccec7..88a4630 100644 --- a/includes/api.php +++ b/includes/api.php @@ -24,9 +24,14 @@ * GET a path on the SendBeam API with the saved key. * * @param string $path Path beginning with a slash, e.g. '/api/v1/forms'. + * @param array $args Optional. `timeout` in seconds. Ten is right for a + * request somebody pressed a button for; a screen that + * renders one on every load wants far less, because the + * alternative is wp-admin sitting there for ten seconds + * over a panel nobody was reading. * @return array{ok:bool,status:int,data:array,error:string} */ -function sendbeam_api_get( $path ) { +function sendbeam_api_get( $path, $args = array() ) { $key = sendbeam_api_key(); if ( '' === $key ) { return array( @@ -37,10 +42,12 @@ function sendbeam_api_get( $path ) { ); } + $timeout = isset( $args['timeout'] ) ? max( 1, (int) $args['timeout'] ) : 10; + $response = wp_remote_get( sendbeam_app_url() . $path, array( - 'timeout' => 10, + 'timeout' => $timeout, 'headers' => array( 'x-api-key' => $key, 'Accept' => 'application/json', @@ -197,7 +204,7 @@ function sendbeam_flush_cache() { delete_transient( SENDBEAM_CACHE_CONN ); // The Connect status belongs to one key: the workspace, the sending // domain and the sender all change with it. - delete_transient( 'sendbeam_connect_status' ); + sendbeam_connect_forget_status(); delete_transient( SENDBEAM_CACHE_FORMS ); delete_transient( SENDBEAM_CACHE_LISTS ); delete_transient( SENDBEAM_CACHE_SUBS ); diff --git a/includes/connect-status.php b/includes/connect-status.php index 4f2f918..fc98eea 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -60,6 +60,26 @@ */ const SENDBEAM_STATUS_TTL = 60; +/** + * How long the answer is kept after it stops being fresh. + * + * A minute is how long it is *trusted*; half a day is how long it is worth + * *having*. When sendbeam.io cannot be reached, a minute-old copy of the DNS + * records is enormously better than an empty panel — the owner is in the + * middle of copying them into a registrar. + */ +const SENDBEAM_STATUS_KEEP = 12 * HOUR_IN_SECONDS; + +/** + * The seconds a screen render will wait for the status. + * + * The shared ten is right for a button somebody pressed. It is wrong for a + * panel drawn on every Overview load: a slow API would hold wp-admin open for + * ten seconds over something the owner may not even be looking at. Four is + * long enough for a healthy request and short enough not to be noticed. + */ +const SENDBEAM_STATUS_TIMEOUT = 4; + /** * An empty status: every key present, nothing claimed. * @@ -83,6 +103,9 @@ function sendbeam_connect_empty_status() { // nobody. 'domain_state' => '', 'domain_note' => '', + // Served from the cache because the request failed, and how old it is. + 'stale' => false, + 'fetched_at' => 0, 'workspace' => array( 'id' => '', 'name' => '', @@ -311,16 +334,47 @@ function sendbeam_connect_when( $iso ) { } /** - * Remember a status for a minute. + * Where this key's status lives. + * + * Per key, not per site. Two administrators signed in to different SendBeam + * workspaces — one testing, one live — shared a single transient, so for up + * to a minute each of them was shown the other's sending domain and told to + * put its records into their own DNS. The key is hashed rather than used: + * a transient name ends up in the options table, in backups and in logs, and + * an API key does not belong in any of them. + * + * @param string|null $api_key A particular key. Defaults to this site's. + * @return string + */ +function sendbeam_connect_status_key( $api_key = null ) { + $key = null === $api_key ? sendbeam_api_key() : (string) $api_key; + return SENDBEAM_CACHE_STATUS . '_' . substr( sha1( $key ), 0, 12 ); +} + +/** + * Remember a status, and when it was fetched. + * + * The timestamp is what separates "fresh" from "worth having anyway": the + * transient outlives the minute it is trusted for, so a failed request has + * something to fall back on. * * @param array $status Normalised status. */ function sendbeam_connect_cache_status( $status ) { - set_transient( SENDBEAM_CACHE_STATUS, $status, SENDBEAM_STATUS_TTL ); + $status['fetched_at'] = time(); + set_transient( sendbeam_connect_status_key(), $status, SENDBEAM_STATUS_KEEP ); } -/** Forget it — after a disconnect, or when the key changes. */ -function sendbeam_connect_forget_status() { +/** + * Forget it — after a disconnect, or when the key changes. + * + * @param string|null $api_key The key whose answer to forget. Defaults to + * this site's, which is what every caller but the + * key-change path wants. + */ +function sendbeam_connect_forget_status( $api_key = null ) { + delete_transient( sendbeam_connect_status_key( $api_key ) ); + // Everything cached under the single shared name this replaced. delete_transient( SENDBEAM_CACHE_STATUS ); } @@ -338,28 +392,40 @@ function sendbeam_connect_status( $check = false ) { return sendbeam_connect_empty_status(); } - if ( ! $check ) { - $cached = get_transient( SENDBEAM_CACHE_STATUS ); - if ( is_array( $cached ) && isset( $cached['domain'] ) ) { - return $cached; - } + $cached = get_transient( sendbeam_connect_status_key() ); + $cached = is_array( $cached ) && isset( $cached['domain'] ) ? $cached : null; + + if ( ! $check && null !== $cached && ( time() - (int) ( isset( $cached['fetched_at'] ) ? $cached['fetched_at'] : 0 ) ) < SENDBEAM_STATUS_TTL ) { + return $cached; } $result = $check ? sendbeam_api_post( '/api/v1/connect/status', array( 'check_domain' => true ) ) - : sendbeam_api_get( '/api/v1/connect/status' ); + : sendbeam_api_get( '/api/v1/connect/status', array( 'timeout' => SENDBEAM_STATUS_TIMEOUT ) ); if ( ! $result['ok'] ) { - $status = sendbeam_connect_empty_status(); if ( 429 === $result['status'] ) { - $status['error'] = __( 'SendBeam is rate-limiting this site. Wait a few minutes and try again.', 'sendbeam' ); + $error = __( 'SendBeam is rate-limiting this site. Wait a few minutes and try again.', 'sendbeam' ); } elseif ( 401 === $result['status'] || 403 === $result['status'] ) { - $status['error'] = __( 'SendBeam would not answer with this site\'s key. Reconnect the site.', 'sendbeam' ); + $error = __( 'SendBeam would not answer with this site\'s key. Reconnect the site.', 'sendbeam' ); } else { - $status['error'] = __( 'Could not read this site\'s set-up from SendBeam just now.', 'sendbeam' ); + $error = __( 'Could not read this site\'s set-up from SendBeam just now.', 'sendbeam' ); } - // Cached like any other answer: a site whose key has been revoked must - // not make a failing request on every single wp-admin page load. + + /* + * An answer that has gone stale still beats no answer. Someone is in + * the middle of copying DNS records into a registrar, and blanking + * the panel because one request timed out takes them away from what + * they were doing for no gain. It is served with the state saying + * plainly that it is old. + * + * Either way it is cached, which is what stops a revoked key making a + * failing request on every wp-admin page load. + */ + $status = ( null !== $cached && ! empty( $cached['ok'] ) ) ? $cached : sendbeam_connect_empty_status(); + $status['error'] = $error; + $status['stale'] = ( null !== $cached && ! empty( $cached['ok'] ) ); + $status['domain_state'] = 'unavailable'; sendbeam_connect_cache_status( $status ); return $status; } @@ -372,8 +438,10 @@ function sendbeam_connect_status( $check = false ) { * copying. */ if ( empty( $result['data'] ) ) { - $status = sendbeam_connect_empty_status(); - $status['error'] = __( 'SendBeam answered with nothing this site could read.', 'sendbeam' ); + $status = ( null !== $cached && ! empty( $cached['ok'] ) ) ? $cached : sendbeam_connect_empty_status(); + $status['error'] = __( 'SendBeam answered with nothing this site could read.', 'sendbeam' ); + $status['stale'] = ( null !== $cached && ! empty( $cached['ok'] ) ); + $status['domain_state'] = 'unavailable'; sendbeam_connect_cache_status( $status ); return $status; } diff --git a/includes/connect.php b/includes/connect.php index 365980b..c6bdecf 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -696,10 +696,14 @@ function sendbeam_connect_disconnect() { $settings['sendbeam_connect_granted'] = ''; $settings['sendbeam_connect_filled'] = array(); $settings['sendbeam_mail_deferred'] = 0; + + // Before the key is forgotten, not after: the cached answer is filed + // under that key, and a site that has just let go of it can no longer + // name the transient it wrote. + sendbeam_connect_forget_status(); update_option( 'sendbeam_settings', $settings ); sendbeam_flush_cache(); - sendbeam_connect_forget_status(); sendbeam_connect_unschedule_recheck(); delete_transient( 'sendbeam_form_placed' ); diff --git a/includes/settings.php b/includes/settings.php index 3e5be51..e53cff2 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -257,6 +257,9 @@ function sendbeam_sanitize_settings( $input ) { // That includes the Connect marker: a key pasted or removed by hand did not // come from the Connect button, and the screen must stop claiming it did. if ( $out['api_key'] !== (string) $saved['api_key'] ) { + // Named explicitly, because the cache belongs to the key that wrote + // it and that key is on its way out. + sendbeam_connect_forget_status( (string) $saved['api_key'] ); sendbeam_flush_cache(); $out['sendbeam_connected_via'] = ''; $out['sendbeam_connect_workspace'] = ''; diff --git a/tests/smoke.php b/tests/smoke.php index 58f27a5..0ccee46 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -945,7 +945,7 @@ function sb_v2_body( $over = array() ) { function sb_v2_exchange( $body, $settings = array() ) { global $sendbeam_good_state, $sendbeam_good_grant; sb_connect_reset(); - delete_transient( 'sendbeam_connect_status' ); + sendbeam_connect_forget_status(); update_option( 'sendbeam_settings', $settings ); sb_connect_pending( $sendbeam_good_state ); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => $body ); @@ -965,7 +965,7 @@ function sb_v2_exchange( $body, $settings = array() ) { ok( sendbeam_connect_granted( 'domain' ), 'connect v2: the screen can ask whether a permission was granted' ); ok( ! sendbeam_connect_granted( 'ecommerce' ), 'connect v2: a permission that was not granted reads false' ); -$v2_status = get_transient( 'sendbeam_connect_status' ); +$v2_status = get_transient( sendbeam_connect_status_key() ); ok( is_array( $v2_status ), 'connect v2: the status is cached for the Overview instead of being fetched again' ); ok( 'harbourlane.co.uk' === $v2_status['domain']['name'], 'connect v2: the sending domain is cached' ); ok( 2 === count( $v2_status['domain']['records'] ), 'connect v2: the DNS records are cached' ); @@ -976,9 +976,9 @@ function sb_v2_exchange( $body, $settings = array() ) { // A domain-connect link pointing anywhere but SendBeam is a phishing link // wearing the plugin's chrome. It never becomes a button. sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array(), 'domain_connect_url' => 'https://evil.example.com/dns' ) ) ) ); -ok( '' === get_transient( 'sendbeam_connect_status' )['domain']['domain_connect_url'], 'connect v2: a domain-connect link on another host is dropped' ); +ok( '' === get_transient( sendbeam_connect_status_key() )['domain']['domain_connect_url'], 'connect v2: a domain-connect link on another host is dropped' ); sb_v2_exchange( sb_v2_body( array( 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array(), 'domain_connect_url' => 'http://sendbeam.io/dns' ) ) ) ); -ok( '' === get_transient( 'sendbeam_connect_status' )['domain']['domain_connect_url'], 'connect v2: an http domain-connect link is dropped' ); +ok( '' === get_transient( sendbeam_connect_status_key() )['domain']['domain_connect_url'], 'connect v2: an http domain-connect link is dropped' ); // A form ID that is not a form ID never becomes this site's default. sb_v2_exchange( sb_v2_body( array( 'default_form' => array( 'id' => 'nonsense', 'name' => 'X' ) ) ) ); @@ -1007,7 +1007,7 @@ function sb_v2_exchange( $body, $settings = array() ) { // ── /api/v1/connect/status ───────────────────────────────────────────── sb_connect_reset(); -delete_transient( 'sendbeam_connect_status' ); +sendbeam_connect_forget_status(); update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_statusstatusstatus' ) ); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), @@ -1046,7 +1046,7 @@ function sb_v2_exchange( $body, $settings = array() ) { // A rejected key is reported, cached, and never crashes a template. sb_connect_reset(); -delete_transient( 'sendbeam_connect_status' ); +sendbeam_connect_forget_status(); update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_revokedrevokedrevoked' ) ); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 401 ), 'body' => '{"error":"unauthorised"}' ); $st = sendbeam_connect_status(); @@ -1058,7 +1058,7 @@ function sb_v2_exchange( $body, $settings = array() ) { // A 200 carrying nothing usable is a failure, not an answer: caching it as // one would blank the DNS records somebody is halfway through copying. sb_connect_reset(); -delete_transient( 'sendbeam_connect_status' ); +sendbeam_connect_forget_status(); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => 'proxy error' ); $st = sendbeam_connect_status(); ok( ! $st['ok'] && '' !== $st['error'], 'status: a 200 that is not JSON is treated as a failure, not as an empty workspace' ); @@ -1219,6 +1219,53 @@ function sb_step_details( $status, $settings = null ) { sb_connect_reset(); update_option( 'sendbeam_settings', array() ); +// ── A slow SendBeam must not be a slow wp-admin ──────────────────────── +sb_connect_reset(); +sendbeam_connect_forget_status(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_statusstatusstatus' ) ); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) ); +$sb_first = sendbeam_connect_status(); +ok( 4 === $GLOBALS['stub']['remote'][0]['args']['timeout'], 'status: a screen render waits four seconds, not the shared ten' ); + +// The answer goes stale after a minute, but it is kept far longer than that: +// when SendBeam cannot be reached, a minute-old copy of the DNS records is +// enormously better than an empty panel to somebody halfway through copying +// them into a registrar. +$sb_kept = get_transient( sendbeam_connect_status_key() ); +$sb_kept['fetched_at'] = time() - 300; +set_transient( sendbeam_connect_status_key(), $sb_kept, 60 ); +$GLOBALS['stub']['remote_reply'] = new WP_Error( 'http_request_failed', 'cURL error 28' ); +$sb_stale = sendbeam_connect_status(); +ok( 'harbourlane.co.uk' === $sb_stale['domain']['name'], 'status: a failed request serves the last answer rather than blanking the panel' ); +ok( ! empty( $sb_stale['stale'] ), 'status: and says it is doing so' ); +ok( 'unavailable' === $sb_stale['domain_state'], 'status: the state says SendBeam could not be reached' ); +ok( '' !== $sb_stale['error'], 'status: the failure is still reported' ); + +// Nothing cached and nothing reachable: empties, and the state that says why. +sendbeam_connect_forget_status(); +$sb_cold = sendbeam_connect_status(); +ok( '' === $sb_cold['domain']['name'] && empty( $sb_cold['stale'] ), 'status: with nothing cached there is nothing to fall back on' ); +ok( 'unavailable' === $sb_cold['domain_state'], 'status: and the state still says why' ); + +// One transient per key, so two administrators on different workspaces cannot +// read each other's sending domain — and the key itself is not the name. +$sb_key_a = sendbeam_connect_status_key( 'sb_live_aaaaaaaaaaaaaaaaaaaa' ); +$sb_key_b = sendbeam_connect_status_key( 'sb_live_bbbbbbbbbbbbbbbbbbbb' ); +ok( $sb_key_a !== $sb_key_b, 'status: two keys do not share one cached answer' ); +ok( 0 === strpos( $sb_key_a, 'sendbeam_connect_status_' ), 'status: the transient is still swept by prefix on uninstall' ); +lacks( $sb_key_a, 'sb_live_', 'status: the key is hashed, not used — a transient name ends up in backups and logs' ); + +// Pasting a different key takes the old key's answer with it. +sb_connect_reset(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_aaaaaaaaaaaaaaaaaaaa' ) ); +set_transient( $sb_key_a, sendbeam_connect_empty_status(), 60 ); +update_option( 'sendbeam_settings', sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => 'sb_live_bbbbbbbbbbbbbbbbbbbb' ) ) ); +ok( false === get_transient( $sb_key_a ), 'status: changing the key deletes what the old one had cached' ); + +sb_connect_reset(); +sendbeam_connect_forget_status(); +update_option( 'sendbeam_settings', array() ); + // ── Check now ────────────────────────────────────────────────────────── /** Drive an admin-post handler that ends in a redirect. */ function sb_run_admin_post( $fn ) { @@ -1233,7 +1280,7 @@ function sb_run_admin_post( $fn ) { /** A connected site with site email approved but held back. */ function sb_deferred_site() { sb_connect_reset(); - delete_transient( 'sendbeam_connect_status' ); + sendbeam_connect_forget_status(); update_option( 'sendbeam_settings', array( @@ -1282,7 +1329,7 @@ function sb_status_body( $verified ) { ok( empty( $off['sendbeam_mail_deferred'] ), 'check: turning site email off by hand cancels the held-back switch-on' ); $_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check' ); $_REQUEST = $_POST; -delete_transient( 'sendbeam_connect_status' ); +sendbeam_connect_forget_status(); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); $url = sb_run_admin_post( 'sendbeam_handle_domain_check' ); has( $url, 'sendbeam_domain=verified', 'check: a verified domain is still reported' ); @@ -1350,7 +1397,7 @@ function sb_connected_site() { 'sendbeam_mail_deferred' => 1, ) ); - set_transient( 'sendbeam_connect_status', sendbeam_connect_empty_status(), 60 ); + sendbeam_connect_cache_status( sendbeam_connect_empty_status() ); $_POST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' ); $_REQUEST = $_POST; } @@ -1367,7 +1414,7 @@ function sb_connected_site() { ok( '' === $v2['api_key'], 'disconnect: the key is forgotten' ); ok( '' === $v2['sendbeam_connected_via'] && '' === $v2['sendbeam_connect_workspace'], 'disconnect: the Connect marker and workspace name go with it' ); ok( '' === $v2['sendbeam_connect_granted'] && empty( $v2['sendbeam_mail_deferred'] ), 'disconnect: the permissions and the held-back switch-on are forgotten' ); -ok( false === get_transient( 'sendbeam_connect_status' ), 'disconnect: the cached status is dropped' ); +ok( false === get_transient( sendbeam_connect_status_key() ), 'disconnect: the cached status is dropped' ); has( $url, 'sendbeam_disconnected=ok', 'disconnect: the notice says the key was revoked' ); // SendBeam unreachable: the site still forgets the key, and says so. @@ -1722,7 +1769,7 @@ function sb_overview( $settings, $status, $get = array() ) { set_transient( 'sendbeam_remote_forms', array() ); set_transient( 'sendbeam_remote_lists', array() ); set_transient( 'sendbeam_subscriber_count', 0 ); - set_transient( 'sendbeam_connect_status', sendbeam_connect_normalise_status( $status ), 60 ); + sendbeam_connect_cache_status( sendbeam_connect_normalise_status( $status ) ); ob_start(); sendbeam_screen_overview(); return ob_get_clean(); @@ -1841,7 +1888,7 @@ function sb_overview( $settings, $status, $get = array() ) { has( $ov, 'Connect the site first', 'overview: the domain step says to connect first' ); sb_connect_reset(); -delete_transient( 'sendbeam_connect_status' ); +sendbeam_connect_forget_status(); delete_transient( 'sendbeam_connection' ); delete_transient( 'sendbeam_remote_forms' ); delete_transient( 'sendbeam_remote_lists' ); From d9128bc9dfc68e39b04ce36373409962bd30dfaa Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:12:11 +0000 Subject: [PATCH 16/75] Do not offer to store a key wp-config.php will overrule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A key defined as SENDBEAM_API_KEY beats anything saved in the database, everywhere. Connecting on such a site minted a real key, stored it, and then never used it — a live credential sitting unused in a database, and a checklist telling its owner to go and make one. The panel now says where the live key actually is and how to change it, the connected card says the same and warns that Disconnect will not revoke it, and step 1 stops telling anybody to press a button that is deliberately not on the screen. The smoke test defines that constant for the status and disconnect checks, and a constant cannot be un-defined again in one process, so the handful of assertions about a site with no key anywhere now run before it is defined. --- includes/connect.php | 21 ++++++++++++++ includes/onboarding.php | 25 +++++++++++++++-- includes/screens.php | 4 +++ tests/smoke.php | 61 +++++++++++++++++++++++++++++------------ 4 files changed, 91 insertions(+), 20 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index c6bdecf..6978b95 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -711,6 +711,15 @@ function sendbeam_connect_disconnect() { exit; } +/** + * Is this site's key pinned in wp-config.php? + * + * @return bool + */ +function sendbeam_key_in_config() { + return defined( 'SENDBEAM_API_KEY' ) && '' !== trim( (string) SENDBEAM_API_KEY ); +} + /** * Was this site connected through the button rather than a pasted key? * @@ -809,6 +818,18 @@ function sendbeam_connect_render_result( $connected, $heading, $detail, $is_popu function sendbeam_connect_panel() { $origin = sendbeam_connect_site_origin(); + /* + * A key defined in wp-config.php beats anything stored here, everywhere. + * Connecting on such a site mints a key, stores it, and then never uses + * it — a real key sitting unused in a database, which is the worst of + * both worlds. So the button is not offered, and the panel says where the + * live key actually is. + */ + if ( sendbeam_key_in_config() ) { + echo '

    ' . esc_html__( 'This site sends with the key defined as SENDBEAM_API_KEY in wp-config.php. That key wins over anything saved here, so connecting would store a second key nothing would ever use. Change it in wp-config.php, or remove that line to connect from this screen instead.', 'sendbeam' ) . '

    '; + return; + } + if ( ! sendbeam_connect_origin_ok( $origin ) ) { echo '

    ' . esc_html__( 'This site is not served over https, so SendBeam cannot connect to it. Paste an API key below instead.', 'sendbeam' ) . '

    '; return; diff --git a/includes/onboarding.php b/includes/onboarding.php index 991932b..cc46091 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -238,6 +238,27 @@ function sendbeam_form_in_widgets( $needles ) { return ''; } +/** + * What step 1 says. + * + * A key pinned in wp-config.php is the one this site sends with, so telling + * its owner to press a button that is deliberately not on the screen — and + * which would store a second key nothing would use — is the wrong + * instruction twice over. + * + * @param bool $connected Whether the key works. + * @return string + */ +function sendbeam_connect_step_sentence( $connected ) { + if ( $connected ) { + return __( 'Your key works.', 'sendbeam' ); + } + if ( sendbeam_key_in_config() ) { + return __( 'This site\'s key is the one in wp-config.php, and SendBeam is not answering to it. Change it there.', 'sendbeam' ); + } + return __( 'Press Connect SendBeam, approve what this site may do, and the key arrives on its own.', 'sendbeam' ); +} + /** * What step 2 says once there really is a sending domain. * @@ -369,9 +390,7 @@ function sendbeam_setup_steps() { 'key' => 'connect', 'done' => $connected, 'label' => __( 'Connect your SendBeam account', 'sendbeam' ), - 'detail' => $connected - ? __( 'Your key works.', 'sendbeam' ) - : __( 'Press Connect SendBeam, approve what this site may do, and the key arrives on its own.', 'sendbeam' ), + 'detail' => sendbeam_connect_step_sentence( $connected ), 'target' => sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', ), array( diff --git a/includes/screens.php b/includes/screens.php index 94aa0aa..fb34eb7 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -494,6 +494,10 @@ function sendbeam_connect_connected_panel( $status = null ) { echo '

    ' . esc_html( sprintf( __( 'Connected to %s', 'sendbeam' ), $workspace ) ) . '

    '; } + if ( sendbeam_key_in_config() ) { + echo '

    ' . esc_html__( 'This site sends with the key defined as SENDBEAM_API_KEY in wp-config.php, not the one stored here. Change it there; Disconnect will not revoke it.', 'sendbeam' ) . '

    '; + } + $granted = sendbeam_connect_granted_list(); if ( $granted ) { echo '
      '; diff --git a/tests/smoke.php b/tests/smoke.php index 0ccee46..b90e303 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -320,9 +320,6 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), ok( sendbeam_sanitize_settings( array( 'api_key_remove' => '1' ) )['api_key'] === '', 'remove clears the key' ); ok( sendbeam_sanitize_settings( array( 'api_key' => 'sb_new_0123456789abcdef' ) )['api_key'] === 'sb_new_0123456789abcdef', 'new key saved' ); -// wp-config constant wins over the option. -define( 'SENDBEAM_API_KEY', 'sb_const_0123456789abcdef' ); -ok( sendbeam_api_key() === 'sb_const_0123456789abcdef', 'constant wins' ); // ── Form plugin bridges ───────────────────────────────────────────────── @@ -606,6 +603,41 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), sendbeam_ecommerce_clear_scheduled(); ok( 1 === count( $stub['cron'] ) && 'something_else' === $stub['cron'][0]['hook'], 'deactivation: only this plugin\'s own scheduled checks are cleared' ); +// ── A site with no key anywhere ──────────────────────────────────────── +// Everything from here on runs with SENDBEAM_API_KEY defined in wp-config.php, +// because that is what the status and disconnect tests are about — and a key +// pinned there cannot be un-defined again inside one process. These run first: +// a site with no key at all is the site the Connect button exists for. +// +// The helpers below are declared further down the file; PHP binds top-level +// functions before the first line runs, so they are callable from here. +sb_connect_reset(); +ob_start(); +sendbeam_connect_panel(); +$sb_panel = ob_get_clean(); +has( $sb_panel, 'Connect SendBeam', 'panel: a site with no key gets the button' ); +has( $sb_panel, 'name="sendbeam_popup" value="0"', 'panel: the form defaults to "this tab" until the script says otherwise' ); +has( $sb_panel, 'example-site.test', 'panel: the domain permission names this site\'s domain' ); + +$sb_ov = sb_overview( array(), array() ); +has( $sb_ov, 'Connect SendBeam', 'overview: an unconnected site gets the button' ); +has( $sb_ov, 'I already have an API key', 'overview: pasting a key is still possible' ); +lacks( $sb_ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); +lacks( $sb_ov, 'value="sendbeam_disconnect"', 'overview: nothing offers to disconnect what is not connected' ); +has( $sb_ov, 'Connect the site first', 'overview: the domain step says to connect first' ); + +sb_connect_reset(); +sendbeam_connect_forget_status(); +delete_transient( 'sendbeam_connection' ); +delete_transient( 'sendbeam_remote_forms' ); +delete_transient( 'sendbeam_remote_lists' ); +delete_transient( 'sendbeam_subscriber_count' ); +update_option( 'sendbeam_settings', array() ); + +// wp-config constant wins over the option. +define( 'SENDBEAM_API_KEY', 'sb_const_0123456789abcdef' ); +ok( sendbeam_api_key() === 'sb_const_0123456789abcdef', 'constant wins' ); + // ── Connect ──────────────────────────────────────────────────────────── // // The plugin is the client: it mints the state, sends the person to @@ -1736,13 +1768,7 @@ function sb_placement( $db, $options = array() ) { has( $popup_html, 'window.close()', 'pop-up: a real pop-up still closes itself' ); has( $popup_html, 'Back to SendBeam settings', 'pop-up: the link underneath still points at the settings screen' ); -// The form carries the flag the script flips, and the script flips it. -sb_connect_reset(); -ob_start(); -sendbeam_connect_panel(); -$panel_html = ob_get_clean(); -has( $panel_html, 'name="sendbeam_popup" value="0"', 'pop-up: the form defaults to "this tab" until the script says otherwise' ); -has( $panel_html, 'example-site.test', 'pop-up: the domain permission names this site\'s domain' ); +// The script flips the flag the form carries. has( sendbeam_connect_admin_js(), 'sb-connect-popup', 'pop-up: the script sets the flag it was given' ); // ── The Overview itself ──────────────────────────────────────────────── @@ -1864,6 +1890,14 @@ function sb_overview( $settings, $status, $get = array() ) { lacks( $ov, 'Reconnect with more permissions', 'overview: a step with nothing missing does not offer it' ); has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); +// A key pinned in wp-config.php beats anything stored here, so connecting +// would mint a real key, save it, and never use it. +$ov = sb_overview( array(), array() ); +has( $ov, 'SENDBEAM_API_KEY in wp-config.php', 'overview: a site with the key pinned in wp-config is told where its key is' ); +lacks( $ov, 'Connect SendBeam', 'overview: and is not offered a button that would store a key nothing uses' ); +$ov = sb_overview( $sb_connected, $sb_verified ); +has( $ov, 'Disconnect will not revoke it', 'overview: the connected card says the live key is the pinned one' ); + // A site connected with a key pasted by hand: no recorded permissions, but a // domain it can plainly read. The screen must not print a table of records // under a sentence saying it has no permission to read them. @@ -1879,13 +1913,6 @@ function sb_overview( $settings, $status, $get = array() ) { lacks( $ov, 'table class="sb-table sb-dns"', 'overview: no records table for a domain that does not exist' ); lacks( $ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); -// Never connected: the Connect button, and no checklist that pretends to know anything. -$ov = sb_overview( array(), array() ); -has( $ov, 'Connect SendBeam', 'overview: an unconnected site gets the button' ); -has( $ov, 'I already have an API key', 'overview: pasting a key is still possible' ); -lacks( $ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); -lacks( $ov, 'value="sendbeam_disconnect"', 'overview: nothing offers to disconnect what is not connected' ); -has( $ov, 'Connect the site first', 'overview: the domain step says to connect first' ); sb_connect_reset(); sendbeam_connect_forget_status(); From fee1fb19e2b1bf0ff7a4f3d3a4480e2745707db3 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:14:02 +0000 Subject: [PATCH 17/75] Come back to WordPress when the registrar has finished MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pressing "Set up DNS automatically" started in a wp-admin checklist and ended on SendBeam's sending settings — a reasonable place to finish if you had started there, and the wrong one entirely when what you wanted was to come back and see the step ticked. The link now carries this site's Overview as the address to return to, and the page it returns to says what happened: the records were added and it is checking, or the registrar refused and here is SendBeam's reason with the records right underneath to enter by hand. Coming back spends exactly one check, and a domain that verifies on it finishes the held-back switch-on the same way pressing Check now does. The flag comes straight off the address bar once it has been read, so a refresh neither checks again nor claims to be checking. --- includes/connect-status.php | 44 +++++++++++++++++-------- includes/connect.php | 16 ++++++++++ includes/screens.php | 64 +++++++++++++++++++++++++++++++++++-- tests/smoke.php | 28 ++++++++++++++++ 4 files changed, 136 insertions(+), 16 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index fc98eea..b1e2bbd 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -475,15 +475,7 @@ function sendbeam_handle_domain_check() { } elseif ( '' === $status['domain']['name'] ) { $note = 'nodomain'; } elseif ( $status['domain']['verified'] ) { - $note = 'verified'; - $settings = sendbeam_settings(); - if ( ! empty( $settings['sendbeam_mail_deferred'] ) - && empty( $settings['mail_enabled'] ) - && sendbeam_connect_granted( 'transactional:send' ) ) { - sendbeam_connect_enable_mail( $status ); - $note = 'verified_mail'; - } - sendbeam_connect_unschedule_recheck(); + $note = sendbeam_connect_finish_deferred( $status ) ? 'verified_mail' : 'verified'; } else { $note = 'pending'; } @@ -634,12 +626,36 @@ function sendbeam_connect_run_recheck() { return; } - $settings = sendbeam_settings(); - if ( ! empty( $settings['sendbeam_mail_deferred'] ) - && empty( $settings['mail_enabled'] ) - && sendbeam_connect_granted( 'transactional:send' ) ) { - sendbeam_connect_enable_mail( $status ); + sendbeam_connect_finish_deferred( $status ); +} + +/** + * A domain has verified: finish what consent started, and stop asking. + * + * Three things reach this point — the **Check now** button, the hourly + * re-check, and coming back from a registrar that set the DNS up for you — + * and all three mean exactly the same thing to a site whose email is waiting + * on the domain. Switching it on is finishing a job the owner already said + * yes to; it is not the same as switching on something they turned off, which + * is why `sendbeam_mail_deferred` has to still be set. + * + * @param array $status A fresh status. + * @return bool Whether site email was switched on as a result. + */ +function sendbeam_connect_finish_deferred( $status ) { + if ( empty( $status['domain']['verified'] ) ) { + return false; } sendbeam_connect_unschedule_recheck(); + + $settings = sendbeam_settings(); + if ( empty( $settings['sendbeam_mail_deferred'] ) + || ! empty( $settings['mail_enabled'] ) + || ! sendbeam_connect_granted( 'transactional:send' ) ) { + return false; + } + + sendbeam_connect_enable_mail( $status ); + return true; } diff --git a/includes/connect.php b/includes/connect.php index 6978b95..1ede520 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -901,6 +901,22 @@ function sendbeam_connect_admin_js() { } } ); } + /* + * Coming back from a registrar leaves sb_dc in the address bar, and + * sb_dc=done spends a check. A refresh, or a bookmark, would spend + * another one and print "Checking now…" over a page that is not, + * so the flag is taken off the URL the moment it has been read. + */ + if ( window.history && history.replaceState && window.URL ) { + try { + var here = new URL( window.location.href ); + if ( here.searchParams.has( "sb_dc" ) ) { + here.searchParams.delete( "sb_dc" ); + here.searchParams.delete( "sb_dc_reason" ); + history.replaceState( null, "", here.toString() ); + } + } catch ( err ) {} + } window.addEventListener( "message", function ( e ) { if ( e.origin !== origin || ! e.data || "connected" !== e.data.sendbeam ) { return; } window.location.reload(); diff --git a/includes/screens.php b/includes/screens.php index fb34eb7..d3a604d 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -42,7 +42,19 @@ function sendbeam_screen_overview() { // is one subscriber, and adding the lists up counted them three times. $subscribers = sendbeam_subscriber_count(); $connected = sendbeam_is_connected(); - $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + + /* + * Straight back from the registrar. The records were written a second + * ago, so this is the one page load that has a reason to ask SendBeam to + * look again rather than read the minute-old cache — and if that check + * verifies the domain, it finishes the held-back switch-on exactly as + * pressing Check now would. + */ + $returned = sendbeam_overview_dns_return(); + $status = $connected ? sendbeam_connect_status( 'done' === $returned ) : sendbeam_connect_empty_status(); + if ( $connected && 'done' === $returned ) { + sendbeam_connect_finish_deferred( $status ); + } sendbeam_overview_notices(); @@ -112,8 +124,24 @@ function sendbeam_overview_notices() { $mail = isset( $_GET['sendbeam_mail'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_mail'] ) ) : ''; $placed = isset( $_GET['sendbeam_form'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_form'] ) ) : ''; $gone = isset( $_GET['sendbeam_disconnected'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_disconnected'] ) ) : ''; + $reason = isset( $_GET['sb_dc_reason'] ) ? sanitize_key( wp_unslash( $_GET['sb_dc_reason'] ) ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended + // Back from the registrar. Not in the table below because the failure + // carries SendBeam's own reason code, and the table is fixed sentences. + $returned = sendbeam_overview_dns_return(); + if ( 'done' === $returned ) { + echo '

      ' . esc_html__( 'Your registrar added the records. Checking now…', 'sendbeam' ) . '

      '; + } elseif ( 'error' === $returned ) { + echo '

      ' . esc_html( + sprintf( + /* translators: %s: SendBeam's reason the registrar refused, e.g. "state mismatch" */ + __( 'Your registrar could not add the records (%s). Add them by hand below.', 'sendbeam' ), + '' !== $reason ? str_replace( '_', ' ', substr( $reason, 0, 60 ) ) : __( 'no reason given', 'sendbeam' ) + ) + ) . '

      '; + } + $messages = array( 'domain' => array( 'verified' => array( 'ok', __( 'Verified. SendBeam can now send email as your domain.', 'sendbeam' ) ), @@ -152,6 +180,22 @@ function sendbeam_overview_notices() { } } +/** + * Did this page load arrive back from the registrar, and how did it go? + * + * The two values come from a redirect SendBeam issued, and the only thing + * read out of them is which of two sentences to print — and, for `done`, + * whether to spend one check. The script strips both from the address bar + * afterwards so a refresh does not check again. + * + * @return string 'done', 'error', or empty. + */ +function sendbeam_overview_dns_return() { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a two-value flag on a redirect from the registrar; it chooses a sentence and one read-only check. + $value = isset( $_GET['sb_dc'] ) ? sanitize_key( wp_unslash( $_GET['sb_dc'] ) ) : ''; + return in_array( $value, array( 'done', 'error' ), true ) ? $value : ''; +} + /** * The working part of a checklist step, under its sentence. * @@ -277,7 +321,7 @@ function sendbeam_overview_domain_panel( $status, $connected ) { if ( ! $verified && '' !== $domain['domain_connect_url'] ) { printf( '%s', - esc_url( $domain['domain_connect_url'] ), + esc_url( sendbeam_domain_connect_url( $domain['domain_connect_url'] ) ), esc_html__( 'Set up DNS automatically', 'sendbeam' ) ); } @@ -344,6 +388,22 @@ function sendbeam_domain_records_table( $records ) { echo ''; } +/** + * The one-click DNS link, told where to send the owner afterwards. + * + * Without this the journey ends on SendBeam's own sending settings — which is + * a reasonable place for it to end if you started there, and the wrong one + * entirely when you started in wp-admin, pressed a button in a checklist, and + * expected to come back and see the step ticked. SendBeam honours the return + * address only when it belongs to a site one of its own keys was issued to. + * + * @param string $url The registrar link SendBeam sent. + * @return string + */ +function sendbeam_domain_connect_url( $url ) { + return add_query_arg( 'return_to', rawurlencode( sendbeam_tab_url( 'overview' ) ), $url ); +} + /** * One record's verdict, in the three states the check actually has. * diff --git a/tests/smoke.php b/tests/smoke.php index b90e303..2dbaf62 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1890,6 +1890,34 @@ function sb_overview( $settings, $status, $get = array() ) { lacks( $ov, 'Reconnect with more permissions', 'overview: a step with nothing missing does not offer it' ); has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); +// ── Back from the registrar ──────────────────────────────────────────── +// Automatic DNS used to end on SendBeam's own sending settings: a reasonable +// place to finish if you started there, and the wrong one entirely when you +// started in a wp-admin checklist and expected to come back and see the step +// ticked. +$ov = sb_overview( $sb_connected, $sb_unverified ); +has( $ov, 'return_to=' . rawurlencode( 'https://www.example-site.test/wp-admin/options-general.php?page=sendbeam&tab=overview' ), 'automatic DNS: the one-click link tells SendBeam where to send the owner back to' ); +has( $ov, 'https://sendbeam.io/dc/1?return_to=', 'automatic DNS: and is otherwise the link SendBeam sent' ); + +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +sendbeam_connect_forget_status(); +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => 'done' ) ); +has( $ov, 'Your registrar added the records. Checking now', 'automatic DNS: coming back says what happened' ); +$sb_posts = array_filter( $GLOBALS['stub']['remote'], function ( $r ) { return 'POST' === $r['method']; } ); +ok( 1 === count( $sb_posts ), 'automatic DNS: coming back spends exactly one check' ); +ok( ! empty( sendbeam_settings()['mail_enabled'] ), 'automatic DNS: a domain that verifies finishes the held-back switch-on' ); + +sendbeam_connect_forget_status(); +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => 'error', 'sb_dc_reason' => 'state_mismatch' ) ); +has( $ov, 'Your registrar could not add the records (state mismatch)', 'automatic DNS: a refusal says why, in SendBeam\'s own reason' ); +has( $ov, 'Add them by hand below', 'automatic DNS: and points at the records that are right there' ); +ok( empty( array_filter( $GLOBALS['stub']['remote'], function ( $r ) { return 'POST' === $r['method']; } ) ), 'automatic DNS: a refusal spends no check' ); + +$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => '' ) ); +lacks( $ov, 'alert(1)', 'automatic DNS: the flag is one of two values, not a message to print' ); +lacks( $ov, 'Checking now', 'automatic DNS: and anything else is ignored' ); +has( sendbeam_connect_admin_js(), 'sb_dc', 'automatic DNS: the flag is taken off the address bar once it has been read' ); + // A key pinned in wp-config.php beats anything stored here, so connecting // would mint a real key, save it, and never use it. $ov = sb_overview( array(), array() ); From 852299d21ca962effa1b824f4afca88c50651541 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:15:45 +0000 Subject: [PATCH 18/75] Say what changed, in the words a site owner would use readme.txt, README.md and CHANGELOG.md cover every refinement in this release: choosing the domain you send from, the per-record verdict, why there is no sending domain when there is none, reconnecting without disconnecting, what Disconnect leaves behind, the hourly re-check, automatic DNS returning to WordPress, where the form step looks, the four-second render, one cached answer per key, and a key pinned in wp-config.php. Three new FAQ answers for the questions this release creates: sending from a domain that is not the site's, what survives a disconnect, and the form step that will not tick because the form is somewhere nothing can read. No version bump: 1.8.3 has not shipped. --- CHANGELOG.md | 12 ++++++++++++ README.md | 22 +++++++++++++++------- readme.txt | 29 ++++++++++++++++++++++++++++- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1700f19..47f9dc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,18 @@ - Disconnect will not revoke a key defined as `SENDBEAM_API_KEY` in `wp-config.php`. That key beats the saved one everywhere, including in the revoke call, so pressing the button on such a site would have taken down a key Connect never issued and something else is probably using. The stored key is forgotten, nothing is revoked, and the screen says where the live one is. - A blocked pop-up is no longer a dead end: the Connect form falls back to navigating the current tab, and the page it lands on offers **Back to the site** instead of trying to close a window nothing opened. - The Overview screen itself is now covered by the smoke tests. No test could see a settings screen before, which is how a permission check or a form on the page layer could drift without anything noticing. +- **The sending host is the owner's to choose.** The consent page suggests this site's domain and takes another if you type one, and the plugin shows `domain.name` from the answer rather than deriving a host from `site_url`. A brand domain or a `mail.` subdomain was previously impossible from either end. +- **Every DNS record carries the check's verdict.** Two records right out of three looked exactly like none of them. Never-checked is kept apart from not-found, because telling somebody their DNS is wrong when nothing has looked at it is its own bug. Every record SendBeam asks for is a CNAME, so the table says nothing about priority — an always-empty Priority column is a box people go hunting for at their registrar. +- **A missing sending domain says which of four things happened.** `domain: null` meant the box was never ticked, the key predates domains being readable, the key has no site host, or the row was removed by hand, and step 2 answered "not set up" to all of them. The status now carries `domain_state` and a sentence, and every word step 2 says comes from the answer rather than from what the site remembers granting — which is what made a site with a pasted key announce a missing permission while printing that domain's records underneath. +- **Reconnecting no longer means disconnecting first.** A step whose sentence names a permission you did not give offers **Reconnect with more permissions**, which starts the ordinary Connect flow with every box preselected; the connected card carries a plain **Reconnect** asking for what the key already holds. +- **Disconnect puts back what Connect filled in, and only that.** The form it chose, the sender it worked out and the site email it switched on are recorded as they are filled, and released again the moment you save that tab by hand. A default form belonging to a workspace this site no longer has a key for makes every embed 404 without a word, which is what used to happen. The workspace keeps its list, form, domain and sender; the confirmation says so. +- **The DNS is checked again without anybody watching**, hourly for a day after connecting, completing the held-back switch-on when the domain verifies and stopping as soon as there is nothing left to find out. Records almost never spread while somebody is still in wp-admin. Deactivating the plugin clears the event — there was no deactivation hook at all before. +- **Automatic DNS comes back to WordPress.** The one-click link carries this site's Overview as its return address; the page it lands on says whether the registrar added the records, spends exactly one check, and takes the flag off the address bar so a refresh does not check again. +- **"Put a form on the site" looks where forms actually are**: every public post type, block templates and template parts, block widgets, the text widgets a sidebar really holds, and the layouts page builders keep in post meta — plus the form's own hosted URL alongside the block and the shortcodes. The step says where it found one, and "I've placed it elsewhere" ticks it on your word, with a way back. +- **The Overview never waits ten seconds for a panel.** Screen renders ask with a four-second timeout and fall back to the last answer they had, marked as old; the answer is kept for half a day rather than the minute it is trusted for. +- **One cached status per key, hashed.** Two administrators signed in to different workspaces shared a single transient, so for up to a minute each was shown the other's sending domain and told to put its records into their own DNS. The key is hashed because a transient name ends up in the options table, in backups and in logs. +- **A key pinned in `wp-config.php` is no longer offered a Connect button.** It beats anything stored in the database, so connecting minted a real key, saved it and never used it. The panel and the connected card say where the live key is and how to change it. +- "Last checked" is rendered with the site's own date and time formats and timezone instead of the API's ISO string. ## 1.8.2 diff --git a/README.md b/README.md index 11f7709..9b67d9f 100644 --- a/README.md +++ b/README.md @@ -40,13 +40,21 @@ in one call. Nothing is sent to SendBeam until you press the button. If you alre have an API key" on the same screen still takes one. Forms are then picked from a dropdown of the connected workspace's own forms — no IDs to copy. -Leaving the sending-domain box ticked does the next piece of setting up for you. SendBeam adds this site's -domain to the workspace, and the Overview's second step shows its DNS records with a Copy button on every -value, a **Check now** button that re-runs the check without leaving wp-admin, and a **Set up DNS -automatically** button where your registrar supports one-click set-up. Site email fills in its sender from the -workspace but only switches on once that domain is verified — a site should never have its password resets -quietly routed through a domain nothing has set up yet. **Disconnect**, on the connected card, revokes the key -in SendBeam first and then forgets it here. +Leaving the sending-domain box ticked does the next piece of setting up for you. The consent page suggests +this site's own domain and lets you type a different one — a brand domain, or `mail.` something — and whatever +you enter is what SendBeam sets up and what the plugin shows. The Overview's second step lists its DNS records +with a Copy button on every value and a column saying which of them are live yet, a **Check now** button that +re-runs the check without leaving wp-admin, and a **Set up DNS automatically** button where your registrar +supports one-click set-up — that one brings you back here when it is done. Records rarely spread while you are +still looking at wp-admin, so the site quietly checks again every hour for a day and finishes the job when +they appear. + +Site email fills in its sender from the workspace but only switches on once that domain is verified — a site +should never have its password resets quietly routed through a domain nothing has set up yet. If a permission +turns out to be missing, the step that needs it offers **Reconnect with more permissions** rather than making +you disconnect first. **Disconnect**, on the connected card, revokes the key in SendBeam, forgets it here, and +puts back the settings Connect filled in — your list, form, sending domain and sender stay in the workspace, +where other sites may still be using them. ## API key permissions diff --git a/readme.txt b/readme.txt index c2cb9f2..97ddf22 100644 --- a/readme.txt +++ b/readme.txt @@ -25,6 +25,8 @@ This plugin puts your SendBeam forms on a WordPress site without copying embed c * **Site email** — send everything WordPress sends with `wp_mail()` (WooCommerce order confirmations, password resets, form and comment notifications, plugin alerts) through your verified SendBeam domain. No SMTP host, port or password: one API key, one switch, a test button and a log of recent results. * **E-commerce events** (WooCommerce) — feed SendBeam's native Cart Abandoned, Product Viewed and Order Placed automation triggers. Order placed also keeps a running lifetime-value total on the contact. Each event has its own switch, off by default. +**Connecting** is one button: tick what this site may do, sign in or create your account in the window that opens, and the key arrives on its own. You choose the domain you send from — this site's, or a brand domain you own — and the plugin shows you its DNS records, checks them again on its own for a day afterwards, and switches your site email on once they are live. If you did not give a permission, the step that needs it offers to reconnect; disconnecting revokes this site's key and leaves everything in your workspace where it is. + Forms are shown exactly as configured in SendBeam (fields, double opt-in, the thank-you message, the list they join), so changing a form there changes it on your site straight away. Displaying a form makes no request from your server — the visitor's browser fetches it. Site email, when you switch it on, is one HTTPS call per message to SendBeam's API. A site can listen for `sendbeam:submitted` on `document` to track a signup as an analytics goal or redirect to a thank-you page. @@ -61,7 +63,7 @@ A SendBeam account (the Free plan is enough) with at least one form. Form IDs ar 1. Install and activate the plugin. 2. Go to **Settings → SendBeam** and click **Connect SendBeam**. Create your account or sign in in the window that opens, tick what this site may do, and the key arrives on its own — there is nothing to copy. If you already have an API key, "I already have an API key" on the same screen still takes one. -3. Verify your sending domain — the plugin shows the records, or sets them up for you where your registrar supports it. Copy each value into your DNS, press **Check now**, and the step ticks itself off. Nothing SendBeam sends for you leaves your own domain until this is done. +3. Verify your sending domain — the plugin shows the records, with a column saying which are live yet, or sets them up for you where your registrar supports it and brings you back here when it has. Copy each value into your DNS and the step ticks itself off: the site checks again every hour for a day, so you can close the tab. Nothing SendBeam sends for you leaves your own domain until this is done. 4. Pick your signup form (and, if you like, a contact form and a pop-up form) from the dropdown of your own forms. 5. Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. @@ -99,6 +101,18 @@ Only what you actually use, and the plugin works with less: Placing a form or a pop-up needs no key at all. Make a separate key for each site under Settings → API keys in SendBeam, and you can define `SENDBEAM_API_KEY` in `wp-config.php` instead of saving it in the database. += Can I send from a domain that is not this site's? = + +Yes. The consent page suggests this site's own domain and lets you type another — a brand domain, or a `mail.` subdomain — and that is what SendBeam sets up and what the plugin shows from then on. If this site runs on a hosting company's own domain (something.wordpress.com and the like) you cannot send from it at all, and the consent page says so and asks for one you own. + += What happens to my list and my forms if I disconnect? = + +They stay in SendBeam. Disconnecting revokes this site's key and nothing else: your list, your form, your sending domain and your sender are all still there, and any other site sending from that domain carries on. On this site it puts back the settings Connect filled in for you, and leaves anything you set yourself alone. + += The form step will not tick, but the form is on my site = + +It looks in pages and posts, block templates, widgets and the layouts page builders store alongside a page — but not in a theme that prints the shortcode from PHP, or a page built somewhere it cannot read. Press "I've placed it elsewhere" on that step and it will take your word for it. + = Does it work with Contact Form 7, Elementor Pro, WPForms, Gravity Forms or Fluent Forms? = Yes. Each is set up where that plugin keeps its own settings, and the Audience tab lists which are active: @@ -138,6 +152,19 @@ Yes. The form is an iframe and the pop-up is a script tag, both cache-safe. * Site email can be switched on from the Overview in one click, but only once the sending domain is verified. A site's password resets should never start going out through a domain that has not been set up. * **Disconnect** is now a visible button on the Overview, and it revokes the key in SendBeam before forgetting it here. Before, it only forgot this site's copy and left the key live in your account. * If your browser blocks the pop-up, connecting now carries on in the same tab and offers a link back instead of a blank window. +* You choose the domain you send from. The consent page suggests this site's own and lets you type another — a brand domain, or a `mail.` subdomain — and the plugin shows whichever one you picked rather than guessing from the site address. +* The DNS table says which records are live. Two of three right used to look exactly like none of them. +* Nothing on the table mentions priority any more: every record SendBeam asks for is a CNAME, so there is no priority box to fill in at your registrar. +* The site checks the DNS again by itself, once an hour for a day after you connect, and switches your site email on the moment the domain verifies. Records almost never spread while you are still sitting in wp-admin. +* **Set up DNS automatically** brings you back to this screen when your registrar has finished, and says whether it worked. +* When there is no sending domain, the step says which of the four reasons it is — you did not tick the box, the key is too old to read domains, there is no domain for this site, or SendBeam could not be reached — instead of "not set up" for all of them. +* A step that needs a permission you did not give now offers **Reconnect with more permissions**, and the connected card has a plain **Reconnect**. Neither needs you to disconnect first. +* **Disconnect** puts back the settings Connect filled in — the form it chose, the sender it worked out, the site email it switched on — and leaves anything you set yourself alone. Your list, form, sending domain and sender stay in SendBeam, where your other sites may still be using them. +* "Put a form on the site" now looks in block templates, widgets and page-builder layouts as well as in pages and posts, says where it found one, and takes your word for it if you have put a form somewhere it cannot see. +* The Overview no longer waits on a slow SendBeam: it gives up after four seconds and shows the last answer it had, marked as old, rather than an empty panel. +* Two administrators signed in to different workspaces no longer see each other's sending domain for a minute. +* On a site with the key set in `wp-config.php`, the Overview says so instead of offering a button that would store a second key nothing would use. +* "Last checked" is now a time you can read, in your site's own date format and timezone. = 1.8.2 = * Pop-ups come in four styles — split with image, editorial, bold colour and slide-in — with an image, an eyebrow, a button label and an optional subscriber count, set per pop-up. From a792100cba929246d4ba2bb3a2d9c0f6976c1e50 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:16:43 +0000 Subject: [PATCH 19/75] Prove the sender address Connect set up lands in an empty From field --- tests/smoke.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/smoke.php b/tests/smoke.php index 2dbaf62..036c254 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1028,6 +1028,14 @@ function sb_v2_exchange( $body, $settings = array() ) { ok( empty( $v2['mail_enabled'] ), 'connect v2: a verified domain does not switch on site email the key cannot send' ); ok( '' === $v2['mail_from_name'], 'connect v2: the sender is not filled in for a key that cannot send' ); +// Provisioning defaults the workspace sender to hello@ when the +// workspace has none. Whatever it comes back as, it fills an empty From +// address here and never overwrites one that is set. +sb_v2_exchange( sb_v2_body( array( 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'hello@mail.brand.co.uk' ) ) ) ); +ok( 'hello@mail.brand.co.uk' === sendbeam_settings()['mail_from_email'], 'connect v2: the sender address SendBeam set up lands in the empty From address' ); +sb_v2_exchange( sb_v2_body( array( 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'not an address' ) ) ) ); +ok( '' === sendbeam_settings()['mail_from_email'], 'connect v2: something that is not an address never becomes the From address' ); + // A form the site already chose is never repointed: an embed may be live on a page. sb_v2_exchange( sb_v2_body(), array( 'default_form' => $other ) ); ok( $other === sendbeam_settings()['default_form'], 'connect v2: reconnecting does not repoint a form the site already chose' ); From f504febb06569cc1cfe4f439d372855200c15101 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:18:37 +0000 Subject: [PATCH 20/75] Do not act on an answer SendBeam did not just give MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Falling back to the last known status keeps a screen useful when sendbeam.io cannot be reached, but it quietly changed what the buttons mean: a Check now whose request never left would have reported the cached verdict as if it had just been checked, and a cached body from this morning saying the domain had verified would have switched the site's email on. Anything that acts on a status — the button, the hourly re-check, the held-back switch-on — now asks whether the answer is one SendBeam actually just gave. Screens carry on showing the old one, marked as old. --- includes/connect-status.php | 23 ++++++++++++++++++++--- tests/smoke.php | 13 +++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/includes/connect-status.php b/includes/connect-status.php index b1e2bbd..cef502f 100644 --- a/includes/connect-status.php +++ b/includes/connect-status.php @@ -451,6 +451,23 @@ function sendbeam_connect_status( $check = false ) { return $status; } +/** + * Is this answer one SendBeam gave just now? + * + * The difference matters wherever something is about to be *done* on the + * strength of it. Serving a stale body to a screen is a kindness; telling + * somebody who pressed **Check now** that their domain is still unverified, + * when in truth the request never got through, is not — and switching their + * site email on because a cached body from this morning said the domain had + * verified is worse again. + * + * @param array $status A status. + * @return bool + */ +function sendbeam_status_is_fresh( $status ) { + return ! empty( $status['ok'] ) && empty( $status['stale'] ); +} + /** * **Check now**: ask SendBeam to look the DNS up again, then come back. * @@ -470,7 +487,7 @@ function sendbeam_handle_domain_check() { $status = sendbeam_connect_status( true ); $note = 'checked'; - if ( ! $status['ok'] ) { + if ( ! sendbeam_status_is_fresh( $status ) ) { $note = 'unreachable'; } elseif ( '' === $status['domain']['name'] ) { $note = 'nodomain'; @@ -615,7 +632,7 @@ function sendbeam_connect_run_recheck() { } $status = sendbeam_connect_status( true ); - if ( ! $status['ok'] ) { + if ( ! sendbeam_status_is_fresh( $status ) ) { return; // Ask again next hour. } if ( '' === $status['domain']['name'] ) { @@ -643,7 +660,7 @@ function sendbeam_connect_run_recheck() { * @return bool Whether site email was switched on as a result. */ function sendbeam_connect_finish_deferred( $status ) { - if ( empty( $status['domain']['verified'] ) ) { + if ( ! sendbeam_status_is_fresh( $status ) || empty( $status['domain']['verified'] ) ) { return false; } diff --git a/tests/smoke.php b/tests/smoke.php index 036c254..8af8991 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1375,6 +1375,19 @@ function sb_status_body( $verified ) { has( $url, 'sendbeam_domain=verified', 'check: a verified domain is still reported' ); ok( empty( sendbeam_settings()['mail_enabled'] ), 'check: a verified domain does NOT re-enable site email the owner switched off' ); +// A check that never got through is not a check. Serving the last answer to +// a screen is a kindness; telling somebody who pressed the button that their +// domain is still unverified, when the request never left, is not. +sb_deferred_site(); +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); +sendbeam_connect_status(); +$GLOBALS['stub']['remote_reply'] = new WP_Error( 'http_request_failed', 'cURL error 28' ); +$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check' ); +$_REQUEST = $_POST; +$url = sb_run_admin_post( 'sendbeam_handle_domain_check' ); +has( $url, 'sendbeam_domain=unreachable', 'check: a check that failed says so, even with a verified answer in the cache' ); +ok( empty( sendbeam_settings()['mail_enabled'] ), 'check: and switches nothing on off the back of a cached claim' ); + // Nonce and capability. sb_deferred_site(); $_POST = array(); From c4bbc0a8898e30b040c365ada64367a204e94743 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:25:54 +0000 Subject: [PATCH 21/75] Do not offer to paste a key wp-config.php would overrule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Connect panel already says, on a site that defines SENDBEAM_API_KEY, that the live key is the one in wp-config.php and that connecting here would store a second key nothing ever reads. The paste field underneath went on offering exactly that — a key saved into the options table that loses to the constant on every single request. It is no longer rendered on those sites. The sentence above it is the whole answer: the key lives in wp-config.php, and that is where it changes. --- includes/screens.php | 8 ++++++++ tests/smoke.php | 2 ++ 2 files changed, 10 insertions(+) diff --git a/includes/screens.php b/includes/screens.php index d3a604d..4eafbe4 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -515,8 +515,16 @@ function sendbeam_overview_mail_panel( $status, $connected ) { * * Open by default would make the screen look like it still wants a key * copied across, which is the friction Connect exists to remove. + * + * On a site whose key is pinned in wp-config.php there is nothing to paste: + * a key saved here would lose to the constant on every request. The panel + * above has already said where the live key is, so this simply goes away + * rather than inviting somebody to store a second one. */ function sendbeam_connect_paste_disclosure() { + if ( sendbeam_key_in_config() ) { + return; + } echo '
      '; echo '' . esc_html__( 'I already have an API key', 'sendbeam' ) . ''; echo '
      '; diff --git a/tests/smoke.php b/tests/smoke.php index 8af8991..59fa750 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1944,6 +1944,8 @@ function sb_overview( $settings, $status, $get = array() ) { $ov = sb_overview( array(), array() ); has( $ov, 'SENDBEAM_API_KEY in wp-config.php', 'overview: a site with the key pinned in wp-config is told where its key is' ); lacks( $ov, 'Connect SendBeam', 'overview: and is not offered a button that would store a key nothing uses' ); +lacks( $ov, 'I already have an API key', 'overview: nor a paste field whose key wp-config.php would overrule' ); +lacks( $ov, 'sendbeam_settings[api_key]', 'overview: the paste field itself is gone, not merely folded away' ); $ov = sb_overview( $sb_connected, $sb_verified ); has( $ov, 'Disconnect will not revoke it', 'overview: the connected card says the live key is the pinned one' ); From 608e3b34c81c403942151821c3a3f2ce2ab435c2 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:27:37 +0000 Subject: [PATCH 22/75] Let go of the old workspace before joining a new one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reconnecting is how a site changes workspace, and everything Connect filled in names something in the workspace it has just left. The form ID stayed behind in the settings, so every embed on the site went on asking a workspace this site no longer has a key for and 404ing without a word; the From address went on naming a domain the new workspace cannot send from. The site now remembers which workspace it joined, by ID rather than by name — names are not unique and renaming one is not moving to another. When an exchange comes back from a different workspace, the values Connect filled are released first, and the fills that follow come entirely out of the new workspace's answer. Anything the owner typed themselves is not on that list and is untouched, and reconnecting into the same workspace still leaves a live embed pointing where it pointed. --- includes/connect.php | 68 +++++++++++++++++++++++++++++++++++++++---- includes/helpers.php | 5 ++++ includes/settings.php | 7 +++-- tests/smoke.php | 44 ++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 9 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index 1ede520..a8b84f7 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -535,9 +535,32 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { $before = sendbeam_settings(); $filled = isset( $before['sendbeam_connect_filled'] ) && is_array( $before['sendbeam_connect_filled'] ) ? $before['sendbeam_connect_filled'] : array(); - $clean['sendbeam_connected_via'] = 'connect'; - $clean['sendbeam_connect_workspace'] = $workspace; - $clean['sendbeam_connect_granted'] = implode( ',', $granted ); + /* + * A reconnect into a *different* workspace is not a reconnect, it is a + * move. Everything Connect filled in points at the workspace this site + * has just left — a form ID the new workspace does not own, a From + * address on a domain it cannot send from — and carrying it across is + * how an embed starts 404ing silently on a live page. So the filled-in + * values are released first, and the fills below start from empty and + * come entirely out of the new workspace's answer. Anything the owner + * typed themselves is not on that list, and is left alone. + */ + if ( sendbeam_connect_moved_workspace( $before, $status, $workspace ) ) { + foreach ( array( 'default_form', 'mail_from_name', 'mail_from_email' ) as $key ) { + if ( in_array( $key, $filled, true ) ) { + $clean[ $key ] = ''; + } + } + if ( in_array( 'mail_enabled', $filled, true ) ) { + $clean['mail_enabled'] = 0; + } + $filled = array(); + } + + $clean['sendbeam_connected_via'] = 'connect'; + $clean['sendbeam_connect_workspace'] = $workspace; + $clean['sendbeam_connect_workspace_id'] = (string) $status['workspace']['id']; + $clean['sendbeam_connect_granted'] = implode( ',', $granted ); // The form SendBeam made during consent becomes this site's default, but // only when the site has not already chosen one: a reconnect must not @@ -587,6 +610,38 @@ function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { return true; } +/** + * Did this connection land in a different workspace from the last one? + * + * The ID is the answer wherever there is one on both sides: workspace names + * are not unique and can be changed, so comparing them would call a rename a + * move and miss two workspaces that happen to share a name. Connections made + * before the ID was recorded have only the name, and the name is better than + * nothing for them. + * + * A site that has never connected has nothing to move away from, so it is + * never a move — the first connection must not throw away settings the owner + * put there by hand before it. + * + * @param array $before This site's settings before the write. + * @param array $status The normalised exchange response. + * @param string $workspace The workspace name the exchange reported. + * @return bool + */ +function sendbeam_connect_moved_workspace( $before, $status, $workspace ) { + $was_id = isset( $before['sendbeam_connect_workspace_id'] ) ? (string) $before['sendbeam_connect_workspace_id'] : ''; + $now_id = isset( $status['workspace']['id'] ) ? (string) $status['workspace']['id'] : ''; + if ( '' !== $was_id && '' !== $now_id ) { + return $was_id !== $now_id; + } + + $was_name = isset( $before['sendbeam_connect_workspace'] ) ? (string) $before['sendbeam_connect_workspace'] : ''; + if ( '' === $was_name || '' === (string) $workspace ) { + return false; + } + return $was_name !== (string) $workspace; +} + /** * Which permissions the key actually carries. * @@ -690,9 +745,10 @@ function sendbeam_connect_disconnect() { } $settings['api_key'] = ''; - $settings['sendbeam_connected_via'] = ''; - $settings['sendbeam_connect_workspace'] = ''; - $settings['sendbeam_connect_notes'] = array(); + $settings['sendbeam_connected_via'] = ''; + $settings['sendbeam_connect_workspace'] = ''; + $settings['sendbeam_connect_workspace_id'] = ''; + $settings['sendbeam_connect_notes'] = array(); $settings['sendbeam_connect_granted'] = ''; $settings['sendbeam_connect_filled'] = array(); $settings['sendbeam_mail_deferred'] = 0; diff --git a/includes/helpers.php b/includes/helpers.php index 036b150..c319512 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -53,6 +53,11 @@ function sendbeam_default_settings() { // Cleared the moment the key is changed or removed by hand. 'sendbeam_connected_via' => '', 'sendbeam_connect_workspace' => '', + // The workspace's own ID, which is what says whether a reconnect + // landed in the same workspace or a different one. The name cannot + // answer that: two workspaces can share one, and renaming a + // workspace would otherwise look like moving to another. + 'sendbeam_connect_workspace_id' => '', // The permissions SendBeam actually granted this key, as a csv. What // was *asked* for is not the same thing — the person can untick a box // on the consent page — and the Overview has to say "you did not give diff --git a/includes/settings.php b/includes/settings.php index e53cff2..be82003 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -261,9 +261,10 @@ function sendbeam_sanitize_settings( $input ) { // it and that key is on its way out. sendbeam_connect_forget_status( (string) $saved['api_key'] ); sendbeam_flush_cache(); - $out['sendbeam_connected_via'] = ''; - $out['sendbeam_connect_workspace'] = ''; - $out['sendbeam_connect_notes'] = array(); + $out['sendbeam_connected_via'] = ''; + $out['sendbeam_connect_workspace'] = ''; + $out['sendbeam_connect_workspace_id'] = ''; + $out['sendbeam_connect_notes'] = array(); // The permissions and the held-back site email belonged to the old // key. A pasted key's permissions are unknown, and claiming the old // ones would offer buttons that cannot work. diff --git a/tests/smoke.php b/tests/smoke.php index 59fa750..e82eae8 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1045,6 +1045,50 @@ function sb_v2_exchange( $body, $settings = array() ) { $v2 = sendbeam_settings(); ok( 'orders@harbourlane.co.uk' === $v2['mail_from_email'] && 'Orders' === $v2['mail_from_name'], 'connect v2: a sender the owner set is left alone' ); +// ── Reconnecting into a different workspace ──────────────────────────── +// Everything Connect filled in names something in the workspace this site +// has just left: a form the new workspace does not own 404s on every page it +// is embedded on, and a From address on a domain it cannot send from bounces. +sb_v2_exchange( sb_v2_body() ); +$v2_first = sendbeam_settings(); +ok( $form === $v2_first['default_form'], 'workspace move: the first connection fills the form in' ); +ok( 'ws_1' === $v2_first['sendbeam_connect_workspace_id'], 'workspace move: the workspace ID is remembered, not only its name' ); + +$sb_second = sb_v2_body( + array( + 'api_key' => 'sb_live_' . str_repeat( 'm', 32 ), + 'workspace' => array( 'id' => 'ws_2', 'name' => 'Second Roastery' ), + 'default_form' => array( 'id' => $other, 'name' => 'Second signup' ), + 'sender' => array( 'from_name' => 'Second Roastery', 'from_email' => 'hello@second.example' ), + ) +); +sb_v2_exchange( $sb_second, $v2_first ); +$v2_moved = sendbeam_settings(); +ok( $other === $v2_moved['default_form'], 'workspace move: the old workspace\'s form is released, and the new workspace\'s takes its place' ); +ok( 'hello@second.example' === $v2_moved['mail_from_email'], 'workspace move: the sender follows the site to the new workspace' ); +ok( 'ws_2' === $v2_moved['sendbeam_connect_workspace_id'], 'workspace move: the new workspace ID is what is remembered afterwards' ); + +// The same workspace is not a move: nothing is released, and a reconnect +// does not repoint an embed that is live on a page. +sb_v2_exchange( sb_v2_body() ); +$v2_first = sendbeam_settings(); +sb_v2_exchange( sb_v2_body( array( 'api_key' => 'sb_live_' . str_repeat( 'n', 32 ) ) ), $v2_first ); +ok( $form === sendbeam_settings()['default_form'], 'workspace move: reconnecting into the same workspace keeps what Connect filled' ); + +// A setting the owner typed is not Connect's to release, wherever the site +// reconnects to. Saving the tab by hand is what takes it off the list. +sb_v2_exchange( sb_v2_body() ); +$v2_owned = sendbeam_settings(); +$v2_owned['mail_from_email'] = 'orders@harbourlane.co.uk'; +$v2_owned['sendbeam_connect_filled'] = array_values( array_diff( $v2_owned['sendbeam_connect_filled'], array( 'mail_from_email' ) ) ); +sb_v2_exchange( $sb_second, $v2_owned ); +ok( 'orders@harbourlane.co.uk' === sendbeam_settings()['mail_from_email'], 'workspace move: an address the owner typed survives the move' ); + +// What counts as a move. +ok( ! sendbeam_connect_moved_workspace( array(), array( 'workspace' => array( 'id' => 'ws_1' ) ), 'Harbour Lane' ), 'workspace move: a first connection has nothing to move away from' ); +ok( sendbeam_connect_moved_workspace( array( 'sendbeam_connect_workspace' => 'Harbour Lane' ), array( 'workspace' => array( 'id' => '' ) ), 'Second Roastery' ), 'workspace move: a connection made before IDs were recorded falls back to the name' ); +ok( ! sendbeam_connect_moved_workspace( array( 'sendbeam_connect_workspace_id' => 'ws_1', 'sendbeam_connect_workspace' => 'Old Name' ), array( 'workspace' => array( 'id' => 'ws_1' ) ), 'New Name' ), 'workspace move: renaming a workspace is not moving to another one' ); + // ── /api/v1/connect/status ───────────────────────────────────────────── sb_connect_reset(); sendbeam_connect_forget_status(); From ab7637288945a29cd1a734c0f5aabdfd0557e7e0 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:28:10 +0000 Subject: [PATCH 23/75] Offer the way out on the step somebody is standing on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Site email held back by an unverified domain says it is waiting on step 2. When step 2 is itself waiting on a permission that was never ticked, the sentence sent the owner up the page to find a link that is the same link — and the step they actually came to use offered nothing at all. It now carries the reconnect link as well whenever the missing piece is the domain permission, not only when it is the send permission. --- includes/onboarding.php | 7 +++++++ tests/smoke.php | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/includes/onboarding.php b/includes/onboarding.php index cc46091..46d12b1 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -381,6 +381,13 @@ function sendbeam_setup_steps() { $mail_reconnect = true; } elseif ( ! $verified ) { $mail_detail = __( 'Waiting on step 2: this site\'s email can only go out once the sending domain is verified.', 'sendbeam' ); + /* + * Step 4 is waiting on step 2, and step 2 is waiting on a permission + * nobody ticked. Sending the owner to step 2 to read that is one hop + * too many when the way out is the same link either way: this step + * offers it as well, because this is the step they came to use. + */ + $mail_reconnect = $domain_reconnect; } else { $mail_detail = __( 'Ready. Switch it on and password resets, receipts and notifications go out through your own domain.', 'sendbeam' ); } diff --git a/tests/smoke.php b/tests/smoke.php index e82eae8..bfeecc9 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1951,6 +1951,10 @@ function sb_overview( $settings, $status, $get = array() ) { $ov = sb_overview( $sb_nodomain_scope, array( 'workspace' => array( 'id' => 'ws_1' ), 'domain_state' => 'not_granted' ) ); has( $ov, 'Reconnect with more permissions', 'overview: a step that names a missing permission offers to reconnect' ); has( $ov, 'action=sendbeam_connect_start', 'overview: the reconnect link starts the Connect flow' ); +// Site email is waiting on step 2, and step 2 is waiting on a permission +// nobody ticked. The way out is offered on the step the owner came to use, +// not only on the one it is queued behind. +ok( 2 === substr_count( $ov, 'Reconnect with more permissions' ), 'overview: the site email step offers the reconnect too when the domain permission is the missing piece' ); $ov = sb_overview( $sb_connected, $sb_verified ); lacks( $ov, 'Reconnect with more permissions', 'overview: a step with nothing missing does not offer it' ); has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); From 89a15a404232188152b92262b92e5b71c3a96906 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:28:51 +0000 Subject: [PATCH 24/75] Say how to change the domain, not only how to finish it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sending host is chosen once, on the consent page, and the plugin never mentioned that again. A site owner who set up the wrong domain — the site's own rather than the brand's, or a subdomain they meant to keep for something else — had a step full of DNS records for a domain they did not want and no sentence anywhere saying where the choice was made. Step 2 now carries one line to the consent page at all times, including when the domain is verified and everything looks finished, because that is when people notice. --- includes/screens.php | 14 ++++++++++++++ tests/smoke.php | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/includes/screens.php b/includes/screens.php index 4eafbe4..aa7dc5d 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -219,6 +219,20 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { break; case 'domain': sendbeam_overview_domain_panel( $status, $connected ); + /* + * The domain this site sends from is chosen on the consent page, + * and going back there is the only way to change it. Nothing said + * so while the step was working — which is precisely when someone + * notices they set up the wrong domain, and the point at which + * every other sentence on the step has stopped talking to them. + */ + if ( $connected ) { + printf( + '

      %s

      ', + esc_url( sendbeam_connect_start_url() ), + esc_html__( 'Sending from the wrong domain? Reconnect and enter the one you want.', 'sendbeam' ) + ); + } break; case 'form': sendbeam_overview_form_panel( $step, $connected ); diff --git a/tests/smoke.php b/tests/smoke.php index bfeecc9..a2ac5bf 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1957,6 +1957,15 @@ function sb_overview( $settings, $status, $get = array() ) { ok( 2 === substr_count( $ov, 'Reconnect with more permissions' ), 'overview: the site email step offers the reconnect too when the domain permission is the missing piece' ); $ov = sb_overview( $sb_connected, $sb_verified ); lacks( $ov, 'Reconnect with more permissions', 'overview: a step with nothing missing does not offer it' ); +// Changing the domain a site sends from means going back to the consent +// page, and a verified domain is exactly when somebody notices it is the +// wrong one — so the line is there whether anything is missing or not. +has( $ov, 'Sending from the wrong domain? Reconnect and enter the one you want.', 'overview: a working domain step still says how to change the domain' ); +$ov = sb_overview( $sb_connected, array( 'workspace' => array( 'id' => 'ws_1' ), 'domain_state' => 'no_site' ) ); +has( $ov, 'Sending from the wrong domain? Reconnect and enter the one you want.', 'overview: and so does a step with no domain at all' ); +$ov = sb_overview( array(), array( 'workspace' => array( 'id' => 'ws_1' ), 'domain_state' => 'no_site' ) ); +lacks( $ov, 'Sending from the wrong domain?', 'overview: a site that has not connected is not offered a reconnection' ); +$ov = sb_overview( $sb_connected, $sb_verified ); has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); // ── Back from the registrar ──────────────────────────────────────────── From 3408557b51ff5caf0a29b190995394a7e77c480f Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:29:45 +0000 Subject: [PATCH 25/75] Believe the owner about a form this site cannot see MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "I've placed it elsewhere" link is the answer for a form nothing on this site can read: one kept in a page builder's own storage, one on a page behind a login, one named in its own shortcode rather than by the default. It was offered only when a default or contact form had been chosen here, which is exactly the site that does not need it — and the sites that do were left with a step that would never tick and no way to say so. It is now offered whenever there is any form in the workspace at all. The shortcode beside it still appears only when there is a default form for it to mean. --- includes/screens.php | 30 ++++++++++++++++++++++-------- tests/smoke.php | 16 ++++++++++++++-- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/includes/screens.php b/includes/screens.php index aa7dc5d..3202926 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -462,17 +462,31 @@ function sendbeam_overview_form_panel( $step, $connected ) { } $settings = sendbeam_settings(); - if ( '' === (string) $settings['default_form'] && '' === (string) $settings['contact_form'] ) { + $chosen = '' !== (string) $settings['default_form'] || '' !== (string) $settings['contact_form']; + $forms = sendbeam_remote_forms(); + + /* + * The override is the answer for a form this site cannot find — one in a + * page builder's own storage, or on a page behind a login. That is not + * conditional on a *default* form being chosen: the form on the page may + * be named in its own shortcode, and this step was leaving those sites + * with an untickable step and no way to say so. Any form in the workspace + * is enough of a reason to offer it. + */ + if ( ! $chosen && ! ( is_array( $forms ) && $forms ) ) { return; } - echo '
      [sendbeam_form]'; - printf( - '', - esc_attr( '[sendbeam_form]' ), - esc_attr__( 'Copied', 'sendbeam' ), - esc_html__( 'Copy', 'sendbeam' ) - ); + echo '
      '; + if ( $chosen ) { + echo '[sendbeam_form]'; + printf( + '', + esc_attr( '[sendbeam_form]' ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy', 'sendbeam' ) + ); + } printf( '%s', esc_url( sendbeam_form_placed_url() ), diff --git a/tests/smoke.php b/tests/smoke.php index a2ac5bf..fdc7a47 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1847,9 +1847,10 @@ function sb_placement( $db, $options = array() ) { * @param array $settings Saved settings. * @param array $status Status payload, as the API would send it. * @param array $get Query arguments on the screen. + * @param array $forms The forms this key can see in the workspace. * @return string */ -function sb_overview( $settings, $status, $get = array() ) { +function sb_overview( $settings, $status, $get = array(), $forms = array() ) { $GLOBALS['stub']['caps']['manage_options'] = true; $GLOBALS['stub']['user_id'] = 7; $GLOBALS['stub']['current_user'] = array( 'email' => 'admin@example-site.test' ); @@ -1857,7 +1858,7 @@ function sb_overview( $settings, $status, $get = array() ) { $_GET = $get; update_option( 'sendbeam_settings', $settings ); set_transient( 'sendbeam_connection', array( 'state' => '' === (string) ( $settings['api_key'] ?? '' ) ? 'none' : 'ok', 'message' => '', 'count' => 1 ) ); - set_transient( 'sendbeam_remote_forms', array() ); + set_transient( 'sendbeam_remote_forms', $forms ); set_transient( 'sendbeam_remote_lists', array() ); set_transient( 'sendbeam_subscriber_count', 0 ); sendbeam_connect_cache_status( sendbeam_connect_normalise_status( $status ) ); @@ -1968,6 +1969,17 @@ function sb_overview( $settings, $status, $get = array() ) { $ov = sb_overview( $sb_connected, $sb_verified ); has( $ov, '>Reconnect<', 'overview: the connected card offers a plain Reconnect beside Disconnect' ); +// The form step's override exists for a form nothing on this site can read: +// one stored by a page builder, or on a page behind a login. That does not +// depend on a *default* form being chosen — the form on the page may name +// itself — so any form in the workspace is reason enough to offer it. +$ov = sb_overview( $sb_connected, $sb_unverified ); +lacks( $ov, 'I've placed it elsewhere', 'overview: no override while the workspace has no form to have placed' ); +$sb_one_form = array( array( 'id' => $form, 'name' => 'Newsletter signup', 'kind' => 'signup' ) ); +$ov = sb_overview( $sb_connected, $sb_unverified, array(), $sb_one_form ); +has( $ov, 'I've placed it elsewhere', 'overview: a workspace with a form offers the override even when no default is chosen' ); +lacks( $ov, '[sendbeam_form]', 'overview: and does not hand out a shortcode that names no form' ); + // ── Back from the registrar ──────────────────────────────────────────── // Automatic DNS used to end on SendBeam's own sending settings: a reasonable // place to finish if you started there, and the wrong one entirely when you From d929d9cadf17d328930f6869f07cde52c3b3d48e Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:30:25 +0000 Subject: [PATCH 26/75] Say the check has run, because it has MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Coming back from the registrar said "Checking now…", which promised a page about to change and then never changed: the check runs at the top of that same render, so the step underneath is already showing what it found by the time anybody reads the line above it. It now says the records were checked just now, in the tense it happened in. --- includes/connect.php | 4 ++-- includes/screens.php | 6 +++++- tests/smoke.php | 5 +++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index a8b84f7..60de30d 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -960,8 +960,8 @@ function sendbeam_connect_admin_js() { /* * Coming back from a registrar leaves sb_dc in the address bar, and * sb_dc=done spends a check. A refresh, or a bookmark, would spend - * another one and print "Checking now…" over a page that is not, - * so the flag is taken off the URL the moment it has been read. + * another one and say the records were checked just now when they + * were not, so the flag comes off the URL the moment it is read. */ if ( window.history && history.replaceState && window.URL ) { try { diff --git a/includes/screens.php b/includes/screens.php index 3202926..bc82fcb 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -131,7 +131,11 @@ function sendbeam_overview_notices() { // carries SendBeam's own reason code, and the table is fixed sentences. $returned = sendbeam_overview_dns_return(); if ( 'done' === $returned ) { - echo '

      ' . esc_html__( 'Your registrar added the records. Checking now…', 'sendbeam' ) . '

      '; + // Past tense on purpose: the check ran at the top of this render, so + // by the time anybody reads this the step underneath is already + // showing what it found. "Checking now…" promised a page that was + // about to change and then never changed. + echo '

      ' . esc_html__( 'Your registrar added the records. Checked just now.', 'sendbeam' ) . '

      '; } elseif ( 'error' === $returned ) { echo '

      ' . esc_html( sprintf( diff --git a/tests/smoke.php b/tests/smoke.php index fdc7a47..711f8f7 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1992,7 +1992,8 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); sendbeam_connect_forget_status(); $ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => 'done' ) ); -has( $ov, 'Your registrar added the records. Checking now', 'automatic DNS: coming back says what happened' ); +has( $ov, 'Your registrar added the records. Checked just now.', 'automatic DNS: coming back says what happened, in the tense it happened in' ); +has( $ov, 'harbourlane.co.uk is verified', 'automatic DNS: and the step underneath is already showing what the check found' ); $sb_posts = array_filter( $GLOBALS['stub']['remote'], function ( $r ) { return 'POST' === $r['method']; } ); ok( 1 === count( $sb_posts ), 'automatic DNS: coming back spends exactly one check' ); ok( ! empty( sendbeam_settings()['mail_enabled'] ), 'automatic DNS: a domain that verifies finishes the held-back switch-on' ); @@ -2005,7 +2006,7 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { $ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => '' ) ); lacks( $ov, 'alert(1)', 'automatic DNS: the flag is one of two values, not a message to print' ); -lacks( $ov, 'Checking now', 'automatic DNS: and anything else is ignored' ); +lacks( $ov, 'Checked just now', 'automatic DNS: and anything else is ignored' ); has( sendbeam_connect_admin_js(), 'sb_dc', 'automatic DNS: the flag is taken off the address bar once it has been read' ); // A key pinned in wp-config.php beats anything stored here, so connecting From 3cc15d152bb449c7f893ea94e67d593f474f8cf0 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:32:15 +0000 Subject: [PATCH 27/75] Point step one at the button, not at the fallback under it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 1 of the checklist linked to the paste field — the way of connecting this plugin stopped leading with a release ago, and the one now folded away inside a disclosure. Following the checklist therefore walked straight past the Connect button to the thing it exists to replace. The Connect panel now has an id and step 1 points at it. A site whose key is pinned in wp-config.php has no panel to point at, so it keeps the key field's anchor. --- includes/connect.php | 12 ++++++++++-- includes/onboarding.php | 6 +++++- includes/screens.php | 2 +- tests/smoke.php | 12 ++++++++++++ 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index 60de30d..0e3b174 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -874,6 +874,13 @@ function sendbeam_connect_render_result( $connected, $heading, $detail, $is_popu function sendbeam_connect_panel() { $origin = sendbeam_connect_site_origin(); + /* + * The id is what step 1 links to. It is on the wrapper rather than on the + * button, so every version of this panel — the button, the note about + * wp-config.php, the note about http — is what the link lands on. + */ + echo '

      '; + /* * A key defined in wp-config.php beats anything stored here, everywhere. * Connecting on such a site mints a key, stores it, and then never uses @@ -882,12 +889,12 @@ function sendbeam_connect_panel() { * live key actually is. */ if ( sendbeam_key_in_config() ) { - echo '

      ' . esc_html__( 'This site sends with the key defined as SENDBEAM_API_KEY in wp-config.php. That key wins over anything saved here, so connecting would store a second key nothing would ever use. Change it in wp-config.php, or remove that line to connect from this screen instead.', 'sendbeam' ) . '

      '; + echo '

      ' . esc_html__( 'This site sends with the key defined as SENDBEAM_API_KEY in wp-config.php. That key wins over anything saved here, so connecting would store a second key nothing would ever use. Change it in wp-config.php, or remove that line to connect from this screen instead.', 'sendbeam' ) . '

      '; return; } if ( ! sendbeam_connect_origin_ok( $origin ) ) { - echo '

      ' . esc_html__( 'This site is not served over https, so SendBeam cannot connect to it. Paste an API key below instead.', 'sendbeam' ) . '

      '; + echo '

      ' . esc_html__( 'This site is not served over https, so SendBeam cannot connect to it. Paste an API key below instead.', 'sendbeam' ) . '

      '; return; } @@ -926,6 +933,7 @@ function sendbeam_connect_panel() { esc_html__( 'Connect SendBeam', 'sendbeam' ) ); echo ''; + echo '
      '; } /** diff --git a/includes/onboarding.php b/includes/onboarding.php index 46d12b1..3f3e01d 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -398,7 +398,11 @@ function sendbeam_setup_steps() { 'done' => $connected, 'label' => __( 'Connect your SendBeam account', 'sendbeam' ), 'detail' => sendbeam_connect_step_sentence( $connected ), - 'target' => sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', + // The button, where there is one. A site whose key is pinned in + // wp-config.php has no Connect panel and no paste field either, + // so the old anchor is kept for the one screen that still has a + // key field on it: a key pasted by hand. + 'target' => sendbeam_tab_url( 'overview' ) . ( sendbeam_key_in_config() ? '#sendbeam_api_key' : '#sendbeam-connect' ), ), array( 'key' => 'domain', diff --git a/includes/screens.php b/includes/screens.php index bc82fcb..4ab2b10 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -232,7 +232,7 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { */ if ( $connected ) { printf( - '

      %s

      ', + '

      %s

      ', esc_url( sendbeam_connect_start_url() ), esc_html__( 'Sending from the wrong domain? Reconnect and enter the one you want.', 'sendbeam' ) ); diff --git a/tests/smoke.php b/tests/smoke.php index 711f8f7..99141d4 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -625,6 +625,14 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), lacks( $sb_ov, 'Check now', 'overview: nothing offers to check a domain that does not exist' ); lacks( $sb_ov, 'value="sendbeam_disconnect"', 'overview: nothing offers to disconnect what is not connected' ); has( $sb_ov, 'Connect the site first', 'overview: the domain step says to connect first' ); +// Step 1 names the thing it is asking for. It pointed at the paste field, +// which is the one way of connecting this plugin no longer leads with, so +// anything following the checklist walked straight past the button to the +// fallback folded away underneath it. +has( $sb_panel, 'id="sendbeam-connect"', 'panel: the Connect panel is something a link can land on' ); +$sb_steps = sendbeam_setup_steps(); +has( $sb_steps[0]['target'], '#sendbeam-connect', 'steps: step 1 points at the Connect panel' ); +lacks( $sb_steps[0]['target'], '#sendbeam_api_key', 'steps: not at the paste field underneath it' ); sb_connect_reset(); sendbeam_connect_forget_status(); @@ -637,6 +645,10 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), // wp-config constant wins over the option. define( 'SENDBEAM_API_KEY', 'sb_const_0123456789abcdef' ); ok( sendbeam_api_key() === 'sb_const_0123456789abcdef', 'constant wins' ); +// With the key pinned there is no Connect panel and no paste field either, +// so step 1 keeps the anchor of the one key field a site can still have: the +// card a pasted key gets. +has( sendbeam_setup_steps()[0]['target'], '#sendbeam_api_key', 'steps: a pinned key leaves step 1 pointing at the key field' ); // ── Connect ──────────────────────────────────────────────────────────── // From 84588a5419cbaba1c5a801f44b08348c3479d937 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:33:21 +0000 Subject: [PATCH 28/75] Give the two new block comments the blank line the standard wants Squiz.Commenting.BlockComment.NoEmptyLineBefore, in the reconnect branch on step 4 and above the wrong-domain line on step 2. Whitespace only. --- includes/onboarding.php | 1 + includes/screens.php | 1 + 2 files changed, 2 insertions(+) diff --git a/includes/onboarding.php b/includes/onboarding.php index 3f3e01d..808297f 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -381,6 +381,7 @@ function sendbeam_setup_steps() { $mail_reconnect = true; } elseif ( ! $verified ) { $mail_detail = __( 'Waiting on step 2: this site\'s email can only go out once the sending domain is verified.', 'sendbeam' ); + /* * Step 4 is waiting on step 2, and step 2 is waiting on a permission * nobody ticked. Sending the owner to step 2 to read that is one hop diff --git a/includes/screens.php b/includes/screens.php index 4ab2b10..74a5a65 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -223,6 +223,7 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { break; case 'domain': sendbeam_overview_domain_panel( $status, $connected ); + /* * The domain this site sends from is chosen on the consent page, * and going back there is the only way to change it. Nothing said From 246e2d5ed065e726f62ec1e0e9cc7bf572f41976 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 06:34:36 +0000 Subject: [PATCH 29/75] Line up the assignments the new setting lengthened The workspace ID is a longer key than anything beside it, so the default settings array and the disconnect block were left with their arrows out of step. Whitespace only. --- includes/connect.php | 8 +++---- includes/helpers.php | 52 ++++++++++++++++++++++---------------------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/includes/connect.php b/includes/connect.php index 0e3b174..970bfa3 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -744,14 +744,14 @@ function sendbeam_connect_disconnect() { $settings['mail_enabled'] = 0; } - $settings['api_key'] = ''; + $settings['api_key'] = ''; $settings['sendbeam_connected_via'] = ''; $settings['sendbeam_connect_workspace'] = ''; $settings['sendbeam_connect_workspace_id'] = ''; $settings['sendbeam_connect_notes'] = array(); - $settings['sendbeam_connect_granted'] = ''; - $settings['sendbeam_connect_filled'] = array(); - $settings['sendbeam_mail_deferred'] = 0; + $settings['sendbeam_connect_granted'] = ''; + $settings['sendbeam_connect_filled'] = array(); + $settings['sendbeam_mail_deferred'] = 0; // Before the key is forgotten, not after: the cached answer is filed // under that key, and a site that has just let go of it can no longer diff --git a/includes/helpers.php b/includes/helpers.php index c319512..e6c4101 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -27,32 +27,32 @@ function sendbeam_app_url() { */ function sendbeam_default_settings() { return array( - 'default_form' => '', - 'contact_form' => '', - 'popup_form' => '', - 'popup_where' => 'off', - 'popup_trigger' => 'timer', - 'popup_delay' => 5, - 'popup_once' => 'day', - 'popup_label' => '', - 'style_accent' => '', - 'style_text' => '', - 'style_field' => '', - 'style_border' => '', - 'style_radius' => '', - 'style_font' => 'inherit', - 'style_size' => '', - 'style_bare' => 1, - 'mail_enabled' => 0, - 'api_key' => '', - 'mail_from_name' => '', - 'mail_from_email' => '', - 'mail_fallback' => 1, + 'default_form' => '', + 'contact_form' => '', + 'popup_form' => '', + 'popup_where' => 'off', + 'popup_trigger' => 'timer', + 'popup_delay' => 5, + 'popup_once' => 'day', + 'popup_label' => '', + 'style_accent' => '', + 'style_text' => '', + 'style_field' => '', + 'style_border' => '', + 'style_radius' => '', + 'style_font' => 'inherit', + 'style_size' => '', + 'style_bare' => 1, + 'mail_enabled' => 0, + 'api_key' => '', + 'mail_from_name' => '', + 'mail_from_email' => '', + 'mail_fallback' => 1, // Set only when the key arrived through Connect, so the Overview can // name the workspace and offer Disconnect rather than a paste field. // Cleared the moment the key is changed or removed by hand. - 'sendbeam_connected_via' => '', - 'sendbeam_connect_workspace' => '', + 'sendbeam_connected_via' => '', + 'sendbeam_connect_workspace' => '', // The workspace's own ID, which is what says whether a reconnect // landed in the same workspace or a different one. The name cannot // answer that: two workspaces can share one, and renaming a @@ -62,18 +62,18 @@ function sendbeam_default_settings() { // was *asked* for is not the same thing — the person can untick a box // on the consent page — and the Overview has to say "you did not give // this site that permission" rather than guess. - 'sendbeam_connect_granted' => '', + 'sendbeam_connect_granted' => '', // Which of this site's settings Connect filled in for the owner, so // that disconnecting can put back exactly what it changed and not one // thing more. Anything the owner has since saved by hand comes off // the list: it is theirs now. - 'sendbeam_connect_filled' => array(), + 'sendbeam_connect_filled' => array(), // Site email was approved at consent time but held back because the // sending domain was not verified yet. The domain check switches it // on and clears this; turning site email off by hand clears it too, // so a later check never re-enables something deliberately switched // off. - 'sendbeam_mail_deferred' => 0, + 'sendbeam_mail_deferred' => 0, ); } From 326b51d7b769200db86211fd1eefb92bc0c430ff Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 07:39:22 +0000 Subject: [PATCH 30/75] Give SendBeam its own menu, so its sections can be found MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything lived at Settings → SendBeam behind seven tabs that did not appear in the admin menu: to reach the pop-up settings you had to know the plugin was under Settings and then know the tab existed. There is now a top-level menu with the three-square mark and a real item per section, one router behind all of them, and a 301 from every old address so bookmarks and support links still land in the right place. The Plugins-screen "Settings" link points at the new Settings page rather than at a dashboard. The Docs tab becomes Help. --- includes/admin-ui.php | 90 ++++++++------ includes/connect.php | 2 +- includes/mail.php | 3 +- includes/menu.php | 258 ++++++++++++++++++++++++++++++++++++++++ includes/onboarding.php | 5 +- includes/screens.php | 200 +++++++++++++++++++++++++++---- includes/settings.php | 93 ++++----------- sendbeam.php | 1 + tests/smoke.php | 155 +++++++++++++++++++++++- tests/wp-stubs.php | 46 +++++++ 10 files changed, 719 insertions(+), 134 deletions(-) create mode 100644 includes/menu.php diff --git a/includes/admin-ui.php b/includes/admin-ui.php index 97a219f..a3251a3 100644 --- a/includes/admin-ui.php +++ b/includes/admin-ui.php @@ -18,49 +18,51 @@ defined( 'ABSPATH' ) || exit; /** - * The tabs, in order. + * The old tab keys, and the page each one became. * - * @return array + * Every handler in the plugin redirects to `sendbeam_tab_url( 'overview' )` + * and friends, and every bookmark anyone made points at + * `options-general.php?page=sendbeam&tab=X`. Keeping one table of what became + * what means the move is a change of address rather than a change of + * behaviour — and the 301 in menu.php reads the same table. + * + * @return array Old tab key => new page slug. */ -function sendbeam_tabs() { +function sendbeam_tab_pages() { return array( - 'overview' => __( 'Overview', 'sendbeam' ), - 'forms' => __( 'Forms', 'sendbeam' ), - 'audience' => __( 'Audience', 'sendbeam' ), - 'popup' => __( 'Pop-ups', 'sendbeam' ), - 'mail' => __( 'Site email', 'sendbeam' ), - 'ecommerce' => __( 'E-commerce events', 'sendbeam' ), - 'docs' => __( 'Docs', 'sendbeam' ), + 'overview' => 'sendbeam', + 'forms' => 'sendbeam-forms', + 'audience' => 'sendbeam-audience', + 'popup' => 'sendbeam-popups', + 'mail' => 'sendbeam-mail', + 'ecommerce' => 'sendbeam-ecommerce', + // The Docs tab is gone; the Help page carries what it held. + 'docs' => 'sendbeam-help', ); } /** - * Which tab is showing. - * - * @return string - */ -function sendbeam_current_tab() { - $tabs = sendbeam_tabs(); - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation. - $tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'overview'; - return isset( $tabs[ $tab ] ) ? $tab : 'overview'; -} - -/** - * URL for a tab. + * URL for what used to be a tab. * * @param string $tab Tab key. * @return string */ function sendbeam_tab_url( $tab ) { - return admin_url( 'options-general.php?page=sendbeam&tab=' . rawurlencode( $tab ) ); + $pages = sendbeam_tab_pages(); + return sendbeam_page_url( isset( $pages[ $tab ] ) ? $pages[ $tab ] : 'sendbeam' ); } /** - * Header and tab bar. + * The branded band at the top of every SendBeam screen. + * + * It replaces the visual `

      ` (the screen-reader one is in the router), and + * it names the section it is above: a header that says only "SendBeam" on + * eight different pages tells you the plugin you are in and nothing about + * where in it you are. + * + * @param string $title The section name. */ -function sendbeam_render_header() { - $current = sendbeam_current_tab(); +function sendbeam_render_header( $title = '' ) { $connection = sendbeam_connection(); $states = array( 'ok' => array( 'moss', __( 'Connected', 'sendbeam' ) ), @@ -75,23 +77,41 @@ function sendbeam_render_header() {
      SendBeam - v + + + +

      - $tabs Key => label. + * @param string $current The active key. + * @param string $slug The page the tabs live on. + * @param string $label Accessible name for the nav. + */ +function sendbeam_render_tabs( $tabs, $current, $slug, $label ) { + echo ''; +} + /** * Open a card. * diff --git a/includes/connect.php b/includes/connect.php index 970bfa3..e228b6f 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -813,7 +813,7 @@ function sendbeam_connect_workspace_name() { * leave them staring at nothing. */ function sendbeam_connect_render_result( $connected, $heading, $detail, $is_popup = true ) { - $overview = admin_url( 'options-general.php?page=sendbeam' ); + $overview = sendbeam_tab_url( 'overview' ); $origin = sendbeam_connect_site_origin(); nocache_headers(); diff --git a/includes/mail.php b/includes/mail.php index d98c98f..5bb4f3c 100644 --- a/includes/mail.php +++ b/includes/mail.php @@ -323,11 +323,10 @@ function sendbeam_handle_test_mail() { wp_safe_redirect( add_query_arg( array( - 'page' => 'sendbeam', 'sendbeam_test' => $ok ? 'ok' : 'error', 'sendbeam_note' => rawurlencode( $note ), ), - admin_url( 'options-general.php' ) + sendbeam_tab_url( 'mail' ) ) ); exit; diff --git a/includes/menu.php b/includes/menu.php new file mode 100644 index 0000000..54e49f0 --- /dev/null +++ b/includes/menu.php @@ -0,0 +1,258 @@ + + */ +function sendbeam_pages() { + return array( + 'sendbeam' => array( + 'menu' => __( 'Overview', 'sendbeam' ), + 'title' => __( 'Overview', 'sendbeam' ), + 'render' => 'sendbeam_screen_overview', + ), + 'sendbeam-forms' => array( + 'menu' => __( 'Forms', 'sendbeam' ), + 'title' => __( 'Forms', 'sendbeam' ), + 'render' => 'sendbeam_screen_forms', + ), + 'sendbeam-popups' => array( + 'menu' => __( 'Pop-ups', 'sendbeam' ), + 'title' => __( 'Pop-ups', 'sendbeam' ), + 'render' => 'sendbeam_screen_popup', + ), + 'sendbeam-audience' => array( + 'menu' => __( 'Audience', 'sendbeam' ), + 'title' => __( 'Audience', 'sendbeam' ), + 'render' => 'sendbeam_screen_audience', + ), + 'sendbeam-mail' => array( + 'menu' => __( 'Site email', 'sendbeam' ), + 'title' => __( 'Site email', 'sendbeam' ), + 'render' => 'sendbeam_screen_mail', + ), + 'sendbeam-ecommerce' => array( + 'menu' => __( 'E-commerce', 'sendbeam' ), + 'title' => __( 'E-commerce events', 'sendbeam' ), + 'render' => 'sendbeam_screen_ecommerce', + ), + 'sendbeam-settings' => array( + 'menu' => __( 'Settings', 'sendbeam' ), + 'title' => __( 'Settings', 'sendbeam' ), + 'render' => 'sendbeam_screen_settings', + ), + 'sendbeam-help' => array( + 'menu' => __( 'Help', 'sendbeam' ), + 'title' => __( 'Help', 'sendbeam' ), + 'render' => 'sendbeam_screen_help', + ), + ); +} + +/** + * The menu mark: the three squares, in the grey wp-admin gives every other icon. + * + * A data URI rather than a dashicon, because none of the 300-odd dashicons is + * this product and a borrowed envelope is worse than a shape people already + * recognise from sendbeam.io. WordPress paints menu icons by swapping the + * whole image, so the colour is baked in at the one value core uses for a + * menu at rest; the active state is handled by opacity. + * + * @return string + */ +function sendbeam_menu_icon() { + $svg = '' + . '' + . '' + . '' + . ''; + return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- add_menu_page() takes the icon as a base64 data URI; this is not obfuscation. +} + +/** + * Register the top-level menu and one submenu per section. + */ +function sendbeam_admin_menu() { + $pages = sendbeam_pages(); + + add_menu_page( + __( 'SendBeam', 'sendbeam' ), + __( 'SendBeam', 'sendbeam' ), + 'manage_options', + SENDBEAM_MENU_SLUG, + 'sendbeam_render_admin_page', + sendbeam_menu_icon(), + 58.9 + ); + + foreach ( $pages as $slug => $page ) { + if ( ! empty( $page['hidden'] ) ) { + // Registered with no parent: routable, capability-checked and + // titled, but absent from the menu. + add_submenu_page( '', $page['title'], $page['menu'], 'manage_options', $slug, 'sendbeam_render_admin_page' ); + continue; + } + add_submenu_page( + SENDBEAM_MENU_SLUG, + $page['title'], + $page['menu'], + 'manage_options', + $slug, + 'sendbeam_render_admin_page' + ); + } +} + +/** + * Which SendBeam page is being rendered. + * + * @return string A slug from sendbeam_pages(), defaulting to the Overview. + */ +function sendbeam_current_page() { + $pages = sendbeam_pages(); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation. + $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; + return isset( $pages[ $page ] ) ? $page : SENDBEAM_MENU_SLUG; +} + +/** + * The URL of one SendBeam page. + * + * @param string $slug Page slug. + * @return string + */ +function sendbeam_page_url( $slug ) { + return admin_url( 'admin.php?page=' . rawurlencode( $slug ) ); +} + +/** + * Is this admin screen one of ours? + * + * Screen ids are `toplevel_page_sendbeam` for the Overview and + * `sendbeam_page_` for every submenu — plus, on a translated site, + * `_page_`, which is why the slug rather than the + * prefix is what this matches on. + * + * @param string|WP_Screen|null $screen A screen, a hook suffix, or null for the current screen. + * @return bool + */ +function sendbeam_is_our_screen( $screen = null ) { + if ( null === $screen ) { + $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; + } + $id = is_object( $screen ) && isset( $screen->id ) ? (string) $screen->id : (string) $screen; + if ( '' === $id ) { + return false; + } + foreach ( array_keys( sendbeam_pages() ) as $slug ) { + $suffix = '_page_' . $slug; + if ( substr( $id, -strlen( $suffix ) ) === $suffix ) { + return true; + } + } + return false; +} + +/** + * The one router. + * + * Every page registered above points here; this decides which screen function + * runs and wraps it in the shell they all share. + */ +function sendbeam_render_admin_page() { + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + $slug = sendbeam_current_page(); + $pages = sendbeam_pages(); + $page = $pages[ $slug ]; + + ?> +
      +

      + +
      + +
      +
      + $value ) { + if ( in_array( $key, array( 'page', 'tab' ), true ) || ! is_scalar( $value ) ) { + continue; + } + // add_query_arg() does not encode what it is given, so anything with + // an ampersand or a space in it would split the URL in two. + $carry[ sanitize_key( $key ) ] = rawurlencode( sanitize_text_field( (string) $value ) ); + } + if ( $carry ) { + $target = add_query_arg( $carry, $target ); + } + + wp_safe_redirect( $target, 301 ); + exit; +} diff --git a/includes/onboarding.php b/includes/onboarding.php index 808297f..7c26eac 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -440,8 +440,7 @@ function sendbeam_setup_notice() { return; } - $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; - if ( $screen && 'settings_page_sendbeam' === $screen->id ) { + if ( sendbeam_is_our_screen() ) { return; // They are already here. } @@ -453,7 +452,7 @@ function sendbeam_setup_notice() { return; // Resolved: the notice removes itself. } - $settings_url = admin_url( 'options-general.php?page=sendbeam' ); + $settings_url = sendbeam_page_url( 'sendbeam' ); $dismiss_url = wp_nonce_url( admin_url( 'admin-post.php?action=sendbeam_dismiss_setup' ), 'sendbeam_dismiss_setup' ); ?>
      diff --git a/includes/screens.php b/includes/screens.php index 74a5a65..6491b3d 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -96,19 +96,6 @@ function sendbeam_screen_overview() { sendbeam_card_close(); echo '
      '; - - // A pasted key still gets its own card: there is a field to edit. A key - // that arrived through Connect has nothing to edit, and its Disconnect - // button lives in step 1 where someone looking at the connection will - // actually find it — the old card was below the fold and titled - // "Connect", which read as an invitation to connect something. - if ( $connected && ! sendbeam_connected_via_connect() ) { - sendbeam_card_open( __( 'API key', 'sendbeam' ) ); - sendbeam_form_open( 'connect' ); - do_settings_sections( 'sendbeam_connect_page' ); - sendbeam_form_close(); - sendbeam_card_close(); - } } /** @@ -222,7 +209,9 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { } break; case 'domain': - sendbeam_overview_domain_panel( $status, $connected ); + if ( $connected ) { + sendbeam_domain_panel( $status ); + } /* * The domain this site sends from is chosen on the consent page, @@ -273,14 +262,12 @@ function sendbeam_overview_step_panel( $step, $status, $connected ) { * something to retype, and **Check now** is right there so they can find out * whether it worked without leaving wp-admin. * - * @param array $status Normalised Connect status. - * @param bool $connected Whether the key works. + * @param array $status Normalised Connect status. + * @param bool $standalone True on the Settings page, where the panel is the + * whole subject rather than one step in a checklist + * that has already explained itself. */ -function sendbeam_overview_domain_panel( $status, $connected ) { - if ( ! $connected ) { - return; - } - +function sendbeam_domain_panel( $status, $standalone = false ) { $domain = $status['domain']; $verified = ! empty( $domain['verified'] ); $state = sendbeam_connect_domain_state( $status ); @@ -636,6 +623,51 @@ function sendbeam_connect_connected_panel( $status = null ) { echo ''; } +/** + * What the Connection card says when the key was pasted rather than granted. + * + * There is no workspace name to print — a key pasted by hand arrives with + * nothing but itself — so the card says what it does know: that the key + * works, what SendBeam answers to it, and where the field to change it is. + * + * @param array $status Normalised Connect status. + */ +function sendbeam_connect_pasted_panel( $status ) { + $connection = sendbeam_connection(); + $workspace = is_array( $status ) ? (string) $status['workspace']['name'] : ''; + + if ( '' !== $workspace ) { + /* translators: %s: the SendBeam workspace name */ + echo '

      ' . esc_html( sprintf( __( 'Connected to %s', 'sendbeam' ), $workspace ) ) . '

      '; + } else { + echo '

      ' . esc_html__( 'Connected with a pasted API key.', 'sendbeam' ) . '

      '; + } + + if ( sendbeam_key_in_config() ) { + echo '

      ' . esc_html__( 'The key is the one defined as SENDBEAM_API_KEY in wp-config.php. Change it there.', 'sendbeam' ) . '

      '; + } + + if ( 'no_scope' === $connection['state'] && '' !== $connection['message'] ) { + echo '

      ' . esc_html( $connection['message'] ) . '

      '; + } + + echo '
      '; + printf( + '%s', + esc_url( add_query_arg( 'tab', 'advanced', sendbeam_page_url( 'sendbeam-settings' ) ) ), + esc_html__( 'Change the key', 'sendbeam' ) + ); + if ( ! sendbeam_key_in_config() ) { + printf( + '%s', + esc_url( sendbeam_connect_start_url( true ) ), + esc_html__( 'Connect properly instead', 'sendbeam' ) + ); + } + echo '
      '; + echo '

      ' . esc_html__( 'Connecting replaces the pasted key with one SendBeam issues for this site, and tells the plugin which permissions it has — which is what lets the sending domain, the form list and the checklist say anything useful.', 'sendbeam' ) . '

      '; +} + /** * The permissions this site's key holds, in the consent page's own words. * @@ -772,6 +804,8 @@ function sendbeam_screen_forms() { echo '

      ' . esc_html__( 'Paste a shortcode anywhere, or add the SendBeam Form block and pick the form from its dropdown. Every form on this list can be used as many times as you like, on as many pages as you like.', 'sendbeam' ) . '

      '; } sendbeam_card_close(); + + sendbeam_placing_forms_card(); } /* -------------------------------------------------------------- Audience */ @@ -1070,6 +1104,8 @@ function sendbeam_screen_popup() { echo ''; sendbeam_card_close(); + + sendbeam_placing_forms_card(); } /** @@ -1345,7 +1381,123 @@ function sendbeam_screen_ecommerce() { } } -/* ------------------------------------------------------------------ Docs */ +/* -------------------------------------------------------------- Settings */ + +/** + * Which Settings tab is showing. + * + * @return string + */ +function sendbeam_settings_tab() { + $tabs = array_keys( sendbeam_settings_tabs() ); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation. + $tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : ''; + return in_array( $tab, $tabs, true ) ? $tab : 'connection'; +} + +/** + * The three things this page is for. + * + * @return array + */ +function sendbeam_settings_tabs() { + return array( + 'connection' => __( 'Connection', 'sendbeam' ), + 'domain' => __( 'Sending domain', 'sendbeam' ), + 'advanced' => __( 'Advanced', 'sendbeam' ), + ); +} + +/** + * Settings: the connection itself, the domain it sends from, and the key. + * + * Everything on this page is about the account rather than about the site — + * which is why the forms, the pop-ups and the site email settings are not + * here. A settings page that holds every setting in the plugin is a settings + * page nobody can find anything on. + */ +function sendbeam_screen_settings() { + $tab = sendbeam_settings_tab(); + $connected = sendbeam_is_connected(); + $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + + sendbeam_render_tabs( sendbeam_settings_tabs(), $tab, 'sendbeam-settings', __( 'Settings sections', 'sendbeam' ) ); + + if ( 'domain' === $tab ) { + sendbeam_settings_domain_card( $status, $connected ); + return; + } + if ( 'advanced' === $tab ) { + sendbeam_settings_advanced_card(); + return; + } + sendbeam_settings_connection_card( $status, $connected ); +} + +/** + * Settings → Connection: one card, in the shape every connect screen has. + * + * @param array $status Normalised Connect status. + * @param bool $connected Whether the key works. + */ +function sendbeam_settings_connection_card( $status, $connected ) { + sendbeam_card_open( __( 'Connection', 'sendbeam' ), __( 'This site and the SendBeam workspace it talks to.', 'sendbeam' ) ); + if ( $connected && sendbeam_connected_via_connect() ) { + sendbeam_connect_connected_panel( $status ); + } elseif ( $connected ) { + sendbeam_connect_pasted_panel( $status ); + } else { + sendbeam_connect_panel(); + } + sendbeam_card_close(); +} + +/** + * Settings → Sending domain: the records and the two ways to finish them. + * + * @param array $status Normalised Connect status. + * @param bool $connected Whether the key works. + */ +function sendbeam_settings_domain_card( $status, $connected ) { + sendbeam_card_open( __( 'Sending domain', 'sendbeam' ), __( 'The domain this site\'s email is sent from.', 'sendbeam' ) ); + if ( ! $connected ) { + echo '

      ' . esc_html__( 'Connect this site first and SendBeam will set the domain up and show you the records to add.', 'sendbeam' ) . '

      '; + printf( + '

      %s

      ', + esc_url( add_query_arg( 'tab', 'connection', sendbeam_page_url( 'sendbeam-settings' ) ) ), + esc_html__( 'Go to Connection', 'sendbeam' ) + ); + sendbeam_card_close(); + return; + } + sendbeam_domain_panel( $status, true ); + sendbeam_card_close(); +} + +/** + * Settings → Advanced: the key, where it can live, and what uninstalling takes with it. + */ +function sendbeam_settings_advanced_card() { + sendbeam_card_open( __( 'API key', 'sendbeam' ), __( 'For a key you already have, or one you would rather keep out of the database.', 'sendbeam' ) ); + if ( sendbeam_key_in_config() ) { + echo '

      ' . esc_html__( 'This site sends with the key defined as SENDBEAM_API_KEY in wp-config.php. It wins over anything saved here, so there is nothing to paste: change it in wp-config.php, or remove that line to manage the key from this screen.', 'sendbeam' ) . '

      '; + } else { + sendbeam_form_open( 'connect' ); + do_settings_sections( 'sendbeam_connect_page' ); + sendbeam_form_close(); + } + sendbeam_card_close(); + + sendbeam_card_open( __( 'When this plugin is deleted', 'sendbeam' ) ); + echo '
        '; + echo '
      • ' . esc_html__( 'Everything this plugin stored on this site is removed: the settings, the saved key, the pop-up rules, the recent email and event logs, and the cached answers from SendBeam.', 'sendbeam' ) . '
      • '; + echo '
      • ' . esc_html__( 'Nothing is removed from your SendBeam workspace. Your lists, forms, subscribers and sending domain stay exactly as they are.', 'sendbeam' ) . '
      • '; + echo '
      • ' . esc_html__( 'Deactivating changes nothing at either end. Only deleting the plugin clears this site\'s settings.', 'sendbeam' ) . '
      • '; + echo '
      '; + sendbeam_card_close(); +} + +/* ------------------------------------------------------------------ Help */ /** * A reference that works without leaving WordPress. @@ -1380,9 +1532,9 @@ function sendbeam_doc_snippet( $code, $what ) { } /** - * Docs tab: the shortcodes, the API key permissions, and links to the full documentation. + * Help: the documentation, the shortcodes, and what each permission is for. */ -function sendbeam_screen_docs() { +function sendbeam_screen_help() { sendbeam_card_open( __( 'Documentation', 'sendbeam' ) ); echo '
      '; echo '

      ' . esc_html__( 'The essentials are below. The full documentation is kept with SendBeam itself, so it stays current with the product rather than with whichever version of this plugin you happen to have installed.', 'sendbeam' ) . '

      '; diff --git a/includes/settings.php b/includes/settings.php index be82003..c6462cd 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -1,43 +1,34 @@ ' . esc_html__( 'Settings', 'sendbeam' ) . '' ); return $links; } @@ -499,55 +490,21 @@ function sendbeam_field_select( $args ) { } /** - * The page itself. - */ -function sendbeam_render_settings_page() { - if ( ! current_user_can( 'manage_options' ) ) { - return; - } - $tab = sendbeam_current_tab(); - $screens = array( - 'overview' => 'sendbeam_screen_overview', - 'forms' => 'sendbeam_screen_forms', - 'audience' => 'sendbeam_screen_audience', - 'popup' => 'sendbeam_screen_popup', - 'mail' => 'sendbeam_screen_mail', - 'ecommerce' => 'sendbeam_screen_ecommerce', - 'docs' => 'sendbeam_screen_docs', - ); - ?> -
      -

      - -
      - '; - echo '
    • ' . wp_kses( __( 'Add the SendBeam Form block to any post or page and pick the form from its dropdown — search "SendBeam" in the block inserter.', 'sendbeam' ), array( 'strong' => array() ) ) . '
    • '; - echo '
    • ' . wp_kses( __( '[sendbeam_form id="…"] places any form, as often as you like. height="600" sets a different height.', 'sendbeam' ), array( 'code' => array() ) ) . '
    • '; - echo '
    • ' . wp_kses( __( '[sendbeam_contact] shows the contact form chosen above.', 'sendbeam' ), array( 'code' => array() ) ) . '
    • '; - echo '
    • ' . wp_kses( __( '[sendbeam_popup_button label="Subscribe"] opens the pop-up on click, on pages where it is not shown by itself.', 'sendbeam' ), array( 'code' => array() ) ) . '
    • '; - echo '
    '; - sendbeam_card_close(); - } - ?> - - - '; + echo '
  • ' . wp_kses( __( 'Add the SendBeam Form block to any post or page and pick the form from its dropdown — search "SendBeam" in the block inserter.', 'sendbeam' ), array( 'strong' => array() ) ) . '
  • '; + echo '
  • ' . wp_kses( __( '[sendbeam_form id="…"] places any form, as often as you like. height="600" sets a different height.', 'sendbeam' ), array( 'code' => array() ) ) . '
  • '; + echo '
  • ' . wp_kses( __( '[sendbeam_contact] shows the contact form chosen above.', 'sendbeam' ), array( 'code' => array() ) ) . '
  • '; + echo '
  • ' . wp_kses( __( '[sendbeam_popup_button label="Subscribe"] opens the pop-up on click, on pages where it is not shown by itself.', 'sendbeam' ), array( 'code' => array() ) ) . '
  • '; + echo ''; + sendbeam_card_close(); +} /** Intro for the Connect section: the live state of the key. */ function sendbeam_section_connect_intro() { @@ -605,7 +562,7 @@ function sendbeam_handle_refresh() { check_admin_referer( 'sendbeam_refresh' ); sendbeam_flush_cache(); sendbeam_connection( true ); - wp_safe_redirect( admin_url( 'options-general.php?page=sendbeam' ) ); + wp_safe_redirect( sendbeam_page_url( 'sendbeam-settings' ) ); exit; } @@ -615,13 +572,13 @@ function sendbeam_handle_refresh() { * @param string $hook Current admin page. */ function sendbeam_admin_assets( $hook ) { - if ( 'settings_page_sendbeam' !== $hook ) { + if ( ! sendbeam_is_our_screen( $hook ) ) { return; } - // The pop-up tab offers a picture; that is the only screen that needs the + // The pop-up screen offers a picture; that is the only one that needs the // media frame, so it is the only one that loads it. - if ( 'popup' === sendbeam_current_tab() ) { + if ( 'sendbeam-popups' === sendbeam_current_page() ) { wp_enqueue_media(); } diff --git a/sendbeam.php b/sendbeam.php index 5dde57a..c9cb9fd 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -28,6 +28,7 @@ require SENDBEAM_DIR . 'includes/ecommerce.php'; require SENDBEAM_DIR . 'includes/bridges.php'; require SENDBEAM_DIR . 'includes/admin-ui.php'; +require SENDBEAM_DIR . 'includes/menu.php'; require SENDBEAM_DIR . 'includes/screens.php'; require SENDBEAM_DIR . 'includes/settings.php'; require SENDBEAM_DIR . 'includes/render.php'; diff --git a/tests/smoke.php b/tests/smoke.php index 99141d4..b932039 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -1998,7 +1998,7 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { // started in a wp-admin checklist and expected to come back and see the step // ticked. $ov = sb_overview( $sb_connected, $sb_unverified ); -has( $ov, 'return_to=' . rawurlencode( 'https://www.example-site.test/wp-admin/options-general.php?page=sendbeam&tab=overview' ), 'automatic DNS: the one-click link tells SendBeam where to send the owner back to' ); +has( $ov, 'return_to=' . rawurlencode( 'https://www.example-site.test/wp-admin/admin.php?page=sendbeam' ), 'automatic DNS: the one-click link tells SendBeam where to send the owner back to' ); has( $ov, 'https://sendbeam.io/dc/1?return_to=', 'automatic DNS: and is otherwise the link SendBeam sent' ); $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( true ) ); @@ -2055,6 +2055,159 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { delete_transient( 'sendbeam_subscriber_count' ); update_option( 'sendbeam_settings', array() ); +/* ─────────────────────────── The admin menu ──────────────────────────── + * SendBeam lived under Settings → SendBeam with seven invisible tabs. Every + * section is now a real menu item, and every old URL still goes somewhere. + */ +$GLOBALS['stub']['menu'] = array(); +$GLOBALS['stub']['submenu'] = array(); +sendbeam_admin_menu(); +$menu = $GLOBALS['stub']['menu']; +$subs = $GLOBALS['stub']['submenu']; + +ok( isset( $menu['sendbeam'] ) && null === $menu['sendbeam']['parent'], 'menu: SendBeam is a top-level menu, not a Settings submenu' ); +ok( 'SendBeam' === $menu['sendbeam']['menu_title'], 'menu: the menu is called SendBeam' ); +ok( 58.9 === $menu['sendbeam']['position'], 'menu: it sits below Settings at 58.9' ); +has( $menu['sendbeam']['icon'], 'data:image/svg+xml;base64,', 'menu: the icon is a base64 SVG data URI, not a dashicon' ); +has( base64_decode( substr( $menu['sendbeam']['icon'], strlen( 'data:image/svg+xml;base64,' ) ) ), '#a7aaad', 'menu: the mark is drawn in the grey wp-admin gives every other menu icon' ); +ok( substr_count( base64_decode( substr( $menu['sendbeam']['icon'], strlen( 'data:image/svg+xml;base64,' ) ) ), ' 'Overview', + 'sendbeam-forms' => 'Forms', + 'sendbeam-popups' => 'Pop-ups', + 'sendbeam-audience' => 'Audience', + 'sendbeam-mail' => 'Site email', + 'sendbeam-ecommerce' => 'E-commerce', + 'sendbeam-settings' => 'Settings', + 'sendbeam-help' => 'Help', +); +foreach ( $sendbeam_expected as $sendbeam_slug => $sendbeam_label ) { + ok( isset( $subs[ $sendbeam_slug ] ), "menu: $sendbeam_slug is registered as a submenu item" ); + ok( $sendbeam_label === $subs[ $sendbeam_slug ]['menu_title'], "menu: $sendbeam_slug is labelled $sendbeam_label" ); + ok( 'manage_options' === $subs[ $sendbeam_slug ]['cap'], "menu: $sendbeam_slug needs manage_options" ); + ok( 'sendbeam_render_admin_page' === $subs[ $sendbeam_slug ]['callback'], "menu: $sendbeam_slug is rendered by the one router" ); + ok( 'sendbeam' === $subs[ $sendbeam_slug ]['parent'], "menu: $sendbeam_slug hangs off the SendBeam menu" ); +} +ok( ! isset( $subs['sendbeam-docs'] ), 'menu: the Docs tab is gone; Help replaced it' ); +ok( count( $subs ) === count( sendbeam_pages() ), 'menu: every page in the table is registered, and nothing else is' ); + +// Every page in the table renders, and renders something. +foreach ( sendbeam_pages() as $sendbeam_slug => $sendbeam_page ) { + ok( function_exists( $sendbeam_page['render'] ), "router: {$sendbeam_page['render']}() exists for $sendbeam_slug" ); +} + +// The router picks the screen off `page`, and falls back to the Overview +// rather than fataling on a slug that is not ours. +$_GET = array( 'page' => 'sendbeam-mail' ); +ok( 'sendbeam-mail' === sendbeam_current_page(), 'router: the current page comes from the query string' ); +$_GET = array( 'page' => 'sendbeam-nonsense' ); +ok( 'sendbeam' === sendbeam_current_page(), 'router: an unknown page falls back to the Overview' ); +$_GET = array(); + +ok( 'https://www.example-site.test/wp-admin/admin.php?page=sendbeam-forms' === sendbeam_page_url( 'sendbeam-forms' ), 'router: page URLs are admin.php?page=' ); + +// Screen detection, which decides where the styles and the notice appear. +ok( sendbeam_is_our_screen( 'toplevel_page_sendbeam' ), 'screens: the Overview is one of ours' ); +ok( sendbeam_is_our_screen( 'sendbeam_page_sendbeam-help' ), 'screens: a submenu page is one of ours' ); +ok( ! sendbeam_is_our_screen( 'dashboard' ), 'screens: the Dashboard is not' ); +ok( ! sendbeam_is_our_screen( 'plugins' ), 'screens: the Plugins screen is not' ); +ok( ! sendbeam_is_our_screen( '' ), 'screens: nothing is not' ); + +// Old URLs. Every tab that existed goes somewhere, permanently. +$sendbeam_moves = array( + '' => 'sendbeam', + 'overview' => 'sendbeam', + 'forms' => 'sendbeam-forms', + 'audience' => 'sendbeam-audience', + 'popup' => 'sendbeam-popups', + 'mail' => 'sendbeam-mail', + 'ecommerce' => 'sendbeam-ecommerce', + 'docs' => 'sendbeam-help', +); +foreach ( $sendbeam_moves as $sendbeam_tab => $sendbeam_to ) { + $GLOBALS['pagenow'] = 'options-general.php'; + $_GET = array( 'page' => 'sendbeam' ); + if ( '' !== $sendbeam_tab ) { + $_GET['tab'] = $sendbeam_tab; + } + unset( $GLOBALS['stub']['redirect'] ); + try { + sendbeam_redirect_old_urls(); + } catch ( SendBeamStubExit $e ) { + unset( $e ); + } + ok( isset( $GLOBALS['stub']['redirect'] ), "old URL: tab=$sendbeam_tab redirects" ); + ok( 301 === $GLOBALS['stub']['redirect']['status'], "old URL: tab=$sendbeam_tab moves permanently" ); + ok( sendbeam_page_url( $sendbeam_to ) === $GLOBALS['stub']['redirect']['url'], "old URL: tab=$sendbeam_tab lands on $sendbeam_to" ); +} + +// A notice the old URL carried has to survive the move, or every handler that +// redirects with one goes silent. +$GLOBALS['pagenow'] = 'options-general.php'; +$_GET = array( + 'page' => 'sendbeam', + 'tab' => 'mail', + 'sendbeam_test' => 'ok', + 'sendbeam_note' => 'Sent to a@b.test.', +); +unset( $GLOBALS['stub']['redirect'] ); +try { + sendbeam_redirect_old_urls(); +} catch ( SendBeamStubExit $e ) { + unset( $e ); +} +has( $GLOBALS['stub']['redirect']['url'], 'sendbeam_test=ok', 'old URL: the notice on the old address is carried to the new one' ); +has( $GLOBALS['stub']['redirect']['url'], 'sendbeam_note=Sent%20to%20a%40b.test.', 'old URL: a carried value is encoded, so a space cannot split the URL' ); + +// Someone else's options-general.php page is left alone. +$GLOBALS['pagenow'] = 'options-general.php'; +$_GET = array( 'page' => 'not-sendbeam' ); +unset( $GLOBALS['stub']['redirect'] ); +sendbeam_redirect_old_urls(); +ok( ! isset( $GLOBALS['stub']['redirect'] ), 'old URL: another plugin\'s settings page is not hijacked' ); +$GLOBALS['pagenow'] = 'admin.php'; +$_GET = array(); + +/* + * Every page renders. No test could see an .astro page in the app and no test + * could see one of these either: a screen function that calls something that + * does not exist is a white page on a live wp-admin, and the only way to find + * out was to load it. + */ +$GLOBALS['stub']['caps']['manage_options'] = true; +foreach ( array_keys( sendbeam_pages() ) as $sendbeam_slug ) { + $_GET = array( 'page' => $sendbeam_slug ); + ob_start(); + sendbeam_render_admin_page(); + $sendbeam_html = ob_get_clean(); + has( $sendbeam_html, 'class="wrap sendbeam-app"', "render: $sendbeam_slug sits in a .wrap" ); + has( $sendbeam_html, 'class="screen-reader-text"', "render: $sendbeam_slug has a real h1 for screen readers" ); + has( $sendbeam_html, 'sb-head', "render: $sendbeam_slug carries the header band" ); + ok( strlen( $sendbeam_html ) > 800, "render: $sendbeam_slug renders a screenful, not an empty shell" ); +} + +// The header band names the section, so eight pages do not all say "SendBeam". +$_GET = array( 'page' => 'sendbeam-mail' ); +ob_start(); +sendbeam_render_admin_page(); +$sendbeam_html = ob_get_clean(); +has( $sendbeam_html, 'Site email', 'render: the header band names the section' ); +has( $sendbeam_html, 'SendBeam — Site email', 'render: the screen-reader heading names the section too' ); + +// Someone without the capability gets nothing, not a partial page. +$GLOBALS['stub']['caps']['manage_options'] = false; +ob_start(); +sendbeam_render_admin_page(); +ok( '' === ob_get_clean(), 'render: a user who cannot manage options sees nothing at all' ); +$GLOBALS['stub']['caps']['manage_options'] = true; +$_GET = array(); + +// The Plugins-screen link goes to the Settings page, not to a dashboard. +$sendbeam_links = sendbeam_action_links( array() ); +has( $sendbeam_links[0], 'admin.php?page=sendbeam-settings', 'plugins screen: the Settings link points at the Settings page' ); +lacks( $sendbeam_links[0], 'options-general.php', 'plugins screen: the Settings link does not point at the old address' ); + // One version number, five files. 1.6.2 shipped with the block's asset // version still on 1.6.1, which is how WordPress decides whether the editor // may reuse a cached copy of the block script. diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 349407a..fa5e67d 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -259,3 +259,49 @@ public function get_var( $sql ) { return empty( $db['posts'] ) ? null : 1; } } + +// ── The admin menu ────────────────────────────────────────────────────── +/** + * Menu registration. The stubs record what was registered rather than + * building a menu, because what the test needs to know is which slugs exist, + * what they are called and which callback answers for them — which is exactly + * what a wrong `add_submenu_page()` argument order gets wrong. + */ +function add_menu_page( $page_title, $menu_title, $cap, $slug, $cb = '', $icon = '', $position = null ) { + $GLOBALS['stub']['menu'][ $slug ] = array( + 'page_title' => $page_title, + 'menu_title' => $menu_title, + 'cap' => $cap, + 'callback' => $cb, + 'icon' => $icon, + 'position' => $position, + 'parent' => null, + ); + return 'toplevel_page_' . $slug; +} +function add_submenu_page( $parent, $page_title, $menu_title, $cap, $slug, $cb = '', $position = null ) { + // WordPress registers a top-level page's first submenu item under the + // same slug, to rename it; recording both in one bucket would hide the + // top-level registration behind it. + $GLOBALS['stub']['submenu'][ $slug ] = array( + 'page_title' => $page_title, + 'menu_title' => $menu_title, + 'cap' => $cap, + 'callback' => $cb, + 'parent' => $parent, + 'position' => $position, + ); + return ( $parent ? 'sendbeam_page_' : 'admin_page_' ) . $slug; +} +function get_current_screen() { + return isset( $GLOBALS['stub']['screen'] ) ? (object) array( 'id' => $GLOBALS['stub']['screen'] ) : null; +} +function settings_errors( $setting = '', $sanitize = false, $hide_on_update = false ) {} +function _n( $single, $plural, $number, $domain = null ) { return 1 === (int) $number ? $single : $plural; } +function _x( $text, $context, $domain = null ) { return $text; } +function esc_textarea( $text ) { return esc_html( $text ); } +function disabled( $a, $b = true, $echo = true ) { return $a == $b ? ' disabled="disabled"' : ''; } +function wp_enqueue_media( $args = array() ) {} +function get_admin_page_title() { return 'SendBeam'; } +function submit_button_wrapper() {} +function esc_attr_e( $s, $d = null ) { echo esc_attr( $s ); } From 6e086d6f5ae873930c438b7a6237bed5bbdd440b Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 07:44:27 +0000 Subject: [PATCH 31/75] Let the lists be lists, so they search, page and fit a phone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Forms, the email log and the audience lists were hand-rolled tables: no search, no pagination, no bulk actions, no empty state, and none of core's column collapsing — which is why Forms and Site email were the two screens that scrolled sideways on a phone. All three are now WP_List_Table subclasses with a primary column, a per-page Screen Option and an empty state that says what to do next. The email log gains a bulk delete. The two read-only lists offer no bulk actions, because their rows live in SendBeam and there is nothing here to change. --- includes/class-sendbeam-forms-table.php | 248 +++++++++++++++++++++ includes/class-sendbeam-lists-table.php | 165 ++++++++++++++ includes/class-sendbeam-mail-log-table.php | 197 ++++++++++++++++ includes/list-tables.php | 128 +++++++++++ includes/menu.php | 58 ++++- includes/screens.php | 151 +++++-------- sendbeam.php | 1 + tests/smoke.php | 200 +++++++++++++++++ tests/wp-stubs.php | 118 ++++++++++ 9 files changed, 1160 insertions(+), 106 deletions(-) create mode 100644 includes/class-sendbeam-forms-table.php create mode 100644 includes/class-sendbeam-lists-table.php create mode 100644 includes/class-sendbeam-mail-log-table.php create mode 100644 includes/list-tables.php diff --git a/includes/class-sendbeam-forms-table.php b/includes/class-sendbeam-forms-table.php new file mode 100644 index 0000000..06e0057 --- /dev/null +++ b/includes/class-sendbeam-forms-table.php @@ -0,0 +1,248 @@ + 'sendbeam_form', + 'plural' => 'sendbeam_forms', + 'ajax' => false, + ) + ); + $this->placement = sendbeam_form_placement(); + } + + /** + * The columns, in order. + * + * @return array + */ + public function get_columns() { + return array( + 'name' => __( 'Form', 'sendbeam' ), + 'kind' => __( 'Kind', 'sendbeam' ), + 'shortcode' => __( 'Shortcode', 'sendbeam' ), + 'placed' => __( 'Placed on', 'sendbeam' ), + ); + } + + /** + * Name is the column that survives on a phone. + * + * @return string + */ + protected function get_default_primary_column_name() { + return 'name'; + } + + /** + * Nothing here can be changed in bulk, so nothing is offered. + * + * @return array + */ + protected function get_bulk_actions() { + return array(); + } + + /** + * There are no bulk actions, so there is nothing to process. + * + * Defined all the same: the loader calls it on every list, and a list + * that quietly has no such method is a fatal error waiting for whoever + * adds a bulk action to one of the others. + */ + public function process_bulk_action() {} + + /** Load, filter and page the rows. */ + public function prepare_items() { + $forms = sendbeam_remote_forms(); + $forms = is_array( $forms ) ? $forms : array(); + $search = sendbeam_list_search(); + + if ( '' !== $search ) { + $needle = strtolower( $search ); + $forms = array_values( + array_filter( + $forms, + function ( $form ) use ( $needle ) { + $hay = strtolower( (string) ( isset( $form['name'] ) ? $form['name'] : '' ) . ' ' . (string) $form['id'] ); + return false !== strpos( $hay, $needle ); + } + ) + ); + } + + $per_page = sendbeam_per_page( 'sendbeam_forms_per_page' ); + $page = max( 1, (int) $this->get_pagenum() ); + $total = count( $forms ); + + $this->items = array_slice( $forms, ( $page - 1 ) * $per_page, $per_page ); + $this->_column_headers = array( $this->get_columns(), array(), array(), $this->get_default_primary_column_name() ); + $this->set_pagination_args( + array( + 'total_items' => $total, + 'per_page' => $per_page, + 'total_pages' => (int) ceil( $total / max( 1, $per_page ) ), + ) + ); + } + + /** What an empty list says, and what to do about it. */ + public function no_items() { + $forms = sendbeam_remote_forms(); + if ( null === $forms ) { + esc_html_e( 'Your forms cannot be read with the current key. Give it the Forms (read) permission in SendBeam, or reconnect this site.', 'sendbeam' ); + return; + } + if ( '' !== sendbeam_list_search() ) { + esc_html_e( 'No form here matches that.', 'sendbeam' ); + return; + } + echo wp_kses( + sprintf( + /* translators: %s: link to create a form in SendBeam */ + __( 'No forms in this workspace yet. %s, and it will appear here.', 'sendbeam' ), + '' . esc_html__( 'Create your first form', 'sendbeam' ) . '' + ), + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + 'rel' => array(), + ), + ) + ); + } + + /** + * The form's name, and the row actions under it. + * + * @param array $item One form. + * @return string + */ + public function column_name( $item ) { + $id = (string) $item['id']; + $name = isset( $item['name'] ) && '' !== $item['name'] ? (string) $item['name'] : __( '(untitled form)', 'sendbeam' ); + + $actions = array( + 'preview' => sprintf( + '%s', + esc_url( sendbeam_form_url( $id, false ) ), + esc_html__( 'Preview', 'sendbeam' ) + ), + 'edit' => sprintf( + '%s', + esc_url( sendbeam_app_url() . '/forms/' . rawurlencode( $id ) ), + esc_html__( 'Edit in SendBeam', 'sendbeam' ) + ), + ); + + return '' . esc_html( $name ) . '' . $this->row_actions( $actions ); + } + + /** + * Signup or contact. + * + * @param array $item One form. + * @return string + */ + public function column_kind( $item ) { + $kind = isset( $item['kind'] ) ? (string) $item['kind'] : 'signup'; + return '' . esc_html( $kind ) . ''; + } + + /** + * The shortcode, one click from the clipboard. + * + * @param array $item One form. + * @return string + */ + public function column_shortcode( $item ) { + $kind = isset( $item['kind'] ) ? (string) $item['kind'] : 'signup'; + $shortcode = 'contact' === $kind ? '[sendbeam_contact]' : '[sendbeam_form id="' . (string) $item['id'] . '"]'; + return '' . esc_html( $shortcode ) . ' ' + . sprintf( + '', + esc_attr( $shortcode ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy', 'sendbeam' ) + ); + } + + /** + * Whether this site is showing a SendBeam form anywhere. + * + * The answer is about the site, not about this particular form: a search + * for the block name and the shortcodes cannot tell which form a + * `[sendbeam_form]` with no id will render. Saying so is better than a + * per-row tick that would be wrong half the time. + * + * @param array $item One form. + * @return string + */ + public function column_placed( $item ) { + $settings = sendbeam_settings(); + $id = strtolower( (string) $item['id'] ); + $default = strtolower( (string) $settings['default_form'] ) === $id; + $contact = strtolower( (string) $settings['contact_form'] ) === $id; + + $where = array( + 'manual' => __( 'Somewhere you told us about', 'sendbeam' ), + 'popup' => __( 'A pop-up', 'sendbeam' ), + 'content' => __( 'A page or post', 'sendbeam' ), + 'template' => __( 'A theme template', 'sendbeam' ), + 'widget' => __( 'A widget', 'sendbeam' ), + 'meta' => __( 'A page builder layout', 'sendbeam' ), + ); + + $out = array(); + if ( $default ) { + $out[] = '' . esc_html__( 'Default signup form', 'sendbeam' ) . ''; + } + if ( $contact ) { + $out[] = '' . esc_html__( 'Default contact form', 'sendbeam' ) . ''; + } + if ( ( $default || $contact ) && isset( $where[ $this->placement ] ) ) { + $out[] = '' . esc_html( $where[ $this->placement ] ) . ''; + } + if ( ! $out ) { + $out[] = '' . esc_html__( 'Not a default — place it by shortcode', 'sendbeam' ) . ''; + } + return implode( ' ', $out ); + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/class-sendbeam-lists-table.php b/includes/class-sendbeam-lists-table.php new file mode 100644 index 0000000..954dd28 --- /dev/null +++ b/includes/class-sendbeam-lists-table.php @@ -0,0 +1,165 @@ + 'sendbeam_list', + 'plural' => 'sendbeam_lists', + 'ajax' => false, + ) + ); + } + + /** + * The columns, in order. + * + * @return array + */ + public function get_columns() { + return array( + 'name' => __( 'List', 'sendbeam' ), + 'count' => __( 'Subscribers', 'sendbeam' ), + 'confirmation' => __( 'Confirmation', 'sendbeam' ), + ); + } + + /** + * The list's name. + * + * @return string + */ + protected function get_default_primary_column_name() { + return 'name'; + } + + /** + * Nothing here can be changed in bulk. + * + * @return array + */ + protected function get_bulk_actions() { + return array(); + } + + /** + * There are no bulk actions, so there is nothing to process. + * + * Defined all the same: the loader calls it on every list, and a list + * that quietly has no such method is a fatal error waiting for whoever + * adds a bulk action to one of the others. + */ + public function process_bulk_action() {} + + /** Load, filter and page the rows. */ + public function prepare_items() { + $lists = sendbeam_lists(); + $lists = is_array( $lists ) ? $lists : array(); + $search = sendbeam_list_search(); + + if ( '' !== $search ) { + $needle = strtolower( $search ); + $lists = array_values( + array_filter( + $lists, + function ( $list ) use ( $needle ) { + return false !== strpos( strtolower( (string) $list['name'] ), $needle ); + } + ) + ); + } + + $per_page = sendbeam_per_page( 'sendbeam_lists_per_page' ); + $page = max( 1, (int) $this->get_pagenum() ); + $total = count( $lists ); + + $this->items = array_slice( $lists, ( $page - 1 ) * $per_page, $per_page ); + $this->_column_headers = array( $this->get_columns(), array(), array(), $this->get_default_primary_column_name() ); + $this->set_pagination_args( + array( + 'total_items' => $total, + 'per_page' => $per_page, + 'total_pages' => (int) ceil( $total / max( 1, $per_page ) ), + ) + ); + } + + /** What an empty list of lists says. */ + public function no_items() { + $lists = sendbeam_lists(); + if ( null === $lists ) { + esc_html_e( 'Your lists cannot be read with the current key. Give it the Lists (read) permission in SendBeam, or reconnect this site.', 'sendbeam' ); + return; + } + if ( '' !== sendbeam_list_search() ) { + esc_html_e( 'No list here matches that.', 'sendbeam' ); + return; + } + esc_html_e( 'This workspace has no lists yet. Connecting a site creates one called Subscribers; you can add more in SendBeam.', 'sendbeam' ); + } + + /** + * The list's name, with a link to it in SendBeam. + * + * @param array $item One list. + * @return string + */ + public function column_name( $item ) { + $actions = array( + 'open' => sprintf( + '%s', + esc_url( sendbeam_app_url() . '/lists/' . rawurlencode( (string) $item['id'] ) ), + esc_html__( 'Open in SendBeam', 'sendbeam' ) + ), + ); + return '' . esc_html( (string) $item['name'] ) . '' . $this->row_actions( $actions ); + } + + /** + * How many people are on it. + * + * @param array $item One list. + * @return string + */ + public function column_count( $item ) { + return '' . ( null === $item['count'] ? '—' : esc_html( number_format_i18n( $item['count'] ) ) ) . ''; + } + + /** + * Single or double opt-in. + * + * @param array $item One list. + * @return string + */ + public function column_confirmation( $item ) { + if ( ! empty( $item['double_optin'] ) ) { + return '' . esc_html__( 'Double opt-in', 'sendbeam' ) . ''; + } + return '' . esc_html__( 'Single opt-in', 'sendbeam' ) . ''; + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/class-sendbeam-mail-log-table.php b/includes/class-sendbeam-mail-log-table.php new file mode 100644 index 0000000..5930e93 --- /dev/null +++ b/includes/class-sendbeam-mail-log-table.php @@ -0,0 +1,197 @@ + 'sendbeam_message', + 'plural' => 'sendbeam_messages', + 'ajax' => false, + ) + ); + } + + /** + * The columns, in order. + * + * @return array + */ + public function get_columns() { + return array( + 'cb' => '', + 'date' => __( 'Date', 'sendbeam' ), + 'to' => __( 'To', 'sendbeam' ), + 'subject' => __( 'Subject', 'sendbeam' ), + 'result' => __( 'Result', 'sendbeam' ), + 'note' => __( 'Note', 'sendbeam' ), + ); + } + + /** + * Date is what identifies a row here; every other column repeats. + * + * @return string + */ + protected function get_default_primary_column_name() { + return 'date'; + } + + /** + * Clearing the log is the one thing that can be done to it. + * + * @return array + */ + protected function get_bulk_actions() { + return array( 'delete' => __( 'Delete', 'sendbeam' ) ); + } + + /** + * Delete the ticked rows. + * + * Runs before the rows are read, on `load-`, so the table the + * screen renders is the one the delete left behind rather than the one + * it started with. The nonce is core's own `bulk-`, which + * `display_tablenav()` prints for us. + */ + public function process_bulk_action() { + if ( 'delete' !== $this->current_action() ) { + return; + } + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); + } + check_admin_referer( 'bulk-' . $this->_args['plural'] ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked immediately above. + $chosen = isset( $_REQUEST['message'] ) ? array_map( 'absint', (array) wp_unslash( $_REQUEST['message'] ) ) : array(); + if ( ! $chosen ) { + return; + } + + $log = get_option( 'sendbeam_mail_log', array() ); + if ( ! is_array( $log ) ) { + return; + } + foreach ( $chosen as $index ) { + unset( $log[ $index ] ); + } + update_option( 'sendbeam_mail_log', array_values( $log ), false ); + + $GLOBALS['sendbeam_deleted'] = count( $chosen ); + } + + /** Load, filter and page the rows. */ + public function prepare_items() { + $log = get_option( 'sendbeam_mail_log', array() ); + $log = is_array( $log ) ? array_values( $log ) : array(); + + // Each row carries its position in the stored log, because that is + // what a bulk delete has to name: two messages can share a second, + // an address and a subject. + foreach ( $log as $i => $row ) { + $log[ $i ]['index'] = $i; + } + + $search = sendbeam_list_search(); + if ( '' !== $search ) { + $needle = strtolower( $search ); + $log = array_values( + array_filter( + $log, + function ( $row ) use ( $needle ) { + $hay = strtolower( (string) $row['to'] . ' ' . (string) $row['subject'] . ' ' . (string) $row['note'] ); + return false !== strpos( $hay, $needle ); + } + ) + ); + } + + $per_page = sendbeam_per_page( 'sendbeam_mail_log_per_page' ); + $page = max( 1, (int) $this->get_pagenum() ); + $total = count( $log ); + + $this->items = array_slice( $log, ( $page - 1 ) * $per_page, $per_page ); + $this->_column_headers = array( $this->get_columns(), array(), array(), $this->get_default_primary_column_name() ); + $this->set_pagination_args( + array( + 'total_items' => $total, + 'per_page' => $per_page, + 'total_pages' => (int) ceil( $total / max( 1, $per_page ) ), + ) + ); + } + + /** What an empty log says. */ + public function no_items() { + if ( '' !== sendbeam_list_search() ) { + esc_html_e( 'No message here matches that.', 'sendbeam' ); + return; + } + esc_html_e( 'Nothing has been sent through SendBeam from this site yet. Send yourself a test above and it will show up here.', 'sendbeam' ); + } + + /** + * The row's checkbox. + * + * @param array $item Row. + * @return string + */ + public function column_cb( $item ) { + return sprintf( '', (int) $item['index'] ); + } + + /** + * When it went, in the site's own format. + * + * @param array $item Row. + * @return string + */ + public function column_date( $item ) { + return '' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $item['at'] ) ) . ''; + } + + /** + * Sent, fell back, or failed. + * + * @param array $item Row. + * @return string + */ + public function column_result( $item ) { + $map = array( + 'sent' => array( 'moss', __( 'Sent via SendBeam', 'sendbeam' ) ), + 'fallback' => array( 'amber', __( 'Server mailer', 'sendbeam' ) ), + 'failed' => array( 'vermilion', __( 'Failed', 'sendbeam' ) ), + ); + $key = isset( $map[ $item['result'] ] ) ? $item['result'] : 'failed'; + return '' . esc_html( $map[ $key ][1] ) . ''; + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/list-tables.php b/includes/list-tables.php new file mode 100644 index 0000000..88d0963 --- /dev/null +++ b/includes/list-tables.php @@ -0,0 +1,128 @@ +` by hand: no search, no + * pagination, no bulk actions, no empty state, and — the part that mattered + * most on a phone — none of core's column collapsing, so the Forms and Site + * email screens were the two that scrolled sideways. + * + * `WP_List_Table` is marked `@access private` in core, which every plugin that + * has a list ignores, because there is no public alternative and core's own + * screens are the convention people expect. The risk is a core change to the + * class; the mitigation is that these subclasses override only the documented + * extension points (`get_columns`, `prepare_items`, `column_*`, + * `get_bulk_actions`, `no_items`) and nothing else. + * + * @package SendBeam + */ + +defined( 'ABSPATH' ) || exit; + +add_filter( 'set-screen-option', 'sendbeam_set_screen_option', 10, 3 ); +add_action( 'admin_head', 'sendbeam_list_table_columns' ); + +/** + * WP_List_Table is not loaded on every admin page; ask for it before use. + */ +function sendbeam_load_list_table() { + if ( ! class_exists( 'WP_List_Table' ) && defined( 'ABSPATH' ) && file_exists( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; + } + return class_exists( 'WP_List_Table' ); +} + +/** + * Keep the per-page choice the Screen Options tab offers. + * + * Without this filter WordPress throws the value away on save and the box + * silently snaps back to the default, which reads as a broken control. + * + * @param mixed $status Whatever an earlier filter decided. + * @param string $option The option being saved. + * @param mixed $value The value chosen. + * @return mixed + */ +function sendbeam_set_screen_option( $status, $option, $value ) { + if ( in_array( $option, array( 'sendbeam_forms_per_page', 'sendbeam_mail_log_per_page', 'sendbeam_lists_per_page' ), true ) ) { + return max( 1, min( 200, (int) $value ) ); + } + return $status; +} + +/** + * Register the per-page screen option for a list screen. + * + * Called from `load-`, which is the only point late enough for + * `get_current_screen()` to exist and early enough for Screen Options to be + * rendered with it. + * + * @param string $option Option name. + * @param string $label Label on the Screen Options tab. + * @param int $default Rows per page out of the box. + */ +function sendbeam_add_per_page_option( $option, $label, $default = 20 ) { + if ( ! function_exists( 'add_screen_option' ) ) { + return; + } + add_screen_option( + 'per_page', + array( + 'label' => $label, + 'default' => $default, + 'option' => $option, + ) + ); +} + +/** + * How many rows this screen shows. + * + * @param string $option Option name. + * @param int $default Fallback. + * @return int + */ +function sendbeam_per_page( $option, $default = 20 ) { + $user = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; + $per = $user ? get_user_meta( $user, $option, true ) : ''; + $per = '' === $per ? 0 : (int) $per; + return $per > 0 ? $per : $default; +} + +/** + * The search term for a list screen. + * + * @return string + */ +function sendbeam_list_search() { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a search box is a GET form; core's own list tables read `s` the same way. + return isset( $_REQUEST['s'] ) ? trim( sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) ) : ''; +} + +/** + * Give core the column widths it needs to collapse a row on a phone. + * + * Core's responsive list table hides every column but the primary one behind + * a toggle, and works out which is primary from `get_primary_column_name()`. + * Nothing else is needed — this only pins the checkbox column, which core + * otherwise lets stretch. + */ +function sendbeam_list_table_columns() { + if ( ! sendbeam_is_our_screen() ) { + return; + } + echo ''; +} + +if ( ! class_exists( 'WP_List_Table' ) ) { + // The smoke tests load this file without WordPress. Everything below + // extends a core class, so without it the require is a parse-time fatal — + // and the functions above are the half worth having in that case. + return; +} + +// One class per file, because that is what the WordPress standard asks for +// and what the plugin review tooling checks; this file is the module. +require_once __DIR__ . '/class-sendbeam-forms-table.php'; +require_once __DIR__ . '/class-sendbeam-mail-log-table.php'; +require_once __DIR__ . '/class-sendbeam-lists-table.php'; diff --git a/includes/menu.php b/includes/menu.php index 54e49f0..18ef653 100644 --- a/includes/menu.php +++ b/includes/menu.php @@ -43,6 +43,7 @@ function sendbeam_pages() { 'menu' => __( 'Forms', 'sendbeam' ), 'title' => __( 'Forms', 'sendbeam' ), 'render' => 'sendbeam_screen_forms', + 'list' => array( 'SendBeam_Forms_Table', 'sendbeam_forms_per_page', __( 'Forms per page', 'sendbeam' ) ), ), 'sendbeam-popups' => array( 'menu' => __( 'Pop-ups', 'sendbeam' ), @@ -53,11 +54,13 @@ function sendbeam_pages() { 'menu' => __( 'Audience', 'sendbeam' ), 'title' => __( 'Audience', 'sendbeam' ), 'render' => 'sendbeam_screen_audience', + 'list' => array( 'SendBeam_Lists_Table', 'sendbeam_lists_per_page', __( 'Lists per page', 'sendbeam' ) ), ), 'sendbeam-mail' => array( 'menu' => __( 'Site email', 'sendbeam' ), 'title' => __( 'Site email', 'sendbeam' ), 'render' => 'sendbeam_screen_mail', + 'list' => array( 'SendBeam_Mail_Log_Table', 'sendbeam_mail_log_per_page', __( 'Messages per page', 'sendbeam' ) ), ), 'sendbeam-ecommerce' => array( 'menu' => __( 'E-commerce', 'sendbeam' ), @@ -117,20 +120,55 @@ function sendbeam_admin_menu() { if ( ! empty( $page['hidden'] ) ) { // Registered with no parent: routable, capability-checked and // titled, but absent from the menu. - add_submenu_page( '', $page['title'], $page['menu'], 'manage_options', $slug, 'sendbeam_render_admin_page' ); - continue; + $hook = add_submenu_page( '', $page['title'], $page['menu'], 'manage_options', $slug, 'sendbeam_render_admin_page' ); + } else { + $hook = add_submenu_page( + SENDBEAM_MENU_SLUG, + $page['title'], + $page['menu'], + 'manage_options', + $slug, + 'sendbeam_render_admin_page' + ); + } + if ( $hook && ! empty( $page['list'] ) ) { + add_action( 'load-' . $hook, 'sendbeam_load_list_screen' ); } - add_submenu_page( - SENDBEAM_MENU_SLUG, - $page['title'], - $page['menu'], - 'manage_options', - $slug, - 'sendbeam_render_admin_page' - ); } } +/** + * Prepare a screen that has a list on it, before anything is rendered. + * + * Three things have to happen here rather than in the screen function: + * Screen Options is built before the page body, a bulk action has to be acted + * on before the rows are read, and `WP_List_Table` wants constructing while + * `get_current_screen()` is the screen it belongs to. + */ +function sendbeam_load_list_screen() { + $pages = sendbeam_pages(); + $slug = sendbeam_current_page(); + if ( empty( $pages[ $slug ]['list'] ) || ! sendbeam_load_list_table() ) { + return; + } + list( $class, $option, $label ) = $pages[ $slug ]['list']; + + sendbeam_add_per_page_option( $option, $label ); + + $GLOBALS['sendbeam_list_table'] = new $class(); + $GLOBALS['sendbeam_list_table']->process_bulk_action(); + $GLOBALS['sendbeam_list_table']->prepare_items(); +} + +/** + * The list table this screen prepared, if it has one. + * + * @return WP_List_Table|null + */ +function sendbeam_list_table() { + return isset( $GLOBALS['sendbeam_list_table'] ) ? $GLOBALS['sendbeam_list_table'] : null; +} + /** * Which SendBeam page is being rendered. * diff --git a/includes/screens.php b/includes/screens.php index 6491b3d..30c8ea6 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -756,54 +756,11 @@ function sendbeam_screen_forms() { sendbeam_form_close(); sendbeam_card_close(); - $forms = sendbeam_remote_forms(); - - sendbeam_card_open( __( 'Your forms', 'sendbeam' ), is_array( $forms ) ? sprintf( /* translators: %d: count */ _n( '%d form', '%d forms', count( $forms ), 'sendbeam' ), count( $forms ) ) : '' ); - - if ( null === $forms ) { - echo '

    ' . esc_html__( 'Add an API key with the Forms (read) permission on the Overview tab and every form in this workspace will be listed here, ready to drop into a page.', 'sendbeam' ) . '

    '; - } elseif ( ! $forms ) { - echo '

    ' . wp_kses( - sprintf( - /* translators: %s: link */ - __( 'No forms in this workspace yet. %s.', 'sendbeam' ), - '' . esc_html__( 'Create your first form', 'sendbeam' ) . '' - ), - array( - 'a' => array( - 'href' => array(), - 'target' => array(), - 'rel' => array(), - ), - ) - ) . '

    '; - } else { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - foreach ( $forms as $form ) { - $id = (string) $form['id']; - $kind = isset( $form['kind'] ) ? (string) $form['kind'] : 'signup'; - $name = isset( $form['name'] ) && '' !== $form['name'] ? (string) $form['name'] : __( '(untitled form)', 'sendbeam' ); - $shortcode = 'contact' === $kind ? '[sendbeam_contact]' : '[sendbeam_form id="' . $id . '"]'; - ?> - - - - - - -
    ' . esc_html__( 'Form', 'sendbeam' ) . '' . esc_html__( 'Kind', 'sendbeam' ) . '' . esc_html__( 'Shortcode', 'sendbeam' ) . '
    - - -
    '; - echo '

    ' . esc_html__( 'Paste a shortcode anywhere, or add the SendBeam Form block and pick the form from its dropdown. Every form on this list can be used as many times as you like, on as many pages as you like.', 'sendbeam' ) . '

    '; - } - sendbeam_card_close(); + sendbeam_list_card( + __( 'Your forms', 'sendbeam' ), + __( 'Every form in this workspace, ready to drop into a page.', 'sendbeam' ), + __( 'Search forms', 'sendbeam' ) + ); sendbeam_placing_forms_card(); } @@ -816,37 +773,11 @@ function sendbeam_screen_forms() { function sendbeam_screen_audience() { $lists = sendbeam_lists(); - sendbeam_card_open( __( 'Lists', 'sendbeam' ), is_array( $lists ) ? sprintf( /* translators: %d: count */ _n( '%d list', '%d lists', count( $lists ), 'sendbeam' ), count( $lists ) ) : '' ); - - if ( null === $lists ) { - echo '

    ' . esc_html__( 'Your lists cannot be read with the current key. Add the Lists (read) permission to it in SendBeam to see them here.', 'sendbeam' ) . '

    '; - } elseif ( ! $lists ) { - echo '

    ' . esc_html__( 'This workspace has no lists yet.', 'sendbeam' ) . '

    '; - } else { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - foreach ( $lists as $list ) { - ?> - - - - - -
    ' . esc_html__( 'List', 'sendbeam' ) . '' . esc_html__( 'Subscribers', 'sendbeam' ) . '' . esc_html__( 'Confirmation', 'sendbeam' ) . '
    - - - - - -
    '; - } - echo '

    ' . esc_html__( 'Which list a form subscribes people to is set on the form itself, in SendBeam.', 'sendbeam' ) . '

    '; - sendbeam_card_close(); + sendbeam_list_card( + __( 'Lists', 'sendbeam' ), + __( 'Which list a form subscribes people to is set on the form itself, in SendBeam.', 'sendbeam' ), + __( 'Search lists', 'sendbeam' ) + ); sendbeam_screen_sync( $lists ); sendbeam_screen_form_plugins( $lists ); @@ -1279,25 +1210,53 @@ function sendbeam_screen_mail() { '; - echo '' . esc_html__( 'When', 'sendbeam' ) . '' . esc_html__( 'To', 'sendbeam' ) . ''; - echo '' . esc_html__( 'Subject', 'sendbeam' ) . '' . esc_html__( 'Result', 'sendbeam' ) . ''; - echo ''; - foreach ( $log as $row ) { - $result = 'sent' === $row['result'] ? __( 'Sent via SendBeam', 'sendbeam' ) : ( 'fallback' === $row['result'] ? __( 'Server mailer', 'sendbeam' ) : __( 'Failed', 'sendbeam' ) ); - echo ''; - echo '' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $row['at'] ) ) . ''; - echo '' . esc_html( $row['to'] ) . ''; - echo '' . esc_html( $row['subject'] ) . ''; - echo '' . esc_html( $result . ( $row['note'] ? ' — ' . $row['note'] : '' ) ) . ''; - echo ''; - } - echo ''; + sendbeam_list_card( + __( 'Email log', 'sendbeam' ), + __( 'The last few messages this site handed to SendBeam, and what became of each.', 'sendbeam' ), + __( 'Search the log', 'sendbeam' ) + ); +} + +/** + * A card whose body is the screen's list table. + * + * One function because all three are the same shape: a heading, a sentence, + * the search box, and core's table. The table itself was prepared on + * `load-` — before any of this ran — so a bulk action has already been + * applied by the time the rows are read. + * + * @param string $title Card heading. + * @param string $note The sentence under it. + * @param string $search Placeholder and label for the search box. + */ +function sendbeam_list_card( $title, $note, $search ) { + $table = function_exists( 'sendbeam_list_table' ) ? sendbeam_list_table() : null; + + sendbeam_card_open( $title ); + echo '

    ' . esc_html( $note ) . '

    '; + + if ( ! $table ) { + echo '

    ' . esc_html__( 'This list cannot be shown on this version of WordPress.', 'sendbeam' ) . '

    '; sendbeam_card_close(); + return; } + + // GET, because a search is a place you can link to and come back to. The + // hidden `page` keeps the search on this screen rather than throwing it + // at the admin dashboard. + echo '
    '; + printf( '', esc_attr( sendbeam_current_page() ) ); + $table->search_box( $search, 'sendbeam-search' ); + echo '
    '; + + // POST, for the bulk actions and their nonce. Core prints both inside + // display(); the form around it is ours to provide. + echo '
    '; + printf( '', esc_attr( sendbeam_current_page() ) ); + $table->display(); + echo '
    '; + + sendbeam_card_close(); } /* ------------------------------------------------------------ E-commerce */ diff --git a/sendbeam.php b/sendbeam.php index c9cb9fd..160dfd5 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -28,6 +28,7 @@ require SENDBEAM_DIR . 'includes/ecommerce.php'; require SENDBEAM_DIR . 'includes/bridges.php'; require SENDBEAM_DIR . 'includes/admin-ui.php'; +require SENDBEAM_DIR . 'includes/list-tables.php'; require SENDBEAM_DIR . 'includes/menu.php'; require SENDBEAM_DIR . 'includes/screens.php'; require SENDBEAM_DIR . 'includes/settings.php'; diff --git a/tests/smoke.php b/tests/smoke.php index b932039..390589e 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -2208,6 +2208,206 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { has( $sendbeam_links[0], 'admin.php?page=sendbeam-settings', 'plugins screen: the Settings link points at the Settings page' ); lacks( $sendbeam_links[0], 'options-general.php', 'plugins screen: the Settings link does not point at the old address' ); +/* ────────────────────────── The list tables ──────────────────────────── + * Three hand-rolled tables with no search, no pagination, no empty state and + * no phone behaviour became three WP_List_Table subclasses. What matters + * here is what a browser gets: the right columns, a primary column core can + * collapse a row down to, rows that render, and an empty state that says what + * to do rather than nothing at all. + */ +$GLOBALS['stub']['caps']['manage_options'] = true; +$_REQUEST = array(); + +/** Render one list table the way sendbeam_list_card() does. */ +function sb_render_table( $table ) { + $table->prepare_items(); + ob_start(); + $table->display(); + return ob_get_clean(); +} + +// ── Forms ─────────────────────────────────────────────────────────────── +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 200 ), + 'body' => wp_json_encode( + array( + 'forms' => array( + array( + 'id' => $form, + 'name' => 'Newsletter signup', + 'kind' => 'signup', + ), + array( + 'id' => $other, + 'name' => 'Ask us anything', + 'kind' => 'contact', + ), + ), + ) + ), +); +sendbeam_flush_cache(); +update_option( 'sendbeam_settings', array_merge( sendbeam_settings(), array( 'api_key' => 'sb_live_listtablekey1', 'default_form' => $form, 'contact_form' => '' ) ) ); + +$forms_table = new SendBeam_Forms_Table(); +$html = sb_render_table( $forms_table ); +has( $html, 'wp-list-table', 'forms table: it is a core list table' ); +has( $html, 'column-name column-primary', 'forms table: Form is the primary column, so a phone collapses to it' ); +foreach ( array( 'Form', 'Kind', 'Shortcode', 'Placed on' ) as $sendbeam_col ) { + has( $html, '>' . $sendbeam_col . '', "forms table: the $sendbeam_col column is there" ); +} +has( $html, 'Newsletter signup', 'forms table: a form renders as a row' ); +has( $html, 'Ask us anything', 'forms table: every form renders' ); +has( $html, '[sendbeam_form id="' . $form . '"]', 'forms table: a signup form shows the shortcode that places it' ); +has( $html, '[sendbeam_contact]', 'forms table: a contact form shows its own shortcode' ); +has( $html, 'sb-copy', 'forms table: the shortcode is one click from the clipboard' ); +has( $html, 'row-actions', 'forms table: rows carry actions, as core rows do' ); +has( $html, 'Preview', 'forms table: Preview is a row action' ); +has( $html, 'Default signup form', 'forms table: the default form is marked as the default' ); +lacks( $html, 'name="action"', 'forms table: nothing here can be changed in bulk, so no bulk control is offered' ); + +// Search narrows it, and says so when it finds nothing. +$_REQUEST['s'] = 'newsletter'; +has( sb_render_table( new SendBeam_Forms_Table() ), 'Newsletter signup', 'forms table: search keeps what matches' ); +lacks( sb_render_table( new SendBeam_Forms_Table() ), 'Ask us anything', 'forms table: search drops what does not' ); +$_REQUEST['s'] = 'nothing like this'; +has( sb_render_table( new SendBeam_Forms_Table() ), 'No form here matches that', 'forms table: a search with no hits says so' ); +$_REQUEST = array(); + +// Empty, and unreadable, are different answers. +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 200 ), + 'body' => wp_json_encode( array( 'forms' => array() ) ), +); +sendbeam_flush_cache(); +has( sb_render_table( new SendBeam_Forms_Table() ), 'Create your first form', 'forms table: an empty workspace is offered a way to fill it' ); +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 403 ), + 'body' => '{"error":"forbidden"}', +); +sendbeam_flush_cache(); +has( sb_render_table( new SendBeam_Forms_Table() ), 'Forms (read) permission', 'forms table: a key that cannot read forms is told which permission is missing' ); + +// ── The email log ─────────────────────────────────────────────────────── +update_option( + 'sendbeam_mail_log', + array( + array( 'at' => 1758700000, 'to' => 'ada@customer.test', 'subject' => 'Order #1001', 'result' => 'sent', 'note' => '' ), + array( 'at' => 1758600000, 'to' => 'bob@customer.test', 'subject' => 'Password reset', 'result' => 'failed', 'note' => 'Monthly email limit reached' ), + array( 'at' => 1758500000, 'to' => 'cat@customer.test', 'subject' => 'New comment', 'result' => 'fallback', 'note' => 'has attachments' ), + ) +); +$log_table = new SendBeam_Mail_Log_Table(); +$html = sb_render_table( $log_table ); +has( $html, 'column-date column-primary', 'email log: Date is the primary column' ); +foreach ( array( 'Date', 'To', 'Subject', 'Result', 'Note' ) as $sendbeam_col ) { + has( $html, '>' . $sendbeam_col . '', "email log: the $sendbeam_col column is there" ); +} +has( $html, 'ada@customer.test', 'email log: a sent message is listed' ); +has( $html, 'Sent via SendBeam', 'email log: a sent message says so' ); +has( $html, 'Monthly email limit reached', 'email log: a failure keeps the reason it failed' ); +has( $html, 'Server mailer', 'email log: a fall-back to the server mailer is named as one' ); +has( $html, 'name="message[]"', 'email log: rows can be ticked' ); +has( $html, '', 'email log: the one bulk action is Delete' ); + +$_REQUEST['s'] = 'password'; +has( sb_render_table( new SendBeam_Mail_Log_Table() ), 'bob@customer.test', 'email log: search keeps what matches' ); +lacks( sb_render_table( new SendBeam_Mail_Log_Table() ), 'ada@customer.test', 'email log: search drops what does not' ); +$_REQUEST = array(); + +update_option( 'sendbeam_mail_log', array() ); +has( sb_render_table( new SendBeam_Mail_Log_Table() ), 'Nothing has been sent through SendBeam', 'email log: an empty log says what to do about it' ); + +// Bulk delete: the rows that were ticked go, and nothing else does. +update_option( + 'sendbeam_mail_log', + array( + array( 'at' => 3, 'to' => 'a@t.test', 'subject' => 'A', 'result' => 'sent', 'note' => '' ), + array( 'at' => 2, 'to' => 'b@t.test', 'subject' => 'B', 'result' => 'sent', 'note' => '' ), + array( 'at' => 1, 'to' => 'c@t.test', 'subject' => 'C', 'result' => 'sent', 'note' => '' ), + ) +); +$_REQUEST = array( + 'action' => 'delete', + 'message' => array( 1 ), + '_wpnonce' => 'nonce:bulk-sendbeam_messages', +); +$table = new SendBeam_Mail_Log_Table(); +$table->process_bulk_action(); +$kept = get_option( 'sendbeam_mail_log' ); +ok( 2 === count( $kept ), 'email log: a bulk delete removes exactly the rows that were ticked' ); +ok( 'a@t.test' === $kept[0]['to'] && 'c@t.test' === $kept[1]['to'], 'email log: the rows that were not ticked are untouched, and stay in order' ); + +// The same request without the nonce must not delete anything. +$_REQUEST = array( + 'action' => 'delete', + 'message' => array( 0 ), +); +$threw = false; +try { + ( new SendBeam_Mail_Log_Table() )->process_bulk_action(); +} catch ( SendBeamStubExit $e ) { + $threw = true; +} +ok( $threw, 'email log: a bulk delete without a valid nonce is refused' ); +ok( 2 === count( get_option( 'sendbeam_mail_log' ) ), 'email log: and nothing was deleted' ); +$_REQUEST = array(); +update_option( 'sendbeam_mail_log', array() ); + +// ── Audience lists ────────────────────────────────────────────────────── +$GLOBALS['stub']['remote_reply'] = function ( $url ) { + if ( false !== strpos( $url, '/contacts?limit=1' ) ) { + $total = false !== strpos( $url, '/lists/l1/' ) ? 412 : 7; + return array( + 'response' => array( 'code' => 200 ), + 'body' => wp_json_encode( array( 'pagination' => array( 'total' => $total ) ) ), + ); + } + return array( + 'response' => array( 'code' => 200 ), + 'body' => wp_json_encode( + array( + 'lists' => array( + array( 'id' => 'l1', 'name' => 'Subscribers', 'double_optin' => true ), + array( 'id' => 'l2', 'name' => 'Trade buyers', 'double_optin' => false ), + ), + ) + ), + ); +}; +sendbeam_flush_cache(); +$html = sb_render_table( new SendBeam_Lists_Table() ); +has( $html, 'column-name column-primary', 'lists table: List is the primary column' ); +foreach ( array( 'List', 'Subscribers', 'Confirmation' ) as $sendbeam_col ) { + has( $html, '>' . $sendbeam_col . '', "lists table: the $sendbeam_col column is there" ); +} +has( $html, 'Subscribers', 'lists table: a list renders as a row' ); +has( $html, 'Trade buyers', 'lists table: every list renders' ); +has( $html, '412', 'lists table: the subscriber count is shown' ); +has( $html, 'Double opt-in', 'lists table: a double opt-in list is marked as one' ); +has( $html, 'Single opt-in', 'lists table: and a single opt-in list is too' ); +has( $html, 'Open in SendBeam', 'lists table: the row links through to the list itself' ); + +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 403 ), + 'body' => '{"error":"forbidden"}', +); +sendbeam_flush_cache(); +has( sb_render_table( new SendBeam_Lists_Table() ), 'Lists (read) permission', 'lists table: a key that cannot read lists is told which permission is missing' ); + +// ── Screen options ────────────────────────────────────────────────────── +$GLOBALS['stub']['screen_options'] = array(); +sendbeam_add_per_page_option( 'sendbeam_forms_per_page', 'Forms per page' ); +ok( isset( $GLOBALS['stub']['screen_options']['per_page'] ), 'screen options: a list screen offers a rows-per-page box' ); +ok( 'sendbeam_forms_per_page' === $GLOBALS['stub']['screen_options']['per_page']['option'], 'screen options: it saves against the screen\'s own option' ); +ok( 20 === sendbeam_set_screen_option( false, 'sendbeam_forms_per_page', '20' ), 'screen options: a sane per-page value is kept' ); +ok( 200 === sendbeam_set_screen_option( false, 'sendbeam_forms_per_page', '99999' ), 'screen options: an absurd one is clamped' ); +ok( 1 === sendbeam_set_screen_option( false, 'sendbeam_forms_per_page', '0' ), 'screen options: and so is zero' ); +ok( false === sendbeam_set_screen_option( false, 'another_plugin_per_page', '50' ), 'screen options: another plugin\'s option is left alone' ); + +sendbeam_flush_cache(); +$GLOBALS['stub']['remote_reply'] = null; + // One version number, five files. 1.6.2 shipped with the block's asset // version still on 1.6.1, which is how WordPress decides whether the editor // may reuse a cached copy of the block script. diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index fa5e67d..9512782 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -305,3 +305,121 @@ function wp_enqueue_media( $args = array() ) {} function get_admin_page_title() { return 'SendBeam'; } function submit_button_wrapper() {} function esc_attr_e( $s, $d = null ) { echo esc_attr( $s ); } + +// ── WP_List_Table ─────────────────────────────────────────────────────── +/** + * Enough of core's list table to render one. + * + * Not a copy of core: the point is to exercise the parts the plugin's + * subclasses override — the columns, the primary column, the row callbacks, + * the empty state and the bulk actions — and to produce markup shaped like + * core's, so an assertion about `column-primary` or `wp-list-table` is an + * assertion about what a browser would actually receive. + */ +#[AllowDynamicProperties] +class WP_List_Table { + public $items = array(); + public $_args = array(); + public $_column_headers = array(); + public $_pagination = array(); + + public function __construct( $args = array() ) { + $this->_args = array_merge( + array( + 'singular' => '', + 'plural' => '', + 'ajax' => false, + ), + $args + ); + } + + public function get_columns() { + return array(); } + protected function get_bulk_actions() { + return array(); } + public function no_items() { + echo 'No items.'; } + public function get_pagenum() { + return isset( $_REQUEST['paged'] ) ? max( 1, (int) $_REQUEST['paged'] ) : 1; } + public function set_pagination_args( $args ) { + $this->_pagination = $args; } + public function current_action() { + foreach ( array( 'action', 'action2' ) as $key ) { + if ( isset( $_REQUEST[ $key ] ) && '-1' !== $_REQUEST[ $key ] ) { + return sanitize_key( $_REQUEST[ $key ] ); + } + } + return false; + } + + protected function get_primary_column_name() { + return method_exists( $this, 'get_default_primary_column_name' ) ? $this->get_default_primary_column_name() : key( $this->get_columns() ); + } + + protected function row_actions( $actions, $always_visible = false ) { + $out = array(); + foreach ( $actions as $key => $link ) { + $out[] = '' . $link . ''; + } + return '
    ' . implode( ' | ', $out ) . '
    '; + } + + public function search_box( $text, $input_id ) { + printf( + '', + esc_attr( $input_id ), + esc_attr( $text ), + esc_attr( isset( $_REQUEST['s'] ) ? $_REQUEST['s'] : '' ) + ); + } + + public function display() { + $columns = $this->get_columns(); + $primary = $this->get_primary_column_name(); + $bulk = $this->get_bulk_actions(); + + if ( $bulk ) { + echo '
    '; + wp_nonce_field( 'bulk-' . $this->_args['plural'] ); + echo '
    '; + } + + echo ''; + foreach ( $columns as $key => $label ) { + $class = 'manage-column column-' . $key . ( $key === $primary ? ' column-primary' : '' ); + echo ''; + } + echo ''; + if ( ! $this->items ) { + echo ''; + } + foreach ( $this->items as $item ) { + echo ''; + foreach ( $columns as $key => $label ) { + $method = 'column_' . $key; + $value = method_exists( $this, $method ) ? $this->$method( $item ) : $this->column_default( $item, $key ); + $class = 'column-' . $key . ( $key === $primary ? ' has-row-actions column-primary' : '' ); + $tag = 'cb' === $key ? 'th' : 'td'; + echo '<' . $tag . ' class="' . esc_attr( $class ) . '" data-colname="' . esc_attr( wp_strip_all_tags( $label ) ) . '">' . $value . ''; + } + echo ''; + } + echo '
    ' . $label . '
    '; + $this->no_items(); + echo '
    '; + printf( '
    %d items
    ', isset( $this->_pagination['total_items'] ) ? (int) $this->_pagination['total_items'] : 0 ); + } + + protected function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; } +} + +function wp_strip_all_tags( $string, $remove_breaks = false ) { return strip_tags( (string) $string ); } +function add_screen_option( $option, $args = array() ) { $GLOBALS['stub']['screen_options'][ $option ] = $args; } From d95707e37a797ae4ecbda6f6c4d7ad202918c642 Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 07:47:43 +0000 Subject: [PATCH 32/75] Walk a new site through setup once, and let it walk away Installing the plugin left a notice on the Dashboard and nothing else, so a site owner who missed it had a plugin that did nothing. Activation now sends them once to a four-step guide: connect, verify the sending domain, switch on site email, place a form. Once, and guarded: a bulk activation is left alone, a site that already has a key is left alone, and a host can switch the whole thing off with the sendbeam_setup_wizard filter. The admin menu and admin bar stay put, every step can be skipped, and "Go back to the Dashboard" is under all of them. Where it got to is remembered, so leaving and coming back resumes. Each step is the panel the matching settings screen already uses, so there is still only one Connect button and one records table in this plugin. --- includes/menu.php | 17 +- includes/onboarding.php | 9 + includes/wizard.php | 408 ++++++++++++++++++++++++++++++++++++++++ sendbeam.php | 1 + tests/smoke.php | 192 ++++++++++++++++++- tests/wp-stubs.php | 12 +- 6 files changed, 635 insertions(+), 4 deletions(-) create mode 100644 includes/wizard.php diff --git a/includes/menu.php b/includes/menu.php index 18ef653..78644ed 100644 --- a/includes/menu.php +++ b/includes/menu.php @@ -28,7 +28,9 @@ /** * Every SendBeam admin page: its slug, its menu label, its heading and what renders it. * - * `hidden` pages are routable and titled but never appear in the menu. + * `hidden` pages are routable and titled but never appear in the menu — the + * setup wizard is reached from a redirect and from the Overview, not from a + * menu item somebody would press a second time. * * @return array */ @@ -77,6 +79,12 @@ function sendbeam_pages() { 'title' => __( 'Help', 'sendbeam' ), 'render' => 'sendbeam_screen_help', ), + 'sendbeam-setup' => array( + 'menu' => __( 'Set up SendBeam', 'sendbeam' ), + 'title' => __( 'Set up SendBeam', 'sendbeam' ), + 'render' => 'sendbeam_screen_wizard', + 'hidden' => true, + ), ); } @@ -234,6 +242,13 @@ function sendbeam_render_admin_page() { $pages = sendbeam_pages(); $page = $pages[ $slug ]; + // The wizard supplies its own shell: it has a progress rail where the + // other screens have a section name, and no card grid at all. + if ( 'sendbeam-setup' === $slug ) { + call_user_func( $page['render'] ); + return; + } + ?>

    diff --git a/includes/onboarding.php b/includes/onboarding.php index 7c26eac..dabcb33 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -32,6 +32,15 @@ function sendbeam_on_activate() { add_option( 'sendbeam_activated_at', time(), '', false ); } sendbeam_flush_cache(); + + /* + * A transient rather than an option, and a short one: the redirect it + * asks for should happen on the very next admin page load or not at all. + * An activation that ends in a fatal, or a WP-CLI activation nobody is + * watching, must not leave a site that hijacks its owner's next visit to + * wp-admin half an hour later. + */ + set_transient( SENDBEAM_WIZARD_FLAG, 1, 30 ); } /** diff --git a/includes/wizard.php b/includes/wizard.php new file mode 100644 index 0000000..704bdb0 --- /dev/null +++ b/includes/wizard.php @@ -0,0 +1,408 @@ + + */ +function sendbeam_wizard_steps() { + return array( + array( + 'key' => 'connect', + 'label' => __( 'Connect', 'sendbeam' ), + ), + array( + 'key' => 'domain', + 'label' => __( 'Sending domain', 'sendbeam' ), + ), + array( + 'key' => 'mail', + 'label' => __( 'Site email', 'sendbeam' ), + ), + array( + 'key' => 'form', + 'label' => __( 'Place a form', 'sendbeam' ), + ), + ); +} + +/** + * Which step is showing: the URL, else where this person got to, else the first. + * + * @return int A 1-based step number. + */ +function sendbeam_wizard_current_step() { + $max = count( sendbeam_wizard_steps() ); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation between steps of a form nobody has submitted yet. + $asked = isset( $_GET['step'] ) ? (int) $_GET['step'] : 0; + if ( $asked >= 1 && $asked <= $max ) { + return $asked; + } + $saved = (int) get_user_meta( get_current_user_id(), SENDBEAM_WIZARD_STEP, true ); + return ( $saved >= 1 && $saved <= $max ) ? $saved : 1; +} + +/** + * The URL of one step. + * + * @param int $step 1-based step number. + * @return string + */ +function sendbeam_wizard_url( $step = 1 ) { + return add_query_arg( 'step', max( 1, (int) $step ), sendbeam_page_url( 'sendbeam-setup' ) ); +} + +/** + * Has this site finished, or deliberately left, the wizard? + * + * @return bool + */ +function sendbeam_wizard_done() { + return (bool) get_option( 'sendbeam_setup_done' ); +} + +/** + * Mark the wizard finished, for everyone on the site. + * + * Finishing is about the site rather than the person: a second administrator + * arriving at a connected site should not be walked through connecting it. + */ +function sendbeam_wizard_finish() { + update_option( 'sendbeam_setup_done', 1, false ); + delete_user_meta( get_current_user_id(), SENDBEAM_WIZARD_STEP ); +} + +/** + * Send someone to the wizard once, on the page load after activation. + * + * Three guards, and each one is a real case rather than defensive padding: + * `activate-multi` is somebody activating twenty plugins at once and being + * thrown at the first one's welcome screen, which is the behaviour that makes + * people hate this pattern; a site that already has a key has already done + * this; and a host or an agency that never wants it can switch it off with + * one filter. + */ +function sendbeam_maybe_redirect_to_wizard() { + if ( ! get_transient( SENDBEAM_WIZARD_FLAG ) ) { + return; + } + // Once, whatever happens next — including a redirect somebody's browser + // never follows. + delete_transient( SENDBEAM_WIZARD_FLAG ); + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- core's own flag on the Plugins screen; read, never acted on. + if ( isset( $_GET['activate-multi'] ) ) { + return; + } + if ( ! current_user_can( 'manage_options' ) || wp_doing_ajax() || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) { + return; + } + if ( sendbeam_wizard_done() || '' !== sendbeam_api_key() ) { + return; + } + /** + * Whether to offer the first-run wizard at all. + * + * A host that installs this plugin for its customers, or an agency + * rolling it out across fifty sites, has already done the setting up. + * + * @param bool $show Whether to redirect to the wizard on activation. + */ + if ( ! apply_filters( 'sendbeam_setup_wizard', true ) ) { + return; + } + + wp_safe_redirect( sendbeam_wizard_url( 1 ) ); + exit; +} + +/** + * Skip, continue, or leave. + * + * All three are the same POST, because all three are "remember where I am and + * put me somewhere else" — and a skip that used a GET link would be followed + * by a link prefetcher on somebody's behalf. + */ +function sendbeam_handle_wizard_step() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); + } + check_admin_referer( 'sendbeam_wizard_step' ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked immediately above. + $step = isset( $_POST['step'] ) ? (int) $_POST['step'] : 1; + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked immediately above. + $go = isset( $_POST['go'] ) ? sanitize_key( wp_unslash( $_POST['go'] ) ) : 'next'; + + $max = count( sendbeam_wizard_steps() ); + $next = min( $max, max( 1, $step + 1 ) ); + + if ( 'exit' === $go ) { + // Left, not finished. Where they got to is kept, so the link on the + // Overview picks the wizard up rather than restarting it. + update_user_meta( get_current_user_id(), SENDBEAM_WIZARD_STEP, max( 1, min( $max, $step ) ) ); + wp_safe_redirect( admin_url() ); + exit; + } + + if ( 'finish' === $go || $step >= $max ) { + sendbeam_wizard_finish(); + wp_safe_redirect( sendbeam_page_url( 'sendbeam' ) ); + exit; + } + + update_user_meta( get_current_user_id(), SENDBEAM_WIZARD_STEP, $next ); + wp_safe_redirect( sendbeam_wizard_url( $next ) ); + exit; +} + +/** + * The wizard page. + * + * Inside `.wrap`, with the admin bar and menu left alone. Full-screen routes + * are the other convention and they are the one that traps people: a wizard + * that hides the way out is a wizard somebody closes the tab on. + */ +function sendbeam_screen_wizard() { + $steps = sendbeam_wizard_steps(); + $current = sendbeam_wizard_current_step(); + $total = count( $steps ); + $step = $steps[ $current - 1 ]; + $last = $current >= $total; + ?> +
    +

    + +

    + +
    +
    + + SendBeam + + +
    +
    + + + +
    +
    + + + +
    + +
    +
    + '; + foreach ( $steps as $i => $step ) { + $number = $i + 1; + $state = 'sb-rail__step'; + if ( $number < $current ) { + $state .= ' is-done'; + } elseif ( $number === $current ) { + $state .= ' is-current'; + } + printf( + '
  • %4$s
  • ', + esc_attr( $state ), + $number === $current ? ' aria-current="step"' : '', + $number < $current ? '✓' : (int) $number, + esc_html( $step['label'] ) + ); + } + echo ''; +} + +/** + * The heading above one step. + * + * @param string $key Step key. + * @return string + */ +function sendbeam_wizard_heading( $key ) { + $headings = array( + 'connect' => __( 'Connect your SendBeam account', 'sendbeam' ), + 'domain' => __( 'Verify the domain your email is sent from', 'sendbeam' ), + 'mail' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), + 'form' => __( 'Put a form on the site', 'sendbeam' ), + ); + return isset( $headings[ $key ] ) ? $headings[ $key ] : __( 'Set up SendBeam', 'sendbeam' ); +} + +/** + * The controls under every step. + * + * Skip and Continue are the same button in two moods: both move on, and the + * only difference is whether the step was finished. Saying so plainly is + * better than hiding Skip on the steps somebody most wants to skip. + * + * @param int $current 1-based step number. + * @param bool $last Whether this is the final step. + */ +function sendbeam_wizard_foot( $current, $last ) { + echo '
    '; + wp_nonce_field( 'sendbeam_wizard_step' ); + echo ''; + printf( '', (int) $current ); + + printf( + '', + esc_attr( $last ? 'finish' : 'next' ), + esc_html( $last ? __( 'Finish', 'sendbeam' ) : __( 'Continue', 'sendbeam' ) ) + ); + + if ( ! $last ) { + printf( + '', + esc_html__( 'Skip this step', 'sendbeam' ) + ); + } + + printf( + '', + esc_html__( 'Go back to the Dashboard', 'sendbeam' ) + ); + echo '
    '; + echo '

    ' . esc_html__( 'Nothing here has to be done now. Every step is also on the Overview, and skipping one leaves it there for later.', 'sendbeam' ) . '

    '; +} + +/** + * Step 1: the Connect panel, exactly as the Settings page shows it. + */ +function sendbeam_wizard_step_connect() { + if ( sendbeam_is_connected() ) { + $status = sendbeam_connect_status(); + $workspace = sendbeam_connect_workspace_name(); + if ( '' === $workspace ) { + $workspace = (string) $status['workspace']['name']; + } + echo '

    ' . esc_html( + '' !== $workspace + /* translators: %s: the SendBeam workspace name */ + ? sprintf( __( 'Connected to %s. Nothing more to do here.', 'sendbeam' ), $workspace ) + : __( 'This site is connected. Nothing more to do here.', 'sendbeam' ) + ) . '

    '; + return; + } + sendbeam_connect_panel(); + sendbeam_connect_paste_disclosure(); +} + +/** + * Step 2: the sending-domain panel, exactly as the Settings page shows it. + */ +function sendbeam_wizard_step_domain() { + if ( ! sendbeam_is_connected() ) { + echo '

    ' . esc_html__( 'This step needs a connected site. Go back to step 1, or skip this one and come back to it from the Overview.', 'sendbeam' ) . '

    '; + return; + } + sendbeam_domain_panel( sendbeam_connect_status(), true ); +} + +/** + * Step 3: the site-email settings and the test send, as the Site email screen has them. + */ +function sendbeam_wizard_step_mail() { + if ( ! sendbeam_is_connected() ) { + echo '

    ' . esc_html__( 'This step needs a connected site. Go back to step 1, or skip this one and come back to it from the Overview.', 'sendbeam' ) . '

    '; + return; + } + + $status = sendbeam_connect_status(); + echo '

    ' . esc_html__( 'Optional, and easy to change later. With this on, the email WordPress already sends — password resets, receipts, comment and form notifications — goes out through your verified SendBeam domain instead of the web server\'s own mailer.', 'sendbeam' ) . '

    '; + + sendbeam_overview_mail_panel( $status, true ); + + $settings = sendbeam_settings(); + if ( empty( $settings['mail_enabled'] ) && empty( $status['domain']['verified'] ) ) { + echo '

    ' . esc_html__( 'Site email waits on step 2: a site must never have its password resets routed through a domain nothing has verified yet.', 'sendbeam' ) . '

    '; + } +} + +/** + * Step 4: the form, and the two ways it gets onto a page. + */ +function sendbeam_wizard_step_form() { + if ( ! sendbeam_is_connected() ) { + echo '

    ' . esc_html__( 'This step needs a connected site. Go back to step 1, or skip this one and come back to it from the Overview.', 'sendbeam' ) . '

    '; + return; + } + + $steps = sendbeam_setup_steps(); + $step = $steps[2]; + + echo '

    ' . esc_html( $step['detail'] ) . '

    '; + echo '

    ' . wp_kses( + __( 'In the editor, press the + button and search for "SendBeam", or type /sendbeam on a new line.', 'sendbeam' ), + array( + 'strong' => array(), + 'code' => array(), + ) + ) . '

    '; + + sendbeam_overview_form_panel( $step, true ); +} diff --git a/sendbeam.php b/sendbeam.php index 160dfd5..4ac9fd4 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -35,5 +35,6 @@ require SENDBEAM_DIR . 'includes/render.php'; require SENDBEAM_DIR . 'includes/mail.php'; require SENDBEAM_DIR . 'includes/onboarding.php'; +require SENDBEAM_DIR . 'includes/wizard.php'; require SENDBEAM_DIR . 'includes/connect.php'; require SENDBEAM_DIR . 'includes/connect-status.php'; diff --git a/tests/smoke.php b/tests/smoke.php index 390589e..c539bff 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -642,6 +642,179 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), delete_transient( 'sendbeam_subscriber_count' ); update_option( 'sendbeam_settings', array() ); +/* ─────────────────────────── The setup wizard ────────────────────────── + * One redirect, once, guarded three ways, into a page that can be left from + * every step. The guards are the whole of the argument for doing this at all: + * a redirect that fires twice, or during a bulk activation, is the behaviour + * that makes people hate first-run wizards. + */ +$GLOBALS['stub']['user_id'] = 7; +$GLOBALS['stub']['caps']['manage_options'] = true; +delete_option( 'sendbeam_setup_done' ); +update_option( 'sendbeam_settings', array() ); +sendbeam_flush_cache(); + +/** Drive the redirect guard and say where it sent us, or '' for nowhere. */ +function sb_wizard_redirect() { + unset( $GLOBALS['stub']['redirect'] ); + try { + sendbeam_maybe_redirect_to_wizard(); + } catch ( SendBeamStubExit $e ) { + unset( $e ); + } + return isset( $GLOBALS['stub']['redirect'] ) ? $GLOBALS['stub']['redirect']['url'] : ''; +} + +// Activation arms it, and the very next admin page load spends it. +$GLOBALS['stub']['transients'] = array(); +sendbeam_on_activate(); +ok( 1 === get_transient( SENDBEAM_WIZARD_FLAG ), 'wizard: activation arms the redirect' ); +has( sb_wizard_redirect(), 'page=sendbeam-setup', 'wizard: the first admin page load after activating lands on the wizard' ); +ok( '' === sb_wizard_redirect(), 'wizard: and the load after that does not — it fires once' ); + +// Twenty plugins at once must not throw somebody at this one's welcome page. +sendbeam_on_activate(); +$_GET = array( 'activate-multi' => 'true' ); +ok( '' === sb_wizard_redirect(), 'wizard: a bulk activation is left alone' ); +$_GET = array(); + +// A site that already has a key has already done this. +sendbeam_on_activate(); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_alreadysetupkey' ) ); +ok( '' === sb_wizard_redirect(), 'wizard: a site that already has a key is not walked through setup' ); +update_option( 'sendbeam_settings', array() ); + +// A site that has been through it, or walked out of it, is not sent back. +sendbeam_on_activate(); +update_option( 'sendbeam_setup_done', 1 ); +ok( '' === sb_wizard_redirect(), 'wizard: a site that has finished setup is not sent back' ); +delete_option( 'sendbeam_setup_done' ); + +// And a host that never wants it can say so. +sendbeam_on_activate(); +add_filter( 'sendbeam_setup_wizard', '__return_false' ); +ok( '' === sb_wizard_redirect(), 'wizard: the sendbeam_setup_wizard filter switches the redirect off' ); +add_filter( 'sendbeam_setup_wizard', '__return_true' ); + +// ── The four steps ────────────────────────────────────────────────────── +$GLOBALS['stub']['remote_reply'] = array( + 'response' => array( 'code' => 200 ), + 'body' => wp_json_encode( array( 'forms' => array() ) ), +); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_wizardkeywizardkey' ) ); +sendbeam_flush_cache(); + +$sendbeam_wizard_headings = array( + 1 => 'Connect your SendBeam account', + 2 => 'Verify the domain your email is sent from', + 3 => 'Send this site's email through SendBeam', + 4 => 'Put a form on the site', +); +foreach ( $sendbeam_wizard_headings as $sendbeam_n => $sendbeam_heading ) { + $_GET = array( 'page' => 'sendbeam-setup', 'step' => (string) $sendbeam_n ); + ob_start(); + sendbeam_render_admin_page(); + $html = ob_get_clean(); + has( $html, $sendbeam_heading, "wizard: step $sendbeam_n renders its own heading" ); + has( $html, 'Step ' . $sendbeam_n . ' of 4', "wizard: step $sendbeam_n says which step it is" ); + has( $html, 'sb-rail', "wizard: step $sendbeam_n shows the progress rail" ); + has( $html, 'Go back to the Dashboard', "wizard: step $sendbeam_n offers the way out" ); + has( $html, 'name="step" value="' . $sendbeam_n . '"', "wizard: step $sendbeam_n posts its own number" ); + if ( $sendbeam_n < 4 ) { + has( $html, 'Skip this step', "wizard: step $sendbeam_n can be skipped" ); + has( $html, '>Continue<', "wizard: step $sendbeam_n moves on" ); + } else { + has( $html, '>Finish<', 'wizard: the last step finishes rather than continuing' ); + lacks( $html, 'Skip this step', 'wizard: there is nothing left to skip on the last step' ); + } +} + +// The rail marks what is behind you and what you are standing on. +$_GET = array( 'page' => 'sendbeam-setup', 'step' => '3' ); +ob_start(); +sendbeam_render_admin_page(); +$html = ob_get_clean(); +has( $html, 'sb-rail__step is-done', 'wizard: a finished step is marked done on the rail' ); +has( $html, 'sb-rail__step is-current" aria-current="step"', 'wizard: the step you are on is marked current' ); + +// The steps reuse the panels the settings screens use, rather than a second +// copy of the Connect button and a second copy of the records table. +update_option( 'sendbeam_settings', array() ); +sendbeam_flush_cache(); +$_GET = array( 'page' => 'sendbeam-setup', 'step' => '1' ); +ob_start(); +sendbeam_render_admin_page(); +$html = ob_get_clean(); +has( $html, 'id="sendbeam-connect"', 'wizard: step 1 is the Connect panel itself, not a copy of it' ); +has( $html, 'Connect SendBeam', 'wizard: step 1 offers the one Connect button this plugin has' ); + +$_GET = array( 'page' => 'sendbeam-setup', 'step' => '2' ); +ob_start(); +sendbeam_render_admin_page(); +$html = ob_get_clean(); +has( $html, 'This step needs a connected site', 'wizard: a step that cannot run yet says why, rather than rendering an empty panel' ); + +// ── Skip, continue, finish, leave ─────────────────────────────────────── +delete_option( 'sendbeam_setup_done' ); +delete_user_meta( 7, SENDBEAM_WIZARD_STEP ); + +/** Post the wizard's footer form and say where it sent us. */ +function sb_wizard_post( $step, $go ) { + $_POST = array( 'step' => (string) $step, 'go' => $go, '_wpnonce' => 'nonce:sendbeam_wizard_step' ); + $_REQUEST = $_POST; + unset( $GLOBALS['stub']['redirect'] ); + try { + sendbeam_handle_wizard_step(); + } catch ( SendBeamStubExit $e ) { + unset( $e ); + } + $_POST = array(); + $_REQUEST = array(); + return isset( $GLOBALS['stub']['redirect'] ) ? $GLOBALS['stub']['redirect']['url'] : ''; +} + +has( sb_wizard_post( 1, 'next' ), 'page=sendbeam-setup&step=2', 'wizard: Skip advances to the next step' ); +ok( 2 === (int) get_user_meta( 7, SENDBEAM_WIZARD_STEP, true ), 'wizard: and the step is remembered' ); +ok( 2 === sendbeam_wizard_current_step(), 'wizard: coming back with no step in the URL resumes where you were' ); +has( sb_wizard_post( 2, 'next' ), 'step=3', 'wizard: and again' ); +has( sb_wizard_post( 4, 'finish' ), 'page=sendbeam', 'wizard: finishing lands on the Overview' ); +ok( sendbeam_wizard_done(), 'wizard: finishing marks the site set up' ); +ok( '' === get_user_meta( 7, SENDBEAM_WIZARD_STEP, true ), 'wizard: and stops remembering a half-finished run' ); + +delete_option( 'sendbeam_setup_done' ); +$sendbeam_left = sb_wizard_post( 3, 'exit' ); +ok( 'https://www.example-site.test/wp-admin/' === $sendbeam_left, 'wizard: leaving goes to the Dashboard' ); +ok( ! sendbeam_wizard_done(), 'wizard: leaving is not finishing' ); +ok( 3 === (int) get_user_meta( 7, SENDBEAM_WIZARD_STEP, true ), 'wizard: leaving keeps your place, so the Overview link picks it up' ); + +// A step number nobody registered cannot render a step that is not there. +$_GET = array( 'step' => '99' ); +ok( 3 === sendbeam_wizard_current_step(), 'wizard: an out-of-range step falls back to where you were' ); +$_GET = array( 'step' => '0' ); +ok( 3 === sendbeam_wizard_current_step(), 'wizard: and so does a nonsense one' ); +$_GET = array(); + +// Without the nonce, nothing moves. +$_POST = array( 'step' => '1', 'go' => 'finish' ); +$_REQUEST = $_POST; +delete_option( 'sendbeam_setup_done' ); +$threw = false; +try { + sendbeam_handle_wizard_step(); +} catch ( SendBeamStubExit $e ) { + $threw = true; +} +ok( $threw, 'wizard: a step posted without a nonce is refused' ); +ok( ! sendbeam_wizard_done(), 'wizard: and nothing was marked finished' ); +$_POST = array(); +$_REQUEST = array(); + +delete_user_meta( 7, SENDBEAM_WIZARD_STEP ); +delete_option( 'sendbeam_setup_done' ); +update_option( 'sendbeam_settings', array() ); +$GLOBALS['stub']['remote_reply'] = null; +sendbeam_flush_cache(); + // wp-config constant wins over the option. define( 'SENDBEAM_API_KEY', 'sb_const_0123456789abcdef' ); ok( sendbeam_api_key() === 'sb_const_0123456789abcdef', 'constant wins' ); @@ -2181,7 +2354,7 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { ob_start(); sendbeam_render_admin_page(); $sendbeam_html = ob_get_clean(); - has( $sendbeam_html, 'class="wrap sendbeam-app"', "render: $sendbeam_slug sits in a .wrap" ); + has( $sendbeam_html, 'class="wrap sendbeam-app', "render: $sendbeam_slug sits in a .wrap" ); has( $sendbeam_html, 'class="screen-reader-text"', "render: $sendbeam_slug has a real h1 for screen readers" ); has( $sendbeam_html, 'sb-head', "render: $sendbeam_slug carries the header band" ); ok( strlen( $sendbeam_html ) > 800, "render: $sendbeam_slug renders a screenful, not an empty shell" ); @@ -2408,6 +2581,23 @@ function sb_render_table( $table ) { sendbeam_flush_cache(); $GLOBALS['stub']['remote_reply'] = null; +/* + * A site whose key is pinned in wp-config.php has already been set up by + * whoever pinned it. This runs down here because the constant, once defined, + * cannot be undefined — which is exactly why the wizard has to cope with it. + */ +$GLOBALS['stub']['transients'] = array(); +delete_option( 'sendbeam_setup_done' ); +sendbeam_on_activate(); +unset( $GLOBALS['stub']['redirect'] ); +try { + sendbeam_maybe_redirect_to_wizard(); +} catch ( SendBeamStubExit $e ) { + unset( $e ); +} +ok( ! isset( $GLOBALS['stub']['redirect'] ), 'wizard: a site whose key is pinned in wp-config.php is not walked through setup' ); +delete_option( 'sendbeam_setup_done' ); + // One version number, five files. 1.6.2 shipped with the block's asset // version still on 1.6.1, which is how WordPress decides whether the editor // may reuse a cached copy of the block script. diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 9512782..7953b27 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -94,7 +94,12 @@ function add_query_arg( ...$a ) { foreach ( $query as $k => $v ) { $pairs[] = $k . '=' . $v; } return $parts[0] . ( $pairs ? '?' . implode( '&', $pairs ) : '' ); } -function get_user_meta( $user_id, $key = '', $single = false ) { return $single ? '' : array(); } +function get_user_meta( $user_id, $key = '', $single = false ) { + $all = isset( $GLOBALS['stub']['usermeta'][ $user_id ] ) ? $GLOBALS['stub']['usermeta'][ $user_id ] : array(); + if ( '' === $key ) { return $all; } + if ( ! isset( $all[ $key ] ) ) { return $single ? '' : array(); } + return $single ? $all[ $key ] : array( $all[ $key ] ); +} /** * Transients. The admin API client caches through these, and the settings @@ -112,7 +117,7 @@ function wp_remote_get( $url, $args = array() ) { $r = isset( $GLOBALS['stub']['remote_reply'] ) ? $GLOBALS['stub']['remote_reply'] : array( 'response' => array( 'code' => 200 ), 'body' => '{}' ); return ( $r instanceof Closure ) ? $r( $url, $args ) : $r; } -function update_user_meta( $user_id, $key, $value ) { return true; } +function update_user_meta( $user_id, $key, $value ) { $GLOBALS['stub']['usermeta'][ $user_id ][ $key ] = $value; return true; } // ── Site email stubs ──────────────────────────────────────────────────── class WP_Error { @@ -423,3 +428,6 @@ protected function column_default( $item, $column ) { function wp_strip_all_tags( $string, $remove_breaks = false ) { return strip_tags( (string) $string ); } function add_screen_option( $option, $args = array() ) { $GLOBALS['stub']['screen_options'][ $option ] = $args; } +function delete_user_meta( $user_id, $key, $value = '' ) { unset( $GLOBALS['stub']['usermeta'][ $user_id ][ $key ] ); return true; } +function __return_false() { return false; } +function __return_true() { return true; } From 1b9e60037df7e0a2ee8b3372aaa21563d11f22ae Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 07:56:56 +0000 Subject: [PATCH 33/75] Say what is actually happening, where somebody is looking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four surfaces, each one copied from the plugin that does it best. The sending domain is a core widefat table of Type, Host and Value, with read-only fields that copy when you click them, numbered steps either side, a per-record verdict and one of three states — verified, pending, not found. "Pending" and "not found" looked identical before, and only one of them has work left in it. The test email sends a real HTML message a site owner can keep: the From name and address used, the sending domain and whether it is verified, the workspace, the version and the time, and what this changes. Its result replaces the form in the page rather than becoming a notice — a failure gets what went wrong, what it means, what to do, and a block of detail captured at the moment it failed that copies in one click. The key is never in it. Site Health gains three tests. The one worth having is site email switched on behind a domain nothing has verified: that is a site quietly sending its password resets from an address no mailbox provider will trust, and it now reports as critical. Every message the plugin prints moved out of the middle of each screen and into core's notice component, on SendBeam's screens only. The one exception is the setup notice, which sits on the Dashboard, opens the wizard, and goes for good when it is dismissed or the site is set up. The old Docs tab becomes a Help page: documentation, a system status block that copies for support, who to ask, the shortcodes and the permissions table. --- includes/admin-ui.php | 34 +++ includes/bridges.php | 2 +- includes/mail.php | 323 +++++++++++++++++++++++-- includes/notices.php | 146 ++++++++++++ includes/onboarding.php | 45 ++-- includes/screens.php | 494 ++++++++++++++++++++++++++------------- includes/settings.php | 18 ++ includes/site-health.php | 400 +++++++++++++++++++++++++++++++ includes/sync.php | 2 +- sendbeam.php | 2 + tests/smoke.php | 308 ++++++++++++++++++++++++ tests/wp-stubs.php | 11 +- 12 files changed, 1580 insertions(+), 205 deletions(-) create mode 100644 includes/notices.php create mode 100644 includes/site-health.php diff --git a/includes/admin-ui.php b/includes/admin-ui.php index a3251a3..62c7a99 100644 --- a/includes/admin-ui.php +++ b/includes/admin-ui.php @@ -112,6 +112,40 @@ function sendbeam_render_tabs( $tabs, $current, $slug, $label ) { echo ''; } +/** + * One admin notice, in core's own markup. + * + * `wp_admin_notice()` arrived in WordPress 6.4 and this plugin supports 6.1, + * so the fallback is not decoration: it is what a third of sites would see. + * Both paths emit the same classes, because the point of using core's notice + * is that it looks and behaves like every other notice on the screen — + * including being dismissible by core's own script. + * + * @param string $message The sentence. Already-escaped HTML. + * @param string $type info, success, warning or error. + * @param bool $dismissible Whether core's dismiss button is offered. + */ +function sendbeam_notice( $message, $type = 'info', $dismissible = true ) { + $args = array( + 'type' => $type, + 'dismissible' => $dismissible, + 'additional_classes' => array( 'sendbeam-notice' ), + 'paragraph_wrap' => true, + ); + + if ( function_exists( 'wp_admin_notice' ) ) { + wp_admin_notice( $message, $args ); + return; + } + + printf( + '

    %3$s

    ', + esc_attr( $type ), + $dismissible ? ' is-dismissible' : '', + wp_kses_post( $message ) + ); +} + /** * Open a card. * diff --git a/includes/bridges.php b/includes/bridges.php index 3653a2e..39620f0 100644 --- a/includes/bridges.php +++ b/includes/bridges.php @@ -315,7 +315,7 @@ function sendbeam_bridge_settings() { add_action( 'admin_post_sendbeam_save_bridges', 'sendbeam_handle_save_bridges' ); -/** Save the Fluent Forms settings from the Audience tab. */ +/** Save the Fluent Forms settings from the Audience screen. */ function sendbeam_handle_save_bridges() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); diff --git a/includes/mail.php b/includes/mail.php index 5bb4f3c..9dc4c67 100644 --- a/includes/mail.php +++ b/includes/mail.php @@ -296,6 +296,182 @@ function sendbeam_pre_wp_mail( $short_circuit, $atts ) { return false; } +/** + * What the site owner should know about the connection, at the moment of asking. + * + * Gathered once and used twice: it is the body of the test email, and — when + * the send fails — the bundle the failure card offers to copy. Collecting it + * at failure time rather than at render time is the whole point: a support + * request that describes the state of the site half an hour later describes a + * different site. + * + * @return array + */ +function sendbeam_mail_facts() { + $settings = sendbeam_settings(); + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + $domain = $status['domain']; + + $domain_line = __( 'None set up', 'sendbeam' ); + if ( '' !== $domain['name'] ) { + $domain_line = $domain['name'] . ' — ' . ( $domain['verified'] ? __( 'verified', 'sendbeam' ) : __( 'not verified yet', 'sendbeam' ) ); + } elseif ( '' !== (string) $status['domain_state'] ) { + $domain_line = sprintf( + /* translators: %s: a SendBeam domain state, e.g. not_granted */ + __( 'None set up (%s)', 'sendbeam' ), + (string) $status['domain_state'] + ); + } + + $from_email = '' !== (string) $settings['mail_from_email'] ? (string) $settings['mail_from_email'] : (string) $status['sender']['from_email']; + $from_name = '' !== (string) $settings['mail_from_name'] ? (string) $settings['mail_from_name'] : (string) $status['sender']['from_name']; + + return array( + __( 'Site', 'sendbeam' ) => get_bloginfo( 'name' ) . ' — ' . home_url(), + __( 'From name', 'sendbeam' ) => '' !== $from_name ? $from_name : __( 'the workspace sender', 'sendbeam' ), + __( 'From address', 'sendbeam' ) => '' !== $from_email ? $from_email : __( 'the workspace sender', 'sendbeam' ), + __( 'Sending domain', 'sendbeam' ) => $domain_line, + __( 'Workspace', 'sendbeam' ) => '' !== (string) $status['workspace']['name'] ? (string) $status['workspace']['name'] : __( 'not reported', 'sendbeam' ), + __( 'Sent', 'sendbeam' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ), + __( 'Plugin', 'sendbeam' ) => 'SendBeam ' . SENDBEAM_VERSION, + ); +} + +/** + * The test email itself: one screenful a site owner can keep. + * + * Table-based and inline-styled, because that is still the only HTML an email + * client can be relied on to render, and with a plain-text alternative that + * says the same things — a test email that only exists as HTML proves less + * than one that proves both halves arrived. + * + * No images: the three-square mark is three table cells with a background + * colour, which needs no remote request, survives an image-blocking client + * and cannot be used to tell whether the message was opened. + * + * @param array $facts Rows from sendbeam_mail_facts(). + * @return string + */ +function sendbeam_test_mail_html( $facts ) { + $body = 'margin:0;padding:0;background:#EDEBE6;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:#121212;'; + $cell = 'padding:24px 28px;'; + + $rows = ''; + foreach ( $facts as $label => $value ) { + $rows .= '' + . '' . esc_html( $label ) . '' + . '' . esc_html( $value ) . '' + . ''; + } + + $log_url = sendbeam_page_url( 'sendbeam-mail' ); + + $html = '' + . '' + . '' . esc_html__( 'SendBeam test email', 'sendbeam' ) . '' + . '' + . '' + . '
    ' + . '' + + // The mark, on the ink band, as three coloured cells. + . '' + + // The verdict. + . '' + + // The facts. + . '' + + // What happens now. + . '' + + . '
    '; + + return $html; +} + +/** + * The same thing in words, for a client that will not render the HTML. + * + * @param array $facts Rows from sendbeam_mail_facts(). + * @return string + */ +function sendbeam_test_mail_text( $facts ) { + $lines = array( + __( 'Your site can send email through SendBeam', 'sendbeam' ), + '', + __( 'This message was sent by your WordPress site, through SendBeam, using the settings below. Nothing else needs doing.', 'sendbeam' ), + '', + ); + foreach ( $facts as $label => $value ) { + $lines[] = $label . ': ' . $value; + } + $lines[] = ''; + $lines[] = __( 'What happens now', 'sendbeam' ); + $lines[] = __( 'Every email this site already sends goes out this way from now on: order confirmations, password resets, and comment and form notifications.', 'sendbeam' ); + $lines[] = __( 'Each one is recorded in the email log in wp-admin, with whether it was sent, fell back to the server\'s own mailer, or failed.', 'sendbeam' ); + $lines[] = ''; + $lines[] = __( 'Open the email log:', 'sendbeam' ) . ' ' . sendbeam_page_url( 'sendbeam-mail' ); + + return implode( "\n", $lines ); +} + +/** + * Everything somebody would be asked for in a support reply, in one block. + * + * Captured at the moment of failure, with the raw error, so that the person + * pasting it into an email is describing the send that went wrong rather than + * the state of the site whenever they got round to writing. + * + * @param string $error The raw error from the API. + * @param int $status HTTP status, or 0 when the request never landed. + * @return string + */ +function sendbeam_mail_error_bundle( $error, $status = 0 ) { + $lines = array( + 'SendBeam ' . SENDBEAM_VERSION, + 'WordPress ' . get_bloginfo( 'version' ), + 'PHP ' . PHP_VERSION, + 'Site: ' . home_url(), + 'Key: ' . ( '' === sendbeam_api_key() ? 'none' : ( sendbeam_key_in_config() ? 'wp-config.php constant' : 'stored in options' ) ), + ); + foreach ( sendbeam_mail_facts() as $label => $value ) { + $lines[] = $label . ': ' . $value; + } + $lines[] = 'HTTP: ' . ( $status ? (int) $status : 'no response' ); + $lines[] = 'Error: ' . $error; + + return implode( "\n", $lines ); +} + /** * "Send a test email" on the settings page. */ @@ -304,30 +480,141 @@ function sendbeam_handle_test_mail() { wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) ); } check_admin_referer( 'sendbeam_test_mail' ); - $user = wp_get_current_user(); - $ok = false; + + $user = wp_get_current_user(); + $to = (string) $user->user_email; + $facts = sendbeam_mail_facts(); + if ( ! sendbeam_mail_enabled() ) { - $note = __( 'Turn on "Send this site\'s email through SendBeam" and save an API key first.', 'sendbeam' ); - } else { - $result = sendbeam_api_send( + $outcome = array( + 'ok' => false, + 'title' => __( 'Site email is not switched on yet', 'sendbeam' ), + 'means' => __( 'Nothing was sent, because this site is still handing its email to the web server\'s own mailer.', 'sendbeam' ), + 'do' => __( 'Tick "Send this site\'s email through SendBeam" above, save, and try again. It needs a working API key with the "Send site email" permission.', 'sendbeam' ), + 'to' => $to, + 'bundle' => sendbeam_mail_error_bundle( 'site email is switched off', 0 ), + 'at' => time(), + ); + sendbeam_finish_test_mail( $outcome ); + } + + $result = sendbeam_api_send( + array( + 'to' => $to, + 'subject' => sprintf( /* translators: %s: site name */ __( 'Test email from %s via SendBeam', 'sendbeam' ), get_bloginfo( 'name' ) ), + 'html' => sendbeam_test_mail_html( $facts ), + 'text' => sendbeam_test_mail_text( $facts ), + ) + ); + + sendbeam_mail_log( $to, __( 'Test email', 'sendbeam' ), $result['ok'] ? 'sent' : 'failed', $result['ok'] ? '' : $result['error'] ); + + if ( $result['ok'] ) { + sendbeam_finish_test_mail( array( - 'to' => $user->user_email, - 'subject' => sprintf( /* translators: %s: site name */ __( 'Test email from %s via SendBeam', 'sendbeam' ), get_bloginfo( 'name' ) ), - 'text' => __( "This is a test email from your WordPress site, sent through SendBeam.\n\nIf you can read this, order confirmations, password resets and every other email this site sends will go out the same way.", 'sendbeam' ), + 'ok' => true, + 'to' => $to, + 'at' => time(), ) ); - $ok = $result['ok']; - $note = $ok ? sprintf( /* translators: %s: email address */ __( 'Sent to %s.', 'sendbeam' ), $user->user_email ) : $result['error']; - sendbeam_mail_log( $user->user_email, 'Test email', $ok ? 'sent' : 'failed', $ok ? '' : $result['error'] ); } - wp_safe_redirect( - add_query_arg( - array( - 'sendbeam_test' => $ok ? 'ok' : 'error', - 'sendbeam_note' => rawurlencode( $note ), - ), - sendbeam_tab_url( 'mail' ) + + sendbeam_finish_test_mail( + array( + 'ok' => false, + 'title' => __( 'SendBeam would not send that message', 'sendbeam' ), + 'means' => sendbeam_test_mail_means( $result ), + 'do' => sendbeam_test_mail_advice( $result ), + 'to' => $to, + 'error' => $result['error'], + 'status' => (int) $result['status'], + // Captured now, with the answer still in hand: half an hour later + // this site may be in a different state entirely. + 'bundle' => sendbeam_mail_error_bundle( $result['error'], (int) $result['status'] ), + 'at' => time(), ) ); +} + +/** + * What a refusal means, in the site owner's terms rather than the API's. + * + * @param array $result From sendbeam_api_send(). + * @return string + */ +function sendbeam_test_mail_means( $result ) { + $status = (int) $result['status']; + if ( 0 === $status ) { + return __( 'This server could not reach sendbeam.io at all, so SendBeam never saw the message.', 'sendbeam' ); + } + if ( 401 === $status ) { + return __( 'SendBeam did not accept this site\'s API key.', 'sendbeam' ); + } + if ( 403 === $status ) { + return __( 'The key works, but it was not given permission to send this site\'s email, or the From address is not on a verified domain.', 'sendbeam' ); + } + if ( 429 === $status ) { + return __( 'SendBeam is rate-limiting this site, or the workspace has reached its sending limit.', 'sendbeam' ); + } + if ( $status >= 500 ) { + return __( 'SendBeam accepted the request and then failed on it. That is an error at SendBeam\'s end, not at yours.', 'sendbeam' ); + } + return __( 'SendBeam refused the message. The reason it gave is below.', 'sendbeam' ); +} + +/** + * What to do about it. + * + * @param array $result From sendbeam_api_send(). + * @return string + */ +function sendbeam_test_mail_advice( $result ) { + $status = (int) $result['status']; + if ( 0 === $status ) { + return __( 'Check that this server can make outbound HTTPS requests. A firewall, a proxy or a host that blocks outbound traffic will stop this and nothing else on the site will look wrong.', 'sendbeam' ); + } + if ( 401 === $status ) { + return __( 'Reconnect this site under Settings → Connection, or paste a fresh key under Settings → Advanced.', 'sendbeam' ); + } + if ( 403 === $status ) { + return __( 'Check the sending domain is verified under Settings → Sending domain, and that the From address above is on it. If the key is missing the permission, reconnect and tick "Send the site\'s own email".', 'sendbeam' ); + } + if ( 429 === $status ) { + return __( 'Wait a few minutes and try again. If it keeps happening, check the workspace\'s plan and usage in SendBeam.', 'sendbeam' ); + } + if ( $status >= 500 ) { + return __( 'Try again in a few minutes. If it persists, send the details below to hello@sendbeam.io.', 'sendbeam' ); + } + return __( 'Copy the details below and send them to hello@sendbeam.io — they say exactly what this site asked for and what came back.', 'sendbeam' ); +} + +/** + * Park the result where the screen can render it, and go back there. + * + * A transient rather than a query argument, because the failure card carries a + * raw error, a version list and a domain state — none of which belongs in an + * address bar, a server log or somebody's browser history. It is keyed to the + * person who pressed the button and read exactly once. + * + * @param array $outcome What happened. + */ +function sendbeam_finish_test_mail( $outcome ) { + set_transient( 'sendbeam_test_result_' . get_current_user_id(), $outcome, 5 * MINUTE_IN_SECONDS ); + wp_safe_redirect( sendbeam_tab_url( 'mail' ) . '#sendbeam-test' ); exit; } + +/** + * The result of the last test send, once. + * + * @return array|null + */ +function sendbeam_take_test_result() { + $key = 'sendbeam_test_result_' . get_current_user_id(); + $result = get_transient( $key ); + if ( ! is_array( $result ) ) { + return null; + } + delete_transient( $key ); + return $result; +} diff --git a/includes/notices.php b/includes/notices.php new file mode 100644 index 0000000..3b7ebdb --- /dev/null +++ b/includes/notices.php @@ -0,0 +1,146 @@ +` band somewhere in + * the middle of its own markup, which meant the answer to "did that save?" + * appeared in a different place on every screen and in the plugin's own + * styling rather than WordPress's. They are all admin notices now, in core's + * markup, above the page — which is where a person who has just pressed a + * button is looking. + * + * Two rules, both from what other plugins get wrong: + * + * - They appear only on SendBeam's own screens. The one exception is the + * setup notice, which has to be somewhere a new site owner will see it, + * and which goes away for good the first time it is dismissed. + * - Every one of them is dismissible. A notice that cannot be closed is the + * single most complained-about thing a WordPress plugin does. + * + * @package SendBeam + */ + +defined( 'ABSPATH' ) || exit; + +add_action( 'admin_notices', 'sendbeam_admin_notices' ); + +/** + * The sentence behind each query argument a handler redirects with. + * + * Every one of these arrives on a redirect this plugin issued itself, so the + * only thing read out of the URL is which of a fixed list of sentences to + * print. Nothing from the address bar is ever echoed. + * + * @return array> + */ +function sendbeam_notice_messages() { + return array( + 'sendbeam_domain' => array( + 'verified' => array( 'success', __( 'Verified. SendBeam can now send email as your domain.', 'sendbeam' ) ), + 'verified_mail' => array( 'success', __( 'Verified, and this site\'s email has been switched on — it was waiting on exactly this. Send yourself a test below.', 'sendbeam' ) ), + 'pending' => array( 'warning', __( 'Not verified yet. DNS changes can take anything from a few minutes to a day to spread; the records are below, unchanged.', 'sendbeam' ) ), + 'nodomain' => array( 'warning', __( 'There is no sending domain on this workspace yet. Add one under Sending in SendBeam.', 'sendbeam' ) ), + 'unreachable' => array( 'error', __( 'Could not ask SendBeam to check just now. Nothing was changed.', 'sendbeam' ) ), + ), + 'sendbeam_form' => array( + 'placed' => array( 'success', __( 'Noted — the form step is ticked. Say so again if you take the form off the site.', 'sendbeam' ) ), + 'unplaced' => array( 'success', __( 'The form step will look for itself again.', 'sendbeam' ) ), + ), + 'sendbeam_mail' => array( + 'on' => array( 'success', __( 'Site email is on. Password resets, receipts and notifications now go out through SendBeam.', 'sendbeam' ) ), + 'noscope' => array( 'error', __( 'This site\'s key was not given permission to send your site\'s email, so it was not switched on. Reconnect and tick that box.', 'sendbeam' ) ), + 'unverified' => array( 'error', __( 'The sending domain is not verified, so site email was not switched on. Finish step 2 first.', 'sendbeam' ) ), + ), + 'sendbeam_disconnected' => array( + 'ok' => array( 'success', __( 'Disconnected. The key was revoked in SendBeam.', 'sendbeam' ) ), + 'unreachable' => array( 'warning', __( 'Disconnected, but this server could not reach SendBeam; revoke it under Settings → API keys.', 'sendbeam' ) ), + 'constant' => array( 'warning', __( 'Disconnected here, and nothing was revoked: this site sends with the key defined as SENDBEAM_API_KEY in wp-config.php, which is not the one this button issued. Remove it there, and revoke it under Settings → API keys.', 'sendbeam' ) ), + ), + 'sendbeam_sync_saved' => array( + '1' => array( 'success', __( 'Saved. The opt-in box is live where you asked for it.', 'sendbeam' ) ), + ), + 'sendbeam_bridges_saved' => array( + '1' => array( 'success', __( 'Saved. Those forms now send their submissions to SendBeam.', 'sendbeam' ) ), + ), + 'sendbeam_ecommerce_saved' => array( + '1' => array( 'success', __( 'Saved. The events you ticked will reach SendBeam from now on.', 'sendbeam' ) ), + ), + ); +} + +/** + * Print whatever the last button did. + */ +function sendbeam_admin_notices() { + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + if ( ! sendbeam_is_our_screen() ) { + sendbeam_setup_notice(); + return; + } + + sendbeam_dns_return_notice(); + + foreach ( sendbeam_notice_messages() as $arg => $values ) { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- chooses one of a fixed list of sentences; set by this plugin's own redirect. + $value = isset( $_GET[ $arg ] ) ? sanitize_key( wp_unslash( $_GET[ $arg ] ) ) : ''; + if ( '' === $value || ! isset( $values[ $value ] ) ) { + continue; + } + sendbeam_notice( esc_html( $values[ $value ][1] ), $values[ $value ][0] ); + } + + // Pop-ups report a count, so they cannot come out of a fixed table. + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a number this plugin put on its own redirect. + if ( isset( $_GET['sendbeam_saved'] ) ) { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- as above. + $saved = max( 0, (int) $_GET['sendbeam_saved'] ); + sendbeam_notice( + esc_html( sprintf( /* translators: %d: number of pop-ups */ _n( '%d pop-up saved.', '%d pop-ups saved.', $saved, 'sendbeam' ), $saved ) ), + 'success' + ); + } + + if ( ! empty( $GLOBALS['sendbeam_deleted'] ) ) { + $gone = (int) $GLOBALS['sendbeam_deleted']; + sendbeam_notice( + esc_html( sprintf( /* translators: %d: number of log rows */ _n( '%d message removed from the log.', '%d messages removed from the log.', $gone, 'sendbeam' ), $gone ) ), + 'success' + ); + } +} + +/** + * Back from the registrar, and how it went. + * + * Not in the table above because the failure carries SendBeam's own reason + * code, and the table is fixed sentences. + */ +function sendbeam_dns_return_notice() { + $returned = sendbeam_overview_dns_return(); + if ( 'done' === $returned ) { + // Past tense on purpose: the check runs as this screen renders, so by + // the time anybody reads this the step underneath is already showing + // what it found. "Checking now…" promised a page that was about to + // change and then never changed. + sendbeam_notice( esc_html__( 'Your registrar added the records. Checked just now.', 'sendbeam' ), 'success' ); + return; + } + if ( 'error' !== $returned ) { + return; + } + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- SendBeam's own reason code, sanitised to a key and printed as words. + $reason = isset( $_GET['sb_dc_reason'] ) ? sanitize_key( wp_unslash( $_GET['sb_dc_reason'] ) ) : ''; + sendbeam_notice( + esc_html( + sprintf( + /* translators: %s: SendBeam's reason the registrar refused, e.g. "state mismatch" */ + __( 'Your registrar could not add the records (%s). Add them by hand below.', 'sendbeam' ), + '' !== $reason ? str_replace( '_', ' ', substr( $reason, 0, 60 ) ) : __( 'no reason given', 'sendbeam' ) + ) + ), + 'error' + ); +} diff --git a/includes/onboarding.php b/includes/onboarding.php index dabcb33..f230eb9 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -20,7 +20,6 @@ register_activation_hook( SENDBEAM_FILE, 'sendbeam_on_activate' ); register_deactivation_hook( SENDBEAM_FILE, 'sendbeam_on_deactivate' ); -add_action( 'admin_notices', 'sendbeam_setup_notice' ); add_action( 'admin_post_sendbeam_dismiss_setup', 'sendbeam_dismiss_setup' ); add_action( 'admin_post_sendbeam_form_placed', 'sendbeam_handle_form_placed' ); @@ -442,39 +441,47 @@ function sendbeam_setup_steps() { } /** - * The one notice. + * The one notice, on the Dashboard, for a site that has not been set up. + * + * The Dashboard and nowhere else. A plugin that puts its own nag on every + * screen of every other plugin is the top one-star complaint in this whole + * category, and the activation redirect has already offered the wizard once + * to the person who installed this. + * + * It removes itself three ways: the site gets connected, the wizard is + * finished, or the person dismisses it — and the dismissal is per user, in + * user meta, so it stays dismissed. */ function sendbeam_setup_notice() { if ( ! current_user_can( 'manage_options' ) ) { return; } - if ( sendbeam_is_our_screen() ) { - return; // They are already here. + $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; + if ( ! $screen || 'dashboard' !== $screen->id ) { + return; } if ( get_user_meta( get_current_user_id(), 'sendbeam_setup_dismissed', true ) ) { return; } - if ( sendbeam_is_connected() ) { + if ( sendbeam_wizard_done() || sendbeam_is_connected() ) { return; // Resolved: the notice removes itself. } - $settings_url = sendbeam_page_url( 'sendbeam' ); - $dismiss_url = wp_nonce_url( admin_url( 'admin-post.php?action=sendbeam_dismiss_setup' ), 'sendbeam_dismiss_setup' ); - ?> -
    -

    - - -

    -

    - - -

    -
    - ' . esc_html__( 'SendBeam is installed.', 'sendbeam' ) . ' ' + . esc_html__( 'Connect your account in one click and the plugin will list your forms for you, so you never have to copy a key or an ID by hand.', 'sendbeam' ) + . '

    ' + . '' . esc_html__( 'Set up SendBeam', 'sendbeam' ) . ' ' + . '' . esc_html__( 'Not now', 'sendbeam' ) . ''; + + // Core button classes, deliberately: inside a core notice, a brand-styled + // button is the thing that looks out of place. + sendbeam_notice( $message, 'info' ); } /** diff --git a/includes/screens.php b/includes/screens.php index 30c8ea6..3c0f224 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -32,7 +32,7 @@ function sendbeam_form_close() { /* -------------------------------------------------------------- Overview */ /** - * Overview tab: how far through set-up the site is, what the workspace holds, and the API key. + * Overview: how far through set-up the site is, and what the workspace holds. */ function sendbeam_screen_overview() { $forms = sendbeam_remote_forms(); @@ -56,8 +56,6 @@ function sendbeam_screen_overview() { sendbeam_connect_finish_deferred( $status ); } - sendbeam_overview_notices(); - echo '

    '; sendbeam_card_open( __( 'Setup', 'sendbeam' ) ); @@ -98,79 +96,6 @@ function sendbeam_screen_overview() { echo '
    '; } -/** - * Whatever the last button did, said in one line at the top of the screen. - * - * Every one of these arrives as a query argument on a redirect this plugin - * issued itself, so the only thing read out of the URL is which of a fixed - * list of sentences to print. - */ -function sendbeam_overview_notices() { - // phpcs:disable WordPress.Security.NonceVerification.Recommended -- notice text only, chosen from a fixed list, set by our own redirect. - $domain = isset( $_GET['sendbeam_domain'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_domain'] ) ) : ''; - $mail = isset( $_GET['sendbeam_mail'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_mail'] ) ) : ''; - $placed = isset( $_GET['sendbeam_form'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_form'] ) ) : ''; - $gone = isset( $_GET['sendbeam_disconnected'] ) ? sanitize_key( wp_unslash( $_GET['sendbeam_disconnected'] ) ) : ''; - $reason = isset( $_GET['sb_dc_reason'] ) ? sanitize_key( wp_unslash( $_GET['sb_dc_reason'] ) ) : ''; - // phpcs:enable WordPress.Security.NonceVerification.Recommended - - // Back from the registrar. Not in the table below because the failure - // carries SendBeam's own reason code, and the table is fixed sentences. - $returned = sendbeam_overview_dns_return(); - if ( 'done' === $returned ) { - // Past tense on purpose: the check ran at the top of this render, so - // by the time anybody reads this the step underneath is already - // showing what it found. "Checking now…" promised a page that was - // about to change and then never changed. - echo '

    ' . esc_html__( 'Your registrar added the records. Checked just now.', 'sendbeam' ) . '

    '; - } elseif ( 'error' === $returned ) { - echo '

    ' . esc_html( - sprintf( - /* translators: %s: SendBeam's reason the registrar refused, e.g. "state mismatch" */ - __( 'Your registrar could not add the records (%s). Add them by hand below.', 'sendbeam' ), - '' !== $reason ? str_replace( '_', ' ', substr( $reason, 0, 60 ) ) : __( 'no reason given', 'sendbeam' ) - ) - ) . '

    '; - } - - $messages = array( - 'domain' => array( - 'verified' => array( 'ok', __( 'Verified. SendBeam can now send email as your domain.', 'sendbeam' ) ), - 'verified_mail' => array( 'ok', __( 'Verified, and this site\'s email has been switched on — it was waiting on exactly this. Send yourself a test below.', 'sendbeam' ) ), - 'pending' => array( 'warn', __( 'Not verified yet. DNS changes can take anything from a few minutes to a day to spread; the records are below, unchanged.', 'sendbeam' ) ), - 'nodomain' => array( 'warn', __( 'There is no sending domain on this workspace yet. Add one under Sending in SendBeam.', 'sendbeam' ) ), - 'unreachable' => array( 'bad', __( 'Could not ask SendBeam to check just now. Nothing was changed.', 'sendbeam' ) ), - ), - 'form' => array( - 'placed' => array( 'ok', __( 'Noted — the form step is ticked. Say so again if you take the form off the site.', 'sendbeam' ) ), - 'unplaced' => array( 'ok', __( 'The form step will look for itself again.', 'sendbeam' ) ), - ), - 'mail' => array( - 'on' => array( 'ok', __( 'Site email is on. Password resets, receipts and notifications now go out through SendBeam.', 'sendbeam' ) ), - 'noscope' => array( 'bad', __( 'This site\'s key was not given permission to send your site\'s email, so it was not switched on. Reconnect and tick that box.', 'sendbeam' ) ), - 'unverified' => array( 'bad', __( 'The sending domain is not verified, so site email was not switched on. Finish step 2 first.', 'sendbeam' ) ), - ), - 'gone' => array( - 'ok' => array( 'ok', __( 'Disconnected. The key was revoked in SendBeam.', 'sendbeam' ) ), - 'unreachable' => array( 'warn', __( 'Disconnected, but this server could not reach SendBeam; revoke it under Settings → API keys.', 'sendbeam' ) ), - 'constant' => array( 'warn', __( 'Disconnected here, and nothing was revoked: this site sends with the key defined as SENDBEAM_API_KEY in wp-config.php, which is not the one this button issued. Remove it there, and revoke it under Settings → API keys.', 'sendbeam' ) ), - ), - ); - - foreach ( array( - 'domain' => $domain, - 'form' => $placed, - 'mail' => $mail, - 'gone' => $gone, - ) as $group => $value ) { - if ( '' === $value || ! isset( $messages[ $group ][ $value ] ) ) { - continue; - } - list( $tone, $text ) = $messages[ $group ][ $value ]; - echo '

    ' . esc_html( $text ) . '

    '; - } -} - /** * Did this page load arrive back from the registrar, and how did it go? * @@ -273,11 +198,14 @@ function sendbeam_domain_panel( $status, $standalone = false ) { $state = sendbeam_connect_domain_state( $status ); /* - * No domain, so no records and nothing to check — the step's own sentence - * has already said why. What it cannot do is hand over the page where the - * owner fixes it, so that is all this panel is in that case. + * No domain, so no records and nothing to check. On the Overview the + * step's own sentence has already said why; standing on its own, the + * panel has to say it itself. */ if ( '' === $domain['name'] ) { + if ( $standalone ) { + echo '

    ' . esc_html( sendbeam_domain_sentence( '', false ) ) . '

    '; + } if ( in_array( $state, array( 'no_site', 'not_found', 'managed_host' ), true ) ) { echo '
    '; printf( @@ -292,23 +220,30 @@ function sendbeam_domain_panel( $status, $standalone = false ) { echo '
    '; - if ( $verified ) { - echo '

    '; - printf( - /* translators: %s: the sending domain */ - esc_html__( 'Verified — %s', 'sendbeam' ), - esc_html( $domain['name'] ) - ); - echo '

    '; + if ( $standalone ) { + echo '

    ' . esc_html__( 'Proving that this domain is yours is what lets SendBeam send as you. It is also what keeps the mail out of spam folders: a mailbox provider that can check who sent a message treats it very differently from one it cannot.', 'sendbeam' ) . '

    '; } + // The aggregate verdict, in the three states a site owner needs to tell + // apart: done, waiting for DNS, and nothing found at all. + sendbeam_domain_state_pill( $domain, $verified ); + if ( $domain['records'] ) { - if ( $verified ) { + $hidden = $verified; + if ( $hidden ) { echo '
    ' . esc_html__( 'The records SendBeam is using', 'sendbeam' ) . '
    '; + } else { + echo '
    1. '; + echo '

      ' . esc_html__( 'Add these records to the DNS for this domain, wherever you bought it. Every value copies when you click it.', 'sendbeam' ) . '

      '; } + sendbeam_domain_records_table( $domain['records'] ); - if ( $verified ) { + + if ( $hidden ) { echo '
    '; + } else { + echo '
  • '; + echo '

    ' . esc_html__( 'Then press Check now. DNS changes can take up to 24 hours to spread, so it is normal for the first check to find nothing.', 'sendbeam' ) . '

    '; } } elseif ( ! $verified ) { echo '

    ' . esc_html__( 'SendBeam has not sent the DNS records for this domain. Open Sending in SendBeam to see them.', 'sendbeam' ) . '

    '; @@ -319,7 +254,8 @@ function sendbeam_domain_panel( $status, $standalone = false ) { wp_nonce_field( 'sendbeam_domain_check' ); echo ''; printf( - '', + '', + esc_attr( $verified ? '' : ' sb-btn--primary' ), esc_html( $verified ? __( 'Check again', 'sendbeam' ) : __( 'Check now', 'sendbeam' ) ) ); echo ''; @@ -333,6 +269,10 @@ function sendbeam_domain_panel( $status, $standalone = false ) { } echo '
  • '; + if ( $domain['records'] && ! $verified ) { + echo ''; + } + if ( ! $verified && '' !== $domain['domain_connect_url'] ) { echo '

    ' . esc_html__( 'Your registrar supports one-click set-up: that button signs you in there and adds the records for you. It opens in a new tab.', 'sendbeam' ) . '

    '; } @@ -350,6 +290,61 @@ function sendbeam_domain_panel( $status, $standalone = false ) { echo '
    '; } +/** + * Where the domain has got to, in one line. + * + * Three states, because those are the three a site owner acts differently on: + * verified is finished, pending means the records are out there and DNS has + * not caught up, and not found means nothing has been added yet. "Pending" + * and "not found" look identical without something that says which — and the + * second one is the one where somebody still has work to do. + * + * @param array $domain The domain from the status body. + * @param bool $verified Whether SendBeam has seen the records. + */ +function sendbeam_domain_state_pill( $domain, $verified ) { + if ( $verified ) { + echo '

    '; + printf( + /* translators: %s: the sending domain */ + esc_html__( 'Verified — %s', 'sendbeam' ), + esc_html( $domain['name'] ) + ); + echo '

    '; + return; + } + + $found = 0; + foreach ( (array) $domain['records'] as $record ) { + if ( ! empty( $record['found'] ) ) { + ++$found; + } + } + + if ( $found > 0 ) { + echo '

    ' . esc_html__( 'Pending', 'sendbeam' ) . ' '; + echo esc_html( + sprintf( + /* translators: 1: records found, 2: records wanted, 3: the sending domain */ + __( '%1$d of %2$d records are live for %3$s. DNS changes can take up to 24 hours to spread.', 'sendbeam' ), + $found, + count( (array) $domain['records'] ), + $domain['name'] + ) + ) . '

    '; + return; + } + + echo '

    ' . esc_html__( 'Not found', 'sendbeam' ) . ' '; + echo esc_html( + sprintf( + /* translators: %s: the sending domain */ + __( 'Nothing has been found in the DNS for %s yet.', 'sendbeam' ), + $domain['name'] + ) + ) . '

    '; +} + /** * The DNS records, one row each, every value one click from the clipboard. * @@ -363,35 +358,55 @@ function sendbeam_domain_panel( $status, $standalone = false ) { * @param array $records Records. */ function sendbeam_domain_records_table( $records ) { - echo '
    '; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; + echo '
    ' . esc_html__( 'Type', 'sendbeam' ) . '' . esc_html__( 'Name', 'sendbeam' ) . '' . esc_html__( 'Value', 'sendbeam' ) . '' . esc_html__( 'Found', 'sendbeam' ) . '' . esc_html__( 'Copy', 'sendbeam' ) . '
    '; + echo ''; + echo ''; + echo ''; + echo ''; echo ''; - foreach ( $records as $record ) { + + foreach ( $records as $i => $record ) { + $host = '' !== $record['name'] ? $record['name'] : '@'; echo ''; echo ''; - echo ''; - echo ''; + /* translators: %s: a DNS record type, e.g. CNAME */ + $host_label = sprintf( __( 'Host for the %s record', 'sendbeam' ), $record['type'] ); + /* translators: %s: a DNS record type, e.g. CNAME */ + $value_label = sprintf( __( 'Value for the %s record', 'sendbeam' ), $record['type'] ); + echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- every value is escaped inside sendbeam_copy_field(). + echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- as above. echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped inside sendbeam_record_verdict(). - printf( - '', - esc_attr( $record['value'] ), - esc_attr__( 'Copied', 'sendbeam' ), - esc_attr( - sprintf( - /* translators: %s: a DNS record type, e.g. TXT */ - __( 'Copy the %s record value', 'sendbeam' ), - $record['type'] - ) - ), - esc_html__( 'Copy', 'sendbeam' ) - ); echo ''; } echo '
    ' . esc_html__( 'Type', 'sendbeam' ) . '' . esc_html__( 'Host', 'sendbeam' ) . '' . esc_html__( 'Value', 'sendbeam' ) . '' . esc_html__( 'Found', 'sendbeam' ) . '
    ' . esc_html( $record['type'] ) . '' . esc_html( '' !== $record['name'] ? $record['name'] : '@' ) . '' . esc_html( $record['value'] ) . '' . sendbeam_copy_field( $host, $host_label, 'sb-dns-host-' . (int) $i ) . '' . sendbeam_copy_field( $record['value'], $value_label, 'sb-dns-value-' . (int) $i ) . '' . sendbeam_record_verdict( isset( $record['found'] ) ? $record['found'] : null ) . '
    '; + echo '

    ' . esc_html__( 'Click any value to copy it. Your registrar may add the domain to the host for you — if it does, enter only the part shown here.', 'sendbeam' ) . '

    '; +} + +/** + * A value somebody has to retype into a registrar, made not-retypeable. + * + * A read-only input rather than a `` block: it selects on focus, it + * scrolls rather than wrapping a 200-character key across four lines, and it + * is reachable with a keyboard. Clicking it copies; the label says so, and + * the confirmation replaces the label rather than appearing somewhere else on + * the page. + * + * @param string $value The thing to copy. + * @param string $label What it is, for screen readers. + * @param string $id A unique id for the field. + * @return string Escaped HTML. + */ +function sendbeam_copy_field( $value, $label, $id ) { + return sprintf( + '' . + '', + esc_attr( $id ), + esc_html( $label ), + esc_attr( $value ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_attr__( 'Click to copy', 'sendbeam' ) + ); } /** @@ -524,7 +539,7 @@ function sendbeam_overview_mail_panel( $status, $connected ) { echo '

    ' . esc_html( sprintf( /* translators: %s: the From address site email will use */ - __( 'Email will be sent as %s. You can change that on the Site email tab.', 'sendbeam' ), + __( 'Email will be sent as %s. You can change that under Site email.', 'sendbeam' ), '' !== $status['sender']['from_email'] ? $status['sender']['from_email'] : __( 'your workspace sender', 'sendbeam' ) ) ) . '

    '; @@ -697,7 +712,7 @@ function sendbeam_stat( $label, $value ) { /* ----------------------------------------------------------------- Forms */ /** - * Forms tab: the default forms, how embedded forms look, and every form in the workspace. + * Forms: the default forms, how embedded forms look, and every form in the workspace. */ function sendbeam_screen_forms() { sendbeam_card_open( __( 'Defaults', 'sendbeam' ), __( 'Used when a block or shortcode does not name a form.', 'sendbeam' ) ); @@ -768,7 +783,7 @@ function sendbeam_screen_forms() { /* -------------------------------------------------------------- Audience */ /** - * Audience tab: the workspace's lists, and where to ask people to subscribe. + * Audience: the workspace's lists, and where to ask people to subscribe. */ function sendbeam_screen_audience() { $lists = sendbeam_lists(); @@ -800,11 +815,6 @@ function sendbeam_screen_form_plugins( $lists ) { echo '
    '; - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice only. - if ( isset( $_GET['sendbeam_bridges_saved'] ) ) { - echo '

    ' . esc_html__( 'Saved.', 'sendbeam' ) . '

    '; - } - sendbeam_card_open( __( 'Form plugins', 'sendbeam' ) ); echo '

    ' . esc_html__( 'Send the people who fill in forms built with another plugin to SendBeam. Each form is switched on where that plugin keeps its settings, and sends someone only when they ticked the consent field you name — or every submission, when you mark the form as a signup form.', 'sendbeam' ) . '

    '; @@ -913,17 +923,12 @@ function sendbeam_screen_fluentforms( $lists ) { function sendbeam_screen_sync( $lists ) { $sync = sendbeam_sync_settings(); - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice only. - if ( isset( $_GET['sendbeam_sync_saved'] ) ) { - echo '

    ' . esc_html__( 'Saved.', 'sendbeam' ) . '

    '; - } - sendbeam_card_open( __( 'Collect subscribers elsewhere on the site', 'sendbeam' ) ); echo '

    ' . esc_html__( 'Adds an opt-in tick box to things people already do here. Nobody is subscribed without ticking it, and the box is never pre-ticked.', 'sendbeam' ) . '

    '; if ( null === $lists || ! $lists ) { - echo '

    ' . esc_html__( 'This needs at least one list, read with a key that has the Lists (read) permission. Add one on the Overview tab.', 'sendbeam' ) . '

    '; + echo '

    ' . esc_html__( 'This needs at least one list, read with a key that has the Lists (read) permission. Connect this site under Settings, or add one in SendBeam.', 'sendbeam' ) . '

    '; sendbeam_card_close(); return; } @@ -1002,15 +1007,6 @@ function sendbeam_screen_sync( $lists ) { function sendbeam_screen_popup() { $rules = sendbeam_popups(); - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice text only. - if ( isset( $_GET['sendbeam_saved'] ) ) { - // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $n = (int) $_GET['sendbeam_saved']; - echo '

    ' . esc_html( - sprintf( /* translators: %d: number of pop-ups */ _n( '%d pop-up saved.', '%d pop-ups saved.', $n, 'sendbeam' ), $n ) - ) . '

    '; - } - sendbeam_card_open( __( 'Pop-ups', 'sendbeam' ), __( 'First match wins, top to bottom.', 'sendbeam' ) ); echo '

    ' . esc_html__( 'Add as many as you like and target each one. Only the first rule that matches a page opens by itself, so two pop-ups can never fight over the same visitor.', 'sendbeam' ) . '

    '; @@ -1182,7 +1178,7 @@ function sendbeam_popup_row( $i, $rule ) { /* ------------------------------------------------------------ Site email */ /** - * Site email tab: the wp_mail() relay, a test send, and what recently went out. + * Site email: the wp_mail() relay, a test send, and the log of what went out. */ function sendbeam_screen_mail() { sendbeam_card_open( __( 'Site email', 'sendbeam' ) ); @@ -1191,24 +1187,7 @@ function sendbeam_screen_mail() { sendbeam_form_close(); sendbeam_card_close(); - sendbeam_card_open( __( 'Test', 'sendbeam' ) ); - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice text only, set by our own redirect. - if ( isset( $_GET['sendbeam_test'] ) ) { - // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $ok = 'ok' === $_GET['sendbeam_test']; - // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $note = isset( $_GET['sendbeam_note'] ) ? rawurldecode( sanitize_text_field( wp_unslash( $_GET['sendbeam_note'] ) ) ) : ''; - echo '

    ' . esc_html( $note ) . '

    '; - } - ?> -
    - - -

    user_email ) ); ?>

    - -
    - '; + + if ( is_array( $result ) && ! empty( $result['ok'] ) ) { + sendbeam_test_mail_success( $result ); + echo '
    '; + sendbeam_card_close(); + return; + } + if ( is_array( $result ) ) { + sendbeam_test_mail_failure( $result ); + echo '
    '; + sendbeam_card_close(); + return; + } + + sendbeam_test_mail_form( __( 'Send a test email', 'sendbeam' ) ); + echo '
    '; + sendbeam_card_close(); +} + +/** + * The form: who it goes to, and one button. + * + * @param string $label Button text. + */ +function sendbeam_test_mail_form( $label ) { + $to = (string) wp_get_current_user()->user_email; + echo '
    '; + echo ''; + wp_nonce_field( 'sendbeam_test_mail' ); + echo '

    ' . esc_html__( 'Send to', 'sendbeam' ) . ''; + printf( + '

    ', + esc_attr( $to ) + ); + echo '

    ' . esc_html__( 'Your own WordPress address. Changing it here would prove something about a different inbox.', 'sendbeam' ) . '

    '; + printf( '

    ', esc_html( $label ) ); + echo '
    '; +} + +/** + * It worked. + * + * @param array $result From the handler. + */ +function sendbeam_test_mail_success( $result ) { + echo '
    '; + echo '

    ' . esc_html__( 'Sent', 'sendbeam' ) . '

    '; + echo '

    ' . esc_html( + sprintf( + /* translators: %s: email address */ + __( 'Sent to %s — open your inbox to see it.', 'sendbeam' ), + (string) $result['to'] + ) + ) . '

    '; + echo '

    ' . esc_html__( 'The message names the sending domain, the From address and the workspace it went through, so it is worth keeping. If it is not there in a minute, look in the spam folder — and then in the log below, which says whether SendBeam accepted it.', 'sendbeam' ) . '

    '; + echo '
    '; + sendbeam_test_mail_form( __( 'Send another', 'sendbeam' ) ); +} + +/** + * It did not. + * + * @param array $result From the handler. + */ +function sendbeam_test_mail_failure( $result ) { + echo '
    '; + echo '

    ' . esc_html( (string) $result['title'] ) . '

    '; + echo '

    ' . esc_html__( 'What it means', 'sendbeam' ) . '
    ' . esc_html( (string) $result['means'] ) . '

    '; + echo '

    ' . esc_html__( 'What to do', 'sendbeam' ) . '
    ' . esc_html( (string) $result['do'] ) . '

    '; + + if ( ! empty( $result['error'] ) ) { + echo '

    ' . esc_html( + sprintf( + /* translators: %s: the raw error SendBeam returned */ + __( 'SendBeam said: %s', 'sendbeam' ), + (string) $result['error'] + ) + ) . '

    '; + } + + if ( ! empty( $result['bundle'] ) ) { + echo '
    ' . esc_html__( 'Details for support', 'sendbeam' ) . ''; + echo '

    ' . esc_html__( 'Taken at the moment this send failed, so it describes that attempt and not this page.', 'sendbeam' ) . '

    '; + echo '
    ' . esc_html( (string) $result['bundle'] ) . '
    '; + printf( + '

    ', + esc_attr( (string) $result['bundle'] ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy these details', 'sendbeam' ) + ); + echo '
    '; + } + echo '
    '; + sendbeam_test_mail_form( __( 'Try again', 'sendbeam' ) ); +} + /** * A card whose body is the screen's list table. * @@ -1263,16 +1352,11 @@ function sendbeam_list_card( $title, $note, $search ) { /** * E-commerce events tab: the three toggles, the abandoned-cart window, and - * a log of recent attempts — the same shape as the Audience tab's sync log. + * a log of recent attempts — the same shape as the Audience screen's sync log. */ function sendbeam_screen_ecommerce() { $settings = sendbeam_ecommerce_settings(); - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice only. - if ( isset( $_GET['sendbeam_ecommerce_saved'] ) ) { - echo '

    ' . esc_html__( 'Saved.', 'sendbeam' ) . '

    '; - } - sendbeam_card_open( __( 'Cart Abandoned, Product Viewed, Order Placed', 'sendbeam' ), __( 'Feeds the three native SendBeam automation triggers of the same names.', 'sendbeam' ) @@ -1491,9 +1575,74 @@ function sendbeam_doc_snippet( $code, $what ) { } /** - * Help: the documentation, the shortcodes, and what each permission is for. + * Help: the documentation, the state of this site, and who to ask. */ function sendbeam_screen_help() { + sendbeam_help_documentation_card(); + sendbeam_help_status_card(); + sendbeam_help_support_card(); + sendbeam_help_shortcodes_card(); + sendbeam_help_permissions_card(); + sendbeam_help_developers_card(); +} + +/** + * What this site is doing, in one block somebody can hand to support. + * + * The same values Site Health reports, because a person who has a problem + * should not have to know that Site Health exists, or find the SendBeam + * section inside it, before they can describe their site. + */ +function sendbeam_help_status_card() { + $report = sendbeam_status_report(); + + sendbeam_card_open( __( 'System status', 'sendbeam' ), __( 'Nothing here is secret.', 'sendbeam' ) ); + echo '

    ' . esc_html__( 'What this site holds about its SendBeam connection. The API key is reported only as where it is kept and its last four characters, so this is safe to paste into an email.', 'sendbeam' ) . '

    '; + echo '
    ' . esc_html( $report ) . '
    '; + printf( + '

    ' . + '%5$s

    ', + esc_attr( $report ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy for support', 'sendbeam' ), + esc_url( admin_url( 'site-health.php?tab=debug' ) ), + esc_html__( 'Open Site Health', 'sendbeam' ) + ); + sendbeam_card_close(); +} + +/** + * Who to ask, and where. + */ +function sendbeam_help_support_card() { + sendbeam_card_open( __( 'Support', 'sendbeam' ) ); + echo '

    ' . esc_html__( 'A real person reads these. Paste the system status above into whichever you use — it answers the first four questions anybody would ask.', 'sendbeam' ) . '

    '; + echo '
      '; + printf( + '
    • %1$s — %2$s
    • ', + 'hello@sendbeam.io', + esc_html__( 'anything about your account, your sending domain or a message that did not arrive', 'sendbeam' ) + ); + printf( + '
    • %2$s — %3$s
    • ', + esc_url( 'https://wordpress.org/support/plugin/sendbeam/' ), + esc_html__( 'the WordPress.org support forum', 'sendbeam' ), + esc_html__( 'for questions about the plugin itself, in public, where the next person with the same question can find the answer', 'sendbeam' ) + ); + printf( + '
    • %2$s — %3$s
    • ', + esc_url( 'https://github.com/sendbeam-io/sendbeam-wordpress/issues' ), + esc_html__( 'GitHub issues', 'sendbeam' ), + esc_html__( 'for a bug with a reproduction, or a feature request', 'sendbeam' ) + ); + echo '
    '; + sendbeam_card_close(); +} + +/** + * The documentation links. + */ +function sendbeam_help_documentation_card() { sendbeam_card_open( __( 'Documentation', 'sendbeam' ) ); echo '
    '; echo '

    ' . esc_html__( 'The essentials are below. The full documentation is kept with SendBeam itself, so it stays current with the product rather than with whichever version of this plugin you happen to have installed.', 'sendbeam' ) . '

    '; @@ -1526,24 +1675,34 @@ function sendbeam_screen_help() { esc_html__( 'Cart Abandoned, Product Viewed and Order Placed, plus the Shopify webhook.', 'sendbeam' ) ); sendbeam_card_close(); +} +/** + * The four shortcodes. + */ +function sendbeam_help_shortcodes_card() { sendbeam_card_open( __( 'Shortcodes', 'sendbeam' ), __( 'Anywhere shortcodes work: a block, a widget, a page builder.', 'sendbeam' ) ); echo '
    '; sendbeam_doc_snippet( '[sendbeam_form]', __( 'The default signup form', 'sendbeam' ) ); sendbeam_doc_snippet( '[sendbeam_form id="8f3c1a2e-…"]', __( 'Any form, as often as you like', 'sendbeam' ) ); - sendbeam_doc_snippet( '[sendbeam_contact]', __( 'The contact form chosen on the Forms tab', 'sendbeam' ) ); + sendbeam_doc_snippet( '[sendbeam_contact]', __( 'The contact form chosen under Forms', 'sendbeam' ) ); sendbeam_doc_snippet( '[sendbeam_popup_button label="Subscribe"]', __( 'A button that opens a pop-up', 'sendbeam' ) ); echo '

    ' . esc_html__( 'A height attribute works on all of them, but you rarely want one: an embedded form measures itself and the frame follows.', 'sendbeam' ) . '

    '; echo '
    '; sendbeam_card_close(); +} +/** + * What each API key permission is for. + */ +function sendbeam_help_permissions_card() { sendbeam_card_open( __( 'API key permissions', 'sendbeam' ), __( 'Only what you use.', 'sendbeam' ) ); echo '
    '; echo '

    ' . esc_html__( 'Placing a form or a pop-up needs no key at all. Everything else asks for one thing:', 'sendbeam' ) . '

    '; - echo ''; + echo '
    ' . esc_html__( 'Permission', 'sendbeam' ) . '' . esc_html__( 'Needed for', 'sendbeam' ) . '
    '; foreach ( array( 'forms:read' => __( 'Listing your forms here and in the block', 'sendbeam' ), - 'lists:read' => __( 'The Audience tab and its counts', 'sendbeam' ), + 'lists:read' => __( 'The Audience screen and its counts', 'sendbeam' ), 'contacts:read, contacts:write, lists:write' => __( 'The opt-in box at registration, comments or checkout, and forms from Contact Form 7, Elementor Pro, WPForms, Gravity Forms and Fluent Forms', 'sendbeam' ), 'tags:read, tags:write' => __( 'A form plugin form that adds a tag', 'sendbeam' ), 'transactional:send' => __( 'Site email', 'sendbeam' ), @@ -1551,14 +1710,19 @@ function sendbeam_screen_help() { ) as $perm => $why ) { printf( '', esc_html( $perm ), esc_html( $why ) ); } - echo '
    ' . esc_html__( 'Permission', 'sendbeam' ) . '' . esc_html__( 'Needed for', 'sendbeam' ) . '
    %s%s
    '; + echo '
    '; printf( '

    %s

    ', esc_html__( 'Give each site its own key so one can be revoked without disturbing the others. Defining SENDBEAM_API_KEY in wp-config.php keeps the key out of the database entirely.', 'sendbeam' ) ); echo '
    '; sendbeam_card_close(); +} +/** + * The two hooks and where the source is. + */ +function sendbeam_help_developers_card() { sendbeam_card_open( __( 'For developers', 'sendbeam' ) ); echo '
    '; echo '

    ' . esc_html__( 'A page can react to a submission, and a self-hosted SendBeam can be pointed at with a filter.', 'sendbeam' ) . '

    '; diff --git a/includes/settings.php b/includes/settings.php index c6462cd..bc9072c 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -684,7 +684,25 @@ function shut() { box.hidden = true; ask.hidden = false; } var btn = e.target.closest( ".sb-copy" ); if ( ! btn ) { return; } var text = btn.getAttribute( "data-copy" ), done = btn.getAttribute( "data-done" ) || "Copied"; + var isField = "INPUT" === btn.tagName; function flash() { + /* + * A DNS value is a read-only input, not a button: it has no + * text to swap, and selecting what was copied is the + * confirmation people expect from a field. The tooltip and a + * class carry the word for everyone else. + */ + if ( isField ) { + try { btn.select(); } catch ( err ) {} + var wasTitle = btn.getAttribute( "title" ); + btn.setAttribute( "title", done ); + btn.classList.add( "is-copied" ); + setTimeout( function () { + btn.classList.remove( "is-copied" ); + if ( wasTitle ) { btn.setAttribute( "title", wasTitle ); } + }, 1400 ); + return; + } var was = btn.textContent; btn.textContent = done; setTimeout( function () { btn.textContent = was; }, 1400 ); diff --git a/includes/site-health.php b/includes/site-health.php new file mode 100644 index 0000000..911a972 --- /dev/null +++ b/includes/site-health.php @@ -0,0 +1,400 @@ + __( 'SendBeam connection', 'sendbeam' ), + 'test' => 'sendbeam_test_key', + ); + $tests['direct']['sendbeam-domain'] = array( + 'label' => __( 'SendBeam sending domain', 'sendbeam' ), + 'test' => 'sendbeam_test_domain', + ); + $tests['direct']['sendbeam-mail'] = array( + 'label' => __( 'SendBeam site email', 'sendbeam' ), + 'test' => 'sendbeam_test_mail_relay', + ); + return $tests; +} + +/** + * The shape every Site Health test returns, filled in. + * + * @param string $label The heading. + * @param string $status good, recommended or critical. + * @param string $colour blue, orange, red or gray. + * @param string $description One paragraph of HTML. + * @param string $action A link, or ''. + * @param string $test The test's id. + * @return array + */ +function sendbeam_health_result( $label, $status, $colour, $description, $action, $test ) { + return array( + 'label' => $label, + 'status' => $status, + 'badge' => array( + 'label' => __( 'Email', 'sendbeam' ), + 'color' => $colour, + ), + 'description' => '

    ' . $description . '

    ', + 'actions' => $action, + 'test' => $test, + ); +} + +/** + * A link to one of the plugin's own screens, in the markup Site Health uses. + * + * @param string $slug Page slug. + * @param string $label Link text. + * @param string $tab Optional tab on that page. + * @return string + */ +function sendbeam_health_link( $slug, $label, $tab = '' ) { + $url = sendbeam_page_url( $slug ); + if ( '' !== $tab ) { + $url = add_query_arg( 'tab', $tab, $url ); + } + return sprintf( '

    %s

    ', esc_url( $url ), esc_html( $label ) ); +} + +/** + * Does this site's key work? + * + * @return array + */ +function sendbeam_test_key() { + $connection = sendbeam_connection(); + $link = sendbeam_health_link( 'sendbeam-settings', __( 'Open SendBeam settings', 'sendbeam' ), 'connection' ); + + if ( 'none' === $connection['state'] ) { + return sendbeam_health_result( + __( 'SendBeam is not connected', 'sendbeam' ), + 'recommended', + 'orange', + esc_html__( 'The SendBeam plugin is active but this site has no API key, so its forms, lists and site email are not available. Nothing is broken by this — the plugin simply does nothing until it is connected.', 'sendbeam' ), + $link, + 'sendbeam-key' + ); + } + + if ( 'rejected' === $connection['state'] ) { + return sendbeam_health_result( + __( 'SendBeam rejected this site\'s key', 'sendbeam' ), + 'critical', + 'red', + esc_html__( 'SendBeam will not accept the key this site is using. Any form, list or email that depends on it has stopped working. The usual causes are a key that was revoked in SendBeam and a key copied only in part.', 'sendbeam' ), + $link, + 'sendbeam-key' + ); + } + + if ( 'unreachable' === $connection['state'] ) { + return sendbeam_health_result( + __( 'SendBeam could not be reached from this server', 'sendbeam' ), + 'recommended', + 'orange', + esc_html( + sprintf( + /* translators: %s: the error this server reported */ + __( 'The last attempt to reach sendbeam.io failed: %s. That is usually the host blocking outbound requests, or a temporary outage. Stored settings are unaffected.', 'sendbeam' ), + $connection['message'] + ) + ), + $link, + 'sendbeam-key' + ); + } + + if ( 'no_scope' === $connection['state'] ) { + return sendbeam_health_result( + __( 'SendBeam is connected with a limited key', 'sendbeam' ), + 'recommended', + 'orange', + esc_html__( 'The key works, but it was not given permission to read this workspace\'s forms, so they cannot be listed in wp-admin. Everything the key was given permission for still works.', 'sendbeam' ), + $link, + 'sendbeam-key' + ); + } + + return sendbeam_health_result( + __( 'SendBeam is connected', 'sendbeam' ), + 'good', + 'blue', + esc_html__( 'This site\'s API key works and SendBeam is answering to it.', 'sendbeam' ), + '', + 'sendbeam-key' + ); +} + +/** + * Is the sending domain verified? + * + * @return array + */ +function sendbeam_test_domain() { + $link = sendbeam_health_link( 'sendbeam-settings', __( 'Open the sending domain', 'sendbeam' ), 'domain' ); + + if ( ! sendbeam_is_connected() ) { + return sendbeam_health_result( + __( 'SendBeam has no sending domain yet', 'sendbeam' ), + 'recommended', + 'orange', + esc_html__( 'This site is not connected to SendBeam, so there is no sending domain to check.', 'sendbeam' ), + $link, + 'sendbeam-domain' + ); + } + + $status = sendbeam_connect_status(); + $domain = $status['domain']; + + if ( ! empty( $domain['verified'] ) ) { + return sendbeam_health_result( + __( 'The SendBeam sending domain is verified', 'sendbeam' ), + 'good', + 'blue', + esc_html( + sprintf( + /* translators: %s: the sending domain */ + __( 'SendBeam has found the DNS records for %s, so email can be sent as that domain.', 'sendbeam' ), + $domain['name'] + ) + ), + '', + 'sendbeam-domain' + ); + } + + if ( '' === $domain['name'] ) { + return sendbeam_health_result( + __( 'SendBeam has no sending domain yet', 'sendbeam' ), + 'recommended', + 'orange', + esc_html( sendbeam_domain_sentence( '', false ) ), + $link, + 'sendbeam-domain' + ); + } + + return sendbeam_health_result( + __( 'The SendBeam sending domain is not verified', 'sendbeam' ), + 'recommended', + 'orange', + esc_html( + sprintf( + /* translators: %s: the sending domain */ + __( 'SendBeam has not yet found the DNS records for %s. Until it does, email cannot be sent as that domain. The records, and a button to check again, are on the SendBeam settings screen.', 'sendbeam' ), + $domain['name'] + ) + ), + $link, + 'sendbeam-domain' + ); +} + +/** + * Is this site's email actually going through SendBeam, safely? + * + * The interesting failure is the middle one: the relay on with an unverified + * domain. That is a site whose password resets are being handed to a sender + * nothing has proved, which is worse than not using the plugin at all. + * + * @return array + */ +function sendbeam_test_mail_relay() { + $settings = sendbeam_settings(); + $link = sendbeam_health_link( 'sendbeam-mail', __( 'Open the site email settings', 'sendbeam' ) ); + + if ( empty( $settings['mail_enabled'] ) ) { + return sendbeam_health_result( + __( 'This site\'s email does not go through SendBeam', 'sendbeam' ), + 'good', + 'blue', + esc_html__( 'Site email is switched off, so WordPress sends its own email the way it did before this plugin was installed. This is not a fault; it is optional.', 'sendbeam' ), + $link, + 'sendbeam-mail' + ); + } + + $verified = sendbeam_is_connected() && ! empty( sendbeam_connect_status()['domain']['verified'] ); + + if ( ! $verified ) { + return sendbeam_health_result( + __( 'This site\'s email is being sent from an unverified domain', 'sendbeam' ), + 'critical', + 'red', + esc_html__( 'Site email is switched on, but SendBeam has not verified the sending domain. Messages this site sends — password resets included — are likely to be refused or filed as spam. Either finish verifying the domain or switch site email off until it is done.', 'sendbeam' ), + $link, + 'sendbeam-mail' + ); + } + + $fallback = ! empty( $settings['mail_fallback'] ) + ? __( 'A message SendBeam cannot take falls back to the server\'s own mailer, so nothing is lost.', 'sendbeam' ) + : __( 'The fallback to the server\'s own mailer is off, so a message SendBeam cannot take is not sent at all and the plugin that tried is told.', 'sendbeam' ); + + return sendbeam_health_result( + __( 'This site\'s email goes through SendBeam', 'sendbeam' ), + 'good', + 'blue', + esc_html__( 'Site email is on and the sending domain is verified.', 'sendbeam' ) . ' ' . esc_html( $fallback ), + '', + 'sendbeam-mail' + ); +} + +/** + * The SendBeam section of Tools → Site Health → Info. + * + * Everything here is a state, never a secret: the key is reported as where it + * lives and how it ends, because the whole point of this panel is that it can + * be copied in one press and pasted into a support request. + * + * @param array $info Core's sections. + * @return array + */ +function sendbeam_debug_information( $info ) { + $settings = sendbeam_settings(); + $connection = sendbeam_connection(); + $connected = sendbeam_is_connected(); + $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + $key = sendbeam_api_key(); + + $where = __( 'Not set', 'sendbeam' ); + if ( '' !== $key ) { + $where = sendbeam_key_in_config() + ? __( 'wp-config.php constant', 'sendbeam' ) + : __( 'Stored in the options table', 'sendbeam' ); + $where .= ' (…' . substr( $key, -4 ) . ')'; + } + + $recheck = wp_next_scheduled( SENDBEAM_RECHECK_HOOK ); + + $fields = array( + 'version' => array( + 'label' => __( 'Plugin version', 'sendbeam' ), + 'value' => SENDBEAM_VERSION, + ), + 'app_url' => array( + 'label' => __( 'SendBeam address', 'sendbeam' ), + 'value' => sendbeam_app_url(), + ), + 'key' => array( + 'label' => __( 'API key', 'sendbeam' ), + 'value' => $where, + ), + 'connected_via' => array( + 'label' => __( 'Connected by', 'sendbeam' ), + 'value' => sendbeam_connected_via_connect() ? __( 'The Connect button', 'sendbeam' ) : __( 'A pasted key', 'sendbeam' ), + ), + 'state' => array( + 'label' => __( 'Connection state', 'sendbeam' ), + 'value' => $connection['state'], + ), + 'workspace' => array( + 'label' => __( 'Workspace', 'sendbeam' ), + 'value' => '' !== (string) $status['workspace']['name'] ? (string) $status['workspace']['name'] : __( 'Not reported', 'sendbeam' ), + ), + 'granted' => array( + 'label' => __( 'Permissions granted', 'sendbeam' ), + 'value' => '' !== (string) $settings['sendbeam_connect_granted'] ? (string) $settings['sendbeam_connect_granted'] : __( 'Not recorded', 'sendbeam' ), + ), + 'domain' => array( + 'label' => __( 'Sending domain', 'sendbeam' ), + 'value' => '' !== (string) $status['domain']['name'] ? (string) $status['domain']['name'] : __( 'None', 'sendbeam' ), + ), + 'domain_state' => array( + 'label' => __( 'Sending domain state', 'sendbeam' ), + 'value' => ! empty( $status['domain']['verified'] ) ? 'verified' : (string) $status['domain_state'], + ), + 'domain_check' => array( + 'label' => __( 'Sending domain last checked', 'sendbeam' ), + 'value' => '' !== (string) $status['domain']['checked_at'] ? sendbeam_connect_when( (string) $status['domain']['checked_at'] ) : __( 'Never', 'sendbeam' ), + ), + 'mail' => array( + 'label' => __( 'Site email', 'sendbeam' ), + 'value' => ! empty( $settings['mail_enabled'] ) ? __( 'On', 'sendbeam' ) : __( 'Off', 'sendbeam' ), + ), + 'mail_from' => array( + 'label' => __( 'Site email From address', 'sendbeam' ), + 'value' => '' !== (string) $settings['mail_from_email'] ? (string) $settings['mail_from_email'] : __( 'The workspace sender', 'sendbeam' ), + ), + 'mail_fallback' => array( + 'label' => __( 'Site email fallback', 'sendbeam' ), + 'value' => ! empty( $settings['mail_fallback'] ) ? __( 'On', 'sendbeam' ) : __( 'Off', 'sendbeam' ), + ), + 'form_placed' => array( + 'label' => __( 'A SendBeam form on the site', 'sendbeam' ), + 'value' => '' !== sendbeam_form_placement() ? sendbeam_form_placement() : __( 'Not found', 'sendbeam' ), + ), + 'recheck' => array( + 'label' => __( 'Hourly domain re-check', 'sendbeam' ), + 'value' => $recheck ? sendbeam_connect_when( gmdate( 'c', (int) $recheck ) ) : __( 'Not scheduled', 'sendbeam' ), + ), + 'cron' => array( + 'label' => __( 'WordPress cron', 'sendbeam' ), + 'value' => ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ? __( 'Disabled in wp-config.php', 'sendbeam' ) : __( 'Enabled', 'sendbeam' ), + ), + ); + + $info['sendbeam'] = array( + 'label' => __( 'SendBeam', 'sendbeam' ), + 'description' => __( 'What this site holds about its SendBeam connection. None of it is a secret: the API key is reported only as where it is kept and its last four characters.', 'sendbeam' ), + 'fields' => $fields, + ); + + return $info; +} + +/** + * The same values, as one block of text somebody can paste into an email. + * + * @return string + */ +function sendbeam_status_report() { + $info = sendbeam_debug_information( array() ); + $lines = array( + 'SendBeam ' . SENDBEAM_VERSION, + 'WordPress ' . get_bloginfo( 'version' ) . ' / PHP ' . PHP_VERSION, + 'Site: ' . home_url(), + '', + ); + foreach ( $info['sendbeam']['fields'] as $field ) { + $lines[] = $field['label'] . ': ' . $field['value']; + } + return implode( "\n", $lines ); +} diff --git a/includes/sync.php b/includes/sync.php index 4ee764e..6fa45a2 100644 --- a/includes/sync.php +++ b/includes/sync.php @@ -224,7 +224,7 @@ function sendbeam_sync_on_checkout( $order_id ) { * @param string $first_name First name. * @param string $last_name Last name. * @param string $source Where they came from. - * @param string[]|null $lists Lists to join; null means the lists chosen on the Audience tab. + * @param string[]|null $lists Lists to join; null means the lists chosen under Audience. * @param string $tag A tag to add, by name; empty for none. * @return bool */ diff --git a/sendbeam.php b/sendbeam.php index 4ac9fd4..e0099fb 100644 --- a/sendbeam.php +++ b/sendbeam.php @@ -34,7 +34,9 @@ require SENDBEAM_DIR . 'includes/settings.php'; require SENDBEAM_DIR . 'includes/render.php'; require SENDBEAM_DIR . 'includes/mail.php'; +require SENDBEAM_DIR . 'includes/notices.php'; require SENDBEAM_DIR . 'includes/onboarding.php'; require SENDBEAM_DIR . 'includes/wizard.php'; +require SENDBEAM_DIR . 'includes/site-health.php'; require SENDBEAM_DIR . 'includes/connect.php'; require SENDBEAM_DIR . 'includes/connect-status.php'; diff --git a/tests/smoke.php b/tests/smoke.php index c539bff..79e58aa 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -642,6 +642,307 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), delete_transient( 'sendbeam_subscriber_count' ); update_option( 'sendbeam_settings', array() ); +/* ───────────────────────────── The surfaces ──────────────────────────── + * The sending domain, the test email, Site Health and the notices — the four + * places a site owner finds out what is actually going on. + */ +$GLOBALS['stub']['caps']['manage_options'] = true; +$GLOBALS['stub']['user_id'] = 7; +$GLOBALS['stub']['current_user'] = array( 'email' => 'admin@example-site.test' ); + +// ── The sending domain, in MailPoet's shape ───────────────────────────── +function sb_domain_panel( $records, $verified, $standalone = false ) { + $status = sendbeam_connect_normalise_status( + array( + 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ), + 'domain' => array( + 'name' => 'harbourlane.co.uk', + 'verified' => $verified, + 'records' => $records, + 'checked_at' => '2026-09-23T15:04:05Z', + ), + ) + ); + ob_start(); + sendbeam_domain_panel( $status, $standalone ); + return ob_get_clean(); +} + +$sb_records_none = array( + array( 'type' => 'CNAME', 'name' => 'sb1._domainkey', 'value' => 'sb1.dkim.sendbeam.io', 'found' => false ), + array( 'type' => 'CNAME', 'name' => 'sb2._domainkey', 'value' => 'sb2.dkim.sendbeam.io', 'found' => false ), +); +$sb_records_some = $sb_records_none; +$sb_records_some[0]['found'] = true; + +$panel = sb_domain_panel( $sb_records_none, false, true ); +has( $panel, 'class="widefat striped sb-dns"', 'domain: the records sit in a core widefat striped table' ); +has( $panel, 'Type', 'domain: Type is a column' ); +has( $panel, 'Host', 'domain: Host is a column — the word registrars use' ); +has( $panel, 'Value', 'domain: Value is a column' ); +has( $panel, 'Found', 'domain: and the check\'s verdict per row' ); +lacks( $panel, 'Priority', 'domain: every record is a CNAME, so nothing asks for a priority' ); +has( $panel, 'class="sb-copy-field sb-copy"', 'domain: each value is a field that copies when it is clicked' ); +has( $panel, 'readonly', 'domain: and cannot be edited into something wrong' ); +has( $panel, 'title="Click to copy"', 'domain: the field says what clicking it does' ); +has( $panel, 'data-done="Copied"', 'domain: and what it did' ); +has( $panel, 'sb1.dkim.sendbeam.io', 'domain: the value a registrar needs is on the screen' ); +has( $panel, 'screen-reader-text', 'domain: every copy field is labelled for a screen reader' ); +has( $panel, 'up to 24 hours', 'domain: the panel says DNS is slow before somebody decides it is broken' ); +has( $panel, 'sb-numbered', 'domain: the two things to do are numbered' ); +has( $panel, 'Check now', 'domain: and the check is right there' ); +has( $panel, 'Proving that this domain is yours', 'domain: standing on its own, the panel says why any of this matters' ); + +// Three states, and the middle one is the one nobody else distinguishes. +has( sb_domain_panel( $sb_records_none, false ), '>Not found<', 'domain: nothing found yet says Not found' ); +has( sb_domain_panel( $sb_records_none, false ), 'Nothing has been found in the DNS', 'domain: and says it in words' ); +has( sb_domain_panel( $sb_records_some, false ), '>Pending<', 'domain: some records live says Pending' ); +has( sb_domain_panel( $sb_records_some, false ), '1 of 2 records are live', 'domain: and says how far through it is' ); +has( sb_domain_panel( $sb_records_some, true ), 'Verified — harbourlane.co.uk', 'domain: verified says so, and names the domain' ); +has( sb_domain_panel( $sb_records_some, true ), 'Check again', 'domain: a verified domain can still be re-checked' ); +lacks( sb_domain_panel( $sb_records_some, true ), 'sb-numbered', 'domain: a verified domain is not given a list of things to do' ); + +// ── The test email ────────────────────────────────────────────────────── +update_option( + 'sendbeam_settings', + array( + 'api_key' => 'sb_live_testmailtestmailxx', + 'mail_enabled' => 1, + 'mail_from_name' => 'Harbour Lane Roasters', + 'mail_from_email' => 'hello@harbourlane.co.uk', + ) +); +set_transient( 'sendbeam_connection', array( 'state' => 'ok', 'message' => '', 'count' => 1 ) ); +sendbeam_connect_cache_status( + sendbeam_connect_normalise_status( + array( + 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ), + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => $sb_records_some ), + 'sender' => array( 'from_name' => 'Harbour Lane Roasters', 'from_email' => 'hello@harbourlane.co.uk' ), + ) + ) +); + +$facts = sendbeam_mail_facts(); +$mail_html = sendbeam_test_mail_html( $facts ); +$mail_text = sendbeam_test_mail_text( $facts ); +has( $mail_html, '', 'test email: it is a real HTML document' ); +has( $mail_html, ' 'nonce:sendbeam_test_mail' ); + try { + sendbeam_handle_test_mail(); + } catch ( SendBeamStubExit $e ) { + unset( $e ); + } + $_REQUEST = array(); + return sendbeam_take_test_result(); +} + +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{"ok":true}' ); +$GLOBALS['stub']['remote'] = array(); +$sent = sb_send_test(); +ok( ! empty( $sent['ok'] ), 'test email: a 200 is a success' ); +$sent_body = json_decode( $GLOBALS['stub']['remote'][0]['args']['body'], true ); +ok( isset( $sent_body['html'] ), 'test email: the HTML half is sent' ); +ok( isset( $sent_body['text'] ), 'test email: and so is the plain-text half' ); +has( $sent_body['subject'], 'Test email from Example Site via SendBeam', 'test email: the subject names the site' ); + +ob_start(); +sendbeam_test_mail_success( $sent ); +$card = ob_get_clean(); +has( $card, 'sb-result--ok', 'test email: success renders a success card' ); +has( $card, 'Sent to admin@example-site.test — open your inbox to see it.', 'test email: which says where it went and what to do next' ); +has( $card, 'Send another', 'test email: and offers to do it again' ); + +// A failure explains itself, and hands over everything support would ask for. +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 403 ), 'body' => '{"error":"domain not verified"}' ); +$failed = sb_send_test(); +ok( empty( $failed['ok'] ), 'test email: a 403 is a failure' ); +ok( ! empty( $failed['bundle'] ), 'test email: and the bundle is captured at the moment it failed' ); +ob_start(); +sendbeam_test_mail_failure( $failed ); +$card = ob_get_clean(); +has( $card, 'sb-result--bad', 'test email: failure renders a failure card' ); +has( $card, 'SendBeam would not send that message', 'test email: with a title in plain words' ); +has( $card, 'What it means', 'test email: it says what the failure means' ); +has( $card, 'not given permission to send this site', 'test email: and the meaning matches the status code' ); +has( $card, 'What to do', 'test email: it says what to do about it' ); +has( $card, 'Settings → Sending domain', 'test email: and the advice matches the status code too' ); +has( $card, 'SendBeam said: domain not verified', 'test email: the raw error is kept, not swallowed' ); +has( $card, 'Details for support', 'test email: the bundle is there' ); +has( $card, 'sb-copy', 'test email: one click from the clipboard' ); +has( $card, 'Copy these details', 'test email: and says so' ); +has( $card, 'WordPress 6.7.1', 'test email bundle: the WordPress version' ); +has( $card, 'PHP ' . PHP_VERSION, 'test email bundle: the PHP version' ); +has( $card, 'SendBeam ' . SENDBEAM_VERSION, 'test email bundle: the plugin version' ); +has( $card, 'Key: stored in options', 'test email bundle: where the key lives, never the key' ); +has( $card, 'harbourlane.co.uk — verified', 'test email bundle: the sending domain and its state' ); +has( $card, 'HTTP: 403', 'test email bundle: the status code that came back' ); +has( $card, 'Error: domain not verified', 'test email bundle: and the raw error' ); +lacks( $card, 'sb_live_testmailtestmailxx', 'test email bundle: the API key is never in it' ); +has( $card, 'Try again', 'test email: and the form comes back' ); + +// The result is read once, so a refresh does not replay it. +ok( null === sendbeam_take_test_result(), 'test email: the result is taken once, so refreshing does not show it again' ); + +// A server that never answered is a different sentence from a refusal. +$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 0 ), 'body' => '' ); +$failed = sb_send_test(); +has( $failed['means'], 'could not reach sendbeam.io at all', 'test email: a request that never landed says so' ); +has( $failed['do'], 'outbound HTTPS', 'test email: and points at the thing that usually blocks it' ); + +// Site email off is not a send that failed. +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_testmailtestmailxx', 'mail_enabled' => 0 ) ); +$failed = sb_send_test(); +has( $failed['title'], 'Site email is not switched on yet', 'test email: nothing is sent when the relay is off, and the card says so' ); +has( $failed['do'], 'Tick "Send this site', 'test email: and says how to switch it on' ); + +// ── Site Health ───────────────────────────────────────────────────────── +$sendbeam_tests = sendbeam_site_status_tests( array() ); +foreach ( array( 'sendbeam-key', 'sendbeam-domain', 'sendbeam-mail' ) as $sendbeam_t ) { + ok( isset( $sendbeam_tests['direct'][ $sendbeam_t ] ), "site health: $sendbeam_t is registered" ); + ok( is_callable( $sendbeam_tests['direct'][ $sendbeam_t ]['test'] ), "site health: $sendbeam_t has a callable test" ); +} + +update_option( 'sendbeam_settings', array() ); +sendbeam_flush_cache(); +sendbeam_connect_forget_status(); +$r = sendbeam_test_key(); +ok( 'recommended' === $r['status'], 'site health: no key is a recommendation, not a failure — the plugin is simply not in use' ); +has( $r['label'], 'SendBeam is not connected', 'site health: and says so' ); + +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_healthhealthhealth' ) ); +set_transient( 'sendbeam_connection', array( 'state' => 'rejected', 'message' => 'nope' ) ); +$r = sendbeam_test_key(); +ok( 'critical' === $r['status'], 'site health: a rejected key is critical — things have stopped working' ); +set_transient( 'sendbeam_connection', array( 'state' => 'unreachable', 'message' => 'cURL error 28' ) ); +$r = sendbeam_test_key(); +ok( 'recommended' === $r['status'], 'site health: an unreachable SendBeam is a recommendation, not a fault in the site' ); +has( $r['description'], 'cURL error 28', 'site health: and it quotes what the server actually reported' ); +set_transient( 'sendbeam_connection', array( 'state' => 'ok', 'message' => '', 'count' => 1 ) ); +$r = sendbeam_test_key(); +ok( 'good' === $r['status'], 'site health: a working key is good' ); + +sendbeam_connect_cache_status( + sendbeam_connect_normalise_status( + array( + 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ), + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => $sb_records_none ), + ) + ) +); +$r = sendbeam_test_domain(); +ok( 'recommended' === $r['status'], 'site health: an unverified domain is a recommendation' ); +has( $r['actions'], 'tab=domain', 'site health: and links straight at the records' ); + +// The one that matters: the relay on behind a domain nothing has proved. +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_healthhealthhealth', 'mail_enabled' => 1 ) ); +$r = sendbeam_test_mail_relay(); +ok( 'critical' === $r['status'], 'site health: site email on with an unverified domain is critical' ); +has( $r['label'], 'unverified domain', 'site health: and names the problem' ); + +sendbeam_connect_cache_status( + sendbeam_connect_normalise_status( + array( + 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ), + 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => $sb_records_some ), + ) + ) +); +$r = sendbeam_test_mail_relay(); +ok( 'good' === $r['status'], 'site health: site email on behind a verified domain is good' ); +update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_healthhealthhealth', 'mail_enabled' => 0 ) ); +$r = sendbeam_test_mail_relay(); +ok( 'good' === $r['status'], 'site health: site email off is not a fault — it is optional' ); + +// The debug section, and the same thing as one pasteable block. +$info = sendbeam_debug_information( array() ); +ok( isset( $info['sendbeam'] ), 'site health: there is a SendBeam section in the debug info' ); +$labels = wp_list_pluck_stub( $info['sendbeam']['fields'], 'label' ); +foreach ( array( 'Plugin version', 'API key', 'Connection state', 'Sending domain', 'Site email', 'WordPress cron' ) as $sendbeam_f ) { + ok( in_array( $sendbeam_f, $labels, true ), "site health: the debug info reports $sendbeam_f" ); +} +$report = sendbeam_status_report(); +has( $report, 'SendBeam ' . SENDBEAM_VERSION, 'system status: the report names the plugin version' ); +has( $report, 'WordPress 6.7.1', 'system status: and the WordPress version' ); +lacks( $report, 'sb_live_healthhealthhealth', 'system status: and never the key itself' ); +has( $report, 'Stored in the options table (…alth)', 'system status: only where the key lives and how it ends' ); + +// ── Notices ───────────────────────────────────────────────────────────── +/** Capture what admin_notices prints on a given screen with a given query. */ +function sb_notices( $screen, $get ) { + $GLOBALS['stub']['screen'] = $screen; + $_GET = $get; + ob_start(); + sendbeam_admin_notices(); + $out = ob_get_clean(); + $_GET = array(); + return $out; +} + +has( sb_notices( 'toplevel_page_sendbeam', array( 'sendbeam_mail' => 'on' ) ), 'Site email is on', 'notices: a SendBeam screen shows the plugin\'s messages' ); +has( sb_notices( 'toplevel_page_sendbeam', array( 'sendbeam_mail' => 'on' ) ), 'notice-success', 'notices: in core\'s own classes' ); +has( sb_notices( 'toplevel_page_sendbeam', array( 'sendbeam_mail' => 'on' ) ), 'is-dismissible', 'notices: and every one can be closed' ); +has( sb_notices( 'sendbeam_page_sendbeam-popups', array( 'sendbeam_saved' => '3' ) ), '3 pop-ups saved', 'notices: a count is printed as a count' ); +has( sb_notices( 'sendbeam_page_sendbeam-audience', array( 'sendbeam_sync_saved' => '1' ) ), 'Saved.', 'notices: a save on another SendBeam screen is reported there' ); +ok( '' === sb_notices( 'plugins', array( 'sendbeam_mail' => 'on' ) ), 'notices: nothing is printed on the Plugins screen' ); +ok( '' === sb_notices( 'edit-post', array( 'sendbeam_saved' => '3' ) ), 'notices: nor on the posts list' ); +ok( '' === sb_notices( 'woocommerce_page_wc-settings', array( 'sendbeam_domain' => 'verified' ) ), 'notices: nor on another plugin\'s settings screen' ); +ok( '' === sb_notices( 'toplevel_page_sendbeam', array( 'sendbeam_mail' => 'nonsense-from-the-url' ) ), 'notices: a value nobody set prints nothing' ); +lacks( sb_notices( 'toplevel_page_sendbeam', array( 'sendbeam_mail' => '' ) ), 'alert(1)', 'notices: a notice name from the URL is not a message to print' ); + +// The one exception: the Dashboard, once, for a site nobody has set up. +delete_option( 'sendbeam_setup_done' ); +update_option( 'sendbeam_settings', array() ); +sendbeam_flush_cache(); +$GLOBALS['stub']['usermeta'][7]['sendbeam_setup_dismissed'] = ''; +unset( $GLOBALS['stub']['usermeta'][7]['sendbeam_setup_dismissed'] ); +$dash = sb_notices( 'dashboard', array() ); +has( $dash, 'SendBeam is installed', 'notices: the Dashboard carries the one setup notice' ); +has( $dash, 'page=sendbeam-setup', 'notices: and it opens the wizard' ); +has( $dash, 'is-dismissible', 'notices: and it can be dismissed' ); +has( $dash, 'button button-primary', 'notices: inside a core notice the buttons are core\'s, which is where they belong' ); + +update_user_meta( 7, 'sendbeam_setup_dismissed', 1 ); +ok( '' === sb_notices( 'dashboard', array() ), 'notices: dismissing the setup notice is remembered, per user' ); +delete_user_meta( 7, 'sendbeam_setup_dismissed' ); + +update_option( 'sendbeam_setup_done', 1 ); +ok( '' === sb_notices( 'dashboard', array() ), 'notices: and finishing the wizard removes it without anybody dismissing anything' ); +delete_option( 'sendbeam_setup_done' ); + +ok( '' === sb_notices( 'edit-page', array() ), 'notices: the setup notice is on the Dashboard and nowhere else' ); +ok( '' === sb_notices( 'plugins', array() ), 'notices: not even on the Plugins screen' ); + +update_option( 'sendbeam_settings', array() ); +sendbeam_flush_cache(); +$GLOBALS['stub']['remote_reply'] = null; +unset( $GLOBALS['stub']['screen'] ); + /* ─────────────────────────── The setup wizard ────────────────────────── * One redirect, once, guarded three ways, into a page that can be left from * every step. The guards are the whole of the argument for doing this at all: @@ -2047,7 +2348,14 @@ function sb_overview( $settings, $status, $get = array(), $forms = array() ) { set_transient( 'sendbeam_remote_lists', array() ); set_transient( 'sendbeam_subscriber_count', 0 ); sendbeam_connect_cache_status( sendbeam_connect_normalise_status( $status ) ); + + // What a browser gets on this screen: the notices WordPress prints above + // the page, and then the page. The plugin's messages moved out of the + // middle of each screen's markup and into core's notice component, so a + // test that looked only at the screen would stop seeing them. + $GLOBALS['stub']['screen'] = 'toplevel_page_sendbeam'; ob_start(); + sendbeam_admin_notices(); sendbeam_screen_overview(); return ob_get_clean(); } diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php index 7953b27..62a90e7 100644 --- a/tests/wp-stubs.php +++ b/tests/wp-stubs.php @@ -141,7 +141,10 @@ function wp_parse_url( $u, $c = -1 ) { return parse_url( $u, $c ); } function is_email( $e ) { return (bool) filter_var( $e, FILTER_VALIDATE_EMAIL ); } function sanitize_email( $e ) { return trim( (string) $e ); } function checked( $a, $b = true, $echo = true ) { return $a == $b ? ' checked="checked"' : ''; } -function get_bloginfo( $k ) { return isset( $GLOBALS['stub']['bloginfo'][ $k ] ) ? $GLOBALS['stub']['bloginfo'][ $k ] : 'Example Site'; } +function get_bloginfo( $k ) { + if ( isset( $GLOBALS['stub']['bloginfo'][ $k ] ) ) { return $GLOBALS['stub']['bloginfo'][ $k ]; } + return 'version' === $k ? '6.7.1' : 'Example Site'; +} function selected( $a, $b, $echo = true ) { return $a == $b ? ' selected="selected"' : ''; } // ── Connect ───────────────────────────────────────────────────────────── @@ -431,3 +434,9 @@ function add_screen_option( $option, $args = array() ) { $GLOBALS['stub']['scree function delete_user_meta( $user_id, $key, $value = '' ) { unset( $GLOBALS['stub']['usermeta'][ $user_id ][ $key ] ); return true; } function __return_false() { return false; } function __return_true() { return true; } +function wp_kses_post( $data ) { return $data; } +function wp_list_pluck_stub( $rows, $field ) { + $out = array(); + foreach ( $rows as $row ) { $out[] = $row[ $field ]; } + return $out; +} From ec7c0c137c1495962fa5829d1d03fa0b28737a9f Mon Sep 17 00:00:00 2001 From: sendbeam-bot Date: Thu, 24 Sep 2026 08:01:08 +0000 Subject: [PATCH 34/75] Stop the plugin shouting, and let the site choose the button colour MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four things made these screens read as something bolted on rather than part of wp-admin, and none of them was the brand: 10px uppercase mono labels, black primary buttons, labels sitting beside their fields, and a page inset on the right but not on the left. Labels are sentence case at a readable size. Mono is kept for the things people copy — values, code, figures — and taken off everything else. Primary buttons are var(--wp-admin-theme-color), so a site running Midnight or Ocean gets a button that belongs to it; secondary is an ink outline; Disconnect is a vermilion outline, because a filled red button beside a filled blue one is a coin toss at a glance. Fields are label-above and 40px, with the focus ring in the same theme colour, and every on/off setting is a switch. The ink, the paper, the three-square mark, the cards, the header band and the state pill are untouched. Every remaining hand-rolled table sits in the scroll wrapper the plugin already had, which is the one-line fault that made Forms and Site email scroll sideways on a phone. --- includes/admin-ui.php | 290 ++++++++++++++++++++++++++++-------------- includes/connect.php | 2 +- includes/screens.php | 63 +++++---- includes/settings.php | 2 +- tests/smoke.php | 53 ++++++++ 5 files changed, 288 insertions(+), 122 deletions(-) diff --git a/includes/admin-ui.php b/includes/admin-ui.php index 62c7a99..ff6b97f 100644 --- a/includes/admin-ui.php +++ b/includes/admin-ui.php @@ -176,164 +176,268 @@ function sendbeam_card_close() { */ function sendbeam_admin_css() { return ' + /* ── Tokens ───────────────────────────────────────────────────────── */ .sendbeam-app{--paper:#EDEBE6;--ink:#121212;--v:#E2442A;--c:#1F3FBF;--m:#3B7D46;--a:#B26B12;--ink-60:#5c5c5c; - background:var(--paper);margin:20px 20px 0 0;padding:0 0 28px;color:var(--ink); + --rule:#d8d6d0;--hair:#e2e0db; + /* The admin theme colour, so a site that has chosen Midnight or Ocean + gets its own primary rather than one this plugin picked. */ + --brand:var(--wp-admin-theme-color,#2271b1); + --brand-dark:var(--wp-admin-theme-color-darker-10,#135e96); + background:var(--paper);margin:20px 20px 0;padding:0 0 28px;color:var(--ink); font-family:Archivo,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;} .sendbeam-app *{box-sizing:border-box} - .sendbeam-app .sb-mono,.sendbeam-app .sb-label,.sendbeam-app .sb-state,.sendbeam-app .sb-chip,.sendbeam-app .sb-tab,.sendbeam-app code + /* Mono is for values a person copies, and for nothing else. */ + .sendbeam-app .sb-mono,.sendbeam-app code,.sendbeam-app pre,.sendbeam-app .sb-fig,.sendbeam-app .sb-copy-field {font-family:"Martian Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-variant-numeric:tabular-nums} - .sb-scopes{list-style:none;margin:0;padding:0} - .sb-scopes li{margin:0 0 6px} - .sb-scopes label{display:flex;gap:8px;align-items:flex-start;line-height:1.45} - .sb-paste>summary{cursor:pointer;font-size:12px;color:var(--ink-60)} - + /* ── The header band ──────────────────────────────────────────────── */ .sb-head{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap; padding:18px 22px;background:var(--ink);color:var(--paper)} - .sb-head__brand{display:flex;align-items:center;gap:10px} - .sb-mark{width:16px;height:16px;background:var(--v);display:inline-block; - box-shadow:22px 0 0 0 var(--c),44px 0 0 0 var(--m);margin-right:44px;flex:0 0 auto} + .sb-head__brand{display:flex;align-items:center;gap:10px;min-width:0} + .sb-mark{width:14px;height:14px;background:var(--v);display:inline-block; + box-shadow:20px 0 0 0 var(--c),40px 0 0 0 var(--m);margin-right:40px;flex:0 0 auto} .sb-wordmark{font-weight:700;font-size:18px;letter-spacing:-.01em} - .sb-ver{font-size:11px;opacity:.6;letter-spacing:.06em} + .sb-head__where{opacity:.45} + .sb-head__title{font-size:16px;opacity:.9;overflow-wrap:anywhere} .sb-head__right{display:flex;align-items:center;gap:12px;flex-wrap:wrap} - .sb-state{display:inline-block;font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase; - padding:5px 8px 4px;color:#fff;background:var(--ink-60)} + .sb-state{display:inline-block;font-size:12px;font-weight:600;padding:4px 9px;color:#fff;background:var(--ink-60)} .sb-state--moss{background:var(--m)} .sb-state--vermilion{background:var(--v)} .sb-state--amber{background:var(--a)} .sb-state--ink{background:#3a3a3a} + .sb-state-line{display:flex;gap:9px;align-items:baseline;flex-wrap:wrap;margin:0 0 12px} + + /* ── Tabs, on the one screen that still has them ──────────────────── */ + .sb-tabs{display:flex;gap:0;flex-wrap:wrap;background:#fff;border:1px solid var(--ink);margin:0 0 18px} + .sb-tab{display:inline-flex;align-items:center;height:42px;padding:0 18px;text-decoration:none; + font-size:14px;font-weight:500;color:var(--ink-60);border-bottom:3px solid transparent} + .sb-tab:hover{color:var(--ink)} + .sb-tab.is-active{color:var(--ink);font-weight:600;border-bottom-color:var(--brand)} + .sb-tab:focus{box-shadow:none;outline:2px solid var(--brand);outline-offset:-2px} - .sb-tabs{display:flex;gap:0;flex-wrap:wrap;background:var(--ink);padding:0 22px;border-bottom:1px solid var(--ink)} - .sb-tab{display:inline-flex;align-items:center;height:40px;padding:0 16px;text-decoration:none; - font-size:10px;letter-spacing:.1em;text-transform:uppercase;font-weight:600; - color:rgba(237,235,230,.75);border-bottom:3px solid transparent} - .sb-tab:hover{color:#fff} - .sb-tab.is-active{color:var(--ink);background:var(--paper);border-bottom-color:var(--v)} - .sb-tab:focus{box-shadow:none;outline:2px solid var(--v);outline-offset:-2px} - - .sb-wrap{padding:22px} - /* Cards in a row share a height so their bottom rules line up; without this - each one ends wherever its own content does and the row looks ragged. */ + .sb-wrap{padding:22px 0 0} + + /* ── Cards ────────────────────────────────────────────────────────── */ + /* Cards in a row share a height so their bottom rules line up; without + this each one ends wherever its own content does and the row is ragged. */ .sb-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:18px;align-items:stretch;margin-bottom:18px} .sb-grid>.sb-card{margin-bottom:0;display:flex;flex-direction:column} .sb-grid>.sb-card>.sb-card__body{flex:1 1 auto} .sb-card{background:#fff;border:1px solid var(--ink);margin:0 0 18px} .sb-card__head{display:flex;align-items:baseline;justify-content:space-between;gap:1rem; - padding:12px 16px;border-bottom:1px solid var(--ink)} - .sb-card__head h2{margin:0;font-size:14px;font-weight:700;letter-spacing:-.01em} + padding:13px 16px;border-bottom:1px solid var(--ink)} + .sb-card__head h2{margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em} .sb-card__body{padding:16px} - .sb-note{font-size:11px;color:var(--ink-60)} + .sb-note{font-size:13px;color:var(--ink-60)} - .sb-label{display:block;font-size:10px;letter-spacing:.1em;text-transform:uppercase;font-weight:600; - color:var(--ink-60);margin:0 0 4px} - .sb-fig{font-size:30px;font-weight:600;line-height:1;letter-spacing:-.02em; - font-family:"Martian Mono",ui-monospace,monospace;font-variant-numeric:tabular-nums} + /* ── Type ─────────────────────────────────────────────────────────── */ + .sb-label{display:block;font-size:13px;font-weight:600;color:var(--ink);margin:0 0 5px} + .sb-fig{font-size:30px;font-weight:600;line-height:1;letter-spacing:-.02em;display:block} + .sb-bullets{margin:0;padding-left:1.3em;list-style:disc} + .sb-bullets li{margin:0 0 6px} + .sb-numbered{margin:0 0 4px;padding-left:1.4em;list-style:decimal} + .sb-numbered>li{margin:0 0 14px} + .sb-numbered>li::marker{font-weight:700} - .sb-chip{display:inline-block;font-size:10px;letter-spacing:.06em;padding:4px 6px 3px; - border:1px solid var(--ink);background:#fff;text-transform:uppercase;font-weight:600} + .sb-chip{display:inline-block;font-size:12px;padding:3px 8px; + border:1px solid var(--rule);background:#fff;font-weight:500} .sb-chip--signup{border-color:var(--c);color:var(--c)} .sb-chip--contact{border-color:var(--a);color:var(--a)} - .sb-btn{display:inline-flex;align-items:center;gap:6px;height:34px;padding:0 14px;cursor:pointer; - font-size:13px;font-weight:700;text-decoration:none;border:1px solid var(--ink); - background:var(--ink);color:var(--paper)} - .sb-btn:hover{background:var(--v);border-color:var(--v);color:#fff} - .sb-btn--ghost{background:transparent;color:inherit;border-color:currentColor;font-weight:600} - .sb-btn--ghost:hover{background:var(--v);border-color:var(--v);color:#fff} - .sb-btn--small{height:28px;padding:0 10px;font-size:12px} + /* ── Buttons ──────────────────────────────────────────────────────── */ + /* Primary is the admin theme colour, so a site running Midnight or Ocean + gets a button that belongs to it. Black read as disabled to half the + people who saw it, and as a third-party widget to the rest. */ + .sendbeam-app .sb-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px; + min-height:36px;padding:0 16px;cursor:pointer;font-size:14px;font-weight:600;text-decoration:none; + border:1px solid var(--brand);border-radius:0;background:var(--brand);color:#fff;line-height:1.2} + .sendbeam-app .sb-btn:hover,.sendbeam-app .sb-btn:focus{background:var(--brand-dark);border-color:var(--brand-dark);color:#fff} + .sendbeam-app .sb-btn:focus{outline:2px solid var(--ink);outline-offset:1px;box-shadow:none} + .sendbeam-app .sb-btn--primary{background:var(--brand);border-color:var(--brand);color:#fff} + /* Secondary: ink outline. It sits beside a primary without competing. */ + .sendbeam-app .sb-btn--ghost{background:transparent;color:var(--ink);border-color:var(--ink);font-weight:500} + .sendbeam-app .sb-btn--ghost:hover,.sendbeam-app .sb-btn--ghost:focus{background:var(--ink);border-color:var(--ink);color:var(--paper)} + /* On the ink band the outline has to be the band\'s own foreground. */ + .sb-head .sb-btn--ghost{color:inherit;border-color:currentColor} + .sb-head .sb-btn--ghost:hover,.sb-head .sb-btn--ghost:focus{background:var(--paper);border-color:var(--paper);color:var(--ink)} + /* Danger: outlined, never filled. A filled red button beside a filled + blue one is a coin toss at a glance. */ + .sendbeam-app .sb-btn--danger{background:transparent;color:var(--v);border-color:var(--v)} + .sendbeam-app .sb-btn--danger:hover,.sendbeam-app .sb-btn--danger:focus{background:var(--v);border-color:var(--v);color:#fff} + .sendbeam-app .sb-btn--small{min-height:30px;padding:0 12px;font-size:13px} + .sendbeam-app .sb-link{background:none;border:0;padding:0;margin:0;cursor:pointer; + color:var(--brand);font-size:14px;text-decoration:underline;font-family:inherit} + .sendbeam-app .sb-link:hover{color:var(--brand-dark)} + + /* ── Fields ───────────────────────────────────────────────────────── */ + /* Label above, always: a label to the left of a field wraps to three + lines on a phone and the field ends up a thumb-width wide. */ + .sendbeam-app .sb-field{display:block;margin:0 0 14px} + .sendbeam-app input[type=text],.sendbeam-app input[type=email],.sendbeam-app input[type=url], + .sendbeam-app input[type=number],.sendbeam-app input[type=password],.sendbeam-app input[type=search], + .sendbeam-app select,.sendbeam-app textarea + {min-height:40px;border:1px solid var(--ink);border-radius:0;background:#fff; + font-size:14px;padding:0 10px;max-width:100%} + .sendbeam-app textarea{padding:8px 10px} + .sendbeam-app input:focus,.sendbeam-app select:focus,.sendbeam-app textarea:focus + {outline:2px solid var(--brand);outline-offset:-2px;box-shadow:none;border-color:var(--brand)} + .sendbeam-app .description{font-size:13px;color:var(--ink-60);margin:4px 0 0} + .sendbeam-app h2{color:var(--ink)} + + /* The Settings API renders label-beside-field; this turns its two columns + into one on every width, which is what the rest of the plugin does. */ + .sendbeam-app .form-table,.sendbeam-app .form-table tbody,.sendbeam-app .form-table tr, + .sendbeam-app .form-table th,.sendbeam-app .form-table td{display:block;width:auto;padding:0} + .sendbeam-app .form-table th{font-size:13px;font-weight:600;color:var(--ink);padding:0 0 5px} + .sendbeam-app .form-table td{padding:0 0 18px} + .sendbeam-app .form-table tr:last-child td{padding-bottom:0} + + /* ── Toggles ──────────────────────────────────────────────────────── */ + /* A switch, because an on/off setting reads as a state rather than as a + choice being made now — which is what a tick box says. */ + .sendbeam-app .sb-toggle{display:flex;gap:10px;align-items:flex-start;line-height:1.45;font-size:14px} + .sendbeam-app .sb-toggle input[type=checkbox]{appearance:none;-webkit-appearance:none; + flex:0 0 auto;width:38px;height:22px;margin:1px 0 0;border:1px solid var(--ink);border-radius:11px; + background:#fff;position:relative;cursor:pointer;transition:background .12s ease} + .sendbeam-app .sb-toggle input[type=checkbox]::before{content:"";position:absolute;top:2px;left:2px; + width:16px;height:16px;border-radius:50%;background:var(--ink);margin:0;transition:transform .12s ease} + .sendbeam-app .sb-toggle input[type=checkbox]:checked{background:var(--brand);border-color:var(--brand)} + .sendbeam-app .sb-toggle input[type=checkbox]:checked::before{background:#fff;transform:translateX(16px)} + .sendbeam-app .sb-toggle input[type=checkbox]:disabled{opacity:.5;cursor:not-allowed} + .sendbeam-app .sb-toggle input[type=checkbox]:focus{outline:2px solid var(--brand);outline-offset:2px;box-shadow:none} + /* ── Tables ───────────────────────────────────────────────────────── */ + .sb-scroll{overflow-x:auto;margin:0 0 10px;max-width:100%} .sb-table{width:100%;border-collapse:collapse;border:1px solid var(--ink);background:#fff} - .sb-table th{text-align:left;font-size:10px;letter-spacing:.1em;text-transform:uppercase; - font-family:"Martian Mono",ui-monospace,monospace;color:var(--ink-60);font-weight:600; + .sb-table th{text-align:left;font-size:13px;color:var(--ink);font-weight:600; padding:9px 12px;border-bottom:1px solid var(--ink)} - .sb-table td{padding:11px 12px;border-bottom:1px solid #e2e0db;vertical-align:middle} + .sb-table td{padding:11px 12px;border-bottom:1px solid var(--hair);vertical-align:middle} .sb-table tr:last-child td{border-bottom:0} - .sb-table code{font-size:11px;background:var(--paper);padding:3px 5px;border:1px solid #d8d6d0} + .sb-table code{font-size:12px;background:var(--paper);padding:3px 5px;border:1px solid var(--rule)} - .sb-steps{list-style:none;margin:0;padding:0;counter-reset:none} - .sb-steps li{display:flex;gap:12px;align-items:flex-start;padding:12px 0;border-bottom:1px solid #e2e0db} + /* The DNS records. Values are fields rather than text, so they select on + focus, scroll rather than wrapping, and copy on click. */ + .sb-dns th{font-size:13px} + .sb-dns .sb-copy-field{width:100%;min-width:14ch;font-size:12px;cursor:pointer} + .sb-dns__value .sb-copy-field{min-width:26ch} + .sendbeam-app .sb-copy-field.is-copied{border-color:var(--m);outline:2px solid var(--m);outline-offset:-2px} + .sb-dns__found{white-space:nowrap} + .sb-verified{margin:0 0 10px;font-weight:600;color:var(--m);display:flex;gap:8px;align-items:center} + .sb-tick{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px; + background:var(--m);color:#fff;font-size:11px;flex:0 0 auto} + .sb-granted{list-style:none;margin:0 0 12px;padding:0;font-size:13px;color:var(--ink-60)} + .sb-granted li{position:relative;padding-left:16px;margin:0 0 4px} + .sb-granted li::before{content:"\2713";position:absolute;left:0;color:var(--m)} + + /* Core list tables: their own look, inside our card, and core\'s phone + collapse left alone — it is the thing that makes them work at 393px. */ + .sendbeam-app .wp-list-table{border:1px solid var(--ink)} + .sendbeam-app .wp-list-table th,.sendbeam-app .wp-list-table td{font-size:14px} + .sendbeam-app .search-box{margin:0 0 12px;display:flex;gap:8px;flex-wrap:wrap} + .sendbeam-app .tablenav{height:auto;margin:10px 0 0;display:flex;gap:8px;align-items:center;flex-wrap:wrap} + .sendbeam-app .tablenav .actions{padding:0;display:flex;gap:8px;flex-wrap:wrap} + + /* ── Steps and the checklist ──────────────────────────────────────── */ + .sb-steps{list-style:none;margin:0;padding:0} + .sb-steps li{display:flex;gap:12px;align-items:flex-start;padding:12px 0;border-bottom:1px solid var(--hair)} .sb-steps li:last-child{border-bottom:0} .sb-steps .sb-num{flex:0 0 auto;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center; - font-size:11px;font-weight:700;background:var(--paper);border:1px solid var(--ink); - font-family:"Martian Mono",ui-monospace,monospace} + font-size:12px;font-weight:700;background:var(--paper);border:1px solid var(--ink)} .sb-steps li.is-done .sb-num{background:var(--m);border-color:var(--m);color:#fff} .sb-steps strong{display:block;font-size:14px} /* Scoped to the note, not to every span in the step: a step now contains a table, buttons and a disclosure, and `.sb-steps span` was greying all of it out and forcing each one onto its own line. */ .sb-steps .sb-step{flex:1 1 auto;min-width:0} - .sb-steps .sb-step__note{display:block;font-size:12px;color:var(--ink-60);margin-top:2px} + .sb-steps .sb-step__note{display:block;font-size:13px;color:var(--ink-60);margin-top:3px} .sb-step__panel{margin-top:10px} .sb-step__panel>*:first-child{margin-top:0} .sb-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:10px 0 6px} .sb-actions form{margin:0} - /* The sending domain. The value column is the one people copy, so it gets - the room; the whole table scrolls sideways rather than squeezing a TXT - record into three words per line on a phone. */ - .sb-scroll{overflow-x:auto;margin:0 0 10px} - .sb-dns td code{display:inline-block;max-width:46ch;overflow-wrap:anywhere} - .sb-dns__value{white-space:normal} - .sb-verified{margin:0 0 8px;font-weight:700;color:var(--m);display:flex;gap:6px;align-items:center} - .sb-tick{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px; - background:var(--m);color:#fff;font-size:11px;flex:0 0 auto} - .sb-granted{list-style:none;margin:0 0 12px;padding:0;font-size:12px;color:var(--ink-60)} - .sb-granted li{position:relative;padding-left:14px;margin:0 0 3px} - .sb-granted li::before{content:"\2713";position:absolute;left:0;color:var(--m)} + /* ── The wizard ───────────────────────────────────────────────────── */ + .sb-rail{display:flex;gap:0;list-style:none;margin:0;padding:0;background:#fff; + border:1px solid var(--ink);border-top:0;flex-wrap:wrap} + .sb-rail__step{display:flex;gap:9px;align-items:center;padding:12px 16px;flex:1 1 auto;min-width:0; + font-size:13px;color:var(--ink-60);border-right:1px solid var(--hair)} + .sb-rail__step:last-child{border-right:0} + .sb-rail__num{flex:0 0 auto;width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center; + font-size:12px;font-weight:700;border:1px solid currentColor} + .sb-rail__label{overflow-wrap:anywhere} + .sb-rail__step.is-done{color:var(--m)} + .sb-rail__step.is-done .sb-rail__num{background:var(--m);border-color:var(--m);color:#fff} + .sb-rail__step.is-current{color:var(--ink);font-weight:600;background:var(--paper)} + .sb-rail__step.is-current .sb-rail__num{background:var(--brand);border-color:var(--brand);color:#fff} + .sb-wizard__count{color:rgba(237,235,230,.75)} + .sb-wizard__foot{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:0 0 10px} + .sb-wizard__note{margin:0} + /* ── Results and details ──────────────────────────────────────────── */ + .sb-result{border:1px solid var(--ink);border-left-width:4px;background:#fff;padding:14px 16px;margin:0 0 16px} + .sb-result--ok{border-left-color:var(--m)} + .sb-result--bad{border-left-color:var(--v)} + .sb-result__title{margin:0 0 8px;font-size:16px;font-weight:700;display:flex;gap:8px;align-items:center} + .sb-result p{margin:0 0 10px} + .sb-result p:last-child{margin-bottom:0} + .sb-bundle{background:var(--paper);border:1px solid var(--rule);padding:12px;margin:10px 0; + font-size:12px;line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere;max-height:22em;overflow:auto} + .sb-paste>summary{cursor:pointer;font-size:13px;color:var(--ink-60);padding:4px 0} + .sb-paste>summary:hover{color:var(--ink)} + + /* ── Confirmation, scopes, messages ───────────────────────────────── */ /* Inline confirmation. With no script the box is simply already open and the plain button beside it never appears, so the form still submits. */ .sb-confirm{margin:0} - .sb-confirm__box{border-left:4px solid var(--v);background:var(--paper);padding:10px 12px} - .sb-confirm__box p{margin:0 0 8px} + .sb-confirm__box{border-left:4px solid var(--v);background:var(--paper);padding:12px 14px;margin-top:10px} + .sb-confirm__box p{margin:0 0 10px} - .sb-msg{padding:10px 14px;border-left:4px solid var(--ink-60);background:#fff;border-top:1px solid var(--ink); + .sb-msg{padding:11px 14px;border-left:4px solid var(--ink-60);background:#fff;border-top:1px solid var(--ink); border-right:1px solid var(--ink);border-bottom:1px solid var(--ink);margin:0 0 14px; display:flex;gap:12px;align-items:baseline;flex-wrap:wrap} .sb-msg--ok{border-left-color:var(--m)} .sb-msg--warn{border-left-color:var(--a)} .sb-msg--bad{border-left-color:var(--v)} - .sendbeam-app .form-table th{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-60); - font-family:"Martian Mono",ui-monospace,monospace;font-weight:600;padding:16px 10px 16px 0} - .sendbeam-app .form-table td{padding:12px 10px} - .sendbeam-app input[type=text],.sendbeam-app input[type=number],.sendbeam-app input[type=password], - .sendbeam-app select{border:1px solid var(--ink);border-radius:0;background:#fff} - .sendbeam-app input:focus,.sendbeam-app select:focus{outline:2px solid var(--c);outline-offset:-2px;box-shadow:none} - .sendbeam-app .description{font-size:12px;color:var(--ink-60)} - .sendbeam-app h2{color:var(--ink)} + .sb-scopes{list-style:none;margin:0 0 14px;padding:0} + .sb-scopes li{margin:0 0 8px} + .sb-scope{align-items:flex-start;line-height:1.45} + .sb-scope input[type=checkbox]{margin:2px 0 0;flex:0 0 auto;border-color:var(--ink);border-radius:0;min-height:0} + .sb-scope input[type=checkbox]:checked{background:#fff} + .sb-scope input[type=checkbox]:focus{box-shadow:0 0 0 1px var(--ink)} + .sb-scope .sb-note{margin-left:4px} + .sb-inline{display:inline-flex;align-items:center;gap:8px;font-size:14px} + .sendbeam-app [hidden]{display:none!important} + /* ── Pop-up rules ─────────────────────────────────────────────────── */ .sb-rule{border:1px solid var(--ink);background:var(--paper);padding:14px 16px;margin:0 0 14px} - .sb-rule legend{padding:0 6px;background:var(--ink);color:var(--paper);font-size:10px;letter-spacing:.1em; - text-transform:uppercase;font-weight:700} + .sb-rule legend{padding:0 6px;background:var(--ink);color:var(--paper);font-size:12px;font-weight:600} .sb-rule__grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;align-items:end} .sb-rule__grid label{display:block} .sb-rule__grid select,.sb-rule__grid input[type=text]{width:100%;max-width:100%} .sb-rule__foot{display:flex;align-items:center;justify-content:space-between;gap:12px; - margin-top:14px;padding-top:12px;border-top:1px solid #d8d6d0} - .sb-inline{display:inline-flex;align-items:center;gap:6px;font-size:13px} - /* Connect: the permission list. The plugin colour on the native box, the - box aligned to the first line of a label that may wrap on a phone. */ - .sb-scopes{list-style:none;margin:0 0 14px;padding:0} - .sb-scopes li{margin:0 0 8px} - .sb-scope{align-items:flex-start;line-height:1.4} - .sb-scope input[type=checkbox]{margin:2px 0 0;flex:0 0 auto;border-color:#121212;border-radius:0} - .sb-scope input[type=checkbox]:checked::before{content:url("data:image/svg+xml;utf8,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 20 20%27%3E%3Cpath d=%27M14.83 4.89l1.34.94-5.81 8.38H9.02L5.78 9.67l1.34-1.25 2.57 2.4z%27 fill=%27%23121212%27/%3E%3C/svg%3E")} - .sb-scope input[type=checkbox]:checked,.sb-scope input[type=checkbox]:disabled{background:#fff;opacity:1} - .sb-scope input[type=checkbox]:disabled:checked::before{opacity:1} - .sb-scope input[type=checkbox]:focus{box-shadow:0 0 0 1px #121212} - .sb-scope .sb-note{margin-left:4px} - .sendbeam-app [hidden]{display:none!important} + margin-top:14px;padding-top:12px;border-top:1px solid var(--rule)} - .sb-doc h3{font-size:14px;margin:0 0 6px} + /* ── Help ─────────────────────────────────────────────────────────── */ + .sb-doc h3{font-size:15px;margin:0 0 6px} .sb-doc p{margin:0 0 10px;max-width:62ch} .sb-doc ul{margin:0 0 10px 1.1em;list-style:disc} .sb-doc li{margin:4px 0} - .sb-doc code{font-size:12px;background:var(--paper);padding:2px 5px;border:1px solid #d8d6d0} + .sb-doc code{font-size:12px;background:var(--paper);padding:2px 5px;border:1px solid var(--rule)} .sb-doc__row{display:flex;gap:12px;align-items:center;justify-content:space-between; - padding:9px 0;border-bottom:1px solid #e2e0db;flex-wrap:wrap} + padding:9px 0;border-bottom:1px solid var(--hair);flex-wrap:wrap} .sb-doc__row:last-child{border-bottom:0} - .sb-doc__row code{flex:1 1 22em} + .sb-doc__row code{flex:1 1 22em;min-width:0;overflow-wrap:anywhere} - @media (max-width:782px){ .sb-head{padding:14px} .sb-tabs{padding:0 8px} .sb-wrap{padding:14px} } + /* ── Phones ───────────────────────────────────────────────────────── */ + @media (max-width:782px){ + .sendbeam-app{margin:10px} + .sb-head{padding:14px} + .sb-mark{margin-right:36px} + .sb-wrap{padding-top:16px} + .sb-card__body{padding:14px} + .sb-rail__step{flex:1 1 100%;border-right:0;border-bottom:1px solid var(--hair);padding:10px 14px} + .sb-rail__step:last-child{border-bottom:0} + .sb-wizard__foot .sb-btn{flex:1 1 100%} + .sb-doc__row code{flex:1 1 100%} + } '; } diff --git a/includes/connect.php b/includes/connect.php index e228b6f..ee56304 100644 --- a/includes/connect.php +++ b/includes/connect.php @@ -929,7 +929,7 @@ function sendbeam_connect_panel() { } echo ''; printf( - '

    ', + '

    ', esc_html__( 'Connect SendBeam', 'sendbeam' ) ); echo ''; diff --git a/includes/screens.php b/includes/screens.php index 3c0f224..c808139 100644 --- a/includes/screens.php +++ b/includes/screens.php @@ -23,9 +23,17 @@ function sendbeam_form_open( $tab ) { printf( '', esc_attr( $tab ) ); } -/** Close a settings form. */ +/** + * Close a settings form. + * + * The plugin's own button rather than `submit_button()`: core's renders a + * `.button-primary`, and a core blue pill in the middle of a screen built out + * of square ink-ruled cards is the one element that looks pasted in. It is + * the admin theme colour either way — this one just wears the rest of the + * plugin's shape. + */ function sendbeam_form_close() { - submit_button( __( 'Save changes', 'sendbeam' ) ); + printf( '

    ', esc_html__( 'Save changes', 'sendbeam' ) ); echo ''; } @@ -533,7 +541,7 @@ function sendbeam_overview_mail_panel( $status, $connected ) { echo '
    '; wp_nonce_field( 'sendbeam_mail_switch_on' ); echo ''; - printf( '', esc_html__( 'Switch on', 'sendbeam' ) ); + printf( '', esc_html__( 'Switch on', 'sendbeam' ) ); echo '
    '; echo '
    '; echo '

    ' . esc_html( @@ -626,12 +634,12 @@ function sendbeam_connect_connected_panel( $status = null ) { esc_html__( 'Reconnect', 'sendbeam' ) ); printf( - '', + '', esc_html__( 'Disconnect', 'sendbeam' ) ); echo '

    '; echo '

    ' . esc_html__( 'Disconnect this site? Its key is revoked. Your list, form and sending domain stay in SendBeam. Forms already on your pages stop loading until you connect again.', 'sendbeam' ) . '

    '; - printf( ' ', esc_html__( 'Yes, disconnect', 'sendbeam' ) ); + printf( ' ', esc_html__( 'Yes, disconnect', 'sendbeam' ) ); printf( '', esc_html__( 'Cancel', 'sendbeam' ) ); echo '
    '; @@ -764,7 +772,7 @@ function sendbeam_screen_forms() { echo ''; echo ''; printf( - '

    ', + '

    ', checked( ! empty( $s['style_bare'] ), true, false ), esc_html__( 'Hide the form name and subtitle inside the embed (your page already has a heading)', 'sendbeam' ) ); @@ -818,7 +826,7 @@ function sendbeam_screen_form_plugins( $lists ) { sendbeam_card_open( __( 'Form plugins', 'sendbeam' ) ); echo '

    ' . esc_html__( 'Send the people who fill in forms built with another plugin to SendBeam. Each form is switched on where that plugin keeps its settings, and sends someone only when they ticked the consent field you name — or every submission, when you mark the form as a signup form.', 'sendbeam' ) . '

    '; - echo ''; + echo '
    '; echo ''; echo ''; foreach ( $rows as $key => $row ) { @@ -829,7 +837,7 @@ function sendbeam_screen_form_plugins( $lists ) { esc_html( $row[1] ) ); } - echo '
    ' . esc_html__( 'Form plugin', 'sendbeam' ) . '' . esc_html__( 'On this site', 'sendbeam' ) . '' . esc_html__( 'Where to set it up', 'sendbeam' ) . '
    '; + echo ''; echo '

    ' . esc_html__( 'The key needs Contacts (read and write), Lists (write) to add people to a list, and Tags (read and write) when a form adds a tag. Each person\'s source in SendBeam names the form plugin they came from.', 'sendbeam' ) . '

    '; if ( $hosts['fluentforms'] && function_exists( 'sendbeam_fluentforms_forms' ) ) { @@ -868,7 +876,7 @@ function sendbeam_screen_fluentforms( $lists ) { echo '
    '; printf( - '

    ', + '

    ', esc_attr( $name ), checked( $config['enabled'], 1, false ), esc_html( '' !== $title ? $title : sprintf( /* translators: %d: form ID */ __( 'Form %d', 'sendbeam' ), $form_id ) ) @@ -889,7 +897,7 @@ function sendbeam_screen_fluentforms( $lists ) { ); } printf( - '

    ', + '

    ', esc_attr( $name ), checked( $config['consent'], 'signup', false ), esc_html__( 'Everyone who submits this form is asking to subscribe, so no consent field is needed', 'sendbeam' ) @@ -911,7 +919,7 @@ function sendbeam_screen_fluentforms( $lists ) { } echo '

    ' . esc_html__( 'Field names are the names shown in each field\'s settings in Fluent Forms. A name field is written as names.first_name and names.last_name.', 'sendbeam' ) . '

    '; - echo '

    '; + echo '

    '; echo ''; } @@ -946,7 +954,7 @@ function sendbeam_screen_sync( $lists ) { echo '

    ' . esc_html__( 'Ask on', 'sendbeam' ) . '

    '; foreach ( $sources as $key => $meta ) { printf( - '

    %5$s

    ', + '

    ', esc_attr( $key ), checked( ! empty( $sync[ $key ] ), true, false ), $meta[1] ? '' : 'disabled', @@ -975,14 +983,14 @@ function sendbeam_screen_sync( $lists ) { esc_attr( sendbeam_sync_label() ) ); - echo '

    '; + echo '

    '; echo ''; sendbeam_card_close(); $log = get_option( SENDBEAM_SYNC_LOG, array() ); if ( is_array( $log ) && $log ) { sendbeam_card_open( __( 'Recent subscriptions', 'sendbeam' ) ); - echo ''; + echo '
    '; echo ''; echo ''; echo ''; @@ -994,7 +1002,7 @@ function sendbeam_screen_sync( $lists ) { echo ''; echo ''; } - echo '
    ' . esc_html__( 'When', 'sendbeam' ) . '' . esc_html__( 'Who', 'sendbeam' ) . '' . esc_html__( 'From', 'sendbeam' ) . '' . esc_html__( 'Result', 'sendbeam' ) . '
    ' . ( $row['ok'] ? esc_html__( 'Subscribed', 'sendbeam' ) : esc_html( __( 'Failed', 'sendbeam' ) . ' — ' . $row['note'] ) ) . '
    '; + echo ''; sendbeam_card_close(); } } @@ -1022,7 +1030,7 @@ function sendbeam_screen_popup() { echo ''; echo '

    '; - echo '

    '; + echo '

    '; echo ''; // The blank row the "add" button clones. __i__ is swapped for the index. @@ -1143,10 +1151,11 @@ function sendbeam_popup_row( $i, $rule ) { placeholder="" class="regular-text" /> -