array( plugin folders, name ). */ const KNOWN = array( '^wc_(avatars_cache|comments_subscription|follow_users|phrases|users_voted|feedback_forms|users_rated)$' => array( array( 'wpdiscuz' ), 'wpDiscuz' ), '^(wc_|woocommerce_)' => array( array( 'woocommerce' ), 'WooCommerce' ), '^actionscheduler_' => array( array( 'woocommerce', 'action-scheduler', 'wp-mail-smtp', 'mailpoet', 'woocommerce-payments', 'all-in-one-seo-pack', 'seo-by-rank-math', 'wpforms-lite', 'wpforms' ), 'Action Scheduler' ), '^wf' => array( array( 'wordfence' ), 'Wordfence' ), '^aiowps_' => array( array( 'all-in-one-wp-security-and-firewall' ), 'All-In-One Security' ), '^yoast_' => array( array( 'wordpress-seo', 'wordpress-seo-premium' ), 'Yoast SEO' ), '^rank_math' => array( array( 'seo-by-rank-math', 'seo-by-rank-math-pro' ), 'Rank Math' ), '^aioseo_' => array( array( 'all-in-one-seo-pack', 'all-in-one-seo-pack-pro' ), 'All in One SEO' ), '^e_(events|submissions|notes|notes_users_relations|submissions_values|submissions_actions_log)$' => array( array( 'elementor', 'elementor-pro' ), 'Elementor' ), '^wpforms_' => array( array( 'wpforms-lite', 'wpforms' ), 'WPForms' ), '^(gf_|rg_)' => array( array( 'gravityforms' ), 'Gravity Forms' ), '^frm_' => array( array( 'formidable', 'formidable-pro' ), 'Formidable Forms' ), '^nf3_' => array( array( 'ninja-forms' ), 'Ninja Forms' ), '^fluentform_' => array( array( 'fluentform', 'fluentformpro' ), 'Fluent Forms' ), '^frmt_' => array( array( 'forminator' ), 'Forminator' ), '^db7_forms$' => array( array( 'contact-form-cfdb7' ), 'Contact Form 7 Database Addon' ), '^redirection_' => array( array( 'redirection' ), 'Redirection' ), '^litespeed_' => array( array( 'litespeed-cache' ), 'LiteSpeed Cache' ), '^wpr_' => array( array( 'wp-rocket' ), 'WP Rocket' ), '^jetpack_' => array( array( 'jetpack' ), 'Jetpack' ), '^mailpoet_' => array( array( 'mailpoet', 'mailpoet-premium' ), 'MailPoet' ), '^nextend2_' => array( array( 'smart-slider-3', 'nextend-smart-slider3-pro' ), 'Smart Slider 3' ), '^revslider_' => array( array( 'revslider' ), 'Slider Revolution' ), '^icl_' => array( array( 'sitepress-multilingual-cms' ), 'WPML' ), '^trp_' => array( array( 'translatepress-multilingual' ), 'TranslatePress' ), '^bp_' => array( array( 'buddypress' ), 'BuddyPress' ), '^learnpress_' => array( array( 'learnpress' ), 'LearnPress' ), '^tutor_' => array( array( 'tutor', 'tutor-pro' ), 'Tutor LMS' ), '^wpmailsmtp_' => array( array( 'wp-mail-smtp', 'wp-mail-smtp-pro' ), 'WP Mail SMTP' ), '^post_smtp_' => array( array( 'post-smtp' ), 'Post SMTP' ), '^wpml_mails$' => array( array( 'wp-mail-logging' ), 'WP Mail Logging' ), '^simple_history' => array( array( 'simple-history' ), 'Simple History' ), '^statistics_' => array( array( 'wp-statistics' ), 'WP Statistics' ), '^itsec_' => array( array( 'better-wp-security', 'ithemes-security-pro' ), 'Solid Security' ), '^cerber_' => array( array( 'wp-cerber' ), 'WP Cerber' ), '^wsal_' => array( array( 'wp-security-audit-log' ), 'WP Activity Log' ), '^blc_' => array( array( 'broken-link-checker' ), 'Broken Link Checker' ), '^fc_' => array( array( 'fluent-crm' ), 'FluentCRM' ), '^newsletter' => array( array( 'newsletter' ), 'Newsletter' ), '^ewwwio_' => array( array( 'ewww-image-optimizer' ), 'EWWW Image Optimizer' ), '^tm_(tasks|taskmeta)$' => array( array( 'wp-optimize', 'updraftplus', 'wp-optimize-premium' ), 'WP-Optimize / UpdraftPlus task manager' ), '^cmplz_' => array( array( 'complianz-gdpr', 'complianz-gdpr-premium' ), 'Complianz' ), '^cky_' => array( array( 'cookie-law-info' ), 'CookieYes' ), '^pmxi_' => array( array( 'wp-all-import', 'wp-all-import-pro' ), 'WP All Import' ), '^rsssl_' => array( array( 'really-simple-ssl', 'really-simple-ssl-pro' ), 'Really Simple SSL' ), '^sbi_' => array( array( 'instagram-feed', 'instagram-feed-pro' ), 'Smash Balloon Instagram Feed' ), '^cff_' => array( array( 'custom-facebook-feed' ), 'Smash Balloon Facebook Feed' ), '^snippets$' => array( array( 'code-snippets' ), 'Code Snippets' ), '^wpstg_' => array( array( 'wp-staging', 'wp-staging-pro' ), 'WP Staging' ), '^duplicator_' => array( array( 'duplicator', 'duplicator-pro' ), 'Duplicator' ), '^ppress_' => array( array( 'wp-user-avatar' ), 'ProfilePress' ), '^um_' => array( array( 'ultimate-member' ), 'Ultimate Member' ), '^pmpro_' => array( array( 'paid-memberships-pro' ), 'Paid Memberships Pro' ), '^mepr_' => array( array( 'memberpress' ), 'MemberPress' ), '^edd_' => array( array( 'easy-digital-downloads', 'easy-digital-downloads-pro' ), 'Easy Digital Downloads' ), '^(tec_|tribe_)' => array( array( 'the-events-calendar', 'event-tickets' ), 'The Events Calendar' ), '^em_' => array( array( 'events-manager' ), 'Events Manager' ), '^bookly_' => array( array( 'bookly-responsive-appointment-booking-tool' ), 'Bookly' ), '^hustle_' => array( array( 'wordpress-popup' ), 'Hustle' ), '^wpfm_' => array( array( 'wp-file-manager' ), 'WP File Manager' ), '^smush_' => array( array( 'wp-smushit' ), 'Smush' ), '^wcpay_' => array( array( 'woocommerce-payments' ), 'WooPayments' ), '^mc4wp_' => array( array( 'mailchimp-for-wp' ), 'MC4WP' ), '^pv_' => array( array( 'post-views-counter' ), 'Post Views Counter' ), '^wpdatatables' => array( array( 'wpdatatables' ), 'wpDataTables' ), ); public static function init() { add_action( self::HOOK, array( __CLASS__, 'auto_run' ) ); $s = self::settings(); if ( 'off' !== $s['schedule'] && ! wp_next_scheduled( self::HOOK ) ) { wp_schedule_event( time() + DAY_IN_SECONDS, 'monthly' === $s['schedule'] ? 'svabg_monthly' : 'weekly', self::HOOK ); } elseif ( 'off' === $s['schedule'] && wp_next_scheduled( self::HOOK ) ) { wp_clear_scheduled_hook( self::HOOK ); } } /* ------------------------------ settings ------------------------------ */ public static function settings() { $s = get_option( self::OPTION, array() ); return array_merge( array( 'schedule' => 'off', 'items' => array( 'optimize_tables', 'revisions', 'auto_drafts', 'trashed_posts', 'spam_comments', 'expired_transients', 'orphan_postmeta', 'orphan_commentmeta' ), 'keep_revisions' => 0, 'backup' => 1, 'last_auto' => 0, 'last_result' => array(), ), is_array( $s ) ? $s : array() ); } public static function save_settings( array $in ) { $s = self::settings(); $s['schedule'] = in_array( $in['schedule'] ?? '', array( 'off', 'weekly', 'monthly' ), true ) ? $in['schedule'] : $s['schedule']; $s['items'] = array_values( array_intersect( array_keys( self::items() ), (array) ( $in['items'] ?? $s['items'] ) ) ); $s['keep_revisions'] = max( 0, min( 100, (int) ( $in['keep_revisions'] ?? $s['keep_revisions'] ) ) ); $s['backup'] = empty( $in['backup'] ) ? 0 : 1; update_option( self::OPTION, $s, false ); wp_clear_scheduled_hook( self::HOOK ); self::init(); return $s; } /* ---------------------------- optimizations ---------------------------- */ /** * The optimizations: id => title, description, tables touched, default, caution. */ public static function items() { global $wpdb; return array( 'optimize_tables' => array( __( 'Optimize database tables', 'ai-guardwall' ), __( 'Reclaims the space left behind by deleted rows and defragments the tables.', 'ai-guardwall' ), array(), true, false ), 'revisions' => array( __( 'Clean post revisions', 'ai-guardwall' ), __( 'Old copies WordPress keeps every time a post or page is saved.', 'ai-guardwall' ), array( $wpdb->posts, $wpdb->postmeta, $wpdb->term_relationships ), true, false ), 'auto_drafts' => array( __( 'Clean auto-drafts', 'ai-guardwall' ), __( 'Drafts WordPress creates when you open the editor and never save.', 'ai-guardwall' ), array( $wpdb->posts, $wpdb->postmeta, $wpdb->term_relationships ), true, false ), 'trashed_posts' => array( __( 'Empty the post and page trash', 'ai-guardwall' ), __( 'Posts, pages and products in the trash are deleted for good.', 'ai-guardwall' ), array( $wpdb->posts, $wpdb->postmeta, $wpdb->term_relationships ), true, false ), 'spam_comments' => array( __( 'Remove spam and trashed comments', 'ai-guardwall' ), __( 'Comments marked as spam or moved to the trash.', 'ai-guardwall' ), array( $wpdb->comments, $wpdb->commentmeta ), true, false ), 'unapproved_comments' => array( __( 'Remove unapproved comments', 'ai-guardwall' ), __( 'Comments still waiting for moderation. Check them first: real comments may be among them.', 'ai-guardwall' ), array( $wpdb->comments, $wpdb->commentmeta ), false, true ), 'pingbacks' => array( __( 'Remove pingbacks', 'ai-guardwall' ), __( 'Notifications other blogs send when they link to you; mostly spam today.', 'ai-guardwall' ), array( $wpdb->comments, $wpdb->commentmeta ), false, false ), 'trackbacks' => array( __( 'Remove trackbacks', 'ai-guardwall' ), __( 'The older form of pingbacks; mostly spam today.', 'ai-guardwall' ), array( $wpdb->comments, $wpdb->commentmeta ), false, false ), 'expired_transients' => array( __( 'Remove expired transients', 'ai-guardwall' ), __( 'Temporary cached data that has passed its expiry date.', 'ai-guardwall' ), array( $wpdb->options ), true, false ), 'all_transients' => array( __( 'Remove all transients', 'ai-guardwall' ), __( 'Every cached value plugins keep in the options table; they are rebuilt when needed, so pages may be slower for a moment.', 'ai-guardwall' ), array( $wpdb->options ), false, true ), 'oembed_cache' => array( __( 'Remove oEmbed caches', 'ai-guardwall' ), __( 'Cached previews of embedded videos and posts; rebuilt the next time they are shown.', 'ai-guardwall' ), array( $wpdb->posts, $wpdb->postmeta ), false, false ), 'orphan_postmeta' => array( __( 'Clean orphaned post meta', 'ai-guardwall' ), __( 'Settings of posts that no longer exist.', 'ai-guardwall' ), array( $wpdb->postmeta ), true, false ), 'orphan_commentmeta' => array( __( 'Clean orphaned comment meta', 'ai-guardwall' ), __( 'Data of comments that no longer exist.', 'ai-guardwall' ), array( $wpdb->commentmeta ), true, false ), 'orphan_usermeta' => array( __( 'Clean orphaned user meta', 'ai-guardwall' ), __( 'Data of user accounts that no longer exist.', 'ai-guardwall' ), array( $wpdb->usermeta ), false, false ), 'orphan_termmeta' => array( __( 'Clean orphaned term meta', 'ai-guardwall' ), __( 'Data of categories and tags that no longer exist.', 'ai-guardwall' ), array( $wpdb->termmeta ), false, false ), 'orphan_relationships' => array( __( 'Clean orphaned relationships', 'ai-guardwall' ), __( 'Links between deleted posts and their categories or tags.', 'ai-guardwall' ), array( $wpdb->term_relationships ), false, false ), ); } /** * How much each optimization would clean right now. * * @return array id => array( count, text, ... ) */ public static function overview() { global $wpdb; $out = array(); $items = self::items(); $keep = (int) self::settings()['keep_revisions']; foreach ( $items as $id => $item ) { $n = self::count( $id, $keep ); $out[ $id ] = array( 'id' => $id, 'title' => $item[0], 'desc' => $item[1], 'default' => $item[3], 'caution' => $item[4], 'count' => is_array( $n ) ? (int) $n['tables'] : (int) $n, 'text' => self::count_text( $id, $n ), ); if ( 'optimize_tables' === $id && is_array( $n ) ) { $out[ $id ]['gain'] = (int) $n['bytes']; } } $tables = Softvolt_Ai_Bodyguard_Db_Manager::tables(); $size = 0; foreach ( is_array( $tables ) ? $tables['tables'] : array() as $t ) { $size += $t['data'] + $t['index']; } return array( 'items' => array_values( $out ), 'database' => DB_NAME, 'tables' => is_array( $tables ) ? count( $tables['tables'] ) : 0, 'size' => $size, 'size_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( $size ), 'settings' => self::settings(), ); } private static function count_text( $id, $n ) { if ( 'optimize_tables' === $id ) { return $n['tables'] ? sprintf( /* translators: 1: tables, 2: size */ _n( '%1$d table can be optimized (about %2$s to gain).', '%1$d tables can be optimized (about %2$s to gain).', $n['tables'], 'ai-guardwall' ), $n['tables'], Softvolt_Ai_Bodyguard_Helpers::human_size( $n['bytes'] ) ) : __( 'Every table is already optimized.', 'ai-guardwall' ); } $labels = array( 'revisions' => /* translators: %d: number */ _n( '%d post revision in your database.', '%d post revisions in your database.', (int) $n, 'ai-guardwall' ), 'auto_drafts' => /* translators: %d: number */ _n( '%d auto-draft in your database.', '%d auto-drafts in your database.', (int) $n, 'ai-guardwall' ), 'trashed_posts' => /* translators: %d: number */ _n( '%d item in the trash.', '%d items in the trash.', (int) $n, 'ai-guardwall' ), 'spam_comments' => /* translators: %d: number */ _n( '%d spam or trashed comment.', '%d spam or trashed comments.', (int) $n, 'ai-guardwall' ), 'unapproved_comments' => /* translators: %d: number */ _n( '%d unapproved comment.', '%d unapproved comments.', (int) $n, 'ai-guardwall' ), 'pingbacks' => /* translators: %d: number */ _n( '%d pingback.', '%d pingbacks.', (int) $n, 'ai-guardwall' ), 'trackbacks' => /* translators: %d: number */ _n( '%d trackback.', '%d trackbacks.', (int) $n, 'ai-guardwall' ), 'expired_transients' => /* translators: %d: number */ _n( '%d expired transient.', '%d expired transients.', (int) $n, 'ai-guardwall' ), 'all_transients' => /* translators: %d: number */ _n( '%d transient in total.', '%d transients in total.', (int) $n, 'ai-guardwall' ), 'oembed_cache' => /* translators: %d: number */ _n( '%d cached embed.', '%d cached embeds.', (int) $n, 'ai-guardwall' ), 'orphan_postmeta' => /* translators: %d: number */ _n( '%d orphaned post meta row.', '%d orphaned post meta rows.', (int) $n, 'ai-guardwall' ), 'orphan_commentmeta' => /* translators: %d: number */ _n( '%d orphaned comment meta row.', '%d orphaned comment meta rows.', (int) $n, 'ai-guardwall' ), 'orphan_usermeta' => /* translators: %d: number */ _n( '%d orphaned user meta row.', '%d orphaned user meta rows.', (int) $n, 'ai-guardwall' ), 'orphan_termmeta' => /* translators: %d: number */ _n( '%d orphaned term meta row.', '%d orphaned term meta rows.', (int) $n, 'ai-guardwall' ), 'orphan_relationships' => /* translators: %d: number */ _n( '%d orphaned relationship.', '%d orphaned relationships.', (int) $n, 'ai-guardwall' ), ); if ( ! (int) $n ) { return __( 'Nothing to clean.', 'ai-guardwall' ); } return isset( $labels[ $id ] ) ? sprintf( $labels[ $id ], (int) $n ) : (string) $n; } /** * Post IDs that an optimization removes. * * @param string $id Optimization id. * @return int[] */ private static function post_ids( $id ) { global $wpdb; switch ( $id ) { case 'revisions': $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'revision'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'auto_drafts': $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'auto-draft'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'trashed_posts': $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'trash'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'oembed_cache': $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'oembed_cache'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; default: $ids = array(); } return array_map( 'intval', (array) $ids ); } /** * Comment IDs that an optimization removes. * * @param string $id Optimization id. * @return int[] */ private static function comment_ids( $id ) { global $wpdb; switch ( $id ) { case 'spam_comments': $ids = $wpdb->get_col( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved IN ('spam','trash','post-trashed')" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'unapproved_comments': $ids = $wpdb->get_col( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved = '0'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'pingbacks': $ids = $wpdb->get_col( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_type = 'pingback'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'trackbacks': $ids = $wpdb->get_col( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_type = 'trackback'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; default: $ids = array(); } return array_map( 'intval', (array) $ids ); } /** * Names of the timeout rows of transients that have run out. * * @return string[] */ private static function expired_transient_names() { global $wpdb; return (array) $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE ( option_name LIKE %s OR option_name LIKE %s ) AND option_value < %d", $wpdb->esc_like( '_transient_timeout_' ) . '%', $wpdb->esc_like( '_site_transient_timeout_' ) . '%', time() ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. } /** * Rows an optimization would remove (for optimize_tables: tables and bytes). */ public static function count( $id, $keep = 0 ) { global $wpdb; $wpdb->suppress_errors( true ); switch ( $id ) { case 'optimize_tables': $n = 0; $b = 0; foreach ( self::table_status() as $t ) { if ( $t['overhead'] > 0 ) { $n++; $b += $t['overhead']; } } $wpdb->suppress_errors( false ); return array( 'tables' => $n, 'bytes' => $b ); case 'revisions': $n = $keep > 0 ? count( self::revisions_to_delete( $keep ) ) : count( self::post_ids( 'revisions' ) ); break; case 'orphan_postmeta': $n = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE p.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_commentmeta': $n = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->commentmeta} cm LEFT JOIN {$wpdb->comments} c ON c.comment_ID = cm.comment_id WHERE c.comment_ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_usermeta': $n = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->usermeta} um LEFT JOIN {$wpdb->users} u ON u.ID = um.user_id WHERE u.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_termmeta': $n = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->termmeta} tm LEFT JOIN {$wpdb->terms} t ON t.term_id = tm.term_id WHERE t.term_id IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_relationships': $n = self::orphan_relationships( false ); break; case 'all_transients': $n = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->options} WHERE ( option_name LIKE '\\_transient\\_%' OR option_name LIKE '\\_site\\_transient\\_%' ) AND option_name NOT LIKE '%\\_timeout\\_%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; default: if ( 'expired_transients' === $id ) { $n = count( self::expired_transient_names() ); } else { $n = count( self::post_ids( $id ) ) + count( self::comment_ids( $id ) ); } } $wpdb->suppress_errors( false ); return $n; } /** * Relationships whose term no longer exists, or whose post no longer exists for taxonomies that only belong to posts. */ private static function orphan_relationships( $delete ) { global $wpdb; $tt_ids = array(); foreach ( get_taxonomies( array(), 'objects' ) as $tax ) { $types = (array) $tax->object_type; if ( $types && ! array_diff( $types, get_post_types() ) ) { $tt_ids = array_merge( $tt_ids, array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s", $tax->name ) ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. } } $tt_ids = array_values( array_unique( $tt_ids ) ); if ( ! $tt_ids ) { if ( $delete ) { return (int) $wpdb->query( "DELETE tr FROM {$wpdb->term_relationships} tr LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_taxonomy_id IS NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. } return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_relationships} tr LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_taxonomy_id IS NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. } $placeholders = implode( ',', array_fill( 0, count( $tt_ids ), '%d' ) ); if ( $delete ) { return (int) $wpdb->query( $wpdb->prepare( "DELETE tr FROM {$wpdb->term_relationships} tr LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id LEFT JOIN {$wpdb->posts} p ON p.ID = tr.object_id WHERE tt.term_taxonomy_id IS NULL OR ( tr.term_taxonomy_id IN ( {$placeholders} ) AND p.ID IS NULL )", $tt_ids ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). } return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->term_relationships} tr LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id LEFT JOIN {$wpdb->posts} p ON p.ID = tr.object_id WHERE tt.term_taxonomy_id IS NULL OR ( tr.term_taxonomy_id IN ( {$placeholders} ) AND p.ID IS NULL )", $tt_ids ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). } /** * Revision IDs to delete when the newest $keep per post are kept. */ private static function revisions_to_delete( $keep ) { global $wpdb; $rows = $wpdb->get_results( "SELECT ID, post_parent FROM {$wpdb->posts} WHERE post_type = 'revision' ORDER BY post_parent, post_date DESC, ID DESC" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $seen = array(); $out = array(); foreach ( (array) $rows as $r ) { $seen[ $r->post_parent ] = isset( $seen[ $r->post_parent ] ) ? $seen[ $r->post_parent ] + 1 : 1; if ( $seen[ $r->post_parent ] > $keep ) { $out[] = (int) $r->ID; } } return $out; } /** * Run optimizations. * * @param array $ids Optimization ids. * @param bool $backup Back up the touched tables first. * @return array results[], backup */ public static function run( array $ids, $backup = true ) { global $wpdb; $items = self::items(); $ids = array_values( array_intersect( array_keys( $items ), $ids ) ); Softvolt_Ai_Bodyguard_Helpers::raise_limits( 600 ); $touch = array(); foreach ( $ids as $id ) { if ( self::count( $id, (int) self::settings()['keep_revisions'] ) ) { $touch = array_merge( $touch, $items[ $id ][2] ); } } $saved = null; if ( $backup && $touch ) { $saved = self::backup( array_unique( $touch ), 'cleanup' ); if ( is_wp_error( $saved ) ) { return array( 'ok' => false, 'error' => $saved->get_error_message() ); } } $results = array(); $keep = (int) self::settings()['keep_revisions']; foreach ( $ids as $id ) { $results[ $id ] = self::run_one( $id, $keep ); } $total = array_sum( wp_list_pluck( $results, 'done' ) ); Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'db_cleanup', sprintf( /* translators: %s: list of array map */ __( 'Database cleaned: %s', 'ai-guardwall' ), implode( '; ', array_map( function ( $r ) { return $r['message']; }, $results ) ) ), array( 'removed' => $total, 'backup' => $saved ? basename( $saved['path'] ) : '' ) ); wp_cache_flush(); return array( 'ok' => true, 'results' => $results, 'backup' => $saved ? basename( $saved['path'] ) : '', 'overview' => self::overview() ); } private static function run_one( $id, $keep ) { global $wpdb; $items = self::items(); $done = 0; $wpdb->suppress_errors( true ); switch ( $id ) { case 'optimize_tables': $freed = 0; foreach ( self::table_status() as $t ) { if ( $t['overhead'] > 0 ) { $wpdb->query( $wpdb->prepare( 'OPTIMIZE TABLE %i', $t['name'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. $freed += $t['overhead']; $done++; } } $wpdb->suppress_errors( false ); return array( 'done' => $done, 'message' => $done ? sprintf( /* translators: 1: done, 2: size */ _n( '%1$d table optimized, about %2$s reclaimed.', '%1$d tables optimized, about %2$s reclaimed.', $done, 'ai-guardwall' ), $done, Softvolt_Ai_Bodyguard_Helpers::human_size( $freed ) ) : __( 'Every table was already optimized.', 'ai-guardwall' ) ); case 'revisions': case 'auto_drafts': case 'trashed_posts': case 'oembed_cache': if ( 'revisions' === $id && $keep > 0 ) { $posts = self::revisions_to_delete( $keep ); } else { $posts = self::post_ids( $id ); } foreach ( array_chunk( $posts, 500 ) as $chunk ) { $placeholders = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->postmeta} WHERE post_id IN ( {$placeholders} )", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->term_relationships} WHERE object_id IN ( {$placeholders} )", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->comments} WHERE comment_post_ID IN ( {$placeholders} ) AND comment_post_ID <> 0", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $done += (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->posts} WHERE ID IN ( {$placeholders} )", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). } break; case 'spam_comments': case 'unapproved_comments': case 'pingbacks': case 'trackbacks': $ids = self::comment_ids( $id ); $posts = array(); foreach ( array_chunk( $ids, 500 ) as $chunk ) { $placeholders = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); $posts = array_merge( $posts, array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT comment_post_ID FROM {$wpdb->comments} WHERE comment_ID IN ( {$placeholders} )", $chunk ) ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id IN ( {$placeholders} )", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $done += (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->comments} WHERE comment_ID IN ( {$placeholders} )", $chunk ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). } foreach ( array_unique( $posts ) as $pid ) { if ( $pid ) { wp_update_comment_count_now( $pid ); } } break; case 'expired_transients': $names = self::expired_transient_names(); foreach ( $names as $timeout ) { $value = str_replace( '_timeout_', '_', $timeout ); $done += (int) $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN (%s, %s)", $timeout, $value ) ) > 0 ? 1 : 0; } break; case 'all_transients': $done = (int) self::count( 'all_transients' ); $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\\_transient\\_%' OR option_name LIKE '\\_site\\_transient\\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. break; case 'orphan_postmeta': $done = (int) $wpdb->query( "DELETE pm FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE p.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_commentmeta': $done = (int) $wpdb->query( "DELETE cm FROM {$wpdb->commentmeta} cm LEFT JOIN {$wpdb->comments} c ON c.comment_ID = cm.comment_id WHERE c.comment_ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_usermeta': $done = (int) $wpdb->query( "DELETE um FROM {$wpdb->usermeta} um LEFT JOIN {$wpdb->users} u ON u.ID = um.user_id WHERE u.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_termmeta': $done = (int) $wpdb->query( "DELETE tm FROM {$wpdb->termmeta} tm LEFT JOIN {$wpdb->terms} t ON t.term_id = tm.term_id WHERE t.term_id IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'orphan_relationships': $done = self::orphan_relationships( true ); break; } $error = $wpdb->last_error; $wpdb->suppress_errors( false ); if ( '' !== $error ) { return array( 'done' => $done, 'error' => $error, 'message' => $items[ $id ][0] . ': ' . $error ); } /* translators: 1: optimization name, 2: number of removed rows. */ return array( 'done' => $done, 'message' => sprintf( __( '%1$s: %2$s removed.', 'ai-guardwall' ), $items[ $id ][0], number_format_i18n( $done ) ) ); } public static function auto_run() { $s = self::settings(); if ( 'off' === $s['schedule'] || ! $s['items'] ) { return; } $r = self::run( $s['items'], (bool) $s['backup'] ); $s['last_auto'] = time(); $s['last_result'] = isset( $r['results'] ) ? wp_list_pluck( $r['results'], 'message' ) : array( $r['error'] ?? '' ); update_option( self::OPTION, $s, false ); } /* -------------------------------- tables -------------------------------- */ /** * SHOW TABLE STATUS with real overhead: MyISAM/Aria free space, and InnoDB * free space only when the table is clearly fragmented. */ private static function table_status() { global $wpdb; $out = array(); foreach ( (array) $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A ) as $r ) { $data = (int) $r['Data_length']; $index = (int) $r['Index_length']; $free = (int) $r['Data_free']; $innodb = 'innodb' === strtolower( (string) $r['Engine'] ); $over = $innodb ? ( $free > 8 * MB_IN_BYTES && $free > 0.25 * ( $data + $index ) ? $free : 0 ) : $free; $out[] = array( 'name' => $r['Name'], 'engine' => (string) $r['Engine'], 'rows' => (int) $r['Rows'], 'data' => $data, 'index' => $index, 'overhead' => $over, 'comment' => (string) $r['Comment'], ); } return $out; } /** * Every table with its owner and what can be done with it. * * @param bool $refresh Search the plugin code again. * @return array */ public static function tables( $refresh = false ) { global $wpdb; $status = self::table_status(); $owners = self::owners( wp_list_pluck( $status, 'name' ), $refresh ); $rows = array(); $tot = array( 'rows' => 0, 'data' => 0, 'index' => 0, 'overhead' => 0, 'unused' => 0, 'unused_size' => 0 ); foreach ( $status as $t ) { $o = isset( $owners['map'][ $t['name'] ] ) ? $owners['map'][ $t['name'] ] : array( 'status' => 'unknown', 'owner' => '' ); $removable = in_array( $o['status'], array( 'not_installed', 'unknown', 'backup' ), true ) && ! $owners['partial']; $row = array_merge( $t, array( 'size_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( $t['data'] ), 'index_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( $t['index'] ), 'overhead_h' => $t['overhead'] ? Softvolt_Ai_Bodyguard_Helpers::human_size( $t['overhead'] ) : '', 'owner' => $o['owner'], 'status' => $o['status'], 'removable' => $removable, 'repairable' => in_array( strtolower( $t['engine'] ), array( 'myisam', 'aria' ), true ), ) ); $rows[] = $row; foreach ( array( 'rows', 'data', 'index', 'overhead' ) as $k ) { $tot[ $k ] += $t[ $k ]; } if ( $removable ) { $tot['unused']++; $tot['unused_size'] += $t['data'] + $t['index']; } } $tot['data_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $tot['data'] ); $tot['index_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $tot['index'] ); $tot['overhead_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $tot['overhead'] ); $tot['unused_size_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $tot['unused_size'] ); return array( 'tables' => $rows, 'totals' => $tot, 'prefix' => $wpdb->prefix, 'checked' => $owners['checked'], 'partial' => $owners['partial'], 'progress' => isset( $owners['progress'] ) ? (int) $owners['progress'] : 100 ); } /** * Who owns each table: WordPress, AI GuardWall, a backup copy, a known plugin * (active, inactive or not installed), a plugin or theme whose code names it, * or nobody (unknown: probably left over from a deleted plugin). * * @param array $names Table names. * @param bool $refresh Ignore the cached code search. * @return array map, checked, partial */ public static function owners( array $names, $refresh = false ) { global $wpdb; if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $core = array( 'commentmeta', 'comments', 'links', 'options', 'postmeta', 'posts', 'termmeta', 'terms', 'term_relationships', 'term_taxonomy', 'usermeta', 'users', 'blogs', 'blogmeta', 'blog_versions', 'registration_log', 'signups', 'site', 'sitemeta' ); $plugins = self::installed_plugins(); $themes = wp_get_themes(); $key = 'svabg_dbopt_owners_' . md5( wp_json_encode( array( $names, array_keys( $plugins ), array_keys( $themes ), get_option( 'active_plugins' ), get_stylesheet() ) ) ); $cached = $refresh ? false : get_transient( $key ); if ( is_array( $cached ) ) { return $cached; } $map = array(); $pending = array(); foreach ( $names as $name ) { $short = 0 === strpos( $name, $wpdb->prefix ) ? substr( $name, strlen( $wpdb->prefix ) ) : null; if ( 0 === strpos( $name, '_svabg_bak_' ) ) { $map[ $name ] = array( 'status' => 'backup', 'owner' => __( 'AI GuardWall backup copy', 'ai-guardwall' ) ); } elseif ( null === $short ) { $map[ $name ] = array( 'status' => 'foreign', 'owner' => __( 'Not this site (other prefix)', 'ai-guardwall' ) ); } elseif ( in_array( $short, $core, true ) ) { $map[ $name ] = array( 'status' => 'core', 'owner' => 'WordPress' ); } elseif ( 0 === strpos( $short, 'svabg_' ) ) { $map[ $name ] = array( 'status' => 'bodyguard', 'owner' => 'AI GuardWall' ); } else { $found = false; foreach ( self::KNOWN as $pattern => $info ) { if ( preg_match( '#' . $pattern . '#i', $short ) ) { $state = 'not_installed'; $label = $info[1]; foreach ( $info[0] as $folder ) { if ( isset( $plugins[ $folder ] ) ) { $label = $plugins[ $folder ]['name']; $state = $plugins[ $folder ]['active'] ? 'active' : ( 'not_installed' === $state ? 'inactive' : $state ); if ( 'active' === $state ) { break; } } } // Action Scheduler ships inside many plugins: in use whenever its class is loaded. if ( 'Action Scheduler' === $info[1] && class_exists( 'ActionScheduler' ) ) { $state = 'active'; } $map[ $name ] = array( 'status' => $state, 'owner' => $label ); $found = true; break; } } if ( ! $found ) { $pending[ $name ] = $short; } } } $partial = false; $progress = 100; if ( $pending ) { $res = self::search_code( $key, $pending, $plugins, $themes, $refresh ); $partial = ! $res['done']; $progress = $res['progress']; foreach ( $pending as $name => $short ) { $map[ $name ] = isset( $res['found'][ $name ] ) ? $res['found'][ $name ] : array( 'status' => 'unknown', 'owner' => '' ); } } $out = array( 'map' => $map, 'checked' => time(), 'partial' => $partial, 'progress' => $progress ); if ( ! $partial ) { set_transient( $key, $out, 12 * HOUR_IN_SECONDS ); delete_option( self::SEARCH ); } return $out; } /** * folder => name, active (plus mu-plugins as one active "folder"). */ private static function installed_plugins() { $out = array(); foreach ( get_plugins() as $file => $data ) { $folder = false !== strpos( $file, '/' ) ? dirname( $file ) : basename( $file, '.php' ); $active = is_plugin_active( $file ) || ( is_multisite() && is_plugin_active_for_network( $file ) ); if ( ! isset( $out[ $folder ] ) || $active ) { $out[ $folder ] = array( 'name' => $data['Name'], 'active' => $active, 'dir' => Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/plugins' ) . '/' . ( false !== strpos( $file, '/' ) ? dirname( $file ) : $file ) ); } } return $out; } /** * Where table names are searched: plugins, themes and MU plugins, smallest first * (a plugin's own tables are named in its own code; huge plugins rarely own unknown tables). * * @return array[] array( dir, name, active|inactive, bytes ) */ private static function search_places( array $plugins, $themes ) { $places = array(); foreach ( $plugins as $p ) { $places[] = array( $p['dir'], $p['name'], $p['active'] ? 'active' : 'inactive' ); } foreach ( $themes as $slug => $theme ) { $active = $slug === get_stylesheet() || $slug === get_template(); $places[] = array( $theme->get_stylesheet_directory(), sprintf( /* translators: %s: value */ __( 'Theme: %s', 'ai-guardwall' ), $theme->get( 'Name' ) ), $active ? 'active' : 'inactive' ); } $mu = Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/mu-plugins' ); if ( is_dir( $mu ) ) { $places[] = array( $mu, __( 'Must-use plugins', 'ai-guardwall' ), 'active' ); } foreach ( $places as &$place ) { $place[3] = array_sum( array_column( self::php_files( $place[0] ), 1 ) ); } unset( $place ); usort( $places, function ( $a, $b ) { return $a[3] - $b[3]; } ); return $places; } /** * The PHP files of a folder (without vendor, tests, languages and build folders), in a stable order. * * @return array[] array( path, bytes ) */ private static function php_files( $dir ) { $out = array(); if ( is_file( $dir ) ) { return 'php' === strtolower( pathinfo( $dir, PATHINFO_EXTENSION ) ) ? array( array( $dir, (int) filesize( $dir ) ) ) : array(); } if ( ! is_dir( $dir ) ) { return $out; } $skip = '#[\\\\/](?:vendor|node_modules|tests?|languages|lang|assets|dist|build|\.git)[\\\\/]#i'; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS ) ); foreach ( $it as $file ) { if ( $file->isFile() && 'php' === strtolower( $file->getExtension() ) && $file->getSize() < 2 * MB_IN_BYTES && ! preg_match( $skip, substr( $file->getPathname(), strlen( $dir ) ) ) ) { $out[] = array( $file->getPathname(), (int) $file->getSize() ); } } } catch ( Exception $e ) { return $out; } usort( $out, function ( $a, $b ) { return strcmp( $a[0], $b[0] ); } ); return $out; } /** * Look for the table names in the installed code, a few seconds per call: * the position is kept between calls, so a big site is searched in steps. * * @return array found (name => owner), done, progress (0-100) */ private static function search_code( $key, array $pending, array $plugins, $themes, $restart = false ) { $deadline = microtime( true ) + self::SEARCH_BUDGET; $state = get_option( self::SEARCH, array() ); if ( $restart || ! is_array( $state ) || ( isset( $state['key'] ) ? $state['key'] : '' ) !== $key ) { $state = array( 'key' => $key, 'places' => self::search_places( $plugins, $themes ), 'place' => 0, 'file' => 0, 'found' => array() ); } // The whole name, and a distinctive prefix ("myplugin_") when it is long enough (only inside quotes). $needles = array(); foreach ( $pending as $name => $short ) { $needles[ $name ] = array( strtolower( $short ) ); if ( preg_match( '/^([a-z0-9]{4,})_/i', $short, $m ) && ! in_array( strtolower( $m[1] ), array( 'user', 'post', 'term', 'data', 'site', 'blog', 'wp', 'options', 'meta', 'list', 'item', 'items', 'temp', 'test', 'cache', 'logs', 'table' ), true ) ) { $needles[ $name ][] = strtolower( $m[1] ) . '_'; } } // A match ranks by how sure it is: the full table name (2) beats a quoted prefix (1); an active owner beats an inactive one. $rank = function ( $strength, $status ) { return $strength * 2 + ( 'active' === $status ? 1 : 0 ); }; $found = (array) $state['found']; $total = array_sum( array_column( $state['places'], 3 ) ); $done = true; while ( $state['place'] < count( $state['places'] ) ) { $sure = count( $found ) === count( $pending ) && ! array_filter( $found, function ( $f ) { return 5 !== $f['rank']; } ); if ( $sure ) { break; } $place = $state['places'][ $state['place'] ]; $files = self::php_files( $place[0] ); for ( $j = (int) $state['file']; $j < count( $files ); $j++ ) { if ( microtime( true ) > $deadline ) { $state['file'] = $j; $done = false; break 2; } $code = (string) @file_get_contents( $files[ $j ][0] ); if ( '' === $code ) { continue; } foreach ( $needles as $name => $list ) { $have = isset( $found[ $name ] ) ? $found[ $name ]['rank'] : -1; if ( $have >= $rank( 2, $place[2] ) ) { continue; } foreach ( $list as $n => $needle ) { $strength = 0 === $n ? 2 : 1; if ( $rank( $strength, $place[2] ) <= $have ) { continue; } $hit = 0 === $n ? false !== stripos( $code, $needle ) : (bool) preg_match( '/[\'"]' . preg_quote( $needle, '/' ) . '/', $code ); if ( $hit ) { $found[ $name ] = array( 'status' => $place[2], 'owner' => $place[1], 'rank' => $rank( $strength, $place[2] ) ); break; } } } } if ( ! $done ) { break; } $state['place']++; $state['file'] = 0; } $state['found'] = $found; $progress = 100; if ( ! $done ) { $before = array_sum( array_column( array_slice( $state['places'], 0, $state['place'] ), 3 ) ); $cur = $state['places'][ $state['place'] ]; $files = self::php_files( $cur[0] ); $part = $files ? array_sum( array_column( array_slice( $files, 0, $state['file'] ), 1 ) ) : 0; $progress = $total ? min( 99, (int) floor( ( $before + $part ) * 100 / $total ) ) : 99; update_option( self::SEARCH, $state, false ); } foreach ( $found as &$f ) { unset( $f['rank'] ); } unset( $f ); return array( 'found' => $found, 'done' => $done, 'progress' => $progress ); } /** * optimize, repair or remove one table. */ public static function table_action( $table, $action, $backup = true ) { $tables = self::tables(); $row = null; foreach ( $tables['tables'] as $t ) { if ( $t['name'] === $table ) { $row = $t; break; } } if ( ! $row ) { return new WP_Error( 'svabg_db_table', __( 'That table does not exist in this database.', 'ai-guardwall' ) ); } switch ( $action ) { case 'optimize': case 'repair': $r = Softvolt_Ai_Bodyguard_Db_Manager::table_op( $table, $action ); return is_wp_error( $r ) ? $r : array( 'message' => $r['message'] ); case 'remove': if ( ! $row['removable'] ) { return new WP_Error( 'svabg_db_keep', __( 'This table is in use (WordPress, AI GuardWall or an installed plugin), so it cannot be removed here.', 'ai-guardwall' ) ); } $saved = null; if ( $backup ) { $saved = self::backup( array( $table ), 'table-' . $table ); if ( is_wp_error( $saved ) ) { return $saved; } } $r = Softvolt_Ai_Bodyguard_Db_Manager::table_op( $table, 'drop' ); if ( is_wp_error( $r ) ) { return $r; } Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'db_cleanup', sprintf( /* translators: 1: table, 2: value */ __( 'Unused table %1$s removed (%2$s).', 'ai-guardwall' ), $table, $saved ? sprintf( /* translators: %s: file name */ __( 'backup %s', 'ai-guardwall' ), basename( $saved['path'] ) ) : __( 'no backup', 'ai-guardwall' ) ) ); return array( 'message' => sprintf( /* translators: %s: table */ __( 'Table %s removed.', 'ai-guardwall' ), $table ) . ( $saved ? ' ' . sprintf( /* translators: %s: file name */ __( 'Backup: %s', 'ai-guardwall' ), basename( $saved['path'] ) ) : '' ) ); } return new WP_Error( 'svabg_db_op', __( 'Unknown table action.', 'ai-guardwall' ) ); } /** * Optimize every table that has overhead (or the ones named). */ public static function optimize_tables( array $only = array() ) { global $wpdb; $done = array(); $freed = 0; Softvolt_Ai_Bodyguard_Helpers::raise_limits( 600 ); foreach ( self::table_status() as $t ) { if ( ( $only && in_array( $t['name'], $only, true ) ) || ( ! $only && $t['overhead'] > 0 ) ) { $wpdb->query( $wpdb->prepare( 'OPTIMIZE TABLE %i', $t['name'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. $done[] = $t['name']; $freed += $t['overhead']; } } Softvolt_Ai_Bodyguard_Logger::log( 'info', 'db_cleanup', sprintf( /* translators: %d: number of done */ _n( '%d table optimized.', '%d tables optimized.', count( $done ), 'ai-guardwall' ), count( $done ) ) ); return array( 'done' => $done, 'freed' => $freed, 'message' => $done ? sprintf( /* translators: 1: number of done, 2: size */ _n( '%1$d table optimized, about %2$s reclaimed.', '%1$d tables optimized, about %2$s reclaimed.', count( $done ), 'ai-guardwall' ), count( $done ), Softvolt_Ai_Bodyguard_Helpers::human_size( $freed ) ) : __( 'Every table was already optimized.', 'ai-guardwall' ) ); } /* -------------------------------- backups ------------------------------- */ public static function backup_dir() { return Softvolt_Ai_Bodyguard_Helpers::work_dir( 'db-backups' ); } /** * Save tables before a change; keeps the newest backups only. */ public static function backup( array $tables, $label ) { $file = self::backup_dir() . '/' . gmdate( 'Y-m-d-His' ) . '-' . sanitize_file_name( substr( $label, 0, 60 ) ) . '-' . strtolower( wp_generate_password( 16, false, false ) ) . '.sql.gz'; $saved = Softvolt_Ai_Bodyguard_Db_Manager::dump_to_file( $tables, $file ); if ( ! is_wp_error( $saved ) ) { $all = self::backups(); foreach ( array_slice( $all, self::KEEP_FILES ) as $old ) { wp_delete_file( self::backup_dir() . '/' . $old['file'] ); } } return $saved; } public static function backups() { $out = array(); foreach ( (array) glob( self::backup_dir() . '/*.sql*' ) as $path ) { $out[] = array( 'file' => basename( $path ), 'size' => (int) filesize( $path ), 'size_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( (int) filesize( $path ) ), 'time' => (int) filemtime( $path ), 'ago' => human_time_diff( (int) filemtime( $path ) ), 'url' => wp_nonce_url( admin_url( 'admin-post.php?action=svabg_dbopt_download&file=' . rawurlencode( basename( $path ) ) ), 'svabg_dbopt_download' ), ); } usort( $out, function ( $a, $b ) { return $b['time'] - $a['time']; } ); return $out; } public static function backup_path( $file ) { $file = basename( (string) $file ); if ( ! preg_match( '/^[A-Za-z0-9._-]+\.sql(\.gz)?$/', $file ) ) { return ''; } $path = self::backup_dir() . '/' . $file; return is_file( $path ) ? $path : ''; } public static function delete_backup( $file ) { $path = self::backup_path( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- removes a file the plugin manages and needs the result. return '' !== $path && @unlink( $path ); } /** * admin-post: download a backup file. */ public static function download() { if ( ! current_user_can( Softvolt_Ai_Bodyguard::cap() ) ) { wp_die( esc_html__( 'You are not allowed to do that.', 'ai-guardwall' ), 403 ); } check_admin_referer( 'svabg_dbopt_download' ); $path = self::backup_path( isset( $_GET['file'] ) ? sanitize_file_name( wp_unslash( $_GET['file'] ) ) : '' ); if ( '' === $path ) { wp_die( esc_html__( 'That backup does not exist.', 'ai-guardwall' ), 404 ); } while ( ob_get_level() ) { ob_end_clean(); } nocache_headers(); header( 'Content-Type: application/gzip' ); header( 'Content-Disposition: attachment; filename="' . basename( $path ) . '"' ); header( 'Content-Length: ' . filesize( $path ) ); readfile( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile exit; } public static function remove() { wp_clear_scheduled_hook( self::HOOK ); delete_option( self::OPTION ); delete_option( self::SEARCH ); } }