# ContactUsIQ for WordPress

Developer and AI-agent documentation for the plugin in this folder. End-user copy is in [`readme.txt`](readme.txt).

- PHP 8.1+, WordPress 6.4+, GPL-2.0-or-later, slug `contactusiq`, text domain `contactusiq`.
- No build step and no Composer: the block's editor script is plain JavaScript on the `wp.*` globals.
- Every form posts from the browser straight to `https://api.contactusiq.com/s/{formPublicId}`; nothing posts to WordPress on submit.

This README uses the placeholder form id `au_xxxxxxx` and the Turnstile site key placeholder `0x4AAAAAAA_PLACEHOLDER`.

## Layout

```
contactusiq.php                  plugin header, constants, autoloader, boot
uninstall.php                    removes options on delete
includes/class-settings.php      Settings > ContactUsIQ, Connect AJAX receiver, sanitisation
includes/class-verification.php  <meta name="contactusiq-verify"> in wp_head, "Verify now"
includes/class-shortcode.php     [contactusiq] and the shared renderer (HTML form or embed)
includes/class-block.php         registers block/ from block.json, server-rendered via the renderer
includes/class-widget.php        widget.js tag in wp_footer with data attributes
includes/class-cf7-adapter.php   Contact Form 7 -> intake URL forwarding
includes/class-health.php        Site Health test and info panel
block/block.json                 block metadata (attributes formId, mode, redirect, subject, buttonLabel)
block/edit.js                    editor script (wp.blocks, wp.element, no JSX)
block/edit.asset.php             hand-written dependency list for edit.js
block/editor.css                 editor-only styles
assets/admin.js                  Connect popup and postMessage handshake
readme.txt                       wordpress.org readme
```

Classes autoload by name: `ContactUsIQ_Foo_Bar` -> `includes/class-foo-bar.php`.

## Settings

Stored in one option, `contactusiq_settings` (array), plus `contactusiq_verification` (last verification result) and `contactusiq_last_delivery` (last server-side forward). Keys:

| Key | Type | Set by |
| --- | --- | --- |
| `api_key` | string | Connect, or pasted. Masked on display (`cuiq••••abcd`); an empty field keeps the stored key, a checkbox clears it. |
| `workspace_id`, `domain_id`, `verify_token` | string | Connect, or pasted. |
| `form_id` | string | Default form id for the block, shortcode and CF7 adapter. |
| `turnstile_site_key` | string | Added to HTML-mode forms; the Turnstile script is enqueued only when a form on the page uses it. |
| `widget_enabled`, `widget_form_id`, `widget_post_types[]`, `widget_pass_user` | bool, string, array, bool | Feedback widget. |
| `cf7_enabled_forms[]`, `cf7_skip_mail` | int[], bool | Contact Form 7 adapter. |

All admin forms use the Settings API (`options.php` with `settings_fields`), so nonces and `manage_options` checks are enforced. The AJAX receiver and the "Verify now" action check their own nonces and `manage_options`.

## Connect handshake

The server side of this flow does not exist yet; this documents what the plugin implements and what `app.contactusiq.com` must do.

1. `assets/admin.js` opens a popup at
   `https://app.contactusiq.com/connect/wordpress?site=<home_url>&return=<admin settings url>`.
2. The user signs in or signs up, picks a workspace, approves the site. ContactUsIQ creates (or finds) the domain for `site`, issues a **site-scoped API key**, creates a default "Contact" form, and registers the admin email as a recipient.
3. The popup calls `window.opener.postMessage(payload, returnOrigin)` where `returnOrigin` is the origin of the `return` parameter and `payload` is:

   ```json
   {
     "type": "contactusiq:connect",
     "apiKey": "cuiq_live_...",
     "workspaceId": "ws_xxxxxxx",
     "domainId": "dom_xxxxxxx",
     "verifyToken": "a1b2c3...",
     "formId": "au_xxxxxxx",
     "turnstileSiteKey": "0x4AAAAAAA_PLACEHOLDER"
   }
   ```

4. `admin.js` accepts the message only when `event.origin === 'https://app.contactusiq.com'` and `event.source` is the popup it opened, then POSTs the fields to `admin-ajax.php?action=contactusiq_connect` with a nonce (`contactusiq_connect`). `ContactUsIQ_Settings::ajax_connect()` checks `manage_options` and the nonce, sanitises every value and stores them.
5. The page reloads. The `verifyToken` is now printed in `wp_head` as `<meta name="contactusiq-verify" content="...">`, so the user (or the popup, via a follow-up call) can trigger verification.

