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( 'wp_ajax_adminease_save_settings', [ $this, 'ajax_save_settings' ] );
}
/**
* Adds custom filters for the plugin.
* @return void
*/
private function add_filters(): void {
add_filter( 'plugin_action_links_' . ADMINEASE_BASENAME, [ $this, 'action_links' ] );
add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 4 );
}
/**
* 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() {
// Additional permission check if needed
if( !current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Insufficient permissions to access this page.', 'adminease' ) );
}
include ADMINEASE_DIR . 'partials/dashboard.php';
},
ADMINEASE_PLUGIN_URL . 'assets/img/favicon.svg',
2
);
}
/**
* Enqueue admin-specific styles and scripts.
* Enqueues required CSS and JavaScript files for the WordPress admin area.
* Additionally, localizes JavaScript variables for AJAX interactions and internationalization.
* @return void
*/
public function admin_enqueue_scripts(): void {
$screen = get_current_screen();
wp_enqueue_style(
ADMINEASE_NAME . 'Global',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseGlobal.css',
[],
ADMINEASE_VERSION
);
$additional_css = apply_filters( 'adminease_global_inline_css', '' );
if( !empty( $additional_css ) ) {
// WordPress's recommended approach for CSS sanitization
$sanitized_css = wp_strip_all_tags( $additional_css );
// Additional security: Remove potentially dangerous CSS constructs
$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( $screen->id === 'toplevel_page_' . ADMINEASE_SLUG ) {
$filetime = filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseFlexboxgrid.min.css' );
wp_enqueue_style(
ADMINEASE_NAME . 'Flexboxgrid',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseFlexboxgrid.min.css',
[],
$filetime
);
wp_enqueue_style(
ADMINEASE_NAME . 'Choices',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseChoices.min.css',
[],
'11.1.0'
);
$filetime = filemtime( ADMINEASE_DIR . 'assets/css/AdminEase.css' );
wp_enqueue_style(
ADMINEASE_NAME,
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEase.css',
[],
$filetime
);
wp_enqueue_script(
ADMINEASE_NAME . 'Choices',
ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseChoices.min.js',
[ 'jquery' ],
'11.1.0',
true
);
$filetime = filemtime( ADMINEASE_DIR . 'assets/js/AdminEase.js' );
wp_enqueue_script(
ADMINEASE_NAME,
ADMINEASE_PLUGIN_URL . 'assets/js/AdminEase.js',
[ 'jquery', ADMINEASE_NAME . 'Choices' ],
$filetime,
true
);
wp_localize_script(
ADMINEASE_NAME,
ADMINEASE_NAME . 'AjaxObj',
apply_filters( 'adminease_localize_script',
[
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'isMobile' => wp_is_mobile(),
'security' => [
'saveSettings' => wp_create_nonce( 'save_settings' ),
],
'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' ),
],
]
)
);
}
}
/**
* 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.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data is validated elsewhere in the method
parse_str( $_POST['data'], $parsed_data );
if( empty( $parsed_data['adminease'] ) ) {
wp_send_json_error( new \WP_Error( 'data', esc_html__( 'No data was provided', 'adminease' ) ) );
}
$sanitized_settings = $this->wp_recursive_sanitize( $parsed_data['adminease'] );
$sanitized_settings = $this->validate_settings( $sanitized_settings );
if( is_wp_error( $sanitized_settings ) ) {
wp_send_json_error( $sanitized_settings );
}
update_option( 'adminease_settings', $sanitized_settings );
self::$settings = $sanitized_settings;
do_action( 'adminease_settings_saved', $sanitized_settings );
wp_send_json_success( [ 'message' => esc_html__( 'Settings saved successfully', 'adminease' ) ] );
}
/**
* 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;
}
/**
* Recursively sanitize all types of values.
*
* @param mixed $value The value to sanitize.
*
* @return mixed The sanitized value.
*/
private function wp_recursive_sanitize( $value ) {
if( is_array( $value ) ) {
foreach( $value as $key => $item ) {
$value[ $key ] = $this->wp_recursive_sanitize( $item );
}
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 ) ) {
return sanitize_text_field( $value );
} else {
return $value;
}
}
/**
* 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.
*
* @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 ) {
foreach( $sanitized_settings as $key => $fields ) {
switch( $key ) {
case 'performance':
{
if( 'other' === $fields['wp_memory_limit'] && '' === $fields['wp_memory_limit_other'] ) {
return new \WP_Error( 'wp_memory_limit_other', esc_html__( 'Memory limit cannot be empty', 'adminease' ) );
}
if( 'other' === $fields['wp_max_memory_limit'] && '' === $fields['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 = Utils::parse_memory_limit( $fields['wp_memory_limit'] );
$max_memory_limit = Utils::parse_memory_limit( $fields['wp_max_memory_limit'] );
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' ) );
}
break;
}
case 'posts':
{
if( 'other' === $fields['number_posts_revisions'] && '' === $fields['number_posts_revisions_other'] ) {
return new \WP_Error( 'number_posts_revisions_other', esc_html__( 'Number of revisions cannot be empty', 'adminease' ) );
}
}
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_minimum_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'] ) ) {
return new \WP_Error( 'site_password_empty', esc_html__( 'Site password cannot be empty', 'adminease' ) );
}
if( !empty( $sanitized_settings['security']['password_protect_site_enabled'] ) &&
!empty( $sanitized_settings['security']['password_protect_site_remember_device'] ) &&
'other' === $sanitized_settings['security']['password_protect_site_remember_device'] &&
empty( $sanitized_settings['security']['password_protect_site_remember_device_other'] ) ) {
return new \WP_Error( 'remember_device_other', esc_html__( 'Remember device duration 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;
}
}
}
return $sanitized_settings;
}
/**
* 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 );
}
/**
* 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 {
$fields = [
'updates-and-notifications' => [
'title' => __( 'Updates and Notifications', 'adminease' ),
'fields' => [],
],
'security' => [
'title' => __( 'Security', 'adminease' ),
'fields' => [],
],
'performance' => [
'title' => __( 'Performance', 'adminease' ),
'fields' => [],
],
'posts' => [
'title' => __( 'Posts', 'adminease' ),
'fields' => [],
],
'taxonomies' => [
'title' => __( 'Taxonomies', 'adminease' ),
'fields' => [],
],
'users' => [
'title' => __( 'Users', 'adminease' ),
'fields' => [],
],
'debug' => [
'title' => __( 'Debug', 'adminease' ),
'fields' => [],
],
'media' => [
'title' => __( 'Media', 'adminease' ),
'fields' => [],
],
];
$fields = apply_filters( 'adminease_settings_fields', $fields );
return $fields[ $key ] ?? $fields;
}
/**
* 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( in_array( $plugin_file, [ ADMINEASE_BASENAME, 'adminease-pro/adminease-pro.php' ] ) ) {
$plugin_meta[1] = 'By
PrecisionWP'; // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
}
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.
*
* @return int|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 ): ?int {
foreach( $all_fields[ $group_key ]['fields'] as $key => $field ) {
if( false !== strpos( $field['name'], $field_key ) ) {
return (int) $key;
}
}
return null;
}
}