true, 'reason' => '', 'database' => DB_NAME, 'prefix' => $GLOBALS['wpdb']->prefix, 'server' => self::server_version(), 'charset' => $GLOBALS['wpdb']->charset, ); } /** * "8.0.35" from a server string such as "8.0.35-0ubuntu0.22.04.1" or "5.5.5-10.6.12-MariaDB". */ private static function server_version() { global $wpdb; $info = (string) $wpdb->db_server_info(); if ( preg_match( '/(\d+\.\d+\.\d+)-MariaDB/i', $info, $m ) ) { return $m[1] . ' (MariaDB)'; } return preg_match( '/^(\d+\.\d+\.\d+)/', $info, $m ) ? $m[1] : $info; } private static function allowed() { $status = self::status(); return $status['enabled'] ? true : new WP_Error( 'svabg_db_off', $status['reason'] ); } /** * The raw mysqli connection WordPress uses. * * @return mysqli|WP_Error */ private static function conn() { global $wpdb; $dbh = $wpdb->dbh; if ( ! ( $dbh instanceof mysqli ) ) { return new WP_Error( 'svabg_db_conn', __( 'The database connection is not a MySQL connection this manager can use.', 'ai-guardwall' ) ); } return $dbh; } public static function quote_id( $name ) { return '`' . str_replace( '`', '``', (string) $name ) . '`'; } private static function table_exists( $table ) { if ( in_array( (string) $table, array_column( self::tables_raw(), 'name' ), true ) ) { return true; } self::forget_tables(); return in_array( (string) $table, array_column( self::tables_raw(), 'name' ), true ); } private static $tables_cache = null; private static function tables_raw() { global $wpdb; if ( null !== self::$tables_cache ) { return self::$tables_cache; } $rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A ); $cache = array(); foreach ( (array) $rows as $row ) { $cache[] = array( 'name' => $row['Name'], 'engine' => (string) $row['Engine'], 'rows' => (int) $row['Rows'], 'data' => (int) $row['Data_length'], 'index' => (int) $row['Index_length'], 'collation' => (string) $row['Collation'], 'auto' => isset( $row['Auto_increment'] ) ? (int) $row['Auto_increment'] : 0, 'comment' => (string) $row['Comment'], 'updated' => (string) $row['Update_time'], // InnoDB reports pre-allocated tablespace space here, not reclaimable overhead. 'free' => isset( $row['Data_free'] ) && 'innodb' !== strtolower( (string) $row['Engine'] ) ? (int) $row['Data_free'] : 0, ); } self::$tables_cache = $cache; return $cache; } private static function forget_tables() { self::$tables_cache = null; } /* ------------------------------ tables ------------------------------ */ /** * Every table in this database, with WordPress/AI GuardWall/other labels. */ public static function tables() { $ok = self::allowed(); if ( is_wp_error( $ok ) ) { return $ok; } global $wpdb; $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' ); $out = array(); $total = 0; foreach ( self::tables_raw() as $t ) { $kind = 'other'; if ( 0 === strpos( $t['name'], $wpdb->prefix . 'svabg_' ) ) { $kind = 'bodyguard'; } elseif ( 0 === strpos( $t['name'], $wpdb->prefix ) && in_array( substr( $t['name'], strlen( $wpdb->prefix ) ), $core, true ) ) { $kind = 'core'; } elseif ( 0 === strpos( $t['name'], $wpdb->prefix ) ) { $kind = 'plugin'; } elseif ( 0 === strpos( $t['name'], '_svabg_bak_' ) ) { $kind = 'backup'; } $t['kind'] = $kind; $t['size_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $t['data'] + $t['index'] ); $total += $t['data'] + $t['index']; $out[] = $t; } return array( 'database' => DB_NAME, 'prefix' => $wpdb->prefix, 'tables' => $out, 'size_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( $total ), 'status' => self::status(), ); } private static function table_status( $table ) { foreach ( self::tables_raw() as $t ) { if ( $t['name'] === $table ) { $t['size_h'] = Softvolt_Ai_Bodyguard_Helpers::human_size( $t['data'] + $t['index'] ); return $t; } } return null; } /* ------------------------------ rows ------------------------------ */ /* ------------------------------ SQL console ------------------------------ */ /* ------------------------------ table operations ------------------------------ */ /** * Copy a table (structure and data) to _svabg_bak__. */ public static function backup_table( $table ) { $ok = self::allowed(); if ( is_wp_error( $ok ) ) { return $ok; } if ( ! self::table_exists( $table ) ) { return new WP_Error( 'svabg_db_table', __( 'That table does not exist in this database.', 'ai-guardwall' ) ); } global $wpdb; $name = '_svabg_bak_' . $table . '_' . gmdate( 'Ymd_His' ); if ( strlen( $name ) > 64 ) { $name = substr( '_svabg_bak_' . substr( md5( $table ), 0, 8 ) . '_' . $table, 0, 48 ) . '_' . gmdate( 'Ymd_His' ); } $wpdb->suppress_errors( true ); $ok1 = $wpdb->query( $wpdb->prepare( 'CREATE TABLE %i LIKE %i', $name, $table ) ); $ok2 = false !== $ok1 ? $wpdb->query( $wpdb->prepare( 'INSERT INTO %i SELECT * FROM %i', $name, $table ) ) : false; $error = $wpdb->last_error; $wpdb->suppress_errors( false ); if ( false === $ok1 || false === $ok2 ) { return new WP_Error( 'svabg_db_query', $error ? $error : __( 'The backup table could not be created.', 'ai-guardwall' ) ); } self::forget_tables(); self::log( 'db_table_backup', sprintf( /* translators: 1: table, 2: name */ __( 'Table %1$s copied to %2$s', 'ai-guardwall' ), $table, $name ) ); return array( 'message' => sprintf( /* translators: %s: name */ __( 'Backup copy created: %s', 'ai-guardwall' ), $name ), 'table' => $name ); } /** * optimize, repair, check, analyze, truncate, drop, rename, copy, backup. */ public static function table_op( $table, $op, $arg = '' ) { $ok = self::allowed(); if ( is_wp_error( $ok ) ) { return $ok; } if ( ! self::table_exists( $table ) ) { return new WP_Error( 'svabg_db_table', __( 'That table does not exist in this database.', 'ai-guardwall' ) ); } global $wpdb; $sql = ''; $done = ''; switch ( $op ) { case 'backup': return self::backup_table( $table ); case 'optimize': case 'repair': case 'check': case 'analyze': if ( 'optimize' === $op ) { $sql = $wpdb->prepare( 'OPTIMIZE TABLE %i', $table ); } elseif ( 'repair' === $op ) { $sql = $wpdb->prepare( 'REPAIR TABLE %i', $table ); } elseif ( 'check' === $op ) { $sql = $wpdb->prepare( 'CHECK TABLE %i', $table ); } else { $sql = $wpdb->prepare( 'ANALYZE TABLE %i', $table ); } $done = strtoupper( $op ) . ' %s'; break; case 'truncate': $sql = $wpdb->prepare( 'TRUNCATE TABLE %i', $table ); $done = sprintf( /* translators: %s: table */ __( 'Table %s emptied.', 'ai-guardwall' ), $table ); break; case 'drop': $sql = $wpdb->prepare( 'DROP TABLE %i', $table ); $done = sprintf( /* translators: %s: table */ __( 'Table %s dropped.', 'ai-guardwall' ), $table ); break; case 'rename': case 'copy': $arg = (string) $arg; if ( ! preg_match( '/^[A-Za-z0-9_$]{1,64}$/', $arg ) ) { return new WP_Error( 'svabg_db_name', __( 'Use letters, digits and underscores for the new table name.', 'ai-guardwall' ) ); } if ( self::table_exists( $arg ) ) { return new WP_Error( 'svabg_db_exists', __( 'A table with that name already exists.', 'ai-guardwall' ) ); } if ( 'rename' === $op ) { $sql = $wpdb->prepare( 'RENAME TABLE %i TO %i', $table, $arg ); $done = sprintf( /* translators: %s: arg */ __( 'Table renamed to %s.', 'ai-guardwall' ), $arg ); } else { $wpdb->suppress_errors( true ); $ok1 = $wpdb->query( $wpdb->prepare( 'CREATE TABLE %i LIKE %i', $arg, $table ) ); $ok2 = false !== $ok1 ? $wpdb->query( $wpdb->prepare( 'INSERT INTO %i SELECT * FROM %i', $arg, $table ) ) : false; $error = $wpdb->last_error; $wpdb->suppress_errors( false ); if ( false === $ok1 || false === $ok2 ) { return new WP_Error( 'svabg_db_query', $error ? $error : __( 'The table could not be copied.', 'ai-guardwall' ) ); } self::forget_tables(); self::log( 'db_table_op', sprintf( /* translators: 1: table, 2: arg */ __( 'Table %1$s copied to %2$s', 'ai-guardwall' ), $table, $arg ) ); return array( 'message' => sprintf( /* translators: %s: arg */ __( 'Table copied to %s.', 'ai-guardwall' ), $arg ) ); } break; default: return new WP_Error( 'svabg_db_op', __( 'Unknown table operation.', 'ai-guardwall' ) ); } $wpdb->suppress_errors( true ); $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared -- Already prepared with %i in the switch above. $error = $wpdb->last_error; $wpdb->suppress_errors( false ); if ( '' !== $error ) { return new WP_Error( 'svabg_db_query', $error ); } self::forget_tables(); self::after_change( $table ); $status = ''; foreach ( (array) $rows as $r ) { if ( isset( $r['Msg_type'], $r['Msg_text'] ) ) { $status .= $r['Msg_type'] . ': ' . $r['Msg_text'] . ' '; } } self::log( 'db_table_op', sprintf( /* translators: 1: operation, 2: table */ __( 'Table operation %1$s on %2$s', 'ai-guardwall' ), $op, $table ), array( 'result' => trim( $status ) ) ); return array( 'message' => false !== strpos( $done, '%s' ) ? sprintf( $done, trim( $status ) ) : $done ); } private static function after_change( $table ) { global $wpdb; // Keep WordPress's caches honest after direct edits. if ( $wpdb->options === $table ) { wp_cache_flush(); } elseif ( in_array( $table, array( $wpdb->posts, $wpdb->postmeta, $wpdb->users, $wpdb->usermeta, $wpdb->terms, $wpdb->term_taxonomy, $wpdb->term_relationships, $wpdb->comments, $wpdb->commentmeta ), true ) ) { wp_cache_flush(); } } /* ------------------------------ export ------------------------------ */ /** * Write an SQL dump of tables through an emitter (shared by the download and the backup files). * * @param mysqli $conn Connection. * @param array $tables Table names (validated). * @param bool $with_data Include INSERTs. * @param callable $emit function ( string $chunk, bool $final ). */ private static function write_dump( mysqli $conn, array $tables, $with_data, callable $emit ) { global $wpdb; $emit( "-- AI GuardWall SQL dump\n-- Database: " . DB_NAME . "\n-- Site: " . home_url() . "\n-- Generated: " . gmdate( 'Y-m-d H:i:s' ) . " UTC\n\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\nSET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';\n\n" ); foreach ( $tables as $table ) { $q = self::quote_id( $table ); $create = $wpdb->get_row( $wpdb->prepare( 'SHOW CREATE TABLE %i', $table ), ARRAY_N ); $emit( "--\n-- Table {$table}\n--\n\nDROP TABLE IF EXISTS {$q};\n" . ( $create ? $create[1] : '' ) . ";\n\n" ); if ( ! $with_data ) { continue; } $res = $conn->query( "SELECT * FROM {$q}", MYSQLI_USE_RESULT ); if ( ! $res ) { $emit( '-- could not read ' . $table . ': ' . $conn->error . "\n\n" ); continue; } $fields = $res->fetch_fields(); $cols = array(); foreach ( $fields as $f ) { $cols[] = self::quote_id( $f->name ); } $binary = array(); foreach ( $fields as $idx => $f ) { $binary[ $idx ] = ( $f->flags & MYSQLI_BINARY_FLAG ) && in_array( $f->type, array( MYSQLI_TYPE_TINY_BLOB, MYSQLI_TYPE_MEDIUM_BLOB, MYSQLI_TYPE_LONG_BLOB, MYSQLI_TYPE_BLOB, MYSQLI_TYPE_STRING, MYSQLI_TYPE_VAR_STRING ), true ) && 63 === (int) $f->charsetnr; } $numeric = array(); foreach ( $fields as $idx => $f ) { $numeric[ $idx ] = in_array( $f->type, array( MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_LONG, MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE, MYSQLI_TYPE_LONGLONG, MYSQLI_TYPE_INT24, MYSQLI_TYPE_DECIMAL, MYSQLI_TYPE_NEWDECIMAL, MYSQLI_TYPE_YEAR ), true ); } $batch = array(); $bytes = 0; $head = "INSERT INTO {$q} (" . implode( ', ', $cols ) . ") VALUES\n"; while ( $row = $res->fetch_row() ) { $vals = array(); foreach ( $row as $idx => $v ) { if ( null === $v ) { $vals[] = 'NULL'; } elseif ( $numeric[ $idx ] && is_numeric( $v ) ) { $vals[] = $v; } elseif ( $binary[ $idx ] ) { $vals[] = '' === $v ? "''" : '0x' . bin2hex( $v ); } else { $vals[] = "'" . $conn->real_escape_string( $v ) . "'"; } } $line = '(' . implode( ', ', $vals ) . ')'; $batch[] = $line; $bytes += strlen( $line ); if ( count( $batch ) >= 200 || $bytes > 900000 ) { $emit( $head . implode( ",\n", $batch ) . ";\n" ); $batch = array(); $bytes = 0; } } if ( $batch ) { $emit( $head . implode( ",\n", $batch ) . ";\n" ); } $res->free(); $emit( "\n" ); } $emit( "SET FOREIGN_KEY_CHECKS=1;\n", true ); } /** * Save tables as a gzipped SQL file (taken before cleanups and table removals). * * @param array $tables Table names. * @param string $path Target .sql.gz file. * @return array|WP_Error array( path, size, tables ) */ public static function dump_to_file( array $tables, $path ) { $ok = self::allowed(); if ( is_wp_error( $ok ) ) { return $ok; } $conn = self::conn(); if ( is_wp_error( $conn ) ) { return $conn; } $all = array_column( self::tables_raw(), 'name' ); $tables = array_values( array_intersect( $all, $tables ) ); if ( ! $tables ) { return new WP_Error( 'svabg_db_table', __( 'No tables to back up.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Helpers::raise_limits( 300 ); $gz = function_exists( 'gzopen' ) ? @gzopen( $path, 'wb6' ) : false; if ( ! $gz ) { $path = preg_replace( '/\.gz$/', '', $path ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- large files are streamed in chunks; WP_Filesystem cannot stream. $fh = $gz ? null : @fopen( $path, 'wb' ); if ( ! $gz && ! $fh ) { return new WP_Error( 'svabg_db_backup', __( 'The backup file could not be written (uploads folder not writable).', 'ai-guardwall' ) ); } self::write_dump( $conn, $tables, true, function ( $chunk ) use ( $gz, $fh ) { if ( $gz ) { gzwrite( $gz, $chunk ); } else { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite -- large files are streamed in chunks; WP_Filesystem cannot stream. fwrite( $fh, $chunk ); } } ); if ( $gz ) { gzclose( $gz ); } else { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- large files are streamed in chunks; WP_Filesystem cannot stream. fclose( $fh ); } clearstatcache( true, $path ); self::log( 'db_table_backup', sprintf( /* translators: 1: number of tables, 2: file name */ _n( 'Backup of %1$d table saved: %2$s', 'Backup of %1$d tables saved: %2$s', count( $tables ), 'ai-guardwall' ), count( $tables ), basename( $path ) ) ); return array( 'path' => $path, 'size' => (int) filesize( $path ), 'tables' => $tables ); } /* ------------------------------ import ------------------------------ */ private static function log( $event, $message, $data = array() ) { Softvolt_Ai_Bodyguard_Logger::log( 'notice', $event, $message, $data ); } }