Server-side TODO(spec): the `/connect/wordpress` page, the site-scoped key type, and which of `formId` and `turnstileSiteKey` are returned (both are optional in the plugin).

## Verification

- `wp_head` (priority 1): `<meta name="contactusiq-verify" content="{verify_token}">` whenever the token is set.
- "Verify now" (`admin-post.php?action=contactusiq_verify`, nonce `contactusiq_verify`): `wp_remote_post` to `https://app.contactusiq.com/v1/domains/{domain_id}/verify` with `Authorization: Bearer {api_key}` and a JSON body `{"method":"meta","site":"<home_url>"}`. The response's `status` (`verified`, `pending`, ...) and `message` are stored in `contactusiq_verification` and shown as an admin notice. `401/403` -> "key rejected", `404` -> "domain not in workspace".

## Shortcode

```
[contactusiq form="au_xxxxxxx" mode="html"]
[contactusiq form="au_xxxxxxx" mode="embed"]
[contactusiq]                                     default form id from settings, HTML mode
```

Attributes: `form`, `mode` (`html` | `embed`), `sitekey` (overrides the setting), `redirect` (absolute URL for the 303), `subject`, `button`.

- `html`: a `<form action="https://api.contactusiq.com/s/au_xxxxxxx" method="POST">` with the fields from `contactusiq_form_fields`, an off-screen empty `_honeypot`, hidden `_redirect`, `_subject`, `_page`, the Turnstile `div` when a site key is known, and a submit button. No nonce: nothing posts to WordPress.
- `embed`: `<div id="contactusiq-N"></div><script src="https://api.contactusiq.com/f/au_xxxxxxx/embed.js" data-target="#contactusiq-N" async defer></script>`.

`ContactUsIQ_Shortcode::render(array $args)` is the shared renderer the block uses.

## Block

`contactusiq/form`, registered with `register_block_type( CONTACTUSIQ_DIR . 'block', ['render_callback' => ...] )`. Attributes: `formId`, `mode` (`html` | `embed`), `redirect`, `subject`, `buttonLabel`. `save` returns `null`; the front end is server-rendered through the shortcode renderer. The editor shows a live `ServerSideRender` preview for HTML mode and a placeholder for embed mode (the embed script does not run inside the editor iframe).

`block/edit.js` is registered via `"editorScript": "file:./edit.js"`; `block/edit.asset.php` lists the `wp-*` dependencies by hand so no `@wordpress/scripts` build is needed.

## Feedback widget

When enabled, `wp_footer` prints:

```html
<script src="https://api.contactusiq.com/f/au_xxxxxxx/widget.js" data-form="au_xxxxxxx" data-position="bottom-right" data-app-version="wordpress/6.7" async defer></script>
```

With "pass logged-in user" on and a user logged in, `data-user-id`, `data-user-name` and `data-user-email` are added. Post-type selection limits it to `is_singular($types)`; no selection means every front-end request. Never printed in admin, feeds or embeds.

## Contact Form 7 adapter

Active only when `WPCF7_ContactForm` exists.

- `wpcf7_before_send_mail` (priority 10, 3 args): for routed forms, maps posted data and `wp_remote_post`s JSON to the intake URL of the default form (filterable per CF7 form with `contactusiq_cf7_form_id`). Headers: `Origin: home_url()`, `Referer: <page>`, `X-Forwarded-For: <visitor ip>`, `Accept: application/json`. The result (`status`, `id`, `message`) is stored in `contactusiq_last_delivery` and fired as `contactusiq_cf7_forwarded`.
- `wpcf7_skip_mail`: returns `true` for routed forms when "Skip Contact Form 7's own email" is on.
- Field map (filter `contactusiq_cf7_field_map`): `your-name -> name`, `your-email -> email`, `your-message -> message`, `your-subject -> _subject`, `your-phone`/`your-tel -> phone`. Everything else passes through with its CF7 name; `_wpcf7*` internals and `g-recaptcha-response` are dropped. Arrays (checkboxes) are joined with `, `.

Note that server-side forwarding means ContactUsIQ sees the WordPress server's IP as the client; `X-Forwarded-For` carries the visitor's IP but the intake API only trusts its own edge header, so per-IP rate limits apply to the server. TODO(spec): a trusted server-to-server header for plugin traffic.

## Hooks and filters

