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/.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/.wordpress-org/screenshot-1.png b/.wordpress-org/screenshot-1.png index 11c2970..de14931 100644 Binary files a/.wordpress-org/screenshot-1.png and b/.wordpress-org/screenshot-1.png differ diff --git a/.wordpress-org/screenshot-2.png b/.wordpress-org/screenshot-2.png index 7ccf2d6..716b242 100644 Binary files a/.wordpress-org/screenshot-2.png and b/.wordpress-org/screenshot-2.png differ diff --git a/.wordpress-org/screenshot-3.png b/.wordpress-org/screenshot-3.png index 18bf4b9..08dd69b 100644 Binary files a/.wordpress-org/screenshot-3.png and b/.wordpress-org/screenshot-3.png differ diff --git a/.wordpress-org/screenshot-4.png b/.wordpress-org/screenshot-4.png index fc8c0a5..22da25b 100644 Binary files a/.wordpress-org/screenshot-4.png and b/.wordpress-org/screenshot-4.png differ diff --git a/.wordpress-org/screenshot-5.png b/.wordpress-org/screenshot-5.png index 5731ed5..1351019 100644 Binary files a/.wordpress-org/screenshot-5.png and b/.wordpress-org/screenshot-5.png differ 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..5b77e4a 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 Server 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. + +To set up, enter the OWA Server 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 = @@ -46,19 +48,23 @@ 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 Server Endpoint and click Check. Check finds OWA there, uses 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 Server Endpoint = + +The URL has not been checked yet, or the OWA server did not answer. The page shows why. The plugin requests `api/index.php` under the OWA Server 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()`. +The tag is added once Enable OWA is on and the OWA Server Endpoint and Observation Profile are saved. Your theme must call `wp_head()`. = The Observation Profiles do not load over http = @@ -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 and Check. 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 Server Endpoint and shows only that version's settings; until a version is detected, only the OWA Server 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 Server 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..6f752eb 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,87 @@ 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 || []; +} + +/** + * 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 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. + */ +export function serverState( server ) { + if ( server.network ) { + return 'network'; + } + 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. */ @@ -41,11 +112,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/network/index.js b/js/network/index.js index 8a685c3..eca51da 100644 --- a/js/network/index.js +++ b/js/network/index.js @@ -200,7 +200,7 @@ function NetworkPage() { 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. 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 { @@ -18,21 +22,89 @@ 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 { canSave, fieldText, serverState, setupNotices, shownServer, 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, and Check. */ +function ServerStatus( { server, onCheck, checking } ) { + const state = serverState( server ); + const check = ( label ) => ( + + ); + // changes with every check, so a check that finds the same still shows + const when = server.checkedAt ? ( + + { sprintf( + /* translators: %s: a time of day */ + __( 'Checked at %s.', 'open-web-analytics' ), + new Date( server.checkedAt * 1000 ).toLocaleTimeString() + ) } + + ) : null; + + switch ( state ) { + case 'none': + case 'unchecked': + return ( +
+

{ __( 'Enter the URL of your OWA server and check it. The settings for the OWA version it runs then appear.', 'open-web-analytics' ) }

+ { check( __( 'Check', 'open-web-analytics' ) ) } +
+ ); + case 'unidentified': + return ( + + { sprintf( + /* translators: 1: the OWA Server Endpoint URL, 2: the error */ + __( 'The OWA server at %1$s did not answer (%2$s). Check the URL and try again.', 'open-web-analytics' ), + server.url, + server.reason + ) }{ ' ' }{ when }{ ' ' }{ check( __( 'Check again', 'open-web-analytics' ) ) } + + ); + case 'stale': + return ( + + { sprintf( + /* translators: 1: the OWA Server Endpoint URL, 2: the error, 3: the OWA major version found before */ + __( 'The OWA server at %1$s did not answer (%2$s). Showing the settings for OWA %3$s.x, the version found there before.', 'open-web-analytics' ), + server.url, + server.reason, + server.version + ) }{ ' ' }{ when }{ ' ' }{ check( __( 'Check again', 'open-web-analytics' ) ) } + + ); + case 'identified': + return ( +

+ { sprintf( + /* translators: %s: the OWA major version */ + __( 'This is an OWA %s.x server.', 'open-web-analytics' ), + server.version + ) }{ ' ' }{ when }{ ' ' }{ check( __( 'Check again', 'open-web-analytics' ) ) } +

+ ); + default: + return null; + } +} + +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 ]; return ( @@ -51,7 +123,7 @@ function WebsiteId( { field, value, onChange, sites, payload, values } ) { ) } { sites.notice &&

{ sites.notice }

} { payload.network.note &&

{ payload.network.note }

} - { showTagSettingsLink( payload, values ) && ( + { v2 && showTagSettingsLink( payload, values ) && (

Configure this Observation Profile's tracking tag in OWA

@@ -60,9 +132,9 @@ function WebsiteId( { field, value, onChange, sites, payload, values } ) { ); } -function Field( { field, payload, values, setValue, secrets, setSecret, sites, error } ) { +function Field( { field, payload, values, setValue, secrets, setSecret, sites, version, server } ) { const value = values[ field.key ]; - const text = fieldText( field, values.owaVersion ); + const text = fieldText( field, version ); const common = { label: text.title, help: text.description }; switch ( field.type ) { @@ -96,23 +168,31 @@ function Field( { field, payload, values, setValue, secrets, setSecret, sites, e ) }

+ { field.helpUrl && ( +

+ { __( '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 +205,9 @@ function SettingsPage() { const [ errors, setErrors ] = useState( {} ); const [ notice, setNotice ] = useState( null ); const [ saving, setSaving ] = useState( false ); + const [ checking, setChecking ] = useState( false ); + // the result of checking a URL that is not the saved one + const [ checked, setChecked ] = useState( null ); const loadSites = () => { setSites( ( current ) => ( { ...current, loading: true } ) ); @@ -138,6 +221,7 @@ function SettingsPage() { setValues( result.values ); setSecrets( {} ); setErrors( {} ); + setChecked( null ); }; useEffect( () => { @@ -163,11 +247,42 @@ function SettingsPage() { .finally( () => setSaving( false ) ); }; + // checks the URL in the field; what was typed stays + const checkServer = () => { + const started = Date.now(); + setChecking( true ); + setNotice( null ); + setErrors( ( current ) => ( { ...current, owaEndpoint: '' } ) ); + apiFetch( { path: SERVER, method: 'POST', data: { owaEndpoint: values.owaEndpoint || '' } } ) + .then( ( result ) => { + if ( ! result.server ) { + setErrors( ( current ) => ( { ...current, owaEndpoint: result.error } ) ); + return; + } + // the URL as it would be stored: with its scheme and slash + setValues( ( current ) => ( { ...current, owaEndpoint: result.server.url } ) ); + if ( result.saved ) { + setPayload( ( current ) => ( { ...current, server: result.server, notices: result.notices, tagSettingsUrl: result.tagSettingsUrl } ) ); + setChecked( null ); + loadSites(); + } else { + setChecked( result.server ); + } + } ) + .catch( ( error ) => setNotice( { status: 'error', text: error.message } ) ) + // long enough to be seen when OWA answers at once + .finally( () => setTimeout( () => setChecking( false ), Math.max( 0, 600 - ( Date.now() - started ) ) ) ); + }; + if ( ! payload ) { return notice ? { notice.text } : ; } - const version = values.owaVersion || '1'; + const server = shownServer( payload, values, checked ); + const version = server.version; + // another server than the saved one: the saved one's list and notices do not apply + const isSaved = server === payload.server; + const shownSites = isSaved ? sites : { choices: [], notice: '', loading: false, loaded: false }; const tabs = visibleSections( payload.sections, payload.fields, version ).map( ( section ) => ( { name: section.name, title: section.title, @@ -184,7 +299,7 @@ function SettingsPage() { { notice.text } ) } - { setupNotices( payload, values ).map( ( text ) => ( + { isSaved && setupNotices( payload, values ).map( ( text ) => ( { text } @@ -195,7 +310,7 @@ function SettingsPage() {

{ tab.description }

{ visibleFields( payload.fields, version, tab.name ).map( ( field ) => ( -
+
@@ -211,9 +328,11 @@ function SettingsPage() {
) } - + { canSave( payload, values, secrets, server ) && ( + + ) }
); } diff --git a/js/settings/style.css b/js/settings/style.css index 3101107..7ff11d8 100644 --- a/js/settings/style.css +++ b/js/settings/style.css @@ -69,3 +69,23 @@ width: 1%; white-space: nowrap; } + +/* under the OWA Endpoint: the version found there */ +.owa-wp-server { + margin: 8px 0 0; +} + +.owa-wp-server .owa-wp-check { + margin-left: 4px; + vertical-align: middle; +} + +.owa-wp-checked-at { + color: #646970; +} + +/* Enable OWA: the switch for the whole plugin */ +.owa-wp-field-enable .components-toggle-control__label { + font-size: 15px; + font-weight: 600; +} diff --git a/owa-plugin.php b/owa-plugin.php index 9f4d083..b61d98e 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,11 +750,20 @@ 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 Server Endpoint URL */ + ? sprintf( __( 'The OWA server at %s did not answer. Check the OWA Server Endpoint under OWA > Settings.', 'open-web-analytics' ), $this->getOption( 'owaEndpoint' ) ) + : __( 'Enter the URL of your OWA server as the OWA Server Endpoint under OWA > Settings.', 'open-web-analytics' ) ]; + } + if ( ! $this->isOwaSdkReady( $version ) ) { $notices[] = $version === 2 - ? 'Enter your OWA Endpoint and an Application Password to load the list of Observation Profiles from OWA.' - : 'Enter your OWA Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.'; + ? 'Enter your OWA Server Endpoint and an Application Password to load the list of Observation Profiles from OWA.' + : 'Enter your OWA Server Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.'; } // where the network sets the Observation Profile, the site admin cannot, and the page says so @@ -819,32 +848,33 @@ public function registerOptions() { $settings = array( - 'owaVersion' => array( + 'enable' => array( - 'default_value' => '1', + 'default_value' => true, 'field' => array( - 'type' => 'radio', - 'title' => 'OWA Server Version', + 'type' => 'boolean', + 'title' => 'Enable OWA', '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)' ], - 'error_message' => '' + 'description' => 'Adds the OWA tracking tag to this website\'s public pages.', + 'label_for' => 'Enable OWA.', + 'error_message' => 'You must select On or Off.' ) ), - 'enable' => array( + 'owaEndpoint' => array( - 'default_value' => true, + 'default_value' => '', 'field' => array( - 'type' => 'boolean', - 'title' => 'Enable OWA ', + 'type' => 'url', + 'title' => 'OWA Server Endpoint', 'page_name' => 'owa-wordpress', 'section' => 'general', - 'description' => 'Enable OWA.', - 'label_for' => 'Enable OWA.', - 'error_message' => 'You must select On or Off.' + '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. Check finds OWA there and the version it runs, and shows the settings for that version. Without https:// or http://, https is tried first.', + 'label_for' => 'OWA Server Endpoint', + 'length' => 70, + 'endWithSlash' => true, + 'error_message' => '' ) ), @@ -894,28 +924,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' => '', @@ -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..976445e 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: which OWA version the endpoint in the field runs + register_rest_route( self::NAMESPACE, '/server', [ + [ 'methods' => 'POST', 'callback' => fn( $request ) => self::checkServer( $plugin, (array) $request->get_json_params() ), '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(), (string) ( $stored['owaEndpoint'] ?? '' ) ); + 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,79 @@ 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: which OWA version the endpoint in the field runs. The saved + * endpoint is checked and the result stored, as the daily check does + * (saved: true). Any other is found and probed and nothing is stored: the + * save that follows checks it again (saved: false). Either way the + * server status for that endpoint is returned, its url as it would be + * stored. + * + * @param array $input owaEndpoint: what the field holds; the saved endpoint when left out + * @return array{saved: bool, server: array|null, error?: string, notices?: list, tagSettingsUrl?: string} + */ + public static function checkServer( $plugin, array $input = [] ) { + + $saved = (string) $plugin->getOption( 'owaEndpoint' ); + $typed = array_key_exists( 'owaEndpoint', $input ) ? trim( (string) $input['owaEndpoint'] ) : $saved; + + [ $url, $problem ] = self::normalizeEndpoint( $typed, $saved ); + + if ( network::isActive() || ( $url !== '' && $url === $saved ) ) { + + server::check( $plugin ); + $payload = self::settingsPayload( $plugin ); + + return [ 'saved' => true, 'server' => $payload['server'], 'notices' => $payload['notices'], 'tagSettingsUrl' => $payload['tagSettingsUrl'] ]; + } + + // not a URL, or no OWA there: said under the field, as a save says it + if ( $url === '' ) { + + return [ 'saved' => false, 'server' => null, 'error' => $problem !== '' ? $problem : __( 'Enter the URL of your OWA server.', 'open-web-analytics' ) ]; + } + + $result = server::probe( $url ); + + return [ + 'saved' => false, + 'server' => [ + 'version' => $result['version'] ? (string) $result['version'] : '', + 'url' => $url, + 'identified' => $result['version'] > 0, + 'reason' => (string) $result['reason'], + 'checkedAt' => time(), + 'network' => false, + ], + ]; } /** diff --git a/src/server.php b/src/server.php new file mode 100644 index 0000000..7683ddd --- /dev/null +++ b/src/server.php @@ -0,0 +1,402 @@ + 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 ( $code < 200 || $code >= 500 || in_array( $code, self::NO_ANSWER, true ) ) { + + /* translators: %d: an HTTP status code */ + return [ 'version' => 0, 'reason' => sprintf( __( 'HTTP %d', 'open-web-analytics' ), $code ) ]; + } + + if ( self::isV2Envelope( (string) wp_remote_retrieve_body( $response ) ) + || ( $code === 401 && self::hasBearerChallenge( wp_remote_retrieve_header( $response, 'www-authenticate' ) ) ) ) { + + return [ 'version' => 2, 'reason' => '' ]; + } + + return [ 'version' => 1, 'reason' => '' ]; + } + + /** + * 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 2.x's REST envelope: a JSON object with data and + * error, error a string or null, and none of 1.x's requestId. + */ + public static function isV2Envelope( $body ) { + + $json = json_decode( $body, true ); + + return is_array( $json ) + && array_key_exists( 'data', $json ) + && array_key_exists( 'error', $json ) + && ( $json['error'] === null || is_string( $json['error'] ) ) + && ! array_key_exists( 'requestId', $json ); + } + + /** + * The stored settings after a check of $endpoint: the version found. When + * none was found, the version before if $endpoint is the endpoint it was + * found at ($previous), and none otherwise. 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 + * @param string $previous the endpoint stored before + * @return array + */ + public static function applyResult( array $stored, $endpoint, array $result, $now, $previous ) { + + $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'] = (string) $previous === (string) $endpoint ? $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(), $endpoint ); + + 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..93c25a8 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 its envelope and a + * Bearer challenge. + */ + 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/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'; diff --git a/tests/NetworkTest.php b/tests/NetworkTest.php index 0dcd980..adc81b5 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(); @@ -509,7 +531,7 @@ public function testTheNetworksEndpointIsStoredWhereOwaAnswers(): void { $this->networkMode(); Functions\when( 'wp_remote_get' )->alias( fn( $url ) => str_starts_with( $url, 'https://owa2.example.com/' ) - ? [ 'response' => [ 'code' => 200 ] ] + ? ( str_contains( $url, \owaWp\server::PROBE_PATH ) ? self::owa2Answer() : [ 'response' => [ 'code' => 200 ] ] ) : new \WP_Error( 'http_request_failed', 'cURL error 7' ) ); network::save( [ 'owaEndpoint' => 'owa2.example.com' ], $this->networkPlugin() ); diff --git a/tests/OwaV2Test.php b/tests/OwaV2Test.php index 16fc2b1..587e58a 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 + [ 'enable', 'owaEndpoint', 'appPassword', 'siteId', 'trackNamedUsers', 'excludeLoggedInUsers' ], + $shown, + 'Enable first, then the endpoint; 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/PluginTest.php b/tests/PluginTest.php index 5eeb671..244e6c1 100644 --- a/tests/PluginTest.php +++ b/tests/PluginTest.php @@ -105,8 +105,8 @@ public function testSetupNoticesAreWordedForTheVersionAsked(): void { $plugin = $this->makePlugin( [ 'owaVersion' => '1' ] ); - $this->assertSame( [ 'Enter your OWA Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ], $plugin->setupNotices() ); - $this->assertSame( [ 'Enter your OWA Endpoint and an Application Password to load the list of Observation Profiles from OWA.' ], $plugin->setupNotices( 2 ) ); + $this->assertSame( [ 'Enter your OWA Server Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ], $plugin->setupNotices() ); + $this->assertSame( [ 'Enter your OWA Server Endpoint and an Application Password to load the list of Observation Profiles from OWA.' ], $plugin->setupNotices( 2 ) ); } public function testChoosingAWebsiteIdIsAskedForOnceTheCredentialsAreIn(): void { @@ -131,7 +131,7 @@ public function testSetupNoticesGoOnceTheSettingsAreSaved(): void { $plugin = $this->makePlugin( [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => 'owa_app_x', 'siteId' => 'abc123' ] ); $this->assertSame( [], $plugin->setupNotices() ); - $this->assertSame( [ 'Enter your OWA Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ], $plugin->setupNotices( 1 ) ); + $this->assertSame( [ 'Enter your OWA Server Endpoint, API Key and Secret Auth Key to load the list of websites from OWA.' ], $plugin->setupNotices( 1 ) ); } public function testTheSettingsScreenLeavesSetupNoticesToThePage(): void { @@ -150,6 +150,6 @@ public function testTheSettingsScreenLeavesSetupNoticesToThePage(): void { $dashboard = ob_get_clean(); $this->assertSame( '

Broken.

', $settings ); - $this->assertStringContainsString( 'Enter your OWA Endpoint, API Key and Secret Auth Key', $dashboard ); + $this->assertStringContainsString( 'Enter your OWA Server Endpoint, API Key and Secret Auth Key', $dashboard ); } } diff --git a/tests/RestTest.php b/tests/RestTest.php index 6ea24ca..edfb177 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( [ 'enable' => 0, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'OWA-9b62dc7ce78a6934', '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'] ); @@ -240,7 +243,8 @@ public function testASiteSavePurgesWhenItsTagChanges(): void { public function testASiteSaveThatLeavesTheTagAlonePurgesNothing(): void { - $this->stored = [ 'enable' => 1, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123', 'trackNamedUsers' => 1 ]; + $this->stored = [ 'enable' => 1, 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123', 'trackNamedUsers' => 1, + 'owaVersion' => '1', 'owaVersionCheck' => [ 'url' => 'https://owa.example.com/', 'version' => 1, 'reason' => '', 'at' => 1 ] ]; $plugin = new \owaWp_plugin(); $plugin->reloadOptions(); @@ -280,7 +284,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..9b3d75f --- /dev/null +++ b/tests/ServerTest.php @@ -0,0 +1,585 @@ +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 testOwa2IsItsEnvelopeOrA401WithABearerChallenge(): void { + + $this->assertSame( [ 'version' => 2, 'reason' => '' ], server::classify( self::owa2Answer() ) ); + $this->assertSame( 2, server::classify( self::probeResponse( 401, [], '{"data":null,"error":"Check the API credentials or this user\'s permissions."}' ) )['version'], 'A proxy removed the challenge.' ); + $this->assertSame( 2, server::classify( self::probeResponse( 401, [ 'www-authenticate' => 'Bearer realm="OWA"' ], '401' ) )['version'], 'A proxy replaced the body.' ); + $this->assertSame( 2, server::classify( self::probeResponse( 200, [], '{"data":[{"profileId":"OWA-1"}],"error":null}' ) )['version'], 'Anonymous visitors may list Profiles.' ); + } + + public function testAnyOtherAnswerIs1x(): void { + + $this->assertSame( [ 'version' => 1, 'reason' => '' ], server::classify( self::owa1Answer( 401 ) ), '1.14 answers the unknown route.' ); + $this->assertSame( 1, server::classify( self::owa1Answer( 403 ) )['version'] ); + $this->assertSame( 1, server::classify( self::owa1Answer( 200 ) )['version'] ); + $this->assertSame( 1, server::classify( self::probeResponse( 200, [], '' ) )['version'], 'Before 1.14, an empty answer.' ); + $this->assertSame( 1, server::classify( self::probeResponse( 404, [ 'content-type' => 'text/html' ], 'Not Found' ) )['version'] ); + $this->assertSame( 1, server::classify( self::probeResponse( 200, [ 'www-authenticate' => 'Bearer realm="OWA"' ], '{}' ) )['version'], 'A challenge without the 401.' ); + $this->assertSame( 1, server::classify( self::probeResponse( 401, [ 'www-authenticate' => 'Basic realm="staging"' ], '401' ) )['version'], 'A proxy\'s login.' ); + $this->assertSame( 1, server::classify( self::probeResponse( 200, [], '{"data":[]}' ) )['version'], 'No error key.' ); + $this->assertSame( 1, server::classify( self::probeResponse( 200, [], '{"data":null,"error":[{"headline":"x"}]}' ) )['version'], '1.x errors are a list.' ); + } + + public function testNoAnswerIdentifiesNothing(): 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' ) ) + ); + + foreach ( [ 500, 502, 503, 504, 408, 429 ] as $code ) { + + $this->assertSame( [ 'version' => 0, 'reason' => "HTTP $code" ], server::classify( self::probeResponse( $code, [], 'down' ) ) ); + } + } + + 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/v2/profiles', $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' ], 1700000000, 'https://owa.example.com/' ); + + $this->assertSame( '2', $stored['owaVersion'] ); + $this->assertSame( [ 'url' => 'https://owa.example.com/', 'version' => 0, 'reason' => 'HTTP 502', 'at' => 1700000000 ], $stored['owaVersionCheck'] ); + } + + public function testANewEndpointThatDoesNotAnswerHasNoVersion(): void { + + $stored = server::applyResult( [ 'owaVersion' => '1' ], 'https://owa2.example.com/', [ 'version' => 0, 'reason' => 'HTTP 502' ], 1, 'https://owa1.example.com/' ); + + $this->assertSame( '', $stored['owaVersion'], 'The version was found at another server.' ); + } + + public function testA1xServerThatBecomes2xFlagsTheNotice(): void { + + $stored = server::applyResult( [ 'owaVersion' => '1', 'apiKey' => 'k', 'authKey' => 'a' ], 'https://owa.example.com/', [ 'version' => 2, 'reason' => '' ], 1, 'https://owa.example.com/' ); + + $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, 'https://owa.example.com/' ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $with_password, 'Nothing to add.' ); + + $fresh = server::applyResult( [ 'owaVersion' => '' ], 'https://owa.example.com/', [ 'version' => 2, 'reason' => '' ], 1, 'https://owa.example.com/' ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $fresh, 'Not an upgrade.' ); + + $back = server::applyResult( $stored, 'https://owa1.example.com/', [ 'version' => 1, 'reason' => '' ], 1, 'https://owa1.example.com/' ); + $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 testSavingA1xEndpointStores1(): void { + + $this->owaServer( self::owa1Answer() ); + + $result = rest::saveSettings( $this->plugin(), [ 'owaEndpoint' => 'https://owa.example.com/' ] ); + + $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] ); + $this->assertSame( '1', $result['server']['version'] ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $this->options['owa_wp'] ); + } + + public function testSavingAnEndpointThatDoesNotAnswerShowsOnlyTheEndpoint(): void { + + $this->owaServer( self::probeResponse( 503, [], '' ) ); + + $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 503', 'checkedAt' => $result['server']['checkedAt'], 'network' => false ], $result['server'] ); + $this->assertSame( [], $result['notices'], 'The server status says it.' ); + } + + public function testMovingToAServerThatDoesNotAnswerDropsTheOldVersion(): void { + + $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa1.example.com/', 'siteId' => 'abc123', 'owaVersionCheck' => [ 'url' => 'https://owa1.example.com/', 'version' => 1, 'reason' => '', 'at' => 1 ] ]; + $this->owaServer( self::probeResponse( 502 ) ); + + rest::saveSettings( $this->plugin(), [ 'owaEndpoint' => 'https://owa2.example.com/' ] ); + + $this->assertSame( '', $this->options['owa_wp']['owaVersion'], 'No 1.x tag against a server never identified.' ); + } + + 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 Server 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 Server 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 Server Endpoint under OWA > Settings.' ], $this->makePlugin( [ 'owaVersion' => '' ] )->setupNotices() ); + $this->assertSame( [ 'The OWA server at https://owa.example.com/ did not answer. Check the OWA Server 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['saved'] ); + $this->assertSame( '2', $result['server']['version'] ); + $this->assertSame( 'k', $this->options['owa_wp']['apiKey'], 'The 1.x key is not deleted.' ); + } + + public function testCheckingAnotherUrlStoresNothing(): void { + + $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa1.example.com/', 'siteId' => 'abc123' ]; + $requests = $this->owaServer( self::owa2Answer() ); + + Actions\expectDone( \owaWp\cache::TAG_CHANGED )->never(); + + $result = rest::checkServer( $this->plugin(), [ 'owaEndpoint' => 'https://owa2.example.com' ] ); + + $this->assertFalse( $result['saved'] ); + $this->assertSame( [ '2', 'https://owa2.example.com/', true ], [ $result['server']['version'], $result['server']['url'], $result['server']['identified'] ], 'The URL as it would be stored.' ); + $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] ); + $this->assertSame( 'https://owa1.example.com/', $this->options['owa_wp']['owaEndpoint'] ); + $urls = array_column( $requests->getArrayCopy(), 0 ); + $this->assertContains( 'https://owa2.example.com/' . server::PROBE_PATH, $urls ); + } + + public function testCheckingA1xUrlOnAFreshInstallStoresNothing(): void { + + $this->owaServer( self::owa1Answer() ); + + $result = rest::checkServer( $this->plugin(), [ 'owaEndpoint' => 'owa.example.com' ] ); + + $this->assertFalse( $result['saved'] ); + $this->assertSame( [ '1', 'https://owa.example.com/', true ], [ $result['server']['version'], $result['server']['url'], $result['server']['identified'] ] ); + $this->assertArrayNotHasKey( 'owa_wp', $this->options ); + } + + public function testCheckingAUrlWithoutOwaSaysSoUnderTheField(): void { + + Functions\when( 'wp_remote_get' )->justReturn( new \WP_Error( 'http_request_failed', 'cURL error 7' ) ); + + $result = rest::checkServer( $this->plugin(), [ 'owaEndpoint' => 'https://nothing.example.com/' ] ); + + $this->assertFalse( $result['saved'] ); + $this->assertNull( $result['server'] ); + $this->assertStringStartsWith( 'No OWA server found at https://nothing.example.com/', $result['error'] ); + } + + public function testCheckingTheSavedUrlWithoutItsSlashChecksTheSavedOne(): void { + + $this->options['owa_wp'] = [ 'owaVersion' => '1', 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123' ]; + $this->owaServer( self::owa1Answer() ); + + $result = rest::checkServer( $this->plugin(), [ 'owaEndpoint' => 'https://owa.example.com' ] ); + + $this->assertTrue( $result['saved'] ); + $this->assertSame( 'https://owa.example.com/', $result['server']['url'] ); + $this->assertSame( 1, $this->options['owa_wp']['owaVersionCheck']['version'], 'Stored, as the daily check does.' ); + } + + 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 testAnUpdateAgainstA1xServerKeeps1(): void { + + // never saved a version, the old default: 1 + $this->options['owa_wp'] = [ 'owaEndpoint' => 'https://owa.example.com/', 'apiKey' => 'k', 'authKey' => 'a', 'siteId' => 'abc123' ]; + $this->owaServer( self::owa1Answer() ); + + Actions\expectDone( \owaWp\cache::TAG_CHANGED )->never(); + + server::onAdminInit( $this->plugin() ); + + $this->assertSame( OWA_WP_VERSION, $this->options[ server::VERSION_OPTION ] ); + $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] ); + $this->assertSame( 1, $this->options['owa_wp']['owaVersionCheck']['version'] ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $this->options['owa_wp'] ); + } + + public function testAnUpdateOfA2xSiteAgainstA2xServerKeeps2(): void { + + $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/', 'appPassword' => self::TOKEN, 'siteId' => 'OWA-9b62dc7ce78a6934' ]; + $this->owaServer( self::owa2Answer() ); + + Actions\expectDone( \owaWp\cache::TAG_CHANGED )->never(); + + server::onAdminInit( $this->plugin() ); + + $this->assertSame( '2', $this->options['owa_wp']['owaVersion'] ); + $this->assertSame( 2, $this->options['owa_wp']['owaVersionCheck']['version'] ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $this->options['owa_wp'] ); + } + + public function testAnUpdateOfASiteSetTo2AgainstA1xServerSwitchesTo1(): void { + + // 2.4 let the user choose 2.x for a 1.x server: its tag did not work + $this->options['owa_wp'] = [ 'owaVersion' => '2', 'owaEndpoint' => 'https://owa.example.com/', 'siteId' => 'abc123' ]; + $this->owaServer( self::owa1Answer() ); + + Actions\expectDone( \owaWp\cache::TAG_CHANGED )->once(); + + $plugin = $this->plugin(); + server::onAdminInit( $plugin ); + + $this->assertSame( '1', $this->options['owa_wp']['owaVersion'] ); + $this->assertArrayNotHasKey( 'owaUpgradeNotice', $this->options['owa_wp'] ); + $this->assertSame( 1, $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..1980cb0 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -36,10 +36,16 @@ protected function setUp(): void { 'is_customize_preview' => false, 'is_multisite' => false, 'get_current_screen' => fn() => null, - // an OWA server at every endpoint: saving one asks for its tracker - 'wp_remote_get' => fn() => [ 'response' => [ 'code' => 200 ] ], + // an OWA 2.x server at every endpoint: saving one asks for its tracker and its version + 'wp_remote_get' => fn( $url = '' ) => str_contains( (string) $url, \owaWp\server::PROBE_PATH ) ? self::owa2Answer() : [ '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"' ], + '{"data":null,"error":"Check the API credentials or this user\'s permissions."}' ); + } + + /** What OWA 1.14 answers the probe: its envelope (401 for a route it does not have). */ + 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/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..273fc8d 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'; @@ -20,10 +20,10 @@ test( 'the network configures each site\'s Profile', async ( { page, browser }, await login( page ); await page.goto( NETWORK_PAGE ); - await expect( page.getByLabel( 'OWA Endpoint' ) ).toBeVisible(); + await expect( page.getByLabel( 'OWA Server Endpoint' ) ).toBeVisible(); await shot( page, testInfo, '01-network-empty' ); - await page.getByLabel( 'OWA Endpoint' ).fill( env( 'OWA_URL' ) ); + await page.getByLabel( 'OWA Server Endpoint' ).fill( env( 'OWA_URL' ) ); await page.getByLabel( 'Application Password' ).fill( env( 'OWA_APP_PASSWORD' ) ); await page.getByLabel( /Network configures each site's Observation Profile/ ).check(); await save.click(); @@ -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,8 +102,8 @@ 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( 'OWA Endpoint' ) ).toHaveCount( 0 ); + await expect( page.getByLabel( 'Observation Profile', { exact: true } ).locator( 'option:checked' ) ).toHaveText( profileLabel( 'https://a.wp.test', 'Site A' ) ); + await expect( page.getByLabel( 'OWA Server Endpoint' ) ).toHaveCount( 0 ); await expect( page.getByLabel( 'Application Password' ) ).toHaveCount( 0 ); await expect( page.getByLabel( '2.x (beta)' ) ).toHaveCount( 0 ); await expect( page.getByText( 'configures this site\'s Observation Profile and has tracking on this site turned off' ) ).toBeVisible(); @@ -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' ); diff --git a/tests/e2e/single.spec.js b/tests/e2e/single.spec.js index 429abf5..842e641 100644 --- a/tests/e2e/single.spec.js +++ b/tests/e2e/single.spec.js @@ -1,9 +1,11 @@ -// 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 checking the OWA server's URL, +// the version found there decides which settings show (2.x here: an +// application password), Save Changes appears once the password is entered, +// 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 +15,52 @@ 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 Server Endpoint' ) ).toBeVisible(); + await expect( page.getByText( 'Enter the URL of your OWA server and check it.' ) ).toBeVisible(); + await expect( save ).toHaveCount( 0 ); + 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 Server Endpoint' ).fill( bare ); + await page.getByRole( 'button', { name: 'Check', exact: true } ).click(); + await expect( field( 'OWA Server 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\/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' ); + // nothing is saved until the password is entered + await expect( save ).toHaveCount( 0 ); + 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 +74,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..56b61d8 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 { canSave, fieldText, isVisible, serverState, setupNotices, shownServer, 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,87 @@ 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' ); +} ); + +const SAVED_2X = { version: '2', url: 'https://owa.example.com/', identified: true, reason: '', checkedAt: 1, network: false }; +const page = ( server, secrets = {} ) => ( { fields: FIELDS, server, secrets } ); + +test( 'the server shown follows the URL in the field', () => { + const payload = page( SAVED_2X ); + const checked = { ...SAVED_2X, version: '1', url: 'https://owa1.example.com/' }; + + expect( shownServer( payload, { owaEndpoint: 'https://owa.example.com/' }, checked ) ).toBe( payload.server ); + expect( shownServer( payload, { owaEndpoint: 'https://owa1.example.com/' }, checked ) ).toBe( checked ); + expect( serverState( shownServer( payload, { owaEndpoint: 'https://owa1.example.com/x' }, checked ) ) ).toBe( 'unchecked' ); + expect( serverState( shownServer( page( { ...SAVED_2X, url: '', version: '' } ), { owaEndpoint: '' }, null ) ) ).toBe( 'none' ); + expect( shownServer( page( { ...SAVED_2X, network: true } ), { owaEndpoint: 'typed' }, null ).network ).toBe( true ); +} ); + +test( 'a fresh install saves once the server is identified and its credentials are entered', () => { + const payload = page( { version: '', url: '', identified: false, reason: '', checkedAt: 0, network: false }, { apiKey: false, authKey: false, appPassword: false } ); + const values = { owaEndpoint: 'https://owa.example.com/' }; + + expect( canSave( payload, { owaEndpoint: '' }, {}, shownServer( payload, { owaEndpoint: '' }, null ) ) ).toBe( false ); + expect( canSave( payload, values, {}, shownServer( payload, values, null ) ) ).toBe( false ); + + const v2 = shownServer( payload, values, SAVED_2X ); + expect( canSave( payload, values, {}, v2 ) ).toBe( false ); + expect( canSave( payload, values, { appPassword: { value: 'A'.repeat( 44 ), clear: false } }, v2 ) ).toBe( true ); + + const v1 = shownServer( payload, values, { ...SAVED_2X, version: '1' } ); + expect( canSave( payload, values, { apiKey: { value: 'k' } }, v1 ) ).toBe( false ); + expect( canSave( payload, values, { apiKey: { value: 'k' }, authKey: { value: 'a' } }, v1 ) ).toBe( true ); + expect( canSave( payload, values, {}, { ...v1, version: '', identified: false, reason: 'HTTP 503' } ) ).toBe( false ); +} ); + +test( 'the saved server saves without new credentials; another needs its own', () => { + const payload = page( { ...SAVED_2X, version: '1' }, { apiKey: true, authKey: true, appPassword: false } ); + const saved = { owaEndpoint: 'https://owa.example.com/' }; + const moved = { owaEndpoint: 'https://owa2.example.com/' }; + + expect( canSave( payload, saved, {}, payload.server ) ).toBe( true ); + expect( canSave( { ...payload, server: SAVED_2X }, saved, {}, SAVED_2X ), 'Upgraded to 2.x, no password yet.' ).toBe( true ); + expect( canSave( payload, moved, {}, { ...SAVED_2X, url: moved.owaEndpoint, version: '1' } ), 'The saved 1.x keys.' ).toBe( true ); + expect( canSave( payload, moved, { apiKey: { clear: true } }, { ...SAVED_2X, url: moved.owaEndpoint, version: '1' } ) ).toBe( false ); + expect( canSave( payload, moved, {}, { ...SAVED_2X, url: moved.owaEndpoint } ), 'A 2.x server needs a password.' ).toBe( false ); + expect( canSave( payload, { owaEndpoint: '' }, {}, shownServer( payload, { owaEndpoint: '' }, null ) ), 'Emptying the endpoint.' ).toBe( true ); +} ); + 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.' } ); + expect( fieldText( { title: 'OWA Server Endpoint', description: 'The URL.', v2: [] }, '2' ) ).toEqual( { title: 'OWA Server 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', () => {