repository = new User_Settings_Repository(); } /** * Register WordPress hooks. * * @since 1.5.2 * * @return void */ public function register_hooks(): void { // Priority 11: appear after Settings and Documentation (both registered at 10). add_action( 'admin_menu', array( $this, 'register_menu' ), 11 ); add_action( 'admin_notices', array( $this, 'maybe_show_notice' ) ); add_action( 'admin_init', array( $this, 'maybe_handle_dismiss' ) ); add_action( 'admin_post_robotstxt_2fa_import_otp', array( $this, 'handle_import' ) ); add_action( 'admin_post_robotstxt_2fa_save_migration_prefs', array( $this, 'handle_save_prefs' ) ); } /** * Register the Import submenu page. * * @since 1.5.2 * * @return void */ public function register_menu(): void { add_submenu_page( Dashboard_Page::PAGE_SLUG, __( 'Import / Migration — 2FA', 'robotstxt-2fa' ), __( 'Import', 'robotstxt-2fa' ), 'manage_options', self::PAGE_SLUG, array( $this, 'render_page' ) ); } /** * Show an admin banner when importable secrets are found. * * Suppressed when permanently hidden in preferences or temporarily dismissed. * * @since 1.5.2 * * @return void */ public function maybe_show_notice(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } $prefs = $this->get_prefs(); if ( ! empty( $prefs['hide_notice'] ) ) { return; } $user_id = get_current_user_id(); if ( get_transient( self::DISMISS_TRANSIENT_PREFIX . $user_id ) ) { return; } $count = count( $this->get_all_candidates() ); if ( 0 === $count ) { return; } $dismiss_url = wp_nonce_url( add_query_arg( 'action', 'robotstxt_2fa_dismiss_notice', admin_url( 'admin.php' ) ), self::DISMISS_NONCE_ACTION ); $import_url = admin_url( 'admin.php?page=' . self::PAGE_SLUG ); ?>

 

get_prefs(); $candidates = $this->get_all_candidates(); $result = $this->get_result_from_query(); ?>

render_result_notice( $result ); ?> render_prefs_section( $prefs ); ?>

user_login ); ?> display_name && $row['user']->display_name !== $row['user']->user_login ) : ?>
display_name ); ?>
user_email ); ?> roles ) ); ?> get_source_label( $row['source'] ) ); ?>

