diff --git a/.distignore b/.distignore
index 21c4732..154cc8a 100644
--- a/.distignore
+++ b/.distignore
@@ -13,3 +13,8 @@ phpunit.xml.dist
README.md
composer.json
composer.lock
+
+package.json
+package-lock.json
+/node_modules
+/scripts
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index 1dc1b86..2bff4dd 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -4,6 +4,9 @@ on:
release:
types: [released]
+permissions:
+ contents: write
+
jobs:
deploy_to_wordpress_org:
name: Deploy release
@@ -11,12 +14,14 @@ jobs:
steps:
# Checkout the code
- name: Checkout code
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
# Optional: if we add a build step to the plugin, we can run it here.
# Deploy the plugin to WordPress.org
- name: WordPress plugin deploy
id: deploy
- uses: 10up/action-wordpress-plugin-deploy@stable
+ uses: 10up/action-wordpress-plugin-deploy@54bd289b8525fd23a5c365ec369185f2966529c2 # stable
with:
generate-zip: true
env:
@@ -25,7 +30,7 @@ jobs:
# After the deploy, we also want to create a zip and upload it to the release on Github. We don't want
# users to have to go to the repository to find our plugin :).
- name: Upload release asset
- uses: Shopify/upload-to-release@master
+ uses: Shopify/upload-to-release@d0164d4ca84081447a4c6751d3bae0e834c501de # master
with:
name: ${{ github.event.repository.name }}.zip
path: ${{ steps.deploy.outputs.zip-path }}
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index ba843cf..4b08362 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -70,3 +70,16 @@ jobs:
- name: Lint known plugins file
run: composer lint-known-plugins
+
+ javascript-regressions:
+ name: Admin action regressions
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - name: Setup Node.js
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22'
+ - name: Test exact option names and deletion confirmation
+ run: node --test tests/admin-hardening.test.cjs
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
index a57a11f..df98652 100644
--- a/.github/workflows/security.yml
+++ b/.github/workflows/security.yml
@@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
# Don't run the cronjob in this workflow on forks.
- if: github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository_owner == 'Emilia-Capital')
+ if: github.event_name != 'schedule' || (github.event_name == 'schedule' && github.repository == 'ProgressPlanner/aaa-option-optimizer')
steps:
- name: Checkout code
diff --git a/README.md b/README.md
index cba8259..ba57c24 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,18 @@ starting the name with AAA made sense.
Yes!! Backup your database.
+### Who can view option values?
+
+Every REST route requires `manage_options`. Option values can include API keys, SMTP passwords and licence keys, and the tables return these values to authorized administrators. This also applies to site administrators on multisite. Only enable the plugin where those administrators are trusted to inspect all site options.
+
+### Which actions are protected?
+
+Essential WordPress options, including site URLs, active plugins, the active theme's settings, salts and keys stored in the database, and the current site's roles option, cannot be deleted, created with a false value, or have their autoload state changed through this plugin. Single and bulk deletion require confirmation in the admin screen. Autoload changes preserve the stored value and use WordPress's cache-aware autoload API.
+
+### Why are unused-option recommendations paused?
+
+Tracking stores up to about 10,000 distinct names. The limit is checked without locking, so concurrent requests can push slightly past it. Once it is reached, names already recorded keep counting, but a new name is dropped, and the plugin then marks observations incomplete and pauses unused-option recommendations, because a dropped name could otherwise be reported as unused. Data migrated from older versions is kept in full, even past the limit. A failed tracking write does not pause recommendations; it loses at most that request's counts. Reset tracking to start a fresh observation period.
+
### How can I add recognized plugins?
Please do a pull request via GitHub on [this file](https://github.com/ProgressPlanner/aaa-option-optimizer/blob/develop/known-plugins/known-plugins.json) in the plugin.
@@ -40,3 +52,9 @@ Please do a pull request via GitHub on [this file](https://github.com/ProgressPl
### How can I report security bugs?
You can report security bugs through the Patchstack Vulnerability Disclosure Program. The Patchstack team help validate, triage and handle any security vulnerabilities. [Report a security vulnerability.](https://patchstack.com/database/vdp/aaa-option-optimizer)
+
+## Development checks
+
+Run `composer lint`, `composer check-cs`, `composer phpstan`, and `composer lint-known-plugins` with the development dependencies installed, and `npm run test:hardening:js` for the admin action regressions. The plugin-map validator requires an object keyed by plugin slug, with exactly a non-empty `name` and a non-empty array of unique string `option_prefixes` per entry.
+
+Run `wp eval-file /path/to/aaa-option-optimizer/tests/hardening.php` only on a disposable WordPress installation with an administrator at user ID 1 and `define( 'AAAOO_DISPOSABLE_TEST_SITE', true );` in its configuration. The test creates and deletes fixtures and resets tracking data. It covers REST validation, exact option names, protected options, failed autoload updates, raw-value preservation, malformed sorting, and tracking limits.
diff --git a/composer.json b/composer.json
index be386a0..3d327ce 100644
--- a/composer.json
+++ b/composer.json
@@ -42,7 +42,7 @@
"@php -r \"exit( intval( is_null( json_decode( file_get_contents( './.wordpress-org/blueprints/blueprint.json' ) ) ) ) );\""
],
"lint-known-plugins": [
- "@php -r \"exit( intval( is_null( json_decode( file_get_contents( './known-plugins/known-plugins.json' ) ) ) ) );\""
+ "@php scripts/validate-known-plugins.php"
],
"test": [
"@php ./vendor/phpunit/phpunit/phpunit"
diff --git a/js/admin-script.js b/js/admin-script.js
index d2270b4..306c1aa 100644
--- a/js/admin-script.js
+++ b/js/admin-script.js
@@ -106,7 +106,9 @@ jQuery( document ).ready( function () {
responsive: true,
columns: getColumns( selector ),
rowId( data ) {
- return generateRowId( data.name );
+ return (
+ selector.substring( 1 ) + '-' + generateRowId( data.name )
+ );
},
initComplete() {
this.api().columns( 'source:name' ).every( filterSetup );
@@ -122,6 +124,16 @@ jQuery( document ).ready( function () {
headers: { 'X-WP-Nonce': aaaOptionOptimizer.nonce },
type: 'GET',
dataSrc( json ) {
+ if (
+ json.tracking_limited &&
+ ! jQuery( '#aaa-tracking-limited' ).length
+ ) {
+ jQuery(
+ '
'
+ )
+ .text( aaaOptionOptimizer.i18n.trackingLimited )
+ .insertBefore( selector );
+ }
tableSources[ selector ] = json.sources || [];
return json.data;
},
@@ -444,7 +456,7 @@ jQuery( document ).ready( function () {
`,
];
- return actions.join( '' );
+ return ( row.protected ? actions.slice( 0, 2 ) : actions ).join( '' );
}
/**
@@ -455,6 +467,9 @@ jQuery( document ).ready( function () {
* @return {string} - The HTML for the value column.
*/
function renderNonExistingOptionsColumn( row ) {
+ if ( row.protected ) {
+ return '';
+ }
return `
@@ -471,6 +486,9 @@ jQuery( document ).ready( function () {
* @return {string} - The HTML for the value column.
*/
function renderCheckboxColumn( row, tableId ) {
+ if ( row.protected ) {
+ return '';
+ }
// Build the checkbox id from the sanitized row id, never the raw name, so
// the id and its matching label `for` cannot break out of the markup.
// The same option can be listed in several tables, so prefix the table id to keep it unique.
@@ -494,8 +512,13 @@ jQuery( document ).ready( function () {
response // eslint-disable-line no-unused-vars
) =>
( window.location = `${ window.location.href }&tracking_reset=true` ),
- error: ( response ) =>
- console.error( 'Failed to reset tracking.', response ), // eslint-disable-line no-console
+ error: ( response ) => {
+ // eslint-disable-next-line no-alert
+ alert(
+ response.responseJSON?.message ||
+ aaaOptionOptimizer.i18n.actionFailed
+ );
+ },
} );
} );
@@ -507,8 +530,7 @@ jQuery( document ).ready( function () {
function handleTableActions( e ) {
e.preventDefault();
const button = jQuery( this );
- const table = button.closest( 'table' ).DataTable();
- const optionName = button.data( 'option' );
+ const optionName = button.attr( 'data-option' );
const requestData = { option_name: optionName };
let action = '';
@@ -517,6 +539,14 @@ jQuery( document ).ready( function () {
if ( button.hasClass( 'create-option-false' ) ) {
action = route = 'create-option-false';
} else if ( button.hasClass( 'delete-option' ) ) {
+ if (
+ // eslint-disable-next-line no-alert
+ ! window.confirm(
+ aaaOptionOptimizer.i18n.confirmDelete + '\n' + optionName
+ )
+ ) {
+ return;
+ }
action = route = 'delete-option';
} else {
action = button.hasClass( 'add-autoload' )
@@ -526,6 +556,8 @@ jQuery( document ).ready( function () {
requestData.autoload = action === 'add-autoload' ? 'yes' : 'no';
}
+ const table = button.closest( 'table' ).DataTable();
+
jQuery.ajax( {
url: `${ aaaOptionOptimizer.root }aaa-option-optimizer/v1/${ route }`,
method: 'POST',
@@ -534,12 +566,14 @@ jQuery( document ).ready( function () {
data: requestData,
success: ( response ) =>
updateRowOnSuccess( response, table, optionName, action ),
- error: ( response ) =>
- // eslint-disable-next-line no-console
- console.error(
- `Failed to ${ action } for ${ optionName }.`,
- response
- ),
+ error: ( response ) => {
+ table.ajax.reload( null, false );
+ // eslint-disable-next-line no-alert
+ alert(
+ response.responseJSON?.message ||
+ aaaOptionOptimizer.i18n.actionFailed
+ );
+ },
} );
}
@@ -553,7 +587,9 @@ jQuery( document ).ready( function () {
*/
function updateRowOnSuccess( response, table, optionName, action ) {
// Look the row up by DataTables row ID, not a CSS selector, so option names with special characters still match.
- const row = table.row( '#' + generateRowId( optionName ) );
+ const row = table.row(
+ '#' + table.table().node().id + '-' + generateRowId( optionName )
+ );
if ( action === 'delete-option' || action === 'create-option-false' ) {
row.remove().draw( 'full-hold' );
} else if (
@@ -658,7 +694,19 @@ jQuery( document ).ready( function () {
return;
}
- // For now we only have delete in bulk action.
+ if (
+ bulkAction === 'delete' &&
+ // eslint-disable-next-line no-alert
+ ! window.confirm(
+ aaaOptionOptimizer.i18n.confirmDelete +
+ '\n' +
+ selectedOptions.length +
+ ' ' +
+ aaaOptionOptimizer.i18n.selectedOptions
+ )
+ ) {
+ return;
+ }
const requestData = {
option_names: Array.from( selectedOptions ).map( ( option ) =>
@@ -691,11 +739,7 @@ jQuery( document ).ready( function () {
success: () => {
const dt = table.DataTable();
- requestData.option_names.forEach( ( optionName ) => {
- dt.row( '#' + generateRowId( optionName ) ).remove();
- } );
-
- dt.draw( 'full-hold' );
+ dt.ajax.reload( null, false );
// Clear the select-all checkbox.
table
@@ -703,6 +747,12 @@ jQuery( document ).ready( function () {
.prop( 'checked', false );
},
error: ( response ) => {
+ table.DataTable().ajax.reload( null, false );
+ // eslint-disable-next-line no-alert
+ alert(
+ response.responseJSON?.message ||
+ aaaOptionOptimizer.i18n.actionFailed
+ );
// eslint-disable-next-line no-console
console.error( 'Failed to delete options.', response );
},
@@ -783,8 +833,11 @@ jQuery( document ).ready( function () {
}, 1000 );
}
},
- error() {
- statusText.text( aaaOptionOptimizer.i18n.migrationError );
+ error( response ) {
+ statusText.text(
+ response.responseJSON?.message ||
+ aaaOptionOptimizer.i18n.migrationError
+ );
button.prop( 'disabled', false );
},
} );
diff --git a/package.json b/package.json
index 9aa2ce1..36e1a12 100644
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
"stylelint": "^16.26.1"
},
"scripts": {
+ "test:hardening:js": "node --test tests/admin-hardening.test.cjs",
"format": "wp-scripts format ./assets",
"lint:css": "wp-scripts lint-style \"**/*.css\"",
"lint:css:fix": "npm run lint:css -- --fix",
diff --git a/scripts/validate-known-plugins.php b/scripts/validate-known-plugins.php
new file mode 100644
index 0000000..6a1863c
--- /dev/null
+++ b/scripts/validate-known-plugins.php
@@ -0,0 +1,72 @@
+ $plugin ) {
+ if ( ! preg_match( '/^[a-z0-9][a-z0-9_-]*$/D', (string) $slug ) ) {
+ $errors[] = "Invalid plugin slug: $slug";
+ }
+ if ( ! $plugin instanceof \stdClass ) {
+ $errors[] = "$slug must be an object.";
+ continue;
+ }
+ $keys = array_keys( get_object_vars( $plugin ) );
+ sort( $keys );
+ if ( [ 'name', 'option_prefixes' ] !== $keys ) {
+ $errors[] = "$slug must contain exactly name and option_prefixes.";
+ }
+ if ( ! isset( $plugin->name ) || ! is_string( $plugin->name ) || '' === trim( $plugin->name ) ) {
+ $errors[] = "$slug.name must be a non-empty string.";
+ }
+ if ( ! isset( $plugin->option_prefixes ) || ! is_array( $plugin->option_prefixes ) || ! $plugin->option_prefixes ) {
+ $errors[] = "$slug.option_prefixes must be a non-empty array.";
+ continue;
+ }
+ $seen = [];
+ foreach ( $plugin->option_prefixes as $prefix ) {
+ if ( ! is_string( $prefix ) || '' === trim( $prefix ) || preg_match( '/[\x00-\x1f\x7f]/', $prefix ) || preg_match_all( '/./us', $prefix ) > 191 ) {
+ $errors[] = "$slug has an invalid option prefix.";
+ continue;
+ }
+ if ( in_array( $prefix, $seen, true ) ) {
+ $errors[] = "$slug has a duplicate option prefix.";
+ }
+ $seen[] = $prefix;
+ }
+ }
+ }
+
+ if ( $errors ) {
+ fwrite( STDERR, implode( "\n", $errors ) . "\n" );
+ exit( 1 );
+ }
+ fwrite( STDOUT, "Known plugins schema is valid.\n" );
+}
+
+validate_known_plugins( $argv[1] ?? dirname( __DIR__ ) . '/known-plugins/known-plugins.json' );
diff --git a/src/class-admin-page.php b/src/class-admin-page.php
index 709ec49..e786bf9 100644
--- a/src/class-admin-page.php
+++ b/src/class-admin-page.php
@@ -7,6 +7,10 @@
namespace Progress_Planner\OptionOptimizer;
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
/**
* Admin page functionality for AAA Autoload Optimizer.
*/
@@ -197,9 +201,13 @@ public function enqueue_scripts( $hook ) {
'showValue' => \esc_html__( 'Show', 'aaa-option-optimizer' ),
'addAutoload' => \esc_html__( 'Add autoload', 'aaa-option-optimizer' ),
'removeAutoload' => \esc_html__( 'Remove autoload', 'aaa-option-optimizer' ),
+ 'confirmDelete' => \__( 'Permanently delete the selected option(s)? This cannot be undone. Make sure you have a database backup.', 'aaa-option-optimizer' ),
+ 'selectedOptions' => \__( 'options selected', 'aaa-option-optimizer' ),
+ 'trackingLimited' => \__( 'Tracking is incomplete. Reset tracking and collect fresh observations before reviewing unused options.', 'aaa-option-optimizer' ),
+ 'actionFailed' => \__( 'The action could not be completed.', 'aaa-option-optimizer' ),
'deleteOption' => \esc_html__( 'Delete', 'aaa-option-optimizer' ),
'createOptionFalse' => \esc_html__( 'Create option with value false', 'aaa-option-optimizer' ),
- 'noAutoloadedButNotUsed' => \esc_html__( 'All autoloaded options are in use.', 'aaa-option-optimizer' ),
+ 'noAutoloadedButNotUsed' => \esc_html__( 'No unused autoloaded options to display.', 'aaa-option-optimizer' ),
'noUsedButNotAutoloaded' => \esc_html__( 'All options that are used are autoloaded.', 'aaa-option-optimizer' ),
'noOptionsSelected' => \esc_html__( 'No options selected.', 'aaa-option-optimizer' ),
'bulkActions' => \esc_html__( 'Bulk actions', 'aaa-option-optimizer' ),
@@ -272,6 +280,11 @@ public function render_admin_page_ajax() {
?>
+
+
+
+
+
diff --git a/src/class-database.php b/src/class-database.php
index 962bc1d..5dba778 100644
--- a/src/class-database.php
+++ b/src/class-database.php
@@ -7,6 +7,10 @@
namespace Progress_Planner\OptionOptimizer;
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
/**
* Handles custom database table for tracking options.
*/
@@ -19,6 +23,35 @@ class Database {
*/
const TABLE_NAME = 'option_optimizer_tracked';
+ /**
+ * Maximum retained option names, including missing options.
+ *
+ * @var int
+ */
+ const MAX_TRACKED_OPTIONS = 10000;
+
+ /**
+ * Record that observations have been dropped until the next reset.
+ *
+ * @return void
+ */
+ public static function mark_tracking_limited() {
+ \update_option( 'aaa_option_optimizer_tracking_limited', true, false );
+ }
+
+ /**
+ * Whether unused-option recommendations would be incomplete.
+ *
+ * True only after an observation was actually dropped because tracking storage was full,
+ * or a single request read more names than can be stored. Transient write failures don't
+ * set it: they lose at most one request's counts, which the next request records again.
+ *
+ * @return bool
+ */
+ public static function is_tracking_limited() {
+ return (bool) \get_option( 'aaa_option_optimizer_tracking_limited', false );
+ }
+
/**
* Get the full table name with prefix.
*
@@ -123,7 +156,7 @@ public static function get_migration_status() {
*
* Processes in chunks to avoid timeouts on slow hosts with large datasets.
*
- * @return array{success: bool, remaining: int, total: int}
+ * @return array{success: bool, remaining: int, total: int, message?: string}
*/
public static function migrate_chunk() {
$option_data = \get_option( 'option_optimizer' );
@@ -153,13 +186,22 @@ public static function migrate_chunk() {
// Take a chunk of options to migrate.
$chunk = \array_slice( $option_data['used_options'], 0, self::MIGRATION_CHUNK_SIZE, true );
- // Batch insert chunk to custom table.
- self::batch_insert( $chunk );
-
- // Remove migrated options from the array.
- $option_data['used_options'] = \array_slice( $option_data['used_options'], self::MIGRATION_CHUNK_SIZE, null, true );
-
- \update_option( 'option_optimizer', $option_data, false );
+ // Legacy observations were already stored in full, so they are migrated without the
+ // capacity limit; otherwise a large legacy dataset could never finish migrating.
+ // Remove only committed observations, so a failed write can be retried.
+ $written = self::batch_insert( $chunk, 500, false );
+ if ( false === $written ) {
+ return [
+ 'success' => false,
+ 'remaining' => count( $option_data['used_options'] ),
+ 'total' => (int) $total,
+ 'message' => \__( 'Tracking data could not be saved. Please retry the migration.', 'aaa-option-optimizer' ),
+ ];
+ }
+ if ( $written ) {
+ $option_data['used_options'] = array_diff_key( $option_data['used_options'], $written );
+ \update_option( 'option_optimizer', $option_data, false );
+ }
$remaining = \count( $option_data['used_options'] );
@@ -186,23 +228,97 @@ public static function migrate_chunk() {
* VALUES list; with per-request access order, concurrent requests lock
* the same rows in different orders and deadlock each other.
*
+ * The capacity limit is soft: it is checked without a lock, so concurrent
+ * requests near the limit can each add their new names and overshoot it
+ * slightly. Taking a global lock on every request costs far more than a
+ * few extra rows, and isn't portable beyond MySQL.
+ *
* @param array
$options Array of option_name => count.
* @param int $chunk_size Number of options per query. Default 500.
+ * @param bool $enforce_cap Whether new names are limited to MAX_TRACKED_OPTIONS. Default true.
*
- * @return void
+ * @return array|false Committed observations, or false on a write failure.
*/
- public static function batch_insert( $options, $chunk_size = 500 ) {
+ public static function batch_insert( $options, $chunk_size = 500, $enforce_cap = true ) {
+ global $wpdb;
if ( empty( $options ) ) {
- return;
+ return [];
}
- // SORT_STRING: numeric option names become int keys, keep one total order.
\ksort( $options, SORT_STRING );
+ $chunk_size = max( 1, min( 500, (int) $chunk_size ) );
+ $accepted = $options;
- // A deadlock rolls back the whole transaction, so one retry can't double count.
- if ( ! self::write_chunks( $options, $chunk_size ) && self::last_error_is_deadlock() ) {
- self::write_chunks( $options, $chunk_size );
+ if ( $enforce_cap ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', self::get_table_name() ) );
+ if ( null === $count ) {
+ return false;
+ }
+ $remaining = self::MAX_TRACKED_OPTIONS - (int) $count;
+
+ // Below the limit with room for every name: no need to tell new names from existing ones.
+ if ( count( $options ) > $remaining ) {
+ $existing = self::get_existing_names( array_keys( $options ) );
+ if ( false === $existing ) {
+ return false;
+ }
+ $accepted = [];
+ $dropped = false;
+ foreach ( $options as $name => $accesses ) {
+ if ( isset( $existing[ $name ] ) ) {
+ $accepted[ $name ] = $accesses;
+ } elseif ( $remaining > 0 ) {
+ $accepted[ $name ] = $accesses;
+ --$remaining;
+ } else {
+ $dropped = true;
+ }
+ }
+ if ( $dropped ) {
+ self::mark_tracking_limited();
+ }
+ }
+ }
+
+ if ( $accepted && ! self::write_chunks( $accepted, $chunk_size ) ) {
+ if ( ! self::last_error_is_deadlock() || ! self::write_chunks( $accepted, $chunk_size ) ) {
+ return false;
+ }
}
+ return $accepted;
+ }
+
+ /**
+ * Find which submitted names already have a row, using the table's own collation.
+ *
+ * The submitted names are joined against the table in SQL, so a name that differs from a
+ * stored row only by case or accents counts as existing, exactly as the primary key and
+ * ON DUPLICATE KEY UPDATE treat it. Comparing the returned rows in PHP would not.
+ *
+ * @param string[] $names Submitted option names.
+ *
+ * @return array|false Submitted names that match a row, or false on a query failure.
+ */
+ private static function get_existing_names( array $names ) {
+ global $wpdb;
+
+ $table = self::get_table_name();
+ $existing = [];
+ foreach ( array_chunk( $names, 500 ) as $chunk ) {
+ $selects = implode( ' UNION ALL ', array_fill( 0, count( $chunk ), 'SELECT %s AS n' ) );
+ // The table must come first: for non-ASCII names wpdb parses the first FROM to check the
+ // table's charset, and a leading subquery makes that check fail the whole query.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Placeholders are generated above.
+ $found = $wpdb->get_col( $wpdb->prepare( "SELECT s.n FROM %i t INNER JOIN ($selects) s ON t.option_name = s.n", array_merge( [ $table ], array_map( 'strval', $chunk ) ) ) );
+ if ( $wpdb->last_error ) {
+ return false;
+ }
+ foreach ( $found as $name ) {
+ $existing[ $name ] = true;
+ }
+ }
+ return $existing;
}
/**
@@ -211,6 +327,7 @@ public static function batch_insert( $options, $chunk_size = 500 ) {
* @param array $options Array of option_name => count, already sorted.
* @param int $chunk_size Number of options per query.
*
+ * @phpstan-impure
* @return bool Whether the transaction was committed.
*/
private static function write_chunks( $options, $chunk_size ) {
@@ -222,7 +339,9 @@ private static function write_chunks( $options, $chunk_size ) {
// recognizes it as a transaction and skips caching — `BEGIN` slips past its
// regex and triggers a fatal in wpdb::load_col_info() on the boolean result.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query( 'START TRANSACTION' );
+ if ( false === $wpdb->query( 'START TRANSACTION' ) ) {
+ return false;
+ }
foreach ( array_chunk( $options, $chunk_size, true ) as $chunk ) {
$values = [];
@@ -250,7 +369,12 @@ private static function write_chunks( $options, $chunk_size ) {
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- return false !== $wpdb->query( 'COMMIT' );
+ if ( false === $wpdb->query( 'COMMIT' ) ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->query( 'ROLLBACK' );
+ return false;
+ }
+ return true;
}
/**
@@ -275,7 +399,7 @@ public static function get_tracked_options() {
$table_name = self::get_table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe (from constant).
- $results = $wpdb->get_results( "SELECT option_name, access_count FROM {$table_name}", ARRAY_A );
+ $results = $wpdb->get_results( $wpdb->prepare( 'SELECT option_name, access_count FROM %i', $table_name ), ARRAY_A );
if ( empty( $results ) ) {
return [];
@@ -300,7 +424,7 @@ public static function get_tracked_option_keys() {
$table_name = self::get_table_name();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe (from constant).
- $option_names = $wpdb->get_col( "SELECT option_name FROM {$table_name}" );
+ $option_names = $wpdb->get_col( $wpdb->prepare( 'SELECT option_name FROM %i', $table_name ) );
if ( empty( $option_names ) ) {
return [];
@@ -312,14 +436,15 @@ public static function get_tracked_option_keys() {
/**
* Clear all tracked options from the table.
*
- * @return void
+ * @return bool Whether tracking data and the incomplete flag were cleared.
*/
public static function clear_tracked_options() {
global $wpdb;
-
- $table_name = self::get_table_name();
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe (from constant).
- $wpdb->query( "TRUNCATE TABLE {$table_name}" );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ if ( false === $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', self::get_table_name() ) ) ) {
+ return false;
+ }
+ \delete_option( 'aaa_option_optimizer_tracking_limited' );
+ return ! \get_option( 'aaa_option_optimizer_tracking_limited', false );
}
}
diff --git a/src/class-map-plugin-to-options.php b/src/class-map-plugin-to-options.php
index 799d8fe..b86de41 100644
--- a/src/class-map-plugin-to-options.php
+++ b/src/class-map-plugin-to-options.php
@@ -7,6 +7,10 @@
namespace Progress_Planner\OptionOptimizer;
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
/**
* Class Map_Plugin_To_Options
*
diff --git a/src/class-plugin.php b/src/class-plugin.php
index 0446277..f768f24 100644
--- a/src/class-plugin.php
+++ b/src/class-plugin.php
@@ -7,6 +7,10 @@
namespace Progress_Planner\OptionOptimizer;
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
/**
* Core functionality of AAA Autoload Optimizer.
*/
@@ -34,12 +38,19 @@ class Plugin {
protected $is_processing = false;
/**
- * Whether the plugin should reset the option_optimizer data.
+ * Whether a successful reset should suppress tracking writes for this request.
*
* @var boolean
*/
protected $should_reset = false;
+ /**
+ * Whether the request exceeded the observation budget.
+ *
+ * @var bool
+ */
+ protected $tracking_limited = false;
+
/**
* Initializes the plugin.
*
@@ -91,14 +102,18 @@ public function register_hooks() {
}
/**
- * Sets the 'should_reset' property.
+ * Reset tracking immediately and suppress this request's shutdown write.
*
- * @param boolean $should_reset Whether the plugin should reset the option_optimizer data.
+ * @param boolean $should_reset Whether a successful reset should suppress tracking writes for this request.
*
- * @return void
+ * @return bool Whether the reset succeeded.
*/
public function reset( $should_reset = true ) {
+ if ( $should_reset && ! Database::clear_tracked_options() ) {
+ return false;
+ }
$this->should_reset = $should_reset;
+ return true;
}
/**
@@ -159,6 +174,12 @@ public function monitor_option_accesses_pre_option( $pre, $option_name ) {
*/
protected function add_option_usage( $option_name ) {
if ( ! array_key_exists( $option_name, $this->accessed_options ) ) {
+ // Only a request reading more names than storage can hold is capped; reaching this means
+ // the observation really is incomplete.
+ if ( count( $this->accessed_options ) >= Database::MAX_TRACKED_OPTIONS ) {
+ $this->tracking_limited = true;
+ return;
+ }
// Only validate the first access in a request, repeat accesses are already known to be valid.
if ( ! $this->is_trackable_option_name( $option_name ) ) {
return;
@@ -204,16 +225,19 @@ protected function is_trackable_option_name( $option_name ) {
*/
public function update_tracked_options() {
// phpcs:ignore WordPress.Security.NonceVerification -- not doing anything.
- if ( isset( $_GET['page'] ) && $_GET['page'] === 'aaa-option-optimizer' ) {
+ if ( \is_admin() && \current_user_can( 'manage_options' ) && isset( $_GET['page'] ) && $_GET['page'] === 'aaa-option-optimizer' ) {
return;
}
- // Handle reset.
+ // A successful synchronous reset must not be undone by shutdown tracking.
if ( $this->should_reset ) {
- Database::clear_tracked_options();
return;
}
+ if ( $this->tracking_limited ) {
+ Database::mark_tracking_limited();
+ }
+
// Write accessed options directly to the custom table.
if ( ! empty( $this->accessed_options ) ) {
Database::batch_insert( $this->accessed_options );
diff --git a/src/class-protected-options.php b/src/class-protected-options.php
new file mode 100644
index 0000000..25b100c
--- /dev/null
+++ b/src/class-protected-options.php
@@ -0,0 +1,248 @@
+|null
+ */
+ private static $static_names = null;
+
+ /**
+ * Lowercased protected names, keyed for lookups.
+ *
+ * Names that depend on the current site (roles prefix, active theme) are added per call so
+ * the map stays correct after switch_to_blog() or a theme switch within the request.
+ *
+ * @return array
+ */
+ private static function names() {
+ global $wpdb;
+
+ if ( null === self::$static_names ) {
+ $names = self::core_options();
+ $names[] = 'alloptions';
+ $names[] = 'notoptions';
+ $names[] = 'option_optimizer';
+ $names[] = 'aaa_option_optimizer_tracking_limited';
+
+ self::$static_names = array_fill_keys( array_map( 'strtolower', $names ), true );
+ }
+
+ $names = self::$static_names;
+ $names[ strtolower( $wpdb->prefix . 'user_roles' ) ] = true;
+ $names[ strtolower( 'theme_mods_' . \get_stylesheet() ) ] = true;
+ return $names;
+ }
+
+
+ /**
+ * Check core, blog-specific roles, the active theme's mods, and this plugin's own settings.
+ *
+ * @param string $option_name Option name.
+ * @return bool
+ */
+ public static function is_protected( $option_name ) {
+ return isset( self::names()[ strtolower( $option_name ) ] );
+ }
+
+ /**
+ * Resolve database collation aliases before checking a mutation.
+ *
+ * @param string $option_name Submitted option name.
+ * @return bool
+ */
+ public static function is_mutation_protected( $option_name ) {
+ return [] !== self::get_mutation_protected( [ $option_name ] );
+ }
+
+ /**
+ * Return the submitted names that are protected, directly or through a collation alias.
+ *
+ * Resolves every name with a single query, so bulk actions don't run one query per name.
+ *
+ * @param string[] $option_names Submitted option names.
+ * @return string[] Protected submitted names.
+ */
+ public static function get_mutation_protected( array $option_names ) {
+ global $wpdb;
+
+ $protected = array_values( array_filter( $option_names, [ self::class, 'is_protected' ] ) );
+ if ( $protected ) {
+ return $protected;
+ }
+ if ( ! $option_names ) {
+ return [];
+ }
+
+ $slots = implode( ',', array_fill( 0, count( $option_names ), '%s' ) );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Placeholders are generated above.
+ $stored = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name IN ($slots)", array_values( $option_names ) ) );
+
+ // The database matched these rows by collation, so the stored name stands in for the submitted one.
+ return array_values( array_filter( $stored, [ self::class, 'is_protected' ] ) );
+ }
+}
diff --git a/src/class-rest.php b/src/class-rest.php
index f0c61cf..8076b58 100644
--- a/src/class-rest.php
+++ b/src/class-rest.php
@@ -7,10 +7,16 @@
namespace Progress_Planner\OptionOptimizer;
+if ( ! defined( 'ABSPATH' ) ) {
+ exit;
+}
+
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
+// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Core REST authentication checks cookie nonces; application passwords need no nonce.
+
/**
* REST functionality of AAA Autoload Optimizer.
*/
@@ -34,6 +40,75 @@ public function register_hooks() {
add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
}
+ /**
+ * Describe an option identifier without changing its contents.
+ *
+ * @return array
+ */
+ protected function get_option_name_arg() {
+ return [
+ 'required' => true,
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 191,
+ 'validate_callback' => [ $this, 'validate_option_name' ],
+ ];
+ }
+
+ /**
+ * Reject identifiers that WordPress would trim or that cannot exist.
+ *
+ * @param mixed $value Submitted identifier.
+ * @return bool
+ */
+ public function validate_option_name( $value ) {
+ return is_string( $value ) && '' !== $value && trim( $value ) === $value
+ && false === strpos( $value, "\0" ) && mb_strlen( $value ) <= 191;
+ }
+
+ /**
+ * Describe a bounded list of exact option identifiers.
+ *
+ * @return array
+ */
+ protected function get_option_names_arg() {
+ return [
+ 'required' => true,
+ 'type' => 'array',
+ 'minItems' => 1,
+ 'maxItems' => 500,
+ 'items' => [
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 191,
+ ],
+ 'validate_callback' => function ( $value ) {
+ if ( ! is_array( $value ) || ! $value || count( $value ) > 500 || array_keys( $value ) !== range( 0, count( $value ) - 1 ) ) {
+ return false;
+ }
+ foreach ( $value as $name ) {
+ if ( ! $this->validate_option_name( $name ) ) {
+ return false;
+ }
+ }
+ return true;
+ },
+ ];
+ }
+
+ /**
+ * Describe supported autoload states.
+ *
+ * @return array
+ */
+ protected function get_autoload_arg() {
+ return [
+ 'required' => true,
+ 'type' => 'string',
+ 'enum' => [ 'yes', 'on', 'no', 'off', 'auto', 'auto-on', 'auto-off' ],
+ ];
+ }
+
/**
* Register the REST API routes.
*
@@ -50,14 +125,8 @@ public function register_rest_routes() {
return current_user_can( 'manage_options' );
},
'args' => [
- 'option_name' => [
- 'required' => true,
- 'sanitize_callback' => 'sanitize_text_field',
- ],
- 'autoload' => [
- 'required' => true,
- 'sanitize_callback' => 'sanitize_text_field',
- ],
+ 'option_name' => $this->get_option_name_arg(),
+ 'autoload' => $this->get_autoload_arg(),
],
]
);
@@ -72,10 +141,7 @@ public function register_rest_routes() {
return current_user_can( 'manage_options' );
},
'args' => [
- 'option_name' => [
- 'required' => true,
- 'sanitize_callback' => 'sanitize_text_field',
- ],
+ 'option_name' => $this->get_option_name_arg(),
],
]
);
@@ -90,10 +156,7 @@ public function register_rest_routes() {
return current_user_can( 'manage_options' );
},
'args' => [
- 'option_name' => [
- 'required' => true,
- 'sanitize_callback' => 'sanitize_text_field',
- ],
+ 'option_name' => $this->get_option_name_arg(),
],
]
);
@@ -167,6 +230,9 @@ public function register_rest_routes() {
'permission_callback' => function () {
return current_user_can( 'manage_options' );
},
+ 'args' => [
+ 'option_names' => $this->get_option_names_arg(),
+ ],
]
);
@@ -179,6 +245,10 @@ public function register_rest_routes() {
'permission_callback' => function () {
return current_user_can( 'manage_options' );
},
+ 'args' => [
+ 'option_names' => $this->get_option_names_arg(),
+ 'autoload' => $this->get_autoload_arg(),
+ ],
]
);
@@ -201,7 +271,9 @@ public function register_rest_routes() {
* @return \WP_Error|\WP_REST_Response
*/
public function reset_stats() {
- Plugin::get_instance()->reset();
+ if ( ! Plugin::get_instance()->reset() ) {
+ return new \WP_Error( 'tracking_reset_failed', \__( 'Tracking could not be reset. Please try again.', 'aaa-option-optimizer' ), [ 'status' => 503 ] );
+ }
return new \WP_REST_Response( [ 'success' => true ], 200 );
}
@@ -212,7 +284,7 @@ public function reset_stats() {
*/
public function migrate_chunk() {
$result = Database::migrate_chunk();
- return new \WP_REST_Response( $result, 200 );
+ return new \WP_REST_Response( $result, $result['success'] ? 200 : 503 );
}
/**
@@ -228,12 +300,13 @@ public function get_all_options() {
$options = $wpdb->get_results( "SELECT option_name, option_value, autoload FROM $wpdb->options" );
foreach ( $options as $option ) {
$output[] = [
- 'name' => $option->option_name,
- 'plugin' => $this->get_plugin_name( $option->option_name ),
- 'value' => $option->option_value,
- 'size' => $this->get_length( $option->option_value ),
- 'raw_size' => strlen( $option->option_value ),
- 'autoload' => $option->autoload,
+ 'name' => $option->option_name,
+ 'protected' => Protected_Options::is_protected( $option->option_name ),
+ 'plugin' => $this->get_plugin_name( $option->option_name ),
+ 'value' => $option->option_value,
+ 'size' => $this->get_length( $option->option_value ),
+ 'raw_size' => strlen( $option->option_value ),
+ 'autoload' => $option->autoload,
];
}
return new \WP_REST_Response( [ 'data' => $output ], 200 );
@@ -245,8 +318,18 @@ public function get_all_options() {
* @return \WP_Error|\WP_REST_Response
*/
public function get_unused_options() {
- if ( ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) || ! \wp_verify_nonce( \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' ) ) {
- return new \WP_REST_Response( [ 'error' => 'Invalid nonce' ], 403 );
+ if ( Database::is_tracking_limited() ) {
+ return new \WP_REST_Response(
+ [
+ 'draw' => intval( $_GET['draw'] ?? 0 ),
+ 'recordsTotal' => 0,
+ 'recordsFiltered' => 0,
+ 'data' => [],
+ 'sources' => [],
+ 'tracking_limited' => true,
+ ],
+ 200
+ );
}
global $wpdb;
@@ -308,24 +391,18 @@ public function get_unused_options() {
$response_data = [];
if ( ! empty( $paged_option_names ) ) {
- $placeholders = implode( ',', array_fill( 0, count( $paged_option_names ), '%s' ) );
- $value_query = "
- SELECT option_name, option_value
- FROM {$wpdb->options}
- WHERE option_name IN ( {$placeholders} )
- ";
-
- $results = $wpdb->get_results( $wpdb->prepare( $value_query, ...$paged_option_names ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
+ $results = $this->get_option_rows( $paged_option_names );
// Format output.
foreach ( $results as $row ) {
$response_data[] = [
- 'name' => $row->option_name,
- 'plugin' => $this->get_plugin_name( $row->option_name ),
- 'value' => $row->option_value,
- 'size' => $this->get_length( $row->option_value ),
- 'raw_size' => strlen( $row->option_value ),
- 'autoload' => 'yes',
+ 'name' => $row->option_name,
+ 'protected' => Protected_Options::is_protected( $row->option_name ),
+ 'plugin' => $this->get_plugin_name( $row->option_name ),
+ 'value' => $row->option_value,
+ 'size' => $this->get_length( $row->option_value ),
+ 'raw_size' => strlen( $row->option_value ),
+ 'autoload' => 'yes',
];
}
@@ -357,13 +434,6 @@ public function get_unused_options() {
* @return \WP_Error|\WP_REST_Response
*/
public function get_used_not_autoloaded_options() {
- if (
- ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) ||
- ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' )
- ) {
- return new \WP_REST_Response( [ 'error' => 'Invalid nonce' ], 403 );
- }
-
global $wpdb;
// Load used options from custom table (with counts).
@@ -447,25 +517,18 @@ function ( $option_name ) use ( $search ) {
$response_data = [];
- // $paged_option_names is not empty.
- // Fetch values directly from DB without using get_option().
- $placeholders = implode( ',', array_fill( 0, count( $paged_option_names ), '%s' ) );
- $sql = "
- SELECT option_name, option_value
- FROM {$wpdb->options}
- WHERE option_name IN ( {$placeholders} )"; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
-
- $results = $wpdb->get_results( $wpdb->prepare( $sql, ...$paged_option_names ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ $results = $this->get_option_rows( $paged_option_names );
foreach ( $results as $row ) {
$response_data[] = [
- 'name' => $row->option_name,
- 'plugin' => $this->get_plugin_name( $row->option_name ),
- 'value' => maybe_serialize( $row->option_value ),
- 'size' => $this->get_length( $row->option_value ),
- 'raw_size' => strlen( $row->option_value ),
- 'autoload' => 'no',
- 'count' => $used_options[ $row->option_name ] ?? 0,
+ 'name' => $row->option_name,
+ 'protected' => Protected_Options::is_protected( $row->option_name ),
+ 'plugin' => $this->get_plugin_name( $row->option_name ),
+ 'value' => $row->option_value,
+ 'size' => $this->get_length( $row->option_value ),
+ 'raw_size' => strlen( $row->option_value ),
+ 'autoload' => 'no',
+ 'count' => $used_options[ $row->option_name ] ?? 0,
];
}
@@ -495,10 +558,6 @@ function ( $option_name ) use ( $search ) {
* @return \WP_Error|\WP_REST_Response
*/
public function get_options_that_do_not_exist() {
- if ( ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) || ! wp_verify_nonce( \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' ) ) {
- return new \WP_REST_Response( [ 'error' => 'Invalid nonce' ], 403 );
- }
-
global $wpdb;
// Load used options from custom table (with counts).
@@ -544,15 +603,7 @@ public function get_options_that_do_not_exist() {
}
// Check which of them actually exist in the options table.
- $option_names = array_keys( $non_autoloaded_keys );
- $placeholders = implode( ',', array_fill( 0, count( $option_names ), '%s' ) );
-
- $existing_option_names = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->prepare(
- "SELECT option_name FROM {$wpdb->options} WHERE option_name IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
- ...$option_names
- )
- );
+ $existing_option_names = array_column( $this->get_option_rows( array_keys( $non_autoloaded_keys ), false ), 'option_name' );
$existing_keys = array_fill_keys( $existing_option_names, true );
// Build array of non-existing options (before any filtering).
@@ -560,10 +611,11 @@ public function get_options_that_do_not_exist() {
foreach ( $non_autoloaded_keys as $option => $count ) {
if ( ! isset( $existing_keys[ $option ] ) ) {
$non_existing_options[ $option ] = [
- 'name' => $option,
+ 'name' => (string) $option,
+ 'protected' => Protected_Options::is_protected( (string) $option ),
'plugin' => $this->get_plugin_name( $option ),
'count' => $count,
- 'option_name' => $option,
+ 'option_name' => (string) $option,
];
}
}
@@ -624,49 +676,49 @@ function ( $row ) use ( $search ) {
);
}
+ /**
+ * Fetch option rows in bounded queries.
+ *
+ * @param array $names Option identifiers.
+ * @param bool $include_values Whether values are needed.
+ * @return object[]
+ */
+ private function get_option_rows( array $names, $include_values = true ) {
+ global $wpdb;
+ $rows = [];
+ $columns = $include_values ? 'option_name, option_value' : 'option_name';
+ foreach ( array_chunk( $names, 500 ) as $chunk ) {
+ $slots = implode( ',', array_fill( 0, count( $chunk ), '%s' ) );
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
+ $rows = array_merge( $rows, $wpdb->get_results( $wpdb->prepare( "SELECT $columns FROM {$wpdb->options} WHERE option_name IN ($slots) ORDER BY option_name", $chunk ) ) );
+ }
+ return $rows;
+ }
+
/**
* Update autoload status of an option.
*
- * @param \WP_REST_Request $request The REST request object.
+ * @param \WP_REST_Request> $request The REST request object.
*
* @return \WP_Error|\WP_REST_Response
*/
public function update_option_autoload( $request ) {
- $option_name = $request['option_name'];
- $autoload = $request['autoload'];
- $option_value = get_option( $option_name );
-
- if ( ! in_array( $autoload, [ 'yes', 'on', 'no', 'off','auto', 'auto-on', 'auto-off' ], true ) ) {
- return new \WP_Error( 'invalid_autoload_value', 'Invalid autoload value', [ 'status' => 400 ] );
- }
-
- if ( false === $option_value ) {
- return new \WP_Error( 'option_not_found', 'Option does not exist', [ 'status' => 404 ] );
- }
-
- delete_option( $option_name );
- $autoload_values = \wp_autoload_values_to_autoload();
- $bool_autoload = false;
- if ( in_array( $autoload, $autoload_values, true ) ) {
- $bool_autoload = true;
- }
- $succeeded = add_option( $option_name, $option_value, '', $bool_autoload );
-
- if ( ! $succeeded ) {
- return new \WP_Error( 'update_failed', 'Updating the option failed', [ 'status' => 400 ] );
- }
- return new \WP_REST_Response( [ 'success' => true ], 200 );
+ return $this->update_autoload( [ $request['option_name'] ], $request['autoload'] );
}
/**
* Delete an option.
*
- * @param \WP_REST_Request $request The REST request object.
+ * @param \WP_REST_Request> $request The REST request object.
*
* @return \WP_REST_Response|\WP_Error
*/
public function delete_option( $request ) {
$option_name = $request['option_name'];
+ if ( Protected_Options::is_mutation_protected( $option_name ) ) {
+ return new \WP_Error( 'option_protected', 'Option is protected', [ 'status' => 403 ] );
+ }
+
if ( delete_option( $option_name ) ) {
return new \WP_REST_Response( [ 'success' => true ], 200 );
}
@@ -676,18 +728,31 @@ public function delete_option( $request ) {
/**
* Delete multiple options.
*
- * @param \WP_REST_Request $request The REST request object.
+ * @param \WP_REST_Request> $request The REST request object.
*
* @return \WP_Error|\WP_REST_Response
*/
public function delete_options( $request ) {
- if ( ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) || ! \wp_verify_nonce( \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' ) ) {
- return new \WP_REST_Response( [ 'error' => 'Invalid nonce' ], 403 );
- }
-
$option_names = $request['option_names'];
- foreach ( $option_names as $option_name ) {
- delete_option( $option_name );
+ // Preflight the entire batch before deleting anything.
+ if ( Protected_Options::get_mutation_protected( $option_names ) ) {
+ return new \WP_Error( 'option_protected', 'Option is protected', [ 'status' => 403 ] );
+ }
+ $failed = [];
+ foreach ( array_unique( $option_names ) as $option_name ) {
+ if ( ! delete_option( $option_name ) ) {
+ $failed[] = $option_name;
+ }
+ }
+ if ( $failed ) {
+ return new \WP_Error(
+ 'delete_failed',
+ 'Some options could not be deleted',
+ [
+ 'status' => 400,
+ 'option_names' => $failed,
+ ]
+ );
}
return new \WP_REST_Response( [ 'success' => true ], 200 );
}
@@ -695,52 +760,73 @@ public function delete_options( $request ) {
/**
* Set autoload status of multiple options.
*
- * @param \WP_REST_Request $request The REST request object.
+ * @param \WP_REST_Request> $request The REST request object.
*
* @return \WP_Error|\WP_REST_Response
*/
public function set_autoload_options( $request ) {
- if ( ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) || ! \wp_verify_nonce( \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' ) ) {
- return new \WP_REST_Response( [ 'error' => 'Invalid nonce' ], 403 );
- }
-
- $autoload = \sanitize_text_field( \wp_unslash( $request['autoload'] ) );
-
- if ( ! in_array( $autoload, [ 'yes', 'on', 'no', 'off','auto', 'auto-on', 'auto-off' ], true ) ) {
- return new \WP_Error( 'invalid_autoload_value', 'Invalid autoload value', [ 'status' => 400 ] );
- }
+ return $this->update_autoload( $request['option_names'], $request['autoload'] );
+ }
- $autoload_values = \wp_autoload_values_to_autoload();
- $bool_autoload = false;
- if ( in_array( $autoload, $autoload_values, true ) ) {
- $bool_autoload = true;
+ /**
+ * Update autoload flags without reading or rewriting option values.
+ *
+ * @param string[] $option_names Exact option identifiers.
+ * @param string $state Requested autoload state.
+ * @return \WP_Error|\WP_REST_Response
+ */
+ private function update_autoload( array $option_names, string $state ) {
+ if ( Protected_Options::get_mutation_protected( $option_names ) ) {
+ return new \WP_Error( 'option_protected', 'Option is protected', [ 'status' => 403 ] );
}
- $option_names = $request['option_names'];
-
+ $autoload = in_array( $state, \wp_autoload_values_to_autoload(), true );
+ $results = \wp_set_option_autoload_values( array_fill_keys( $option_names, $autoload ) );
+ $failed = [];
foreach ( $option_names as $option_name ) {
- $option_value = get_option( $option_name );
-
- // If the option does not exist, skip it.
- if ( false === $option_value ) {
- continue;
+ // Core returns false for unchanged rows too. Check the raw state, never the filtered value.
+ if ( empty( $results[ $option_name ] ) && $this->get_raw_autoload( $option_name ) !== ( $autoload ? 'on' : 'off' ) ) {
+ $failed[] = $option_name;
}
-
- delete_option( $option_name );
- add_option( $option_name, $option_value, '', $bool_autoload );
+ }
+ if ( $failed ) {
+ return new \WP_Error(
+ 'update_failed',
+ 'Some options could not be updated',
+ [
+ 'status' => 400,
+ 'option_names' => $failed,
+ ]
+ );
}
return new \WP_REST_Response( [ 'success' => true ], 200 );
}
+ /**
+ * Read only the raw autoload state, without option filters.
+ *
+ * @param string $option_name Option name.
+ * @return string|null
+ */
+ private function get_raw_autoload( $option_name ) {
+ global $wpdb;
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ return $wpdb->get_var( $wpdb->prepare( "SELECT autoload FROM {$wpdb->options} WHERE option_name = %s", $option_name ) );
+ }
+
/**
* Create an option with a false value.
*
- * @param \WP_REST_Request $request The REST request object.
+ * @param \WP_REST_Request> $request The REST request object.
*
* @return \WP_Error|\WP_REST_Response
*/
public function create_option_false( $request ) {
$option_name = $request['option_name'];
+ if ( Protected_Options::is_mutation_protected( $option_name ) ) {
+ return new \WP_Error( 'option_protected', 'Option is protected', [ 'status' => 403 ] );
+ }
+
if ( add_option( $option_name, false, '', false ) ) {
return new \WP_REST_Response( [ 'success' => true ], 200 );
}
@@ -789,17 +875,10 @@ function ( $a, $b ) use ( $column, $direction ) {
* }
*/
protected function get_pagination_params(): array {
- if (
- ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) ||
- ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' )
- ) {
- return [ 0, 25 ]; // Fallback default.
- }
-
$offset = isset( $_GET['start'] ) ? intval( $_GET['start'] ) : 0;
$limit = isset( $_GET['length'] ) ? intval( $_GET['length'] ) : 25;
- return [ $offset, $limit ];
+ return [ max( 0, $offset ), max( 1, min( 500, $limit ) ) ];
}
/**
@@ -808,28 +887,19 @@ protected function get_pagination_params(): array {
* @return array{0: string, 1: int} [ string $column, int $direction (SORT_ASC|SORT_DESC) ]
*/
public function get_sort_params(): array {
- if (
- ! isset( $_SERVER['HTTP_X_WP_NONCE'] ) ||
- ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest' )
- ) {
- return [ 'name', SORT_ASC ]; // Fallback default.
- }
-
- if (
- ! isset( $_GET['order'][0]['column'], $_GET['columns'] )
- || ! is_array( $_GET['columns'] )
- || ! isset( $_GET['columns'][ $_GET['order'][0]['column'] ]['data'] )
- ) {
- return [ 'name', SORT_ASC ]; // Fallback default.
- }
-
- $column_index = isset( $_GET['order'][0]['column'] ) ? intval( $_GET['order'][0]['column'] ) : 0;
- $column_data = isset( $_GET['columns'][ $column_index ]['data'] ) ? \sanitize_text_field( \wp_unslash( $_GET['columns'][ $column_index ]['data'] ) ) : 'name';
-
- $dir = strtolower( \sanitize_text_field( \wp_unslash( $_GET['order'][0]['dir'] ?? 'asc' ) ) );
- $dir_flag = $dir === 'desc' ? SORT_DESC : SORT_ASC;
-
- return [ $column_data, $dir_flag ];
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Type and allowlist checked before use.
+ $index = $_GET['order'][0]['column'] ?? null;
+ if ( ! is_scalar( $index ) || ! ctype_digit( (string) $index ) ) {
+ return [ 'name', SORT_ASC ];
+ }
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Type and allowlist checked before use.
+ $column = $_GET['columns'][ (int) $index ]['data'] ?? 'name';
+ if ( ! is_string( $column ) || ! in_array( $column, [ 'name', 'plugin', 'size', 'count', 'autoload' ], true ) ) {
+ $column = 'name';
+ }
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Type and allowlist checked before use.
+ $direction = $_GET['order'][0]['dir'] ?? 'asc';
+ return [ $column, is_string( $direction ) && 'desc' === strtolower( $direction ) ? SORT_DESC : SORT_ASC ];
}
/**
diff --git a/tests/admin-hardening.test.cjs b/tests/admin-hardening.test.cjs
new file mode 100644
index 0000000..2a1c40c
--- /dev/null
+++ b/tests/admin-hardening.test.cjs
@@ -0,0 +1,106 @@
+/* Regression tests for the real admin event handlers, without a browser. */
+const assert = require( 'node:assert/strict' );
+const { readFileSync } = require( 'node:fs' );
+const { join } = require( 'node:path' );
+const { runInNewContext } = require( 'node:vm' );
+const { test } = require( 'node:test' );
+
+function setup( confirmDelete ) {
+ const handlers = new Map();
+ const requests = [];
+ const rowIds = [];
+ const alerts = [];
+ const window = { confirm: () => confirmDelete, location: { href: 'http://example.test/admin' } };
+ const row = { remove: () => row, draw: () => row };
+ const table = {
+ table: () => ( { node: () => ( { id: 'test_table' } ) } ),
+ row: ( id ) => { rowIds.push( id ); return row; },
+ ajax: { reload() {} },
+ };
+ const selection = [];
+ const tableElement = {
+ DataTable: () => table,
+ find: () => selection,
+ };
+ function jQuery( selector ) {
+ if ( typeof selector === 'object' && selector !== null && selector.attr ) {
+ return selector;
+ }
+ if ( selector === '#test_table' ) {
+ return tableElement;
+ }
+ const stub = {
+ length: 0,
+ hide: () => stub,
+ ready: ( callback ) => callback(),
+ on: ( event, filter, callback ) => {
+ handlers.set( selector + ':' + event + ':' + filter, callback || filter );
+ return stub;
+ },
+ };
+ return stub;
+ }
+ jQuery.ajax = ( request ) => requests.push( request );
+ runInNewContext( readFileSync( join( __dirname, '../js/admin-script.js' ), 'utf8' ), {
+ jQuery,
+ document: {},
+ window,
+ aaaOptionOptimizer: { root: '/', nonce: 'test', i18n: { confirmDelete: 'Delete?', selectedOptions: 'selected' } },
+ alert: ( message ) => alerts.push( message ),
+ } );
+ const actionHandler = handlers.get( 'table tbody:click:.add-autoload, .remove-autoload, .delete-option, .create-option-false' );
+ const bulkHandler = handlers.get( '.aaa-option-optimizer-tabs:click:.aaaoo-apply-bulk-action' );
+ function button( name, action ) {
+ return {
+ attr: () => name,
+ data: ( key ) => { assert.equal( key, 'table' ); return '#test_table'; },
+ closest: () => tableElement,
+ hasClass: ( candidate ) => candidate === action,
+ siblings: () => ( { val: () => action } ),
+ };
+ }
+ return { actionHandler, bulkHandler, button, selection, requests, rowIds, alerts, window, handlers };
+}
+
+test( 'single actions preserve numeric and JSON-like identifiers', () => {
+ const ui = setup( true );
+ for ( const name of [ '123', 'true', '["foo"]', 'a b', 'ac', 'literal%20name' ] ) {
+ ui.actionHandler.call( ui.button( name, 'delete-option' ), { preventDefault() {} } );
+ const request = ui.requests.at( -1 );
+ assert.equal( request.data.option_name, name );
+ assert.equal( typeof request.data.option_name, 'string' );
+ request.success( { success: true } );
+ assert.ok( ui.rowIds.at( -1 ).startsWith( '#test_table-option_' ) );
+ }
+} );
+
+test( 'cancelling single deletion sends no request', () => {
+ const ui = setup( false );
+ ui.actionHandler.call( ui.button( 'plugin_option', 'delete-option' ), { preventDefault() {} } );
+ assert.equal( ui.requests.length, 0 );
+} );
+
+test( 'cancelling bulk deletion sends no request', () => {
+ const ui = setup( false );
+ ui.selection.push( { getAttribute: () => '123' } );
+ ui.bulkHandler.call( ui.button( '', 'delete' ), { preventDefault() {} } );
+ assert.equal( ui.requests.length, 0 );
+} );
+
+test( 'confirmed bulk deletion preserves identifiers', () => {
+ const ui = setup( true );
+ const names = [ '123', '["foo"]', 'ac' ];
+ ui.selection.push( ...names.map( ( name ) => ( { getAttribute: () => name } ) ) );
+ ui.bulkHandler.call( ui.button( '', 'delete' ), { preventDefault() {} } );
+ assert.deepEqual( Array.from( ui.requests[ 0 ].data.option_names ), names );
+} );
+
+
+test( 'failed reset displays the server error without redirecting to success', () => {
+ const ui = setup( true );
+ const resetHandler = Array.from( ui.handlers ).find( ( [ key ] ) => key.startsWith( '#aaa-option-reset-data:click:' ) )[ 1 ];
+ resetHandler( { preventDefault() {} } );
+ ui.requests[ 0 ].error( { responseJSON: { message: 'Tracking could not be reset.' } } );
+ assert.deepEqual( ui.alerts, [ 'Tracking could not be reset.' ] );
+ assert.equal( ui.window.location.href, 'http://example.test/admin' );
+} );
diff --git a/tests/hardening.php b/tests/hardening.php
new file mode 100644
index 0000000..dc2a30e
--- /dev/null
+++ b/tests/hardening.php
@@ -0,0 +1,441 @@
+set_header( 'Content-Type', 'application/json' );
+ $request->set_body( wp_json_encode( $params ) );
+ return rest_do_request( $request );
+}
+
+global $wpdb;
+$names = [ '123', 'true', '["foo"]', 'a b', 'ac', 'literal%20name', 'quote\'"\\name', 'é😀' ];
+foreach ( $names as $name ) {
+ add_option( $name, [ 'raw' => 'unchanged' ], '', false );
+ $before = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $name ) );
+ add_filter(
+ 'option_' . $name,
+ static function () {
+ return 'filtered';
+ }
+ );
+ check(
+ 200 === request(
+ 'update-autoload',
+ [
+ 'option_name' => $name,
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'Exact-name autoload: ' . $name
+ );
+ check( $before === $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $name ) ), 'Autoload changed raw value: ' . $name );
+ check(
+ 200 === request(
+ 'update-autoload',
+ [
+ 'option_name' => $name,
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'Unchanged state should succeed.'
+ );
+}
+check(
+ 200 === request(
+ 'set-autoload-options',
+ [
+ 'option_names' => $names,
+ 'autoload' => 'no',
+ ]
+ )->get_status(),
+ 'Bulk autoload.'
+);
+// List responses must preserve the serialized bytes already stored in wp_options.
+Database::batch_insert( array_fill_keys( $names, 1 ) );
+// List routes paginate from $_GET (25 rows by default); fetch one full page so fixtures are present on busy sites.
+$_GET = [ 'length' => 500 ];
+$listed_values = array_column( request( 'used-not-autoloaded-options', [], 'GET' )->get_data()['data'], 'value', 'name' );
+$_GET = [];
+foreach ( $names as $name ) {
+ $stored_value = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $name ) );
+ check( $stored_value === ( $listed_values[ $name ] ?? null ), 'List response must not serialize the raw value again: ' . $name );
+}
+add_option( 'aaaoo_false', false, '', false );
+check(
+ 200 === request(
+ 'update-autoload',
+ [
+ 'option_name' => 'aaaoo_false',
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'False-valued option must be supported.'
+);
+check(
+ 400 === request(
+ 'update-autoload',
+ [
+ 'option_name' => 'aaaoo_missing',
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'Missing option must fail.'
+);
+
+// Failed SQL must leave the original row and bytes intact.
+$fail_update = static function ( $query ) use ( $wpdb ) {
+ return str_starts_with( $query, "UPDATE $wpdb->options SET autoload" ) ? 'UPDATE aaaoo_nonexistent_table SET autoload = 1' : $query;
+};
+$before = $wpdb->get_row( "SELECT * FROM $wpdb->options WHERE option_name = 'aaaoo_false'", ARRAY_A );
+$wpdb->suppress_errors( true );
+add_filter( 'query', $fail_update );
+check(
+ 400 === request(
+ 'update-autoload',
+ [
+ 'option_name' => 'aaaoo_false',
+ 'autoload' => 'no',
+ ]
+ )->get_status(),
+ 'Failed update must report failure.'
+);
+remove_filter( 'query', $fail_update );
+$wpdb->suppress_errors( false );
+check( $before === $wpdb->get_row( "SELECT * FROM $wpdb->options WHERE option_name = 'aaaoo_false'", ARRAY_A ), 'Failed update must preserve row.' );
+
+foreach ( [ 123, true, [], [ 'foo' ], '', ' siteurl', 'siteurl ', str_repeat( 'a', 192 ) ] as $bad ) {
+ foreach ( [ 'delete-option', 'create-option-false', 'update-autoload' ] as $route ) {
+ check(
+ 400 === request(
+ $route,
+ [
+ 'option_name' => $bad,
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'Reject malformed single identifier.'
+ );
+ }
+}
+foreach ( [ 'one,two', [], [ 123 ], [ true ], [ [ 'foo' ] ], [ 'key' => 'foo' ], [ 'foo', '' ], array_fill( 0, 501, 'foo' ) ] as $bad ) {
+ foreach ( [ 'delete-options', 'set-autoload-options' ] as $route ) {
+ check(
+ 400 === request(
+ $route,
+ [
+ 'option_names' => $bad,
+ 'autoload' => 'yes',
+ ]
+ )->get_status(),
+ 'Reject malformed bulk identifiers.'
+ );
+ }
+}
+foreach ( [ [], true, 'invalid' ] as $bad ) {
+ check(
+ 400 === request(
+ 'set-autoload-options',
+ [
+ 'option_names' => [ 'aaaoo_false' ],
+ 'autoload' => $bad,
+ ]
+ )->get_status(),
+ 'Reject malformed autoload state.'
+ );
+}
+
+foreach ( [ 'siteurl', 'SITEURL', 'sitéurl', 'active_plugins', $wpdb->prefix . 'user_roles', 'alloptions', 'notoptions', 'theme_mods_' . get_stylesheet(), strtoupper( 'theme_mods_' . get_stylesheet() ), 'auth_salt', 'NONCE_KEY', 'logged_in_salt' ] as $protected ) {
+ // Alias folding depends on the database: MySQL matches 'sitéurl' to 'siteurl', SQLite doesn't.
+ // Where the engine doesn't fold it, the name is a different, unprotected option and is skipped.
+ $resolved = $wpdb->get_var( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_name = %s", $protected ) );
+ if ( ! Protected_Options::is_protected( $protected ) && ( null === $resolved || ! Protected_Options::is_protected( $resolved ) ) ) {
+ continue;
+ }
+ foreach ( [ 'delete-option', 'create-option-false', 'update-autoload' ] as $route ) {
+ check(
+ 403 === request(
+ $route,
+ [
+ 'option_name' => $protected,
+ 'autoload' => 'no',
+ ]
+ )->get_status(),
+ 'Protect critical identifier: ' . $protected
+ );
+ }
+ foreach ( [ 'delete-options', 'set-autoload-options' ] as $route ) {
+ check(
+ 403 === request(
+ $route,
+ [
+ 'option_names' => [ 'aaaoo_false', $protected ],
+ 'autoload' => 'no',
+ ]
+ )->get_status(),
+ 'Preflight protected batch.'
+ );
+ check( null !== $wpdb->get_var( "SELECT option_name FROM $wpdb->options WHERE option_name = 'aaaoo_false'" ), 'Protected batch deleted an earlier option.' );
+ }
+}
+// Leftover mods of an inactive theme stay removable; only the active theme's are protected.
+add_option( 'theme_mods_aaaoo_inactive_theme', [ 'header_textcolor' => 'fff' ], '', false );
+check( ! Protected_Options::is_protected( 'theme_mods' ), 'The bare theme_mods name is not a core option.' );
+check( 200 === request( 'delete-option', [ 'option_name' => 'theme_mods_aaaoo_inactive_theme' ] )->get_status(), 'Inactive theme mods are removable.' );
+check(
+ 200 === request(
+ 'set-autoload-options',
+ [
+ 'option_names' => [ 'aaaoo_false' ],
+ 'autoload' => 'no',
+ ]
+ )->get_status(),
+ 'Unprotected batch still passes the batch preflight.'
+);
+
+wp_set_current_user( 0 );
+check( 401 === request( 'delete-option', [ 'option_name' => 'aaaoo_false' ] )->get_status(), 'Anonymous mutation denied.' );
+wp_set_current_user( 1 );
+check( 200 === request( 'delete-options', [ 'option_names' => $names ] )->get_status(), 'Authenticated bulk route needs no extra nonce.' );
+foreach ( $names as $name ) {
+ check( null === $wpdb->get_var( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_name = %s", $name ) ), 'Exact-name delete: ' . $name );
+}
+
+$rest = new REST();
+$_GET = [
+ 'order' => [
+ [
+ 'column' => [ 'bad' ],
+ 'dir' => [ 'bad' ],
+ ],
+ ],
+ 'columns' => [],
+];
+check( [ 'name', SORT_ASC ] === $rest->get_sort_params(), 'Array sort index must not throw.' );
+foreach ( [ 'DESC', 'Desc', 'desc' ] as $dir ) {
+ $_GET = [
+ 'order' => [
+ [
+ 'column' => '0',
+ 'dir' => $dir,
+ ],
+ ],
+ 'columns' => [ [ 'data' => 'size' ] ],
+ ];
+ check( [ 'size', SORT_DESC ] === $rest->get_sort_params(), 'Sort direction is case-insensitive: ' . $dir );
+}
+$_GET = [
+ 'order' => [
+ [
+ 'column' => '0',
+ 'dir' => 'desc',
+ ],
+ ],
+ 'columns' => [ [ 'data' => 'size' ] ],
+];
+check( [ 'size', SORT_DESC ] === $rest->get_sort_params(), 'Valid sort without redundant nonce.' );
+$_GET = [];
+
+Database::clear_tracked_options();
+Database::batch_insert( [ 'before_reset' => 2 ] );
+Database::mark_tracking_limited();
+$table = Database::get_table_name();
+$source = [
+ 'used_options' => [
+ 'migration_one' => 7,
+ 'migration_two' => 3,
+ ],
+];
+update_option( 'option_optimizer', $source, false );
+
+// A concurrent connection holding the old GET_LOCK name must not block or fail tracking writes.
+$other_connection = new \wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
+$other_connection->get_var( $other_connection->prepare( 'SELECT GET_LOCK(%s, 0)', 'aaaoo_' . md5( DB_NAME . $table ) ) );
+try {
+ $started = microtime( true );
+ check( [ 'lock_free' => 1 ] === Database::batch_insert( [ 'lock_free' => 1 ] ), 'Tracking writes take no global lock.' );
+ check( microtime( true ) - $started < 0.5, 'Tracking writes never wait on a lock.' );
+} finally {
+ $other_connection->close();
+}
+$wpdb->query( "DELETE FROM $table WHERE option_name = 'lock_free'" );
+
+$fail_tracking_insert = static function ( $query ) use ( $table ) {
+ return str_starts_with( $query, "INSERT INTO $table " ) ? 'INSERT INTO aaaoo_missing_table VALUES (1)' : $query;
+};
+$wpdb->suppress_errors( true );
+add_filter( 'query', $fail_tracking_insert );
+try {
+ check( 503 === request( 'migrate' )->get_status(), 'Failed tracking INSERT must report migration failure.' );
+ check( $source === get_option( 'option_optimizer' ), 'Failed INSERT must preserve migration source.' );
+} finally {
+ remove_filter( 'query', $fail_tracking_insert );
+ $wpdb->suppress_errors( false );
+}
+$response = request( 'migrate' );
+check( 200 === $response->get_status() && 0 === $response->get_data()['remaining'], 'Migration retry must complete.' );
+check( [] === get_option( 'option_optimizer' )['used_options'], 'Successful migration removes committed observations.' );
+check( 7 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'migration_one'" ), 'Retry must not duplicate failed migration counts.' );
+
+$fail_tracking_reset = static function ( $query ) {
+ return str_starts_with( $query, 'TRUNCATE TABLE ' ) ? 'TRUNCATE TABLE aaaoo_missing_table' : $query;
+};
+$wpdb->suppress_errors( true );
+add_filter( 'query', $fail_tracking_reset );
+try {
+ check( 503 === request( 'reset' )->get_status(), 'Failed TRUNCATE must report reset failure.' );
+ check( 3 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Failed TRUNCATE must preserve tracking rows.' );
+ check( Database::is_tracking_limited(), 'Failed TRUNCATE must preserve incomplete state.' );
+} finally {
+ remove_filter( 'query', $fail_tracking_reset );
+ $wpdb->suppress_errors( false );
+}
+$reset_plugin = Plugin::get_instance();
+$reset_plugin->monitor_option_accesses_pre_option( false, 'before_reset_request' );
+check( 200 === request( 'reset' )->get_status(), 'Reset retry must succeed.' );
+check( 0 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Successful reset must clear data before returning.' );
+check( ! Database::is_tracking_limited(), 'Successful reset clears incomplete state.' );
+$reset_plugin->monitor_option_accesses_pre_option( false, 'after_reset_request' );
+$reset_plugin->update_tracked_options();
+check( 0 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Shutdown must not repopulate a successful reset.' );
+
+// A failed tracking write loses at most that request's counts; it must not pause recommendations.
+Database::clear_tracked_options();
+$wpdb->suppress_errors( true );
+add_filter( 'query', $fail_tracking_insert );
+try {
+ check( false === Database::batch_insert( [ 'write_fails' => 1 ] ), 'Failed tracking INSERT reports failure.' );
+ check( ! Database::is_tracking_limited(), 'A failed write must not mark tracking incomplete.' );
+} finally {
+ remove_filter( 'query', $fail_tracking_insert );
+ $wpdb->suppress_errors( false );
+}
+
+// Capacity: new names beyond the limit are dropped and flagged; existing names keep counting.
+$observations = [];
+for ( $index = 0; $index < Database::MAX_TRACKED_OPTIONS; ++$index ) {
+ $observations[ 'dynamic_' . $index ] = 1;
+}
+Database::batch_insert( $observations );
+check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Fill storage to the limit.' );
+check( ! Database::is_tracking_limited(), 'A full table alone, with nothing dropped, keeps recommendations.' );
+
+// Names that match a stored row only by case or accents are existing rows, not new ones.
+Database::batch_insert( [ 'DYNAMIC_0' => 2 ] );
+check( 3 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Collation alias updates the existing row at capacity.' );
+check( ! Database::is_tracking_limited(), 'Collation alias at capacity is not a dropped observation.' );
+check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Collation alias adds no row.' );
+// Non-ASCII names at capacity go through wpdb's charset check, which must still find the table.
+$wpdb->query( "UPDATE $table SET option_name = 'é😀_stored' WHERE option_name = 'dynamic_9999'" );
+check( [ 'é😀_STORED' => 1 ] === Database::batch_insert( [ 'é😀_STORED' => 1 ] ), 'Non-ASCII alias (ASCII case differs) at capacity is written, not failed.' );
+check( 2 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'é😀_stored'" ), 'Non-ASCII alias updates the existing row.' );
+check( [] === Database::batch_insert( [ 'ñew_😀' => 1 ] ), 'New non-ASCII name at capacity is dropped, not failed.' );
+check( Database::is_tracking_limited(), 'Dropped non-ASCII name marks observations incomplete.' );
+delete_option( 'aaa_option_optimizer_tracking_limited' );
+
+$written = Database::batch_insert(
+ [
+ 'dynamic_1' => 3,
+ 'another_missing' => 1,
+ ]
+);
+check( [ 'dynamic_1' => 3 ] === $written, 'Only the existing name is written at capacity.' );
+check( 4 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_1'" ), 'Existing counts still update at capacity.' );
+check( Database::is_tracking_limited(), 'A dropped new name marks observations incomplete.' );
+check( [] === request( 'unused-options', [], 'GET' )->get_data()['data'], 'Do not recommend deletions from incomplete observations.' );
+
+// Legacy data is migrated in full, even past the limit, so migration always finishes.
+update_option(
+ 'option_optimizer',
+ [
+ 'used_options' => [
+ 'dynamic_0' => 7,
+ 'zz_unmigrated' => 3,
+ ],
+ ],
+ false
+);
+$response = request( 'migrate' );
+check( 200 === $response->get_status() && 0 === $response->get_data()['remaining'], 'Migration completes at capacity.' );
+check( [] === get_option( 'option_optimizer' )['used_options'], 'Migration leaves no observations behind.' );
+check( 10 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Commit the existing observation once.' );
+check( 3 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'zz_unmigrated'" ), 'Migrate the new observation past the limit.' );
+check( 200 === request( 'migrate' )->get_status(), 'Retry after completion is a no-op.' );
+check( 10 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Retry must not replay already migrated observations.' );
+
+// An oversized table is never pruned: reads return every row, and core rows survive.
+$rows = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" );
+check( Database::MAX_TRACKED_OPTIONS + 1 === $rows, 'Table may exceed the soft limit.' );
+Database::batch_insert( [ 'dynamic_2' => 1 ] );
+check( $rows === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Writes never prune rows.' );
+check( $rows === count( Database::get_tracked_options() ), 'Reads are not truncated at the limit.' );
+check( $rows === count( Database::get_tracked_option_keys() ), 'Key reads are not truncated at the limit.' );
+
+Database::clear_tracked_options();
+check( ! Database::is_tracking_limited(), 'Reset clears incomplete state.' );
+
+// A heavy request (well over 1,000 names) is normal and must not pause recommendations.
+$plugin = new Plugin();
+for ( $index = 0; $index < 3000; ++$index ) {
+ $plugin->monitor_option_accesses_pre_option( false, 'request_' . $index );
+}
+$_GET['page'] = 'aaa-option-optimizer';
+$plugin->update_tracked_options();
+check( ! Database::is_tracking_limited(), 'A heavy request is not an incomplete observation.' );
+check( 3000 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Frontend page parameter must not suppress tracking.' );
+$_GET = [];
+
+// Only a request reading more names than storage holds is capped and flagged.
+Database::clear_tracked_options();
+$plugin = new Plugin();
+for ( $index = 0; $index <= Database::MAX_TRACKED_OPTIONS; ++$index ) {
+ $plugin->monitor_option_accesses_pre_option( false, 'huge_' . $index );
+}
+$plugin->update_tracked_options();
+check( Database::is_tracking_limited(), 'Request cap must be visible.' );
+check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Request cap bounds one request.' );
+Database::clear_tracked_options();
+
+\WP_CLI::success( 'Hardening integration regressions passed.' );
diff --git a/tests/phpunit/class-plugin-test.php b/tests/phpunit/class-plugin-test.php
index f4a7669..8cdc818 100644
--- a/tests/phpunit/class-plugin-test.php
+++ b/tests/phpunit/class-plugin-test.php
@@ -176,11 +176,16 @@ public function test_legacy_tracking_recognizes_option_hooks() {
}
/**
- * Nothing is written while the plugin's own admin page is rendered.
+ * Nothing is written while an administrator views the plugin's own admin page.
*
* @return void
*/
public function test_nothing_is_stored_on_the_plugin_admin_page() {
+ \wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) );
+ if ( \is_multisite() ) {
+ \grant_super_admin( \get_current_user_id() );
+ }
+ \set_current_screen( 'tools_page_aaa-option-optimizer' );
$_GET['page'] = 'aaa-option-optimizer';
$this->plugin->monitor_option_accesses_pre_option( false, self::PREFIX . 'a' );
@@ -189,6 +194,20 @@ public function test_nothing_is_stored_on_the_plugin_admin_page() {
$this->assertSame( [], Database::get_tracked_options() );
}
+ /**
+ * A front-end visitor can't switch tracking off by adding the admin page's query argument.
+ *
+ * @return void
+ */
+ public function test_page_query_argument_does_not_stop_tracking_on_the_front_end() {
+ $_GET['page'] = 'aaa-option-optimizer';
+
+ $this->plugin->monitor_option_accesses_pre_option( false, self::PREFIX . 'a' );
+ $this->plugin->update_tracked_options();
+
+ $this->assertSame( [ self::PREFIX . 'a' => 1 ], Database::get_tracked_options() );
+ }
+
/**
* A reset clears the table instead of writing this request's accesses.
*
diff --git a/tests/phpunit/class-rest-test.php b/tests/phpunit/class-rest-test.php
index 4b8a6e4..fe29bed 100644
--- a/tests/phpunit/class-rest-test.php
+++ b/tests/phpunit/class-rest-test.php
@@ -211,7 +211,7 @@ public function test_update_autoload_rejects_an_invalid_value() {
);
$this->assertSame( 400, $response->get_status() );
- $this->assertSame( 'invalid_autoload_value', $response->get_data()['code'] );
+ $this->assertSame( 'rest_invalid_param', $response->get_data()['code'] );
$this->assertAutoloaded( $name );
$this->assertSame( 'value', \get_option( $name ) );
}
@@ -234,7 +234,9 @@ public function test_update_autoload_reports_a_missing_option() {
]
);
- $this->assertSame( 404, $response->get_status() );
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( 'update_failed', $response->get_data()['code'] );
+ $this->assertSame( [ $name ], $response->get_data()['data']['option_names'] );
$this->assertNull( $this->get_autoload_flag( $name ) );
}
@@ -251,11 +253,11 @@ public function test_update_autoload_requires_its_parameters() {
}
/**
- * The bulk route changes every existing option and skips missing ones.
+ * The bulk route changes every existing option and reports the missing ones.
*
* @return void
*/
- public function test_set_autoload_options_changes_existing_options_only() {
+ public function test_set_autoload_options_changes_existing_options_and_reports_missing_ones() {
$this->log_in_as( 'administrator' );
$first = self::PREFIX . 'bulk_1';
@@ -275,7 +277,9 @@ public function test_set_autoload_options_changes_existing_options_only() {
]
);
- $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( 'update_failed', $response->get_data()['code'] );
+ $this->assertSame( [ $missing ], $response->get_data()['data']['option_names'] );
$this->assertNotAutoloaded( $first );
$this->assertNotAutoloaded( $second );
$this->assertNull( $this->get_autoload_flag( $missing ) );
@@ -287,31 +291,106 @@ public function test_set_autoload_options_changes_existing_options_only() {
}
/**
- * The bulk routes need a REST nonce on top of the capability.
+ * The bulk route succeeds when every option exists, also when nothing needs to change.
*
* @return void
*/
- public function test_bulk_routes_require_a_nonce() {
+ public function test_set_autoload_options_succeeds_for_existing_options() {
$this->log_in_as( 'administrator' );
- unset( $_SERVER['HTTP_X_WP_NONCE'] );
- $name = self::PREFIX . 'nonce';
- \add_option( $name, 'value', '', true );
+ $changed = self::PREFIX . 'bulk_changed';
+ $unchanged = self::PREFIX . 'bulk_unchanged';
+ \add_option( $changed, 'value', '', true );
+ \add_option( $unchanged, 'value', '', false );
- $set = $this->request(
+ $response = $this->request(
'set-autoload-options',
[
- 'option_names' => [ $name ],
+ 'option_names' => [ $changed, $unchanged ],
+ 'autoload' => 'no',
+ ]
+ );
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertNotAutoloaded( $changed );
+ $this->assertNotAutoloaded( $unchanged );
+ }
+
+ /**
+ * Options WordPress can't run without can't be deleted, in any letter case.
+ *
+ * @return void
+ */
+ public function test_protected_options_cannot_be_deleted() {
+ $this->log_in_as( 'administrator' );
+
+ $siteurl = \get_option( 'siteurl' );
+ $other = self::PREFIX . 'beside_protected';
+ \add_option( $other, 'value' );
+
+ $this->assertSame( 403, $this->request( 'delete-option', [ 'option_name' => 'siteurl' ] )->get_status() );
+ $this->assertSame( 403, $this->request( 'delete-option', [ 'option_name' => 'SiteURL' ] )->get_status() );
+
+ // A protected name refuses the whole batch: nothing in it is deleted.
+ $response = $this->request( 'delete-options', [ 'option_names' => [ $other, 'siteurl' ] ] );
+
+ $this->assertSame( 403, $response->get_status() );
+ $this->assertSame( 'option_protected', $response->get_data()['code'] );
+ $this->assertNotNull( $this->get_autoload_flag( $other ) );
+ $this->assertNotNull( $this->get_autoload_flag( 'siteurl' ) );
+ $this->assertSame( $siteurl, \get_option( 'siteurl' ) );
+ }
+
+ /**
+ * The autoload flag of a protected option can't be changed.
+ *
+ * @return void
+ */
+ public function test_protected_options_keep_their_autoload_flag() {
+ $this->log_in_as( 'administrator' );
+
+ $before = $this->get_autoload_flag( 'siteurl' );
+ $other = self::PREFIX . 'beside_protected';
+ \add_option( $other, 'value', '', true );
+
+ $single = $this->request(
+ 'update-autoload',
+ [
+ 'option_name' => 'siteurl',
+ 'autoload' => 'no',
+ ]
+ );
+ $bulk = $this->request(
+ 'set-autoload-options',
+ [
+ 'option_names' => [ $other, 'siteurl' ],
'autoload' => 'no',
]
);
- $this->assertSame( 403, $set->get_status() );
- $delete = $this->request( 'delete-options', [ 'option_names' => [ $name ] ] );
- $this->assertSame( 403, $delete->get_status() );
+ $this->assertSame( 403, $single->get_status() );
+ $this->assertSame( 403, $bulk->get_status() );
+ $this->assertSame( $before, $this->get_autoload_flag( 'siteurl' ) );
+ $this->assertAutoloaded( $other );
+ }
+
+ /**
+ * Option names WordPress would trim, or that are not a list of strings, are rejected.
+ *
+ * @return void
+ */
+ public function test_malformed_option_names_are_rejected() {
+ $this->log_in_as( 'administrator' );
+
+ $name = self::PREFIX . 'padded';
+ \add_option( $name, 'value', '', true );
+
+ $this->assertSame( 400, $this->request( 'delete-option', [ 'option_name' => ' ' . $name ] )->get_status() );
+ $this->assertSame( 400, $this->request( 'delete-option', [ 'option_name' => '' ] )->get_status() );
+ $this->assertSame( 400, $this->request( 'delete-options', [ 'option_names' => [] ] )->get_status() );
+ $this->assertSame( 400, $this->request( 'delete-options', [ 'option_names' => [ $name, ' ' . $name ] ] )->get_status() );
$this->assertAutoloaded( $name );
- $this->assertSame( 'value', \get_option( $name ) );
}
/**
diff --git a/uninstall.php b/uninstall.php
index 05bf9fe..06c30b5 100644
--- a/uninstall.php
+++ b/uninstall.php
@@ -24,3 +24,5 @@
// Delete the plugin option.
delete_option( 'option_optimizer' );
+
+delete_option( 'aaa_option_optimizer_tracking_limited' );