Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/plugins-garbage-collector/includes/classes/ajax.php
+++ b/plugins-garbage-collector/includes/classes/ajax.php
@@ -0,0 +1,257 @@
+<?php
+
+defined( 'ABSPATH' ) || exit;
+
+/*
+ * Database Cleanup (former Plugins Garbage Collector) WordPress plugin
+ * Author: Vladimir Garagulia
+ * Email: vladimir@shinephp.com
+ * License: GPLv2 or later
+ */
+
+
+/**
+ * Process AJAX request from Database Cleanup
+ *
+ * @author Vladimir Gargulia
+ */
+final class PGC_Ajax {
+
+ private static ?string $action = null;
+ private static array $allowed_actions = [
+ 'get-plugins-list',
+ 'scan-plugin-for-db-tables-use',
+ 'get-scan-results',
+ 'check-wp-tables-structure',
+ 'hide-table',
+ 'show-table'
+ ];
+
+ /**
+ * Returns value by name from GET/POST/REQUEST. Minimal type checking is provided
+ *
+ * @param string $var_name Variable name to return
+ * @param string $var_type variable type to provide value checking
+ * @return mix variable value from request
+ */
+ private static function get_post_var( $var_name, $var_type = 'string') {
+
+ $result = 0;
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ if ( isset($_POST[$var_name] ) ) {
+ if ($var_type != 'checkbox') {
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ $result = sanitize_text_field( wp_unslash( $_POST[$var_name] ) );
+ } else {
+ $result = 1;
+ }
+ }
+
+ if ( $result ) {
+ if ( $var_type === 'int' && !is_numeric( $result ) ) {
+ $result = 0;
+ }
+ if ( $var_type !== 'int') {
+ $result = esc_attr( $result );
+ }
+ }
+
+ return $result;
+ }
+ // end of get_request_var()
+
+
+ private static function get_action() {
+
+ $action = self::get_post_var( 'subaction' );
+
+ if ( !in_array( $action, self::$allowed_actions, true ) ) {
+ $action = false;
+ }
+
+ return $action;
+ }
+ // end of get_action()
+
+
+ private static function valid_nonce() {
+
+ // check_ajax_referer() is used (with $stop=false) rather than check_admin_referer()
+ // because the latter always calls wp_die() itself on a failed nonce for a named action,
+ // which would return WordPress's generic HTML "link expired" page instead of the JSON
+ // error response below - breaking JSON.parse() on the JS side.
+ if ( !check_ajax_referer( 'plugins-garbage-collector', '_ajax_nonce', false ) ) {
+ echo wp_json_encode( array('result'=>'error', 'message'=>esc_html__('Database Cleanup: Wrong or expired request', 'plugins-garbage-collector' ) ) );
+ return false;
+ }
+
+ return true;
+ }
+ // end of check_nonce()
+
+
+ private static function user_can() {
+
+ if ( !current_user_can( PGC_Bootstrap::CAPABILITY ) ) {
+ echo wp_json_encode( array('result'=>'error', 'message'=>esc_html__('Database Cleanup: Insufficient permissions', 'plugins-garbage-collector' ) ) );
+ return false;
+ }
+
+ return true;
+ }
+ // end of user_can()
+
+
+ private static function switch_table_visibility( bool $make_visible ) {
+
+ $table_name = self::get_post_var('table_name' );
+ if ( empty( $table_name ) ) {
+ $answer = array('result'=>'error', 'message'=>esc_html__('Wrong request - required parameter table_name is missed.','plugins-garbage-collector') );
+ return $answer;
+ }
+
+ if ( $make_visible ) {
+ $answer = PGC_Settings::show_table( $table_name );
+ } else {
+ $answer = PGC_Settings::hide_table( $table_name );
+ }
+
+ return $answer;
+ }
+ // end of show_table()
+
+
+ private static function get_session_tables() {
+ if ( isset( $_SESSION['plugins-garbage-collector'] ) &&
+ isset( $_SESSION['plugins-garbage-collector']['tables'] ) &&
+ is_array( $_SESSION['plugins-garbage-collector']['tables'] ) &&
+ count( $_SESSION['plugins-garbage-collector']['tables'] ) > 0 ) {
+ // sanitize_key keeps only a-z, 0-9, _, and -
+ $sanitized_tables0 = map_deep( $_SESSION['plugins-garbage-collector']['tables'], 'sanitize_text_field' );
+ // Remove any empty items that failed sanitization
+ $sanitized_tables = array_filter( $sanitized_tables0 );
+ } else {
+ $sanitized_tables = array();
+ }
+
+ return $sanitized_tables;
+ }
+ // end of get_session_tables()
+
+
+ private static function scan_plugin_for_db_tables_use() {
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ if ( !isset( $_POST['plugin'] ) || empty( $_POST['plugin'] ) ) {
+ $answer = ['result' => 'error', 'message' => esc_html__('Invalid request - missed plugin parameter', 'plugins-garbage-collector' )];
+ return $answer;
+ }
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ if ( !isset( $_POST['plugin']['key'] ) || !isset( $_POST['plugin']['title'] ) || !isset( $_POST['plugin']['version'] ) ) {
+ $answer = ['result' => 'error', 'message' => esc_html__('Invalid request - wrong plugin parameter value', 'plugins-garbage-collector') ];
+ return $answer;
+ }
+ $plugin = [];
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ $plugin['key'] = sanitize_text_field( wp_unslash( $_POST['plugin']['key'] ) );
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ $plugin['title'] = sanitize_text_field( wp_unslash( $_POST['plugin']['title'] ) );
+// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is verified in self::dispatch()
+ $plugin['version'] = sanitize_text_field( wp_unslash( $_POST['plugin']['version'] ) );
+
+ $current_file = self::get_post_var( 'current_file', 'int' );
+ $tables = self::get_session_tables();
+
+ $answer = PGC_Scanner::scan_plugin_for_db_tables_use( $plugin, $current_file, $tables );
+
+ return $answer;
+ }
+ // end of scan_plugin_for_db_table_use()
+
+
+ private static function get_scan_results() {
+
+ $tables = self::get_session_tables();
+ $show_hidden_tables = self::get_post_var('show_hidden_tables', 'checkbox' );
+ $answer = PGC_Scanner::get_scan_results( $tables, $show_hidden_tables );
+
+ return $answer;
+ }
+ // end of get_scan_results()
+
+
+ private static function get_wpdb_scan_results() {
+
+ $show_hidden_tables = self::get_post_var('show_hidden_tables', 'checkbox' );
+ $answer = PGC_Scanner_WPDB::get_scan_results( $show_hidden_tables );
+
+ return $answer;
+ }
+ // end of get_scan_results()
+
+
+ private static function process() {
+
+ switch (self::$action) {
+ case 'get-plugins-list': {
+ $answer = PGC_Scanner::get_plugins_list();
+ break;
+ }
+ case 'scan-plugin-for-db-tables-use': {
+ $answer = self::scan_plugin_for_db_tables_use();
+ break;
+ }
+ case 'get-scan-results': {
+ $answer = self::get_scan_results();
+ break;
+ }
+ case 'check-wp-tables-structure': {
+ $answer = self::get_wpdb_scan_results();
+ break;
+ }
+ case 'hide-table': {
+ $answer = self::switch_table_visibility( false );
+ break;
+ }
+ case 'show-table': {
+ $answer = self::switch_table_visibility( true );
+ break;
+ }
+ default: {
+ $answer = ['result' => 'error', 'message' => esc_html__('Unknown action', 'plugins-garbage-collector') ];
+ }
+ } // end of switch
+
+ return $answer;
+
+ }
+ // end of process()
+
+
+ public static function dispatch() {
+
+ self::$action = self::get_action();
+ if ( !self::$action ) {
+ echo wp_json_encode( array('result' => 'error', 'message' => esc_html__('Unknown action', 'plugins-garbage-collector') ) );
+ wp_die();
+ }
+
+ if ( !self::valid_nonce() || !self::user_can() ) {
+ wp_die();
+ }
+
+
+ if ( session_status() !== PHP_SESSION_ACTIVE ) {
+ session_start();
+ }
+
+ if ( function_exists( 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
+// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Needed for plugin files scan / database cleanup process; safely guarded by function_exists() and limited by 90 seconds only.
+ @set_time_limit( 90 ); // 90 seconds
+ }
+ $data = self::process();
+ echo wp_json_encode( $data );
+ wp_die();
+ }
+ // end of dispatch()
+}
+// end of PGC_Ajax class
No newline at end of file
--- a/plugins-garbage-collector/includes/classes/bootstrap.php
+++ b/plugins-garbage-collector/includes/classes/bootstrap.php
@@ -0,0 +1,209 @@
+<?php
+
+defined( 'ABSPATH' ) || exit;
+
+/*
+ * Bootstrap class of Database Cleanup (former Plugins Garbage Collector) WordPress plugin
+ * Author: Vladimir Garagulya
+ * Author email: vladimir@shinephp.com
+ * Author URI: http://shinephp.com
+ * License: GPL v2+
+ *
+*/
+
+final class PGC_Bootstrap {
+ public const VERSION = '0.15';
+ public const MIN_PHP_VERSION = '7.4';
+ public const MIN_WP_VERSION = '4.6';
+ public const DATA_VERSION_URL = 'https://database-cleanup.s3.us-east-1.amazonaws.com/version.json';
+ public const DATA_SKIP_LIST_URL = 'https://database-cleanup.s3.us-east-1.amazonaws.com/skip-list.json';
+ public const DATA_PLUGINS_URL = 'https://database-cleanup.s3.us-east-1.amazonaws.com/plugins.json';
+ public const DATA_DB_TABLES_URL = 'https://database-cleanup.s3.us-east-1.amazonaws.com/db-tables.json';
+ public const CAPABILITY = 'activate_plugins';
+ public const DATA_DIR_NAME = 'pgc-data';
+ public const DATA_FILE_NAMES = array( 'skip-list.json', 'plugins.json', 'db-tables.json', 'version.json' );
+
+ private static ?string $data_version_path = null;
+ private static ?string $data_dir = null;
+ private static ?string $plugin_file = null;
+ private static ?string $plugin_dir = null;
+ private static ?string $plugin_url = null;
+ private static ?string $plugin_basename = null;
+
+
+ public static function get_plugin_file() {
+
+ return self::$plugin_file;
+ }
+ // end of get_plugin_file()
+
+
+ public static function get_plugin_dir() {
+
+ if ( self::$plugin_dir===null) {
+ self::$plugin_dir = plugin_dir_path( self::$plugin_file );
+ }
+
+ return self::$plugin_dir;
+ }
+ // end of get_plugin_dir()
+
+
+ public static function get_plugin_url() {
+
+ if ( self::$plugin_url===null) {
+ self::$plugin_url = plugin_dir_url( self::$plugin_file );
+ }
+
+ return self::$plugin_url;
+ }
+ // end of get_plugin_dir()
+
+
+ public static function get_plugin_basename() {
+
+ if ( self::$plugin_basename===null) {
+ self::$plugin_basename = plugin_basename( self::$plugin_file );
+ }
+
+ return self::$plugin_basename;
+ }
+ // end of get_plugin_basename()
+
+
+ private static function check_versions() {
+ global $wp_version;
+
+ if ( version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '<' ) ) {
+ deactivate_plugins( self::get_plugin_file() );
+ if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
+ $exit_msg = 'Plugins Garbage Collector requires PHP version ' . self::MIN_PHP_VERSION . ' or newer.' .
+ ' <a href="https://wordpress.org/about/requirements/"> Please update!</a>';
+// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Only executes when WP_DEBUG is enabled.
+ error_log( $exit_msg );
+ }
+ return false;
+ }
+
+ if ( version_compare( $wp_version, self::MIN_WP_VERSION, '<') ) {
+ deactivate_plugins( self::get_plugin_file() );
+ if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
+ $exit_msg = 'Plugins Garbage Collector requires WordPress ' . self::MIN_WP_VERSION . ' or newer.' .
+ ' <a href="https://codex.wordpress.org/Upgrading_WordPress"> Please update!</a>';
+// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Only executes when WP_DEBUG is enabled.
+ error_log( $exit_msg );
+ }
+ return false;
+ }
+
+ return true;
+ }
+ // end of check_versions()
+
+
+ public static function get_data_version_path() {
+
+ if ( self::$data_version_path===null ) {
+ self::$data_version_path = self::get_data_dir() . 'version.json';
+ }
+
+ return self::$data_version_path;
+ }
+ // end of get_data_version_path()
+
+
+ /*
+ * Returns the writable directory the plugin caches its auto-refreshed data files in:
+ * wp-content/uploads/pgc-data/, seeded on first use from the shipped ./data defaults.
+ * Falls back to the plugin's own data/ directory (as before) if uploads isn't usable -
+ * that keeps the plugin working, though it won't be able to persist refreshed data there
+ * on hosts where the plugin directory itself isn't writable.
+ */
+ public static function get_data_dir() {
+
+ if ( self::$data_dir===null ) {
+ self::$data_dir = self::resolve_data_dir();
+ }
+
+ return self::$data_dir;
+ }
+ // end of get_data_dir()
+
+
+ private static function resolve_data_dir() {
+
+ $upload_dir = wp_upload_dir();
+ if ( empty( $upload_dir['basedir'] ) || ! empty( $upload_dir['error'] ) ) {
+ return self::get_plugin_dir() . 'data/';
+ }
+
+ $dir = trailingslashit( $upload_dir['basedir'] ) . self::DATA_DIR_NAME . '/';
+ if ( ! wp_mkdir_p( $dir ) ) {
+ return self::get_plugin_dir() . 'data/';
+ }
+
+ self::seed_data_dir( $dir );
+
+ return $dir;
+ }
+ // end of resolve_data_dir()
+
+
+ /*
+ * Copies the plugin's shipped default data files into the writable data dir the first
+ * time it's used, so a fresh install has working data before the first remote refresh.
+ * Never overwrites files already present (e.g. ones a previous refresh already wrote).
+ */
+ private static function seed_data_dir( $dir ) {
+
+ global $wp_filesystem;
+ if ( ! $wp_filesystem || ! method_exists( $wp_filesystem, 'exists' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ WP_Filesystem();
+ }
+ if ( ! $wp_filesystem ) {
+ return;
+ }
+
+ foreach ( self::DATA_FILE_NAMES as $file_name ) {
+ $target = $dir . $file_name;
+ if ( $wp_filesystem->exists( $target ) ) {
+ continue;
+ }
+
+ $source = self::get_plugin_dir() . 'data/' . $file_name;
+ if ( $wp_filesystem->exists( $source ) ) {
+ $wp_filesystem->copy( $source, $target, false, 0664 );
+ }
+ }
+ }
+ // end of seed_data_dir()
+
+
+ public static function init( $plugin_file ) {
+
+ if ( self::$plugin_file===null ) {
+ self::$plugin_file = $plugin_file;
+ }
+
+ if ( ! self::check_versions() ) {
+ return;
+ }
+
+ require_once( self::get_plugin_dir() . 'includes/classes/ajax.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/settings.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/known-plugins.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/db-edit.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/tables-list.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/tables-list-wpdb.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/scanner.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/scanner-wpdb.php');
+ require_once( self::get_plugin_dir() . 'includes/classes/plugins-garbage-collector.php');
+
+ Plugins_Garbage_Collector::get_instance()->run();
+
+ }
+ // end of init()
+
+}
+// end of PGC_Bootstrap class
--- a/plugins-garbage-collector/includes/classes/db-edit.php
+++ b/plugins-garbage-collector/includes/classes/db-edit.php
@@ -0,0 +1,106 @@
+<?php
+
+/*
+ * Database Edit methods container class of Plugins Garbage Collector WordPress plugin
+ * Author: Vladimir Garagulya
+ * Author email: vladimir@shinephp.com
+ * Author URI: http://shinephp.com
+ * License: GPL v2+
+ *
+*/
+
+class PGC_DB_Edit {
+
+ private static function get_tables_to_delete( $post_tables ) {
+ global $wpdb;
+
+ $wp_tables = $wpdb->tables('all', true );
+ $tables = array();
+ foreach ( $post_tables as $table) {
+ // do not touch WordPress built-in tables
+ if ( !in_array( $table, $wp_tables, true ) ) {
+ $tables[] = $table;
+ }
+ }
+
+ return $tables;
+ }
+ // end of get_tables_to_delete()
+
+
+ private static function switch_off_foreigh_key_check() {
+ global $wpdb;
+
+// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query with no variables/placeholders; $wpdb->prepare() is not required and would trigger _doing_it_wrong().
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup. Backtick-escaped db table name identifier.
+ $result = $wpdb->get_row( "SHOW VARIABLES LIKE 'FOREIGN_KEY_CHECKS'" );
+ $fkc_value = $result->Value;
+ if ( $fkc_value == 'ON' ) {
+// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query with no variables/placeholders; $wpdb->prepare() is not required and would trigger _doing_it_wrong().
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup. Backtick-escaped db table name identifier.
+ $wpdb->query( 'SET FOREIGN_KEY_CHECKS=0' );
+ }
+
+ return $fkc_value;
+ }
+ // end of pgc_switch_off_foreign_key_check()
+
+
+ private static function restore_foreign_key_check( $old_fkc_value ) {
+ global $wpdb;
+
+ if ($old_fkc_value == 'ON' || $old_fkc_value == 1) {
+// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query with no variables/placeholders; $wpdb->prepare() is not required and would trigger _doing_it_wrong().
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup. Backtick-escaped db table name identifier.
+ $wpdb->query( 'SET FOREIGN_KEY_CHECKS=1' );
+ }
+ }
+ // end of restore_foreign_key_check()
+
+
+ public static function delete_unused_db_tables( $tables ) {
+ global $wpdb;
+
+ $tables = self::get_tables_to_delete( $tables );
+ if ( empty( $tables ) ) {
+ return;
+ }
+
+ $old_fkc_value = self::switch_off_foreigh_key_check();
+ $action_result = '';
+ foreach ( $tables as $table ) {
+ if ( $action_result ) {
+ $action_result .= ', ';
+ }
+// Manually escape backticks for legacy WP compatibility
+ $safe_table_name = '`' . str_replace( '`', '``', $table ) . '`';
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- PGC requires direct database access for table inspection and cleanup. Db tables which don't belong to WP deletion is the PGC main task. Backtick-escaped db table name identifier. Backtick-escaped DB table name identifier. Escaped via sanitize_text_field( wp_unslash() ) earlier.
+ $wpdb->query( "DROP TABLE {$safe_table_name}" );
+ if ( $wpdb->last_error ) {
+ if ( $action_result ) {
+ $action_result = esc_html__('Tables are deleted: ', 'plugins-garbage-collector') . $action_result;
+ }
+ self::restore_foreign_key_check( $old_fkc_value );
+ return $action_result . ' ' . $wpdb->last_error;
+ }
+ $action_result .= ' ' . $table;
+ }
+
+ self::restore_foreign_key_check( $old_fkc_value );
+
+ return esc_html__('Tables are deleted successfully: ', 'plugins-garbage-collector') . esc_html( $action_result );
+ }
+ // end of delete_unused_db_tables()
+
+
+ public static function delete_extra_columns_from_wp_tables() {
+
+ $message = esc_html__('This feature is still under development and will be realized in the future version', 'plugins-garbage-collector');
+
+ return $message;
+ }
+ // end of deleteExtraColumnsFromWPTables()
+
+
+}
+// end of PGC_DB_Edit class
--- a/plugins-garbage-collector/includes/classes/known-plugins.php
+++ b/plugins-garbage-collector/includes/classes/known-plugins.php
@@ -1,102 +1,123 @@
<?php
-class PGC_Known_Plugins {
-
- const VERSION_URL = 'https://storage.yandexcloud.net/database-cleanup/version.json';
- const SKIP_LIST_URL = 'https://storage.yandexcloud.net/database-cleanup/skip-list.json';
- const PLUGINS_URL = 'https://storage.yandexcloud.net/database-cleanup/plugins.json';
- const DB_TABLES_URL = 'https://storage.yandexcloud.net/database-cleanup/db-tables.json';
- const VERSION_PATH = PGC_PLUGIN_DIR .'/data/version.json';
+class PGC_Known_Plugins {
+ static private ?string $version_path = null;
- // List of plugins which create/use own database tables
+ // List of plugins which create/use own database tables and known to the PGC plugins
static private $plugins = null;
- // List of plugins, which do not create own database tables
+ // List of plugins, which do not create own database tables, not need to scan/check them
static private $skip_list = null;
// Database tables which belong to plugins and/or themes
static private $db_tables = null;
-
+
+ /*
+ * Returns an initialized WP_Filesystem instance, initializing it on first use only
+ */
+ static private function get_wp_filesystem() {
+
+ global $wp_filesystem;
+
+ if ( ! $wp_filesystem || ! method_exists( $wp_filesystem, 'get_contents' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ WP_Filesystem();
+ }
+
+ return $wp_filesystem;
+ }
+ // end of get_wp_filesystem()
+
+
static private function get_data_local_version() {
-
- $version = 0;
- $data = file_get_contents( self::VERSION_PATH );
+
+ $version = 0;
+ $fs = self::get_wp_filesystem();
+ $data = $fs ? $fs->get_contents( PGC_Bootstrap::get_data_version_path() ) : false;
$object = json_decode( $data );
if ( isset( $object->version ) ) {
$version = $object->version;
- }
-
+ }
+
return $version;
}
// end of get_data_local_version()
-
-
+
+
static private function get_data_remote_version() {
$version = 0;
- $file_date = date("Ymd", filemtime( self::VERSION_PATH ) );
- $current_date = date("Ymd");
+ $fs = self::get_wp_filesystem();
+ $mtime = $fs ? $fs->mtime( PGC_Bootstrap::get_data_version_path() ) : false;
+ $file_date = gmdate( 'Ymd', $mtime ? $mtime : 0 );
+ $current_date = gmdate("Ymd");
if ( $file_date==$current_date ) {
return $version;
}
-
- $answer = wp_remote_get( self::VERSION_URL, array('timeout' => 5 ) );
+
+ $answer = wp_remote_get( PGC_Bootstrap::DATA_VERSION_URL, array('timeout' => 5 ) );
if ( is_wp_error( $answer ) ) {
$error_message = $answer->get_error_message();
} else {
if ($answer['response']['code']==200) {
$obj = json_decode( $answer['body'] );
- $version = $obj->version;
+ $version = $obj->version;
} else {
$error_message = $answer['response']['code'] .' '. $answer['response']['message'];
}
- }
-
+ }
+
return $version;
}
- // end of get_data_local_version()
-
-
+ // end of get_data_remote_version()
+
+
static private function get_remote_data( $url, $file_name ) {
-
+
$result = -1;
$answer = wp_remote_get( $url, array('timeout' => 5 ) );
if ( is_wp_error( $answer ) ) {
- $error_message = $answer->get_error_message();
+ $error_message = $answer->get_error_message();
} else {
if ($answer['response']['code']==200) {
- unlink( $file_name );
- file_put_contents( $file_name, $answer['body'] );
- $result = 1;
+ $fs = self::get_wp_filesystem();
+ if ( $fs ) {
+ wp_delete_file( $file_name );
+ $fs->put_contents( $file_name, $answer['body'], 0664 );
+ $result = 1;
+ }
} else {
$error_message = $answer['response']['code'] .' '. $answer['response']['message'];
}
}
-
+
return $result;
}
// end of get_remote_data()
-
-
+
+
static private function update_version( $version ) {
-
- unlink( self::VERSION_PATH );
+
$object = new stdClass();
$object->version = $version;
- $json_data = json_encode( $object );
- file_put_contents( self::VERSION_PATH, $json_data );
-
+ $json_data = wp_json_encode( $object );
+ $fs = self::get_wp_filesystem();
+ if ( $fs ) {
+ wp_delete_file( PGC_Bootstrap::get_data_version_path() );
+ $fs->put_contents( PGC_Bootstrap::get_data_version_path(), $json_data, 0664 );
+ }
+
}
// end of update_version()
static private function _refresh_data( $version ) {
- $result1 = self::get_remote_data( self::SKIP_LIST_URL, PGC_PLUGIN_DIR .'/data/skip-list.json');
- $result2 = self::get_remote_data( self::PLUGINS_URL, PGC_PLUGIN_DIR .'/data/plugins.json');
- $result3 = self::get_remote_data( self::DB_TABLES_URL, PGC_PLUGIN_DIR .'/data/db-tables.json');
+ $result1 = self::get_remote_data( PGC_Bootstrap::DATA_SKIP_LIST_URL, PGC_Bootstrap::get_data_dir() . 'skip-list.json');
+ $result2 = self::get_remote_data( PGC_Bootstrap::DATA_PLUGINS_URL, PGC_Bootstrap::get_data_dir() . 'plugins.json');
+ $result3 = self::get_remote_data( PGC_Bootstrap::DATA_DB_TABLES_URL, PGC_Bootstrap::get_data_dir() . 'db-tables.json');
$result = $result1 + $result2 + $result3;
if ( $result!=3 ) { // Something is wrong. We will try again later.
@@ -122,14 +143,18 @@
}
// end of refresh_data()
-
+
+/*
+ * Read the own list of plugins which don't create own database tables
+ */
static private function init_skip_list() {
if ( !empty( self::$skip_list ) ) {
return;
}
- $data = file_get_contents( PGC_PLUGIN_DIR .'/data/skip-list.json');
+ $fs = self::get_wp_filesystem();
+ $data = $fs ? $fs->get_contents( PGC_Bootstrap::get_data_dir() . 'skip-list.json' ) : false;
self::$skip_list = json_decode( $data, true );
}
@@ -142,12 +167,18 @@
return;
}
- $data = file_get_contents( PGC_PLUGIN_DIR .'/data/plugins.json' );
+ $fs = self::get_wp_filesystem();
+ $data = $fs ? $fs->get_contents( PGC_Bootstrap::get_data_dir() . 'plugins.json' ) : false;
self::$plugins = json_decode( $data, true );
}
// end of init_plugins
+
+ /*
+ * Adds to the skip list the list of plugins which own db tables are known
+ * and returns as the list of plugins for which no need to scan plugin files
+ */
static public function get_skip_list() {
self::init_skip_list();
@@ -161,6 +192,7 @@
return $checked;
}
+ // end of get_skip_list()
static private function init_db_tables() {
@@ -170,7 +202,8 @@
}
self::init_plugins();
- $data = file_get_contents( PGC_PLUGIN_DIR .'/data/db-tables.json');
+ $fs = self::get_wp_filesystem();
+ $data = $fs ? $fs->get_contents( PGC_Bootstrap::get_data_dir() . 'db-tables.json' ) : false;
self::$db_tables = json_decode( $data, true );
if ( !is_multisite() ) {
// Global WordPress table for multisite. It's created by BuddyPress for WP single site
@@ -185,10 +218,10 @@
self::init_db_tables();
$name_lc = strtolower( $table->name_without_prefix );
- if ( !isset( self::$db_tables[$name_lc] ) ) {
+ if ( !isset( self::$db_tables[$name_lc] ) || !isset( self::$plugins[self::$db_tables[$name_lc]] ) ) {
return false;
}
-
+
$plugin = self::$plugins[self::$db_tables[$name_lc]];
$table->plugin_name = $plugin['name'];
$table->plugin_file = $plugin['file'];
--- a/plugins-garbage-collector/includes/classes/plugins-garbage-collector.php
+++ b/plugins-garbage-collector/includes/classes/plugins-garbage-collector.php
@@ -10,58 +10,64 @@
class Plugins_Garbage_Collector {
- public function __construct() {
+ static ?Plugins_Garbage_Collector $instance = null;
+
- //register_activation_hook( PGC_PLUGIN_FILE, array($this, 'install') );
+ /**
+ * Singleton template.
+ *
+ * @return user_switching User Switching instance.
+ */
+ public static function get_instance(): Plugins_Garbage_Collector {
- add_action( 'admin_init', array($this, 'plugin_init'), 1);
- // Add the translation function after the plugins loaded hook.
- add_action( 'plugins_loaded', array($this, 'load_translation') );
+ if ( self::$instance===null ) {
+ self::$instance = new Plugins_Garbage_Collector();
+ }
- // add menu item
- add_action( 'admin_menu', array($this, 'plugin_menu') );
-
- // set AJAX requests processing hook
- add_action( 'wp_ajax_plugins_garbage_collector', 'plugins_garbage_collector_ajax' );
-
+ return self::$instance;
}
- // end of __construct()
-
+ // end of get_instance()
- public function plugin_init() {
-
- if ( !is_admin() ) {
- return;
- }
+ /*
+ * Do not instantiate class directly, via get_instance() only
+ */
+ private function __construct() {
- // add a Settings link in the installed plugins page
- add_filter( 'plugin_action_links', array($this, 'plugin_action_links'), 10, 2 );
- add_filter( 'plugin_row_meta', array($this, 'plugin_row_meta'), 10, 2 );
-
- register_setting( 'pgc_options', 'pgc_options' );
-
}
- // end of plugin_init()
+ // end of __construct()
- public function load_translation() {
+ public function run() {
+
+ add_action( 'admin_init', [$this, 'init'], 1);
+
+ // add menu item
+ add_action( 'admin_menu', [$this, 'plugin_menu'] );
- load_plugin_textdomain( 'plugins-garbage-collector', false, basename(dirname(PGC_PLUGIN_FILE)) .'/lang/' );
+ // set AJAX requests processing hook
+ add_action( 'wp_ajax_plugins_garbage_collector', ['PGC_Ajax', 'dispatch'] );
}
- // end of load_translation()
+ // end of run()
+
-/*
- public function install() {
+ public function init() {
+
+ // add a Settings link in the installed plugins page
+ add_filter( 'plugin_action_links', array($this, 'plugin_action_links'), 10, 2 );
+ add_filter( 'plugin_row_meta', array($this, 'plugin_row_meta'), 10, 2 );
+
+ // Add the translation
+ load_plugin_textdomain( 'plugins-garbage-collector', false, basename( dirname( PGC_Bootstrap::get_plugin_file() ) ) .'/lang/' );
}
- // end of install()
-*/
+ // end of init()
+
public function plugin_action_links( $links, $file ) {
- if ( $file == plugin_basename( PGC_PLUGIN_FILE ) ) {
+ if ( $file === PGC_Bootstrap::get_plugin_basename() ) {
$settings_link = '<a href="tools.php?page=plugins-garbage-collector.php">'. esc_html__('Scan','plugins-garbage-collector') .'</a>';
array_unshift( $links, $settings_link );
}
@@ -74,43 +80,92 @@
public function plugin_row_meta( $links, $file ) {
- if ( $file == plugin_basename( PGC_PLUGIN_FILE ) ) {
- $links[] = '<a target="_blank" href="http://www.shinephp.com/plugins-garbage-collector-wordpress-plugin/#changelog">'. esc_html__('Changelog', 'plugins-garbage-collector').'</a>';
+ if ( $file === PGC_Bootstrap::get_plugin_basename() ) {
+ $links[] = '<a target="_blank" href="https://www.shinephp.com/plugins-garbage-collector-wordpress-plugin/#changelog">'. esc_html__('Changelog', 'plugins-garbage-collector').'</a>';
}
return $links;
}
// end of plugin_row_meta()
+
+
+ private function is_it_right_post() {
+
+ $result = ['result'=>false, 'action'=>'', 'message'=>''];
+ if ( !isset( $_POST['action'] ) ) {
+ // It's not our turn this time
+ return $result;
+ }
+
+ if ( !check_admin_referer( 'plugins-garbage-collector-options', '_wpnonce' ) ) {
+ $result['message'] = esc_html__('Database Cleanup: Wrong or expired request', 'plugins-garbage-collector' );
+ return $result;
+ }
+
+ if ( !current_user_can( PGC_Bootstrap::CAPABILITY ) ) {
+ $result['message'] = esc_html__('You do not have sufficient permissions.', 'plugins-garbage-collector' );
+ return $result;
+ }
+
+ $action = sanitize_text_field( wp_unslash( $_POST['action'] ) );
+ if ( !in_array( $action, ['delete_selected_tables', 'delete_extra_columns'], true ) ) {
+ $result['message'] = esc_html__('Database Cleanup: Wrong action!', 'plugins-garbage-collector');
+ return $result;
+ }
+
+ if ( $action==='delete_selected_tables' ) {
+ $post_keys = array_keys( $_POST );
+ $tables_esc = [];
+ foreach( $post_keys as $value ) {
+ $val_sec = trim( sanitize_text_field( wp_unslash( $value ) ) );
+ if ( strpos( $val_sec, 'delete_' ) === 0 ) {
+ $table_name = strtolower( substr( $val_sec, 7 ) );
+ // Only accept well-formed MySQL identifiers - reject anything crafted to break out of this shape.
+ if ( preg_match( '/^[a-zA-Z0-9_]+$/', $table_name ) ) {
+ $tables_esc[] = $table_name;
+ }
+ }
+ }
+ $result['tables'] = $tables_esc;
+ } else {
+ // Process input parameters for the 'delete_extra_columns' action here
+ }
+ $result['result'] = true;
+ $result['action'] = $action;
+
+ return $result;
+ }
+ // end of is_id_right_post()
private function process_post_actions() {
-
- if ( isset( $_POST['drop_table_action'] ) ) {
- $mess = pgc_delete_unused_db_tables();
- } else if ( isset( $_POST['delete_extra_columns_action'] ) ) {
- $mess = pgc_delete_extra_columns_from_wp_tables();
+
+ $result = $this->is_it_right_post();
+ if ( $result['result']===false ) {
+ return $result['message'];
+ }
+
+ if ( $result['action']==='delete_selected_tables' ) {
+
+ $mess = PGC_DB_Edit::delete_unused_db_tables( $result['tables'] );
+ } else if ( $result['action']==='delete_extra_columns' ) {
+ $mess = PGC_DB_Edit::delete_extra_columns_from_wp_tables();
} else {
$mess = '';
}
- return $mess;
-
+ return $mess;
}
// end of process_post_actions()
public function actions_page() {
-
- if ( !current_user_can( 'activate_plugins' ) ) {
- wp_die( 'You do not have sufficient permissions.' );
- }
-
- PGC_Known_Plugins::refresh_data();
-
+
+ PGC_Known_Plugins::refresh_data();
$mess = $this->process_post_actions();
- require_once( PGC_PLUGIN_DIR . 'includes/options.php' );
+ require_once( PGC_Bootstrap::get_plugin_dir() . 'includes/options.php' );
}
// end of actions_page()
@@ -118,8 +173,20 @@
public function admin_css() {
- wp_enqueue_style( 'pgc_jquery_ui', PGC_PLUGIN_URL.'/css/vendors/jquery-ui/jquery-ui.min.css', array(), false, 'screen' );
- wp_enqueue_style( 'pgc_admin_css', PGC_PLUGIN_URL.'/css/pgc-admin.css', array(), false, 'screen' );
+ wp_enqueue_style(
+ 'pgc_jquery_ui',
+ PGC_Bootstrap::get_plugin_url() .'css/vendors/jquery-ui/jquery-ui.min.css',
+ array(),
+ PGC_Bootstrap::VERSION,
+ 'screen'
+ );
+ wp_enqueue_style(
+ 'pgc_admin_css',
+ PGC_Bootstrap::get_plugin_url() .'css/pgc-admin.css',
+ array(),
+ PGC_Bootstrap::VERSION,
+ 'screen'
+ );
}
// end of admin_css()
@@ -127,35 +194,49 @@
function admin_scripts() {
- wp_enqueue_script( 'pgc_js_script', PGC_PLUGIN_URL . '/js/pgc.js', array('jquery', 'jquery-form', 'jquery-ui-core', 'jquery-ui-progressbar'), PGC_VERSION );
+ wp_enqueue_script(
+ 'pgc_js_script',
+ PGC_Bootstrap::get_plugin_url() . 'js/pgc.js',
+ ['jquery', 'jquery-form', 'jquery-ui-core', 'jquery-ui-progressbar'],
+ PGC_Bootstrap::VERSION,
+ true
+ );
wp_localize_script(
- 'pgc_js_script', 'pgcSettings', array('plugin_url' => PGC_PLUGIN_URL,
- 'ajax_nonce' => wp_create_nonce('plugins-garbage-collector'),
- 'ajax_url' => admin_url('admin-ajax.php'),
- 'redirect_url' => admin_url('/tools.php?page=plugins-garbage-collector.php&action='),
- 'turn_on_cb_before_scan' => esc_html__('Turn on at least one Search checkbox before start Scan process!', 'plugins-garbage-collector'),
- 'receive_plugins_list' => esc_html__('Receive plugins list', 'plugins-garbage-collector'),
- 'scanning' => esc_html__('Scanning', 'plugins-garbage-collector'),
- 'checking_plugin' => esc_html__('Checking plugin', 'plugins-garbage-collector'),
- 'take_some_time' => esc_html__('will take some time. Please confirm to continue', 'plugins-garbage-collector'),
- 'select_table_before_delete' => esc_html__('Select at least one table before click on Delete button', 'plugins-garbage-collector'),
- 'confirm_before_tables_deletion1' => esc_html__('These tables will be permanently deleted. Continue?', 'plugins-garbage-collector'),
- 'confirm_before_tables_deletion2' => esc_html__('Delete database tables last confirmation: Click "Cancel" if you have any doubt.', 'plugins-garbage-collector'),
- 'work_done' => esc_html('Done', 'plugins-garbage-collector')
- ));
+ 'pgc_js_script',
+ 'pgcSettings',
+ ['plugin_url' => PGC_Bootstrap::get_plugin_url(),
+ 'ajax_nonce' => wp_create_nonce('plugins-garbage-collector'),
+ 'ajax_url' => admin_url('admin-ajax.php'),
+ 'redirect_url' => admin_url('/tools.php?page=plugins-garbage-collector.php&action='),
+ 'turn_on_cb_before_scan' => esc_html__('Turn on at least one Search checkbox before start Scan process!', 'plugins-garbage-collector'),
+ 'receive_plugins_list' => esc_html__('Receive plugins list', 'plugins-garbage-collector'),
+ 'scanning' => esc_html__('Scanning', 'plugins-garbage-collector'),
+ 'checking_plugin' => esc_html__('Checking plugin', 'plugins-garbage-collector'),
+ 'take_some_time' => esc_html__('will take some time. Please confirm to continue', 'plugins-garbage-collector'),
+ 'select_table_before_delete' => esc_html__('Select at least one table before click on Delete button', 'plugins-garbage-collector'),
+ 'confirm_before_tables_deletion1' => esc_html__('These tables will be permanently deleted. Continue?', 'plugins-garbage-collector'),
+ 'confirm_before_tables_deletion2' => esc_html__('Delete database tables last confirmation: Click "Cancel" if you have any doubt.', 'plugins-garbage-collector'),
+ 'confirm_before_column_deletion1' => esc_html__('These columns will be permanently deleted. Continue?', 'plugins-garbage-collector'),
+ 'confirm_before_column_deletion2' => esc_html__('Delete database table columns last confirmation: Click "Cancel" if you have any doubt.', 'plugins-garbage-collector'),
+ 'work_done' => esc_html('Done', 'plugins-garbage-collector')
+ ]);
}
// end of admin_scripts()
- public function plugin_menu() {
-
+ public function plugin_menu() {
if ( !function_exists( 'add_management_page' ) ) {
return;
}
- $pgc_page = add_management_page( PGC_PLUGIN_NAME, PGC_PLUGIN_NAME, 'activate_plugins', basename( __FILE__), array($this, 'actions_page') );
+ $pgc_page = add_management_page(
+ __('Cleanup Database', 'plugins-garbage-collector'),
+ __('Cleanup Database', 'plugins-garbage-collector'),
+ PGC_Bootstrap::CAPABILITY,
+ 'plugins-garbage-collector',
+ [$this, 'actions_page'] );
add_action( "admin_print_styles-$pgc_page", array($this, 'admin_css') );
add_action( "admin_print_scripts-$pgc_page", array($this, 'admin_scripts') );
--- a/plugins-garbage-collector/includes/classes/scanner-wpdb.php
+++ b/plugins-garbage-collector/includes/classes/scanner-wpdb.php
@@ -0,0 +1,116 @@
+<?php
+/*
+ * Scan WordPress database tables for structure changes made comparing to the initial state
+ * Author: Vladimir Garagulya
+ * Author email: vladimir@shinephp.com
+ * Author URI: http://shinephp.com
+ * License: GPL v2+
+ *
+*/
+
+class PGC_Scanner_WPDB {
+
+ /*
+ * Get all of the field names in the query from between the parens
+ */
+
+ private static function extract_field_names($query) {
+
+ $columns = array();
+ $match2 = array();
+ preg_match("|((.*))|ms", strtolower($query), $match2);
+ $line = trim($match2[1]);
+ // Separate field lines into an array
+ $fields = explode("n", $line);
+ // For every field line specified in the query
+ foreach ($fields as $field) {
+ $validfield = true;
+ $field = trim($field);
+ // Extract the field name
+ $fvalue = array();
+ preg_match("|^([^ ]*)|", $field, $fvalue);
+ $fieldname = strtolower(trim($fvalue[1], '`'));
+ // Verify the found field name
+ switch ($fieldname) {
+ case '':
+ case 'primary':
+ case 'index':
+ case 'fulltext':
+ case 'unique':
+ case 'key':
+ $validfield = false;
+ break;
+ }
+
+ // If it's a valid field, add it to the field array
+ if ($validfield) {
+ $columns[$fieldname] = 1;
+ }
+ }
+
+ return $columns;
+ }
+ // end of extract_field_names()
+
+
+ public static function check_wp_tables_structure() {
+
+ global $wpdb;
+
+ $admin_path = str_replace(get_bloginfo('url') . '/', ABSPATH, get_admin_url());
+ require_once($admin_path . 'includes/schema.php');
+
+ $wp_db_schema = wp_get_db_schema('all');
+// Separate individual queries into an array
+ $queries = explode(';', $wp_db_schema);
+ if ('' == $queries[count($queries) - 1]) {
+ array_pop($queries);
+ }
+
+ $wp_tables_list = array();
+ $matches = [];
+ foreach ( $queries as $query ) {
+ if ( preg_match("|CREATE TABLE ([^ ]*)|", $query, $matches ) ) {
+ $wp_tables_list[ trim( strtolower( $matches[1] ), '`') ] = $query;
+ }
+ }
+
+ $changed_tables = array();
+ $i = 1;
+ foreach ( $wp_tables_list as $table => $create_query) {
+ // orginal structure columns list
+ $orig_columns = self::extract_field_names( $create_query );
+
+// Manually escape backticks for legacy WP compatibility
+ $safe_table_name = '`' . str_replace( '`', '``', $table ) . '`';
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- PGC requires direct database access for table inspection and cleanup. Backtick-escaped db table name identifier, which went through sanitize_text_field( wp_unslash() ) earlier.
+ $fact_columns = $wpdb->get_results( "DESCRIBE {$safe_table_name}" );
+ foreach ( $fact_columns as $fact_column ) {
+ if ( !isset( $orig_columns[strtolower( $fact_column->Field)] ) ) {
+ if ( !isset( $changed_tables[$table] ) ) {
+ $changed_tables[$table] = [];
+ }
+ $changed_tables[$table][$fact_column->Field] = new stdClass();
+ $changed_tables[$table][$fact_column->Field]->plugin_name = '';
+ $changed_tables[$table][$fact_column->Field]->plugin_state = '';
+ }
+ }
+ }
+
+ return $changed_tables;
+ }
+ // end of check_wp_tables_structure()
+
+
+ public static function get_scan_results( $show_hidden_tables ) {
+
+ $changed_tables = self::check_wp_tables_structure();
+ $data = PGC_Tables_List_WPDB::show( $changed_tables, $show_hidden_tables );
+
+ return $data;
+ }
+ // end of get_scan_results()
+
+
+}
+// end of PGC_Scanner_WP
--- a/plugins-garbage-collector/includes/classes/scanner.php
+++ b/plugins-garbage-collector/includes/classes/scanner.php
@@ -0,0 +1,361 @@
+<?php
+/*
+ * Scan installed plugins files to know if they use own database tables
+ * Author: Vladimir Garagulya
+ * Author email: vladimir@shinephp.com
+ * Author URI: http://shinephp.com
+ * License: GPL v2+
+ *
+*/
+class PGC_Scanner {
+
+ private static function get_blog_ids() {
+ global $wpdb;
+
+ if ( !is_multisite() ) {
+ return null;
+ }
+
+ $network = get_current_site();
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup.
+ $blog_ids = $wpdb->get_col(
+ $wpdb->prepare(
+ "SELECT blog_id FROM {$wpdb->blogs}
+ WHERE site_id=%d ORDER BY blog_id ASC",
+ [$network->id] )
+ );
+
+ return $blog_ids;
+ }
+ // end of get_blog_ids()
+
+
+ private static function table_from_current_blog($table_name, $blog_ids) {
+ global $wpdb;
+
+ $current_blog_id = get_current_blog_id();
+ $current_blog_prefix = $wpdb->get_blog_prefix();
+ if ( substr( $table_name, 0, strlen( $current_blog_prefix ) ) !== $current_blog_prefix ) { // wp_1 != $wp_2
+ return false;
+ }
+
+ // Exclude wp_11, wp_12 and similar to leave wp_1 only
+ foreach ( $blog_ids as $blog_id ) {
+ if ( $blog_id == $current_blog_id ) {
+ continue;
+ }
+ $prefix = $wpdb->base_prefix . $blog_id . '_';
+ if ( substr( $table_name, 0, strlen( $prefix ) ) === $prefix ) {
+ // table from other blog detected
+ return false;
+ }
+ }
+
+ return true;
+ }
+ // end of table_from_current_blog()
+
+
+ private static function get_db_table_info( $table_name ) {
+ global $wpdb;
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup.
+ $result = $wpdb->get_results(
+ $wpdb->prepare(
+ "SHOW TABLE STATUS LIKE %s",
+ $wpdb->esc_like( $table_name ) )
+ );
+
+ $table = new stdClass;
+ $table->name = $table_name;
+ $table->name_without_prefix = substr_replace( $table_name, '', 0, strlen( $wpdb->prefix ) );
+ $table->records = isset( $result[0]->Rows ) ? $result[0]->Rows : 0;
+ $table->kbytes = isset( $result[0]->Data_length ) ? ROUND( ( $result[0]->Data_length + $result[0]->Index_length ) / 1024, 2) : 0;
+ if ( !PGC_Known_Plugins::fill_data( $table ) ) {
+ $table->plugin_name = '';
+ $table->plugin_file = '';
+ $table->plugin_state = '';
+ }
+
+ return $table;
+ }
+ // end of get_db_table_info()
+
+
+ /*
+ * Returns the list of DB tables which don't belong to WordPress itself
+ */
+ private static function get_not_wp_tables() {
+ global $wpdb;
+
+ $all_plugins = get_plugins();
+ $blog_ids = self::get_blog_ids();
+ $wp_tables = $wpdb->tables('all', true);
+ $not_wp_tables = [];
+// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query with no variables/placeholders; $wpdb->prepare() is not required and would trigger _doing_it_wrong().
+// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- PGC requires direct database access for table inspection and cleanup.
+ $db_tables = $wpdb->get_col( 'SHOW TABLES' );
+ foreach ( $db_tables as $table_name ) {
+ if ( in_array( $table_name, $wp_tables, true ) ||
+ strpos( $table_name, $wpdb->prefix, 0 ) === false) {
+ continue;
+ }
+ if ( is_multisite() && ! self::table_from_current_blog( $table_name, $blog_ids ) ) {
+ continue;
+ }
+
+ $table = self::get_db_table_info( $table_name );
+ if ( !empty( $table->plugin_file ) && isset( $all_plugins[$table->plugin_file] ) ) {
+ $plugin_data = $all_plugins[$table->plugin_file];
+ $table->plugin_name .= ' ' . $plugin_data['Version'];
+ }
+ $not_wp_tables[] = $table;
+ }
+
+ PGC_Settings::update_hidden_tables_list( $not_wp_tables );
+
+ return $not_wp_tables;
+ }
+ // end of get_not_wp_tables()
+
+
+ /*
+ * Returns installed plugins list to scan for working with own database tables
+ */
+ public static function get_plugins_list() {
+
+ $_SESSION['plugins-garbage-collector'] = null;
+ $_SESSION['plugins-garbage-collector']['tables'] = self::get_not_wp_tables();
+ $plugins = get_plugins();
+ $skip_list = PGC_Known_Plugins::get_skip_list();
+ $plugins_list = [];
+ foreach ($plugins as $key => $plugin) {
+ $key_lc = strtolower( $key );
+ if ( in_array( $key_lc, $skip_list, true ) ) {
+ continue;
+ }
+ $plugin_short = new stdClass();
+ $plugin_short->key = $key;
+ $plugin_short->title = $plugin['Title'];
+ $plugin_short->version = $plugin['Version'];
+ $plugins_list[] = $plugin_short;
+ }
+
+ $data = array('result' => 'success', 'plugins_list' => $plugins_list );
+
+ return $data;
+ }
+ // end of get_plugins_list()
+
+
+ /*
+ * Return the list of PHP files included into the plugin
+ */
+ private static function get_plugin_php_files( $plugin ) {
+
+ $all_files = get_plugin_files( $plugin['key'] );
+ if ( empty( $all_files ) ) {
+ $answer = ['result' => 'error', 'message' => esc_html__('Invalid request - unexisted plugin ', 'plugins-garbage-collector') . $plugin['key'] ];
+ return $answer;
+ }
+
+ // Extract PHP files only
+ $php_files = [];
+ foreach ( $all_files as $plugin_file ) {
+ $ext = pathinfo( $plugin_file, PATHINFO_EXTENSION );
+ if ( strtolower( $ext ) !== 'php') {
+ continue;
+ }
+ $php_files[] = $plugin_file;
+ }
+
+ return $php_files;
+ }
+ // end of get_plugin_php_files()
+
+
+ /*
+ * returns text file content as array with elements line by line
+ */
+ private static function read_file( $file ) {
+ global $wp_filesystem;
+
+ if ( ! $wp_filesystem || ! method_exists( $wp_filesystem, 'get_contents' ) ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ WP_Filesystem();
+ }
+
+ if ( !$wp_filesystem || !method_exists($wp_filesystem, 'get_contents') ) {
+ return false;
+ }
+
+ $file_path = WP_PLUGIN_DIR . '/' . $file;
+ if ( !$wp_filesystem->exists( $file_path ) ) {
+ return false;
+ }
+
+ $content = $wp_filesystem->get_contents($file_path);
+ if ( $content === false ) {
+ // Failed to read file
+ return false;
+ }
+
+ // Normalize raw endings and split into raws
+ $normalized0 = str_replace("rn", "n", $content );
+ $normalized1 = str_replace("r", "n", $normalized0 );
+ $raws = explode("n", $normalized1 );
+
+ return $raws;
+ }
+ // end of read_file()
+
+
+ private static function is_session_data_available() {
+
+ if ( !isset( $_SESSION['plugins-garbage-collector'] ) ||
+ !isset( $_SESSION['plugins-garbage-collector']['tables'] ) ||
+ !is_array( $_SESSION['plugins-garbage-collector']['tables'] ) ) {
+ return false;
+ }
+
+ return true;
+ }
+ // end of is_session_data_available()
+
+
+ private static function scan_file( $file, $plugin, $tables ) {
+
+ if ( !self::is_session_data_available() ) {
+ return;
+ }
+
+ $raws = self::read_file( $file );
+ if ( $raws === false ) {
+ return;
+ }
+
+
+ foreach ($raws as $key=>$raw) {
+ $raw = strtolower( rtrim( $raw, "nr") );
+ foreach( $tables as $table ) {
+ if ( !empty( $table->plugin_name ) ) {
+ continue;
+ }
+ if ( strpos( $raw, $table->name_without_prefix ) !== false ) {
+ $table->plugin_name = $plugin['title'] . ' ' . $plugin['version'];
+ $table->plugin_file = $plugin['key'];
+ }
+ } // foreach()
+ }
+
+ }
+ // end of scan_file()
+
+
+ /*
+ * Scan plugin PHP files if it uses own database tables
+ */
+ public static function scan_plugin_for_db_tables_use( $plugin, $current_file, $tables ) {
+
+ $php_files = self::get_plugin_php_files( $plugin );
+ if ( isset( $php_files['result'] ) ) {
+ // Invalid request - unexisted plugin
+ return $php_files;
+ }
+
+ $cf = empty( $current_file ) ? 0 : $current_file;
+ $files_to_process = 500;
+ for ( $i = $cf; $i < count( $php_files ); $i++ ) {
+ self::scan_file( $php_files[$i], $plugin, $tables );
+ $files_to_process--;
+ if ( $files_to_process < 1 ) {
+ break;
+ }
+ }
+
+ $total_files = count( $php_files );
+ // $i is the index of the last file actually processed (loop breaks before its own increment runs);
+ // resume from the next one so a batch limit doesn't re-scan the same file twice.
+ $cf = $i + 1;
+ $answer = [
+ 'result' => 'success',
+ 'current_file' => $cf,
+ 'total_files' => $total_files,
+ 'message' => $plugin['title'] . ' ' . esc_html__(' checked', 'plugins-garbage-collector')
+ ];
+
+ return $answer;
+ }
+ // end of scan_plugin_for_db_tables_use()
+
+
+ private static function get_active_plugins() {
+
+ $list = (array) get_option('active_plugins', [] );
+ if ( is_multisite() ) {
+ $list2 = get_site_option('active_sitewide_plugins', [] );
+ if ( !empty( $list2 ) ) {
+ $list = array_merge( $list, array_keys( $list2 ) );
+ }
+ }
+
+ return $list;
+ }
+ // end of get_active_plugins()
+
+
+ private static function get_plugin_state( $all_plugins, $active_plugins, $plugin_file ) {
+
+ $plugin_active = false;
+ foreach ( $active_plugins as $active_plugin ) {
+ if ( $plugin_file === $active_plugin ) {
+ $plugin_active = true;
+ break;
+ }
+ }
+ if ( $plugin_active ) {
+ $plugin_state = 'active';
+ } else {
+ if ( isset( $all_plugins[$plugin_file] ) ) {
+ $plugin_state = 'inactive';
+ } else {
+ $plugin_state = 'unused';
+ }
+ }
+
+ return $plugin_state;
+ }
+ // end of get_plugin_state()
+
+
+ private static function set_plugin_state_for_tables( $tables ) {
+
+ if ( !self::is_session_data_available() ) {
+ return;
+ }
+
+ $all_plugins = get_plugins();
+ $active_plugins = self::get_active_plugins();
+ foreach ( $tables as $table ) {
+ if ( $table->plugin_file ) {
+ $table->plugin_state = self::get_plugin_state( $all_plugins, $active_plugins, $table->plugin_file );
+ } else {
+ $table->plugin_state = 'unused';
+ }
+ }
+ }
+ // end of set_plugin_state_for_tables()
+
+
+
+ public static function get_scan_results( $tables, $show_hidden_tables ) {
+
+ self::set_plugin_state_for_tables( $tables );
+ $html = PGC_Tables_List::show( $show_hidden_tables );
+ $answer = ['result' => 'success', 'html' => $html];
+
+ return $answer;
+ }
+ // end of pgc_scan_db_tables()
+
+}
+// end of PGC_Scanner class
No newline at end of file
--- a/plugins-garbage-collector/includes/classes/settings.php
+++ b/plugins-garbage-collector/includes/classes/settings.php
@@ -0,0 +1,81 @@
+<?php
+/*
+ * Project: Database Cleanup (former P