| Hook | Type | Signature | Purpose |
| --- | --- | --- | --- |
| `contactusiq_intake_url` | filter | `(string $url, string $form_id)` | Change the intake URL (proxy, staging cell). |
| `contactusiq_form_fields` | filter | `(array $fields, string $form_id)` | Fields of the HTML form: each `['name','label','type','required']`, type in `text|email|tel|url|textarea`. |
| `contactusiq_show_widget` | filter | `(bool $show)` | Suppress the widget on specific requests. |
| `contactusiq_widget_attributes` | filter | `(array $attributes)` | Change `data-position`, add `data-intents`, etc. |
| `contactusiq_cf7_enabled` | filter | `(bool $enabled, int $cf7_form_id)` | Route a CF7 form programmatically. |
| `contactusiq_cf7_form_id` | filter | `(string $form_id, int $cf7_form_id)` | Send a CF7 form to a different ContactUsIQ form. |
| `contactusiq_cf7_field_map` | filter | `(array $map)` | CF7 name -> ContactUsIQ name. |
| `contactusiq_cf7_forwarded` | action | `(array $result, array $payload, int $cf7_form_id)` | After a forward. |

Example, add a phone field to the HTML form:

```php
add_filter( 'contactusiq_form_fields', function ( array $fields ) {
    $fields[] = array( 'name' => 'phone', 'label' => 'Phone', 'type' => 'tel', 'required' => false );
    return $fields;
} );
```

## Site Health

`Tools > Site Health > Status` gains "ContactUsIQ connection": good when connected and verified; recommended when not connected, verification not confirmed, or the last server-side delivery failed. The Info tab lists version, connection, masked key, ids, verification and widget state.

## Security notes

- Output escaped with `esc_html`, `esc_attr`, `esc_url`; input through `sanitize_text_field`, `sanitize_key`, `esc_url_raw`, `absint` and regex whitelists for ids.
- Admin actions: Settings API nonces, `check_ajax_referer`, `check_admin_referer`, `current_user_can('manage_options')`.
- The API key is stored in the options table (not hashed; the plugin needs it to call the management API) and only ever displayed masked. Consider a `CONTACTUSIQ_API_KEY` constant override in a later version.
- The plugin registers the Turnstile script under its own handle `contactusiq-turnstile` and enqueues it only on pages that render an HTML-mode form with a site key.

## Testing locally with wp-env (documented only; nothing is installed here)

1. Install Docker and Node 22. In this folder create `.wp-env.json`:

   ```json
   { "core": "WordPress/WordPress#6.7", "phpVersion": "8.2", "plugins": [ ".", "https://downloads.wordpress.org/plugin/contact-form-7.zip" ] }
   ```

2. `npx @wordpress/env start` then open `http://localhost:8888/wp-admin` (admin / password).
3. Settings > ContactUsIQ: paste a form id and Turnstile key (Connect needs the real app), enable the widget, tick a CF7 form.
4. Add the block to a page, publish, submit. Note that `localhost` is not a verified domain, so the intake API answers `200` and drops the message unless the form allows any origin; test the front-end on a verified domain or point `contactusiq_intake_url` at a request bin during development.
5. `npx @wordpress/env run cli wp option get contactusiq_settings` to inspect stored settings; `npx @wordpress/env destroy` to clean up.

Lint: `php -l` on every file passes on PHP 8.1+. For coding standards, `composer global require wp-coding-standards/wpcs` and `phpcs --standard=WordPress .`.

## For AI agents

To integrate a WordPress site with ContactUsIQ using this plugin: copy the `apps/wp-plugin` folder to `wp-content/plugins/contactusiq` and activate it; in Settings > ContactUsIQ set the default form id (`au_xxxxxxx`) and Turnstile site key (`0x4AAAAAAA_PLACEHOLDER`), or click Connect; then place the "ContactUsIQ Form" block or `[contactusiq form="au_xxxxxxx"]` on a page. The rendered form posts directly from the browser to `https://api.contactusiq.com/s/au_xxxxxxx` with an empty `_honeypot`, optional `_redirect`, `_subject`, `_page` and the Turnstile token; success is `200` or `303`, errors are `400`, `404`, `413`, `429` with `Retry-After`. To route existing Contact Form 7 forms, tick them in the same settings screen. To show the feedback widget everywhere, enable it and optionally pass the logged-in user.

```text
[contactusiq form="au_xxxxxxx" mode="html" redirect="https://www.example.com/thanks/" subject="Website enquiry"]
```
