diff --git a/.wordpress-org/README.md b/.wordpress-org/README.md index 59887b4..293dce4 100644 --- a/.wordpress-org/README.md +++ b/.wordpress-org/README.md @@ -11,10 +11,12 @@ inside them. `.distignore` keeps this folder out of the distributed zip. | `icon.svg` | The same mark as vector, preferred where it is supported | | `banner-772x250.png` | The header of the listing page | | `banner-1544x500.png` | The same, on high-density screens | -| `screenshot-1.png` … `screenshot-7.png` | The Screenshots section, captioned in order by `readme.txt` | +| `screenshot-1.png` … `screenshot-9.png` | The Screenshots section, captioned in order by `readme.txt` | Captions come from the `== Screenshots ==` list in `readme.txt`: the *n*th line captions `screenshot-n.png`. Adding a screenshot means adding both. -Screenshots are 1280px wide, taken on a real site running the plugin against a -live SendBeam workspace. +Screenshots are 1280x800 at 1x, taken on a real site running the plugin +against a live SendBeam workspace. Nothing in them is seeded, mocked or +blurred: the only editing is that other plugins' admin notices are hidden, so +each one shows this plugin rather than somebody else's nag. diff --git a/.wordpress-org/screenshot-1.png b/.wordpress-org/screenshot-1.png index 050ae25..6bf34e1 100644 Binary files a/.wordpress-org/screenshot-1.png and b/.wordpress-org/screenshot-1.png differ diff --git a/.wordpress-org/screenshot-2.png b/.wordpress-org/screenshot-2.png index 9292ce5..9cb810d 100644 Binary files a/.wordpress-org/screenshot-2.png and b/.wordpress-org/screenshot-2.png differ diff --git a/.wordpress-org/screenshot-3.png b/.wordpress-org/screenshot-3.png index 48915ab..365f07c 100644 Binary files a/.wordpress-org/screenshot-3.png and b/.wordpress-org/screenshot-3.png differ diff --git a/.wordpress-org/screenshot-4.png b/.wordpress-org/screenshot-4.png index 943d0f2..de0add7 100644 Binary files a/.wordpress-org/screenshot-4.png and b/.wordpress-org/screenshot-4.png differ diff --git a/.wordpress-org/screenshot-5.png b/.wordpress-org/screenshot-5.png index d8dca03..4cd0199 100644 Binary files a/.wordpress-org/screenshot-5.png and b/.wordpress-org/screenshot-5.png differ diff --git a/.wordpress-org/screenshot-6.png b/.wordpress-org/screenshot-6.png index 9a55188..c3ff9be 100644 Binary files a/.wordpress-org/screenshot-6.png and b/.wordpress-org/screenshot-6.png differ diff --git a/.wordpress-org/screenshot-7.png b/.wordpress-org/screenshot-7.png index 3bd2b5c..850b649 100644 Binary files a/.wordpress-org/screenshot-7.png and b/.wordpress-org/screenshot-7.png differ diff --git a/.wordpress-org/screenshot-8.png b/.wordpress-org/screenshot-8.png new file mode 100644 index 0000000..ec525a8 Binary files /dev/null and b/.wordpress-org/screenshot-8.png differ diff --git a/.wordpress-org/screenshot-9.png b/.wordpress-org/screenshot-9.png new file mode 100644 index 0000000..a94305b Binary files /dev/null and b/.wordpress-org/screenshot-9.png differ diff --git a/CHANGELOG.md b/CHANGELOG.md index 2141530..c0f5c9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,133 @@ # Changelog +## 1.8.3 + +- The DNS records are visible on the Overview at every width; a checklist styling rule had squeezed the table to two pixels inside step 2. +- The sending-domain step opens the plugin's own Sending domain screen rather than the SendBeam app. + +- WooCommerce's block checkout now gets the opt-in box (registered as an additional checkout field) and fires the order event; both were classic-checkout only. +- Order placed fires when an order is paid (payment complete, processing or completed), once per order, instead of at checkout before payment. +- Pop-ups are never shown on the cart, checkout or account pages. + +### The admin experience + +- **A top-level menu with a page per section.** SendBeam 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. Sixteen of the eighteen established plugins this was measured against take a top-level menu with their own icon; the one that does not compensates with a full-screen activation wizard, and this plugin had neither. There is now `add_menu_page()` at position 58.9 with the three-square mark as a base64 SVG, eight submenu items (Overview, Forms, Pop-ups, Audience, Site email, E-commerce, Settings, Help) and one router behind all of them. `options-general.php?page=sendbeam` and each of its tabs 301 to the page that replaced it, carrying any notice the old URL held, so every bookmark and every link in an old support reply still lands somewhere useful. The Plugins-screen "Settings" link points at the Settings page rather than at a dashboard. +- **A first run.** Activation sets a 30-second transient and the next admin page load goes once to `sendbeam-setup`: connect, verify your sending domain, switch on site email, place a form. It is guarded three ways — never during a bulk activation, never on a site that already has a key, and `apply_filters( 'sendbeam_setup_wizard', true )` switches it off for a host or an agency that sets these up itself. It renders inside `.wrap` with the admin menu and admin bar left alone, because a wizard that hides the way out is a wizard people close the tab on; **Skip this step** is on every step and **Go back to the Dashboard** is under all of them, and where somebody got to is kept in user meta so leaving and coming back resumes rather than restarts. Each step is the panel the matching settings screen already uses, so there is still one Connect button and one records table in this plugin. +- **`WP_List_Table` for the three lists.** Forms, the audience lists and the email log were hand-rolled ``: no search, no pagination, no bulk actions, no empty state, and — the part that mattered — none of core's column collapsing, which is why Forms and Site email were the two screens that scrolled sideways at 393px. All three are subclasses now with a primary column, a per-page Screen Option and an empty state that says what to do next; the log gains a bulk delete. The two read-only lists return an empty `get_bulk_actions()`, which is core's own way of saying a list has none rather than offering a dropdown with nothing in it. There is no Resend row action on the log because the log keeps what a message was sent *to* and *about*, never its body — a Resend that could only send a different email is worse than no button. +- **The sending domain, in MailPoet's shape.** A "why" sentence, numbered steps, `
` 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 `', + esc_attr( $shortcode ), + esc_attr__( 'Copied', 'sendbeam' ), + esc_html__( 'Copy', 'sendbeam' ) + ); + } + + /** + * Whether this site is showing a SendBeam form anywhere. + * + * The answer is about the site, not about this particular form: a search + * for the block name and the shortcodes cannot tell which form a + * `[sendbeam_form]` with no id will render. Saying so is better than a + * per-row tick that would be wrong half the time. + * + * @param array $item One form. + * @return string + */ + public function column_placed( $item ) { + $settings = sendbeam_settings(); + $id = strtolower( (string) $item['id'] ); + $default = strtolower( (string) $settings['default_form'] ) === $id; + $contact = strtolower( (string) $settings['contact_form'] ) === $id; + + $where = array( + 'manual' => __( 'Somewhere you told us about', 'sendbeam' ), + 'popup' => __( 'A pop-up', 'sendbeam' ), + 'content' => __( 'A page or post', 'sendbeam' ), + 'template' => __( 'A theme template', 'sendbeam' ), + 'widget' => __( 'A widget', 'sendbeam' ), + 'meta' => __( 'A page builder layout', 'sendbeam' ), + ); + + $out = array(); + if ( $default ) { + $out[] = '' . esc_html__( 'Default signup form', 'sendbeam' ) . ''; + } + if ( $contact ) { + $out[] = '' . esc_html__( 'Default contact form', 'sendbeam' ) . ''; + } + if ( ( $default || $contact ) && isset( $where[ $this->placement ] ) ) { + $out[] = '' . esc_html( $where[ $this->placement ] ) . ''; + } + if ( ! $out ) { + $out[] = '' . esc_html__( 'Not a default — place it by shortcode', 'sendbeam' ) . ''; + } + return implode( ' ', $out ); + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/class-sendbeam-lists-table.php b/includes/class-sendbeam-lists-table.php new file mode 100644 index 0000000..a9499b8 --- /dev/null +++ b/includes/class-sendbeam-lists-table.php @@ -0,0 +1,171 @@ + 'sendbeam_list', + 'plural' => 'sendbeam_lists', + 'ajax' => false, + ) + ); + } + + /** + * The columns, in order. + * + * @return array + */ + public function get_columns() { + return array( + 'name' => __( 'List', 'sendbeam' ), + 'count' => __( 'Subscribers', 'sendbeam' ), + 'confirmation' => __( 'Confirmation', 'sendbeam' ), + ); + } + + /** + * The list's name. + * + * @return string + */ + protected function get_default_primary_column_name() { + return 'name'; + } + + /** + * Nothing here can be changed in bulk. + * + * @return array + */ + protected function get_bulk_actions() { + return array(); + } + + /** + * There are no bulk actions, so there is nothing to process. + * + * Defined all the same: the loader calls it on every list, and a list + * that quietly has no such method is a fatal error waiting for whoever + * adds a bulk action to one of the others. + */ + public function process_bulk_action() {} + + /** Load, filter and page the rows. */ + public function prepare_items() { + $lists = sendbeam_lists(); + $lists = is_array( $lists ) ? $lists : array(); + $search = sendbeam_list_search(); + + if ( '' !== $search ) { + $needle = strtolower( $search ); + $lists = array_values( + array_filter( + $lists, + function ( $list ) use ( $needle ) { + return false !== strpos( strtolower( (string) $list['name'] ), $needle ); + } + ) + ); + } + + $per_page = sendbeam_per_page( 'sendbeam_lists_per_page' ); + $page = max( 1, (int) $this->get_pagenum() ); + $total = count( $lists ); + + $this->items = array_slice( $lists, ( $page - 1 ) * $per_page, $per_page ); + $this->_column_headers = array( $this->get_columns(), array(), array(), $this->get_default_primary_column_name() ); + $this->set_pagination_args( + array( + 'total_items' => $total, + 'per_page' => $per_page, + 'total_pages' => (int) ceil( $total / max( 1, $per_page ) ), + ) + ); + } + + /** What an empty list of lists says. */ + public function no_items() { + $lists = sendbeam_lists(); + if ( null === $lists ) { + // See the note on the same branch in the forms table: a site with + // no key is not a site with a key missing a permission. + if ( '' === sendbeam_api_key() ) { + esc_html_e( 'This site is not connected to SendBeam yet, so there are no lists to show. Connect it on the Overview.', 'sendbeam' ); + return; + } + esc_html_e( 'Your lists cannot be read with the current key. Give it the Lists (read) permission in SendBeam, or reconnect this site.', 'sendbeam' ); + return; + } + if ( '' !== sendbeam_list_search() ) { + esc_html_e( 'No list here matches that.', 'sendbeam' ); + return; + } + esc_html_e( 'This workspace has no lists yet. Connecting a site creates one called Subscribers; you can add more in SendBeam.', 'sendbeam' ); + } + + /** + * The list's name, with a link to it in SendBeam. + * + * @param array $item One list. + * @return string + */ + public function column_name( $item ) { + $actions = array( + 'open' => sprintf( + '%s', + esc_url( sendbeam_app_link( '/lists/' . rawurlencode( (string) $item['id'] ) ) ), + esc_html__( 'Open in SendBeam', 'sendbeam' ) + ), + ); + return '' . esc_html( (string) $item['name'] ) . '' . $this->row_actions( $actions ); + } + + /** + * How many people are on it. + * + * @param array $item One list. + * @return string + */ + public function column_count( $item ) { + return '' . ( null === $item['count'] ? '—' : esc_html( number_format_i18n( $item['count'] ) ) ) . ''; + } + + /** + * Single or double opt-in. + * + * @param array $item One list. + * @return string + */ + public function column_confirmation( $item ) { + if ( ! empty( $item['double_optin'] ) ) { + return '' . esc_html__( 'Double opt-in', 'sendbeam' ) . ''; + } + return '' . esc_html__( 'Single opt-in', 'sendbeam' ) . ''; + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/class-sendbeam-mail-log-table.php b/includes/class-sendbeam-mail-log-table.php new file mode 100644 index 0000000..2b97d17 --- /dev/null +++ b/includes/class-sendbeam-mail-log-table.php @@ -0,0 +1,277 @@ + 'sendbeam_message', + 'plural' => 'sendbeam_messages', + 'ajax' => false, + ) + ); + } + + /** + * The columns, in order. + * + * @return array + */ + public function get_columns() { + return array( + 'cb' => '', + 'date' => __( 'Date', 'sendbeam' ), + 'to' => __( 'To', 'sendbeam' ), + 'subject' => __( 'Subject', 'sendbeam' ), + 'result' => __( 'Result', 'sendbeam' ), + 'source' => __( 'Sent by', 'sendbeam' ), + 'note' => __( 'Note', 'sendbeam' ), + ); + } + + /** + * The two columns worth ordering by. + * + * @return array + */ + protected function get_sortable_columns() { + return array( + 'date' => array( 'sent_at', true ), + 'result' => array( 'result', false ), + ); + } + + /** + * All / Sent / Server mailer / Failed, with counts. + * + * The counts are the point: "did anything fail?" is the question this + * screen exists to answer, and a list of two hundred rows does not answer + * it at a glance. + * + * @return array + */ + protected function get_views() { + $counts = sendbeam_mail_log_counts(); + $now = $this->current_view(); + $base = sendbeam_page_url( 'sendbeam-mail' ); + + $labels = array( + '' => __( 'All', 'sendbeam' ), + 'sent' => __( 'Sent', 'sendbeam' ), + 'fallback' => __( 'Server mailer', 'sendbeam' ), + 'failed' => __( 'Failed', 'sendbeam' ), + ); + + $views = array(); + foreach ( $labels as $key => $label ) { + $count = '' === $key ? $counts['all'] : $counts[ $key ]; + // A view nobody has any rows for is a link to an empty screen. + if ( '' !== $key && 0 === $count ) { + continue; + } + $url = '' === $key ? $base : add_query_arg( 'result', $key, $base ); + $views[ $key ] = sprintf( + '%3$s (%4$s)', + esc_url( $url ), + $key === $now ? ' class="current" aria-current="page"' : '', + esc_html( $label ), + esc_html( number_format_i18n( $count ) ) + ); + } + return $views; + } + + /** + * Which view is showing. + * + * @return string + */ + private function current_view() { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation between views of a list. + $view = isset( $_REQUEST['result'] ) ? sanitize_key( wp_unslash( $_REQUEST['result'] ) ) : ''; + return in_array( $view, array( 'sent', 'fallback', 'failed' ), true ) ? $view : ''; + } + + /** + * Date is what identifies a row here; every other column repeats. + * + * @return string + */ + protected function get_default_primary_column_name() { + return 'date'; + } + + /** + * Deleting the rows somebody ticked, and nothing else. + * + * Emptying the whole log is a button of its own on the screen, behind its + * own confirmation. It is not in here, because "Delete" sitting one + * mis-click from "Delete all" in the same dropdown is how a log gets lost. + * + * @return array + */ + protected function get_bulk_actions() { + return array( 'delete' => __( 'Delete', 'sendbeam' ) ); + } + + /** + * Delete the ticked rows. + * + * Runs before the rows are read, on `load-`, so the table the + * screen renders is the one the delete left behind rather than the one + * it started with. The nonce is core's own `bulk-`, which + * `display_tablenav()` prints for us. + */ + public function process_bulk_action() { + if ( 'delete' !== $this->current_action() ) { + return; + } + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) ); + } + check_admin_referer( 'bulk-' . $this->_args['plural'] ); + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked immediately above. + $chosen = isset( $_REQUEST['message'] ) ? array_map( 'absint', (array) wp_unslash( $_REQUEST['message'] ) ) : array(); + if ( ! $chosen ) { + return; + } + + $GLOBALS['sendbeam_deleted'] = sendbeam_mail_log_delete( $chosen ); + } + + /** Load, filter and page the rows. */ + public function prepare_items() { + $per_page = sendbeam_per_page( 'sendbeam_mail_log_per_page' ); + + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- sorting a list is a GET; core's own list tables read these the same way. + $orderby = isset( $_REQUEST['orderby'] ) ? sanitize_key( wp_unslash( $_REQUEST['orderby'] ) ) : 'sent_at'; + $order = isset( $_REQUEST['order'] ) ? sanitize_key( wp_unslash( $_REQUEST['order'] ) ) : 'desc'; + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + $page = sendbeam_mail_log_query( + array( + 'search' => sendbeam_list_search(), + 'view' => $this->current_view(), + 'orderby' => $orderby, + 'order' => $order, + 'per_page' => $per_page, + 'page' => max( 1, (int) $this->get_pagenum() ), + ) + ); + + $this->items = $page['rows']; + $this->_column_headers = array( $this->get_columns(), array(), $this->get_sortable_columns(), $this->get_default_primary_column_name() ); + $this->set_pagination_args( + array( + 'total_items' => $page['total'], + 'per_page' => $per_page, + 'total_pages' => (int) ceil( $page['total'] / max( 1, $per_page ) ), + ) + ); + } + + /** What an empty log says. */ + public function no_items() { + if ( '' !== sendbeam_list_search() ) { + esc_html_e( 'No message here matches that.', 'sendbeam' ); + return; + } + if ( '' !== $this->current_view() ) { + esc_html_e( 'Nothing in the log ended that way.', 'sendbeam' ); + return; + } + esc_html_e( 'Nothing has been sent through SendBeam from this site yet. Send yourself a test above and it will show up here.', 'sendbeam' ); + } + + /** + * The row's checkbox. + * + * @param array $item Row. + * @return string + */ + public function column_cb( $item ) { + return sprintf( '', (int) $item['id'] ); + } + + /** + * When it went, in the site's own format. + * + * @param array $item Row. + * @return string + */ + public function column_date( $item ) { + $at = sendbeam_mail_log_stamp( $item ); + return '' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $at ) ) . ''; + } + + /** + * What asked for the message, when the plugin could tell. + * + * @param array $item Row. + * @return string + */ + public function column_source( $item ) { + $source = isset( $item['source'] ) ? (string) $item['source'] : ''; + if ( '' === $source ) { + return '—'; + } + if ( 'wp-core' === $source ) { + return esc_html__( 'WordPress', 'sendbeam' ); + } + return '' . esc_html( $source ) . ''; + } + + /** + * Who it went to. + * + * @param array $item Row. + * @return string + */ + public function column_to( $item ) { + return esc_html( (string) $item['to_addr'] ); + } + + /** + * Sent, fell back, or failed. + * + * @param array $item Row. + * @return string + */ + public function column_result( $item ) { + $map = array( + 'sent' => array( 'moss', __( 'Sent via SendBeam', 'sendbeam' ) ), + 'fallback' => array( 'amber', __( 'Server mailer', 'sendbeam' ) ), + 'failed' => array( 'vermilion', __( 'Failed', 'sendbeam' ) ), + ); + $key = isset( $map[ $item['result'] ] ) ? $item['result'] : 'failed'; + return '' . esc_html( $map[ $key ][1] ) . ''; + } + + /** + * Anything without a column_* method. + * + * @param array $item Row. + * @param string $column Column name. + * @return string + */ + public function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; + } +} diff --git a/includes/connect-status.php b/includes/connect-status.php new file mode 100644 index 0000000..c415c98 --- /dev/null +++ b/includes/connect-status.php @@ -0,0 +1,797 @@ + + */ +function sendbeam_connect_empty_status() { + return array( + 'ok' => false, + 'error' => '', + 'notes' => array(), + // Why there is no sending domain, when there is none. `domain` being + // null meant four different things before this — the box was never + // ticked, the key is too old to read domains, the key has no site + // host, the row was deleted by hand — and the screen could only say + // "not set up" to all four, which is the one answer that helps + // nobody. + 'domain_state' => '', + 'domain_note' => '', + // Served from the cache because the request failed, and how old it is. + 'stale' => false, + 'fetched_at' => 0, + 'workspace' => array( + 'id' => '', + 'name' => '', + ), + 'default_form' => array( + 'id' => '', + 'name' => '', + ), + 'domain' => array( + 'name' => '', + 'verified' => false, + 'records' => array(), + 'domain_connect_url' => '', + 'checked_at' => '', + ), + 'sender' => array( + 'from_name' => '', + 'from_email' => '', + ), + ); +} + +/** + * Turn an exchange or status reply into that fixed shape. + * + * The contract allows `default_form` and `domain` to be null — no form yet, + * or the key was never given `domains:read` — and null is not a thing a + * template can read a name out of. Absence becomes an empty string here, once, + * rather than a null check at every point of use. + * + * @param mixed $data Decoded JSON body. + * @return array + */ +function sendbeam_connect_normalise_status( $data ) { + $out = sendbeam_connect_empty_status(); + if ( ! is_array( $data ) ) { + return $out; + } + + $out['ok'] = true; + + if ( isset( $data['workspace'] ) && is_array( $data['workspace'] ) ) { + $out['workspace']['id'] = isset( $data['workspace']['id'] ) ? sanitize_text_field( (string) $data['workspace']['id'] ) : ''; + $out['workspace']['name'] = isset( $data['workspace']['name'] ) ? sanitize_text_field( (string) $data['workspace']['name'] ) : ''; + } + + // What SendBeam could not set up, in its words, so step 2 can say why. + $out['notes'] = array(); + if ( isset( $data['notes'] ) && is_array( $data['notes'] ) ) { + foreach ( array_slice( $data['notes'], 0, 3 ) as $note ) { + if ( is_string( $note ) && '' !== trim( $note ) ) { + $out['notes'][] = mb_substr( sanitize_text_field( $note ), 0, 200 ); + } + } + } + + // A form ID that is not a form ID is dropped rather than stored: it would + // become this site's default form and every embed would 404. + if ( isset( $data['default_form'] ) && is_array( $data['default_form'] ) && sendbeam_is_form_id( isset( $data['default_form']['id'] ) ? $data['default_form']['id'] : null ) ) { + $out['default_form']['id'] = strtolower( (string) $data['default_form']['id'] ); + $out['default_form']['name'] = isset( $data['default_form']['name'] ) ? sanitize_text_field( (string) $data['default_form']['name'] ) : ''; + } + + $out['domain_state'] = sendbeam_connect_clean_domain_state( isset( $data['domain_state'] ) ? $data['domain_state'] : '' ); + if ( isset( $data['domain_note'] ) && is_string( $data['domain_note'] ) ) { + $out['domain_note'] = mb_substr( sanitize_text_field( $data['domain_note'] ), 0, 200 ); + } + // v2 said the same thing in an array called `notes`. A site talking to a + // SendBeam that predates `domain_note` still gets its sentence. + if ( '' === $out['domain_note'] && $out['notes'] ) { + $out['domain_note'] = (string) $out['notes'][0]; + } + + if ( isset( $data['domain'] ) && is_array( $data['domain'] ) && ! empty( $data['domain']['name'] ) ) { + $out['domain']['name'] = sanitize_text_field( (string) $data['domain']['name'] ); + $out['domain']['verified'] = ! empty( $data['domain']['verified'] ); + $out['domain']['checked_at'] = isset( $data['domain']['checked_at'] ) ? sanitize_text_field( (string) $data['domain']['checked_at'] ) : ''; + $out['domain']['records'] = sendbeam_connect_clean_records( isset( $data['domain']['records'] ) ? $data['domain']['records'] : array() ); + + /* + * The registrar's one-click DNS link. It is put in front of the site + * owner as a button, so it is held to the same rule as every other + * off-site link this plugin renders: https, and SendBeam's own host. + * A "set up my DNS" button pointing anywhere else is a phishing link + * with the plugin's face on it. + */ + $url = isset( $data['domain']['domain_connect_url'] ) ? esc_url_raw( (string) $data['domain']['domain_connect_url'] ) : ''; + if ( '' !== $url && sendbeam_connect_is_app_url( $url ) ) { + $out['domain']['domain_connect_url'] = $url; + } + } + + if ( isset( $data['sender'] ) && is_array( $data['sender'] ) ) { + $out['sender']['from_name'] = isset( $data['sender']['from_name'] ) ? sanitize_text_field( (string) $data['sender']['from_name'] ) : ''; + $email = isset( $data['sender']['from_email'] ) ? sanitize_email( (string) $data['sender']['from_email'] ) : ''; + $out['sender']['from_email'] = ( $email && is_email( $email ) ) ? $email : ''; + } + + $out['domain_state'] = sendbeam_connect_domain_state( $out ); + + return $out; +} + +/** + * The states the contract defines, and nothing else. + * + * @param mixed $raw Value from the API. + * @return string Empty when it is not one of them. + */ +function sendbeam_connect_clean_domain_state( $raw ) { + $known = array( 'ok', 'not_granted', 'no_permission', 'no_site', 'not_found', 'managed_host', 'unavailable' ); + $raw = is_string( $raw ) ? strtolower( trim( $raw ) ) : ''; + return in_array( $raw, $known, true ) ? $raw : ''; +} + +/** + * A status's domain state, worked out when the answer did not carry one. + * + * A cached body written before this field existed, or an older SendBeam, + * would otherwise leave every sentence on step 2 blank. A domain that came + * back is `ok`; no domain and no reason is `not_found`, which is both the + * commonest case and the one whose sentence is safe to show for any of them. + * + * @param array $status Normalised status. + * @return string + */ +function sendbeam_connect_domain_state( $status ) { + $state = isset( $status['domain_state'] ) ? sendbeam_connect_clean_domain_state( $status['domain_state'] ) : ''; + if ( '' !== $state ) { + return $state; + } + return ( isset( $status['domain']['name'] ) && '' !== $status['domain']['name'] ) ? 'ok' : 'not_found'; +} + +/** + * Did this status come from SendBeam just now, or out of the cupboard? + * + * `domain_state` of `unavailable` means one of two opposite things: the + * plugin could not reach SendBeam, or SendBeam answered and said it could + * not set the domain up. This is the difference. A reply that was served + * because the request failed is marked stale and carries the error; a reply + * SendBeam actually gave carries neither, and its `domain_note` is SendBeam + * speaking rather than a sentence left over from the last successful call. + * + * @param array $status Normalised status. + * @return bool + */ +function sendbeam_connect_status_is_live( $status ) { + if ( ! empty( $status['stale'] ) ) { + return false; + } + if ( '' !== trim( (string) ( isset( $status['error'] ) ? $status['error'] : '' ) ) ) { + return false; + } + return ! empty( $status['ok'] ); +} + +/** + * Is this an https URL on the SendBeam app's own host? + * + * @param string $url Candidate URL. + * @return bool + */ +function sendbeam_connect_is_app_url( $url ) { + $parts = wp_parse_url( (string) $url ); + $app = wp_parse_url( sendbeam_app_url() ); + if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) || empty( $app['host'] ) ) { + return false; + } + if ( 'https' !== strtolower( $parts['scheme'] ) ) { + return false; + } + return strtolower( $parts['host'] ) === strtolower( $app['host'] ); +} + +/** + * The DNS records, cleaned for display. + * + * Nothing is dropped for being an unfamiliar record type — a record the site + * owner has to enter and cannot see is worse than an odd-looking row — but + * the type is reduced to the letters and digits a DNS type can contain, and + * every field is plain text. Twenty is far more than any sending domain needs + * and stops a malformed reply filling the screen. + * + * `found` is the check's verdict for that one record, and it has three + * values rather than two: true, false, and never-checked. They are three + * different sentences to a site owner — "this one is live", "this one is not + * there yet", "nobody has looked" — and collapsing the last two into false + * tells someone their DNS is wrong when in fact nothing has been asked. + * + * @param mixed $raw Records from the API. + * @return array + */ +function sendbeam_connect_clean_records( $raw ) { + if ( ! is_array( $raw ) ) { + return array(); + } + $out = array(); + foreach ( $raw as $record ) { + if ( ! is_array( $record ) || count( $out ) >= 20 ) { + continue; + } + $type = isset( $record['type'] ) ? strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', (string) $record['type'] ) ) : ''; + $name = isset( $record['name'] ) ? sanitize_text_field( (string) $record['name'] ) : ''; + $val = isset( $record['value'] ) ? sanitize_text_field( (string) $record['value'] ) : ''; + if ( '' === $type || '' === $val ) { + continue; + } + $found = null; + if ( array_key_exists( 'found', $record ) && null !== $record['found'] ) { + $found = (bool) $record['found']; + } + $out[] = array( + 'type' => substr( $type, 0, 10 ), + 'name' => $name, + 'value' => $val, + 'found' => $found, + ); + } + return $out; +} + +/** + * A timestamp from the API, in the site's own words. + * + * SendBeam answers in ISO 8601 UTC, which is the right thing to send and the + * wrong thing to show: "2026-09-24T05:49:24.291+00:00" is not a time anybody + * reads, and it is not even the right hour for most of the people reading it. + * WordPress already knows the site's timezone and the formats its owner + * chose, so it does the rendering. + * + * Anything that will not parse is handed back untouched rather than dropped — + * a strange-looking date is better than a step that silently stops saying + * when it last ran. + * + * @param string $iso A timestamp from the API. + * @return string + */ +function sendbeam_connect_when( $iso ) { + $iso = trim( (string) $iso ); + if ( '' === $iso ) { + return ''; + } + $stamp = strtotime( $iso ); + if ( ! $stamp ) { + return $iso; + } + return wp_date( get_option( 'date_format', 'j F Y' ) . ', ' . get_option( 'time_format', 'g:i a' ), $stamp ); +} + +/** + * Where this key's status lives. + * + * Per key, not per site. Two administrators signed in to different SendBeam + * workspaces — one testing, one live — shared a single transient, so for up + * to a minute each of them was shown the other's sending domain and told to + * put its records into their own DNS. The key is hashed rather than used: + * a transient name ends up in the options table, in backups and in logs, and + * an API key does not belong in any of them. + * + * @param string|null $api_key A particular key. Defaults to this site's. + * @return string + */ +function sendbeam_connect_status_key( $api_key = null ) { + $key = null === $api_key ? sendbeam_api_key() : (string) $api_key; + return SENDBEAM_CACHE_STATUS . '_' . substr( sha1( $key ), 0, 12 ); +} + +/** + * Remember a status, and when it was fetched. + * + * The timestamp is what separates "fresh" from "worth having anyway": the + * transient outlives the minute it is trusted for, so a failed request has + * something to fall back on. + * + * @param array $status Normalised status. + */ +function sendbeam_connect_cache_status( $status ) { + $status['fetched_at'] = time(); + set_transient( sendbeam_connect_status_key(), $status, SENDBEAM_STATUS_KEEP ); +} + +/** + * Forget it — after a disconnect, or when the key changes. + * + * @param string|null $api_key The key whose answer to forget. Defaults to + * this site's, which is what every caller but the + * key-change path wants. + */ +function sendbeam_connect_forget_status( $api_key = null ) { + delete_transient( sendbeam_connect_status_key( $api_key ) ); + // Everything cached under the single shared name this replaced. + delete_transient( SENDBEAM_CACHE_STATUS ); +} + +/** + * The connection's status: workspace, default form, sending domain, sender. + * + * @param bool $check True to ask SendBeam to re-check the domain's DNS now. + * That is a POST, it is rate-limited at the other end, and + * it never reads the cache. + * @return array Always the full shape; `ok` says whether the + * values came from SendBeam or are just empties. + */ +function sendbeam_connect_status( $check = false ) { + if ( '' === sendbeam_api_key() ) { + return sendbeam_connect_empty_status(); + } + + $cached = get_transient( sendbeam_connect_status_key() ); + $cached = is_array( $cached ) && isset( $cached['domain'] ) ? $cached : null; + + if ( ! $check && null !== $cached && ( time() - (int) ( isset( $cached['fetched_at'] ) ? $cached['fetched_at'] : 0 ) ) < SENDBEAM_STATUS_TTL ) { + return $cached; + } + + $result = $check + ? sendbeam_api_post( '/api/v1/connect/status', array( 'check_domain' => true ) ) + : sendbeam_api_get( '/api/v1/connect/status', array( 'timeout' => SENDBEAM_STATUS_TIMEOUT ) ); + + if ( ! $result['ok'] ) { + if ( 429 === $result['status'] ) { + $error = __( 'SendBeam is rate-limiting this site. Wait a few minutes and try again.', 'sendbeam' ); + } elseif ( 401 === $result['status'] || 403 === $result['status'] ) { + $error = __( 'SendBeam would not answer with this site\'s key. Reconnect the site.', 'sendbeam' ); + } else { + $error = __( 'Could not read this site\'s set-up from SendBeam just now.', 'sendbeam' ); + } + + /* + * An answer that has gone stale still beats no answer. Someone is in + * the middle of copying DNS records into a registrar, and blanking + * the panel because one request timed out takes them away from what + * they were doing for no gain. It is served with the state saying + * plainly that it is old. + * + * Either way it is cached, which is what stops a revoked key making a + * failing request on every wp-admin page load. + */ + $status = ( null !== $cached && ! empty( $cached['ok'] ) ) ? $cached : sendbeam_connect_empty_status(); + $status['error'] = $error; + $status['stale'] = ( null !== $cached && ! empty( $cached['ok'] ) ); + $status['domain_state'] = 'unavailable'; + sendbeam_connect_cache_status( $status ); + return $status; + } + + /* + * A 200 carrying nothing usable — an empty body, HTML from a proxy, a + * reply that did not parse — is a failure, not an answer. Normalising it + * would give every field an empty value and cache that for a minute, and + * the Overview would lose the DNS records someone was halfway through + * copying. + */ + if ( empty( $result['data'] ) ) { + $status = ( null !== $cached && ! empty( $cached['ok'] ) ) ? $cached : sendbeam_connect_empty_status(); + $status['error'] = __( 'SendBeam answered with nothing this site could read.', 'sendbeam' ); + $status['stale'] = ( null !== $cached && ! empty( $cached['ok'] ) ); + $status['domain_state'] = 'unavailable'; + sendbeam_connect_cache_status( $status ); + return $status; + } + + $status = sendbeam_connect_normalise_status( $result['data'] ); + sendbeam_connect_cache_status( $status ); + return $status; +} + +/** + * Is this answer one SendBeam gave just now? + * + * The difference matters wherever something is about to be *done* on the + * strength of it. Serving a stale body to a screen is a kindness; telling + * somebody who pressed **Check now** that their domain is still unverified, + * when in truth the request never got through, is not — and switching their + * site email on because a cached body from this morning said the domain had + * verified is worse again. + * + * @param array $status A status. + * @return bool + */ +function sendbeam_status_is_fresh( $status ) { + return ! empty( $status['ok'] ) && empty( $status['stale'] ); +} + +/** + * **Check now**: ask SendBeam to look the DNS up again, then come back. + * + * If the domain turns out to be verified and site email was approved at + * consent time but held back for exactly this reason, it is switched on here. + * That is finishing a job the site owner already said yes to — it is not the + * same as switching on something they turned off, which is why it happens + * only while `sendbeam_mail_deferred` is set and why turning site email off by + * hand clears that flag. + */ +function sendbeam_handle_domain_check() { + 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_domain_check' ); + + $status = sendbeam_connect_status( true ); + $note = 'checked'; + + if ( ! sendbeam_status_is_fresh( $status ) ) { + $note = 'unreachable'; + } elseif ( '' === $status['domain']['name'] ) { + $note = 'nodomain'; + } elseif ( $status['domain']['verified'] ) { + $note = sendbeam_connect_finish_deferred( $status ) ? 'verified_mail' : 'verified'; + } else { + $note = 'pending'; + } + + wp_safe_redirect( add_query_arg( 'sendbeam_domain', $note, sendbeam_check_return_url() ) ); + exit; +} + +/** + * Where a Check now should land: the screen it was pressed on. + * + * The check is offered on the Overview and on Settings → Sending domain, and + * always redirected to the Overview — so somebody working through the records + * on the Sending tab was moved to a different screen to be told the result and + * had to navigate back to carry on. The form says which screen it is on; a + * value that is not one of this plugin's own pages falls back to the Overview. + * + * @return string + */ +function sendbeam_check_return_url() { + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the caller checks the nonce before calling this. + $back = isset( $_POST['sendbeam_back'] ) ? sanitize_key( wp_unslash( $_POST['sendbeam_back'] ) ) : ''; + $page = sendbeam_pages(); + + if ( '' === $back || ! isset( $page[ $back ] ) ) { + return sendbeam_tab_url( 'overview' ); + } + if ( 'sendbeam-settings' === $back ) { + return add_query_arg( 'tab', 'domain', sendbeam_page_url( $back ) ); + } + return sendbeam_page_url( $back ); +} + +/** + * **Switch on**: route this site's email through SendBeam. + * + * Both conditions are re-read from the saved settings and a fresh status + * rather than trusted from the page that drew the button: a form can be + * replayed, and "the domain was verified when the page rendered" is not the + * same as "the domain is verified". + */ +function sendbeam_handle_mail_switch_on() { + 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_mail_switch_on' ); + + // A pasted key's permissions are not on record, so this cannot be + // decided here: SendBeam decides it, on the first message. + if ( sendbeam_connect_permissions_known() && ! sendbeam_connect_granted( 'transactional:send' ) ) { + wp_safe_redirect( add_query_arg( 'sendbeam_mail', 'noscope', sendbeam_tab_url( 'overview' ) ) ); + exit; + } + + $status = sendbeam_connect_status(); + if ( empty( $status['domain']['verified'] ) ) { + wp_safe_redirect( add_query_arg( 'sendbeam_mail', 'unverified', sendbeam_tab_url( 'overview' ) ) ); + exit; + } + + sendbeam_connect_enable_mail( $status ); + wp_safe_redirect( add_query_arg( 'sendbeam_mail', 'on', sendbeam_tab_url( 'overview' ) ) ); + exit; +} + +/** + * Switch the wp_mail() relay on, filling in the sender only where it is blank. + * + * A From name or address the site owner typed is never replaced: they may well + * have chosen `orders@` deliberately, and this is not the place to argue. + * + * @param array $status Normalised status, for the workspace sender. + */ +function sendbeam_connect_enable_mail( $status ) { + $settings = sendbeam_settings(); + + /* + * A held-back switch-on is Connect finishing the job consent started, so + * what it fills goes on the same list the exchange writes and Disconnect + * puts back. Pressing **Switch on** by hand is the owner's own decision + * and is recorded as nobody's but theirs. + */ + $connects = ! empty( $settings['sendbeam_mail_deferred'] ); + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + + if ( empty( $settings['mail_enabled'] ) && $connects ) { + $filled[] = 'mail_enabled'; + } + $settings['mail_enabled'] = 1; + $settings['sendbeam_mail_deferred'] = 0; + if ( '' === trim( (string) $settings['mail_from_name'] ) && '' !== $status['sender']['from_name'] ) { + $settings['mail_from_name'] = $status['sender']['from_name']; + if ( $connects ) { + $filled[] = 'mail_from_name'; + } + } + + /* + * The From address, and the one thing it must not be. The workspace + * sender is SendBeam's shared `ws-…@post.sendbeam.io` until somebody + * changes it, so filling it in blind on a site whose own domain has just + * verified leaves that site sending as SendBeam — after telling its owner + * the domain was verified. Once there is a verified domain, the address + * is on it. + */ + $own = sendbeam_own_domain_sender( $status ); + $current = trim( (string) $settings['mail_from_email'] ); + $fill = '' !== $own ? $own : trim( (string) $status['sender']['from_email'] ); + + if ( '' === $current && '' !== $fill ) { + $settings['mail_from_email'] = $fill; + if ( $connects ) { + $filled[] = 'mail_from_email'; + } + } elseif ( '' !== $own && $current !== $own && sendbeam_connect_filled( 'mail_from_email' ) ) { + // Connect put the shared address there, and the domain it was waiting + // for is now live. Correcting what this plugin wrote is not the same + // as overruling something the owner typed. + $sender = sendbeam_effective_sender( $status ); + if ( 'shared' === $sender['kind'] ) { + $settings['mail_from_email'] = $own; + } + } + $settings['sendbeam_connect_filled'] = array_values( array_unique( $filled ) ); + + sendbeam_write_settings( $settings ); +} + +/** + * Start re-checking the DNS on this site's own, for a day. + * + * Records almost never propagate while somebody is sitting in wp-admin: they + * enter them at the registrar, close the tab, and come back tomorrow. Until + * now that meant step 2 stayed unticked and the site's email stayed held back + * until a human pressed **Check now** — the plugin was waiting for the one + * thing it had just told the owner they did not need to do. + * + * One request an hour is well inside the check's own rate limit, and it stops + * the moment there is nothing left to find out. + * + * @param array $status The status that decided there was something to wait for. + */ +function sendbeam_connect_schedule_recheck( $status ) { + if ( '' === sendbeam_api_key() || ! sendbeam_connect_granted( 'domain' ) ) { + return; + } + // Nothing to wait for: no domain to check, or one that is already done. + if ( '' === $status['domain']['name'] || ! empty( $status['domain']['verified'] ) ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + update_option( SENDBEAM_RECHECK_COUNT, 0, false ); + if ( ! wp_next_scheduled( SENDBEAM_RECHECK_HOOK ) ) { + wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', SENDBEAM_RECHECK_HOOK ); + } +} + +/** Stop re-checking: verified, disconnected, deactivated, or out of tries. */ +function sendbeam_connect_unschedule_recheck() { + wp_clear_scheduled_hook( SENDBEAM_RECHECK_HOOK ); + delete_option( SENDBEAM_RECHECK_COUNT ); +} + +/** + * One hourly re-check. + * + * It does exactly what **Check now** does, including finishing the held-back + * switch-on, and then decides whether there is any reason to run again. A + * request that fails is not counted against the site — sendbeam.io being down + * for an hour is not the same as the DNS not being there — but the tally is, + * so a site cannot ask forever. + */ +function sendbeam_connect_run_recheck() { + if ( '' === sendbeam_api_key() ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + $runs = (int) get_option( SENDBEAM_RECHECK_COUNT, 0 ) + 1; + update_option( SENDBEAM_RECHECK_COUNT, $runs, false ); + if ( $runs > SENDBEAM_RECHECK_MAX ) { + sendbeam_connect_unschedule_recheck(); + return; + } + + $status = sendbeam_connect_status( true ); + if ( ! sendbeam_status_is_fresh( $status ) ) { + return; // Ask again next hour. + } + if ( '' === $status['domain']['name'] ) { + sendbeam_connect_unschedule_recheck(); + return; + } + if ( empty( $status['domain']['verified'] ) ) { + return; + } + + sendbeam_connect_finish_deferred( $status ); +} + +/** + * A domain has verified: finish what consent started, and stop asking. + * + * Three things reach this point — the **Check now** button, the hourly + * re-check, and coming back from a registrar that set the DNS up for you — + * and all three mean exactly the same thing to a site whose email is waiting + * on the domain. Switching it on is finishing a job the owner already said + * yes to; it is not the same as switching on something they turned off, which + * is why `sendbeam_mail_deferred` has to still be set. + * + * @param array $status A fresh status. + * @return bool Whether site email was switched on as a result. + */ +function sendbeam_connect_finish_deferred( $status ) { + if ( ! sendbeam_status_is_fresh( $status ) || empty( $status['domain']['verified'] ) ) { + return false; + } + + sendbeam_connect_unschedule_recheck(); + + $settings = sendbeam_settings(); + if ( empty( $settings['sendbeam_mail_deferred'] ) + || ! empty( $settings['mail_enabled'] ) + || ! sendbeam_connect_granted( 'transactional:send' ) ) { + return false; + } + + sendbeam_connect_enable_mail( $status ); + return true; +} + +/** + * Did Connect fill this setting in, rather than the site owner? + * + * @param string $key Settings key. + * @return bool + */ +function sendbeam_connect_filled( $key ) { + $settings = sendbeam_settings(); + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + return in_array( $key, $filled, true ); +} + +/** + * "Send from " — the one press that makes step 2's promise true. + * + * A site whose domain is verified and whose From address is still SendBeam's + * shared one is working, and is not doing the thing its owner set the domain + * up for. This is the button that fixes it. + */ +function sendbeam_handle_mail_own_domain() { + 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_mail_own_domain' ); + + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + $own = sendbeam_own_domain_sender( $status ); + + if ( '' === $own ) { + wp_safe_redirect( add_query_arg( 'sendbeam_sender', 'unverified', sendbeam_tab_url( 'overview' ) ) ); + exit; + } + + $settings = sendbeam_settings(); + $settings['mail_from_email'] = $own; + + // Recorded as Connect's doing, so disconnecting puts back what it found. + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + $filled[] = 'mail_from_email'; + $settings['sendbeam_connect_filled'] = array_values( array_unique( $filled ) ); + + sendbeam_write_settings( $settings ); + + wp_safe_redirect( add_query_arg( 'sendbeam_sender', 'own', sendbeam_tab_url( 'overview' ) ) ); + exit; +} diff --git a/includes/connect.php b/includes/connect.php new file mode 100644 index 0000000..5d7b860 --- /dev/null +++ b/includes/connect.php @@ -0,0 +1,1084 @@ + + */ +function sendbeam_connect_scopes() { + return array( + 'forms' => array( + 'label' => __( 'Show your forms on the site', 'sendbeam' ), + 'always' => true, + ), + 'contacts:write' => array( + 'label' => __( 'Add people who tick an opt-in box at registration, in comments or at checkout', 'sendbeam' ), + 'always' => false, + ), + 'transactional:send' => array( + 'label' => __( 'Send the site\'s own email (password resets, order emails, notifications) through SendBeam', 'sendbeam' ), + 'always' => false, + ), + 'ecommerce' => array( + 'label' => __( 'Send WooCommerce order, cart and product events to SendBeam', 'sendbeam' ), + 'always' => false, + ), + 'domain' => array( + /* translators: %s: this site's domain, e.g. harbourlane.co.uk */ + 'label' => sprintf( __( "Set up this site's sending domain (%s) in SendBeam", 'sendbeam' ), sendbeam_connect_site_host() ), + 'always' => false, + ), + ); +} + +/** + * The domain this site would send from: its host, without the `www.`. + * + * `www.` is stripped because a sending domain is the registrable name people + * see in the From address — mail from `www.harbourlane.co.uk` would be + * correct DNS and wrong to every human reading it — and because SendBeam + * derives the same value from `site_url` at the other end. The two must agree + * or the records shown here belong to a domain nobody set up. + * + * @return string Empty when this site has no usable host. + */ +function sendbeam_connect_site_host() { + $parts = wp_parse_url( site_url() ); + if ( empty( $parts['host'] ) ) { + return ''; + } + return preg_replace( '/^www\./i', '', strtolower( (string) $parts['host'] ) ); +} + +/** + * This site's origin — scheme, host and port, nothing else. + * + * SendBeam binds the grant to this exact string and refuses to hand the key to + * anything else, so it must be the origin and not a path: a site installed in + * a subdirectory would otherwise present a different value on the way out than + * on the way back. + * + * @return string + */ +function sendbeam_connect_site_origin() { + $parts = wp_parse_url( site_url() ); + if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { + return ''; + } + $origin = $parts['scheme'] . '://' . $parts['host']; + if ( ! empty( $parts['port'] ) ) { + $origin .= ':' . (int) $parts['port']; + } + return $origin; +} + +/** + * Is this origin one SendBeam will accept? + * + * Https everywhere, because the grant travels over it: http is allowed only on + * the hostnames a development machine uses, which cannot be reached from the + * internet — refusing those outright would make the feature untestable on a + * local install without weakening it anywhere that matters. + * + * @param string $origin Origin from sendbeam_connect_site_origin(). + * @return bool + */ +function sendbeam_connect_origin_ok( $origin ) { + $parts = wp_parse_url( (string) $origin ); + if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { + return false; + } + if ( 'https' === $parts['scheme'] ) { + return true; + } + if ( 'http' !== $parts['scheme'] ) { + return false; + } + $host = strtolower( $parts['host'] ); + if ( in_array( $host, array( 'localhost', '127.0.0.1', '::1', '[::1]' ), true ) ) { + return true; + } + return (bool) preg_match( '/\.(test|local)$/', $host ); +} + +/** + * Where the pop-up's state lives while the person is on sendbeam.io. + * + * Per user, not per site: two administrators connecting at once must not + * overwrite each other's state, and a state minted by one of them must not be + * usable by the other. + * + * @param int $user_id User ID. + * @return string + */ +function sendbeam_connect_transient_key( $user_id ) { + return 'sendbeam_connect_' . (int) $user_id; +} + +/** + * The consent page's URL on sendbeam.io, exactly as the contract specifies it. + * + * Nothing here is left to add_query_arg(), which does not encode: every value + * is rawurlencode()d first. A site name with a space or an ampersand would + * otherwise cut the query in half and SendBeam would read the wrong return + * address. + * + * @param string[] $scopes Approved scope names. + * @param string $state The CSRF token. + * @param string $sending_host The domain this site already sends from, so + * the consent page offers it back rather than + * deriving one from site_url. Empty on a first + * connect, and on the one link whose whole + * point is choosing a different domain. + * @return string Empty when this site cannot be connected (bad origin). + */ +function sendbeam_connect_consent_url( $scopes, $state, $sending_host = '' ) { + $origin = sendbeam_connect_site_origin(); + if ( '' === $origin || ! sendbeam_connect_origin_ok( $origin ) ) { + return ''; + } + + $user = wp_get_current_user(); + $name = trim( (string) get_bloginfo( 'name' ) ); + if ( function_exists( 'mb_substr' ) ) { + $name = mb_substr( $name, 0, 80 ); + } else { + $name = substr( $name, 0, 80 ); + } + + $args = array( + 'site_url' => rawurlencode( $origin ), + 'site_name' => rawurlencode( $name ), + 'email' => rawurlencode( isset( $user->user_email ) ? (string) $user->user_email : '' ), + 'scopes' => rawurlencode( implode( ',', $scopes ) ), + 'state' => rawurlencode( $state ), + 'return_to' => rawurlencode( sendbeam_connect_return_url() ), + ); + + /* + * The domain this site already sends from, so the consent page prefills + * SEND FROM with it rather than with this site's host. Without it, + * pressing Reconnect for any other reason — more permissions, a changed + * workspace, a key rotation — re-set the sending domain to the default + * and took the existing one, and its DNS records, out of the workspace. + * Nothing warned anybody: an owner half-way through entering three CNAMEs + * simply found them gone. + */ + $sending_host = sendbeam_connect_clean_host( $sending_host ); + if ( '' !== $sending_host ) { + $args['sending_host'] = rawurlencode( $sending_host ); + } + + return add_query_arg( $args, sendbeam_app_url() . '/connect/wordpress' ); +} + +/** + * A hostname, or ''. Nothing else goes out in a consent request. + * + * @param string $host Candidate. + * @return string + */ +function sendbeam_connect_clean_host( $host ) { + $host = strtolower( trim( (string) $host ) ); + if ( '' === $host || strlen( $host ) > 253 ) { + return ''; + } + return preg_match( '/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/', $host ) ? $host : ''; +} + +/** + * The sending domain this site already has, from the cached status body. + * + * The status body and not the site's host: the owner chooses the sending host + * at consent time and it is often not this site's domain at all. + * + * @return string Empty when this site has no sending domain. + */ +function sendbeam_connect_current_sending_host() { + if ( ! sendbeam_is_connected() ) { + return ''; + } + $status = sendbeam_connect_status(); + return sendbeam_connect_clean_host( isset( $status['domain']['name'] ) ? $status['domain']['name'] : '' ); +} + +/** + * The URL that starts the Connect flow from a link rather than the panel. + * + * Reconnecting is the answer to more than one dead end — a permission + * un-ticked at consent, a sending domain nobody was allowed to set up, a key + * that predates a permission existing — and every one of them used to end in + * "disconnect and connect again", which is a frightening instruction to give + * someone whose site is already working. A link is not a form, so the scopes + * it asks for are decided here: everything, or exactly what this site's key + * already carries. + * + * @param bool $all_scopes True to preselect every permission. False asks for + * the ones the key already holds, which is what a + * plain Reconnect means; a key pasted by hand records + * none, so that falls back to everything too. + * @param bool $keep_domain True to offer the sending domain this site already + * has back to the consent page, which is what every + * reconnect should do. False only for the one link + * whose purpose is choosing a different domain. + * @return string + */ +function sendbeam_connect_start_url( $all_scopes = false, $keep_domain = true ) { + $scopes = array_keys( sendbeam_connect_scopes() ); + + if ( ! $all_scopes ) { + $settings = sendbeam_settings(); + $granted = array_filter( array_map( 'trim', explode( ',', (string) $settings['sendbeam_connect_granted'] ) ) ); + $known = array_values( array_intersect( $scopes, $granted ) ); + if ( $known ) { + $scopes = $known; + } + } + + $args = array( + 'action' => 'sendbeam_connect_start', + 'sendbeam_scopes' => rawurlencode( implode( ',', $scopes ) ), + ); + + // Keeping the site's existing sending domain is the default, because + // every reconnect but one is being done for some other reason entirely. + // The exception says so here, and the handler reads it. + if ( ! $keep_domain ) { + $args['sendbeam_new_domain'] = '1'; + } + + return wp_nonce_url( add_query_arg( $args, admin_url( 'admin-post.php' ) ), 'sendbeam_connect_start' ); +} + +/** + * Where SendBeam sends the pop-up back to. Always on this site's own origin. + * + * @return string + */ +function sendbeam_connect_return_url() { + return admin_url( 'admin-post.php?action=sendbeam_connect_return' ); +} + +/** + * Only the scopes we offer, and `forms` whether it was ticked or not. + * + * Nothing works without `forms` — the settings screen cannot list a single + * form — so it is presented as fixed rather than as a choice that quietly + * breaks the plugin. + * + * @param mixed $raw Posted scope list. + * @return string[] + */ +function sendbeam_connect_clean_scopes( $raw ) { + $known = sendbeam_connect_scopes(); + $out = array(); + foreach ( $known as $scope => $meta ) { + if ( $meta['always'] ) { + $out[] = $scope; + continue; + } + if ( is_array( $raw ) && in_array( $scope, array_map( 'strval', $raw ), true ) ) { + $out[] = $scope; + } + } + return $out; +} + +/** + * Step one: mint the state, remember it, and send the pop-up to SendBeam. + */ +function sendbeam_connect_start() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) ); + } + check_admin_referer( 'sendbeam_connect_start' ); + + /* + * The panel posts a checkbox per scope; a Reconnect link carries the same + * list as a csv, because a link cannot post an array. Both are cleaned by + * the same function, and the consent page is the real gate either way — + * asking for a permission is not being given it. + */ + $raw = array(); + if ( isset( $_REQUEST['sendbeam_scopes'] ) ) { + $asked = wp_unslash( $_REQUEST['sendbeam_scopes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitised on the next two lines, as an array or as a string. + $raw = is_array( $asked ) + ? array_map( 'sanitize_text_field', $asked ) + : array_map( 'trim', explode( ',', sanitize_text_field( $asked ) ) ); + } + $scopes = sendbeam_connect_clean_scopes( $raw ); + + // [A-Za-z0-9] only, and 43 of them: comfortably past the 32 the contract + // asks for, and safe in a query string without escaping surprises. + $state = wp_generate_password( 43, false, false ); + + // Built before anything is remembered: a site that cannot be connected at + // all should not be left holding a pending connection it can never finish. + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- the nonce is checked at the top of this handler. + $keep_domain = empty( $_REQUEST['sendbeam_new_domain'] ); + $url = sendbeam_connect_consent_url( $scopes, $state, $keep_domain ? sendbeam_connect_current_sending_host() : '' ); + if ( '' === $url ) { + wp_die( esc_html__( 'This site has no https address, so it cannot be connected to SendBeam. Add a certificate, or paste an API key instead.', 'sendbeam' ) ); + } + + /* + * Whether a pop-up actually opened. The script sets this to 1 in the + * submit handler when window.open() returned a window; a blocked pop-up + * leaves it at 0 and the form simply navigates this tab instead. The + * return page cannot work this out for itself — window.opener is null in + * both cases once the redirect has happened — so it is remembered here + * and used to decide between closing the window and offering a way back. + */ + $popup = isset( $_POST['sendbeam_popup'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['sendbeam_popup'] ) ); + + set_transient( + sendbeam_connect_transient_key( get_current_user_id() ), + array( + 'state' => $state, + 'scopes' => $scopes, + 'popup' => $popup ? 1 : 0, + ), + SENDBEAM_CONNECT_TTL + ); + + // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- deliberately off-site: this is the whole point of the button, and the destination is sendbeam_app_url(). + wp_redirect( $url, 302 ); + exit; +} + +/** + * Step two: the pop-up comes back. Swap the grant for a key, server to server. + */ +function sendbeam_connect_return() { + if ( ! current_user_can( 'manage_options' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'sendbeam' ), '', array( 'response' => 403 ) ); + } + + /* + * No nonce, by design (see the file header): this is a redirect arriving + * from sendbeam.io, and `state` is the token. It is read once and the + * transient is deleted immediately, in every branch below, so the same + * return URL cannot be replayed. + */ + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- `state`, checked below against a per-user transient, is the CSRF token for this cross-site return. + $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; + $grant = isset( $_GET['grant'] ) ? sanitize_text_field( wp_unslash( $_GET['grant'] ) ) : ''; + $error = isset( $_GET['error'] ) ? sanitize_key( wp_unslash( $_GET['error'] ) ) : ''; + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + $key = sendbeam_connect_transient_key( get_current_user_id() ); + $stored = get_transient( $key ); + delete_transient( $key ); + + $expected = is_array( $stored ) && isset( $stored['state'] ) ? (string) $stored['state'] : ''; + + // A connection nobody can be sure about is treated as a pop-up, which is + // what it was before this flag existed: the window closes, and the link + // underneath is there either way. + $is_popup = ! is_array( $stored ) || ! isset( $stored['popup'] ) || ! empty( $stored['popup'] ); + + if ( '' === $expected || '' === $state || ! hash_equals( $expected, $state ) ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'This window did not come back from the request this site started. Nothing was changed. Close it and press Connect SendBeam again.', 'sendbeam' ), + $is_popup + ); + exit; + } + + if ( '' !== $error ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'You did not approve the connection, so this site was given nothing. You can press Connect SendBeam again whenever you like.', 'sendbeam' ), + $is_popup + ); + exit; + } + + if ( ! preg_match( '/^[A-Za-z0-9_\-]{20,128}$/', $grant ) ) { + sendbeam_connect_render_result( + false, + __( 'Not connected', 'sendbeam' ), + __( 'SendBeam did not send anything this site could use. Nothing was changed.', 'sendbeam' ), + $is_popup + ); + exit; + } + + $result = sendbeam_connect_exchange( $grant, $state ); + if ( $result['ok'] ) { + sendbeam_connect_render_result( + true, + __( 'Connected', 'sendbeam' ), + $result['workspace'] + /* translators: %s: the SendBeam workspace name */ + ? sprintf( __( 'This site is connected to %s. You can close this window.', 'sendbeam' ), $result['workspace'] ) + : __( 'This site is connected. You can close this window.', 'sendbeam' ), + $is_popup + ); + exit; + } + + sendbeam_connect_render_result( false, __( 'Not connected', 'sendbeam' ), $result['error'], $is_popup ); + exit; +} + +/** + * The server-to-server half: grant in, key out, once. + * + * The key never touches the browser and is never written to a log — not the + * error branch either, which is where that usually happens. + * + * @param string $grant Single-use grant ID from the redirect. + * @param string $state The state it is bound to. + * @return array{ok:bool,workspace:string,error:string} + */ +function sendbeam_connect_exchange( $grant, $state ) { + $origin = sendbeam_connect_site_origin(); + $response = wp_remote_post( + sendbeam_app_url() . '/api/v1/connect/exchange', + array( + 'timeout' => 15, + 'headers' => array( + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + 'User-Agent' => 'SendBeam-WordPress/' . SENDBEAM_VERSION . ' (' . $origin . ')', + ), + 'body' => wp_json_encode( + array( + 'grant' => $grant, + 'state' => $state, + 'site_url' => $origin, + ) + ), + ) + ); + + if ( is_wp_error( $response ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'This server could not reach sendbeam.io to finish the connection. Nothing was changed. Try again, or paste an API key instead.', 'sendbeam' ), + ); + } + + $status = (int) wp_remote_retrieve_response_code( $response ); + $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); + $data = is_array( $body ) ? $body : array(); + + if ( 410 === $status ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'That connection had already been used, or it was left too long. Nothing was changed. Press Connect SendBeam again to start a fresh one.', 'sendbeam' ), + ); + } + if ( 429 === $status ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam is rate-limiting this site. Wait a few minutes and press Connect SendBeam again.', 'sendbeam' ), + ); + } + if ( 200 !== $status || empty( $data['api_key'] ) || ! is_string( $data['api_key'] ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam refused to finish the connection. Nothing was changed. Press Connect SendBeam again, or paste an API key instead.', 'sendbeam' ), + ); + } + + $workspace = ''; + if ( isset( $data['workspace']['name'] ) && is_string( $data['workspace']['name'] ) ) { + $workspace = sanitize_text_field( $data['workspace']['name'] ); + } + + if ( ! sendbeam_connect_store_key( $data['api_key'], $workspace, $data ) ) { + return array( + 'ok' => false, + 'workspace' => '', + 'error' => __( 'SendBeam sent something that does not look like an API key, so nothing was saved. Press Connect SendBeam again, or paste a key instead.', 'sendbeam' ), + ); + } + + return array( + 'ok' => true, + 'workspace' => $workspace, + 'error' => '', + ); +} + +/** + * Save the key the way a pasted one is saved. + * + * Through sendbeam_sanitize_settings() rather than straight into the option: + * that function is where the key is validated, where the other tabs' settings + * are preserved and where the cached workspace data is dropped. A second way + * of writing the same option is a second set of rules to keep in step, and + * the one that skips the validation is the one that stores rubbish. + * + * Everything else the exchange came back with is applied in the same write: + * the form SendBeam just made, the sender it worked out, and — only when the + * sending domain is already verified — site email itself. One update_option() + * rather than five, so a site is never left half-configured by a failure + * between them. + * + * @param string $api_key The key SendBeam minted. + * @param string $workspace Workspace name, for the screen to show. + * @param array $data The whole exchange response. + * @return bool False when the key did not survive validation — nothing saved. + */ +function sendbeam_connect_store_key( $api_key, $workspace, $data = array() ) { + $clean = sendbeam_sanitize_settings( + array( + '_tab' => 'connect', + 'api_key' => $api_key, + ) + ); + + if ( trim( (string) $api_key ) !== (string) $clean['api_key'] || '' === (string) $clean['api_key'] ) { + return false; + } + + $granted = sendbeam_connect_granted_from_response( $data ); + $status = sendbeam_connect_normalise_status( $data ); + + /* + * Everything below fills a setting the site had left empty, and Disconnect + * has to be able to put those back without touching anything the owner + * chose. So each one is recorded as it is filled. A reconnect adds to the + * list rather than replacing it — the first connection's work is still + * this plugin's to undo — and saving the tab by hand takes a setting off + * it again, in sendbeam_sanitize_settings(). + */ + $before = sendbeam_settings(); + $filled = isset( $before['sendbeam_connect_filled'] ) && is_array( $before['sendbeam_connect_filled'] ) ? $before['sendbeam_connect_filled'] : array(); + + /* + * A reconnect into a *different* workspace is not a reconnect, it is a + * move. Everything Connect filled in points at the workspace this site + * has just left — a form ID the new workspace does not own, a From + * address on a domain it cannot send from — and carrying it across is + * how an embed starts 404ing silently on a live page. So the filled-in + * values are released first, and the fills below start from empty and + * come entirely out of the new workspace's answer. Anything the owner + * typed themselves is not on that list, and is left alone. + */ + if ( sendbeam_connect_moved_workspace( $before, $status, $workspace ) ) { + foreach ( array( 'default_form', 'mail_from_name', 'mail_from_email' ) as $key ) { + if ( in_array( $key, $filled, true ) ) { + $clean[ $key ] = ''; + } + } + if ( in_array( 'mail_enabled', $filled, true ) ) { + $clean['mail_enabled'] = 0; + } + $filled = array(); + } + + $clean['sendbeam_connected_via'] = 'connect'; + $clean['sendbeam_connect_workspace'] = $workspace; + $clean['sendbeam_connect_workspace_id'] = (string) $status['workspace']['id']; + $clean['sendbeam_connect_granted'] = implode( ',', $granted ); + + // The form SendBeam made during consent becomes this site's default, but + // only when the site has not already chosen one: a reconnect must not + // quietly repoint an embed that is already live on a page. + $clean['sendbeam_connect_notes'] = isset( $status['notes'] ) && is_array( $status['notes'] ) ? array_values( $status['notes'] ) : array(); + if ( '' === trim( (string) $clean['default_form'] ) && sendbeam_is_form_id( $status['default_form']['id'] ) ) { + $clean['default_form'] = strtolower( $status['default_form']['id'] ); + $filled[] = 'default_form'; + } + + if ( in_array( 'transactional:send', $granted, true ) ) { + if ( '' === trim( (string) $clean['mail_from_name'] ) && '' !== $status['sender']['from_name'] ) { + $clean['mail_from_name'] = $status['sender']['from_name']; + $filled[] = 'mail_from_name'; + } + if ( '' === trim( (string) $clean['mail_from_email'] ) && '' !== $status['sender']['from_email'] ) { + $clean['mail_from_email'] = $status['sender']['from_email']; + $filled[] = 'mail_from_email'; + } + + /* + * Site email is the one thing consent does not switch on by itself. + * An unverified domain means every message would be sent from a name + * the receiving server has no reason to trust, and a site whose + * password resets silently stop arriving is worse off than one that + * never turned the feature on. So: on when the domain is already + * verified, and otherwise held — `sendbeam_mail_deferred` is what the + * domain check later reads to finish the job. + */ + if ( empty( $clean['mail_enabled'] ) ) { + if ( ! empty( $status['domain']['verified'] ) ) { + $clean['mail_enabled'] = 1; + $clean['sendbeam_mail_deferred'] = 0; + $filled[] = 'mail_enabled'; + } else { + $clean['sendbeam_mail_deferred'] = 1; + } + } + } + + $clean['sendbeam_connect_filled'] = array_values( array_unique( $filled ) ); + + sendbeam_write_settings( $clean ); + sendbeam_flush_cache(); + sendbeam_connect_cache_status( $status ); + sendbeam_connect_schedule_recheck( $status ); + return true; +} + +/** + * Did this connection land in a different workspace from the last one? + * + * The ID is the answer wherever there is one on both sides: workspace names + * are not unique and can be changed, so comparing them would call a rename a + * move and miss two workspaces that happen to share a name. Connections made + * before the ID was recorded have only the name, and the name is better than + * nothing for them. + * + * A site that has never connected has nothing to move away from, so it is + * never a move — the first connection must not throw away settings the owner + * put there by hand before it. + * + * @param array $before This site's settings before the write. + * @param array $status The normalised exchange response. + * @param string $workspace The workspace name the exchange reported. + * @return bool + */ +function sendbeam_connect_moved_workspace( $before, $status, $workspace ) { + $was_id = isset( $before['sendbeam_connect_workspace_id'] ) ? (string) $before['sendbeam_connect_workspace_id'] : ''; + $now_id = isset( $status['workspace']['id'] ) ? (string) $status['workspace']['id'] : ''; + if ( '' !== $was_id && '' !== $now_id ) { + return $was_id !== $now_id; + } + + $was_name = isset( $before['sendbeam_connect_workspace'] ) ? (string) $before['sendbeam_connect_workspace'] : ''; + if ( '' === $was_name || '' === (string) $workspace ) { + return false; + } + return $was_name !== (string) $workspace; +} + +/** + * Which permissions the key actually carries. + * + * Read from the response, never from what was asked for: the consent page can + * untick a box, and a screen that assumes otherwise tells someone to press a + * button that will always fail. + * + * @param array $data Exchange or status response. + * @return string[] + */ +function sendbeam_connect_granted_from_response( $data ) { + $known = array_keys( sendbeam_connect_scopes() ); + $out = array(); + $raw = isset( $data['scopes'] ) && is_array( $data['scopes'] ) ? $data['scopes'] : array(); + foreach ( $raw as $scope ) { + $scope = is_string( $scope ) ? $scope : ''; + if ( in_array( $scope, $known, true ) && ! in_array( $scope, $out, true ) ) { + $out[] = $scope; + } + } + return $out; +} + +/** + * Does this site know what its key is allowed to do? + * + * Only a connection made through Connect has its permissions on record. A + * pasted key arrives with nothing but itself, so "was this key given that + * permission?" has three answers rather than two — and the third, "no idea", + * was being said as "no", which is a claim about somebody's key that this + * site has no way of making. + * + * @return bool + */ +function sendbeam_connect_permissions_known() { + return sendbeam_connected_via_connect() && '' !== (string) sendbeam_settings()['sendbeam_connect_granted']; +} + +/** + * Whether this site's key was granted one permission. + * + * False for a pasted key, whose permissions are unknown — callers that need + * to tell "no" apart from "unknown" ask sendbeam_connect_permissions_known() + * first. + * + * @param string $scope Scope name. + * @return bool + */ +function sendbeam_connect_granted( $scope ) { + $settings = sendbeam_settings(); + $granted = array_filter( array_map( 'trim', explode( ',', (string) $settings['sendbeam_connect_granted'] ) ) ); + return in_array( $scope, $granted, true ); +} + +/** + * Disconnect: revoke the key at SendBeam, then forget it here. + * + * In that order, and only in that order. Forgetting the key first would leave + * a live key in the workspace that nothing on this site can name any more — + * the exact situation the old "Remove the saved key" checkbox produced, and + * the reason its help text had to end with an instruction to go and revoke it + * by hand. + * + * The revoke is best-effort with a short timeout. If sendbeam.io cannot be + * reached the site still forgets the key — a site owner pressing Disconnect + * has decided, and leaving the key in the database because a request timed + * out would be answering a different question — and is told plainly that the + * key is still live and where to revoke it. + */ +function sendbeam_connect_disconnect() { + 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_disconnect' ); + + $note = sendbeam_connect_release_key(); + $settings = sendbeam_settings(); + + /* + * The workspace keeps its list, its form, its sending domain and its + * sender — disconnecting one site is not a reason to dismantle a + * workspace other sites may be sending from. What this site puts back is + * what Connect filled in here, and only that: a form ID belonging to a + * workspace this site no longer has a key for makes every embed 404 + * silently, and a From address pointing at a domain it can no longer send + * from is worse than an empty field. + */ + $filled = isset( $settings['sendbeam_connect_filled'] ) && is_array( $settings['sendbeam_connect_filled'] ) ? $settings['sendbeam_connect_filled'] : array(); + foreach ( array( 'default_form', 'mail_from_name', 'mail_from_email' ) as $key ) { + if ( in_array( $key, $filled, true ) ) { + $settings[ $key ] = ''; + } + } + if ( in_array( 'mail_enabled', $filled, true ) ) { + $settings['mail_enabled'] = 0; + } + + $settings['api_key'] = ''; + $settings['sendbeam_connected_via'] = ''; + $settings['sendbeam_connect_workspace'] = ''; + $settings['sendbeam_connect_workspace_id'] = ''; + $settings['sendbeam_connect_notes'] = array(); + $settings['sendbeam_connect_granted'] = ''; + $settings['sendbeam_connect_filled'] = array(); + $settings['sendbeam_mail_deferred'] = 0; + + // Before the key is forgotten, not after: the cached answer is filed + // under that key, and a site that has just let go of it can no longer + // name the transient it wrote. + sendbeam_connect_forget_status(); + sendbeam_write_settings( $settings ); + + sendbeam_flush_cache(); + sendbeam_connect_unschedule_recheck(); + delete_transient( 'sendbeam_form_placed' ); + + wp_safe_redirect( add_query_arg( 'sendbeam_disconnected', $note, sendbeam_tab_url( 'overview' ) ) ); + exit; +} + +/** + * Give this site's key back to SendBeam, where that is the right thing to do. + * + * SENDBEAM_API_KEY in wp-config.php beats the stored key everywhere, + * including here — so on a site that defines it, POST /connect/disconnect + * would revoke *that* key, which this plugin never issued and which is very + * likely shared with something else. A key this site does not store is not + * this site's to revoke: it is left alone, the stored one is forgotten, and + * the screen says where the live one is. + * + * Shared by Disconnect and by "Remove the saved key" on Settings → Advanced, + * which is a second, quieter door to the same place and used to leave a + * Connect-issued key live in the workspace without saying so. + * + * @return string ok, pasted, constant or unreachable — what to tell the owner. + */ +function sendbeam_connect_release_key() { + $stored = (string) sendbeam_settings()['api_key']; + $constant = ( defined( 'SENDBEAM_API_KEY' ) && SENDBEAM_API_KEY ) ? (string) SENDBEAM_API_KEY : ''; + + if ( '' !== $constant && $constant !== $stored ) { + return 'constant'; + } + if ( ! sendbeam_connected_via_connect() ) { + /* + * A key somebody pasted was minted for whatever they minted it for, + * and may well be in use on another site. Revoking it because this + * one is being disconnected would take those down without warning. + * It is forgotten here and left alone there, and the screen says so. + */ + return 'pasted'; + } + if ( '' === sendbeam_api_key() ) { + return 'unreachable'; + } + + $result = sendbeam_api_post( '/api/v1/connect/disconnect', array(), 10 ); + // A key SendBeam has already forgotten is a key that is not live, so + // 401 counts as revoked rather than as a failure to report. + return ( $result['ok'] || 401 === $result['status'] ) ? 'ok' : 'unreachable'; +} + +/** + * Is this site's key pinned in wp-config.php? + * + * @return bool + */ +function sendbeam_key_in_config() { + return defined( 'SENDBEAM_API_KEY' ) && '' !== trim( (string) SENDBEAM_API_KEY ); +} + +/** + * Was this site connected through the button rather than a pasted key? + * + * @return bool + */ +function sendbeam_connected_via_connect() { + $settings = sendbeam_settings(); + return 'connect' === (string) $settings['sendbeam_connected_via'] && '' !== sendbeam_api_key(); +} + +/** + * The workspace the button connected this site to, if it was the button. + * + * @return string + */ +function sendbeam_connect_workspace_name() { + $settings = sendbeam_settings(); + return (string) $settings['sendbeam_connect_workspace']; +} + +/** + * The little page the pop-up ends on. + * + * It tells the opener what happened and closes itself. The link underneath is + * not decoration: a browser will only close a window that script opened, and + * if the person reached this through something other than the pop-up — a + * blocker, a middle-click — the window stays and the link is the way out. + * + * @param bool $connected Whether a key was stored. + * @param string $heading Heading. + * @param string $detail One sentence under it. + * @param bool $is_popup Whether this really is the pop-up. False when the + * browser blocked it and the form navigated the tab + * the person was already on — closing that would + * leave them staring at nothing. + */ +function sendbeam_connect_render_result( $connected, $heading, $detail, $is_popup = true ) { + $overview = sendbeam_tab_url( 'overview' ); + $origin = sendbeam_connect_site_origin(); + + nocache_headers(); + if ( ! headers_sent() ) { + header( 'Content-Type: text/html; charset=utf-8' ); + } + + echo ''; + echo ''; + echo '' . esc_html( $heading ) . ''; + echo ''; + printf( '

%s

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

%s

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

%s

', + esc_url( $overview ), + esc_html( $is_popup ? __( 'Back to SendBeam settings', 'sendbeam' ) : __( 'Back to the site', 'sendbeam' ) ) + ); + + /* + * Nothing is closed when this is not the pop-up. A blocked pop-up turns + * the whole flow into an ordinary navigation, and window.close() on a + * window script did not open does nothing in every current browser — so + * the person would be left on a dead-end page with no way back but the + * link. It is the link they get. + */ + if ( $is_popup ) { + // Only a success is announced; the opener reloads on it and would + // otherwise throw away an unsaved settings form for nothing. + if ( $connected && '' !== $origin ) { + printf( + '', + wp_json_encode( $origin, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) + ); + } else { + echo ''; + } + } + + echo ''; + + /** + * Fires when the Connect pop-up has rendered its outcome, immediately + * before the request ends. + * + * @param bool $connected Whether a key was stored. + * @param string $detail The sentence shown to the person. + */ + do_action( 'sendbeam_connect_result', $connected, $detail ); +} + +/** + * The Connect panel: what the site wants to do, and the button. + * + * @return void + */ +function sendbeam_connect_panel() { + $origin = sendbeam_connect_site_origin(); + + /* + * The id is what step 1 links to. It is on the wrapper rather than on the + * button, so every version of this panel — the button, the note about + * wp-config.php, the note about http — is what the link lands on. + */ + echo '
'; + + /* + * A key defined in wp-config.php beats anything stored here, everywhere. + * Connecting on such a site mints a key, stores it, and then never uses + * it — a real key sitting unused in a database, which is the worst of + * both worlds. So the button is not offered, and the panel says where the + * live key actually is. + */ + if ( sendbeam_key_in_config() ) { + echo '

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

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

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

'; + return; + } + + echo '

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

'; + + printf( '', esc_url( admin_url( 'admin-post.php' ) ) ); + wp_nonce_field( 'sendbeam_connect_start' ); + echo ''; + + /* + * Flipped to 1 by the submit handler when window.open() actually returned + * a window. Left at 0 when the pop-up was blocked, when the browser has + * no script at all, or when someone submitted this form some other way — + * all three of which mean the flow is happening in this very tab, and the + * page it lands on must offer a way back instead of trying to close. + */ + echo ''; + echo '

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

'; + echo '
    '; + foreach ( sendbeam_connect_scopes() as $scope => $meta ) { + echo '
  • '; + } + echo '
'; + printf( + '

', + esc_html__( 'Connect SendBeam', 'sendbeam' ) + ); + echo ''; + echo ''; +} + +/** + * The two behaviours the panel needs, appended to the admin script. + * + * The window is opened in the submit handler — synchronously, inside the + * click — because a pop-up opened any later is a pop-up the browser blocks. + * If it is blocked anyway the form is left alone and simply navigates, which + * still works: the return page has a link back. + * + * @return string + */ +function sendbeam_connect_admin_js() { + $origin = wp_json_encode( sendbeam_connect_site_origin(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); + return ' + ( function () { + var origin = ' . $origin . '; + var form = document.getElementById( "sb-connect-form" ); + if ( form ) { + form.addEventListener( "submit", function () { + var flag = document.getElementById( "sb-connect-popup" ); + var win = window.open( "", "sendbeam-connect", "width=600,height=760" ); + if ( win ) { + form.target = "sendbeam-connect"; + if ( flag ) { flag.value = "1"; } + } else { + form.removeAttribute( "target" ); + if ( flag ) { flag.value = "0"; } + } + } ); + } + /* + * Coming back from a registrar leaves sb_dc in the address bar, and + * sb_dc=done spends a check. A refresh, or a bookmark, would spend + * another one and say the records were checked just now when they + * were not, so the flag comes off the URL the moment it is read. + */ + if ( window.history && history.replaceState && window.URL ) { + try { + var here = new URL( window.location.href ); + if ( here.searchParams.has( "sb_dc" ) ) { + here.searchParams.delete( "sb_dc" ); + here.searchParams.delete( "sb_dc_reason" ); + history.replaceState( null, "", here.toString() ); + } + } catch ( err ) {} + } + window.addEventListener( "message", function ( e ) { + if ( e.origin !== origin || ! e.data || "connected" !== e.data.sendbeam ) { return; } + window.location.reload(); + } ); + }() ); + '; +} diff --git a/includes/ecommerce.php b/includes/ecommerce.php index 22ecf85..971ac53 100644 --- a/includes/ecommerce.php +++ b/includes/ecommerce.php @@ -40,6 +40,8 @@ const SENDBEAM_CART_CHECK_HOOK = 'sendbeam_check_cart_abandonment'; const SENDBEAM_CART_WINDOW_MIN = 5; const SENDBEAM_CART_WINDOW_MAX = 10080; // 7 days. +/** Order meta that says Order placed has already gone out for this order. */ +const SENDBEAM_ORDER_PLACED_META = '_sendbeam_order_placed_sent'; add_action( 'admin_post_sendbeam_save_ecommerce', 'sendbeam_handle_save_ecommerce' ); add_action( SENDBEAM_ECOMMERCE_HOOK, 'sendbeam_ecommerce_run_event' ); @@ -48,7 +50,19 @@ // WooCommerce. Every callback is a no-op the moment WooCommerce, or the // specific function/class it needs, is not there — exactly how sync.php's // own checkout hook already degrades. -add_action( 'woocommerce_checkout_order_processed', 'sendbeam_ecommerce_on_order_placed', 10, 1 ); + +/* + * Order placed means PAID. The checkout hook fires while WooCommerce is still + * creating the order — before any gateway has taken a penny, and whatever + * the order ends up as — so a card that is declined had already produced an + * "order placed" event and a lifetime-value increment. Payment complete + * covers gateways; processing and completed cover cash on delivery and a + * merchant marking an order paid by hand. One order reaches more than one of + * these, so the send is recorded on the order and made once. + */ +add_action( 'woocommerce_payment_complete', 'sendbeam_ecommerce_on_order_paid', 10, 1 ); +add_action( 'woocommerce_order_status_processing', 'sendbeam_ecommerce_on_order_paid', 10, 1 ); +add_action( 'woocommerce_order_status_completed', 'sendbeam_ecommerce_on_order_paid', 10, 1 ); add_action( 'woocommerce_single_product_summary', 'sendbeam_ecommerce_on_product_viewed', 1 ); add_action( 'woocommerce_add_to_cart', 'sendbeam_ecommerce_on_add_to_cart', 10, 6 ); add_action( 'woocommerce_before_checkout_form', 'sendbeam_ecommerce_refresh_cart_email' ); @@ -109,7 +123,7 @@ function sendbeam_ecommerce_active( $event ) { */ function sendbeam_handle_save_ecommerce() { 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_ecommerce' ); @@ -249,7 +263,7 @@ function sendbeam_ecommerce_on_order_placed( $order_id ) { if ( ! sendbeam_ecommerce_active( 'order_placed' ) || ! function_exists( 'wc_get_order' ) ) { return; } - $order = wc_get_order( $order_id ); + $order = $order_id instanceof WC_Order ? $order_id : wc_get_order( $order_id ); if ( ! $order ) { return; } @@ -268,6 +282,26 @@ function sendbeam_ecommerce_on_order_placed( $order_id ) { ); } +/** + * The paid-order hooks land here. Whichever of them fires first sends the + * event and marks the order; the rest find the mark and do nothing, so an + * order that goes processing → completed is one Order placed, not two. + * + * @param int|WC_Order $order_id Order ID, or the order itself. + */ +function sendbeam_ecommerce_on_order_paid( $order_id ) { + if ( ! sendbeam_ecommerce_active( 'order_placed' ) || ! function_exists( 'wc_get_order' ) ) { + return; + } + $order = $order_id instanceof WC_Order ? $order_id : wc_get_order( $order_id ); + if ( ! $order || $order->get_meta( SENDBEAM_ORDER_PLACED_META ) ) { + return; + } + $order->update_meta_data( SENDBEAM_ORDER_PLACED_META, time() ); + $order->save(); + sendbeam_ecommerce_on_order_placed( $order ); +} + /* ---------------------------------------------------------- Product viewed */ /** diff --git a/includes/helpers.php b/includes/helpers.php index e1b0b2f..16a4e26 100644 --- a/includes/helpers.php +++ b/includes/helpers.php @@ -20,6 +20,26 @@ function sendbeam_app_url() { return untrailingslashit( esc_url_raw( $url ) ); } +/** + * A link into SendBeam for somebody to click. + * + * Distinct from `sendbeam_app_url()`, which is the origin the API is called + * against and the origin messages are checked for. The bare origin is the + * marketing site: "Open SendBeam" on the Overview was sending people who + * already have an account to a page inviting them to get one. The app's + * signed-in home is /dashboard, which sends a signed-out visitor to /login + * and back. + * + * Every human-facing link goes through here, deep ones included, so there is + * one place that knows what a link into SendBeam looks like. + * + * @param string $path Path within the app, with a leading slash. + * @return string + */ +function sendbeam_app_link( $path = '/dashboard' ) { + return sendbeam_app_url() . $path; +} + /** * Default values for every setting, so callers never test for missing keys. * @@ -27,27 +47,56 @@ function sendbeam_app_url() { */ function sendbeam_default_settings() { return array( - 'default_form' => '', - 'contact_form' => '', - 'popup_form' => '', - 'popup_where' => 'off', - 'popup_trigger' => 'timer', - 'popup_delay' => 5, - 'popup_once' => 'day', - 'popup_label' => '', - 'style_accent' => '', - 'style_text' => '', - 'style_field' => '', - 'style_border' => '', - 'style_radius' => '', - 'style_font' => 'inherit', - 'style_size' => '', - 'style_bare' => 1, - 'mail_enabled' => 0, - 'api_key' => '', - 'mail_from_name' => '', - 'mail_from_email' => '', - 'mail_fallback' => 1, + 'default_form' => '', + 'contact_form' => '', + 'popup_form' => '', + 'popup_where' => 'off', + 'popup_trigger' => 'timer', + 'popup_delay' => 5, + 'popup_once' => 'day', + 'popup_label' => '', + 'style_accent' => '', + 'style_text' => '', + 'style_field' => '', + 'style_border' => '', + 'style_radius' => '', + 'style_font' => 'inherit', + 'style_size' => '', + 'style_bare' => 1, + 'mail_enabled' => 0, + 'api_key' => '', + 'mail_from_name' => '', + 'mail_from_email' => '', + 'mail_fallback' => 1, + // How many days of the email log to keep. 0 is for ever, which the + // hard row cap still puts a ceiling on. + 'mail_log_days' => 30, + // Set only when the key arrived through Connect, so the Overview can + // name the workspace and offer Disconnect rather than a paste field. + // Cleared the moment the key is changed or removed by hand. + 'sendbeam_connected_via' => '', + 'sendbeam_connect_workspace' => '', + // The workspace's own ID, which is what says whether a reconnect + // landed in the same workspace or a different one. The name cannot + // answer that: two workspaces can share one, and renaming a + // workspace would otherwise look like moving to another. + 'sendbeam_connect_workspace_id' => '', + // The permissions SendBeam actually granted this key, as a csv. What + // was *asked* for is not the same thing — the person can untick a box + // on the consent page — and the Overview has to say "you did not give + // this site that permission" rather than guess. + 'sendbeam_connect_granted' => '', + // Which of this site's settings Connect filled in for the owner, so + // that disconnecting can put back exactly what it changed and not one + // thing more. Anything the owner has since saved by hand comes off + // the list: it is theirs now. + 'sendbeam_connect_filled' => array(), + // Site email was approved at consent time but held back because the + // sending domain was not verified yet. The domain check switches it + // on and clears this; turning site email off by hand clears it too, + // so a later check never re-enables something deliberately switched + // off. + 'sendbeam_mail_deferred' => 0, ); } diff --git a/includes/list-tables.php b/includes/list-tables.php new file mode 100644 index 0000000..13be18d --- /dev/null +++ b/includes/list-tables.php @@ -0,0 +1,132 @@ +` by hand: no search, no + * pagination, no bulk actions, no empty state, and — the part that mattered + * most on a phone — none of core's column collapsing, so the Forms and Site + * email screens were the two that scrolled sideways. + * + * `WP_List_Table` is marked `@access private` in core, which every plugin that + * has a list ignores, because there is no public alternative and core's own + * screens are the convention people expect. The risk is a core change to the + * class; the mitigation is that these subclasses override only the documented + * extension points (`get_columns`, `prepare_items`, `column_*`, + * `get_bulk_actions`, `no_items`) and nothing else. + * + * @package SendBeam + */ + +defined( 'ABSPATH' ) || exit; + +add_filter( 'set-screen-option', 'sendbeam_set_screen_option', 10, 3 ); +add_action( 'admin_head', 'sendbeam_list_table_columns' ); + +/** + * Load core's WP_List_Table, and then this plugin's three subclasses. + * + * Both halves have to happen here rather than at the top of the file. + * `WP_List_Table` lives in wp-admin/includes and is not loaded when plugins + * are, so a subclass declared at plugin-load time is a fatal error on every + * page of the site. Requiring the subclasses only once core's class is in + * memory is the whole of the fix — and it is why this is a function a screen + * calls rather than three requires in sendbeam.php. + * + * @return bool Whether the list tables are available. + */ +function sendbeam_load_list_table() { + if ( ! class_exists( 'WP_List_Table' ) && defined( 'ABSPATH' ) && file_exists( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; + } + if ( ! class_exists( 'WP_List_Table' ) ) { + return false; + } + // One class per file, because that is what the WordPress standard asks + // for and what the plugin review tooling checks. + require_once __DIR__ . '/class-sendbeam-forms-table.php'; + require_once __DIR__ . '/class-sendbeam-mail-log-table.php'; + require_once __DIR__ . '/class-sendbeam-lists-table.php'; + return true; +} + +/** + * Keep the per-page choice the Screen Options tab offers. + * + * Without this filter WordPress throws the value away on save and the box + * silently snaps back to the default, which reads as a broken control. + * + * @param mixed $status Whatever an earlier filter decided. + * @param string $option The option being saved. + * @param mixed $value The value chosen. + * @return mixed + */ +function sendbeam_set_screen_option( $status, $option, $value ) { + if ( in_array( $option, array( 'sendbeam_forms_per_page', 'sendbeam_mail_log_per_page', 'sendbeam_lists_per_page' ), true ) ) { + return max( 1, min( 200, (int) $value ) ); + } + return $status; +} + +/** + * Register the per-page screen option for a list screen. + * + * Called from `load-`, which is the only point late enough for + * `get_current_screen()` to exist and early enough for Screen Options to be + * rendered with it. + * + * @param string $option Option name. + * @param string $label Label on the Screen Options tab. + * @param int $default Rows per page out of the box. + */ +function sendbeam_add_per_page_option( $option, $label, $default = 20 ) { + if ( ! function_exists( 'add_screen_option' ) ) { + return; + } + add_screen_option( + 'per_page', + array( + 'label' => $label, + 'default' => $default, + 'option' => $option, + ) + ); +} + +/** + * How many rows this screen shows. + * + * @param string $option Option name. + * @param int $default Fallback. + * @return int + */ +function sendbeam_per_page( $option, $default = 20 ) { + $user = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; + $per = $user ? get_user_meta( $user, $option, true ) : ''; + $per = '' === $per ? 0 : (int) $per; + return $per > 0 ? $per : $default; +} + +/** + * The search term for a list screen. + * + * @return string + */ +function sendbeam_list_search() { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a search box is a GET form; core's own list tables read `s` the same way. + return isset( $_REQUEST['s'] ) ? trim( sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) ) : ''; +} + +/** + * Give core the column widths it needs to collapse a row on a phone. + * + * Core's responsive list table hides every column but the primary one behind + * a toggle, and works out which is primary from `get_primary_column_name()`. + * Nothing else is needed — this only pins the checkbox column, which core + * otherwise lets stretch. + */ +function sendbeam_list_table_columns() { + if ( ! sendbeam_is_our_screen() ) { + return; + } + echo ''; +} diff --git a/includes/mail-log.php b/includes/mail-log.php new file mode 100644 index 0000000..ad9eba0 --- /dev/null +++ b/includes/mail-log.php @@ -0,0 +1,516 @@ +prefix` is per-site on multisite, so each site in a network keeps + * its own log — which is what a network administrator would expect, since + * each site has its own key, workspace and sending domain. + * + * @return string + */ +function sendbeam_mail_log_table() { + global $wpdb; + return $wpdb->prefix . 'sendbeam_mail_log'; +} + +/** + * The same name, backticked, for the statements that interpolate it. + * + * A table name cannot be a placeholder before WordPress 6.2's `%i`, and this + * plugin supports 6.1. Nothing about the name comes from anywhere a request + * could reach — it is `$wpdb->prefix` and a literal — but escaping it anyway + * means a reviewer does not have to take that on trust, and the review + * tooling does not have to either. + * + * @return string + */ +function sendbeam_mail_log_table_sql() { + return '`' . str_replace( '`', '``', sendbeam_mail_log_table() ) . '`'; +} + +/** + * Is the table there to be read? + * + * Every read goes through this. A screen that queries a table an upgrade has + * not created yet is a database error printed into wp-admin. + * + * @return bool + */ +function sendbeam_mail_log_ready() { + global $wpdb; + return isset( $wpdb ) && is_object( $wpdb ) && method_exists( $wpdb, 'get_results' ); +} + +/** + * Create or update the table. + * + * The SQL is written the way dbDelta insists on and not one character + * otherwise: two spaces after PRIMARY KEY, one field per line, lower-case + * types, and KEY names that match what it finds. Getting any of that wrong + * makes it silently try to add a column that already exists, on every load. + */ +function sendbeam_mail_log_install() { + global $wpdb; + if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_charset_collate' ) ) { + return; + } + + $table = sendbeam_mail_log_table(); + $collate = $wpdb->get_charset_collate(); + + // dbDelta parses the name itself, so this one is the bare form. + $sql = "CREATE TABLE {$table} ( + id bigint(20) unsigned NOT NULL AUTO_INCREMENT, + sent_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + to_addr varchar(255) NOT NULL DEFAULT '', + subject text NOT NULL, + result varchar(16) NOT NULL DEFAULT '', + note text NOT NULL, + source varchar(64) NOT NULL DEFAULT '', + PRIMARY KEY (id), + KEY sent_at (sent_at), + KEY result (result) + ) {$collate};"; + + if ( ! function_exists( 'dbDelta' ) && defined( 'ABSPATH' ) && file_exists( ABSPATH . 'wp-admin/includes/upgrade.php' ) ) { + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + } + if ( function_exists( 'dbDelta' ) ) { + dbDelta( $sql ); + } + + update_option( 'sendbeam_db_version', SENDBEAM_DB_VERSION, false ); +} + +/** + * Run the install when the stored version is behind, and not otherwise. + * + * On `admin_init` rather than on activation alone: a plugin updated by + * uploading a zip over the top, or by WP-CLI, never fires an activation hook, + * and a site whose table was never created would otherwise just fail quietly + * on every send. + */ +function sendbeam_mail_log_maybe_upgrade() { + if ( (int) get_option( 'sendbeam_db_version' ) === SENDBEAM_DB_VERSION ) { + return; + } + sendbeam_mail_log_install(); + sendbeam_mail_log_migrate(); + + /* + * And the tidy-up, here as well as on activation: a plugin updated by + * uploading a zip over the top fires no activation hook, so a site that + * upgraded that way would keep a log for ever with nothing pruning it. + */ + sendbeam_mail_log_schedule_prune(); +} + +/** + * Move the twenty rows the option holds into the table, once. + * + * Idempotent by construction: the option is deleted as part of the move, so + * a second run has nothing to find. Timestamps are preserved — a log that + * says every message arrived at the moment of the upgrade is worse than no + * log at all. + */ +function sendbeam_mail_log_migrate() { + $log = get_option( 'sendbeam_mail_log' ); + if ( ! is_array( $log ) ) { + delete_option( 'sendbeam_mail_log' ); + return 0; + } + + $moved = 0; + // Oldest first, so the table's ids run the same way its timestamps do. + foreach ( array_reverse( $log ) as $row ) { + if ( ! is_array( $row ) ) { + continue; + } + $moved += sendbeam_mail_log_insert( + isset( $row['to'] ) ? $row['to'] : '', + isset( $row['subject'] ) ? $row['subject'] : '', + isset( $row['result'] ) ? $row['result'] : 'failed', + isset( $row['note'] ) ? $row['note'] : '', + '', + isset( $row['at'] ) ? (int) $row['at'] : 0 + ) ? 1 : 0; + } + + delete_option( 'sendbeam_mail_log' ); + return $moved; +} + +/** + * Record one attempt. + * + * @param string|string[] $to Recipient(s). + * @param string $subject Subject. + * @param string $result 'sent', 'fallback' or 'failed'. + * @param string $note Error or reason. + * @param string $source What asked for the send, when it is knowable. + * @param int $at Unix timestamp; now when omitted. + * @return bool + */ +function sendbeam_mail_log_insert( $to, $subject, $result, $note = '', $source = '', $at = 0 ) { + global $wpdb; + if ( ! sendbeam_mail_log_ready() || ! method_exists( $wpdb, 'insert' ) ) { + return false; + } + + $allowed = array( 'sent', 'fallback', 'failed' ); + $result = in_array( $result, $allowed, true ) ? $result : 'failed'; + $at = $at > 0 ? $at : time(); + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table; $wpdb->insert prepares every value, and a log write is not a thing to cache. + $ok = $wpdb->insert( + sendbeam_mail_log_table(), + array( + 'sent_at' => gmdate( 'Y-m-d H:i:s', $at ), + 'to_addr' => mb_substr( is_array( $to ) ? implode( ', ', $to ) : (string) $to, 0, 255 ), + 'subject' => (string) $subject, + 'result' => $result, + 'note' => (string) $note, + 'source' => mb_substr( (string) $source, 0, 64 ), + ), + array( '%s', '%s', '%s', '%s', '%s', '%s' ) + ); + + return false !== $ok; +} + +/** + * The `WHERE` a search and a view add up to, ready for prepare(). + * + * @param string $search Search term. + * @param string $view One of the result values, or '' for all. + * @return array{sql:string,args:array} + */ +function sendbeam_mail_log_where( $search = '', $view = '' ) { + global $wpdb; + $where = array( '1=1' ); + $args = array(); + + if ( '' !== $view && in_array( $view, array( 'sent', 'fallback', 'failed' ), true ) ) { + $where[] = 'result = %s'; + $args[] = $view; + } + if ( '' !== $search && method_exists( $wpdb, 'esc_like' ) ) { + $like = '%' . $wpdb->esc_like( $search ) . '%'; + $where[] = '( to_addr LIKE %s OR subject LIKE %s OR note LIKE %s )'; + $args[] = $like; + $args[] = $like; + $args[] = $like; + } + + return array( + 'sql' => implode( ' AND ', $where ), + 'args' => $args, + ); +} + +/** + * A page of the log. + * + * @param array $args search, view, orderby, order, per_page, page. + * @return array{rows:array,total:int} + */ +function sendbeam_mail_log_query( $args = array() ) { + global $wpdb; + $empty = array( + 'rows' => array(), + 'total' => 0, + ); + if ( ! sendbeam_mail_log_ready() ) { + return $empty; + } + + $args = array_merge( + array( + 'search' => '', + 'view' => '', + 'orderby' => 'sent_at', + 'order' => 'DESC', + 'per_page' => 20, + 'page' => 1, + ), + $args + ); + + // Neither of these may come from the request without passing through a + // list this file owns: they are the two parts of a query that cannot be + // a placeholder. + $orderby = in_array( $args['orderby'], array( 'sent_at', 'result' ), true ) ? $args['orderby'] : 'sent_at'; + $order = 'ASC' === strtoupper( (string) $args['order'] ) ? 'ASC' : 'DESC'; + + $per_page = max( 1, min( 500, (int) $args['per_page'] ) ); + $offset = max( 0, ( max( 1, (int) $args['page'] ) - 1 ) * $per_page ); + $table = sendbeam_mail_log_table_sql(); + $where = sendbeam_mail_log_where( $args['search'], $args['view'] ); + + /* + * Both statements are built the same way: a table name taken from + * $wpdb->prefix, an ORDER BY from the two allow-lists above, and every + * value a placeholder filled by prepare(). Neither the table nor the + * order column can be a placeholder — `%i` would do it, but that is + * WordPress 6.2 and this plugin supports 6.1. + * + * A count with nothing to filter by has no values at all, and + * $wpdb->prepare() refuses a statement with no placeholders, so that one + * branch runs the literal. + */ + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- as above; the only interpolations are the escaped table name and a WHERE of literal placeholders. + $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where['sql']}"; + if ( $where['args'] ) { + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- see the block comment above: the only interpolations are the plugin's own table name and a WHERE of literal placeholders. + $count_sql = $wpdb->prepare( $count_sql, $where['args'] ); + } + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- as above; an admin screen reading its own log has nothing to cache. + $total = (int) $wpdb->get_var( $count_sql ); + + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- see the block comment above: the table name is backtick-escaped and the two ORDER BY fragments come from the allow-lists a dozen lines up. + $select = "SELECT * FROM {$table} WHERE {$where['sql']} ORDER BY {$orderby} {$order}, id {$order} LIMIT %d OFFSET %d"; + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- every value in it is a placeholder, filled here. + $rows_sql = $wpdb->prepare( $select, array_merge( $where['args'], array( $per_page, $offset ) ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- as above. + $rows = $wpdb->get_results( $rows_sql, ARRAY_A ); + + return array( + 'rows' => is_array( $rows ) ? $rows : array(), + 'total' => $total, + ); +} + +/** + * How many of each result there are, for the view links. + * + * @return array{all:int,sent:int,fallback:int,failed:int} + */ +function sendbeam_mail_log_counts() { + global $wpdb; + $counts = array( + 'all' => 0, + 'sent' => 0, + 'fallback' => 0, + 'failed' => 0, + ); + if ( ! sendbeam_mail_log_ready() ) { + return $counts; + } + + $table = sendbeam_mail_log_table_sql(); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the plugin's own table, backtick-escaped above; no user input reaches this statement. + $rows = $wpdb->get_results( "SELECT result, COUNT(*) AS n FROM {$table} GROUP BY result", ARRAY_A ); + + foreach ( (array) $rows as $row ) { + $key = isset( $row['result'] ) ? (string) $row['result'] : ''; + if ( isset( $counts[ $key ] ) ) { + $counts[ $key ] = (int) $row['n']; + } + $counts['all'] += (int) $row['n']; + } + return $counts; +} + +/** + * The newest few, for the Overview. + * + * @param int $limit How many. + * @return array> + */ +function sendbeam_mail_log_recent( $limit = 5 ) { + $page = sendbeam_mail_log_query( + array( + 'per_page' => max( 1, (int) $limit ), + 'page' => 1, + ) + ); + return $page['rows']; +} + +/** + * A row's Unix timestamp, from the UTC datetime it is stored as. + * + * Stored in UTC so the log does not move when a site changes timezone; + * rendered in the site's own timezone by wp_date(), which is what somebody + * comparing it against "when did that order come in" needs. + * + * @param array $row A log row. + * @return int + */ +function sendbeam_mail_log_stamp( $row ) { + if ( isset( $row['sent_at'] ) && '' !== $row['sent_at'] ) { + $at = strtotime( $row['sent_at'] . ' UTC' ); + if ( $at ) { + return (int) $at; + } + } + return isset( $row['at'] ) ? (int) $row['at'] : 0; +} + +/** + * Delete the rows somebody ticked. + * + * @param int[] $ids Row ids. + * @return int How many went. + */ +function sendbeam_mail_log_delete( $ids ) { + global $wpdb; + $ids = array_values( array_filter( array_map( 'absint', (array) $ids ) ) ); + if ( ! $ids || ! sendbeam_mail_log_ready() ) { + return 0; + } + + $table = sendbeam_mail_log_table_sql(); + $in = implode( ', ', array_fill( 0, count( $ids ), '%d' ) ); + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the table is backtick-escaped above and {$in} is a run of %d placeholders built here, which the sniff cannot see; every id goes through prepare(). + $sql = $wpdb->prepare( "DELETE FROM {$table} WHERE id IN ( {$in} )", $ids ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- prepared immediately above; deleting the plugin's own log rows has nothing to cache. + return (int) $wpdb->query( $sql ); +} + +/** + * Empty the log. + * + * @return int How many went. + */ +function sendbeam_mail_log_clear() { + global $wpdb; + if ( ! sendbeam_mail_log_ready() || ! method_exists( $wpdb, 'query' ) ) { + return 0; + } + $table = sendbeam_mail_log_table_sql(); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the plugin's own table, backtick-escaped above. DELETE rather than TRUNCATE so the row count comes back. + return (int) $wpdb->query( "DELETE FROM {$table}" ); +} + +/** + * How long this site keeps its log, in days. Zero means for ever. + * + * @return int + */ +function sendbeam_mail_log_days() { + $settings = sendbeam_settings(); + $days = (int) $settings['mail_log_days']; + return in_array( $days, array( 0, 7, 30, 90 ), true ) ? $days : 30; +} + +/** + * The choices, in the order they are offered. + * + * @return array + */ +function sendbeam_mail_log_retentions() { + return array( + 7 => __( '7 days', 'sendbeam' ), + 30 => __( '30 days', 'sendbeam' ), + 90 => __( '90 days', 'sendbeam' ), + 0 => __( 'For ever', 'sendbeam' ), + ); +} + +/** + * The daily tidy-up: anything past its date, then anything past the ceiling. + * + * Both halves matter. The setting is what the owner asked for; the cap is + * what stops "for ever" meaning "until the disk fills", on hosting that is + * very often not theirs. + * + * @return int How many rows went. + */ +function sendbeam_mail_log_prune() { + global $wpdb; + if ( ! sendbeam_mail_log_ready() || ! method_exists( $wpdb, 'query' ) ) { + return 0; + } + + $table = sendbeam_mail_log_table_sql(); + $gone = 0; + $days = sendbeam_mail_log_days(); + + if ( $days > 0 ) { + $cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- the plugin's own table, backtick-escaped above; the cutoff goes through prepare(). + $gone += (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE sent_at < %s", $cutoff ) ); + } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- as above; no user input reaches this statement. + $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); + if ( $total > SENDBEAM_MAIL_LOG_MAX ) { + // Oldest first, and by id after the timestamp so two messages in the + // same second still have an order to be deleted in. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- as above; the limit goes through prepare(). + $gone += (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} ORDER BY sent_at ASC, id ASC LIMIT %d", $total - SENDBEAM_MAIL_LOG_MAX ) ); + } + + return $gone; +} + +/** Start the daily tidy-up. */ +function sendbeam_mail_log_schedule_prune() { + if ( ! wp_next_scheduled( SENDBEAM_PRUNE_HOOK ) ) { + wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', SENDBEAM_PRUNE_HOOK ); + } +} + +/** Stop it. A deactivated plugin that leaves a cron behind is a site doing work nobody can see. */ +function sendbeam_mail_log_unschedule_prune() { + wp_clear_scheduled_hook( SENDBEAM_PRUNE_HOOK ); +} + +/** + * "Clear the log" — everything, on purpose, confirmed first. + */ +function sendbeam_handle_clear_log() { + 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_clear_log' ); + + $gone = sendbeam_mail_log_clear(); + + wp_safe_redirect( add_query_arg( 'sendbeam_log_cleared', max( 0, $gone ), sendbeam_tab_url( 'mail' ) ) ); + exit; +} diff --git a/includes/mail.php b/includes/mail.php index d98c98f..a084acf 100644 --- a/includes/mail.php +++ b/includes/mail.php @@ -18,9 +18,6 @@ add_filter( 'pre_wp_mail', 'sendbeam_pre_wp_mail', 10, 2 ); add_action( 'admin_post_sendbeam_test_mail', 'sendbeam_handle_test_mail' ); -/** How many results to keep for the settings page. */ -const SENDBEAM_MAIL_LOG_SIZE = 20; - /** * The API key: the wp-config.php constant wins over the saved setting, so a * key never has to live in the database. @@ -45,6 +42,29 @@ function sendbeam_mail_enabled() { return ! empty( $settings['mail_enabled'] ) && '' !== sendbeam_api_key(); } +/** + * Why site email is not running, in one word. + * + * The setting and the ability are two different things, and every screen that + * conflated them said something untrue about the other. A site that + * disconnects keeps `mail_enabled = 1` — which is right, because reconnecting + * should not make the owner find the switch again — and with no key + * sendbeam_pre_wp_mail() never short-circuits, so every message goes out the + * server's own mailer exactly as it did before the plugin was installed. + * Nothing is broken; the screens simply have to say which of the two is + * missing rather than blaming the one that is not. + * + * @return string '' when it is running, 'off' when the box is unticked, + * 'no_key' when it is ticked with no key to send with. + */ +function sendbeam_mail_blocked() { + $settings = sendbeam_settings(); + if ( empty( $settings['mail_enabled'] ) ) { + return 'off'; + } + return '' === sendbeam_api_key() ? 'no_key' : ''; +} + /** * Turn wp_mail()'s headers (string or array) into what the API wants. * @@ -233,29 +253,60 @@ function sendbeam_api_send( $body ) { } /** - * Remember the outcome for the settings page (last few only). + * Remember the outcome. + * + * A thin wrapper over the table, kept because every caller in the plugin + * already speaks this shape and because "what asked for this send" is worked + * out here rather than at each of them. + * + * @param string|string[] $to Recipient(s). + * @param string $subject Subject. + * @param string $result 'sent', 'fallback' or 'failed'. + * @param string $note Error or reason. + * @param string $source What asked for it; worked out when omitted. + */ +function sendbeam_mail_log( $to, $subject, $result, $note = '', $source = null ) { + sendbeam_mail_log_insert( $to, $subject, $result, $note, null === $source ? sendbeam_mail_source() : $source ); +} + +/** + * Which plugin or part of WordPress asked for this message. + * + * Worth knowing and impossible to ask for directly: `wp_mail()` takes no + * caller. The backtrace is the only place the answer exists, and it is read + * once per send, only for the log, and never for a decision. + * + * The sentinel for "core itself" is `wp-core` rather than the product's name, + * because the coding standard's own auto-fixer rewrites that word wherever it + * finds it — including inside a string that is a stored value, which turns a + * sentinel the screen matches on into one it does not. * - * @param string $to Recipient(s). - * @param string $subject Subject. - * @param string $result 'sent', 'fallback' or 'failed'. - * @param string $note Error or reason. + * @return string A plugin folder name, 'wp-core', or '' when it cannot be told. */ -function sendbeam_mail_log( $to, $subject, $result, $note = '' ) { - $log = get_option( 'sendbeam_mail_log', array() ); - if ( ! is_array( $log ) ) { - $log = array(); +function sendbeam_mail_source() { + if ( ! function_exists( 'debug_backtrace' ) ) { + return ''; } - array_unshift( - $log, - array( - 'at' => time(), - 'to' => is_array( $to ) ? implode( ', ', $to ) : (string) $to, - 'subject' => (string) $subject, - 'result' => $result, - 'note' => (string) $note, - ) - ); - update_option( 'sendbeam_mail_log', array_slice( $log, 0, SENDBEAM_MAIL_LOG_SIZE ), false ); + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- the only way to name the caller of wp_mail(), which takes none; used for one log column and never for a decision. + $frames = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 12 ); + $plugins = defined( 'WP_PLUGIN_DIR' ) ? wp_normalize_path( WP_PLUGIN_DIR ) : ''; + + foreach ( (array) $frames as $frame ) { + if ( empty( $frame['file'] ) ) { + continue; + } + $file = wp_normalize_path( $frame['file'] ); + if ( '' !== $plugins && 0 === strpos( $file, $plugins . '/' ) ) { + $rest = substr( $file, strlen( $plugins ) + 1 ); + $slug = strtok( $rest, '/' ); + // This plugin asking on somebody else's behalf is not an answer. + if ( 'sendbeam' !== $slug && false !== $slug ) { + return (string) $slug; + } + } + } + + return 'wp-core'; } /** @@ -296,39 +347,746 @@ function sendbeam_pre_wp_mail( $short_circuit, $atts ) { return false; } +/** + * What the site owner should know about the connection, at the moment of asking. + * + * Gathered once and used three times: the body of the test email, the note on + * the in-page result, and — when the send fails — the bundle the failure card + * offers to copy. Collecting it at the moment of the send rather than at + * render time is the whole point: a support request that describes the state + * of the site half an hour later describes a different site. + * + * Every row that can mislead is qualified. "From address + * ws-…@post.sendbeam.io" two rows above "Sending domain harbourlane.co.uk — + * verified" told a reader their domain was verified *and in use* when only + * the first half was true, under a headline saying the site could send. + * + * @param array|null $status Normalised Connect status, fetched if omitted. + * @return array + */ +function sendbeam_mail_facts( $status = null ) { + $settings = sendbeam_settings(); + if ( ! is_array( $status ) ) { + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + } + $sender = sendbeam_effective_sender( $status ); + $domain = $status['domain']; + + $from_name = '' !== (string) $settings['mail_from_name'] ? (string) $settings['mail_from_name'] : (string) $status['sender']['from_name']; + + $rows = array( + __( 'Site', 'sendbeam' ) => get_bloginfo( 'name' ) . ' — ' . home_url(), + ); + + if ( 'none' === $sender['kind'] ) { + $rows[ __( 'From address', 'sendbeam' ) ] = __( 'Your workspace sender — this site has not set one of its own', 'sendbeam' ); + } else { + $rows[ __( 'From name', 'sendbeam' ) ] = '' !== $from_name ? $from_name : __( 'the workspace sender', 'sendbeam' ); + $rows[ __( 'From address', 'sendbeam' ) ] = sendbeam_from_address_row( $sender ); + // So a reader can compare this with the sending-domain row at a + // glance: this is the domain that actually authenticated the message, + // which is not the one the site asked for when SendBeam substituted + // its own sender. Telling somebody their domain signed a message it + // took no part in is the one thing a test email must never do. + $rows[ __( 'Signed by', 'sendbeam' ) ] = '' !== $sender['signed'] ? $sender['signed'] : __( 'not reported', 'sendbeam' ); + } + + $rows[ __( 'Sending domain', 'sendbeam' ) ] = sendbeam_sending_domain_row( $sender, $domain ); + $rows[ __( 'Workspace', 'sendbeam' ) ] = '' !== (string) $status['workspace']['name'] ? (string) $status['workspace']['name'] : __( 'not reported', 'sendbeam' ); + $rows[ __( 'Sent', 'sendbeam' ) ] = wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ); + $rows[ __( 'Plugin', 'sendbeam' ) ] = 'SendBeam ' . SENDBEAM_VERSION; + + return $rows; +} + +/** + * The From address, and what kind of address it is. + * + * @param array $sender From sendbeam_effective_sender(). + * @return string + */ +function sendbeam_from_address_row( $sender ) { + if ( 'own_domain' === $sender['kind'] ) { + return $sender['email']; + } + if ( 'shared' === $sender['kind'] ) { + /* translators: %s: the From address */ + return sprintf( __( '%s — SendBeam\'s shared address, not your domain', 'sendbeam' ), $sender['email'] ); + } + if ( 'other' === $sender['kind'] ) { + if ( ! empty( $sender['substituted'] ) ) { + return sprintf( + /* translators: 1: the From address this site asked for, 2: its domain, 3: the address SendBeam used instead */ + __( '%1$s was asked for, but %2$s is not a domain verified in this workspace, so SendBeam sent this as %3$s', 'sendbeam' ), + $sender['email'], + $sender['host'], + $sender['used'] + ); + } + return sprintf( + /* translators: 1: the From address, 2: its domain */ + __( '%1$s — %2$s is not a domain verified in this workspace', 'sendbeam' ), + $sender['email'], + $sender['host'] + ); + } + return __( 'the workspace sender', 'sendbeam' ); +} + +/** + * The sending domain, and whether this message actually used it. + * + * @param array $sender From sendbeam_effective_sender(). + * @param array $domain The domain from the status body. + * @return string + */ +function sendbeam_sending_domain_row( $sender, $domain ) { + $name = (string) $domain['name']; + if ( '' === $name ) { + return __( 'None set up', 'sendbeam' ); + } + if ( empty( $domain['verified'] ) ) { + /* translators: %s: the sending domain */ + return sprintf( __( '%s — not verified yet', 'sendbeam' ), $name ); + } + if ( 'own_domain' === $sender['kind'] ) { + /* translators: %s: the sending domain */ + return sprintf( __( '%s — verified and in use', 'sendbeam' ), $name ); + } + /* translators: %s: the sending domain */ + return sprintf( __( '%s — verified, but not in use yet', 'sendbeam' ), $name ); +} + +/** + * The one line at the top of the test email. + * + * @param array $sender From sendbeam_effective_sender(). + * @return string + */ +function sendbeam_test_mail_headline( $sender ) { + if ( 'own_domain' === $sender['kind'] ) { + return sprintf( + /* translators: %s: the sending domain */ + __( 'Your site can send email through SendBeam from %s', 'sendbeam' ), + $sender['host'] + ); + } + if ( 'shared' === $sender['kind'] ) { + return __( 'Your site can send email through SendBeam (from the shared address for now)', 'sendbeam' ); + } + return __( 'Your site can send email through SendBeam', 'sendbeam' ); +} + +/** + * What to do next, when there is something. + * + * A message that arrives is not the same as a message that arrives from you, + * and this is the difference between the two said in one block. + * + * @param array $sender From sendbeam_effective_sender(). + * @param array|null $status Normalised Connect status, for the domain. + * @return array{title:string,text:string,label:string,url:string}|null + */ +function sendbeam_test_mail_next_step( $sender, $status = null ) { + if ( 'own_domain' === $sender['kind'] || 'none' === $sender['kind'] ) { + return null; + } + + if ( 'other' === $sender['kind'] ) { + /* + * Not "SendBeam refuses messages from it". It does not: it accepts + * them and sends them under the workspace's own address, which is + * what the headers of this very message show. Saying otherwise in a + * message that has just arrived is the plugin contradicting the + * thing the reader is holding. + */ + return array( + 'title' => __( 'Next step', 'sendbeam' ), + 'text' => sprintf( + /* translators: 1: the From address's domain, 2: the address SendBeam used instead */ + __( '%1$s is not a domain this workspace has verified, so SendBeam sent this under its own address, %2$s, rather than yours. Change the From address to one on your verified sending domain, or verify that domain.', 'sendbeam' ), + $sender['host'], + '' !== $sender['used'] ? $sender['used'] : __( 'the workspace sender', 'sendbeam' ) + ), + 'label' => __( 'Open Site email', 'sendbeam' ), + 'url' => sendbeam_page_url( 'sendbeam-mail' ), + ); + } + + if ( ! empty( $sender['verified'] ) ) { + return array( + 'title' => __( 'Next step', 'sendbeam' ), + 'text' => sprintf( + /* translators: %s: the verified sending domain */ + __( 'Send from your own domain: open Site email in wp-admin and press Send from %s. Mail from your own domain is what mailbox providers trust.', 'sendbeam' ), + $sender['domain'] + ), + 'label' => __( 'Open Site email', 'sendbeam' ), + 'url' => sendbeam_page_url( 'sendbeam-mail' ), + ); + } + + return array( + 'title' => __( 'Next step', 'sendbeam' ), + 'text' => __( 'Add the DNS records under Settings → Sending domain so SendBeam can send as you. Until then mail goes out from the shared address on your behalf.', 'sendbeam' ), + 'label' => __( 'Open the sending domain', 'sendbeam' ), + 'url' => add_query_arg( 'tab', 'domain', sendbeam_page_url( 'sendbeam-settings' ) ), + ); +} + +/** + * The test email itself: one screenful a site owner can keep. + * + * Table-based and inline-styled, because that is still the only HTML an email + * client can be relied on to render, and with a plain-text alternative that + * says the same things — a test email that only exists as HTML proves less + * than one that proves both halves arrived. + * + * No images: the three-square mark is three table cells with a background + * colour, which needs no remote request, survives an image-blocking client + * and cannot be used to tell whether the message was opened. + * + * Dark mode is declared rather than left to a client's guess. Apple Mail + * inverts a message that says nothing, which turns the ink band into paper, + * the green check into something unreadable, and every address in the table + * into a blue auto-detected link. + * + * @param array $facts Rows from sendbeam_mail_facts(). + * @param array|null $sender From sendbeam_effective_sender(); derived if omitted. + * @param array|null $status Normalised Connect status. + * @return string + */ +function sendbeam_test_mail_html( $facts, $sender = null, $status = null ) { + if ( ! is_array( $sender ) ) { + $sender = sendbeam_effective_sender( $status ); + } + $next = sendbeam_test_mail_next_step( $sender, $status ); + + $ink = '#121212'; + $paper = '#EDEBE6'; + $rule = '#e2e0db'; + $muted = '#5c5c5c'; + + $rows = ''; + foreach ( $facts as $label => $value ) { + $rows .= '
' + . '' + . '' + . ''; + } + + $step = ''; + if ( is_array( $next ) ) { + $step = ''; + } + + $style = ' + :root{color-scheme:light dark;supported-color-schemes:light dark} + /* Apple Mail turns an address or a domain into a blue link of its own + accord; this puts the table\'s own colour back. */ + a[x-apple-data-detectors]{color:inherit!important;text-decoration:none!important; + font-size:inherit!important;font-family:inherit!important;font-weight:inherit!important;line-height:inherit!important} + @media only screen and (max-width:620px){.sb-container{width:100%!important}.sb-pad{padding:20px!important}} + /* Below 480px the label above its value, because a quarter of 380px is + not enough for "Sending domain" and the URL wrapped mid-word. */ + @media only screen and (max-width:480px){ + .sb-k,.sb-v{display:block!important;width:100%!important;border-bottom:0!important;padding-left:0!important} + .sb-k{padding-bottom:2px!important} + .sb-v{padding-top:0!important;padding-bottom:10px!important;border-bottom:1px solid ' . $rule . '!important} + }'; + + $html = '' + . '' + . '' + . '' + . '' . esc_html__( 'SendBeam test email', 'sendbeam' ) . '' + . '' + . '' + . '
' . esc_html( $label ) . '' . esc_html( $value ) . '
' + . '

' . esc_html( $next['title'] ) . '

' + . '

' . esc_html( $next['text'] ) . '

' + . '

' + . esc_html( $next['label'] ) . '

' + . '
' + . '' + + // The mark, on the ink band, as three coloured cells. + . '' + + // The verdict. + . '' + + // The facts. + . '' + + . $step + + // What happens now. + . '' + + . '
'; + + return $html; +} + +/** + * The same thing in words, for a client that will not render the HTML. + * + * @param array $facts Rows from sendbeam_mail_facts(). + * @param array|null $sender From sendbeam_effective_sender(); derived if omitted. + * @param array|null $status Normalised Connect status. + * @return string + */ +function sendbeam_test_mail_text( $facts, $sender = null, $status = null ) { + if ( ! is_array( $sender ) ) { + $sender = sendbeam_effective_sender( $status ); + } + $next = sendbeam_test_mail_next_step( $sender, $status ); + + $lines = array( + sendbeam_test_mail_headline( $sender ), + '', + __( 'This message was sent by your WordPress site, through SendBeam, using the settings below.', 'sendbeam' ), + '', + ); + foreach ( $facts as $label => $value ) { + $lines[] = $label . ': ' . $value; + } + + if ( is_array( $next ) ) { + $lines[] = ''; + $lines[] = $next['title']; + $lines[] = $next['text']; + $lines[] = $next['label'] . ': ' . $next['url']; + } + + $lines[] = ''; + $lines[] = __( 'What happens now', 'sendbeam' ); + $lines[] = __( 'Every email this site already sends goes out this way from now on: order confirmations, password resets, and comment and form notifications.', 'sendbeam' ); + $lines[] = __( 'Each one is recorded in the email log in wp-admin, with whether it was sent, fell back to the server\'s own mailer, or failed.', 'sendbeam' ); + $lines[] = ''; + $lines[] = __( 'Open the email log:', 'sendbeam' ) . ' ' . sendbeam_page_url( 'sendbeam-mail' ); + + return implode( "\n", $lines ); +} + +/** + * Everything somebody would be asked for in a support reply, in one block. + * + * Captured at the moment of failure, with the raw error, so that the person + * pasting it into an email is describing the send that went wrong rather than + * the state of the site whenever they got round to writing. + * + * @param string $error The raw error from the API. + * @param int $status HTTP status, or 0 when the request never landed. + * @return string + */ +function sendbeam_mail_error_bundle( $error, $status = 0 ) { + $lines = array( + 'SendBeam ' . SENDBEAM_VERSION, + 'WordPress ' . get_bloginfo( 'version' ), + 'PHP ' . PHP_VERSION, + 'Site: ' . home_url(), + 'Key: ' . ( '' === sendbeam_api_key() ? 'none' : ( sendbeam_key_in_config() ? 'wp-config.php constant' : 'stored in options' ) ), + ); + foreach ( sendbeam_mail_facts() as $label => $value ) { + $lines[] = $label . ': ' . $value; + } + $lines[] = 'HTTP: ' . ( $status ? (int) $status : 'no response' ); + $lines[] = 'Error: ' . $error; + + return implode( "\n", $lines ); +} + /** * "Send a test email" on the settings page. */ function sendbeam_handle_test_mail() { 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_test_mail' ); - $user = wp_get_current_user(); - $ok = false; - if ( ! sendbeam_mail_enabled() ) { - $note = __( 'Turn on "Send this site\'s email through SendBeam" and save an API key first.', 'sendbeam' ); - } else { - $result = sendbeam_api_send( + + $user = wp_get_current_user(); + $to = (string) $user->user_email; + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + $sender = sendbeam_effective_sender( $status ); + $facts = sendbeam_mail_facts( $status ); + + $blocked = sendbeam_mail_blocked(); + + // Two different reasons, and telling somebody to tick a box they have + // just ticked is a loop with no way out of it. + if ( 'no_key' === $blocked ) { + sendbeam_finish_test_mail( array( - 'to' => $user->user_email, - 'subject' => sprintf( /* translators: %s: site name */ __( 'Test email from %s via SendBeam', 'sendbeam' ), get_bloginfo( 'name' ) ), - 'text' => __( "This is a test email from your WordPress site, sent through SendBeam.\n\nIf you can read this, order confirmations, password resets and every other email this site sends will go out the same way.", 'sendbeam' ), + 'ok' => false, + 'title' => __( 'This site is not connected to SendBeam', 'sendbeam' ), + 'means' => __( 'Site email is switched on, but there is no API key to send with, so this site is still handing its email to the web server\'s own mailer. Nothing was sent.', 'sendbeam' ), + 'do' => __( 'Connect the site on the Overview, or paste a key under Settings → Advanced. The key needs the "Send site email" permission.', 'sendbeam' ), + 'to' => $to, + 'bundle' => sendbeam_mail_error_bundle( 'no API key is saved', 0 ), + 'at' => time(), ) ); - $ok = $result['ok']; - $note = $ok ? sprintf( /* translators: %s: email address */ __( 'Sent to %s.', 'sendbeam' ), $user->user_email ) : $result['error']; - sendbeam_mail_log( $user->user_email, 'Test email', $ok ? 'sent' : 'failed', $ok ? '' : $result['error'] ); } - wp_safe_redirect( - add_query_arg( + + if ( 'off' === $blocked ) { + sendbeam_finish_test_mail( array( - 'page' => 'sendbeam', - 'sendbeam_test' => $ok ? 'ok' : 'error', - 'sendbeam_note' => rawurlencode( $note ), - ), - admin_url( 'options-general.php' ) + 'ok' => false, + 'title' => __( 'Site email is not switched on yet', 'sendbeam' ), + 'means' => __( 'Nothing was sent, because this site is still handing its email to the web server\'s own mailer.', 'sendbeam' ), + 'do' => __( 'Tick "Send this site\'s email through SendBeam" above, save, and try again. It needs a working API key with the "Send site email" permission.', 'sendbeam' ), + 'to' => $to, + 'bundle' => sendbeam_mail_error_bundle( 'site email is switched off', 0 ), + 'at' => time(), + ) + ); + } + + $result = sendbeam_api_send( + array( + 'to' => $to, + 'subject' => sprintf( /* translators: %s: site name */ __( 'Test email from %s via SendBeam', 'sendbeam' ), get_bloginfo( 'name' ) ), + 'html' => sendbeam_test_mail_html( $facts, $sender, $status ), + 'text' => sendbeam_test_mail_text( $facts, $sender, $status ), ) ); + + sendbeam_mail_log( $to, __( 'Test email', 'sendbeam' ), $result['ok'] ? 'sent' : 'failed', $result['ok'] ? '' : $result['error'] ); + + if ( $result['ok'] ) { + /* + * Arrived is not the same as arrived from you. A message sent from + * SendBeam's shared address while the site's own domain sits verified + * and unused is a success with something left to do, and the card has + * to say which — WP Mail SMTP words the same case as "might have + * sent, but its deliverability should be improved". + */ + sendbeam_finish_test_mail( + array( + 'ok' => true, + 'to' => $to, + 'at' => time(), + 'sender' => $sender['kind'], + 'next' => sendbeam_test_mail_next_step( $sender, $status ), + ) + ); + } + + sendbeam_finish_test_mail( + array( + 'ok' => false, + 'title' => __( 'SendBeam would not send that message', 'sendbeam' ), + 'means' => sendbeam_test_mail_means( $result ), + 'do' => sendbeam_test_mail_advice( $result ), + 'to' => $to, + 'error' => $result['error'], + 'status' => (int) $result['status'], + // Captured now, with the answer still in hand: half an hour later + // this site may be in a different state entirely. + 'bundle' => sendbeam_mail_error_bundle( $result['error'], (int) $result['status'] ), + 'at' => time(), + ) + ); +} + +/** + * What a refusal means, in the site owner's terms rather than the API's. + * + * @param array $result From sendbeam_api_send(). + * @return string + */ +function sendbeam_test_mail_means( $result ) { + $status = (int) $result['status']; + if ( 0 === $status ) { + return __( 'This server could not reach sendbeam.io at all, so SendBeam never saw the message.', 'sendbeam' ); + } + if ( 401 === $status ) { + return __( 'SendBeam did not accept this site\'s API key.', 'sendbeam' ); + } + if ( 403 === $status ) { + return __( 'The key works, but it was not given permission to send this site\'s email, or the From address is not on a verified domain.', 'sendbeam' ); + } + if ( 429 === $status ) { + return __( 'SendBeam is rate-limiting this site, or the workspace has reached its sending limit.', 'sendbeam' ); + } + if ( $status >= 500 ) { + return __( 'SendBeam accepted the request and then failed on it. That is an error at SendBeam\'s end, not at yours.', 'sendbeam' ); + } + return __( 'SendBeam refused the message. The reason it gave is below.', 'sendbeam' ); +} + +/** + * What to do about it. + * + * @param array $result From sendbeam_api_send(). + * @return string + */ +function sendbeam_test_mail_advice( $result ) { + $status = (int) $result['status']; + if ( 0 === $status ) { + return __( 'Check that this server can make outbound HTTPS requests. A firewall, a proxy or a host that blocks outbound traffic will stop this and nothing else on the site will look wrong.', 'sendbeam' ); + } + if ( 401 === $status ) { + return __( 'Reconnect this site under Settings → Connection, or paste a fresh key under Settings → Advanced.', 'sendbeam' ); + } + if ( 403 === $status ) { + return __( 'Check the sending domain is verified under Settings → Sending domain, and that the From address above is on it. If the key is missing the permission, reconnect and tick "Send the site\'s own email".', 'sendbeam' ); + } + if ( 429 === $status ) { + return __( 'Wait a few minutes and try again. If it keeps happening, check the workspace\'s plan and usage in SendBeam.', 'sendbeam' ); + } + if ( $status >= 500 ) { + return __( 'Try again in a few minutes. If it persists, send the details below to hello@sendbeam.io.', 'sendbeam' ); + } + return __( 'Copy the details below and send them to hello@sendbeam.io — they say exactly what this site asked for and what came back.', 'sendbeam' ); +} + +/** + * Park the result where the screen can render it, and go back there. + * + * A transient rather than a query argument, because the failure card carries a + * raw error, a version list and a domain state — none of which belongs in an + * address bar, a server log or somebody's browser history. It is keyed to the + * person who pressed the button and read exactly once. + * + * @param array $outcome What happened. + */ +function sendbeam_finish_test_mail( $outcome ) { + set_transient( 'sendbeam_test_result_' . get_current_user_id(), $outcome, 5 * MINUTE_IN_SECONDS ); + wp_safe_redirect( sendbeam_tab_url( 'mail' ) . '#sendbeam-test' ); exit; } + +/** + * The result of the last test send, once. + * + * @return array|null + */ +function sendbeam_take_test_result() { + $key = 'sendbeam_test_result_' . get_current_user_id(); + $result = get_transient( $key ); + if ( ! is_array( $result ) ) { + return null; + } + delete_transient( $key ); + return $result; +} + +/** + * One answer to "what does this site actually send as?". + * + * The Overview was capable of telling a site owner two true things that added + * up to a lie: step 2 said the sending domain was verified and that email + * "will be sent from your own domain", while the From address in the site's + * own settings was still SendBeam's shared one. Both sentences were right. + * Together they were wrong, and the owner had no way to see which. + * + * So there is one function that works out the address the next message would + * go out as, and classifies it: + * + * own_domain — on the verified sending domain, which is the point of all this + * shared — on SendBeam's own host, which works but is not your domain + * other — somewhere else, which SendBeam sends under its own address + * none — nothing to say yet + * + * `kind` is what the site asked for. `used`, `signed` and `substituted` + * are what happens to the message — see the note beside them. + * + * @param array|null $status Normalised Connect status, fetched if omitted. + * @return array{email:string,host:string,kind:string,domain:string,verified:bool,used:string,signed:string,substituted:bool} + */ +function sendbeam_effective_sender( $status = null ) { + $settings = sendbeam_settings(); + if ( ! is_array( $status ) ) { + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + } + + // What sendbeam_build_mail_body() would put in From: this site's own + // setting, else the workspace sender it falls back to. + $email = trim( (string) $settings['mail_from_email'] ); + if ( '' === $email ) { + $email = trim( (string) $status['sender']['from_email'] ); + } + + $domain = (string) $status['domain']['name']; + $verified = ! empty( $status['domain']['verified'] ); + $host = ''; + if ( '' !== $email && false !== strpos( $email, '@' ) ) { + $host = strtolower( trim( substr( strrchr( $email, '@' ), 1 ) ) ); + } + + /* + * The site's own verified domain settles it first and settles it for + * good, whatever that domain happens to be a subdomain of. A customer + * sending from a `*.sendbeam.io` domain they have verified is sending + * from their own domain, not from SendBeam's shared address. + */ + $kind = 'none'; + if ( '' !== $host ) { + if ( '' !== $domain && sendbeam_host_is_within( $host, strtolower( $domain ) ) ) { + $kind = 'own_domain'; + } elseif ( sendbeam_is_shared_sender_host( $host ) ) { + $kind = 'shared'; + } else { + $kind = 'other'; + } + } + + /* + * What the site asked for is not always what leaves the building. + * SendBeam does not refuse a message whose From sits on a domain the + * workspace has not verified — it accepts it and substitutes the + * workspace's own sender, which is what the received headers of a test + * email show: From ws-…@mail.sendbeam.io, DKIM d=mail.sendbeam.io. So + * the address a reader will see, and the domain that will actually sign + * the message, are worked out here too. The requested address is used + * only when it is on the sending domain SendBeam has verified. + */ + $workspace = trim( (string) $status['sender']['from_email'] ); + $as_asked = ( 'own_domain' === $kind && $verified ) || 'shared' === $kind; + $used = ( $as_asked || '' === $workspace ) ? $email : $workspace; + $signed = ''; + if ( '' !== $used && false !== strpos( $used, '@' ) ) { + $signed = strtolower( trim( substr( strrchr( $used, '@' ), 1 ) ) ); + } + + return array( + 'email' => $email, + 'host' => $host, + 'kind' => $kind, + 'domain' => $domain, + 'verified' => $verified, + // The address the message actually goes out as, the domain that + // signs it, and whether those differ from what was asked for. + 'used' => $used, + 'signed' => $signed, + 'substituted' => ( '' !== $used && $used !== $email ), + ); +} + +/** + * Is one host that host, or under it? + * + * @param string $host Candidate. + * @param string $parent The domain it might belong to. + * @return bool + */ +function sendbeam_host_is_within( $host, $parent ) { + if ( '' === $host || '' === $parent ) { + return false; + } + if ( $host === $parent ) { + return true; + } + $suffix = '.' . $parent; + return substr( $host, -strlen( $suffix ) ) === $suffix; +} + +/** + * The platform's shared sending hosts, and only those. + * + * SendBeam sends a workspace's default mail from `post.`. An + * address there is the shared one: it works, and it is not the customer's + * domain, which is the distinction the Overview and the test email are built + * on. + * + * Derived from `sendbeam_app_url()` so a self-hosted SendBeam pointed at with + * the `sendbeam_app_url` filter recognises its own, with the published pair + * kept as a fallback for a filter pointing somewhere else entirely. + * + * @return string[] Lower-case hosts. + */ +function sendbeam_shared_sender_hosts() { + $hosts = array( 'post.sendbeam.io', 'mail.sendbeam.io' ); + + $app = strtolower( (string) wp_parse_url( sendbeam_app_url(), PHP_URL_HOST ) ); + if ( '' !== $app ) { + $hosts[] = 'post.' . $app; + $hosts[] = 'mail.' . $app; + } + + return array_values( array_unique( $hosts ) ); +} + +/** + * Is this address on one of those hosts? + * + * An exact match, never "somewhere under the app's domain". A customer whose + * site is a subdomain of SendBeam's own — which every site on the staging + * host is, and which any customer using a `*.sendbeam.io` address would be — + * was being told that their own verified domain was SendBeam's shared + * address. `post.` and `mail.` are 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 is never reached by this at + * all, because the caller settles that first. + * + * @param string $host The From address's host. + * @return bool + */ +function sendbeam_is_shared_sender_host( $host ) { + return in_array( strtolower( (string) $host ), sendbeam_shared_sender_hosts(), true ); +} + +/** + * The address this site should be sending as, once its domain is verified. + * + * The workspace's own sender when that is already on the verified domain — + * it is the address the account holder chose — and `hello@` when it + * is not, which is what SendBeam sets up at consent time anyway. + * + * @param array $status Normalised Connect status. + * @return string Empty when there is no verified domain to send from. + */ +function sendbeam_own_domain_sender( $status ) { + $domain = strtolower( (string) $status['domain']['name'] ); + if ( '' === $domain || empty( $status['domain']['verified'] ) ) { + return ''; + } + + $workspace = trim( (string) $status['sender']['from_email'] ); + if ( '' !== $workspace && false !== strpos( $workspace, '@' ) ) { + $host = strtolower( trim( substr( strrchr( $workspace, '@' ), 1 ) ) ); + if ( sendbeam_host_is_within( $host, $domain ) ) { + return $workspace; + } + } + + $candidate = 'hello@' . $domain; + return is_email( $candidate ) ? $candidate : ''; +} diff --git a/includes/menu.php b/includes/menu.php new file mode 100644 index 0000000..4f31773 --- /dev/null +++ b/includes/menu.php @@ -0,0 +1,322 @@ + + */ +function sendbeam_pages() { + return array( + 'sendbeam' => array( + 'menu' => __( 'Overview', 'sendbeam' ), + 'title' => __( 'Overview', 'sendbeam' ), + 'render' => 'sendbeam_screen_overview', + ), + 'sendbeam-forms' => array( + 'menu' => __( 'Forms', 'sendbeam' ), + 'title' => __( 'Forms', 'sendbeam' ), + 'render' => 'sendbeam_screen_forms', + 'list' => array( 'SendBeam_Forms_Table', 'sendbeam_forms_per_page', __( 'Forms per page', 'sendbeam' ) ), + ), + 'sendbeam-popups' => array( + 'menu' => __( 'Pop-ups', 'sendbeam' ), + 'title' => __( 'Pop-ups', 'sendbeam' ), + 'render' => 'sendbeam_screen_popup', + ), + 'sendbeam-audience' => array( + 'menu' => __( 'Audience', 'sendbeam' ), + 'title' => __( 'Audience', 'sendbeam' ), + 'render' => 'sendbeam_screen_audience', + 'list' => array( 'SendBeam_Lists_Table', 'sendbeam_lists_per_page', __( 'Lists per page', 'sendbeam' ) ), + ), + 'sendbeam-mail' => array( + 'menu' => __( 'Site email', 'sendbeam' ), + 'title' => __( 'Site email', 'sendbeam' ), + 'render' => 'sendbeam_screen_mail', + 'list' => array( 'SendBeam_Mail_Log_Table', 'sendbeam_mail_log_per_page', __( 'Messages per page', 'sendbeam' ) ), + ), + 'sendbeam-ecommerce' => array( + 'menu' => __( 'E-commerce', 'sendbeam' ), + 'title' => __( 'E-commerce events', 'sendbeam' ), + 'render' => 'sendbeam_screen_ecommerce', + ), + 'sendbeam-settings' => array( + 'menu' => __( 'Settings', 'sendbeam' ), + 'title' => __( 'Settings', 'sendbeam' ), + 'render' => 'sendbeam_screen_settings', + ), + 'sendbeam-help' => array( + 'menu' => __( 'Help', 'sendbeam' ), + 'title' => __( 'Help', 'sendbeam' ), + 'render' => 'sendbeam_screen_help', + ), + 'sendbeam-setup' => array( + 'menu' => __( 'Set up SendBeam', 'sendbeam' ), + 'title' => __( 'Set up SendBeam', 'sendbeam' ), + 'render' => 'sendbeam_screen_wizard', + 'hidden' => true, + ), + ); +} + +/** + * The menu mark: the three squares, in the grey wp-admin gives every other icon. + * + * A data URI rather than a dashicon, because none of the 300-odd dashicons is + * this product and a borrowed envelope is worse than a shape people already + * recognise from sendbeam.io. WordPress paints menu icons by swapping the + * whole image, so the colour is baked in at the one value core uses for a + * menu at rest; the active state is handled by opacity. + * + * @return string + */ +function sendbeam_menu_icon() { + $svg = '' + . '' + . '' + . '' + . ''; + return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- add_menu_page() takes the icon as a base64 data URI; this is not obfuscation. +} + +/** + * Register the top-level menu and one submenu per section. + */ +function sendbeam_admin_menu() { + $pages = sendbeam_pages(); + + add_menu_page( + __( 'SendBeam', 'sendbeam' ), + __( 'SendBeam', 'sendbeam' ), + 'manage_options', + SENDBEAM_MENU_SLUG, + 'sendbeam_render_admin_page', + sendbeam_menu_icon(), + 58.9 + ); + + foreach ( $pages as $slug => $page ) { + if ( ! empty( $page['hidden'] ) ) { + /* + * `options.php` as the parent is the documented way to register a + * routable page that appears in no menu, now that passing null is + * deprecated. An empty string works for the routing and then + * breaks the title: `get_admin_page_parent()` returns '', + * `get_admin_page_title()` takes its no-parent branch, finds + * nothing, and WordPress hands a null to strip_tags() — a + * deprecation notice on PHP 8 and a browser tab that reads + * "— WordPress" with nothing in front of it. + */ + $hook = add_submenu_page( 'options.php', $page['title'], $page['menu'], 'manage_options', $slug, 'sendbeam_render_admin_page' ); + } else { + $hook = add_submenu_page( + SENDBEAM_MENU_SLUG, + $page['title'], + $page['menu'], + 'manage_options', + $slug, + 'sendbeam_render_admin_page' + ); + } + if ( ! $hook ) { + continue; + } + if ( ! empty( $page['list'] ) ) { + add_action( 'load-' . $hook, 'sendbeam_load_list_screen' ); + } + } +} + +/** + * Prepare a screen that has a list on it, before anything is rendered. + * + * Three things have to happen here rather than in the screen function: + * Screen Options is built before the page body, a bulk action has to be acted + * on before the rows are read, and `WP_List_Table` wants constructing while + * `get_current_screen()` is the screen it belongs to. + */ +function sendbeam_load_list_screen() { + $pages = sendbeam_pages(); + $slug = sendbeam_current_page(); + if ( empty( $pages[ $slug ]['list'] ) || ! sendbeam_load_list_table() ) { + return; + } + list( $class, $option, $label ) = $pages[ $slug ]['list']; + + sendbeam_add_per_page_option( $option, $label ); + + $GLOBALS['sendbeam_list_table'] = new $class(); + $GLOBALS['sendbeam_list_table']->process_bulk_action(); + $GLOBALS['sendbeam_list_table']->prepare_items(); +} + +/** + * The list table this screen prepared, if it has one. + * + * @return WP_List_Table|null + */ +function sendbeam_list_table() { + return isset( $GLOBALS['sendbeam_list_table'] ) ? $GLOBALS['sendbeam_list_table'] : null; +} + +/** + * Which SendBeam page is being rendered. + * + * @return string A slug from sendbeam_pages(), defaulting to the Overview. + */ +function sendbeam_current_page() { + $pages = sendbeam_pages(); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation. + $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; + return isset( $pages[ $page ] ) ? $page : SENDBEAM_MENU_SLUG; +} + +/** + * The URL of one SendBeam page. + * + * @param string $slug Page slug. + * @return string + */ +function sendbeam_page_url( $slug ) { + return admin_url( 'admin.php?page=' . rawurlencode( $slug ) ); +} + +/** + * Is this admin screen one of ours? + * + * Screen ids are `toplevel_page_sendbeam` for the Overview and + * `sendbeam_page_` for every submenu — plus, on a translated site, + * `_page_`, which is why the slug rather than the + * prefix is what this matches on. + * + * @param string|WP_Screen|null $screen A screen, a hook suffix, or null for the current screen. + * @return bool + */ +function sendbeam_is_our_screen( $screen = null ) { + if ( null === $screen ) { + $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; + } + $id = is_object( $screen ) && isset( $screen->id ) ? (string) $screen->id : (string) $screen; + if ( '' === $id ) { + return false; + } + foreach ( array_keys( sendbeam_pages() ) as $slug ) { + $suffix = '_page_' . $slug; + if ( substr( $id, -strlen( $suffix ) ) === $suffix ) { + return true; + } + } + return false; +} + +/** + * The one router. + * + * Every page registered above points here; this decides which screen function + * runs and wraps it in the shell they all share. + */ +function sendbeam_render_admin_page() { + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + $slug = sendbeam_current_page(); + $pages = sendbeam_pages(); + $page = $pages[ $slug ]; + + // The wizard supplies its own shell: it has a progress rail where the + // other screens have a section name, and no card grid at all. + if ( 'sendbeam-setup' === $slug ) { + call_user_func( $page['render'] ); + return; + } + + ?> +
+

+ +
+ +
+
+ $value ) { + if ( in_array( $key, array( 'page', 'tab' ), true ) || ! is_scalar( $value ) ) { + continue; + } + // add_query_arg() does not encode what it is given, so anything with + // an ampersand or a space in it would split the URL in two. + $carry[ sanitize_key( $key ) ] = rawurlencode( sanitize_text_field( (string) $value ) ); + } + if ( $carry ) { + $target = add_query_arg( $carry, $target ); + } + + wp_safe_redirect( $target, 301 ); + exit; +} diff --git a/includes/notices.php b/includes/notices.php new file mode 100644 index 0000000..5e3eac8 --- /dev/null +++ b/includes/notices.php @@ -0,0 +1,161 @@ +` band somewhere in + * the middle of its own markup, which meant the answer to "did that save?" + * appeared in a different place on every screen and in the plugin's own + * styling rather than WordPress's. They are all admin notices now, in core's + * markup, above the page — which is where a person who has just pressed a + * button is looking. + * + * Two rules, both from what other plugins get wrong: + * + * - They appear only on SendBeam's own screens. The one exception is the + * setup notice, which has to be somewhere a new site owner will see it, + * and which goes away for good the first time it is dismissed. + * - Every one of them is dismissible. A notice that cannot be closed is the + * single most complained-about thing a WordPress plugin does. + * + * @package SendBeam + */ + +defined( 'ABSPATH' ) || exit; + +add_action( 'admin_notices', 'sendbeam_admin_notices' ); + +/** + * The sentence behind each query argument a handler redirects with. + * + * Every one of these arrives on a redirect this plugin issued itself, so the + * only thing read out of the URL is which of a fixed list of sentences to + * print. Nothing from the address bar is ever echoed. + * + * @return array> + */ +function sendbeam_notice_messages() { + return array( + 'sendbeam_domain' => array( + 'verified' => array( 'success', __( 'Verified. SendBeam can now send email as your domain.', 'sendbeam' ) ), + 'verified_mail' => array( 'success', __( 'Verified, and this site\'s email has been switched on — it was waiting on exactly this. Send yourself a test below.', 'sendbeam' ) ), + 'pending' => array( 'warning', __( 'Not verified yet. DNS changes can take anything from a few minutes to a day to spread; the records are below, unchanged.', 'sendbeam' ) ), + 'nodomain' => array( 'warning', __( 'There is no sending domain on this workspace yet. Add one under Sending in SendBeam.', 'sendbeam' ) ), + 'unreachable' => array( 'error', __( 'Could not ask SendBeam to check just now. Nothing was changed.', 'sendbeam' ) ), + ), + 'sendbeam_form' => array( + 'placed' => array( 'success', __( 'Noted — the form step is ticked. Say so again if you take the form off the site.', 'sendbeam' ) ), + 'unplaced' => array( 'success', __( 'The form step will look for itself again.', 'sendbeam' ) ), + ), + 'sendbeam_mail' => array( + 'on' => array( 'success', __( 'Site email is on. Password resets, receipts and notifications now go out through SendBeam.', 'sendbeam' ) ), + 'noscope' => array( 'error', __( 'This site\'s key was not given permission to send your site\'s email, so it was not switched on. Reconnect and tick that box.', 'sendbeam' ) ), + 'unverified' => array( 'error', __( 'The sending domain is not verified, so site email was not switched on. Finish step 2 first.', 'sendbeam' ) ), + ), + 'sendbeam_disconnected' => array( + 'ok' => array( 'success', __( 'Disconnected. The key was revoked in SendBeam.', 'sendbeam' ) ), + 'pasted' => array( 'success', __( 'Disconnected. The saved key was removed from this site; nothing was revoked in SendBeam, because a key you pasted may be in use somewhere else.', 'sendbeam' ) ), + 'unreachable' => array( 'warning', __( 'Disconnected, but this server could not reach SendBeam; revoke it under Settings → API keys.', 'sendbeam' ) ), + 'constant' => array( 'warning', __( 'Disconnected here, and nothing was revoked: this site sends with the key defined as SENDBEAM_API_KEY in wp-config.php, which is not the one this button issued. Remove it there, and revoke it under Settings → API keys.', 'sendbeam' ) ), + ), + 'sendbeam_sender' => array( + 'own' => array( 'success', __( 'This site now sends as your own domain. Send yourself a test to be sure.', 'sendbeam' ) ), + 'unverified' => array( 'warning', __( 'There is no verified sending domain to send from yet, so nothing was changed. Finish step 2 first.', 'sendbeam' ) ), + ), + 'sendbeam_sync_saved' => array( + '1' => array( 'success', __( 'Saved. The opt-in box is live where you asked for it.', 'sendbeam' ) ), + ), + 'sendbeam_bridges_saved' => array( + '1' => array( 'success', __( 'Saved. Those forms now send their submissions to SendBeam.', 'sendbeam' ) ), + ), + 'sendbeam_ecommerce_saved' => array( + '1' => array( 'success', __( 'Saved. The events you ticked will reach SendBeam from now on.', 'sendbeam' ) ), + ), + ); +} + +/** + * Print whatever the last button did. + */ +function sendbeam_admin_notices() { + if ( ! current_user_can( 'manage_options' ) ) { + return; + } + + if ( ! sendbeam_is_our_screen() ) { + sendbeam_setup_notice(); + return; + } + + sendbeam_dns_return_notice(); + + foreach ( sendbeam_notice_messages() as $arg => $values ) { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- chooses one of a fixed list of sentences; set by this plugin's own redirect. + $value = isset( $_GET[ $arg ] ) ? sanitize_key( wp_unslash( $_GET[ $arg ] ) ) : ''; + if ( '' === $value || ! isset( $values[ $value ] ) ) { + continue; + } + sendbeam_notice( esc_html( $values[ $value ][1] ), $values[ $value ][0] ); + } + + // Pop-ups report a count, so they cannot come out of a fixed table. + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a number this plugin put on its own redirect. + if ( isset( $_GET['sendbeam_saved'] ) ) { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- as above. + $saved = max( 0, (int) $_GET['sendbeam_saved'] ); + sendbeam_notice( + esc_html( sprintf( /* translators: %d: number of pop-ups */ _n( '%d pop-up saved.', '%d pop-ups saved.', $saved, 'sendbeam' ), $saved ) ), + 'success' + ); + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a count this plugin put on its own redirect. + if ( isset( $_GET['sendbeam_log_cleared'] ) ) { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- as above. + $cleared = max( 0, (int) $_GET['sendbeam_log_cleared'] ); + sendbeam_notice( + esc_html( sprintf( /* translators: %d: number of log rows */ _n( 'The log is empty. %d entry was deleted.', 'The log is empty. %d entries were deleted.', $cleared, 'sendbeam' ), $cleared ) ), + 'success' + ); + } + + if ( ! empty( $GLOBALS['sendbeam_deleted'] ) ) { + $gone = (int) $GLOBALS['sendbeam_deleted']; + sendbeam_notice( + esc_html( sprintf( /* translators: %d: number of log rows */ _n( '%d message removed from the log.', '%d messages removed from the log.', $gone, 'sendbeam' ), $gone ) ), + 'success' + ); + } +} + +/** + * Back from the registrar, and how it went. + * + * Not in the table above because the failure carries SendBeam's own reason + * code, and the table is fixed sentences. + */ +function sendbeam_dns_return_notice() { + $returned = sendbeam_overview_dns_return(); + if ( 'done' === $returned ) { + // Past tense on purpose: the check runs as this screen renders, so by + // the time anybody reads this the step underneath is already showing + // what it found. "Checking now…" promised a page that was about to + // change and then never changed. + sendbeam_notice( esc_html__( 'Your registrar added the records. Checked just now.', 'sendbeam' ), 'success' ); + return; + } + if ( 'error' !== $returned ) { + return; + } + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- SendBeam's own reason code, sanitised to a key and printed as words. + $reason = isset( $_GET['sb_dc_reason'] ) ? sanitize_key( wp_unslash( $_GET['sb_dc_reason'] ) ) : ''; + sendbeam_notice( + esc_html( + sprintf( + /* translators: %s: SendBeam's reason the registrar refused, e.g. "state mismatch" */ + __( 'Your registrar could not add the records (%s). Add them by hand below.', 'sendbeam' ), + '' !== $reason ? str_replace( '_', ' ', substr( $reason, 0, 60 ) ) : __( 'no reason given', 'sendbeam' ) + ) + ), + 'error' + ); +} diff --git a/includes/onboarding.php b/includes/onboarding.php index 7bc6a76..75a257e 100644 --- a/includes/onboarding.php +++ b/includes/onboarding.php @@ -19,8 +19,10 @@ defined( 'ABSPATH' ) || exit; register_activation_hook( SENDBEAM_FILE, 'sendbeam_on_activate' ); -add_action( 'admin_notices', 'sendbeam_setup_notice' ); +register_deactivation_hook( SENDBEAM_FILE, 'sendbeam_on_deactivate' ); add_action( 'admin_post_sendbeam_dismiss_setup', 'sendbeam_dismiss_setup' ); +add_action( 'admin_post_sendbeam_form_placed', 'sendbeam_handle_form_placed' ); +add_action( 'admin_post_sendbeam_hide_checklist', 'sendbeam_handle_hide_checklist' ); /** * Remember when we were switched on, so the notice can be new-install-only. @@ -30,6 +32,33 @@ function sendbeam_on_activate() { add_option( 'sendbeam_activated_at', time(), '', false ); } sendbeam_flush_cache(); + + // The log's table, and the daily tidy-up that keeps it from growing + // without limit. + sendbeam_mail_log_install(); + sendbeam_mail_log_migrate(); + sendbeam_mail_log_schedule_prune(); + + /* + * A transient rather than an option, and a short one: the redirect it + * asks for should happen on the very next admin page load or not at all. + * An activation that ends in a fatal, or a WP-CLI activation nobody is + * watching, must not leave a site that hijacks its owner's next visit to + * wp-admin half an hour later. + */ + set_transient( SENDBEAM_WIZARD_FLAG, 1, 30 ); +} + +/** + * Switched off: stop the clock. + * + * A deactivated plugin that leaves a scheduled event behind is a site making + * requests nobody can see, explain or stop from the screen they turned it off + * on. The hourly DNS re-check is the only one Connect owns. + */ +function sendbeam_on_deactivate() { + sendbeam_connect_unschedule_recheck(); + sendbeam_mail_log_unschedule_prune(); } /** @@ -42,47 +71,494 @@ function sendbeam_is_connected() { return in_array( $connection['state'], array( 'ok', 'no_scope' ), true ); } +/** + * Is a SendBeam form actually on the site? + * + * "A form is chosen in the settings" and "a visitor can see a form" are not + * the same claim, and the checklist was making the first one while sounding + * like the second. + * + * @param bool $force Skip the cache. + * @return bool + */ +function sendbeam_form_is_placed( $force = false ) { + return '' !== sendbeam_form_placement( $force ); +} + +/** + * Where the form was found, or an empty string when it was not. + * + * The first version of this read published `post_content` and nothing else, + * which is one of perhaps six places a form actually ends up. A site running + * a block theme keeps its footer in `wp_template_part`; a classic theme keeps + * it in a block widget; every page builder worth the name stores its layout + * in post meta rather than in the post. All three tick nothing, and the owner + * is left looking at an unfinished checklist beside a working form. + * + * So all of them are looked at — and, because no list of six will ever be + * seven, the owner can simply say so and be believed. + * + * One query family, answered once and cached for half a day: this drives one + * tick on one settings screen and is not worth a query per page load. + * + * @param bool $force Skip the cache. + * @return string One of manual, popup, content, template, widget, meta; empty + * when no form could be found anywhere. + */ +function sendbeam_form_placement( $force = false ) { + if ( get_option( 'sendbeam_form_placed' ) ) { + return 'manual'; + } + // A rule that is switched off, or has no form chosen, puts nothing on + // the site: the front end serves no loader at all for it. + if ( sendbeam_live_popups() ) { + return 'popup'; + } + + if ( ! $force ) { + $cached = get_transient( 'sendbeam_form_placed' ); + if ( is_string( $cached ) && '' !== $cached ) { + return 'no' === $cached ? '' : $cached; + } + } + + $found = sendbeam_find_form_placement(); + set_transient( 'sendbeam_form_placed', '' === $found ? 'no' : $found, 12 * HOUR_IN_SECONDS ); + return $found; +} + +/** + * The needles: the block, both shortcodes, and the form's own hosted URL. + * + * The URL is what a page builder or an HTML block holding an iframe contains, + * and it is the only one of the four that names a particular form. + * + * @return string[] + */ +function sendbeam_form_needles() { + $needles = array( 'wp:sendbeam/form', '[sendbeam_form', '[sendbeam_contact' ); + $settings = sendbeam_settings(); + foreach ( array( 'default_form', 'contact_form' ) as $key ) { + $id = (string) $settings[ $key ]; + if ( sendbeam_is_form_id( $id ) ) { + $needles[] = sendbeam_app_url() . '/f/' . strtolower( $id ); + } + } + return $needles; +} + +/** + * Look in all six places, cheapest first. + * + * @return string + */ +function sendbeam_find_form_placement() { + $needles = sendbeam_form_needles(); + + $widget = sendbeam_form_in_widgets( $needles ); + if ( '' !== $widget ) { + return $widget; + } + + global $wpdb; + if ( ! isset( $wpdb ) || ! is_object( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) ) { + // No database to ask (the smoke tests, WP-CLI oddities): fall back to + // what the settings say rather than claiming the step is unfinished. + $settings = sendbeam_settings(); + return ( '' !== $settings['default_form'] || '' !== $settings['contact_form'] ) ? 'content' : ''; + } + + $like = array(); + foreach ( $needles as $needle ) { + $like[] = '%' . $wpdb->esc_like( $needle ) . '%'; + } + $content_or = implode( ' OR ', array_fill( 0, count( $like ), 'post_content LIKE %s' ) ); + + // Published content, in post types a visitor can actually reach. + $types = get_post_types( array( 'public' => true ), 'names' ); + $types = array_values( array_filter( array_map( 'strval', (array) $types ) ) ); + if ( ! $types ) { + $types = array( 'post', 'page' ); + } + $type_in = implode( ', ', array_fill( 0, count( $types ), '%s' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- cached in a transient by the caller; the two interpolated fragments are runs of %s placeholders built here, so the sniff cannot see them, and every value goes through prepare(). + if ( $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ( $type_in ) AND ( $content_or ) LIMIT 1", array_merge( $types, $like ) ) ) ) { + return 'content'; + } + + // A block theme keeps the header, the footer and every page layout here. + // Templates are not "published" in the way a page is, so status is not + // part of the question. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- as above. + if ( $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'wp_template', 'wp_template_part' ) AND post_status != 'trash' AND ( $content_or ) LIMIT 1", $like ) ) ) { + return 'template'; + } + + // Page builders keep their layout beside the post, not in it. + $meta_or = implode( ' OR ', array_fill( 0, count( $like ), 'meta_value LIKE %s' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- as above. + if ( $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->postmeta} WHERE $meta_or LIMIT 1", $like ) ) ) { + return 'meta'; + } + + return ''; +} + +/** + * Block widgets, and the text widgets a sidebar actually holds. + * + * Widgets live in options rather than in posts, so no amount of looking at + * `post_content` will ever find one. A text widget that is in `widget_text` + * but in no sidebar is not on the site — it is a leftover — so the sidebars + * decide which of them count. + * + * @param string[] $needles What a placed form looks like. + * @return string 'widget', or empty. + */ +function sendbeam_form_in_widgets( $needles ) { + $haystacks = array(); + + $blocks = get_option( 'widget_block' ); + if ( is_array( $blocks ) ) { + foreach ( $blocks as $block ) { + if ( is_array( $block ) && isset( $block['content'] ) ) { + $haystacks[] = (string) $block['content']; + } + } + } + + $sidebars = get_option( 'sidebars_widgets' ); + $text = get_option( 'widget_text' ); + if ( is_array( $sidebars ) && is_array( $text ) ) { + foreach ( $sidebars as $key => $ids ) { + if ( 'wp_inactive_widgets' === $key || ! is_array( $ids ) ) { + continue; + } + foreach ( $ids as $id ) { + if ( ! is_string( $id ) || 0 !== strpos( $id, 'text-' ) ) { + continue; + } + $number = (int) substr( $id, 5 ); + if ( isset( $text[ $number ]['text'] ) ) { + $haystacks[] = (string) $text[ $number ]['text']; + } + } + } + } + + foreach ( $haystacks as $haystack ) { + foreach ( $needles as $needle ) { + if ( false !== strpos( $haystack, $needle ) ) { + return 'widget'; + } + } + } + return ''; +} + +/** + * What step 1 says. + * + * A key pinned in wp-config.php is the one this site sends with, so telling + * its owner to press a button that is deliberately not on the screen — and + * which would store a second key nothing would use — is the wrong + * instruction twice over. + * + * @param bool $connected Whether the key works. + * @return string + */ +function sendbeam_connect_step_sentence( $connected ) { + if ( $connected ) { + return __( 'Your key works.', 'sendbeam' ); + } + if ( sendbeam_key_in_config() ) { + return __( 'This site\'s key is the one in wp-config.php, and SendBeam is not answering to it. Change it there.', 'sendbeam' ); + } + return __( 'Press Connect SendBeam, approve what this site may do, and the key arrives on its own.', 'sendbeam' ); +} + +/** + * What step 2 says once there really is a sending domain. + * + * The name is always the one the answer carried, never one derived from + * site_url: the owner chooses the sending host at consent time and it is + * often not this site's domain at all. + * + * @param string $name The sending domain, from the response. + * @param bool $verified Whether SendBeam has seen its records. + * @return string + */ +function sendbeam_domain_sentence( $name, $verified ) { + if ( '' === (string) $name ) { + return sendbeam_domain_missing_sentence( null ); + } + if ( $verified ) { + /* + * What this step knows, and nothing more. It used to add "email from + * this site will be sent from your own domain", which is step 4's + * business and was a lie on every site still sending as SendBeam's + * shared address — two true sentences that added up to a wrong one. + */ + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + return sprintf( __( '%s is verified.', 'sendbeam' ), $name ); + } + /* translators: %s: the sending domain, e.g. harbourlane.co.uk */ + return sprintf( __( 'Add these records to the DNS for %s, then press Check now. Until they are in place SendBeam cannot send as you.', 'sendbeam' ), $name ); +} + +/** + * What to say when this site has no sending domain. + * + * One sentence in one place, because there were two: the Overview's said why, + * using the reason SendBeam gave, and the screen actually dedicated to the + * sending domain said only "No sending domain is set up for this site. Add + * one under Settings → Domains in SendBeam" — dropping the explanation on the + * page most likely to be read by somebody looking for it. + * + * SendBeam's own note also tends to end in an instruction, and appending ours + * after it named two different SendBeam screens in consecutive sentences. + * Where SendBeam has said what to do, that stands on its own. + * + * @param array|null $status Normalised status, fetched when omitted. + * @return string + */ +function sendbeam_domain_missing_sentence( $status = null ) { + if ( ! is_array( $status ) ) { + $status = sendbeam_is_connected() ? sendbeam_connect_status() : sendbeam_connect_empty_status(); + } + $note = isset( $status['domain_note'] ) ? trim( (string) $status['domain_note'] ) : ''; + $out = __( 'No sending domain is set up for this site.', 'sendbeam' ); + + if ( '' !== $note && sendbeam_connect_status_is_live( $status ) ) { + return $out . ' ' . rtrim( $note, '.' ) . '.'; + } + return $out . ' ' . __( 'Add one under Settings → Domains in SendBeam.', 'sendbeam' ); +} + /** * How far through setup are they? Drives the checklist on the settings page. * - * @return array + * Four steps now, not three, and the new one is second on purpose. Verifying + * the sending domain is the step every other step quietly depends on — a form + * that cannot send a confirmation email is a form that collects nothing, and + * site email through an unverified domain is worse than no site email at all + * — and it is the step a site owner cannot even start without the DNS records + * Connect has just fetched. Burying it under "optional" was the gap the owner + * found on the test site. + * + * Each step carries a `key`, and the Overview renders a panel per key. The + * old version relied on position, which meant inserting a step in the middle + * silently pointed every link after it at the wrong tab. + * + * @return array */ function sendbeam_setup_steps() { $settings = sendbeam_settings(); $connection = sendbeam_connection(); $connected = in_array( $connection['state'], array( 'ok', 'no_scope' ), true ); + $status = $connected ? sendbeam_connect_status() : sendbeam_connect_empty_status(); $using_form = '' !== $settings['default_form'] || '' !== $settings['contact_form']; - $using_popup = (bool) sendbeam_popups(); + $using_popup = (bool) sendbeam_live_popups(); $using_mail = ! empty( $settings['mail_enabled'] ); + $domain = $status['domain']; + $verified = ! empty( $domain['verified'] ); + + /* + * Everything step 2 says comes out of the answer SendBeam just gave, and + * nothing out of what this site remembers granting. The two disagree more + * often than they look like they would — a key pasted by hand has no + * recorded permissions at all, and the step used to tell those sites they + * had no permission to read a domain while printing that domain's DNS + * records directly underneath. + */ + $state = $connected ? sendbeam_connect_domain_state( $status ) : ''; + $note = isset( $status['domain_note'] ) ? trim( (string) $status['domain_note'] ) : ''; + $domain_reconnect = false; + + if ( ! $connected ) { + $domain_detail = __( 'Connect the site first and SendBeam will set the domain up and show you the records.', 'sendbeam' ); + } elseif ( 'not_granted' === $state ) { + $domain_detail = __( 'You did not allow SendBeam to set up a sending domain, so this site has none.', 'sendbeam' ); + $domain_reconnect = true; + } elseif ( 'no_permission' === $state ) { + $domain_detail = sendbeam_connected_via_connect() + ? __( 'This connection was made before domains could be read, so this site cannot see its sending domain.', 'sendbeam' ) + : __( 'The key this site is using cannot read sending domains, so this step has nothing to show.', 'sendbeam' ); + $domain_reconnect = true; + } elseif ( 'managed_host' === $state ) { + $domain_detail = '' !== $note + ? $note + : __( 'This site runs on a hosting company\'s own domain, so mail cannot be sent from it. Add a domain you own under Settings → Domains in SendBeam.', 'sendbeam' ); + } elseif ( 'unavailable' === $state ) { + /* + * Two different things wear this word. The plugin sets it when the + * request failed, and SendBeam sends it in a perfectly successful + * answer to mean "I could not set that domain up, and here is why" — + * "That domain is already registered", most often. Only the first + * reading was in the sentence, so a site that had just connected, + * and whose cached status held SendBeam's own explanation in two + * places, was told SendBeam could not be reached. + */ + if ( sendbeam_connect_status_is_live( $status ) && '' !== $note ) { + $domain_detail = rtrim( $note, '.' ) . '. ' . __( 'Add one under Settings → Domains in SendBeam, or reconnect and choose a different one.', 'sendbeam' ); + } else { + $domain_detail = __( 'SendBeam could not be reached; showing the last known state.', 'sendbeam' ); + if ( '' !== $domain['name'] ) { + $domain_detail .= ' ' . sendbeam_domain_sentence( $domain['name'], $verified ); + } + } + } elseif ( 'no_site' === $state || 'not_found' === $state ) { + $domain_detail = sendbeam_domain_missing_sentence( $status ); + + /* + * A key with no site host behind it cannot be told which domain this + * site sends from — which is precisely the thing Connect settles at + * consent time. This is where the offer belongs, and the only place + * a pasted key is actually the worse option. + */ + $domain_reconnect = ( 'no_site' === $state ); + } else { + $domain_detail = sendbeam_domain_sentence( $domain['name'], $verified ); + } + + $where = ( $using_form || $using_popup ) ? sendbeam_form_placement() : ''; + $placed = '' !== $where; + + if ( $placed ) { + $found = array( + 'manual' => __( 'You said a SendBeam form is on the site.', 'sendbeam' ), + 'popup' => __( 'A SendBeam pop-up is live on the site.', 'sendbeam' ), + 'content' => __( 'A SendBeam form is on a published page or post.', 'sendbeam' ), + 'template' => __( 'A SendBeam form is in one of the theme\'s block templates.', 'sendbeam' ), + 'widget' => __( 'A SendBeam form is in a widget.', 'sendbeam' ), + 'meta' => __( 'A SendBeam form is in a layout stored with a page — a page builder, most likely.', 'sendbeam' ), + ); + $form_detail = isset( $found[ $where ] ) ? $found[ $where ] : __( 'A SendBeam form is on the site.', 'sendbeam' ); + } elseif ( $using_form || $using_popup ) { + $form_name = '' !== $status['default_form']['name'] ? $status['default_form']['name'] : __( 'Your form', 'sendbeam' ); + /* translators: %s: the form name, e.g. Newsletter signup */ + $form_detail = sprintf( __( '%s is ready — add the SendBeam Form block to a page. In the editor press the + button and search for "SendBeam", or type /sendbeam on a new line. The shortcode [sendbeam_form] does the same anywhere shortcodes work.', 'sendbeam' ), $form_name ); + } else { + $form_detail = __( 'Choose a signup, contact or pop-up form below.', 'sendbeam' ); + } + + $mail_reconnect = false; + $mail_attention = false; + $mail_done = $using_mail; + $sender = sendbeam_effective_sender( $status ); + + if ( $using_mail && 'own_domain' === $sender['kind'] ) { + /* translators: %s: the From address, e.g. hello@harbourlane.co.uk */ + $mail_detail = sprintf( __( 'On, sending as %s. Send yourself a test to be sure.', 'sendbeam' ), $sender['email'] ); + } elseif ( $using_mail && 'shared' === $sender['kind'] && $verified ) { + /* + * The state the Overview used to describe as finished: the domain is + * verified, site email is on, and every message still goes out as + * SendBeam rather than as this site. It works — and it is not what + * the owner set the domain up for, so the step stays open and says so. + */ + $mail_detail = sprintf( + /* translators: 1: the shared From address, 2: the verified sending domain */ + __( 'On — but sending as %1$s, which is SendBeam\'s shared address, not %2$s. Your domain is verified, so it does not have to be.', 'sendbeam' ), + $sender['email'], + $domain['name'] + ); + $mail_done = false; + $mail_attention = true; + } elseif ( $using_mail && 'shared' === $sender['kind'] ) { + $mail_detail = sprintf( + /* translators: %s: the shared From address */ + __( 'On, sending as %s — SendBeam\'s shared address. Once your sending domain is verified you can send as your own.', 'sendbeam' ), + $sender['email'] + ); + } elseif ( $using_mail && 'other' === $sender['kind'] ) { + $mail_detail = sprintf( + /* translators: 1: the From address, 2: its domain */ + __( 'On, sending as %1$s — but %2$s is not a domain this workspace has verified, so SendBeam refuses these messages. Change the From address under Site email.', 'sendbeam' ), + $sender['email'], + $sender['host'] + ); + $mail_done = false; + $mail_attention = true; + } elseif ( $using_mail ) { + $mail_detail = __( 'On. Send yourself a test to be sure.', 'sendbeam' ); + } elseif ( $connected && sendbeam_connect_permissions_known() && ! sendbeam_connect_granted( 'transactional:send' ) ) { + $mail_detail = __( 'This site\'s key was not given permission to send your site\'s email. Reconnect and tick that box to use it.', 'sendbeam' ); + $mail_reconnect = true; + } elseif ( ! $verified ) { + $mail_detail = __( 'Waiting on step 2: this site\'s email can only go out once the sending domain is verified.', 'sendbeam' ); + + /* + * Step 4 is waiting on step 2, and step 2 is waiting on a permission + * nobody ticked. Sending the owner to step 2 to read that is one hop + * too many when the way out is the same link either way: this step + * offers it as well, because this is the step they came to use. + */ + $mail_reconnect = $domain_reconnect; + } else { + $mail_detail = __( 'Ready. Switch it on and password resets, receipts and notifications go out through your own domain.', 'sendbeam' ); + } + return array( array( + 'key' => 'connect', 'done' => $connected, 'label' => __( 'Connect your SendBeam account', 'sendbeam' ), - 'detail' => $connected - ? __( 'Your key works.', 'sendbeam' ) - : __( 'Paste an API key so this plugin can list your forms for you.', 'sendbeam' ), + 'detail' => sendbeam_connect_step_sentence( $connected ), + // The button, where there is one. A site whose key is pinned in + // wp-config.php has no Connect panel and no paste field either, + // so the old anchor is kept for the one screen that still has a + // key field on it: a key pasted by hand. + 'target' => sendbeam_tab_url( 'overview' ) . ( sendbeam_key_in_config() ? '#sendbeam_api_key' : '#sendbeam-connect' ), + ), + array( + 'key' => 'domain', + 'done' => $verified, + 'label' => __( 'Verify your sending domain', 'sendbeam' ), + 'detail' => $domain_detail, + + /* + * The step points at the plugin's own Sending domain screen, where + * the records live: an owner pressing it was being sent to the + * SendBeam app instead, as if the plugin could not do this. Only a + * site with no domain at all is sent to where one is added. + */ + 'target' => ! empty( $domain['name'] ) ? add_query_arg( 'tab', 'domain', sendbeam_page_url( 'sendbeam-settings' ) ) : sendbeam_app_link( '/settings/domains' ), + 'reconnect' => $domain_reconnect, ), array( - 'done' => $using_form || $using_popup, + 'key' => 'form', + 'done' => $placed, 'label' => __( 'Put a form on the site', 'sendbeam' ), - 'detail' => ( $using_form || $using_popup ) - ? __( 'A form is chosen. Add the SendBeam block to any page, or use the pop-up.', 'sendbeam' ) - : __( 'Choose a signup, contact or pop-up form below.', 'sendbeam' ), + 'detail' => $form_detail, + 'target' => sendbeam_tab_url( 'forms' ), + 'where' => $where, ), array( - 'done' => $using_mail, - 'label' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), - 'detail' => $using_mail - ? __( 'On. Send yourself a test to be sure.', 'sendbeam' ) - : __( 'Optional. Routes password resets, receipts and notifications through your verified domain.', 'sendbeam' ), + 'key' => 'mail', + 'done' => $mail_done, + 'attention' => $mail_attention, + 'label' => __( 'Send this site\'s email through SendBeam', 'sendbeam' ), + 'detail' => $mail_detail, + 'target' => sendbeam_tab_url( 'mail' ), + 'reconnect' => $mail_reconnect, ), ); } /** - * The one notice. + * The one notice, on the Dashboard, for a site that has not been set up. + * + * The Dashboard and nowhere else. A plugin that puts its own nag on every + * screen of every other plugin is the top one-star complaint in this whole + * category, and the activation redirect has already offered the wizard once + * to the person who installed this. + * + * It removes itself three ways: the site gets connected, the wizard is + * finished, or the person dismisses it — and the dismissal is per user, in + * user meta, so it stays dismissed. */ function sendbeam_setup_notice() { if ( ! current_user_can( 'manage_options' ) ) { @@ -90,32 +566,30 @@ function sendbeam_setup_notice() { } $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; - if ( $screen && 'settings_page_sendbeam' === $screen->id ) { - return; // They are already here. + if ( ! $screen || 'dashboard' !== $screen->id ) { + return; } if ( get_user_meta( get_current_user_id(), 'sendbeam_setup_dismissed', true ) ) { return; } - if ( sendbeam_is_connected() ) { + if ( sendbeam_wizard_done() || sendbeam_is_connected() ) { return; // Resolved: the notice removes itself. } - $settings_url = admin_url( 'options-general.php?page=sendbeam' ); - $dismiss_url = wp_nonce_url( admin_url( 'admin-post.php?action=sendbeam_dismiss_setup' ), 'sendbeam_dismiss_setup' ); - ?> -
-

- - -

-

- - -

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

' + . '' . esc_html__( 'Set up SendBeam', 'sendbeam' ) . ' ' + . '' . esc_html__( 'Not now', 'sendbeam' ) . ''; + + // Core button classes, deliberately: inside a core notice, a brand-styled + // button is the thing that looks out of place. + sendbeam_notice( $message, 'info' ); } /** @@ -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( '

', 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( - '
  1. %4$s%5$s
  2. ', - $step['done'] ? 'is-done' : '', - $step['done'] ? '✓' : (int) ( $i + 1 ), - esc_url( $targets[ $i ] ), - esc_html( $step['label'] ), - esc_html( $step['detail'] ) + '
  3. ', + 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 '
  4. '; } 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 '
    1. '; + echo '

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

      '; + } + + sendbeam_domain_records_table( $domain['records'] ); + + if ( $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( + '', + 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 ''; + echo ''; + echo ''; + echo ''; + echo ''; + + foreach ( $records as $i => $record ) { + $host = '' !== $record['name'] ? $record['name'] : '@'; + + /* translators: %s: a DNS record type, e.g. CNAME */ + $host_label = sprintf( __( 'Host for the %s record', 'sendbeam' ), $record['type'] ); + /* translators: %s: a DNS record type, e.g. CNAME */ + $value_label = sprintf( __( 'Value for the %s record', 'sendbeam' ), $record['type'] ); + + /* + * Every cell carries the column it belongs to. On a phone the row + * becomes a block and those labels are the only thing left saying + * which field is the host and which is the value — the header row is + * gone by then. + */ + echo ''; + printf( + '', + esc_attr__( 'Type', 'sendbeam' ), + esc_html( $record['type'] ) + ); + printf( ''; + printf( ''; + printf( ''; + echo ''; + } + echo '
    ' . esc_html__( 'Type', 'sendbeam' ) . '' . esc_html__( 'Host', 'sendbeam' ) . '' . esc_html__( 'Value', 'sendbeam' ) . '' . esc_html__( 'Found', 'sendbeam' ) . '
    %2$s', esc_attr__( 'Host', 'sendbeam' ) ); + echo sendbeam_copy_field( $host, $host_label, 'sb-dns-host-' . (int) $i ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- every value is escaped inside sendbeam_copy_field(). + echo '', esc_attr__( 'Value', 'sendbeam' ) ); + echo sendbeam_copy_field( $record['value'], $value_label, 'sb-dns-value-' . (int) $i ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- as above. + echo '', esc_attr__( 'Found', 'sendbeam' ) ); + echo sendbeam_record_verdict( isset( $record['found'] ) ? $record['found'] : null ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped inside sendbeam_record_verdict(). + 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( + '' . + '', + 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( + '', + 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( + '', + 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( '', 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( '', 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( '', 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( - '

    ', + '

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

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

    '; - } - sendbeam_card_close(); + sendbeam_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 ''; - echo ''; - echo ''; - echo ''; - foreach ( $lists as $list ) { - ?> - - - - - -
    ' . esc_html__( 'List', 'sendbeam' ) . '' . esc_html__( 'Subscribers', 'sendbeam' ) . '' . esc_html__( 'Confirmation', 'sendbeam' ) . '
    - - - - - -
    '; - } - echo '

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

    '; - sendbeam_card_close(); + sendbeam_list_card( + __( 'Lists', 'sendbeam' ), + __( 'Which list a form subscribes people to is set on the form itself, in SendBeam.', 'sendbeam' ), + __( 'Search lists', 'sendbeam' ) + ); sendbeam_screen_sync( $lists ); sendbeam_screen_form_plugins( $lists ); @@ -264,26 +1130,26 @@ function sendbeam_screen_form_plugins( $lists ) { echo '
    '; - // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- notice only. - if ( isset( $_GET['sendbeam_bridges_saved'] ) ) { - echo '

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

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

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

    '; - echo ''; + echo '
    '; echo ''; echo ''; foreach ( $rows as $key => $row ) { printf( '', esc_html( $row[0] ), - $hosts[ $key ] ? '' . esc_html__( 'Active', 'sendbeam' ) . '' : '' . esc_html__( 'Not installed', 'sendbeam' ) . '', + // "Not active", not "Not installed". The probe is for a class or + // a function, which is the right probe — but it answers "is this + // running", and a plugin sitting in wp-content/plugins waiting to + // be activated is installed. Somebody who has just installed one + // and is wondering why nothing changed needs the true word. + $hosts[ $key ] ? '' . esc_html__( 'Active', 'sendbeam' ) . '' : '' . esc_html__( 'Not active', 'sendbeam' ) . '', esc_html( $row[1] ) ); } - echo '
    ' . esc_html__( 'Form plugin', 'sendbeam' ) . '' . esc_html__( 'On this site', 'sendbeam' ) . '' . esc_html__( 'Where to set it up', 'sendbeam' ) . '
    %1$s%2$s%3$s
    '; + 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( - '

    ', + '

    ', 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( - '

    ', + '

    ', 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 '

    '; + echo '

    '; 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( - '

    %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 '

    '; + echo '

    '; echo ''; sendbeam_card_close(); $log = get_option( SENDBEAM_SYNC_LOG, array() ); if ( is_array( $log ) && $log ) { sendbeam_card_open( __( 'Recent subscriptions', 'sendbeam' ) ); - echo ''; + echo '
    '; echo ''; echo ''; echo ''; @@ -453,7 +1314,7 @@ function sendbeam_screen_sync( $lists ) { echo ''; echo ''; } - echo '
    ' . esc_html__( 'When', 'sendbeam' ) . '' . esc_html__( 'Who', 'sendbeam' ) . '' . esc_html__( 'From', 'sendbeam' ) . '' . esc_html__( 'Result', 'sendbeam' ) . '
    ' . ( $row['ok'] ? esc_html__( 'Subscribed', 'sendbeam' ) : esc_html( __( 'Failed', 'sendbeam' ) . ' — ' . $row['note'] ) ) . '
    '; + echo '
    '; sendbeam_card_close(); } } @@ -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 '

    '; + echo '

    '; 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( '', 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 ''; - echo ''; - echo ''; - foreach ( $log as $row ) { - $result = 'sent' === $row['result'] ? __( 'Sent via SendBeam', 'sendbeam' ) : ( 'fallback' === $row['result'] ? __( 'Server mailer', 'sendbeam' ) : __( 'Failed', 'sendbeam' ) ); - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - 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( '

    ', 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( + '

    ', + 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 '
    ' . esc_html__( 'When', 'sendbeam' ) . '' . esc_html__( 'To', 'sendbeam' ) . '' . esc_html__( 'Subject', 'sendbeam' ) . '' . esc_html__( 'Result', 'sendbeam' ) . '
    ' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $row['at'] ) ) . '' . esc_html( $row['to'] ) . '' . esc_html( $row['subject'] ) . '' . esc_html( $result . ( $row['note'] ? ' — ' . $row['note'] : '' ) ) . '
    '; + } +} + +/** + * 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( - '

    ', + '

    ', 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( - '

    ', + '

    ', 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( - '

    ', + '

    ', 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 '

    '; + echo '

    '; 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 ''; + echo '
    '; echo ''; echo ''; echo ''; @@ -769,12 +1855,139 @@ function sendbeam_screen_ecommerce() { echo ''; echo ''; } - echo '
    ' . esc_html__( 'When', 'sendbeam' ) . '' . esc_html__( 'Event', 'sendbeam' ) . '' . esc_html__( 'Who', 'sendbeam' ) . '' . esc_html__( 'Result', 'sendbeam' ) . '
    ' . ( $row['ok'] ? esc_html__( 'Sent', 'sendbeam' ) : esc_html( __( 'Failed', 'sendbeam' ) . ' — ' . $row['note'] ) ) . '
    '; + 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( + '

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

    %s

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

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

    '; diff --git a/includes/settings.php b/includes/settings.php index 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( - '', + '', 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 ' '; 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( + '
  • %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 '
    '; + wp_nonce_field( 'sendbeam_wizard_step' ); + echo ''; + printf( '', (int) $current ); + + printf( + '', + esc_attr( $last ? 'finish' : 'next' ), + esc_html( $last ? __( 'Finish', 'sendbeam' ) : __( 'Continue', 'sendbeam' ) ) + ); + + if ( ! $last ) { + printf( + '', + esc_html__( 'Skip this step', 'sendbeam' ) + ); + } + + printf( + '', + esc_html__( 'Go back to the Dashboard', 'sendbeam' ) + ); + echo '
    '; + echo '

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    '; + echo '

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

    '; + + sendbeam_overview_form_panel( $step, true ); +} + +/** + * 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, '', '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, '', '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 ''; } +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( + '', + esc_attr( $input_id ), + esc_attr( $text ), + esc_attr( isset( $_REQUEST['s'] ) ? $_REQUEST['s'] : '' ) + ); + } + + public function display() { + $columns = $this->get_columns(); + $primary = $this->get_primary_column_name(); + $bulk = $this->get_bulk_actions(); + + if ( $bulk ) { + echo '
    '; + wp_nonce_field( 'bulk-' . $this->_args['plural'] ); + echo '
    '; + } + + echo '
    '; + foreach ( $columns as $key => $label ) { + $class = 'manage-column column-' . $key . ( $key === $primary ? ' column-primary' : '' ); + echo ''; + } + echo ''; + if ( ! $this->items ) { + echo ''; + } + foreach ( $this->items as $item ) { + echo ''; + foreach ( $columns as $key => $label ) { + $method = 'column_' . $key; + $value = method_exists( $this, $method ) ? $this->$method( $item ) : $this->column_default( $item, $key ); + $class = 'column-' . $key . ( $key === $primary ? ' has-row-actions column-primary' : '' ); + $tag = 'cb' === $key ? 'th' : 'td'; + echo '<' . $tag . ' class="' . esc_attr( $class ) . '" data-colname="' . esc_attr( wp_strip_all_tags( $label ) ) . '">' . $value . ''; + } + echo ''; + } + echo '
    ' . $label . '
    '; + $this->no_items(); + echo '
    '; + printf( '
    %d items
    ', isset( $this->_pagination['total_items'] ) ? (int) $this->_pagination['total_items'] : 0 ); + } + + protected function column_default( $item, $column ) { + return isset( $item[ $column ] ) ? esc_html( (string) $item[ $column ] ) : ''; } +} + +function wp_strip_all_tags( $string, $remove_breaks = false ) { return strip_tags( (string) $string ); } +function add_screen_option( $option, $args = array() ) { $GLOBALS['stub']['screen_options'][ $option ] = $args; } +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(); } }