robotstxt-2fa/includes/admin/class-settings-page.php
2026-06-06 05:08:20 +00:00

1541 lines
57 KiB
PHP

<?php
/**
* Admin settings management.
*
* @package Robotstxt_2FA
*/
namespace Robotstxt\TwoFA\Admin;
use Robotstxt\TwoFA\Frequency_Options;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin settings page and enforcement logic configuration.
*/
class Settings_Page {
/**
* Option group for settings registration.
*/
private const OPTION_GROUP = 'robotstxt_2fa_settings_group';
/**
* Option name for storing settings.
*/
public const OPTION_NAME = 'robotstxt_2fa_settings';
/**
* Settings page slug (also serves as the top-level menu slug).
*/
private const PAGE_SLUG = 'robotstxt-2fa-settings';
/**
* Documentation page slug.
*/
private const DOCS_PAGE_SLUG = 'robotstxt-2fa-docs';
/**
* Dashboard page slug (single-site parent menu, owned by Dashboard_Page).
*/
private const DASHBOARD_PAGE_SLUG = 'robotstxt-2fa-dashboard';
/**
* Verification methods available for per-role configuration.
*
* @var array<string, string>
*/
private const AVAILABLE_METHODS = array(
'email' => 'Email code',
'otp' => 'Authenticator app (OTP)',
'recovery_codes' => 'Recovery codes',
);
/**
* Register admin-related hooks.
*
* @return void
*/
public function register_hooks(): void {
add_action( 'admin_menu', array( $this, 'register_menu' ) );
if ( is_multisite() ) {
add_action( 'network_admin_menu', array( $this, 'register_network_menu' ) );
add_action( 'network_admin_edit_robotstxt_2fa_network_save', array( $this, 'handle_network_save' ) );
}
add_action( 'admin_init', array( $this, 'register_settings' ) );
}
/**
* Register plugin settings page on single-site dashboards.
*
* @return void
*/
public function register_menu(): void {
$this->register_admin_page( false );
}
/**
* Register plugin settings page on the network dashboard.
*
* @return void
*/
public function register_network_menu(): void {
$this->register_admin_page( true );
}
/**
* Render plugin settings page.
*
* @return void
*/
public function render_page(): void {
$capability = $this->get_required_capability();
if ( ! current_user_can( $capability ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
}
settings_errors( self::OPTION_NAME );
$form_action = $this->is_network_context()
? network_admin_url( 'edit.php?action=robotstxt_2fa_network_save' )
: 'options.php';
?>
<div class="wrap">
<h1><?php esc_html_e( 'Two-Factor Authentication settings', 'robotstxt-2fa' ); ?></h1>
<form action="<?php echo esc_url( $form_action ); ?>" method="post">
<?php
if ( $this->is_network_context() ) {
wp_nonce_field( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
} else {
settings_fields( self::OPTION_GROUP );
}
do_settings_sections( self::PAGE_SLUG );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register settings and sections.
*
* @return void
*/
public function register_settings(): void {
register_setting(
self::OPTION_GROUP,
self::OPTION_NAME,
array(
'type' => 'array',
'sanitize_callback' => array( $this, 'sanitize_settings' ),
'default' => $this->get_default_settings(),
'autoload' => false,
)
);
add_settings_section(
'robotstxt_2fa_general',
__( 'General options', 'robotstxt-2fa' ),
array( $this, 'render_general_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_role_methods',
__( 'Required methods per role', 'robotstxt-2fa' ),
array( $this, 'render_role_methods_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_general'
);
add_settings_field(
'robotstxt_2fa_frequency',
__( 'Verification frequency', 'robotstxt-2fa' ),
array( $this, 'render_frequency_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_general'
);
add_settings_field(
'robotstxt_2fa_force_frequency',
__( 'Enforce frequency', 'robotstxt-2fa' ),
array( $this, 'render_force_frequency_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_general'
);
add_settings_section(
'robotstxt_2fa_security',
__( 'Security', 'robotstxt-2fa' ),
array( $this, 'render_security_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_max_attempts',
__( 'Max failed attempts', 'robotstxt-2fa' ),
array( $this, 'render_max_attempts_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_security'
);
add_settings_field(
'robotstxt_2fa_lockout_duration',
__( 'Lockout duration', 'robotstxt-2fa' ),
array( $this, 'render_lockout_duration_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_security'
);
add_settings_field(
'robotstxt_2fa_trust_device_days',
__( 'Trust browser for', 'robotstxt-2fa' ),
array( $this, 'render_trust_device_days_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_security'
);
add_settings_field(
'robotstxt_2fa_grace_period_days',
__( 'Grace period', 'robotstxt-2fa' ),
array( $this, 'render_grace_period_days_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_security'
);
add_settings_field(
'robotstxt_2fa_grace_period_action',
__( 'After grace period', 'robotstxt-2fa' ),
array( $this, 'render_grace_period_action_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_security'
);
add_settings_section(
'robotstxt_2fa_data',
__( 'Data management', 'robotstxt-2fa' ),
array( $this, 'render_data_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_delete_on_uninstall',
__( 'Delete data on uninstall', 'robotstxt-2fa' ),
array( $this, 'render_delete_on_uninstall_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_data'
);
add_settings_section(
'robotstxt_2fa_access',
__( 'Access control', 'robotstxt-2fa' ),
array( $this, 'render_access_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_app_passwords_exempt',
__( 'Application Passwords', 'robotstxt-2fa' ),
array( $this, 'render_app_passwords_exempt_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_access'
);
add_settings_field(
'robotstxt_2fa_app_passwords_require_2fa_creation',
__( 'Require 2FA to create Application Passwords', 'robotstxt-2fa' ),
array( $this, 'render_app_passwords_require_2fa_creation_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_access'
);
add_settings_field(
'robotstxt_2fa_ip_allow',
__( 'IP allow list', 'robotstxt-2fa' ),
array( $this, 'render_ip_allow_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_access'
);
add_settings_field(
'robotstxt_2fa_ip_deny',
__( 'IP deny list', 'robotstxt-2fa' ),
array( $this, 'render_ip_deny_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_access'
);
add_settings_section(
'robotstxt_2fa_notifications',
__( 'Email notifications', 'robotstxt-2fa' ),
array( $this, 'render_notifications_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_notif_on_enable',
__( 'On method activation', 'robotstxt-2fa' ),
array( $this, 'render_notif_on_enable_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_notifications'
);
add_settings_field(
'robotstxt_2fa_notif_on_new_ip',
__( 'New location', 'robotstxt-2fa' ),
array( $this, 'render_notif_on_new_ip_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_notifications'
);
add_settings_field(
'robotstxt_2fa_notif_on_recovery',
__( 'Recovery code used', 'robotstxt-2fa' ),
array( $this, 'render_notif_on_recovery_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_notifications'
);
add_settings_field(
'robotstxt_2fa_notif_digest',
__( 'Activity digest', 'robotstxt-2fa' ),
array( $this, 'render_notif_digest_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_notifications'
);
add_settings_section(
'robotstxt_2fa_geoip',
__( 'GeoIP / Country restrictions', 'robotstxt-2fa' ),
array( $this, 'render_geoip_section' ),
self::PAGE_SLUG
);
add_settings_field(
'robotstxt_2fa_geoip_database_path',
__( 'Database path', 'robotstxt-2fa' ),
array( $this, 'render_geoip_database_path_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_geoip'
);
add_settings_field(
'robotstxt_2fa_geoip_country_allow',
__( 'Country allow list (bypass 2FA)', 'robotstxt-2fa' ),
array( $this, 'render_geoip_country_allow_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_geoip'
);
add_settings_field(
'robotstxt_2fa_geoip_country_deny',
__( 'Country deny list (block login)', 'robotstxt-2fa' ),
array( $this, 'render_geoip_country_deny_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_geoip'
);
add_settings_field(
'robotstxt_2fa_geoip_always_challenge',
__( 'Always challenge countries', 'robotstxt-2fa' ),
array( $this, 'render_geoip_always_challenge_field' ),
self::PAGE_SLUG,
'robotstxt_2fa_geoip'
);
}
/**
* Render general settings section description.
*
* @return void
*/
public function render_general_section(): void {
echo '<p>' . esc_html__( 'Control how two-factor authentication is enforced for user roles.', 'robotstxt-2fa' ) . '</p>';
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
echo '<p class="description">' . esc_html__( 'These settings are locked by a network administrator. Any changes made here will be ignored.', 'robotstxt-2fa' ) . '</p>';
}
}
/**
* Render the per-role method matrix field.
*
* Each row represents a role; each column represents a verification method.
* Checking a method for a role forces users of that role to verify with it.
* Leaving all methods unchecked for a role makes 2FA optional for that role.
* Row and column "select all" controls are provided via JavaScript.
*
* @return void
*/
public function render_role_methods_field(): void {
$settings = $this->get_settings();
$role_methods = $settings['role_methods'];
$roles = get_editable_roles();
$locked = $this->has_network_settings() && ! $this->is_network_context();
$disabled = $locked ? disabled( true, true, false ) : '';
if ( empty( $roles ) ) {
echo '<p class="description">' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '</p>';
return;
}
$methods = array(
'email' => __( 'Email code', 'robotstxt-2fa' ),
'otp' => __( 'Authenticator app', 'robotstxt-2fa' ),
'recovery_codes' => __( 'Recovery codes', 'robotstxt-2fa' ),
);
?>
<table class="widefat fixed striped robotstxt-2fa-role-methods-table" id="robotstxt-2fa-role-methods-table" style="max-width:680px;">
<thead>
<tr>
<th><?php esc_html_e( 'Role', 'robotstxt-2fa' ); ?></th>
<?php foreach ( $methods as $method_key => $method_label ) : ?>
<th style="text-align:center;">
<?php echo esc_html( $method_label ); ?>
<?php if ( ! $locked ) : ?>
<br />
<label style="font-weight:normal;font-size:11px;cursor:pointer;">
<input
type="checkbox"
class="robotstxt-2fa-col-toggle"
data-2fa-col="<?php echo esc_attr( $method_key ); ?>"
style="margin-top:4px;"
/>
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
</label>
<?php endif; ?>
</th>
<?php endforeach; ?>
<?php if ( ! $locked ) : ?>
<th style="text-align:center;font-weight:normal;font-size:11px;">
<?php esc_html_e( 'All methods', 'robotstxt-2fa' ); ?>
</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ( $roles as $role_key => $role_details ) : ?>
<tr data-2fa-role="<?php echo esc_attr( $role_key ); ?>">
<td><?php echo esc_html( translate_user_role( $role_details['name'] ) ); ?></td>
<?php foreach ( $methods as $method_key => $method_label ) : ?>
<td style="text-align:center;">
<label>
<span class="screen-reader-text">
<?php
printf(
/* translators: 1: role name, 2: method name. */
esc_html__( '%1$s: require %2$s', 'robotstxt-2fa' ),
esc_html( translate_user_role( $role_details['name'] ) ),
esc_html( $method_label )
);
?>
</span>
<input
type="checkbox"
class="robotstxt-2fa-cell"
data-2fa-role="<?php echo esc_attr( $role_key ); ?>"
data-2fa-method="<?php echo esc_attr( $method_key ); ?>"
name="<?php echo esc_attr( self::OPTION_NAME ); ?>[role_methods][<?php echo esc_attr( $role_key ); ?>][]"
value="<?php echo esc_attr( $method_key ); ?>"
<?php checked( in_array( $method_key, $role_methods[ $role_key ] ?? array(), true ) ); ?>
<?php echo $disabled; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function. ?>
/>
</label>
</td>
<?php endforeach; ?>
<?php if ( ! $locked ) : ?>
<td style="text-align:center;">
<label style="font-size:11px;cursor:pointer;">
<input
type="checkbox"
class="robotstxt-2fa-row-toggle"
data-2fa-row="<?php echo esc_attr( $role_key ); ?>"
/>
<?php esc_html_e( 'All', 'robotstxt-2fa' ); ?>
</label>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p class="description">
<?php esc_html_e( 'Check which verification methods are required for each role. Users assigned to a role with at least one checked method must complete two-factor authentication using one of those methods. Roles with no methods checked leave the choice to the user.', 'robotstxt-2fa' ); ?>
</p>
<?php if ( ! $locked ) : ?>
<script>
(function () {
var table = document.getElementById( 'robotstxt-2fa-role-methods-table' );
if ( ! table ) { return; }
function cells() {
return table.querySelectorAll( '.robotstxt-2fa-cell' );
}
function updateToggle( toggle, checked, total ) {
if ( total === 0 ) { return; }
toggle.indeterminate = checked > 0 && checked < total;
toggle.checked = checked === total;
}
function syncRow( roleKey ) {
var rowCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' );
var rowToggle = table.querySelector( '.robotstxt-2fa-row-toggle[data-2fa-row="' + roleKey + '"]' );
if ( ! rowToggle ) { return; }
var checked = 0;
rowCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
updateToggle( rowToggle, checked, rowCells.length );
}
function syncCol( methodKey ) {
var colCells = table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' );
var colToggle = table.querySelector( '.robotstxt-2fa-col-toggle[data-2fa-col="' + methodKey + '"]' );
if ( ! colToggle ) { return; }
var checked = 0;
colCells.forEach( function ( c ) { if ( c.checked ) { checked++; } } );
updateToggle( colToggle, checked, colCells.length );
}
/* Sync all toggles on load */
var allRoles = {}, allMethods = {};
cells().forEach( function ( c ) {
allRoles[ c.dataset['2faRole'] ] = true;
allMethods[ c.dataset['2faMethod'] ] = true;
} );
Object.keys( allRoles ).forEach( syncRow );
Object.keys( allMethods ).forEach( syncCol );
/* Row toggle: check / uncheck all cells in that role's row */
table.querySelectorAll( '.robotstxt-2fa-row-toggle' ).forEach( function ( toggle ) {
toggle.addEventListener( 'change', function () {
var roleKey = toggle.dataset['2faRow'];
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-role="' + roleKey + '"]' ).forEach( function ( c ) {
c.checked = toggle.checked;
} );
Object.keys( allMethods ).forEach( syncCol );
} );
} );
/* Column toggle: check / uncheck all cells in that method's column */
table.querySelectorAll( '.robotstxt-2fa-col-toggle' ).forEach( function ( toggle ) {
toggle.addEventListener( 'change', function () {
var methodKey = toggle.dataset['2faCol'];
table.querySelectorAll( '.robotstxt-2fa-cell[data-2fa-method="' + methodKey + '"]' ).forEach( function ( c ) {
c.checked = toggle.checked;
} );
Object.keys( allRoles ).forEach( syncRow );
} );
} );
/* Individual cell: keep toggles in sync */
cells().forEach( function ( c ) {
c.addEventListener( 'change', function () {
syncRow( c.dataset['2faRole'] );
syncCol( c.dataset['2faMethod'] );
} );
} );
}());
</script>
<?php endif; ?>
<?php
}
/**
* Sanitize settings before saving them.
*
* @param mixed $raw_settings Raw settings submitted by the user.
*
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
*/
public function sanitize_settings( $raw_settings ): array {
$capability = $this->get_required_capability();
if ( ! current_user_can( $capability ) ) {
add_settings_error(
self::OPTION_NAME,
'robotstxt_2fa_capability',
__( 'You are not allowed to update these settings.', 'robotstxt-2fa' )
);
return $this->get_settings();
}
$raw_settings = is_array( $raw_settings ) ? $raw_settings : array();
$sanitized = $this->get_default_settings();
$current_settings = $this->get_settings();
$editable_roles = array_keys( get_editable_roles() );
$valid_methods = array_keys( self::AVAILABLE_METHODS );
$sanitized['role_methods'] = array();
if ( isset( $raw_settings['role_methods'] ) && is_array( $raw_settings['role_methods'] ) ) {
foreach ( $raw_settings['role_methods'] as $role_key => $raw_methods ) {
$role_key = sanitize_key( is_string( $role_key ) ? $role_key : '' );
if ( '' === $role_key || ! in_array( $role_key, $editable_roles, true ) ) {
continue;
}
if ( ! is_array( $raw_methods ) ) {
continue;
}
$methods = array();
foreach ( $raw_methods as $method ) {
$method = sanitize_key( is_string( $method ) ? $method : '' );
if ( in_array( $method, $valid_methods, true ) ) {
$methods[] = $method;
}
}
if ( ! empty( $methods ) ) {
$sanitized['role_methods'][ $role_key ] = array_values( array_unique( $methods ) );
}
}
}
$frequency_value = $current_settings['frequency'];
if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) {
$frequency_value = $raw_settings['frequency'];
}
$sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value );
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
$sanitized['force_frequency'] = $current_settings['force_frequency'];
} elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) {
$sanitized['force_frequency'] = '1' === ( is_scalar( $raw_settings['force_frequency'] ) ? (string) $raw_settings['force_frequency'] : '' );
}
if ( array_key_exists( 'delete_on_uninstall', $raw_settings ) ) {
$sanitized['delete_on_uninstall'] = '1' === ( is_scalar( $raw_settings['delete_on_uninstall'] ) ? (string) $raw_settings['delete_on_uninstall'] : '' );
}
if ( isset( $raw_settings['max_attempts'] ) && is_numeric( $raw_settings['max_attempts'] ) ) {
$sanitized['max_attempts'] = max( 0, absint( $raw_settings['max_attempts'] ) );
}
if ( isset( $raw_settings['lockout_duration'] ) && is_numeric( $raw_settings['lockout_duration'] ) ) {
$sanitized['lockout_duration'] = max( 1, absint( $raw_settings['lockout_duration'] ) );
}
if ( isset( $raw_settings['trust_device_days'] ) && is_numeric( $raw_settings['trust_device_days'] ) ) {
$sanitized['trust_device_days'] = max( 0, absint( $raw_settings['trust_device_days'] ) );
}
if ( isset( $raw_settings['grace_period_days'] ) && is_numeric( $raw_settings['grace_period_days'] ) ) {
$sanitized['grace_period_days'] = max( 0, absint( $raw_settings['grace_period_days'] ) );
}
if ( isset( $raw_settings['grace_period_action'] ) && in_array( $raw_settings['grace_period_action'], array( 'block', 'wizard' ), true ) ) {
$sanitized['grace_period_action'] = $raw_settings['grace_period_action'];
}
if ( array_key_exists( 'app_passwords_exempt', $raw_settings ) ) {
$sanitized['app_passwords_exempt'] = '1' === ( is_scalar( $raw_settings['app_passwords_exempt'] ) ? (string) $raw_settings['app_passwords_exempt'] : '' );
}
if ( isset( $raw_settings['ip_allow'] ) && is_string( $raw_settings['ip_allow'] ) ) {
$sanitized['ip_allow'] = sanitize_textarea_field( $raw_settings['ip_allow'] );
}
if ( isset( $raw_settings['ip_deny'] ) && is_string( $raw_settings['ip_deny'] ) ) {
$sanitized['ip_deny'] = sanitize_textarea_field( $raw_settings['ip_deny'] );
}
$raw_notif = isset( $raw_settings['notifications'] ) && is_array( $raw_settings['notifications'] ) ? $raw_settings['notifications'] : array();
$sanitized['notifications'] = array(
'on_enable' => ! empty( $raw_notif['on_enable'] ),
'on_new_ip' => ! empty( $raw_notif['on_new_ip'] ),
'on_recovery_used' => ! empty( $raw_notif['on_recovery_used'] ),
'on_recovery_used_admin' => ! empty( $raw_notif['on_recovery_used_admin'] ),
'digest_enabled' => ! empty( $raw_notif['digest_enabled'] ),
'digest_frequency' => isset( $raw_notif['digest_frequency'] ) && 'monthly' === $raw_notif['digest_frequency'] ? 'monthly' : 'weekly',
);
if ( array_key_exists( 'app_passwords_require_2fa_creation', $raw_settings ) ) {
$sanitized['app_passwords_require_2fa_creation'] = '1' === ( is_scalar( $raw_settings['app_passwords_require_2fa_creation'] ) ? (string) $raw_settings['app_passwords_require_2fa_creation'] : '' );
}
if ( isset( $raw_settings['geoip_database_path'] ) && is_string( $raw_settings['geoip_database_path'] ) ) {
$sanitized['geoip_database_path'] = sanitize_text_field( $raw_settings['geoip_database_path'] );
}
if ( isset( $raw_settings['geoip_country_allow'] ) && is_string( $raw_settings['geoip_country_allow'] ) ) {
$sanitized['geoip_country_allow'] = strtoupper( sanitize_textarea_field( $raw_settings['geoip_country_allow'] ) );
}
if ( isset( $raw_settings['geoip_country_deny'] ) && is_string( $raw_settings['geoip_country_deny'] ) ) {
$sanitized['geoip_country_deny'] = strtoupper( sanitize_textarea_field( $raw_settings['geoip_country_deny'] ) );
}
if ( isset( $raw_settings['geoip_always_challenge'] ) && is_string( $raw_settings['geoip_always_challenge'] ) ) {
$sanitized['geoip_always_challenge'] = strtoupper( sanitize_textarea_field( $raw_settings['geoip_always_challenge'] ) );
}
return $sanitized;
}
/**
* Retrieve plugin settings, migrating from legacy format when necessary.
*
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
*/
public function get_settings(): array {
$options = array();
if ( is_multisite() ) {
$network_options = get_site_option( self::OPTION_NAME, false );
if ( is_array( $network_options ) ) {
$options = $network_options;
}
}
if ( empty( $options ) ) {
$raw = get_option( self::OPTION_NAME, array() );
if ( is_array( $raw ) ) {
$options = $raw;
}
}
$defaults = $this->get_default_settings();
$raw_notif = isset( $options['notifications'] ) && is_array( $options['notifications'] ) ? $options['notifications'] : array();
$def_notif = $defaults['notifications'];
return array(
'role_methods' => $this->resolve_role_methods( $options ),
'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ),
'force_frequency' => ! empty( $options['force_frequency'] ),
'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ),
'max_attempts' => isset( $options['max_attempts'] ) && is_numeric( $options['max_attempts'] ) ? max( 0, absint( $options['max_attempts'] ) ) : $defaults['max_attempts'],
'lockout_duration' => isset( $options['lockout_duration'] ) && is_numeric( $options['lockout_duration'] ) ? max( 1, absint( $options['lockout_duration'] ) ) : $defaults['lockout_duration'],
'trust_device_days' => isset( $options['trust_device_days'] ) && is_numeric( $options['trust_device_days'] ) ? max( 0, absint( $options['trust_device_days'] ) ) : $defaults['trust_device_days'],
'grace_period_days' => isset( $options['grace_period_days'] ) && is_numeric( $options['grace_period_days'] ) ? max( 0, absint( $options['grace_period_days'] ) ) : $defaults['grace_period_days'],
'grace_period_action' => isset( $options['grace_period_action'] ) && in_array( $options['grace_period_action'], array( 'block', 'wizard' ), true ) ? $options['grace_period_action'] : $defaults['grace_period_action'],
'app_passwords_exempt' => isset( $options['app_passwords_exempt'] ) ? (bool) $options['app_passwords_exempt'] : $defaults['app_passwords_exempt'],
'ip_allow' => isset( $options['ip_allow'] ) && is_string( $options['ip_allow'] ) ? $options['ip_allow'] : $defaults['ip_allow'],
'ip_deny' => isset( $options['ip_deny'] ) && is_string( $options['ip_deny'] ) ? $options['ip_deny'] : $defaults['ip_deny'],
'notifications' => array(
'on_enable' => isset( $raw_notif['on_enable'] ) ? (bool) $raw_notif['on_enable'] : $def_notif['on_enable'],
'on_new_ip' => isset( $raw_notif['on_new_ip'] ) ? (bool) $raw_notif['on_new_ip'] : $def_notif['on_new_ip'],
'on_recovery_used' => isset( $raw_notif['on_recovery_used'] ) ? (bool) $raw_notif['on_recovery_used'] : $def_notif['on_recovery_used'],
'on_recovery_used_admin' => isset( $raw_notif['on_recovery_used_admin'] ) ? (bool) $raw_notif['on_recovery_used_admin'] : $def_notif['on_recovery_used_admin'],
'digest_enabled' => isset( $raw_notif['digest_enabled'] ) ? (bool) $raw_notif['digest_enabled'] : $def_notif['digest_enabled'],
'digest_frequency' => isset( $raw_notif['digest_frequency'] ) && 'monthly' === $raw_notif['digest_frequency'] ? 'monthly' : $def_notif['digest_frequency'],
),
'app_passwords_require_2fa_creation' => isset( $options['app_passwords_require_2fa_creation'] ) ? (bool) $options['app_passwords_require_2fa_creation'] : $defaults['app_passwords_require_2fa_creation'],
'geoip_database_path' => isset( $options['geoip_database_path'] ) && is_string( $options['geoip_database_path'] ) ? $options['geoip_database_path'] : $defaults['geoip_database_path'],
'geoip_country_allow' => isset( $options['geoip_country_allow'] ) && is_string( $options['geoip_country_allow'] ) ? $options['geoip_country_allow'] : $defaults['geoip_country_allow'],
'geoip_country_deny' => isset( $options['geoip_country_deny'] ) && is_string( $options['geoip_country_deny'] ) ? $options['geoip_country_deny'] : $defaults['geoip_country_deny'],
'geoip_always_challenge' => isset( $options['geoip_always_challenge'] ) && is_string( $options['geoip_always_challenge'] ) ? $options['geoip_always_challenge'] : $defaults['geoip_always_challenge'],
);
}
/**
* Retrieve default settings.
*
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}, app_passwords_require_2fa_creation: bool, geoip_database_path: string, geoip_country_allow: string, geoip_country_deny: string, geoip_always_challenge: string}
*/
private function get_default_settings(): array {
return array(
'role_methods' => array(),
'frequency' => Frequency_Options::FREQUENCY_SESSION,
'force_frequency' => false,
'delete_on_uninstall' => false,
'max_attempts' => 3,
'lockout_duration' => 15,
'trust_device_days' => 30,
'grace_period_days' => 7,
'grace_period_action' => 'wizard',
'app_passwords_exempt' => true,
'ip_allow' => '',
'ip_deny' => '',
'notifications' => array(
'on_enable' => false,
'on_new_ip' => false,
'on_recovery_used' => false,
'on_recovery_used_admin' => false,
'digest_enabled' => false,
'digest_frequency' => 'weekly',
),
'app_passwords_require_2fa_creation' => false,
'geoip_database_path' => '',
'geoip_country_allow' => '',
'geoip_country_deny' => '',
'geoip_always_challenge' => '',
);
}
/**
* Resolve role_methods from stored options, migrating legacy force_roles + default_method if needed.
*
* @param array<string, mixed> $options Raw stored options.
*
* @return array<string, array<int, string>>
*/
private function resolve_role_methods( array $options ): array {
$valid_methods = array_keys( self::AVAILABLE_METHODS );
if ( isset( $options['role_methods'] ) && is_array( $options['role_methods'] ) ) {
$role_methods = array();
foreach ( $options['role_methods'] as $role => $methods ) {
$role = is_string( $role ) ? sanitize_key( $role ) : '';
if ( '' === $role || ! is_array( $methods ) ) {
continue;
}
$clean = array();
foreach ( $methods as $m ) {
$m = is_string( $m ) ? sanitize_key( $m ) : '';
if ( in_array( $m, $valid_methods, true ) ) {
$clean[] = $m;
}
}
if ( ! empty( $clean ) ) {
$role_methods[ $role ] = array_values( array_unique( $clean ) );
}
}
return $role_methods;
}
// Migrate legacy force_roles + default_method to role_methods.
if ( isset( $options['force_roles'] ) && is_array( $options['force_roles'] ) ) {
$default_method = isset( $options['default_method'] ) && is_string( $options['default_method'] ) ? sanitize_key( $options['default_method'] ) : 'email';
if ( ! in_array( $default_method, $valid_methods, true ) ) {
$default_method = 'email';
}
$role_methods = array();
foreach ( $options['force_roles'] as $role ) {
$role = is_string( $role ) ? sanitize_key( $role ) : '';
if ( '' !== $role ) {
$role_methods[ $role ] = array( $default_method );
}
}
return $role_methods;
}
return array();
}
/**
* Render verification frequency field.
*
* @return void
*/
public function render_frequency_field(): void {
$settings = $this->get_settings();
$selected = $settings['frequency'];
$disabled_attr = '';
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
$disabled_attr = disabled( true, true, false );
}
$options = Frequency_Options::get_options();
echo '<select name="' . esc_attr( self::OPTION_NAME ) . '[frequency]" ' . $disabled_attr . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
foreach ( $options as $value => $labels ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( $value ),
selected( $selected, $value, false ),
esc_html( $labels['label'] )
);
}
echo '</select>';
if ( isset( $options[ $selected ]['description'] ) && '' !== $options[ $selected ]['description'] ) {
echo '<p class="description">' . esc_html( $options[ $selected ]['description'] ) . '</p>';
}
}
/**
* Render frequency enforcement checkbox.
*
* @return void
*/
public function render_force_frequency_field(): void {
$settings = $this->get_settings();
$is_checked = $settings['force_frequency'];
$disabled_attr = '';
if ( $this->has_network_settings() && ! $this->is_network_context() ) {
$disabled_attr = disabled( true, true, false );
}
if ( '' === $disabled_attr ) {
printf(
'<input type="hidden" name="%1$s[force_frequency]" value="0" />',
esc_attr( self::OPTION_NAME )
);
}
printf(
'<label><input type="checkbox" name="%1$s[force_frequency]" value="1" %2$s %3$s/> %4$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
$disabled_attr, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function.
esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the Security section description.
*
* @return void
*/
public function render_security_section(): void {
echo '<p>' . esc_html__( 'Brute-force protection, trusted device cookies, and grace period for new enrollments.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the max failed attempts field.
*
* @return void
*/
public function render_max_attempts_field(): void {
$settings = $this->get_settings();
printf(
'<input type="number" name="%1$s[max_attempts]" value="%2$s" min="0" max="99" style="width:70px;" /> %3$s',
esc_attr( self::OPTION_NAME ),
absint( $settings['max_attempts'] ),
esc_html__( '(0 = unlimited)', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'Number of consecutive failed 2FA attempts before the user is temporarily locked out. The lock is cleared after the lockout duration expires.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the lockout duration field.
*
* @return void
*/
public function render_lockout_duration_field(): void {
$settings = $this->get_settings();
printf(
'<input type="number" name="%1$s[lockout_duration]" value="%2$s" min="1" max="1440" style="width:70px;" /> %3$s',
esc_attr( self::OPTION_NAME ),
absint( $settings['lockout_duration'] ),
esc_html__( 'minutes', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'How long the account is locked after too many failed attempts. Applies only when Max failed attempts is greater than 0.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the trusted device days field.
*
* @return void
*/
public function render_trust_device_days_field(): void {
$settings = $this->get_settings();
printf(
'<input type="number" name="%1$s[trust_device_days]" value="%2$s" min="0" max="365" style="width:70px;" /> %3$s',
esc_attr( self::OPTION_NAME ),
absint( $settings['trust_device_days'] ),
esc_html__( 'days (0 = disable trusted devices)', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When greater than 0, users see a "Remember this browser" checkbox after a successful 2FA verification. Trusted browsers skip the 2FA challenge for the configured duration.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the grace period days field.
*
* @return void
*/
public function render_grace_period_days_field(): void {
$settings = $this->get_settings();
printf(
'<input type="number" name="%1$s[grace_period_days]" value="%2$s" min="0" max="90" style="width:70px;" /> %3$s',
esc_attr( self::OPTION_NAME ),
absint( $settings['grace_period_days'] ),
esc_html__( 'days (0 = no grace period)', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'Users whose role requires 2FA but who have not yet configured any method are allowed to log in for this many days before enforcement begins. The timer starts on their first login after the role requirement is applied.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the grace period action field.
*
* @return void
*/
public function render_grace_period_action_field(): void {
$settings = $this->get_settings();
$selected = $settings['grace_period_action'];
echo '<fieldset>';
printf(
'<label><input type="radio" name="%1$s[grace_period_action]" value="block" %2$s /> %3$s</label><br />',
esc_attr( self::OPTION_NAME ),
checked( 'block', $selected, false ),
esc_html__( 'Block login — the user cannot access the dashboard until an administrator enables a method for them.', 'robotstxt-2fa' )
);
printf(
'<label><input type="radio" name="%1$s[grace_period_action]" value="wizard" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( 'wizard', $selected, false ),
esc_html__( 'Forced setup — the user can log in but is redirected to the 2FA profile section on every page until at least one method is confirmed.', 'robotstxt-2fa' )
);
echo '</fieldset>';
}
/**
* Render the data management section description.
*
* @return void
*/
public function render_data_section(): void {
echo '<p>' . esc_html__( 'Control what happens to plugin data when the plugin is deleted.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the delete-on-uninstall checkbox.
*
* @return void
*/
public function render_delete_on_uninstall_field(): void {
$settings = $this->get_settings();
$is_checked = $settings['delete_on_uninstall'];
printf(
'<input type="hidden" name="%1$s[delete_on_uninstall]" value="0" />',
esc_attr( self::OPTION_NAME )
);
printf(
'<label><input type="checkbox" name="%1$s[delete_on_uninstall]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
esc_html__( 'Remove all plugin data when the plugin is deleted.', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When checked, deleting this plugin will permanently remove all settings, per-user 2FA preferences, stored secrets, recovery codes, and verification history. This action cannot be undone. Leave unchecked (default) to preserve all data if you reinstall later.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Handle the network admin settings form submission.
*
* WordPress's Settings API does not work in network admin; this handler
* validates the nonce, sanitizes input, and saves via update_site_option().
*
* @return void
*/
public function handle_network_save(): void {
check_admin_referer( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' );
if ( ! current_user_can( 'manage_network_options' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
}
$raw = isset( $_POST[ self::OPTION_NAME ] ) && is_array( $_POST[ self::OPTION_NAME ] )
? wp_unslash( $_POST[ self::OPTION_NAME ] )
: array();
$sanitized = $this->sanitize_settings( $raw );
update_site_option( self::OPTION_NAME, $sanitized );
wp_safe_redirect(
add_query_arg(
array(
'page' => 'robotstxt-2fa-settings',
'updated' => 'true',
),
network_admin_url( 'admin.php' )
)
);
exit;
}
/**
* Determine the capability required to manage settings.
*
* @return string
*/
private function get_required_capability(): string {
return $this->is_network_context() ? 'manage_network_options' : 'manage_options';
}
/**
* Check if the current request runs in a network admin context.
*
* @return bool
*/
private function is_network_context(): bool {
return is_multisite() && is_network_admin();
}
/**
* Determine if network-level settings have been stored.
*
* @return bool
*/
private function has_network_settings(): bool {
if ( ! is_multisite() ) {
return false;
}
return false !== get_site_option( self::OPTION_NAME, false );
}
/**
* Register the plugin admin page in the desired context.
*
* On the network dashboard the Settings_Page creates its own top-level menu.
* On single-site installs the top-level menu is owned by Dashboard_Page; this
* method only registers the Settings and Documentation submenus under it.
*
* @param bool $network Whether the menu is registered for the network dashboard.
*
* @return void
*/
private function register_admin_page( bool $network ): void {
$capability = $this->get_required_capability();
if ( $network ) {
add_menu_page(
__( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ),
__( '2FA', 'robotstxt-2fa' ),
$capability,
self::PAGE_SLUG,
array( $this, 'render_page' ),
'dashicons-shield'
);
// Rename the first auto-created submenu entry to "Settings".
add_submenu_page(
self::PAGE_SLUG,
__( 'Settings — 2FA', 'robotstxt-2fa' ),
__( 'Settings', 'robotstxt-2fa' ),
$capability,
self::PAGE_SLUG,
array( $this, 'render_page' )
);
add_submenu_page(
self::PAGE_SLUG,
__( 'Documentation — 2FA', 'robotstxt-2fa' ),
__( 'Documentation', 'robotstxt-2fa' ),
$capability,
self::DOCS_PAGE_SLUG,
array( $this, 'render_docs_page' )
);
} else {
// Single-site: Dashboard_Page owns the top-level menu. Register submenus only.
add_submenu_page(
self::DASHBOARD_PAGE_SLUG,
__( 'Settings — 2FA', 'robotstxt-2fa' ),
__( 'Settings', 'robotstxt-2fa' ),
$capability,
self::PAGE_SLUG,
array( $this, 'render_page' )
);
add_submenu_page(
self::DASHBOARD_PAGE_SLUG,
__( 'Documentation — 2FA', 'robotstxt-2fa' ),
__( 'Documentation', 'robotstxt-2fa' ),
$capability,
self::DOCS_PAGE_SLUG,
array( $this, 'render_docs_page' )
);
}
}
/**
* Render the Access control section description.
*
* @return void
*/
public function render_access_section(): void {
echo '<p>' . esc_html__( 'Application Passwords, IP allow lists and deny lists.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the Application Passwords exemption checkbox.
*
* @return void
*/
public function render_app_passwords_exempt_field(): void {
$settings = $this->get_settings();
$is_checked = $settings['app_passwords_exempt'];
printf(
'<input type="hidden" name="%1$s[app_passwords_exempt]" value="0" />',
esc_attr( self::OPTION_NAME )
);
printf(
'<label><input type="checkbox" name="%1$s[app_passwords_exempt]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
esc_html__( 'Exempt Application Password requests from the 2FA challenge', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'Application Password requests cannot complete browser-based 2FA challenges. Enable to let REST API and WP-CLI clients using Application Passwords skip the verification step.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the IP allow list textarea field.
*
* @return void
*/
public function render_ip_allow_field(): void {
$settings = $this->get_settings();
printf(
'<textarea name="%1$s[ip_allow]" rows="5" cols="40">%2$s</textarea>',
esc_attr( self::OPTION_NAME ),
esc_textarea( $settings['ip_allow'] )
);
echo '<p class="description">' . esc_html__( 'One IP address or CIDR range per line (e.g. 192.168.1.0/24). Requests from these IPs skip the 2FA challenge.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the IP deny list textarea field.
*
* @return void
*/
public function render_ip_deny_field(): void {
$settings = $this->get_settings();
printf(
'<textarea name="%1$s[ip_deny]" rows="5" cols="40">%2$s</textarea>',
esc_attr( self::OPTION_NAME ),
esc_textarea( $settings['ip_deny'] )
);
echo '<p class="description">' . esc_html__( 'One IP address or CIDR range per line. Login is blocked outright for these IPs.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the Email notifications section description.
*
* @return void
*/
public function render_notifications_section(): void {
echo '<p>' . esc_html__( 'Automatic email alerts for security-relevant events.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the on-method-enable notification checkbox.
*
* @return void
*/
public function render_notif_on_enable_field(): void {
$settings = $this->get_settings();
printf(
'<label><input type="checkbox" name="%1$s[notifications][on_enable]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $settings['notifications']['on_enable'], true, false ),
esc_html__( 'Notify the user when an administrator enables 2FA for their account.', 'robotstxt-2fa' )
);
}
/**
* Render the new-IP notification checkbox.
*
* @return void
*/
public function render_notif_on_new_ip_field(): void {
$settings = $this->get_settings();
printf(
'<label><input type="checkbox" name="%1$s[notifications][on_new_ip]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $settings['notifications']['on_new_ip'], true, false ),
esc_html__( 'Notify the user on login from an unrecognised browser or IP.', 'robotstxt-2fa' )
);
}
/**
* Render the recovery-code-used notification checkboxes.
*
* @return void
*/
public function render_notif_on_recovery_field(): void {
$settings = $this->get_settings();
printf(
'<label><input type="checkbox" name="%1$s[notifications][on_recovery_used]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $settings['notifications']['on_recovery_used'], true, false ),
esc_html__( 'Notify user when a recovery code is used.', 'robotstxt-2fa' )
);
echo '<br />';
printf(
'<label style="margin-top:6px;display:inline-block;"><input type="checkbox" name="%1$s[notifications][on_recovery_used_admin]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $settings['notifications']['on_recovery_used_admin'], true, false ),
esc_html__( 'Also notify site administrator.', 'robotstxt-2fa' )
);
}
/**
* Render the activity digest checkbox and frequency radio buttons.
*
* @return void
*/
public function render_notif_digest_field(): void {
$settings = $this->get_settings();
$frequency = $settings['notifications']['digest_frequency'];
printf(
'<label><input type="checkbox" name="%1$s[notifications][digest_enabled]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $settings['notifications']['digest_enabled'], true, false ),
esc_html__( 'Send a periodic activity digest to site administrators.', 'robotstxt-2fa' )
);
echo '<fieldset style="margin-top:8px;">';
printf(
'<label><input type="radio" name="%1$s[notifications][digest_frequency]" value="weekly" %2$s /> %3$s</label><br />',
esc_attr( self::OPTION_NAME ),
checked( 'weekly', $frequency, false ),
esc_html__( 'Weekly', 'robotstxt-2fa' )
);
printf(
'<label><input type="radio" name="%1$s[notifications][digest_frequency]" value="monthly" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( 'monthly', $frequency, false ),
esc_html__( 'Monthly (every 30 days)', 'robotstxt-2fa' )
);
echo '</fieldset>';
}
/**
* Render the Application Passwords require 2FA creation checkbox.
*
* @return void
*/
public function render_app_passwords_require_2fa_creation_field(): void {
$settings = $this->get_settings();
$is_checked = $settings['app_passwords_require_2fa_creation'];
printf(
'<input type="hidden" name="%1$s[app_passwords_require_2fa_creation]" value="0" />',
esc_attr( self::OPTION_NAME )
);
printf(
'<label><input type="checkbox" name="%1$s[app_passwords_require_2fa_creation]" value="1" %2$s /> %3$s</label>',
esc_attr( self::OPTION_NAME ),
checked( $is_checked, true, false ),
esc_html__( 'Require a recent 2FA verification before creating a new Application Password.', 'robotstxt-2fa' )
);
echo '<p class="description">' . esc_html__( 'When enabled, users must have completed a 2FA challenge within the last 15 minutes before they can generate a new Application Password via the REST API.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the GeoIP section description.
*
* @return void
*/
public function render_geoip_section(): void {
echo '<p>' . esc_html__( 'Requires a MaxMind GeoLite2 Country database file (.mmdb). Leave empty to disable country-based rules. Download the free GeoLite2 Country database from maxmind.com.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the GeoIP database path field.
*
* @return void
*/
public function render_geoip_database_path_field(): void {
$settings = $this->get_settings();
printf(
'<input type="text" name="%1$s[geoip_database_path]" value="%2$s" size="60" />',
esc_attr( self::OPTION_NAME ),
esc_attr( $settings['geoip_database_path'] )
);
echo '<p class="description">' . esc_html__( 'Absolute path to the GeoLite2-Country.mmdb file. Leave empty to disable GeoIP features.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the GeoIP country allow list textarea.
*
* @return void
*/
public function render_geoip_country_allow_field(): void {
$settings = $this->get_settings();
printf(
'<textarea name="%1$s[geoip_country_allow]" rows="3" cols="40">%2$s</textarea>',
esc_attr( self::OPTION_NAME ),
esc_textarea( $settings['geoip_country_allow'] )
);
echo '<p class="description">' . esc_html__( 'ISO country codes (one per line, e.g. ES, US) whose logins bypass the 2FA challenge.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the GeoIP country deny list textarea.
*
* @return void
*/
public function render_geoip_country_deny_field(): void {
$settings = $this->get_settings();
printf(
'<textarea name="%1$s[geoip_country_deny]" rows="3" cols="40">%2$s</textarea>',
esc_attr( self::OPTION_NAME ),
esc_textarea( $settings['geoip_country_deny'] )
);
echo '<p class="description">' . esc_html__( 'ISO country codes blocked from logging in altogether.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the GeoIP always-challenge countries textarea.
*
* @return void
*/
public function render_geoip_always_challenge_field(): void {
$settings = $this->get_settings();
printf(
'<textarea name="%1$s[geoip_always_challenge]" rows="3" cols="40">%2$s</textarea>',
esc_attr( self::OPTION_NAME ),
esc_textarea( $settings['geoip_always_challenge'] )
);
echo '<p class="description">' . esc_html__( 'ISO country codes that always trigger a 2FA challenge, regardless of the verification frequency setting.', 'robotstxt-2fa' ) . '</p>';
}
/**
* Render the Documentation page.
*
* @return void
*/
public function render_docs_page(): void {
$capability = $this->get_required_capability();
if ( ! current_user_can( $capability ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
}
?>
<div class="wrap">
<h1><?php esc_html_e( 'Documentation — 2FA (by ROBOTSTXT)', 'robotstxt-2fa' ); ?></h1>
<p><?php esc_html_e( 'Reference for developers: all actions, filters, and shortcodes exposed by the plugin.', 'robotstxt-2fa' ); ?></p>
<h2><?php esc_html_e( 'Shortcode', 'robotstxt-2fa' ); ?></h2>
<p><?php esc_html_e( 'Renders the full 2FA settings section on any page or post without requiring wp-admin access. Useful for membership sites with a frontend dashboard.', 'robotstxt-2fa' ); ?></p>
<pre style="background:#f6f7f7;border:1px solid #dcdcde;padding:10px 14px;display:inline-block;">[robotstxt_2fa_profile]
[robotstxt_2fa_profile user_id="42" redirect="https://example.com/account"]</pre>
<table class="widefat striped" style="max-width:700px;margin-top:1em;">
<thead><tr><th><?php esc_html_e( 'Attribute', 'robotstxt-2fa' ); ?></th><th><?php esc_html_e( 'Default', 'robotstxt-2fa' ); ?></th><th><?php esc_html_e( 'Description', 'robotstxt-2fa' ); ?></th></tr></thead>
<tbody>
<tr><td><code>user_id</code></td><td><?php esc_html_e( 'Current user', 'robotstxt-2fa' ); ?></td><td><?php esc_html_e( 'ID of the user to edit. Admins can specify another user.', 'robotstxt-2fa' ); ?></td></tr>
<tr><td><code>redirect</code></td><td><?php esc_html_e( 'Current page', 'robotstxt-2fa' ); ?></td><td><?php esc_html_e( 'URL to redirect to after a successful save.', 'robotstxt-2fa' ); ?></td></tr>
</tbody>
</table>
<h2 style="margin-top:2em;"><?php esc_html_e( 'Action hooks', 'robotstxt-2fa' ); ?></h2>
<table class="widefat striped">
<thead><tr>
<th><?php esc_html_e( 'Hook', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Since', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Arguments', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Description', 'robotstxt-2fa' ); ?></th>
</tr></thead>
<tbody>
<?php
$actions = array(
array( 'robotstxt_2fa_before_send_email', '1.0.0', 'int $user_id, string $code, int $expires', __( 'Fires just before the email verification code is delivered.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_verification_success', '1.0.0', 'WP_User $user, string $method', __( 'Fires after a successful 2FA challenge. Use for audit logs or trusted-device recording.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_verification_failed', '1.0.0', 'WP_User $user, string $method', __( 'Fires on each failed 2FA attempt. Use for rate-limiting or alerting.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_method_enabled', '1.0.0', 'WP_User $user, string $method', __( 'Fires when a user activates a method from their profile.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_method_disabled', '1.0.0', 'WP_User $user, string $method', __( 'Fires when a user deactivates a method from their profile.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_qr_generation_failed', '0.2.0', 'Throwable $e, string $uri', __( 'Fires when QR code SVG rendering throws an exception.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_recovery_generation_failed', '0.2.0', 'Throwable $e', __( 'Fires when recovery code generation throws an exception.', 'robotstxt-2fa' ) ),
);
foreach ( $actions as $hook ) :
?>
<tr>
<td><code><?php echo esc_html( $hook[0] ); ?></code></td>
<td><?php echo esc_html( $hook[1] ); ?></td>
<td><code style="white-space:normal;"><?php echo esc_html( $hook[2] ); ?></code></td>
<td><?php echo esc_html( $hook[3] ); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2 style="margin-top:2em;"><?php esc_html_e( 'Filter hooks', 'robotstxt-2fa' ); ?></h2>
<table class="widefat striped">
<thead><tr>
<th><?php esc_html_e( 'Filter', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Since', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Default', 'robotstxt-2fa' ); ?></th>
<th><?php esc_html_e( 'Description', 'robotstxt-2fa' ); ?></th>
</tr></thead>
<tbody>
<?php
$filters = array(
array( 'robotstxt_2fa_skip_challenge', '1.0.0', 'false', __( 'Return true to bypass the 2FA challenge entirely (REST API, WP-CLI, trusted IP…).', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_required_methods_for_user', '1.0.0', 'string[]', __( 'Override the required methods for a specific user; receives current role-based array and WP_User.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_code_length', '1.0.0', '7', __( 'Number of digits in the email verification code.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_code_ttl', '1.0.0', '600', __( 'Seconds before an email verification code expires.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_resend_interval', '1.0.0', '60', __( 'Minimum seconds between email resend requests.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_email_subject', '1.0.0', 'string', __( 'Subject line of the verification code email. Receives subject and WP_User.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_email_message', '1.0.0', 'string', __( 'Body of the verification code email. Receives message, WP_User, and plain-text code.', 'robotstxt-2fa' ) ),
array( 'robotstxt_2fa_profile_wrapper_class', '1.0.0', 'robotstxt-2fa-frontend', __( 'CSS class on the [robotstxt_2fa_profile] shortcode container.', 'robotstxt-2fa' ) ),
);
foreach ( $filters as $hook ) :
?>
<tr>
<td><code><?php echo esc_html( $hook[0] ); ?></code></td>
<td><?php echo esc_html( $hook[1] ); ?></td>
<td><code><?php echo esc_html( $hook[2] ); ?></code></td>
<td><?php echo esc_html( $hook[3] ); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p style="margin-top:1.5em;">
<?php
printf(
/* translators: %s: link to hooks.md file. */
esc_html__( 'Full documentation with code examples: %s', 'robotstxt-2fa' ),
'<a href="https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/src/branch/main/docs/hooks.md" target="_blank" rel="noopener">docs/hooks.md</a>'
);
?>
</p>
</div>
<?php
}
}