suppress_errors( true ); $last = $wpdb->last_error; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- planning the caller's own statement; it is never executed. $wpdb->get_results( 'EXPLAIN ' . $sql ); $failed = '' !== (string) $wpdb->last_error; if ( $failed ) { $wpdb->last_error = $last; $wpdb->suppress_errors( $suppressed ); return array(); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- MySQL's rewritten form of the statement just planned. $warnings = $wpdb->get_results( 'SHOW WARNINGS', ARRAY_A ); $wpdb->last_error = $last; $wpdb->suppress_errors( $suppressed ); if ( ! is_array( $warnings ) || array() === $warnings ) { return array(); } $normalised = ''; foreach ( $warnings as $row ) { $normalised .= ' ' . (string) ( $row['Message'] ?? '' ); } return self::qualified_names( $normalised ); } /** * Table names out of MySQL's rewritten statement. * * Matches `` `db`.`name` `` for the current database only, and excludes anything immediately * followed by a further `.` — MySQL qualifies column references the same way * (`` `local`.`p`.`ID` ``), so without the lookahead every alias is collected as if it were a * table. * * @since 0.0.45 * @param string $normalised MySQL's rewritten statement. * @return string[] */ private static function qualified_names( string $normalised ): array { $database = defined( 'DB_NAME' ) ? (string) DB_NAME : ''; if ( '' === $database ) { return array(); } $pattern = '/`' . preg_quote( $database, '/' ) . '`\.`([A-Za-z0-9_]+)`(?!\s*\.)/'; if ( ! preg_match_all( $pattern, $normalised, $matches ) ) { return array(); } return array_values( array_unique( $matches[1] ) ); } /** * Tables named in the obvious places, found without asking the database. * * Comments are stripped first so a name cannot be hidden behind one, and so a commented-out * clause does not produce a refusal that makes no sense to the caller. * * @since 0.0.45 * @param string $sql Raw statement. * @return string[] */ private static function from_scan( string $sql ): array { $stripped = (string) preg_replace( '#/\*.*?\*/|--[^\n]*|\#[^\n]*#s', ' ', $sql ); if ( ! preg_match_all( '/\b(?:FROM|JOIN|INTO|UPDATE|TABLE)\s+`?([A-Za-z0-9_]+)`?/i', $stripped, $matches ) ) { return array(); } return array_values( array_unique( $matches[1] ) ); } }