init_filesystem() ) {
return;
}
$this->set_file_paths();
add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ], 999 );
}
/**
* Retrieves the singleton instance of the class. If the instance does not already exist, it is created.
* @return self The singleton instance of the class.
*/
public static function get_instance(): self {
static $instance = null;
if( is_null( $instance ) ) {
$instance = new self();
}
return $instance;
}
/**
* Write a diagnostic line to the PHP error log, but only on a debug build.
*
* Every call site is a failure path. Success is never logged: a plugin that
* writes to error_log on a normal request fills the host's log with noise and
* gets flagged for it.
*
* @param string $message The message to log, without the plugin prefix.
*
* @return void
*/
private static function log( string $message ): void {
if( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( 'AdminEase: ' . $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
}
/**
* Handles the saving of Adminease settings and processes the stack if valid.
*
* @param array $sanitized_settings The sanitized settings data to be saved.
*
* @return void
*/
public function adminease_settings_saved( array $sanitized_settings ) {
if( !Utils::can_write_shared_files() ) {
$this->clear_all_stacks();
return;
}
if( $this->validate_stack() ) {
$this->execute_stack();
}
}
/**
* Initialize WordPress Filesystem API
* Adds admin notice and logs when initialization fails.
*
* @return bool True if initialized, false otherwise.
*/
private function init_filesystem(): bool {
global $wp_filesystem;
if( isset( $this->filesystem ) && $this->filesystem instanceof WP_Filesystem_Base ) {
return true;
}
if( !function_exists( 'WP_Filesystem' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
ob_start();
$credentials = request_filesystem_credentials( '', '', false, false, null );
ob_end_clean();
$initialized = WP_Filesystem( $credentials );
if( !$initialized || !( $wp_filesystem instanceof WP_Filesystem_Base ) ) {
if( is_admin() ) {
add_action(
'admin_notices',
function() {
?>
filesystem = $wp_filesystem;
return true;
}
/**
* Set file paths for wp-config.php and .htaccess.
*
* Backup files are stored in a randomly named sub-directory of the uploads
* dir (`adminease-backups-`, deny-listed via .htaccess + web.config
* + index.php silence) rather than adjacent to the originals in the webroot.
* This avoids exposing DB credentials if the backup is ever accidentally
* renamed off `.php` or directory listing is enabled, and the unguessable
* name is what protects it on servers that ignore .htaccess. If the
* directory cannot be created we fall back to the legacy in-webroot
* location so the plugin still functions on permission-restricted hosts.
*/
private function set_file_paths() {
$this->wp_config_path = $this->locate_wp_config();
$this->htaccess_path = ABSPATH . '.htaccess';
$this->robots_txt_path = $this->locate_home_path() . 'robots.txt';
$backup_dir = $this->init_backup_dir();
if( false === $backup_dir ) {
$config_dir = dirname( $this->wp_config_path );
$this->wp_config_backup_path = $config_dir . '/wp-config-adminease-backup.php';
$this->htaccess_backup_path = ABSPATH . '.htaccess_adminease_backup';
$this->robots_txt_backup_path = ABSPATH . 'robots.txt_adminease_backup';
return;
}
$this->wp_config_backup_path = $backup_dir . '/wp-config-adminease-backup.php';
$this->htaccess_backup_path = $backup_dir . '/htaccess-adminease-backup';
$this->robots_txt_backup_path = $backup_dir . '/robots-txt-adminease-backup';
$this->migrate_legacy_backups();
}
/**
* Locate the directory that serves the site root.
*
* robots.txt is fetched from the *home* URL root, which is not always ABSPATH:
* on a "Giving WordPress its own directory" install the core files live in a
* subdirectory while robots.txt must sit one level up. get_home_path() is the
* only core helper that resolves this correctly.
*
* It lives in wp-admin/includes/file.php. init_filesystem() has already loaded
* that file by the time this runs, so the require below is only a safety net.
*
* @return string Trailing-slashed path to the site root.
*/
private function locate_home_path(): string {
if( !function_exists( 'get_home_path' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$home_path = get_home_path();
if( !is_string( $home_path ) || '' === $home_path ) {
return ABSPATH;
}
$home_path = trailingslashit( str_replace( '\\', '/', $home_path ) );
$abspath = trailingslashit( str_replace( '\\', '/', ABSPATH ) );
if( '/' === $home_path || 0 !== strpos( $abspath, $home_path ) ) {
return ABSPATH;
}
return $home_path;
}
/**
* Ensure the hardened backup directory exists with deny rules.
*
* Creates `/adminease-backups-/` on first use and writes
* idempotent .htaccess (Apache) + web.config (IIS) deny rules plus an
* index.php silence file. Returns the absolute directory path on success
* or false if the directory could not be created (e.g. uploads dir not
* writable). Falls back to legacy paths if false.
*
* @return string|false Backup directory path, or false on failure.
*/
private function init_backup_dir() {
if( !isset( $this->filesystem ) || !( $this->filesystem instanceof WP_Filesystem_Base ) ) {
return false;
}
$upload = wp_upload_dir( null, false );
if( !empty( $upload['error'] ) || empty( $upload['basedir'] ) ) {
return false;
}
$uploads_dir = wp_normalize_path( untrailingslashit( $upload['basedir'] ) );
$backup_dir = $uploads_dir . '/' . $this->resolve_backup_dir_name( $uploads_dir );
if( !$this->filesystem->is_dir( $backup_dir ) ) {
if( !wp_mkdir_p( $backup_dir ) ) {
return false;
}
}
$this->write_backup_dir_guards( $backup_dir );
return $backup_dir;
}
/**
* Resolve the backup directory name, minting the secret and migrating on first run.
*
* The name carries a 32-character random suffix because the directory sits
* under the public uploads URL. The .htaccess and web.config deny rules the
* directory ships are read by Apache and IIS only, so on Nginx, native-mode
* LiteSpeed and CDN or static handlers the deny is silently absent and the
* backup of wp-config.php sits at a fixed, guessable URL. An unguessable
* name closes that on every server, because it does not depend on the web
* server honouring a config file.
*
* The directory is moved before the option is written: a failed move then
* leaves the site on the legacy path with its backups intact and retries on
* the next request, whereas storing the secret first would point every
* backup path at a directory that does not exist. The stored value is
* pattern checked rather than trusted, and so is a freshly minted one,
* because it becomes a path segment and because wp_generate_password() runs
* through the `random_password` filter that any plugin may override.
*
* @param string $uploads_dir Absolute path of the uploads directory, no trailing slash.
*
* @return string Directory name, no slashes.
*/
private function resolve_backup_dir_name( string $uploads_dir ): string {
$stored = get_option( self::DIR_SECRET_OPTION, '' );
if( is_string( $stored ) && 1 === preg_match( '/^[A-Za-z0-9]{32}$/', $stored ) ) {
return self::LEGACY_BACKUP_DIR_NAME . '-' . $stored;
}
$legacy_dir = $uploads_dir . '/' . self::LEGACY_BACKUP_DIR_NAME;
$secret = wp_generate_password( 32, false );
if( !is_string( $secret ) || 1 !== preg_match( '/^[A-Za-z0-9]{32}$/', $secret ) ) {
self::log( "Could not mint a backup directory secret: wp_generate_password() returned a value that is not 32 alphanumerics, most likely because another plugin filters random_password. Backups stay at the guessable path {$legacy_dir}" );
$this->record_backup_dir_exposure( $legacy_dir, self::EXPOSURE_SECRET_REJECTED );
return self::LEGACY_BACKUP_DIR_NAME;
}
$new_name = self::LEGACY_BACKUP_DIR_NAME . '-' . $secret;
$target_dir = $uploads_dir . '/' . $new_name;
if( $this->filesystem->is_dir( $legacy_dir ) && !$this->filesystem->move( $legacy_dir, $target_dir ) ) {
self::log( "Could not move the backup directory to a private name, backups stay readable over the web on servers that ignore .htaccess. Tried: {$legacy_dir} -> {$target_dir}" );
$this->record_backup_dir_exposure( $legacy_dir, self::EXPOSURE_MOVE_FAILED );
return self::LEGACY_BACKUP_DIR_NAME;
}
update_option( self::DIR_SECRET_OPTION, $secret );
$this->clear_backup_dir_exposure();
return $new_name;
}
/**
* Record that the backups were left behind at the legacy, guessable path.
*
* The first sighting sets `time`, and every later one leaves it alone, which is
* the opposite of how EmailFailureAlert treats its option and deliberately so.
* That one reports discrete events, so a new failure re-raises a dismissed
* notice. This reports a standing state: resolve_backup_dir_name() re-attempts
* the whole thing on every single request, so refreshing `time` would push it
* past `dismissed_at` on each one and leave the admin with a notice they can
* never dismiss. Preserving the first timestamp is what makes Dismiss mean
* something.
*
* The reason IS refreshed, because it can genuinely change under the admin's
* feet: fixing the plugin that was filtering random_password moves a site from
* EXPOSURE_SECRET_REJECTED to a real move attempt, which may then fail on
* permissions. Leaving the first reason in place would have the notice naming a
* cause the admin already dealt with, and a remedy that no longer applies.
* Dismissal still survives that: the exposure is one condition, and the admin
* dismissed the condition rather than the explanation.
*
* @param string $legacy_dir Absolute path the backups were left at.
* @param string $reason One of the EXPOSURE_* constants.
*
* @return void
*/
private function record_backup_dir_exposure( string $legacy_dir, string $reason ): void {
$recorded = get_option( self::BACKUP_DIR_NOTICE_OPTION );
$recorded = is_array( $recorded ) ? $recorded : [];
if( !empty( $recorded['time'] ) && ( $recorded['reason'] ?? '' ) === $reason && ( $recorded['path'] ?? '' ) === $legacy_dir ) {
return;
}
$first = empty( $recorded['time'] ) ? time() : (int) $recorded['time'];
update_option(
self::BACKUP_DIR_NOTICE_OPTION,
[
'path' => $legacy_dir,
'reason' => $reason,
'time' => $first,
'dismissed_at' => (int) ( $recorded['dismissed_at'] ?? 0 ),
],
false
);
}
/**
* Clear the exposure state once the backups reach their private directory.
*
* The move is retried on every request, so reaching this point means the
* problem the notice describes has actually gone away, whether the uploads
* directory became writable again or the admin removed the legacy directory
* by hand. Clearing here rather than on a schedule is what keeps the notice
* from outliving the condition it reports.
*
* @return void
*/
private function clear_backup_dir_exposure(): void {
if( false !== get_option( self::BACKUP_DIR_NOTICE_OPTION, false ) ) {
delete_option( self::BACKUP_DIR_NOTICE_OPTION );
}
}
/**
* Render the standing notice while the backups remain at the guessable path.
*
* @return void
*/
public function maybe_render_backup_dir_notice(): void {
if( !current_user_can( 'manage_options' ) ) {
return;
}
$notice = get_option( self::BACKUP_DIR_NOTICE_OPTION );
if( !is_array( $notice ) || empty( $notice['time'] ) ) {
return;
}
if( (int) ( $notice['dismissed_at'] ?? 0 ) >= (int) $notice['time'] ) {
return;
}
?>
get_backup_dir_notice_remedy( $notice['reason'] ?? self::EXPOSURE_MOVE_FAILED ) ); ?>
self::BACKUP_DIR_DISMISS_ACTION,
'_wp_http_referer' => $referer,
],
admin_url( 'admin-post.php' )
);
return wp_nonce_url( $url, self::BACKUP_DIR_DISMISS_ACTION );
}
/**
* Stamp the notice as dismissed and return the admin to where they were.
*
* A server-persisted dismissal rather than a client-side "is-dismissible" notice, so the
* choice survives the next page load. The recorded state is kept rather than deleted:
* deleting it would let record_backup_dir_exposure() write a fresh entry on the very next
* request, since the condition is still true, and the notice would come straight back.
*
* @return void
*/
public function handle_backup_dir_notice_dismiss(): void {
if( !current_user_can( 'manage_options' ) || !check_admin_referer( self::BACKUP_DIR_DISMISS_ACTION ) ) {
wp_die( esc_html__( 'Invalid request.', 'adminease' ) );
}
$notice = get_option( self::BACKUP_DIR_NOTICE_OPTION, [] );
if( !is_array( $notice ) ) {
$notice = [];
}
$notice['dismissed_at'] = time();
update_option( self::BACKUP_DIR_NOTICE_OPTION, $notice, false );
wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() );
exit;
}
/**
* Write the deny rules and silence file into the backup directory.
*
* Idempotent, and best effort by design: the directory's random name is what
* actually protects it, so these files are a second layer for Apache and
* IIS. A failed write is logged rather than treated as fatal, because
* refusing to back up wp-config.php would be the worse outcome. The rules
* deliberately carry no `Options -Indexes`: `Require all denied` already
* covers listing, and an `Options` directive returns a 500 on hosts whose
* AllowOverride does not permit it.
*
* @param string $backup_dir Absolute path of the backup directory.
*
* @return void
*/
private function write_backup_dir_guards( string $backup_dir ) {
$guards = [
'.htaccess' => "# AdminEase: deny all direct web access to backup files.\n" .
"\n\tRequire all denied\n\n" .
"\n\tOrder deny,allow\n\tDeny from all\n\n",
'web.config' => "\n" .
"\n" .
"\t\n" .
"\t\t\n" .
"\t\t\t\n" .
"\t\t\t\t\n" .
"\t\t\t\t\n" .
"\t\t\t\n" .
"\t\t\n" .
"\t\n" .
"\n",
'index.php' => " $contents ) {
$path = $backup_dir . '/' . $name;
if( $this->filesystem->exists( $path ) ) {
continue;
}
if( !$this->filesystem->put_contents( $path, $contents, FS_CHMOD_FILE ) ) {
self::log( "Failed to write {$name} into the backup directory {$backup_dir}" );
}
}
}
/**
* Move any existing legacy in-webroot backups to the hardened location.
*
* Idempotent: only moves when a legacy file exists AND no file is already
* present at the new path (so an in-progress migration cannot clobber a
* fresh backup).
*/
private function migrate_legacy_backups() {
$legacy_wp_config = dirname( $this->wp_config_path ) . '/wp-config-adminease-backup.php';
$legacy_htaccess = ABSPATH . '.htaccess_adminease_backup';
if( $this->filesystem->exists( $legacy_wp_config )
&& !$this->filesystem->exists( $this->wp_config_backup_path ) ) {
$this->filesystem->move( $legacy_wp_config, $this->wp_config_backup_path, true );
}
if( $this->filesystem->exists( $legacy_htaccess )
&& !$this->filesystem->exists( $this->htaccess_backup_path ) ) {
$this->filesystem->move( $legacy_htaccess, $this->htaccess_backup_path, true );
}
}
/**
* Locate wp-config.php file
* Searches for wp-config.php in the WordPress root directory
* and one level up, following WordPress conventions.
* @return string Path to wp-config.php
*/
private function locate_wp_config() {
$config_file = ABSPATH . 'wp-config.php';
if( $this->filesystem->exists( $config_file ) ) {
return $config_file;
}
$config_file = dirname( ABSPATH ) . '/wp-config.php';
if( $this->filesystem->exists( $config_file ) ) {
return $config_file;
}
return ABSPATH . 'wp-config.php';
}
/**
* Add wp-config.php constant to the change stack
*
* @param string $constant Constant name
* @param mixed $value Constant value (null to remove)
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_wp_config_constant( $constant, $value = null, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_constant_name( $constant ) ) {
return false;
}
$this->wp_config_stack[ $constant ] = [
'value' => $value,
'mode' => $mode,
'timestamp' => time(),
];
return true;
}
/**
* Add multiple wp-config.php constants to the change stack
*
* @param array $constants Array of constants ['CONSTANT_NAME' => 'value']
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_wp_config_constants( $constants, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_constants( $constants ) ) {
return false;
}
foreach( $constants as $constant => $value ) {
$this->stack_wp_config_constant( $constant, $value, $mode );
}
return true;
}
/**
* Add PHP ini directive to the wp-config.php change stack
*
* @param string $directive PHP ini directive name (e.g., 'max_execution_time')
* @param mixed $value Directive value (null to remove)
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_wp_config_ini_directive( $directive, $value = null, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_ini_directive_name( $directive ) ) {
return false;
}
$stack_key = 'INI_' . strtoupper( $directive );
if( $this->is_empty_value( $value ) ) {
$mode = self::STACK_MODE_REMOVE;
$value = null;
}
$this->wp_config_stack[ $stack_key ] = [
'value' => $value,
'mode' => $mode,
'timestamp' => time(),
'type' => 'ini_directive',
'directive_name' => $directive,
];
return true;
}
/**
* Add multiple PHP ini directives to the wp-config.php change stack
*
* @param array $directives Array of directives ['directive_name' => 'value']
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_wp_config_ini_directives( $directives, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_ini_directives( $directives ) ) {
return false;
}
foreach( $directives as $directive => $value ) {
$this->stack_wp_config_ini_directive( $directive, $value, $mode );
}
return true;
}
/**
* Queue removal of an ini directive from wp-config.php
*
* Stacks a REMOVE operation rather than unsetting a pending entry. Unsetting
* only cancelled a change that had not been written yet; a block already
* present in wp-config.php stayed there forever, and the "not found in stack"
* error fired on every normal call because the stack is empty at that point.
*
* @param string $directive Directive name
*
* @return bool True on success, false on failure
*/
public function remove_wp_config_ini_from_stack( $directive ) {
return $this->stack_wp_config_ini_directive( $directive, null, self::STACK_MODE_REMOVE );
}
/**
* Validate ini directive name
*
* @param string $directive Directive name
*
* @return bool True if valid, false otherwise
*/
private function validate_ini_directive_name( $directive ) {
if( !is_string( $directive ) || empty( $directive ) ) {
$this->add_error( 'Invalid ini directive name' );
return false;
}
if( !preg_match( '/^[a-zA-Z0-9_.-]+$/', $directive ) ) {
$this->add_error( 'Ini directive name contains invalid characters' );
return false;
}
$allowed_directives = [
'max_execution_time',
'post_max_size',
'upload_max_filesize',
];
if( !in_array( $directive, $allowed_directives, true ) ) {
$this->add_error( "Ini directive '{$directive}' is not in the allowed list" );
return false;
}
return true;
}
/**
* Validate ini directives array
*
* @param array $directives Directives to validate
*
* @return bool True if valid, false otherwise
*/
private function validate_ini_directives( $directives ) {
if( !is_array( $directives ) ) {
$this->add_error( 'Directives must be an array' );
return false;
}
foreach( $directives as $directive => $value ) {
if( !$this->validate_ini_directive_name( $directive ) ) {
return false;
}
}
return true;
}
/**
* Remove legacy ini_set() calls
*
* @param string $content File content
* @param string $directive Directive name
*
* @return string Content with legacy ini_set calls removed
*/
private function remove_legacy_ini_set( $content, $directive ) {
$pattern = '/\n?ini_set\s*\(\s*[\'"]' . preg_quote( $directive, '/' ) . '[\'"]\s*,.*?\)\s*;?\n?/i';
return preg_replace( $pattern, '', $content );
}
/**
* Generate wp-config.php ini directive block
*
* @param string $directive Directive name
* @param mixed $value Directive value
* @param string $start_marker Start marker
* @param string $end_marker End marker
*
* @return string Generated block
*/
private function generate_wp_config_ini_block( $directive, $value, $start_marker, $end_marker ) {
$sanitized_value = $this->sanitize_ini_value( $value );
$block = $start_marker . "\n";
$block .= "ini_set('" . $directive . "', " . $sanitized_value . ");\n";
$block .= $end_marker;
return $block;
}
/**
* Sanitize ini directive value
*
* @param mixed $value Value to sanitize
*
* @return string Sanitized value
*/
private function sanitize_ini_value( $value ) {
if( is_bool( $value ) ) {
return $value ? '1' : '0';
} else if( is_numeric( $value ) ) {
return (string) $value;
} else if( is_string( $value ) ) {
$value = trim( $value );
if( preg_match( '/^\d+[KMGT]?$/i', $value ) ) {
return "'" . $value . "'";
}
if( preg_match( '/^\d+[smhd]?$/i', $value ) ) {
return "'" . $value . "'";
}
if( in_array( strtolower( $value ), [ 'on', 'off', 'true', 'false', 'yes', 'no' ] ) ) {
return "'" . $value . "'";
}
return "'" . addslashes( $value ) . "'";
} else {
return "'" . addslashes( (string) $value ) . "'";
}
}
/**
* Get ini directives from the current stack
* @return array Array of ini directives in the stack
*/
public function get_wp_config_ini_stack() {
$ini_stack = [];
foreach( $this->wp_config_stack as $stack_key => $change ) {
if( isset( $change['type'] ) && $change['type'] === 'ini_directive' ) {
$ini_stack[ $change['directive_name'] ] = $change;
}
}
return $ini_stack;
}
/**
* Get constants from the current stack (excluding ini directives)
* @return array Array of constants in the stack
*/
public function get_wp_config_constants_stack() {
$constants_stack = [];
foreach( $this->wp_config_stack as $stack_key => $change ) {
if( !isset( $change['type'] ) || $change['type'] !== 'ini_directive' ) {
$constants_stack[ $stack_key ] = $change;
}
}
return $constants_stack;
}
/**
* Add .htaccess rule to the change stack
*
* @param string $rule_name Rule name
* @param string $content Rule content (null to remove)
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_htaccess_rule( $rule_name, $content = null, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_rule_name( $rule_name ) ) {
return false;
}
$this->htaccess_stack[ $rule_name ] = [
'content' => $content,
'mode' => $mode,
'timestamp' => time(),
];
return true;
}
/**
* Add multiple .htaccess rules to the change stack
*
* @param array $rules Array of rules ['RULE_NAME' => 'content']
* @param string $mode Stack mode (replace, append, remove)
*
* @return bool True on success, false on failure
*/
public function stack_htaccess_rules( $rules, $mode = self::STACK_MODE_REPLACE ) {
if( !$this->validate_htaccess_rules( $rules ) ) {
return false;
}
foreach( $rules as $rule_name => $content ) {
$this->stack_htaccess_rule( $rule_name, $content, $mode );
}
return true;
}
/**
* Remove a constant from the wp-config stack
*
* @param string $constant Constant name
*
* @return bool True on success, false on failure
*/
public function remove_wp_config_from_stack( $constant ) {
if( !isset( $this->wp_config_stack[ $constant ] ) ) {
$this->add_error( "Constant {$constant} not found in stack" );
return false;
}
unset( $this->wp_config_stack[ $constant ] );
return true;
}
/**
* Queue removal of a rule from .htaccess
*
* Stacks a REMOVE operation rather than unsetting a pending entry, for the
* same reason as remove_wp_config_ini_from_stack(): unsetting cancels an
* unwritten change, it does not remove a block that is already in the file.
*
* @param string $rule_name Rule name
*
* @return bool True on success, false on failure
*/
public function remove_htaccess_from_stack( $rule_name ) {
return $this->stack_htaccess_rule( $rule_name, null, self::STACK_MODE_REMOVE );
}
/**
* Enhanced PHP configuration management with fallback methods
*/
public function apply_php_configuration( $directive, $value ) {
if( !Utils::can_write_shared_files() ) {
return false;
}
if( $this->is_empty_value( $value ) ) {
return $this->remove_php_configuration( $directive );
}
$success = false;
if( $this->can_use_user_ini() ) {
$success = $this->set_user_ini_directive( $directive, $value );
if( $success ) {
return true;
}
}
if( $this->can_use_ini_set( $directive ) ) {
$success = $this->stack_wp_config_ini_directive( $directive, $value );
if( $success ) {
return true;
}
}
if( $this->can_use_htaccess_php_value() ) {
$success = $this->set_htaccess_php_value( $directive, $value );
if( $success ) {
return true;
}
}
return false;
}
/**
* Remove PHP configuration directive from all possible locations
*/
public function remove_php_configuration( $directive ) {
if( !Utils::can_write_shared_files() ) {
return false;
}
$success = false;
if( $this->can_use_user_ini() ) {
if( $this->remove_user_ini_directive( $directive ) ) {
$success = true;
}
}
if( $this->remove_wp_config_ini_from_stack( $directive ) ) {
$success = true;
}
if( $this->can_use_htaccess_php_value() ) {
$rule_name = 'PHP_' . strtoupper( $directive );
if( $this->remove_htaccess_from_stack( $rule_name ) ) {
$success = true;
}
}
return $success;
}
/**
* Remove directive from .user.ini file
*/
private function remove_user_ini_directive( $directive ) {
$user_ini_path = ABSPATH . '.user.ini';
if( !$this->filesystem->exists( $user_ini_path ) ) {
return true;
}
$marker_start = "; ADMINEASE_" . strtoupper( $directive ) . " START";
$marker_end = "; ADMINEASE_" . strtoupper( $directive ) . " END";
$content = $this->filesystem->get_contents( $user_ini_path );
if( false === $content ) {
$this->add_error( 'Failed to read .user.ini for directive removal' );
return false;
}
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
$content = $this->cleanup_file_content( $content );
if( trim( $content ) === '' ) {
wp_delete_file( $user_ini_path );
return !$this->filesystem->exists( $user_ini_path );
}
return $this->atomic_write( $user_ini_path, $content, 'user-ini' );
}
/**
* Clean up file content by removing excessive newlines
*/
private function cleanup_file_content( $content ) {
$content = preg_replace( '/\n{3,}/', "\n\n", $content );
$content = trim( $content );
if( !empty( $content ) ) {
$content .= "\n";
}
return $content;
}
/**
* Check if a value is considered empty for PHP configuration
*/
private function is_empty_value( $value ) {
return $value === null || $value === '' || ( is_string( $value ) && trim( $value ) === '' );
}
/**
* Check if .user.ini is supported and writable
*/
private function can_use_user_ini() {
$user_ini_path = ABSPATH . '.user.ini';
if( !ini_get( 'user_ini.filename' ) ) {
return false;
}
return $this->filesystem->is_writable( ABSPATH );
}
/**
* Set directive in .user.ini file
*/
private function set_user_ini_directive( $directive, $value ) {
$user_ini_path = ABSPATH . '.user.ini';
$marker_start = "; ADMINEASE_" . strtoupper( $directive ) . " START";
$marker_end = "; ADMINEASE_" . strtoupper( $directive ) . " END";
if( $this->filesystem->exists( $user_ini_path ) ) {
$content = $this->filesystem->get_contents( $user_ini_path );
if( false === $content ) {
$this->add_error( 'Failed to read existing .user.ini' );
return false;
}
} else {
$content = '';
}
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
if( !$this->is_empty_value( $value ) ) {
$new_block = $marker_start . "\n";
$new_block .= $directive . " = " . $this->sanitize_ini_value_for_file( $value ) . "\n";
$new_block .= $marker_end . "\n";
$content .= "\n" . $new_block;
}
$content = $this->cleanup_file_content( $content );
if( trim( $content ) === '' ) {
wp_delete_file( $user_ini_path );
return !$this->filesystem->exists( $user_ini_path );
}
return $this->atomic_write( $user_ini_path, $content, 'user-ini' );
}
/**
* Write or remove a marker-delimited block in the site's physical robots.txt.
*
* WordPress only serves its virtual robots.txt - and therefore only runs the
* `robots_txt` filter - when no physical robots.txt exists. When one does exist
* it shadows the virtual file completely, so anything a feature publishes through
* that filter is silently never served. This writes the same directives straight
* into the real file instead.
*
* The file is NEVER created. With no physical robots.txt the `robots_txt` filter
* already works, and creating one would permanently shadow the virtual file,
* killing WordPress core's own rules along with any output from SEO plugins that
* hook the same filter.
*
* Only the marked block is touched; the rest of the user's file is left exactly
* as it was. Passing an empty $rule_content removes the block again.
*
* @param string $rule_name Marker name, uppercase with underscores.
* @param string $rule_content Directives to place inside the block, or '' to remove it.
*
* @return bool True on success, false on failure.
*/
public function set_robots_txt_block( string $rule_name, string $rule_content ): bool {
if( !Utils::can_write_shared_files() ) {
return false;
}
if( !$this->validate_rule_name( $rule_name ) ) {
return false;
}
if( !isset( $this->filesystem ) || !( $this->filesystem instanceof WP_Filesystem_Base ) ) {
$this->add_error( 'Filesystem unavailable for robots.txt' );
return false;
}
if( !$this->filesystem->exists( $this->robots_txt_path ) ) {
return true;
}
$errors_before = $this->errors;
if( !$this->create_backup( 'robots-txt' ) ) {
$this->errors = $errors_before;
self::log( 'Could not back up robots.txt before editing' );
}
$content = $this->filesystem->get_contents( $this->robots_txt_path );
if( false === $content ) {
$this->add_error( 'Failed to read robots.txt' );
return false;
}
$marker_start = '# ADMINEASE_' . strtoupper( $rule_name ) . ' START';
$marker_end = '# ADMINEASE_' . strtoupper( $rule_name ) . ' END';
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
if( !$this->is_empty_value( $rule_content ) ) {
$content .= "\n" . $marker_start . "\n" . trim( $rule_content ) . "\n" . $marker_end . "\n";
}
$content = $this->cleanup_file_content( $content );
if( '' === trim( $content ) ) {
wp_delete_file( $this->robots_txt_path );
return !$this->filesystem->exists( $this->robots_txt_path );
}
return $this->atomic_write( $this->robots_txt_path, $content, 'robots-txt' );
}
/**
* Report the state of the physical robots.txt file.
* Lets the settings UI describe what will actually happen without duplicating
* the path resolution logic.
*
* @return array{exists: bool, writable: bool, path: string}
*/
public function get_robots_txt_status(): array {
$status = [
'exists' => false,
'writable' => false,
'path' => $this->robots_txt_path ?? '',
];
if( !isset( $this->filesystem ) || !( $this->filesystem instanceof WP_Filesystem_Base ) ) {
return $status;
}
if( !$this->filesystem->exists( $this->robots_txt_path ) ) {
return $status;
}
$status['exists'] = true;
$status['writable'] = $this->filesystem->is_writable( $this->robots_txt_path );
return $status;
}
/**
* Check if directive can be set via ini_set()
*/
private function can_use_ini_set( $directive ) {
if( !function_exists( 'ini_set' ) ) {
return false;
}
$changeable_directives = [
'max_execution_time' => true,
'memory_limit' => true,
'max_input_vars' => false,
'post_max_size' => false,
'upload_max_filesize' => false,
];
return isset( $changeable_directives[ $directive ] ) ? $changeable_directives[ $directive ] : false;
}
/**
* Set PHP value in .htaccess
*/
private function set_htaccess_php_value( $directive, $value ) {
$htaccess_directives = [
'post_max_size',
'upload_max_filesize',
'max_input_vars',
'max_file_uploads',
];
if( !in_array( $directive, $htaccess_directives ) ) {
return false;
}
$rule_name = 'PHP_' . strtoupper( $directive );
if( $this->is_empty_value( $value ) ) {
return $this->stack_htaccess_rule( $rule_name, null, self::STACK_MODE_REMOVE );
}
$content = "php_value " . $directive . " " . $value;
return $this->stack_htaccess_rule( $rule_name, $content );
}
/**
* Check if server supports .htaccess php_value
*/
private function can_use_htaccess_php_value() {
if( !isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
return false;
}
$server_software = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) );
$is_apache = stripos( $server_software, 'apache' ) !== false;
$is_mod_php = php_sapi_name() === 'apache2handler';
return $is_apache && $is_mod_php;
}
/**
* Sanitize value for .user.ini file format
*/
private function sanitize_ini_value_for_file( $value ) {
if( is_bool( $value ) ) {
return $value ? 'On' : 'Off';
}
if( is_numeric( $value ) ) {
return (string) $value;
}
return (string) $value;
}
/**
* Get current wp-config stack contents
* @return array Current stack contents
*/
public function get_wp_config_stack() {
return $this->wp_config_stack;
}
/**
* Get current htaccess stack contents
* @return array Current stack contents
*/
public function get_htaccess_stack() {
return $this->htaccess_stack;
}
/**
* Check if wp-config stack has changes
* @return bool True if stack has changes, false otherwise
*/
public function has_wp_config_changes() {
return !empty( $this->wp_config_stack );
}
/**
* Check if htaccess stack has changes
* @return bool True if stack has changes, false otherwise
*/
public function has_htaccess_changes() {
return !empty( $this->htaccess_stack );
}
/**
* Check if any stack has changes
* @return bool True if any stack has changes, false otherwise
*/
public function has_pending_changes() {
return $this->has_wp_config_changes() || $this->has_htaccess_changes();
}
/**
* Clear the wp-config stack
*/
public function clear_wp_config_stack() {
$this->wp_config_stack = [];
}
/**
* Clear the htaccess stack
*/
public function clear_htaccess_stack() {
$this->htaccess_stack = [];
}
/**
* Clear all stacks
*/
public function clear_all_stacks() {
$this->clear_wp_config_stack();
$this->clear_htaccess_stack();
}
/**
* Execute all pending changes in the stacks
*
* @param bool $create_backups Whether to create backups before applying changes
*
* @return bool True on success, false on failure
*/
public function execute_stack( $create_backups = true ) {
$success = true;
$this->clear_errors();
if( $create_backups ) {
if( $this->has_wp_config_changes() ) {
if( !$this->create_backup( 'wp-config' ) ) {
return false;
}
}
if( $this->has_htaccess_changes() ) {
if( !$this->create_backup( 'htaccess' ) ) {
return false;
}
}
}
if( $this->has_wp_config_changes() ) {
if( !$this->execute_wp_config_stack() ) {
$success = false;
}
}
if( $this->has_htaccess_changes() ) {
if( !$this->execute_htaccess_stack() ) {
$success = false;
}
}
if( $success ) {
$this->clear_all_stacks();
}
return $success;
}
/**
* Execute wp-config stack changes
* @return bool True on success, false on failure
*/
private function execute_wp_config_stack() {
$current_content = $this->filesystem->get_contents( $this->wp_config_path );
if( $current_content === false ) {
$this->add_error( 'Failed to read wp-config.php' );
return false;
}
$new_content = $this->process_wp_config_stack( $current_content );
$new_content = $this->ensure_php_tag_newline( $new_content );
return $this->atomic_write( $this->wp_config_path, $new_content, 'wp-config' );
}
/**
* Execute htaccess stack changes
* @return bool True on success, false on failure
*/
private function execute_htaccess_stack() {
$current_content = '';
if( $this->filesystem->exists( $this->htaccess_path ) ) {
$current_content = $this->filesystem->get_contents( $this->htaccess_path );
if( $current_content === false ) {
$this->add_error( 'Failed to read .htaccess' );
return false;
}
}
$new_content = $this->process_htaccess_stack( $current_content );
return $this->atomic_write( $this->htaccess_path, $new_content, 'htaccess' );
}
/**
* Process wp-config stack and generate new content
*
* @param string $content Current file content
*
* @return string Updated content
*/
private function process_wp_config_stack( $content ) {
uasort(
$this->wp_config_stack, function( $a, $b ) {
return $a['timestamp'] - $b['timestamp'];
}
);
foreach( $this->wp_config_stack as $stack_key => $change ) {
$marker_start = "// ADMINEASE_" . strtoupper( $stack_key ) . " START";
$marker_end = "// ADMINEASE_" . strtoupper( $stack_key ) . " END";
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
if( isset( $change['type'] ) && $change['type'] === 'ini_directive' ) {
$directive_name = $change['directive_name'];
$content = $this->remove_legacy_ini_set( $content, $directive_name );
if( $change['mode'] !== self::STACK_MODE_REMOVE && !$this->is_empty_value( $change['value'] ) ) {
$new_block = $this->generate_wp_config_ini_block( $directive_name, $change['value'], $marker_start, $marker_end );
$content = $this->insert_wp_config_block( $content, $new_block );
}
} else {
$constant = $stack_key;
$content = $this->remove_legacy_constant_definitions( $content, $constant );
if( $change['mode'] !== self::STACK_MODE_REMOVE && !$this->is_empty_value( $change['value'] ) ) {
$new_block = $this->generate_wp_config_block( $constant, $change['value'], $marker_start, $marker_end );
$content = $this->insert_wp_config_block( $content, $new_block );
}
}
}
$content = $this->cleanup_wp_config_content( $content );
return $content;
}
/**
* Clean up wp-config.php content by collapsing runs of blank lines
*
* Counterpart to cleanup_htaccess_content(). Older builds left one blank line
* behind for every marker block they removed, and those accumulated on each
* deactivate/re-activate cycle; this heals files that already carry them.
*
* Deliberately does not trim(): the trailing newline after the wp-settings.php
* require must survive.
*
* @param string $content Content to clean up
*
* @return string Cleaned content
*/
private function cleanup_wp_config_content( $content ) {
return preg_replace( '/\n{3,}/', "\n\n", $content );
}
/**
* Process htaccess stack and generate new content
*
* @param string $content Current file content
*
* @return string Updated content
*/
private function process_htaccess_stack( $content ) {
uasort(
$this->htaccess_stack, function( $a, $b ) {
return $a['timestamp'] - $b['timestamp'];
}
);
$new_blocks = [];
foreach( $this->htaccess_stack as $rule_name => $change ) {
$marker_start = "# ADMINEASE_" . strtoupper( $rule_name ) . " START";
$marker_end = "# ADMINEASE_" . strtoupper( $rule_name ) . " END";
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
if( $change['mode'] !== self::STACK_MODE_REMOVE && !$this->is_empty_value( $change['content'] ) ) {
$new_block = $this->generate_htaccess_block( $change['content'], $marker_start, $marker_end );
$new_blocks[] = $new_block;
}
}
if( !empty( $new_blocks ) ) {
$blocks_content = implode( "\n\n", $new_blocks );
$content = ltrim( $content );
$content = $blocks_content . "\n\n" . $content;
}
$content = $this->cleanup_htaccess_content( $content );
return $content;
}
/**
* Clean up htaccess content by removing excessive newlines while maintaining structure
*
* @param string $content Content to clean up
*
* @return string Cleaned content
*/
private function cleanup_htaccess_content( $content ) {
$content = preg_replace( '/\n{4,}/', "\n\n\n", $content );
$content = trim( $content );
if( !empty( $content ) ) {
$content .= "\n";
}
return $content;
}
/**
* Check if a value is considered empty for htaccess rules
*
* @param mixed $value Value to check
*
* @return bool True if empty, false otherwise
*/
private function is_empty_htaccess_value( $value ) {
return $value === null || $value === '' || ( is_string( $value ) && trim( $value ) === '' );
}
/**
* Validate a stack before execution
* @return bool True if valid, false otherwise
*/
public function validate_stack() {
$this->clear_errors();
if( $this->has_wp_config_changes() ) {
foreach( $this->wp_config_stack as $stack_key => $change ) {
if( isset( $change['type'] ) && $change['type'] === 'ini_directive' ) {
if( !$this->validate_ini_directive_name( $change['directive_name'] ) ) {
return false;
}
} else {
if( !$this->validate_constant_name( $stack_key ) ) {
return false;
}
}
if( !in_array( $change['mode'], [ self::STACK_MODE_REPLACE, self::STACK_MODE_APPEND, self::STACK_MODE_REMOVE ] ) ) {
$this->add_error( "Invalid mode '{$change['mode']}' for {$stack_key}" );
return false;
}
}
}
if( $this->has_htaccess_changes() ) {
foreach( $this->htaccess_stack as $rule_name => $change ) {
if( !$this->validate_rule_name( $rule_name ) ) {
return false;
}
if( !in_array( $change['mode'], [ self::STACK_MODE_REPLACE, self::STACK_MODE_APPEND, self::STACK_MODE_REMOVE ] ) ) {
$this->add_error( "Invalid mode '{$change['mode']}' for rule {$rule_name}" );
return false;
}
}
}
return true;
}
/**
* Remove content between markers
*
* @param string $content File content
* @param string $start_marker Start marker
* @param string $end_marker End marker
*
* @return string Content with block removed
*/
private function remove_marker_block( $content, $start_marker, $end_marker ) {
$pattern = '/\n?' . preg_quote( $start_marker, '/' ) . '.*?' . preg_quote( $end_marker, '/' ) . '\n?/s';
return preg_replace( $pattern, '', $content );
}
/**
* Remove legacy constant definitions
*
* @param string $content File content
* @param string $constant Constant name
*
* @return string Content with legacy definitions removed
*/
private function remove_legacy_constant_definitions( $content, $constant ) {
$pattern = '/\n?define\s*\(\s*[\'"]' . preg_quote( $constant, '/' ) . '[\'"]\s*,.*?\)\s*;?\n?/i';
$content = preg_replace( $pattern, '', $content );
if( in_array( $constant, [ 'WP_MEMORY_LIMIT', 'WP_MAX_MEMORY_LIMIT' ] ) ) {
$ini_name = $constant === 'WP_MEMORY_LIMIT' ? 'memory_limit' : 'memory_limit';
$pattern = '/\n?ini_set\s*\(\s*[\'"]' . preg_quote( $ini_name, '/' ) . '[\'"]\s*,.*?\)\s*;?\n?/i';
$content = preg_replace( $pattern, '', $content );
}
return $content;
}
/**
* Generate wp-config.php block
*
* @param string $constant Constant name
* @param mixed $value Constant value
* @param string $start_marker Start marker
* @param string $end_marker End marker
*
* @return string Generated block
*/
private function generate_wp_config_block( $constant, $value, $start_marker, $end_marker ) {
$sanitized_value = $this->sanitize_constant_value( $value );
$block = $start_marker . "\n";
$block .= "define('" . $constant . "', " . $sanitized_value . ");\n";
$block .= $end_marker;
return $block;
}
/**
* Generates a formatted .htaccess block with specific start and end markers.
*
* @param string $rule_content The content to be placed within the .htaccess block.
* @param string $start_marker The marker that denotes the beginning of the block.
* @param string $end_marker The marker that denotes the end of the block.
*
* @return string Returns the complete .htaccess block as a formatted string.
*/
private function generate_htaccess_block( $rule_content, string $start_marker, string $end_marker ): string {
$sanitized_content = $this->sanitize_htaccess_content( $rule_content );
$block = $start_marker . "\n";
$block .= trim( $sanitized_content ) . "\n";
$block .= $end_marker;
return $block;
}
/**
* Insert wp-config block into content
*
* Inserts immediately before the `require_once ABSPATH . 'wp-settings.php';`
* line - the last point at which a constant can still be defined before
* WordPress boots and reads it.
*
* Falls back to the FIRST ` ... add_error( 'Invalid constant name' );
return false;
}
if( !preg_match( '/^[A-Z_][A-Z0-9_]*$/', $constant ) ) {
$this->add_error( 'Constant name must contain only uppercase letters, numbers, and underscores' );
return false;
}
return true;
}
/**
* Validate rule name
*
* @param string $rule_name Rule name
*
* @return bool True if valid, false otherwise
*/
private function validate_rule_name( $rule_name ) {
if( !is_string( $rule_name ) || empty( $rule_name ) ) {
$this->add_error( 'Invalid rule name' );
return false;
}
if( !preg_match( '/^[A-Z_][A-Z0-9_]*$/', $rule_name ) ) {
$this->add_error( 'Rule name must contain only uppercase letters, numbers, and underscores' );
return false;
}
return true;
}
/**
* Validate constants array
*
* @param array $constants Constants to validate
*
* @return bool True if valid, false otherwise
*/
private function validate_constants( $constants ) {
if( !is_array( $constants ) ) {
$this->add_error( 'Constants must be an array' );
return false;
}
foreach( $constants as $constant => $value ) {
if( !$this->validate_constant_name( $constant ) ) {
return false;
}
}
return true;
}
/**
* Validate htaccess rules array
*
* @param array $rules Rules to validate
*
* @return bool True if valid, false otherwise
*/
private function validate_htaccess_rules( $rules ) {
if( !is_array( $rules ) ) {
$this->add_error( 'Rules must be an array' );
return false;
}
foreach( $rules as $rule_name => $content ) {
if( !$this->validate_rule_name( $rule_name ) ) {
return false;
}
}
return true;
}
/**
* Sanitize constant value for wp-config.php
*
* @param mixed $value Value to sanitize
*
* @return string Sanitized value
*/
private function sanitize_constant_value( $value ) {
if( is_bool( $value ) ) {
return $value ? 'true' : 'false';
} else if( is_numeric( $value ) ) {
return (string) $value;
} else if( is_string( $value ) ) {
return "'" . addslashes( $value ) . "'";
} else {
return "'" . addslashes( (string) $value ) . "'";
}
}
/**
* Sanitize .htaccess content
*
* @param string $content Content to sanitize
*
* @return string Sanitized content
*/
private function sanitize_htaccess_content( $content ) {
if( !is_string( $content ) ) {
return '';
}
$content = preg_replace( '/<\?php.*?\?>/si', '', $content );
$content = preg_replace( '/<\?.*?\?>/si', '', $content );
$content = preg_replace( '/<(?!\/?(?:Files|Directory|Location|VirtualHost|IfModule|IfDefine|Limit|LimitExcept|RequireAll|RequireAny|RequireNone)(?:\s|>))[^>]*>/i', '', $content );
$content = preg_replace( '/