settings = Plugin::get_settings( 'security' );
$this->client_ip_address = Utils::get_client_ip();
$this->table_name = $wpdb->prefix . 'adminease_password_protection_log';
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
add_filter( 'adminease_localize_script', [ $this, 'adminease_localize_script' ] );
add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] );
add_action( 'adminease_after_child_field_render', [ $this, 'adminease_after_child_field_render' ], 10, 2 );
add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_filter( 'adminease_validate_settings', [ $this, 'normalize_password_on_save' ], 20 );
add_filter( 'pre_update_option_adminease_settings', [ $this, 'maybe_hash_password_on_save' ], 10, 2 );
add_action( 'wp_ajax_adminease_get_password_protection_log', [ $this, 'ajax_get_password_protection_log' ] );
add_action( 'wp_ajax_adminease_download_password_protection_log', [ $this, 'ajax_download_password_protection_log' ] );
add_action( 'wp_ajax_adminease_unlock_password_protection_ip', [ $this, 'ajax_unlock_ip' ] );
add_action( 'wp_ajax_adminease_get_password_protection_locked', [ $this, 'ajax_get_locked_ips' ] );
add_action( 'wp_ajax_adminease_search_pages_for_exclusion', [ $this, 'ajax_search_pages' ] );
add_action( 'wp_ajax_adminease_search_pages_for_inclusion', [ $this, 'ajax_search_pages' ] );
if( empty( $this->settings['password_protect_site_enabled'] ) ) {
return;
}
$this->maybe_create_table();
$this->session_timeout = $this->resolve_session_timeout();
$legacy_cron = wp_next_scheduled( 'adminease_cleanup_failed_attempts' );
if( false !== $legacy_cron ) {
wp_unschedule_event( $legacy_cron, 'adminease_cleanup_failed_attempts' );
}
add_action( 'parse_request', [ $this, 'check_early_access' ], -1000 );
add_action( 'template_redirect', [ $this, 'check_access' ], 0 );
add_filter( 'robots_txt', [ $this, 'robots_txt' ], PHP_INT_MAX );
add_filter( 'rest_pre_dispatch', [ $this, 'check_rest_access' ], -1000, 3 );
add_action( 'wp_ajax_adminease_site_password_check', [ $this, 'ajax_password_check' ] );
add_action( 'wp_ajax_nopriv_adminease_site_password_check', [ $this, 'ajax_password_check' ] );
add_action( 'wp_footer', [ $this, 'cleanup_url_parameter' ], 99 );
}
/**
* Resolve session timeout from settings, with safe fallbacks.
*
* @return int Timeout in seconds.
*/
private function resolve_session_timeout(): int {
$remember = $this->settings['password_protect_site_remember_device'] ?? '';
if( 'other' === $remember && !empty( $this->settings['password_protect_site_remember_device_other'] ) ) {
return max( 0, (int) $this->settings['password_protect_site_remember_device_other'] );
}
if( is_numeric( $remember ) ) {
return max( 0, (int) $remember );
}
$allowed_constants = [
'HOUR_IN_SECONDS',
'DAY_IN_SECONDS',
'WEEK_IN_SECONDS',
'MONTH_IN_SECONDS',
'YEAR_IN_SECONDS',
];
if( in_array( $remember, $allowed_constants, true ) && defined( $remember ) ) {
return (int) constant( $remember );
}
return self::SESSION_DEFAULT;
}
/**
* Reacts to a settings save: creates the log table the first time password
* protection is enabled. Registered unconditionally (not gated on the feature's
* own enabled flag read in the constructor) so enabling the feature for the
* first time in this request still creates the table it is about to log into.
*
* @param array $sanitized_settings The full sanitized settings array.
*
* @return void
*/
public function adminease_settings_saved( array $sanitized_settings ): void {
if( !empty( $sanitized_settings['security']['password_protect_site_enabled'] ) ) {
$this->maybe_create_table();
}
}
/**
* Creates the access log table if it does not already exist, then migrates any
* legacy option-based log entries into it. Safe to call on every request that
* needs it: dbDelta() is idempotent and the migration guards itself on the
* presence of the legacy option.
*
* @return void
*/
private function maybe_create_table(): void {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE {$this->table_name} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
timestamp datetime NOT NULL,
ip_address varchar(45) NOT NULL,
country varchar(255) DEFAULT NULL,
status varchar(20) NOT NULL,
user_agent text DEFAULT NULL,
password_length int(11) DEFAULT 0,
PRIMARY KEY (id),
KEY timestamp (timestamp),
KEY ip_address (ip_address),
KEY status (status)
) {$charset_collate};";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
$this->maybe_migrate_legacy_option_log();
}
/**
* One-time migration of the legacy `adminease_password_protection_logs` option
* (an array capped at MAX_LOG_ENTRIES) into the new database table. Guarded by
* the option's own existence, so it is a no-op on every call after the first.
*
* @return void
*/
private function maybe_migrate_legacy_option_log(): void {
global $wpdb;
$logs = get_option( self::LOG_OPTION, [] );
if( !is_array( $logs ) || empty( $logs ) ) {
return;
}
foreach( $logs as $log ) {
if( !is_array( $log ) ) {
continue;
}
$status = $log['status'] ?? ( !empty( $log['success'] ) ? 'success' : 'failed' );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- One-time migration insert.
$wpdb->insert(
$this->table_name,
[
'timestamp' => $log['timestamp'] ?? current_time( 'mysql' ),
'ip_address' => (string) ( $log['ip'] ?? '' ),
'country' => '',
'status' => (string) $status,
'user_agent' => (string) ( $log['user_agent'] ?? '' ),
'password_length' => (int) ( $log['password_length'] ?? 0 ),
],
[ '%s', '%s', '%s', '%s', '%s', '%d' ]
);
}
delete_option( self::LOG_OPTION );
}
/**
* Add password protection settings fields to the security section
*
* @param array $fields Existing security settings fields
*
* @return array Modified fields with password protection options
*/
public function adminease_settings_fields( array $fields ): array {
$blog_name = get_bloginfo( 'name' );
$has_existing_password = !empty( $this->settings['password_protect_site_password'] );
$fields['security']['fields'][] = [
'type' => 'switch',
'id' => 'password-protect-site-enabled',
'name' => 'adminease[security][password_protect_site_enabled]',
'value' => $this->settings['password_protect_site_enabled'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input toggle-field',
'label' => __( 'Enable Password Protection', 'adminease' ),
'risk' => 'careful',
'breaks' => __( 'Visitors need the password to see your site.', 'adminease' ),
'description' => __( 'Enable password protection for the entire site.', 'adminease' ),
'child_fields' => [
[
'type' => 'switch',
'id' => 'password-protect-site-show-logo',
'name' => 'adminease[security][password_protect_site_show_logo]',
'value' => $this->settings['password_protect_site_show_logo'] ?? true,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Show Site Logo', 'adminease' ),
'description' => __( 'Display the site logo from Customizer settings.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'switch',
'id' => 'password-protect-site-auto-load-log',
'name' => 'adminease[security][password_protect_site_auto_load_log]',
'value' => $this->settings['password_protect_site_auto_load_log'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Auto-load Access Log', 'adminease' ),
'description' => __( 'Automatically load the password protection access log when the page loads.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'number',
'id' => 'password-protect-site-log-retention',
'name' => 'adminease[security][password_protect_site_log_retention]',
'value' => $this->settings['password_protect_site_log_retention'] ?? self::MAX_LOG_ENTRIES,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Access Log Retention', 'adminease' ),
'field_description' => __( 'Maximum number of log entries to keep. Set to 0 to disable logging.', 'adminease' ),
'attributes' => [
'min' => 0,
'max' => 10000,
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'password',
'id' => 'password-protect-site-password',
'name' => 'adminease[security][password_protect_site_password]',
'value' => '',
'placeholder' => $has_existing_password ? '••••••••••••' : '',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Site Password', 'adminease' ),
'description' => $has_existing_password
? __( 'A password is already set. Leave blank to keep the current password, or type a new one to replace it.', 'adminease' )
: __( 'Choose a strong password to gate access to the site.', 'adminease' ),
'field_description' => $has_existing_password
? __( '✓ A password is currently saved (stored hashed). The saved value is never displayed here for security.', 'adminease' )
: __( 'Stored hashed; the value is never displayed back here.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
'autocomplete' => 'new-password',
'data-has-password' => $has_existing_password ? '1' : '0',
],
],
[
'type' => 'switch',
'id' => 'password-protect-site-bind-ip',
'name' => 'adminease[security][password_protect_site_bind_ip]',
'value' => $this->settings['password_protect_site_bind_ip'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Bind Authentication To IP', 'adminease' ),
'description' => __( 'Invalidate the auth cookie if the client IP changes. Disable for mobile users on changing networks.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'number',
'id' => 'password-protect-site-max-attempts',
'name' => 'adminease[security][password_protect_site_max_attempts]',
'value' => $this->settings['password_protect_site_max_attempts'] ?? self::MAX_FAILED_ATTEMPTS,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Failed Attempts Before Lockout', 'adminease' ),
'description' => __( 'After this many wrong passwords from one IP address, that address is locked out for 30 minutes. A locked address can be unlocked from the list under the access log.', 'adminease' ),
'attributes' => [
'min' => 1,
'max' => 50,
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'switch',
'id' => 'password-protect-site-block-robots',
'name' => 'adminease[security][password_protect_site_block_robots]',
'value' => $this->settings['password_protect_site_block_robots'] ?? true,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Ask Search Engines Not To Crawl', 'adminease' ),
'description' => __( 'While the whole site is protected, robots.txt asks search engines to stay away from every page. Not used when Included Pages is set.', 'adminease' ),
'field_description' => $this->get_robots_txt_notice(),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'switch',
'id' => 'password-protect-site-block-rest',
'name' => 'adminease[security][password_protect_site_block_rest]',
'value' => $this->settings['password_protect_site_block_rest'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Protect The REST API', 'adminease' ),
'description' => __( 'While the whole site is protected, visitors who have not entered the password cannot read your posts, pages or products through /wp-json/. Outside services that call your site without logging in, such as some payment and form services, are blocked too. Not used when Included Pages is set.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'select',
'id' => 'password-protect-site-theme',
'name' => 'adminease[security][password_protect_site_theme]',
'value' => $this->settings['password_protect_site_theme'] ?? 'classic',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Page Theme', 'adminease' ),
'description' => __( 'Choose the visual style of the password page.', 'adminease' ),
'options' => $this->get_theme_options(),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'text',
'id' => 'password-protect-site-page-title',
'name' => 'adminease[security][password_protect_site_page_title]',
'value' => $this->settings['password_protect_site_page_title'] ?? $blog_name . ' - ' . __( 'Password Protected', 'adminease' ),
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Page Title', 'adminease' ),
'description' => __( 'The title that appears in the browser tab.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'text',
'id' => 'password-protect-site-headline',
'name' => 'adminease[security][password_protect_site_headline]',
'value' => $this->settings['password_protect_site_headline'] ?? $blog_name,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Headline', 'adminease' ),
'description' => __( 'The main heading displayed on the maintenance page.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'textarea',
'id' => 'password-protect-site-entry-message',
'name' => 'adminease[security][password_protect_site_entry_message]',
'value' => $this->settings['password_protect_site_entry_message'] ?? __( 'This site is password protected. Please enter the password to access the site.', 'adminease' ),
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Message', 'adminease' ),
'description' => __( 'The message displayed on the password protected page.', 'adminease' ),
'field_description' => __( 'You can use basic HTML tags.', 'adminease' ),
'attributes' => [
'rows' => 4,
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'colorpicker',
'id' => 'password-protect-site-primary-color',
'name' => 'adminease[security][password_protect_site_primary_color]',
'value' => $this->settings['password_protect_site_primary_color'] ?? '#0073aa',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child ae-color-field ae-color-field-primary',
'label' => __( 'Primary Color', 'adminease' ),
'description' => __( 'Select the primary color for the password protected page.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'colorpicker',
'id' => 'password-protect-site-secondary-color',
'name' => 'adminease[security][password_protect_site_secondary_color]',
'value' => $this->settings['password_protect_site_secondary_color'] ?? '#23282d',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child ae-color-field ae-color-field-secondary',
'label' => __( 'Secondary Color', 'adminease' ),
'description' => __( 'Select the secondary color for the password protected page.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'colorpicker',
'id' => 'password-protect-site-text-color',
'name' => 'adminease[security][password_protect_site_text_color]',
'value' => $this->settings['password_protect_site_text_color'] ?? '#333333',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child ae-color-field ae-color-field-text',
'label' => __( 'Text Color', 'adminease' ),
'description' => __( 'Select the text color for the password protected page.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'select',
'id' => 'password-protect-site-excluded-pages',
'name' => 'adminease[security][password_protect_site_excluded_pages][]',
'value' => (array) ( $this->settings['password_protect_site_excluded_pages'] ?? [] ),
'options' => $this->get_selected_post_options( (array) ( $this->settings['password_protect_site_excluded_pages'] ?? [] ) ),
'has_optgroups' => true,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input adminease-choices',
'wrapper_class' => 'form-group-child',
'label' => __( 'Excluded Pages', 'adminease' ),
'description' => __( 'Pages that bypass password protection.', 'adminease' ),
'field_description' => __( 'Search and select any page, post, or custom post type. Selected pages will bypass the password form.', 'adminease' ),
'attributes' => [
'multiple' => 'multiple',
'data-allow_clear' => true,
'data-allow_select_all' => true,
'data-parent' => 'password-protect-site-enabled',
'data-ajax-action' => 'adminease_search_pages_for_exclusion',
],
],
[
'type' => 'switch',
'id' => 'password-protect-site-bypass-archives',
'name' => 'adminease[security][password_protect_site_bypass_archives]',
'value' => $this->settings['password_protect_site_bypass_archives'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Bypass On Archives & Home', 'adminease' ),
'description' => __( 'Allow archive pages, the blog index, and the home page through without a password.', 'adminease' ),
'attributes' => [
'data-parent' => 'password-protect-site-enabled',
],
],
[
'type' => 'select',
'id' => 'password-protect-site-included-pages',
'name' => 'adminease[security][password_protect_site_included_pages][]',
'value' => (array) ( $this->settings['password_protect_site_included_pages'] ?? [] ),
'options' => $this->get_selected_post_options( (array) ( $this->settings['password_protect_site_included_pages'] ?? [] ) ),
'has_optgroups' => true,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input adminease-choices',
'wrapper_class' => 'form-group-child',
'label' => __( 'Included Pages', 'adminease' ),
'description' => __( 'Show the password form ONLY on these pages. Leave empty to protect the entire site.', 'adminease' ),
'field_description' => __( 'Search and select any page, post, or custom post type. When set, only these pages will show the password form.', 'adminease' ),
'attributes' => [
'multiple' => 'multiple',
'data-allow_clear' => true,
'data-allow_select_all' => true,
'data-parent' => 'password-protect-site-enabled',
'data-ajax-action' => 'adminease_search_pages_for_inclusion',
],
],
],
];
return $fields;
}
/**
* Warns that the robots.txt switch cannot work when a physical robots.txt shadows the virtual
* one WordPress generates: the web server serves the file and the robots_txt filter never runs.
*
* @return string Notice text, or '' when there is no physical file.
*/
private function get_robots_txt_notice(): string {
$robots_txt = FileHandler::get_instance()->get_robots_txt_status();
if( empty( $robots_txt['exists'] ) ) {
return '';
}
return __( 'Your site has a physical robots.txt file, which replaces the one WordPress generates, so this setting cannot change it. Add "User-agent: *" and "Disallow: /" to that file by hand while the site is protected.', 'adminease' );
}
/**
* Normalize the site password inside the sanitized settings array, before it is
* persisted via update_option(). This is the primary save path and ensures
* Plugin::$settings (assigned post-validation) holds the correct hashed value
* for the remainder of the request.
*
* - Blank submission with an existing stored value → keep existing.
* - Already-hashed submission → keep as-is.
* - Plaintext submission → hash with wp_hash_password().
*
* @param mixed $sanitized_settings The full sanitized settings array.
*
* @return mixed
*/
public function normalize_password_on_save( $sanitized_settings ) {
if( !is_array( $sanitized_settings ) ) {
return $sanitized_settings;
}
if( !isset( $sanitized_settings['security'] ) || !is_array( $sanitized_settings['security'] ) ) {
return $sanitized_settings;
}
$submitted = (string) ( $sanitized_settings['security']['password_protect_site_password'] ?? '' );
$existing = (string) ( Plugin::get_settings( 'security' )['password_protect_site_password'] ?? '' );
if( '' === $submitted ) {
$sanitized_settings['security']['password_protect_site_password'] = $existing;
} elseif( !$this->is_password_hashed( $submitted ) ) {
$sanitized_settings['security']['password_protect_site_password'] = wp_hash_password( $submitted );
}
return $sanitized_settings;
}
/**
* Hash the site password before settings are persisted (defensive layer for
* any code path that calls update_option('adminease_settings', ...) directly).
* If submitted value is empty, retain the previously stored hash.
* If submitted value is already a recognized hash, store as-is.
*
* @param mixed $new_value The settings array about to be saved.
* @param mixed $old_value The existing settings array.
*
* @return mixed Possibly mutated settings array.
*/
public function maybe_hash_password_on_save( $new_value, $old_value ) {
if ( !is_array( $new_value ) ) {
return $new_value;
}
$submitted = $new_value['security']['password_protect_site_password'] ?? '';
$existing = ( is_array( $old_value ) ? ( $old_value['security']['password_protect_site_password'] ?? '' ) : '' );
if ( '' === $submitted ) {
$new_value['security']['password_protect_site_password'] = $existing;
} elseif ( !$this->is_password_hashed( $submitted ) ) {
$new_value['security']['password_protect_site_password'] = wp_hash_password( $submitted );
}
return $new_value;
}
/**
* Detect whether a stored password value is already in a recognized hash format.
*
* @param string $value Stored password value.
*
* @return bool True if the value looks like a phpass / bcrypt / argon2 / WP 6.8+ ($wp$) hash.
*/
private function is_password_hashed( string $value ): bool {
return 0 === strpos( $value, self::HASH_PREFIX_PHPASS )
|| 0 === strpos( $value, self::HASH_PREFIX_BCRYPT )
|| 0 === strpos( $value, self::HASH_PREFIX_ARGON )
|| 0 === strpos( $value, self::HASH_PREFIX_WP );
}
/**
* Determines whether the current user has access to the site and handles access control.
* Skips checks if in the admin area or during an AJAX request. If access is not granted and the user is not authenticated, displays a password form and terminates further execution.
*
* @return void
*/
public function check_access(): void {
if( $this->is_exempt_request() ) {
return;
}
if( is_robots() ) {
return;
}
if( $this->is_page_included_only() ) {
return;
}
if( $this->is_page_excluded() ) {
return;
}
$this->prevent_caching();
if( $this->is_authenticated() ) {
return;
}
$this->show_password_form();
exit;
}
/**
* Gates the request on parse_request, before the main query runs and before any SEO plugin
* prints a sitemap. Feeds and sitemaps are always decided here. Ordinary pages are decided here
* too when nothing is excluded, and are otherwise left to check_access() on template_redirect,
* since excluded pages and archives can only be recognised once the main query has run.
*
* @param \WP $wp Current WordPress environment instance.
*
* @return void
*/
public function check_early_access( $wp ): void {
if( !$this->is_site_wide() || $this->is_exempt_request() ) {
return;
}
$query_vars = ( is_object( $wp ) && isset( $wp->query_vars ) && is_array( $wp->query_vars ) ) ? $wp->query_vars : [];
if( !empty( $query_vars['robots'] ) ) {
return;
}
if( !empty( $query_vars['wc-api'] ) ) {
return;
}
$is_feed_or_sitemap = $this->is_feed_or_sitemap_request( $query_vars );
if( !$is_feed_or_sitemap && $this->has_page_exceptions() ) {
return;
}
$this->prevent_caching();
if( $this->is_authenticated() ) {
return;
}
if( $is_feed_or_sitemap ) {
$this->send_gate_headers();
if( !headers_sent() ) {
header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
}
echo esc_html__( 'This site is password protected.', 'adminease' );
exit;
}
$this->show_password_form();
exit;
}
/**
* Requests that are never gated: the admin, AJAX, logged-in users, REST, cron, and anything
* the adminease_password_protect_site_check_access filter lets through (Pro's role and IP
* bypass).
*
* @return bool
*/
private function is_exempt_request(): bool {
if( is_admin() || wp_doing_ajax() || is_user_logged_in() ) {
return true;
}
if( $this->is_rest_api_request() ) {
return true;
}
if( defined( 'DOING_CRON' ) && DOING_CRON ) {
return true;
}
return (bool) apply_filters( 'adminease_password_protect_site_check_access', false );
}
/**
* Whether the whole site is protected, as opposed to only the pages in the included list.
*
* @return bool
*/
private function is_site_wide(): bool {
return empty( $this->settings['password_protect_site_included_pages'] );
}
/**
* Whether some pages are let through without a password, which can only be decided once the
* main query has run.
*
* @return bool
*/
private function has_page_exceptions(): bool {
return !empty( $this->settings['password_protect_site_bypass_archives'] )
|| !empty( $this->settings['password_protect_site_excluded_pages'] );
}
/**
* Whether the request is for a feed or an XML sitemap. Matches the query vars SEO plugins
* register, plus any URL ending in .xml, .xsl or .rss so sitemaps from plugins that read the
* URL directly (AIOSEO) or that are not listed are caught as well.
*
* @param array $query_vars Query vars parsed by WP::parse_request().
*
* @return bool
*/
private function is_feed_or_sitemap_request( array $query_vars ): bool {
if( !empty( $query_vars['feed'] ) ) {
return true;
}
foreach( self::SITEMAP_QUERY_VARS as $query_var ) {
if( !empty( $query_vars[ $query_var ] ) ) {
return true;
}
}
if( !isset( $_SERVER['REQUEST_URI'] ) ) {
return false;
}
$path = wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH );
return is_string( $path ) && 1 === preg_match( '/\.(xml|xsl|rss)(\.gz)?$/i', $path );
}
/**
* The HTTP status sent with the gate. 401 by default; a 4xx or 5xx from the
* adminease_password_protection_status_code filter replaces it, anything else is ignored.
*
* @return int
*/
private function get_status_code(): int {
$status = (int) apply_filters( 'adminease_password_protection_status_code', self::DEFAULT_STATUS_CODE );
if( $status < 400 || $status > 599 ) {
return self::DEFAULT_STATUS_CODE;
}
return $status;
}
/**
* Headers for a gated response: an error status so search engines never treat the form as the
* page's content, an explicit noindex, and a Cache-Control that keeps the form out of every
* shared cache.
*
* @return void
*/
private function send_gate_headers(): void {
if( headers_sent() ) {
return;
}
status_header( $this->get_status_code() );
header( 'X-Robots-Tag: noindex, nofollow' );
header( 'Cache-Control: ' . self::GATE_CACHE_CONTROL );
}
/**
* Gates the REST API for visitors who have not entered the password, when the "Protect The REST
* API" switch is on and the whole site is protected. Runs on rest_pre_dispatch, after WordPress
* has authenticated the request, so application passwords, WooCommerce API keys and other
* authentication methods still get through.
*
* @param mixed $result Response to replace the requested one with, or null.
* @param \WP_REST_Server $server Server instance.
* @param \WP_REST_Request $request Request used to generate the response.
*
* @return mixed
*/
public function check_rest_access( $result, $server, $request ) {
if( null !== $result || empty( $this->settings['password_protect_site_block_rest'] ) || !$this->is_site_wide() ) {
return $result;
}
if( !defined( 'REST_REQUEST' ) || !REST_REQUEST ) {
return $result;
}
if( is_user_logged_in() || wp_validate_auth_cookie( '', 'logged_in' ) ) {
return $result;
}
if( $this->is_authenticated() || apply_filters( 'adminease_password_protect_site_check_access', false ) ) {
return $result;
}
/**
* Whether a REST request may skip the password, for example a payment webhook route.
*
* @param bool $allowed Whether the request is let through. Default false.
* @param \WP_REST_Request $request The REST request.
*/
if( apply_filters( 'adminease_password_protection_rest_allowed', false, $request ) ) {
return $result;
}
$this->send_gate_headers();
return new WP_Error(
'adminease_password_protected',
__( 'This site is password protected.', 'adminease' ),
[ 'status' => $this->get_status_code() ]
);
}
/**
* Replaces the virtual robots.txt with a rule that asks every crawler to stay away while the
* whole site is protected. Runs last so an SEO plugin's own rules cannot add the sitemap back.
* Has no effect when a physical robots.txt exists, since the web server serves that file.
*
* @param string $output The robots.txt content.
*
* @return string
*/
public function robots_txt( $output ) {
if( !$this->is_site_wide() ) {
return $output;
}
$block = !empty( $this->settings['password_protect_site_block_robots'] ?? true );
/**
* Whether robots.txt asks every crawler to stay away while the site is password protected.
*
* @param bool $block True to replace robots.txt with "Disallow: /".
*/
if( !apply_filters( 'adminease_password_protection_block_robots', $block ) ) {
return $output;
}
if( !headers_sent() ) {
header( 'Cache-Control: ' . self::GATE_CACHE_CONTROL );
}
return "User-agent: *\nDisallow: /\n";
}
/**
* Instruct page caches, hosts, and CDNs not to store the current response. Applied to every
* request inside the protection scope so the gate is never short-circuited by a cached page.
*
* A CDN set to "cache everything" with an explicit edge TTL can still ignore these headers; the
* client-side cache-buster (see cleanup_url_parameter() and the theme escape hatch) covers that
* case, and an optional CDN rule bypassing cache on the auth cookie closes it leak-proof.
*
* @return void
*/
private function prevent_caching(): void {
if( !defined( 'DONOTCACHEPAGE' ) ) {
define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
}
if( !defined( 'DONOTCACHEOBJECT' ) ) {
define( 'DONOTCACHEOBJECT', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
}
if( !defined( 'DONOTMINIFY' ) ) {
define( 'DONOTMINIFY', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
}
if( headers_sent() ) {
return;
}
nocache_headers();
header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0, private' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
}
/**
* Strip the one-shot cache-busting query arg from the address bar after a post-login redirect,
* using the History API so the URL stays clean and shareable (no page reload). Runs on every
* front-end page; it is a no-op unless the arg is present.
*
* @return void
*/
public function cleanup_url_parameter(): void {
if( is_admin() || wp_doing_ajax() ) {
return;
}
?>
get_cookie_name();
if( empty( $_COOKIE[ $cookie_name ] ) ) {
return false;
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated below via json_decode and HMAC compare.
$raw = wp_unslash( $_COOKIE[ $cookie_name ] );
$cookie_data = json_decode( $raw, true );
if( !is_array( $cookie_data ) ) {
return false;
}
$issued = isset( $cookie_data['t'] ) ? (int) $cookie_data['t'] : 0;
$expires = isset( $cookie_data['e'] ) ? (int) $cookie_data['e'] : 0;
$version = isset( $cookie_data['v'] ) ? (int) $cookie_data['v'] : 0;
$signature = isset( $cookie_data['h'] ) && is_string( $cookie_data['h'] ) ? $cookie_data['h'] : '';
if( self::COOKIE_VERSION !== $version || $issued <= 0 || $expires <= 0 || '' === $signature ) {
return false;
}
if( time() >= $expires ) {
$this->clear_auth_cookie();
return false;
}
$expected = $this->compute_signature( $issued, $expires );
if( !hash_equals( $expected, $signature ) ) {
return false;
}
return true;
}
/**
* Retrieves the password page themes registered via the adminease_password_protect_site_themes filter.
*
* @return array Associative array of theme key => fully-qualified theme class name.
*/
private function get_registered_themes(): array {
/**
* Filter the available password page themes.
*
* @param array $themes Associative array of theme key => fully-qualified theme class name.
*/
return apply_filters( 'adminease_password_protect_site_themes', [
'classic' => Classic::class,
'minimal' => Minimal::class,
'split-screen' => SplitScreen::class,
] );
}
/**
* Builds the theme select options from the registered themes. Without Pro, a disabled
* "Terminal (Available in Pro)" placeholder is added, as Maintenance Mode does.
*
* @return array Theme key => label, or key => ['label' => string, 'disabled' => bool].
*/
private function get_theme_options(): array {
$options = [];
foreach( $this->get_registered_themes() as $key => $class ) {
$options[ $key ] = is_callable( [ $class, 'get_label' ] ) ? $class::get_label() : $key;
}
if( !isset( $options['terminal'] ) && !Utils::is_pro_plugin_active() ) {
$options['terminal'] = [
/* translators: %s: theme name */
'label' => sprintf( __( '%s (Available in Pro)', 'adminease' ), __( 'Terminal', 'adminease' ) ),
'disabled' => true,
];
}
return $options;
}
/**
* Displays the password input form for site protection, utilizing the specified theme
* and settings for customization.
*
* @return void
*/
private function show_password_form(): void {
$theme = $this->settings['password_protect_site_theme'] ?? 'classic';
$show_logo = $this->settings['password_protect_site_show_logo'] ?? true;
$custom_logo_id = get_theme_mod( 'custom_logo' );
$theme_args = [
'page_title' => $this->settings['password_protect_site_page_title'] ?? '',
'headline' => $this->settings['password_protect_site_headline'] ?? '',
'entry_message' => $this->settings['password_protect_site_entry_message'] ?? '',
'logo_url' => $show_logo ? wp_get_attachment_image_url( $custom_logo_id, 'full' ) : '',
'primary_color' => $this->settings['password_protect_site_primary_color'] ?? '#0073aa',
'secondary_color' => $this->settings['password_protect_site_secondary_color'] ?? '#23282d',
'text_color' => $this->settings['password_protect_site_text_color'] ?? '#333333',
'remember_device' => $this->settings['password_protect_site_remember_device'] ?? true,
'nocache_arg' => self::NOCACHE_QUERY_ARG,
'hint_cookie_prefix' => self::HINT_COOKIE_PREFIX,
];
$themes = $this->get_registered_themes();
$theme_class = $themes[ $theme ] ?? Classic::class;
if( !is_callable( [ $theme_class, 'render' ] ) ) {
$theme_class = Classic::class;
}
$html = $theme_class::render( $theme_args ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
/**
* Filter the maintenance page HTML
*
* @param string $html The complete HTML output
* @param array $settings Current settings
*/
$html = apply_filters( 'adminease_password_protect_site_html', $html, $this->settings );
$this->send_gate_headers();
echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Handles the AJAX request to verify the site password and authenticate the user.
*
* @return void
*/
public function ajax_password_check(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'adminease_site_password' ) ) {
wp_send_json_error( new WP_Error( 'security_error', esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ) ) );
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Password should not be sanitized, only validated.
$password = wp_unslash( $_POST['data']['password'] ?? '' );
$remember_device = !empty( $_POST['data']['remember_device'] ?? false );
$current_url = wp_validate_redirect( sanitize_url( wp_unslash( $_POST['data']['current_url'] ?? '' ) ), home_url( '/' ) );
if( $this->is_ip_locked() ) {
$this->log_authentication_attempt( 'locked' );
wp_send_json_error( new WP_Error( 'too_many_attempts', esc_html__( 'You have made too many attempts. Please try again later.', 'adminease' ) ), $this->get_status_code() );
}
$site_password = $this->settings['password_protect_site_password'] ?? '';
if( empty( $password ) || empty( $site_password ) ) {
$this->record_failed_attempt();
$this->log_authentication_attempt( 'failed', $password );
wp_send_json_error( new WP_Error( 'wrong_password_message', esc_html__( 'Incorrect password. Please try again.', 'adminease' ) ), $this->get_status_code() );
}
if( !$this->verify_password( $password, $site_password ) ) {
$this->record_failed_attempt();
$this->log_authentication_attempt( 'failed', $password );
wp_send_json_error( new WP_Error( 'wrong_password_message', esc_html__( 'Incorrect password. Please try again.', 'adminease' ) ), $this->get_status_code() );
}
if( !$this->is_password_hashed( $site_password ) ) {
$this->migrate_plaintext_password( $password );
}
$this->authenticate_user( $remember_device );
$this->log_authentication_attempt( 'success' );
wp_send_json_success( [
'message' => esc_html__( 'Access granted. Redirecting...', 'adminease' ),
'redirect_url' => !empty( $current_url ) ? $current_url : home_url( '/' ),
] );
}
/**
* Verify a submitted password against the stored value, supporting both hashed
* (current) and plaintext (legacy) storage formats.
*
* @param string $submitted The user-supplied password.
* @param string $stored The stored password value.
*
* @return bool
*/
private function verify_password( string $submitted, string $stored ): bool {
if( $this->is_password_hashed( $stored ) ) {
return wp_check_password( $submitted, $stored );
}
return hash_equals( $stored, $submitted );
}
/**
* Migrate a verified plaintext password to a hashed value in storage.
*
* @param string $plaintext The verified plaintext password.
*
* @return void
*/
private function migrate_plaintext_password( string $plaintext ): void {
$all_settings = get_option( 'adminease_settings', [] );
if( !is_array( $all_settings ) ) {
return;
}
$all_settings['security']['password_protect_site_password'] = wp_hash_password( $plaintext );
update_option( 'adminease_settings', $all_settings );
$this->settings = $all_settings['security'] ?? [];
}
/**
* Issues a stateless signed auth cookie. When "remember device" is requested, the cookie is
* persisted across browser sessions; otherwise it is a browser-session cookie.
*
* @param bool $remember_device Whether to persist the cookie across browser sessions.
*
* @return void
*/
public function authenticate_user( bool $remember_device ): void {
$lifetime = $this->session_timeout;
$persist = false;
if( $remember_device ) {
$remember_lifetime = (int) apply_filters( 'adminease_password_protect_site_remember_device_expiration', DAY_IN_SECONDS );
if( $remember_lifetime > 0 ) {
$lifetime = $remember_lifetime;
$persist = true;
}
}
$issued = time();
$expires = $issued + max( 60, $lifetime );
$cookie_value = wp_json_encode( [
'v' => self::COOKIE_VERSION,
't' => $issued,
'e' => $expires,
'h' => $this->compute_signature( $issued, $expires ),
] );
$options = [
'expires' => $persist ? $expires : 0,
'path' => defined( 'COOKIEPATH' ) && COOKIEPATH ? COOKIEPATH : '/',
'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '',
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
];
setcookie( $this->get_cookie_name(), $cookie_value, $options );
$_COOKIE[ $this->get_cookie_name() ] = $cookie_value;
$hint_options = $options;
$hint_options['httponly'] = false;
setcookie( $this->get_hint_cookie_name(), '1', $hint_options );
$_COOKIE[ $this->get_hint_cookie_name() ] = '1';
$this->clear_failed_attempts();
}
/**
* Clear the auth cookie, e.g. on expiry detection.
*
* @return void
*/
private function clear_auth_cookie(): void {
$options = [
'expires' => time() - HOUR_IN_SECONDS,
'path' => defined( 'COOKIEPATH' ) && COOKIEPATH ? COOKIEPATH : '/',
'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '',
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
];
setcookie( $this->get_cookie_name(), '', $options );
unset( $_COOKIE[ $this->get_cookie_name() ] );
$hint_options = $options;
$hint_options['httponly'] = false;
setcookie( $this->get_hint_cookie_name(), '', $hint_options );
unset( $_COOKIE[ $this->get_hint_cookie_name() ] );
}
/**
* Compute the HMAC signature for the auth cookie.
*
* @param int $issued Issued-at timestamp.
* @param int $expires Expiration timestamp.
*
* @return string
*/
private function compute_signature( int $issued, int $expires ): string {
$bind = '';
if( !empty( $this->settings['password_protect_site_bind_ip'] ) ) {
$bind = hash( 'sha256', $this->client_ip_address );
}
$payload = $issued . '|' . $expires . '|' . self::COOKIE_VERSION . '|' . $bind;
$key = wp_salt( 'auth' ) . ( $this->settings['password_protect_site_password'] ?? '' );
return hash_hmac( 'sha256', $payload, $key );
}
/**
* Build the cookie name. Hashing the home URL keeps multi-site installs separated.
*
* @return string
*/
private function get_cookie_name(): string {
return 'adminease_pps_auth_' . hash( 'crc32b', home_url() );
}
/**
* Build the non-secret hint cookie name. Set alongside the auth cookie and readable by JS so the
* client-side cache-buster can detect a stale (CDN-cached) gate page. The 'wp-postpass_' prefix
* also trips many caches' native bypass lists. Carries no secret; the real gate is the auth cookie.
*
* @return string
*/
private function get_hint_cookie_name(): string {
return self::HINT_COOKIE_PREFIX . hash( 'crc32b', home_url() );
}
/**
* Failed attempts allowed before an IP is locked out (setting, 1 to 50, default 5).
*
* @return int
*/
private function get_max_attempts(): int {
$value = (int) ( $this->settings['password_protect_site_max_attempts'] ?? self::MAX_FAILED_ATTEMPTS );
return $value >= 1 && $value <= 50 ? $value : self::MAX_FAILED_ATTEMPTS;
}
/**
* Addresses that are locked out right now, newest lock first.
*
* @return array Locked-until timestamp keyed by IP address.
*/
public static function get_locked_ips(): array {
$locked = get_option( self::LOCKED_OPTION, [] );
$locked = is_array( $locked ) ? $locked : [];
$now = time();
$locked = array_filter(
$locked,
static function ( $until ) use ( $now ): bool {
return (int) $until > $now;
}
);
arsort( $locked );
return array_map( 'intval', $locked );
}
/**
* Lifts the lockout of one address, or of all addresses.
*
* @param string $ip IP address, or an empty string for every locked address.
*
* @return void
*/
public static function unlock_ip( string $ip = '' ): void {
$locked = get_option( self::LOCKED_OPTION, [] );
$locked = is_array( $locked ) ? $locked : [];
$ips = '' === $ip ? array_keys( $locked ) : [ $ip ];
foreach( $ips as $address ) {
delete_transient( self::attempts_transient_key( (string) $address ) );
unset( $locked[ $address ] );
}
update_option( self::LOCKED_OPTION, $locked, false );
}
/**
* Whether the current IP is currently locked out due to repeated failed attempts.
*
* @return bool
*/
private function is_ip_locked(): bool {
$attempts_data = get_transient( $this->get_attempts_transient_key() );
if( !$attempts_data || !is_array( $attempts_data ) ) {
return false;
}
if( ( $attempts_data['count'] ?? 0 ) < $this->get_max_attempts() ) {
return false;
}
$first_attempt = (int) ( $attempts_data['first_attempt'] ?? 0 );
if( $first_attempt > 0 && time() - $first_attempt >= self::LOCKOUT_MINUTES * MINUTE_IN_SECONDS ) {
$this->clear_failed_attempts();
return false;
}
return true;
}
/**
* Record a failed attempt against the current IP, clamping the TTL so the window
* is anchored on the first attempt.
*
* @return void
*/
private function record_failed_attempt(): void {
$key = $this->get_attempts_transient_key();
$data = get_transient( $key );
if( !is_array( $data ) ) {
$data = [
'count' => 0,
'first_attempt' => time(),
];
}
$data['count'] = (int) ( $data['count'] ?? 0 ) + 1;
$data['last_attempt'] = time();
$elapsed = time() - (int) $data['first_attempt'];
$remaining = ( self::LOCKOUT_MINUTES * MINUTE_IN_SECONDS ) - $elapsed;
if( $remaining <= 0 ) {
$data['first_attempt'] = time();
$data['count'] = 1;
$remaining = self::LOCKOUT_MINUTES * MINUTE_IN_SECONDS;
}
set_transient( $key, $data, $remaining );
if( $data['count'] >= $this->get_max_attempts() && '' !== $this->client_ip_address ) {
$locked = self::get_locked_ips();
if( !isset( $locked[ $this->client_ip_address ] ) ) {
$locked[ $this->client_ip_address ] = time() + $remaining;
update_option( self::LOCKED_OPTION, array_slice( $locked, 0, 100, true ), false );
}
}
}
/**
* Clear failed attempts for the current IP on success.
*
* @return void
*/
private function clear_failed_attempts(): void {
delete_transient( $this->get_attempts_transient_key() );
}
/**
* Per-IP transient key used to track failed attempts.
*
* @return string
*/
private function get_attempts_transient_key(): string {
return self::attempts_transient_key( $this->client_ip_address );
}
/**
* Transient key that tracks the failed attempts of one IP address.
*
* @param string $ip IP address.
*
* @return string
*/
private static function attempts_transient_key( string $ip ): string {
return 'adminease_pps_attempts_' . hash( 'md5', $ip );
}
/**
* Append an authentication attempt to the access log option.
* Honors the configured retention setting and stores the option without autoload.
*
* @param string $status One of: 'success', 'failed', 'locked'.
* @param string $attempted_password Submitted password. Only its LENGTH is recorded - never the
* value and never a hash of it. An unsalted hash of every
* failed attempt is trivially reversible with a rainbow table,
* and visitors routinely try their other passwords on a gated
* site, which turned this log into a credential-harvesting
* target for anyone with manage_options or a database dump.
*
* @return void
*/
private function log_authentication_attempt( string $status, string $attempted_password = '' ): void {
$retention = isset( $this->settings['password_protect_site_log_retention'] )
? min( 10000, max( 0, (int) $this->settings['password_protect_site_log_retention'] ) )
: self::MAX_LOG_ENTRIES;
if( 0 === $retention ) {
return;
}
global $wpdb;
$country_code = Utils::get_client_country();
$country_name = '';
if( !empty( $country_code ) ) {
$countries = Utils::get_countries_iso();
$country_name = $countries[ $country_code ] ?? $country_code;
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Real-time attempt logging requires direct insert.
$wpdb->insert(
$this->table_name,
[
'timestamp' => current_time( 'mysql' ),
'ip_address' => $this->client_ip_address,
'country' => $country_name,
'status' => $status,
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
'password_length' => ( 'success' === $status ) ? 0 : strlen( $attempted_password ),
],
[ '%s', '%s', '%s', '%s', '%s', '%d' ]
);
$this->enforce_log_retention( $retention );
}
/**
* Trims the access log table down to the configured retention count by deleting
* the oldest rows once it is exceeded.
*
* @param int $retention Maximum number of entries to keep.
*
* @return void
*/
private function enforce_log_retention( int $retention ): void {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Count check for log maintenance, table name is safe.
$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" );
if( $count <= $retention ) {
return;
}
$delete_count = $count - $retention;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Log retention cleanup.
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$this->table_name} ORDER BY id ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$delete_count
)
);
}
/**
* Retrieves a page of access log entries from the database based on the provided filters.
*
* @param array $args Optional. Associative array of filter/pagination arguments:
* - per_page: int Number of records to fetch per page. Default 50.
* - page: int Current page number for pagination. Default 1.
* - status: string Filter by status (success/failed/locked). Default empty.
* - ip: string IP address or partial IP to filter by. Default empty.
* - country: string Country name or partial name to filter by. Default empty.
*
* @return array Array of log rows matching the provided filters and pagination options.
*/
public function get_logs( array $args = [] ): array {
global $wpdb;
$args = wp_parse_args( $args, [
'per_page' => 50,
'page' => 1,
'status' => '',
'ip' => '',
'country' => '',
] );
[ $where_clause, $where_values ] = $this->build_log_where_clause( $args );
$offset = ( max( 1, (int) $args['page'] ) - 1 ) * max( 1, (int) $args['per_page'] );
$where_values[] = max( 1, (int) $args['per_page'] );
$where_values[] = $offset;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Real-time log viewing on a custom table, so the result is deliberately uncached. $where_clause holds only hard-coded 'column = %s' / 'column LIKE %s' fragments from build_log_where_clause() and every user value is bound through the $where_values array handed to wpdb::prepare(). The table name is a class property built from $wpdb->prefix; the %i identifier placeholder needs WP 6.2+ while this plugin supports WP 5.3+.
$logs = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$this->table_name} {$where_clause} ORDER BY id DESC LIMIT %d OFFSET %d", $where_values ),
ARRAY_A
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter
return $logs;
}
/**
* Retrieves the total count of access log entries matching the provided filters.
*
* @param array $args Optional. Same filter keys as get_logs() (status, ip, country).
*
* @return int The total number of matching entries.
*/
public function get_logs_total_count( array $args = [] ): int {
global $wpdb;
[ $where_clause, $where_values ] = $this->build_log_where_clause( $args );
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Real-time pagination count on a custom table, so the result is deliberately uncached. $where_clause holds only hard-coded 'column = %s' / 'column LIKE %s' fragments from build_log_where_clause() and every user value is bound through the $where_values array handed to wpdb::prepare(). The table name is a class property built from $wpdb->prefix; the %i identifier placeholder needs WP 6.2+ while this plugin supports WP 5.3+.
if( empty( $where_values ) ) {
$total = $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" );
} else {
$total = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} {$where_clause}", $where_values ) );
}
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, PluginCheck.Security.DirectDB.UnescapedDBParameter
return (int) $total;
}
/**
* Builds a prepared WHERE clause shared by get_logs() and get_logs_total_count().
*
* @param array $args Filter arguments (status, ip, country).
*
* @return array Two-element array: [ string $where_clause, array $where_values ].
*/
private function build_log_where_clause( array $args ): array {
global $wpdb;
$where = [];
$where_values = [];
if( !empty( $args['status'] ) && in_array( $args['status'], [ 'success', 'failed', 'locked' ], true ) ) {
$where[] = 'status = %s';
$where_values[] = $args['status'];
}
if( !empty( $args['ip'] ) ) {
$where[] = 'ip_address LIKE %s';
$where_values[] = '%' . $wpdb->esc_like( $args['ip'] ) . '%';
}
if( !empty( $args['country'] ) ) {
$where[] = 'country LIKE %s';
$where_values[] = '%' . $wpdb->esc_like( $args['country'] ) . '%';
}
$where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : '';
return [ $where_clause, $where_values ];
}
/**
* Given a list of IP addresses (e.g. the ones present on the current log page), returns the
* subset that have MAX_FAILED_ATTEMPTS or more failed/locked entries in the log table - i.e.
* IPs that look like a brute-force run rather than a single mistyped password.
*
* @param array $ip_addresses IP addresses to check.
*
* @return array Flipped array (IP => true) for O(1) lookups by the caller.
*/
private function get_brute_force_ip_counts( array $ip_addresses ): array {
global $wpdb;
$ip_addresses = array_values( array_unique( array_filter( $ip_addresses ) ) );
if( empty( $ip_addresses ) ) {
return [];
}
$placeholders = implode( ', ', array_fill( 0, count( $ip_addresses ), '%s' ) );
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Real-time brute-force flagging on a custom table, so the result is deliberately uncached. $placeholders is generated by array_fill() as a list of %s tokens only and every IP is bound through wpdb::prepare(). The table name is a class property built from $wpdb->prefix; the %i identifier placeholder needs WP 6.2+ while this plugin supports WP 5.3+.
$flagged_ips = $wpdb->get_col(
$wpdb->prepare(
"SELECT ip_address FROM {$this->table_name}
WHERE status IN ( 'failed', 'locked' ) AND ip_address IN ( {$placeholders} )
GROUP BY ip_address
HAVING COUNT(*) >= %d",
array_merge( $ip_addresses, [ self::MAX_FAILED_ATTEMPTS ] )
)
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
return array_flip( $flagged_ips );
}
/**
* Check if current request is a REST API request.
*
* @return bool True if REST API request, false otherwise
*/
private function is_rest_api_request(): bool {
if( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return true;
}
if( isset( $_GET['rest_route'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return true;
}
if( isset( $_SERVER['REQUEST_URI'] ) ) {
$request_uri = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) );
$rest_prefix = function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : 'wp-json';
if( false !== strpos( $request_uri, '/' . $rest_prefix . '/' ) ) {
return true;
}
}
return false;
}
/**
* Whether the current page is in the admin-configured excluded list.
*
* @return bool True if the current page is excluded from password protection.
*/
private function is_page_excluded(): bool {
if( !empty( $this->settings['password_protect_site_bypass_archives'] ) ) {
if( is_archive() || is_home() || is_front_page() || is_search() || is_404() ) {
return true;
}
}
$excluded = $this->settings['password_protect_site_excluded_pages'] ?? [];
if( empty( $excluded ) ) {
return false;
}
if( is_array( $excluded ) ) {
if( !is_singular() ) {
return false;
}
$current_id = (string) get_queried_object_id();
return in_array( $current_id, $excluded, true );
}
$request_uri = isset( $_SERVER['REQUEST_URI'] )
? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) )
: '';
if( empty( $request_uri ) ) {
return false;
}
$current_path = wp_parse_url( $request_uri, PHP_URL_PATH );
if( false === $current_path || null === $current_path ) {
return false;
}
$home_path = wp_parse_url( home_url(), PHP_URL_PATH );
if( !empty( $home_path ) && 0 === strpos( $current_path, $home_path ) ) {
$current_path = substr( $current_path, strlen( $home_path ) );
}
$current_path = untrailingslashit( $current_path );
$excluded_lines = explode( "\n", $excluded );
foreach( $excluded_lines as $line ) {
$line = trim( $line );
if( empty( $line ) ) {
continue;
}
if( 0 === strpos( $line, 'http://' ) || 0 === strpos( $line, 'https://' ) ) {
$entry_path = wp_parse_url( $line, PHP_URL_PATH );
if( false === $entry_path || null === $entry_path ) {
continue;
}
} else {
$entry_path = $line;
}
if( !empty( $home_path ) && 0 === strpos( $entry_path, $home_path ) ) {
$entry_path = substr( $entry_path, strlen( $home_path ) );
}
$entry_path = untrailingslashit( $entry_path );
if( $current_path === $entry_path ) {
return true;
}
}
return false;
}
/**
* When an included-pages list is configured, returns true if the current page is NOT in it.
*
* @return bool True if this page should bypass protection because it is not in the included list.
*/
private function is_page_included_only(): bool {
$included = $this->settings['password_protect_site_included_pages'] ?? [];
if( empty( $included ) ) {
return false;
}
if( !is_singular() ) {
return true;
}
$current_id = (string) get_queried_object_id();
return !in_array( $current_id, $included, true );
}
/**
* Builds an optgroup-structured options array from an array of post IDs.
*
* @param array $post_ids Array of post ID strings.
*
* @return array Associative array keyed by post type label.
*/
private function get_selected_post_options( array $post_ids ): array {
$options = [];
foreach( $post_ids as $post_id ) {
$post = get_post( (int) $post_id );
if( !$post || 'publish' !== $post->post_status ) {
continue;
}
$type_obj = get_post_type_object( $post->post_type );
$group_label = $type_obj ? $type_obj->labels->name : $post->post_type;
$options[ $group_label ][ (string) $post->ID ] = $post->post_title;
}
return $options;
}
/**
* Handles AJAX requests for searching published posts across all public post types.
*
* @return void
*/
public function ajax_search_pages(): void {
check_ajax_referer( 'adminease_search_pages', 'security' );
if( !current_user_can( 'manage_options' ) ) {
wp_send_json_error( [] );
}
$search = sanitize_text_field( wp_unslash( $_POST['search'] ?? '' ) );
$post_types = get_post_types( [ 'public' => true ], 'objects' );
$results = [];
foreach( $post_types as $post_type ) {
$posts = get_posts( [
'post_type' => $post_type->name,
'post_status' => 'publish',
'posts_per_page' => 10,
's' => $search,
] );
foreach( $posts as $post ) {
$results[] = [
'value' => (string) $post->ID,
'label' => $post->post_title,
];
}
}
wp_send_json_success( $results );
}
/**
* Returns the locked addresses with the time left, for the Refresh button of the Locked Addresses table.
*
* @return void
*/
public function ajax_get_locked_ips(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_unlock_password_protection_ip' ) ) {
wp_send_json_error( new WP_Error( 'security_error', esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ) ) );
}
if( !current_user_can( 'manage_options' ) ) {
wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) );
}
$rows = [];
foreach( self::get_locked_ips() as $ip => $until ) {
$rows[] = [
'ip' => (string) $ip,
'label' => self::locked_label( $until ),
];
}
wp_send_json_success( [ 'locked' => $rows ] );
}
/**
* Text for the time left on a lock.
*
* @param int $until Locked-until timestamp.
*
* @return string
*/
public static function locked_label( int $until ): string {
/* translators: %s: time left, for example "12 minutes". */
return sprintf( __( 'Locked for %s more', 'adminease' ), human_time_diff( time(), $until ) );
}
/**
* Unlocks one locked address, or all of them.
*
* @return void
*/
public function ajax_unlock_ip(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_unlock_password_protection_ip' ) ) {
wp_send_json_error( new WP_Error( 'security_error', esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ) ) );
}
if( !current_user_can( 'manage_options' ) ) {
wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) );
}
$ip = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : '';
if( false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
wp_send_json_error( new WP_Error( 'not_locked', esc_html__( 'This address is not locked.', 'adminease' ) ) );
}
self::unlock_ip( $ip );
wp_send_json_success();
}
/**
* Localizes script data with security nonces and translatable strings.
*
* @param array $data Localization payload.
*
* @return array
*/
public function adminease_localize_script( array $data ): array {
$data['security']['refreshPasswordProtectionLog'] = wp_create_nonce( 'adminease_get_password_protection_log' );
$data['security']['downloadPasswordProtectionLog'] = wp_create_nonce( 'adminease_download_password_protection_log' );
$data['security']['searchPagesNonce'] = wp_create_nonce( 'adminease_search_pages' );
$data['security']['unlockPasswordProtectionIp'] = wp_create_nonce( 'adminease_unlock_password_protection_ip' );
$data['i18n']['passwordProtectionUnlock'] = __( 'Unlock', 'adminease' );
$data['i18n']['passwordProtectionLockedRefreshError'] = esc_html__( 'Could not refresh the locked addresses. Refresh the page and try again.', 'adminease' );
$data['i18n']['passwordProtectionUnlockError'] = esc_html__( 'Could not unlock the address. Refresh the page and try again.', 'adminease' );
$data['i18n']['passwordProtectionLogEmpty'] = esc_html__( 'No password protection attempts logged yet.', 'adminease' );
$data['i18n']['passwordProtectionLogRefreshError'] = esc_html__( 'Failed to get password protection log. Refresh the page and try again.', 'adminease' );
$data['i18n']['passwordProtectionLogDownloadFailed'] = esc_html__( 'Failed to download password protection log. Please try again.', 'adminease' );
$data['i18n']['passwordProtectionLogLoading'] = esc_html__( 'Loading...', 'adminease' );
$data['i18n']['passwordProtectionLogSuccess'] = esc_html__( 'Success', 'adminease' );
$data['i18n']['passwordProtectionLogFailed'] = esc_html__( 'Failed', 'adminease' );
$data['i18n']['passwordProtectionLogLocked'] = esc_html__( 'Locked', 'adminease' );
$data['i18n']['passwordProtectionLogBruteForce'] = esc_html__( '5+ failed attempts from this IP', 'adminease' );
/* translators: %s: number of characters in the attempted password. Filled in client-side by assets/js/AdminEase.js. */
$data['i18n']['passwordProtectionLogChars'] = esc_html__( '%s chars', 'adminease' );
/* translators: 1: number of entries shown, 2: maximum number of entries kept. Filled in client-side by assets/js/AdminEase.js. */
$data['i18n']['passwordProtectionLogCount'] = esc_html__( 'Showing %1$s of %2$s maximum entries (newest first)', 'adminease' );
/* translators: 1: current page number, 2: total number of pages. Filled in client-side by assets/js/AdminEase.js. */
$data['i18n']['passwordProtectionLogPageInfo'] = esc_html__( 'Page %1$s of %2$s', 'adminease' );
return $data;
}
/**
* Enqueues the admin-only stylesheet for the password protection access log
* (filter bar, brute-force row highlight, country flag sizing).
*
* @param string $hook The current admin page hook suffix.
*
* @return void
*/
public function admin_enqueue_scripts( string $hook ): void {
if( 'toplevel_page_adminease' !== $hook ) {
return;
}
wp_enqueue_style(
ADMINEASE_NAME . 'PasswordProtectionLog',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEasePasswordProtectionLog.css',
[ ADMINEASE_NAME ],
filemtime( ADMINEASE_DIR . 'assets/css/AdminEasePasswordProtectionLog.css' )
);
}
/**
* Prints the site password status script after the password field has been rendered.
*
* @param array $field Field info.
*
* @return void
*/
public function adminease_after_field_render( array $field ): void {
if( 'password-protect-site-password' === $field['id'] ) {
$this->render_password_status_script();
}
}
/**
* Renders the Locked Addresses and Access Log tables after the last setting of the group.
*
* @param array $child_field Field info of the child that was just rendered.
* @param array $field Field info of its parent.
*
* @return void
*/
public function adminease_after_child_field_render( array $child_field, array $field ): void {
$children = (array) ( $field['child_fields'] ?? [] );
$last = end( $children );
if( 'password-protect-site-enabled' !== $field['id'] || !is_array( $last ) || ( $last['id'] ?? '' ) !== $child_field['id'] ) {
return;
}
$settings = $this->settings;
include_once ADMINEASE_DIR . 'partials/password-protect-site-log.php';
}
/**
* Emit a one-time inline script that gives the admin immediate visual feedback after
* a successful settings save: if the user typed a non-empty password, swap the field's
* placeholder to masked dots and update the description to confirm a password is stored.
* Without this, the field renders blank with no acknowledgement that the save worked.
*
* @return void
*/
private function render_password_status_script(): void {
static $rendered = false;
if( true === $rendered ) {
return;
}
$rendered = true;
$saved_label = esc_js( __( '✓ A password is currently saved (stored hashed). The saved value is never displayed here for security.', 'adminease' ) );
$mask = '••••••••••••';
?>
$page,
'per_page' => $per_page,
'status' => $status,
'ip' => $ip,
'country' => $country,
];
$logs = $this->get_logs( $args );
$total = $this->get_logs_total_count( $args );
$brute_force_ips = $this->get_brute_force_ip_counts( wp_list_pluck( $logs, 'ip_address' ) );
foreach( $logs as &$log ) {
$log['country_code'] = Utils::get_country_code_by_name( $log['country'] ?? '' );
$log['is_brute_force_ip'] = isset( $brute_force_ips[ $log['ip_address'] ] );
}
unset( $log );
$retention = isset( $this->settings['password_protect_site_log_retention'] )
? min( 10000, max( 0, (int) $this->settings['password_protect_site_log_retention'] ) )
: self::MAX_LOG_ENTRIES;
wp_send_json_success( [
'logs' => $logs,
'total' => $total,
'page' => $page,
'per_page' => $per_page,
'log_limit' => $retention,
] );
}
/**
* Handles the AJAX request to download password protection log as CSV.
*
* @return void
*/
public function ajax_download_password_protection_log(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_download_password_protection_log' ) ) {
wp_die( esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ), '', [ 'response' => 403 ] );
}
if( !current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ), '', [ 'response' => 403 ] );
}
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe, full export respects the existing retention cap, no user input involved.
$logs = $wpdb->get_results( "SELECT * FROM {$this->table_name} ORDER BY id DESC", ARRAY_A );
$timezone = wp_timezone_string();
$csv_content = "\xEF\xBB\xBF";
$csv_content .= sprintf( "Timestamp (%s),IP Address,Country,Status,User Agent,Password Length\n", $timezone );
foreach( $logs as $log ) {
$csv_content .= sprintf(
'"%s","%s","%s","%s","%s","%s"' . "\n",
str_replace( '"', '""', (string) ( $log['timestamp'] ?? '' ) ),
str_replace( '"', '""', (string) ( $log['ip_address'] ?? '' ) ),
str_replace( '"', '""', (string) ( $log['country'] ?? '' ) ),
ucfirst( (string) ( $log['status'] ?? '' ) ),
str_replace( '"', '""', (string) ( $log['user_agent'] ?? '' ) ),
isset( $log['password_length'] ) ? (string) (int) $log['password_length'] : ''
);
}
header( 'Content-Type: text/csv; charset=UTF-8' );
header( 'Content-Disposition: attachment; filename="password-protection-access-log-' . gmdate( 'Y-m-d-His' ) . '.csv"' );
header( 'Content-Length: ' . strlen( $csv_content ) );
header( 'Cache-Control: no-cache, no-store, must-revalidate' );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
echo $csv_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
exit;
}
}