{
"name": "Winnow Search WordPress Plugin",
"dockerComposeFile": "docker-compose.yml",
"service": "plugin",
"workspaceFolder": "/workspaces/winnow-search",
"forwardPorts": [8080],
"customizations": {
"vscode": {
"extensions": [
"bmewburn.vscode-intelephense-client",
"xdebug.php-debug"
]
}
},
"postStartCommand": "bash /workspaces/winnow-search/bin/setup.sh"
} Winnow WordPress plugin
The Winnow WordPress plugin makes it easy to add Winnow to your WordPress site. You can read the source code below.
If you are looking for the plugin itself, ready to install on your WordPress site, you can download it here: Download the plugin.
winnow-search Winnow Search WordPress plugin source code
services:
plugin:
build:
context: ..
dockerfile: .devcontainer/Dockerfile
volumes:
- ..:/workspaces/winnow-search: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="winnow-search.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}" \
winnow-search.php \
uninstall.php \
LICENSE \
README.md \
-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 " winnow-search 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/winnow-search"
PLUGIN_SRC="/workspaces/winnow-search"
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="Winnow Search 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 winnow-search --path=/var/www/html --allow-root 2>/dev/null || echo "Plugin activation will happen on first page load."
echo ""
echo "=== Winnow Search Plugin Dev Environment Ready ==="
echo "WordPress: http://localhost:8080"
echo "Admin: http://localhost:8080/wp-admin (admin / admin)"
echo "Settings: http://localhost:8080/wp-admin/options-general.php?page=winnow-search"
echo ""
echo "Run tests: php /workspaces/winnow-search/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.
Winnow Search 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/>. # Winnow Search - WordPress Plugin
A WordPress plugin that adds [Winnow Search](https://winnow-sear.ch) to your site.
Configure your Site ID in the WordPress admin and let Winnow know when public content changes.
## Features
- Injects the Winnow Search embed script into the `<head>` of every public page
- Admin settings page under **Settings > Winnow Search** to enter your Site ID
- 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 `winnow-search` directory into `wp-content/plugins/`
2. Activate via **Plugins** in WordPress admin
## Configuration
1. Go to **Settings > Winnow Search**
2. Paste your Winnow Site ID (looks like `site_abc123`)
3. Keep **Automatic updates** checked if you want Winnow Search 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 Winnow Search 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/options-general.php?page=winnow-search` 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 `winnow-search` 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/winnow-search/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/options-general.php?page=winnow-search |
**Credentials:** `admin` / `admin`
Run the test suite:
```bash
docker compose -f .devcontainer/docker-compose.yml exec plugin php /workspaces/winnow-search/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/winnow-search.zip` containing only the files needed for production deployment (no devcontainer, tests, or build tooling).
## File Structure
```
winnow-search/
├── .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
├── winnow-search.php Main plugin file
├── 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
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["winnow_test_actions"] = [];
$GLOBALS["winnow_test_options"] = [];
$GLOBALS["winnow_test_option_updates"] = 0;
$GLOBALS["winnow_test_registered_settings"] = [];
$GLOBALS["winnow_test_sections"] = [];
$GLOBALS["winnow_test_fields"] = [];
$GLOBALS["winnow_test_menu_pages"] = [];
$GLOBALS["winnow_test_activation_hooks"] = [];
$GLOBALS["winnow_test_transients"] = [];
$GLOBALS["winnow_test_remote_posts"] = [];
$GLOBALS["winnow_test_remote_gets"] = [];
$GLOBALS["winnow_test_remote_post_responses"] = [];
$GLOBALS["winnow_test_remote_get_responses"] = [];
$GLOBALS["winnow_test_posts"] = [];
$GLOBALS["winnow_test_redirects"] = [];
$GLOBALS["winnow_test_status_headers"] = [];
$GLOBALS["winnow_test_home_url"] = "https://example.test";
function reset_wp_stubs(): void
{
$GLOBALS["winnow_test_actions"] = [];
$GLOBALS["winnow_test_options"] = [];
$GLOBALS["winnow_test_option_updates"] = 0;
$GLOBALS["winnow_test_registered_settings"] = [];
$GLOBALS["winnow_test_sections"] = [];
$GLOBALS["winnow_test_fields"] = [];
$GLOBALS["winnow_test_menu_pages"] = [];
$GLOBALS["winnow_test_activation_hooks"] = [];
$GLOBALS["winnow_test_transients"] = [];
$GLOBALS["winnow_test_remote_posts"] = [];
$GLOBALS["winnow_test_remote_gets"] = [];
$GLOBALS["winnow_test_remote_post_responses"] = [];
$GLOBALS["winnow_test_remote_get_responses"] = [];
$GLOBALS["winnow_test_posts"] = [];
$GLOBALS["winnow_test_redirects"] = [];
$GLOBALS["winnow_test_status_headers"] = [];
$GLOBALS["winnow_test_home_url"] = "https://example.test";
}
function add_action(
string $hook_name,
$callback,
int $priority = 10,
int $accepted_args = 1,
): void
{
$GLOBALS["winnow_test_actions"][$hook_name][] = compact(
"callback",
"priority",
"accepted_args",
);
}
function add_options_page(
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
$callback,
): void {
$GLOBALS["winnow_test_menu_pages"][] = compact(
"page_title",
"menu_title",
"capability",
"menu_slug",
"callback",
);
}
function register_setting(
string $option_group,
string $option_name,
array $args,
): void {
$GLOBALS["winnow_test_registered_settings"][] = compact(
"option_group",
"option_name",
"args",
);
}
function add_settings_section(
string $id,
string $title,
$callback,
string $page,
): void {
$GLOBALS["winnow_test_sections"][] = compact(
"id",
"title",
"callback",
"page",
);
}
function add_settings_field(
string $id,
string $title,
$callback,
string $page,
string $section,
): void {
$GLOBALS["winnow_test_fields"][] = compact(
"id",
"title",
"callback",
"page",
"section",
);
}
function register_activation_hook(string $file, $callback): void
{
$GLOBALS["winnow_test_activation_hooks"][] = compact("file", "callback");
}
function get_option(string $option_name, $default = false)
{
return array_key_exists($option_name, $GLOBALS["winnow_test_options"])
? $GLOBALS["winnow_test_options"][$option_name]
: $default;
}
function add_option(string $option_name, $value): void
{
if (!array_key_exists($option_name, $GLOBALS["winnow_test_options"])) {
$GLOBALS["winnow_test_options"][$option_name] = $value;
}
}
function update_option(string $option_name, $value): void
{
++$GLOBALS["winnow_test_option_updates"];
$GLOBALS["winnow_test_options"][$option_name] = $value;
}
function set_transient(string $transient, $value, int $expiration = 0): void
{
$GLOBALS["winnow_test_transients"][$transient] = $value;
}
function get_transient(string $transient)
{
return $GLOBALS["winnow_test_transients"][$transient] ?? false;
}
function delete_transient(string $transient): void
{
unset($GLOBALS["winnow_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["winnow_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["winnow_test_posts"][$post_id])
? (object) $GLOBALS["winnow_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["winnow_test_posts"][$post]["post_type"])) {
return (string) $GLOBALS["winnow_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["winnow_test_posts"][$post_id]["permalink"] ?? false;
}
function wp_is_post_revision(int $post_id): bool
{
return (bool) ($GLOBALS["winnow_test_posts"][$post_id]["revision"] ?? false);
}
function wp_is_post_autosave(int $post_id): bool
{
return (bool) ($GLOBALS["winnow_test_posts"][$post_id]["autosave"] ?? false);
}
function wp_get_attachment_url(int $post_id)
{
return $GLOBALS["winnow_test_posts"][$post_id]["attachment_url"] ?? false;
}
function wp_remote_post(string $url, array $args)
{
$GLOBALS["winnow_test_remote_posts"][] = compact("url", "args");
if (!empty($GLOBALS["winnow_test_remote_post_responses"])) {
return array_shift($GLOBALS["winnow_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["winnow_test_remote_gets"][] = compact("url", "args");
if (!empty($GLOBALS["winnow_test_remote_get_responses"])) {
return array_shift($GLOBALS["winnow_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["winnow_test_redirects"][] = $location;
}
function wp_redirect(string $location): void
{
$GLOBALS["winnow_test_redirects"][] = $location;
}
function status_header(int $code): void
{
$GLOBALS["winnow_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["winnow_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("WINNOW_SEARCH_TESTING")) {
define("WINNOW_SEARCH_TESTING", true);
}
require dirname(__DIR__) . "/winnow-search.php";
function set_winnow_options(array $overrides): void
{
$GLOBALS["winnow_test_options"]["winnow_search_options"] = array_merge(
Winnow_Search_Plugin\default_options(),
$overrides,
);
}
test("registers the WordPress hooks used by the plugin", function (): void {
assert_true(
isset($GLOBALS["winnow_test_actions"]["wp_head"]),
"Expected wp_head action to be registered.",
);
assert_true(
isset($GLOBALS["winnow_test_actions"]["admin_menu"]),
"Expected admin_menu action to be registered.",
);
assert_true(
isset($GLOBALS["winnow_test_actions"]["admin_init"]),
"Expected admin_init action to be registered.",
);
assert_false(
isset($GLOBALS["winnow_test_actions"]["admin_post_winnow_search_connect"]),
"Expected direct existing-account connect action not to be registered.",
);
assert_true(
isset($GLOBALS["winnow_test_actions"]["admin_post_winnow_search_complete_setup"]),
"Expected nonce-protected setup completion action to be registered.",
);
assert_false(
isset($GLOBALS["winnow_test_actions"]["admin_post_winnow_search_open_admin"]),
"Expected quick-access links to go straight to Winnow without a WordPress action.",
);
assert_same(
1,
count($GLOBALS["winnow_test_activation_hooks"]),
"Expected one activation hook.",
);
});
test(
"activation stores defaults without overwriting an existing option",
function (): void {
call_user_func($GLOBALS["winnow_test_activation_hooks"][0]["callback"]);
$options = get_option("winnow_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_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("winnow_search_activation_redirect"),
"Expected activation redirect marker.",
);
set_winnow_options([
"site_id" => "site_existing",
"push_updates" => "0",
"indexnow_key" => "existing_key",
]);
call_user_func($GLOBALS["winnow_test_activation_hooks"][0]["callback"]);
$existing_options = get_option("winnow_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 = Winnow_Search_Plugin\get_options();
assert_same("", $options["site_id"], "Expected defaults when no option is stored.");
assert_same(
0,
$GLOBALS["winnow_test_option_updates"],
"Reading unset options should not write defaults back to the database.",
);
set_winnow_options(["site_id" => "site_existing"]);
$GLOBALS["winnow_test_option_updates"] = 0;
$options = Winnow_Search_Plugin\get_options();
assert_same("site_existing", $options["site_id"], "Expected stored options to be returned.");
assert_same(
0,
$GLOBALS["winnow_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_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "test_key",
]);
$html = render_wp_head();
assert_contains(
"<!-- Start Winnow Search embed -->",
$html,
"Expected embed start marker.",
);
assert_contains(
"s.src = 'https://winnow-sear.ch/search-embed.js'",
$html,
"Expected production Winnow 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_winnow_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_winnow_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 = Winnow_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_winnow_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 = Winnow_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 an admin settings page for site id and automatic updates",
function (): void {
foreach ($GLOBALS["winnow_test_actions"]["admin_menu"] ?? [] as $action) {
call_user_func($action["callback"]);
}
foreach ($GLOBALS["winnow_test_actions"]["admin_init"] ?? [] as $action) {
call_user_func($action["callback"]);
}
assert_same(
"winnow-search",
$GLOBALS["winnow_test_menu_pages"][0]["menu_slug"],
"Expected settings page slug.",
);
assert_same(
"winnow_search_options",
$GLOBALS["winnow_test_registered_settings"][0]["option_name"],
"Expected registered option.",
);
$field_ids = array_map(
static fn($field) => $field["id"],
$GLOBALS["winnow_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["winnow_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("renders automatic updates without exposing update key details", function (): void {
set_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
Winnow_Search_Plugin\render_push_updates_field();
$html = ob_get_clean();
assert_contains(
"Keep the Winnow 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_winnow_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
'class="wrap winnow-search-admin"',
$html,
"Expected branded settings page wrapper.",
);
assert_contains(
"Welcome to Winnow Search",
$html,
"Expected first-run welcome heading.",
);
assert_contains(
"You can try Winnow for free on your site. Once connected, Winnow will index your public content and create and manage your search index for you. Happy searching!",
$html,
"Expected updated first-run intro copy.",
);
assert_contains(
"<dt>Cost</dt>",
$html,
"Expected setup summary to describe cost without trial wording.",
);
assert_not_contains(
"<dt>Trial</dt>",
$html,
"Expected setup summary not to mention a trial.",
);
assert_contains(
"Free to start",
$html,
"Expected setup summary to keep the free-to-start promise.",
);
assert_contains(
"Winnow Search needs a Winnow account. 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="winnow_setup_email"',
$html,
"Expected new-user setup email field.",
);
assert_contains(
"Already have a Winnow account? Use the same email link to connect it.",
$html,
"Expected existing-account connect copy.",
);
assert_not_contains(
"admin-post.php?action=winnow_search_connect",
$html,
"Expected no direct setup-context connect action.",
);
});
test("matches the first-run CTA dimensions to the email input", function (): void {
set_winnow_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
".winnow-search-actions button[type=\"submit\"] {\n background: var(--winnow-green);\n border-color: var(--winnow-green);\n border-radius: 4px;",
$html,
"Expected primary CTA to match the rendered WordPress input rounding.",
);
assert_contains(
".winnow-search-onboarding-row .winnow-search-input,\n .winnow-search-onboarding-row .button-primary,\n .winnow-search-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(
".winnow-search-onboarding-row .winnow-search-actions {\n display: flex;\n margin-top: 0;",
$html,
"Expected onboarding CTA wrapper not to inherit the settings button offset.",
);
assert_contains(
".winnow-search-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(
".winnow-search-onboarding-row .button-primary,\n .winnow-search-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.",
);
});
test("sends the first-run setup link through Winnow", function (): void {
set_winnow_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_POST["winnow_setup_email"] = "new-user@example.test";
Winnow_Search_Plugin\send_setup_link();
unset($_POST["winnow_setup_email"]);
assert_same(1, count($GLOBALS["winnow_test_remote_posts"]), "Expected one setup request.");
$request = $GLOBALS["winnow_test_remote_posts"][0];
assert_same(
"https://central.winnow-sear.ch/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/options-general.php?page=winnow-search",
$payload["return_url"],
"Expected settings return URL.",
);
assert_same("state_abc123", $payload["state"], "Expected setup state.");
assert_contains("winnow_setup=sent", $GLOBALS["winnow_test_redirects"][0], "Expected sent redirect.");
});
test("existing-account setup no longer requests a public signed setup context", function (): void {
set_winnow_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_same(0, count($GLOBALS["winnow_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 waits for nonce-protected WordPress confirmation", function (): void {
set_winnow_options([
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => "state_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_GET["state"] = "state_abc123";
$_GET["handoff"] = "wph_once";
Winnow_Search_Plugin\maybe_complete_setup_from_handoff();
unset($_GET["state"], $_GET["handoff"]);
$options = get_option("winnow_search_options");
assert_same("", $options["api_key"], "Expected GET return not to store API key.");
assert_same("", $options["assigned_site_id"], "Expected GET return not to store assigned Site ID.");
assert_same(0, count($GLOBALS["winnow_test_remote_posts"]), "Expected GET return not to claim handoff.");
assert_contains("winnow_setup=ready", $GLOBALS["winnow_test_redirects"][0], "Expected clean confirmation redirect.");
ob_start();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
'name="action" value="winnow_search_complete_setup"',
$html,
"Expected nonce-protected finish setup form.",
);
assert_not_contains("wph_once", $html, "Expected handoff token not to be rendered in HTML.");
$GLOBALS["winnow_test_remote_post_responses"][] = [
"response" => ["code" => 200],
"body" => json_encode(["apiKey" => "wsk_claimed", "siteId" => "site_assigned123"]),
];
Winnow_Search_Plugin\complete_setup_from_handoff();
$options = get_option("winnow_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_same(0, count($GLOBALS["winnow_test_remote_gets"]), "Site metadata should come from claim.");
assert_contains("winnow_setup=connected", $GLOBALS["winnow_test_redirects"][1], "Expected clean connected redirect.");
});
test("manual Site ID override is collapsed below Automatic updates", function (): void {
set_winnow_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();
Winnow_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 Winnow assigned.",
$html,
"Expected manual override warning copy.",
);
});
test("renders connected automatic updates as a styled switch", function (): void {
set_winnow_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();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
'class="winnow-search-switch-input"',
$html,
"Expected automatic updates checkbox to use the switch input class.",
);
assert_contains(
'<span class="winnow-search-switch" aria-hidden="true"></span>',
$html,
"Expected a visual switch for automatic updates.",
);
assert_contains(
".winnow-search-switch-input:checked + .winnow-search-switch",
$html,
"Expected switch checked-state styling.",
);
assert_contains(
".winnow-search-settings {\n background: var(--winnow-panel);\n border: 1px solid var(--winnow-border);\n border-radius: 8px;\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 winnow-search-save"',
$html,
"Expected the save button to use the plugin-owned button markup.",
);
assert_contains(
"disabled\n data-winnow-search-save",
$html,
"Expected the save button to start disabled until settings change.",
);
assert_contains(
".winnow-search-actions .button-primary:disabled,\n .winnow-search-actions button[type=\"submit\"]:disabled",
$html,
"Expected disabled save button styling.",
);
assert_contains(
"background: #aeb8b2 !important;",
$html,
"Expected disabled save button styling to override WordPress admin defaults.",
);
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(
".winnow-search-toggle input {\n margin-top: 3px;",
$html,
"Expected connected settings not to rely on the bare WordPress checkbox styling.",
);
assert_not_contains(
".winnow-search-toggle {\n align-items: flex-start;\n border-top: 1px solid var(--winnow-border);",
$html,
"Expected automatic updates not to use a top divider.",
);
assert_not_contains(
".winnow-search-advanced {\n border-top: 1px solid var(--winnow-border);",
$html,
"Expected advanced settings not to create a lower divider under automatic updates.",
);
});
test("renders connected quick access links into Winnow admin", function (): void {
set_winnow_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();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains("Quick access", $html, "Expected quick-access panel heading.");
assert_contains("Documentation", $html, "Expected documentation quick link.");
assert_contains("Design", $html, "Expected design quick link.");
assert_contains("Analytics", $html, "Expected analytics quick link.");
assert_contains("More", $html, "Expected more quick link.");
assert_contains(
"https://winnow-sear.ch/site-search/app/documentation",
$html,
"Expected documentation quick link to open Winnow directly.",
);
assert_contains(
"https://winnow-sear.ch/site-search/app/site/site_assigned123/design",
$html,
"Expected design quick link to open the connected site directly.",
);
assert_contains(
"https://winnow-sear.ch/site-search/app/site/site_assigned123/analytics",
$html,
"Expected analytics quick link to open the connected site directly.",
);
assert_contains(
"https://winnow-sear.ch/site-search/app/site/site_assigned123",
$html,
"Expected more quick link to open the connected site directly.",
);
assert_not_contains(
"admin-post.php?action=winnow_search_open_admin",
$html,
"Expected direct quick links not to call back through WordPress.",
);
assert_not_contains(
"Full analytics",
$html,
"Expected the activity card to no longer render its separate full analytics link.",
);
});
test("renders a connected search analytics card", function (): void {
set_winnow_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();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains("Search activity", $html, "Expected connected analytics card.");
assert_contains(
'data-winnow-search-analytics',
$html,
"Expected analytics card data hook.",
);
assert_contains(
'<section class="winnow-search-hero is-connected">',
$html,
"Expected connected hero wrapper.",
);
assert_contains(
'<div
class="winnow-search-analytics is-in-hero"',
$html,
"Expected analytics to be embedded inside the connected hero card.",
);
assert_true(
strpos($html, '<section class="winnow-search-hero is-connected">') <
strpos($html, '<div
class="winnow-search-analytics is-in-hero"'),
"Expected analytics block to follow the hero copy inside the connected hero.",
);
assert_true(
strpos($html, '<div
class="winnow-search-analytics is-in-hero"') <
strpos($html, '<form class="winnow-search-settings"'),
"Expected analytics block to appear before the settings form.",
);
assert_contains(
"winnow_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("Search volume", $html, "Expected analytics card to show search volume.");
assert_contains(
"winnow-search-analytics-meta",
$html,
"Expected analytics range metadata to sit in the right-aligned analytics header meta.",
);
assert_contains(
".winnow-search-analytics-kicker {\n margin: 12px 0 0;",
$html,
"Expected the analytics kicker to have breathing room under the heading.",
);
assert_contains(
".winnow-search-analytics h2 {\n font-family: Georgia, \"Times New Roman\", serif;\n font-size: 24px;\n font-weight: 500;",
$html,
"Expected the analytics sub-header to be lighter than the main hero heading.",
);
assert_not_contains(
"winnow-search-analytics-title-row",
$html,
"Expected the full analytics link not to sit beside the Search activity title.",
);
assert_contains(
".winnow-search-hero-copy {\n padding: 34px;",
$html,
"Expected the hero content to use the shared card inset.",
);
assert_contains(
".winnow-search-analytics.is-in-hero {\n background: var(--winnow-panel);\n border: 0;\n border-radius: 0;\n border-top: 1px solid var(--winnow-border);\n margin: 0;\n padding: 30px 34px;",
$html,
"Expected in-hero analytics padding to match the surrounding card rhythm.",
);
assert_contains(
".winnow-search-hero-copy,\n .winnow-search-analytics.is-in-hero,\n .winnow-search-status,\n .winnow-search-analytics,\n .winnow-search-settings,",
$html,
"Expected in-hero analytics to share the responsive card inset.",
);
assert_not_contains(
"View full analytics in Winnow",
$html,
"Expected verbose full analytics link text to be removed.",
);
assert_not_contains(
"Open the full analytics page in Winnow for deeper trends, content gaps, and clicked results.",
$html,
"Expected redundant analytics explanation to be removed.",
);
});
test("local analytics AJAX proxies Winnow analytics with the stored API key", function (): void {
set_winnow_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["winnow_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();
Winnow_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["winnow_test_remote_gets"]), "Expected one analytics request.");
$request = $GLOBALS["winnow_test_remote_gets"][0];
assert_contains("/analytics.json", $request["url"], "Expected Winnow analytics endpoint.");
assert_same(
"Bearer wsk_existing",
$request["args"]["headers"]["Authorization"],
"Expected analytics request to use the stored site API key.",
);
});
test("quick access links build direct Winnow admin URLs", function (): void {
set_winnow_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 = Winnow_Search_Plugin\winnow_admin_url(Winnow_Search_Plugin\get_options(), "design");
assert_same(0, count($GLOBALS["winnow_test_remote_posts"]), "Expected no admin-link request.");
assert_same(
"https://winnow-sear.ch/site-search/app/site/site_assigned123/design",
$url,
"Expected direct Winnow design URL.",
);
});
test("removes the redundant connected status summary", function (): void {
set_winnow_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();
Winnow_Search_Plugin\render_settings_page();
$assigned_html = ob_get_clean();
assert_contains("Winnow Search is connected", $assigned_html, "Expected connected hero heading.");
assert_not_contains(
'class="winnow-search-status"',
$assigned_html,
"Expected connected page not to render the redundant status summary.",
);
assert_not_contains(
"<dt>Automatic updates</dt>",
$assigned_html,
"Expected automatic update state to live in the settings control only.",
);
$GLOBALS["winnow_test_options"]["winnow_search_options"]["site_id"] = "site_manual456";
ob_start();
Winnow_Search_Plugin\render_settings_page();
$override_html = ob_get_clean();
assert_not_contains(
'class="winnow-search-status"',
$override_html,
"Expected manual override installs not to bring back the redundant status summary.",
);
assert_contains(
'value="site_manual456"',
$override_html,
"Expected manual override Site ID to remain visible in advanced settings.",
);
});
test("renders connected hero copy as general reassurance", function (): void {
set_winnow_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();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains(
"Winnow Search is working on this site. Your public content is connected to a managed search index, so visitors can search with Winnow while you keep publishing.",
$html,
"Expected connected hero copy to reassure the site owner.",
);
assert_not_contains(
"Automatic updates keep public pages, posts, and files current in Winnow.",
$html,
"Expected connected hero copy not to focus on the Automatic updates feature.",
);
});
test("local pending setup status reports complete once options are saved", function (): void {
set_winnow_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();
Winnow_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_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
ob_start();
Winnow_Search_Plugin\render_settings_page();
$html = ob_get_clean();
assert_contains("Winnow Search 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 Winnow Search", $html, "Manual Site ID installs are connected.");
});
test("serves the IndexNow keyfile only while push updates are enabled", function (): void {
set_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
assert_same(
"indexnow_key_123",
Winnow_Search_Plugin\keyfile_content_for_path("/indexnow_key_123.txt"),
"Expected keyfile content.",
);
$GLOBALS["winnow_test_options"]["winnow_search_options"]["push_updates"] = "0";
assert_same(
null,
Winnow_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_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$_SERVER["REQUEST_URI"] = "/indexnow_key_123.txt";
ob_start();
@Winnow_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["winnow_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["winnow_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_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["winnow_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "https://example.test/hello-world",
];
$GLOBALS["winnow_test_posts"][202] = [
"ID" => 202,
"post_status" => "inherit",
"post_type" => "attachment",
"attachment_url" => "https://example.test/wp-content/uploads/file.pdf",
];
Winnow_Search_Plugin\queue_post_update(101);
Winnow_Search_Plugin\queue_post_update(101);
Winnow_Search_Plugin\queue_attachment_update(202);
Winnow_Search_Plugin\flush_indexnow_updates();
assert_same(1, count($GLOBALS["winnow_test_remote_posts"]), "Expected one request.");
$request = $GLOBALS["winnow_test_remote_posts"][0];
assert_same(
"https://central.winnow-sear.ch/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["winnow_test_home_url"] = "http://example.test";
set_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "1",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["winnow_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "http://example.test/hello-world",
];
Winnow_Search_Plugin\queue_post_update(101);
Winnow_Search_Plugin\flush_indexnow_updates();
assert_same(1, count($GLOBALS["winnow_test_remote_posts"]), "Expected one request.");
$payload = json_decode($GLOBALS["winnow_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_winnow_options([
"site_id" => "site_abc123",
"push_updates" => "0",
"indexnow_key" => "indexnow_key_123",
]);
$GLOBALS["winnow_test_posts"][101] = [
"ID" => 101,
"post_status" => "publish",
"post_type" => "post",
"permalink" => "https://example.test/hello-world",
];
Winnow_Search_Plugin\queue_post_update(101);
Winnow_Search_Plugin\flush_indexnow_updates();
assert_same(0, count($GLOBALS["winnow_test_remote_posts"]), "Expected no request.");
});
test("redirects admins to the settings page after activation", function (): void {
set_transient("winnow_search_activation_redirect", "1");
Winnow_Search_Plugin\maybe_redirect_after_activation();
assert_same(
["https://example.test/wp-admin/options-general.php?page=winnow-search"],
$GLOBALS["winnow_test_redirects"],
"Expected settings redirect.",
);
assert_same(
false,
get_transient("winnow_search_activation_redirect"),
"Expected redirect marker to be cleared.",
);
});
$failures = 0;
foreach ($tests as [$name, $callback]) {
try {
reset_wp_stubs();
Winnow_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
/**
* Winnow Search uninstall handler.
*
* Runs when the plugin is deleted through the WordPress admin.
* Removes all plugin options from the database.
*
* @package Winnow_Search
*/
declare(strict_types=1);
if (!defined('WP_UNINSTALL_PLUGIN')) {
exit;
}
delete_option('winnow_search_options'); <?php
/**
* Plugin Name: Winnow Search
* Plugin URI: https://winnow-sear.ch
* Description: Adds the Winnow Search embed to every WordPress page and provides a small settings page for the Winnow 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: winnow-search
*
* @package Winnow_Search
*/
declare(strict_types=1);
namespace Winnow_Search_Plugin;
if (!defined("ABSPATH")) {
exit();
}
const OPTION_NAME = "winnow_search_options";
const SETTINGS_GROUP = "winnow_search";
const SETTINGS_PAGE = "winnow-search";
const SETTINGS_SECTION = "winnow_search_main";
const EMBED_SCRIPT_URL = "https://winnow-sear.ch/search-embed.js";
const WINNOW_APP_ENDPOINT = "https://winnow-sear.ch";
const INDEXNOW_ENDPOINT = "https://central.winnow-sear.ch/indexnow";
const WORDPRESS_INTEGRATION_ENDPOINT = "https://central.winnow-sear.ch/site-search/integrations/wordpress";
const ACTIVATION_REDIRECT_TRANSIENT = "winnow_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_winnow_search_send_setup_link", __NAMESPACE__ . "\\send_setup_link");
add_action("admin_post_winnow_search_complete_setup", __NAMESPACE__ . "\\complete_setup_from_handoff");
add_action("wp_ajax_winnow_search_setup_status", __NAMESPACE__ . "\\ajax_setup_status");
add_action("wp_ajax_winnow_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, pending_handoff: string, push_updates: string, indexnow_key: string}
*/
function default_options(): array
{
return [
"site_id" => "",
"assigned_site_id" => "",
"api_key" => "",
"setup_state" => generate_setup_state(),
"pending_handoff" => "",
"push_updates" => "1",
"indexnow_key" => generate_indexnow_key(),
];
}
/**
* @return array{site_id: string, assigned_site_id: string, api_key: string, setup_state: string, pending_handoff: 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, pending_handoff: 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");
$pending_handoff = sanitize_hidden_option($input, "pending_handoff");
$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(),
"pending_handoff" => $pending_handoff ?? "",
"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 Winnow Search 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 Winnow Search embed -->\n";
}
function register_admin_page(): void
{
add_options_page(
__("Winnow Search", "winnow-search"),
__("Winnow Search", "winnow-search"),
"manage_options",
SETTINGS_PAGE,
__NAMESPACE__ . '\\render_settings_page',
);
}
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", "winnow-search"),
"__return_empty_string",
SETTINGS_PAGE,
);
add_settings_field(
"site_id",
__("Winnow Site ID", "winnow-search"),
__NAMESPACE__ . '\\render_site_id_field',
SETTINGS_PAGE,
SETTINGS_SECTION,
);
add_settings_field(
"push_updates",
__("Automatic updates", "winnow-search"),
__NAMESPACE__ . '\\render_push_updates_field',
SETTINGS_PAGE,
SETTINGS_SECTION,
);
}
function render_site_id_field(): void
{
$options = get_options(); ?>
<input
id="winnow_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 Winnow assigned.",
"winnow-search",
); ?>
</p>
<?php
}
function render_push_updates_field(): void
{
$options = get_options(); ?>
<label for="winnow_search_push_updates">
<input
id="winnow_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 Winnow search index current as public pages and files change.",
"winnow-search",
); ?>
</label>
<?php
}
function render_settings_page_styles(): void
{ ?>
<style>
.winnow-search-admin {
--winnow-ink: #243128;
--winnow-muted: #5c6a60;
--winnow-border: #cfd9d2;
--winnow-panel: #ffffff;
--winnow-paper: #f6f8f4;
--winnow-green: #2f5b43;
--winnow-green-soft: #e5efe8;
--winnow-alert: #8a4a34;
color: var(--winnow-ink);
max-width: 1120px;
}
.winnow-search-admin * {
box-sizing: border-box;
}
.winnow-search-hero {
align-items: stretch;
background: var(--winnow-paper);
border: 1px solid var(--winnow-border);
border-radius: 8px;
display: grid;
gap: 0;
grid-template-columns: minmax(0, 1fr) 320px;
margin: 22px 0;
overflow: hidden;
}
.winnow-search-hero.is-connected {
grid-template-columns: minmax(0, 1fr);
}
.winnow-search-hero-copy {
padding: 34px;
}
.winnow-search-eyebrow {
color: var(--winnow-green);
font-size: 15px;
font-weight: 600;
margin: 0 0 10px;
}
.winnow-search-admin h1,
.winnow-search-admin h2 {
color: var(--winnow-ink);
font-family: Georgia, "Times New Roman", serif;
font-weight: 600;
letter-spacing: 0;
}
.winnow-search-admin h1 {
font-size: 42px;
line-height: 1.08;
margin: 0;
max-width: 720px;
}
.winnow-search-intro {
color: var(--winnow-muted);
font-size: 17px;
line-height: 1.6;
margin: 18px 0 0;
max-width: 680px;
}
.winnow-search-connected-body {
align-items: flex-start;
display: flex;
gap: 26px;
margin-top: 18px;
}
.winnow-search-connected-body .winnow-search-intro {
flex: 1 1 auto;
margin: 0;
}
.winnow-search-quick-access {
border-left: 1px solid var(--winnow-border);
display: grid;
flex: 0 0 170px;
gap: 8px;
padding-left: 20px;
}
.winnow-search-quick-access-title {
color: var(--winnow-muted);
font-size: 13px;
font-weight: 700;
margin: 0 0 2px;
}
.winnow-search-quick-access a {
color: var(--winnow-green);
font-size: 14px;
font-weight: 700;
line-height: 1.25;
}
.winnow-search-status {
background: var(--winnow-panel);
border-left: 1px solid var(--winnow-border);
display: flex;
flex-direction: column;
justify-content: center;
padding: 28px;
}
.winnow-search-status-badge {
align-self: flex-start;
border-radius: 999px;
display: inline-flex;
font-size: 13px;
font-weight: 700;
line-height: 1;
padding: 8px 11px;
}
.winnow-search-status-badge.is-connected {
background: var(--winnow-green-soft);
color: var(--winnow-green);
}
.winnow-search-status-badge.is-needed {
background: #f8eee8;
color: var(--winnow-alert);
}
.winnow-search-status dl {
display: grid;
gap: 14px;
margin: 22px 0 0;
}
.winnow-search-status dt {
color: var(--winnow-muted);
font-size: 13px;
margin: 0 0 4px;
}
.winnow-search-status dd {
font-size: 15px;
font-weight: 600;
margin: 0;
overflow-wrap: anywhere;
}
.winnow-search-settings {
background: var(--winnow-panel);
border: 1px solid var(--winnow-border);
border-radius: 8px;
margin: 0 0 18px;
padding: 30px 34px 18px;
}
.winnow-search-field {
max-width: 720px;
}
.winnow-search-label {
color: var(--winnow-ink);
display: block;
font-size: 14px;
font-weight: 700;
margin-bottom: 8px;
}
.winnow-search-input {
border-color: var(--winnow-border);
border-radius: 8px;
font-size: 18px;
max-width: 440px;
min-height: 46px;
padding: 8px 12px;
width: 100%;
}
.winnow-search-input:focus {
border-color: var(--winnow-green);
box-shadow: 0 0 0 1px var(--winnow-green);
}
.winnow-search-help {
color: var(--winnow-muted);
font-size: 14px;
line-height: 1.55;
margin: 8px 0 0;
}
.winnow-search-toggle {
align-items: flex-start;
cursor: pointer;
display: flex;
gap: 14px;
margin-top: 0;
max-width: 720px;
padding-top: 0;
position: relative;
}
.winnow-search-toggle .winnow-search-switch-input {
height: 1px;
left: 0;
margin: 0;
min-height: 1px;
min-width: 1px;
opacity: 0;
position: absolute;
top: 0;
width: 1px;
}
.winnow-search-switch {
background: #d6e0da;
border: 1px solid var(--winnow-border);
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;
}
.winnow-search-switch::after {
background: #fff;
border-radius: 999px;
box-shadow: 0 1px 2px rgba(34, 50, 39, 0.22);
content: "";
height: 18px;
left: 2px;
position: absolute;
top: 2px;
transition: transform 140ms ease;
width: 18px;
}
.winnow-search-switch-input:checked + .winnow-search-switch {
background: var(--winnow-green);
border-color: var(--winnow-green);
}
.winnow-search-switch-input:checked + .winnow-search-switch::after {
transform: translateX(20px);
}
.winnow-search-switch-input:focus-visible + .winnow-search-switch {
box-shadow: 0 0 0 2px var(--winnow-panel), 0 0 0 4px var(--winnow-green);
}
.winnow-search-toggle-title {
display: block;
font-size: 15px;
font-weight: 700;
margin-bottom: 4px;
}
.winnow-search-actions {
margin-top: 26px;
}
.winnow-search-onboarding {
background: var(--winnow-panel);
border: 1px solid var(--winnow-border);
border-radius: 8px;
margin: 0 0 18px;
padding: 30px 34px;
}
.winnow-search-onboarding-row {
align-items: end;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 14px;
}
.winnow-search-onboarding-row .winnow-search-field {
flex: 1 1 280px;
max-width: 420px;
}
.winnow-search-alert {
background: var(--winnow-green-soft);
border: 1px solid var(--winnow-border);
border-radius: 8px;
color: var(--winnow-green);
font-size: 14px;
line-height: 1.5;
margin: 0 0 18px;
max-width: 780px;
padding: 14px 16px;
}
.winnow-search-connect-note {
border-top: 1px solid var(--winnow-border);
color: var(--winnow-muted);
font-size: 15px;
line-height: 1.55;
margin: 28px 0 0;
max-width: 720px;
padding-top: 22px;
}
.winnow-search-connect-note a,
.winnow-search-advanced a {
color: var(--winnow-green);
font-weight: 700;
}
.winnow-search-actions .button-primary,
.winnow-search-actions button[type="submit"] {
background: var(--winnow-green);
border-color: var(--winnow-green);
border-radius: 4px;
font-weight: 700;
min-height: 40px;
padding-left: 18px;
padding-right: 18px;
}
.winnow-search-actions .button-primary:disabled,
.winnow-search-actions button[type="submit"]:disabled {
background: #aeb8b2 !important;
border-color: #aeb8b2 !important;
color: #f7f7f4 !important;
cursor: not-allowed;
opacity: 1;
}
.winnow-search-onboarding-row .winnow-search-actions {
display: flex;
margin-top: 0;
}
.winnow-search-onboarding-row .winnow-search-input,
.winnow-search-onboarding-row .button-primary,
.winnow-search-onboarding-row button[type="submit"] {
height: 46px;
min-height: 46px;
}
.winnow-search-onboarding-row .button-primary,
.winnow-search-onboarding-row button[type="submit"] {
align-items: center;
display: inline-flex;
justify-content: center;
margin-bottom: 0;
}
.winnow-search-analytics {
background: var(--winnow-panel);
border: 1px solid var(--winnow-border);
border-radius: 8px;
margin: 0 0 18px;
padding: 30px 34px;
}
.winnow-search-analytics.is-in-hero {
background: var(--winnow-panel);
border: 0;
border-radius: 0;
border-top: 1px solid var(--winnow-border);
margin: 0;
padding: 30px 34px;
}
.winnow-search-analytics-header {
align-items: flex-start;
display: flex;
flex-wrap: wrap;
gap: 18px;
justify-content: space-between;
}
.winnow-search-analytics-header > div:first-child {
flex: 1 1 360px;
min-width: 0;
}
.winnow-search-analytics h2,
.winnow-search-analytics h3 {
color: var(--winnow-ink);
margin: 0;
}
.winnow-search-analytics h2 {
font-family: Georgia, "Times New Roman", serif;
font-size: 24px;
font-weight: 500;
}
.winnow-search-analytics h3 {
font-size: 15px;
font-weight: 700;
}
.winnow-search-analytics-kicker,
.winnow-search-analytics-state {
color: var(--winnow-muted);
font-size: 14px;
line-height: 1.55;
}
.winnow-search-analytics-kicker {
margin: 12px 0 0;
}
.winnow-search-analytics-state {
margin: 8px 0 0;
}
.winnow-search-analytics-range {
color: var(--winnow-green);
font-size: 13px;
font-weight: 700;
}
.winnow-search-analytics-link {
color: var(--winnow-green);
font-size: 14px;
font-weight: 700;
line-height: 1.2;
}
.winnow-search-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;
}
.winnow-search-analytics-metrics {
display: grid;
gap: 18px;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin-top: 24px;
}
.winnow-search-analytics-metric span {
color: var(--winnow-muted);
display: block;
font-size: 13px;
margin-bottom: 5px;
}
.winnow-search-analytics-metric strong {
color: var(--winnow-ink);
display: block;
font-size: 26px;
line-height: 1.1;
}
.winnow-search-analytics-detail {
display: grid;
gap: 26px;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
margin-top: 26px;
}
.winnow-search-query-list,
.winnow-search-volume-list {
display: grid;
gap: 10px;
list-style: none;
margin: 12px 0 0;
padding: 0;
}
.winnow-search-query-list li,
.winnow-search-volume-list li {
align-items: center;
color: var(--winnow-muted);
display: flex;
font-size: 14px;
gap: 12px;
justify-content: space-between;
}
.winnow-search-query-list strong,
.winnow-search-volume-list strong {
color: var(--winnow-ink);
font-weight: 700;
}
.winnow-search-volume-track {
background: var(--winnow-green-soft);
border-radius: 999px;
flex: 1 1 auto;
height: 8px;
overflow: hidden;
}
.winnow-search-volume-fill {
background: var(--winnow-green);
display: block;
height: 100%;
min-width: 4px;
}
.winnow-search-empty {
color: var(--winnow-muted);
font-size: 14px;
line-height: 1.55;
margin: 12px 0 0;
}
.winnow-search-hidden {
display: none;
}
.winnow-search-advanced {
margin-top: 28px;
max-width: 760px;
padding-top: 0;
}
.winnow-search-advanced summary {
color: var(--winnow-ink);
cursor: pointer;
font-size: 15px;
font-weight: 700;
}
.winnow-search-advanced-body {
padding-top: 18px;
}
.winnow-search-guidance {
background: var(--winnow-paper);
border: 1px solid var(--winnow-border);
border-radius: 8px;
display: grid;
gap: 0;
grid-template-columns: repeat(3, minmax(0, 1fr));
overflow: hidden;
}
.winnow-search-guidance-item {
padding: 24px 26px;
}
.winnow-search-guidance-item + .winnow-search-guidance-item {
border-left: 1px solid var(--winnow-border);
}
.winnow-search-guidance h2 {
font-size: 21px;
line-height: 1.2;
margin: 0 0 10px;
}
.winnow-search-guidance p {
color: var(--winnow-muted);
font-size: 14px;
line-height: 1.55;
margin: 0;
}
.winnow-search-guidance a {
color: var(--winnow-green);
font-weight: 700;
}
@media (max-width: 900px) {
.winnow-search-hero,
.winnow-search-guidance,
.winnow-search-connected-body {
grid-template-columns: 1fr;
}
.winnow-search-connected-body {
display: grid;
}
.winnow-search-quick-access {
border-left: 0;
border-top: 1px solid var(--winnow-border);
display: flex;
flex-wrap: wrap;
gap: 10px 16px;
padding-left: 0;
padding-top: 16px;
}
.winnow-search-quick-access-title {
flex: 1 0 100%;
}
.winnow-search-analytics-detail,
.winnow-search-analytics-metrics {
grid-template-columns: 1fr;
}
.winnow-search-admin h1 {
font-size: 34px;
}
.winnow-search-status,
.winnow-search-guidance-item + .winnow-search-guidance-item {
border-left: 0;
border-top: 1px solid var(--winnow-border);
}
.winnow-search-hero-copy,
.winnow-search-analytics.is-in-hero,
.winnow-search-status,
.winnow-search-analytics,
.winnow-search-settings,
.winnow-search-guidance-item {
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["winnow_setup"]) && (string) $_GET["winnow_setup"] === "sent";
$has_pending_handoff = $options["pending_handoff"] !== "";
?>
<div class="wrap winnow-search-admin">
<?php render_settings_page_styles(); ?>
<section class="winnow-search-hero">
<div class="winnow-search-hero-copy">
<p class="winnow-search-eyebrow">
<?php echo esc_html__("Winnow Search for WordPress", "winnow-search"); ?>
</p>
<h1><?php echo esc_html__("Welcome to Winnow Search", "winnow-search"); ?></h1>
<p class="winnow-search-intro">
<?php echo esc_html__(
"You can try Winnow for free on your site. Once connected, Winnow will index your public content and create and manage your search index for you. Happy searching!",
"winnow-search",
); ?>
</p>
</div>
<aside class="winnow-search-status" aria-live="polite">
<span class="winnow-search-status-badge is-needed">
<?php echo esc_html__("Setup needed", "winnow-search"); ?>
</span>
<dl>
<div>
<dt><?php echo esc_html__("Site", "winnow-search"); ?></dt>
<dd><?php echo esc_html(home_url("/")); ?></dd>
</div>
<div>
<dt><?php echo esc_html__("Cost", "winnow-search"); ?></dt>
<dd><?php echo esc_html__("Free to start", "winnow-search"); ?></dd>
</div>
</dl>
</aside>
</section>
<?php if ($sent): ?>
<p class="winnow-search-alert">
<?php echo esc_html__(
"Check your email for the Winnow sign-in link. This page will update when setup finishes in another tab.",
"winnow-search",
); ?>
</p>
<?php endif; ?>
<?php if ($has_pending_handoff): ?>
<section class="winnow-search-onboarding">
<form action="<?php echo esc_url(admin_url("admin-post.php")); ?>" method="post">
<input type="hidden" name="action" value="winnow_search_complete_setup">
<?php wp_nonce_field("winnow_search_complete_setup", "winnow_search_complete_setup_nonce"); ?>
<p class="winnow-search-help">
<?php echo esc_html__(
"Winnow has approved this connection. Finish setup to store the site key in WordPress.",
"winnow-search",
); ?>
</p>
<div class="winnow-search-actions">
<button class="button button-primary" type="submit">
<?php echo esc_html__("Finish setup", "winnow-search"); ?>
</button>
</div>
</form>
</section>
<?php endif; ?>
<section class="winnow-search-onboarding">
<form action="<?php echo esc_url(admin_url("admin-post.php")); ?>" method="post">
<input type="hidden" name="action" value="winnow_search_send_setup_link">
<?php wp_nonce_field("winnow_search_setup", "winnow_search_setup_nonce"); ?>
<label class="winnow-search-label" for="winnow_setup_email">
<?php echo esc_html__("Start with your email", "winnow-search"); ?>
</label>
<p class="winnow-search-help">
<?php echo esc_html__(
"Winnow Search needs a Winnow account. Enter your email and we will send you a link to sign in.",
"winnow-search",
); ?>
</p>
<div class="winnow-search-onboarding-row">
<div class="winnow-search-field">
<input
id="winnow_setup_email"
class="winnow-search-input regular-text"
name="winnow_setup_email"
type="email"
autocomplete="email"
required
placeholder="you@example.com"
>
</div>
<div class="winnow-search-actions">
<button class="button button-primary" type="submit">
<?php echo esc_html__("Try Winnow for free", "winnow-search"); ?>
</button>
</div>
</div>
</form>
<p class="winnow-search-connect-note">
<?php echo esc_html__(
"Already have a Winnow account? Use the same email link to connect it.",
"winnow-search",
); ?>
</p>
</section>
<?php render_setup_polling_script(); ?>
</div>
<?php
}
function render_connected_settings_page(array $options, string $effective_site_id): void
{
?>
<div class="wrap winnow-search-admin">
<?php render_settings_page_styles(); ?>
<section class="winnow-search-hero is-connected">
<div class="winnow-search-hero-copy">
<p class="winnow-search-eyebrow">
<?php echo esc_html__("Winnow Search for WordPress", "winnow-search"); ?>
</p>
<h1>
<?php echo esc_html__(
"Winnow Search is connected",
"winnow-search",
); ?>
</h1>
<div class="winnow-search-connected-body">
<p class="winnow-search-intro">
<?php echo esc_html__(
"Winnow Search is working on this site. Your public content is connected to a managed search index, so visitors can search with Winnow while you keep publishing.",
"winnow-search",
); ?>
</p>
<?php render_quick_access_panel($options); ?>
</div>
</div>
<?php render_search_analytics_card($options, $effective_site_id); ?>
</section>
<form class="winnow-search-settings" action="options.php" method="post" data-winnow-search-settings>
<?php settings_fields(SETTINGS_GROUP); ?>
<label class="winnow-search-toggle" for="winnow_search_push_updates">
<input
class="winnow-search-switch-input"
id="winnow_search_push_updates"
name="<?php echo esc_attr(OPTION_NAME); ?>[push_updates]"
type="checkbox"
value="1"
<?php checked($options["push_updates"], "1"); ?>
>
<span class="winnow-search-switch" aria-hidden="true"></span>
<span>
<span class="winnow-search-toggle-title">
<?php echo esc_html__("Automatic updates", "winnow-search"); ?>
</span>
<span class="winnow-search-help">
<?php echo esc_html__(
"Keep the search index current as you update public pages, posts, custom content, and files.",
"winnow-search",
); ?>
</span>
</span>
</label>
<details class="winnow-search-advanced">
<summary><?php echo esc_html__("Advanced settings", "winnow-search"); ?></summary>
<div class="winnow-search-advanced-body">
<div class="winnow-search-field">
<label class="winnow-search-label" for="winnow_search_site_id">
<?php echo esc_html__("Winnow Site ID", "winnow-search"); ?>
</label>
<input
id="winnow_search_site_id"
class="winnow-search-input regular-text"
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="winnow-search-help">
<?php echo esc_html__(
"Only change this if you want to use a different search index than the default Winnow assigned.",
"winnow-search",
); ?>
</p>
</div>
</div>
</details>
<div class="winnow-search-actions">
<button
class="button button-primary winnow-search-save"
type="submit"
name="submit"
disabled
data-winnow-search-save
>
<?php echo esc_html__("Save Winnow settings", "winnow-search"); ?>
</button>
</div>
</form>
<?php render_search_analytics_script(); ?>
<?php render_settings_form_dirty_script(); ?>
</div>
<?php
}
function render_quick_access_panel(array $options): void
{
if ($options["api_key"] === "") {
return;
}
$links = [
"documentation" => __("Documentation", "winnow-search"),
"design" => __("Design", "winnow-search"),
"analytics" => __("Analytics", "winnow-search"),
"more" => __("More", "winnow-search"),
];
?>
<aside class="winnow-search-quick-access" aria-label="<?php echo esc_attr(__("Winnow quick access", "winnow-search")); ?>">
<p class="winnow-search-quick-access-title">
<?php echo esc_html__("Quick access", "winnow-search"); ?>
</p>
<?php foreach ($links as $destination => $label): ?>
<a
href="<?php echo esc_url(winnow_admin_url($options, $destination)); ?>"
target="_blank"
rel="noopener noreferrer"
>
<?php echo esc_html($label); ?>
</a>
<?php endforeach; ?>
</aside>
<?php
}
function render_settings_form_dirty_script(): void
{
?>
<script>
(function renderSettingsFormDirtyState() {
var form = document.querySelector("[data-winnow-search-settings]");
if (!form) {
return;
}
var saveButton = form.querySelector("[data-winnow-search-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.winnowInitialValue = currentValue(field);
});
function hasChanges() {
return fields.some(function (field) {
return currentValue(field) !== field.dataset.winnowInitialValue;
});
}
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="winnow-search-analytics is-in-hero"
data-winnow-search-analytics
data-endpoint="<?php echo esc_url(admin_url("admin-ajax.php")); ?>"
data-nonce="<?php echo esc_attr(wp_create_nonce("winnow_search_analytics")); ?>"
data-enabled="<?php echo esc_attr($can_load_analytics ? "1" : "0"); ?>"
>
<div class="winnow-search-analytics-header">
<div>
<h2><?php echo esc_html__("Search activity", "winnow-search"); ?></h2>
<p class="winnow-search-analytics-kicker">
<?php echo esc_html__(
"A quick view of how visitors use Winnow Search on this site.",
"winnow-search",
); ?>
</p>
</div>
<div class="winnow-search-analytics-meta">
<span class="winnow-search-analytics-range" data-winnow-analytics-range>
<?php echo esc_html__("Last 30 days", "winnow-search"); ?>
</span>
</div>
</div>
<p class="winnow-search-analytics-state" data-winnow-analytics-state>
<?php echo esc_html__(
$can_load_analytics
? "Loading search activity..."
: "Search activity will appear here once this site is connected with a Winnow API key.",
"winnow-search",
); ?>
</p>
<div class="winnow-search-hidden" data-winnow-analytics-content>
<div class="winnow-search-analytics-metrics">
<div class="winnow-search-analytics-metric">
<span><?php echo esc_html__("Searches", "winnow-search"); ?></span>
<strong data-winnow-analytics-searches>0</strong>
</div>
<div class="winnow-search-analytics-metric">
<span><?php echo esc_html__("Clicks", "winnow-search"); ?></span>
<strong data-winnow-analytics-clicks>0</strong>
</div>
<div class="winnow-search-analytics-metric">
<span><?php echo esc_html__("No-result searches", "winnow-search"); ?></span>
<strong data-winnow-analytics-zero-results>0</strong>
</div>
</div>
<div class="winnow-search-analytics-detail">
<div>
<h3><?php echo esc_html__("Recent search terms", "winnow-search"); ?></h3>
<ol class="winnow-search-query-list" data-winnow-analytics-queries></ol>
<p class="winnow-search-empty winnow-search-hidden" data-winnow-analytics-empty-queries>
<?php echo esc_html__(
"Search terms will appear once visitors start searching.",
"winnow-search",
); ?>
</p>
</div>
<div>
<h3><?php echo esc_html__("Search volume", "winnow-search"); ?></h3>
<ol class="winnow-search-volume-list" data-winnow-analytics-volume></ol>
<p class="winnow-search-empty winnow-search-hidden" data-winnow-analytics-empty-volume>
<?php echo esc_html__(
"Search volume will appear once there is activity in the current period.",
"winnow-search",
); ?>
</p>
</div>
</div>
</div>
</div>
<?php
}
function render_setup_polling_script(): void
{
$ajax_url = admin_url("admin-ajax.php");
$nonce = wp_create_nonce("winnow_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=winnow_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-winnow-search-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-winnow-analytics-state]");
var content = card.querySelector("[data-winnow-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("winnow-search-hidden", !show);
}
}
function renderQueries(queries) {
var list = card.querySelector("[data-winnow-analytics-queries]");
if (!list) {
return;
}
list.innerHTML = "";
if (!queries || !queries.length) {
showEmpty("[data-winnow-analytics-empty-queries]", true);
return;
}
showEmpty("[data-winnow-analytics-empty-queries]", false);
queries.forEach(function (query) {
var item = document.createElement("li");
var term = document.createElement("strong");
var count = document.createElement("span");
term.textContent = query.term || "";
count.textContent = formatCount(query.searches) + " searches";
item.appendChild(term);
item.appendChild(count);
list.appendChild(item);
});
}
function renderVolume(points) {
var list = card.querySelector("[data-winnow-analytics-volume]");
if (!list) {
return;
}
list.innerHTML = "";
if (!points || !points.length) {
showEmpty("[data-winnow-analytics-empty-volume]", true);
return;
}
showEmpty("[data-winnow-analytics-empty-volume]", false);
var max = points.reduce(function (current, point) {
return Math.max(current, parseInt(point.count, 10) || 0);
}, 0);
points.forEach(function (point) {
var item = document.createElement("li");
var label = document.createElement("strong");
var track = document.createElement("span");
var fill = document.createElement("span");
var count = document.createElement("span");
var value = parseInt(point.count, 10) || 0;
var width = max > 0 ? Math.max(Math.round((value / max) * 100), 6) : 0;
label.textContent = point.label || "";
track.className = "winnow-search-volume-track";
fill.className = "winnow-search-volume-fill";
fill.style.width = width + "%";
count.textContent = formatCount(value);
track.appendChild(fill);
item.appendChild(label);
item.appendChild(track);
item.appendChild(count);
list.appendChild(item);
});
}
fetch(endpoint + "?action=winnow_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-winnow-analytics-range]");
if (range && data.range && data.range.label) {
range.textContent = data.range.label;
}
setText("[data-winnow-analytics-searches]", data.totals && data.totals.searches);
setText("[data-winnow-analytics-clicks]", data.totals && data.totals.clicks);
setText("[data-winnow-analytics-zero-results]", data.totals && data.totals.zeroResults);
renderQueries(data.topQueries || []);
renderVolume(data.dailyVolume || []);
if (state) {
state.classList.add("winnow-search-hidden");
}
if (content) {
content.classList.remove("winnow-search-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("winnow_search_setup", "winnow_search_setup_nonce");
$email = isset($_POST["winnow_setup_email"])
? sanitize_email(wp_unslash($_POST["winnow_setup_email"]))
: "";
if (!is_email($email)) {
redirect_to_settings(["winnow_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(["winnow_setup" => "sent"]);
return;
}
redirect_to_settings(["winnow_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(["winnow_setup" => "state_mismatch"]);
return;
}
$options["pending_handoff"] = $handoff;
update_option(OPTION_NAME, sanitize_options($options));
redirect_to_settings(["winnow_setup" => "ready"]);
}
function complete_setup_from_handoff(): void
{
if (!current_user_can("manage_options")) {
status_header(403);
return;
}
check_admin_referer("winnow_search_complete_setup", "winnow_search_complete_setup_nonce");
$options = get_options();
$handoff = $options["pending_handoff"];
if ($handoff === "") {
redirect_to_settings(["winnow_setup" => "claim_failed"]);
return;
}
$claim = claim_handoff($handoff);
if ($claim === null) {
redirect_to_settings(["winnow_setup" => "claim_failed"]);
return;
}
$options["api_key"] = $claim["api_key"];
$options["assigned_site_id"] = $claim["site_id"];
$options["pending_handoff"] = "";
update_option(OPTION_NAME, sanitize_options($options));
redirect_to_settings(["winnow_setup" => "connected"]);
}
function ajax_setup_status(): void
{
if (!current_user_can("manage_options")) {
wp_send_json_error(["connected" => false]);
return;
}
check_ajax_referer("winnow_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("winnow_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 winnow_admin_url(array $options, string $destination): string
{
$site_id = rawurlencode(effective_site_id($options));
switch ($destination) {
case "documentation":
return winnow_app_url("/site-search/app/documentation");
case "design":
return winnow_app_url("/site-search/app/site/" . $site_id . "/design");
case "analytics":
return winnow_app_url("/site-search/app/site/" . $site_id . "/analytics");
case "more":
default:
return winnow_app_url("/site-search/app/site/" . $site_id);
}
}
function winnow_app_url(string $path): string
{
return rtrim(WINNOW_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("options-general.php?page=" . SETTINGS_PAGE);
}
function redirect_to_settings(array $params): void
{
wp_safe_redirect(add_query_arg($params, settings_page_url()));
if (!defined("WINNOW_SEARCH_TESTING") || WINNOW_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(admin_url("options-general.php?page=" . SETTINGS_PAGE));
if (!defined("WINNOW_SEARCH_TESTING") || WINNOW_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("WINNOW_SEARCH_TESTING") || WINNOW_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();