add_actions(); $this->add_filters(); } /** * Retrieve the singleton instance of the class. * * @return self The single instance of the class. */ public static function get_instance(): ?Plugin { if( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Handles the deactivation process of the plugin, which includes restoring files, * cleaning up markers, and optionally deleting backup files. * This method performs the following actions: * - Restores all files from backup. * - Cleans up any remaining markers left by the plugin. * - Deletes backup files if the operation is successful (optional step). * - Logs errors in case any process during deactivation fails. * * @return void */ /** * Registers WordPress actions for the admin interface. * * @return void */ private function add_actions(): void { add_action( 'admin_menu', [ $this, 'admin_menu' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'admin_init', [ $this, 'maybe_reapply_file_settings' ] ); add_action( 'wp_ajax_adminease_save_settings', [ $this, 'ajax_save_settings' ] ); add_action( 'wp_ajax_adminease_toggle_menu_sidebar', [ $this, 'ajax_toggle_menu_sidebar' ] ); add_action( 'wp_ajax_adminease_toggle_menu_sidebar_minmax', [ $this, 'ajax_toggle_menu_sidebar_minmax' ] ); add_action( 'wp_ajax_adminease_dismiss_notices', [ $this, 'ajax_dismiss_notices' ] ); add_action( 'wp_ajax_adminease_save_theme', [ $this, 'ajax_save_theme' ] ); add_filter( 'admin_body_class', [ $this, 'admin_body_class' ] ); } /** * Re-writes wp-config.php / .htaccess from the stored settings after activation. * * Deactivation strips AdminEase's marker blocks out of both files, so without * this the dashboard keeps reporting WP_DEBUG (and every other file-backed * feature) as enabled while wp-config.php no longer defines it. * * This runs on admin_init rather than in the activation hook because that is * the earliest point at which every Feature and the FileHandler commit handler * (priority 999 on adminease_settings_saved) are registered. * * The flag is cleared before the action fires: a fatal inside any listener must * not leave a retry queued on every subsequent admin page load. * * @return void */ public function maybe_reapply_file_settings(): void { if( !get_option( 'adminease_pending_reapply' ) ) { return; } delete_option( 'adminease_pending_reapply' ); if( empty( self::$settings ) ) { return; } do_action( 'adminease_settings_saved', self::$settings ); } /** * Adds custom filters for the plugin. * * @return void */ private function add_filters(): void { add_filter( 'adminease_dashboard_section_classes', [ $this, 'adminease_dashboard_section_classes' ] ); add_filter( 'plugin_action_links_' . ADMINEASE_BASENAME, [ $this, 'action_links' ] ); add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 4 ); add_filter( 'adminease_submenu_tabs', [ $this, 'adminease_submenu_tabs' ] ); } /** * Lists the License tab in the admin submenu whenever the dashboard shows that tab, with or without Pro. * * @param array $tabs Tab title keyed by tab id. * * @return array The tabs, with the License tab last. */ public function adminease_submenu_tabs( array $tabs ): array { $supported = !defined( 'ADMINEASE_PRO_VERSION' ) || has_filter( 'adminease_license_tab_content' ); if( $supported && apply_filters( 'adminease_show_license_tab', true ) ) { $tabs['license'] = __( 'License', 'adminease' ); } return $tabs; } /** * Adds the admin menu for the plugin. * * @return void */ public function admin_menu(): void { add_menu_page( ADMINEASE_NAME, ADMINEASE_NAME, 'manage_options', ADMINEASE_SLUG, function() { if( !current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'adminease' ) ); } include ADMINEASE_DIR . 'partials/dashboard.php'; }, ADMINEASE_PLUGIN_URL . 'assets/img/adminease-logo.png?ver=' . filemtime( ADMINEASE_DIR . 'assets/img/adminease-logo.png' ), 100 ); $tabs = [ 'dashboard' => __( 'Dashboard', 'adminease' ) ]; foreach( self::get_plugin_fields() as $key => $group ) { $tabs[ $key ] = $group['title']; } /** * Filters the dashboard tabs listed in the AdminEase admin submenu. * * @param array $tabs Tab title keyed by tab id, in the order of the tab bar. */ $tabs = apply_filters( 'adminease_submenu_tabs', $tabs ); foreach( $tabs as $key => $title ) { if( '' === sanitize_key( $key ) ) { continue; } add_submenu_page( ADMINEASE_SLUG, ADMINEASE_NAME, esc_html( wp_strip_all_tags( (string) $title ) ), 'manage_options', 'dashboard' === $key ? ADMINEASE_SLUG : 'admin.php?page=' . ADMINEASE_SLUG . '#tab-' . sanitize_key( $key ) ); } } /** * Enqueues scripts and styles for the admin dashboard. * This method handles the inclusion of CSS and JavaScript files required * for the plugin's functionality in the WordPress admin area. It ensures * assets are properly versioned using file modification times and adds * localized script data for client-side use. * * @param string $hook The current admin page hook suffix, used to conditionally load assets * specific to the plugin's pages or globally applicable assets. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { wp_register_script( ADMINEASE_NAME . 'ProgressBar', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseProgressBar.js', [ 'jquery' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseProgressBar.js' ), true ); wp_register_style( ADMINEASE_NAME . 'PrecisionWP', ADMINEASE_PLUGIN_URL . 'assets/css/PrecisionWP.css', [], filemtime( ADMINEASE_DIR . 'assets/css/PrecisionWP.css' ) ); wp_register_style( ADMINEASE_NAME . 'NativeBox', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseNativeBox.css', [], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseNativeBox.css' ) ); wp_enqueue_style( ADMINEASE_NAME . 'Global', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseGlobal.css', [], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseGlobal.css' ) ); $logo_url = ADMINEASE_PLUGIN_URL . 'assets/img/adminease-logo.png?ver=' . filemtime( ADMINEASE_DIR . 'assets/img/adminease-logo.png' ); wp_add_inline_style( ADMINEASE_NAME . 'Global', 'tr[data-slug="adminease"] .plugin-title strong::before, tr[data-slug="admineasepro"] .plugin-title strong::before, tr[data-slug="adminease-pro"] .plugin-title strong::before { background-image: url(' . esc_url( $logo_url ) . '); }' ); $additional_css = apply_filters( 'adminease_global_inline_css', '' ); if( !empty( $additional_css ) ) { $sanitized_css = wp_strip_all_tags( $additional_css ); $sanitized_css = preg_replace( '/javascript\s*:/i', '', $sanitized_css ); $sanitized_css = preg_replace( '/expression\s*\(/i', '', $sanitized_css ); $sanitized_css = preg_replace( '/@import\s+/i', '', $sanitized_css ); wp_add_inline_style( ADMINEASE_NAME . 'Global', $sanitized_css ); } if( 'toplevel_page_adminease' === $hook ) { wp_enqueue_style( ADMINEASE_NAME . 'Flexboxgrid', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseFlexboxgrid.min.css', [], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseFlexboxgrid.min.css' ) ); wp_enqueue_style( ADMINEASE_NAME . 'Choices', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseChoices.min.css', [], '11.1.0' ); wp_enqueue_style( ADMINEASE_NAME, ADMINEASE_PLUGIN_URL . 'assets/css/AdminEase.css', [ ADMINEASE_NAME . 'PrecisionWP' ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEase.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'Choices', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseChoices.min.js', [ 'jquery' ], '11.1.0', true ); wp_enqueue_script( ADMINEASE_NAME, ADMINEASE_PLUGIN_URL . 'assets/js/AdminEase.js', [ 'jquery', ADMINEASE_NAME . 'Choices' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEase.js' ), true ); wp_localize_script( ADMINEASE_NAME, ADMINEASE_NAME . 'AjaxObj', apply_filters( 'adminease_localize_script', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'isMobile' => wp_is_mobile(), 'theme' => self::get_admin_theme(), 'activationFields' => self::get_activation_fields_state(), 'security' => [ 'saveSettings' => wp_create_nonce( 'save_settings' ), 'toggleMenuSidebar' => wp_create_nonce( 'toggle_menu_sidebar' ), 'toggleMenuSidebarMinMax' => wp_create_nonce( 'toggle_menu_sidebar_minmax' ), 'saveTheme' => wp_create_nonce( 'save_theme' ), 'dismissNotices' => wp_create_nonce( 'dismiss_notices' ), ], 'i18n' => [ 'selectChoicesPlaceholder' => esc_html__( 'Select countries', 'adminease' ), 'selectChoicesLoadingText' => esc_html__( 'Loading...', 'adminease' ), 'selectChoicesNoResultsText' => esc_html__( 'No results found', 'adminease' ), 'selectChoicesNoChoicesText' => esc_html__( 'No choices to choose from', 'adminease' ), 'selectChoicesItemSelectText' => esc_html__( 'Press to select', 'adminease' ), 'selectChoicesUniqueItemText' => esc_html__( 'Only unique values can be added', 'adminease' ), 'selectChoicesCustomAddItemText' => esc_html__( 'Only values matching specific conditions can be added', 'adminease' ), 'selectChoicesRemoveItemText' => esc_html__( 'Remove item', 'adminease' ), /* translators: %s: the value of the item being removed. */ 'selectChoicesRemoveItemLabel' => esc_html__( 'Remove item: %s', 'adminease' ), 'unknownError' => esc_html__( 'An unknown error occurred. Refresh the page and try again.', 'adminease' ), 'saving' => esc_html__( 'Saving...', 'adminease' ), 'settingsSaved' => esc_html__( 'Settings saved', 'adminease' ), 'processing' => esc_html__( 'Processing...', 'adminease' ), 'complete' => esc_html__( 'Complete!', 'adminease' ), 'activationTitle' => esc_html__( 'Save and activate?', 'adminease' ), /* translators: %s: name of the feature that was just switched on. */ 'activationMessage' => esc_html__( '%s has to be saved before its tools can be used. Save your settings now and activate it?', 'adminease' ), 'activationMessageFallback' => esc_html__( 'This feature has to be saved before its tools can be used. Save your settings now and activate it?', 'adminease' ), 'activationSave' => esc_html__( 'Save & Activate', 'adminease' ), 'activationCancel' => esc_html__( 'Not now', 'adminease' ), 'activationClose' => esc_html__( 'Close', 'adminease' ), 'searchNoResults' => esc_html__( 'No settings found', 'adminease' ), /* translators: %d: number of settings found by the search box. */ 'searchResultsFound' => esc_html__( '%d settings found', 'adminease' ), ], ] ) ); } } /** * Handles saving settings via AJAX. * This method verifies the security nonce and user permissions, processes the provided data, * sanitizes the settings, and updates the options in the database. Responds with a JSON success or error message. * * @return void */ public function ajax_save_settings(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'save_settings' ) ) { wp_send_json_error( new WP_Error( 'security', esc_html__( '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' ) ) ); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Parsed values are sanitized by wp_recursive_sanitize() below. parse_str( wp_unslash( $_POST['data'] ), $parsed_data ); if( empty( $parsed_data['adminease'] ) ) { wp_send_json_error( new WP_Error( 'data', esc_html__( 'No data was provided', 'adminease' ) ) ); } $original_settings = self::$settings; $saved_settings = $this->write_settings( $parsed_data['adminease'], 'save' ); if( is_wp_error( $saved_settings ) ) { wp_send_json_error( $saved_settings ); } $reload = $this->save_settings_maybe_reload( $original_settings, $saved_settings ); wp_send_json_success( [ 'message' => esc_html__( 'Settings saved successfully', 'adminease' ), 'reload' => $reload ] ); } /** * Lists every registered field that stores a value, nested child fields included, * keyed by tab and setting key. * * @return array> Tab slug => setting key => field definition. */ private function get_registered_value_fields(): array { $registered = []; $pending = []; foreach( self::get_plugin_fields() as $tab ) { foreach( (array) ( $tab['fields'] ?? [] ) as $field ) { $pending[] = $field; } } while( !empty( $pending ) ) { $field = array_shift( $pending ); if( !is_array( $field ) ) { continue; } foreach( (array) ( $field['child_fields'] ?? [] ) as $child ) { $pending[] = $child; } if( !isset( $field['name'] ) || 1 !== preg_match( '/^adminease\[([^\]]+)\]\[([^\]]+)\](\[\])?$/', (string) $field['name'], $match ) ) { continue; } $registered[ $match[1] ][ $match[2] ] = $field; } return $registered; } /** * Checks one submitted value against the field that owns it. * * Every new settings field needs a rule here that fits its type. See "Adding a settings field" * in docs/ARCHITECTURE.md. * * @param array $field The registered field definition. * @param mixed $value The sanitized submitted value. * * @return string|null Error code ('invalid_switch', 'invalid_number' or 'invalid_value'), or null when the value is fine. */ private function check_field_value( array $field, $value ): ?string { $type = (string) ( $field['type'] ?? '' ); $is_multi = '[]' === substr( (string) $field['name'], -2 ); if( 'select' === $type && $is_multi ) { if( '' === $value ) { return null; } if( !is_array( $value ) ) { return 'invalid_value'; } foreach( $value as $item ) { if( !is_scalar( $item ) || !$this->is_allowed_option( $field, (string) $item ) ) { return 'invalid_value'; } } return null; } if( !is_scalar( $value ) ) { return 'switch' === $type ? 'invalid_switch' : 'invalid_value'; } $value = (string) $value; switch( $type ) { case 'switch': return in_array( $value, [ '', '0', '1' ], true ) ? null : 'invalid_switch'; case 'number': return ( '' === $value || is_numeric( $value ) ) ? null : 'invalid_number'; case 'select': return ( '' === $value || $this->is_allowed_option( $field, $value ) ) ? null : 'invalid_value'; } return null; } /** * Whether a value is one of the choices a select field offers. * Lists that are searched or grouped as the user types (pages, posts) cannot be known * in advance, so those are left to sanitizing alone. * * @param array $field The registered field definition. * @param string $value The submitted choice. * * @return bool */ private function is_allowed_option( array $field, string $value ): bool { $options = $field['options'] ?? null; if( !is_array( $options ) || empty( $options ) || !empty( $field['has_optgroups'] ) || isset( $field['attributes']['data-ajax-action'] ) ) { return true; } return in_array( $value, array_map( 'strval', array_keys( $options ) ), true ); } /** * Drops anything that is not a registered setting and refuses values that do not fit * their field: made-up switch text, non-numbers, choices that are not on offer, and * lists where a single value belongs. Those values end up in wp-config.php, .htaccess * and robots.txt, so they are refused rather than guessed at. * * @param array $settings Sanitized tab => fields array. * * @return array|WP_Error The settings without unknown keys, or the error for the first bad value. */ private function check_settings_against_fields( array $settings ) { $registered = $this->get_registered_value_fields(); $checked = []; foreach( $settings as $tab => $values ) { if( !isset( $registered[ $tab ] ) || !is_array( $values ) ) { continue; } foreach( $values as $key => $value ) { if( !isset( $registered[ $tab ][ $key ] ) ) { continue; } $field = $registered[ $tab ][ $key ]; $error = $this->check_field_value( $field, $value ); if( null !== $error ) { $label = wp_strip_all_tags( (string) ( $field['label'] ?? $key ) ); if( 'invalid_switch' === $error ) { /* translators: %s: name of the setting that received an unexpected value. */ return new WP_Error( $error, sprintf( __( 'The value for "%s" is not valid. This setting can only be on or off.', 'adminease' ), $label ) ); } if( 'invalid_number' === $error ) { /* translators: %s: name of the setting that received an unexpected value. */ return new WP_Error( $error, sprintf( __( 'The value for "%s" is not valid. It has to be a number.', 'adminease' ), $label ) ); } /* translators: %s: name of the setting that received an unexpected value. */ return new WP_Error( $error, sprintf( __( 'The value for "%s" is not valid. Choose one of the options offered.', 'adminease' ), $label ) ); } $checked[ $tab ][ $key ] = $value; } } return $checked; } /** * The one place settings are written. Save, import and any later restore, reset or * preset go through here so they behave exactly like the Save button: cleaned, * validated, stored, then announced so FileHandler rewrites the server files. * * Callers must be admin AJAX handlers that already checked a nonce and manage_options, * because some listeners of adminease_settings_saved only act inside such a request. * Pass a complete tab => fields array, with switches as '1' and never true. * * @param array $settings Complete tab => fields array. * @param string $context save, import, restore, reset or preset. Reaches the adminease_validate_settings filter. * * @return array|WP_Error The saved settings, or the validation error (nothing is stored then). */ public function write_settings( array $settings, string $context ) { $sanitized_settings = $this->wp_recursive_sanitize( $settings ); $sanitized_settings = $this->check_settings_against_fields( $sanitized_settings ); if( is_wp_error( $sanitized_settings ) ) { return $sanitized_settings; } $sanitized_settings = $this->validate_settings( $sanitized_settings, $context ); if( is_wp_error( $sanitized_settings ) ) { return $sanitized_settings; } update_option( 'adminease_settings', $sanitized_settings ); self::$settings = $sanitized_settings; do_action( 'adminease_settings_saved', $sanitized_settings ); return $sanitized_settings; } /** * Settings fields whose saved value decides whether a feature's scripts, styles * and AJAX handlers are registered at all on the next page load. * * Toggling one of these on in the UI reveals the feature's controls immediately, * but its assets are still absent until the option has been saved and the page * reloaded - which is why the dashboard offers to save and activate rather than * leaving the user clicking an inert button. * * @return array Settings section slug => list of field keys. */ public static function get_activation_fields(): array { return [ 'updates-and-notifications' => [ 'smtp_enabled', ], 'posts' => [ 'bulk_delete_posts_enabled', ], 'taxonomies' => [ 'taxonomy_switcher_enabled', 'bulk_delete_terms_enabled', ], 'debug' => [ 'network_viewer_enabled', 'enable_email_log', 'cron_viewer_log_enabled', 'http_request_log_enabled', ], 'plugins' => [ 'plugin_download_enabled', ], 'notes' => [ 'sticky_notes_enabled', ], ]; } /** * Builds the map the dashboard JavaScript uses to decide when to offer * "Save & Activate": the DOM id of every activation toggle, paired with whether * that feature is active in the settings that were used to render this page. * * @return array Field DOM id => currently saved as active. */ private static function get_activation_fields_state(): array { $state = []; foreach( self::get_activation_fields() as $section => $fields ) { foreach( $fields as $field ) { $state[ str_replace( '_', '-', $field ) ] = !empty( self::$settings[ $section ][ $field ] ); } } return $state; } private function save_settings_maybe_reload( array $original_settings, array $sanitized_settings ): bool { foreach( self::get_activation_fields() as $section => $fields ) { foreach( $fields as $field ) { if( ( $original_settings[ $section ][ $field ] ?? null ) !== ( $sanitized_settings[ $section ][ $field ] ?? null ) ) { return true; } } } return false; } /** * Handles the AJAX request to toggle the state of the menu sidebar. * This method validates the request for security, ensures the user has sufficient * permissions, and updates the user metadata to save the sidebar state. * * @return void This method does not return any value. Instead, it responds with * a JSON success or error message depending on the execution outcome. */ public function ajax_toggle_menu_sidebar(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'toggle_menu_sidebar' ) ) { wp_send_json_error( new WP_Error( 'security', esc_html__( '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' ) ) ); } $is_active = absint( sanitize_key( wp_unslash( $_POST['data']['isActive'] ?? 0 ) ) ); $user_id = get_current_user_id(); if( empty( $user_id ) ) { wp_send_json_error( new WP_Error( 'user', esc_html__( 'Unable to determine current user', 'adminease' ) ) ); } update_user_meta( $user_id, 'adminease_menu_sidebar_active', $is_active ); wp_send_json_success(); } /** * Handles AJAX requests to toggle the menu sidebar min/max state for a user. * This method verifies the request's security, checks user permissions, and updates * the user meta data to save the menu sidebar's minimized or maximized state. * * @return void Outputs a JSON response indicating success or failure. */ public function ajax_toggle_menu_sidebar_minmax(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'toggle_menu_sidebar_minmax' ) ) { wp_send_json_error( new WP_Error( 'security', esc_html__( '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' ) ) ); } $user_id = get_current_user_id(); if( empty( $user_id ) ) { wp_send_json_error( new WP_Error( 'user', esc_html__( 'Unable to determine current user', 'adminease' ) ) ); } $is_minmax_active = absint( sanitize_key( wp_unslash( $_POST['data']['isMinMaxActive'] ?? 0 ) ) ); update_user_meta( $user_id, 'adminease_menu_sidebar_minmax_active', $is_minmax_active ); wp_send_json_success(); } /** * Gets the Needs attention notices the current user has dismissed. * * @return string[] Notice ids, stored per user. */ public static function get_dismissed_notice_ids(): array { $ids = get_user_meta( get_current_user_id(), 'adminease_dismissed_notices', true ); return is_array( $ids ) ? array_values( array_filter( array_map( 'sanitize_key', $ids ) ) ) : []; } /** * Handles the AJAX request to dismiss a Needs attention notice, or bring all of them back. * Only info notices can be dismissed; warnings always stay visible. * * @return void */ public function ajax_dismiss_notices(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'dismiss_notices' ) ) { wp_send_json_error( new WP_Error( 'security', esc_html__( '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' ) ) ); } $user_id = get_current_user_id(); if( empty( $user_id ) ) { wp_send_json_error( new WP_Error( 'user', esc_html__( 'Unable to determine current user', 'adminease' ) ) ); } if( !empty( $_POST['restore'] ) ) { delete_user_meta( $user_id, 'adminease_dismissed_notices' ); wp_send_json_success(); } $id = sanitize_key( wp_unslash( $_POST['id'] ?? '' ) ); $dismissed = self::get_dismissed_notice_ids(); foreach( self::get_dashboard_notices() as $notice ) { if( $id === ( $notice['id'] ?? '' ) && 'warning' !== ( $notice['severity'] ?? '' ) ) { $dismissed[] = $id; } } update_user_meta( $user_id, 'adminease_dismissed_notices', array_values( array_unique( $dismissed ) ) ); wp_send_json_success(); } /** * Retrieves the current user's admin colour-scheme preference. * * @return string One of 'light' or 'dark'. Defaults to 'light' for new installs. */ public static function get_admin_theme(): string { $theme = get_user_meta( get_current_user_id(), 'adminease_admin_theme', true ); return in_array( $theme, [ 'light', 'dark' ], true ) ? $theme : 'light'; } /** * Mirrors an explicit theme preference onto the element so the wp-admin * content chrome behind the app (which sits above the data-theme'd wrapper in * the DOM) flips too. 'auto' adds no class - the JS resolves it client-side. * * @param string $classes Space-separated list of body class names. * * @return string Modified list of body class names. */ public function admin_body_class( string $classes ): string { $screen = get_current_screen(); if( $screen && 'toplevel_page_adminease' === $screen->id ) { $classes .= ' pwp-app'; $theme = self::get_admin_theme(); if( 'light' === $theme || 'dark' === $theme ) { $classes .= ' adminease-theme-' . $theme . ' pwp-theme-' . $theme; } } return $classes; } /** * Handles saving the admin colour-scheme preference via AJAX. * Verifies the security nonce and user permissions, validates the submitted * value against a whitelist, and persists it to user meta. * * @return void */ public function ajax_save_theme(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'save_theme' ) ) { wp_send_json_error( new WP_Error( 'security', esc_html__( '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' ) ) ); } $theme = isset( $_POST['theme'] ) ? sanitize_key( wp_unslash( $_POST['theme'] ) ) : ''; if( !in_array( $theme, [ 'light', 'dark', 'auto' ], true ) ) { wp_send_json_error( new WP_Error( 'theme', esc_html__( 'Invalid theme value', 'adminease' ) ) ); } update_user_meta( get_current_user_id(), 'adminease_admin_theme', $theme ); wp_send_json_success( [ 'theme' => $theme ] ); } /** * Retrieves the settings or a specific section of settings. * * @param string $section Optional. The section of settings to retrieve. Defaults to an empty string. * * @return mixed Returns the entire settings array if no section is specified, or the specific section of settings if provided. If the section does not exist, an empty array is returned. */ public static function get_settings( string $section = '' ) { if( !empty( $section ) ) { return self::$settings[ $section ] ?? []; } return self::$settings; } /** * Switches that safe mode may turn off. Anything that blocks, locks or protects is left out on purpose, * so a visitor can never get past a protection by someone else's cookie. * * @return array Tab => list of setting keys. */ private static function safe_mode_keys(): array { return [ 'performance' => [ 'disable_emojis', 'disable_front_password_meter', 'heartbeat_control_enabled', 'page_head_cleanup' ], 'posts' => [ 'close_comments', 'disable_comments_enabled', 'disable_feeds', 'unused_pages' ], 'security' => [ 'disable_embeds', 'disable_pingbacks', 'disable_self_pingbacks' ], 'media' => [ 'disable_big_image_threshold', 'disable_generated_image_sizes' ], 'users' => [ 'hide_admin_bar' ], ]; } /** * Builds the signed value of the safe mode cookie. * * @param int $expires Unix time the cookie stops working. * * @return string Empty when the site has no secret keys to sign with. */ public static function safe_mode_cookie_value( int $expires ): string { if( !defined( 'AUTH_KEY' ) || !defined( 'AUTH_SALT' ) || '' === AUTH_KEY . AUTH_SALT ) { return ''; } return $expires . '|' . hash_hmac( 'sha256', 'adminease_safe_mode|' . $expires, AUTH_KEY . AUTH_SALT ); } /** * Tells whether the browser carries a valid, unexpired safe mode cookie. * * @return bool */ public static function has_safe_mode_cookie(): bool { if( empty( $_COOKIE['adminease_safe_mode'] ) ) { return false; } $cookie = (string) wp_unslash( $_COOKIE['adminease_safe_mode'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Compared against a signed value below. $expires = (int) $cookie; if( $expires < time() ) { return false; } $expected = self::safe_mode_cookie_value( $expires ); return '' !== $expected && hash_equals( $expected, $cookie ); } /** * Tells whether this request runs in safe mode: a front end GET request with a valid cookie. * Stores nothing, and the saved settings are never touched. * * @return bool */ public static function is_safe_mode(): bool { return !is_admin() && 'GET' === ( $_SERVER['REQUEST_METHOD'] ?? '' ) && self::has_safe_mode_cookie(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Only compared with a fixed string. } /** * Removes the safe mode switches from an in-memory copy of the settings. * * @param mixed $settings The loaded settings. * * @return mixed */ private static function without_safe_mode_keys( $settings ) { if( !is_array( $settings ) ) { return $settings; } foreach( self::safe_mode_keys() as $tab => $keys ) { if( isset( $settings[ $tab ] ) && is_array( $settings[ $tab ] ) ) { $settings[ $tab ] = array_diff_key( $settings[ $tab ], array_flip( $keys ) ); } } return $settings; } /** * Recursively sanitize all types of values. * * @param mixed $value The value to sanitize. * * @return mixed The sanitized value. */ public function wp_recursive_sanitize( $value, array $context = [] ) { if( is_array( $value ) ) { foreach( $value as $key => $item ) { $new_context = array_merge( $context, [ $key ] ); $value[ $key ] = $this->wp_recursive_sanitize( $item, $new_context ); } return $value; } else if( is_bool( $value ) ) { return (bool) $value; } else if( is_int( $value ) ) { return intval( $value ); } else if( is_float( $value ) ) { return floatval( $value ); } else if( is_string( $value ) ) { if( $this->should_allow_html( $context ) ) { $allowed_tags = [ 'br' => [], 'b' => [], 'strong' => [], 'em' => [], 'i' => [], 'u' => [], 'p' => [], 'span' => [ 'class' => [] ], 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ], ]; return wp_kses( $value, $allowed_tags ); } if( $this->should_sanitize_textarea( $context ) ) { return sanitize_textarea_field( $value ); } if( $this->should_sanitize_credential( $context ) ) { return $this->sanitize_credential( $value ); } return sanitize_text_field( $value ); } else { return $value; } } /** * Determines if a field should allow HTML based on its context path. * * @param array $context The field path (e.g., ['debug', 'maintenance_mode_message']). * * @return bool True if HTML should be allowed, false otherwise. */ private function should_allow_html( array $context ): bool { $html_fields = [ 'maintenance_mode_message', 'password_protect_site_entry_message', ]; if( !empty( array_intersect( $html_fields, $context ) ) ) { return true; } return false; } /** * Determines if a field should use sanitize_textarea_field() to preserve newlines. * * @param array $context The field path (e.g., ['security', 'password_protect_site_excluded_pages']). * * @return bool True if the field should use sanitize_textarea_field(). */ private function should_sanitize_textarea( array $context ): bool { $textarea_fields = [ 'password_protect_site_whitelisted_ips', 'block_specific_countries_excluded_paths', 'crawl_delay_overrides', 'maintenance_mode_ip_allowlist', ]; if( !empty( array_intersect( $textarea_fields, $context ) ) ) { return true; } return false; } /** * Determines if a field holds a credential that must survive byte for byte. * * sanitize_text_field() runs the value through wp_strip_all_tags(), so a password * containing a "<" is silently truncated at that character. A password only has to * match what a remote server expects, so mangling it produces an authentication * failure with nothing on screen to explain it. * * @param array $context The field path (e.g., ['updates-and-notifications', 'smtp_password']). * * @return bool True if the field should be treated as a credential. */ private function should_sanitize_credential( array $context ): bool { $credential_fields = [ 'smtp_password', ]; if( !empty( array_intersect( $credential_fields, $context ) ) ) { return true; } return false; } /** * Sanitizes a credential without altering the characters that make it up. * * Control characters are removed because they cannot appear in a real password and * would allow header injection further down, and the length is capped so an * oversized submission cannot be used to bloat the settings option. * * @param string $value The raw submitted value. * * @return string The credential with control characters removed. */ private function sanitize_credential( string $value ): string { $value = (string) preg_replace( '/[\x00-\x1F\x7F]/', '', $value ); return function_exists( 'mb_substr' ) ? mb_substr( $value, 0, 255 ) : substr( $value, 0, 255 ); } /** * Validates and ensures the settings provided are consistent and adhere to predefined rules. * * @param array $sanitized_settings An array of sanitized settings, including memory limit configurations. * @param string $context Why the settings are being written: save, import, restore, reset or preset. Passed to the adminease_validate_settings filter. * * @return array|WP_Error Returns the sanitized settings if validation passes. Returns a WP_Error object if there is a validation error. */ public function validate_settings( array $sanitized_settings, string $context = 'save' ) { foreach( $sanitized_settings as $key => $fields ) { switch( $key ) { case 'updates-and-notifications': { $customize_recovery_mode_recipient_email = $fields['customize_recovery_mode_recipient_email'] ?? ''; if( !empty( $customize_recovery_mode_recipient_email ) ) { $recovery_mode_recipient_email = $fields['recovery_mode_recipient_email'] ?? ''; if( false !== strpos( $recovery_mode_recipient_email, ',' ) ) { $recovery_mode_recipient_email = array_map( 'trim', explode( ',', $recovery_mode_recipient_email ) ); } if( is_array( $recovery_mode_recipient_email ) ) { foreach( $recovery_mode_recipient_email as $email ) { if( !is_email( $email ) ) { return new WP_Error( 'recovery_mode_recipient_email', esc_html__( 'Please enter valid email addresses for recovery mode notifications.', 'adminease' ) ); } } } else { if( !is_email( $recovery_mode_recipient_email ) ) { return new WP_Error( 'recovery_mode_recipient_email', esc_html__( 'Please enter a valid email address for recovery mode notifications.', 'adminease' ) ); } } } $smtp_enabled = $fields['smtp_enabled'] ?? ''; if( !empty( $smtp_enabled ) ) { $smtp_port = trim( (string) ( $fields['smtp_port'] ?? '' ) ); if( '' !== $smtp_port && ( 1 > (int) $smtp_port || 65535 < (int) $smtp_port ) ) { return new WP_Error( 'smtp_port', esc_html__( 'Please enter a valid SMTP port, usually 587 for TLS or 465 for SSL.', 'adminease' ) ); } $smtp_from_email = trim( (string) ( $fields['smtp_from_email'] ?? '' ) ); if( '' !== $smtp_from_email && !is_email( $smtp_from_email ) ) { return new WP_Error( 'smtp_from_email', esc_html__( 'Please enter a valid From address for outgoing email.', 'adminease' ) ); } $smtp_test_recipient = trim( (string) ( $fields['smtp_test_recipient'] ?? '' ) ); if( '' !== $smtp_test_recipient && !is_email( $smtp_test_recipient ) ) { return new WP_Error( 'smtp_test_recipient', esc_html__( 'Please enter a valid email address to send the SMTP test to.', 'adminease' ) ); } } break; } case 'performance': { $wp_memory_limit = $fields['wp_memory_limit'] ?? ''; $wp_memory_limit_other = $fields['wp_memory_limit_other'] ?? ''; $wp_max_memory_limit = $fields['wp_max_memory_limit'] ?? ''; $wp_max_memory_limit_other = $fields['wp_max_memory_limit_other'] ?? ''; $max_execution_time = $fields['max_execution_time'] ?? ''; if( 'other' === $wp_memory_limit && '' === $wp_memory_limit_other ) { return new WP_Error( 'wp_memory_limit_other', esc_html__( 'Memory limit cannot be empty', 'adminease' ) ); } if( 'other' === $wp_max_memory_limit && '' === $wp_max_memory_limit_other ) { return new WP_Error( 'wp_max_memory_limit_other', esc_html__( 'Maximum memory limit cannot be empty', 'adminease' ) ); } $memory_limit_raw = ( 'other' === $wp_memory_limit ) ? $wp_memory_limit_other : $wp_memory_limit; $max_memory_limit_raw = ( 'other' === $wp_max_memory_limit ) ? $wp_max_memory_limit_other : $wp_max_memory_limit; $memory_limit = Utils::parse_memory_limit( $memory_limit_raw ); $max_memory_limit = Utils::parse_memory_limit( $max_memory_limit_raw ); if( $max_memory_limit < $memory_limit && 0 !== $max_memory_limit ) { return new WP_Error( 'wp_max_memory_limit', esc_html__( 'Maximum memory limit cannot be smaller than memory limit', 'adminease' ) ); } if( '' !== $max_execution_time ) { if( !is_numeric( $max_execution_time ) ) { return new WP_Error( 'max_execution_time', esc_html__( 'Max execution time must be a whole number of seconds.', 'adminease' ) ); } $max_execution_time = (int) $max_execution_time; if( MaxExecutionTime::MIN_SECONDS > $max_execution_time || MaxExecutionTime::MAX_SECONDS < $max_execution_time ) { return new WP_Error( 'max_execution_time', sprintf( /* translators: 1: lowest accepted value, 2: highest accepted value. */ esc_html__( 'Max execution time must be between %1$d and %2$d seconds. Leave it empty to let the server decide.', 'adminease' ), MaxExecutionTime::MIN_SECONDS, MaxExecutionTime::MAX_SECONDS ) ); } } break; } case 'posts': { $number_posts_revisions = $fields['number_posts_revisions'] ?? ''; $number_posts_revisions_other = $fields['number_posts_revisions_other'] ?? ''; if( 'other' === $number_posts_revisions && '' === $number_posts_revisions_other ) { return new WP_Error( 'number_posts_revisions_other', esc_html__( 'Number of revisions cannot be empty', 'adminease' ) ); } break; } case 'users': { if( !empty( $sanitized_settings['users']['force_strong_passwords'] ) && ( empty( $sanitized_settings['users']['password_minimum_length'] ) || $sanitized_settings['users']['password_minimum_length'] < 8 ) ) { return new WP_Error( 'password_minimum_length', esc_html__( 'Password minimum length must be larger than 8 characters.', 'adminease' ) ); } if( !empty( $sanitized_settings['users']['force_strong_passwords'] ) && ( empty( $sanitized_settings['users']['password_maximum_length'] ) || $sanitized_settings['users']['password_maximum_length'] > 64 ) ) { return new WP_Error( 'password_maximum_length', esc_html__( 'Password maximum length must be smaller than 64 characters.', 'adminease' ) ); } if( !empty( $sanitized_settings['users']['auto_logout_user'] ) && empty( $sanitized_settings['users']['auto_logout_user_time'] ) ) { return new WP_Error( 'auto_logout_user_time', esc_html__( 'Auto-logout user after X seconds cannot be empty', 'adminease' ) ); } break; } case 'security': { if( !empty( $sanitized_settings['security']['password_protect_site_enabled'] ) && empty( $sanitized_settings['security']['password_protect_site_password'] ) && empty( self::$settings['security']['password_protect_site_password'] ?? '' ) ) { return new WP_Error( 'password_protect_site_password', esc_html__( 'Site password cannot be empty', 'adminease' ) ); } if( !empty( $sanitized_settings['security']['network_viewer_max_entries'] ) && $sanitized_settings['security']['network_viewer_max_entries'] > 100000 ) { return new WP_Error( 'network_viewer_max_entries', esc_html__( 'Max log entries must be less than or equal to 100000', 'adminease' ) ); } break; } case 'debug': { if( !empty( $sanitized_settings['debug']['cron_viewer_log_max_entries'] ) && $sanitized_settings['debug']['cron_viewer_log_max_entries'] > 100000 ) { return new WP_Error( 'cron_viewer_log_max_entries', esc_html__( 'Max cron log entries must be less than or equal to 100000', 'adminease' ) ); } if( !empty( $sanitized_settings['debug']['maintenance_mode_schedule_enabled'] ) ) { $schedule_start = $sanitized_settings['debug']['maintenance_mode_schedule_start'] ?? ''; $schedule_end = $sanitized_settings['debug']['maintenance_mode_schedule_end'] ?? ''; if( empty( $schedule_start ) || empty( $schedule_end ) ) { return new WP_Error( 'maintenance_mode_schedule_end', esc_html__( 'Please set both a schedule start and end date/time, or disable the scheduled window.', 'adminease' ) ); } if( strtotime( $schedule_end ) <= strtotime( $schedule_start ) ) { return new WP_Error( 'maintenance_mode_schedule_end', esc_html__( 'Schedule end must be after the schedule start.', 'adminease' ) ); } } break; } } } return apply_filters( 'adminease_validate_settings', $sanitized_settings, $context ); } /** * Appends additional CSS classes to the dashboard section based on user preferences. * This method checks the current user's metadata to determine whether specific * UI features, such as a sidebar, should be active, and adjusts the provided * classes accordingly. * * @param array $classes An array of existing CSS classes for the dashboard section. * * @return array The modified array of CSS classes, potentially including additional * classes based on the current user's settings. */ public function adminease_dashboard_section_classes( array $classes ): array { $user_id = get_current_user_id(); if( empty( $user_id ) ) { return $classes; } if( get_user_meta( $user_id, 'adminease_menu_sidebar_active', true ) ) { $classes[] = 'has-sidebar'; } if( get_user_meta( $user_id, 'adminease_menu_sidebar_minmax_active', true ) ) { $classes[] = 'minmax-sidebar'; } return $classes; } /** * Add a settings link to plugin action links. * * @param array $links Existing plugin action links. * * @return array Modified plugin action links. */ public function action_links( $links ): array { $link = '' . esc_html__( 'Settings', 'adminease' ) . ''; return array_merge( [ $link ], $links ); } /** * The AdminEase Pro features listed on the dashboard, grouped by area. * * Each entry is something Pro adds on top of the free plugin. Keep it in step with the * AdminEase Pro readme: when a feature moves into the free plugin, or Pro gains a new one, * this list is the only place the dashboard card needs to change. * * @return array}> */ public static function get_pro_features(): array { $features = [ [ 'label' => __( 'Updates and Notifications', 'adminease' ), 'icon' => 'refresh-cw', 'features' => [ [ 'icon' => 'eye-off', 'name' => __( 'Disable Admin Notices', 'adminease' ), 'desc' => __( 'Hide notices for chosen roles or users', 'adminease' ) ], ], ], [ 'label' => __( 'Security', 'adminease' ), 'icon' => 'lock', 'features' => [ [ 'icon' => 'globe', 'name' => __( 'Block Specific Countries', 'adminease' ), 'desc' => __( 'IP & Bot whitelist control', 'adminease' ) ], [ 'icon' => 'network', 'name' => __( 'Disable XML-RPC', 'adminease' ), 'desc' => __( 'IP allowlist support', 'adminease' ) ], [ 'icon' => 'network', 'name' => __( 'Disable REST API', 'adminease' ), 'desc' => __( 'IP allowlist and routes that stay open', 'adminease' ) ], [ 'icon' => 'key', 'name' => __( 'Password Protect Site', 'adminease' ), 'desc' => __( 'Role/IP bypass & device remember', 'adminease' ) ], ], ], [ 'label' => __( 'Posts', 'adminease' ), 'icon' => 'file-text', 'features' => [ [ 'icon' => 'pencil', 'name' => __( 'Disable Gutenberg', 'adminease' ), 'desc' => __( 'Per post-type control', 'adminease' ) ], [ 'icon' => 'grip-vertical', 'name' => __( 'Drag & Drop Posts', 'adminease' ), 'desc' => __( 'Per post-type control', 'adminease' ) ], [ 'icon' => 'archive', 'name' => __( 'Bulk Delete Posts', 'adminease' ), 'desc' => __( 'Any post type & status', 'adminease' ) ], [ 'icon' => 'list', 'name' => __( 'Posts Metadata Box', 'adminease' ), 'desc' => __( 'Choose which post types get it', 'adminease' ) ], ], ], [ 'label' => __( 'Taxonomies', 'adminease' ), 'icon' => 'table', 'features' => [ [ 'icon' => 'grip-vertical', 'name' => __( 'Drag & Drop Taxonomies', 'adminease' ), 'desc' => __( 'Per taxonomy control', 'adminease' ) ], [ 'icon' => 'filter', 'name' => __( 'Improved Taxonomy Meta Box', 'adminease' ), 'desc' => __( 'Lazy loading for terms', 'adminease' ) ], [ 'icon' => 'archive', 'name' => __( 'Bulk Delete Terms', 'adminease' ), 'desc' => __( 'Any registered taxonomy', 'adminease' ) ], [ 'icon' => 'list', 'name' => __( 'Taxonomy Term Metadata Box', 'adminease' ), 'desc' => __( 'Choose which taxonomies get it', 'adminease' ) ], ], ], [ 'label' => __( 'Users', 'adminease' ), 'icon' => 'users', 'features' => [ [ 'icon' => 'clock', 'name' => __( 'Auto-Logout Users', 'adminease' ), 'desc' => __( 'Per-role with custom timeout', 'adminease' ) ], [ 'icon' => 'file-text', 'name' => __( 'Audit Log', 'adminease' ), 'desc' => __( 'CSV export and WooCommerce events', 'adminease' ) ], ], ], [ 'label' => __( 'Debug', 'adminease' ), 'icon' => 'code', 'features' => [ [ 'icon' => 'network', 'name' => __( 'Network Viewer', 'adminease' ), 'desc' => __( 'Analytics, IP charts & CSV export', 'adminease' ) ], [ 'icon' => 'wrench', 'name' => __( 'Maintenance Mode Terminal Theme', 'adminease' ), 'desc' => __( 'Dark console-style page', 'adminease' ) ], ], ], [ 'label' => __( 'Notes', 'adminease' ), 'icon' => 'pencil', 'features' => [ [ 'icon' => 'users', 'name' => __( 'Shared Sticky Notes', 'adminease' ), 'desc' => __( 'Share, assign, due dates & checklists', 'adminease' ) ], ], ], ]; return apply_filters( 'adminease_pro_features', $features ); } /** * Counts, for every settings tab, how many of its on/off switches are turned on. * * Only top-level switches are counted. Child switches belong to a parent that is already * counted, so including them would make one feature count several times. * * @return array One entry per tab that has switches. */ public static function get_dashboard_summary(): array { $summary = []; foreach( self::get_plugin_fields() as $key => $group ) { $on = 0; $total = 0; foreach( ( $group['fields'] ?? [] ) as $field ) { if( 'switch' !== ( $field['type'] ?? '' ) ) { continue; } ++$total; $value = $field['value'] ?? 0; if( is_scalar( $value ) && (int) $value > 0 ) { ++$on; } } if( $total > 0 ) { $summary[] = [ 'key' => (string) $key, 'title' => (string) ( $group['title'] ?? $key ), 'icon' => (string) ( $group['icon'] ?? '' ), 'on' => $on, 'total' => $total, ]; } } return $summary; } /** * Things on this site the user may want to look at, shown on the dashboard. * * Every check reads a saved option or a server constant. Nothing here may make a remote * call or run a query, because this runs on every dashboard load. * * Features can add their own through the adminease_dashboard_notices filter. An entry is * ['id' => string, 'severity' => 'warning'|'info', 'message' => string, 'field' => string], * where 'field' is the DOM id of the setting to jump to (the dashboard opens its tab). * * @return array */ public static function get_dashboard_notices(): array { $notices = []; $security = self::get_settings( 'security' ); $debug = self::get_settings( 'debug' ); if( !empty( $debug['wp_debug_display'] ) ) { $notices[] = [ 'id' => 'wp-debug-display', 'severity' => 'warning', 'message' => __( 'PHP errors are being shown on your site to every visitor. Turn this off once you have finished debugging.', 'adminease' ), 'field' => 'wp-debug-display', ]; } if( !empty( $debug['maintenance_mode_enabled'] ) ) { $notices[] = [ 'id' => 'maintenance-mode', 'severity' => 'info', 'message' => __( 'Maintenance Mode is on. Visitors who are not logged in see the maintenance page.', 'adminease' ), 'field' => 'maintenance-mode-enabled', ]; } if( !empty( $security['password_protect_site_enabled'] ) ) { $notices[] = [ 'id' => 'password-protect-site', 'severity' => 'info', 'message' => __( 'Password Protect Site is on. Visitors need the password to see your site.', 'adminease' ), 'field' => 'password-protect-site-enabled', ]; } if( !empty( $security['block_specific_countries_enabled'] ) && !Utils::is_cloudflare_enabled() && !Utils::is_geoip_enabled() ) { $notices[] = [ 'id' => 'countries-unsupported', 'severity' => 'warning', 'message' => __( 'Block Specific Countries is on, but your server cannot tell where visitors are from, so nothing is being blocked. It needs Cloudflare in front of your site or the GeoIP module on the server.', 'adminease' ), 'field' => 'block-specific-countries-enabled', ]; } if( !empty( $security['disallow_file_mods'] ) ) { $notices[] = [ 'id' => 'disallow-file-mods', 'severity' => 'warning', 'message' => __( 'Automatic updates are off, including security updates, because AdminEase blocks file changes. Installing and updating plugins and themes from the dashboard is switched off too.', 'adminease' ), 'field' => 'disallow-file-mods', ]; } $uses_htaccess_rules = !empty( $security['disable_xmlrpc'] ) || !empty( $security['block_specific_bots_enabled'] ) || !empty( $security['block_specific_countries_enabled'] ); if( $uses_htaccess_rules && !Utils::is_apache_compatible() ) { $notices[] = [ 'id' => 'php-enforcement', 'severity' => 'info', 'message' => __( 'Your server does not read .htaccess files, so AdminEase enforces XML-RPC, bot and country blocking in PHP instead. Nothing needs to be set up on the server.', 'adminease' ), 'field' => '', ]; } /** * Filters the notices listed on the AdminEase dashboard. * * @param array $notices Notices, each ['id', 'severity', 'message', 'field']. */ $notices = apply_filters( 'adminease_dashboard_notices', $notices ); return is_array( $notices ) ? array_values( $notices ) : []; } /** * Retrieves an array of plugin fields based on the provided settings key. * This method defines various configurable fields for managing * updates, security, and other aspects of the plugin. Each field contains * information about its type, ID, name, value, and other relevant attributes. * * @param string $key Optional. The specific key within the settings array to retrieve. * Defaults to an empty string, which returns all fields. * * @return array An array of fields grouped into categories, * where each category contains its title and a list of field definitions. */ public static function get_plugin_fields( string $key = '' ): array { $svg_open = ''; $fields = [ 'updates-and-notifications' => [ 'title' => __( 'Updates and Notifications', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'email' => [ 'title' => __( 'Email', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'security' => [ 'title' => __( 'Security', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'performance' => [ 'title' => __( 'Performance', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'posts' => [ 'title' => __( 'Posts', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'taxonomies' => [ 'title' => __( 'Taxonomies', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'users' => [ 'title' => __( 'Users', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'debug' => [ 'title' => __( 'Debug', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'media' => [ 'title' => __( 'Media', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'plugins' => [ 'title' => __( 'Plugins', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], 'notes' => [ 'title' => __( 'Notes', 'adminease' ), 'icon' => $svg_open . '' . $svg_close, 'fields' => [], ], ]; $fields = apply_filters( 'adminease_settings_fields', $fields ); return $fields[ $key ] ?? $fields; } /** * Retrieve sub-section (sidebar) groupings for each tab. * * Each sub-section has a title, an inline Lucide SVG icon, and a list of * field IDs that belong to it. Tabs not represented here render as a single * column without a sidebar; field IDs not matched in any sub-section fall * through to a "_general" bucket inside their tab. * * @param string $tab Optional tab key to retrieve a single tab's mapping. * * @return array */ public static function get_plugin_subgroups( string $tab = '' ): array { $svg_open = ''; $icons = [ 'refresh' => $svg_open . '' . $svg_close, 'bell' => $svg_open . '' . $svg_close, 'shield' => $svg_open . '' . $svg_close, 'lock' => $svg_open . '' . $svg_close, 'key' => $svg_open . '' . $svg_close, 'gauge' => $svg_open . '' . $svg_close, 'trash' => $svg_open . '' . $svg_close, 'edit' => $svg_open . '' . $svg_close, 'list' => $svg_open . '' . $svg_close, 'database' => $svg_open . '' . $svg_close, 'wrench' => $svg_open . '' . $svg_close, 'login' => $svg_open . '' . $svg_close, 'activity' => $svg_open . '' . $svg_close, 'terminal' => $svg_open . '' . $svg_close, 'alert-triangle' => $svg_open . '' . $svg_close, 'mail' => $svg_open . '' . $svg_close, 'clock' => $svg_open . '' . $svg_close, 'upload' => $svg_open . '' . $svg_close, 'file' => $svg_open . '' . $svg_close, 'eye' => $svg_open . '' . $svg_close, 'comments' => $svg_open . '' . $svg_close, 'feed' => $svg_open . '' . $svg_close, ]; $subgroups = [ 'updates-and-notifications' => [ 'updates' => [ 'title' => __( 'Updates', 'adminease' ), 'icon' => $icons['refresh'], 'field_ids' => [ 'disable-auto-update-core', 'core-auto-update-mode', 'disable-auto-update-plugin', 'disable-auto-update-theme', 'disable-auto-update-translation' ] ], 'notifications' => [ 'title' => __( 'Notifications', 'adminease' ), 'icon' => $icons['bell'], 'field_ids' => [ 'customize-recovery-mode-recipient-email', 'recovery-mode-recipient-email', 'disable-recovery-mode-email-notification', 'disable-auto-core-update-send-email', 'disable-auto-plugin-update-send-email', 'disable-auto-theme-update-send-email', 'disable-comment-admin-notification-email', 'disable-comment-post-author-notification-email', 'disable-new-user-admin-notification-email', 'disable-user-password-change-admin-notification-email', 'disable-admin-notices-enabled' ] ], ], 'email' => [ 'delivery' => [ 'title' => __( 'Delivery', 'adminease' ), 'icon' => $icons['mail'], 'field_ids' => [ 'smtp-enabled', 'smtp-host', 'smtp-encryption', 'smtp-port', 'smtp-auth', 'smtp-username', 'smtp-password', 'smtp-from-email', 'smtp-force-from-email', 'smtp-from-name', 'smtp-force-from-name', 'smtp-test-recipient', 'smtp-test-submit' ] ], 'alerts' => [ 'title' => __( 'Alerts', 'adminease' ), 'icon' => $icons['bell'], 'field_ids' => [ 'email-failure-alert-enabled' ] ], ], 'security' => [ 'hardening' => [ 'title' => __( 'Hardening', 'adminease' ), 'icon' => $icons['shield'], 'field_ids' => [ 'hide-php-version', 'hide-wordpress-version', 'disable-file-edit', 'disallow-file-mods', 'disable-xmlrpc', 'disable-rest-api', 'enable-rest-api-loggedin', 'hide-rest-index', 'disable-script-concatenation', 'disable-embeds', 'disable-pingbacks', 'disable-self-pingbacks', 'cors-header' ] ], 'access-control' => [ 'title' => __( 'Access Control', 'adminease' ), 'icon' => $icons['lock'], 'field_ids' => [ 'block-author-scans', 'block-access-sensitive-files', 'block-directory-browsing', 'block-specific-bots', 'block-specific-bots-custom', 'block-specific-bots-enabled', 'block-specific-countries', 'block-specific-countries-enabled', 'crawl-delay-enabled', 'crawl-delay-bots', 'crawl-delay-seconds', 'crawl-delay-overrides', 'crawl-delay-default', 'crawl-delay-enforce' ] ], 'site-lock' => [ 'title' => __( 'Site Lock', 'adminease' ), 'icon' => $icons['key'], 'field_ids' => [ 'password-protect-site-enabled', 'password-protect-site-show-logo', 'password-protect-site-auto-load-log', 'password-protect-site-password', 'password-protect-site-page-title', 'password-protect-site-headline', 'password-protect-site-entry-message', 'password-protect-site-primary-color', 'password-protect-site-secondary-color', 'password-protect-site-text-color', 'password-protect-site-excluded-pages', 'password-protect-site-included-pages' ] ], ], 'performance' => [ 'system-limits' => [ 'title' => __( 'System Limits', 'adminease' ), 'icon' => $icons['gauge'], 'field_ids' => [ 'wp-memory-limit', 'wp-memory-limit-other', 'wp-max-memory-limit', 'wp-max-memory-limit-other', 'max-execution-time' ] ], 'background' => [ 'title' => __( 'Background Activity', 'adminease' ), 'icon' => $icons['activity'], 'field_ids' => [ 'heartbeat-control-enabled', 'heartbeat-dashboard', 'heartbeat-editor', 'heartbeat-front', 'disable-wp-cron', 'autosave-interval' ] ], 'page-head' => [ 'title' => __( 'Page Head', 'adminease' ), 'icon' => $icons['list'], 'field_ids' => [ 'page-head-cleanup', 'disable-emojis', 'disable-front-password-meter' ] ], ], 'posts' => [ 'editing' => [ 'title' => __( 'Editing', 'adminease' ), 'icon' => $icons['edit'], 'field_ids' => [ 'disable-gutenberg', 'number-posts-revisions', 'number-posts-revisions-other', 'delete-old-revisions-post-types', 'delete-old-revisions-submit', 'duplicate-post-enabled', 'duplicate-post-post-types' ] ], 'comments' => [ 'title' => __( 'Comments', 'adminease' ), 'icon' => $icons['comments'], 'field_ids' => [ 'close-comments', 'disable-comments-enabled', 'disable-comments-post-types', 'disable-comments-remove-screens' ] ], 'feeds-pages' => [ 'title' => __( 'Feeds and Extra Pages', 'adminease' ), 'icon' => $icons['feed'], 'field_ids' => [ 'disable-feeds', 'unused-pages' ] ], 'display' => [ 'title' => __( 'Display', 'adminease' ), 'icon' => $icons['list'], 'field_ids' => [ 'drag-and-drop-ordering-posts' ] ], 'bulk-actions' => [ 'title' => __( 'Bulk Actions', 'adminease' ), 'icon' => $icons['trash'], 'field_ids' => [ 'empty-trash-days', 'bulk-delete-posts-enabled', 'bulk-delete-posts-post-types', 'bulk-delete-posts-post-status', 'bulk-delete-posts-date-range', 'bulk-delete-posts-deletion-method', 'bulk-delete-posts-batch-size', 'bulk-delete-posts-submit' ] ], 'metadata' => [ 'title' => __( 'Metadata', 'adminease' ), 'icon' => $icons['database'], 'field_ids' => [ 'enable-posts-metadata-box' ] ], ], 'taxonomies' => [ 'editing' => [ 'title' => __( 'Editing', 'adminease' ), 'icon' => $icons['edit'], 'field_ids' => [ 'taxonomy-meta-box', 'enable-taxonomy-term-metadata-box' ] ], 'display' => [ 'title' => __( 'Display', 'adminease' ), 'icon' => $icons['list'], 'field_ids' => [ 'drag-and-drop-ordering-taxonomies' ] ], 'tools' => [ 'title' => __( 'Tools', 'adminease' ), 'icon' => $icons['wrench'], 'field_ids' => [ 'taxonomy-switcher-enabled', 'taxonomy-switcher-source', 'taxonomy-switcher-target', 'taxonomy-switcher-batch-size', 'taxonomy-switcher-merge-duplicates', 'taxonomy-switcher-delete-source', 'taxonomy-switcher-submit' ] ], 'bulk-actions' => [ 'title' => __( 'Bulk Actions', 'adminease' ), 'icon' => $icons['trash'], 'field_ids' => [ 'bulk-delete-terms-enabled', 'bulk-delete-terms-taxonomy', 'bulk-delete-terms-empty-only', 'bulk-delete-terms-name-search', 'bulk-delete-terms-delete-children', 'bulk-delete-terms-batch-size', 'bulk-delete-terms-submit' ] ], ], 'users' => [ 'authentication' => [ 'title' => __( 'Authentication', 'adminease' ), 'icon' => $icons['login'], 'field_ids' => [ 'auto-logout-user', 'auto-logout-user-time', 'auto-logout-user-time-other', 'password-reset-expiration', 'password-reset-expiration-time', 'disable-user-registration', 'disable-application-passwords', 'user-switch-enabled', 'force-strong-passwords', 'minimum-length', 'maximum-length', 'minimum-lowercase-letters', 'minimum-uppercase-letters', 'minimum-numbers', 'minimum-special-characters', 'redirect-after-login', 'redirect-after-login-url', 'redirect-after-logout', 'redirect-after-logout-url' ] ], 'display' => [ 'title' => __( 'Display', 'adminease' ), 'icon' => $icons['eye'], 'field_ids' => [ 'hide-admin-bar', 'hide-admin-bar-user-roles' ] ], 'tracking' => [ 'title' => __( 'Tracking', 'adminease' ), 'icon' => $icons['activity'], 'field_ids' => [ 'enable-last-login-tracking' ] ], 'audit-log' => [ 'title' => __( 'Audit Log', 'adminease' ), 'icon' => $icons['file'], 'field_ids' => [ 'audit-log-enabled', 'audit-log-auto-load', 'audit-log-max-entries', 'audit-log-auto-clear' ] ], 'metadata' => [ 'title' => __( 'Metadata', 'adminease' ), 'icon' => $icons['database'], 'field_ids' => [ 'enable-users-metadata-box' ] ], ], 'debug' => [ 'debug-log' => [ 'title' => __( 'Debug Log', 'adminease' ), 'icon' => $icons['terminal'], 'field_ids' => [ 'wp-debug', 'wp-debug-log', 'wp-debug-display', 'wp-debug-auto-refresh', 'debug-log-auto-refresh-interval', 'debug-log-lines-to-show' ] ], 'maintenance-mode' => [ 'title' => __( 'Maintenance Mode', 'adminease' ), 'icon' => $icons['alert-triangle'], 'field_ids' => [ 'maintenance-mode-enabled', 'maintenance_mode_show_logo', 'maintenance_mode_page_title', 'maintenance_mode_headline', 'maintenance_mode_message', 'maintenance_mode_primary_color', 'maintenance_mode_secondary_color', 'maintenance_mode_text_color', 'maintenance_mode_retry_after' ] ], 'network-viewer' => [ 'title' => __( 'Network Viewer', 'adminease' ), 'icon' => $icons['activity'], 'field_ids' => [ 'network-viewer-enabled', 'network-viewer-auto-refresh', 'network-viewer-auto-refresh-interval', 'network-viewer-log-ajax', 'network-viewer-log-cron', 'network-viewer-log-rest-api', 'network-viewer-auto-load', 'network-viewer-max-entries', 'network-viewer-auto-clear', 'network-viewer-exclude-ips' ] ], 'http-request-log' => [ 'title' => __( 'HTTP Request Log', 'adminease' ), 'icon' => $icons['activity'], 'field_ids' => [ 'http-request-log-enabled', 'http-request-log-errors-only', 'http-request-log-store-response', 'http-request-log-auto-load', 'http-request-log-max-entries', 'http-request-log-auto-clear', 'http-request-log-exclude-hosts' ] ], 'email-log' => [ 'title' => __( 'Email Log', 'adminease' ), 'icon' => $icons['mail'], 'field_ids' => [ 'enable-email-log', 'email-log-store-full-body', 'email-log-failed-only', 'email-log-auto-load', 'email-log-auto-refresh', 'email-log-auto-refresh-interval', 'email-log-ajax', 'email-log-disable-sending', 'email-log-max-entries', 'email-log-auto-clear', 'email-log-exclude-addresses', 'adminease-email-disabled' ] ], 'cron-viewer' => [ 'title' => __( 'Cron Viewer', 'adminease' ), 'icon' => $icons['clock'], 'field_ids' => [ 'cron-viewer-log-enabled', 'cron-viewer-log-auto-load', 'cron-viewer-log-max-entries', 'cron-viewer-log-auto-clear' ] ], ], 'media' => [ 'uploads' => [ 'title' => __( 'Uploads', 'adminease' ), 'icon' => $icons['upload'], 'field_ids' => [ 'upload-max-file-size', 'clean-upload-file-names', 'disable-big-image-threshold', 'disable-generated-image-sizes', 'media-library-infinite-scrolling' ] ], 'file-types' => [ 'title' => __( 'File Types', 'adminease' ), 'icon' => $icons['file'], 'field_ids' => [ 'allow-svg-upload', 'allowed-file-extensions-enable', 'allowed-file-extensions-mime-types', 'allowed-file-extensions-mime-types-other' ] ], ], ]; $subgroups = apply_filters( 'adminease_settings_subgroups', $subgroups ); if( !empty( $tab ) ) { return $subgroups[ $tab ] ?? []; } return $subgroups; } /** * Modifies the row meta displayed for the plugin on the plugins page. * * @param array $plugin_meta Array of the plugin's metadata. * @param string $plugin_file Path to the plugin file, relative to the plugins directory. * @param array $plugin_data Array of plugin data. * @param string $status Plugin status (e.g., 'active', 'inactive'). * * @return array Modified array of plugin metadata. */ public function plugin_row_meta( array $plugin_meta, string $plugin_file, array $plugin_data, string $status ): array { if( ADMINEASE_BASENAME === $plugin_file ) { $plugin_meta[] = '' . esc_attr__( '⚡ Upgrade to Pro', 'adminease' ) . ''; } return $plugin_meta; } /** * Searches for the settings key within a specified group and field. * * @param string $group_key The key of the group to search within. * @param string $field_key The partial or complete key to search for in the fields. * @param array $all_fields An associative array containing all fields grouped by their keys. * * The key is returned exactly as it appears in the array. Core field groups are * numerically indexed, but code hooking into the `adminease_settings_fields` * filter may add string-keyed fields, and casting those to int collapsed every * one of them to 0 - pointing callers at the wrong field. No return type is * declared because the plugin supports PHP 7.4, which has neither union types * nor `mixed`. * * @return int|string|null The matching key if found, or null if no match is found. */ public static function find_settings_key( string $group_key, string $field_key, array $all_fields ) { foreach( $all_fields[ $group_key ]['fields'] as $key => $field ) { if( false !== strpos( $field['name'], $field_key ) ) { return $key; } } return null; } }