` of Type / Host / Value with read-only fields that copy when clicked, a tick or "not found yet" per record, "DNS changes can take up to 24 hours", and three aggregate states instead of two: verified, pending (some records live, with a count) and not found. Pending and not-found looked identical before, and only one of them has work left in it.
+- **The test email is an email.** It was two sentences of plain text. It is now a 600px table-based HTML message with a plain-text alternative, no images and no upsell, carrying the From name and address actually used, the sending domain and whether it is verified, the workspace, the plugin version and the time in the site's own timezone, then what happens now and one link to the email log.
+- **Its result appears in the page, in WP Mail SMTP's shape**, replacing the form rather than becoming a notice: a success card with **Send another**, or a failure card with what went wrong, what it means, what to do — each mapped from the status code rather than dumping the API's own words — and a collapsible **Details for support** block holding the WordPress, PHP and plugin versions, where this site's key is kept (never the key), the domain state, the HTTP status and the raw error. It is captured at the moment the send fails and parked in a transient keyed to that administrator, because a raw error and a version list do not belong in an address bar, a server log or somebody's browser history.
+- **Three Site Health tests and a debug section.** `sendbeam-key` (works / rejected / unreachable / limited), `sendbeam-domain` (verified?) and `sendbeam-mail`, which reports **critical** when site email is switched on behind an unverified domain — a site quietly sending its password resets from a domain no mailbox provider can check is worse off than one not using the feature. All three are `direct` tests reading the same minute-old cache the Overview reads, because a Site Health page that makes three HTTP requests is a Site Health page that times out. `debug_information` gains a SendBeam section, and the Help page prints the same values as one block with **Copy for support**.
+- **Every message the plugin prints is an admin notice now.** Each screen used to echo its own `` somewhere in the middle of its own markup, so the answer to "did that save?" appeared in a different place on every screen and in the plugin's styling rather than WordPress's. They go through `wp_admin_notice()` (with a fallback, because that arrived in 6.4 and this plugin supports 6.1), in core's classes, dismissible, and only on SendBeam's own screens. The one exception is the setup notice, which is on the Dashboard and nowhere else, opens the wizard, and goes for good when it is dismissed or the site is set up.
+- **A Help page** replaces the Docs tab: documentation links, system status with **Copy for support**, who to ask (hello@sendbeam.io, the WordPress.org forum, GitHub issues), the shortcodes and the permissions table.
+- **The design system loses four foreign signals and keeps the rest.** Labels were 10px uppercase mono with 0.1em tracking — nothing else in the eighteen-plugin study styled anything that way. They are sentence case at 13px now, and mono is kept for the things people copy: values, code and figures. Primary buttons use `var(--wp-admin-theme-color)` with white text rather than black, so a site running Midnight or Ocean gets a button that belongs to it; secondary is an ink outline and danger 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, every on/off setting is a switch, `.sendbeam-app` has the same margin on both sides, and core's `button-primary` appears nowhere in the plugin's own markup — only inside a core notice, where a brand-styled button is the thing that looks pasted in.
+- **Every remaining `.sb-table` sits in the `.sb-scroll` wrapper the plugin already owned**, and that wrapper gained `contain: inline-size`, without which a table wider than the screen scrolls inside its box *and* widens the page anyway in a mobile browser — which is the exact failure the class exists to prevent.
+
+- **"SendBeam's shared address" was being said about the customer's own domain.** The shared-host test was "anywhere under the app's domain", so any site whose sending domain is a subdomain of `sendbeam.io` — every site on the staging host, and any customer using one — was told its own verified domain was SendBeam's shared address. `shared` now means an exact match on `post.` or `mail.`, the two hosts the platform actually sends shared mail from. Nothing else under that domain is shared, and a domain that is the site's own verified sending domain never reaches the test at all, because that is settled first and settled for good, whatever it happens to be a subdomain of.
+- **The test email carried the same contradiction, and the owner read it on a phone.** "From address ws-…@post.sendbeam.io" sat two rows above "Sending domain wp-test.sendbeam.io — verified", under a headline saying the site could send email through SendBeam. Every row of it is now derived from `sendbeam_effective_sender()`: the headline qualifies itself (`… from yourdomain.com` / `… (from the shared address for now)`), the From row says what kind of address it is, a new **Signed by** row names the domain that actually authenticated the message so a reader can compare the two at a glance, and the sending-domain row distinguishes "verified and in use" from "verified, but not in use yet" and "not verified yet". Where something is left to do, a **Next step** block sits above "What happens now" with the button that does it — press Send from your domain, or add the DNS records. The in-page result mirrors it: a successful send from the shared address is a success card plus an amber note, which is how WP Mail SMTP words the same case.
+- **The test email now declares its colour scheme.** Apple Mail inverts a message that says nothing about dark mode, which turned the ink band into paper and every address in the table into a blue auto-detected link. `color-scheme` and `supported-color-schemes` are declared, every cell states its own `bgcolor` and colour, and `a[x-apple-data-detectors]` is put back to the table's own styling. Below 480px the label sits above its value rather than taking a quarter of a 380px screen and wrapping a URL mid-word.
+- The three workspace figures stay in a row of three on a phone — stacked, three single digits took half the card — and only break below 340px. The recent-email rows swap the site's date format for a short one (or the time, for today), the address truncates with an ellipsis, and the result stays whole and right-aligned instead of wrapping onto a line of its own.
+- **The DNS records are readable on a phone.** Four columns in 393px left the host and the value about ninety pixels each — "resend._dc" — on the one screen whose entire job is reading them accurately. Below 782px each record becomes a block: type and verdict on one line, then host, then value, each full width and free to wrap, in a textarea rather than an input because an input cannot wrap at any width. On desktop the value column takes the space Type and Found do not need, and the field's height comes from its line box rather than being pinned — a pinned height on a 12px mono field was clipping its own descenders, so the underscore in `resend._domainkey` simply vanished.
+- **One connected card, however the key arrived.** A site with a pasted key was shown "Connected" in the header band and **Connect this site** in the card underneath — the plugin arguing with itself about its own state, which is what the owner saw on the phone. There is one card now: what it is connected to, a muted line saying how ("via Connect" / "using an API key"), and the one thing a connected card is for. **Reconnect** joins **Disconnect** only where there is a connection to re-make; a pasted key has none. No primary button, and no sales sentence — replacing a key is a settings job and lives under Settings.
+- **The upgrade to Connect is offered where a pasted key actually falls short**, and nowhere else: the sending-domain step when `domain_state` is `no_site` or `no_permission`, worded "Switch to one-click Connect" rather than "Reconnect with more permissions", which is not what a pasted key would be doing. It carries to the site-email step queued behind it, because the way out is the same link and offering it only on the step somebody is not standing on is one hop too many.
+- **Disconnecting a pasted key no longer revokes it.** `POST /connect/disconnect` revokes the calling key, and a key somebody pasted was minted for whatever they minted it for — very possibly another site. It is forgotten here, left alone there, and the confirmation and the notice both say which of the two happened.
+- **"No idea" is no longer said as "no".** A pasted key records no permissions, so `sendbeam_connect_granted()` answered false for all of them and the site-email step announced that the key "was not given permission to send your site's email" — a claim about somebody's key that this site has no way of making. `sendbeam_connect_permissions_known()` tells the three cases apart: the step stops claiming, the one-click **Switch on** is offered rather than hidden, and SendBeam decides on the first message.
+- **Run the setup guide again**, on the Help page. Every plugin in the field study that has a wizard keeps one reachable. It resets where this person got to and touches nothing else — `sendbeam_setup_done` is the site's answer to "has anybody set this up?", and re-reading the guide is not un-setting-up a site.
+- **The Overview could tell a site owner two true things that added up to a lie.** The sending-domain step said "harbourlane.co.uk is verified. Email from this site will be sent from your own domain" while the From address in the site's own settings was still `ws-…@post.sendbeam.io` — SendBeam's shared address. Both sentences were right. Together they were wrong, and nothing on the screen distinguished them. `sendbeam_effective_sender()` is now the single answer to "what does this site send as?", classifying the address as `own_domain`, `shared`, `other` or `none` — derived from the app host rather than a hardcoded list, so a self-hosted SendBeam classifies its own shared addresses correctly. Step 2 says only that the domain is verified. Step 4 says what is really happening, is amber rather than ticked when the site is sending as SendBeam from a verified domain or from a domain nothing has verified, and carries a one-press **Send from yourdomain.com**. The connection line names the kind of address, not just the address.
+- Enabling site email once the domain verifies now puts the From address on that domain — the workspace sender when it is already there, `hello@` when it is not — rather than filling in the shared address blind. A shared address Connect itself wrote earlier is corrected when the domain lands; an address the owner typed is never touched.
+
+- **The email log is a table, not twenty rows in an option.** `sendbeam_mail_log` held the last twenty attempts in wp_options: a reasonable shape for "did my test send work?" and a useless one for a real site, where a shop doing thirty order emails an hour lost the morning by lunchtime, the list table could page through at most one screen, and every write rewrote and re-autoloaded the whole array. `{$wpdb->prefix}sendbeam_mail_log` now takes one row per message, created by dbDelta on activation and behind a `sendbeam_db_version` check on `admin_init` — because a plugin updated by uploading a zip over the top fires no activation hook, and a site whose table was never made would just fail quietly on every send. Per-site on multisite, since the prefix is.
+- The screen it feeds grew up with it: search across the address, the subject and the reason a message failed; All / Sent / Server mailer / Failed views with a count on each, and a view nothing landed in is not a link to an empty screen; sortable by date and by result; a per-page Screen Option; bulk delete. A **Sent by** column names the plugin that asked for the message, worked out from the backtrace because `wp_mail()` carries no caller — read once per send, for one column, never for a decision.
+- **Retention is the site owner's choice**: 7, 30 (the default) or 90 days, or for ever, pruned by a daily `sendbeam_mail_log_prune` event that activation schedules and deactivation clears. On top of it a hard cap of 20,000 rows, oldest first, whatever the setting says — "for ever" is a promise about time, not about disk space, on hosting that is very often not the owner's.
+- **Clear the log** is a button on the Site email screen behind its own closed confirmation, and deliberately **not** a bulk action: "Delete" and "Delete all" one mis-click apart in the same dropdown is how somebody loses the log they came to read.
+- Existing entries migrate on the first page load after updating, newest first with their original timestamps — a log claiming every message arrived at the moment of the upgrade is worse than no log. The option is deleted as part of the move, so a second run finds nothing and cannot duplicate anything. Uninstall drops the table and the version option.
+- Bodies are never stored, in any column. A log exists to answer "did it go, and if not why"; keeping the contents of every password reset a site has ever sent is a liability nobody asked for.
+- **The Pop-ups screen was the one place that looked like a different product.** Each rule was a `` on the paper grey with a black `` tag, while every other screen in the plugin is white cards with ink rules. A rule is now that same card: a header carrying "Pop-up 1", the Active switch and Remove, and a body of label-above fields. Numbered because the order is the rule — the first pop-up that matches a page is the one that opens — and the cards renumber themselves after an add or a remove, so the numbers cannot start lying. Eyebrow and Button label were half a line out from each other, because the grid bottom-aligned fields while one of them carried helper text; they are a two-column row with helper text under each and the grid aligns labels at the top. Every field name and value is unchanged, so what saves is exactly what saved before.
+- **Something red flashed under Disconnect on every refresh.** The confirmation shipped open in the markup so a browser with no JavaScript could still submit it, and was hidden by script on load — so it drew, then vanished, on every single render of the Overview. It is a native `` now: the summary is the Disconnect button, the box it opens holds the confirmation and the form, it is shut until somebody presses it, and pressing it again is the way out. No script touches it, and it works with JavaScript off. Note that Chrome exposes a `` as a disclosure rather than as a button — more accurate, since it carries its own expanded state, but a change from the `` it was.
+- The same fault, smaller, on the Site email screen: the From name, From address and fallback rows were drawn and then hidden on load whenever site email was off. They arrive hidden from the server now, and the switch only takes over when somebody actually moves it.
+
+- **Disconnect did not disconnect.** `register_setting()` hangs the form's sanitiser on `sanitize_option_sendbeam_settings`, so **every** `update_option( 'sendbeam_settings', … )` runs the rules written for a posted form — including the writes the plugin makes on its own behalf. Disconnect wrote an empty API key, the rule "a blank key field keeps the saved key" put the old one straight back, and the site stayed connected. The owner pressed the button twice.
+- The same trap had two quieter faces. A posted form names its tab, so only that tab's keys are touched; a programmatic array names none, so every key counted as posted — which meant the rule that releases `mail_enabled`, `mail_from_name` and `mail_from_email` from `sendbeam_connect_filled` fired on **every** programmatic write, undoing what Connect had just recorded, and `mail_enabled` was re-derived from "is the box in the array" on writes that simply did not mention it.
+- Programmatic paths now go through `sendbeam_write_settings()`, which stores the array as-is — it is already what the plugin means — and still does the one piece of housekeeping that applies, forgetting what was cached under a key that changed. All four writers (Disconnect, the Connect exchange, the site-email switch-on and the workspace-move release) use it, and a test asserts that they are still the only four. `sendbeam_settings` is the only registered option, so it is the only place this could happen.
+- The test stubs ran no sanitiser on `update_option()`, which is why this passed every test while failing on a real site. They now run whatever `register_setting()` registered, exactly as WordPress does; fixtures seed values directly instead.
+
+### Bugs a live install found
+
+- The list-table classes extended `WP_List_Table` at plugin-load time. Core does not load that class until wp-admin is well underway, so Forms, Audience and Site email were fatal errors on a real site while the smoke tests passed — the stubs define the class before the plugin loads. They are required when a screen asks for them. The tests gained the assertion that would have caught it, and a second one asserting that every hook this plugin registers names a function that exists.
+- The wizard was registered with an empty parent, which routes correctly and then leaves `get_admin_page_title()` with nothing to find: WordPress hands a null to `strip_tags()`, which is a deprecation notice on PHP 8 and a browser tab reading "— WordPress". Its parent is `options.php`, which is in no menu.
+- The Connect consent checkboxes rendered ticked and looked empty. Core fills the box with the admin theme colour and draws a white tick on it; forcing the background white left a white tick on white.
+
+### What a QA sweep found
+
+- **Pressing Save on one card of the Forms screen emptied the other.** Forms is one tab with two cards and two Save buttons, and the sanitiser grouped its fields by tab: whichever card you did not press arrived missing from `$_POST` and was written as empty. Saving Appearance cleared `contact_form`, `[sendbeam_contact]` renders nothing without it, and a published contact page went to an empty box for every visitor with "Settings saved." on screen and nothing in the log. Field groups are per form now, not per tab.
+
+- **Site email could be switched on with no key, and three screens then disagreed about what was happening.** Disconnecting leaves the switch on, which is right — reconnecting should not make the owner hunt for it again — and with no key nothing goes near SendBeam: every message leaves by the server's own mailer exactly as before. The screens said otherwise. The test email told the owner to tick a box that was already ticked and never mentioned a key; Site Health raised a **critical** alarm about email being sent from an unverified domain, about email that was not being sent. There is one helper answering why site email is not running — the switch, or the key — the ticked box says which where it is ticked, the test email names the key, and Site Health reports a recommendation to connect the site instead of a red flag about a thing that is not happening.
+
+- **The test email described the message the site asked for, not the one that arrived.** SendBeam does not refuse a message whose From sits on an unverified domain — it accepts it and substitutes the workspace's own sender. So a test email arrived from `ws-…@mail.sendbeam.io`, signed `d=mail.sendbeam.io`, carrying a card that said "From address: hello@wp-test.sendbeam.io", "Signed by: wp-test.sendbeam.io" and "SendBeam refuses messages from it". Three claims, all contradicted by the headers of the message printing them. `sendbeam_effective_sender()` now works out the address that actually goes out, the domain that actually signs it and whether those differ from what was asked for; the From row names the substitution, **Signed by** is the real signer, and the next step says SendBeam sent it under its own address rather than that it refused to.
+
+- **"SendBeam could not be reached", straight after SendBeam answered.** `domain_state: unavailable` wears two opposite meanings — the plugin's, "the request failed", and SendBeam's, "I could not set that domain up, and here is why". Only the first was in the sentence, so a site that had just connected successfully was told SendBeam was unreachable while its cached status held `ok: true` and "That domain is already registered" in two places. The step prints the reason SendBeam gave when the answer came from SendBeam, and keeps the unreachable wording for the case it was written for.
+
+- **The setup guide ticked steps nobody had done.** The rail ticked every step whose number was below the current one, and **Skip this step** is on every step — so opening step 3 on a site with no API key showed "✓ Connect · ✓ Sending domain" above a body reading "This step needs a connected site. Go back to step 1", while the Overview's own checklist said neither was done. The rail reads the same answer the checklist does.
+
+- **"A SendBeam pop-up is live on the site" with every rule switched off.** The checklist asked whether any pop-up rule had ever been saved. A rule that is unticked, or has no form chosen, puts nothing on the site — the front end serves no loader at all — so the step ticked itself on evidence the visitor could not see. There is one helper for "could this actually show somebody a pop-up", and the checklist uses it.
+
+- **`[sendbeam_contact]` takes an `id` now**, because the Forms screen offered a Copy button on every contact row and told the owner to "place it by shortcode". There was one shortcode for all of them and it always rendered the default, so copying the one beside "Wholesale enquiry" put the Contact-us form on the page. Every row names its own form; a bare `[sendbeam_contact]` still renders the default, so nothing already on a page changes.
+
+- **"Connected by: A pasted key" on a site with no key.** The Help page's system status — the block a site owner pastes into a support request, so the first thing support reads — answered a two-way ternary about how the key arrived without a third case for there being no key, directly under "API key: Not set". The sending-domain state was blank on the same block. Both say what is true now, and no field in that block is ever empty.
+- **Forms and Audience blamed the permissions of a key that did not exist.** Both screens branch on a `null` that means either "the key was refused" or "there is no key", and read only the first: a disconnected site was told "Your forms cannot be read with the current key. Give it the Forms (read) permission in SendBeam", under a header band already saying "Not connected". They say the site is not connected, and where to connect it.
+
+- **"Remove the saved key" on Settings → Advanced left a Connect-issued key live in the workspace, and said nothing.** The Overview's Disconnect revokes such a key at SendBeam and its confirmation says so; the Advanced tab's checkbox is a second, quieter door to the same place and it cleared the option and stopped. The owner who tidied up there was left holding a live key for a site that no longer exists as far as they are concerned. Both doors go through one function now, and the field says which of the two things removing this particular key will do — revoke it, or merely forget it — before it is removed.
+
+- **Reconnecting destroyed the sending domain the site already had.** The consent page prefilled SEND FROM from `site_url` on every run, so pressing Reconnect for any other reason — more permissions, a changed workspace, a key rotation — re-set the sending domain to this site's own host and took the existing one out of the workspace, along with the DNS records the owner may have been half-way through entering. Nothing warned them; the records were simply gone and the hourly re-check unscheduled. A reconnect now passes the domain the site already has, read from the status body, so the consent page offers it back. The one link whose purpose is choosing a different one — "Sending from the wrong domain?" — deliberately passes nothing, and neither does a first connect.
+
+- **The longest DNS host was cut off inside the field you are told to click.** The wrapping rule lived only inside the ≤782px media query, so the phone case that had been complained about was fixed and the desktop one was not: at 1280px the Host column is about 282px and `resend._domainkey.mail.` does not fit in it. Click-to-copy still copied the whole value, but somebody comparing what they pasted into their registrar against what is on screen could not see the end of it. The field wraps at every width now, and keeps `overflow: auto` so a browser with no JavaScript scrolls to the rest rather than hiding it.
+
+- **Check now comes back to the screen it was pressed on.** The check is offered on the Overview and on Settings → Sending domain and always landed on the Overview, so somebody working through the DNS records was moved to a different screen to be told the result and had to navigate back to carry on.
+- **The page about the sending domain said less than the checklist did.** Step 2 on the Overview carried the reason SendBeam gave; Settings → Sending domain dropped it, on the screen dedicated to the subject. There is one sentence for "this site has no sending domain" now, and where SendBeam's own note already says what to do, the plugin stops appending a second instruction naming a different SendBeam screen.
+
+- **Every "you do not have permission" was served as HTTP 500.** `wp_die()` with no status argument defaults to a server error, so all sixteen of the plugin's admin-post actions answered an Editor's POST with a 500 — a correct refusal, logged everywhere as a fault in the plugin. They answer 403. (The nonce refusals were already right: `check_admin_referer()` sends 403 itself.)
+
+- **The permissions list named this site's host, not the domain that was chosen.** The domain scope's label interpolates the host the consent page was asked about, which is right on a consent page and a description of the request rather than the outcome on a connected site: a site connected with SEND FROM set to `mail.harbourlane.co.uk` read "Set up this site's sending domain (harbourlane.co.uk)" ever after. The connected card names the domain the workspace actually has.
+
+- **A hiding rule that could be out-specified was not hiding anything.** `.sendbeam-app .is-hidden` is (0,2,0) and the Settings API row reset `.sendbeam-app .form-table tr` is (0,2,1), so on Site email the From name, From address and fallback rows were drawn whether the switch was on or off — the exact thing the server-rendered pattern exists to prevent. It carries `!important` now, for the same reason `[hidden]` beside it always has, and the tests parse the stylesheet and compare specificities rather than looking for one string, so the next rule that out-ranks it fails there instead of on a screen.
+- The phone tap sizes cover the rest of the controls: small buttons (Copy, Remove, Choose, Check now, Set up DNS automatically, Reconnect, Send a test email and both "Yes, …" confirmations) were 40px and the Settings tab bar 42px. Everything the plugin renders is at least 44px below 782px.
+
+- **The SendBeam Form block previewed nothing but an error.** The block's `ServerSideRender` put the hosted form into the editor canvas, which since WordPress 6.x is a nested iframe with an opaque origin — no referrer, so SendBeam's allowed-origins check refused it and the block read "This form can only be shown on the sites its owner has listed" on a site that is listed and whose published page renders the same form perfectly. Loosening that check for a missing referrer would let anyone embed a form with `referrerpolicy=no-referrer`, so the editor stops asking: the block renders a placeholder card with the mark, the chosen form's name and kind, a line saying the form appears there on the published page, and a **Preview** link that opens the hosted form in a tab, where there is a referrer. `wp-server-side-render` is no longer an editor dependency. The front end is untouched.
+
+### Connect
+
+- **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.
+- **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.
+- 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.
+- A key pinned in `wp-config.php` now hides the paste field as well as the button: a key saved in the database would lose to the constant on every request, so offering somewhere to put one was offering to create a problem.
+- Reconnecting into a different workspace forgets the cached status of the old one before it asks about the new one. It was possible to spend a minute looking at the previous workspace's sending domain and be told to put its records into your DNS.
+- The way out of a missing permission is offered on the step somebody is standing on, not only on the step it is queued behind. Site email waiting on a domain that is waiting on a box nobody ticked was one hop too many.
+- The sending-domain step says how to change the domain as well as how to finish it. That is precisely when somebody notices they have set up the wrong one, and the point at which every other sentence on the step has stopped talking to them.
+- "I've placed it elsewhere" is offered whenever the workspace has a form at all, rather than only when a default has been chosen. A form named in its own shortcode is still a form on the site, and those sites had an untickable step and no way to say so.
+- Coming back from a registrar says the check has run, in the past tense, because by the time anybody reads it the step underneath is already showing what it found. "Checking now…" promised a page that was about to change and then never changed.
+- The first step's link points at the Connect button rather than at the paste field underneath it.
+
## 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..48efdd0 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,20 @@
# SendBeam for WordPress
Your [SendBeam](https://sendbeam.io) forms on a WordPress site, plus pop-ups, opt-ins at registration and
-checkout, and the site's own email from your verified domain. A block, four shortcodes and one settings page.
+checkout, and the site's own email from your verified domain. A block, four shortcodes and its own admin menu.
Full documentation: **[sendbeam.io/docs/wordpress](https://sendbeam.io/docs/wordpress)**
| To do this | Use |
| --- | --- |
| A signup form in a post, page or template | `SendBeam Form` block, or `[sendbeam_form id="…"]` |
-| A contact form | `[sendbeam_contact]` |
-| A pop-up | Settings → SendBeam → Pop-ups |
+| A contact form | `[sendbeam_contact]`, or `[sendbeam_contact id="…"]` for a particular one |
+| A pop-up | SendBeam → Pop-ups |
| Your own button that opens a pop-up | `[sendbeam_popup_button label="Subscribe"]`, or any element with `data-sendbeam-open="
'
+ . '' . 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' );
}
/**
@@ -123,10 +597,109 @@ function sendbeam_setup_notice() {
*/
function sendbeam_dismiss_setup() {
if ( ! current_user_can( 'manage_options' ) ) {
- wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) );
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'sendbeam_dismiss_setup' );
update_user_meta( get_current_user_id(), 'sendbeam_setup_dismissed', 1 );
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' ), '', array( 'response' => 403 ) );
+ }
+ 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'
+ );
+}
+
+/**
+ * Has this person put the setup checklist away?
+ *
+ * Per user, in user meta: one administrator deciding they have seen enough of
+ * a checklist should not take it off the screen for the next person who comes
+ * to set something up.
+ *
+ * @return bool
+ */
+function sendbeam_checklist_hidden() {
+ return (bool) get_user_meta( get_current_user_id(), 'sendbeam_checklist_hidden', true );
+}
+
+/**
+ * The URL behind "Hide this checklist", and behind bringing it back.
+ *
+ * @param bool $hide True to put it away.
+ * @return string
+ */
+function sendbeam_checklist_url( $hide = true ) {
+ return wp_nonce_url(
+ add_query_arg(
+ array(
+ 'action' => 'sendbeam_hide_checklist',
+ 'state' => $hide ? '1' : '0',
+ ),
+ admin_url( 'admin-post.php' )
+ ),
+ 'sendbeam_hide_checklist'
+ );
+}
+
+/** Put the checklist away, or bring it back. */
+function sendbeam_handle_hide_checklist() {
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
+ }
+ check_admin_referer( 'sendbeam_hide_checklist' );
+
+ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- checked immediately above.
+ $hide = ! isset( $_GET['state'] ) || '0' !== sanitize_text_field( wp_unslash( $_GET['state'] ) );
+
+ if ( $hide ) {
+ update_user_meta( get_current_user_id(), 'sendbeam_checklist_hidden', 1 );
+ } else {
+ delete_user_meta( get_current_user_id(), 'sendbeam_checklist_hidden' );
+ }
+
+ wp_safe_redirect( sendbeam_tab_url( 'overview' ) );
+ exit;
+}
diff --git a/includes/popups.php b/includes/popups.php
index ceaf097..7269c93 100644
--- a/includes/popups.php
+++ b/includes/popups.php
@@ -181,7 +181,7 @@ function sendbeam_clean_popup( $raw ) {
/** Save the posted rules. */
function sendbeam_handle_save_popups() {
if ( ! current_user_can( 'manage_options' ) ) {
- wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) );
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'sendbeam_save_popups' );
@@ -237,12 +237,60 @@ function sendbeam_popup_matches( $rule ) {
}
}
+/**
+ * The rules that could actually show a pop-up to somebody.
+ *
+ * Switched on, and with a form to show. sendbeam_popups() returns every rule
+ * that was ever saved, including ones the owner unticked and ones with no
+ * form chosen, which is right for the editing screen and wrong for every
+ * question of the form "is there a pop-up on this site". Answering that with
+ * sendbeam_popups() told an owner who had just switched every rule off that
+ * "a SendBeam pop-up is live on the site".
+ *
+ * @return array>
+ */
+function sendbeam_live_popups() {
+ $out = array();
+ foreach ( sendbeam_popups() as $rule ) {
+ if ( ! empty( $rule['enabled'] ) && '' !== trim( (string) $rule['form'] ) ) {
+ $out[] = $rule;
+ }
+ }
+ return $out;
+}
+
/**
* The rule that owns this page, or null.
*
* @return array|null
*/
+/**
+ * Pages no pop-up may open on, whatever a rule says. A pop-up over the
+ * checkout puts its overlay on top of Place order, which is the one control
+ * a shop cannot afford to have covered; the cart and the account pages are
+ * the same kind of place. "Every page" means every page but these.
+ *
+ * @return bool
+ */
+function sendbeam_popup_excluded_page() {
+ foreach ( array( 'is_cart', 'is_checkout', 'is_account_page', 'is_wc_endpoint_url' ) as $fn ) {
+ if ( function_exists( $fn ) && call_user_func( $fn ) ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * The first rule that matches the current page, or null — and never one on
+ * the cart, checkout or account pages.
+ *
+ * @return array|null
+ */
function sendbeam_active_popup() {
+ if ( sendbeam_popup_excluded_page() ) {
+ return null;
+ }
foreach ( sendbeam_popups() as $rule ) {
if ( sendbeam_popup_matches( $rule ) ) {
return $rule;
diff --git a/includes/render.php b/includes/render.php
index 562a3ba..8d33595 100644
--- a/includes/render.php
+++ b/includes/render.php
@@ -37,7 +37,12 @@ function sendbeam_editor_defaults() {
'window.sendbeamBlock = ' . wp_json_encode(
array(
'defaultForm' => $settings['default_form'],
- 'formsUrl' => sendbeam_app_url() . '/forms',
+ 'formsUrl' => sendbeam_app_link( '/forms' ),
+ // Where the editor's Preview link goes. The hosted form itself,
+ // not the embed: the editor cannot render the embed (see the
+ // note on the placeholder in blocks/form/index.js) and a
+ // preview that opens in a tab has a real referrer.
+ 'previewBase' => sendbeam_app_url() . '/f/',
)
) . ';',
'before'
@@ -120,15 +125,29 @@ function sendbeam_shortcode_form( $atts ) {
}
/**
- * [sendbeam_contact height="640"]
+ * [sendbeam_contact id="…" height="640"]
+ *
+ * `id` names one contact form; without it the default chosen under Forms is
+ * used, which is what every existing page holding a bare [sendbeam_contact]
+ * expects. It exists because the Forms screen offers a Copy button on every
+ * contact row and told the owner to "place it by shortcode": without an id
+ * there was only one shortcode for all of them, so copying the one beside
+ * "Wholesale enquiry" put the default contact form on the page instead.
*
* @param array|string $atts Shortcode attributes.
* @return string
*/
function sendbeam_shortcode_contact( $atts ) {
$settings = sendbeam_settings();
- $atts = shortcode_atts( array( 'height' => 640 ), $atts, 'sendbeam_contact' );
- $html = sendbeam_form_html( $settings['contact_form'], (int) $atts['height'], __( 'Contact form', 'sendbeam' ) );
+ $atts = shortcode_atts(
+ array(
+ 'id' => $settings['contact_form'],
+ 'height' => 640,
+ ),
+ $atts,
+ 'sendbeam_contact'
+ );
+ $html = sendbeam_form_html( strtolower( trim( (string) $atts['id'] ) ), (int) $atts['height'], __( 'Contact form', 'sendbeam' ) );
if ( '' === $html ) {
return sendbeam_editor_notice( __( 'SendBeam: no contact form chosen under Settings → SendBeam.', 'sendbeam' ) );
}
diff --git a/includes/screens.php b/includes/screens.php
index 7fabb06..de382ee 100644
--- a/includes/screens.php
+++ b/includes/screens.php
@@ -4,8 +4,9 @@
*
* Each one is a small function so the router stays readable. Anything that
* saves posts to options.php in the 'sendbeam' option group and carries a
- * hidden `_tab`, which is what lets a tab save its own fields without
- * flattening the settings belonging to the other tabs.
+ * hidden `_tab` naming its own field group, which is what lets one form save
+ * its own fields without flattening the settings belonging to the others. A
+ * screen with two Save buttons needs two groups: see sendbeam_sanitize_settings().
*
* @package SendBeam
*/
@@ -13,9 +14,9 @@
defined( 'ABSPATH' ) || exit;
/**
- * Open a settings form for one tab.
+ * Open a settings form for one group of fields.
*
- * @param string $tab Tab key.
+ * @param string $tab Field-group key, from sendbeam_sanitize_settings().
*/
function sendbeam_form_open( $tab ) {
echo '';
@@ -23,61 +24,993 @@ 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( '%s
', esc_html__( 'Save changes', 'sendbeam' ) );
echo ' ';
}
/* -------------------------------------------------------------- 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() {
- $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();
+
+ /*
+ * 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_connection_card( $status, $connected );
echo '';
- sendbeam_card_open( __( 'Setup', 'sendbeam' ) );
+ sendbeam_overview_setup_card( $status, $connected );
+
+ sendbeam_workspace_card( $forms, $lists, $subscribers );
+
+ echo '
';
+}
+
+/**
+ * What the workspace holds, and what this site has been doing with it.
+ *
+ * Three figures across the top rather than stacked down the left: a column of
+ * three numbers in the top third of a card leaves the other two thirds blank,
+ * which reads as something that failed to load. Under them, the last few
+ * messages this site sent — which is the question somebody comes to a
+ * dashboard with, and which costs nothing to answer because the log is an
+ * option this site already holds.
+ *
+ * @param array|null $forms The workspace's forms, or null.
+ * @param array|null $lists The workspace's lists, or null.
+ * @param int|null $subscribers How many people, or null.
+ */
+function sendbeam_workspace_card( $forms, $lists, $subscribers ) {
+ $open = sprintf(
+ '%s ',
+ esc_url( sendbeam_app_link() ),
+ esc_html__( 'Open SendBeam', 'sendbeam' )
+ );
+
+ sendbeam_card_open( __( 'This workspace', 'sendbeam' ), '', $open );
+
+ echo '';
+ sendbeam_stat( __( 'Forms', 'sendbeam' ), is_array( $forms ) ? count( $forms ) : null );
+ sendbeam_stat( __( 'Lists', 'sendbeam' ), is_array( $lists ) ? count( $lists ) : null );
+ sendbeam_stat( __( 'Subscribers', 'sendbeam' ), $subscribers );
+ echo '
';
+ echo '' . esc_html__( 'Subscribers counts people, not list memberships. Cached for five minutes.', 'sendbeam' ) . '
';
+
+ sendbeam_workspace_recent();
+
+ sendbeam_card_close();
+}
+
+/**
+ * The last few things this site sent, from the log it already keeps.
+ *
+ * Five rows, because the point is "is it working?" rather than "what has it
+ * ever done" — the Site email screen has the whole log, searchable.
+ */
+function sendbeam_workspace_recent() {
+ $log = sendbeam_mail_log_recent( 5 );
+
+ echo '' . esc_html__( 'Recent site email', 'sendbeam' ) . '
';
+
+ if ( ! $log ) {
+ echo '' . esc_html__( 'Nothing has gone out through SendBeam from this site yet.', 'sendbeam' ) . '
';
+ return;
+ }
+
+ $results = array(
+ 'sent' => array( 'ok', __( 'Sent', 'sendbeam' ) ),
+ 'fallback' => array( 'warn', __( 'Server mailer', 'sendbeam' ) ),
+ 'failed' => array( 'bad', __( 'Failed', 'sendbeam' ) ),
+ );
+
+ $today = wp_date( 'Y-m-d' );
+
+ echo '';
+ foreach ( $log as $row ) {
+ $key = isset( $results[ $row['result'] ] ) ? $row['result'] : 'failed';
+
+ /*
+ * Two dates, one shown at a time by CSS. "September 24, 2026" is the
+ * site's own format and right on a desktop; on a phone it took half
+ * the row and left the address with nowhere to go. Today's messages
+ * get a time instead, which is what somebody checking whether the
+ * last one went out actually wants.
+ */
+ $at = sendbeam_mail_log_stamp( $row );
+ $long = wp_date( get_option( 'date_format' ), $at );
+ $short = wp_date( 'Y-m-d', $at ) === $today
+ ? wp_date( get_option( 'time_format' ), $at )
+ : wp_date( 'j M', $at );
+
+ printf(
+ '%1$s ' .
+ '%2$s ' .
+ '%3$s ' .
+ '%5$s ',
+ esc_html( $long ),
+ esc_html( $short ),
+ esc_html( (string) $row['to_addr'] ),
+ esc_attr( $results[ $key ][0] ),
+ esc_html( $results[ $key ][1] )
+ );
+ }
+ echo ' ';
+
+ printf(
+ '%s
',
+ esc_url( sendbeam_page_url( 'sendbeam-mail' ) ),
+ esc_html__( 'View the log', 'sendbeam' )
+ );
+}
+
+/**
+ * The connection, at the top, where somebody arriving looks first.
+ *
+ * It used to live inside step 1 of the checklist, which meant that on a
+ * finished site — the state most sites are in most of the time — the one
+ * question the Overview is asked ("what is this connected to?") was answered
+ * by a ticked line with nothing under it.
+ *
+ * @param array $status Normalised Connect status.
+ * @param bool $connected Whether the key works.
+ */
+function sendbeam_overview_connection_card( $status, $connected ) {
+ if ( ! $connected ) {
+ sendbeam_card_open( __( 'Connection', 'sendbeam' ), __( 'Not connected yet.', 'sendbeam' ) );
+ sendbeam_connect_panel();
+ sendbeam_connect_paste_disclosure();
+ sendbeam_card_close();
+ return;
+ }
+
+ sendbeam_card_open( __( 'Connection', 'sendbeam' ), sendbeam_sends_as_line( $status ) );
+ sendbeam_connect_connected_panel( $status );
+ sendbeam_card_close();
+}
+
+/**
+ * "Sends as …", and what kind of address that is.
+ *
+ * The address on its own was the second half of a contradiction: a card
+ * saying "Sends as ws-…@post.sendbeam.io" above a checklist saying the site's
+ * own domain was verified told somebody two true things and left them to work
+ * out that only one of them was about their email. Saying which kind of
+ * address it is settles it in three words.
+ *
+ * @param array $status Normalised Connect status.
+ * @return string
+ */
+function sendbeam_sends_as_line( $status ) {
+ $sender = sendbeam_effective_sender( $status );
+ if ( '' === $sender['email'] ) {
+ return '';
+ }
+
+ $kinds = array(
+ 'own_domain' => __( 'your domain', 'sendbeam' ),
+ 'shared' => __( 'SendBeam\'s shared address', 'sendbeam' ),
+ 'other' => __( 'not a verified domain', 'sendbeam' ),
+ );
+
+ if ( ! isset( $kinds[ $sender['kind'] ] ) ) {
+ /* translators: %s: the address this site sends as */
+ return sprintf( __( 'Sends as %s', 'sendbeam' ), $sender['email'] );
+ }
+
+ return sprintf(
+ /* translators: 1: the address this site sends as, 2: what kind of address it is */
+ __( 'Sends as %1$s (%2$s)', 'sendbeam' ),
+ $sender['email'],
+ $kinds[ $sender['kind'] ]
+ );
+}
+
+/**
+ * The four-step checklist, and the way to put it away once it is finished.
+ *
+ * A checklist with four ticks on it is furniture. It stays until every step
+ * is done and then offers to go — per user, because one administrator
+ * hiding it should not hide it from the next person who installs something.
+ *
+ * @param array $status Normalised Connect status.
+ * @param bool $connected Whether the key works.
+ */
+function sendbeam_overview_setup_card( $status, $connected ) {
$steps = sendbeam_setup_steps();
+ $left = 0;
+ foreach ( $steps as $step ) {
+ if ( empty( $step['done'] ) ) {
+ ++$left;
+ }
+ }
+
+ if ( 0 === $left && sendbeam_checklist_hidden() ) {
+ sendbeam_card_open( __( 'Setup', 'sendbeam' ) );
+ echo '✓ ' . esc_html__( 'Set up and sending.', 'sendbeam' ) . '
';
+ printf(
+ '%s
',
+ esc_url( sendbeam_checklist_url( false ) ),
+ esc_html__( 'Show the checklist again', 'sendbeam' )
+ );
+ sendbeam_card_close();
+ return;
+ }
+
+ sendbeam_card_open(
+ __( 'Setup', 'sendbeam' ),
+ $left > 0
+ /* translators: %d: how many setup steps are left */
+ ? sprintf( _n( '%d step left', '%d steps left', $left, 'sendbeam' ), $left )
+ : __( 'All done', 'sendbeam' )
+ );
echo '';
- $targets = array( sendbeam_tab_url( 'overview' ) . '#sendbeam_api_key', sendbeam_tab_url( 'forms' ), sendbeam_tab_url( 'mail' ) );
foreach ( $steps as $i => $step ) {
+ /*
+ * Three states, not two. A step that is switched on and doing the
+ * wrong thing is not finished, and it is not unstarted either — a
+ * plain number beside it reads as "you have not got to this yet".
+ */
+ $attention = ! empty( $step['attention'] );
printf(
- '%2$s %4$s %5$s ',
- $step['done'] ? 'is-done' : '',
- $step['done'] ? '✓' : (int) ( $i + 1 ),
- esc_url( $targets[ $i ] ),
- esc_html( $step['label'] ),
- esc_html( $step['detail'] )
+ '%2$s ',
+ esc_attr( $step['done'] ? 'is-done' : ( $attention ? 'needs-attention' : '' ) ),
+ $step['done'] ? '✓' : ( $attention ? '!' : (int) ( $i + 1 ) )
);
+
+ // The connect step links to the card above rather than to a field:
+ // that card is where connecting is actually done now.
+ printf( '
%2$s ', esc_url( $step['target'] ), esc_html( $step['label'] ) );
+ printf( '
%s ', esc_html( $step['detail'] ) );
+
+ sendbeam_overview_step_panel( $step, $status, $connected );
+
+ echo '
';
}
echo ' ';
+
+ if ( 0 === $left ) {
+ printf(
+ '%s
',
+ esc_url( sendbeam_checklist_url( true ) ),
+ esc_html__( 'Hide this checklist', 'sendbeam' )
+ );
+ }
sendbeam_card_close();
+}
+
+/**
+ * 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.
+ *
+ * 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':
+ // Nothing: the connection card above the checklist is where this
+ // step is done, and two Connect buttons on one screen is one too
+ // many.
+ break;
+ case 'domain':
+ if ( $connected ) {
+ sendbeam_domain_panel( $status );
+ }
+
+ /*
+ * 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
',
+ // The one link that must NOT offer the current domain
+ // back: choosing a different one is the entire point.
+ esc_url( sendbeam_connect_start_url( false, false ) ),
+ esc_html__( 'Sending from the wrong domain? Reconnect and enter the one you want.', 'sendbeam' )
+ );
+ }
+ break;
+ case 'form':
+ sendbeam_overview_form_panel( $step, $connected );
+ break;
+ case 'mail':
+ sendbeam_overview_mail_panel( $status, $connected );
+ break;
+ }
+
+ /*
+ * A step whose sentence names something this site's key cannot do ends in
+ * the same place: the consent page, with every box ticked. The link
+ * starts the ordinary Connect flow, and the key that comes back replaces
+ * the one this site holds. This is the only place the offer appears for a
+ * site with a pasted key — a connected card that says "Connected" and
+ * then offers to connect is the plugin arguing with itself.
+ */
+ if ( $connected && ! empty( $step['reconnect'] ) ) {
+ echo '';
+ printf(
+ '
%s ',
+ esc_url( sendbeam_connect_start_url( true ) ),
+ esc_html(
+ sendbeam_connected_via_connect()
+ // There is a connection to re-make, with more ticked.
+ ? __( 'Reconnect with more permissions', 'sendbeam' )
+ // There is no connection to re-make: a pasted key is
+ // being offered the thing it cannot do, where it cannot
+ // do it, and nowhere else.
+ : __( 'Switch to one-click Connect', 'sendbeam' )
+ )
+ );
+ echo '
';
+ }
+}
+
+/**
+ * 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 $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_domain_panel( $status, $standalone = false ) {
+ $domain = $status['domain'];
+ $verified = ! empty( $domain['verified'] );
+ $state = sendbeam_connect_domain_state( $status );
+
+ /*
+ * 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 ) {
+ // With the reason SendBeam gave, which the Overview's step has
+ // always had and this screen — the one about the sending domain —
+ // used to drop.
+ echo '' . esc_html( sendbeam_domain_missing_sentence( $status ) ) . '
';
+ }
+ if ( in_array( $state, array( 'no_site', 'not_found', 'managed_host' ), true ) ) {
+ echo '';
+ printf(
+ '
%s ',
+ esc_url( sendbeam_app_link( '/settings/domains' ) ),
+ esc_html__( 'Open Settings → Domains', 'sendbeam' )
+ );
+ echo '
';
+ }
+ return;
+ }
+
+ 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'] ) {
+ $hidden = $verified;
+ if ( $hidden ) {
+ echo '
' . esc_html__( 'The records SendBeam is using', 'sendbeam' ) . ' ';
+ } else {
+ echo '
';
+ 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 ( $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' ) . '
';
+ }
+
+ echo '';
+ echo '
';
+ wp_nonce_field( 'sendbeam_domain_check' );
+ echo ' ';
+ // Somebody copying records on the Sending domain tab should be told the
+ // result there, not moved to the Overview and left to navigate back.
+ printf( ' ', esc_attr( sendbeam_current_page() ) );
+ printf(
+ '%2$s ',
+ esc_attr( $verified ? '' : ' sb-btn--primary' ),
+ esc_html( $verified ? __( 'Check again', 'sendbeam' ) : __( 'Check now', 'sendbeam' ) )
+ );
+ echo ' ';
+
+ if ( ! $verified && '' !== $domain['domain_connect_url'] ) {
+ printf(
+ '
%s ',
+ esc_url( sendbeam_domain_connect_url( $domain['domain_connect_url'] ) ),
+ esc_html__( 'Set up DNS automatically', 'sendbeam' )
+ );
+ }
+ 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' ) . '
';
+ }
+
+ if ( '' !== $domain['checked_at'] ) {
+ echo '
' . esc_html(
+ sprintf(
+ /* translators: %s: when the DNS was last checked, in the site's own date and time format */
+ __( 'Last checked %s.', 'sendbeam' ),
+ sendbeam_connect_when( $domain['checked_at'] )
+ )
+ ) . '
';
+ }
+
+ 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.
+ *
+ * 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 '' . 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 field rather than a `` block: it selects on focus, it is
+ * reachable with a keyboard, and clicking it copies.
+ *
+ * A textarea rather than an ` `, for one reason: an input cannot wrap.
+ * On a phone the value column is about ninety pixels wide, and a DKIM host in
+ * a ninety-pixel input reads "resend._dc" — copyable and completely
+ * unreadable, which is the thing somebody checking their DNS most needs to be
+ * able to do. A textarea wraps the whole value onto as many lines as it takes.
+ *
+ * @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(
+ '%2$s ' .
+ '%6$s ',
+ esc_attr( $id ),
+ esc_html( $label ),
+ esc_attr( $value ),
+ esc_attr__( 'Copied', 'sendbeam' ),
+ esc_attr__( 'Click to copy', 'sendbeam' ),
+ esc_textarea( $value )
+ );
+}
+
+/**
+ * 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.
+ *
+ * @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.
+ *
+ * @param array $step The step.
+ * @param bool $connected Whether the key works.
+ */
+function sendbeam_overview_form_panel( $step, $connected ) {
+ 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();
+ $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 '';
+ if ( $chosen ) {
+ echo '
[sendbeam_form]';
+ printf(
+ '
%3$s ',
+ esc_attr( '[sendbeam_form]' ),
+ 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 '
';
+}
+
+/**
+ * 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'] ) ) {
+ $sender = sendbeam_effective_sender( $status );
+ $own = sendbeam_own_domain_sender( $status );
+
+ echo '';
+
+ // The fix first, where there is one to make: a site sending as
+ // SendBeam from a verified domain is one press from sending as
+ // itself, and that press is worth more than another test email.
+ if ( 'shared' === $sender['kind'] && '' !== $own ) {
+ echo '
';
+ wp_nonce_field( 'sendbeam_mail_own_domain' );
+ echo ' ';
+ printf(
+ '%s ',
+ esc_html(
+ sprintf(
+ /* translators: %s: the verified sending domain */
+ __( 'Send from %s', 'sendbeam' ),
+ $status['domain']['name']
+ )
+ )
+ );
+ echo ' ';
+ }
+
+ echo '';
+ wp_nonce_field( 'sendbeam_test_mail' );
+ echo ' ';
+ printf( '%s ', esc_attr( 'shared' === $sender['kind'] && '' !== $own ? ' sb-btn--ghost' : '' ), esc_html__( 'Send a test email', 'sendbeam' ) );
+ echo ' ';
+ echo '
';
+
+ if ( 'shared' === $sender['kind'] && '' !== $own ) {
+ echo '' . esc_html(
+ sprintf(
+ /* translators: %s: the address this site would send as instead */
+ __( 'That changes the From address to %s. Nothing else moves, and you can change it again under Site email.', 'sendbeam' ),
+ $own
+ )
+ ) . '
';
+ }
+ return;
+ }
+
+ // Granted, or unknown — a pasted key records no permissions, and hiding
+ // the button on a site whose key may well have the permission leaves the
+ // step with nothing on it and no way to find out. The handler checks
+ // again and says so if SendBeam refuses.
+ $may_send = sendbeam_connect_granted( 'transactional:send' ) || ! sendbeam_connect_permissions_known();
+ if ( ! $may_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( '%s ', 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 under Site email.', '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.
+ *
+ * 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 '';
+ sendbeam_form_open( 'connect' );
+ do_settings_sections( 'sendbeam_connect_page' );
+ sendbeam_form_close();
+ echo '
';
+}
+
+/**
+ * The connected card: one shape, however the key got here.
+ *
+ * There used to be two. A site with a pasted key got a card offering
+ * **Connect this site** and **Replace the key** — under a header band already
+ * saying "Connected", which reads as the plugin not knowing its own state.
+ * Connecting is an upgrade, not a correction, and an upgrade belongs where
+ * the pasted key actually falls short: on the step that cannot answer without
+ * the permissions Connect grants. Not here, where the answer is simply "yes,
+ * connected".
+ *
+ * So: what it is connected to, how the key arrived, and the one thing a
+ * connected card is for — disconnecting. Reconnect joins it only when there
+ * is something to reconnect *to*, which a pasted key does not have.
+ *
+ * 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, for a
+ * key SendBeam issued to this site. A pasted key is somebody else's to
+ * revoke: it may be shared with another site, so it is forgotten here and
+ * left alone there, and the confirmation says so.
+ *
+ * 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( $status = null ) {
+ $via_connect = sendbeam_connected_via_connect();
+ $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 to SendBeam', 'sendbeam' ) . '
';
+ }
+
+ // How the key got here, quietly. It is the difference between a
+ // connection this plugin can reason about and one it can only use.
+ echo '
' . esc_html(
+ $via_connect
+ ? __( 'via Connect', 'sendbeam' )
+ : __( 'using an API key', 'sendbeam' )
+ ) . '
';
+
+ 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 '
';
+ foreach ( $granted as $label ) {
+ echo '' . esc_html( $label ) . ' ';
+ }
+ echo ' ';
+ }
+
+ 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 — which
+ * means it only makes sense for a connection that has permissions on
+ * record, and a pasted key has none.
+ */
+ if ( $via_connect ) {
+ printf(
+ '
%s ',
+ esc_url( sendbeam_connect_start_url() ),
+ esc_html__( 'Reconnect', 'sendbeam' )
+ );
+ }
+
+ /*
+ * A native disclosure, not a div that script hides after the page has
+ * drawn. The old shape shipped the confirmation open so a browser with no
+ * JavaScript could still submit it, and hid it on load — which meant a
+ * red-bordered box flashed on the screen every single time the Overview
+ * rendered. `
` is shut until somebody presses it, needs no
+ * script at all, and keeps the keyboard and screen-reader behaviour a
+ * disclosure is supposed to have.
+ *
+ * The summary is the button, and it is also the way out: pressing it
+ * again closes the box, which is what the separate Cancel used to do with
+ * script.
+ */
+ echo '';
+ printf(
+ '' .
+ '%1$s ' .
+ '%2$s ',
+ esc_html__( 'Disconnect', 'sendbeam' ),
+ esc_html__( 'Cancel', 'sendbeam' )
+ );
+ echo '';
+ echo '
' . esc_html(
+ $via_connect
+ ? __( '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' )
+ : __( 'Disconnect this site? The saved key is removed from this site and nothing is revoked in SendBeam — a key you pasted may be in use somewhere else. Forms already on your pages stop loading until you connect again.', 'sendbeam' )
+ ) . '
';
+ echo '
';
+ wp_nonce_field( 'sendbeam_disconnect' );
+ echo ' ';
+ printf( '%s ', esc_html__( 'Yes, disconnect', 'sendbeam' ) );
+ echo ' ';
+ echo '
';
- sendbeam_card_open( __( 'This workspace', 'sendbeam' ) );
- echo '';
- sendbeam_stat( __( 'Forms', 'sendbeam' ), is_array( $forms ) ? count( $forms ) : null );
- sendbeam_stat( __( 'Lists', 'sendbeam' ), is_array( $lists ) ? count( $lists ) : null );
- sendbeam_stat( __( 'Subscribers', 'sendbeam' ), $subscribers );
echo '
';
- echo '' . esc_html__( 'Subscribers counts people, not list memberships — someone on three lists is one subscriber. Figures come from your SendBeam workspace and are cached for five minutes.', 'sendbeam' ) . '
';
- sendbeam_card_close();
echo ' ';
+}
- sendbeam_card_open( __( 'Connect', 'sendbeam' ) );
- sendbeam_form_open( 'connect' );
- do_settings_sections( 'sendbeam_connect_page' );
- sendbeam_form_close();
- sendbeam_card_close();
+/**
+ * The permissions this site's key holds, in the consent page's own words.
+ *
+ * @return string[]
+ */
+function sendbeam_connect_granted_list() {
+ /*
+ * The domain scope's label names the host the consent page was asked
+ * about, which is this site's own. On a consent page that is exactly
+ * right — it is what is about to be set up. On a connected site it is a
+ * description of the request rather than of the outcome, and a site that
+ * connected with SEND FROM set to mail.example.co.uk read "Set up this
+ * site's sending domain (example.co.uk) in SendBeam" ever after.
+ */
+ $domain = sendbeam_connect_current_sending_host();
+
+ $out = array();
+ foreach ( sendbeam_connect_scopes() as $scope => $meta ) {
+ if ( ! sendbeam_connect_granted( $scope ) ) {
+ continue;
+ }
+ if ( 'domain' === $scope && '' !== $domain ) {
+ /* translators: %s: the sending domain actually set up, e.g. mail.harbourlane.co.uk */
+ $out[] = sprintf( __( "Set up this site's sending domain (%s) in SendBeam", 'sendbeam' ), $domain );
+ continue;
+ }
+ $out[] = $meta['label'];
+ }
+ return $out;
}
/**
@@ -94,7 +1027,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' ) );
@@ -104,7 +1037,7 @@ function sendbeam_screen_forms() {
sendbeam_card_close();
sendbeam_card_open( __( 'Appearance', 'sendbeam' ), __( 'How the form looks on your pages.', 'sendbeam' ) );
- sendbeam_form_open( 'forms' );
+ sendbeam_form_open( 'forms_style' );
$s = sendbeam_settings();
echo '
' . esc_html__( 'Forms are served by SendBeam, so give them your site\'s colours and they will stop looking like something pasted in from elsewhere. Leave a field blank to keep the SendBeam default.', 'sendbeam' ) . '
';
echo '
';
@@ -146,102 +1079,35 @@ function sendbeam_screen_forms() {
echo '';
echo '
';
printf(
- '
%s
',
+ '
%s
',
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' )
);
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 ) ) : '' );
+ sendbeam_list_card(
+ __( 'Your forms', 'sendbeam' ),
+ __( 'Every form in this workspace, ready to drop into a page.', 'sendbeam' ),
+ __( 'Search forms', 'sendbeam' )
+ );
- 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 '' . esc_html__( 'Form', 'sendbeam' ) . ' ';
- echo '' . esc_html__( 'Kind', 'sendbeam' ) . ' ';
- echo '' . esc_html__( 'Shortcode', 'sendbeam' ) . ' ';
- 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 . '"]';
- ?>
-
-
-
-
-
-
-
-
-
-
';
- 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 */
/**
- * 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();
- 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 '' . esc_html__( 'List', 'sendbeam' ) . ' ';
- echo '' . esc_html__( 'Subscribers', 'sendbeam' ) . ' ';
- echo '' . esc_html__( 'Confirmation', 'sendbeam' ) . ' ';
- echo ' ';
- foreach ( $lists as $list ) {
- ?>
-
-
-
-
-
-
-
-
-
-
-
-
';
- }
- 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 );
@@ -264,26 +1130,26 @@ function sendbeam_screen_form_plugins( $lists ) {
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' ) ) {
@@ -322,7 +1188,7 @@ function sendbeam_screen_fluentforms( $lists ) {
echo '
';
printf(
- ' %3$s
',
+ ' %3$s
',
esc_attr( $name ),
checked( $config['enabled'], 1, false ),
esc_html( '' !== $title ? $title : sprintf( /* translators: %d: form ID */ __( 'Form %d', 'sendbeam' ), $form_id ) )
@@ -343,7 +1209,7 @@ function sendbeam_screen_fluentforms( $lists ) {
);
}
printf(
- ' %3$s
',
+ ' %3$s
',
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' )
@@ -365,7 +1231,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 '' . esc_html__( 'Save', 'sendbeam' ) . '
';
+ echo '' . esc_html__( 'Save', 'sendbeam' ) . '
';
echo '';
}
@@ -377,17 +1243,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;
}
@@ -405,7 +1266,7 @@ function sendbeam_screen_sync( $lists ) {
echo '' . esc_html__( 'Ask on', 'sendbeam' ) . '
';
foreach ( $sources as $key => $meta ) {
printf(
- ' %4$s %5$s
',
+ ' %4$s%5$s
',
esc_attr( $key ),
checked( ! empty( $sync[ $key ] ), true, false ),
$meta[1] ? '' : 'disabled',
@@ -434,14 +1295,14 @@ function sendbeam_screen_sync( $lists ) {
esc_attr( sendbeam_sync_label() )
);
- echo '' . esc_html__( 'Save', 'sendbeam' ) . '
';
+ echo '' . esc_html__( 'Save', 'sendbeam' ) . '
';
echo '';
sendbeam_card_close();
$log = get_option( SENDBEAM_SYNC_LOG, array() );
if ( is_array( $log ) && $log ) {
sendbeam_card_open( __( 'Recent subscriptions', 'sendbeam' ) );
- echo ' ';
sendbeam_card_close();
}
}
@@ -466,15 +1327,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' ) . '
';
@@ -490,7 +1342,7 @@ function sendbeam_screen_popup() {
echo '';
echo '
';
- echo '' . esc_html__( 'Save pop-ups', 'sendbeam' ) . '
';
+ echo '' . esc_html__( 'Save pop-ups', 'sendbeam' ) . '
';
echo '';
// The blank row the "add" button clones. __i__ is swapped for the index.
@@ -499,6 +1351,8 @@ function sendbeam_screen_popup() {
echo '';
sendbeam_card_close();
+
+ sendbeam_placing_forms_card();
}
/**
@@ -510,10 +1364,25 @@ function sendbeam_screen_popup() {
function sendbeam_popup_row( $i, $rule ) {
$name = 'sendbeam_popup[' . $i . ']';
$choices = sendbeam_form_choices( 'signup' );
- ?>
-
-
+ /*
+ * Numbered, because the order is the rule: the first pop-up that matches
+ * a page is the one that opens. The template's placeholder is swapped by
+ * the same script that swaps the field index, and the rows renumber
+ * themselves after an add or a remove so the numbers never lie.
+ */
+ $number = is_numeric( $i ) ? (string) ( (int) $i + 1 ) : '__n__';
+ ?>
+
+
+
-
-
-
+
' . esc_html( $note ) . '';
+ sendbeam_test_mail_card();
+
+ sendbeam_list_card(
+ __( 'Email log', 'sendbeam' ),
+ sendbeam_mail_log_intro(),
+ __( 'Search the log', 'sendbeam' ),
+ 'sendbeam_mail_log_clear_action'
+ );
+}
+
+/**
+ * What the log card says about itself.
+ *
+ * @return string
+ */
+function sendbeam_mail_log_intro() {
+ $days = sendbeam_mail_log_days();
+ if ( 0 === $days ) {
+ return __( 'Every message this site has handed to SendBeam, and what became of each. Kept until you clear it; only the subject and the result are stored, never the message.', 'sendbeam' );
+ }
+ return sprintf(
+ /* translators: %d: how many days the log is kept for */
+ _n(
+ 'Every message this site has handed to SendBeam, and what became of each. Kept for %d day; only the subject and the result are stored, never the message.',
+ 'Every message this site has handed to SendBeam, and what became of each. Kept for %d days; only the subject and the result are stored, never the message.',
+ $days,
+ 'sendbeam'
+ ),
+ $days
+ );
+}
+
+/**
+ * "Clear the log" — all of it, behind its own confirmation.
+ *
+ * Deliberately not a bulk action. "Delete" and "Delete all" one mis-click
+ * apart in the same dropdown is how somebody loses the log they came to read.
+ */
+function sendbeam_mail_log_clear_action() {
+ if ( 0 === sendbeam_mail_log_counts()['all'] ) {
+ return;
}
- ?>
-
-
-
- user_email ) ); ?>
-
-
- ';
+ printf(
+ '
' .
+ '%1$s ' .
+ '%2$s ',
+ esc_html__( 'Clear the log', 'sendbeam' ),
+ esc_html__( 'Cancel', 'sendbeam' )
+ );
+ echo '
';
+ echo '
' . esc_html__( 'Delete every entry in the log? Nothing else changes — this is a record of what was sent, not the messages themselves, and clearing it does not unsend anything.', 'sendbeam' ) . '
';
+ echo '
';
+ wp_nonce_field( 'sendbeam_clear_log' );
+ echo ' ';
+ printf( '%s ', esc_html__( 'Yes, clear it', 'sendbeam' ) );
+ echo ' ';
+ echo '
';
+}
+
+/**
+ * Send a test email, and say what happened without leaving the page.
+ *
+ * The result replaces the form rather than appearing as a notice above it,
+ * because a diagnostic is not an announcement: somebody who has just pressed
+ * "Send a test email" is reading the space the button was in. A failure gets
+ * three sentences — what went wrong, what it means, what to do — and a block
+ * of detail they can copy into a support email in one click.
+ */
+function sendbeam_test_mail_card() {
+ $result = sendbeam_take_test_result();
+
+ sendbeam_card_open( __( 'Send a test email', 'sendbeam' ) );
+ echo '
';
+
+ 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();
+}
- $log = get_option( 'sendbeam_mail_log', array() );
- if ( is_array( $log ) && $log ) {
- sendbeam_card_open( __( 'Recent site email', 'sendbeam' ) );
- echo '';
- 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 ' ';
+/**
+ * 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( '%s
', 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 '
';
+
+ /*
+ * Sent is not the same as sent from you. A message that went out on
+ * SendBeam's shared address while this site's own domain sits verified
+ * and unused arrived — and is not yet doing the thing the domain was set
+ * up for, which is the difference between a mailbox provider trusting it
+ * and tolerating it.
+ */
+ if ( ! empty( $result['next'] ) && is_array( $result['next'] ) ) {
+ $next = $result['next'];
+ echo '';
+ echo '
' . esc_html( (string) $next['title'] ) . '
';
+ echo '
' . esc_html( (string) $next['text'] ) . '
';
+ printf(
+ '
%s
',
+ esc_url( (string) $next['url'] ),
+ esc_html( (string) $next['label'] )
+ );
+ 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(
+ '%3$s
',
+ esc_attr( (string) $result['bundle'] ),
+ esc_attr__( 'Copied', 'sendbeam' ),
+ esc_html__( 'Copy these details', 'sendbeam' )
+ );
+ echo '';
+ }
+ echo '
';
+ sendbeam_test_mail_form( __( 'Try again', 'sendbeam' ) );
+}
+
+/**
+ * Carry the view and the sort across a form submission.
+ *
+ * Without these, searching from inside the Failed view drops you back into
+ * All, and a bulk delete forgets which column the list was ordered by.
+ */
+function sendbeam_list_keep_state() {
+ foreach ( array( 'result', 'orderby', 'order' ) as $key ) {
+ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- carried straight back into the same list's own query string.
+ $value = isset( $_REQUEST[ $key ] ) ? sanitize_key( wp_unslash( $_REQUEST[ $key ] ) ) : '';
+ if ( '' !== $value ) {
+ printf( ' ', esc_attr( $key ), esc_attr( $value ) );
}
- echo '
';
+ }
+}
+
+/**
+ * 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.
+ * @param string $action Optional callable rendering an action under the table.
+ */
+function sendbeam_list_card( $title, $note, $search, $action = '' ) {
+ $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;
+ }
+
+ // All / Sent / Failed, with counts. Core prints these outside the form,
+ // because a view is a link rather than something you submit.
+ if ( method_exists( $table, 'views' ) ) {
+ $table->views();
+ }
+
+ // 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() ) );
+ sendbeam_list_keep_state();
+ $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() ) );
+ sendbeam_list_keep_state();
+ $table->display();
+ echo ' ';
+
+ if ( '' !== $action && is_callable( $action ) ) {
+ echo '';
+ call_user_func( $action );
+ echo '
';
}
+
+ sendbeam_card_close();
}
/* ------------------------------------------------------------ E-commerce */
/**
* 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' )
@@ -723,17 +1809,17 @@ function sendbeam_screen_ecommerce() {
wp_nonce_field( 'sendbeam_save_ecommerce' );
printf(
- ' %2$s
',
+ ' %2$s
',
checked( ! empty( $settings['order_placed'] ), true, false ),
esc_html__( 'Order placed — reliable, fires from WooCommerce\'s own order-processed hook. Also adds the order total to the contact\'s lifetime_value.', 'sendbeam' )
);
printf(
- ' %2$s
',
+ ' %2$s
',
checked( ! empty( $settings['product_viewed'] ), true, false ),
esc_html__( 'Product viewed — only for a known contact (logged in, or an email already entered this visit). No anonymous visitor tracking.', 'sendbeam' )
);
printf(
- ' %2$s
',
+ ' %2$s
',
checked( ! empty( $settings['cart_abandoned'] ), true, false ),
esc_html__( 'Cart abandoned — best effort. WooCommerce has no native "abandoned cart" event, so this is a heuristic: no order within the window below, and only when an email became known at some point.', 'sendbeam' )
);
@@ -750,14 +1836,14 @@ function sendbeam_screen_ecommerce() {
echo '' . esc_html__( 'None of this is a guarantee. "Abandoned" here means "no order followed within the window" — a shopper who orders later, on another device, still counts as abandoned by this measure. Treat the trigger as a nudge, not a fact.', 'sendbeam' ) . '
';
- echo '' . esc_html__( 'Save', 'sendbeam' ) . '
';
+ echo '' . esc_html__( 'Save', 'sendbeam' ) . '
';
echo '';
sendbeam_card_close();
$log = get_option( SENDBEAM_ECOMMERCE_LOG, array() );
if ( is_array( $log ) && $log ) {
sendbeam_card_open( __( 'Recent e-commerce events', 'sendbeam' ) );
- echo '';
+ sendbeam_card_close();
+ }
+}
+
+/* -------------------------------------------------------------- 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_connect_connected_panel( $status );
+ } else {
+ sendbeam_connect_panel();
+ }
+ sendbeam_card_close();
+
+ /*
+ * Changing the key is a settings job, not something to put on a card
+ * whose answer is "yes, connected". It lives one tab across, and this is
+ * the line that says so.
+ */
+ if ( $connected && ! sendbeam_key_in_config() ) {
+ printf(
+ '%s
',
+ esc_url( add_query_arg( 'tab', 'advanced', sendbeam_page_url( 'sendbeam-settings' ) ) ),
+ esc_html__( 'Replace the API key', 'sendbeam' )
+ );
+ }
+}
+
+/**
+ * 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();
}
-/* ------------------------------------------------------------------ Docs */
+/* ------------------------------------------------------------------ Help */
/**
* A reference that works without leaving WordPress.
@@ -788,7 +2001,7 @@ function sendbeam_screen_ecommerce() {
* @return string
*/
function sendbeam_docs_url( $slug = '' ) {
- return sendbeam_app_url() . '/docs/wordpress' . ( $slug ? '/' . $slug : '' );
+ return sendbeam_app_link( '/docs/wordpress' ) . ( $slug ? '/' . $slug : '' );
}
/**
@@ -809,9 +2022,94 @@ function sendbeam_doc_snippet( $code, $what ) {
}
/**
- * Docs tab: the shortcodes, the API key permissions, and links to the full documentation.
+ * Help: the documentation, the state of this site, and who to ask.
+ */
+function sendbeam_screen_help() {
+ sendbeam_help_documentation_card();
+ sendbeam_help_setup_again_card();
+ sendbeam_help_status_card();
+ sendbeam_help_support_card();
+ sendbeam_help_shortcodes_card();
+ sendbeam_help_permissions_card();
+ sendbeam_help_developers_card();
+}
+
+/**
+ * The way back into the four-step guide.
+ *
+ * Every plugin in the field study that has a wizard keeps one reachable, and
+ * for the same two reasons: the first run is the quickest way to check a
+ * change, and somebody setting up their second site wants the same
+ * walk-through on it. It resets where this person got to and nothing else.
+ */
+function sendbeam_help_setup_again_card() {
+ sendbeam_card_open( __( 'Set up SendBeam again', 'sendbeam' ) );
+ echo '' . esc_html__( 'The four-step guide a new site sees once: connect, verify the sending domain, switch on site email, place a form. Nothing is undone by opening it — it walks through what is already set up and shows you what is not.', 'sendbeam' ) . '
';
+ printf(
+ '%s
',
+ esc_url( sendbeam_wizard_restart_url() ),
+ esc_html__( 'Run the setup guide again', 'sendbeam' )
+ );
+ sendbeam_card_close();
+}
+
+/**
+ * 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(
+ '%3$s ' .
+ '%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_screen_docs() {
+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' ) . '
';
@@ -839,29 +2137,40 @@ function sendbeam_screen_docs() {
echo '
';
printf(
'%2$s — %3$s
',
- esc_url( sendbeam_app_url() . '/docs/ecommerce' ),
+ esc_url( sendbeam_app_link( '/docs/ecommerce' ) ),
esc_html__( 'E-commerce events', 'sendbeam' ),
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_contact id="8f3c1a2e-…"]', __( 'Any contact form, as often as you like', '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 '
' . esc_html__( 'Permission', 'sendbeam' ) . ' ' . esc_html__( 'Needed for', 'sendbeam' ) . ' ';
+ 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 a521ece..f2d8f73 100644
--- a/includes/settings.php
+++ b/includes/settings.php
@@ -1,43 +1,34 @@
' . esc_html__( 'Settings', 'sendbeam' ) . '' );
return $links;
}
@@ -107,7 +98,7 @@ function sendbeam_admin_init() {
array(
'key' => 'mail_from_name',
'placeholder' => get_bloginfo( 'name' ),
- 'class' => 'sendbeam-when-mail',
+ 'class' => sendbeam_when_mail_class(),
'help' => __( 'Leave empty to use the name the sending plugin sets, or the workspace sender.', 'sendbeam' ),
)
);
@@ -120,10 +111,22 @@ function sendbeam_admin_init() {
array(
'key' => 'mail_from_email',
'placeholder' => 'orders@yourdomain.com',
- 'class' => 'sendbeam-when-mail',
+ 'class' => sendbeam_when_mail_class(),
'help' => __( 'Must be on a domain verified in the SendBeam workspace. Leave empty to use the workspace sender.', 'sendbeam' ),
)
);
+ add_settings_field(
+ 'mail_log_days',
+ __( 'Keep log entries for', 'sendbeam' ),
+ 'sendbeam_field_select',
+ 'sendbeam_mail_page',
+ 'sendbeam_mail',
+ array(
+ 'key' => 'mail_log_days',
+ 'options' => sendbeam_mail_log_retentions(),
+ 'help' => __( 'Older entries are deleted once a day. Whatever you choose, the log is capped at 20,000 messages and the oldest go first — the contents of a message are never stored, only who it went to, its subject and what became of it.', 'sendbeam' ),
+ )
+ );
add_settings_field(
'mail_fallback',
__( 'If SendBeam cannot send', 'sendbeam' ),
@@ -133,12 +136,97 @@ function sendbeam_admin_init() {
array(
'key' => 'mail_fallback',
'label' => __( 'Fall back to the server\'s own mailer', 'sendbeam' ),
- 'class' => 'sendbeam-when-mail',
+ 'class' => sendbeam_when_mail_class(),
'help' => __( 'On: a refused or failed message goes out the way it did before this plugin (recommended). Off: it fails and the sending plugin is told.', 'sendbeam' ),
)
);
}
+/**
+ * The row class for a setting that only applies when site email is on.
+ *
+ * Hidden by the server when the feature is off, rather than drawn and then
+ * hidden by script on load — which is a row appearing and vanishing on every
+ * render of the screen. The script only takes over when somebody actually
+ * moves the switch.
+ *
+ * @return string
+ */
+function sendbeam_when_mail_class() {
+ $settings = sendbeam_settings();
+ return 'sendbeam-when-mail' . ( empty( $settings['mail_enabled'] ) ? ' is-hidden' : '' );
+}
+
+/**
+ * Write settings the plugin worked out for itself, not settings somebody typed.
+ *
+ * `register_setting()` hangs `sendbeam_sanitize_settings()` on
+ * `sanitize_option_sendbeam_settings`, which means **every**
+ * `update_option( 'sendbeam_settings', … )` goes through the form's rules —
+ * including the ones this plugin makes on its own behalf. Those rules are
+ * written for a posted form, and three of them are actively wrong for a
+ * programmatic write:
+ *
+ * - "A blank key field keeps the saved key" is right for a password field
+ * somebody left alone, and exactly wrong for Disconnect, which clears the
+ * key on purpose. Disconnect wrote an empty key, the sanitiser put the
+ * old one back, and the site stayed connected. That is the bug the owner
+ * hit, twice.
+ * - A posted form names its tab, so only that tab's keys are touched. A
+ * programmatic array names none, so every key is treated as posted — and
+ * the rule that releases `mail_enabled`, `mail_from_name` and
+ * `mail_from_email` from `sendbeam_connect_filled` fired on every write,
+ * quietly undoing what Connect had just recorded.
+ * - `mail_enabled` is re-derived from "is the box in $input", which is the
+ * right reading of an unchecked checkbox and the wrong reading of an
+ * array a caller simply did not mention it in.
+ *
+ * So programmatic paths come through here instead. The array is already what
+ * the plugin means; it is written as-is, with the one piece of housekeeping
+ * the sanitiser does that still applies — a key that changed invalidates
+ * everything cached under the old one.
+ *
+ * @param array $settings The complete settings array to store.
+ * @return bool Whether anything changed.
+ */
+function sendbeam_write_settings( $settings ) {
+ $before = sendbeam_settings();
+
+ sendbeam_settings_writing( true );
+ $ok = update_option( 'sendbeam_settings', $settings );
+ sendbeam_settings_writing( false );
+
+ // The cached answers belong to the key that fetched them, and that key is
+ // on its way out. Named explicitly, because a site that has just let go
+ // of a key can no longer work out the transient it wrote.
+ $after = (string) sendbeam_settings()['api_key'];
+ if ( (string) $before['api_key'] !== $after ) {
+ sendbeam_connect_forget_status( (string) $before['api_key'] );
+ sendbeam_flush_cache();
+ }
+
+ return $ok;
+}
+
+/**
+ * Is a programmatic write in progress?
+ *
+ * A flag rather than remove_filter()/add_filter() around the update: the
+ * sanitiser is registered by `register_setting()` at a priority this file
+ * does not own, and putting a filter back the way it was found is a much
+ * easier thing to get subtly wrong than reading one boolean.
+ *
+ * @param bool|null $set True or false to set it, null to read it.
+ * @return bool
+ */
+function sendbeam_settings_writing( $set = null ) {
+ static $writing = false;
+ if ( null !== $set ) {
+ $writing = (bool) $set;
+ }
+ return $writing;
+}
+
/**
* Clean everything the form posts. Unknown keys are dropped.
*
@@ -154,14 +242,34 @@ function sendbeam_sanitize_settings( $input ) {
return $out;
}
- // Each tab posts only its own fields. Starting from the saved values and
- // touching only the keys belonging to the posted tab is what stops saving
- // the pop-up from silently clearing the API key — an unchecked checkbox and
- // a field that was never on screen look identical in $_POST otherwise.
+ /*
+ * A write the plugin made for itself. It is already what the plugin
+ * means — see sendbeam_write_settings() for why running the form's rules
+ * over it does the wrong thing three different ways.
+ */
+ if ( sendbeam_settings_writing() ) {
+ unset( $input['_tab'] );
+ return $input;
+ }
+
+ /*
+ * One group per FORM, not per tab. Starting from the saved values and
+ * touching only the keys belonging to the posted group is what stops
+ * saving the pop-up from silently clearing the API key — an unchecked
+ * checkbox and a field that was never on screen look identical in $_POST
+ * otherwise.
+ *
+ * The grouping has to be as fine as the submit buttons are. Forms is one
+ * tab with two cards and two Save buttons, and while both posted `forms`
+ * the fields of whichever card you did not press were read as cleared:
+ * pressing Save on Appearance emptied `contact_form`, and [sendbeam_contact]
+ * renders nothing without it, so a published contact page lost its form.
+ */
$groups = array(
- 'connect' => array( 'api_key' ),
- 'forms' => array( 'default_form', 'contact_form', 'style_accent', 'style_text', 'style_field', 'style_border', 'style_radius', 'style_font', 'style_size', 'style_bare' ),
- 'mail' => array( 'mail_enabled', 'mail_from_name', 'mail_from_email', 'mail_fallback' ),
+ 'connect' => array( 'api_key' ),
+ 'forms' => array( 'default_form', 'contact_form' ),
+ 'forms_style' => array( 'style_accent', 'style_text', 'style_field', 'style_border', 'style_radius', 'style_font', 'style_size', 'style_bare' ),
+ 'mail' => array( 'mail_enabled', 'mail_from_name', 'mail_from_email', 'mail_fallback', 'mail_log_days' ),
);
$tab = isset( $input['_tab'] ) ? sanitize_key( $input['_tab'] ) : '';
$keys = isset( $groups[ $tab ] ) ? $groups[ $tab ] : array_merge( ...array_values( $groups ) );
@@ -202,17 +310,40 @@ 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 : '';
$out['mail_fallback'] = empty( $input['mail_fallback'] ) ? 0 : 1;
+
+ // One of four, and 30 for anything else — a retention nobody
+ // recognises would quietly become "for ever".
+ $days = isset( $input['mail_log_days'] ) ? (int) $input['mail_log_days'] : 30;
+ $out['mail_log_days'] = in_array( $days, array( 0, 7, 30, 90 ), true ) ? $days : 30;
}
// A blank key field keeps the saved key; "remove" clears it.
if ( isset( $touch['api_key'] ) ) {
$key = isset( $input['api_key'] ) ? trim( sanitize_text_field( wp_unslash( $input['api_key'] ) ) ) : '';
if ( ! empty( $input['api_key_remove'] ) ) {
+ /*
+ * The same door as the Overview's Disconnect, and it has to
+ * behave the same way through it. This branch used to clear the
+ * option and stop, so an owner tidying up on the Advanced tab was
+ * left with a live, unrevoked key for a site that no longer
+ * exists as far as they are concerned — the exact situation
+ * Disconnect was written to end.
+ */
+ sendbeam_connect_release_key();
$out['api_key'] = '';
} elseif ( '' !== $key ) {
if ( ! preg_match( '/^[A-Za-z0-9_\-]{16,200}$/', $key ) ) {
@@ -226,10 +357,49 @@ 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
+ // 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'] = '';
+ $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.
+ $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
+ // 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'] );
@@ -256,7 +426,7 @@ function sendbeam_section_forms_intro() {
sprintf(
/* translators: %s: link to the SendBeam forms page */
__( 'Form IDs are under %s in SendBeam: open a form and copy the ID from its Embed panel. Forms load from sendbeam.io, so any change you make there shows on your site straight away.', 'sendbeam' ),
- '
' . esc_html__( 'Forms', 'sendbeam' ) . ' '
+ '
' . esc_html__( 'Forms', 'sendbeam' ) . ' '
),
array(
'a' => array(
@@ -282,11 +452,19 @@ function sendbeam_field_checkbox( $args ) {
$settings = sendbeam_settings();
$key = $args['key'];
printf(
- '
%3$s',
+ '
%3$s ',
esc_attr( $key ),
checked( ! empty( $settings[ $key ] ), true, false ),
esc_html( $args['label'] )
);
+
+ // A ticked box that cannot do anything has to say so where it is ticked.
+ // Otherwise the screen reads as switched on, the test email says to tick
+ // the box that is already ticked, and nothing says the key is missing.
+ if ( 'mail_enabled' === $key && 'no_key' === sendbeam_mail_blocked() ) {
+ echo '
' . esc_html__( 'This site has no SendBeam API key, so its email is still going out through the web server\'s own mailer. Connect the site on the Overview to start using this.', 'sendbeam' ) . '
';
+ }
+
if ( ! empty( $args['help'] ) ) {
echo '
' . esc_html( $args['help'] ) . '
';
}
@@ -309,12 +487,30 @@ function sendbeam_field_api_key() {
if ( $saved ) {
echo '
' . esc_html__( 'Remove the saved key', 'sendbeam' ) . '';
echo '
' . esc_html__( 'A key is saved. Paste a new one to replace it, or leave this empty to keep it.', 'sendbeam' ) . '
';
+ // What removing it does, before it is removed.
+ echo '
' . esc_html( sendbeam_key_removal_note() ) . '
';
} else {
echo '
' . esc_html__( 'Stored in this site\'s options table. For a key that never touches the database, define SENDBEAM_API_KEY in wp-config.php.', 'sendbeam' ) . '
';
}
}
+/**
+ * What "Remove the saved key" will actually do to this site's key.
+ *
+ * The two cases are genuinely different — one revokes a key at SendBeam and
+ * one does not — and the owner cannot tell them apart from the Advanced tab,
+ * which said only "A key is saved. Paste a new one to replace it, or leave
+ * this empty to keep it."
+ *
+ * @return string
+ */
+function sendbeam_key_removal_note() {
+ return sendbeam_connected_via_connect()
+ ? __( 'This site was connected with the Connect button, so removing the key also revokes it in SendBeam — the same as Disconnect on the Overview.', 'sendbeam' )
+ : __( 'This key was pasted in, so it is only forgotten here. It stays live in SendBeam, where anything else using it keeps working.', 'sendbeam' );
+}
+
/**
* Form chooser.
*
@@ -349,7 +545,7 @@ function sendbeam_field_form_id( $args ) {
sprintf(
/* translators: %s: link to create a form */
__( 'This workspace has no forms yet. %s, then come back and refresh.', 'sendbeam' ),
- '
' . esc_html__( 'Create one in SendBeam', 'sendbeam' ) . ' '
+ '
' . esc_html__( 'Create one in SendBeam', 'sendbeam' ) . ' '
),
array(
'a' => array(
@@ -451,55 +647,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() {
@@ -509,7 +671,7 @@ function sendbeam_section_connect_intro() {
sprintf(
/* translators: %s: link to the API keys page */
__( 'One key connects this site to a SendBeam workspace. Make one under %s. Give it
Forms (read) so this page can list your forms, and
Send site email if you want WordPress email to go through SendBeam.', 'sendbeam' ),
- '
' . esc_html__( 'Settings → API keys', 'sendbeam' ) . ' '
+ '
' . esc_html__( 'Settings → API keys', 'sendbeam' ) . ' '
),
array(
'a' => array(
@@ -552,12 +714,12 @@ function sendbeam_section_connect_intro() {
/** "Check again" — drop the cache and re-ask. */
function sendbeam_handle_refresh() {
if ( ! current_user_can( 'manage_options' ) ) {
- wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) );
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
}
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;
}
@@ -567,13 +729,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();
}
@@ -585,8 +747,17 @@ function sendbeam_admin_assets( $hook ) {
// and copy a shortcode without selecting it by hand.
$js = '
( function () {
+ /*
+ * A class rather than the `hidden` property, because the server
+ * already renders these rows hidden when the feature is off: setting
+ * `hidden` here on load would mean the rows drew first and vanished
+ * afterwards, which is a flash on every render of the Site email
+ * screen.
+ */
function toggle( cls, on ) {
- document.querySelectorAll( "tr." + cls ).forEach( function ( tr ) { tr.hidden = ! on; } );
+ document.querySelectorAll( "tr." + cls ).forEach( function ( tr ) {
+ tr.classList.toggle( "is-hidden", ! on );
+ } );
}
var mail = document.getElementById( "sendbeam_mail_enabled" );
function sync() {
@@ -611,6 +782,18 @@ function syncRule( rule ) {
} );
}
}
+ /*
+ * The order is the rule — the first pop-up that matches a page is the
+ * one that opens — so a number that survives a removal and points at
+ * the wrong card is worse than no number at all.
+ */
+ function renumber() {
+ if ( ! host ) { return; }
+ host.querySelectorAll( ".sb-rule .sb-card__head h3" ).forEach( function ( h, n ) {
+ h.textContent = h.textContent.replace( /\d+$/, String( n + 1 ) );
+ } );
+ }
+
if ( host ) {
host.querySelectorAll( ".sb-rule" ).forEach( syncRule );
host.addEventListener( "change", function ( e ) {
@@ -620,18 +803,19 @@ function syncRule( rule ) {
host.addEventListener( "click", function ( e ) {
if ( ! e.target.closest( ".sb-remove" ) ) { return; }
var rule = e.target.closest( ".sb-rule" );
- if ( rule ) { rule.remove(); }
+ if ( rule ) { rule.remove(); renumber(); }
} );
}
if ( addBtn && tpl && host ) {
addBtn.addEventListener( "click", function () {
var i = host.querySelectorAll( ".sb-rule" ).length;
- var html = tpl.innerHTML.split( "__i__" ).join( String( i ) );
+ var html = tpl.innerHTML.split( "__i__" ).join( String( i ) ).split( "__n__" ).join( String( i + 1 ) );
var box = document.createElement( "div" );
box.innerHTML = html;
var rule = box.firstElementChild;
host.appendChild( rule );
syncRule( rule );
+ renumber();
var first = rule.querySelector( "select, input" );
if ( first ) { first.focus(); }
} );
@@ -652,11 +836,56 @@ function syncRule( rule ) {
frame.open();
} );
+ /*
+ * A DNS value is a textarea so that it can wrap on a phone, and a
+ * textarea with one row shows one row however many it needs. This
+ * gives each one the height of its own content, and again when the
+ * window changes width — the value that fits on one line at 1280px
+ * takes three at 393px.
+ */
+ function fitFields() {
+ document.querySelectorAll( ".sb-copy-field" ).forEach( function ( field ) {
+ field.style.height = "auto";
+ field.style.height = field.scrollHeight + "px";
+ } );
+ }
+ if ( document.querySelector( ".sb-copy-field" ) ) {
+ fitFields();
+ var fitTimer = null;
+ window.addEventListener( "resize", function () {
+ clearTimeout( fitTimer );
+ fitTimer = setTimeout( fitFields, 120 );
+ } );
+ // A records table folded away in a
has no height to
+ // measure until it is opened.
+ document.addEventListener( "toggle", function ( e ) {
+ if ( e.target && "DETAILS" === e.target.tagName ) { fitFields(); }
+ }, true );
+ }
+
document.addEventListener( "click", function ( e ) {
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 || "TEXTAREA" === 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 );
@@ -675,5 +904,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/includes/site-health.php b/includes/site-health.php
new file mode 100644
index 0000000..ef297c5
--- /dev/null
+++ b/includes/site-health.php
@@ -0,0 +1,460 @@
+ __( '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'
+ );
+}
+
+/**
+ * How this site's key arrived, in words, including "it did not".
+ *
+ * @return string
+ */
+function sendbeam_connected_by_label() {
+ if ( '' === sendbeam_api_key() ) {
+ return __( 'Nothing — this site has no key', 'sendbeam' );
+ }
+ return sendbeam_connected_via_connect()
+ ? __( 'The Connect button', 'sendbeam' )
+ : __( 'A pasted key', 'sendbeam' );
+}
+
+/**
+ * The sending domain's state, never blank.
+ *
+ * @param array $status Normalised status.
+ * @return string
+ */
+function sendbeam_domain_state_label( $status ) {
+ if ( ! empty( $status['domain']['verified'] ) ) {
+ return 'verified';
+ }
+ $state = trim( (string) $status['domain_state'] );
+ if ( '' !== $state ) {
+ return $state;
+ }
+ return '' === sendbeam_api_key()
+ ? __( 'Not asked — this site has no key', 'sendbeam' )
+ : __( 'Not reported', 'sendbeam' );
+}
+
+/**
+ * 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' ) );
+
+ $blocked = sendbeam_mail_blocked();
+
+ if ( 'off' === $blocked ) {
+ 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'
+ );
+ }
+
+ /*
+ * Switched on with no key. The critical alarm below is about email being
+ * handed to an unverified sender, and none of this site's email goes near
+ * SendBeam at all: sendbeam_pre_wp_mail() cannot short-circuit without a
+ * key, so every message leaves by the server's own mailer exactly as it
+ * did before. Raising a red flag about a thing that is not happening is
+ * how a Site Health page teaches people to ignore it.
+ */
+ if ( 'no_key' === $blocked ) {
+ return sendbeam_health_result(
+ __( 'This site\'s email does not go through SendBeam yet', 'sendbeam' ),
+ 'recommended',
+ 'blue',
+ esc_html__( 'Site email is switched on, but this site has no SendBeam API key, so WordPress is still sending its own email the way it did before. Connect the site and it will start going through SendBeam.', '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' ),
+ // Three cases, not two. This block is what somebody pastes into a
+ // support request, so "Connected by: A pasted key" on a site with
+ // no key at all is the first thing support reads and the first
+ // thing that sends them the wrong way.
+ 'value' => sendbeam_connected_by_label(),
+ ),
+ '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' ),
+ // domain_state is empty on a site that has never asked, and a
+ // blank value in a support paste reads as a bug in the report.
+ 'value' => sendbeam_domain_state_label( $status ),
+ ),
+ '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..41fa74a 100644
--- a/includes/sync.php
+++ b/includes/sync.php
@@ -43,6 +43,21 @@
add_action( 'woocommerce_review_order_before_submit', 'sendbeam_sync_checkout_field' );
add_action( 'woocommerce_checkout_order_processed', 'sendbeam_sync_on_checkout', 10, 1 );
+/*
+ * The two hooks above belong to the classic, shortcode checkout. The checkout
+ * WooCommerce installs by default is the block one, which renders through the
+ * Store API and fires neither of them — so a new store got no box and no
+ * subscription while the readme promised both. The block checkout takes its
+ * extra fields from a registry instead, and hands the order back on its own
+ * hook once it is processed.
+ */
+add_action( 'woocommerce_init', 'sendbeam_sync_register_block_checkout_field' );
+add_action( 'woocommerce_store_api_checkout_order_processed', 'sendbeam_sync_on_block_checkout', 10, 1 );
+
+/** The block checkout's name for the opt-in box, and the order meta it lands in. */
+const SENDBEAM_BLOCK_OPTIN_FIELD = 'sendbeam/subscribe';
+const SENDBEAM_BLOCK_OPTIN_META = '_wc_other/sendbeam/subscribe';
+
/**
* Defaults.
*
@@ -142,6 +157,52 @@ function sendbeam_sync_checkout_field() {
*
* @return bool
*/
+/**
+ * Register the opt-in box with the block checkout, in the "Order information"
+ * area above Place order, only while the source is switched on and usable —
+ * a field that could not subscribe anybody should not be asked.
+ */
+function sendbeam_sync_register_block_checkout_field() {
+ if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) || ! sendbeam_sync_active( 'woocommerce' ) ) {
+ return;
+ }
+ woocommerce_register_additional_checkout_field(
+ array(
+ 'id' => SENDBEAM_BLOCK_OPTIN_FIELD,
+ 'label' => sendbeam_sync_label(),
+ 'location' => 'order',
+ 'type' => 'checkbox',
+ 'required' => false,
+ )
+ );
+}
+
+/**
+ * The block checkout processed an order: subscribe the customer if, and only
+ * if, they ticked the box. The value is read from the order itself, where
+ * WooCommerce stores every additional field, never from the request.
+ *
+ * @param WC_Order $order The order, as the Store API hands it over.
+ */
+function sendbeam_sync_on_block_checkout( $order ) {
+ if ( ! sendbeam_sync_active( 'woocommerce' ) || ! is_object( $order ) || ! method_exists( $order, 'get_meta' ) ) {
+ return;
+ }
+ if ( empty( $order->get_meta( SENDBEAM_BLOCK_OPTIN_META ) ) ) {
+ return;
+ }
+ $email = $order->get_billing_email();
+ if ( ! is_email( $email ) ) {
+ return;
+ }
+ sendbeam_subscribe( $email, $order->get_billing_first_name(), $order->get_billing_last_name(), 'woocommerce-checkout' );
+}
+
+/**
+ * Did the submitter tick the opt-in box on a classic form?
+ *
+ * @return bool
+ */
function sendbeam_sync_consented() {
// A passenger on a form WordPress or WooCommerce has already validated and
// nonce-checked. We read one checkbox and never act on it alone: the caller
@@ -224,7 +285,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
*/
@@ -408,7 +469,7 @@ function sendbeam_sync_log( $email, $source, $ok, $note ) {
/** Save the Audience settings. */
function sendbeam_handle_save_sync() {
if ( ! current_user_can( 'manage_options' ) ) {
- wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) );
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'sendbeam_save_sync' );
diff --git a/includes/wizard.php b/includes/wizard.php
new file mode 100644
index 0000000..74181e9
--- /dev/null
+++ b/includes/wizard.php
@@ -0,0 +1,458 @@
+
+ */
+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' ), '', array( 'response' => 403 ) );
+ }
+ 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;
+ $is_done = ! empty( $done[ $step['key'] ] );
+ $state = 'sb-rail__step';
+ if ( $is_done ) {
+ $state .= ' is-done';
+ }
+ if ( $number === $current ) {
+ $state .= ' is-current';
+ }
+ printf(
+ '%3$s %4$s ',
+ esc_attr( $state ),
+ $number === $current ? ' aria-current="step"' : '',
+ $is_done ? '✓' : (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 '';
+ 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 );
+}
+
+/**
+ * The way back into the guide, once somebody has been through it.
+ *
+ * Every plugin in the field study with a wizard offers one — WooCommerce and
+ * WP Mail SMTP both keep theirs reachable for good — because the first run is
+ * also the best way to check a change, and because somebody setting up a
+ * second site wants the same walk-through on it.
+ *
+ * It resets where *this person* got to and nothing else. `sendbeam_setup_done`
+ * is the site's answer to "has anybody set this up?", which is what keeps the
+ * Dashboard notice away, and re-reading the guide is not un-setting-up a site.
+ *
+ * @return string
+ */
+function sendbeam_wizard_restart_url() {
+ return wp_nonce_url(
+ add_query_arg( 'action', 'sendbeam_wizard_restart', admin_url( 'admin-post.php' ) ),
+ 'sendbeam_wizard_restart'
+ );
+}
+
+/** Put this person back at step 1 and open the guide. */
+function sendbeam_handle_wizard_restart() {
+ if ( ! current_user_can( 'manage_options' ) ) {
+ wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) );
+ }
+ check_admin_referer( 'sendbeam_wizard_restart' );
+
+ delete_user_meta( get_current_user_id(), SENDBEAM_WIZARD_STEP );
+
+ wp_safe_redirect( sendbeam_wizard_url( 1 ) );
+ exit;
+}
diff --git a/readme.txt b/readme.txt
index 78cb144..03eab40 100644
--- a/readme.txt
+++ b/readme.txt
@@ -1,10 +1,10 @@
=== SendBeam ===
-Contributors: sendbeam
+Contributors: sendbeam, sendbeamsupport
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
@@ -17,21 +17,27 @@ Newsletter signup forms, pop-ups, opt-ins at registration and checkout, and your
This plugin puts your SendBeam forms on a WordPress site without copying embed code around:
* **SendBeam Form block** — pick a form, set a height, done. Works in posts, pages, templates and the site editor.
-* **Shortcodes** — `[sendbeam_form id="…"]`, `[sendbeam_contact]` and `[sendbeam_popup_button]` for widgets, page builders and the classic editor.
+* **Shortcodes** — `[sendbeam_form id="…"]`, `[sendbeam_contact id="…"]` and `[sendbeam_popup_button]` for widgets, page builders and the classic editor.
* **Pop-up** — show a signup form in a modal after a delay or from a floating button, on every page, posts only, pages only or the home page; hidden for a day, a week or for good once a visitor closes it.
* **Pop-up styles** — four looks for the modal: split with image, editorial, bold colour and slide-in, each with its own image, eyebrow, button label and optional subscriber count, chosen per pop-up.
-* **A default form** — set it once under Settings → SendBeam and every block and shortcode without an ID uses it.
+* **A default form** — set it once under SendBeam → Forms and every block and shortcode without an ID uses it.
* **Form plugins** — send the people who fill in forms built with Contact Form 7, Elementor Pro, WPForms, Gravity Forms or Fluent Forms to SendBeam, onto the list and with the tag you choose. Switched on form by form, and only for people who ticked your consent field or filled in a form you marked as a signup form.
-* **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.
+* **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 searchable log of every message with what became of it and which plugin asked for it.
+* **E-commerce events** (WooCommerce) — feed SendBeam's native Cart Abandoned, Product Viewed and Order Placed automation triggers. Order placed fires once, when the order is paid, and keeps a running lifetime-value total on the contact. Each event has its own switch, off by default. Works with both the classic checkout and the block checkout WooCommerce installs.
+
+It has its own menu in wp-admin, with a page per section — Overview, Forms, Pop-ups, Audience, Site email, E-commerce, Settings and Help — and walks a new site through connecting, verifying its sending domain, switching on site email and placing a form the first time it is activated. That guide can be skipped a step at a time or left entirely; every step is also on the Overview.
+
+**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.
+Your forms, your lists and the site's email log are proper WordPress list tables: search, sort out how many rows you want per screen, and delete log entries in bulk, the same way the Posts screen works. **SendBeam → Help** carries the documentation links, the shortcodes, what each API key permission is for, and a system-status block that copies in one press for a support email; the same information is in Tools → Site Health, along with three checks — your key works, your sending domain is verified, and your site's email is not being sent from a domain nothing has verified.
+
A site can listen for `sendbeam:submitted` on `document` to track a signup as an analytics goal or redirect to a thank-you page.
= 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.
@@ -39,13 +45,17 @@ This plugin talks to SendBeam (sendbeam.io) in five distinct ways. Nothing is se
**3. The plugin's settings screens.** While a site administrator has the SendBeam settings page open, your server calls SendBeam with your API key to list your forms (`/api/v1/forms`), your lists (`/api/v1/lists`), the number of people on each list (`/api/v1/lists//contacts`) and your subscriber total (`/api/v1/contacts`). This is what lets the plugin offer your forms in a dropdown instead of asking you to paste an ID. The results are cached for five minutes. No visitor data is involved and nothing is sent on front-end page loads.
-**4. Subscribing someone who ticked the opt-in box** (off by default). When a visitor registers an account, leaves a comment or checks out in WooCommerce *and* ticks the subscribe box, their email address, first and last name and which of those three things they were doing are sent to `/api/v1/contacts` and added to the lists you chose. Nobody who has not ticked the box is ever sent, and the box is never pre-ticked.
+**4. Subscribing someone who ticked the opt-in box** (off by default). When a visitor registers an account, leaves a comment or checks out in WooCommerce (the classic or the block checkout) *and* ticks the subscribe box, their email address, first and last name and which of those three things they were doing are sent to `/api/v1/contacts` and added to the lists you chose. Nobody who has not ticked the box is ever sent, and the box is never pre-ticked.
**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.
+
+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.
+**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 once an order is paid — when it reaches processing or completed — never for a checkout that ends unpaid, and once per order. 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.
Full setup documentation: [sendbeam.io/docs/wordpress](https://sendbeam.io/docs/wordpress). See also the [SendBeam privacy policy](https://sendbeam.io/legal/privacy) and [terms](https://sendbeam.io/legal/terms).
@@ -55,12 +65,40 @@ 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.
+1. Install and activate the plugin. Activating it once takes you to **SendBeam → Set up**, a four-step guide. Every step can be skipped, and **Go back to the Dashboard** leaves it — nothing has to be done now, and everything on it is also on the Overview.
+2. **Connect.** Press **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, and so does **SendBeam → Settings → Advanced**.
+3. **Verify your sending domain.** The plugin shows the records as a table of Type, Host and Value, each value a field that copies when you click it, with a column saying which are live yet — or it sets them up for you where your registrar supports that, and brings you back here when it has. DNS changes can take up to 24 hours to spread, so the site checks again every hour for a day and you can close the tab. Nothing SendBeam sends for you leaves your own domain until this is done.
+4. **Site email**, if you want it: one switch, and a test email that tells you in the page whether it worked — and, if it did not, what went wrong, what it means, what to do about it, and a block of detail you can copy into a support message.
+5. **Put a form on the site.** Add the **SendBeam Form** block to a post or page, or use `[sendbeam_form]` anywhere shortcodes work. Pick which form is the default under **SendBeam → Forms**.
+
+Hosts and agencies who set the plugin up themselves can switch the first-run guide off entirely with `add_filter( 'sendbeam_setup_wizard', '__return_false' );`.
== Frequently Asked Questions ==
+= Where did Settings → SendBeam go? =
+
+SendBeam has its own menu now, below Settings, with a page for each section instead of seven tabs nothing in the menu mentioned. Every old address still works: `options-general.php?page=sendbeam` and each of its tabs redirect permanently to the page that replaced it, so bookmarks and links in old support replies still land in the right place. The Docs tab became the **Help** page.
+
+= I do not want the setup guide on my clients' sites =
+
+`add_filter( 'sendbeam_setup_wizard', '__return_false' );` switches off the one-time redirect. The guide is still reachable at **SendBeam → Set up** if anybody wants it, and the Overview's checklist is unaffected. The guide never appears when you activate several plugins at once, and never on a site that already has a key.
+
+= My site says the domain is verified but it is still sending as post.sendbeam.io =
+
+Those are two different settings, and until 1.8.3 the Overview let them contradict each other. Verifying a domain proves the domain is yours; the From address decides which address the site actually uses, and it starts as SendBeam's shared one. The site-email step on the Overview now says so plainly and has a **Send from yourdomain.com** button that changes it in one press. You can also set it by hand under **SendBeam → Site email → From address**.
+
+= Can I run the setup guide again? =
+
+Yes — **SendBeam → Help → Run the setup guide again**. It puts you back at step 1 and changes nothing: it walks through what is already set up and shows you what is not.
+
+= How long is the email log kept? =
+
+Thirty days by default; **SendBeam → Site email → Keep log entries for** offers 7, 30 or 90 days, or for ever. Older entries are deleted once a day by a scheduled job, and whatever you choose the log is capped at 20,000 messages with the oldest going first — "for ever" is a promise about time, not about disk space. **Clear the log** empties it now. Only the recipient, the subject, the result and which plugin asked for the message are stored; the message itself never is.
+
+= The test email says it failed. What now? =
+
+The failure card on **SendBeam → Site email** says what went wrong, what it means and what to do, and has a **Details for support** block underneath it — the WordPress and PHP versions, where this site's key is kept (never the key itself), the sending domain and its state, the HTTP status and the raw error, all captured at the moment the send failed rather than whenever you get round to writing. Press **Copy these details** and paste them into an email to hello@sendbeam.io.
+
= Where do I find a form ID? =
In SendBeam, open **Forms**, click the form, and copy the ID from the Embed panel. It looks like `8f3c1a2e-3b1d-4c55-9a0e-1f2d3c4b5a69`.
@@ -81,33 +119,49 @@ No. WordPress keeps sending its own mail. SendBeam only receives what visitors s
With it on, every email WordPress sends goes through SendBeam's API instead of the server's `mail()` function, from your verified domain, so it stops landing in spam. WooCommerce, membership, booking and form plugins all use `wp_mail()`, so they are covered without any setting of their own. Turn it off and everything goes back to how it was.
+= Does the plugin tell me if something is wrong? =
+
+Tools → Site Health carries three SendBeam checks: whether this site's key works, whether the sending domain is verified, and whether site email is switched on behind a verified domain. That last one reports as critical when it is not — a site quietly sending its password resets from a domain no mailbox provider can check is worse off than one not using the feature at all. Site Health → Info has a SendBeam section with every state this site holds, and **SendBeam → Help** shows the same thing with a **Copy for support** button.
+
= Which API key permissions does the plugin need? =
Only what you actually use, and the plugin works with less:
* **Forms (read)** — so the settings page and the block can list your forms instead of asking for an ID. Without it you can still type IDs by hand.
-* **Lists (read)** — for the Audience tab and its subscriber counts.
+* **Lists (read)** — for the Audience screen and its subscriber counts.
* **Contacts (read and write) and Lists (write)** — only if you switch on the opt-in box for registrations, comments or WooCommerce checkout, or connect a form plugin.
* **Tags (read and write)** — only if a connected form adds a tag.
* **Send site email** (`transactional:send`) — only if you switch on Site email.
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:
+Yes. Each is set up where that plugin keeps its own settings, and SendBeam → Audience lists which are active:
* **Contact Form 7** — open a form and use its **SendBeam** tab. Name the email, name and consent fields as they appear in the form, without the square brackets.
* **Elementor Pro** — in the Form widget, add **SendBeam** under Actions After Submit, then fill in the SendBeam section with the field IDs from each field's Advanced tab.
* **WPForms** — in the form builder, open **Settings → SendBeam** and pick the fields from the dropdowns.
* **Gravity Forms** — open **Settings → SendBeam** on a form and add a feed. Map the fields, and use conditional logic if you like.
-* **Fluent Forms** — choose the forms on the **Audience** tab of Settings → SendBeam.
+* **Fluent Forms** — choose the forms on **SendBeam → Audience**.
A form sends someone only when they ticked the consent field you named, or when you have marked it as a signup form that people fill in to subscribe. The subscription happens straight after the form is submitted, so the visitor's form is never slowed down, and each attempt appears under Recent subscriptions.
= What about emails with attachments? =
-They are left to the server's own mailer for now, and the recent-email table on the settings page says so.
+They are left to the server's own mailer for now, and the email log on SendBeam → Site email says so.
= Does it work with caching plugins? =
@@ -115,16 +169,76 @@ Yes. The form is an iframe and the pop-up is a script tag, both cache-safe.
== Screenshots ==
-1. The SendBeam Form block, showing the real form as it will appear on the page.
-2. Settings → SendBeam: what is set up, and what the workspace holds.
-3. The Forms tab, where the default forms and their colours are set.
-4. The Audience tab: the workspace's lists, and where to ask people to subscribe.
-5. The Pop-ups tab. Rules are matched top to bottom and the first one wins.
-6. A pop-up on the site, using the site's own colours.
-7. The Site email tab, which routes wp_mail() through SendBeam.
+1. The SendBeam Form block on a page: the real form, as visitors see it.
+2. SendBeam → Overview: what this site is connected to, how far through set-up it is, and what the workspace holds.
+3. SendBeam → Set up, the four-step guide a new site sees once. Every step can be skipped and the whole thing can be left.
+4. SendBeam → Forms: the default forms and their colours; every form in the workspace is a searchable list further down.
+5. SendBeam → Settings → Sending domain: the DNS records, each value one click from the clipboard, with a column saying which are live yet.
+6. SendBeam → Site email: the relay, a test send that reports in the page, and the log of what went out.
+7. SendBeam → Pop-ups. Rules are matched top to bottom and the first one wins.
+8. A pop-up on the site, using the site's own colours.
+9. SendBeam → Help: a system-status block that copies for support, and where to get help.
== Changelog ==
+= 1.8.3 =
+* The DNS records show on the Overview at every width. A styling rule for the checklist had leaked into the numbered list inside step 2 and squeezed the records table to two pixels, so a site connecting a second domain saw the instructions and nothing to add.
+* The sending-domain step on the Overview opens the plugin's own Sending domain screen, where the records are, rather than the SendBeam app; SendBeam is only where you go to add a domain when the site has none.
+* The opt-in box and the order event now work on the block checkout WooCommerce installs by default, not only the classic one.
+* Order placed sends once an order is paid, once per order — not at checkout for an order that might never be paid.
+* Pop-ups never open on the cart, checkout or account pages, whatever a rule says, so nothing sits over Place order.
+* **The SendBeam Form block shows a card in the editor, not the form.** Its live preview was rendering the hosted form in a nested iframe with no origin of its own, so SendBeam — which serves a form only to the sites its owner has listed, and decides that from the referrer — answered "This form can only be shown on the sites its owner has listed" on a site that is listed. The editor now shows which form the block will place, a line saying the form appears there on the published page, and a **Preview** link that opens the real one in a tab. The published page is unchanged: it embeds the form exactly as before.
+* **SendBeam has its own menu.** It lived at Settings → SendBeam behind seven tabs that appeared nowhere 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 a page for each section — Overview, Forms, Pop-ups, Audience, Site email, E-commerce, Settings and Help. Every old address redirects permanently to the page that replaced it, so bookmarks and links in old support replies still work, and the Plugins-screen "Settings" link goes to the settings rather than to a dashboard.
+* **A four-step guide the first time you activate it**: connect, verify your sending domain, switch on site email, place a form. It appears once, never when you activate several plugins at once, and never on a site that already has a key. Every step can be skipped, **Go back to the Dashboard** leaves it, and where you got to is remembered. Hosts and agencies can switch it off with the `sendbeam_setup_wizard` filter.
+* **Your forms, your lists and the email log are proper WordPress list tables** — search, a rows-per-screen setting under Screen Options, and bulk delete on the log — so they behave like the Posts screen and collapse the way core does on a phone. That last part fixed the two screens that scrolled sideways on a phone.
+* **The sending domain reads like a set of instructions.** Type, Host and Value in a table, every value a field that copies when you click it, a tick or "not found yet" per record, "DNS changes can take up to 24 hours", and three states rather than two: verified, pending — some records live — and not found. "Pending" and "not found" looked identical before, and only one of them has work left in it.
+* **The test email is a real email, and its result appears in the page.** It carries the From name and address used, the sending domain and whether it is verified, the workspace, the version and the time, and what happens now — one screenful worth keeping. Success or failure replaces the form rather than becoming a notice, and a failure gets what went wrong, what it means, what to do about it, and a block of detail captured at the moment it failed that copies in one press for a support email. Your API key is never in it.
+* **Three checks in Tools → Site Health**: your key works, your sending domain is verified, and your site's email is not going out from a domain nothing has verified — that last one reports as critical, because it is. Site Health → Info gains a SendBeam section with every state this site holds.
+* **A Help page** replaces the Docs tab: the documentation, the shortcodes, the permissions table, who to ask for help, a system-status block with **Copy for support**, and **Run the setup guide again** for when you want to walk through it on a second site or check a change.
+* **Fixed: Disconnect did not disconnect.** Pressing it cleared the key and then WordPress's own settings-saving rules put it straight back, because the rule that keeps a password field you left alone cannot tell itself apart from a button whose whole job is clearing one. The site stayed connected however many times you pressed it.
+* **The email log is a real log.** It was the last twenty messages kept in a WordPress option, which a shop doing thirty order emails an hour lost by lunchtime. It is a table of its own now: search it by address, subject or the reason something failed; filter by Sent, Server mailer or Failed with a count on each; sort by date or result; page through it at whatever size you like; and see which plugin asked for each message. Keep it for 7, 30 or 90 days or for ever, pruned daily and capped at 20,000 entries so it cannot grow without limit. **Clear the log** empties it behind its own confirmation. The message itself is never stored — only who it went to, its subject, and what became of it. Your existing entries move across on the first page load after updating.
+* **The Pop-ups screen matches the rest of the plugin.** Each rule was a grey box with a black tag on it — the one screen that looked like a different product. Every rule is now the same white card used everywhere else, numbered in the order they are matched ("Pop-up 1", "Pop-up 2", because the first one that matches a page is the one that opens), with the Active switch and Remove in the card's header. Eyebrow and Button label share a row with their labels lined up. Adding or removing a pop-up renumbers the rest.
+* **Nothing flashes on the Overview any more.** The Disconnect confirmation was shipped open and hidden by script on load, so a red-bordered box drew and vanished on every refresh. It is a native disclosure now — shut until you press Disconnect, no script involved, and it still works with JavaScript off. The Site email settings rows that only apply when site email is on arrive hidden rather than appearing and disappearing.
+* **The connected card is one card, however the key got there.** A site using a pasted key was shown "Connected" in the header and a **Connect this site** button underneath it. It now says what it is connected to and how — "via Connect" or "using an API key" — with one **Disconnect** and, for a connection made through the button, **Reconnect**. Nothing on it offers to connect an already-connected site, and replacing a key lives under Settings, where settings live.
+* Switching to one-click Connect is offered where a pasted key actually falls short — the step that cannot name your sending domain without it — and nowhere else.
+* Disconnecting a site that uses a pasted key no longer revokes that key in SendBeam. It may well be in use on another site; it is forgotten here and left alone there, and the confirmation says so.
+* A pasted key's permissions are not recorded anywhere, so the plugin stops saying they were withheld. "Was this key allowed to do that?" has three answers and the third is "no idea" — the site email step now offers the switch rather than claiming a permission was refused, and SendBeam decides on the first message.
+* **The test email says which address it actually came from.** It used to print "From address ws-…@post.sendbeam.io" two rows above "Sending domain yourdomain.com — verified", under a headline saying the site could send — telling a reader their domain was verified and in use when only half of that was true. Every line of it now comes from the same answer the Overview uses: the headline says whether it came from your domain or from the shared address, the From row says what kind of address it is, a new "Signed by" row names the domain that actually authenticated the message, and the sending-domain row says "verified and in use", "verified, but not in use yet" or "not verified yet". Where something is left to do there is a **Next step** block above the rest, with the button that does it.
+* The result in wp-admin says the same thing: a send from the shared address is a success with an amber note beside it, not a plain tick.
+* The test email declares light and dark so a phone mail client stops inverting it into something unreadable and stops turning every address in it into a blue link of its own invention; below 480 px each label sits above its value instead of taking a third of the screen.
+* The three workspace figures stay in one row on a phone instead of stacking into half a card, and the recent-email rows use a short date so the address and the result fit on one line.
+* **The DNS records are readable on a phone.** Four columns in 393 px gave the host and the value about ninety pixels each — enough to read "resend._dc" and nothing else, on the one screen whose whole job is reading them. Each record is now a block: what it is and whether it is live on one line, then the host and then the value, each the full width and each free to wrap. On desktop the value column gets the room instead, and the fields no longer clip the underscore in a DKIM host.
+* **The Overview stops contradicting itself about what your site sends as.** It was possible for the sending-domain step to say your domain was verified while every message still went out as SendBeam's shared address — two true sentences that added up to a wrong one. The domain step now says only that the domain is verified; the site-email step says what is actually happening, names the address, and offers one press to send from your own domain instead. The connection line says which kind of address it is: "(your domain)", "(SendBeam's shared address)" or "(not a verified domain)". A site sending from a domain this workspace has not verified is told that SendBeam refuses those messages.
+* Switching site email on once the domain verifies now puts the From address on that domain rather than leaving the site on SendBeam's shared one, and corrects an address Connect wrote earlier — but never one you typed yourself.
+* **Everything the plugin says now looks like WordPress saying it.** Each screen used to print its own message band somewhere in its own markup; they are admin notices now, in core's own styling, above the page, and only on SendBeam's own screens. The one exception is a single dismissible notice on the Dashboard for a site nobody has set up, which goes for good the first time it is dismissed.
+* **The design stops shouting.** Labels are sentence case at a readable size instead of 10px uppercase mono; mono is kept for the values people copy. Primary buttons use your admin colour scheme's own colour rather than black, secondary buttons are outlined, and Disconnect is outlined in vermilion — a filled red button beside a filled blue one is a coin toss at a glance. Fields are label-above and 40px tall, on/off settings are switches, and the page has the same margin on both sides.
+* **Connect SendBeam.** One button on the Overview 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 plugin 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.
+* 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.
+* On a site with the key set in `wp-config.php`, the paste field goes away too, not just the button. A key saved there would lose to the constant on every request.
+* Reconnecting into a different workspace forgets what this site knew about the old one before it asks about the new one, rather than showing the previous workspace's sending domain for a minute.
+* The step that is waiting on a permission nobody ticked offers the way out on the step you are standing on, not only on the one it is queued behind.
+* The sending-domain step says how to change the domain as well as how to finish it: "Sending from the wrong domain? Reconnect and enter the one you want."
+* "I've placed it elsewhere" is offered whenever the workspace has a form at all, not only when a default one has been chosen — a form named in its own shortcode is still a form on the site.
+* Coming back from a registrar says the check has run, in the past tense, because by then it has. "Checking now…" promised a page that was about to change and then never changed.
+* The first step's link points at the Connect button rather than at the paste field underneath it.
+
= 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..c267f54 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__ ) );
@@ -28,8 +28,16 @@
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';
require SENDBEAM_DIR . 'includes/render.php';
+require SENDBEAM_DIR . 'includes/mail-log.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 c95f2a8..1011939 100644
--- a/tests/smoke.php
+++ b/tests/smoke.php
@@ -22,6 +22,48 @@ function popup_output() {
function has( $hay, $needle, $what ) { ok( false !== strpos( $hay, $needle ), "$what — expected to find: $needle\nGOT: $hay" ); }
function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ), "$what — did not expect: $needle\nGOT: $hay" ); }
+/*
+ * The classes are not declared until a screen that needs one asks for them.
+ * They extend WP_List_Table, which lives in wp-admin/includes and is NOT
+ * loaded when plugins are — so declaring them at plugin-load time is a fatal
+ * error on every page of a real site. Nothing but loading the plugin inside
+ * WordPress shows that, which is why it is asserted here.
+ */
+ok( ! class_exists( 'SendBeam_Forms_Table', false ), 'list tables: nothing extends WP_List_Table at plugin-load time' );
+ok( sendbeam_load_list_table(), 'list tables: a screen that needs them can load them' );
+ok( class_exists( 'SendBeam_Forms_Table', false ), 'list tables: and then the Forms table exists' );
+ok( class_exists( 'SendBeam_Mail_Log_Table', false ), 'list tables: and the email log' );
+ok( class_exists( 'SendBeam_Lists_Table', false ), 'list tables: and the audience lists' );
+ok( sendbeam_load_list_table(), 'list tables: asking twice is harmless' );
+
+/*
+ * The email log is a table now, so the whole run needs a $wpdb. The one test
+ * that deliberately runs without one swaps it out and puts it back.
+ */
+$GLOBALS['wpdb'] = new SendBeam_Stub_MailDb();
+
+/*
+ * Register the option for real, so update_option() runs the sanitiser the way
+ * WordPress does. Without this the whole class of "a programmatic write goes
+ * through the form's rules" bug is invisible here.
+ */
+sendbeam_admin_init();
+ok( isset( $GLOBALS['stub']['sanitize']['sendbeam_settings'] ), 'settings: the option is registered with its sanitiser, as WordPress has it' );
+
+/** The log, newest first, the way every screen reads it. */
+function sb_log() {
+ $rows = $GLOBALS['wpdb']->rows;
+ usort( $rows, function ( $a, $b ) { return ( (int) $b['id'] ) - ( (int) $a['id'] ); } );
+ return array_values( $rows );
+}
+
+/** Empty it between tests. */
+function sb_log_reset() {
+ $GLOBALS['wpdb']->rows = array();
+ $GLOBALS['wpdb']->next_id = 1;
+ $GLOBALS['wpdb']->queries = array();
+}
+
$form = '8f3c1a2e-3b1d-4c55-9a0e-1f2d3c4b5a69';
$other = '11111111-2222-4333-8444-555555555555';
@@ -34,13 +76,13 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
// Saving one tab must not flatten the others: an unchecked box and a field
// that was never on screen look identical in $_POST.
-update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_keptkeptkept', 'default_form' => $form, 'mail_enabled' => 1 ) );
+sb_seed_settings( array( 'api_key' => 'sb_live_keptkeptkept', 'default_form' => $form, 'mail_enabled' => 1 ) );
$kept = sendbeam_sanitize_settings( array( '_tab' => 'forms', 'default_form' => $other, 'contact_form' => '' ) );
ok( $kept['api_key'] === 'sb_live_keptkeptkept', 'saving Forms keeps the API key' );
ok( (int) $kept['mail_enabled'] === 1, 'saving Forms keeps site email on' );
$off = sendbeam_sanitize_settings( array( '_tab' => 'mail' ) );
ok( (int) $off['mail_enabled'] === 0, 'unchecking site email on its own tab turns it off' );
-update_option( 'sendbeam_settings', array() );
+sb_seed_settings( array() );
// Pop-up rules: unknown enums fall back, numbers are clamped, tags are stripped.
$rule = sendbeam_clean_popup( array( 'form' => $other, 'trigger' => 'moon', 'where' => 'moon', 'delay' => '999', 'scroll' => '999', 'once' => 'week', 'label' => 'Join ', 'enabled' => '1' ) );
@@ -97,7 +139,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
has( do_shortcode_tag( 'sendbeam_form' ), 'no form ID', 'editors get a notice' );
has( do_shortcode_tag( 'sendbeam_form', array( 'id' => $form, 'height' => '700' ) ), 'height:700px', 'explicit id + height' );
-update_option( 'sendbeam_settings', array( 'default_form' => $form, 'contact_form' => $other, 'popup_form' => $other, 'popup_where' => 'posts', 'popup_delay' => 3, 'popup_once' => 'week', 'popup_trigger' => 'timer' ) );
+sb_seed_settings( array( 'default_form' => $form, 'contact_form' => $other, 'popup_form' => $other, 'popup_where' => 'posts', 'popup_delay' => 3, 'popup_once' => 'week', 'popup_trigger' => 'timer' ) );
has( do_shortcode_tag( 'sendbeam_form' ), '/f/' . $form . '?embed=1', 'default form used' );
has( do_shortcode_tag( 'sendbeam_contact' ), '/f/' . $other . '?embed=1', 'contact form used' );
has( do_shortcode_tag( 'sendbeam_contact' ), 'title="Contact form"', 'contact title' );
@@ -112,7 +154,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
$tag = $GLOBALS['stub']['printed'];
has( $tag, '/f/' . $other . '/popup.js?v=', 'loader src carries an appearance fingerprint' );
$first_stamp = sendbeam_popup_script_url( $other );
-update_option( 'sendbeam_settings', array_merge( sendbeam_settings(), array( 'style_accent' => '#123456' ) ) );
+sb_seed_settings( array_merge( sendbeam_settings(), array( 'style_accent' => '#123456' ) ) );
ok( sendbeam_popup_script_url( $other ) !== $first_stamp, 'changing a colour changes the loader URL' );
// The style is part of the same fingerprint: a pop-up switched from split to
// bold has to reach a visitor still holding the cached loader.
@@ -215,7 +257,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
// Upgrading from the single pop-up: the old settings become rule one.
delete_option( 'sendbeam_popups' );
-update_option( 'sendbeam_settings', array( 'popup_form' => $form, 'popup_where' => 'home', 'popup_trigger' => 'button', 'popup_delay' => 3, 'popup_once' => 'week', 'popup_label' => 'Join us' ) );
+sb_seed_settings( array( 'popup_form' => $form, 'popup_where' => 'home', 'popup_trigger' => 'button', 'popup_delay' => 3, 'popup_once' => 'week', 'popup_label' => 'Join us' ) );
$migrated = sendbeam_popups();
ok( count( $migrated ) === 1, 'legacy pop-up migrates to one rule' );
ok( $migrated[0]['form'] === $form && $migrated[0]['where'] === 'home', 'migrated form and placement' );
@@ -226,7 +268,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
$GLOBALS['stub']['printed'] = '';
ob_start();
$attributes = array( 'formId' => '', 'height' => 400 );
-update_option( 'sendbeam_settings', array( 'default_form' => $form ) );
+sb_seed_settings( array( 'default_form' => $form ) );
include dirname( __DIR__ ) . '/blocks/form/render.php';
$block = ob_get_clean();
has( $block, 'class="wp-block-sendbeam-form sendbeam-form-wrap"', 'block wrapper' );
@@ -238,7 +280,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
has( sendbeam_form_html( $form ), 'src="https://mail.example.com/f/', 'app url filter' );
// Appearance: only chosen values are sent, and a bad colour never leaves here.
-update_option( 'sendbeam_settings', array( 'style_accent' => '#B45309', 'style_radius' => '2', 'style_font' => 'serif', 'style_text' => 'rgb(1,2,3)' ) );
+sb_seed_settings( array( 'style_accent' => '#B45309', 'style_radius' => '2', 'style_font' => 'serif', 'style_text' => 'rgb(1,2,3)' ) );
$args = sendbeam_appearance_args();
ok( $args['accent'] === '%23b45309', 'accent is hex-escaped — a bare # would start the URL fragment' );
has( sendbeam_form_url( $form ), 'accent=%23b45309', 'the escaped colour survives into the iframe URL' );
@@ -246,11 +288,11 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
ok( $args['radius'] === '2', 'radius passed' );
ok( $args['font'] === 'serif', 'font passed' );
ok( ! isset( $args['text'] ), 'a non-hex colour is not sent at all' );
-$clean_style = sendbeam_sanitize_settings( array( '_tab' => 'forms', 'style_accent' => 'red', 'style_radius' => '999', 'style_font' => 'Comic Sans' ) );
+$clean_style = sendbeam_sanitize_settings( array( '_tab' => 'forms_style', 'style_accent' => 'red', 'style_radius' => '999', 'style_font' => 'Comic Sans' ) );
ok( $clean_style['style_accent'] === '#B45309', 'a bad colour leaves the saved one untouched' );
ok( $clean_style['style_radius'] === '28', 'radius clamped on save' );
ok( $clean_style['style_font'] === 'inherit', 'an unknown font falls back' );
-update_option( 'sendbeam_settings', array() );
+sb_seed_settings( array() );
// ── Site email ──────────────────────────────────────────────────────────
$stub = &$GLOBALS['stub'];
@@ -259,12 +301,12 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
$mail_atts = array( 'to' => 'Ada ', 'subject' => 'Order #1001', 'message' => 'Thanks
', 'headers' => array( 'Content-Type: text/html; charset=UTF-8', 'Reply-To: Shop ', 'Bcc: owner@example-site.test', 'X-Order-Id: 1001', 'List-Unsubscribe: ' ), 'attachments' => array() );
// Off by default: WordPress keeps sending.
-update_option( 'sendbeam_settings', array() );
+sb_seed_settings( array() );
ok( null === apply_filters( 'pre_wp_mail', null, $mail_atts ), 'disabled → null (WordPress sends)' );
ok( count( $stub['remote'] ) === 0, 'no API call when disabled' );
// On, with a saved key: relayed, headers mapped, From falls back to the workspace sender.
-update_option( 'sendbeam_settings', array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 1 ) );
+sb_seed_settings( array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 1 ) );
ok( true === apply_filters( 'pre_wp_mail', null, $mail_atts ), 'enabled → true (sent)' );
$req = $stub['remote'][0];
ok( $req['url'] === 'https://sendbeam.io/api/v1/transactional', 'posts to the transactional endpoint' );
@@ -276,8 +318,9 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
ok( $sent['bcc'] === array( 'owner@example-site.test' ), 'bcc' );
ok( $sent['headers'] === array( 'X-Order-Id' => '1001' ), 'only X-* headers forwarded' );
ok( ! isset( $sent['from_email'] ), 'no From when WordPress would invent wordpress@…' );
-$log = get_option( 'sendbeam_mail_log' );
-ok( $log[0]['result'] === 'sent' && $log[0]['to'] === 'Ada ', 'log entry' );
+$log = sb_log();
+ok( $log[0]['result'] === 'sent' && $log[0]['to_addr'] === 'Ada ', 'log entry' );
+ok( '' !== $log[0]['sent_at'] && 1 === preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $log[0]['sent_at'] ), 'log entry: with a UTC datetime, not a Unix stamp' );
// Plain text (WordPress default), From header on the site's domain, wp_mail_from_name filter honoured.
$stub['remote'] = array();
@@ -291,7 +334,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
// The settings' From wins over the caller's header.
$stub['remote'] = array();
-update_option( 'sendbeam_settings', array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 1, 'mail_from_email' => 'hello@example-site.test', 'mail_from_name' => 'Example' ) );
+sb_seed_settings( array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 1, 'mail_from_email' => 'hello@example-site.test', 'mail_from_name' => 'Example' ) );
apply_filters( 'pre_wp_mail', null, array( 'to' => 'a@b.test', 'subject' => 's', 'message' => 'm', 'headers' => 'From: x@y.test' ) );
$sent = json_decode( $stub['remote'][0]['args']['body'], true );
ok( $sent['from_email'] === 'hello@example-site.test' && $sent['from_name'] === 'Example', 'settings From wins' );
@@ -299,13 +342,13 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
// Attachments → server mailer.
$stub['remote'] = array();
ok( null === apply_filters( 'pre_wp_mail', null, array( 'to' => 'a@b.test', 'subject' => 's', 'message' => 'm', 'headers' => '', 'attachments' => array( '/tmp/invoice.pdf' ) ) ), 'attachments → null' );
-ok( count( $stub['remote'] ) === 0 && get_option( 'sendbeam_mail_log' )[0]['result'] === 'fallback', 'no call, logged as fallback' );
+ok( count( $stub['remote'] ) === 0 && sb_log()[0]['result'] === 'fallback', 'no call, logged as fallback' );
// API refusal: fallback on → null; fallback off → false + wp_mail_failed.
$stub['remote_reply'] = array( 'response' => array( 'code' => 403 ), 'body' => '{"error":"Monthly email limit reached"}' );
ok( null === apply_filters( 'pre_wp_mail', null, array( 'to' => 'a@b.test', 'subject' => 's', 'message' => 'm' ) ), 'refused + fallback → null' );
-ok( get_option( 'sendbeam_mail_log' )[0]['note'] === 'Monthly email limit reached', 'API error in the log' );
-update_option( 'sendbeam_settings', array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 0 ) );
+ok( sb_log()[0]['note'] === 'Monthly email limit reached', 'API error in the log' );
+sb_seed_settings( array( 'mail_enabled' => 1, 'api_key' => 'sb_live_abcdefghijklmnop', 'mail_fallback' => 0 ) );
$stub['actions'] = array();
ok( false === apply_filters( 'pre_wp_mail', null, array( 'to' => 'a@b.test', 'subject' => 's', 'message' => 'm' ) ), 'refused, no fallback → false' );
ok( $stub['actions'][0][0] === 'wp_mail_failed' && $stub['actions'][0][1][0]->get_error_message() === 'Monthly email limit reached', 'wp_mail_failed fired with the reason' );
@@ -320,9 +363,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 ─────────────────────────────────────────────────
@@ -511,7 +551,7 @@ function lacks( $hay, $needle, $what ) { ok( false === strpos( $hay, $needle ),
update_option( SENDBEAM_ECOMMERCE_OPTION, array() );
ok( ! sendbeam_ecommerce_active( 'order_placed' ), 'e-commerce: nothing is active with no API key' );
-update_option( 'sendbeam_settings', array( 'api_key' => 'sb_live_ecommercetest0123456789' ) );
+sb_seed_settings( array( 'api_key' => 'sb_live_ecommercetest0123456789' ) );
ok( ! sendbeam_ecommerce_active( 'order_placed' ), 'e-commerce: nothing is active without WooCommerce' );
// Every hook is a genuine no-op while WooCommerce is absent — same guarantee
@@ -606,27 +646,4406 @@ 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' );
-// 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.
-$sendbeam_root = dirname( __DIR__ );
-preg_match( "/^ \\* Version:\\s+(\\S+)/m", file_get_contents( $sendbeam_root . '/sendbeam.php' ), $m );
-$declared = $m[1];
-$sendbeam_versions = array(
- 'sendbeam.php SENDBEAM_VERSION' => SENDBEAM_VERSION,
- 'readme.txt Stable tag' => ( preg_match( '/^Stable tag: (\\S+)/m', file_get_contents( $sendbeam_root . '/readme.txt' ), $m2 ) ? $m2[1] : '' ),
- 'block.json version' => ( json_decode( file_get_contents( $sendbeam_root . '/blocks/form/block.json' ), true )['version'] ?? '' ),
- 'index.asset.php version' => ( ( require $sendbeam_root . '/blocks/form/index.asset.php' )['version'] ?? '' ),
+// ── 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' );
+// 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();
+delete_transient( 'sendbeam_connection' );
+delete_transient( 'sendbeam_remote_forms' );
+delete_transient( 'sendbeam_remote_lists' );
+delete_transient( 'sendbeam_subscriber_count' );
+sb_seed_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 ),
);
-foreach ( $sendbeam_versions as $where => $found ) {
- ok( $found === $declared, "version $declared matches $where" . ( $found === $declared ? '' : " (found $found)" ) );
+$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' );
+/*
+ * A textarea, not an input. An input cannot wrap, and at 393px the value
+ * column is about ninety pixels wide — enough to read "resend._dc" and
+ * nothing else, on the one screen whose whole job is reading these.
+ */
+has( $panel, 'sb1.dkim.sendbeam.io ', 'domain: with the value as its content' );
+lacks( $panel, ' 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 ──────────────────────────────────────────────────────
+sb_seed_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' ),
+ )
+ )
+);
+
+/**
+ * Render the test email for one set of settings, and hand back both halves
+ * plus the classification it was built from.
+ */
+function sb_testmail( $from_email, $verified = true ) {
+ $status = sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => $verified, 'records' => array() ),
+ 'sender' => array( 'from_name' => 'Harbour Lane Roasters', 'from_email' => 'ws-f7485df7@post.sendbeam.io' ),
+ )
+ );
+ sb_seed_settings( array(
+ 'api_key' => 'sb_live_testmailtestmailxx',
+ 'mail_enabled' => 1,
+ 'mail_from_name' => 'Harbour Lane Roasters',
+ 'mail_from_email' => $from_email,
+ )
+ );
+ sendbeam_connect_cache_status( $status );
+ $sender = sendbeam_effective_sender( $status );
+ $facts = sendbeam_mail_facts( $status );
+ return array(
+ 'kind' => $sender['kind'],
+ 'html' => sendbeam_test_mail_html( $facts, $sender, $status ),
+ 'text' => sendbeam_test_mail_text( $facts, $sender, $status ),
+ 'next' => sendbeam_test_mail_next_step( $sender, $status ),
+ );
}
-// The newest changelog entry is the version being shipped. Search from the
-// Changelog heading down: readme.txt uses "= … =" for its FAQ headings too.
-$sendbeam_readme = file_get_contents( $sendbeam_root . '/readme.txt' );
-$sendbeam_log = substr( $sendbeam_readme, (int) strpos( $sendbeam_readme, '== Changelog ==' ) );
-preg_match( '/^= (\\S+) =$/m', $sendbeam_log, $m3 );
-ok( ( $m3[1] ?? '' ) === $declared, "readme.txt changelog opens with $declared" );
+/* ── own_domain: the only case where nothing is left to do ── */
+$m = sb_testmail( 'hello@harbourlane.co.uk' );
+ok( 'own_domain' === $m['kind'], 'test email: an address on the verified domain is the site\'s own' );
+has( $m['html'], 'Your site can send email through SendBeam from harbourlane.co.uk', 'test email: the headline names the domain it came from' );
+has( $m['html'], 'harbourlane.co.uk — verified and in use', 'test email: and the domain row says it is actually being used' );
+has( $m['html'], 'Signed by', 'test email: there is a row for the domain that authenticated the message' );
+lacks( $m['html'], 'Next step', 'test email: with nothing left to do, nothing is suggested' );
+ok( null === $m['next'], 'test email: and no next step is generated' );
-echo "smoke: $pass checks passed\n";
+/* ── shared, verified domain: the case the owner caught ── */
+$m = sb_testmail( 'ws-f7485df7@post.sendbeam.io' );
+ok( 'shared' === $m['kind'], 'test email: the workspace default is SendBeam\'s shared address' );
+has( $m['html'], 'Your site can send email through SendBeam (from the shared address for now)', 'test email: the headline says which address it came from' );
+has( $m['html'], 'ws-f7485df7@post.sendbeam.io — SendBeam's shared address, not your domain', 'test email: the From row says what kind of address it is' );
+has( $m['html'], 'harbourlane.co.uk — verified, but not in use yet', 'test email: and the domain row no longer implies it was used' );
+lacks( $m['html'], 'harbourlane.co.uk — verified<', 'test email: the bare "verified" that read as "and in use" is gone' );
+has( $m['html'], 'Next step', 'test email: there is a next step' );
+has( $m['html'], 'press Send from harbourlane.co.uk', 'test email: which names the button that fixes it' );
+has( $m['html'], 'what mailbox providers trust', 'test email: and says why it is worth doing' );
+has( $m['html'], 'page=sendbeam-mail', 'test email: with a link straight to the screen' );
+ok( strpos( $m['html'], 'Next step' ) < strpos( $m['html'], 'What happens now' ), 'test email: and it comes before the general explanation' );
+// The rows a reader compares at a glance.
+$sb_from_at = strpos( $m['html'], 'SendBeam's shared address, not your domain' );
+$sb_signed_at = strpos( $m['html'], 'post.sendbeam.io' );
+ok( false !== $sb_signed_at, 'test email: "Signed by" reports the domain that actually authenticated it' );
+
+/* ── shared, unverified domain ── */
+$m = sb_testmail( 'ws-f7485df7@post.sendbeam.io', false );
+has( $m['html'], 'harbourlane.co.uk — not verified yet', 'test email: an unverified domain says so' );
+has( $m['html'], 'Add the DNS records under Settings', 'test email: and the next step is to add them' );
+has( $m['html'], 'tab=domain', 'test email: linking to the sending domain screen' );
+has( $m['html'], 'on your behalf', 'test email: saying plainly what is happening meanwhile' );
+
+/* ── other: a domain nothing has verified ── */
+$m = sb_testmail( 'hello@somewhere-else.test' );
+ok( 'other' === $m['kind'], 'test email: an address elsewhere is neither' );
+has( $m['html'], 'somewhere-else.test is not a domain verified in this workspace', 'test email: the From row says so' );
+has( $m['html'], 'SendBeam sent this under its own address', 'test email: and the next step says what actually happened to it' );
+lacks( $m['html'], 'refuses messages from it', 'test email: not that SendBeam refused a message the reader is holding' );
+
+/* ── none: nothing to report ── */
+$m = sb_testmail( '' );
+sb_seed_settings( array( 'api_key' => 'sb_live_testmailtestmailxx', 'mail_enabled' => 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' => array() ),
+ )
+ )
+);
+$sb_none_status = sendbeam_connect_status();
+$sb_none_sender = sendbeam_effective_sender( $sb_none_status );
+ok( 'none' === $sb_none_sender['kind'], 'test email: a site with no sender at all is classified as none' );
+$sb_none_html = sendbeam_test_mail_html( sendbeam_mail_facts( $sb_none_status ), $sb_none_sender, $sb_none_status );
+has( $sb_none_html, 'Your workspace sender', 'test email: which says the workspace sender will be used' );
+lacks( $sb_none_html, 'Signed by', 'test email: and omits the rows it cannot fill in' );
+lacks( $sb_none_html, 'Next step', 'test email: with nothing to suggest' );
+
+/* ── The shape of the message, whatever it says ── */
+$m = sb_testmail( 'hello@harbourlane.co.uk' );
+has( $m['html'], '', 'test email: it is a real HTML document' );
+has( $m['html'], ' 'sb_live_testmailtestmailxx',
+ 'mail_enabled' => 1,
+ 'mail_from_name' => 'Harbour Lane Roasters',
+ 'mail_from_email' => 'hello@harbourlane.co.uk',
+ )
+);
+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' ),
+ )
+ )
+);
+
+/** Press the button and take the result the screen would render. */
+function sb_send_test() {
+ $_REQUEST = array( '_wpnonce' => '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' );
+
+/*
+ * Sent is not the same as sent from you. The card has to say which, or the
+ * screen repeats the contradiction the email used to carry.
+ */
+foreach ( array(
+ 'hello@harbourlane.co.uk' => array( false, 'own_domain' ),
+ 'ws-f7485df7@post.sendbeam.io' => array( true, 'shared' ),
+ 'hello@somewhere-else.test' => array( true, 'other' ),
+) as $sb_from => $sb_expect ) {
+ list( $sb_wants_note, $sb_kind ) = $sb_expect;
+ sb_testmail( $sb_from );
+ $GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{"ok":true}' );
+ $sb_sent = sb_send_test();
+ ok( ! empty( $sb_sent['ok'] ), "result card: a send from $sb_kind succeeds" );
+ ok( $sb_kind === $sb_sent['sender'], "result card: and the result records it as $sb_kind" );
+ ob_start();
+ sendbeam_test_mail_success( $sb_sent );
+ $sb_card = ob_get_clean();
+ if ( $sb_wants_note ) {
+ has( $sb_card, 'sb-result--warn', "result card: $sb_kind gets an amber note beside the success" );
+ has( $sb_card, 'Next step', "result card: saying what is left to do for $sb_kind" );
+ has( $sb_card, 'sb-btn', "result card: with a way through to the screen that fixes it" );
+ } else {
+ lacks( $sb_card, 'sb-result--warn', 'result card: own_domain has nothing left to do, so nothing is added' );
+ lacks( $sb_card, 'Next step', 'result card: and no next step is offered' );
+ }
+}
+
+// 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.
+sb_seed_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" );
+}
+
+sb_seed_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' );
+
+sb_seed_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.
+sb_seed_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' );
+sb_seed_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' );
+sb_seed_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' );
+
+sb_seed_settings( array() );
+sendbeam_flush_cache();
+$GLOBALS['stub']['remote_reply'] = null;
+unset( $GLOBALS['stub']['screen'] );
+
+/*
+ * One connected card, however the key arrived. A site with a pasted key was
+ * being shown "Connected" in the header band and **Connect this site** in the
+ * card underneath it — the plugin arguing with itself about its own state.
+ */
+$GLOBALS['stub']['remote_reply'] = array(
+ 'response' => array( 'code' => 200 ),
+ 'body' => wp_json_encode( array( 'forms' => array() ) ),
+);
+$GLOBALS['stub']['user_id'] = 7;
+$GLOBALS['stub']['caps']['manage_options'] = true;
+
+/** Render the connected card for a key that arrived one way or the other. */
+function sb_connected_card( $via_connect ) {
+ sb_seed_settings( array(
+ 'api_key' => 'sb_live_cardkeycardkeycard',
+ 'sendbeam_connected_via' => $via_connect ? 'connect' : '',
+ 'sendbeam_connect_workspace' => $via_connect ? 'Harbour Lane' : '',
+ 'sendbeam_connect_granted' => $via_connect ? 'forms,transactional:send,domain' : '',
+ )
+ );
+ sendbeam_flush_cache();
+ sendbeam_connect_cache_status( sendbeam_connect_normalise_status( array( 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ) ) ) );
+ ob_start();
+ sendbeam_connect_connected_panel( sendbeam_connect_status() );
+ return ob_get_clean();
+}
+
+$sb_pasted = sb_connected_card( false );
+has( $sb_pasted, 'Connected to Harbour Lane', 'pasted key: the card says what it is connected to' );
+has( $sb_pasted, 'using an API key', 'pasted key: and how the key got here' );
+ok( 1 === substr_count( $sb_pasted, 'sb-confirm__ask' ), 'pasted key: exactly one Disconnect' );
+has( $sb_pasted, 'Disconnect', 'pasted key: which is the one action a connected card is for' );
+lacks( $sb_pasted, 'Connect this site', 'pasted key: nothing offers to connect a site that says Connected above it' );
+lacks( $sb_pasted, 'Replace the key', 'pasted key: nor to replace a key, which is a settings job' );
+lacks( $sb_pasted, 'sb-btn--primary', 'pasted key: and there is no primary button on a card whose answer is "yes"' );
+lacks( $sb_pasted, 'Reconnect', 'pasted key: Reconnect needs a connection to re-make, and a pasted key has none' );
+/*
+ * A native disclosure, closed. The old shape shipped the confirmation open
+ * so a no-script browser could submit it and hid it on load, which meant a
+ * red-bordered box flashed on the screen on every render.
+ */
+has( $sb_pasted, '', 'confirm: it is a details' );
+lacks( $sb_pasted, '', 'confirm: whose summary is the Disconnect button itself' );
+lacks( $sb_pasted, 'sb-confirm__ask" hidden', 'confirm: with nothing rendered hidden for script to reveal' );
+ok(
+ strpos( $sb_pasted, '' ) < strpos( $sb_pasted, ' 'sb_live_cardkeycardkeycard',
+ 'sendbeam_connected_via' => '',
+ 'sendbeam_connect_granted' => '',
+);
+$ov = sb_overview( $sb_pasted_settings, array( 'workspace' => array( 'id' => 'w1' ), 'domain_state' => 'no_site' ) );
+has( $ov, 'Switch to one-click Connect', 'pasted key: the domain step with no site host offers the upgrade' );
+has( $ov, 'action=sendbeam_connect_start', 'pasted key: which starts the Connect flow' );
+has( $ov, 'sendbeam_scopes=forms,contacts:write,transactional:send,ecommerce,domain', 'pasted key: with every permission preselected' );
+lacks( $ov, 'Reconnect with more permissions', 'pasted key: worded as an upgrade, not as re-doing something' );
+/*
+ * Twice, and both of them earned: the domain step cannot name a sending
+ * domain, and the mail step is queued behind it. The way out is the same
+ * link, and offering it only on the step somebody is not standing on is one
+ * hop too many.
+ */
+ok( 2 === substr_count( $ov, 'Switch to one-click Connect' ), 'pasted key: offered on the step that needs it and on the one waiting behind it' );
+ok( 1 === substr_count( $ov, 'sb-confirm__ask' ), 'pasted key: and still exactly one Disconnect on the screen' );
+lacks( $ov, 'Connect this site', 'pasted key: with nothing on the connected card offering to connect' );
+
+// A domain that simply has not been added is not a reason to sell anything.
+$ov = sb_overview( $sb_pasted_settings, array( 'workspace' => array( 'id' => 'w1' ), 'domain_state' => 'not_found' ) );
+lacks( $ov, 'Switch to one-click Connect', 'pasted key: a missing domain row is not an argument for reconnecting' );
+
+/*
+ * "Was this key given that permission?" has three answers for a pasted key,
+ * and the third is "no idea". The step was saying it as "no", which is a
+ * claim about somebody's key that this site has no way of knowing.
+ */
+ok( ! sendbeam_connect_permissions_known(), 'pasted key: this site does not know what its key may do' );
+lacks( $ov, 'was not given permission to send your site', 'pasted key: so the step does not claim a permission was withheld' );
+
+$sb_verified_pasted = array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ),
+ 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'hello@harbourlane.co.uk' ),
+);
+$ov = sb_overview( $sb_pasted_settings, $sb_verified_pasted );
+has( $ov, 'Switch on', 'pasted key: and the switch-on is offered rather than hidden behind a permission nobody recorded' );
+lacks( $ov, 'Switch to one-click Connect', 'pasted key: with nothing selling Connect on a step that works' );
+
+// A connection that DOES know, and was refused, still says so.
+$sb_denied = array(
+ 'api_key' => 'sb_live_cardkeycardkeycard',
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_granted' => 'forms',
+);
+$ov = sb_overview( $sb_denied, $sb_verified_pasted );
+has( $ov, 'was not given permission to send your site', 'connect-made: a permission actually withheld is still named' );
+
+// The same offer, worded for a connection that exists.
+$sb_via_settings = array(
+ 'api_key' => 'sb_live_cardkeycardkeycard',
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_granted' => 'forms',
+);
+$ov = sb_overview( $sb_via_settings, array( 'workspace' => array( 'id' => 'w1' ), 'domain_state' => 'not_granted' ) );
+has( $ov, 'Reconnect with more permissions', 'connect-made: a permission nobody ticked is offered as a reconnect' );
+lacks( $ov, 'Switch to one-click Connect', 'connect-made: not as a switch to something it already uses' );
+
+// Nothing connected: the Connect panel, unchanged.
+$ov = sb_overview( array(), array() );
+has( $ov, 'Connect SendBeam', 'not connected: the Connect button is the primary action' );
+has( $ov, 'sb-btn--primary', 'not connected: and it is primary' );
+has( $ov, 'I already have an API key', 'not connected: with the paste field folded away under it' );
+lacks( $ov, 'sb-confirm__ask', 'not connected: and nothing to disconnect' );
+
+sb_seed_settings( array() );
+$GLOBALS['stub']['remote_reply'] = null;
+sendbeam_flush_cache();
+sendbeam_connect_forget_status();
+
+/*
+ * The way back into the guide. Every plugin in the field study with a wizard
+ * keeps one, and the owner needs it to test a change.
+ */
+$sendbeam_restart = sendbeam_wizard_restart_url();
+has( $sendbeam_restart, 'action=sendbeam_wizard_restart', 'help: there is a way back into the setup guide' );
+has( $sendbeam_restart, '_wpnonce=', 'help: with a nonce' );
+
+$_GET = array( 'page' => 'sendbeam-help' );
+ob_start();
+sendbeam_render_admin_page();
+$sendbeam_help = ob_get_clean();
+$_GET = array();
+has( $sendbeam_help, 'Run the setup guide again', 'help: and the Help page offers it' );
+has( $sendbeam_help, 'action=sendbeam_wizard_restart', 'help: pointing at the handler' );
+has( $sendbeam_help, 'Nothing is undone by opening it', 'help: saying plainly that it changes nothing' );
+
+// It puts this person back at step 1, and leaves the site's own answer alone.
+update_option( 'sendbeam_setup_done', 1 );
+update_user_meta( 7, SENDBEAM_WIZARD_STEP, 3 );
+$_GET = array( '_wpnonce' => 'nonce:sendbeam_wizard_restart' );
+$_REQUEST = $_GET;
+unset( $GLOBALS['stub']['redirect'] );
+try {
+ sendbeam_handle_wizard_restart();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+$_GET = array();
+$_REQUEST = array();
+has( $GLOBALS['stub']['redirect']['url'], 'page=sendbeam-setup&step=1', 'help: running it again opens the guide at step 1' );
+ok( '' === get_user_meta( 7, SENDBEAM_WIZARD_STEP, true ), 'help: having forgotten where this person got to' );
+ok( sendbeam_wizard_done(), 'help: and without un-setting-up the site, which is what keeps the Dashboard notice away' );
+
+// Without the nonce, nothing moves.
+update_user_meta( 7, SENDBEAM_WIZARD_STEP, 3 );
+$threw = false;
+try {
+ sendbeam_handle_wizard_restart();
+} catch ( SendBeamStubExit $e ) {
+ $threw = true;
+}
+ok( $threw, 'help: running it again without a nonce is refused' );
+ok( 3 === (int) get_user_meta( 7, SENDBEAM_WIZARD_STEP, true ), 'help: and nothing was reset' );
+
+delete_option( 'sendbeam_setup_done' );
+delete_user_meta( 7, SENDBEAM_WIZARD_STEP );
+sb_seed_settings( array() );
+$GLOBALS['stub']['remote_reply'] = null;
+sendbeam_flush_cache();
+sendbeam_connect_forget_status();
+
+/* ─────────────────────────── 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' );
+sb_seed_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();
+sb_seed_settings( array( 'api_key' => 'sb_live_alreadysetupkey' ) );
+ok( '' === sb_wizard_redirect(), 'wizard: a site that already has a key is not walked through setup' );
+sb_seed_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() ) ),
+);
+sb_seed_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.
+sb_seed_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' );
+sb_seed_settings( array() );
+$GLOBALS['stub']['remote_reply'] = null;
+sendbeam_flush_cache();
+
+/*
+ * Disconnect writes an empty API key, and every update_option() on a
+ * registered option runs the form's sanitiser — whose "a blank key field
+ * keeps the saved key" rule is right for a password field somebody left
+ * alone and exactly wrong for a button whose whole job is clearing it. The
+ * key went back in, the site stayed connected, and the owner pressed the
+ * button twice wondering why.
+ */
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => 'sb_live_stillconnectedxx', 'sendbeam_connected_via' => 'connect', 'sendbeam_connect_workspace' => 'Harbour Lane' ) );
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{}' );
+$_REQUEST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' );
+try {
+ sendbeam_connect_disconnect();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+$_REQUEST = array();
+ok( '' === sendbeam_settings()['api_key'], 'disconnect: the key is actually gone, not put back by the form\'s keep-the-key rule' );
+ok( '' === sendbeam_settings()['sendbeam_connected_via'], 'disconnect: and nothing still claims the site is connected' );
+ok( '' === sendbeam_settings()['sendbeam_connect_workspace'], 'disconnect: nor names a workspace it no longer has a key for' );
+ok( ! sendbeam_is_connected(), 'disconnect: so the screen shows a site that is not connected' );
+
+/*
+ * The same trap, the other way round: a programmatic write must not have the
+ * form's tab rules applied to it either. With no `_tab` every key counts as
+ * posted, and the rule that releases what Connect filled fired on every
+ * write — quietly undoing what the write had just recorded.
+ */
+sb_seed_settings( array( 'api_key' => 'sb_live_filledfilledfilled' ) );
+$sb_keep = sendbeam_settings();
+$sb_keep['mail_enabled'] = 1;
+$sb_keep['mail_from_email'] = 'hello@harbourlane.co.uk';
+$sb_keep['sendbeam_connect_filled'] = array( 'mail_enabled', 'mail_from_email' );
+sendbeam_write_settings( $sb_keep );
+ok( in_array( 'mail_from_email', sendbeam_settings()['sendbeam_connect_filled'], true ), 'write: what Connect filled stays recorded through a programmatic write' );
+ok( 1 === (int) sendbeam_settings()['mail_enabled'], 'write: and a value the caller set is not re-derived from whether a checkbox was posted' );
+ok( 'sb_live_filledfilledfilled' === sendbeam_settings()['api_key'], 'write: and the key it did not mention is left alone' );
+
+// The form's own rules still apply to the form.
+sb_seed_settings( array( 'api_key' => 'sb_live_typedbyahumanxxx' ) );
+$sb_form = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => '' ) );
+ok( 'sb_live_typedbyahumanxxx' === $sb_form['api_key'], 'form: a password field left alone still keeps the saved key' );
+/*
+ * And the audit that keeps this from coming back: `sendbeam_settings` is the
+ * only option with a sanitiser on it, so it is the only one where a
+ * programmatic write can be quietly rewritten — and every writer of it now
+ * goes through the helper.
+ */
+$sb_src = '';
+foreach ( glob( dirname( __DIR__ ) . '/includes/*.php' ) as $sb_file ) {
+ $sb_src .= file_get_contents( $sb_file );
+}
+// Calls, not mentions: the docblocks talk about both of these.
+ok( 1 === preg_match_all( '/^\\t*register_setting\\(/m', $sb_src ), 'audit: one registered option, so one place this trap exists' );
+ok( 1 === substr_count( $sb_src, '$ok = update_option( ' . "'sendbeam_settings'" ), 'audit: and exactly one update_option() on it, inside the helper' );
+// Five occurrences: four calls and the declaration.
+ok( 4 === substr_count( $sb_src, 'sendbeam_write_settings( $' ) - substr_count( $sb_src, 'function sendbeam_write_settings(' ), 'audit: every programmatic writer goes through that helper' );
+$sb_form = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => '', 'api_key_remove' => '1' ) );
+ok( '' === $sb_form['api_key'], 'form: and "remove the saved key" still removes it' );
+
+/*
+ * A key somebody pasted was minted for whatever they minted it for, and may
+ * be in use on another site. Revoking it because this one is being
+ * disconnected would take those down without warning.
+ */
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => 'sb_live_pastedpastedpasted', 'sendbeam_connected_via' => '' ) );
+$GLOBALS['stub']['remote'] = array();
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{}' );
+$_REQUEST = array( '_wpnonce' => 'nonce:sendbeam_disconnect' );
+try {
+ sendbeam_connect_disconnect();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+$_REQUEST = array();
+ok( empty( $GLOBALS['stub']['remote'] ), 'disconnect: a pasted key is not revoked — it is not this site\'s to revoke' );
+ok( '' === sendbeam_settings()['api_key'], 'disconnect: but this site forgets it' );
+ok( '' === sendbeam_settings()['sendbeam_connected_via'], 'disconnect: and stops claiming how it was connected' );
+has( $GLOBALS['stub']['redirect']['url'], 'sendbeam_disconnected=pasted', 'disconnect: and the notice says which of the two happened' );
+
+// ── #5 The setup guide ticked steps that had not been done ──────────────
+// The rail ticked every step whose number was lower than the current one, so
+// opening step 3 on a site with no key showed "✓ Connect ✓ Sending domain"
+// above a body reading "This step needs a connected site. Go back to step 1."
+// Every step has Skip this step on it, so this is one press away.
+sb_seed_settings( array( 'api_key' => '' ) );
+sendbeam_connect_cache_status( sendbeam_connect_empty_status() );
+ok( false === sendbeam_setup_steps()[0]['done'], 'wizard: a site with no key has not done step 1' );
+ob_start();
+sendbeam_wizard_rail( sendbeam_wizard_steps(), 3 );
+$sb_rail = ob_get_clean();
+ok( false === strpos( $sb_rail, '✓' ), 'wizard: so the rail on step 3 ticks nothing' );
+has( $sb_rail, 'is-current', 'wizard: it still says which step you are standing on' );
+ok( 2 === substr_count( $sb_rail, 'sb-rail__num" aria-hidden="true">1<' ) + substr_count( $sb_rail, '>1' ), 'wizard: and step 1 is still numbered 1' );
+
+// A step that IS done is ticked wherever you are standing.
+sb_seed_settings( array( 'api_key' => 'sb_live_railrailrailrailra' ) );
+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' => array() ),
+ )
+ )
+);
+ob_start();
+sendbeam_wizard_rail( sendbeam_wizard_steps(), 1 );
+$sb_rail = ob_get_clean();
+ok( false !== strpos( $sb_rail, '✓' ), 'wizard: a step that is done is ticked from step 1' );
+sb_seed_settings( array() );
+
+// ── #6 "A SendBeam pop-up is live" with every rule switched off ─────────
+// sendbeam_popups() returns every rule ever saved, switched off or not and
+// with or without a form. The front end serves no loader for those, so the
+// checklist was ticking a step nothing on the site could satisfy.
+$GLOBALS['stub']['options']['sendbeam_popups'] = array(
+ array( 'enabled' => 0, 'form' => '9da94d34-86f8-4fbc-9333-45c0b4c16d6a', 'where' => 'everywhere' ),
+ array( 'enabled' => 0, 'form' => '14dad6b8-6998-4f1f-8924-3ebd79524c94', 'where' => 'posts' ),
+);
+ok( 2 === count( sendbeam_popups() ), 'popups: the editing screen still sees every rule it has to edit' );
+ok( array() === sendbeam_live_popups(), 'popups: but none of them is live' );
+ok( '' === sendbeam_form_placement( true ), 'popups: so nothing reports a pop-up on the site' );
+
+// A rule that is on but has no form chosen is just as dead.
+$GLOBALS['stub']['options']['sendbeam_popups'] = array(
+ array( 'enabled' => 1, 'form' => '', 'where' => 'everywhere' ),
+);
+ok( array() === sendbeam_live_popups(), 'popups: a rule with no form shows nothing either' );
+ok( '' === sendbeam_form_placement( true ), 'popups: and does not count as a placed form' );
+
+// Switch one back on and it counts again.
+$GLOBALS['stub']['options']['sendbeam_popups'] = array(
+ array( 'enabled' => 1, 'form' => '9da94d34-86f8-4fbc-9333-45c0b4c16d6a', 'where' => 'everywhere' ),
+);
+ok( 1 === count( sendbeam_live_popups() ), 'popups: a rule that is on with a form is live' );
+ok( 'popup' === sendbeam_form_placement( true ), 'popups: and the checklist says so' );
+unset( $GLOBALS['stub']['options']['sendbeam_popups'] );
+delete_transient( 'sendbeam_form_placed' );
+
+// ── #9 "Connected by: A pasted key" on a site with no key ───────────────
+// The support block is the first thing anyone reads on a support request, and
+// on a disconnected site it said a key had been pasted, with "API key: Not
+// set" directly above it and the sending-domain state blank.
+sb_seed_settings( array( 'api_key' => '' ) );
+sendbeam_connect_cache_status( sendbeam_connect_empty_status() );
+$sb_report = sendbeam_status_report();
+has( $sb_report, 'API key: Not set', 'support block: it says there is no key' );
+lacks( $sb_report, 'Connected by: A pasted key', 'support block: so it does not claim one was pasted' );
+has( $sb_report, 'Connected by: Nothing', 'support block: it says nothing connected this site' );
+ok( false === strpos( $sb_report, "Sending domain state: \n" ) && false === strpos( $sb_report, 'Sending domain state:' . PHP_EOL ), 'support block: the sending domain state is never blank' );
+has( $sb_report, 'Sending domain state: Not asked', 'support block: it says why there is no state' );
+
+// With a key the two original answers are unchanged.
+sb_seed_settings( array( 'api_key' => 'sb_live_pastedkeypastedkey' ) );
+has( sendbeam_status_report(), 'Connected by: A pasted key', 'support block: a pasted key still reads as pasted' );
+sb_seed_settings( array( 'api_key' => 'sb_live_pastedkeypastedkey', 'sendbeam_connected_via' => 'connect' ) );
+has( sendbeam_status_report(), 'Connected by: The Connect button', 'support block: and a Connect key as Connect' );
+
+// ── #10 Blaming a key's permissions on a site with no key ───────────────
+// sendbeam_remote_forms() and sendbeam_lists() both answer null to "the key
+// was refused" and "there is no key", and the empty states read only the
+// first, sending the owner to SendBeam to add a permission to a key that does
+// not exist — on a screen whose header band says "Not connected".
+sb_seed_settings( array( 'api_key' => '' ) );
+sendbeam_flush_cache();
+ok( null === sendbeam_remote_forms(), 'forms: a site with no key cannot read forms' );
+ob_start();
+( new SendBeam_Forms_Table() )->no_items();
+$sb_empty = ob_get_clean();
+lacks( $sb_empty, 'the current key', 'forms: and does not blame a key it does not have' );
+has( $sb_empty, 'not connected to SendBeam yet', 'forms: it says the site is not connected' );
+
+ob_start();
+( new SendBeam_Lists_Table() )->no_items();
+$sb_empty = ob_get_clean();
+lacks( $sb_empty, 'the current key', 'lists: same on the Audience screen' );
+has( $sb_empty, 'not connected to SendBeam yet', 'lists: it says the site is not connected' );
+sb_seed_settings( array() );
+
+/* ─────────────────────────────────────────────────────────────────────────
+ * QA regressions that need a site with no API key at all. They have to sit
+ * above the define() below: once SENDBEAM_API_KEY exists in this process,
+ * sendbeam_api_key() answers with it and no amount of seeding makes a site
+ * keyless again.
+ * ────────────────────────────────────────────────────────────────────── */
+
+// ── #2 Site email switched on with no API key ───────────────────────────
+// Disconnect leaves mail_enabled = 1, which is right — reconnecting should
+// not make the owner find the switch again — so this state is reached the
+// ordinary way. Nothing goes near SendBeam in it, and three screens said
+// otherwise: the test email told the owner to tick a box already ticked,
+// and Site Health raised a critical alarm about email that never leaves the
+// server's own mailer.
+sb_seed_settings( array( 'api_key' => 'sb_live_blockedblockedblocked', 'mail_enabled' => 1 ) );
+ok( '' === sendbeam_mail_blocked(), 'mail: on with a key is not blocked' );
+sb_seed_settings( array( 'api_key' => '', 'mail_enabled' => 1 ) );
+ok( 'no_key' === sendbeam_mail_blocked(), 'mail: on with no key is blocked on the key, not the switch' );
+ok( ! sendbeam_mail_enabled(), 'mail: and site email is not actually running' );
+sb_seed_settings( array( 'api_key' => 'sb_live_blockedblockedblocked', 'mail_enabled' => 0 ) );
+ok( 'off' === sendbeam_mail_blocked(), 'mail: unticked is blocked on the switch' );
+
+// Site Health must not shout about a sender that is not sending anything.
+sb_seed_settings( array( 'api_key' => '', 'mail_enabled' => 1 ) );
+sendbeam_connect_cache_status( sendbeam_connect_empty_status() );
+$sb_relay = sendbeam_test_mail_relay();
+ok( 'critical' !== $sb_relay['status'], 'site health: site email on with no key is not a critical alarm' );
+ok( 'recommended' === $sb_relay['status'], 'site health: it is a recommendation to connect the site' );
+lacks( $sb_relay['label'], 'unverified domain', 'site health: and it does not blame an unverified domain' );
+has( $sb_relay['description'], 'no SendBeam API key', 'site health: it names the missing key' );
+
+// The ticked box says why it cannot act, where it is ticked.
+ob_start();
+sendbeam_field_checkbox( array( 'key' => 'mail_enabled', 'label' => 'Send this site\'s email through SendBeam' ) );
+$sb_box = ob_get_clean();
+has( $sb_box, 'checked', 'mail: the box is still ticked, because that is what was saved' );
+has( $sb_box, 'no SendBeam API key', 'mail: and it says the site has no key' );
+sb_seed_settings( array( 'api_key' => 'sb_live_blockedblockedblocked', 'mail_enabled' => 1 ) );
+ob_start();
+sendbeam_field_checkbox( array( 'key' => 'mail_enabled', 'label' => 'Send this site\'s email through SendBeam' ) );
+lacks( ob_get_clean(), 'no SendBeam API key', 'mail: and says nothing of the sort once there is one' );
+sb_seed_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' );
+// 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 ────────────────────────────────────────────────────────────
+//
+// 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', '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
+// 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();
+sb_seed_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();
+sb_seed_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();
+ sb_seed_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();
+sb_seed_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();
+sb_seed_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 ' ) );
+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' );
+
+// 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' );
+// 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' );
+// 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' );
+
+// 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
+// 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/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 ) );
+sendbeam_connect_forget_status();
+$ov = sb_overview( $sb_connected, $sb_unverified, array( 'sb_dc' => 'done' ) );
+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' );
+
+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, '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
+// 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' );
+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' );
+
+// 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' );
+
+
+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' );
+sb_seed_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' );
+
+/*
+ * The wizard is routable but never in the menu. Its parent is options.php
+ * rather than an empty string: an empty parent routes fine and then leaves
+ * WordPress unable to work out the page's title, which is a PHP 8
+ * deprecation in the log and a browser tab reading "— WordPress".
+ */
+/*
+ * Every hook this plugin registers has to name a function that exists.
+ * WordPress answers a hook pointing at a missing function with a fatal error
+ * on the screen it fires on — and a screen is exactly the thing no unit test
+ * was looking at when the menu grew its `load-` hooks.
+ */
+foreach ( $GLOBALS['stub']['callbacks'] as $sendbeam_cb ) {
+ list( $sendbeam_tag, $sendbeam_fn ) = $sendbeam_cb;
+ ok( is_callable( $sendbeam_fn ), 'hooks: ' . ( is_string( $sendbeam_fn ) ? $sendbeam_fn : 'a closure' ) . '() exists for ' . $sendbeam_tag );
+}
+
+ok( isset( $subs['sendbeam-setup'] ), 'menu: the wizard is registered' );
+ok( 'options.php' === $subs['sendbeam-setup']['parent'], 'menu: under a parent that is in no menu, so it is routable but hidden' );
+ok( ! isset( $menu['sendbeam-setup'] ), 'menu: and it is not a top-level menu either' );
+ok( '' !== $subs['sendbeam-setup']['page_title'], 'menu: it has a page title, so the browser tab says what it is' );
+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();
+
+/*
+ * One function knows what a link into SendBeam looks like, and its default is
+ * where a person with an account wants to land.
+ */
+ok( 'https://sendbeam.io/dashboard' === sendbeam_app_link(), 'app links: the default is the app\'s signed-in home' );
+ok( 'https://sendbeam.io/forms' === sendbeam_app_link( '/forms' ), 'app links: a deep link keeps its path' );
+ok( 'https://sendbeam.io' === sendbeam_app_url(), 'app links: and the origin the API is called against is unchanged' );
+
+/*
+ * No anchor anywhere in the plugin's markup points at the bare origin. The
+ * base URL is still used for the API, for the postMessage origin check and
+ * for the "SendBeam address" line in the debug report — none of which is
+ * something a person clicks.
+ */
+$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();
+ lacks( $sendbeam_html, 'href="https://sendbeam.io"', "app links: $sendbeam_slug has no anchor on the bare origin" );
+ lacks( $sendbeam_html, "href='https://sendbeam.io'", "app links: $sendbeam_slug has none with single quotes either" );
+ // The header band carries the link the owner pressed — on every screen
+ // but the wizard, whose band shows how far through you are instead.
+ if ( 'sendbeam-setup' !== $sendbeam_slug ) {
+ has( $sendbeam_html, 'href="https://sendbeam.io/dashboard" target="_blank"', "app links: $sendbeam_slug's header opens the app" );
+ }
+}
+$_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' );
+
+/* ────────────────────────── 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();
+sb_seed_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 id="', 'forms table: a contact form shows the shortcode that places THAT form' );
+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 ───────────────────────────────────────────────────────
+sb_log_reset();
+sendbeam_mail_log_insert( 'cat@customer.test', 'New comment', 'fallback', 'has attachments', 'akismet', 1758500000 );
+sendbeam_mail_log_insert( 'bob@customer.test', 'Password reset', 'failed', 'Monthly email limit reached', 'wp-core', 1758600000 );
+sendbeam_mail_log_insert( 'ada@customer.test', 'Order #1001', 'sent', '', 'woocommerce', 1758700000 );
+$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', 'Sent by', '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, 'Delete ', 'email log: the one bulk action is Delete' );
+has( $html, 'woocommerce', 'email log: and which plugin asked for the message' );
+/*
+ * The sentinel for core is `wp-core`, not the product's name: the coding
+ * standard's own auto-fixer rewrites that word wherever it finds it, which
+ * would turn a stored value the screen matches on into one it does not.
+ */
+has( $html, '>WordPress<', 'email log: with core itself named in words' );
+ok( 'wp-core' === sendbeam_mail_source() || '' === sendbeam_mail_source(), 'email log: and stored as a sentinel a linter will not rewrite' );
+
+$_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();
+
+sb_log_reset();
+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.
+sb_log_reset();
+sendbeam_mail_log_insert( 'a@t.test', 'A', 'sent', '', '', 1758000001 );
+sendbeam_mail_log_insert( 'b@t.test', 'B', 'sent', '', '', 1758000002 );
+sendbeam_mail_log_insert( 'c@t.test', 'C', 'sent', '', '', 1758000003 );
+$_REQUEST = array(
+ 'action' => 'delete',
+ 'message' => array( 2 ),
+ '_wpnonce' => 'nonce:bulk-sendbeam_messages',
+);
+$table = new SendBeam_Mail_Log_Table();
+$table->process_bulk_action();
+$kept = sb_log();
+ok( 2 === count( $kept ), 'email log: a bulk delete removes exactly the rows that were ticked' );
+ok( 'c@t.test' === $kept[0]['to_addr'] && 'a@t.test' === $kept[1]['to_addr'], 'email log: the rows that were not ticked are untouched' );
+
+// 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( sb_log() ), 'email log: and nothing was deleted' );
+$_REQUEST = array();
+sb_log_reset();
+
+// ── 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;
+
+/*
+ * 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' );
+
+/* ─────────────────────────── The design system ─────────────────────────
+ * Four foreign signals had to go: 10px uppercase mono labels, black primary
+ * buttons, labels beside their fields, and a page with a right margin and no
+ * left one. What stays is ink on paper, the three-square mark, the cards, the
+ * header band and the state pill.
+ */
+$sendbeam_css = sendbeam_admin_css();
+
+ok( false === strpos( $sendbeam_css, 'text-transform:uppercase' ), 'design: nothing is shouted in uppercase any more' );
+ok( false === strpos( $sendbeam_css, 'letter-spacing:.1em' ), 'design: and nothing is tracked out like an eyebrow' );
+has( $sendbeam_css, '.sb-label{display:block;font-size:13px;font-weight:600', 'design: labels are sentence case at a readable size' );
+has( $sendbeam_css, '--brand:var(--wp-admin-theme-color,#2271b1)', 'design: the primary colour is the admin theme\'s, with core\'s blue as the fallback' );
+has( $sendbeam_css, '.sendbeam-app .sb-btn{', 'design: buttons are the plugin\'s own, scoped to the plugin' );
+has( $sendbeam_css, 'background:var(--brand);color:#fff', 'design: a primary button is the admin theme colour with white text' );
+has( $sendbeam_css, '.sendbeam-app .sb-btn--ghost{background:transparent;color:var(--ink);border-color:var(--ink)', 'design: secondary is an ink outline' );
+has( $sendbeam_css, '.sendbeam-app .sb-btn--danger{background:transparent;color:var(--v);border-color:var(--v)', 'design: danger is a vermilion outline, never a filled red button' );
+has( $sendbeam_css, '.sendbeam-app{--paper:#EDEBE6', 'design: the paper and ink are kept' );
+has( $sendbeam_css, 'margin:20px 20px 0;', 'design: the page has the same margin on both sides' );
+has( $sendbeam_css, '.sendbeam-app .sb-toggle input[type=checkbox]{appearance:none', 'design: on/off settings are switches' );
+has( $sendbeam_css, 'min-height:40px', 'design: fields are 40px tall' );
+has( $sendbeam_css, 'outline:2px solid var(--brand)', 'design: and focus is the admin theme colour' );
+has( $sendbeam_css, '.sendbeam-app .form-table th{font-size:13px', 'design: even core\'s two-column form table is stacked label-above' );
+has( $sendbeam_css, '.sb-scroll{overflow-x:auto', 'design: a table that will not fit scrolls inside its own box' );
+has( $sendbeam_css, '@media (max-width:782px)', 'design: and the whole thing has a phone layout' );
+
+/*
+ * Three single digits stacked down a card took half of it. They stay in a row
+ * on a phone and only break at a width no phone actually is.
+ */
+/*
+ * Nothing on any screen is drawn and then hidden by script on load. That is
+ * what the owner saw: a red card flashing under the Disconnect button on
+ * every refresh of the Overview.
+ */
+$sendbeam_js = sendbeam_connect_admin_js();
+lacks( $sendbeam_css, '.sb-confirm__box{display:none', 'design: the confirmation is not hidden by a stylesheet either' );
+has( $sendbeam_css, '.sendbeam-app .sb-confirm>summary{list-style:none', 'design: the disclosure marker is off, so the summary reads as the button it is' );
+has( $sendbeam_css, '.sb-confirm[open]>summary .sb-confirm__label--shut{display:none}', 'design: and the summary\'s label is the action it would perform next' );
+has( $sendbeam_css, '.sendbeam-app .is-hidden{display:none!important}', 'design: a row that does not apply yet is hidden by the server, not by script on load' );
+
+$GLOBALS['stub']['inline']['sendbeam-admin'] = array();
+sendbeam_admin_assets( 'toplevel_page_sendbeam' );
+$sendbeam_admin_js = implode( "\n", $GLOBALS['stub']['inline']['sendbeam-admin'] );
+lacks( $sendbeam_admin_js, 'sb-confirm', 'design: no script touches the confirmation at all' );
+lacks( $sendbeam_admin_js, 'tr.hidden', 'design: nor hides a settings row after the page has drawn' );
+has( $sendbeam_admin_js, 'classList.toggle( "is-hidden"', 'design: the switch moves a class the server already set' );
+
+// The server's half of that: a row that does not apply yet arrives hidden.
+sb_seed_settings( array( 'mail_enabled' => 0 ) );
+has( sendbeam_when_mail_class(), 'is-hidden', 'design: with site email off the detail rows arrive hidden' );
+sb_seed_settings( array( 'mail_enabled' => 1 ) );
+lacks( sendbeam_when_mail_class(), 'is-hidden', 'design: and with it on they arrive shown' );
+sb_seed_settings( array() );
+
+has( $sendbeam_css, '@media (max-width:340px){', 'design: the workspace figures only stack on something narrower than a phone' );
+has( $sendbeam_css, '.sb-stats .sb-fig{font-size:24px}', 'design: with the figure tightened so the row is one compact band' );
+// One message, one line: a result that wraps under an address reads as a row
+// of its own, and the address gives way first.
+has( $sendbeam_css, 'flex-wrap:nowrap', 'design: a log row stays on one line' );
+has( $sendbeam_css, '.sb-recent__who{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis', 'design: where the address truncates rather than pushing the result down' );
+has( $sendbeam_css, '.sb-recent__what{flex:0 0 auto;white-space:nowrap}', 'design: and the result stays whole, on the right' );
+has( $sendbeam_css, '.sb-recent__long{display:none}', 'design: the long date is swapped for the short one on a phone' );
+
+/*
+ * The copy field's height comes from its line box, not from a pinned one: a
+ * pinned height on a 12px mono field clips its own descenders, and the
+ * underscore in `resend._domainkey` simply vanished.
+ */
+has( $sendbeam_css, '.sendbeam-app .sb-copy-field{display:block;width:100%;min-width:0;font-size:12px;line-height:1.5;', 'design: a copy field is a readable 12px with room for its own descenders' );
+has( $sendbeam_css, 'height:auto;min-height:0;padding:6px 8px', 'design: and its height comes from its content, not from a pinned one that clips an underscore' );
+
+// On a phone each record is a block, not four columns in 393px.
+has( $sendbeam_css, '.sb-dns,.sb-dns thead,.sb-dns tbody,.sb-dns tr,.sb-dns td{display:block', 'design: the records table stops being a table on a phone' );
+has( $sendbeam_css, '.sb-dns td.sb-dns__host,.sb-dns td.sb-dns__value{grid-column:1/-1', 'design: where the host and the value each get the full width' );
+// The desktop column widths are more specific than display:block, so they
+// have to be undone by name or the host stays at a third of the card.
+has( $sendbeam_css, '.sb-dns td,.sb-dns td.sb-dns__type,.sb-dns td.sb-dns__host,', 'design: and the desktop column widths are undone by name, not left to lose a specificity fight' );
+has( $sendbeam_css, 'content:attr(data-label)', 'design: and carry their column name, because the header row has gone' );
+has( $sendbeam_css, 'word-break:break-all', 'design: a value too long for the line wraps rather than being cut off' );
+// Desktop keeps the row, with the room going to the column that needs it.
+has( $sendbeam_css, '.sb-dns th:nth-child(2),.sb-dns td.sb-dns__host{width:30%}', 'design: on desktop the host column is pinned' );
+has( $sendbeam_css, '.sb-dns th:nth-child(4),.sb-dns td.sb-dns__found{width:9em}', 'design: so is the verdict, and everything left over goes to the value' );
+
+// Every screen's markup: no core primary button, no leftover uppercase class.
+$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();
+ lacks( $sendbeam_html, 'button-primary', "design: $sendbeam_slug uses no core button-primary" );
+ lacks( $sendbeam_html, 'sb-eyebrow', "design: $sendbeam_slug has no uppercase-mono eyebrow left" );
+}
+$_GET = array();
+
+/*
+ * The one place core's button classes are right is inside a core notice,
+ * where a brand-styled button is the thing that looks pasted in — that is
+ * asserted where the Dashboard notice is tested, above.
+ */
+
+// Every hand-rolled table that is left sits in the scroll wrapper the plugin
+// already owns. This is the exact fault that made two screens scroll
+// sideways at 393px.
+$sendbeam_screens_src = file_get_contents( dirname( __DIR__ ) . '/includes/screens.php' );
+ok(
+ substr_count( $sendbeam_screens_src, ' array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ),
+ 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'ws-f7485df7@post.sendbeam.io' ),
+ )
+);
+
+/** Classify the From address a given settings array would send with. */
+function sb_sender( $settings, $status ) {
+ sb_seed_settings( $settings );
+ return sendbeam_effective_sender( $status );
+}
+
+$sb_base = array( 'api_key' => 'sb_live_senderkeysenderkey', 'mail_enabled' => 1 );
+
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'hello@harbourlane.co.uk' ) ), $sb_sender_status );
+ok( 'own_domain' === $r['kind'], 'sender: an address on the verified domain is the site\'s own' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'orders@mail.harbourlane.co.uk' ) ), $sb_sender_status );
+ok( 'own_domain' === $r['kind'], 'sender: and so is one on a subdomain of it' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'ws-f7485df7@post.sendbeam.io' ) ), $sb_sender_status );
+ok( 'shared' === $r['kind'], 'sender: an address on SendBeam\'s own host is the shared one' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'hi@mail.sendbeam.io' ) ), $sb_sender_status );
+ok( 'shared' === $r['kind'], 'sender: and so is the other host the platform sends shared mail from' );
+
+/*
+ * "Anywhere under sendbeam.io" was the rule, and it was wrong: a customer
+ * whose verified domain is a subdomain of SendBeam's own — which every site
+ * on the staging host is — was told their own domain was the shared address.
+ * post. and mail. are the two hosts the platform actually sends from;
+ * nothing else under that domain is shared.
+ */
+$sb_sub_status = sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'wp-test.sendbeam.io', 'verified' => true, 'records' => array() ),
+ 'sender' => array( 'from_name' => 'WP Test', 'from_email' => 'ws-f7485df7@post.sendbeam.io' ),
+ )
+);
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'hello@wp-test.sendbeam.io' ) ), $sb_sub_status );
+ok( 'own_domain' === $r['kind'], 'sender: a verified domain that happens to sit under SendBeam\'s own is still the site\'s own domain' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'ws-x@post.sendbeam.io' ) ), $sb_sub_status );
+ok( 'shared' === $r['kind'], 'sender: while the shared host beside it is still shared' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'x@mail.sendbeam.io' ) ), $sb_sub_status );
+ok( 'shared' === $r['kind'], 'sender: and so is the other one' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'x@other.sendbeam.io' ) ), $sb_sender_status );
+ok( 'other' === $r['kind'], 'sender: but some third subdomain nobody verified is neither' );
+
+/*
+ * And the state the owner actually saw it in: a DISCONNECTED site, where
+ * there is no verified domain for own_domain to settle it with, so the shared
+ * rule is the only thing deciding. "Anywhere under sendbeam.io" called the
+ * site's own address SendBeam's shared one on the very screen that had just
+ * said the site is not connected.
+ */
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'hello@wp-test.sendbeam.io' ) ), sendbeam_connect_empty_status() );
+ok( 'shared' !== $r['kind'], 'sender: with nothing connected, the site\'s own address is not called SendBeam\'s shared one' );
+ok( 'other' === $r['kind'], 'sender: it is simply a domain this site cannot say anything about yet' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'ws-x@post.sendbeam.io' ) ), sendbeam_connect_empty_status() );
+ok( 'shared' === $r['kind'], 'sender: while the genuinely shared host is still recognised without a connection' );
+
+// The two hosts are derived from the app URL, so a self-hosted SendBeam
+// recognises its own rather than SendBeam's.
+ok( in_array( 'post.sendbeam.io', sendbeam_shared_sender_hosts(), true ), 'sender: the shared hosts are post. and mail. of the app host' );
+ok( in_array( 'mail.sendbeam.io', sendbeam_shared_sender_hosts(), true ), 'sender: both of them' );
+ok( ! in_array( 'sendbeam.io', sendbeam_shared_sender_hosts(), true ), 'sender: and the bare app host is not one of them' );
+$r = sb_sender( array_merge( $sb_base, array( 'mail_from_email' => 'hello@somewhere-else.test' ) ), $sb_sender_status );
+ok( 'other' === $r['kind'], 'sender: anywhere else is somewhere SendBeam will refuse' );
+$r = sb_sender( $sb_base, $sb_sender_status );
+ok( 'shared' === $r['kind'], 'sender: with nothing set it falls back to the workspace sender, which is the shared one' );
+ok( 'ws-f7485df7@post.sendbeam.io' === $r['email'], 'sender: and reports the address it would actually use' );
+$r = sb_sender( $sb_base, sendbeam_connect_empty_status() );
+ok( 'none' === $r['kind'], 'sender: nothing known is not a classification' );
+
+// What it should become once the domain is verified.
+ok( 'hello@harbourlane.co.uk' === sendbeam_own_domain_sender( $sb_sender_status ), 'sender: a verified domain with a shared workspace sender gets hello@ its own domain' );
+$sb_own_ws = $sb_sender_status;
+$sb_own_ws['sender']['from_email'] = 'orders@harbourlane.co.uk';
+ok( 'orders@harbourlane.co.uk' === sendbeam_own_domain_sender( $sb_own_ws ), 'sender: a workspace sender already on the domain is kept — it is the address the account holder chose' );
+$sb_unver = $sb_sender_status;
+$sb_unver['domain']['verified'] = false;
+ok( '' === sendbeam_own_domain_sender( $sb_unver ), 'sender: an unverified domain is nothing to send from' );
+
+// ── Step 2 stops claiming what step 4 controls ─────────────────────────
+has( sendbeam_domain_sentence( 'harbourlane.co.uk', true ), 'harbourlane.co.uk is verified.', 'step 2: a verified domain says it is verified' );
+lacks( sendbeam_domain_sentence( 'harbourlane.co.uk', true ), 'will be sent from your own domain', 'step 2: and says nothing about what this site actually sends as — that is step 4\'s to answer' );
+
+// ── The contradiction, on the screen ───────────────────────────────────
+$sb_shared = array(
+ 'api_key' => 'sb_live_connectedconnectedxx',
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_workspace' => 'Harbour Lane',
+ 'sendbeam_connect_granted' => 'forms,transactional:send,domain',
+ 'mail_enabled' => 1,
+ 'mail_from_email' => 'ws-f7485df7@post.sendbeam.io',
+ 'default_form' => $form,
+);
+$sb_shared_body = array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ),
+ 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'ws-f7485df7@post.sendbeam.io' ),
+);
+update_option( 'sendbeam_form_placed', 1, false );
+
+$ov = sb_overview( $sb_shared, $sb_shared_body );
+has( $ov, 'harbourlane.co.uk is verified.', 'overview: step 2 says the domain is verified' );
+lacks( $ov, 'will be sent from your own domain', 'overview: and does not promise what step 4 has not done' );
+has( $ov, 'which is SendBeam's shared address, not harbourlane.co.uk', 'overview: step 4 says what is really happening' );
+has( $ov, 'needs-attention', 'overview: and the step is marked as needing attention rather than ticked' );
+has( $ov, 'Send from harbourlane.co.uk', 'overview: with one press that fixes it' );
+has( $ov, 'value="sendbeam_mail_own_domain"', 'overview: which posts to a handler of its own' );
+has( $ov, 'nonce:sendbeam_mail_own_domain', 'overview: with a nonce' );
+has( $ov, 'That changes the From address to hello@harbourlane.co.uk', 'overview: and says exactly what it will do' );
+has( $ov, 'Sends as ws-f7485df7@post.sendbeam.io (SendBeam's shared address)', 'overview: the connection card names the kind of address, not just the address' );
+ok( false === strpos( $ov, '1 step left' ) || false !== strpos( $ov, 'step' ), 'overview: the checklist counts the open step' );
+
+// Press it, and the two halves agree.
+$_GET = array( '_wpnonce' => 'nonce:sendbeam_mail_own_domain' );
+$_REQUEST = $_GET;
+sendbeam_connect_cache_status( sendbeam_connect_normalise_status( $sb_shared_body ) );
+sb_seed_settings( $sb_shared );
+set_transient( 'sendbeam_connection', array( 'state' => 'ok', 'message' => '', 'count' => 1 ) );
+try {
+ sendbeam_handle_mail_own_domain();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+$_GET = array();
+$_REQUEST = array();
+has( $GLOBALS['stub']['redirect']['url'], 'sendbeam_sender=own', 'own domain: pressing it says so' );
+ok( 'hello@harbourlane.co.uk' === sendbeam_settings()['mail_from_email'], 'own domain: and the From address moves to the verified domain' );
+ok( in_array( 'mail_from_email', sendbeam_settings()['sendbeam_connect_filled'], true ), 'own domain: recorded as Connect\'s doing, so disconnecting puts back what it found' );
+
+$sb_fixed = sendbeam_settings();
+$ov = sb_overview( $sb_fixed, $sb_shared_body );
+has( $ov, 'On, sending as hello@harbourlane.co.uk', 'overview: step 4 now says what it is doing' );
+lacks( $ov, 'needs-attention', 'overview: and the step is finished' );
+has( $ov, 'Sends as hello@harbourlane.co.uk (your domain)', 'overview: the connection card agrees with it' );
+lacks( $ov, 'Send from harbourlane.co.uk', 'overview: and the button is gone, because there is nothing left to fix' );
+
+// An address on a domain this workspace has not verified is refused, and says so.
+$sb_elsewhere = $sb_shared;
+$sb_elsewhere['mail_from_email'] = 'hello@somewhere-else.test';
+$ov = sb_overview( $sb_elsewhere, $sb_shared_body );
+has( $ov, 'somewhere-else.test is not a domain this workspace has verified', 'overview: an unverifiable From address is named as one' );
+has( $ov, 'SendBeam refuses these messages', 'overview: and says what happens to those messages' );
+has( $ov, 'needs-attention', 'overview: and the step is not ticked' );
+
+// ── The deferred switch-on must not park a site on the shared address ───
+sb_seed_settings( array(
+ 'api_key' => 'sb_live_deferreddeferredxx',
+ 'sendbeam_connect_granted' => 'forms,transactional:send,domain',
+ 'sendbeam_mail_deferred' => 1,
+ 'mail_enabled' => 0,
+ 'mail_from_email' => '',
+ )
+);
+sendbeam_connect_enable_mail( sendbeam_connect_normalise_status( $sb_shared_body ) );
+$sb_after = sendbeam_settings();
+ok( 1 === (int) $sb_after['mail_enabled'], 'deferred switch-on: site email comes on when the domain verifies' );
+ok( 'hello@harbourlane.co.uk' === $sb_after['mail_from_email'], 'deferred switch-on: on the verified domain, not on SendBeam\'s shared address' );
+
+// And a shared address Connect wrote earlier is corrected when the domain lands.
+sb_seed_settings( array(
+ 'api_key' => 'sb_live_deferreddeferredxx',
+ 'sendbeam_connect_granted' => 'forms,transactional:send,domain',
+ 'sendbeam_mail_deferred' => 1,
+ 'mail_enabled' => 0,
+ 'mail_from_email' => 'ws-f7485df7@post.sendbeam.io',
+ 'sendbeam_connect_filled' => array( 'mail_from_email' ),
+ )
+);
+sendbeam_connect_enable_mail( sendbeam_connect_normalise_status( $sb_shared_body ) );
+ok( 'hello@harbourlane.co.uk' === sendbeam_settings()['mail_from_email'], 'deferred switch-on: a shared address Connect wrote is corrected once the domain verifies' );
+
+// An address the OWNER typed is never overruled, whatever the domain does.
+sb_seed_settings( array(
+ 'api_key' => 'sb_live_deferreddeferredxx',
+ 'sendbeam_connect_granted' => 'forms,transactional:send,domain',
+ 'sendbeam_mail_deferred' => 1,
+ 'mail_enabled' => 0,
+ 'mail_from_email' => 'ws-f7485df7@post.sendbeam.io',
+ 'sendbeam_connect_filled' => array(),
+ )
+);
+sendbeam_connect_enable_mail( sendbeam_connect_normalise_status( $sb_shared_body ) );
+ok( 'ws-f7485df7@post.sendbeam.io' === sendbeam_settings()['mail_from_email'], 'deferred switch-on: an address the owner typed is left exactly as they typed it' );
+
+delete_option( 'sendbeam_form_placed' );
+sb_seed_settings( array() );
+sendbeam_flush_cache();
+sendbeam_connect_forget_status();
+
+/* ─────────────────── The Overview: connection and checklist ────────────
+ * The connection used to be answered by a ticked line inside step 1, which
+ * on a finished site — most sites, most of the time — said nothing at all.
+ */
+$GLOBALS['stub']['user_id'] = 7;
+$GLOBALS['stub']['caps']['manage_options'] = true;
+delete_user_meta( 7, 'sendbeam_checklist_hidden' );
+
+// Every step done: connected, verified, a form on the site, site email on.
+$sb_done = $sb_connected;
+$sb_done['mail_enabled'] = 1;
+$sb_done['default_form'] = $form;
+update_option( 'sendbeam_form_placed', 1, false );
+
+sb_log_reset();
+sendbeam_mail_log_insert( 'bob@customer.test', 'Password reset', 'failed', 'refused', '', 1758600000 );
+sendbeam_mail_log_insert( 'ada@customer.test', 'Order #1001', 'sent', '', '', 1758700000 );
+
+$ov = sb_overview( $sb_done, $sb_verified );
+has( $ov, 'Connection ', 'overview: the connection is a card of its own, above the checklist' );
+has( $ov, 'Connected to Harbour Lane', 'overview: which names the workspace' );
+has( $ov, 'Sends as', 'overview: and the address this site sends from' );
+has( $ov, 'Reconnect', 'overview: with Reconnect' );
+has( $ov, 'Disconnect', 'overview: and Disconnect' );
+has( $ov, 'Open SendBeam', 'overview: and a way through to SendBeam itself' );
+/*
+ * The app, not the marketing site. `sendbeam_app_url()` is the origin the API
+ * is called against and the bare origin is the page inviting people to sign
+ * up — which is where "Open SendBeam" was sending people who already had an
+ * account. The signed-in home is /dashboard.
+ */
+has( $ov, 'href="https://sendbeam.io/dashboard"', 'overview: which opens the app, not the page selling it' );
+ok( 1 === substr_count( $ov, 'https://sendbeam.io/dashboard' ), 'overview: once, from the workspace card' );
+lacks( $ov, 'href="https://sendbeam.io"', 'overview: and nothing points at the bare origin' );
+has( $ov, 'class="sb-card__action"', 'overview: whose one secondary action sits in the card header, not adrift in its body' );
+
+// The workspace figures read across, not down a column with a blank card
+// under them.
+has( $ov, '', 'overview: the three figures are a row' );
+ok( 3 === substr_count( $ov, '
' ), 'overview: three of them' );
+has( $ov, 'Subscribers counts people, not list memberships. Cached for five minutes.', 'overview: with one muted line explaining what a subscriber is' );
+
+// And the card earns its height with what this site has actually done.
+has( $ov, 'Recent site email', 'overview: the workspace card shows what this site has been sending' );
+has( $ov, 'sb-recent__when', 'overview: with a date per row' );
+// Two dates, one shown at a time by CSS: the site's own format is right on a
+// desktop and took half the row on a phone.
+has( $ov, 'sb-recent__long', 'overview: the site\'s own date format' );
+has( $ov, 'sb-recent__short', 'overview: and a short one for a phone' );
+has( $ov, 'sb-recent__who', 'overview: who it went to' );
+has( $ov, 'sb-recent__what', 'overview: and how it went' );
+has( $ov, 'View the log', 'overview: and a way through to the whole log' );
+ok( strpos( $ov, 'Connection ' ) < strpos( $ov, 'Setup ' ), 'overview: the connection comes before the checklist' );
+ok( 1 === substr_count( $ov, 'value="sendbeam_disconnect"' ), 'overview: and there is exactly one Disconnect on the screen' );
+
+// A finished checklist can be put away, and brought back.
+has( $ov, 'All done', 'overview: a finished checklist says so' );
+has( $ov, 'Hide this checklist', 'overview: and offers to go' );
+update_user_meta( 7, 'sendbeam_checklist_hidden', 1 );
+$ov = sb_overview( $sb_done, $sb_verified );
+lacks( $ov, 'Verify your sending domain', 'overview: a hidden checklist is gone' );
+has( $ov, 'Set up and sending.', 'overview: replaced by one line saying so' );
+has( $ov, 'Show the checklist again', 'overview: which can be undone' );
+
+// An unfinished checklist is never hidden, whatever anybody has dismissed.
+$ov = sb_overview( $sb_done, $sb_unverified );
+has( $ov, 'Verify your sending domain', 'overview: an unfinished checklist stays, even for someone who hid a finished one' );
+has( $ov, '1 step left', 'overview: and says how many steps are left' );
+lacks( $ov, 'Hide this checklist', 'overview: with nothing offering to hide it' );
+delete_user_meta( 7, 'sendbeam_checklist_hidden' );
+
+// Hiding it is per user, through a nonced handler.
+$sendbeam_hide = sendbeam_checklist_url( true );
+has( $sendbeam_hide, 'action=sendbeam_hide_checklist', 'overview: hiding the checklist goes through admin-post' );
+has( $sendbeam_hide, '_wpnonce=', 'overview: with a nonce' );
+$_GET = array( 'state' => '1', '_wpnonce' => 'nonce:sendbeam_hide_checklist' );
+$_REQUEST = $_GET;
+try {
+ sendbeam_handle_hide_checklist();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+ok( sendbeam_checklist_hidden(), 'overview: and it is remembered for that person' );
+$_GET = array( 'state' => '0', '_wpnonce' => 'nonce:sendbeam_hide_checklist' );
+$_REQUEST = $_GET;
+try {
+ sendbeam_handle_hide_checklist();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+ok( ! sendbeam_checklist_hidden(), 'overview: and can be undone' );
+$_GET = array();
+$_REQUEST = array();
+delete_option( 'sendbeam_form_placed' );
+
+// With nothing sent yet the card says so rather than showing an empty list.
+sb_log_reset();
+has( sb_overview( $sb_done, $sb_verified ), 'Nothing has gone out through SendBeam from this site yet', 'overview: a site that has sent nothing is told so, not shown an empty list' );
+
+/* ────────────────────── The pop-up rules, as cards ─────────────────────
+ * Each rule was a grey fieldset with a black legend tag — the one screen in
+ * the plugin that looked like a different product.
+ */
+$GLOBALS['stub']['caps']['manage_options'] = true;
+update_option(
+ 'sendbeam_popups',
+ array(
+ array( 'enabled' => 1, 'form' => $form, 'trigger' => 'timer', 'delay' => 3, 'scroll' => 50, 'label' => '', 'once' => 'week', 'where' => 'everywhere', 'url' => '', 'heading' => 'Get the roast notes', 'blurb' => '', 'style' => 'split', 'image' => '', 'eyebrow' => 'Monthly', 'button' => 'Subscribe', 'proof' => 1 ),
+ array( 'enabled' => 0, 'form' => $other, 'trigger' => 'scroll', 'delay' => 5, 'scroll' => 70, 'label' => '', 'once' => 'day', 'where' => 'posts', 'url' => '', 'heading' => 'Before you go', 'blurb' => '', 'style' => 'bold', 'image' => '', 'eyebrow' => '', 'button' => '', 'proof' => 0 ),
+ )
+);
+
+ob_start();
+sendbeam_screen_popup();
+$sb_popups = ob_get_clean();
+
+has( $sb_popups, '', 'pop-ups: a rule is the same card as everything else on every other screen' );
+lacks( $sb_popups, '', 'pop-ups: not a fieldset' );
+lacks( $sb_popups, '' ), 'pop-ups: one card per rule, plus the template' );
+
+// The order is the rule, so the cards say which is which.
+has( $sb_popups, 'Pop-up 1 ', 'pop-ups: numbered, because the first match wins' );
+has( $sb_popups, 'Pop-up 2 ', 'pop-ups: in the order they are matched' );
+
+// The header carries the two things you do to a whole rule.
+$sb_head = substr( $sb_popups, strpos( $sb_popups, 'Pop-up 1 ' ) );
+$sb_head = substr( $sb_head, 0, strpos( $sb_head, '' ) );
+has( $sb_head, '[enabled]', 'pop-ups: the Active toggle is in the card header' );
+has( $sb_head, 'sb-toggle', 'pop-ups: as a switch' );
+has( $sb_head, 'sb-remove', 'pop-ups: and Remove beside it' );
+
+// Two fields that belong together, side by side and the same width.
+has( $sb_popups, '', 'pop-ups: Eyebrow and Button label share a row' );
+has( $sb_popups, 'The words on the pop-up', 'pop-ups: with helper text under each, so the labels line up' );
+
+// Every field keeps its name, so saving is unchanged.
+foreach ( array( 'form', 'where', 'url', 'trigger', 'delay', 'scroll', 'heading', 'blurb', 'style', 'image', 'eyebrow', 'button', 'proof', 'label', 'once', 'enabled' ) as $sb_field ) {
+ has( $sb_popups, 'sendbeam_popup[0][' . $sb_field . ']', "pop-ups: the $sb_field field keeps its name" );
+}
+has( $sb_popups, 'sendbeam_popup[1][form]', 'pop-ups: and the second rule keeps its index' );
+
+// The blank row the Add button clones carries placeholders for both.
+has( $sb_popups, 'sendbeam_popup[__i__]', 'pop-ups: the template still carries the index placeholder' );
+has( $sb_popups, '
Pop-up __n__ ', 'pop-ups: and one for the number, so a new card is not called Pop-up __i__' );
+
+// The page's own actions sit below the cards.
+ok(
+ strpos( $sb_popups, '+ Add a pop-up' ) > strpos( $sb_popups, '
Pop-up 2 ' ),
+ 'pop-ups: Add a pop-up sits below the cards'
+);
+has( $sb_popups, 'Save pop-ups', 'pop-ups: and Save with it' );
+
+// The grey is gone from the stylesheet too.
+lacks( $sendbeam_css, '.sb-rule{border:1px solid var(--ink);background:var(--paper)', 'pop-ups: nothing paints a rule grey any more' );
+has( $sendbeam_css, '.sb-rule__pair{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr', 'pop-ups: the paired fields are equal columns' );
+has( $sendbeam_css, '.sb-rule__grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:16px;align-items:start}', 'pop-ups: and the grid aligns labels at the top rather than fields at the bottom' );
+
+// Removing a card renumbers the rest, or the numbers start lying.
+has( $sendbeam_admin_js, 'function renumber()', 'pop-ups: the cards renumber themselves' );
+ok( 2 === substr_count( $sendbeam_admin_js, 'renumber();' ), 'pop-ups: after an add and after a remove' );
+
+update_option( 'sendbeam_popups', array() );
+
+/* ─────────────────────────── The email log ─────────────────────────────
+ * It was twenty rows in an option: a shop doing thirty order emails an hour
+ * lost the morning by lunchtime, and every write rewrote the whole array.
+ */
+sb_log_reset();
+$GLOBALS['stub']['dbdelta'] = array();
+delete_option( 'sendbeam_db_version' );
+
+// ── The table's shape ───────────────────────────────────────────────────
+sendbeam_mail_log_install();
+$sb_ddl = $GLOBALS['stub']['dbdelta'][0];
+has( $sb_ddl, 'CREATE TABLE wp_sendbeam_mail_log', 'log table: named from $wpdb->prefix, so multisite gets one per site' );
+foreach ( array(
+ 'id bigint(20) unsigned NOT NULL AUTO_INCREMENT',
+ 'sent_at datetime NOT NULL',
+ 'to_addr varchar(255)',
+ 'subject text NOT NULL',
+ 'result varchar(16)',
+ 'note text NOT NULL',
+ 'source varchar(64)',
+) as $sb_col ) {
+ has( $sb_ddl, $sb_col, "log table: the $sb_col column" );
+}
+has( $sb_ddl, 'PRIMARY KEY (id)', 'log table: with the two spaces dbDelta insists on' );
+has( $sb_ddl, 'KEY sent_at (sent_at)', 'log table: an index on the column everything orders by' );
+has( $sb_ddl, 'KEY result (result)', 'log table: and on the one the views filter by' );
+has( $sb_ddl, 'utf8mb4', 'log table: in the site\'s own charset and collation' );
+lacks( $sb_ddl, 'body', 'log table: the message itself is never stored' );
+lacks( $sb_ddl, 'html', 'log table: in any column' );
+ok( SENDBEAM_DB_VERSION === (int) get_option( 'sendbeam_db_version' ), 'log table: and the version is recorded' );
+
+// Installing again when the version already matches does nothing.
+$GLOBALS['stub']['dbdelta'] = array();
+sendbeam_mail_log_maybe_upgrade();
+ok( 0 === count( $GLOBALS['stub']['dbdelta'] ), 'log table: a version that already matches does not run dbDelta again' );
+
+// An upgrade by zip fires no activation hook, so the tidy-up is scheduled
+// from here too or a site that upgraded that way keeps its log for ever.
+$GLOBALS['stub']['cron'] = array();
+delete_option( 'sendbeam_db_version' );
+sendbeam_mail_log_maybe_upgrade();
+ok( (bool) wp_next_scheduled( SENDBEAM_PRUNE_HOOK ), 'log table: an upgrade schedules the daily tidy-up, activation hook or not' );
+
+// ── Writing ────────────────────────────────────────────────────────────
+sb_log_reset();
+ok( sendbeam_mail_log_insert( 'ada@customer.test', 'Order #1001', 'sent', '', 'woocommerce', 1758700000 ), 'log: a row goes in' );
+$sb_row = sb_log()[0];
+ok( 'ada@customer.test' === $sb_row['to_addr'], 'log: with the address it went to' );
+ok( '2025-09-24 07:46:40' === $sb_row['sent_at'], 'log: and a UTC datetime, so the log does not move when the site changes timezone' );
+ok( 'woocommerce' === $sb_row['source'], 'log: and which plugin asked for it' );
+sendbeam_mail_log_insert( 'bob@t.test', 'X', 'nonsense-result', '', '', 1758700001 );
+ok( 'failed' === sb_log()[0]['result'], 'log: a result nobody recognises is recorded as a failure, not as a success' );
+sendbeam_mail_log_insert( array( 'a@t.test', 'b@t.test' ), 'Y', 'sent', '', '', 1758700002 );
+ok( 'a@t.test, b@t.test' === sb_log()[0]['to_addr'], 'log: several recipients become one readable field' );
+sendbeam_mail_log_insert( str_repeat( 'x', 400 ) . '@t.test', 'Z', 'sent', '', str_repeat( 's', 200 ), 1758700003 );
+ok( 255 === mb_strlen( sb_log()[0]['to_addr'] ), 'log: an address longer than the column is cut, not refused' );
+ok( 64 === mb_strlen( sb_log()[0]['source'] ), 'log: and so is the source' );
+
+// ── The migration off the option ───────────────────────────────────────
+sb_log_reset();
+update_option(
+ 'sendbeam_mail_log',
+ array(
+ array( 'at' => 1758700000, 'to' => 'new@t.test', 'subject' => 'Newest', 'result' => 'sent', 'note' => '' ),
+ array( 'at' => 1758600000, 'to' => 'old@t.test', 'subject' => 'Oldest', 'result' => 'failed', 'note' => 'refused' ),
+ )
+);
+ok( 2 === sendbeam_mail_log_migrate(), 'migration: both rows move into the table' );
+ok( false === get_option( 'sendbeam_mail_log' ), 'migration: and the option is gone' );
+$sb_moved = sb_log();
+ok( 'new@t.test' === $sb_moved[0]['to_addr'], 'migration: newest first, as it was' );
+ok( '2025-09-23 04:00:00' === $sb_moved[1]['sent_at'], 'migration: with the original timestamps, not the moment of the upgrade' );
+ok( 'refused' === $sb_moved[1]['note'], 'migration: and the reason it failed' );
+
+// Twice is not twice as many rows.
+ok( 0 === sendbeam_mail_log_migrate(), 'migration: running it again finds nothing' );
+ok( 2 === count( sb_log() ), 'migration: and does not duplicate what it already moved' );
+
+// ── Reading ────────────────────────────────────────────────────────────
+sb_log_reset();
+sendbeam_mail_log_insert( 'ada@customer.test', 'Order #1001', 'sent', '', 'woocommerce', 1758700000 );
+sendbeam_mail_log_insert( 'bob@customer.test', 'Password reset', 'failed', 'Monthly email limit reached', 'wp-core', 1758600000 );
+sendbeam_mail_log_insert( 'cat@customer.test', 'New comment', 'fallback', 'has attachments', '', 1758500000 );
+sendbeam_mail_log_insert( 'dan@customer.test', 'Receipt', 'sent', '', 'woocommerce', 1758400000 );
+
+$sb_counts = sendbeam_mail_log_counts();
+ok( 4 === $sb_counts['all'], 'views: the counts add up' );
+ok( 2 === $sb_counts['sent'] && 1 === $sb_counts['failed'] && 1 === $sb_counts['fallback'], 'views: one per result' );
+
+$sb_page = sendbeam_mail_log_query( array( 'per_page' => 2 ) );
+ok( 4 === $sb_page['total'], 'query: the total counts every match, not the page' );
+ok( 2 === count( $sb_page['rows'] ), 'query: and the page is the page' );
+ok( 'ada@customer.test' === $sb_page['rows'][0]['to_addr'], 'query: newest first by default' );
+$sb_page = sendbeam_mail_log_query( array( 'per_page' => 2, 'page' => 2 ) );
+ok( 'cat@customer.test' === $sb_page['rows'][0]['to_addr'], 'query: the second page carries on where the first stopped' );
+
+$sb_page = sendbeam_mail_log_query( array( 'view' => 'sent' ) );
+ok( 2 === $sb_page['total'], 'query: a view narrows it to one result' );
+$sb_page = sendbeam_mail_log_query( array( 'view' => 'nonsense' ) );
+ok( 4 === $sb_page['total'], 'query: a view nobody defined is ignored rather than obeyed' );
+
+$sb_page = sendbeam_mail_log_query( array( 'search' => 'password' ) );
+ok( 1 === $sb_page['total'], 'search: the subject is searched' );
+$sb_page = sendbeam_mail_log_query( array( 'search' => 'cat@' ) );
+ok( 1 === $sb_page['total'], 'search: and the address' );
+$sb_page = sendbeam_mail_log_query( array( 'search' => 'limit reached' ) );
+ok( 1 === $sb_page['total'], 'search: and the reason it failed, which is what somebody actually looks for' );
+
+// Neither of the two things that cannot be a placeholder comes from a
+// request without passing through an allow-list first.
+$sb_page = sendbeam_mail_log_query( array( 'orderby' => 'note; DROP TABLE wp_posts', 'order' => 'DESC' ) );
+$sb_sql = implode( ' ', $GLOBALS['wpdb']->queries );
+lacks( $sb_sql, 'DROP TABLE wp_posts', 'query: an order column from the request cannot reach the statement' );
+has( $sb_sql, 'FROM `wp_sendbeam_mail_log`', 'query: and the table name is backticked, since it cannot be a placeholder before WordPress 6.2' );
+has( $sb_sql, 'ORDER BY sent_at', 'query: it falls back to the one column that is always safe' );
+sendbeam_mail_log_query( array( 'orderby' => 'result', 'order' => 'asc' ) );
+has( implode( ' ', $GLOBALS['wpdb']->queries ), 'ORDER BY result ASC', 'query: and an order it does recognise is used' );
+
+ok( 4 === count( sendbeam_mail_log_recent( 5 ) ), 'recent: asks for five and gets the four there are' );
+ok( 2 === count( sendbeam_mail_log_recent( 2 ) ), 'recent: and takes the limit seriously' );
+
+// ── Deleting ───────────────────────────────────────────────────────────
+$sb_ids = array_column( sb_log(), 'id' );
+ok( 1 === sendbeam_mail_log_delete( array( $sb_ids[0] ) ), 'delete: one row goes' );
+ok( 3 === count( sb_log() ), 'delete: and only that one' );
+ok( 0 === sendbeam_mail_log_delete( array() ), 'delete: nothing ticked deletes nothing' );
+ok( 3 === sendbeam_mail_log_clear(), 'clear: takes the rest' );
+ok( 0 === count( sb_log() ), 'clear: and leaves an empty table' );
+
+// ── Retention ──────────────────────────────────────────────────────────
+sb_seed_settings( array() );
+ok( 30 === sendbeam_mail_log_days(), 'retention: thirty days out of the box' );
+foreach ( array( 7, 30, 90, 0 ) as $sb_days ) {
+ sb_seed_settings( array( 'mail_log_days' => $sb_days ) );
+ ok( $sb_days === sendbeam_mail_log_days(), "retention: $sb_days is a choice" );
+}
+sb_seed_settings( array( 'mail_log_days' => 4000 ) );
+ok( 30 === sendbeam_mail_log_days(), 'retention: a number nobody offered falls back to thirty, not to for ever' );
+$sb_clean = sendbeam_sanitize_settings( array( '_tab' => 'mail', 'mail_log_days' => '90' ) );
+ok( 90 === $sb_clean['mail_log_days'], 'retention: the form saves a choice it recognises' );
+$sb_clean = sendbeam_sanitize_settings( array( '_tab' => 'mail', 'mail_log_days' => '-1' ) );
+ok( 30 === $sb_clean['mail_log_days'], 'retention: and refuses one it does not' );
+
+// ── Pruning ────────────────────────────────────────────────────────────
+sb_log_reset();
+sb_seed_settings( array( 'mail_log_days' => 7 ) );
+sendbeam_mail_log_insert( 'old@t.test', 'Old', 'sent', '', '', time() - ( 30 * DAY_IN_SECONDS ) );
+sendbeam_mail_log_insert( 'new@t.test', 'New', 'sent', '', '', time() - HOUR_IN_SECONDS );
+ok( 1 === sendbeam_mail_log_prune(), 'prune: a row past its date goes' );
+ok( 1 === count( sb_log() ) && 'new@t.test' === sb_log()[0]['to_addr'], 'prune: and the one inside it stays' );
+
+sb_seed_settings( array( 'mail_log_days' => 0 ) );
+sendbeam_mail_log_insert( 'ancient@t.test', 'Ancient', 'sent', '', '', time() - ( 900 * DAY_IN_SECONDS ) );
+ok( 0 === sendbeam_mail_log_prune(), 'prune: "for ever" keeps a nine-hundred-day-old row' );
+ok( 2 === count( sb_log() ), 'prune: whatever its date' );
+
+/*
+ * The cap is the other half. "For ever" is a promise about time, not about
+ * size, and a forgotten site on somebody else's hosting should not be able to
+ * fill their disk with it.
+ */
+ok( 20000 === SENDBEAM_MAIL_LOG_MAX, 'prune: there is a ceiling regardless' );
+sb_log_reset();
+for ( $sb_n = 0; $sb_n < 12; $sb_n++ ) {
+ sendbeam_mail_log_insert( "n{$sb_n}@t.test", 'X', 'sent', '', '', 1758000000 + $sb_n );
+}
+$GLOBALS['stub']['log_max'] = 10;
+ok( 12 === count( sb_log() ), 'prune: twelve rows in' );
+// With the constant at twenty thousand the cap cannot be reached in a test,
+// so the statement it would issue is what gets checked.
+$GLOBALS['wpdb']->queries = array();
+sendbeam_mail_log_prune();
+has( implode( ' ', $GLOBALS['wpdb']->queries ), 'SELECT COUNT(*) FROM `wp_sendbeam_mail_log`', 'prune: the cap is measured before it is applied' );
+
+// ── The cron that runs it ──────────────────────────────────────────────
+$GLOBALS['stub']['cron'] = array();
+sendbeam_mail_log_schedule_prune();
+$sb_cron = array_values( array_filter( $GLOBALS['stub']['cron'], function ( $c ) { return SENDBEAM_PRUNE_HOOK === $c['hook']; } ) );
+ok( 1 === count( $sb_cron ), 'cron: the tidy-up is scheduled' );
+ok( 'daily' === $sb_cron[0]['recurrence'], 'cron: once a day' );
+sendbeam_mail_log_schedule_prune();
+ok( 1 === count( array_filter( $GLOBALS['stub']['cron'], function ( $c ) { return SENDBEAM_PRUNE_HOOK === $c['hook']; } ) ), 'cron: scheduling twice does not schedule twice' );
+sendbeam_on_deactivate();
+ok( ! wp_next_scheduled( SENDBEAM_PRUNE_HOOK ), 'cron: deactivating clears it, so a switched-off plugin does no work' );
+sendbeam_on_activate();
+ok( wp_next_scheduled( SENDBEAM_PRUNE_HOOK ), 'cron: and activating puts it back' );
+
+// ── Clear the log ──────────────────────────────────────────────────────
+sb_log_reset();
+sendbeam_mail_log_insert( 'a@t.test', 'A', 'sent', '', '', 1758000001 );
+sendbeam_mail_log_insert( 'b@t.test', 'B', 'sent', '', '', 1758000002 );
+$GLOBALS['stub']['caps']['manage_options'] = true;
+$_REQUEST = array( '_wpnonce' => 'nonce:sendbeam_clear_log' );
+unset( $GLOBALS['stub']['redirect'] );
+try {
+ sendbeam_handle_clear_log();
+} catch ( SendBeamStubExit $e ) {
+ unset( $e );
+}
+$_REQUEST = array();
+ok( 0 === count( sb_log() ), 'clear the log: the button empties it' );
+has( $GLOBALS['stub']['redirect']['url'], 'sendbeam_log_cleared=2', 'clear the log: and says how many went' );
+
+// Without the nonce, or without the capability, nothing goes.
+sendbeam_mail_log_insert( 'c@t.test', 'C', 'sent', '', '', 1758000003 );
+$threw = false;
+try {
+ sendbeam_handle_clear_log();
+} catch ( SendBeamStubExit $e ) {
+ $threw = true;
+}
+ok( $threw, 'clear the log: refused without a nonce' );
+ok( 1 === count( sb_log() ), 'clear the log: and nothing was deleted' );
+
+$GLOBALS['stub']['caps']['manage_options'] = false;
+$_REQUEST = array( '_wpnonce' => 'nonce:sendbeam_clear_log' );
+$threw = false;
+try {
+ sendbeam_handle_clear_log();
+} catch ( SendBeamStubExit $e ) {
+ $threw = true;
+}
+ok( $threw, 'clear the log: refused without the capability' );
+ok( 1 === count( sb_log() ), 'clear the log: and still nothing was deleted' );
+$GLOBALS['stub']['caps']['manage_options'] = true;
+$_REQUEST = array();
+
+// It is a button on the screen, behind a closed confirmation, and NOT a
+// bulk action sitting one mis-click from "Delete".
+ob_start();
+sendbeam_mail_log_clear_action();
+$sb_clear = ob_get_clean();
+has( $sb_clear, '
', 'clear the log: behind a confirmation that renders nothing until it is pressed' );
+has( $sb_clear, 'Clear the log', 'clear the log: which is what the button says' );
+has( $sb_clear, 'value="sendbeam_clear_log"', 'clear the log: posting to its own handler' );
+has( $sb_clear, 'nonce:sendbeam_clear_log', 'clear the log: with a nonce' );
+$sb_bulk = ( new SendBeam_Mail_Log_Table() );
+ob_start();
+$sb_bulk->prepare_items();
+$sb_bulk->display();
+$sb_bulk_html = ob_get_clean();
+lacks( $sb_bulk_html, 'Delete all', 'clear the log: and never as a bulk action beside Delete' );
+
+// ── The views, on the screen ───────────────────────────────────────────
+sb_log_reset();
+sendbeam_mail_log_insert( 'a@t.test', 'A', 'sent', '', '', 1758000001 );
+sendbeam_mail_log_insert( 'b@t.test', 'B', 'failed', 'nope', '', 1758000002 );
+$sb_views = new SendBeam_Mail_Log_Table();
+$sb_views->prepare_items();
+ob_start();
+$sb_views->views();
+$sb_views_html = ob_get_clean();
+has( $sb_views_html, 'All (2) ', 'views: All, with a count' );
+has( $sb_views_html, 'Sent (1) ', 'views: Sent, with a count' );
+has( $sb_views_html, 'Failed (1) ', 'views: Failed, with a count' );
+lacks( $sb_views_html, 'Server mailer', 'views: and a view nothing landed in is not a link to an empty screen' );
+
+// ── Uninstall ──────────────────────────────────────────────────────────
+$sb_uninstall = file_get_contents( dirname( __DIR__ ) . '/uninstall.php' );
+has( $sb_uninstall, 'DROP TABLE IF EXISTS', 'uninstall: the table is dropped' );
+has( $sb_uninstall, "\$wpdb->prefix . 'sendbeam_mail_log'", 'uninstall: the one this site made' );
+has( $sb_uninstall, "str_replace( '`', '``'", 'uninstall: with the name backtick-escaped, since a DROP cannot take a placeholder' );
+has( $sb_uninstall, "'sendbeam_db_version'", 'uninstall: and the version that says it exists' );
+has( $sb_uninstall, "'sendbeam_mail_log'", 'uninstall: with the old option swept too, for a site that never upgraded past it' );
+
+sb_log_reset();
+sb_seed_settings( array() );
+
+// ── #1 Two Save buttons on one tab, two field groups ────────────────────
+// The Forms screen has a Defaults card and an Appearance card, each its own
+// . While both posted `_tab=forms` the sanitiser read the absent card's
+// fields as cleared, so pressing Save on Appearance emptied contact_form and
+// took the contact form off every published page that used [sendbeam_contact].
+sb_seed_settings(
+ sendbeam_sanitize_settings(
+ array(
+ '_tab' => 'forms',
+ 'default_form' => '9da94d34-86f8-4fbc-9333-45c0b4c16d6a',
+ 'contact_form' => '14dad6b8-6998-4f1f-8924-3ebd79524c94',
+ )
+ )
+);
+sb_seed_settings(
+ sendbeam_sanitize_settings(
+ array(
+ '_tab' => 'forms_style',
+ 'style_accent' => '#a8452a',
+ 'style_radius' => '4',
+ 'style_size' => '15',
+ 'style_bare' => '1',
+ )
+ )
+);
+$sb_before = sendbeam_settings();
+ok( '#a8452a' === $sb_before['style_accent'] && '14dad6b8-6998-4f1f-8924-3ebd79524c94' === $sb_before['contact_form'], 'forms: both cards are saved to begin with' );
+
+// Press Save on Defaults, having typed nothing. Appearance is not in $_POST.
+$sb_after = sendbeam_sanitize_settings( array( '_tab' => 'forms', 'default_form' => $sb_before['default_form'], 'contact_form' => $sb_before['contact_form'] ) );
+ok( '#a8452a' === $sb_after['style_accent'], 'forms: saving Defaults leaves the accent colour alone' );
+ok( '4' === $sb_after['style_radius'] && '15' === $sb_after['style_size'], 'forms: saving Defaults leaves radius and text size alone' );
+ok( 1 === (int) $sb_after['style_bare'], 'forms: saving Defaults does not untick "hide the form name"' );
+
+// Press Save on Appearance, having typed nothing. The form IDs are not in $_POST.
+$sb_after = sendbeam_sanitize_settings( array( '_tab' => 'forms_style', 'style_accent' => '#a8452a', 'style_radius' => '4', 'style_size' => '15', 'style_bare' => '1' ) );
+ok( '14dad6b8-6998-4f1f-8924-3ebd79524c94' === $sb_after['contact_form'], 'forms: saving Appearance does not empty the contact form — [sendbeam_contact] renders nothing without it' );
+ok( '9da94d34-86f8-4fbc-9333-45c0b4c16d6a' === $sb_after['default_form'], 'forms: saving Appearance does not empty the default form' );
+
+// And the guarantee that made the grouping exist in the first place still holds.
+$sb_after = sendbeam_sanitize_settings( array( '_tab' => 'forms_style', 'style_accent' => '#a8452a' ) );
+ok( $sb_before['api_key'] === $sb_after['api_key'], 'forms: saving Appearance does not touch the API key' );
+sb_seed_settings( array() );
+
+// ── #3 The test email must describe the message it is ──────────────────
+// The card said "SendBeam refuses messages from it" in a message SendBeam had
+// just delivered, gave the From address the site asked for rather than the one
+// in the headers, and named the site's own domain as the signer when the DKIM
+// signature was SendBeam's. Everything in it came from what the site wanted
+// and nothing from what happened.
+sb_seed_settings( array( 'api_key' => 'sb_live_substitutedxxxxxxx', 'mail_enabled' => 1, 'mail_from_email' => 'hello@not-verified.test' ) );
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'ws-db645350@mail.sendbeam.io' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => true, 'records' => array() ),
+ )
+ )
+);
+$sb_s = sendbeam_effective_sender();
+ok( 'other' === $sb_s['kind'], 'sender: an address on an unverified domain is still classified as other' );
+ok( true === $sb_s['substituted'], 'sender: and the plugin knows SendBeam will not use it' );
+ok( 'ws-db645350@mail.sendbeam.io' === $sb_s['used'], 'sender: the workspace sender is the address that actually goes out' );
+ok( 'mail.sendbeam.io' === $sb_s['signed'], 'sender: and its host is what signs the message, not the one asked for' );
+ok( 'not-verified.test' !== $sb_s['signed'], 'sender: never the domain that took no part in the transaction' );
+
+$sb_rows = sendbeam_mail_facts();
+ok( 'mail.sendbeam.io' === $sb_rows['Signed by'], 'test email: the Signed by row is the real signer' );
+has( $sb_rows['From address'], 'SendBeam sent this as ws-db645350@mail.sendbeam.io', 'test email: the From row names the substitution' );
+
+$sb_next = sendbeam_test_mail_next_step( $sb_s );
+has( $sb_next['text'], 'sent this under its own address', 'test email: the next step describes the substitution' );
+lacks( $sb_next['text'], 'refuses', 'test email: and does not claim a refusal' );
+
+// The address the site asked for IS used once its domain is verified, and
+// then its own domain is the signer.
+sb_seed_settings( array( 'api_key' => 'sb_live_substitutedxxxxxxx', 'mail_enabled' => 1, 'mail_from_email' => 'hello@harbourlane.co.uk' ) );
+$sb_s = sendbeam_effective_sender();
+ok( false === $sb_s['substituted'], 'sender: a verified domain is not substituted' );
+ok( 'hello@harbourlane.co.uk' === $sb_s['used'] && 'harbourlane.co.uk' === $sb_s['signed'], 'sender: and it signs its own mail' );
+
+// A verified domain the site is not using yet: the shared address goes out
+// as asked, so the shared host is the signer and nothing is substituted.
+sb_seed_settings( array( 'api_key' => 'sb_live_substitutedxxxxxxx', 'mail_enabled' => 1, 'mail_from_email' => 'ws-db645350@mail.sendbeam.io' ) );
+$sb_s = sendbeam_effective_sender();
+ok( 'shared' === $sb_s['kind'] && false === $sb_s['substituted'], 'sender: the shared address is used as asked' );
+ok( 'mail.sendbeam.io' === $sb_s['signed'], 'sender: and signs as the shared host' );
+
+// The domain is NOT verified, so even an address on it is substituted.
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'sender' => array( 'from_name' => 'Harbour Lane', 'from_email' => 'ws-db645350@mail.sendbeam.io' ),
+ 'domain' => array( 'name' => 'harbourlane.co.uk', 'verified' => false, 'records' => array() ),
+ )
+ )
+);
+sb_seed_settings( array( 'api_key' => 'sb_live_substitutedxxxxxxx', 'mail_enabled' => 1, 'mail_from_email' => 'hello@harbourlane.co.uk' ) );
+$sb_s = sendbeam_effective_sender();
+ok( 'own_domain' === $sb_s['kind'], 'sender: an address on the site\'s own unverified domain is still its own' );
+ok( true === $sb_s['substituted'] && 'mail.sendbeam.io' === $sb_s['signed'], 'sender: but nothing signs for a domain DNS has not proved' );
+sb_seed_settings( array() );
+
+// ── #4 "SendBeam could not be reached" when SendBeam answered ───────────
+// domain_state 'unavailable' means two opposite things: the plugin could not
+// reach SendBeam, and SendBeam answered saying it could not create the domain.
+// Straight after a successful Connect the cached status held ok:true and
+// "wp-test.sendbeam.io could not be added as a sending domain: That domain is
+// already registered." in two places, and step 2 printed a different, false
+// reason instead.
+sb_seed_settings( array( 'api_key' => 'sb_live_unavailablexxxxxxxx' ) );
+$sb_live = sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'E2E UI' ),
+ 'domain' => null,
+ 'domain_state' => 'unavailable',
+ 'domain_note' => 'wp-test.sendbeam.io could not be added as a sending domain: That domain is already registered.',
+ )
+);
+ok( sendbeam_connect_status_is_live( $sb_live ), 'status: an answer SendBeam gave is live' );
+sendbeam_connect_cache_status( $sb_live );
+$sb_step = sendbeam_setup_steps()[1];
+has( $sb_step['detail'], 'That domain is already registered', 'step 2: prints the reason SendBeam gave' );
+lacks( $sb_step['detail'], 'could not be reached', 'step 2: and does not claim SendBeam was unreachable' );
+
+// The other reading of the same word still says the right thing.
+$sb_dead = sendbeam_connect_empty_status();
+$sb_dead['stale'] = true;
+$sb_dead['ok'] = true;
+$sb_dead['error'] = 'cURL error 28: Operation timed out';
+$sb_dead['domain_state'] = 'unavailable';
+$sb_dead['domain_note'] = 'wp-test.sendbeam.io could not be added as a sending domain: That domain is already registered.';
+ok( ! sendbeam_connect_status_is_live( $sb_dead ), 'status: a stale copy served after a failed request is not live' );
+sendbeam_connect_cache_status( $sb_dead );
+$sb_step = sendbeam_setup_steps()[1];
+has( $sb_step['detail'], 'could not be reached', 'step 2: a failed request still says so' );
+lacks( $sb_step['detail'], 'already registered', 'step 2: and does not pass off a stale note as this answer' );
+sb_seed_settings( array() );
+
+// ── #7 Copy on a contact row handed you a different form ────────────────
+// Every contact row offered a bare [sendbeam_contact], which renders
+// $settings['contact_form'] and nothing else. The Placed on column said "Not
+// a default — place it by shortcode", and the shortcode it gave could not
+// carry out that instruction for any contact form but the chosen default.
+$sb_wholesale = 'aaaaaaaa-1111-2222-3333-444444444444';
+$sb_default = '14dad6b8-6998-4f1f-8924-3ebd79524c94';
+sb_seed_settings( array_merge( sendbeam_settings(), array( 'contact_form' => $sb_default ) ) );
+
+ok( false !== strpos( do_shortcode_tag( 'sendbeam_contact' ), '/f/' . $sb_default ), 'contact: a bare shortcode still renders the chosen default' );
+ok( false !== strpos( do_shortcode_tag( 'sendbeam_contact', array( 'id' => $sb_wholesale ) ), '/f/' . $sb_wholesale ), 'contact: and a named one renders the form it names' );
+ok( false === strpos( do_shortcode_tag( 'sendbeam_contact', array( 'id' => $sb_wholesale ) ), '/f/' . $sb_default ), 'contact: not the default instead of it' );
+has( do_shortcode_tag( 'sendbeam_contact', array( 'id' => $sb_wholesale ) ), 'sendbeam-contact-wrap', 'contact: still the contact wrapper, so existing styling holds' );
+
+// An id that is not a form id embeds nothing at all, rather than quietly
+// falling back to the default and placing the wrong form.
+lacks( do_shortcode_tag( 'sendbeam_contact', array( 'id' => 'not-an-id' ) ), '/f/', 'contact: a nonsense id embeds no form at all' );
+sb_seed_settings( array() );
+
+// ── #11 "Remove the saved key" left a Connect key live in the workspace ─
+// The Overview's Disconnect revokes a Connect-issued key at SendBeam. The
+// Advanced tab's checkbox is a second, quieter door to the same place, and it
+// cleared the option and stopped — leaving the owner who tidied up there with
+// a live key for a site that no longer exists as far as they are concerned.
+sb_connect_reset();
+sb_seed_settings(
+ array(
+ 'api_key' => SENDBEAM_API_KEY,
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_workspace' => 'Harbour Lane',
+ )
+);
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 204 ), 'body' => '' );
+$sb_removed = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => '', 'api_key_remove' => '1' ) );
+ok( '' === $sb_removed['api_key'], 'advanced: the key is removed, as it always was' );
+ok( 1 === count( $GLOBALS['stub']['remote'] ), 'advanced: and SendBeam is asked to revoke it' );
+ok( 'https://sendbeam.io/api/v1/connect/disconnect' === $GLOBALS['stub']['remote'][0]['url'], 'advanced: through the same endpoint Disconnect uses' );
+ok( SENDBEAM_API_KEY === $GLOBALS['stub']['remote'][0]['args']['headers']['x-api-key'], 'advanced: the key revokes itself' );
+ok( '' === $sb_removed['sendbeam_connected_via'], 'advanced: and the site stops claiming how it was connected' );
+
+// A pasted key was minted for whatever it was minted for and may be in use
+// elsewhere. It is forgotten here and left alone there, as Disconnect does.
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => 'sb_live_pastedpastedpasted', 'sendbeam_connected_via' => '' ) );
+$sb_removed = sendbeam_sanitize_settings( array( '_tab' => 'connect', 'api_key' => '', 'api_key_remove' => '1' ) );
+ok( '' === $sb_removed['api_key'], 'advanced: a pasted key is forgotten too' );
+ok( empty( $GLOBALS['stub']['remote'] ), 'advanced: but nothing revokes a key this site did not issue' );
+
+// And the field says which of the two will happen, before it happens.
+sb_seed_settings( array( 'api_key' => SENDBEAM_API_KEY, 'sendbeam_connected_via' => 'connect' ) );
+has( sendbeam_key_removal_note(), 'also revokes it in SendBeam', 'advanced: the field says a Connect key will be revoked' );
+sb_seed_settings( array( 'api_key' => 'sb_live_pastedpastedpasted', 'sendbeam_connected_via' => '' ) );
+has( sendbeam_key_removal_note(), 'only forgotten here', 'advanced: and that a pasted key is only forgotten' );
+sb_connect_reset();
+sb_seed_settings( array() );
+
+// ── #12 Reconnect destroyed the sending domain the site already had ─────
+// The consent page prefilled SEND FROM from site_url on every run, so pressing
+// Reconnect for any other reason — more permissions, a changed workspace, a
+// key rotation — re-set the sending domain to this site's host. The domain the
+// owner chose, and the three CNAMEs they may have been half-way through
+// entering, simply vanished from the workspace with no warning.
+sb_connect_reset();
+sb_seed_settings(
+ array(
+ 'api_key' => SENDBEAM_API_KEY,
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_granted' => 'forms,domain',
+ )
+);
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'mail.wp-test.sendbeam.io', 'verified' => false, 'records' => array() ),
+ )
+ )
+);
+ok( 'mail.wp-test.sendbeam.io' === sendbeam_connect_current_sending_host(), 'reconnect: the site knows the domain it already sends from' );
+
+/** The consent URL one of the three links produces. */
+function sb_consent_for( $url ) {
+ parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $q );
+ $keep = empty( $q['sendbeam_new_domain'] );
+ parse_str(
+ (string) wp_parse_url(
+ sendbeam_connect_consent_url( array( 'forms' ), 'statestatestate', $keep ? sendbeam_connect_current_sending_host() : '' ),
+ PHP_URL_QUERY
+ ),
+ $c
+ );
+ return $c;
+}
+
+// 1. The connected card's plain Reconnect.
+$sb_c = sb_consent_for( sendbeam_connect_start_url() );
+ok( 'mail.wp-test.sendbeam.io' === rawurldecode( $sb_c['sending_host'] ), 'reconnect: a plain Reconnect offers the existing domain back' );
+
+// 2. "Reconnect with more permissions".
+$sb_c = sb_consent_for( sendbeam_connect_start_url( true ) );
+ok( 'mail.wp-test.sendbeam.io' === rawurldecode( $sb_c['sending_host'] ), 'reconnect: so does reconnecting for more permissions' );
+
+// 3. "Sending from the wrong domain? Reconnect and enter the one you want."
+$sb_wrong = sendbeam_connect_start_url( false, false );
+has( $sb_wrong, 'sendbeam_new_domain=1', 'reconnect: the wrong-domain link says it wants a different one' );
+$sb_c = sb_consent_for( $sb_wrong );
+ok( ! isset( $sb_c['sending_host'] ), 'reconnect: and passes no domain, because choosing another is the point' );
+
+// A first connect has no domain to offer, so it offers none.
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => '' ) );
+sendbeam_connect_cache_status( sendbeam_connect_empty_status() );
+ok( '' === sendbeam_connect_current_sending_host(), 'reconnect: a site with no key has no domain to keep' );
+$sb_c = sb_consent_for( sendbeam_connect_start_url() );
+ok( ! isset( $sb_c['sending_host'] ), 'reconnect: so a first connect sends no sending_host at all' );
+
+// Only a hostname ever goes out.
+ok( '' === sendbeam_connect_clean_host( 'not a host' ), 'reconnect: a value that is not a hostname is dropped' );
+ok( '' === sendbeam_connect_clean_host( 'https://example.com/path' ), 'reconnect: a URL is not a hostname' );
+ok( '' === sendbeam_connect_clean_host( str_repeat( 'a', 250 ) . '.example.com' ), 'reconnect: and nothing over 253 characters' );
+ok( 'mail.example.co.uk' === sendbeam_connect_clean_host( ' MAIL.Example.CO.UK ' ), 'reconnect: a real host is trimmed and lowercased' );
+sb_connect_reset();
+sb_seed_settings( array() );
+
+// ── #13 The longest DNS host was clipped on desktop ─────────────────────
+// The Host column is 30% — about 282px at 1280 — and a
+// `resend._domainkey.mail.` host is longer than that. The wrapping
+// rule lived only inside the <=782px media query, so the phone case that had
+// been complained about was fixed and the desktop one was not: the value was
+// cut off inside the very field the owner is told to read from.
+$sb_css = sendbeam_admin_css();
+$sb_field_rule = substr( $sb_css, strpos( $sb_css, '.sendbeam-app .sb-copy-field{' ) );
+$sb_field_rule = substr( $sb_field_rule, 0, strpos( $sb_field_rule, '}' ) );
+has( $sb_field_rule, 'white-space:pre-wrap', 'records: the copy field wraps at every width, not only on a phone' );
+has( $sb_field_rule, 'word-break:break-all', 'records: and breaks a host that has nowhere else to break' );
+lacks( $sb_field_rule, 'white-space:pre;', 'records: nothing pins it to one line' );
+has( $sb_field_rule, 'overflow:auto', 'records: with no script it scrolls rather than hiding the rest' );
+
+// The media query must not be the only place wrapping is switched on again.
+$sb_phone = substr( $sb_css, strpos( $sb_css, '@media (max-width:782px)' ) );
+lacks( $sb_phone, '.sb-dns .sb-copy-field{white-space:pre-wrap', 'records: the phone override is gone, because it is the default now' );
+
+// And a real host still renders whole into the field.
+$sb_long = 'resend._domainkey.mail.wp-test.sendbeam.io';
+has( sendbeam_copy_field( $sb_long, 'Host', 'sb-h1' ), '>' . $sb_long . '', 'records: the whole host is in the field' );
+has( sendbeam_copy_field( $sb_long, 'Host', 'sb-h1' ), 'data-copy="' . $sb_long . '"', 'records: and the whole host is what gets copied' );
+
+// ── #14 Check now threw you to the Overview ─────────────────────────────
+// The check is offered on the Overview and on Settings → Sending domain, and
+// always landed on the Overview. Somebody copying records on the Sending tab
+// was moved to another screen to be told the result and had to navigate back
+// to carry on with the records they were half-way through.
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => SENDBEAM_API_KEY ) );
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) );
+$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check', 'sendbeam_back' => 'sendbeam-settings' );
+$_REQUEST = $_POST;
+$sb_url = sb_run_admin_post( 'sendbeam_handle_domain_check' );
+has( $sb_url, 'page=sendbeam-settings', 'check: pressed on the Sending tab, it comes back to the Sending tab' );
+has( $sb_url, 'tab=domain', 'check: on the records themselves' );
+has( $sb_url, 'sendbeam_domain=', 'check: still carrying the result' );
+
+// Pressed on the Overview, it stays on the Overview.
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) );
+$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check', 'sendbeam_back' => 'sendbeam' );
+$_REQUEST = $_POST;
+$sb_url = sb_run_admin_post( 'sendbeam_handle_domain_check' );
+has( $sb_url, 'page=sendbeam&', 'check: pressed on the Overview, it stays there' );
+
+// Anything that is not one of this plugin's pages goes to the Overview.
+$GLOBALS['stub']['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => sb_status_body( false ) );
+$_POST = array( '_wpnonce' => 'nonce:sendbeam_domain_check', 'sendbeam_back' => 'https://evil.test/' );
+$_REQUEST = $_POST;
+$sb_url = sb_run_admin_post( 'sendbeam_handle_domain_check' );
+lacks( $sb_url, 'evil.test', 'check: a return value that is not one of our pages is ignored' );
+has( $sb_url, 'page=sendbeam&', 'check: and falls back to the Overview' );
+$_POST = array();
+$_REQUEST = array();
+sb_connect_reset();
+sb_seed_settings( array() );
+
+// ── #15 The page about the sending domain said less than the checklist ──
+// The Overview's step 2 gave SendBeam's own reason; Settings → Sending domain
+// dropped it and said only "Add one under Settings → Domains in SendBeam" —
+// on the screen dedicated to the subject. The Overview also named two
+// different SendBeam screens in consecutive sentences, because its own
+// instruction was appended after SendBeam's.
+sb_connect_reset();
+sb_seed_settings( array( 'api_key' => SENDBEAM_API_KEY ) );
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => null,
+ 'domain_state' => 'not_found',
+ 'domain_note' => "This site's sending domain is no longer in the workspace. Reconnect the site, or add the domain again under Settings → Sending.",
+ )
+ )
+);
+$sb_status = sendbeam_connect_status();
+
+$sb_sentence = sendbeam_domain_missing_sentence( $sb_status );
+has( $sb_sentence, 'no longer in the workspace', 'domain: the sentence carries the reason SendBeam gave' );
+lacks( $sb_sentence, 'Settings → Domains', 'domain: and does not name a second SendBeam screen after SendBeam named one' );
+
+ob_start();
+sendbeam_domain_panel( $sb_status, true );
+$sb_panel = ob_get_clean();
+has( $sb_panel, 'no longer in the workspace', 'domain: the Sending domain screen says as much as the checklist does' );
+
+// With no note, the plugin's own instruction is the only one there is.
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => null,
+ 'domain_state' => 'not_found',
+ )
+ )
+);
+$sb_sentence = sendbeam_domain_missing_sentence( sendbeam_connect_status() );
+has( $sb_sentence, 'Add one under Settings → Domains in SendBeam', 'domain: with nothing from SendBeam, the plugin says where to go' );
+sb_connect_reset();
+sb_seed_settings( array() );
+
+// ── #16 Every permission refusal was served as HTTP 500 ─────────────────
+// wp_die() with no status argument defaults to 500, so every one of this
+// plugin's admin-post actions answered an Editor's POST with a server error.
+// The refusal itself was right; the status line put a 500 in every access log
+// and every uptime monitor watching status codes. The nonce refusals were
+// already correct, because check_admin_referer() answers 403.
+//
+// The list is taken from the hooks the plugin actually registered, so an
+// action added later cannot quietly miss this.
+$sb_actions = array();
+foreach ( $GLOBALS['stub']['callbacks'] as $sb_cb ) {
+ if ( 0 === strpos( $sb_cb[0], 'admin_post_sendbeam_' ) ) {
+ $sb_actions[ $sb_cb[0] ] = $sb_cb[1];
+ }
+}
+ok( count( $sb_actions ) >= 16, 'refusal: there are ' . count( $sb_actions ) . ' admin-post actions to check' );
+
+$GLOBALS['stub']['caps']['manage_options'] = false;
+foreach ( $sb_actions as $sb_hook => $sb_fn ) {
+ $GLOBALS['stub']['died'] = null;
+ $_POST = array();
+ $_REQUEST = array();
+ try {
+ call_user_func( $sb_fn );
+ } catch ( SendBeamStubExit $e ) {
+ unset( $e ); // Expected: each of these refuses before doing anything.
+ }
+ $sb_died = $GLOBALS['stub']['died'];
+ ok( is_array( $sb_died ), "refusal: $sb_hook refuses a caller without the capability" );
+ has( $sb_died['message'], 'do not have permission', "refusal: $sb_hook says why" );
+ ok( 403 === $sb_died['status'], "refusal: $sb_hook answers 403, not a server error" );
+}
+$GLOBALS['stub']['caps']['manage_options'] = true;
+$GLOBALS['stub']['died'] = null;
+$_POST = array();
+$_REQUEST = array();
+
+// And no permission refusal anywhere in the plugin is left on the default —
+// the bulk-action guard on the email log table is not an admin-post action
+// and would not be reached by the loop above.
+$sb_bad = array();
+foreach ( glob( dirname( __DIR__ ) . '/includes/*.php' ) as $sb_file ) {
+ if ( false !== strpos( file_get_contents( $sb_file ), "wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ) );" ) ) {
+ $sb_bad[] = basename( $sb_file );
+ }
+}
+ok( array() === $sb_bad, 'refusal: no wp_die() is left on the 500 default — ' . implode( ', ', $sb_bad ) );
+
+// ── #17 Phone tap targets were 26-36px ──────────────────────────────────
+// Apple asks for 44pt and Android for 48dp. Every button on every SendBeam
+// screen measured 26-36px at 393px, and the 26px "I already have an API key"
+// disclosure on the Overview is the one an owner reaches for first.
+$sb_css = sendbeam_admin_css();
+$sb_phone = substr( $sb_css, strpos( $sb_css, '@media (max-width:782px)' ) );
+has( $sb_phone, '.sendbeam-app .sb-btn{min-height:44px', 'touch: buttons are 44px on a phone' );
+has( $sb_phone, '.sendbeam-app .sb-btn--small{min-height:44px', 'touch: and the small ones grow to the same 44px' );
+has( $sb_phone, '.sb-paste>summary{padding:12px 0;min-height:44px', 'touch: so does the paste-a-key disclosure' );
+has( $sb_phone, '.sendbeam-app .sb-link{min-height:44px', 'touch: and a link that acts as a button' );
+
+// The desktop metrics are untouched: this is a phone problem.
+$sb_desk = substr( $sb_css, 0, strpos( $sb_css, '@media (max-width:782px)' ) );
+has( $sb_desk, '.sendbeam-app .sb-btn{display:inline-flex', 'touch: the desktop button rule is still there' );
+has( $sb_desk, 'min-height:36px', 'touch: at its original 36px' );
+
+// ── #18 "Not installed" about plugins that are installed ────────────────
+// The probe is a class or function check, which is the right probe; it
+// answers "is this running". A plugin sitting in wp-content/plugins waiting
+// to be activated is installed, and somebody who has just installed one and
+// is wondering why nothing changed is exactly the person reading this row.
+ob_start();
+sendbeam_screen_form_plugins( array() );
+$sb_plugins = ob_get_clean();
+has( $sb_plugins, 'Contact Form 7', 'bridges: the table lists every plugin it supports' );
+lacks( $sb_plugins, 'Not installed', 'bridges: it never says "Not installed", which the probe cannot know' );
+
+// The probe answers "is this running", so that is the word, wherever it is
+// rendered. Asserted against the source because every bridge class exists in
+// this process, so every row renders Active here.
+$sb_bridges_src = file_get_contents( dirname( __DIR__ ) . '/includes/screens.php' );
+has( $sb_bridges_src, "esc_html__( 'Not active', 'sendbeam' )", 'bridges: the label a row gets when the plugin is not running is "Not active"' );
+$sb_all_src = '';
+foreach ( glob( dirname( __DIR__ ) . '/includes/*.php' ) as $sb_file ) {
+ $sb_all_src .= file_get_contents( $sb_file );
+}
+lacks( $sb_all_src, "'Not installed'", 'bridges: and "Not installed" is said nowhere in the plugin' );
+
+// ── #19 The permissions list named the site's host, not the domain ──────
+// The domain scope's label names the host the consent page was asked about.
+// On a consent page that is right; on a connected site it describes the
+// request rather than the outcome, so a site connected with SEND FROM set to
+// mail.wp-test.sendbeam.io read "Set up this site's sending domain
+// (wp-test.sendbeam.io) in SendBeam" ever after.
+sb_connect_reset();
+sb_seed_settings(
+ array(
+ 'api_key' => SENDBEAM_API_KEY,
+ 'sendbeam_connected_via' => 'connect',
+ 'sendbeam_connect_granted' => 'forms,domain',
+ )
+);
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => array( 'name' => 'mail.wp-test.sendbeam.io', 'verified' => false, 'records' => array() ),
+ )
+ )
+);
+$sb_granted = implode( ' | ', sendbeam_connect_granted_list() );
+has( $sb_granted, 'mail.wp-test.sendbeam.io', 'permissions: the list names the domain that was actually set up' );
+lacks( $sb_granted, '(www.example-site.test)', 'permissions: not the host the request was about' );
+
+// With no domain there is nothing better to say, so the scope's own label
+// stands — it is still true, and an empty parenthesis would not be.
+sendbeam_connect_cache_status(
+ sendbeam_connect_normalise_status(
+ array(
+ 'workspace' => array( 'id' => 'w1', 'name' => 'Harbour Lane' ),
+ 'domain' => null,
+ )
+ )
+);
+has( implode( ' | ', sendbeam_connect_granted_list() ), "Set up this site's sending domain", 'permissions: a site with no domain keeps the original wording' );
+sb_connect_reset();
+sb_seed_settings( array() );
+
+// ── The hiding rule has to beat every layout rule in the file ───────────
+// .sendbeam-app .is-hidden is (0,2,0) and the Settings API reset
+// `.sendbeam-app .form-table tr` is (0,2,1), so the From name, From address
+// and fallback rows on Site email were drawn whether the switch was on or
+// off — the exact thing the server-rendered pattern exists to prevent. This
+// parses the stylesheet rather than looking for one string, so the next rule
+// that out-specifies it fails here instead of on a screen.
+$sb_css = sendbeam_admin_css();
+
+/**
+ * Every declaration block in the stylesheet, with its selectors.
+ *
+ * Media queries are flattened: a rule inside one still competes with a rule
+ * outside it, because a media query adds nothing to specificity.
+ *
+ * @param string $css The stylesheet.
+ * @return array
+ */
+function sb_css_rules( $css ) {
+ $css = preg_replace( '!/\*.*?\*/!s', '', $css );
+ $css = preg_replace( '/@media[^{]*\{/', '', $css );
+ $rules = array();
+ if ( preg_match_all( '/([^{}]+)\{([^{}]*)\}/', $css, $m, PREG_SET_ORDER ) ) {
+ foreach ( $m as $one ) {
+ $sel = trim( $one[1] );
+ if ( '' === $sel || 0 === strpos( $sel, '@' ) ) {
+ continue;
+ }
+ $rules[] = array(
+ 'selectors' => array_map( 'trim', explode( ',', $sel ) ),
+ 'body' => $one[2],
+ );
+ }
+ }
+ return $rules;
+}
+
+/**
+ * CSS specificity as one comparable number: ids, classes, elements.
+ *
+ * @param string $selector One selector.
+ * @return int
+ */
+function sb_specificity( $selector ) {
+ $s = preg_replace( '/::?[a-z-]+(\([^)]*\))?/', ' PSEUDO ', $selector );
+ $ids = preg_match_all( '/#[A-Za-z0-9_-]+/', $s );
+ $classes = preg_match_all( '/\.[A-Za-z0-9_-]+/', $s ) + preg_match_all( '/\[[^\]]+\]/', $s );
+ $bare = preg_replace( '/[#.][A-Za-z0-9_-]+|\[[^\]]+\]|PSEUDO/', ' ', $s );
+ $els = preg_match_all( '/\b[a-z][a-z0-9]*\b/', $bare );
+ return $ids * 10000 + $classes * 100 + $els;
+}
+
+$sb_rules = sb_css_rules( $sb_css );
+$sb_hiders = array();
+foreach ( $sb_rules as $rule ) {
+ foreach ( $rule['selectors'] as $sel ) {
+ if ( false !== strpos( $sel, '.is-hidden' ) && preg_match( '/display\s*:\s*none/i', $rule['body'] ) ) {
+ $sb_hiders[] = array(
+ 'selector' => $sel,
+ 'spec' => sb_specificity( $sel ),
+ 'important' => (bool) preg_match( '/display\s*:\s*none\s*!important/i', $rule['body'] ),
+ );
+ }
+ }
+}
+ok( $sb_hiders, 'hiding: there is a rule that hides .is-hidden' );
+
+// Every rule that could put a display back on an element carrying .is-hidden.
+$sb_beats = array();
+foreach ( $sb_rules as $rule ) {
+ if ( ! preg_match( '/display\s*:\s*(block|flex|inline-flex|inline-block|grid|table|table-row|inline)/i', $rule['body'] ) ) {
+ continue;
+ }
+ $sb_loud = (bool) preg_match( '/display\s*:\s*[a-z-]+\s*!important/i', $rule['body'] );
+ foreach ( $rule['selectors'] as $sel ) {
+ if ( false !== strpos( $sel, '.is-hidden' ) ) {
+ continue;
+ }
+ $sb_spec = sb_specificity( $sel );
+ $sb_won = false;
+ foreach ( $sb_hiders as $h ) {
+ // !important beats anything that is not important; otherwise the
+ // hider needs at least equal specificity, since it is declared
+ // after the layout rules it has to beat.
+ if ( $h['important'] && ! $sb_loud ) {
+ $sb_won = true;
+ } elseif ( $h['important'] === $sb_loud && $h['spec'] >= $sb_spec ) {
+ $sb_won = true;
+ }
+ }
+ if ( ! $sb_won ) {
+ $sb_beats[] = $sel . ' (' . $sb_spec . ')';
+ }
+ }
+}
+ok( array() === $sb_beats, 'hiding: no display rule in the stylesheet out-ranks it — ' . implode( ', ', array_slice( $sb_beats, 0, 4 ) ) );
+
+// The one that actually bit, named, so the regression is unmistakable.
+$sb_tr_spec = sb_specificity( '.sendbeam-app .form-table tr' );
+ok( $sb_tr_spec > sb_specificity( '.sendbeam-app .is-hidden' ), 'hiding: the Settings API row reset really is the more specific selector' );
+ok( $sb_hiders[0]['important'], 'hiding: so the hiding rule wins on !important rather than on specificity' );
+
+// ── #17 again: small buttons and the tab bar are tap targets too ────────
+$sb_phone = substr( $sb_css, strpos( $sb_css, '@media (max-width:782px)' ) );
+has( $sb_phone, '.sendbeam-app .sb-btn--small{min-height:44px', 'touch: Copy, Remove, Check now and the confirmations are 44px' );
+has( $sb_phone, '.sb-tab{height:44px;min-height:44px}', 'touch: and so is the Settings tab bar' );
+lacks( $sb_phone, 'min-height:40px', 'touch: nothing on a phone is left at 40px' );
+lacks( $sb_phone, 'min-height:42px', 'touch: or at 42px' );
+
+// ── The block editor shows a placeholder, not the hosted form ───────────
+// The form is a cross-origin iframe and SendBeam serves it only to the sites
+// its owner has listed, which it decides from the referrer. The block editor
+// renders inside a nested iframe with an opaque origin, so there is no
+// referrer to send and the hosted page answered "This form can only be shown
+// on the sites its owner has listed" — on a site that is listed, and whose
+// published page rendered the same form perfectly.
+$sb_editor_js = file_get_contents( dirname( __DIR__ ) . '/blocks/form/index.js' );
+lacks( $sb_editor_js, 'ServerSideRender', 'block: the editor does not try to render the hosted form' );
+has( $sb_editor_js, 'The form appears here on the published page.', 'block: it says where the form will be instead' );
+has( $sb_editor_js, "__( 'Preview', 'sendbeam' )", 'block: and offers to open the real one in a tab' );
+has( $sb_editor_js, 'config.previewBase + effectiveId', 'block: the Preview link points at the form itself' );
+
+// The dependency that only existed for the live preview goes with it.
+$sb_asset = require dirname( __DIR__ ) . '/blocks/form/index.asset.php';
+ok( ! in_array( 'wp-server-side-render', $sb_asset['dependencies'], true ), 'block: and the editor stops loading a script nothing uses' );
+foreach ( array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-api-fetch' ) as $sb_dep ) {
+ ok( in_array( $sb_dep, $sb_asset['dependencies'], true ), "block: $sb_dep is still a dependency" );
+}
+
+// The editor is told where a preview lives, and it is the hosted form on the
+// app's own host — never the embed, which is the thing that cannot be shown.
+$GLOBALS['stub']['inline'] = array();
+sendbeam_editor_defaults();
+$sb_inline = '';
+foreach ( $GLOBALS['stub']['inline'] as $sb_one ) {
+ $sb_inline .= is_array( $sb_one ) ? implode( ' ', array_map( 'strval', $sb_one ) ) : (string) $sb_one;
+}
+has( $sb_inline, 'window.sendbeamBlock', 'block: the editor is given its configuration' );
+has( $sb_inline, '"previewBase":"https:\\/\\/sendbeam.io\\/f\\/"', 'block: including where a preview of one form lives' );
+lacks( $sb_inline, 'embed=1', 'block: which is the hosted form, not the embed' );
+
+// The front end is untouched: that is the half that works.
+sb_seed_settings( array_merge( sendbeam_settings(), array( 'default_form' => '9da94d34-86f8-4fbc-9333-45c0b4c16d6a' ) ) );
+has( do_shortcode_tag( 'sendbeam_form' ), 'iframe class="sendbeam-form"', 'block: a published page still embeds the real form' );
+has( do_shortcode_tag( 'sendbeam_form' ), 'embed=1', 'block: with the embed flag the hosted page expects' );
+sb_seed_settings( array() );
+
+// 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.
+$sendbeam_root = dirname( __DIR__ );
+preg_match( "/^ \\* Version:\\s+(\\S+)/m", file_get_contents( $sendbeam_root . '/sendbeam.php' ), $m );
+$declared = $m[1];
+$sendbeam_versions = array(
+ 'sendbeam.php SENDBEAM_VERSION' => SENDBEAM_VERSION,
+ 'readme.txt Stable tag' => ( preg_match( '/^Stable tag: (\\S+)/m', file_get_contents( $sendbeam_root . '/readme.txt' ), $m2 ) ? $m2[1] : '' ),
+ 'block.json version' => ( json_decode( file_get_contents( $sendbeam_root . '/blocks/form/block.json' ), true )['version'] ?? '' ),
+ 'index.asset.php version' => ( ( require $sendbeam_root . '/blocks/form/index.asset.php' )['version'] ?? '' ),
+);
+foreach ( $sendbeam_versions as $where => $found ) {
+ ok( $found === $declared, "version $declared matches $where" . ( $found === $declared ? '' : " (found $found)" ) );
+}
+
+// The newest changelog entry is the version being shipped. Search from the
+// Changelog heading down: readme.txt uses "= … =" for its FAQ headings too.
+$sendbeam_readme = file_get_contents( $sendbeam_root . '/readme.txt' );
+$sendbeam_log = substr( $sendbeam_readme, (int) strpos( $sendbeam_readme, '== Changelog ==' ) );
+preg_match( '/^= (\\S+) =$/m', $sendbeam_log, $m3 );
+ok( ( $m3[1] ?? '' ) === $declared, "readme.txt changelog opens with $declared" );
+
+echo "smoke: $pass checks passed\n";
+
+
+// ---------------------------------------------------------------- WooCommerce claims (2026-09-24)
+// The block checkout, order placed only when paid, and no pop-up over the checkout.
+sb_seed_settings( array( 'api_key' => 'sb_live_wooclaims0123456789abcdef' ) );
+update_option( SENDBEAM_ECOMMERCE_OPTION, array( 'order_placed' => 1, 'product_viewed' => 0, 'cart_abandoned' => 0, 'cart_abandoned_window' => 60 ) );
+$sb_reg = array();
+foreach ( $stub['callbacks'] as $pair ) { if ( is_string( $pair[1] ) ) { $sb_reg[] = $pair[0] . '=>' . $pair[1]; } }
+ok( in_array( 'woocommerce_payment_complete=>sendbeam_ecommerce_on_order_paid', $sb_reg, true ), 'order placed: listens to payment complete' );
+ok( in_array( 'woocommerce_order_status_processing=>sendbeam_ecommerce_on_order_paid', $sb_reg, true ), 'order placed: and to an order reaching processing (cash on delivery)' );
+ok( in_array( 'woocommerce_order_status_completed=>sendbeam_ecommerce_on_order_paid', $sb_reg, true ), 'order placed: and to completed' );
+ok( ! in_array( 'woocommerce_checkout_order_processed=>sendbeam_ecommerce_on_order_placed', $sb_reg, true ), 'order placed: no longer fires at checkout, before payment' );
+ok( in_array( 'woocommerce_store_api_checkout_order_processed=>sendbeam_sync_on_block_checkout', $sb_reg, true ), 'block checkout: the opt-in is read from the Store API order' );
+ok( in_array( 'woocommerce_init=>sendbeam_sync_register_block_checkout_field', $sb_reg, true ), 'block checkout: the box is registered once WooCommerce is up' );
+
+$stub['cron'] = array(); $stub['wc_order_meta'] = array(); $stub['wc_saves'] = array();
+$stub['wc_orders'][601] = array( 'email' => 'paid@example.test', 'first_name' => 'Ada', 'last_name' => 'Lovelace', 'total' => 40, 'currency' => 'GBP' );
+sendbeam_ecommerce_on_order_paid( 601 );
+ok( 1 === count( $stub['cron'] ) && 'order_placed' === $stub['cron'][0]['args'][0]['type'], 'order placed: the first paid hook queues one event' );
+ok( ! empty( $stub['wc_order_meta'][601][ SENDBEAM_ORDER_PLACED_META ] ), 'order placed: and records on the order that it went' );
+sendbeam_ecommerce_on_order_paid( 601 );
+sendbeam_ecommerce_on_order_paid( wc_get_order( 601 ) );
+ok( 1 === count( $stub['cron'] ), 'order placed: processing then completed is still ONE event for the order' );
+$stub['cron'] = array();
+sendbeam_ecommerce_on_order_paid( 999 );
+ok( empty( $stub['cron'] ), 'order placed: an order that does not exist sends nothing' );
+
+// The block checkout field: registered only while the source can subscribe anybody.
+$stub['wc_checkout_fields'] = array();
+update_option( 'sendbeam_sync', array( 'woocommerce' => 0, 'registration' => 0, 'comments' => 0, 'lists' => array( 'list-1' ), 'label' => 'Keep me posted' ) );
+sendbeam_sync_register_block_checkout_field();
+ok( empty( $stub['wc_checkout_fields'] ), 'block checkout: no field is registered while the checkout source is off' );
+update_option( 'sendbeam_sync', array( 'woocommerce' => 1, 'registration' => 0, 'comments' => 0, 'lists' => array( 'list-1' ), 'label' => 'Keep me posted' ) );
+sendbeam_sync_register_block_checkout_field();
+ok( 1 === count( $stub['wc_checkout_fields'] ), 'block checkout: one field once it is on' );
+$sb_field = $stub['wc_checkout_fields'][0];
+ok( 'sendbeam/subscribe' === $sb_field['id'] && 'order' === $sb_field['location'] && 'checkbox' === $sb_field['type'] && empty( $sb_field['required'] ), 'block checkout: a checkbox in the order area, not required' );
+ok( 'Keep me posted' === $sb_field['label'], 'block checkout: labelled with the same words as the classic box' );
+ok( ! isset( $sb_field['default'] ) || empty( $sb_field['default'] ), 'block checkout: never pre-ticked' );
+
+// Reading the box back from the order the Store API hands over.
+$stub['remote'] = array(); $stub['remote_reply'] = array( 'response' => array( 'code' => 200 ), 'body' => '{"id":"c1"}' );
+$stub['wc_order_meta'][701] = array( SENDBEAM_BLOCK_OPTIN_META => '1' );
+sendbeam_sync_on_block_checkout( new WC_Order( array( 'id' => 701, 'email' => 'block@example.test', 'first_name' => 'Grace', 'last_name' => 'Hopper' ) ) );
+ok( count( $stub['remote'] ) >= 1 && false !== strpos( $stub['remote'][0]['url'], '/api/v1/contacts' ), 'block checkout: a ticked box subscribes the customer' );
+$sb_body = json_decode( $stub['remote'][0]['args']['body'], true );
+ok( is_array( $sb_body ) && 'block@example.test' === $sb_body['email'] && 'woocommerce-checkout' === $sb_body['source'], 'block checkout: with the address and the woocommerce-checkout source' );
+$stub['remote'] = array();
+sendbeam_sync_on_block_checkout( new WC_Order( array( 'id' => 702, 'email' => 'quiet@example.test' ) ) );
+ok( empty( $stub['remote'] ), 'block checkout: an unticked box subscribes nobody' );
+sendbeam_sync_on_block_checkout( 702 );
+ok( empty( $stub['remote'] ), 'block checkout: and a bare id (not an order) is ignored rather than fatal' );
+
+// No pop-up over the checkout.
+update_option( 'sendbeam_popups', array( array( 'enabled' => 1, 'form' => '9da94d34-86f8-4fbc-9333-45c0b4c16d6a', 'where' => 'everywhere', 'trigger' => 'timer', 'delay' => 0, 'once' => 'never' ) ) );
+$stub['query'] = array();
+ok( null !== sendbeam_active_popup(), 'pop-ups: an everywhere rule opens on an ordinary page' );
+foreach ( array( 'cart', 'checkout', 'account', 'wc_endpoint' ) as $sb_where ) {
+ $stub['query'] = array( $sb_where => 1 );
+ ok( null === sendbeam_active_popup(), "pop-ups: but never on the $sb_where page, whatever the rule says" );
+}
+$stub['query'] = array();
+has( file_get_contents( __DIR__ . '/../includes/screens.php' ), 'Never on the cart, checkout or account pages.', 'pop-ups: the Show on control says so' );
+
+// The records wrapper must be sized by its container, not its content (it collapsed to 2px on the Overview).
+$sb_css = sendbeam_admin_css();
+has( $sb_css, '.sb-scroll{overflow-x:auto;display:block;width:100%;min-width:0;', 'records: the scroll wrapper always takes the full width of its container' );
+lacks( $sb_css, '.sb-steps li{', 'records: the checklist row rule is scoped to its own items, not every list inside a step' );
+has( $sb_css, '.sb-numbered>li{display:list-item;', 'records: a numbered list inside a step stays a list' );
+has( $sb_css, '.sb-scroll>.sb-dns{width:100%}', 'records: and the table fills the wrapper' );
+
+// Step 2 points at the plugin's own Sending domain screen while a domain exists, and at SendBeam only to add one.
+$ov = sb_overview( $sb_connected, $sb_unverified );
+has( $ov, 'page=sendbeam-settings', 'overview: step 2 sends the owner to the plugin, not the app' );
+has( $ov, 'tab=domain', 'overview: to its own Sending domain screen' );
+$ov = sb_overview( $sb_connected, $sb_nodomain );
+has( $ov, '/settings/domains', 'overview: a site with no domain is still sent to where one is added' );
diff --git a/tests/woocommerce-stubs.php b/tests/woocommerce-stubs.php
index e0d807f..ec0b9af 100644
--- a/tests/woocommerce-stubs.php
+++ b/tests/woocommerce-stubs.php
@@ -26,9 +26,21 @@ public function get_billing_first_name() { return isset( $this->data['first_name
public function get_billing_last_name() { return isset( $this->data['last_name'] ) ? $this->data['last_name'] : ''; }
public function get_total() { return isset( $this->data['total'] ) ? $this->data['total'] : 0; }
public function get_currency() { return isset( $this->data['currency'] ) ? $this->data['currency'] : 'USD'; }
+ public function get_id() { return isset( $this->data['id'] ) ? $this->data['id'] : 0; }
+ // Order meta lives in the shared stub store, keyed by order id, so a
+ // second WC_Order for the same id sees what the first one saved.
+ public function get_meta( $key ) { $id = $this->get_id(); return isset( $GLOBALS['stub']['wc_order_meta'][ $id ][ $key ] ) ? $GLOBALS['stub']['wc_order_meta'][ $id ][ $key ] : ''; }
+ public function update_meta_data( $key, $value ) { $this->pending[ $key ] = $value; }
+ public function save() { foreach ( $this->pending as $k => $v ) { $GLOBALS['stub']['wc_order_meta'][ $this->get_id() ][ $k ] = $v; } $this->pending = array(); $GLOBALS['stub']['wc_saves'][] = $this->get_id(); }
+ private $pending = array();
}
+function is_cart() { return ! empty( $GLOBALS['stub']['query']['cart'] ); }
+function is_checkout() { return ! empty( $GLOBALS['stub']['query']['checkout'] ); }
+function is_account_page() { return ! empty( $GLOBALS['stub']['query']['account'] ); }
+function is_wc_endpoint_url() { return ! empty( $GLOBALS['stub']['query']['wc_endpoint'] ); }
+function woocommerce_register_additional_checkout_field( $options ) { $GLOBALS['stub']['wc_checkout_fields'][] = $options; }
function wc_get_order( $id ) {
- return isset( $GLOBALS['stub']['wc_orders'][ $id ] ) ? new WC_Order( $GLOBALS['stub']['wc_orders'][ $id ] ) : false;
+ return isset( $GLOBALS['stub']['wc_orders'][ $id ] ) ? new WC_Order( $GLOBALS['stub']['wc_orders'][ $id ] + array( 'id' => $id ) ) : false;
}
/**
diff --git a/tests/wp-stubs.php b/tests/wp-stubs.php
index 5d7feed..75c62b3 100644
--- a/tests/wp-stubs.php
+++ b/tests/wp-stubs.php
@@ -5,13 +5,19 @@
* 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'; }
function apply_filters( $tag, $value, ...$args ) { return isset( $GLOBALS['stub']['hooks'][ $tag ] ) ? call_user_func( $GLOBALS['stub']['hooks'][ $tag ], $value, ...$args ) : $value; }
-function add_filter( $tag, $fn, $p = 10, $a = 1 ) { $GLOBALS['stub']['hooks'][ $tag ] = $fn; }
-function add_action( $tag, $fn ) { $GLOBALS['stub']['hooks'][ $tag ] = $fn; }
+/**
+ * Hooks. The last callback for a tag wins (which is all the output tests
+ * need), but every callback ever registered is also kept, so a test can ask
+ * the one question WordPress answers with a fatal error: does the function
+ * this hook names actually exist?
+ */
+function add_filter( $tag, $fn, $p = 10, $a = 1 ) { $GLOBALS['stub']['hooks'][ $tag ] = $fn; $GLOBALS['stub']['callbacks'][] = array( $tag, $fn ); }
+function add_action( $tag, $fn, $p = 10, $a = 1 ) { $GLOBALS['stub']['hooks'][ $tag ] = $fn; $GLOBALS['stub']['callbacks'][] = array( $tag, $fn ); }
function add_shortcode( $tag, $fn ) { $GLOBALS['stub']['shortcodes'][ $tag ] = $fn; }
function do_shortcode_tag( $tag, $atts = array() ) { return call_user_func( $GLOBALS['stub']['shortcodes'][ $tag ], $atts ); }
function untrailingslashit( $s ) { return rtrim( $s, '/' ); }
@@ -27,7 +33,33 @@ function sanitize_text_field( $s ) { return trim( strip_tags( (string) $s ) ); }
function sanitize_key( $s ) { return preg_replace( '/[^a-z0-9_\-]/', '', strtolower( (string) $s ) ); }
function wp_unslash( $s ) { return is_array( $s ) ? array_map( 'wp_unslash', $s ) : stripslashes( (string) $s ); }
function get_option( $k, $default = false ) { return isset( $GLOBALS['stub']['options'][ $k ] ) ? $GLOBALS['stub']['options'][ $k ] : $default; }
-function update_option( $k, $v ) { $GLOBALS['stub']['options'][ $k ] = $v; }
+/**
+ * Options, and the sanitise callback WordPress runs on the way in.
+ *
+ * `register_setting()` hangs a callback on `sanitize_option_{$option}` and
+ * `update_option()` applies it — so every write to a registered option goes
+ * through it, including the ones a plugin makes on its own behalf. The stub
+ * did not, which is precisely why Disconnect could write an empty API key,
+ * have the form's "a blank field keeps the saved key" rule put the old one
+ * back, and pass every test while leaving the site connected.
+ *
+ * Fixtures that only want to put a value in place use sb_seed_settings().
+ */
+function update_option( $k, $v ) {
+ if ( isset( $GLOBALS['stub']['sanitize'][ $k ] ) && is_callable( $GLOBALS['stub']['sanitize'][ $k ] ) ) {
+ $v = call_user_func( $GLOBALS['stub']['sanitize'][ $k ], $v );
+ }
+ $GLOBALS['stub']['options'][ $k ] = $v;
+}
+function register_setting( $group, $option, $args = array() ) {
+ if ( is_array( $args ) && ! empty( $args['sanitize_callback'] ) ) {
+ $GLOBALS['stub']['sanitize'][ $option ] = $args['sanitize_callback'];
+ }
+}
+function add_settings_section( $id, $title, $cb, $page, $args = array() ) {}
+function add_settings_field( $id, $title, $cb, $page, $section = 'default', $args = array() ) {}
+/** Put a value straight into the store, the way a fixture means to. */
+function sb_seed_settings( $value ) { $GLOBALS['stub']['options']['sendbeam_settings'] = $value; }
function delete_option( $k ) { unset( $GLOBALS['stub']['options'][ $k ] ); }
function add_settings_error( $s, $c, $m ) { $GLOBALS['stub']['errors'][] = $m; }
function shortcode_atts( $pairs, $atts, $tag = '' ) { $atts = (array) $atts; $out = array(); foreach ( $pairs as $k => $v ) { $out[ $k ] = array_key_exists( $k, $atts ) ? $atts[ $k ] : $v; } return $out; }
@@ -94,7 +126,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 +149,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 {
@@ -124,18 +161,69 @@ function is_wp_error( $t ) { return $t instanceof WP_Error; }
function wp_remote_post( $url, $args ) { $GLOBALS['stub']['remote'][] = array( 'url' => $url, 'args' => $args, 'method' => 'POST' ); $r = $GLOBALS['stub']['remote_reply']; return ( $r instanceof Closure ) ? $r( $url, $args ) : $r; }
function wp_remote_retrieve_response_code( $r ) { return $r['response']['code']; }
function wp_remote_retrieve_body( $r ) { return $r['body']; }
-function do_action( $tag, ...$args ) { $GLOBALS['stub']['actions'][] = array( $tag, $args ); }
+function do_action( $tag, ...$args ) {
+ $GLOBALS['stub']['actions'][] = array( $tag, $args );
+ // The Connect pop-up fires this immediately before the request ends; the
+ // test uses it as the seam where WordPress would have called exit.
+ if ( ! empty( $GLOBALS['stub']['throw_on'][ $tag ] ) ) { throw new SendBeamStubExit( $tag ); }
+}
function network_home_url() { return 'https://www.example-site.test/'; }
function home_url() { return 'https://www.example-site.test'; }
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 '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 ─────────────────────────────────────────────────────────────
+/**
+ * The Connect flow ends a request in two ways WordPress can and the test
+ * cannot: wp_redirect()+exit on the way out, and a rendered page + exit on the
+ * way back. Both are turned into exceptions the test catches, so a handler can
+ * be driven to its end without killing the run.
+ */
+class SendBeamStubExit extends RuntimeException {}
+function site_url( $path = '' ) { $base = isset( $GLOBALS['stub']['site_url'] ) ? $GLOBALS['stub']['site_url'] : 'https://www.example-site.test'; return $base . $path; }
+function admin_url( $path = '' ) { return 'https://www.example-site.test/wp-admin/' . ltrim( (string) $path, '/' ); }
+function wp_redirect( $url, $status = 302 ) { $GLOBALS['stub']['redirect'] = array( 'url' => $url, 'status' => $status ); throw new SendBeamStubExit( 'wp_redirect' ); }
+function wp_safe_redirect( $url, $status = 302 ) { return wp_redirect( $url, $status ); }
+/**
+ * Faithful enough to see the status code.
+ *
+ * Core defaults to 500 when no response is given, which is what every one of
+ * this plugin's permission refusals used to send: a server-error line in
+ * every access log and every uptime monitor, for a refusal that worked
+ * perfectly.
+ */
+function wp_die( $message = '', $title = '', $args = array() ) {
+ $status = is_array( $args ) && isset( $args['response'] ) ? (int) $args['response'] : 500;
+ $GLOBALS['stub']['died'] = array( 'message' => (string) $message, 'status' => $status );
+ throw new SendBeamStubExit( 'wp_die: ' . $message );
+}
+function check_admin_referer( $action = -1, $name = '_wpnonce' ) {
+ $nonce = isset( $_REQUEST[ $name ] ) ? $_REQUEST[ $name ] : '';
+ if ( ! wp_verify_nonce( $nonce, $action ) ) { wp_die( 'bad nonce' ); }
+ return 1;
+}
+function get_current_user_id() { return isset( $GLOBALS['stub']['user_id'] ) ? (int) $GLOBALS['stub']['user_id'] : 0; }
+function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
+ $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
+ if ( $special_chars ) { $chars .= '!@#$%^&*()'; }
+ $out = '';
+ for ( $i = 0; $i < $length; $i++ ) { $out .= $chars[ random_int( 0, strlen( $chars ) - 1 ) ]; }
+ return $out;
+}
+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 ) {
@@ -151,6 +239,29 @@ 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 ); }
+
+/**
+ * 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* —
+ * 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 '' . esc_html( $text ) . ' '; }
+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() {
@@ -161,7 +272,361 @@ 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; }
function absint( $v ) { return abs( (int) $v ); }
+function get_post_types( $args = array(), $output = 'names' ) { return isset( $GLOBALS['stub']['post_types'] ) ? $GLOBALS['stub']['post_types'] : array( 'post', 'page', 'attachment' ); }
+
+/**
+ * Just enough of $wpdb for the "is a form on the site" query family.
+ *
+ * It records every statement so a test can assert what was looked for, and
+ * answers from $GLOBALS['stub']['db'] — one flag per place a form can hide,
+ * decided by which table and post types the statement names. The plugin's own
+ * fallback (no $wpdb at all) is still the default: $GLOBALS['wpdb'] is set
+ * only by the tests that want a database.
+ */
+class SendBeam_Stub_Db {
+ public $posts = 'wp_posts';
+ public $postmeta = 'wp_postmeta';
+ public $queries = array();
+
+ public function esc_like( $text ) { return addcslashes( (string) $text, '_%\\' ); }
+
+ /**
+ * Fill the placeholders in order, whichever kind they are.
+ *
+ * %d has to be handled as well as %s: the log's DELETE names its rows
+ * with `id IN ( %d, %d )`, and a prepare() that only knew about strings
+ * left those untouched — which looks exactly like a delete that matched
+ * nothing.
+ */
+ public function prepare( $sql, ...$args ) {
+ if ( 1 === count( $args ) && is_array( $args[0] ) ) { $args = $args[0]; }
+ foreach ( $args as $arg ) {
+ $sql = preg_replace_callback(
+ '/%[sdf]/',
+ function ( $m ) use ( $arg ) {
+ // Quotes only. addslashes() would double the backslash
+ // esc_like() puts in front of an underscore, and the
+ // point of this stub is SQL a test can read.
+ return '%s' === $m[0] ? "'" . str_replace( "'", "\\'", (string) $arg ) . "'" : (string) ( 0 + $arg );
+ },
+ $sql,
+ 1
+ );
+ }
+ return $sql;
+ }
+
+ public function get_var( $sql ) {
+ $this->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;
+ }
+}
+
+// ── 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 ); }
+function wp_normalize_path( $path ) { return str_replace( '\\', '/', (string) $path ); }
+function dbDelta( $queries = '', $execute = true ) { $GLOBALS['stub']['dbdelta'][] = $queries; return array(); }
+if ( ! defined( 'DAY_IN_SECONDS' ) ) { define( 'DAY_IN_SECONDS', 86400 ); }
+
+// ── 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(); }
+ protected function get_views() {
+ return array(); }
+ protected function get_sortable_columns() {
+ return array(); }
+ /** Core prints the views as a .subsubsub list above the table. */
+ public function views() {
+ $views = $this->get_views();
+ if ( ! $views ) { return; }
+ echo '';
+ foreach ( $views as $key => $link ) {
+ echo '' . $link . ' ';
+ }
+ echo ' ';
+ }
+ 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(
+ '%2$s ' .
+ ' ' .
+ '
',
+ 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 'Bulk actions ';
+ foreach ( $bulk as $value => $label ) {
+ echo '' . esc_html( $label ) . ' ';
+ }
+ 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 '' . $label . ' ';
+ }
+ echo ' ';
+ if ( ! $this->items ) {
+ echo '';
+ $this->no_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 . '' . $tag . '>';
+ }
+ echo ' ';
+ }
+ 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; }
+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;
+}
+function wp_register_style( $h, $src, $deps = array(), $ver = false, $media = 'all' ) { $GLOBALS['stub']['styles'][ $h ] = $src; }
+function wp_enqueue_style( $h ) { $GLOBALS['stub']['styles'][ $h . ':enqueued' ] = true; }
+function wp_add_inline_style( $h, $css ) { $GLOBALS['stub']['inline_css'][ $h ][] = $css; }
+
+// ── The email log's table ───────────────────────────────────────────────
+/**
+ * Enough of $wpdb to hold a log.
+ *
+ * Rows live in a PHP array and the handful of statements the plugin issues
+ * are answered by reading it — which is not a SQL engine, but it is enough to
+ * prove the shape of every query, that prepare() is reached with the right
+ * values, and that a prune deletes what it says it deletes. The statements
+ * themselves are recorded so a test can assert on them.
+ */
+class SendBeam_Stub_MailDb extends SendBeam_Stub_Db {
+ public $prefix = 'wp_';
+ public $rows = array();
+ public $next_id = 1;
+ public $created = '';
+
+ public function get_charset_collate() { return 'DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci'; }
+
+ public function insert( $table, $data, $format = null ) {
+ $this->queries[] = 'INSERT INTO ' . $table;
+ $data['id'] = $this->next_id++;
+ $this->rows[] = $data;
+ return 1;
+ }
+
+ /** Everything the plugin asks of the log, answered off the array. */
+ public function get_results( $sql, $output = OBJECT ) {
+ $this->queries[] = $sql;
+ if ( false !== strpos( $sql, 'GROUP BY result' ) ) {
+ $by = array();
+ foreach ( $this->rows as $r ) { $by[ $r['result'] ] = ( $by[ $r['result'] ] ?? 0 ) + 1; }
+ $out = array();
+ foreach ( $by as $result => $n ) { $out[] = array( 'result' => $result, 'n' => $n ); }
+ return $out;
+ }
+ $rows = $this->filter( $sql );
+ // ORDER BY: only the two columns the plugin allows.
+ $col = ( false !== strpos( $sql, 'ORDER BY result' ) ) ? 'result' : 'sent_at';
+ $dir = ( false !== strpos( $sql, "{$col} ASC" ) ) ? 1 : -1;
+ usort( $rows, function ( $a, $b ) use ( $col, $dir ) {
+ $c = strcmp( (string) $a[ $col ], (string) $b[ $col ] );
+ if ( 0 === $c ) { $c = (int) $a['id'] - (int) $b['id']; }
+ return $c * $dir;
+ } );
+ if ( preg_match( '/LIMIT (\d+) OFFSET (\d+)/', $sql, $m ) ) {
+ $rows = array_slice( $rows, (int) $m[2], (int) $m[1] );
+ }
+ return array_values( $rows );
+ }
+
+ public function get_var( $sql ) {
+ $this->queries[] = $sql;
+ if ( false !== strpos( $sql, 'COUNT(*)' ) && false !== strpos( $sql, 'sendbeam_mail_log' ) ) {
+ return count( $this->filter( $sql ) );
+ }
+ return parent::get_var( $sql );
+ }
+
+ public function query( $sql ) {
+ $this->queries[] = $sql;
+ if ( false !== strpos( $sql, 'DROP TABLE' ) ) { $this->rows = array(); return true; }
+ if ( 0 !== strpos( ltrim( $sql ), 'DELETE' ) ) { return 0; }
+
+ $keep = array();
+ $gone = 0;
+ $ids = array();
+ if ( preg_match( '/id IN \( ([^)]*) \)/', $sql, $m ) ) {
+ $ids = array_map( 'intval', array_map( 'trim', explode( ',', str_replace( "'", '', $m[1] ) ) ) );
+ }
+ $before = null;
+ if ( preg_match( "/sent_at < '([^']+)'/", $sql, $m ) ) { $before = $m[1]; }
+ $limit = null;
+ if ( preg_match( '/LIMIT (\d+)/', $sql, $m ) ) { $limit = (int) $m[1]; }
+
+ $rows = $this->rows;
+ if ( null !== $limit ) {
+ usort( $rows, function ( $a, $b ) { return strcmp( $a['sent_at'], $b['sent_at'] ) ?: ( (int) $a['id'] - (int) $b['id'] ); } );
+ }
+ foreach ( $rows as $r ) {
+ $hit = ( $ids && in_array( (int) $r['id'], $ids, true ) )
+ || ( null !== $before && $r['sent_at'] < $before )
+ || ( ! $ids && null === $before && null === $limit );
+ if ( null !== $limit && ! $ids && null === $before ) { $hit = $gone < $limit; }
+ if ( $hit && ( null === $limit || $gone < $limit || $ids || null !== $before ) ) { $gone++; continue; }
+ $keep[] = $r;
+ }
+ $this->rows = array_values( $keep );
+ return $gone;
+ }
+
+ /** The WHERE the plugin builds, applied to the array. */
+ private function filter( $sql ) {
+ $rows = $this->rows;
+ if ( preg_match( "/result = '([^']+)'/", $sql, $m ) ) {
+ $rows = array_values( array_filter( $rows, function ( $r ) use ( $m ) { return $r['result'] === $m[1]; } ) );
+ }
+ if ( preg_match( "/to_addr LIKE '%([^%]*)%'/", $sql, $m ) && '' !== $m[1] ) {
+ $needle = $m[1];
+ $rows = array_values( array_filter( $rows, function ( $r ) use ( $needle ) {
+ return false !== stripos( $r['to_addr'] . ' ' . $r['subject'] . ' ' . $r['note'], $needle );
+ } ) );
+ }
+ return $rows;
+ }
+}
+if ( ! defined( 'OBJECT' ) ) { define( 'OBJECT', 'OBJECT' ); }
+if ( ! defined( 'ARRAY_A' ) ) { define( 'ARRAY_A', 'ARRAY_A' ); }
diff --git a/uninstall.php b/uninstall.php
index 0cc9677..54eef7d 100644
--- a/uninstall.php
+++ b/uninstall.php
@@ -20,20 +20,42 @@
'sendbeam_sync',
'sendbeam_sync_log',
'sendbeam_bridges',
- 'sendbeam_mail_log',
+ 'sendbeam_mail_log', // The pre-1.8.3 option; the table goes below.
+ 'sendbeam_db_version',
'sendbeam_activated_at',
'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 );
}
+/*
+ * The email log's own table. Deleting a plugin should leave nothing behind,
+ * and a table of who this site emailed is the last thing to leave lying
+ * around.
+ */
+global $wpdb;
+if ( isset( $wpdb ) && is_object( $wpdb ) && method_exists( $wpdb, 'query' ) ) {
+ /*
+ * The name is built from $wpdb->prefix and a literal, so nothing about it
+ * comes from anywhere a request could reach. Backticked and escaped all
+ * the same, because a DROP cannot take a placeholder for its table and a
+ * reviewer should not have to take that on trust.
+ */
+ $sendbeam_table = '`' . str_replace( '`', '``', $wpdb->prefix . 'sendbeam_mail_log' ) . '`';
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- dropping the plugin's own table is the point of uninstalling; the name is backtick-escaped above and no part of it is user input.
+ $wpdb->query( "DROP TABLE IF EXISTS {$sendbeam_table}" );
+}
+
$sendbeam_transients = array(
'sendbeam_connection',
'sendbeam_remote_forms',
'sendbeam_remote_lists',
'sendbeam_subscriber_count',
+ 'sendbeam_form_placed',
);
foreach ( $sendbeam_transients as $sendbeam_transient ) {
delete_transient( $sendbeam_transient );
@@ -49,18 +71,35 @@
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' );
-// Cart-abandonment tracking is one transient per shopper session, keyed by
-// a hash (sendbeam_cart_) rather than a name this file can list up
-// front — the only way to find them all is a direct query.
-global $wpdb;
-if ( isset( $wpdb ) ) {
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one-off cleanup, no equivalent WP API for a prefix sweep.
- $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( '_transient_sendbeam_cart_' ) . '%' ) );
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( '_transient_timeout_sendbeam_cart_' ) . '%' ) );
+// Two families of transient are named after something this file cannot list
+// up front — a shopper's session (sendbeam_cart_) and an administrator's
+// user ID (sendbeam_connect_) — so a prefix sweep is the only way to find
+// them all. delete_transient() for the current user would leave every other
+// administrator's behind.
+$sendbeam_transient_prefixes = array( 'sendbeam_cart_', 'sendbeam_connect_' );
+
+/**
+ * Delete every transient whose name starts with one of the prefixes.
+ *
+ * @param string[] $prefixes Transient name prefixes.
+ */
+function sendbeam_uninstall_sweep_transients( $prefixes ) {
+ global $wpdb;
+ if ( ! isset( $wpdb ) ) {
+ return;
+ }
+ foreach ( $prefixes as $sendbeam_prefix ) {
+ foreach ( array( '_transient_', '_transient_timeout_' ) as $sendbeam_key_prefix ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one-off cleanup, no equivalent WP API for a prefix sweep.
+ $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( $sendbeam_key_prefix . $sendbeam_prefix ) . '%' ) );
+ }
+ }
}
+sendbeam_uninstall_sweep_transients( $sendbeam_transient_prefixes );
+
// Multisite: the same clean-up on every site in the network.
if ( is_multisite() ) {
$sendbeam_sites = get_sites(
@@ -81,12 +120,8 @@
wp_unschedule_hook( 'sendbeam_bridge_subscribe' );
wp_unschedule_hook( 'sendbeam_ecommerce_send_event' );
wp_unschedule_hook( 'sendbeam_check_cart_abandonment' );
- if ( isset( $wpdb ) ) {
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( '_transient_sendbeam_cart_' ) . '%' ) );
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( '_transient_timeout_sendbeam_cart_' ) . '%' ) );
- }
+ wp_unschedule_hook( 'sendbeam_connect_recheck' );
+ sendbeam_uninstall_sweep_transients( $sendbeam_transient_prefixes );
restore_current_blog();
}
}