Install the plugin
Download the zip, upload it in WordPress, and activate SearchCue from your plugins screen.
The SearchCue WordPress plugin makes it easy to add SearchCue to your WordPress site. You can read the source code below, or download the plugin ready to install.
Download the zip, upload it in WordPress, and activate SearchCue from your plugins screen.
Sign in to SearchCue, copy your site settings, and let the hosted crawler index your public content.
SearchCue runs search and answers from our hosted index instead of adding a heavy search engine to your database.
The browser below is generated from the plugin files during the site build. Pick a file to read it without downloading anything.
{
"name": "SearchCue WordPress Plugin",
"dockerComposeFile": "docker-compose.yml",
"service": "plugin",
"workspaceFolder": "/workspaces/searchcue",
"forwardPorts": [8080],
"customizations": {
"vscode": {
"extensions": [
"bmewburn.vscode-intelephense-client",
"xdebug.php-debug"
]
}
},
"postStartCommand": "bash /workspaces/searchcue/bin/setup.sh"
} services:
plugin:
build:
context: ..
dockerfile: .devcontainer/Dockerfile
volumes:
- ..:/workspaces/searchcue:cached
- wordpress_data:/var/www/html
depends_on:
- db
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
XDEBUG_MODE: "${XDEBUG_MODE:-off}"
db:
image: mariadb:10.6
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
volumes:
- db_data:/var/lib/mysql
volumes:
wordpress_data:
db_data: FROM wordpress:6.7-php8.2-apache
# Install dependencies needed for development and debugging
RUN apt-get update && apt-get install -y --no-install-recommends \
git \
mariadb-client \
sudo \
&& rm -rf /var/lib/apt/lists/*
# Install Xdebug for step debugging
RUN pecl install xdebug-3.4.1 \
&& docker-php-ext-enable xdebug
# Configure Xdebug (off by default, enable via XDEBUG_MODE env var)
RUN echo "xdebug.client_host=host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.discover_client_host=true" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.start_with_request=trigger" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
# Enable Apache mod_rewrite
RUN a2enmod rewrite # Build output
dist/
# Editor / OS
.vscode/
.idea/
*.swp
*.swo
.DS_Store #!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_DIR="$(dirname "$SCRIPT_DIR")"
DIST_DIR="${PLUGIN_DIR}/dist"
ZIP_NAME="searchcue.zip"
# Clean previous builds
rm -rf "$DIST_DIR"
mkdir -p "$DIST_DIR"
# Build the ZIP from the plugin root, including only production files
cd "$PLUGIN_DIR"
zip -r "${DIST_DIR}/${ZIP_NAME}" \
searchcue.php \
assets \
uninstall.php \
LICENSE \
README.md \
readme.txt \
-x "*.DS_Store"
echo "Built ${DIST_DIR}/${ZIP_NAME}"
echo "Contents:"
unzip -l "${DIST_DIR}/${ZIP_NAME}" #!/usr/bin/env bash
set -euo pipefail
# ------------------------------------------------------------------
# Dev-container-only setup script.
#
# Creates a symlink from the WordPress plugins directory into the
# workspace, installs WP-CLI, bootstraps a fresh WordPress database,
# and activates the plugin. This is invoked automatically via the
# postStartCommand in .devcontainer/devcontainer.json and relies on
# paths that only exist inside the container.
#
# Do NOT run this on a real / production WordPress installation.
# ------------------------------------------------------------------
if [ ! -f /.dockerenv ]; then
echo "ERROR: This script is meant to run inside the dev container only." >&2
echo " To install the plugin on a real WordPress site, copy the" >&2
echo " searchcue directory into wp-content/plugins/ instead." >&2
exit 1
fi
# Paths are specific to the official wordpress Docker image
# (/var/www/html) and the devcontainer workspace mount.
PLUGIN_DIR="/var/www/html/wp-content/plugins/searchcue"
PLUGIN_SRC="/workspaces/searchcue"
if [ ! -d "/var/www/html/wp-content" ]; then
echo "Waiting for WordPress to be installed..."
# WordPress container initializes wp-content on first run
sleep 3
fi
# Remove any existing symlink or directory
if [ -L "$PLUGIN_DIR" ]; then
rm "$PLUGIN_DIR"
elif [ -d "$PLUGIN_DIR" ]; then
rm -rf "$PLUGIN_DIR"
fi
# Create symlink
mkdir -p /var/www/html/wp-content/plugins
ln -s "$PLUGIN_SRC" "$PLUGIN_DIR"
echo "Plugin symlinked to $PLUGIN_DIR"
# Install WP-CLI if not present
if ! command -v wp &>/dev/null; then
echo "Installing WP-CLI..."
curl -sO https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
mv wp-cli.phar /usr/local/bin/wp
fi
# Wait for database
echo "Waiting for database..."
for i in $(seq 1 30); do
if mysqladmin ping -h db -uwordpress -pwordpress --silent 2>/dev/null; then
break
fi
sleep 1
done
# Install WordPress if not already installed
if ! wp core is-installed --path=/var/www/html --allow-root 2>/dev/null; then
echo "Installing WordPress..."
wp config create \
--path=/var/www/html \
--dbname=wordpress \
--dbuser=wordpress \
--dbpass=wordpress \
--dbhost=db \
--allow-root
wp db create --path=/var/www/html --allow-root 2>/dev/null || true
wp core install \
--path=/var/www/html \
--url="http://localhost:8080" \
--title="SearchCue Plugin Dev" \
--admin_user="admin" \
--admin_password="admin" \
--admin_email="admin@example.com" \
--allow-root
echo "WordPress installed. Admin at http://localhost:8080/wp-admin (admin/admin)"
else
echo "WordPress already installed."
fi
# Activate the plugin
wp plugin activate searchcue --path=/var/www/html --allow-root 2>/dev/null || echo "Plugin activation will happen on first page load."
echo ""
echo "=== SearchCue Plugin Dev Environment Ready ==="
echo "WordPress: http://localhost:8080"
echo "Admin: http://localhost:8080/wp-admin (admin / admin)"
echo "SearchCue: http://localhost:8080/wp-admin/admin.php?page=searchcue"
echo ""
echo "Run tests: php /workspaces/searchcue/tests/run-tests.php"
echo "" GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print such an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
SearchCue WordPress Plugin
Copyright (C) 2026 DoNoHarm - Bauer & Eide GbR
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>. # SearchCue - WordPress Plugin
A WordPress plugin that adds [SearchCue](https://searchcue.com) to your site.
Configure your Site ID in the WordPress admin and let SearchCue know when public content changes.
## Features
- Injects the SearchCue embed script into the `<head>` of every public page
- Dedicated **SearchCue** admin menu page to connect and configure your site
- Optional automatic updates when public pages, posts, custom post types, or attachments change
- No external dependencies beyond WordPress core
## Installation
### From ZIP (for production use)
1. Download or build the plugin ZIP (see below)
2. In WordPress admin, go to **Plugins > Add New > Upload Plugin**
3. Upload the ZIP and activate
### Manual
1. Copy the `searchcue` directory into `wp-content/plugins/`
2. Activate via **Plugins** in WordPress admin
## Configuration
1. Open **SearchCue** from the WordPress admin menu
2. Paste your SearchCue Site ID (looks like `site_abc123`)
3. Keep **Automatic updates** checked if you want SearchCue to re-index changed pages automatically
4. Save changes
The embed script will appear in the `<head>` of all public pages that call `wp_head()`.
WordPress can also notify SearchCue when public content or attachments change.
## Development
### Dev Container (recommended)
This project includes a fully containerized development environment:
1. Open this directory in [VS Code](https://code.visualstudio.com/) or any editor that supports Dev Containers
2. When prompted, click **Reopen in Container** (or run **Dev Containers: Reopen in Container** from the command palette)
3. The container will build, install WordPress, symlink the plugin, and activate it
4. Visit `http://localhost:8080` to see the WordPress site
5. Visit `http://localhost:8080/wp-admin/admin.php?page=searchcue` for plugin settings
**Credentials:** `admin` / `admin`
### Local CLI with Docker Compose
If you prefer the terminal over a dev container editor, you can bring up the full WordPress test site with plain Docker Compose commands. You only need [Docker](https://docs.docker.com/get-docker/) installed.
From the `searchcue` plugin directory:
```bash
# Build and start WordPress + MariaDB
docker compose -f .devcontainer/docker-compose.yml up -d --build
# Run the one-time setup (install WordPress, symlink the plugin, activate it)
docker compose -f .devcontainer/docker-compose.yml exec -T plugin bash /workspaces/searchcue/bin/setup.sh
```
Then open your browser:
| What | URL |
| --------------- | --------------------------------------------------------------------- |
| WordPress site | http://localhost:8080 |
| Admin dashboard | http://localhost:8080/wp-admin |
| Plugin settings | http://localhost:8080/wp-admin/admin.php?page=searchcue |
**Credentials:** `admin` / `admin`
Run the test suite:
```bash
docker compose -f .devcontainer/docker-compose.yml exec plugin php /workspaces/searchcue/tests/run-tests.php
```
Tear everything down when you are done:
```bash
docker compose -f .devcontainer/docker-compose.yml down
```
To also remove the WordPress database and uploaded files (fresh start next time):
```bash
docker compose -f .devcontainer/docker-compose.yml down -v
```
### Running Tests (without Docker)
If you have PHP 7.4+ installed locally:
```bash
php tests/run-tests.php
```
The test suite uses stub WordPress functions so it runs without a full WordPress installation.
### Building a Distribution ZIP
```bash
bin/build-zip.sh
```
This creates `dist/searchcue.zip` containing only the files needed for production deployment (no devcontainer, tests, or build tooling).
## File Structure
```
searchcue/
├── assets/ WordPress admin menu icon assets
├── .devcontainer/ Dev container configuration for local testing
│ ├── devcontainer.json
│ ├── docker-compose.yml
│ └── Dockerfile
├── bin/
│ ├── setup.sh WordPress installation and plugin activation
│ └── build-zip.sh Build a distributable ZIP
├── tests/
│ └── run-tests.php Standalone test suite with WP function stubs
├── searchcue.php Main plugin file
├── readme.txt WordPress plugin compatibility metadata
├── uninstall.php Cleanup options on plugin uninstall
└── README.md
```
## Uninstalling
When you delete the plugin through WordPress, `uninstall.php` runs automatically and removes all stored options from the database.
## License
This plugin is licensed under the [GNU General Public License v2.0 or later](https://www.gnu.org/licenses/gpl-2.0.html) (GPLv2+), which is the same license as WordPress itself. This is required for plugins published in the [WordPress.org Plugin Directory](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#1-plugins-must-be-compatible-with-the-gnu-general-public-license). <?php
/**
* Plugin Name: SearchCue
* Plugin URI: https://searchcue.com
* Description: Adds the SearchCue embed to every WordPress page and provides a small settings page for the SearchCue Site ID.
* Version: 0.1.0
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: DoNoHarm
* Author URI: https://donoharm.world
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: searchcue
*
* @package SearchCue_Search
*/
declare(strict_types=1);
namespace SearchCue_Search_Plugin;
if (!defined("ABSPATH")) {
exit();
}
const OPTION_NAME = "searchcue_search_options";
const SETTINGS_GROUP = "searchcue_search";
const SETTINGS_PAGE = "searchcue";
const SETTINGS_SECTION = "searchcue_search_main";
const EMBED_SCRIPT_URL = "https://searchcue.com/search-embed.js";
const SEARCHCUE_APP_ENDPOINT = "https://searchcue.com";
const INDEXNOW_ENDPOINT = "https://central.searchcue.com/indexnow";
const WORDPRESS_INTEGRATION_ENDPOINT = "https://central.searchcue.com/site-search/integrations/wordpress";
const ACTIVATION_REDIRECT_TRANSIENT = "searchcue_search_activation_redirect";
$pending_indexnow_urls = [];
function bootstrap(): void
{
add_action("wp_head", __NAMESPACE__ . '\\render_embed');
add_action("template_redirect", __NAMESPACE__ . '\\serve_indexnow_keyfile');
add_action("admin_menu", __NAMESPACE__ . '\\register_admin_page');
add_action("admin_init", __NAMESPACE__ . '\\register_settings');
add_action("admin_init", __NAMESPACE__ . '\\maybe_complete_setup_from_handoff');
add_action("admin_init", __NAMESPACE__ . '\\maybe_redirect_after_activation');
add_action("admin_post_searchcue_search_send_setup_link", __NAMESPACE__ . "\\send_setup_link");
add_action("wp_ajax_searchcue_search_setup_status", __NAMESPACE__ . "\\ajax_setup_status");
add_action("wp_ajax_searchcue_search_analytics", __NAMESPACE__ . "\\ajax_search_analytics");
register_update_hooks();
register_activation_hook(__FILE__, __NAMESPACE__ . "\\activate");
}
function activate(): void
{
add_option(OPTION_NAME, default_options());
set_transient(ACTIVATION_REDIRECT_TRANSIENT, "1", 30);
}
/**
* @return array{site_id: string, assigned_site_id: string, api_key: string, setup_state: string, push_updates: string, indexnow_key: string}
*/
function default_options(): array
{
return [
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => generate_setup_state(),
"push_updates" => "1",
"indexnow_key" => generate_indexnow_key(),
];
}
/**
* @return array{site_id: string, assigned_site_id: string, api_key: string, setup_state: string, push_updates: string, indexnow_key: string}
*/
function get_options(): array
{
$stored_options = get_option(OPTION_NAME);
return is_array($stored_options) ? $stored_options : default_options();
}
/**
* @param mixed $input
*
* @return array{site_id: string, assigned_site_id: string, api_key: string, setup_state: string, push_updates: string, indexnow_key: string}
*/
function sanitize_options($input): array
{
if (!is_array($input)) {
return default_options();
}
$site_id = isset($input["site_id"]) ? trim((string) $input["site_id"]) : "";
$site_id = preg_replace("/[^A-Za-z0-9_-]/", "", $site_id);
$assigned_site_id = sanitize_hidden_option($input, "assigned_site_id");
$api_key = sanitize_hidden_option($input, "api_key");
$setup_state = sanitize_hidden_option($input, "setup_state");
$push_updates =
isset($input["push_updates"]) && (string) $input["push_updates"] === "1" ? "1" : "0";
$indexnow_key = sanitize_hidden_option($input, "indexnow_key");
if ($indexnow_key === "") {
$indexnow_key = generate_indexnow_key();
}
if ($setup_state === "") {
$setup_state = generate_setup_state();
}
return [
"site_id" => $site_id ?? "",
"assigned_site_id" => $assigned_site_id ?? "",
"api_key" => $api_key ?? "",
"setup_state" => $setup_state ?? generate_setup_state(),
"push_updates" => $push_updates,
"indexnow_key" => $indexnow_key ?? generate_indexnow_key(),
];
}
function sanitize_hidden_option(array $input, string $key): string
{
if (isset($input[$key])) {
$value = trim((string) $input[$key]);
} else {
$stored_options = get_option(OPTION_NAME, []);
$value = is_array($stored_options) && isset($stored_options[$key]) ? trim((string) $stored_options[$key]) : "";
}
return preg_replace("/[^A-Za-z0-9_-]/", "", $value) ?? "";
}
function effective_site_id(array $options): string
{
return $options["site_id"] !== "" ? $options["site_id"] : $options["assigned_site_id"];
}
function render_embed(): void
{
$options = get_options();
$site_id = effective_site_id($options);
if ($site_id === "") {
return;
}
$src = esc_url(EMBED_SCRIPT_URL);
$siteid = esc_attr($site_id);
echo "\n<!-- Start SearchCue embed -->\n";
echo "<script>\n";
echo " (function(){\n";
echo " var s = document.createElement('script');\n";
echo " s.src = '$src';\n";
echo " s.async = true;\n";
echo " s.setAttribute('siteid', '$siteid');\n";
echo " var f = document.getElementsByTagName('script')[0]?.parentNode\n";
echo " || document.head || document.body || document.documentElement;\n";
echo " f.insertBefore(s, document.getElementsByTagName('script')[0] || null);\n";
echo " })();\n";
echo "</script>\n";
echo "<!-- End SearchCue embed -->\n";
}
function register_admin_page(): void
{
add_menu_page(
__("SearchCue", "searchcue"),
__("SearchCue", "searchcue"),
"manage_options",
SETTINGS_PAGE,
__NAMESPACE__ . '\\render_settings_page',
plugin_dir_url(__FILE__) . "assets/searchcue-menu-icon.svg",
);
$options = get_options();
if ($options["api_key"] === "") {
return;
}
$links = [
["documentation", __("Documentation", "searchcue")],
["design", __("Design", "searchcue")],
["analytics", __("Analytics", "searchcue")],
["more", __("SearchCue Dashboard", "searchcue")],
];
foreach ($links as [$destination, $label]) {
add_submenu_page(
SETTINGS_PAGE,
$label,
$label,
"manage_options",
searchcue_admin_url($options, $destination),
);
}
}
function register_settings(): void
{
register_setting(SETTINGS_GROUP, OPTION_NAME, [
"type" => "array",
"sanitize_callback" => __NAMESPACE__ . "\\sanitize_options",
"default" => default_options(),
]);
add_settings_section(
SETTINGS_SECTION,
__("Settings", "searchcue"),
"__return_empty_string",
SETTINGS_PAGE,
);
add_settings_field(
"site_id",
__("SearchCue Site ID", "searchcue"),
__NAMESPACE__ . '\\render_site_id_field',
SETTINGS_PAGE,
SETTINGS_SECTION,
);
add_settings_field(
"push_updates",
__("Automatic updates", "searchcue"),
__NAMESPACE__ . '\\render_push_updates_field',
SETTINGS_PAGE,
SETTINGS_SECTION,
);
}
function render_site_id_field(): void
{
$options = get_options(); ?>
<input
id="searchcue_search_site_id"
class="regular-text"
name="<?php echo esc_attr(OPTION_NAME); ?>[site_id]"
type="text"
value="<?php echo esc_attr($options["site_id"]); ?>"
placeholder="site_..."
autocomplete="off"
>
<p class="description">
<?php echo esc_html__(
"Only change this if you want to use a different search index than the default SearchCue assigned.",
"searchcue",
); ?>
</p>
<?php
}
function render_push_updates_field(): void
{
$options = get_options(); ?>
<label for="searchcue_search_push_updates">
<input
id="searchcue_search_push_updates"
name="<?php echo esc_attr(OPTION_NAME); ?>[push_updates]"
type="checkbox"
value="1"
<?php checked($options["push_updates"], "1"); ?>
>
<?php echo esc_html__(
"Keep the SearchCue search index current as public pages and files change.",
"searchcue",
); ?>
</label>
<?php
}
function render_settings_page_styles(): void
{ ?>
<style>
@font-face {
font-family: "Schibsted Grotesk";
src: url("https://searchcue.com/fonts/searchcue/SchibstedGrotesk-Regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Schibsted Grotesk";
src: url("https://searchcue.com/fonts/searchcue/SchibstedGrotesk-Medium.woff2") format("woff2");
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Schibsted Grotesk";
src: url("https://searchcue.com/fonts/searchcue/SchibstedGrotesk-SemiBold.woff2") format("woff2");
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Schibsted Grotesk";
src: url("https://searchcue.com/fonts/searchcue/SchibstedGrotesk-Bold.woff2") format("woff2");
font-weight: 700;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Spline Sans Mono";
src: url("https://searchcue.com/fonts/searchcue/SplineSansMono-Regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Spline Sans Mono";
src: url("https://searchcue.com/fonts/searchcue/SplineSansMono-Medium.woff2") format("woff2");
font-weight: 500;
font-style: normal;
font-display: swap;
}
.searchcue-admin {
--searchcue-ink-900: #1b1b19;
--searchcue-ink-700: #44443f;
--searchcue-ink-500: #6e6e66;
--searchcue-ink-300: #b0b0a7;
--searchcue-paper: #fafaf6;
--searchcue-paper-shade: #f2f2ec;
--searchcue-surface: #ffffff;
--searchcue-line-strong: #cfcfc6;
--searchcue-line: #e2e2da;
--searchcue-line-soft: #edede6;
--searchcue-cue: #1e6b50;
--searchcue-cue-deep: #14503b;
--searchcue-cue-wash: #e9f2ec;
--searchcue-cue-line: #bfd9cb;
--searchcue-ok: #1e6b50;
--searchcue-ok-wash: #e9f2ec;
--searchcue-warn: #8a6018;
--searchcue-warn-wash: #f7f0df;
--searchcue-font-mono: "Spline Sans Mono", ui-monospace, "SF Mono", Menlo, monospace;
color: var(--searchcue-ink-900);
font-family: "Schibsted Grotesk", "Helvetica Neue", Helvetica, Arial, sans-serif;
max-width: 1120px;
}
.searchcue-admin * {
box-sizing: border-box;
}
.searchcue-mono {
font-family: var(--searchcue-font-mono);
}
.searchcue-hero {
align-items: stretch;
background: var(--searchcue-paper);
border: 1px solid var(--searchcue-line);
border-radius: 6px;
display: grid;
gap: 0;
grid-template-columns: minmax(0, 1fr) 320px;
margin: 22px 0;
overflow: hidden;
}
.searchcue-hero.is-connected {
grid-template-columns: minmax(0, 1fr);
}
.searchcue-hero-copy {
padding: 34px;
}
.searchcue-eyebrow {
color: var(--searchcue-cue);
font-size: 15px;
font-weight: 600;
margin: 0 0 10px;
}
.searchcue-admin h1,
.searchcue-admin h2 {
color: var(--searchcue-ink-900);
font-weight: 600;
letter-spacing: 0;
}
.searchcue-admin h1 {
font-size: 42px;
line-height: 1.08;
margin: 0;
max-width: 720px;
}
.searchcue-admin h1.searchcue-wordmark {
align-items: baseline;
display: inline-flex;
font-weight: 700;
gap: 3px;
letter-spacing: -0.022em;
line-height: 1;
white-space: nowrap;
}
.searchcue-wordmark-caret {
background: var(--searchcue-cue);
border-radius: 1px;
display: inline-block;
height: 0.78em;
transform: translateY(0.04em);
width: 0.09em;
}
.searchcue-connected-status {
align-items: center;
color: var(--searchcue-ink-700);
display: flex;
font-size: 15px;
font-weight: 600;
gap: 8px;
margin: 16px 0 0;
}
.searchcue-connected-check {
align-items: center;
background: var(--searchcue-ok-wash);
border-radius: 9999px;
color: var(--searchcue-ok);
display: inline-flex;
height: 20px;
justify-content: center;
width: 20px;
}
.searchcue-connected-check svg {
display: block;
height: 12px;
width: 12px;
}
.searchcue-intro {
color: var(--searchcue-ink-500);
font-size: 17px;
line-height: 1.6;
margin: 18px 0 0;
max-width: 680px;
}
.searchcue-status {
background: var(--searchcue-surface);
border-left: 1px solid var(--searchcue-line);
display: flex;
flex-direction: column;
justify-content: center;
padding: 28px;
}
.searchcue-status-badge {
align-self: flex-start;
border-radius: 2px;
display: inline-flex;
font-size: 12px;
font-weight: 700;
line-height: 1;
padding: 6px 8px;
}
.searchcue-status-badge.is-connected {
background: var(--searchcue-cue-wash);
color: var(--searchcue-cue);
}
.searchcue-status-badge.is-needed {
background: var(--searchcue-warn-wash);
color: var(--searchcue-warn);
}
.searchcue-status dl {
display: grid;
gap: 14px;
margin: 22px 0 0;
}
.searchcue-status dt {
color: var(--searchcue-ink-500);
font-size: 13px;
margin: 0 0 4px;
}
.searchcue-status dd {
font-size: 15px;
font-weight: 600;
margin: 0;
overflow-wrap: anywhere;
}
.searchcue-settings {
background: var(--searchcue-surface);
border: 1px solid var(--searchcue-line);
border-radius: 6px;
margin: 0 0 18px;
padding: 30px 34px 18px;
}
.searchcue-field {
max-width: 720px;
}
.searchcue-label {
color: var(--searchcue-ink-900);
display: block;
font-size: 14px;
font-weight: 700;
margin-bottom: 8px;
}
.searchcue-input {
border-color: var(--searchcue-line-strong);
border-radius: 4px;
font-size: 18px;
max-width: 440px;
min-height: 46px;
padding: 8px 12px;
width: 100%;
}
.searchcue-input:focus {
border-color: var(--searchcue-cue);
box-shadow: none;
outline: 2px solid var(--searchcue-cue);
outline-offset: 1px;
}
.searchcue-help {
color: var(--searchcue-ink-500);
font-size: 14px;
line-height: 1.55;
margin: 8px 0 0;
}
.searchcue-toggle {
align-items: flex-start;
cursor: pointer;
display: flex;
gap: 14px;
margin-top: 0;
max-width: 720px;
padding-top: 0;
position: relative;
}
.searchcue-toggle .searchcue-switch-input {
height: 1px;
left: 0;
margin: 0;
min-height: 1px;
min-width: 1px;
opacity: 0;
position: absolute;
top: 0;
width: 1px;
}
.searchcue-switch {
background: var(--searchcue-paper-shade);
border: 1px solid var(--searchcue-line-strong);
border-radius: 999px;
flex: 0 0 auto;
height: 24px;
margin-top: 1px;
position: relative;
transition: background-color 140ms ease, border-color 140ms ease;
width: 44px;
}
.searchcue-switch::after {
background: var(--searchcue-surface);
border-radius: 999px;
content: "";
height: 18px;
left: 2px;
position: absolute;
top: 2px;
transition: transform 140ms ease;
width: 18px;
}
.searchcue-switch-input:checked + .searchcue-switch {
background: var(--searchcue-cue);
border-color: var(--searchcue-cue);
}
.searchcue-switch-input:checked + .searchcue-switch::after {
transform: translateX(20px);
}
.searchcue-switch-input:focus-visible + .searchcue-switch {
outline: 2px solid var(--searchcue-cue);
outline-offset: 2px;
}
.searchcue-toggle-title {
display: block;
font-size: 15px;
font-weight: 700;
margin-bottom: 4px;
}
.searchcue-actions {
margin-top: 26px;
}
.searchcue-onboarding {
background: var(--searchcue-surface);
border: 1px solid var(--searchcue-line);
border-radius: 6px;
margin: 0 0 18px;
padding: 30px 34px;
}
.searchcue-onboarding-row {
align-items: end;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 14px;
}
.searchcue-onboarding-row .searchcue-field {
flex: 1 1 280px;
max-width: 420px;
}
.searchcue-alert {
background: var(--searchcue-cue-wash);
border: 1px solid var(--searchcue-cue-line);
border-radius: 6px;
color: var(--searchcue-cue-deep);
font-size: 14px;
line-height: 1.5;
margin: 0 0 18px;
max-width: 780px;
padding: 14px 16px;
}
.searchcue-connect-note {
border-top: 1px solid var(--searchcue-line);
color: var(--searchcue-ink-500);
font-size: 15px;
line-height: 1.55;
margin: 28px 0 0;
max-width: 720px;
padding-top: 22px;
}
.searchcue-connect-note a,
.searchcue-advanced a {
color: var(--searchcue-cue);
font-weight: 700;
}
.searchcue-actions .button-primary,
.searchcue-actions button[type="submit"] {
background: var(--searchcue-ink-900);
border-color: var(--searchcue-ink-900);
border-radius: 4px;
box-shadow: none;
color: var(--searchcue-paper);
font-weight: 600;
min-height: 40px;
padding-left: 18px;
padding-right: 18px;
}
.searchcue-actions .button-primary:hover,
.searchcue-actions button[type="submit"]:hover {
background: #000000;
border-color: #000000;
color: var(--searchcue-paper);
}
.searchcue-actions .button-primary:focus,
.searchcue-actions button[type="submit"]:focus {
border-color: var(--searchcue-cue);
box-shadow: none;
color: var(--searchcue-paper);
outline: 2px solid var(--searchcue-cue);
outline-offset: 2px;
}
.searchcue-actions .button-primary:disabled,
.searchcue-actions button[type="submit"]:disabled {
background: var(--searchcue-paper-shade) !important;
border-color: var(--searchcue-line-soft) !important;
box-shadow: none !important;
color: var(--searchcue-ink-300) !important;
cursor: not-allowed;
opacity: 1;
}
.searchcue-onboarding-row .searchcue-actions {
display: flex;
margin-top: 0;
}
.searchcue-onboarding-row .searchcue-input,
.searchcue-onboarding-row .button-primary,
.searchcue-onboarding-row button[type="submit"] {
height: 46px;
min-height: 46px;
}
.searchcue-onboarding-row .button-primary,
.searchcue-onboarding-row button[type="submit"] {
align-items: center;
display: inline-flex;
justify-content: center;
margin-bottom: 0;
}
.searchcue-analytics {
background: var(--searchcue-surface);
border: 1px solid var(--searchcue-line);
border-radius: 6px;
margin: 0 0 18px;
padding: 30px 34px;
}
.searchcue-analytics.is-in-hero {
background: var(--searchcue-surface);
border: 0;
border-radius: 0;
border-top: 1px solid var(--searchcue-line);
margin: 0;
padding: 30px 34px;
}
.searchcue-analytics-header {
align-items: flex-start;
display: flex;
flex-wrap: wrap;
gap: 18px;
justify-content: space-between;
}
.searchcue-analytics-header > div:first-child {
flex: 1 1 360px;
min-width: 0;
}
.searchcue-analytics h2,
.searchcue-analytics h3 {
color: var(--searchcue-ink-900);
margin: 0;
}
.searchcue-analytics h2 {
font-size: 24px;
font-weight: 500;
}
.searchcue-analytics h3 {
font-size: 15px;
font-weight: 700;
}
.searchcue-analytics-kicker,
.searchcue-analytics-state {
color: var(--searchcue-ink-500);
font-size: 14px;
line-height: 1.55;
}
.searchcue-analytics-kicker {
margin: 12px 0 0;
}
.searchcue-analytics-state {
margin: 8px 0 0;
}
.searchcue-analytics-range {
color: var(--searchcue-cue);
font-size: 13px;
font-weight: 700;
}
.searchcue-analytics-link {
color: var(--searchcue-cue);
font-size: 14px;
font-weight: 700;
line-height: 1.2;
}
.searchcue-analytics-meta {
align-items: flex-end;
display: flex;
flex: 0 0 auto;
flex-direction: column;
gap: 8px;
margin-left: auto;
margin-top: 4px;
text-align: right;
}
.searchcue-analytics-metrics {
border-top: 1px solid var(--searchcue-line-soft);
display: grid;
gap: 24px;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin-top: 24px;
padding-top: 24px;
}
.searchcue-analytics-metric {
min-width: 0;
}
.searchcue-analytics-metric span {
color: var(--searchcue-ink-500);
display: block;
font-size: 13px;
margin-bottom: 6px;
}
.searchcue-analytics-metric strong {
color: var(--searchcue-ink-900);
display: block;
font-size: 28px;
font-variant-numeric: tabular-nums;
font-weight: 600;
line-height: 1.1;
}
.searchcue-analytics-detail {
display: grid;
gap: 26px;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
margin-top: 26px;
}
.searchcue-query-table {
margin-top: 14px;
overflow-x: auto;
}
.searchcue-query-table table {
border-collapse: collapse;
width: 100%;
}
.searchcue-query-table thead th {
border-bottom: 1px solid var(--searchcue-line);
color: var(--searchcue-ink-500);
font-size: 13px;
font-weight: 500;
padding: 0 0 10px;
text-align: left;
}
.searchcue-query-table thead th.searchcue-query-num {
text-align: right;
}
.searchcue-query-table tbody td {
border-bottom: 1px solid var(--searchcue-line-soft);
color: var(--searchcue-ink-700);
font-size: 14px;
padding: 11px 0;
}
.searchcue-query-table tbody tr:last-child td {
border-bottom: 0;
}
.searchcue-query-table tbody tr {
transition: background-color 140ms ease;
}
.searchcue-query-table tbody tr:hover {
background: var(--searchcue-paper-shade);
}
.searchcue-query-term {
color: var(--searchcue-ink-900);
font-weight: 600;
max-width: 0;
overflow: hidden;
padding-right: 16px;
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
}
.searchcue-query-num {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
width: 1%;
}
.searchcue-volume-chart {
margin-top: 12px;
min-height: 180px;
}
.searchcue-volume-chart svg {
display: block;
height: 180px;
overflow: visible;
width: 100%;
}
.searchcue-volume-chart text {
fill: var(--searchcue-ink-500);
font-family: inherit;
font-size: 11px;
}
.searchcue-volume-grid {
stroke: var(--searchcue-line);
stroke-width: 1;
}
.searchcue-volume-axis {
stroke: var(--searchcue-ink-500);
stroke-width: 1;
}
.searchcue-volume-line {
fill: none;
stroke: var(--searchcue-cue);
stroke-linecap: round;
stroke-linejoin: round;
stroke-width: 3;
}
.searchcue-volume-point {
fill: var(--searchcue-surface);
stroke: var(--searchcue-cue);
stroke-width: 2.5;
}
.searchcue-empty {
color: var(--searchcue-ink-500);
font-size: 14px;
line-height: 1.55;
margin: 12px 0 0;
}
.searchcue-hidden {
display: none;
}
.searchcue-advanced {
margin-top: 28px;
max-width: 760px;
padding-top: 0;
}
.searchcue-advanced summary {
color: var(--searchcue-ink-900);
cursor: pointer;
font-size: 15px;
font-weight: 700;
}
.searchcue-advanced-body {
padding-top: 18px;
}
@media (max-width: 900px) {
.searchcue-hero {
grid-template-columns: 1fr;
}
.searchcue-analytics-detail,
.searchcue-analytics-metrics {
grid-template-columns: 1fr;
}
.searchcue-admin h1 {
font-size: 34px;
}
.searchcue-status {
border-left: 0;
border-top: 1px solid var(--searchcue-line);
}
.searchcue-hero-copy,
.searchcue-analytics.is-in-hero,
.searchcue-status,
.searchcue-analytics,
.searchcue-settings {
padding-left: 22px;
padding-right: 22px;
}
}
</style>
<?php
}
function render_settings_page(): void
{
if (!current_user_can("manage_options")) {
return;
}
$options = get_options();
$effective_site_id = effective_site_id($options);
if ($effective_site_id === "") {
render_first_run_settings_page($options);
return;
}
render_connected_settings_page($options, $effective_site_id);
}
function render_first_run_settings_page(array $options): void
{
$sent = isset($_GET["searchcue_setup"]) && (string) $_GET["searchcue_setup"] === "sent";
?>
<div class="wrap searchcue-admin">
<?php render_settings_page_styles(); ?>
<section class="searchcue-hero">
<div class="searchcue-hero-copy">
<p class="searchcue-eyebrow">
<?php echo esc_html__("SearchCue for WordPress", "searchcue"); ?>
</p>
<h1><?php echo esc_html__("Welcome to SearchCue", "searchcue"); ?></h1>
<p class="searchcue-intro">
<?php echo esc_html__(
"You can try SearchCue for free on your site. Once connected, SearchCue indexes your public content and keeps your search index managed as you publish.",
"searchcue",
); ?>
</p>
</div>
<aside class="searchcue-status" aria-live="polite">
<span class="searchcue-status-badge is-needed">
<?php echo esc_html__("Setup needed", "searchcue"); ?>
</span>
<dl>
<div>
<dt><?php echo esc_html__("Site", "searchcue"); ?></dt>
<dd class="searchcue-mono"><?php echo esc_html(home_url("/")); ?></dd>
</div>
<div>
<dt><?php echo esc_html__("Cost", "searchcue"); ?></dt>
<dd><?php echo esc_html__("Free trial", "searchcue"); ?></dd>
</div>
</dl>
</aside>
</section>
<?php if ($sent): ?>
<p class="searchcue-alert">
<?php echo esc_html__(
"Check your email for the SearchCue sign-in link. This page will update when setup finishes in another tab.",
"searchcue",
); ?>
</p>
<?php endif; ?>
<section class="searchcue-onboarding">
<form action="<?php echo esc_url(admin_url("admin-post.php")); ?>" method="post">
<input type="hidden" name="action" value="searchcue_search_send_setup_link">
<?php wp_nonce_field("searchcue_search_setup", "searchcue_search_setup_nonce"); ?>
<label class="searchcue-label" for="searchcue_setup_email">
<?php echo esc_html__("Start with your email", "searchcue"); ?>
</label>
<p class="searchcue-help">
<?php echo esc_html__(
"You need an account to use SearchCue. Enter your email and we will send you a link to sign in.",
"searchcue",
); ?>
</p>
<div class="searchcue-onboarding-row">
<div class="searchcue-field">
<input
id="searchcue_setup_email"
class="searchcue-input regular-text"
name="searchcue_setup_email"
type="email"
autocomplete="email"
required
placeholder="you@example.com"
>
</div>
<div class="searchcue-actions">
<button class="button button-primary" type="submit">
<?php echo esc_html__("Try SearchCue for free", "searchcue"); ?>
</button>
</div>
</div>
</form>
<p class="searchcue-connect-note">
<?php echo esc_html__(
"Already have a SearchCue account? Use the same email link to connect it.",
"searchcue",
); ?>
</p>
</section>
<?php render_setup_polling_script(); ?>
</div>
<?php
}
function render_connected_settings_page(array $options, string $effective_site_id): void
{
?>
<div class="wrap searchcue-admin">
<?php render_settings_page_styles(); ?>
<section class="searchcue-hero is-connected">
<div class="searchcue-hero-copy">
<h1 class="searchcue-wordmark">
<span><?php echo esc_html__("SearchCue", "searchcue"); ?></span>
<span class="searchcue-wordmark-caret" aria-hidden="true"></span>
</h1>
<p class="searchcue-connected-status">
<span class="searchcue-connected-check" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none">
<path
d="M3.5 8.5 6.5 11.5 12.5 4.5"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
/>
</svg>
</span>
<span><?php echo esc_html__("SearchCue is connected", "searchcue"); ?></span>
</p>
</div>
<?php render_search_analytics_card($options, $effective_site_id); ?>
</section>
<form class="searchcue-settings" action="options.php" method="post" data-searchcue-settings>
<?php settings_fields(SETTINGS_GROUP); ?>
<label class="searchcue-toggle" for="searchcue_search_push_updates">
<input
class="searchcue-switch-input"
id="searchcue_search_push_updates"
name="<?php echo esc_attr(OPTION_NAME); ?>[push_updates]"
type="checkbox"
value="1"
<?php checked($options["push_updates"], "1"); ?>
>
<span class="searchcue-switch" aria-hidden="true"></span>
<span>
<span class="searchcue-toggle-title">
<?php echo esc_html__("Automatic updates", "searchcue"); ?>
</span>
<span class="searchcue-help">
<?php echo esc_html__(
"Keep the search index current as you update public pages, posts, custom content, and files.",
"searchcue",
); ?>
</span>
</span>
</label>
<details class="searchcue-advanced">
<summary><?php echo esc_html__("Advanced settings", "searchcue"); ?></summary>
<div class="searchcue-advanced-body">
<div class="searchcue-field">
<label class="searchcue-label" for="searchcue_search_site_id">
<?php echo esc_html__("SearchCue Site ID", "searchcue"); ?>
</label>
<input
id="searchcue_search_site_id"
class="searchcue-input regular-text searchcue-mono"
name="<?php echo esc_attr(OPTION_NAME); ?>[site_id]"
type="text"
value="<?php echo esc_attr($options["site_id"]); ?>"
placeholder="<?php echo esc_attr($options["assigned_site_id"] !== "" ? $options["assigned_site_id"] : "site_..."); ?>"
autocomplete="off"
>
<p class="searchcue-help">
<?php echo esc_html__(
"Only change this if you want to use a different search index than the default SearchCue assigned.",
"searchcue",
); ?>
</p>
</div>
</div>
</details>
<div class="searchcue-actions">
<button
class="button button-primary searchcue-save"
type="submit"
name="submit"
disabled
data-searchcue-save
>
<?php echo esc_html__("Save SearchCue settings", "searchcue"); ?>
</button>
</div>
</form>
<?php render_search_analytics_script(); ?>
<?php render_settings_form_dirty_script(); ?>
</div>
<?php
}
function render_settings_form_dirty_script(): void
{
?>
<script>
(function renderSettingsFormDirtyState() {
var form = document.querySelector("[data-searchcue-settings]");
if (!form) {
return;
}
var saveButton = form.querySelector("[data-searchcue-save]");
if (!saveButton) {
return;
}
var fields = Array.prototype.slice.call(
form.querySelectorAll(<?php echo wp_json_encode("input[name^='" . OPTION_NAME . "']"); ?>)
);
function currentValue(field) {
return field.type === "checkbox" ? (field.checked ? "1" : "0") : field.value;
}
fields.forEach(function (field) {
field.dataset.searchcueInitialValue = currentValue(field);
});
function hasChanges() {
return fields.some(function (field) {
return currentValue(field) !== field.dataset.searchcueInitialValue;
});
}
function syncSaveButton() {
saveButton.disabled = !hasChanges();
}
fields.forEach(function (field) {
field.addEventListener("change", syncSaveButton);
field.addEventListener("input", syncSaveButton);
});
syncSaveButton();
})();
</script>
<?php
}
function render_search_analytics_card(array $options, string $effective_site_id): void
{
$can_load_analytics = $options["api_key"] !== "";
?>
<div
class="searchcue-analytics is-in-hero"
data-searchcue-analytics
data-endpoint="<?php echo esc_url(admin_url("admin-ajax.php")); ?>"
data-nonce="<?php echo esc_attr(wp_create_nonce("searchcue_search_analytics")); ?>"
data-enabled="<?php echo esc_attr($can_load_analytics ? "1" : "0"); ?>"
>
<div class="searchcue-analytics-header">
<div>
<h2><?php echo esc_html__("Search activity", "searchcue"); ?></h2>
<p class="searchcue-analytics-kicker">
<?php echo esc_html__(
"A quick view of how visitors use SearchCue on this site.",
"searchcue",
); ?>
</p>
</div>
<div class="searchcue-analytics-meta">
<span class="searchcue-analytics-range" data-searchcue-analytics-range>
<?php echo esc_html__("Last 30 days", "searchcue"); ?>
</span>
</div>
</div>
<p class="searchcue-analytics-state" data-searchcue-analytics-state>
<?php echo esc_html__(
$can_load_analytics
? "Loading search activity..."
: "Search activity will appear here once this site is connected with a SearchCue API key.",
"searchcue",
); ?>
</p>
<div class="searchcue-hidden" data-searchcue-analytics-content>
<div class="searchcue-analytics-metrics">
<div class="searchcue-analytics-metric">
<span><?php echo esc_html__("Searches", "searchcue"); ?></span>
<strong data-searchcue-analytics-searches>0</strong>
</div>
<div class="searchcue-analytics-metric">
<span><?php echo esc_html__("Clicks", "searchcue"); ?></span>
<strong data-searchcue-analytics-clicks>0</strong>
</div>
<div class="searchcue-analytics-metric">
<span><?php echo esc_html__("No-result searches", "searchcue"); ?></span>
<strong data-searchcue-analytics-zero-results>0</strong>
</div>
</div>
<div class="searchcue-analytics-detail">
<div>
<h3><?php echo esc_html__("Recent search terms", "searchcue"); ?></h3>
<div class="searchcue-query-table" data-searchcue-analytics-query-table>
<table>
<thead>
<tr>
<th scope="col">
<?php echo esc_html__("Search term", "searchcue"); ?>
</th>
<th scope="col" class="searchcue-query-num">
<?php echo esc_html__("Searches", "searchcue"); ?>
</th>
</tr>
</thead>
<tbody data-searchcue-analytics-queries></tbody>
</table>
</div>
<p class="searchcue-empty searchcue-hidden" data-searchcue-analytics-empty-queries>
<?php echo esc_html__(
"Search terms will appear once visitors start searching.",
"searchcue",
); ?>
</p>
</div>
<div>
<h3><?php echo esc_html__("Search volume", "searchcue"); ?></h3>
<div class="searchcue-volume-chart" data-searchcue-analytics-volume></div>
<p class="searchcue-empty searchcue-hidden" data-searchcue-analytics-empty-volume>
<?php echo esc_html__(
"Search volume will appear once there is activity in the current period.",
"searchcue",
); ?>
</p>
</div>
</div>
</div>
</div>
<?php
}
function render_setup_polling_script(): void
{
$ajax_url = admin_url("admin-ajax.php");
$nonce = wp_create_nonce("searchcue_search_setup_status");
?>
<script>
(function () {
var endpoint = <?php echo wp_json_encode($ajax_url); ?>;
var nonce = <?php echo wp_json_encode($nonce); ?>;
function checkSetup() {
var url = endpoint + "?action=searchcue_search_setup_status&_ajax_nonce=" + encodeURIComponent(nonce);
fetch(url, { credentials: "same-origin" })
.then(function (response) { return response.json(); })
.then(function (payload) {
if (payload && payload.success && payload.data && payload.data.connected) {
window.location.reload();
}
})
.catch(function () {});
}
window.setInterval(checkSetup, 5000);
})();
</script>
<?php
}
function render_search_analytics_script(): void
{
?>
<script>
(function () {
var card = document.querySelector("[data-searchcue-analytics]");
if (!card || card.getAttribute("data-enabled") !== "1") {
return;
}
var endpoint = card.getAttribute("data-endpoint");
var nonce = card.getAttribute("data-nonce");
var state = card.querySelector("[data-searchcue-analytics-state]");
var content = card.querySelector("[data-searchcue-analytics-content]");
function setText(selector, value) {
var node = card.querySelector(selector);
if (node) {
node.textContent = formatCount(value);
}
}
function formatCount(value) {
var number = parseInt(value, 10);
if (isNaN(number)) {
number = 0;
}
return number.toLocaleString();
}
function showEmpty(selector, show) {
var node = card.querySelector(selector);
if (node) {
node.classList.toggle("searchcue-hidden", !show);
}
}
function renderQueries(queries) {
var body = card.querySelector("[data-searchcue-analytics-queries]");
var table = card.querySelector("[data-searchcue-analytics-query-table]");
if (!body) {
return;
}
body.innerHTML = "";
if (!queries || !queries.length) {
if (table) {
table.classList.add("searchcue-hidden");
}
showEmpty("[data-searchcue-analytics-empty-queries]", true);
return;
}
if (table) {
table.classList.remove("searchcue-hidden");
}
showEmpty("[data-searchcue-analytics-empty-queries]", false);
queries.forEach(function (query) {
var row = document.createElement("tr");
var term = document.createElement("td");
var count = document.createElement("td");
term.className = "searchcue-query-term";
term.textContent = query.term || "";
count.className = "searchcue-query-num";
count.textContent = formatCount(query.searches);
row.appendChild(term);
row.appendChild(count);
body.appendChild(row);
});
}
function renderVolume(points) {
var chart = card.querySelector("[data-searchcue-analytics-volume]");
if (!chart) {
return;
}
chart.innerHTML = "";
if (!points || !points.length) {
chart.classList.add("searchcue-hidden");
showEmpty("[data-searchcue-analytics-empty-volume]", true);
return;
}
chart.classList.remove("searchcue-hidden");
showEmpty("[data-searchcue-analytics-empty-volume]", false);
var max = points.reduce(function (current, point) {
return Math.max(current, parseInt(point.count, 10) || 0);
}, 0);
var width = 360;
var height = 160;
var plot = {
left: 32,
right: 354,
top: 8,
bottom: 132
};
var plotWidth = plot.right - plot.left;
var plotHeight = plot.bottom - plot.top;
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var chartPoints = points.map(function (point, index) {
var value = parseInt(point.count, 10) || 0;
return {
label: point.label || "",
value: value,
x: points.length === 1
? plot.left + plotWidth / 2
: plot.left + index / (points.length - 1) * plotWidth,
y: max > 0
? plot.top + (1 - value / max) * plotHeight
: plot.bottom
};
});
svg.setAttribute("viewBox", "0 0 " + width + " " + height);
svg.setAttribute("role", "img");
svg.setAttribute(
"aria-label",
"Search volume by day. " + chartPoints.map(function (point) {
return point.label + ": " + formatCount(point.value) +
(point.value === 1 ? " search" : " searches");
}).join(", ")
);
var tickValues = max > 0 ? [max, max / 2, 0] : [0];
tickValues.forEach(function (tickValue) {
var tickY = max > 0
? plot.top + (1 - tickValue / max) * plotHeight
: plot.bottom;
var grid = document.createElementNS("http://www.w3.org/2000/svg", "line");
var label = document.createElementNS("http://www.w3.org/2000/svg", "text");
var roundedTick = Math.round(tickValue * 10) / 10;
grid.setAttribute("x1", plot.left);
grid.setAttribute("y1", tickY);
grid.setAttribute("x2", plot.right);
grid.setAttribute("y2", tickY);
grid.setAttribute(
"class",
tickValue === 0 ? "searchcue-volume-axis" : "searchcue-volume-grid"
);
label.setAttribute("x", plot.left - 8);
label.setAttribute("y", tickY);
label.setAttribute("text-anchor", "end");
label.setAttribute("dominant-baseline", "middle");
label.textContent = roundedTick.toLocaleString();
svg.appendChild(grid);
svg.appendChild(label);
});
chartPoints.forEach(function (point) {
var xLabel = document.createElementNS("http://www.w3.org/2000/svg", "text");
xLabel.setAttribute("x", point.x);
xLabel.setAttribute("y", plot.bottom + 20);
xLabel.setAttribute("text-anchor", "middle");
xLabel.textContent = point.label;
svg.appendChild(xLabel);
});
var line = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
line.setAttribute("class", "searchcue-volume-line");
line.setAttribute("points", chartPoints.map(function (point) {
return point.x + "," + point.y;
}).join(" "));
svg.appendChild(line);
chartPoints.forEach(function (point) {
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
var title = document.createElementNS("http://www.w3.org/2000/svg", "title");
circle.setAttribute("class", "searchcue-volume-point");
circle.setAttribute("cx", point.x);
circle.setAttribute("cy", point.y);
circle.setAttribute("r", 4);
title.textContent = point.label + ": " + formatCount(point.value) +
(point.value === 1 ? " search" : " searches");
circle.appendChild(title);
svg.appendChild(circle);
});
chart.appendChild(svg);
}
fetch(endpoint + "?action=searchcue_search_analytics&_ajax_nonce=" + encodeURIComponent(nonce), {
credentials: "same-origin"
})
.then(function (response) { return response.json(); })
.then(function (payload) {
if (!payload || !payload.success || !payload.data) {
throw new Error("analytics unavailable");
}
var data = payload.data;
var range = card.querySelector("[data-searchcue-analytics-range]");
if (range && data.range && data.range.label) {
range.textContent = data.range.label;
}
setText("[data-searchcue-analytics-searches]", data.totals && data.totals.searches);
setText("[data-searchcue-analytics-clicks]", data.totals && data.totals.clicks);
setText("[data-searchcue-analytics-zero-results]", data.totals && data.totals.zeroResults);
renderQueries(data.topQueries || []);
renderVolume(data.dailyVolume || []);
if (state) {
state.classList.add("searchcue-hidden");
}
if (content) {
content.classList.remove("searchcue-hidden");
}
})
.catch(function () {
if (state) {
state.textContent = "Search activity is not available right now.";
}
});
})();
</script>
<?php
}
function send_setup_link(): void
{
if (!current_user_can("manage_options")) {
status_header(403);
return;
}
check_admin_referer("searchcue_search_setup", "searchcue_search_setup_nonce");
$email = isset($_POST["searchcue_setup_email"])
? sanitize_email(wp_unslash($_POST["searchcue_setup_email"]))
: "";
if (!is_email($email)) {
redirect_to_settings(["searchcue_setup" => "invalid_email"]);
return;
}
$options = ensure_setup_state(get_options());
$response = wp_safe_remote_post(wordpress_integration_url("/setup-link"), [
"timeout" => 10,
"headers" => [
"Content-Type" => "application/json",
],
"body" => wp_json_encode([
"email" => $email,
"site_url" => home_url("/"),
"return_url" => settings_page_url(),
"state" => $options["setup_state"],
]),
]);
if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
redirect_to_settings(["searchcue_setup" => "sent"]);
return;
}
redirect_to_settings(["searchcue_setup" => "send_failed"]);
}
function maybe_complete_setup_from_handoff(): void
{
if (!current_user_can("manage_options")) {
return;
}
if (!isset($_GET["state"], $_GET["handoff"])) {
return;
}
$state = sanitize_text_field(wp_unslash($_GET["state"]));
$handoff = sanitize_text_field(wp_unslash($_GET["handoff"]));
$options = get_options();
if ($state === "" || $handoff === "" || $state !== $options["setup_state"]) {
redirect_to_settings(["searchcue_setup" => "state_mismatch"]);
return;
}
$claim = claim_handoff($handoff);
if ($claim === null) {
redirect_to_settings(["searchcue_setup" => "claim_failed"]);
return;
}
$options["api_key"] = $claim["api_key"];
$options["assigned_site_id"] = $claim["site_id"];
update_option(OPTION_NAME, sanitize_options($options));
redirect_to_settings(["searchcue_setup" => "connected"]);
}
function ajax_setup_status(): void
{
if (!current_user_can("manage_options")) {
wp_send_json_error(["connected" => false]);
return;
}
check_ajax_referer("searchcue_search_setup_status");
$options = get_options();
$site_id = effective_site_id($options);
wp_send_json_success([
"connected" => $site_id !== "",
"siteId" => $site_id,
"assignedSiteId" => $options["assigned_site_id"],
]);
}
function ajax_search_analytics(): void
{
if (!current_user_can("manage_options")) {
wp_send_json_error(["message" => "forbidden"]);
return;
}
check_ajax_referer("searchcue_search_analytics");
$options = get_options();
if ($options["api_key"] === "") {
wp_send_json_error(["message" => "missing_api_key"]);
return;
}
$analytics = fetch_site_analytics($options["api_key"]);
if ($analytics === null) {
wp_send_json_error(["message" => "analytics_unavailable"]);
return;
}
wp_send_json_success($analytics);
}
/**
* @return array{range: array{label: string, days: int}, totals: array{searches: int, zeroResults: int, clicks: int}, topQueries: array<int, array{term: string, searches: int}>, dailyVolume: array<int, array{label: string, count: int}>}|null
*/
function fetch_site_analytics(string $api_key): ?array
{
$response = wp_remote_get(wordpress_integration_url("/analytics.json"), [
"timeout" => 10,
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer " . $api_key,
],
]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return null;
}
$payload = json_decode(wp_remote_retrieve_body($response), true);
return sanitize_site_analytics_payload($payload);
}
/**
* @param mixed $payload
*
* @return array{range: array{label: string, days: int}, totals: array{searches: int, zeroResults: int, clicks: int}, topQueries: array<int, array{term: string, searches: int}>, dailyVolume: array<int, array{label: string, count: int}>}|null
*/
function sanitize_site_analytics_payload($payload): ?array
{
if (!is_array($payload)) {
return null;
}
$range = is_array($payload["range"] ?? null) ? $payload["range"] : [];
$totals = is_array($payload["totals"] ?? null) ? $payload["totals"] : [];
$top_queries = is_array($payload["topQueries"] ?? null) ? $payload["topQueries"] : [];
$daily_volume = is_array($payload["dailyVolume"] ?? null) ? $payload["dailyVolume"] : [];
return [
"range" => [
"label" => sanitize_text_field($range["label"] ?? "30 days"),
"days" => max(0, (int) ($range["days"] ?? 30)),
],
"totals" => [
"searches" => max(0, (int) ($totals["searches"] ?? 0)),
"zeroResults" => max(0, (int) ($totals["zeroResults"] ?? 0)),
"clicks" => max(0, (int) ($totals["clicks"] ?? 0)),
],
"topQueries" => sanitize_site_analytics_queries($top_queries),
"dailyVolume" => sanitize_site_analytics_volume($daily_volume),
];
}
/**
* @param array<int, mixed> $queries
*
* @return array<int, array{term: string, searches: int}>
*/
function sanitize_site_analytics_queries(array $queries): array
{
$sanitized = [];
foreach (array_slice($queries, 0, 5) as $query) {
if (!is_array($query)) {
continue;
}
$term = sanitize_text_field($query["term"] ?? "");
if ($term === "") {
continue;
}
$sanitized[] = [
"term" => $term,
"searches" => max(0, (int) ($query["searches"] ?? 0)),
];
}
return $sanitized;
}
/**
* @param array<int, mixed> $points
*
* @return array<int, array{label: string, count: int}>
*/
function sanitize_site_analytics_volume(array $points): array
{
$sanitized = [];
foreach (array_slice($points, -7) as $point) {
if (!is_array($point)) {
continue;
}
$label = sanitize_text_field($point["label"] ?? "");
if ($label === "") {
continue;
}
$sanitized[] = [
"label" => $label,
"count" => max(0, (int) ($point["count"] ?? 0)),
];
}
return $sanitized;
}
/**
* @return array{api_key: string, site_id: string}|null
*/
function claim_handoff(string $handoff): ?array
{
$response = wp_safe_remote_post(wordpress_integration_url("/claim"), [
"timeout" => 10,
"headers" => [
"Content-Type" => "application/json",
],
"body" => wp_json_encode(["handoff" => $handoff]),
]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return null;
}
$payload = json_decode(wp_remote_retrieve_body($response), true);
if (
!is_array($payload) ||
!isset($payload["apiKey"], $payload["siteId"]) ||
!is_string($payload["apiKey"]) ||
!is_string($payload["siteId"])
) {
return null;
}
return [
"api_key" => sanitize_hidden_value($payload["apiKey"]),
"site_id" => sanitize_hidden_value($payload["siteId"]),
];
}
function searchcue_admin_url(array $options, string $destination): string
{
$site_id = rawurlencode(effective_site_id($options));
switch ($destination) {
case "documentation":
return searchcue_app_url("/site-search/app/documentation");
case "design":
return searchcue_app_url("/site-search/app/site/" . $site_id . "/design");
case "analytics":
return searchcue_app_url("/site-search/app/site/" . $site_id . "/analytics");
case "more":
default:
return searchcue_app_url("/site-search/app/site/" . $site_id);
}
}
function searchcue_app_url(string $path): string
{
return rtrim(SEARCHCUE_APP_ENDPOINT, "/") . "/" . ltrim($path, "/");
}
function wordpress_integration_url(string $path): string
{
return rtrim(WORDPRESS_INTEGRATION_ENDPOINT, "/") . "/" . ltrim($path, "/");
}
function settings_page_url(): string
{
return admin_url("admin.php?page=" . SETTINGS_PAGE);
}
function redirect_to_settings(array $params): void
{
wp_safe_redirect(add_query_arg($params, settings_page_url()));
if (!defined("SEARCHCUE_SEARCH_TESTING") || SEARCHCUE_SEARCH_TESTING !== true) {
exit();
}
}
function ensure_setup_state(array $options): array
{
if ($options["setup_state"] === "") {
$options["setup_state"] = generate_setup_state();
update_option(OPTION_NAME, sanitize_options($options));
}
return $options;
}
function sanitize_hidden_value(string $value): string
{
return preg_replace("/[^A-Za-z0-9_-]/", "", trim($value)) ?? "";
}
function register_update_hooks(): void
{
add_action("save_post", __NAMESPACE__ . "\\queue_post_update", 10, 3);
add_action("transition_post_status", __NAMESPACE__ . "\\queue_transition_update", 10, 3);
add_action("trashed_post", __NAMESPACE__ . "\\queue_post_update");
add_action("untrashed_post", __NAMESPACE__ . "\\queue_post_update");
add_action("deleted_post", __NAMESPACE__ . "\\queue_post_update");
add_action("add_attachment", __NAMESPACE__ . "\\queue_attachment_update");
add_action("edit_attachment", __NAMESPACE__ . "\\queue_attachment_update");
add_action("delete_attachment", __NAMESPACE__ . "\\queue_attachment_update");
add_action("shutdown", __NAMESPACE__ . "\\flush_indexnow_updates");
}
function maybe_redirect_after_activation(): void
{
if (get_transient(ACTIVATION_REDIRECT_TRANSIENT) !== "1") {
return;
}
if (!current_user_can("manage_options")) {
return;
}
if (function_exists("wp_doing_ajax") && wp_doing_ajax()) {
return;
}
delete_transient(ACTIVATION_REDIRECT_TRANSIENT);
wp_safe_redirect(settings_page_url());
if (!defined("SEARCHCUE_SEARCH_TESTING") || SEARCHCUE_SEARCH_TESTING !== true) {
exit();
}
}
function serve_indexnow_keyfile(): void
{
$path = wp_parse_url($_SERVER["REQUEST_URI"] ?? "", PHP_URL_PATH);
$content = keyfile_content_for_path(is_string($path) ? $path : "");
if ($content === null) {
return;
}
status_header(200);
header("Content-Type: text/plain; charset=utf-8");
header("X-Robots-Tag: noindex");
echo $content;
if (!defined("SEARCHCUE_SEARCH_TESTING") || SEARCHCUE_SEARCH_TESTING !== true) {
exit();
}
}
function keyfile_content_for_path(string $path): ?string
{
$options = get_options();
if ($options["push_updates"] !== "1" || $options["indexnow_key"] === "") {
return null;
}
$expected_path = "/" . $options["indexnow_key"] . ".txt";
return rawurldecode($path) === $expected_path ? $options["indexnow_key"] : null;
}
function queue_transition_update(string $new_status, string $old_status, $post): void
{
$post_id = is_object($post) && isset($post->ID) ? (int) $post->ID : 0;
if ($post_id > 0) {
queue_post_update($post_id);
}
}
function queue_post_update(int $post_id): void
{
if (!updates_enabled() || wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
return;
}
$post = get_post($post_id);
if (!$post || !public_post_type($post)) {
return;
}
$url = get_permalink($post_id);
if (is_string($url) && $url !== "") {
queue_indexnow_url($url);
}
}
function queue_attachment_update(int $post_id): void
{
if (!updates_enabled()) {
return;
}
$url = wp_get_attachment_url($post_id);
if (is_string($url) && $url !== "") {
queue_indexnow_url($url);
}
}
function queue_indexnow_url(string $url): void
{
global $pending_indexnow_urls;
if (!updates_enabled() || !same_host_url($url)) {
return;
}
$pending_indexnow_urls[] = $url;
}
function flush_indexnow_updates(): void
{
global $pending_indexnow_urls;
if (!updates_enabled() || empty($pending_indexnow_urls)) {
$pending_indexnow_urls = [];
return;
}
$options = get_options();
$urls = array_values(array_unique($pending_indexnow_urls));
$pending_indexnow_urls = [];
$host = home_host();
if ($host === null || empty($urls)) {
return;
}
wp_remote_post(INDEXNOW_ENDPOINT, [
"timeout" => 2,
"headers" => [
"Content-Type" => "application/json",
],
"body" => json_encode([
"host" => $host,
"key" => $options["indexnow_key"],
"keyLocation" => indexnow_key_location($options["indexnow_key"]),
"urlList" => $urls,
]),
]);
}
function updates_enabled(): bool
{
$options = get_options();
return effective_site_id($options) !== "" &&
$options["push_updates"] === "1" &&
$options["indexnow_key"] !== "";
}
function public_post_type($post): bool
{
$post_type = get_post_type($post);
$post_type_object = get_post_type_object($post_type);
return is_object($post_type_object) && !empty($post_type_object->public);
}
function same_host_url(string $url): bool
{
$home_host = home_host();
$url_host = wp_parse_url($url, PHP_URL_HOST);
return is_string($home_host) &&
is_string($url_host) &&
strcasecmp($home_host, $url_host) === 0;
}
function home_host(): ?string
{
$host = wp_parse_url(home_url("/"), PHP_URL_HOST);
return is_string($host) && $host !== "" ? $host : null;
}
function indexnow_key_location(string $key): string
{
return (string) preg_replace("/^http:/i", "https:", home_url("/" . $key . ".txt"));
}
function generate_indexnow_key(): string
{
return wp_generate_password(48, false, false);
}
function generate_setup_state(): string
{
return wp_generate_password(32, false, false);
}
bootstrap(); <?php
declare(strict_types=1);
$tests = [];
function test(string $name, callable $callback): void
{
global $tests;
$tests[] = [$name, $callback];
}
function assert_true(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function assert_false(bool $condition, string $message): void
{
assert_true(!$condition, $message);
}
function assert_contains(
string $needle,
string $haystack,
string $message
): void {
assert_true(strpos($haystack, $needle) !== false, $message);
}
function assert_not_contains(
string $needle,
string $haystack,
string $message
): void {
assert_false(strpos($haystack, $needle) !== false, $message);
}
function assert_same($expected, $actual, string $message): void
{
if ($expected !== $actual) {
throw new RuntimeException(
$message .
"\nExpected: " .
var_export($expected, true) .
"\nActual: " .
var_export($actual, true),
);
}
}
$GLOBALS["searchcue_test_actions"] = [];
$GLOBALS["searchcue_test_options"] = [];
$GLOBALS["searchcue_test_option_updates"] = 0;
$GLOBALS["searchcue_test_registered_settings"] = [];
$GLOBALS["searchcue_test_sections"] = [];
$GLOBALS["searchcue_test_fields"] = [];
$GLOBALS["searchcue_test_menu_pages"] = [];
$GLOBALS["searchcue_test_submenu_pages"] = [];
$GLOBALS["searchcue_test_activation_hooks"] = [];
$GLOBALS["searchcue_test_transients"] = [];
$GLOBALS["searchcue_test_remote_posts"] = [];
$GLOBALS["searchcue_test_remote_gets"] = [];
$GLOBALS["searchcue_test_remote_post_responses"] = [];
$GLOBALS["searchcue_test_remote_get_responses"] = [];
$GLOBALS["searchcue_test_posts"] = [];
$GLOBALS["searchcue_test_redirects"] = [];
$GLOBALS["searchcue_test_status_headers"] = [];
$GLOBALS["searchcue_test_home_url"] = "https://example.test";
function reset_wp_stubs(): void
{
$GLOBALS["searchcue_test_actions"] = [];
$GLOBALS["searchcue_test_options"] = [];
$GLOBALS["searchcue_test_option_updates"] = 0;
$GLOBALS["searchcue_test_registered_settings"] = [];
$GLOBALS["searchcue_test_sections"] = [];
$GLOBALS["searchcue_test_fields"] = [];
$GLOBALS["searchcue_test_menu_pages"] = [];
$GLOBALS["searchcue_test_submenu_pages"] = [];
$GLOBALS["searchcue_test_activation_hooks"] = [];
$GLOBALS["searchcue_test_transients"] = [];
$GLOBALS["searchcue_test_remote_posts"] = [];
$GLOBALS["searchcue_test_remote_gets"] = [];
$GLOBALS["searchcue_test_remote_post_responses"] = [];
$GLOBALS["searchcue_test_remote_get_responses"] = [];
$GLOBALS["searchcue_test_posts"] = [];
$GLOBALS["searchcue_test_redirects"] = [];
$GLOBALS["searchcue_test_status_headers"] = [];
$GLOBALS["searchcue_test_home_url"] = "https://example.test";
}
function add_action(
string $hook_name,
$callback,
int $priority = 10,
int $accepted_args = 1
): void
{
$GLOBALS["searchcue_test_actions"][$hook_name][] = compact(
"callback",
"priority",
"accepted_args",
);
}
function add_menu_page(
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
$callback,
string $icon_url = "",
$position = null
): void {
$GLOBALS["searchcue_test_menu_pages"][] = compact(
"page_title",
"menu_title",
"capability",
"menu_slug",
"callback",
"icon_url",
"position",
);
}
function add_submenu_page(
string $parent_slug,
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
$callback = "",
$position = null
): void {
$GLOBALS["searchcue_test_submenu_pages"][] = compact(
"parent_slug",
"page_title",
"menu_title",
"capability",
"menu_slug",
"callback",
"position",
);
}
function plugin_dir_url(string $file): string
{
return "https://example.test/wp-content/plugins/searchcue/";
}
function register_setting(
string $option_group,
string $option_name,
array $args
): void {
$GLOBALS["searchcue_test_registered_settings"][] = compact(
"option_group",
"option_name",
"args",
);
}
function add_settings_section(
string $id,
string $title,
$callback,
string $page
): void {
$GLOBALS["searchcue_test_sections"][] = compact(
"id",
"title",
"callback",
"page",
);
}
function add_settings_field(
string $id,
string $title,
$callback,
string $page,
string $section
): void {
$GLOBALS["searchcue_test_fields"][] = compact(
"id",
"title",
"callback",
"page",
"section",
);
}
function register_activation_hook(string $file, $callback): void
{
$GLOBALS["searchcue_test_activation_hooks"][] = compact("file", "callback");
}
function get_option(string $option_name, $default = false)
{
return array_key_exists($option_name, $GLOBALS["searchcue_test_options"])
? $GLOBALS["searchcue_test_options"][$option_name]
: $default;
}
function add_option(string $option_name, $value): void
{
if (!array_key_exists($option_name, $GLOBALS["searchcue_test_options"])) {
$GLOBALS["searchcue_test_options"][$option_name] = $value;
}
}
function update_option(string $option_name, $value): void
{
++$GLOBALS["searchcue_test_option_updates"];
$GLOBALS["searchcue_test_options"][$option_name] = $value;
}
function set_transient(string $transient, $value, int $expiration = 0): void
{
$GLOBALS["searchcue_test_transients"][$transient] = $value;
}
function get_transient(string $transient)
{
return $GLOBALS["searchcue_test_transients"][$transient] ?? false;
}
function delete_transient(string $transient): void
{
unset($GLOBALS["searchcue_test_transients"][$transient]);
}
function checked($checked, $current = true, bool $display = true): string
{
$result = (string) $checked === (string) $current ? ' checked="checked"' : "";
if ($display) {
echo $result;
}
return $result;
}
function esc_attr($value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
}
function esc_html($value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
}
function esc_url($value): string
{
return str_replace("&", "&", filter_var((string) $value, FILTER_SANITIZE_URL));
}
function esc_url_raw($value): string
{
return filter_var((string) $value, FILTER_SANITIZE_URL);
}
function settings_fields(string $option_group): void
{
echo '<input type="hidden" name="option_page" value="' .
esc_attr($option_group) .
'">';
}
function __($text, string $domain = "default"): string
{
return (string) $text;
}
function esc_html__($text, string $domain = "default"): string
{
return esc_html($text);
}
function wp_generate_password(
int $length = 12,
bool $special_chars = true,
bool $extra_special_chars = false
): string {
return str_repeat("k", $length);
}
function home_url(string $path = ""): string
{
return rtrim($GLOBALS["searchcue_test_home_url"], "/") . "/" . ltrim($path, "/");
}
function wp_parse_url(string $url, int $component = -1)
{
return $component === -1 ? parse_url($url) : parse_url($url, $component);
}
function sanitize_email($email): string
{
return filter_var((string) $email, FILTER_SANITIZE_EMAIL);
}
function is_email($email)
{
return filter_var((string) $email, FILTER_VALIDATE_EMAIL) ? (string) $email : false;
}
function sanitize_text_field($value): string
{
return trim(strip_tags((string) $value));
}
function wp_unslash($value)
{
return $value;
}
function wp_json_encode($value): string
{
return json_encode($value);
}
function wp_create_nonce(string $action): string
{
return "nonce_" . $action;
}
function wp_nonce_field(
string $action,
string $name = "_wpnonce",
bool $referer = true,
bool $display = true
): string {
$field =
'<input type="hidden" name="' .
esc_attr($name) .
'" value="' .
esc_attr(wp_create_nonce($action)) .
'">';
if ($display) {
echo $field;
}
return $field;
}
function check_admin_referer(string $action, string $query_arg = "_wpnonce"): bool
{
return true;
}
function check_ajax_referer(
string $action = "-1",
$query_arg = false,
bool $stop = true
): bool {
return true;
}
function add_query_arg($args, string $url = ""): string
{
if (!is_array($args)) {
return $url;
}
$parts = parse_url($url);
$query = [];
if (isset($parts["query"])) {
parse_str($parts["query"], $query);
}
$query = array_merge($query, $args);
$scheme = isset($parts["scheme"]) ? $parts["scheme"] . "://" : "";
$host = $parts["host"] ?? "";
$path = $parts["path"] ?? "";
$fragment = isset($parts["fragment"]) ? "#" . $parts["fragment"] : "";
return $scheme . $host . $path . "?" . http_build_query($query) . $fragment;
}
function get_post(int $post_id)
{
return isset($GLOBALS["searchcue_test_posts"][$post_id])
? (object) $GLOBALS["searchcue_test_posts"][$post_id]
: null;
}
function get_post_type($post): string
{
if (is_object($post) && isset($post->post_type)) {
return (string) $post->post_type;
}
if (is_int($post) && isset($GLOBALS["searchcue_test_posts"][$post]["post_type"])) {
return (string) $GLOBALS["searchcue_test_posts"][$post]["post_type"];
}
return "post";
}
function get_post_type_object(string $post_type)
{
return (object) [
"public" => $post_type !== "private_type",
];
}
function get_permalink(int $post_id)
{
return $GLOBALS["searchcue_test_posts"][$post_id]["permalink"] ?? false;
}
function wp_is_post_revision(int $post_id): bool
{
return (bool) ($GLOBALS["searchcue_test_posts"][$post_id]["revision"] ?? false);
}
function wp_is_post_autosave(int $post_id): bool
{
return (bool) ($GLOBALS["searchcue_test_posts"][$post_id]["autosave"] ?? false);
}
function wp_get_attachment_url(int $post_id)
{
return $GLOBALS["searchcue_test_posts"][$post_id]["attachment_url"] ?? false;
}
function wp_remote_post(string $url, array $args)
{
$GLOBALS["searchcue_test_remote_posts"][] = compact("url", "args");
if (!empty($GLOBALS["searchcue_test_remote_post_responses"])) {
return array_shift($GLOBALS["searchcue_test_remote_post_responses"]);
}
return ["response" => ["code" => 200], "body" => "{}"];
}
function wp_safe_remote_post(string $url, array $args)
{
return wp_remote_post($url, $args);
}
function wp_remote_get(string $url, array $args = [])
{
$GLOBALS["searchcue_test_remote_gets"][] = compact("url", "args");
if (!empty($GLOBALS["searchcue_test_remote_get_responses"])) {
return array_shift($GLOBALS["searchcue_test_remote_get_responses"]);
}
return ["response" => ["code" => 200], "body" => "{}"];
}
function wp_remote_retrieve_response_code($response): int
{
return (int) ($response["response"]["code"] ?? 0);
}
function wp_remote_retrieve_body($response): string
{
return (string) ($response["body"] ?? "");
}
function is_wp_error($value): bool
{
return false;
}
function admin_url(string $path = ""): string
{
return "https://example.test/wp-admin/" . ltrim($path, "/");
}
function current_user_can(string $capability): bool
{
return $capability === "manage_options";
}
function wp_safe_redirect(string $location): void
{
$GLOBALS["searchcue_test_redirects"][] = $location;
}
function wp_redirect(string $location): void
{
$GLOBALS["searchcue_test_redirects"][] = $location;
}
function status_header(int $code): void
{
$GLOBALS["searchcue_test_status_headers"][] = $code;
}
function wp_send_json($response): void
{
echo json_encode($response);
}
function wp_send_json_success($data = null): void
{
wp_send_json(["success" => true, "data" => $data]);
}
function wp_send_json_error($data = null): void
{
wp_send_json(["success" => false, "data" => $data]);
}
function render_wp_head(): string
{
ob_start();
foreach ($GLOBALS["searchcue_test_actions"]["wp_head"] ?? [] as $action) {
call_user_func($action["callback"]);
}
return ob_get_clean();
}
if (!defined("ABSPATH")) {
define("ABSPATH", dirname(__DIR__) . "/wordpress-test-root/");
}
if (!defined("SEARCHCUE_SEARCH_TESTING")) {
define("SEARCHCUE_SEARCH_TESTING", true);
}
require dirname(__DIR__) . "/searchcue.php";
function set_searchcue_options(array $overrides): void
{
$GLOBALS["searchcue_test_options"]["searchcue_search_options"] = array_merge(
SearchCue_Search_Plugin\default_options(),
$overrides,
);
}
test("documents WordPress 7 compatibility while preserving older minimums", function (): void {
$plugin_source = file_get_contents(dirname(__DIR__) . "/searchcue.php");
assert_contains(
"Requires at least: 6.0",
$plugin_source,
"Expected plugin header to keep the WordPress 6.0 minimum.",
);
assert_contains(
"Requires PHP: 7.4",
$plugin_source,
"Expected plugin header to keep the PHP 7.4 minimum required by WordPress 7.0.",
);
$readme_path = dirname(__DIR__) . "/readme.txt";
assert_true(is_file($readme_path), "Expected WordPress readme metadata.");
$readme = file_get_contents($readme_path);
assert_contains("Requires at least: 6.0", $readme, "Expected readme to preserve older WordPress support.");
assert_contains("Tested up to: 7.0", $readme, "Expected readme to document WordPress 7.0 testing.");
assert_contains("Requires PHP: 7.4", $readme, "Expected readme to preserve the PHP 7.4 floor.");
});
test("registers the WordPress hooks used by the plugin", function (): void {
assert_true(
isset($GLOBALS["searchcue_test_actions"]["wp_head"]),
"Expected wp_head action to be registered.",
);
assert_true(
isset($GLOBALS["searchcue_test_actions"]["admin_menu"]),
"Expected admin_menu action to be registered.",
);
assert_true(
isset($GLOBALS["searchcue_test_actions"]["admin_init"]),
"Expected admin_init action to be registered.",
);
assert_false(
isset($GLOBALS["searchcue_test_actions"]["admin_post_searchcue_search_connect"]),
"Expected direct existing-account connect action not to be registered.",
);
assert_false(
isset($GLOBALS["searchcue_test_actions"]["admin_post_searchcue_search_complete_setup"]),
"Expected setup completion to happen directly from the SearchCue handoff return.",
);
assert_false(
isset($GLOBALS["searchcue_test_actions"]["admin_post_searchcue_search_open_admin"]),
"Expected submenu links to go straight to SearchCue without a WordPress action.",
);
assert_same(
1,
count($GLOBALS["searchcue_test_activation_hooks"]),
"Expected one activation hook.",
);
});
test(
"activation stores defaults without overwriting an existing option",
function (): void {
call_user_func($GLOBALS["searchcue_test_activation_hooks"][0]["callback"]);
$options = get_option("searchcue_search_options");
assert_same("", $options["site_id"], "Expected empty site id default.");
assert_same("", $options["assigned_site_id"], "Expected empty assigned site id default.");
assert_same("", $options["api_key"], "Expected empty API key default.");
assert_true(
isset($options["setup_state"]) && $options["setup_state"] !== "",
"Expected setup state default.",
);
assert_false(
array_key_exists("pending_handoff", $options),
"Expected no stored pending handoff state.",
);
assert_same("1", $options["push_updates"], "Expected push updates default.");
assert_same(str_repeat("k", 48), $options["indexnow_key"], "Expected generated key.");
assert_same(
"1",
get_transient("searchcue_search_activation_redirect"),
"Expected activation redirect marker.",
);
set_searchcue_options([
"site_id" => "site_existing",
"push_updates" => "0",
"indexnow_key" => "existing_key",
]);
call_user_func($GLOBALS["searchcue_test_activation_hooks"][0]["callback"]);
$existing_options = get_option("searchcue_search_options");
assert_same("site_existing", $existing_options["site_id"], "Activation should not overwrite Site ID.");
assert_same("0", $existing_options["push_updates"], "Activation should not overwrite settings.");
assert_same("existing_key", $existing_options["indexnow_key"], "Activation should not overwrite update key.");
},
);
test("reads plugin options without writing missing defaults back", function (): void {
$options = SearchCue_Search_Plugin\get_options();
assert_same("", $options["site_id"], "Expected defaults when no option is stored.");
assert_same(
0,
$GLOBALS["searchcue_test_option_updates"],
"Reading unset options should not write defaults back to the database.",
);
set_searchcue_options(["site_id" => "site_existing"]);
$GLOBALS["searchcue_test_option_updates"] = 0;
$options = SearchCue_Search_Plugin\get_options();
assert_same("site_existing", $options["site_id"], "Expected stored options to be returned.");
assert_same(
0,
$GLOBALS["searchcue_test_option_updates"],
"Reading stored options should not write sanitized values back to the database.",
);
});
test(
"renders the embed script in the page head when configured",
function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "test_key",
]);
$html = render_wp_head();
assert_contains(
"<!-- Start SearchCue embed -->",
$html,
"Expected embed start marker.",
);
assert_contains(
"s.src = 'https://searchcue.com/search-embed.js'",
$html,
"Expected production SearchCue embed URL.",
);
assert_contains(
"s.setAttribute('siteid', 'site_abc123')",
$html,
"Expected configured site id.",
);
assert_contains("s.async = true", $html, "Expected async script loading.");
assert_contains(
"document.createElement('script')",
$html,
"Expected dynamic script creation.",
);
},
);
test(
"renders the embed with the assigned site id when no manual override is set",
function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_test",
"push_updates" => "1",
"indexnow_key" => "test_key",
]);
$html = render_wp_head();
assert_contains(
"s.setAttribute('siteid', 'site_assigned123')",
$html,
"Expected assigned site id to be used by the embed.",
);
},
);
test(
"does not render the embed when missing an effective site id",
function (): void {
set_searchcue_options([
"site_id" => "",
"push_updates" => "1",
"indexnow_key" => "test_key",
]);
assert_same(
"",
trim(render_wp_head()),
"Missing site id should not output an embed.",
);
},
);
test("sanitizes admin options before storing them", function (): void {
$sanitized = SearchCue_Search_Plugin\sanitize_options([
"site_id" => " site_<script>abc 123 ",
"assigned_site_id" => " assigned<script>456 ",
"api_key" => " wsk_bad key! ",
"setup_state" => " setup state! ",
"push_updates" => "0",
"indexnow_key" => " bad key! ",
]);
assert_same(
"site_scriptabc123",
$sanitized["site_id"],
"Expected unsafe characters stripped from site id.",
);
assert_same(
"assignedscript456",
$sanitized["assigned_site_id"],
"Expected unsafe characters stripped from assigned site id.",
);
assert_same("wsk_badkey", $sanitized["api_key"], "Expected API key sanitized.");
assert_same("setupstate", $sanitized["setup_state"], "Expected setup state sanitized.");
assert_same("0", $sanitized["push_updates"], "Expected push setting.");
assert_same("badkey", $sanitized["indexnow_key"], "Expected key sanitized.");
});
test("preserves the hidden update key when saving admin options", function (): void {
set_searchcue_options([
"site_id" => "site_existing",
"assigned_site_id" => "site_assigned",
"api_key" => "wsk_existing",
"setup_state" => "state_existing",
"push_updates" => "1",
"indexnow_key" => "existing_key",
]);
$sanitized = SearchCue_Search_Plugin\sanitize_options([
"site_id" => "site_updated",
"push_updates" => "0",
]);
assert_same("site_updated", $sanitized["site_id"], "Expected updated site id.");
assert_same("0", $sanitized["push_updates"], "Expected updated automatic setting.");
assert_same(
"existing_key",
$sanitized["indexnow_key"],
"Expected existing hidden update key to be preserved.",
);
assert_same(
"site_assigned",
$sanitized["assigned_site_id"],
"Expected assigned Site ID to be preserved.",
);
assert_same("wsk_existing", $sanitized["api_key"], "Expected API key to be preserved.");
assert_same(
"state_existing",
$sanitized["setup_state"],
"Expected setup state to be preserved.",
);
});
test(
"registers a top-level SearchCue admin page for site id and automatic updates",
function (): void {
foreach ($GLOBALS["searchcue_test_actions"]["admin_menu"] ?? [] as $action) {
call_user_func($action["callback"]);
}
foreach ($GLOBALS["searchcue_test_actions"]["admin_init"] ?? [] as $action) {
call_user_func($action["callback"]);
}
$menu_page = $GLOBALS["searchcue_test_menu_pages"][0];
assert_same("SearchCue", $menu_page["menu_title"], "Expected SearchCue menu title.");
assert_same("manage_options", $menu_page["capability"], "Expected administrator access.");
assert_same("searchcue", $menu_page["menu_slug"], "Expected admin page slug.");
assert_same(
"https://example.test/wp-content/plugins/searchcue/assets/searchcue-menu-icon.svg",
$menu_page["icon_url"],
"Expected the SearchCue menu icon.",
);
assert_same(
[],
$GLOBALS["searchcue_test_submenu_pages"],
"Expected account-specific submenus only after SearchCue is connected.",
);
assert_same(
"searchcue_search_options",
$GLOBALS["searchcue_test_registered_settings"][0]["option_name"],
"Expected registered option.",
);
$field_ids = array_map(
static fn($field) => $field["id"],
$GLOBALS["searchcue_test_fields"],
);
assert_true(
in_array("site_id", $field_ids, true),
"Expected site id field.",
);
assert_true(
in_array("push_updates", $field_ids, true),
"Expected automatic updates field.",
);
assert_false(
in_array("indexnow_key", $field_ids, true),
"Update key field should not be shown.",
);
$push_field = null;
foreach ($GLOBALS["searchcue_test_fields"] as $field) {
if ($field["id"] === "push_updates") {
$push_field = $field;
break;
}
}
assert_same("Automatic updates", $push_field["title"], "Expected automatic update label.");
},
);
test("ships a crisp SearchCue menu icon as an SVG", function (): void {
$path = dirname(__DIR__) . "/assets/searchcue-menu-icon.svg";
assert_true(is_file($path), "Expected searchcue-menu-icon.svg to exist.");
$contents = file_get_contents($path);
assert_true(is_string($contents), "Expected searchcue-menu-icon.svg contents.");
assert_contains("<svg", $contents, "Expected the menu icon to be an SVG.");
assert_contains('viewBox="0 0 20 20"', $contents, "Expected a 20x20 menu icon.");
assert_contains("#1E6B50", $contents, "Expected the SearchCue cue accent in the icon.");
});
test("renders automatic updates without exposing update key details", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_push_updates_field();
$html = ob_get_clean();
assert_contains(
"Keep the SearchCue search index current as public pages and files change.",
$html,
"Expected automatic updates copy.",
);
assert_not_contains("IndexNow", $html, "IndexNow should not be mentioned.");
assert_not_contains("indexnow_key", $html, "Hidden update key should not be rendered.");
assert_not_contains("indexnow_key_123", $html, "Stored update key should not be rendered.");
});
test("renders a first-run welcome flow on the settings page", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
'class="wrap searchcue-admin"',
$html,
"Expected branded settings page wrapper.",
);
assert_contains(
"Welcome to SearchCue",
$html,
"Expected first-run welcome heading.",
);
assert_contains(
"You can try SearchCue for free on your site. Once connected, SearchCue indexes your public content and keeps your search index managed as you publish.",
$html,
"Expected updated first-run intro copy.",
);
assert_not_contains(
"Happy searching!",
$html,
"Expected SearchCue product copy not to use exclamation marks.",
);
assert_contains(
"<dt>Cost</dt>",
$html,
"Expected setup summary to keep cost as the summary label.",
);
assert_not_contains(
"<dt>Trial</dt>",
$html,
"Expected setup summary not to mention a trial.",
);
assert_contains(
"Free trial",
$html,
"Expected setup summary to describe the free trial.",
);
assert_contains(
"You need an account to use SearchCue. Enter your email and we will send you a link to sign in.",
$html,
"Expected simplified email setup copy.",
);
assert_not_contains(
"If you are new, this creates your account.",
$html,
"Expected email setup copy not to duplicate the account-choice flow.",
);
assert_contains(
'name="searchcue_setup_email"',
$html,
"Expected new-user setup email field.",
);
assert_contains(
"Already have a SearchCue account? Use the same email link to connect it.",
$html,
"Expected existing-account connect copy.",
);
assert_not_contains(
"admin-post.php?action=searchcue_search_connect",
$html,
"Expected no direct setup-context connect action.",
);
assert_contains(
'class="searchcue-mono"',
$html,
"Expected the home URL value to render in the SearchCue mono face.",
);
});
test("matches the first-run CTA to SearchCue design-system controls", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
"--searchcue-ink-900: #1b1b19;",
$html,
"Expected plugin CSS to expose the SearchCue ink token.",
);
assert_contains(
"--searchcue-cue: #1e6b50;",
$html,
"Expected plugin CSS to expose the SearchCue cue token.",
);
assert_contains(
'font-family: "Schibsted Grotesk", "Helvetica Neue", Helvetica, Arial, sans-serif;',
$html,
"Expected plugin UI to use the SearchCue sans type stack.",
);
assert_contains(
".searchcue-actions .button-primary,\n .searchcue-actions button[type=\"submit\"] {\n background: var(--searchcue-ink-900);\n border-color: var(--searchcue-ink-900);\n border-radius: 4px;",
$html,
"Expected primary CTA to be ink-black with SearchCue button rounding.",
);
assert_contains(
".searchcue-onboarding-row .searchcue-input,\n .searchcue-onboarding-row .button-primary,\n .searchcue-onboarding-row button[type=\"submit\"] {\n height: 46px;\n min-height: 46px;",
$html,
"Expected onboarding email input and CTA to share the same height.",
);
assert_contains(
".searchcue-onboarding-row .searchcue-actions {\n display: flex;\n margin-top: 0;",
$html,
"Expected onboarding CTA wrapper not to inherit the settings button offset.",
);
assert_contains(
".searchcue-onboarding-row {\n align-items: end;\n display: flex;\n flex-wrap: wrap;\n gap: 12px;\n margin-top: 14px;",
$html,
"Expected the email row to sit close to the supporting copy.",
);
assert_contains(
".searchcue-onboarding-row .button-primary,\n .searchcue-onboarding-row button[type=\"submit\"] {\n align-items: center;\n display: inline-flex;\n justify-content: center;\n margin-bottom: 0;",
$html,
"Expected onboarding CTA not to inherit the WordPress admin button bottom margin.",
);
assert_not_contains(
"font-family: Georgia",
$html,
"Expected plugin headings not to use the legacy Georgia stack.",
);
assert_not_contains(
"background: var(--searchcue-green);",
$html,
"Expected primary actions not to use cue green as their fill color.",
);
});
test("sends the first-run setup link through SearchCue", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_POST["searchcue_setup_email"] = "new-user@example.test";
SearchCue_Search_Plugin\send_setup_link();
unset($_POST["searchcue_setup_email"]);
assert_same(1, count($GLOBALS["searchcue_test_remote_posts"]), "Expected one setup request.");
$request = $GLOBALS["searchcue_test_remote_posts"][0];
assert_same(
"https://central.searchcue.com/site-search/integrations/wordpress/setup-link",
$request["url"],
"Expected setup-link endpoint.",
);
$payload = json_decode($request["args"]["body"], true);
assert_same("new-user@example.test", $payload["email"], "Expected submitted email.");
assert_same("https://example.test/", $payload["site_url"], "Expected WordPress site URL.");
assert_same(
"https://example.test/wp-admin/admin.php?page=searchcue",
$payload["return_url"],
"Expected top-level SearchCue return URL.",
);
assert_same("state_abc123", $payload["state"], "Expected setup state.");
assert_contains("searchcue_setup=sent", $GLOBALS["searchcue_test_redirects"][0], "Expected sent redirect.");
});
test("existing-account setup no longer requests a public signed setup context", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_same(0, count($GLOBALS["searchcue_test_remote_posts"]), "Expected no setup-context request.");
assert_not_contains("/setup-context", $html, "Expected setup-context not to appear in markup.");
});
test("handoff return claims setup immediately after state validation", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_remote_post_responses"][] = [
"response" => ["code" => 200],
"body" => json_encode(["apiKey" => "wsk_claimed", "siteId" => "site_assigned123"]),
];
$_GET["state"] = "state_abc123";
$_GET["handoff"] = "wph_once";
SearchCue_Search_Plugin\maybe_complete_setup_from_handoff();
unset($_GET["state"], $_GET["handoff"]);
assert_same(1, count($GLOBALS["searchcue_test_remote_posts"]), "Expected GET return to claim handoff.");
$request = $GLOBALS["searchcue_test_remote_posts"][0];
assert_contains("/claim", $request["url"], "Expected claim endpoint.");
$payload = json_decode($request["args"]["body"], true);
assert_same("wph_once", $payload["handoff"], "Expected handoff token to be claimed.");
$options = get_option("searchcue_search_options");
assert_same("wsk_claimed", $options["api_key"], "Expected claimed API key to be stored.");
assert_same(
"site_assigned123",
$options["assigned_site_id"],
"Expected assigned Site ID to be cached.",
);
assert_same("", $options["site_id"], "Manual Site ID should stay empty.");
assert_false(
array_key_exists("pending_handoff", $options),
"Expected handoff state not to be stored after direct claim.",
);
assert_contains("searchcue_setup=connected", $GLOBALS["searchcue_test_redirects"][0], "Expected clean connected redirect.");
assert_same(0, count($GLOBALS["searchcue_test_remote_gets"]), "Site metadata should come from claim.");
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_not_contains(
'name="action" value="searchcue_search_complete_setup"',
$html,
"Expected no second-step setup form.",
);
assert_not_contains("Finish setup", $html, "Expected no finish setup button.");
});
test("handoff return rejects mismatched state without claiming setup", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_GET["state"] = "wrong_state";
$_GET["handoff"] = "wph_once";
SearchCue_Search_Plugin\maybe_complete_setup_from_handoff();
unset($_GET["state"], $_GET["handoff"]);
$options = get_option("searchcue_search_options");
assert_same("", $options["api_key"], "Expected mismatched state not to store API key.");
assert_same("", $options["assigned_site_id"], "Expected mismatched state not to store assigned Site ID.");
assert_same(0, count($GLOBALS["searchcue_test_remote_posts"]), "Expected mismatched state not to claim handoff.");
assert_contains("searchcue_setup=state_mismatch", $GLOBALS["searchcue_test_redirects"][0], "Expected state mismatch redirect.");
});
test("handoff return reports claim failure without storing credentials", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_remote_post_responses"][] = [
"response" => ["code" => 500],
"body" => "{}",
];
$_GET["state"] = "state_abc123";
$_GET["handoff"] = "wph_once";
SearchCue_Search_Plugin\maybe_complete_setup_from_handoff();
unset($_GET["state"], $_GET["handoff"]);
$options = get_option("searchcue_search_options");
assert_same("", $options["api_key"], "Expected failed claim not to store API key.");
assert_same("", $options["assigned_site_id"], "Expected failed claim not to store assigned Site ID.");
assert_same(1, count($GLOBALS["searchcue_test_remote_posts"]), "Expected valid state to attempt claim.");
assert_contains("searchcue_setup=claim_failed", $GLOBALS["searchcue_test_redirects"][0], "Expected claim failure redirect.");
});
test("manual Site ID override is collapsed below Automatic updates", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
$updates_pos = strpos($html, "Automatic updates");
$advanced_pos = strpos($html, "Advanced settings");
assert_true($updates_pos !== false, "Expected Automatic updates control.");
assert_true($advanced_pos !== false, "Expected advanced settings section.");
assert_true(
$updates_pos < $advanced_pos,
"Expected advanced settings below Automatic updates.",
);
assert_contains("<details", $html, "Expected collapsed details element.");
assert_not_contains("<details open", $html, "Advanced settings should be collapsed.");
assert_contains(
"Only change this if you want to use a different search index than the default SearchCue assigned.",
$html,
"Expected manual override warning copy.",
);
assert_contains(
'class="searchcue-input regular-text searchcue-mono"',
$html,
"Expected the Site ID field to render in the SearchCue mono face.",
);
});
test("renders connected automatic updates as a styled switch", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
'class="searchcue-switch-input"',
$html,
"Expected automatic updates checkbox to use the switch input class.",
);
assert_contains(
'<span class="searchcue-switch" aria-hidden="true"></span>',
$html,
"Expected a visual switch for automatic updates.",
);
assert_contains(
".searchcue-switch-input:checked + .searchcue-switch",
$html,
"Expected switch checked-state styling.",
);
assert_contains(
".searchcue-settings {\n background: var(--searchcue-surface);\n border: 1px solid var(--searchcue-line);\n border-radius: 6px;\n margin: 0 0 18px;\n padding: 30px 34px 18px;",
$html,
"Expected connected settings card to use compressed bottom padding.",
);
assert_contains(
'class="button button-primary searchcue-save"',
$html,
"Expected the save button to use the plugin-owned button markup.",
);
assert_contains(
"disabled\n data-searchcue-save",
$html,
"Expected the save button to start disabled until settings change.",
);
assert_contains(
".searchcue-actions .button-primary:disabled,\n .searchcue-actions button[type=\"submit\"]:disabled",
$html,
"Expected disabled save button styling.",
);
assert_contains(
"background: var(--searchcue-paper-shade) !important;",
$html,
"Expected disabled save button styling to override WordPress admin defaults without green.",
);
assert_contains(
"color: var(--searchcue-ink-300) !important;",
$html,
"Expected disabled save button text to use the SearchCue muted disabled token.",
);
assert_contains(
"function renderSettingsFormDirtyState",
$html,
"Expected settings form dirty-state script.",
);
assert_contains(
"Keep the search index current as you update public pages, posts, custom content, and files.",
$html,
"Expected automatic updates copy to describe the user-visible effect.",
);
assert_not_contains(
"Send changed public URLs",
$html,
"Expected automatic updates copy not to describe implementation details.",
);
assert_not_contains(
".searchcue-toggle input {\n margin-top: 3px;",
$html,
"Expected connected settings not to rely on the bare WordPress checkbox styling.",
);
assert_not_contains(
".searchcue-toggle {\n align-items: flex-start;\n border-top: 1px solid var(--searchcue-border);",
$html,
"Expected automatic updates not to use a top divider.",
);
assert_not_contains(
".searchcue-advanced {\n border-top: 1px solid var(--searchcue-border);",
$html,
"Expected advanced settings not to create a lower divider under automatic updates.",
);
assert_not_contains(
"box-shadow: 0 1px 2px",
$html,
"Expected the visual switch not to use a decorative shadow.",
);
});
test("registers connected quick access links as SearchCue submenus", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
foreach ($GLOBALS["searchcue_test_actions"]["admin_menu"] ?? [] as $action) {
call_user_func($action["callback"]);
}
$submenus = $GLOBALS["searchcue_test_submenu_pages"];
assert_same(
["Documentation", "Design", "Analytics", "SearchCue Dashboard"],
array_column($submenus, "menu_title"),
"Expected quick access links under the SearchCue menu.",
);
assert_same(
["searchcue", "searchcue", "searchcue", "searchcue"],
array_column($submenus, "parent_slug"),
"Expected quick access links to belong to SearchCue.",
);
assert_same(
[
"https://searchcue.com/site-search/app/documentation",
"https://searchcue.com/site-search/app/site/site_assigned123/design",
"https://searchcue.com/site-search/app/site/site_assigned123/analytics",
"https://searchcue.com/site-search/app/site/site_assigned123",
],
array_column($submenus, "menu_slug"),
"Expected quick access submenus to open their SearchCue destinations.",
);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_not_contains("Quick access", $html, "Expected no quick-access panel in the hero.");
assert_not_contains("searchcue-quick-access", $html, "Expected obsolete quick-access CSS removed.");
});
test("renders a connected search analytics card", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains("Search activity", $html, "Expected connected analytics card.");
assert_contains(
'data-searchcue-analytics',
$html,
"Expected analytics card data hook.",
);
assert_contains(
'<section class="searchcue-hero is-connected">',
$html,
"Expected connected hero wrapper.",
);
assert_contains(
'<div
class="searchcue-analytics is-in-hero"',
$html,
"Expected analytics to be embedded inside the connected hero card.",
);
assert_true(
strpos($html, '<section class="searchcue-hero is-connected">') <
strpos($html, '<div
class="searchcue-analytics is-in-hero"'),
"Expected analytics block to follow the hero copy inside the connected hero.",
);
assert_true(
strpos($html, '<div
class="searchcue-analytics is-in-hero"') <
strpos($html, '<form class="searchcue-settings"'),
"Expected analytics block to appear before the settings form.",
);
assert_contains(
"searchcue_search_analytics",
$html,
"Expected analytics card to load through local WordPress AJAX.",
);
assert_contains(
"Recent search terms",
$html,
"Expected analytics card to show search terms.",
);
assert_contains(
'class="searchcue-query-table"',
$html,
"Expected search terms to render as a SearchCue-style table.",
);
assert_contains(
"<th scope=\"col\">",
$html,
"Expected the search-term table to use scoped column headers.",
);
assert_not_contains(
"searchcue-query-list",
$html,
"Expected the old loose query list to be removed.",
);
assert_contains(
'createElement("tr")',
$html,
"Expected search terms to be rendered as table rows.",
);
assert_contains(
'"searchcue-query-term"',
$html,
"Expected each search term row to use the term cell class.",
);
assert_contains("Search volume", $html, "Expected analytics card to show search volume.");
assert_contains(
'class="searchcue-volume-chart"',
$html,
"Expected search volume to render as one horizontal time-series chart.",
);
assert_contains(
'createElementNS("http://www.w3.org/2000/svg", "polyline")',
$html,
"Expected search volume to connect daily values in a line chart.",
);
assert_contains(
'createElementNS("http://www.w3.org/2000/svg", "circle")',
$html,
"Expected the line chart to expose each daily value as a point.",
);
assert_not_contains(
"searchcue-volume-track",
$html,
"Expected the old stacked progress rows to be removed.",
);
assert_contains(
"searchcue-analytics-meta",
$html,
"Expected analytics range metadata to sit in the right-aligned analytics header meta.",
);
assert_contains(
".searchcue-analytics-kicker {\n margin: 12px 0 0;",
$html,
"Expected the analytics kicker to have breathing room under the heading.",
);
assert_contains(
".searchcue-analytics h2 {\n font-size: 24px;\n font-weight: 500;",
$html,
"Expected the analytics sub-header to use the SearchCue sans heading scale.",
);
assert_contains(
".searchcue-hero-copy {\n padding: 34px;",
$html,
"Expected the hero content to use the shared card inset.",
);
assert_contains(
".searchcue-analytics.is-in-hero {\n background: var(--searchcue-surface);\n border: 0;\n border-radius: 0;\n border-top: 1px solid var(--searchcue-line);\n margin: 0;\n padding: 30px 34px;",
$html,
"Expected in-hero analytics padding to match the surrounding card rhythm.",
);
assert_contains(
"https://searchcue.com/fonts/searchcue/SchibstedGrotesk-Regular.woff2",
$html,
"Expected the SearchCue sans face to load from searchcue.com.",
);
assert_contains(
"https://searchcue.com/fonts/searchcue/SplineSansMono-Regular.woff2",
$html,
"Expected the SearchCue mono face to load from searchcue.com.",
);
assert_contains(
'--searchcue-font-mono: "Spline Sans Mono"',
$html,
"Expected a mono type token mirroring the SearchCue design system.",
);
assert_contains(
".searchcue-hero-copy,\n .searchcue-analytics.is-in-hero,\n .searchcue-status,\n .searchcue-analytics,\n .searchcue-settings",
$html,
"Expected in-hero analytics to share the responsive card inset.",
);
});
test("local analytics AJAX proxies SearchCue analytics with the stored API key", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_remote_get_responses"][] = [
"response" => ["code" => 200],
"body" => json_encode([
"range" => ["label" => "30 days", "days" => 30],
"totals" => ["searches" => 42, "zeroResults" => 3, "clicks" => 11],
"topQueries" => [
["term" => "pricing", "searches" => 14],
["term" => "support", "searches" => 8],
],
"dailyVolume" => [
["label" => "May 16", "count" => 7],
["label" => "May 17", "count" => 9],
],
]),
];
ob_start();
SearchCue_Search_Plugin\ajax_search_analytics();
$response = json_decode(ob_get_clean(), true);
assert_same(true, $response["success"], "Expected successful analytics response.");
assert_same(42, $response["data"]["totals"]["searches"], "Expected proxied search count.");
assert_same("pricing", $response["data"]["topQueries"][0]["term"], "Expected proxied search term.");
assert_same(1, count($GLOBALS["searchcue_test_remote_gets"]), "Expected one analytics request.");
$request = $GLOBALS["searchcue_test_remote_gets"][0];
assert_contains("/analytics.json", $request["url"], "Expected SearchCue analytics endpoint.");
assert_same(
"Bearer wsk_existing",
$request["args"]["headers"]["Authorization"],
"Expected analytics request to use the stored site API key.",
);
});
test("submenu links build direct SearchCue admin URLs", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$url = SearchCue_Search_Plugin\searchcue_admin_url(SearchCue_Search_Plugin\get_options(), "design");
assert_same(0, count($GLOBALS["searchcue_test_remote_posts"]), "Expected no admin-link request.");
assert_same(
"https://searchcue.com/site-search/app/site/site_assigned123/design",
$url,
"Expected direct SearchCue design URL.",
);
});
test("connected settings keep hero and manual override controls", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$assigned_html = ob_get_clean();
assert_contains(
'<h1 class="searchcue-wordmark">',
$assigned_html,
"Expected the connected hero to use the SearchCue wordmark.",
);
assert_contains("SearchCue is connected", $assigned_html, "Expected connected status.");
$GLOBALS["searchcue_test_options"]["searchcue_search_options"]["site_id"] = "site_manual456";
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$override_html = ob_get_clean();
assert_contains(
'value="site_manual456"',
$override_html,
"Expected manual override Site ID to remain visible in advanced settings.",
);
});
test("renders a compact connected wordmark and positive status", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains('<h1 class="searchcue-wordmark">', $html, "Expected SearchCue wordmark.");
assert_contains(
'class="searchcue-wordmark-caret" aria-hidden="true"',
$html,
"Expected the Cue-green wordmark caret.",
);
assert_contains(
'class="searchcue-connected-status"',
$html,
"Expected connected status on its own line.",
);
assert_contains(
'class="searchcue-connected-check" aria-hidden="true"',
$html,
"Expected a positive connected tick.",
);
assert_contains("SearchCue is connected", $html, "Expected explicit connected confirmation.");
assert_contains(
".searchcue-admin h1.searchcue-wordmark {",
$html,
"Expected live-type wordmark styling.",
);
assert_not_contains("SearchCue for WordPress", $html, "Expected no connected eyebrow.");
assert_not_contains(
"SearchCue is working on this site. Your public content is connected to a managed search index, so visitors can search with SearchCue while you keep publishing.",
$html,
"Expected the connected explanatory paragraph removed.",
);
assert_not_contains("searchcue-connected-body", $html, "Expected obsolete connected body removed.");
});
test("local pending setup status reports complete once options are saved", function (): void {
set_searchcue_options([
"site_id" => "",
"assigned_site_id" => "site_assigned123",
"api_key" => "wsk_existing",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\ajax_setup_status();
$response = json_decode(ob_get_clean(), true);
assert_same(true, $response["success"], "Expected successful AJAX response.");
assert_same(true, $response["data"]["connected"], "Expected connected setup status.");
assert_same("site_assigned123", $response["data"]["siteId"], "Expected effective Site ID.");
});
test("renders a connected status when the Site ID is configured", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
SearchCue_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains("SearchCue is connected", $html, "Expected connected Site ID status.");
assert_contains("site_abc123", $html, "Expected configured Site ID to be visible.");
assert_not_contains("Welcome to SearchCue", $html, "Manual Site ID installs are connected.");
});
test("serves the IndexNow keyfile only while push updates are enabled", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
assert_same(
"indexnow_key_123",
SearchCue_Search_Plugin\keyfile_content_for_path("/indexnow_key_123.txt"),
"Expected keyfile content.",
);
$GLOBALS["searchcue_test_options"]["searchcue_search_options"]["push_updates"] = "0";
assert_same(
null,
SearchCue_Search_Plugin\keyfile_content_for_path("/indexnow_key_123.txt"),
"Disabled push updates should disable the keyfile.",
);
});
test("serves the IndexNow keyfile with an explicit successful status", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_SERVER["REQUEST_URI"] = "/indexnow_key_123.txt";
ob_start();
@SearchCue_Search_Plugin\serve_indexnow_keyfile();
$body = ob_get_clean();
unset($_SERVER["REQUEST_URI"]);
assert_same("indexnow_key_123", $body, "Expected keyfile response body.");
assert_same(
[200],
$GLOBALS["searchcue_test_status_headers"],
"Expected keyfile response to force HTTP 200.",
);
});
test("registers public content update hooks without comment hooks", function (): void {
$hook_names = array_keys($GLOBALS["searchcue_test_actions"]);
foreach ([
"save_post",
"transition_post_status",
"trashed_post",
"untrashed_post",
"deleted_post",
"add_attachment",
"edit_attachment",
"delete_attachment",
"shutdown",
] as $hook_name) {
assert_true(in_array($hook_name, $hook_names, true), "Expected {$hook_name} hook.");
}
foreach ($hook_names as $hook_name) {
assert_false(
strpos($hook_name, "comment") !== false,
"Comment hooks should not be registered.",
);
}
});
test("coalesces changed URLs into one IndexNow request", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "https://example.test/hello-world",
];
$GLOBALS["searchcue_test_posts"][202] = [
"ID" => 202,
"post_status" => "inherit",
"post_type" => "attachment",
"attachment_url" => "https://example.test/wp-content/uploads/file.pdf",
];
SearchCue_Search_Plugin\queue_post_update(101);
SearchCue_Search_Plugin\queue_post_update(101);
SearchCue_Search_Plugin\queue_attachment_update(202);
SearchCue_Search_Plugin\flush_indexnow_updates();
assert_same(1, count($GLOBALS["searchcue_test_remote_posts"]), "Expected one request.");
$request = $GLOBALS["searchcue_test_remote_posts"][0];
assert_same(
"https://central.searchcue.com/indexnow",
$request["url"],
"Expected central IndexNow endpoint.",
);
$payload = json_decode($request["args"]["body"], true);
assert_same("example.test", $payload["host"], "Expected home host.");
assert_same("indexnow_key_123", $payload["key"], "Expected IndexNow key.");
assert_same(
"https://example.test/indexnow_key_123.txt",
$payload["keyLocation"],
"Expected key location.",
);
assert_same(
[
"https://example.test/hello-world",
"https://example.test/wp-content/uploads/file.pdf",
],
$payload["urlList"],
"Expected unique changed URLs.",
);
});
test("sends an HTTPS IndexNow key location even when WordPress home URL is HTTP", function (): void {
$GLOBALS["searchcue_test_home_url"] = "http://example.test";
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "http://example.test/hello-world",
];
SearchCue_Search_Plugin\queue_post_update(101);
SearchCue_Search_Plugin\flush_indexnow_updates();
assert_same(1, count($GLOBALS["searchcue_test_remote_posts"]), "Expected one request.");
$payload = json_decode($GLOBALS["searchcue_test_remote_posts"][0]["args"]["body"], true);
assert_same(
"https://example.test/indexnow_key_123.txt",
$payload["keyLocation"],
"Expected HTTPS key location.",
);
});
test("does not send IndexNow requests when push updates are disabled", function (): void {
set_searchcue_options([
"site_id" => "site_abc123",
"push_updates" => "0",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["searchcue_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "https://example.test/hello-world",
];
SearchCue_Search_Plugin\queue_post_update(101);
SearchCue_Search_Plugin\flush_indexnow_updates();
assert_same(0, count($GLOBALS["searchcue_test_remote_posts"]), "Expected no request.");
});
test("redirects admins to the settings page after activation", function (): void {
set_transient("searchcue_search_activation_redirect", "1");
SearchCue_Search_Plugin\maybe_redirect_after_activation();
assert_same(
["https://example.test/wp-admin/admin.php?page=searchcue"],
$GLOBALS["searchcue_test_redirects"],
"Expected top-level SearchCue redirect.",
);
assert_same(
false,
get_transient("searchcue_search_activation_redirect"),
"Expected redirect marker to be cleared.",
);
});
$failures = 0;
foreach ($tests as [$name, $callback]) {
try {
reset_wp_stubs();
SearchCue_Search_Plugin\bootstrap();
$callback();
fwrite(STDOUT, ". {$name}\n");
} catch (Throwable $error) {
++$failures;
fwrite(STDERR, "F {$name}\n{$error->getMessage()}\n\n");
}
}
if ($failures > 0) {
fwrite(STDERR, "{$failures} test(s) failed.\n");
exit(1);
}
fwrite(STDOUT, count($tests) . " test(s) passed.\n"); <?php
/**
* SearchCue uninstall handler.
*
* Runs when the plugin is deleted through the WordPress admin.
* Removes all plugin options from the database.
*
* @package SearchCue_Search
*/
declare(strict_types=1);
if (!defined('WP_UNINSTALL_PLUGIN')) {
exit;
}
delete_option('searchcue_search_options');