$raw_source ) { $user_id = absint( (string) $raw_id ); $source = is_string( $raw_source ) ? sanitize_key( $raw_source ) : ''; if ( 0 === $user_id || ! in_array( $source, $valid_sources, true ) ) { ++$failed; continue; } $secret = $this->read_secret( $user_id, $source ); if ( '' === $secret ) { ++$failed; continue; } update_user_meta( $user_id, self::DEST_META_KEY, $secret ); $settings = $this->repository->get_user_settings( $user_id ); $settings['enabled'] = true; if ( ! in_array( 'otp', $settings['methods'], true ) ) { $settings['methods'][] = 'otp'; } $this->repository->save_user_settings( $user_id, $settings ); ++$imported; } wp_safe_redirect( add_query_arg( array( 'page' => self::PAGE_SLUG, 'robotstxt_imported' => $imported, 'robotstxt_skipped' => $skipped, 'robotstxt_failed' => $failed, ), admin_url( 'admin.php' ) ) ); exit; } /** * Handle saving migration preferences. * * @since 1.5.2 * * @return void */ public function handle_save_prefs(): void { check_admin_referer( self::PREFS_NONCE_ACTION ); if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Sorry, you are not allowed to perform this action.', 'robotstxt-2fa' ) ); } $hide_notice = isset( $_POST['hide_notice'] ) && '1' === $_POST['hide_notice']; update_option( self::PREFS_OPTION, array( 'hide_notice' => $hide_notice ), false ); wp_safe_redirect( add_query_arg( 'page', self::PAGE_SLUG, admin_url( 'admin.php' ) ) ); exit; } // ------------------------------------------------------------------------- // Candidate discovery // ------------------------------------------------------------------------- /** * Return all importable users across all supported source plugins. * * Deduplicates by user ID: if a user appears in multiple sources, the first * detected source wins (priority: Two Factor → WP 2FA → Wordfence). * * @since 1.5.2 * * @return array */ private function get_all_candidates(): array { $candidates = array(); foreach ( $this->get_candidates_from_meta( self::META_TWO_FACTOR, self::SOURCE_TWO_FACTOR ) as $row ) { $candidates[ $row['user']->ID ] = $row; } foreach ( $this->get_candidates_from_meta( self::META_WP_2FA, self::SOURCE_WP_2FA ) as $row ) { if ( ! isset( $candidates[ $row['user']->ID ] ) ) { $candidates[ $row['user']->ID ] = $row; } } foreach ( $this->get_candidates_from_wordfence() as $row ) { if ( ! isset( $candidates[ $row['user']->ID ] ) ) { $candidates[ $row['user']->ID ] = $row; } } return array_values( $candidates ); } /** * Find users who have a source secret but have NOT activated OTP in our plugin. * * A user is excluded when 'otp' appears in their active methods list — that * means they deliberately set up OTP in our plugin and should not be overwritten. * Users with a lazily generated secret (secret exists but OTP never activated) * are treated as candidates: the un-activated secret will be replaced with the * imported one. * * @since 1.5.2 * * @param string $source_meta_key Meta key to check for the source secret. * @param string $source Source plugin identifier. * * @return array */ private function get_candidates_from_meta( string $source_meta_key, string $source ): array { $query = new \WP_User_Query( array( 'meta_key' => $source_meta_key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Admin-only, intentional. 'meta_compare' => 'EXISTS', 'fields' => 'all', 'number' => -1, ) ); $results = $query->get_results(); $rows = array(); foreach ( $results as $user ) { if ( ! $user instanceof \WP_User ) { continue; } // Skip users who already have OTP actively configured in our plugin. if ( $this->user_has_otp_active( $user->ID ) ) { continue; } $rows[] = array( 'user' => $user, 'source' => $source, ); } return $rows; } /** * Find users who have a Wordfence 2FA secret but not yet our secret. * * @since 1.5.2 * * @return array */ private function get_candidates_from_wordfence(): array { /** * WordPress database abstraction. Typed for PHPStan level max. * * @var \wpdb $wpdb */ global $wpdb; $table = $wpdb->prefix . self::WORDFENCE_TABLE; // Silently skip if the Wordfence table does not exist. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name built from trusted prefix constant. $exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ); if ( $table !== $exists ) { return array(); } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted prefix constant; the user ID is a validated integer. $rows = $wpdb->get_results( "SELECT s.user_id, s.secret FROM `{$table}` s", ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $candidates = array(); foreach ( $rows as $row ) { if ( ! isset( $row['user_id'] ) || ! is_numeric( $row['user_id'] ) ) { continue; } $user_id = (int) $row['user_id']; $src_binary = isset( $row['secret'] ) && is_string( $row['secret'] ) ? $row['secret'] : ''; $src = '' !== $src_binary ? $this->base32_encode( $src_binary ) : ''; if ( '' === $src ) { continue; } // Skip users who already have OTP actively configured in our plugin. if ( $this->user_has_otp_active( $user_id ) ) { continue; } $user = get_user_by( 'ID', $user_id ); if ( $user instanceof \WP_User ) { $candidates[] = array( 'user' => $user, 'source' => self::SOURCE_WORDFENCE, ); } } return $candidates; } // ------------------------------------------------------------------------- // Secret readers // ------------------------------------------------------------------------- /** * Read and return the Base32-encoded TOTP secret for a user from a given source. * * Returns an empty string when the secret cannot be retrieved or decoded. * * @since 1.5.2 * * @param int $user_id User identifier. * @param string $source Source plugin identifier. * * @return string Base32-encoded secret, or empty string on failure. */ private function read_secret( int $user_id, string $source ): string { switch ( $source ) { case self::SOURCE_TWO_FACTOR: return $this->read_two_factor_secret( $user_id ); case self::SOURCE_WP_2FA: return $this->read_wp_2fa_secret( $user_id ); case self::SOURCE_WORDFENCE: return $this->read_wordfence_secret( $user_id ); default: return ''; } } /** * Read a plain-Base32 secret stored by the Two Factor (community) plugin. * * @since 1.5.2 * * @param int $user_id User identifier. * * @return string */ private function read_two_factor_secret( int $user_id ): string { $raw = get_user_meta( $user_id, self::META_TWO_FACTOR, true ); if ( ! is_string( $raw ) || '' === $raw ) { return ''; } return strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $raw ) ?? '' ); } /** * Read the TOTP secret stored by WP 2FA (Melapress). * * The value may be plain Base32 or encrypted with an `lsc_`, `ssl_`, or `wps_` * prefix. When WP 2FA is still installed and its classes are available the * decrypted secret is returned directly. When WP 2FA is not installed, only * plain-text (unencrypted) secrets can be imported. * * @since 1.5.2 * * @param int $user_id User identifier. * * @return string */ private function read_wp_2fa_secret( int $user_id ): string { $raw = get_user_meta( $user_id, self::META_WP_2FA, true ); if ( ! is_string( $raw ) || '' === $raw ) { return ''; } $encrypted_prefixes = array( 'lsc_', 'ssl_', 'wps_' ); $is_encrypted = false; foreach ( $encrypted_prefixes as $prefix ) { if ( str_starts_with( $raw, $prefix ) ) { $is_encrypted = true; break; } } if ( $is_encrypted ) { // Try to decrypt via WP 2FA's own class if the plugin is still active. if ( class_exists( 'WP2FA\Admin\Methods\TOTP' ) ) { $user = get_user_by( 'ID', $user_id ); if ( ! $user instanceof \WP_User ) { return ''; } try { $decrypted = \WP2FA\Admin\Methods\TOTP::get_totp_decrypted( $user ); return is_string( $decrypted ) ? strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $decrypted ) ?? '' ) : ''; } catch ( \Throwable $e ) { return ''; } } // WP 2FA not available — cannot decrypt. return ''; } // Plain text — validate and return. return strtoupper( preg_replace( '/[^A-Za-z2-7]/', '', $raw ) ?? '' ); } /** * Read the TOTP secret stored by Wordfence Login Security. * * Wordfence stores the raw 20-byte secret as a binary blob. We Base32-encode * it to produce the standard representation expected by authenticator apps and * our plugin's OTP_Manager. * * @since 1.5.2 * * @param int $user_id User identifier. * * @return string */ private function read_wordfence_secret( int $user_id ): string { /** * WordPress database abstraction. Typed for PHPStan level max. * * @var \wpdb $wpdb */ global $wpdb; $table = $wpdb->prefix . self::WORDFENCE_TABLE; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a trusted prefix constant; the user ID is a validated integer. $secret_binary = $wpdb->get_var( "SELECT `secret` FROM `{$table}` WHERE `user_id` = {$user_id} LIMIT 1" ); if ( ! is_string( $secret_binary ) ) { return ''; } return $this->base32_encode( $secret_binary ); } // ------------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------------- /** * Base32-encode binary data using the RFC 4648 alphabet. * * Wordfence stores the raw TOTP secret as binary; this produces the Base32 * string that authenticator apps and our OTP_Manager expect. * * @since 1.5.2 * * @param string $data Raw binary string. * * @return string */ private function base32_encode( string $data ): string { $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $bits = ''; for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) { $bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT ); } $chunks = str_split( $bits, 5 ); $encoded = ''; foreach ( $chunks as $chunk ) { if ( strlen( $chunk ) < 5 ) { $chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT ); } $encoded .= $alphabet[ (int) bindec( $chunk ) ]; } return $encoded; } /** * Check whether the user has OTP actively configured in our plugin. * * Returns true when 'otp' appears in the stored methods list, meaning the user * has deliberately set up and confirmed an OTP secret in our plugin. A lazily * generated secret that was never activated does NOT qualify. * * @since 1.5.2 * * @param int $user_id User identifier. * * @return bool */ private function user_has_otp_active( int $user_id ): bool { $settings = $this->repository->get_user_settings( $user_id ); return in_array( 'otp', $settings['methods'], true ); } /** * Return a human-readable label for a source plugin identifier. * * @since 1.5.2 * * @param string $source Source identifier. * * @return string */ private function get_source_label( string $source ): string { $labels = array( self::SOURCE_TWO_FACTOR => __( 'Two Factor (community)', 'robotstxt-2fa' ), self::SOURCE_WP_2FA => __( 'WP 2FA (Melapress)', 'robotstxt-2fa' ), self::SOURCE_WORDFENCE => __( 'Wordfence Login Security', 'robotstxt-2fa' ), ); return $labels[ $source ] ?? $source; } /** * Retrieve migration preferences. * * @since 1.5.2 * * @return array{hide_notice: bool} */ private function get_prefs(): array { $raw = get_option( self::PREFS_OPTION, array() ); if ( ! is_array( $raw ) ) { $raw = array(); } return array( 'hide_notice' => ! empty( $raw['hide_notice'] ), ); } /** * Read and sanitize import result query args set after an import redirect. * * @since 1.5.2 * * @return array{imported: int, skipped: int, failed: int}|null */ private function get_result_from_query(): ?array { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only display; nonce verified in handle_import(). if ( ! array_key_exists( 'robotstxt_imported', $_GET ) ) { return null; } return array( 'imported' => absint( isset( $_GET['robotstxt_imported'] ) && is_scalar( $_GET['robotstxt_imported'] ) ? $_GET['robotstxt_imported'] : 0 ), 'skipped' => absint( isset( $_GET['robotstxt_skipped'] ) && is_scalar( $_GET['robotstxt_skipped'] ) ? $_GET['robotstxt_skipped'] : 0 ), 'failed' => absint( isset( $_GET['robotstxt_failed'] ) && is_scalar( $_GET['robotstxt_failed'] ) ? $_GET['robotstxt_failed'] : 0 ), ); // phpcs:enable WordPress.Security.NonceVerification.Recommended } /** * Render the notice preferences section. * * @since 1.5.2 * * @param array{hide_notice: bool} $prefs Current preferences. * * @return void */ private function render_prefs_section( array $prefs ): void { ?>

0 ? 'notice-warning' : 'notice-success'; $imported = $result['imported']; $skipped = $result['skipped']; $failed = $result['failed']; ?>

0 ) : ?> 0 ) : ?> 0 ) : ?>   0 ) : ?> 0 || $skipped > 0 ) : ?>