From 31a4b450f106e9beb14347e871fd8ca0235337fa Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:00:56 +0000
Subject: [PATCH 01/15] Detect the OWA server version; show only its settings
The OWA Server Version switch is gone. The plugin asks the endpoint which
version it runs: GET api/index.php?owa_rest_params=base/v1/sites with
Authorization: Bearer owa-version-probe. 401 with a Bearer
WWW-Authenticate challenge is 2.x; OWA 1.x's REST envelope without one is
1.x; anything else identifies nothing, keeps the version found before and
the settings page says why.
- owaVersion stays the stored option, now detected: '1', '2', or '' while
none is known. Only the OWA Endpoint shows until a version is known;
then only that version's fields. On 2.x the Tracking tab stays without
click tracking and Domstreams, as before.
- Checked when the endpoint is saved (new, or not identified yet), once a
day on an administrator's admin page load, and with Check again
(POST owa-wp/v1/server).
- After an update, the first admin page load checks the server and
replaces the chosen version; when nothing is identified the chosen
version (or 1, the old default) is kept. Until then the tag is as before.
- A server that was 1.x and is now 2.x flags a dismissible notice on the
dashboard, Plugins and settings screens asking for an application
password. The 1.x keys are kept.
- Network Admin > OWA refuses an endpoint that identifies as 1.x.
- The Application Password field links to OWA's documentation.
- CI: OWA's v2 branch is gone; the 2.x jobs run on master, which refuses
1.x keys, so that integration job runs the owa2 group only.
---
.github/workflows/ci.yml | 13 +-
README.md | 2 +-
README.txt | 28 +-
bin/check-package.sh | 2 +-
js/lib/fields.js | 44 ++-
js/settings/index.js | 118 +++++--
js/settings/style.css | 9 +
owa-plugin.php | 107 +++---
src/admin.php | 5 +
src/network.php | 10 +-
src/rest.php | 77 ++++-
src/server.php | 394 ++++++++++++++++++++++
tests/Integration/OwaServerTest.php | 17 +-
tests/Integration/OwaV2ServerTest.php | 13 +
tests/Integration/RealHttp.php | 53 +++
tests/NetworkTest.php | 24 +-
tests/OwaV2Test.php | 70 +++-
tests/RestTest.php | 14 +-
tests/ServerTest.php | 463 ++++++++++++++++++++++++++
tests/TestCase.php | 53 ++-
tests/bootstrap.php | 1 +
tests/e2e/single.spec.js | 66 ++--
tests/js/fields.test.js | 62 ++--
23 files changed, 1479 insertions(+), 166 deletions(-)
create mode 100644 src/server.php
create mode 100644 tests/Integration/RealHttp.php
create mode 100644 tests/ServerTest.php
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bb5987f..241b22f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -65,7 +65,8 @@ jobs:
run: bin/check-package.sh
# The plugin against a real OWA server: the tracker is served where the tag
- # loads it, and the signed GET /base/v1/sites answers the Website ID picker.
+ # loads it, GET /base/v1/sites answers the Website ID picker, and the version
+ # probe identifies the server.
integration:
name: OWA ${{ matrix.owa }}
runs-on: ubuntu-latest
@@ -76,10 +77,10 @@ jobs:
- owa: '1.14.0'
release: '1.14.0'
groups: 'owa1'
- - owa: 'v2'
- branch: 'v2'
- # v2 still takes the 1.x keys; owa2 is the bundle tag and app passwords
- groups: 'owa1,owa2'
+ - owa: 'master'
+ branch: 'master'
+ # 2.x refuses the 1.x keys: the bundle tag and app passwords
+ groups: 'owa2'
services:
mysql:
image: mysql:8.0
@@ -142,7 +143,7 @@ jobs:
run: composer install --no-interaction --no-progress
- uses: ./.github/actions/owa-server
with:
- branch: v2
+ branch: master
app-passwords: 'true'
domain: https://wp.test
profiles: |
diff --git a/README.md b/README.md
index 060811f..ab43efd 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
Adds Open Web Analytics (OWA) tracking to WordPress sites and multisite networks.
-- OWA 1.x (API key) and 2.x (application password and tracking bundle, beta)
+- OWA 1.x (API key) and 2.x (application password and tracking bundle, beta), detected from the server; the settings page shows only the detected version's settings
- Multisite network mode for OWA 2.x: one server and password for the network, an Observation Profile and tracking switch per site
- Fires `owa_wp_tag_changed` when a site's tag changes, so page caches can purge; Proxy Cache Purge does
diff --git a/README.txt b/README.txt
index b4402ba..960b2e6 100644
--- a/README.txt
+++ b/README.txt
@@ -18,10 +18,12 @@ Adds the Open Web Analytics (OWA) tracking tag to your site's public pages. Requ
= OWA 1.x and 2.x =
-Choose the server version under OWA > Settings.
+The plugin detects which version the OWA server at the OWA Endpoint runs and shows only the settings for that version.
* **1.x** authenticates with an OWA user's API key and the server's Secret Auth Key. Tracker options are set in WordPress.
-* **2.x (beta)** authenticates with an OWA application password and loads the Observation Profile's tracking bundle. Tracker options are set on the OWA server; the settings page links to them.
+* **2.x (beta)** authenticates with an OWA application password and loads the Observation Profile's tracking bundle. Click tracking and Domstreams are set on the OWA server; the settings page links to them.
+
+The version is checked when the OWA Endpoint is saved, once a day when an administrator opens an admin page, and with Check again on the settings page. When a 1.x server is upgraded to 2.x, the dashboard, Plugins screen and settings page ask for an application password. Tracking continues meanwhile.
= What is tracked =
@@ -46,16 +48,20 @@ A cached page keeps the tracking tag it was rendered with. When a site's tag cha
1. Install and activate the plugin.
2. Go to OWA > Settings.
-3. Enter your OWA server's URL as the OWA Endpoint. Saving checks that OWA answers there and stores the URL it answers at, after any redirect. Without `https://` or `http://`, https is tried first, then http.
-4. Enter the credentials:
+3. Enter your OWA server's URL as the OWA Endpoint and save. Saving checks that OWA answers there, stores the URL it answers at (after any redirect), and detects the OWA version. Without `https://` or `http://`, https is tried first, then http.
+4. Enter the credentials the page now asks for:
* 1.x: the API Key (OWA: Settings > Users > Edit) and the Secret Auth Key (`OWA_AUTH_KEY` in the server's `owa-config.php`).
- * 2.x: select 2.x and enter an Application Password (OWA: My Preferences > Application Passwords). A read-only password is enough.
+ * 2.x: an Application Password (OWA: My Preferences > Application Passwords). A read-only password is enough.
5. Save. Once OWA accepts the credentials, the Observation Profile list appears: select the one to track and save again. The plugin stores its site ID; in 1.x the field is labeled Website ID.
-On a multisite network, set up OWA 2.x once under Network Admin > OWA.
+On a multisite network, set up OWA 2.x once under Network Admin > OWA. A 1.x server is refused there.
== Frequently Asked Questions ==
+= The settings page shows only the OWA Endpoint =
+
+No OWA version was detected at that URL. The page shows why. The plugin requests `api/index.php` under the OWA Endpoint, so OWA's REST API has to answer there.
+
= No tracking tag appears =
The tag is added once Enable OWA is on and the OWA Endpoint and Observation Profile are saved. Your theme must call `wp_head()`.
@@ -68,7 +74,7 @@ Application passwords are sent only over https. To use an http OWA server, turn
== Screenshots ==
-1. Settings for OWA 1.x.
+1. Setup starts with the OWA server's URL.
2. Settings for OWA 2.x.
3. Network Admin > OWA: each site's Observation Profile and tracking switch.
4. A site whose Observation Profile the network sets.
@@ -76,6 +82,14 @@ Application passwords are sent only over https. To use an http OWA server, turn
== Changelog ==
+= 2.5.0 =
+
+* The OWA Server Version setting is gone. The plugin detects the version at the OWA Endpoint and shows only that version's settings; until a version is detected, only the OWA Endpoint. It checks when the endpoint is saved, once a day on admin page loads, and with Check again. If no version can be detected, the version found before is kept and the page says so.
+* After updating, the first admin page load checks the server and replaces the version chosen before. If the server cannot be identified, the version chosen before is kept.
+* A 1.x server upgraded to 2.x: the dashboard, Plugins screen and settings page ask for an application password (dismissible). The 1.x keys stay stored, and tracking continues with the 2.x tag.
+* The Application Password field links to OWA's documentation.
+* Network Admin > OWA refuses an OWA Endpoint that identifies as 1.x.
+
= 2.4.1 =
* Don't Track Logged-in Users: a logged-in user now gets the tracker paused instead of no tracker, so OWA's heatmap and Domstream player open on the site. Nothing is sent to OWA for them, but their browser still loads the tracker from the OWA server. Admin pages still get no tracker.
diff --git a/bin/check-package.sh b/bin/check-package.sh
index 208a704..3f2d274 100755
--- a/bin/check-package.sh
+++ b/bin/check-package.sh
@@ -12,7 +12,7 @@ rsync -rc --exclude-from="$root/.distignore" "$root/" "$out/"
fail=0
-for path in owa-plugin.php README.txt src/module.php src/rest.php src/admin.php src/network.php \
+for path in owa-plugin.php README.txt src/module.php src/rest.php src/admin.php src/network.php src/server.php \
vendor/autoload.php vendor/open-web-analytics/owa-php-sdk/src/sdk.php \
build/settings.js build/settings.asset.php build/network.js build/network.asset.php build/style-settings.css; do
[ -e "$out/$path" ] || { echo "missing from package: $path"; fail=1; }
diff --git a/js/lib/fields.js b/js/lib/fields.js
index ef95b20..1166fef 100644
--- a/js/lib/fields.js
+++ b/js/lib/fields.js
@@ -1,14 +1,19 @@
/**
* Which fields and tabs the site settings page shows.
*
- * A field tagged with a server version ("1" or "2") shows only while that
- * version is chosen. A field the network manages is hidden, unless it is shown
- * read-only (the Website ID the network assigned).
+ * The version is the one the server detected at the saved endpoint ("1" or
+ * "2"), or "" while none is known: then only the endpoint shows. A field
+ * tagged with a version shows only for that version. A field the network
+ * manages is hidden, unless it is shown read-only (the Website ID the network
+ * assigned).
*/
export function isVisible( field, version ) {
if ( field.managed && ! field.readonly ) {
return false;
}
+ if ( ! version ) {
+ return field.type === 'url';
+ }
return ! field.version || field.version === version;
}
@@ -16,21 +21,42 @@ export function visibleFields( fields, version, section ) {
return fields.filter( ( field ) => isVisible( field, version ) && ( ! section || field.section === section ) );
}
-/** A field's title and description for the chosen version: 2.x has its own wording for some. */
+/** A field's title and description for the detected version: 2.x has its own wording for some. */
export function fieldText( field, version ) {
const v2 = version === '2' ? field.v2 || {} : {};
return { title: v2.title || field.title, description: v2.description || field.description };
}
/**
- * What is left to set up, as the server found it in the saved settings,
- * worded for the version chosen on the page; none while tracking is off.
+ * What is left to set up, as the server found it in the saved settings; none
+ * while tracking is off.
*/
export function setupNotices( payload, values ) {
if ( ! Number( values.enable ) ) {
return [];
}
- return ( payload.notices || {} )[ values.owaVersion === '2' ? '2' : '1' ] || [];
+ return payload.notices || [];
+}
+
+/**
+ * What the page says about the server at the saved endpoint:
+ * - "network": the network administrator manages it; nothing is said.
+ * - "none": no endpoint saved yet.
+ * - "unidentified": an endpoint, and no version was ever found there.
+ * - "stale": the last check found no version; the one found before is used.
+ * - "identified": the last check found the version shown.
+ */
+export function serverState( server ) {
+ if ( server.network ) {
+ return 'network';
+ }
+ if ( ! server.url ) {
+ return 'none';
+ }
+ if ( ! server.version ) {
+ return 'unidentified';
+ }
+ return server.identified ? 'identified' : 'stale';
}
/** The tabs that have something to show. */
@@ -41,11 +67,11 @@ export function visibleSections( sections, fields, version ) {
/**
* The link to the Website ID's tracking tag screen in OWA shows only for what
* is saved: the server builds it from the saved settings, so it is hidden
- * while the version, the endpoint or the Website ID differs from them.
+ * while the endpoint or the Website ID differs from them.
*/
export function showTagSettingsLink( payload, values ) {
return Boolean( payload.tagSettingsUrl ) &&
- [ 'owaVersion', 'owaEndpoint', 'siteId' ].every( ( key ) => values[ key ] === payload.values[ key ] );
+ [ 'owaEndpoint', 'siteId' ].every( ( key ) => values[ key ] === payload.values[ key ] );
}
/**
diff --git a/js/settings/index.js b/js/settings/index.js
index b928449..904a362 100644
--- a/js/settings/index.js
+++ b/js/settings/index.js
@@ -2,8 +2,9 @@
* OWA > Settings: the site's settings, from GET/POST owa-wp/v1/settings.
*
* The fields come from the server (owaWp_plugin::registerOptions()), with
- * the version each belongs to and whether the network manages it, so this
- * page decides only how each type is drawn and which ones show.
+ * the version each belongs to and whether the network manages it, and the
+ * version detected at the saved endpoint (payload.server), so this page
+ * decides only how each type is drawn and which ones show.
*/
import { createRoot, useEffect, useState } from '@wordpress/element';
import {
@@ -18,21 +19,77 @@ import {
ToggleControl,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
+import { __, sprintf } from '@wordpress/i18n';
-import { fieldText, setupNotices, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../lib/fields';
+import { fieldText, serverState, setupNotices, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../lib/fields';
import { secretHint, secretsPayload } from '../lib/secrets';
import './style.css';
const SETTINGS = '/owa-wp/v1/settings';
const SITES = '/owa-wp/v1/sites';
+const SERVER = '/owa-wp/v1/server';
function FieldError( { message } ) {
return message ?
{ message }
: null;
}
-function WebsiteId( { field, value, onChange, sites, payload, values } ) {
- const v2 = values.owaVersion === '2';
- const text = fieldText( field, values.owaVersion );
+/** Under the endpoint: the OWA version found there, or why none was. */
+function ServerStatus( { server, onCheck, checking } ) {
+ const state = serverState( server );
+ const check = (
+
+ );
+
+ switch ( state ) {
+ case 'none':
+ return (
+
+ { __( 'Enter the URL of your OWA server and save. The settings for the OWA version it runs then appear.', 'open-web-analytics' ) }
+
+ );
+ case 'unidentified':
+ return (
+
+ { sprintf(
+ /* translators: 1: the OWA Endpoint URL, 2: why it was not identified */
+ __( 'No OWA server could be identified at %1$s (%2$s). Check the URL and save it again.', 'open-web-analytics' ),
+ server.url,
+ server.reason
+ ) }{ ' ' }{ check }
+
+ );
+ case 'stale':
+ return (
+
+ { sprintf(
+ /* translators: 1: the OWA Endpoint URL, 2: why it was not identified, 3: the OWA major version found before */
+ __( 'The OWA server at %1$s could not be identified (%2$s). Showing the settings for OWA %3$s.x, the version found there before.', 'open-web-analytics' ),
+ server.url,
+ server.reason,
+ server.version
+ ) }{ ' ' }{ check }
+
+ );
+ case 'identified':
+ return (
+
+ { sprintf(
+ /* translators: %s: the OWA major version */
+ __( 'This is an OWA %s.x server.', 'open-web-analytics' ),
+ server.version
+ ) }{ ' ' }{ check }
+
+ { __( 'How to create an application password', 'open-web-analytics' ) }
+
+ ) }
>
);
}
case 'select':
- return setValue( field.key, v ) } sites={ sites } payload={ payload } values={ values } />;
+ return setValue( field.key, v ) } sites={ sites } payload={ payload } values={ values } version={ version } />;
default:
return (
- setValue( field.key, v ) }
- />
+ <>
+ setValue( field.key, v ) }
+ />
+ { field.type === 'url' && server && }
+ >
);
}
}
@@ -125,6 +190,7 @@ function SettingsPage() {
const [ errors, setErrors ] = useState( {} );
const [ notice, setNotice ] = useState( null );
const [ saving, setSaving ] = useState( false );
+ const [ checking, setChecking ] = useState( false );
const loadSites = () => {
setSites( ( current ) => ( { ...current, loading: true } ) );
@@ -163,11 +229,23 @@ function SettingsPage() {
.finally( () => setSaving( false ) );
};
+ const checkServer = () => {
+ setChecking( true );
+ setNotice( null );
+ apiFetch( { path: SERVER, method: 'POST' } )
+ .then( ( result ) => {
+ apply( result );
+ loadSites();
+ } )
+ .catch( ( error ) => setNotice( { status: 'error', text: error.message } ) )
+ .finally( () => setChecking( false ) );
+ };
+
if ( ! payload ) {
return notice ? { notice.text } : ;
}
- const version = values.owaVersion || '1';
+ const version = payload.server.version;
const tabs = visibleSections( payload.sections, payload.fields, version ).map( ( section ) => ( {
name: section.name,
title: section.title,
@@ -204,6 +282,8 @@ function SettingsPage() {
secrets={ secrets }
setSecret={ setSecret }
sites={ sites }
+ version={ version }
+ server={ { server: payload.server, onCheck: checkServer, checking } }
/>
diff --git a/js/settings/style.css b/js/settings/style.css
index 3101107..b6249fa 100644
--- a/js/settings/style.css
+++ b/js/settings/style.css
@@ -69,3 +69,12 @@
width: 1%;
white-space: nowrap;
}
+
+/* under the OWA Endpoint: the version found there */
+.owa-wp-server {
+ margin: 8px 0 0;
+}
+
+.owa-wp-server .components-button.is-link {
+ vertical-align: baseline;
+}
diff --git a/owa-plugin.php b/owa-plugin.php
index 9f4d083..d6a81ce 100644
--- a/owa-plugin.php
+++ b/owa-plugin.php
@@ -5,10 +5,11 @@
Plugin URI: http://www.openwebanalytics.com
Description: This plugin enables Wordpress blog owners to use the Open Web Analytics Framework.
Author: Peter Adams
-Version: 2.4.1
+Version: 2.5.0
Requires at least: 5.2
Requires PHP: 8.2
Author URI: http://www.openwebanalytics.com
+Text Domain: open-web-analytics
*/
//
@@ -37,6 +38,11 @@
define('OWA_WP_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
+// the plugin version (the header's), for the migration run after an update
+if ( ! defined( 'OWA_WP_VERSION' ) ) {
+ define( 'OWA_WP_VERSION', '2.5.0' );
+}
+
// Hook package creation
add_action('plugins_loaded', [ 'owaWp_plugin', 'getInstance' ], 10 );
@@ -160,6 +166,9 @@ function _init() {
// the settings pages (React, src/js) and the REST routes they use
owaWp\admin::register( $this );
owaWp\rest::register( $this );
+
+ // which OWA version the endpoint runs: checked after an update, daily, and on request
+ owaWp\server::register( $this );
}
@@ -189,8 +198,8 @@ function showNag() {
$messages = $this->adminMsgs;
- // the settings page shows these itself, for the version chosen on it
- if ( ! $this->isSettingsScreen() ) {
+ // the settings page shows these itself; the upgrade notice says what to do instead
+ if ( ! $this->isSettingsScreen() && ! owaWp\server::upgradeNoticeApplies( $this ) ) {
foreach ( $this->setupNotices() as $notice ) {
@@ -231,6 +240,9 @@ private function initOptions() {
$this->options = array_merge( $this->options, $options );
}
+ // detected, not chosen: '' until a version is known (see owaWp\server)
+ $this->options['owaVersion'] = owaWp\server::storedVersion( $options );
+
$this->applyNetworkOptions();
}
@@ -450,11 +462,12 @@ function getLastSitesError() {
}
/**
- * The OWA server version the settings are for: 1 or 2.
+ * The OWA server version detected at the endpoint: 1 or 2, or 0 while
+ * none is known (owaWp\server).
*/
function getOwaVersion() {
- return (string) $this->getOption( 'owaVersion' ) === '2' ? 2 : 1;
+ return [ '1' => 1, '2' => 2 ][ (string) $this->getOption( 'owaVersion' ) ] ?? 0;
}
/**
@@ -464,7 +477,8 @@ function isOwaReadyToTrack( $version = null ) {
$version = $version ?? $this->getOwaVersion();
- if ( ! $this->getOption( 'owaEndpoint' ) || ! $this->getOption( 'siteId' ) ) {
+ // which tag works depends on the version
+ if ( ! $version || ! $this->getOption( 'owaEndpoint' ) || ! $this->getOption( 'siteId' ) ) {
return false;
}
@@ -497,7 +511,12 @@ function isOwaSdkReady( $version = null ) {
return (bool) $this->getOption( 'appPassword' );
}
- return $this->getOption( 'apiKey' ) && $this->getOption( 'authKey' );
+ if ( $version === 1 ) {
+
+ return $this->getOption( 'apiKey' ) && $this->getOption( 'authKey' );
+ }
+
+ return false;
}
// init the OWA SDK
@@ -588,7 +607,8 @@ function insertTrackingTag() {
if ( $this->getOwaVersion() === 2 ) {
- // the bundle sets the site ID, the Profile's features and the page view
+ // the bundle sets the site ID, the Profile's tracker options and
+ // features and the page view; the page adds only what WordPress knows
$this->setPageTypeCmd();
$this->setPageTitleCmd();
@@ -730,6 +750,15 @@ function setupNotices( $version = null ) {
$version = $version ?? $this->getOwaVersion();
$notices = [];
+ // no version yet: the settings for one show once the endpoint identifies it
+ if ( ! $version ) {
+
+ return [ $this->getOption( 'owaEndpoint' )
+ /* translators: %s: the OWA Endpoint URL */
+ ? sprintf( __( 'No OWA server could be identified at %s. Check the OWA Endpoint under OWA > Settings.', 'open-web-analytics' ), $this->getOption( 'owaEndpoint' ) )
+ : __( 'Enter the URL of your OWA server as the OWA Endpoint under OWA > Settings.', 'open-web-analytics' ) ];
+ }
+
if ( ! $this->isOwaSdkReady( $version ) ) {
$notices[] = $version === 2
@@ -819,35 +848,22 @@ public function registerOptions() {
$settings = array(
- 'owaVersion' => array(
+ 'owaEndpoint' => array(
- 'default_value' => '1',
+ 'default_value' => '',
'field' => array(
- 'type' => 'radio',
- 'title' => 'OWA Server Version',
+ 'type' => 'url',
+ 'title' => 'OWA Endpoint',
'page_name' => 'owa-wordpress',
'section' => 'general',
- 'description' => 'Which Open Web Analytics server this site reports to. 2.x (beta) loads the Observation Profile's tracking bundle; its tracker settings are made on the OWA server.',
- 'label_for' => 'OWA server version',
- 'options' => [ '1' => '1.x', '2' => '2.x (beta)' ],
+ 'description' => 'The URL of your OWA instance (e.g. https://owa.example.com/path/to/owa/), the OWA_PUBLIC_URL in its owa-config.php. Saving checks that OWA answers there and which version it runs, and shows the settings for that version. Without https:// or http://, https is tried first.',
+ 'label_for' => 'OWA Endpoint',
+ 'length' => 70,
+ 'endWithSlash' => true,
'error_message' => ''
)
),
- 'enable' => array(
-
- 'default_value' => true,
- 'field' => array(
- 'type' => 'boolean',
- 'title' => 'Enable OWA ',
- 'page_name' => 'owa-wordpress',
- 'section' => 'general',
- 'description' => 'Enable OWA.',
- 'label_for' => 'Enable OWA.',
- 'error_message' => 'You must select On or Off.'
- )
- ),
-
'apiKey' => array(
'default_value' => '',
@@ -894,28 +910,13 @@ public function registerOptions() {
'page_name' => 'owa-wordpress',
'section' => 'general',
'description' => 'An application password from your OWA 2.x server (My Preferences > Application Passwords). A read-only one is enough. OWA refuses it over plain http unless the server allows that.',
+ 'help_url' => owaWp\server::APP_PASSWORDS_URL,
'label_for' => 'Application password',
'length' => 60,
'error_message' => ''
)
),
- 'owaEndpoint' => array(
-
- 'default_value' => '',
- 'field' => array(
- 'type' => 'url',
- 'title' => 'OWA Endpoint',
- 'page_name' => 'owa-wordpress',
- 'section' => 'general',
- 'description' => 'The URL of your OWA instance (e.g. https://owa.example.com/path/to/owa/), the OWA_PUBLIC_URL in its owa-config.php. Saving checks that OWA answers there. Without https:// or http://, https is tried first.',
- 'label_for' => 'OWA Endpoint',
- 'length' => 70,
- 'endWithSlash' => true,
- 'error_message' => ''
- )
- ),
-
'siteId' => array(
'default_value' => '',
@@ -935,6 +936,20 @@ public function registerOptions() {
),
+ 'enable' => array(
+
+ 'default_value' => true,
+ 'field' => array(
+ 'type' => 'boolean',
+ 'title' => 'Enable OWA ',
+ 'page_name' => 'owa-wordpress',
+ 'section' => 'general',
+ 'description' => 'Enable OWA.',
+ 'label_for' => 'Enable OWA.',
+ 'error_message' => 'You must select On or Off.'
+ )
+ ),
+
'trackClicks' => array(
'default_value' => true,
@@ -1031,7 +1046,7 @@ public function registerOptions() {
if ( owaWp\network::isActive() ) {
- $managed = [ 'owaVersion', 'owaEndpoint', 'appPassword', 'apiKey', 'authKey' ];
+ $managed = [ 'owaEndpoint', 'appPassword', 'apiKey', 'authKey' ];
if ( owaWp\network::options()['assignProfiles'] ) {
diff --git a/src/admin.php b/src/admin.php
index dd68465..be9e766 100644
--- a/src/admin.php
+++ b/src/admin.php
@@ -109,6 +109,11 @@ public static function enqueue( $hook ) {
$url = plugins_url( 'build/', OWA_WP_PLUGIN_PATH . 'owa-plugin.php' );
wp_enqueue_script( 'owa-wp-' . $entry, $url . $entry . '.js', $asset['dependencies'], $asset['version'], true );
+
+ if ( function_exists( 'wp_set_script_translations' ) ) {
+
+ wp_set_script_translations( 'owa-wp-' . $entry, 'open-web-analytics' );
+ }
wp_enqueue_style( 'wp-components' );
// both pages import the same stylesheet, which webpack emits once
diff --git a/src/network.php b/src/network.php
index 7d6c1ab..feb569b 100644
--- a/src/network.php
+++ b/src/network.php
@@ -4,7 +4,7 @@
/**
- * Multisite network mode (OWA 2.x only).
+ * Multisite network mode (OWA 2.x only; a 1.x endpoint is refused on save).
*
* The network administrator enters the OWA endpoint and one application
* password; each site picks its own Website ID (Profile) with them, from the
@@ -580,6 +580,14 @@ public static function save( array $input, $plugin ) {
[ $options, $errors ] = self::sanitize( $input, $stored );
+ // network mode is 2.x only: a new endpoint that identifies as 1.x is refused
+ $endpoint = (string) ( $options['owaEndpoint'] ?? '' );
+
+ if ( ! $errors && $endpoint !== '' && $endpoint !== (string) ( $stored['owaEndpoint'] ?? '' ) && server::probe( $endpoint )['version'] === 1 ) {
+
+ $errors['owaEndpoint'] = __( 'This is an OWA 1.x server. Network mode needs OWA 2.x; set up OWA 1.x on each site under OWA > Settings.', 'open-web-analytics' );
+ }
+
if ( $errors ) {
return [ null, $errors, [] ];
diff --git a/src/rest.php b/src/rest.php
index 6fe55d0..135a8d1 100644
--- a/src/rest.php
+++ b/src/rest.php
@@ -40,6 +40,11 @@ public static function registerRoutes( $plugin ) {
[ 'methods' => 'POST', 'callback' => fn( $request ) => self::saveSettings( $plugin, (array) $request->get_json_params() ), 'permission_callback' => $site ],
] );
+ // "Check again": which OWA version the saved endpoint runs
+ register_rest_route( self::NAMESPACE, '/server', [
+ [ 'methods' => 'POST', 'callback' => fn() => self::checkServer( $plugin ), 'permission_callback' => $site ],
+ ] );
+
register_rest_route( self::NAMESPACE, '/sites', [
[ 'methods' => 'GET', 'callback' => fn() => self::sitesPayload( $plugin ), 'permission_callback' => $site ],
] );
@@ -76,6 +81,7 @@ public static function settingsPayload( $plugin ) {
fn( $text ) => html_entity_decode( (string) $text, ENT_QUOTES, 'UTF-8' ),
array_filter( [ 'title' => $field['title_v2'] ?? '', 'description' => $field['description_v2'] ?? '' ] )
),
+ 'helpUrl' => (string) ( $field['help_url'] ?? '' ),
'section' => $field['section'] ?? 'general',
'version' => $field['owa_version'] ?? null,
'options' => self::choices( $field['options'] ?? [] ),
@@ -106,8 +112,10 @@ public static function settingsPayload( $plugin ) {
'secrets' => $secrets,
'sections' => $sections,
'network' => [ 'active' => network::isActive(), 'note' => $plugin->getNetworkNote() ],
- // what is left to set up, worded for each version, from the saved settings
- 'notices' => [ '1' => $plugin->setupNotices( 1 ), '2' => $plugin->setupNotices( 2 ) ],
+ // the version detected at the endpoint decides which fields show
+ 'server' => server::status( $plugin ),
+ // what is left to set up for that version; without one, the server status says it
+ 'notices' => $plugin->getOwaVersion() ? $plugin->setupNotices() : [],
'tagSettingsUrl' => $plugin->getOwaVersion() === 2 && $plugin->getOption( 'owaEndpoint' ) && $plugin->getOption( 'siteId' ) ? $plugin->getTagSettingsUrl() : '',
];
}
@@ -142,6 +150,36 @@ public static function saveSettings( $plugin, array $input ) {
[ $out, $errors ] = self::sanitizeSettings( $plugin->registerOptions(), $input, $stored );
+ // a new endpoint, or one not identified yet, is checked for its version
+ if ( ! $errors && ! network::isActive() ) {
+
+ $out['owaVersion'] = server::storedVersion( $stored ?: false );
+
+ if ( server::needsCheck( $stored, (string) ( $out['owaEndpoint'] ?? '' ) ) ) {
+
+ $out = server::applyResult( $out, $out['owaEndpoint'], server::probe( $out['owaEndpoint'] ), time() );
+ set_transient( server::TRANSIENT, $out['owaEndpoint'], DAY_IN_SECONDS );
+ }
+
+ if ( (string) ( $out['owaEndpoint'] ?? '' ) === '' ) {
+
+ $out['owaVersion'] = '';
+ }
+
+ $problem = self::siteIdProblem( $out );
+
+ if ( $problem ) {
+
+ $errors['siteId'] = $problem;
+ }
+ }
+
+ // the upgrade notice asks for an application password
+ if ( (string) ( $out['appPassword'] ?? '' ) !== '' ) {
+
+ unset( $out['owaUpgradeNotice'] );
+ }
+
if ( $errors ) {
return new \WP_Error( 'owa_wp_invalid', 'The settings were not saved.', [ 'status' => 400, 'errors' => $errors ] );
@@ -249,15 +287,42 @@ public static function sanitizeSettings( array $schema, array $input, array $sto
}
}
- // 2.x loads .js, so the ID has to be a file name OWA can publish
- if ( (string) ( $out['owaVersion'] ?? '1' ) === '2'
+ $problem = self::siteIdProblem( $out );
+
+ if ( $problem ) {
+
+ $errors['siteId'] = $problem;
+ }
+
+ return [ $out, $errors ];
+ }
+
+ /**
+ * Why the stored Website ID cannot be used with the stored version, or ''.
+ * 2.x loads .js, so the ID has to be a file name OWA can publish.
+ *
+ * @param array $out
+ */
+ public static function siteIdProblem( array $out ) {
+
+ if ( (string) ( $out['owaVersion'] ?? '' ) === '2'
&& (string) ( $out['siteId'] ?? '' ) !== ''
&& ! preg_match( \owaWp_plugin::BUNDLE_SITE_ID_PATTERN, (string) $out['siteId'] ) ) {
- $errors['siteId'] = 'OWA 2.x cannot publish a tracking bundle for this Observation Profile.';
+ return 'OWA 2.x cannot publish a tracking bundle for this Observation Profile.';
}
- return [ $out, $errors ];
+ return '';
+ }
+
+ /**
+ * "Check again": checks the saved endpoint's version now.
+ */
+ public static function checkServer( $plugin ) {
+
+ server::check( $plugin );
+
+ return self::settingsPayload( $plugin ) + [ 'checked' => true ];
}
/**
diff --git a/src/server.php b/src/server.php
new file mode 100644
index 0000000..2357ff1
--- /dev/null
+++ b/src/server.php
@@ -0,0 +1,394 @@
+ self::onAdminInit( $plugin ) );
+ add_action( 'admin_notices', fn() => self::showUpgradeNotice( $plugin ) );
+ add_action( 'wp_ajax_' . self::DISMISS_ACTION, fn() => self::dismissUpgradeNotice() );
+ }
+
+ /**
+ * Requests the probe route at an endpoint and reads the answer.
+ *
+ * @return array{version: int, reason: string} version 0 when the server was not identified
+ */
+ public static function probe( $endpoint ) {
+
+ $response = wp_remote_get( trailingslashit( (string) $endpoint ) . self::PROBE_PATH, [
+ 'timeout' => 5,
+ 'headers' => [ 'Authorization' => 'Bearer ' . self::PROBE_TOKEN, 'Accept' => 'application/json' ],
+ ] );
+
+ return self::classify( $response );
+ }
+
+ /**
+ * @param array|\WP_Error $response a wp_remote_get() result
+ * @return array{version: int, reason: string}
+ */
+ public static function classify( $response ) {
+
+ if ( is_wp_error( $response ) ) {
+
+ return [ 'version' => 0, 'reason' => $response->get_error_message() ];
+ }
+
+ $code = (int) wp_remote_retrieve_response_code( $response );
+
+ if ( self::hasBearerChallenge( wp_remote_retrieve_header( $response, 'www-authenticate' ) ) ) {
+
+ return $code === 401
+ ? [ 'version' => 2, 'reason' => '' ]
+ /* translators: %d: an HTTP status code */
+ : [ 'version' => 0, 'reason' => sprintf( __( 'HTTP %d with a Bearer challenge', 'open-web-analytics' ), $code ) ];
+ }
+
+ if ( in_array( $code, [ 200, 401, 403 ], true ) && self::isLegacyEnvelope( (string) wp_remote_retrieve_body( $response ) ) ) {
+
+ return [ 'version' => 1, 'reason' => '' ];
+ }
+
+ return [
+ 'version' => 0,
+ /* translators: %d: an HTTP status code */
+ 'reason' => sprintf( __( 'HTTP %d, not an answer from the OWA REST API', 'open-web-analytics' ), $code ),
+ ];
+ }
+
+ /**
+ * Whether a WWW-Authenticate value (one string, or one per header line)
+ * offers the Bearer scheme.
+ *
+ * @param string|string[] $header
+ */
+ public static function hasBearerChallenge( $header ) {
+
+ foreach ( (array) $header as $value ) {
+
+ if ( preg_match( '/(^|,)\s*Bearer(\s|,|$)/i', (string) $value ) ) {
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Whether a body is OWA 1.x's REST envelope: a JSON object with requestId
+ * and httpResponse.
+ */
+ public static function isLegacyEnvelope( $body ) {
+
+ $json = json_decode( $body, true );
+
+ return is_array( $json ) && array_key_exists( 'requestId', $json ) && array_key_exists( 'httpResponse', $json );
+ }
+
+ /**
+ * The stored settings after a check of $endpoint: the version found, or
+ * the one before when none was found. A server that was 1 and is now 2
+ * flags the upgrade notice, unless an application password is stored.
+ *
+ * @param array $stored the owa_wp option
+ * @param array{version: int, reason: string} $result
+ * @return array
+ */
+ public static function applyResult( array $stored, $endpoint, array $result, $now ) {
+
+ $before = (string) ( $stored['owaVersion'] ?? '' );
+
+ $stored['owaVersionCheck'] = [
+ 'url' => (string) $endpoint,
+ 'version' => (int) $result['version'],
+ 'reason' => (string) $result['reason'],
+ 'at' => (int) $now,
+ ];
+
+ if ( $result['version'] === 0 ) {
+
+ $stored['owaVersion'] = $before;
+
+ return $stored;
+ }
+
+ $stored['owaVersion'] = (string) $result['version'];
+
+ if ( $before === '1' && $result['version'] === 2 && (string) ( $stored['appPassword'] ?? '' ) === '' ) {
+
+ $stored['owaUpgradeNotice'] = 1;
+ }
+
+ if ( $result['version'] === 1 ) {
+
+ unset( $stored['owaUpgradeNotice'] );
+ }
+
+ return $stored;
+ }
+
+ /**
+ * Whether a save of $endpoint should check the server: the endpoint
+ * changed, or the last check of it found no version.
+ *
+ * @param array $stored
+ */
+ public static function needsCheck( array $stored, $endpoint ) {
+
+ if ( (string) $endpoint === '' ) {
+
+ return false;
+ }
+
+ $check = (array) ( $stored['owaVersionCheck'] ?? [] );
+
+ return (string) ( $stored['owaEndpoint'] ?? '' ) !== (string) $endpoint
+ || (string) ( $check['url'] ?? '' ) !== (string) $endpoint
+ || empty( $check['version'] )
+ || (string) ( $stored['owaVersion'] ?? '' ) === '';
+ }
+
+ /**
+ * Checks the stored endpoint now and stores the result. Pages are purged
+ * when the version, and with it the tag, changes.
+ *
+ * @return array{version: int, reason: string}|null null without an endpoint or in network mode
+ */
+ public static function check( $plugin ) {
+
+ $stored = get_option( 'owa_wp' );
+ $stored = is_array( $stored ) ? $stored : [];
+ $endpoint = (string) ( $stored['owaEndpoint'] ?? '' );
+
+ if ( $endpoint === '' || network::isActive() ) {
+
+ return null;
+ }
+
+ $result = self::probe( $endpoint );
+ $after = self::applyResult( $stored + [ 'owaVersion' => self::storedVersion( $stored ) ], $endpoint, $result, time() );
+
+ set_transient( self::TRANSIENT, $endpoint, DAY_IN_SECONDS );
+
+ update_option( 'owa_wp', $after );
+
+ if ( (string) $after['owaVersion'] !== self::storedVersion( $stored ) ) {
+
+ cache::tagChanged();
+ }
+
+ $plugin->reloadOptions();
+
+ return $result;
+ }
+
+ /**
+ * The version an owa_wp option stands for. Before 2.5.0 the version was
+ * chosen by the user and '1' when never saved; an install without the
+ * option has none yet.
+ *
+ * @param array|false $stored
+ */
+ public static function storedVersion( $stored ) {
+
+ if ( ! is_array( $stored ) ) {
+
+ return '';
+ }
+
+ $version = (string) ( $stored['owaVersion'] ?? '1' );
+
+ return in_array( $version, [ '1', '2' ], true ) ? $version : '';
+ }
+
+ /**
+ * Admin page loads: the first after an update of the plugin checks the
+ * server, and keeps the version chosen before when the check finds none.
+ * Later loads check again at most once a day.
+ */
+ public static function onAdminInit( $plugin ) {
+
+ if ( wp_doing_ajax() || ! current_user_can( 'manage_options' ) ) {
+
+ return;
+ }
+
+ if ( get_option( self::VERSION_OPTION ) !== OWA_WP_VERSION ) {
+
+ self::migrate( $plugin );
+
+ return;
+ }
+
+ $endpoint = (string) $plugin->getOption( 'owaEndpoint' );
+
+ if ( $endpoint === '' || network::isActive() || get_transient( self::TRANSIENT ) === $endpoint ) {
+
+ return;
+ }
+
+ self::check( $plugin );
+ }
+
+ /**
+ * Run once per plugin update. The stored owaVersion becomes the version
+ * the server reports; when it reports none, the version stored before
+ * (or '1', the old default) is kept. Without an endpoint there is nothing
+ * to check and no version.
+ */
+ public static function migrate( $plugin ) {
+
+ update_option( self::VERSION_OPTION, OWA_WP_VERSION );
+
+ $stored = get_option( 'owa_wp' );
+
+ if ( ! is_array( $stored ) || network::isActive() ) {
+
+ return;
+ }
+
+ if ( (string) ( $stored['owaEndpoint'] ?? '' ) === '' ) {
+
+ $stored['owaVersion'] = '';
+ update_option( 'owa_wp', $stored );
+ $plugin->reloadOptions();
+
+ return;
+ }
+
+ // the version the user chose is what the check falls back to
+ $stored['owaVersion'] = self::storedVersion( $stored );
+ update_option( 'owa_wp', $stored );
+
+ self::check( $plugin );
+ }
+
+ /**
+ * Whether the upgrade notice applies to this request's screen and user.
+ */
+ public static function upgradeNoticeApplies( $plugin ) {
+
+ if ( empty( $plugin->getOption( 'owaUpgradeNotice' ) ) || network::isActive() || $plugin->getOwaVersion() !== 2 ) {
+
+ return false;
+ }
+
+ if ( ! function_exists( 'current_user_can' ) || ! current_user_can( 'manage_options' ) ) {
+
+ return false;
+ }
+
+ $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
+
+ return $screen && in_array( $screen->id, self::NOTICE_SCREENS, true );
+ }
+
+ public static function upgradeNoticeHtml() {
+
+ return sprintf(
+ /* translators: %s: the URL of the plugin's settings screen */
+ __( 'Your OWA server is now version 2. Add an application password to choose its Observation Profiles. Tracking continues meanwhile.', 'open-web-analytics' ),
+ esc_url( admin_url( 'admin.php?page=' . admin::SLUG ) )
+ );
+ }
+
+ public static function showUpgradeNotice( $plugin ) {
+
+ if ( ! self::upgradeNoticeApplies( $plugin ) ) {
+
+ return;
+ }
+
+ printf(
+ '
%s
',
+ esc_attr( wp_create_nonce( self::DISMISS_ACTION ) ),
+ wp_kses( self::upgradeNoticeHtml(), [ 'a' => [ 'href' => [] ] ] )
+ );
+
+ // the dismiss button only hides the notice; this tells the server too
+ printf(
+ '',
+ wp_json_encode( self::DISMISS_ACTION )
+ );
+ }
+
+ public static function dismissUpgradeNotice() {
+
+ check_ajax_referer( self::DISMISS_ACTION );
+
+ if ( ! current_user_can( 'manage_options' ) ) {
+
+ wp_send_json_error( null, 403 );
+ }
+
+ $stored = get_option( 'owa_wp' );
+
+ if ( is_array( $stored ) ) {
+
+ unset( $stored['owaUpgradeNotice'] );
+ update_option( 'owa_wp', $stored );
+ }
+
+ wp_send_json_success();
+ }
+
+ /**
+ * What the settings page shows about the server.
+ *
+ * @return array{version: string, url: string, identified: bool, reason: string, checkedAt: int, network: bool}
+ */
+ public static function status( $plugin ) {
+
+ $check = (array) ( $plugin->getOption( 'owaVersionCheck' ) ?: [] );
+ $url = (string) $plugin->getOption( 'owaEndpoint' );
+ $current = (string) ( $check['url'] ?? '' ) === $url;
+
+ return [
+ 'version' => $plugin->getOwaVersion() ? (string) $plugin->getOwaVersion() : '',
+ 'url' => $url,
+ // the last check of this endpoint found a version
+ 'identified' => $current && ! empty( $check['version'] ),
+ 'reason' => $current ? (string) ( $check['reason'] ?? '' ) : __( 'not checked yet', 'open-web-analytics' ),
+ 'checkedAt' => $current ? (int) ( $check['at'] ?? 0 ) : 0,
+ 'network' => network::isActive(),
+ ];
+ }
+}
+
+?>
diff --git a/tests/Integration/OwaServerTest.php b/tests/Integration/OwaServerTest.php
index 5da07db..4ef91d0 100644
--- a/tests/Integration/OwaServerTest.php
+++ b/tests/Integration/OwaServerTest.php
@@ -6,16 +6,18 @@
use PHPUnit\Framework\Attributes\Group;
/**
- * The two things the plugin needs from a live OWA server: the tracker served
- * at the path the tag loads, and the signed GET /base/v1/sites behind the
- * Website ID picker.
+ * What the plugin needs from a live OWA 1.x server: the tracker served at the
+ * path the tag loads, the signed GET /base/v1/sites behind the Website ID
+ * picker, and an answer to the version probe that identifies it as 1.x.
*
- * CI installs OWA (a release, or the v2 branch built from source) and sets OWA_URL, OWA_API_KEY, OWA_AUTH_KEY and
+ * CI installs an OWA 1.x release from its tarball and sets OWA_URL, OWA_API_KEY, OWA_AUTH_KEY and
* OWA_SITE_ID; without them these tests are skipped.
*/
#[Group( 'owa1' )]
class OwaServerTest extends TestCase {
+ use RealHttp;
+
protected function setUp(): void {
parent::setUp();
@@ -71,6 +73,13 @@ public function testSitePickerListsTheInstallsSite(): void {
$this->assertStringContainsString( 'wp.example.test', $sites[ getenv( 'OWA_SITE_ID' ) ]['label'] );
}
+ public function testTheServerIdentifiesAs1x(): void {
+
+ $this->realWpRemoteGet();
+
+ $this->assertSame( [ 'version' => 1, 'reason' => '' ], \owaWp\server::probe( getenv( 'OWA_URL' ) ) );
+ }
+
public function testWrongAuthKeyIsReportedUnderThePicker(): void {
$plugin = $this->plugin( [ 'authKey' => 'not-the-auth-key', 'siteId' => 'saved1' ] );
diff --git a/tests/Integration/OwaV2ServerTest.php b/tests/Integration/OwaV2ServerTest.php
index d03ce1a..8498aa2 100644
--- a/tests/Integration/OwaV2ServerTest.php
+++ b/tests/Integration/OwaV2ServerTest.php
@@ -17,6 +17,8 @@
#[Group( 'owa2' )]
class OwaV2ServerTest extends TestCase {
+ use RealHttp;
+
protected function setUp(): void {
parent::setUp();
@@ -101,6 +103,17 @@ public function testAWrongApplicationPasswordIsReportedUnderThePicker(): void {
$this->assertStringStartsWith( 'Could not load the list of Observation Profiles from OWA: ', $plugin->getSitesNotice() );
}
+ /**
+ * OWA 2.x answers the probe's invalid token with 401 and a Bearer
+ * challenge, also where anonymous visitors may list sites.
+ */
+ public function testTheServerIdentifiesAs2x(): void {
+
+ $this->realWpRemoteGet();
+
+ $this->assertSame( [ 'version' => 2, 'reason' => '' ], \owaWp\server::probe( getenv( 'OWA_URL' ) ) );
+ }
+
public function testTheTrackingTagLinkIsARealScreen(): void {
[ $status, $headers ] = self::get( $this->plugin()->getTagSettingsUrl() );
diff --git a/tests/Integration/RealHttp.php b/tests/Integration/RealHttp.php
new file mode 100644
index 0000000..9eb1f0f
--- /dev/null
+++ b/tests/Integration/RealHttp.php
@@ -0,0 +1,53 @@
+alias( function ( $url, $args = [] ) {
+
+ $headers = '';
+
+ foreach ( (array) ( $args['headers'] ?? [] ) as $name => $value ) {
+
+ $headers .= "$name: $value\r\n";
+ }
+
+ $body = @file_get_contents( $url, false, stream_context_create( [ 'http' => [
+ 'ignore_errors' => true,
+ 'header' => $headers,
+ 'timeout' => (float) ( $args['timeout'] ?? 5 ),
+ // as WordPress sends one
+ 'user_agent' => 'WordPress/6.8; https://wp.example.test',
+ ] ] ) );
+
+ if ( $body === false || empty( $http_response_header ) ) {
+
+ return new \WP_Error( 'http_request_failed', "GET $url failed" );
+ }
+
+ preg_match( '#^HTTP/\S+ (\d{3})#', $http_response_header[0], $m );
+ $response_headers = [];
+
+ foreach ( array_slice( $http_response_header, 1 ) as $line ) {
+
+ if ( str_contains( $line, ':' ) ) {
+
+ [ $name, $value ] = explode( ':', $line, 2 );
+ $response_headers[ strtolower( trim( $name ) ) ] = trim( $value );
+ }
+ }
+
+ return [ 'response' => [ 'code' => (int) $m[1] ], 'headers' => $response_headers, 'body' => (string) $body ];
+ } );
+ }
+}
diff --git a/tests/NetworkTest.php b/tests/NetworkTest.php
index 0dcd980..1770855 100644
--- a/tests/NetworkTest.php
+++ b/tests/NetworkTest.php
@@ -211,7 +211,7 @@ public function testTheNetworksFieldsAreMarkedManaged(): void {
$options = ( new \owaWp_plugin() )->registerOptions();
- foreach ( [ 'owaVersion', 'owaEndpoint', 'appPassword', 'apiKey', 'authKey' ] as $key ) {
+ foreach ( [ 'owaEndpoint', 'appPassword', 'apiKey', 'authKey' ] as $key ) {
$this->assertTrue( $options[ $key ]['field']['managed'] ?? false, $key );
$this->assertStringContainsString( 'owa-wp-network-managed', $options[ $key ]['field']['class'], $key );
@@ -323,6 +323,28 @@ public function testInvalidNetworkSettingsStoreNothing(): void {
$this->assertStringStartsWith( 'This looks like a 1.x API key. Network mode needs an OWA 2.x application password', $errors['appPassword'] );
}
+ public function testANetworkEndpointThatIdentifiesAs1xIsRefused(): void {
+
+ $this->stubBlogs();
+ $this->owaServer( self::owa1Answer() );
+
+ [ $saved, $errors ] = network::save( [ 'owaEndpoint' => 'https://owa1.example.com/', 'appPassword' => self::TOKEN ], $this->networkPlugin() );
+
+ $this->assertNull( $saved );
+ $this->assertSame( [], $this->network );
+ $this->assertStringStartsWith( 'This is an OWA 1.x server. Network mode needs OWA 2.x', $errors['owaEndpoint'] );
+ }
+
+ public function testANetworkEndpointThatCannotBeIdentifiedIsSaved(): void {
+
+ $this->stubBlogs();
+ $this->owaServer( new \WP_Error( 'http_request_failed', 'cURL error 28: timed out' ) );
+
+ [ $saved ] = network::save( [ 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN ], $this->networkPlugin() );
+
+ $this->assertSame( 'https://owa.example.com/', $saved['owaEndpoint'] );
+ }
+
public function testTheApplicationPasswordIsKeptUnlessReplacedOrCleared(): void {
$this->stubBlogs();
diff --git a/tests/OwaV2Test.php b/tests/OwaV2Test.php
index 16fc2b1..9428dc4 100644
--- a/tests/OwaV2Test.php
+++ b/tests/OwaV2Test.php
@@ -251,16 +251,74 @@ public function testOnly2xFieldsAreShownIn2x(): void {
}
$this->assertSame(
- [ 'owaVersion', 'enable', 'appPassword', 'owaEndpoint', 'siteId', 'trackNamedUsers', 'excludeLoggedInUsers' ],
- $shown
+ [ 'owaEndpoint', 'appPassword', 'siteId', 'enable', 'trackNamedUsers', 'excludeLoggedInUsers' ],
+ $shown,
+ 'The endpoint first; click tracking and Domstreams are set on the Profile in OWA.'
);
}
- public function testTheSwitchDefaultsTo1x(): void {
+ public function testThereIsNoVersionSwitch(): void {
- $options = $this->makePlugin()->registerOptions();
+ $this->assertArrayNotHasKey( 'owaVersion', $this->makePlugin()->registerOptions() );
+ }
+
+ public function testTheApplicationPasswordLinksToOwasDocumentation(): void {
+
+ $fields = array_column( \owaWp\rest::settingsPayload( $this->v2() )['fields'], null, 'key' );
+
+ $this->assertSame( \owaWp\server::APP_PASSWORDS_URL, $fields['appPassword']['helpUrl'] );
+ $this->assertSame( '', $fields['apiKey']['helpUrl'] );
+ }
+
+ /**
+ * The 2.x tag is OWA's bundle tag, with only the page's own commands in
+ * the queue: the site ID, the Profile's tracker options and features and
+ * the page view come from the bundle.
+ */
+ public function testThe2xTagIsTheBundleTagWithoutWhatTheBundleCarries(): void {
+
+ $this->stubConditionals( [ 'is_single' ] );
+ Functions\when( 'wp_title' )->justReturn( 'Post' );
+
+ $tag = $this->renderTag( $this->v2( [ 'trackClicks' => true, 'trackDomstreams' => true, 'debug' => true, 'trackNamedUsers' => false ] ) );
+
+ $this->assertSame(
+ '' . "\n"
+ . '' . "\n"
+ . "\n"
+ . "\n"
+ . '' . "\n"
+ . "\n",
+ $tag
+ );
+
+ foreach ( [ 'trackClicks', 'trackDomStream', 'trackPageView', 'setSiteId', 'setDebug' ] as $carried ) {
+
+ $this->assertStringNotContainsString( $carried, $tag );
+ }
+ }
+
+ public function testThe1xTagStillCarriesTheTrackingTabsCommands(): void {
+
+ $this->stubConditionals( [ 'is_single' ] );
+ Functions\when( 'wp_title' )->justReturn( 'Post' );
+
+ $plugin = $this->makePlugin( [ 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123', 'trackClicks' => true, 'trackDomstreams' => true ] );
+
+ $this->assertSame(
+ [ 'setSiteId', 'setPageType', 'setPageTitle', 'trackClicks', 'trackDomStream', 'trackPageView' ],
+ array_column( $this->pushedCmds( $this->renderTag( $plugin ) ), 0 )
+ );
+ }
+
+ public function testNoVersionDetectedMeansNoTag(): void {
+
+ $this->stubConditionals( [ 'is_single' ] );
+ Functions\when( 'wp_title' )->justReturn( 'Post' );
- $this->assertSame( '1', $options['owaVersion']['default_value'] );
- $this->assertSame( 1, $this->makePlugin()->getOwaVersion() );
+ $this->assertSame( '', $this->renderTag( $this->v2( [ 'owaVersion' => '' ] ) ), 'Which tag works is not known.' );
}
}
diff --git a/tests/RestTest.php b/tests/RestTest.php
index 6ea24ca..16130c6 100644
--- a/tests/RestTest.php
+++ b/tests/RestTest.php
@@ -150,23 +150,23 @@ public function testFieldsAreStoredByType(): void {
], [] );
$this->assertSame( [], $errors );
- $this->assertSame( [ 'owaVersion' => '2', 'enable' => 0, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'OWA-9b62dc7ce78a6934', 'trackNamedUsers' => 1 ], $out );
+ $this->assertSame( [ 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'OWA-9b62dc7ce78a6934', 'enable' => 0, 'trackNamedUsers' => 1 ], $out,
+ 'owaVersion is detected, never taken from the page.' );
}
public function testEachProblemIsReturnedUnderItsField(): void {
[ , $errors ] = rest::sanitizeSettings( $this->schema(), [
- 'owaVersion' => '3',
'owaEndpoint' => 'ftp://owa.example.com/',
'appPassword' => 'not-a-token',
], [] );
- $this->assertSame( [ 'owaVersion', 'appPassword', 'owaEndpoint' ], array_keys( $errors ) );
+ $this->assertSame( [ 'owaEndpoint', 'appPassword' ], array_keys( $errors ) );
}
public function testA2xWebsiteIdMustBeABundleFileName(): void {
- [ , $errors ] = rest::sanitizeSettings( $this->schema(), [ 'owaVersion' => '2', 'siteId' => '../owa-config' ], [] );
+ [ , $errors ] = rest::sanitizeSettings( $this->schema(), [ 'siteId' => '../owa-config' ], [ 'owaVersion' => '2' ] );
$this->assertSame( 'OWA 2.x cannot publish a tracking bundle for this Observation Profile.', $errors['siteId'] );
}
@@ -201,11 +201,14 @@ public function testAnInvalidSaveStoresNothing(): void {
public function testASaveStoresAndReturnsThePageAgain(): void {
+ $this->owaServer( self::owa2Answer() );
+
$plugin = new \owaWp_plugin();
- $result = rest::saveSettings( $plugin, [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN, 'siteId' => 'OWA-1' ] );
+ $result = rest::saveSettings( $plugin, [ 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN, 'siteId' => 'OWA-1' ] );
$this->assertTrue( $result['saved'] );
+ $this->assertSame( '2', $this->stored['owaVersion'] );
$this->assertSame( self::TOKEN, $this->stored['appPassword'] );
$this->assertSame( 'OWA-1', $result['values']['siteId'], 'The plugin reread its options.' );
$this->assertTrue( $result['secrets']['appPassword'] );
@@ -280,7 +283,6 @@ public function testThePageIsGivenEachFieldsVersionAndTab(): void {
$this->assertSame( '1', $fields['trackClicks']['version'] );
$this->assertNull( $fields['siteId']['version'], 'Both versions.' );
$this->assertSame( 'tracking', $fields['excludeLoggedInUsers']['section'] );
- $this->assertSame( [ [ 'value' => '1', 'label' => '1.x' ], [ 'value' => '2', 'label' => '2.x (beta)' ] ], $fields['owaVersion']['options'] );
$this->assertSame( "Don't Track Logged-in Users", $fields['excludeLoggedInUsers']['title'], 'Entities decoded for the page.' );
}
diff --git a/tests/ServerTest.php b/tests/ServerTest.php
new file mode 100644
index 0000000..c136d74
--- /dev/null
+++ b/tests/ServerTest.php
@@ -0,0 +1,463 @@
+options = [];
+ $this->transients = [];
+
+ Functions\when( 'get_option' )->alias( fn( $name, $default = false ) => $this->options[ $name ] ?? $default );
+ Functions\when( 'update_option' )->alias( function ( $name, $value ) { $this->options[ $name ] = $value; return true; } );
+ Functions\when( 'get_transient' )->alias( fn( $name ) => $this->transients[ $name ] ?? false );
+ Functions\when( 'set_transient' )->alias( function ( $name, $value ) { $this->transients[ $name ] = $value; return true; } );
+ Functions\when( 'current_user_can' )->justReturn( true );
+ Functions\when( 'admin_url' )->alias( fn( $path ) => 'https://wp.test/wp-admin/' . $path );
+ }
+
+ private function plugin(): \owaWp_plugin {
+
+ $plugin = new \owaWp_plugin();
+ $plugin->reloadOptions();
+
+ return $plugin;
+ }
+
+ // ---- the probe ------------------------------------------------------------
+
+ public function testOwa2IsA401WithABearerChallenge(): void {
+
+ $this->assertSame( [ 'version' => 2, 'reason' => '' ], server::classify( self::owa2Answer() ) );
+ }
+
+ public function testOwa1IsItsEnvelopeWithoutAChallenge(): void {
+
+ $this->assertSame( 1, server::classify( self::owa1Answer( 401 ) )['version'], 'Anonymous visitors may not list sites.' );
+ $this->assertSame( 1, server::classify( self::owa1Answer( 403 ) )['version'] );
+ $this->assertSame( 1, server::classify( self::owa1Answer( 200 ) )['version'], 'A public install lists them.' );
+ }
+
+ public function testANetworkErrorIdentifiesNothing(): void {
+
+ $this->assertSame(
+ [ 'version' => 0, 'reason' => 'cURL error 6: Could not resolve host: owa.example.com' ],
+ server::classify( new \WP_Error( 'http_request_failed', 'cURL error 6: Could not resolve host: owa.example.com' ) )
+ );
+ }
+
+ public function testAnHtml404IdentifiesNothing(): void {
+
+ $this->assertSame(
+ [ 'version' => 0, 'reason' => 'HTTP 404, not an answer from the OWA REST API' ],
+ server::classify( self::probeResponse( 404, [ 'content-type' => 'text/html' ], 'Not Found' ) )
+ );
+ }
+
+ public function testOtherAnswersIdentifyNothing(): void {
+
+ $this->assertSame( 0, server::classify( self::probeResponse( 200, [ 'www-authenticate' => 'Bearer realm="OWA"' ], '{}' ) )['version'], 'A challenge without the 401.' );
+ $this->assertSame( 0, server::classify( self::probeResponse( 401, [ 'www-authenticate' => 'Basic realm="staging"' ], '401' ) )['version'], 'A proxy\'s login.' );
+ $this->assertSame( 0, server::classify( self::probeResponse( 404, [], '{"requestId":"1","httpResponse":{"status_code":404}}' ) )['version'], 'The route is missing.' );
+ $this->assertSame( 0, server::classify( self::probeResponse( 200, [], '{"data":[]}' ) )['version'], 'Some other JSON.' );
+ $this->assertSame( 0, server::classify( self::probeResponse( 200, [], '' ) )['version'] );
+ }
+
+ public function testTheBearerSchemeIsFoundAmongOthers(): void {
+
+ $this->assertTrue( server::hasBearerChallenge( 'Basic realm="x", Bearer realm="OWA"' ) );
+ $this->assertTrue( server::hasBearerChallenge( [ 'Basic realm="x"', 'bearer realm="OWA"' ] ), 'One header line each.' );
+ $this->assertFalse( server::hasBearerChallenge( 'BearerToken realm="x"' ) );
+ $this->assertFalse( server::hasBearerChallenge( '' ) );
+ }
+
+ public function testTheProbeSendsOnlyTheInvalidToken(): void {
+
+ $requests = $this->owaServer( self::owa2Answer() );
+
+ $this->assertSame( 2, server::probe( 'http://owa.example.com:8080/owa' )['version'] );
+
+ [ $url, $args ] = $requests[0];
+
+ $this->assertSame( 'http://owa.example.com:8080/owa/api/index.php?owa_rest_params=base/v1/sites', $url, 'The stored scheme, unchanged.' );
+ $this->assertSame( 'Bearer owa-version-probe', $args['headers']['Authorization'] );
+ $this->assertArrayNotHasKey( 'X-API-KEY', $args['headers'] );
+ $this->assertArrayNotHasKey( 'X-SIGNATURE', $args['headers'] );
+ }
+
+ // ---- the stored version -----------------------------------------------------
+
+ public function testAFreshInstallHasNoVersionAndALegacyOneIs1(): void {
+
+ $this->assertSame( '', server::storedVersion( false ), 'Never saved.' );
+ $this->assertSame( '1', server::storedVersion( [ 'owaEndpoint' => 'https://owa.example.com/' ] ), 'Saved before 2.5.0 without choosing: the old default.' );
+ $this->assertSame( '2', server::storedVersion( [ 'owaVersion' => '2' ] ) );
+ $this->assertSame( '', server::storedVersion( [ 'owaVersion' => '' ] ) );
+
+ $this->assertSame( 0, $this->plugin()->getOwaVersion() );
+ }
+
+ public function testACheckThatFindsNothingKeepsTheVersionBefore(): void {
+
+ $stored = server::applyResult( [ 'owaVersion' => '2' ], 'https://owa.example.com/', [ 'version' => 0, 'reason' => 'HTTP 502, not an answer from the OWA REST API' ], 1700000000 );
+
+ $this->assertSame( '2', $stored['owaVersion'] );
+ $this->assertSame( [ 'url' => 'https://owa.example.com/', 'version' => 0, 'reason' => 'HTTP 502, not an answer from the OWA REST API', 'at' => 1700000000 ], $stored['owaVersionCheck'] );
+ }
+
+ public function testA1xServerThatBecomes2xFlagsTheNotice(): void {
+
+ $stored = server::applyResult( [ 'owaVersion' => '1', 'apiKey' => 'k', 'authKey' => 'a' ], 'https://owa.example.com/', [ 'version' => 2, 'reason' => '' ], 1 );
+
+ $this->assertSame( '2', $stored['owaVersion'] );
+ $this->assertSame( 1, $stored['owaUpgradeNotice'] );
+ $this->assertSame( [ 'k', 'a' ], [ $stored['apiKey'], $stored['authKey'] ], 'The 1.x keys are kept.' );
+
+ $with_password = server::applyResult( [ 'owaVersion' => '1', 'appPassword' => self::TOKEN ], 'https://owa.example.com/', [ 'version' => 2, 'reason' => '' ], 1 );
+ $this->assertArrayNotHasKey( 'owaUpgradeNotice', $with_password, 'Nothing to add.' );
+
+ $fresh = server::applyResult( [ 'owaVersion' => '' ], 'https://owa.example.com/', [ 'version' => 2, 'reason' => '' ], 1 );
+ $this->assertArrayNotHasKey( 'owaUpgradeNotice', $fresh, 'Not an upgrade.' );
+
+ $back = server::applyResult( $stored, 'https://owa1.example.com/', [ 'version' => 1, 'reason' => '' ], 1 );
+ $this->assertArrayNotHasKey( 'owaUpgradeNotice', $back );
+ }
+
+ public function testASaveChecksANewEndpointOrOneNotIdentified(): void {
+
+ $identified = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 1 ] ];
+
+ $this->assertFalse( server::needsCheck( $identified, 'https://owa.example.com/' ) );
+ $this->assertTrue( server::needsCheck( $identified, 'https://other.example.com/' ) );
+ $this->assertTrue( server::needsCheck( [ 'owaVersionCheck' => [ 'version' => 0 ] ] + $identified, 'https://owa.example.com/' ) );
+ $this->assertTrue( server::needsCheck( [ 'owaEndpoint' => 'https://owa.example.com/' ], 'https://owa.example.com/' ), 'Never checked.' );
+ $this->assertFalse( server::needsCheck( $identified, '' ) );
+ }
+
+ // ---- saving the endpoint ------------------------------------------------------
+
+ public function testSavingTheEndpointStoresTheVersionFound(): void {
+
+ $this->owaServer( self::owa2Answer() );
+
+ $result = rest::saveSettings( $this->plugin(), [ 'owaEndpoint' => 'https://owa.example.com/' ] );
+
+ $this->assertSame( '2', $this->options['owa_wp']['owaVersion'] );
+ $this->assertSame( '2', $result['server']['version'] );
+ $this->assertTrue( $result['server']['identified'] );
+ $this->assertSame( 'https://owa.example.com/', $this->transients[ server::TRANSIENT ], 'Not checked again today.' );
+ }
+
+ public function testSavingAnEndpointThatIsNotIdentifiedShowsOnlyTheEndpoint(): void {
+
+ $this->owaServer( self::probeResponse( 404, [], '' ) );
+
+ $result = rest::saveSettings( $this->plugin(), [ 'owaEndpoint' => 'https://owa.example.com/' ] );
+
+ $this->assertTrue( $result['saved'] );
+ $this->assertSame( '', $this->options['owa_wp']['owaVersion'] );
+ $this->assertSame( [ 'version' => '', 'url' => 'https://owa.example.com/', 'identified' => false, 'reason' => 'HTTP 404, not an answer from the OWA REST API', 'checkedAt' => $result['server']['checkedAt'], 'network' => false ], $result['server'] );
+ $this->assertSame( [], $result['notices'], 'The server status says it.' );
+ }
+
+ public function testAnUnchangedIdentifiedEndpointIsNotCheckedOnSave(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 1, 'reason' => '', 'at' => 1 ] ];
+ $requests = $this->owaServer( self::owa2Answer() );
+
+ rest::saveSettings( $this->plugin(), [ 'owaEndpoint' => 'https://owa.example.com/', 'trackClicks' => false ] );
+
+ $this->assertCount( 0, $requests );
+ $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] );
+ }
+
+ public function testTheVersionCannotBeSetFromThePage(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 1, 'reason' => '', 'at' => 1 ] ];
+
+ rest::saveSettings( $this->plugin(), [ 'owaVersion' => '2' ] );
+
+ $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] );
+ }
+
+ public function testSavingAnApplicationPasswordEndsTheUpgradeNotice(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaUpgradeNotice' => 1, 'owaEndpoint' => 'https://owa.example.com/', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 2, 'reason' => '', 'at' => 1 ] ];
+
+ rest::saveSettings( $this->plugin(), [ 'appPassword' => self::TOKEN ] );
+
+ $this->assertArrayNotHasKey( 'owaUpgradeNotice', $this->options['owa_wp'] );
+ }
+
+ // ---- what each version's page shows ---------------------------------------------
+
+ public function testEachVersionIsGivenItsOwnSetupNotices(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/' ];
+ $this->assertSame( [ 'Enter your OWA Endpoint and an Application Password to load the list of Observation Profiles from OWA.' ], rest::settingsPayload( $this->plugin() )['notices'] );
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/' ];
+ $this->assertSame( [ 'Enter your OWA Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ], rest::settingsPayload( $this->plugin() )['notices'] );
+ }
+
+ public function testOnTheDashboardAnUnidentifiedServerIsSaidSo(): void {
+
+ $this->assertSame( [ 'Enter the URL of your OWA server as the OWA Endpoint under OWA > Settings.' ], $this->makePlugin( [ 'owaVersion' => '' ] )->setupNotices() );
+ $this->assertSame( [ 'No OWA server could be identified at https://owa.example.com/. Check the OWA Endpoint under OWA > Settings.' ],
+ $this->makePlugin( [ 'owaVersion' => '', 'owaEndpoint' => 'https://owa.example.com/' ] )->setupNotices() );
+ }
+
+ public function testThePageSaysWhenTheVersionShownWasFoundBefore(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 0, 'reason' => 'cURL error 28: timed out', 'at' => 5 ] ];
+
+ $server = rest::settingsPayload( $this->plugin() )['server'];
+
+ $this->assertSame( [ '1', false, 'cURL error 28: timed out', 5 ], [ $server['version'], $server['identified'], $server['reason'], $server['checkedAt'] ] );
+ }
+
+ // ---- checking again ---------------------------------------------------------------
+
+ public function testCheckAgainChecksNowAndPurgesWhenTheTagChanges(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123', 'apiKey' => 'k', 'authKey' => 'a' ];
+ $this->transients[ server::TRANSIENT ] = 'https://owa.example.com/';
+ $this->owaServer( self::owa2Answer() );
+
+ Actions\expectDone( \owaWp\cache::TAG_CHANGED )->once();
+
+ $result = rest::checkServer( $this->plugin() );
+
+ $this->assertTrue( $result['checked'] );
+ $this->assertSame( '2', $result['server']['version'] );
+ $this->assertSame( 'k', $this->options['owa_wp']['apiKey'], 'The 1.x key is not deleted.' );
+ }
+
+ public function testTheCheckRouteNeedsManageOptions(): void {
+
+ $routes = [];
+
+ Functions\when( 'register_rest_route' )->alias( function ( $namespace, $route, $handlers ) use ( &$routes ) {
+ foreach ( $handlers as $handler ) {
+ $routes[ $handler['methods'] . ' ' . $route ] = $handler['permission_callback'];
+ }
+ } );
+
+ rest::registerRoutes( new \owaWp_plugin() );
+
+ Functions\when( 'current_user_can' )->alias( fn( $capability ) => $capability === 'manage_options' );
+ $this->assertTrue( $routes['POST /server']() );
+
+ Functions\when( 'current_user_can' )->justReturn( false );
+ $this->assertFalse( $routes['POST /server']() );
+ }
+
+ public function testAdminPagesCheckAtMostOnceADay(): void {
+
+ $this->options[ server::VERSION_OPTION ] = OWA_WP_VERSION;
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/' ];
+ $requests = $this->owaServer( self::owa1Answer() );
+
+ $plugin = $this->plugin();
+
+ server::onAdminInit( $plugin );
+ server::onAdminInit( $plugin );
+
+ $this->assertCount( 1, $requests );
+ $this->assertSame( 1, $this->options['owa_wp']['owaVersionCheck']['version'] );
+ }
+
+ public function testOnlyAdministratorsPageLoadsCheck(): void {
+
+ $this->options[ server::VERSION_OPTION ] = OWA_WP_VERSION;
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/' ];
+ $requests = $this->owaServer( self::owa1Answer() );
+
+ Functions\when( 'current_user_can' )->justReturn( false );
+ server::onAdminInit( $this->plugin() );
+
+ Functions\when( 'current_user_can' )->justReturn( true );
+ Functions\when( 'wp_doing_ajax' )->justReturn( true );
+ server::onAdminInit( $this->plugin() );
+
+ $this->assertCount( 0, $requests );
+ }
+
+ public function testNetworkModeIsNeverChecked(): void {
+
+ Functions\when( 'is_multisite' )->justReturn( true );
+ Functions\when( 'get_site_option' )->justReturn( [ 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN ] );
+ $this->options[ server::VERSION_OPTION ] = OWA_WP_VERSION;
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://own.example.com/' ];
+ $requests = $this->owaServer( self::owa1Answer() );
+
+ $plugin = $this->plugin();
+ server::onAdminInit( $plugin );
+
+ $this->assertCount( 0, $requests );
+ $this->assertSame( 2, $plugin->getOwaVersion(), 'The network\'s server is 2.x.' );
+ }
+
+ // ---- updating from 2.4 --------------------------------------------------------------
+
+ public function testAnUpdateReplacesTheChosenVersionWithTheDetectedOne(): void {
+
+ // left on 1 (never saved) against a 2.x server: its site list was broken
+ $this->options['owa_wp'] = [ 'owaEndpoint' => 'https://owa.example.com/', 'apiKey' => 'k', 'authKey' => 'a', 'siteId' => 'abc123' ];
+ $this->owaServer( self::owa2Answer() );
+
+ $plugin = $this->plugin();
+ $this->assertSame( 1, $plugin->getOwaVersion(), 'Until an administrator loads a page, the tag stays as it was.' );
+
+ server::onAdminInit( $plugin );
+
+ $this->assertSame( OWA_WP_VERSION, $this->options[ server::VERSION_OPTION ] );
+ $this->assertSame( '2', $this->options['owa_wp']['owaVersion'] );
+ $this->assertSame( 1, $this->options['owa_wp']['owaUpgradeNotice'] );
+ $this->assertSame( 2, $plugin->getOwaVersion() );
+ }
+
+ public function testAnUpdateKeepsTheChosenVersionWhenTheServerIsNotIdentified(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN ];
+ $this->owaServer( new \WP_Error( 'http_request_failed', 'cURL error 7: Failed to connect' ) );
+
+ server::onAdminInit( $this->plugin() );
+
+ $this->assertSame( '2', $this->options['owa_wp']['owaVersion'] );
+ $this->assertSame( 0, $this->options['owa_wp']['owaVersionCheck']['version'] );
+
+ // never chosen: the old default
+ unset( $this->options[ server::VERSION_OPTION ] );
+ $this->options['owa_wp'] = [ 'owaEndpoint' => 'https://owa.example.com/' ];
+
+ server::onAdminInit( $this->plugin() );
+
+ $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] );
+ }
+
+ public function testAnUpdateWithoutAnEndpointLeavesNoVersion(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '1', 'enable' => 1 ];
+ $requests = $this->owaServer( self::owa1Answer() );
+
+ server::onAdminInit( $this->plugin() );
+
+ $this->assertCount( 0, $requests );
+ $this->assertSame( '', $this->options['owa_wp']['owaVersion'] );
+ }
+
+ public function testAFreshInstallRecordsTheUpdateAndChecksNothing(): void {
+
+ $requests = $this->owaServer( self::owa2Answer() );
+
+ server::onAdminInit( $this->plugin() );
+
+ $this->assertCount( 0, $requests );
+ $this->assertSame( OWA_WP_VERSION, $this->options[ server::VERSION_OPTION ] );
+ $this->assertArrayNotHasKey( 'owa_wp', $this->options );
+ }
+
+ public function testTheHeaderVersionIsTheOneTheMigrationRecords(): void {
+
+ preg_match( '/^Version:\s*(\S+)$/m', file_get_contents( dirname( __DIR__ ) . '/owa-plugin.php' ), $m );
+
+ $this->assertSame( $m[1], OWA_WP_VERSION );
+ }
+
+ // ---- the upgrade notice ---------------------------------------------------------------
+
+ private function noticeOn( string $screen ): string {
+
+ Functions\when( 'get_current_screen' )->justReturn( (object) [ 'id' => $screen ] );
+ Functions\when( 'wp_create_nonce' )->justReturn( 'n0nce' );
+
+ ob_start();
+ server::showUpgradeNotice( $this->plugin() );
+
+ return ob_get_clean();
+ }
+
+ public function testTheUpgradeNoticeShowsOnTheDashboardPluginsAndSettings(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaUpgradeNotice' => 1, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123' ];
+
+ foreach ( [ 'dashboard', 'plugins', 'toplevel_page_owa-wordpress' ] as $screen ) {
+
+ $html = $this->noticeOn( $screen );
+
+ $this->assertStringContainsString( 'class="notice notice-warning is-dismissible owa-wp-server-notice"', $html, $screen );
+ $this->assertStringContainsString( 'Your OWA server is now version 2. Add an application password', $html, $screen );
+ }
+
+ $this->assertSame( '', $this->noticeOn( 'edit-post' ) );
+
+ Functions\when( 'current_user_can' )->justReturn( false );
+ $this->assertSame( '', $this->noticeOn( 'dashboard' ), 'Only for those who can add one.' );
+ }
+
+ public function testWithoutTheFlagThereIsNoUpgradeNotice(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/' ];
+
+ $this->assertSame( '', $this->noticeOn( 'dashboard' ) );
+ }
+
+ public function testTheUpgradeNoticeReplacesTheSetupNoticeOnTheDashboard(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaUpgradeNotice' => 1, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123' ];
+ Functions\when( 'get_current_screen' )->justReturn( (object) [ 'id' => 'dashboard' ] );
+
+ ob_start();
+ $this->plugin()->showNag();
+
+ $this->assertSame( '', ob_get_clean() );
+ }
+
+ public function testDismissingTheUpgradeNoticeClearsIt(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaUpgradeNotice' => 1 ];
+
+ Functions\expect( 'check_ajax_referer' )->once()->with( server::DISMISS_ACTION );
+ Functions\expect( 'wp_send_json_success' )->once();
+
+ server::dismissUpgradeNotice();
+
+ $this->assertSame( [ 'owaVersion' => '2' ], $this->options['owa_wp'] );
+ }
+
+ public function testOnlyAdministratorsCanDismissIt(): void {
+
+ $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaUpgradeNotice' => 1 ];
+
+ Functions\when( 'check_ajax_referer' )->justReturn( 1 );
+ Functions\when( 'current_user_can' )->justReturn( false );
+ Functions\expect( 'wp_send_json_error' )->once()->andReturnUsing( function () { throw new \RuntimeException( 'sent' ); } );
+
+ try {
+
+ server::dismissUpgradeNotice();
+
+ } catch ( \RuntimeException $e ) {}
+
+ $this->assertSame( 1, $this->options['owa_wp']['owaUpgradeNotice'] );
+ }
+}
diff --git a/tests/TestCase.php b/tests/TestCase.php
index f3d6c13..63d4d3b 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -40,6 +40,12 @@ protected function setUp(): void {
'wp_remote_get' => fn() => [ 'response' => [ 'code' => 200 ] ],
'is_wp_error' => fn( $thing ) => $thing instanceof \WP_Error,
'wp_remote_retrieve_response_code' => fn( $response ) => $response['response']['code'] ?? '',
+ 'wp_remote_retrieve_header' => fn( $response, $name ) => $response['headers'][ $name ] ?? '',
+ 'wp_remote_retrieve_body' => fn( $response ) => $response['body'] ?? '',
+ 'trailingslashit' => fn( $text ) => rtrim( $text, '/' ) . '/',
+ 'wp_doing_ajax' => false,
+ 'get_transient' => false,
+ 'set_transient' => true,
] );
require_once dirname( __DIR__ ) . '/owa-plugin.php';
@@ -53,10 +59,13 @@ protected function tearDown(): void {
/**
* A plugin instance with the given options set, as initOptions() would
- * leave them after reading the owa_wp option.
+ * leave them after reading the owa_wp option. The server is 1.x unless
+ * owaVersion says otherwise ('' for none detected).
*/
protected function makePlugin( array $options = [] ): \owaWp_plugin {
+ $options += [ 'owaVersion' => '1' ];
+
$plugin = new \owaWp_plugin();
foreach ( $options as $key => $value ) {
@@ -67,6 +76,48 @@ protected function makePlugin( array $options = [] ): \owaWp_plugin {
return $plugin;
}
+ /**
+ * A wp_remote_get() result for the version probe.
+ *
+ * @param array $headers
+ */
+ protected static function probeResponse( int $code, array $headers = [], string $body = '' ): array {
+
+ return [ 'response' => [ 'code' => $code ], 'headers' => $headers, 'body' => $body ];
+ }
+
+ /** What OWA 2.x answers the probe. */
+ protected static function owa2Answer(): array {
+
+ return self::probeResponse( 401, [ 'www-authenticate' => 'Bearer realm="OWA"' ],
+ '{"requestId":"1","httpResponse":{"status_code":401},"error":[{"headline":"Not authenticated."}],"data":null}' );
+ }
+
+ /** What OWA 1.x answers the probe when anonymous visitors may not list sites. */
+ protected static function owa1Answer( int $code = 401 ): array {
+
+ return self::probeResponse( $code, [],
+ $code === 200
+ ? '{"requestId":"1","httpResponse":{"status_code":200},"error":[],"data":{"abc123":{"site_id":"abc123","domain":"https://wp.example.test"}}}'
+ : '{"requestId":"1","httpResponse":{"status_code":' . $code . '},"error":[{"headline":"Not authenticated."}],"data":null}' );
+ }
+
+ /**
+ * OWA at every endpoint (its tracker loads), answering the version probe
+ * with $probe. Returns the requests made: [url, args].
+ */
+ protected function owaServer( array|\WP_Error $probe ): \ArrayObject {
+
+ $requests = new \ArrayObject();
+
+ Functions\when( 'wp_remote_get' )->alias( function ( $url, $args = [] ) use ( $probe, $requests ) {
+ $requests[] = [ $url, $args ];
+ return str_contains( $url, \owaWp\server::PROBE_PATH ) ? $probe : [ 'response' => [ 'code' => 200 ] ];
+ } );
+
+ return $requests;
+ }
+
/**
* Every WordPress conditional getPageType() asks, false unless named.
*/
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index dc84f8a..2a2bc6c 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -6,5 +6,6 @@
define( 'WPINC', 'wp-includes' );
define( 'ABSPATH', '/tmp/wordpress/' );
+define( 'DAY_IN_SECONDS', 86400 );
require_once __DIR__ . '/stubs.php';
diff --git a/tests/e2e/single.spec.js b/tests/e2e/single.spec.js
index 429abf5..e18f2c9 100644
--- a/tests/e2e/single.spec.js
+++ b/tests/e2e/single.spec.js
@@ -1,9 +1,10 @@
-// A single-site WordPress: the 1.x / 2.x switch, 2.x settings with an
-// application password, and the bundle tag on a public page.
+// A single-site WordPress: setup starts with the OWA server's URL, the
+// version found there decides which settings show (2.x here: an application
+// password), and public pages get the 2.x bundle tag.
const { test, expect } = require( '@playwright/test' );
const { env, docShot, login, notice, shot } = require( './helpers' );
-test( 'switching to 2.x shows its fields, saves, and tags pages with the bundle', async ( { page, browser }, testInfo ) => {
+test( 'the URL comes first, 2.x is detected, its fields save, and pages get the bundle', async ( { page, browser }, testInfo ) => {
const siteId = env( 'OWA_SITE_ID' );
const save = page.getByRole( 'button', { name: 'Save Changes' } );
@@ -13,45 +14,51 @@ test( 'switching to 2.x shows its fields, saves, and tags pages with the bundle'
await login( page );
await page.goto( '/wp-admin/admin.php?page=owa-wordpress' );
- // 1.x is the default
- await expect( field( '1.x' ) ).toBeChecked();
- await expect( field( 'API Key' ) ).toBeVisible();
- await expect( field( 'Application Password' ) ).toHaveCount( 0 );
- // no picker until OWA accepts the credentials, and so no request to choose from it
- await expect( field( 'Website ID' ) ).toHaveCount( 0 );
- // what is left to set up, worded for 1.x, shown by the page and not again by WordPress
- await expect( notice( page, 'Enter your OWA Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ) ).toBeVisible();
- await expect( notice( page, 'before tracking can begin' ) ).toHaveCount( 0 );
+ // a fresh install knows no version: only the URL is asked for, and no version switch exists
+ await expect( field( 'OWA Endpoint' ) ).toBeVisible();
+ await expect( page.getByText( 'Enter the URL of your OWA server and save.' ) ).toBeVisible();
+ for ( const label of [ 'API Key', 'Secret Auth Key', 'Application Password', 'Enable OWA', '1.x', '2.x (beta)' ] ) {
+ await expect( field( label ) ).toHaveCount( 0 );
+ }
+ await expect( tab( 'Tracking' ) ).toHaveCount( 0 );
+ await expect( tab( 'Advanced' ) ).toHaveCount( 0 );
await expect( page.locator( 'div.notice-warning' ) ).toHaveCount( 0 );
- await shot( page, testInfo, '01-settings-1x' );
+ await shot( page, testInfo, '01-settings-url-first' );
await docShot( page, 1 );
- await tab( 'Tracking' ).click();
- await expect( field( 'Track Clicks' ) ).toBeVisible();
- await expect( field( "Don't Track Logged-in Users" ) ).toBeChecked();
- await shot( page, testInfo, '02-tracking-tab-1x' );
- await tab( 'General' ).click();
+ // the endpoint without its scheme or slash: OWA is found over http://, and identified as 2.x
+ const bare = env( 'OWA_URL' ).replace( /^https?:\/\//, '' ).replace( /\/$/, '' );
+ await field( 'OWA Endpoint' ).fill( bare );
+ await save.click();
+ await expect( notice( page, 'Settings saved.' ) ).toBeVisible();
+ await expect( field( 'OWA Endpoint' ) ).toHaveValue( env( 'OWA_URL' ) );
+ await expect( page.getByText( 'This is an OWA 2.x server.' ) ).toBeVisible();
- // flip the switch: 2.x fields in, 1.x fields and the empty Advanced tab out
- await field( '2.x (beta)' ).check();
- await expect( field( 'API Key' ) ).toHaveCount( 0 );
+ // 2.x's fields only
await expect( field( 'Application Password' ) ).toBeVisible();
+ await expect( page.getByRole( 'link', { name: /How to create an application password/ } ) ).toHaveAttribute( 'href', /wiki\/v2-Application-Passwords$/ );
+ await expect( field( 'API Key' ) ).toHaveCount( 0 );
+ await expect( field( 'Secret Auth Key' ) ).toHaveCount( 0 );
await expect( tab( 'Advanced' ) ).toHaveCount( 0 );
await expect( field( 'Observation Profile' ) ).toHaveCount( 0 );
- // the notices switch to 2.x wording with it
await expect( notice( page, 'Enter your OWA Endpoint and an Application Password to load the list of Observation Profiles from OWA.' ) ).toBeVisible();
- await expect( notice( page, 'API Key and Secret Auth Key' ) ).toHaveCount( 0 );
- await shot( page, testInfo, '03-switched-to-2x' );
+ await shot( page, testInfo, '02-detected-2x' );
+ // the Tracking tab stays, without the options OWA sets on the Profile
await tab( 'Tracking' ).click();
await expect( field( 'Track Clicks' ) ).toHaveCount( 0 );
+ await expect( field( 'Track Domstreams' ) ).toHaveCount( 0 );
await expect( field( 'Track Named Users' ) ).toBeVisible();
- await expect( field( "Don't Track Logged-in Users" ) ).toBeVisible();
- await shot( page, testInfo, '04-tracking-tab-2x' );
+ await expect( field( "Don't Track Logged-in Users" ) ).toBeChecked();
+ await shot( page, testInfo, '03-tracking-tab-2x' );
await tab( 'General' ).click();
+ // checking again asks the server again and finds the same
+ await page.getByRole( 'button', { name: 'Check again' } ).click();
+ await expect( page.getByText( 'This is an OWA 2.x server.' ) ).toBeVisible();
+ await expect( field( 'Application Password' ) ).toBeVisible();
+
// a 1.x key in the password field is refused, and nothing is saved
- await field( 'OWA Endpoint' ).fill( env( 'OWA_URL' ) );
await field( 'Application Password' ).fill( '0123456789abcdef0123456789abcdef' );
await save.click();
await expect( page.getByText( 'This looks like a 1.x API key.' ) ).toBeVisible();
@@ -65,13 +72,10 @@ test( 'switching to 2.x shows its fields, saves, and tags pages with the bundle'
await expect( page.getByText( 'Could not load the list of Observation Profiles from OWA' ) ).toBeVisible();
await expect( field( 'Observation Profile' ) ).toHaveCount( 0 );
- // the endpoint without its scheme or slash: OWA is found over http:// and that is stored
- const bare = env( 'OWA_URL' ).replace( /^https?:\/\//, '' ).replace( /\/$/, '' );
- await field( 'OWA Endpoint' ).fill( bare );
+ // the password OWA minted
await field( 'Application Password' ).fill( env( 'OWA_APP_PASSWORD' ) );
await save.click();
await expect( notice( page, 'Settings saved.' ) ).toBeVisible();
- await expect( field( 'OWA Endpoint' ) ).toHaveValue( env( 'OWA_URL' ) );
await expect( page.getByText( 'Saved. Enter a new one to replace it.' ) ).toBeVisible();
// saved credentials: that notice goes without a reload; choosing an Observation Profile is left
await expect( notice( page, 'to load the list of Observation Profiles from OWA' ) ).toHaveCount( 0 );
diff --git a/tests/js/fields.test.js b/tests/js/fields.test.js
index 4a7385d..1904221 100644
--- a/tests/js/fields.test.js
+++ b/tests/js/fields.test.js
@@ -1,25 +1,37 @@
import { test, expect } from 'vitest';
-import { fieldText, isVisible, setupNotices, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../../js/lib/fields';
+import { fieldText, isVisible, serverState, setupNotices, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../../js/lib/fields';
const FIELDS = [
- { key: 'owaVersion', section: 'general', version: null },
- { key: 'apiKey', section: 'general', version: '1' },
- { key: 'appPassword', section: 'general', version: '2' },
- { key: 'owaEndpoint', section: 'general', version: null },
- { key: 'siteId', section: 'general', version: null },
- { key: 'trackClicks', section: 'tracking', version: '1' },
- { key: 'trackNamedUsers', section: 'tracking', version: null },
- { key: 'debug', section: 'advanced', version: '1' },
+ { key: 'owaEndpoint', type: 'url', section: 'general', version: null },
+ { key: 'apiKey', type: 'secret', section: 'general', version: '1' },
+ { key: 'authKey', type: 'secret', section: 'general', version: '1' },
+ { key: 'appPassword', type: 'app_password', section: 'general', version: '2' },
+ { key: 'siteId', type: 'select', section: 'general', version: null },
+ { key: 'enable', type: 'boolean', section: 'general', version: null },
+ { key: 'trackClicks', type: 'boolean', section: 'tracking', version: '1' },
+ { key: 'trackDomstreams', type: 'boolean', section: 'tracking', version: '1' },
+ { key: 'trackNamedUsers', type: 'boolean', section: 'tracking', version: null },
+ { key: 'excludeLoggedInUsers', type: 'boolean', section: 'tracking', version: null },
+ { key: 'debug', type: 'boolean', section: 'advanced', version: '1' },
];
const SECTIONS = [ { name: 'general' }, { name: 'tracking' }, { name: 'advanced' } ];
const keys = ( fields ) => fields.map( ( field ) => field.key );
-test( 'each version shows its own fields and those of both', () => {
- expect( keys( visibleFields( FIELDS, '1', 'general' ) ) ).toEqual( [ 'owaVersion', 'apiKey', 'owaEndpoint', 'siteId' ] );
- expect( keys( visibleFields( FIELDS, '2', 'general' ) ) ).toEqual( [ 'owaVersion', 'appPassword', 'owaEndpoint', 'siteId' ] );
- expect( keys( visibleFields( FIELDS, '2', 'tracking' ) ) ).toEqual( [ 'trackNamedUsers' ] );
+test( 'each detected version shows its own fields and those of both, never the other\'s', () => {
+ expect( keys( visibleFields( FIELDS, '1', 'general' ) ) ).toEqual( [ 'owaEndpoint', 'apiKey', 'authKey', 'siteId', 'enable' ] );
+ expect( keys( visibleFields( FIELDS, '2', 'general' ) ) ).toEqual( [ 'owaEndpoint', 'appPassword', 'siteId', 'enable' ] );
+} );
+
+test( 'the Tracking tab: all of it on 1.x; on 2.x without clicks and Domstreams, which OWA sets per Profile', () => {
+ expect( keys( visibleFields( FIELDS, '1', 'tracking' ) ) ).toEqual( [ 'trackClicks', 'trackDomstreams', 'trackNamedUsers', 'excludeLoggedInUsers' ] );
+ expect( keys( visibleFields( FIELDS, '2', 'tracking' ) ) ).toEqual( [ 'trackNamedUsers', 'excludeLoggedInUsers' ] );
+} );
+
+test( 'with no version detected, only the endpoint shows', () => {
+ expect( keys( visibleFields( FIELDS, '' ) ) ).toEqual( [ 'owaEndpoint' ] );
+ expect( visibleSections( SECTIONS, FIELDS, '' ).map( ( s ) => s.name ) ).toEqual( [ 'general' ] );
} );
test( 'a tab with nothing to show is left out', () => {
@@ -27,35 +39,43 @@ test( 'a tab with nothing to show is left out', () => {
expect( visibleSections( SECTIONS, FIELDS, '2' ).map( ( s ) => s.name ) ).toEqual( [ 'general', 'tracking' ] );
} );
+test( 'what the page says about the server', () => {
+ const server = { version: '2', url: 'https://owa.example.com/', identified: true, reason: '', network: false };
+ expect( serverState( server ) ).toBe( 'identified' );
+ expect( serverState( { ...server, identified: false, reason: 'HTTP 502' } ) ).toBe( 'stale' );
+ expect( serverState( { ...server, version: '', identified: false } ) ).toBe( 'unidentified' );
+ expect( serverState( { ...server, version: '', url: '' } ) ).toBe( 'none' );
+ expect( serverState( { ...server, network: true } ) ).toBe( 'network' );
+} );
+
test( 'a field the network manages is hidden unless shown read-only', () => {
expect( isVisible( { key: 'owaEndpoint', managed: true, readonly: false }, '2' ) ).toBe( false );
expect( isVisible( { key: 'siteId', managed: true, readonly: true }, '2' ) ).toBe( true );
} );
test( 'the link to OWA\'s tracking tag screen shows only for the saved Website ID', () => {
- const saved = { owaVersion: '2', owaEndpoint: 'https://owa.example.com/', siteId: 'OWA-1', trackNamedUsers: true };
+ const saved = { owaEndpoint: 'https://owa.example.com/', siteId: 'OWA-1', trackNamedUsers: true };
const payload = { tagSettingsUrl: 'https://owa.example.com/index.php?owa_do=base.sitesInvocation&owa_siteId=OWA-1', values: saved };
expect( showTagSettingsLink( payload, saved ) ).toBe( true );
expect( showTagSettingsLink( payload, { ...saved, trackNamedUsers: false } ) ).toBe( true );
expect( showTagSettingsLink( payload, { ...saved, siteId: 'OWA-2' } ) ).toBe( false );
- expect( showTagSettingsLink( payload, { ...saved, owaVersion: '1' } ) ).toBe( false );
expect( showTagSettingsLink( payload, { ...saved, owaEndpoint: 'https://other.example.com/' } ) ).toBe( false );
expect( showTagSettingsLink( { ...payload, tagSettingsUrl: '' }, saved ) ).toBe( false );
} );
-test( 'a field takes its 2.x wording only while 2.x is chosen', () => {
+test( 'a field takes its 2.x wording only while 2.x is detected', () => {
const siteId = { title: 'Website ID', description: 'Pick a website.', v2: { title: 'Observation Profile', description: 'Pick a Profile.' } };
expect( fieldText( siteId, '1' ) ).toEqual( { title: 'Website ID', description: 'Pick a website.' } );
expect( fieldText( siteId, '2' ) ).toEqual( { title: 'Observation Profile', description: 'Pick a Profile.' } );
expect( fieldText( { title: 'OWA Endpoint', description: 'The URL.', v2: [] }, '2' ) ).toEqual( { title: 'OWA Endpoint', description: 'The URL.' } );
} );
-test( 'the setup notices follow the version chosen on the page, and go while tracking is off', () => {
- const payload = { notices: { 1: [ 'Enter your API Key.' ], 2: [ 'Enter an Application Password.' ] } };
- expect( setupNotices( payload, { enable: true, owaVersion: '1' } ) ).toEqual( [ 'Enter your API Key.' ] );
- expect( setupNotices( payload, { enable: true, owaVersion: '2' } ) ).toEqual( [ 'Enter an Application Password.' ] );
- expect( setupNotices( payload, { enable: false, owaVersion: '2' } ) ).toEqual( [] );
+test( 'the setup notices are the server\'s, and go while tracking is off', () => {
+ const payload = { notices: [ 'Enter an Application Password.' ] };
+ expect( setupNotices( payload, { enable: true } ) ).toEqual( [ 'Enter an Application Password.' ] );
+ expect( setupNotices( payload, { enable: false } ) ).toEqual( [] );
+ expect( setupNotices( {}, { enable: true } ) ).toEqual( [] );
} );
test( 'the Website ID picker shows once OWA has returned its list', () => {
From 4cc872be72b47265a899a5f1bb722e34a6f126ce Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:04:58 +0000
Subject: [PATCH 02/15] CI: install OWA 2.0 with its renamed CLI; php -S router
serves api/index.php as Apache does
OWA master renamed cmd=install to cmd=core-install, takes no scope= for
app-password-create, and refuses an owa-config.php that uses $this, so
app_passwords_require_https is stored with persistSetting() instead.
The router rewrote api/index.php itself and replaced its owa_rest_params
with 'index.php'; Apache's rule skips existing files.
---
.github/actions/owa-server/action.yml | 12 ++++++++----
tests/Integration/router.php | 9 +++++++--
2 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/.github/actions/owa-server/action.yml b/.github/actions/owa-server/action.yml
index e48db62..7ae9f23 100644
--- a/.github/actions/owa-server/action.yml
+++ b/.github/actions/owa-server/action.yml
@@ -67,7 +67,10 @@ runs:
# a name rather than an address, as screenshots and docs show it
echo "127.0.0.1 owa.test" | sudo tee -a /etc/hosts > /dev/null
mysql -h 127.0.0.1 -uroot -proot -e 'CREATE DATABASE IF NOT EXISTS owa'
- (cd "$OWA_DIR" && php cli.php cmd=install user_id=admin email_address=admin@example.test domain="${{ inputs.domain }}")
+ # 2.0 renamed cmd=install to cmd=core-install
+ INSTALL=install
+ if grep -q "'core-install'" "$OWA_DIR/modules/Base/config/cli_commands.php" 2>/dev/null; then INSTALL=core-install; fi
+ (cd "$OWA_DIR" && php cli.php cmd=$INSTALL user_id=admin email_address=admin@example.test domain="${{ inputs.domain }}")
q() { mysql -h 127.0.0.1 -uroot -proot owa -N -B -e "$1"; }
{
echo "OWA_URL=http://owa.test:8080/"
@@ -91,9 +94,10 @@ runs:
shell: bash
working-directory: ${{ runner.temp }}/owa
run: |
- # php -S is plain http, and v2 refuses application passwords over http by default
- php -r '$f = $argv[1]; file_put_contents( $f, preg_replace( "/\?>\s*$/", "\$this->set( \"base\", \"app_passwords_require_https\", false );\n?>\n", file_get_contents( $f ) ) );' owa-config.php
- TOKEN=$(php cli.php cmd=app-password-create user=admin name=wp-plugin-ci scope=read | grep -oE '\b[0-9A-Za-z]{44}\b' | tail -n 1)
+ # php -S is plain http, and 2.x refuses application passwords over http by
+ # default. The setting is stored (owa-config.php may not use $this in 2.0).
+ php -r 'define( "OWA_CLI", true ); require "owa.php"; new owa( [ "request_type" => "cli" ] ); exit( \OWA\Core\CoreAPI::persistSetting( "base", "app_passwords_require_https", false ) ? 0 : 1 );'
+ TOKEN=$(php cli.php cmd=app-password-create user=admin name=wp-plugin-ci | grep -oE '\b[0-9A-Za-z]{44}\b' | tail -n 1)
[ -n "$TOKEN" ] || { echo "no application password minted"; exit 1; }
echo "::add-mask::$TOKEN"
echo "OWA_APP_PASSWORD=$TOKEN" >> "$GITHUB_ENV"
diff --git a/tests/Integration/router.php b/tests/Integration/router.php
index ef0e1de..f86f1a9 100644
--- a/tests/Integration/router.php
+++ b/tests/Integration/router.php
@@ -4,6 +4,7 @@
* Router for `php -S`, standing in for the one OWA .htaccess rule the plugin
* depends on:
*
+ * RewriteCond %{REQUEST_FILENAME} !-f
* RewriteRule api/(.*)$ api/index.php?owa_rest_params=$1 [QSA,NC,L]
*
* Everything else is served from the document root as a file.
@@ -13,8 +14,12 @@
if ( preg_match( '#^/api/(.+)$#', $path, $m ) ) {
- $_GET['owa_rest_params'] = $m[1];
- $_REQUEST['owa_rest_params'] = $m[1];
+ // RewriteCond %{REQUEST_FILENAME} !-f: api/index.php itself keeps its query
+ if ( ! is_file( $_SERVER['DOCUMENT_ROOT'] . $path ) ) {
+
+ $_GET['owa_rest_params'] = $m[1];
+ $_REQUEST['owa_rest_params'] = $m[1];
+ }
chdir( $_SERVER['DOCUMENT_ROOT'] . '/api' );
require $_SERVER['DOCUMENT_ROOT'] . '/api/index.php';
From dd22619136d1f2b6ed5efd40b89b8cc995001873 Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:09:37 +0000
Subject: [PATCH 03/15] Link the Application-Passwords wiki page, its name once
the 2.0 wiki is published
---
src/server.php | 4 ++--
tests/e2e/single.spec.js | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/server.php b/src/server.php
index 2357ff1..faf12b0 100644
--- a/src/server.php
+++ b/src/server.php
@@ -33,8 +33,8 @@ class server {
// the screens the upgrade notice shows on
const NOTICE_SCREENS = [ 'dashboard', 'plugins', 'toplevel_page_owa-wordpress' ];
- // OWA's documentation of application passwords
- const APP_PASSWORDS_URL = 'https://github.com/Open-Web-Analytics/Open-Web-Analytics/wiki/v2-Application-Passwords';
+ // OWA's documentation of application passwords (the 2.0 wiki's page name)
+ const APP_PASSWORDS_URL = 'https://github.com/Open-Web-Analytics/Open-Web-Analytics/wiki/Application-Passwords';
public static function register( $plugin ) {
diff --git a/tests/e2e/single.spec.js b/tests/e2e/single.spec.js
index e18f2c9..d8b308f 100644
--- a/tests/e2e/single.spec.js
+++ b/tests/e2e/single.spec.js
@@ -36,7 +36,7 @@ test( 'the URL comes first, 2.x is detected, its fields save, and pages get the
// 2.x's fields only
await expect( field( 'Application Password' ) ).toBeVisible();
- await expect( page.getByRole( 'link', { name: /How to create an application password/ } ) ).toHaveAttribute( 'href', /wiki\/v2-Application-Passwords$/ );
+ await expect( page.getByRole( 'link', { name: /How to create an application password/ } ) ).toHaveAttribute( 'href', /wiki\/Application-Passwords$/ );
await expect( field( 'API Key' ) ).toHaveCount( 0 );
await expect( field( 'Secret Auth Key' ) ).toHaveCount( 0 );
await expect( tab( 'Advanced' ) ).toHaveCount( 0 );
From 1170e4539570d401987c2ce8c0bb029ed44075c7 Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:09:37 +0000
Subject: [PATCH 04/15] TEMPORARY: run the 2.x jobs on OWA
fix/pre-2.0.0-blockers (#1754), which sends WWW-Authenticate
---
.github/workflows/ci.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 241b22f..4d66e11 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -78,7 +78,7 @@ jobs:
release: '1.14.0'
groups: 'owa1'
- owa: 'master'
- branch: 'master'
+ branch: 'fix/pre-2.0.0-blockers'
# 2.x refuses the 1.x keys: the bundle tag and app passwords
groups: 'owa2'
services:
@@ -143,7 +143,7 @@ jobs:
run: composer install --no-interaction --no-progress
- uses: ./.github/actions/owa-server
with:
- branch: master
+ branch: fix/pre-2.0.0-blockers
app-passwords: 'true'
domain: https://wp.test
profiles: |
From 0716ab99bf4496a684af735625ff9b572231ee00 Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:14:25 +0000
Subject: [PATCH 05/15] Settings page: the Website ID keeps its values prop;
e2e reads the domain OWA stored
The tag-settings link read values, which WebsiteId no longer received:
the page crashed once the picker rendered.
OWA 2.0 stores a Profile's bare host, so the e2e labels and site IDs are
read with the domain as stored.
---
js/settings/index.js | 2 +-
tests/e2e/helpers.js | 21 +++++++++++++++++----
tests/e2e/multisite.spec.js | 12 ++++++------
3 files changed, 24 insertions(+), 11 deletions(-)
diff --git a/js/settings/index.js b/js/settings/index.js
index 904a362..d44c08f 100644
--- a/js/settings/index.js
+++ b/js/settings/index.js
@@ -87,7 +87,7 @@ function ServerStatus( { server, onCheck, checking } ) {
}
}
-function WebsiteId( { field, value, onChange, sites, payload, version } ) {
+function WebsiteId( { field, value, onChange, sites, payload, values, version } ) {
const v2 = version === '2';
const text = fieldText( field, version );
const options = [ { label: sites.loading ? 'Loading…' : v2 ? 'Select Profile…' : 'Select…', value: '' }, ...sites.choices ];
diff --git a/tests/e2e/helpers.js b/tests/e2e/helpers.js
index 3d3dfd0..f59593a 100644
--- a/tests/e2e/helpers.js
+++ b/tests/e2e/helpers.js
@@ -54,10 +54,23 @@ async function docShot( page, number ) {
await page.locator( '#wpbody-content' ).screenshot( { path: path.join( dir, `screenshot-${ number }.png` ) } );
}
-/** The OWA site ID (Profile) of a domain, from the OWA database. */
+/** A Profile's row for a domain, from the OWA database; OWA 2.0 stores the bare host. */
+function owaSite( domain ) {
+ const host = domain.replace( /^https?:\/\//, '' );
+ const row = execFileSync( 'mysql', [ '-h', '127.0.0.1', '-uroot', '-proot', 'owa', '-N', '-B', '-e',
+ `SELECT site_id, domain FROM owa_site WHERE domain IN ( '${ domain }', '${ host }' ) LIMIT 1` ] ).toString().trim().split( '\t' );
+ return { id: row[ 0 ] || '', domain: row[ 1 ] || '' };
+}
+
+/** The OWA site ID (Profile) of a domain. */
function owaSiteId( domain ) {
- return execFileSync( 'mysql', [ '-h', '127.0.0.1', '-uroot', '-proot', 'owa', '-N', '-B', '-e',
- `SELECT site_id FROM owa_site WHERE domain = '${ domain }' LIMIT 1` ] ).toString().trim();
+ return owaSite( domain ).id;
+}
+
+/** A Profile's label in the plugin: "site ID – domain (name)", with the domain as OWA stored it. */
+function profileLabel( domain, name ) {
+ const site = owaSite( domain );
+ return `${ site.id } – ${ site.domain } (${ name })`;
}
/** Runs OWA's CLI in the CI install. */
@@ -70,4 +83,4 @@ function wp( ...args ) {
return execFileSync( 'wp', [ `--path=${ env( 'WP_DIR' ) }`, ...args ] ).toString();
}
-module.exports = { env, docShot, login, notice, shot, owaSiteId, owaCli, wp };
+module.exports = { env, docShot, login, notice, shot, owaSiteId, profileLabel, owaCli, wp };
diff --git a/tests/e2e/multisite.spec.js b/tests/e2e/multisite.spec.js
index 8214be3..cab50be 100644
--- a/tests/e2e/multisite.spec.js
+++ b/tests/e2e/multisite.spec.js
@@ -3,7 +3,7 @@
// a reload that brings in a new Profile and a new site, and both ways a site
// gets its Website ID.
const { test, expect } = require( '@playwright/test' );
-const { env, docShot, login, notice, shot, owaSiteId, owaCli, wp } = require( './helpers' );
+const { env, docShot, login, notice, shot, owaSiteId, profileLabel, owaCli, wp } = require( './helpers' );
const NETWORK_PAGE = 'http://wp.test/wp-admin/network/admin.php?page=owa-wordpress-network';
@@ -32,7 +32,7 @@ test( 'the network configures each site\'s Profile', async ( { page, browser },
// b.wp.test has none, so it keeps its dropdown and has no switch
await expect( notice( page, 'Settings saved.' ) ).toBeVisible();
await expect( row( page, 'wp.test' ) ).toContainText( main );
- await expect( row( page, 'a.wp.test' ) ).toContainText( `${ siteA } – https://a.wp.test (Site A)` );
+ await expect( row( page, 'a.wp.test' ) ).toContainText( profileLabel( 'https://a.wp.test', 'Site A' ) );
await expect( site( page, 'a.wp.test' ) ).toHaveCount( 0 );
await expect( edit( page, 'a.wp.test' ) ).toBeVisible();
await expect( tracking( page, 'a.wp.test' ) ).toBeVisible();
@@ -72,7 +72,7 @@ test( 'the network configures each site\'s Profile', async ( { page, browser },
await save.click();
await expect( notice( page, 'Settings saved.' ) ).toBeVisible();
// b.wp.test now has a saved Profile: text, Edit and its switch, on
- await expect( row( page, 'b.wp.test' ) ).toContainText( `${ siteB } – https://b.wp.test (Site B)` );
+ await expect( row( page, 'b.wp.test' ) ).toContainText( profileLabel( 'https://b.wp.test', 'Site B' ) );
await expect( site( page, 'b.wp.test' ) ).toHaveCount( 0 );
await expect( tracking( page, 'b.wp.test' ) ).toBeChecked();
// c.wp.test was saved without a Profile: no longer New, still a dropdown and no switch
@@ -91,7 +91,7 @@ test( 'the network configures each site\'s Profile', async ( { page, browser },
await expect( notice( page, 'Settings saved.' ) ).toBeVisible();
await expect( tracking( page, 'a.wp.test' ) ).not.toBeChecked();
await expect( row( page, 'a.wp.test' ) ).toHaveClass( /is-disabled/ );
- await expect( row( page, 'a.wp.test' ) ).toContainText( `${ siteA } – https://a.wp.test (Site A)` );
+ await expect( row( page, 'a.wp.test' ) ).toContainText( profileLabel( 'https://a.wp.test', 'Site A' ) );
await shot( page, testInfo, '05b-site-switched-off' );
await page.reload();
await expect( tracking( page, 'a.wp.test' ) ).not.toBeChecked();
@@ -102,7 +102,7 @@ test( 'the network configures each site\'s Profile', async ( { page, browser },
await expect( page.getByLabel( 'Observation Profile', { exact: true } ) ).toBeDisabled();
await expect( page.getByLabel( 'Observation Profile', { exact: true } ) ).toHaveValue( siteA );
// labelled from OWA's list, though the network has tracking off here
- await expect( page.getByLabel( 'Observation Profile', { exact: true } ).locator( 'option:checked' ) ).toHaveText( `${ siteA } – https://a.wp.test (Site A)` );
+ await expect( page.getByLabel( 'Observation Profile', { exact: true } ).locator( 'option:checked' ) ).toHaveText( profileLabel( 'https://a.wp.test', 'Site A' ) );
await expect( page.getByLabel( 'OWA Endpoint' ) ).toHaveCount( 0 );
await expect( page.getByLabel( 'Application Password' ) ).toHaveCount( 0 );
await expect( page.getByLabel( '2.x (beta)' ) ).toHaveCount( 0 );
@@ -140,7 +140,7 @@ test( 'each site picks from the Profiles sharing its domain', async ( { page },
// the wp.test family, not www.other.example
const labels = await picker.locator( 'option' ).allTextContents();
- expect( labels.some( ( v ) => v.includes( 'https://a.wp.test' ) ) ).toBe( true );
+ expect( labels.some( ( v ) => v.includes( 'a.wp.test' ) ) ).toBe( true );
expect( labels.some( ( v ) => v.includes( 'other.example' ) ) ).toBe( false );
await expect( page.getByText( 'The list shows the Observation Profiles that share this site\'s domain.' ) ).toBeVisible();
await shot( page, testInfo, '08-site-choice' );
From 6162fa5c56b9a6bd4817741fd96385193cb6fe86 Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 06:19:38 +0000
Subject: [PATCH 06/15] Revert "TEMPORARY: run the 2.x jobs on OWA
fix/pre-2.0.0-blockers (#1754), which sends WWW-Authenticate"
This reverts commit 1170e4539570d401987c2ce8c0bb029ed44075c7.
---
.github/workflows/ci.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4d66e11..241b22f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -78,7 +78,7 @@ jobs:
release: '1.14.0'
groups: 'owa1'
- owa: 'master'
- branch: 'fix/pre-2.0.0-blockers'
+ branch: 'master'
# 2.x refuses the 1.x keys: the bundle tag and app passwords
groups: 'owa2'
services:
@@ -143,7 +143,7 @@ jobs:
run: composer install --no-interaction --no-progress
- uses: ./.github/actions/owa-server
with:
- branch: fix/pre-2.0.0-blockers
+ branch: master
app-passwords: 'true'
domain: https://wp.test
profiles: |
From bb9c3b8d6641bea8c3f5032d8cd7e69cb1875a73 Mon Sep 17 00:00:00 2001
From: padams <249756+padams@users.noreply.github.com>
Date: Wed, 2 Dec 2026 08:41:42 +0000
Subject: [PATCH 07/15] Detect 2.x by a positive answer; Check before Save
The probe asks for base/v2/profiles. OWA 2.x's envelope ({data, error}),
or a 401 with a Bearer challenge, is 2.x; any other answer is 1.x. No
answer (network error, 408, 429, 5xx) keeps the version found at the same
endpoint before; a new endpoint that does not answer gets none.
Settings page: the endpoint comes with Check, which identifies the URL in
the field without storing it. That version's fields then show, and Save
Changes once its credentials are entered (on the saved endpoint, always).
Check no longer reloads the form, so typed values stay.
---
README.txt | 6 +-
js/lib/fields.js | 51 ++++++++++-
js/settings/index.js | 77 +++++++++++------
owa-plugin.php | 2 +-
src/rest.php | 51 +++++++++--
src/server.php | 68 ++++++++-------
tests/Integration/OwaV2ServerTest.php | 4 +-
tests/NetworkTest.php | 2 +-
tests/RestTest.php | 3 +-
tests/ServerTest.php | 118 +++++++++++++++++++-------
tests/TestCase.php | 8 +-
tests/e2e/single.spec.js | 16 ++--
tests/js/fields.test.js | 46 +++++++++-
13 files changed, 335 insertions(+), 117 deletions(-)
diff --git a/README.txt b/README.txt
index 960b2e6..5294d1a 100644
--- a/README.txt
+++ b/README.txt
@@ -23,7 +23,7 @@ The plugin detects which version the OWA server at the OWA Endpoint runs and sho
* **1.x** authenticates with an OWA user's API key and the server's Secret Auth Key. Tracker options are set in WordPress.
* **2.x (beta)** authenticates with an OWA application password and loads the Observation Profile's tracking bundle. Click tracking and Domstreams are set on the OWA server; the settings page links to them.
-The version is checked when the OWA Endpoint is saved, once a day when an administrator opens an admin page, and with Check again on the settings page. When a 1.x server is upgraded to 2.x, the dashboard, Plugins screen and settings page ask for an application password. Tracking continues meanwhile.
+To set up, enter the OWA Endpoint and click Check. That version's settings appear, and Save Changes appears once its credentials are entered. The version is checked again when the endpoint is saved, once a day when an administrator opens an admin page, and with Check again. When a 1.x server is upgraded to 2.x, the dashboard, Plugins screen and settings page ask for an application password. Tracking continues meanwhile.
= What is tracked =
@@ -84,8 +84,8 @@ Application passwords are sent only over https. To use an http OWA server, turn
= 2.5.0 =
-* The OWA Server Version setting is gone. The plugin detects the version at the OWA Endpoint and shows only that version's settings; until a version is detected, only the OWA Endpoint. It checks when the endpoint is saved, once a day on admin page loads, and with Check again. If no version can be detected, the version found before is kept and the page says so.
-* After updating, the first admin page load checks the server and replaces the version chosen before. If the server cannot be identified, the version chosen before is kept.
+* The OWA Server Version setting is gone. The plugin detects the version at the OWA Endpoint and shows only that version's settings; until a version is detected, only the OWA Endpoint and Check. It checks with Check, when the endpoint is saved, and once a day on admin page loads. If the server does not answer, the version found there before is kept and the page says so.
+* After updating, the first admin page load checks the server and replaces the version chosen before. If the server does not answer, the version chosen before is kept.
* A 1.x server upgraded to 2.x: the dashboard, Plugins screen and settings page ask for an application password (dismissible). The 1.x keys stay stored, and tracking continues with the 2.x tag.
* The Application Password field links to OWA's documentation.
* Network Admin > OWA refuses an OWA Endpoint that identifies as 1.x.
diff --git a/js/lib/fields.js b/js/lib/fields.js
index 1166fef..6f752eb 100644
--- a/js/lib/fields.js
+++ b/js/lib/fields.js
@@ -39,10 +39,27 @@ export function setupNotices( payload, values ) {
}
/**
- * What the page says about the server at the saved endpoint:
+ * The server the page shows: the saved endpoint's (payload.server) while the
+ * field holds the saved URL; else the result of checking what the field
+ * holds ($checked), while it still holds that; else one not checked yet.
+ */
+export function shownServer( payload, values, checked ) {
+ const url = values.owaEndpoint || '';
+ if ( payload.server.network || url === payload.server.url ) {
+ return payload.server;
+ }
+ if ( checked && checked.url === url ) {
+ return checked;
+ }
+ return { version: '', url, identified: false, reason: '', checkedAt: 0, network: false, unchecked: true };
+}
+
+/**
+ * What the page says about the shown server:
* - "network": the network administrator manages it; nothing is said.
- * - "none": no endpoint saved yet.
- * - "unidentified": an endpoint, and no version was ever found there.
+ * - "none": no URL in the field.
+ * - "unchecked": a URL that is not the saved one and was not checked.
+ * - "unidentified": a URL, and no version was ever found there.
* - "stale": the last check found no version; the one found before is used.
* - "identified": the last check found the version shown.
*/
@@ -53,12 +70,40 @@ export function serverState( server ) {
if ( ! server.url ) {
return 'none';
}
+ if ( server.unchecked ) {
+ return 'unchecked';
+ }
if ( ! server.version ) {
return 'unidentified';
}
return server.identified ? 'identified' : 'stale';
}
+/**
+ * Whether Save Changes shows. Emptying a saved endpoint can always be saved.
+ * Otherwise the server has to be identified, and for a URL that is not the
+ * saved one (a new setup, or another server) its version's credentials have
+ * to be there, saved or typed.
+ */
+export function canSave( payload, values, secrets, server ) {
+ const url = values.owaEndpoint || '';
+ if ( url === '' ) {
+ return Boolean( payload.server.url );
+ }
+ if ( ! server.version ) {
+ return false;
+ }
+ if ( server.network || url === payload.server.url ) {
+ return true;
+ }
+ return visibleFields( payload.fields, server.version )
+ .filter( ( field ) => field.type === 'secret' || field.type === 'app_password' )
+ .every( ( field ) => {
+ const edit = secrets[ field.key ] || {};
+ return Boolean( edit.value ) || ( Boolean( payload.secrets[ field.key ] ) && ! edit.clear );
+ } );
+}
+
/** The tabs that have something to show. */
export function visibleSections( sections, fields, version ) {
return sections.filter( ( section ) => visibleFields( fields, version, section.name ).length > 0 );
diff --git a/js/settings/index.js b/js/settings/index.js
index d44c08f..49b3094 100644
--- a/js/settings/index.js
+++ b/js/settings/index.js
@@ -4,7 +4,10 @@
* The fields come from the server (owaWp_plugin::registerOptions()), with
* the version each belongs to and whether the network manages it, and the
* version detected at the saved endpoint (payload.server), so this page
- * decides only how each type is drawn and which ones show.
+ * decides only how each type is drawn and which ones show. A URL typed in
+ * place of the saved one is checked first (POST owa-wp/v1/server, nothing
+ * stored); its version's fields then show, and Save Changes once its
+ * credentials are entered.
*/
import { createRoot, useEffect, useState } from '@wordpress/element';
import {
@@ -21,7 +24,7 @@ import {
import apiFetch from '@wordpress/api-fetch';
import { __, sprintf } from '@wordpress/i18n';
-import { fieldText, serverState, setupNotices, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../lib/fields';
+import { canSave, fieldText, serverState, setupNotices, shownServer, showPicker, showTagSettingsLink, visibleFields, visibleSections } from '../lib/fields';
import { secretHint, secretsPayload } from '../lib/secrets';
import './style.css';
@@ -33,43 +36,45 @@ function FieldError( { message } ) {
return message ?
{ message }
: null;
}
-/** Under the endpoint: the OWA version found there, or why none was. */
+/** Under the endpoint: the OWA version found there, or why none was, and Check. */
function ServerStatus( { server, onCheck, checking } ) {
const state = serverState( server );
- const check = (
-