init_filesystem() ) {
// Fail softly: leave the object constructed, but file operations will return false.
// This avoids killing AJAX/REST/frontend unexpectedly.
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;
}
/**
* 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( $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';
}
// Avoid unexpected output (credentials UI) in admin screens and non-admin contexts.
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
*/
private function set_file_paths() {
$this->wp_config_path = $this->locate_wp_config();
$this->htaccess_path = ABSPATH . '.htaccess';
$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';
}
/**
* 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;
}
// Check one level up
$config_file = dirname( ABSPATH ) . '/wp-config.php';
if( $this->filesystem->exists( $config_file ) ) {
return $config_file;
}
// Fallback to standard location
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 value is empty, set mode to remove
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;
}
/**
* Remove an ini directive from the wp-config stack
*
* @param string $directive Directive name
*
* @return bool True on success, false on failure
*/
public function remove_wp_config_ini_from_stack( $directive ) {
$stack_key = 'INI_' . strtoupper( $directive );
if( !isset( $this->wp_config_stack[ $stack_key ] ) ) {
$this->add_error( "Ini directive {$directive} not found in stack" );
return false;
}
unset( $this->wp_config_stack[ $stack_key ] );
return true;
}
/**
* 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;
}
// Allow alphanumeric characters, underscores, dots, and hyphens
if( !preg_match( '/^[a-zA-Z0-9_.-]+$/', $directive ) ) {
$this->add_error( 'Ini directive name contains invalid characters' );
return false;
}
// Check against a whitelist of common and safe ini directives
$allowed_directives = [
'max_execution_time',
'post_max_size',
'upload_max_filesize',
];
if( !in_array( $directive, $allowed_directives ) ) {
$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 ) {
// Remove ini_set() statements for this 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 ) ) {
// Handle common PHP ini value formats
$value = trim( $value );
// If it's a size value (like '256M', '2G'), keep it as string
if( preg_match( '/^\d+[KMGT]?$/i', $value ) ) {
return "'" . $value . "'";
}
// If it's a time value (like '30s', '5m'), keep it as string
if( preg_match( '/^\d+[smhd]?$/i', $value ) ) {
return "'" . $value . "'";
}
// If it's a boolean-like string
if( in_array( strtolower( $value ), [ 'on', 'off', 'true', 'false', 'yes', 'no' ] ) ) {
return "'" . $value . "'";
}
// Default string handling
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;
}
/**
* Remove a rule from the htaccess stack
*
* @param string $rule_name Rule name
*
* @return bool True on success, false on failure
*/
public function remove_htaccess_from_stack( $rule_name ) {
if( !isset( $this->htaccess_stack[ $rule_name ] ) ) {
$this->add_error( "Rule {$rule_name} not found in stack" );
return false;
}
unset( $this->htaccess_stack[ $rule_name ] );
return true;
}
/**
* Enhanced PHP configuration management with fallback methods
*/
public function apply_php_configuration( $directive, $value ) {
// If value is empty, null, or whitespace only, remove the directive
if( $this->is_empty_value( $value ) ) {
return $this->remove_php_configuration( $directive );
}
$success = false;
// Method 1: Try .user.ini first (modern shared hosting)
if( $this->can_use_user_ini() ) {
$success = $this->set_user_ini_directive( $directive, $value );
if( $success ) {
return true;
}
}
// Method 2: Fallback to ini_set() in wp-config.php
if( $this->can_use_ini_set( $directive ) ) {
$success = $this->stack_wp_config_ini_directive( $directive, $value );
if( $success ) {
return true;
}
}
// Method 3: Fallback to .htaccess php_value (Apache only)
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 ) {
$success = false;
// Remove from .user.ini
if( $this->can_use_user_ini() ) {
if( $this->remove_user_ini_directive( $directive ) ) {
$success = true;
}
}
// Remove from wp-config.php
if( $this->remove_wp_config_ini_from_stack( $directive ) ) {
$success = true;
}
// Remove from .htaccess
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( !file_exists( $user_ini_path ) ) {
return true; // Nothing to remove
}
$marker_start = "; ADMINEASE_" . strtoupper( $directive ) . " START";
$marker_end = "; ADMINEASE_" . strtoupper( $directive ) . " END";
$content = file_get_contents( $user_ini_path );
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
$content = $this->cleanup_file_content( $content );
// If content is empty, remove the file
if( trim( $content ) === '' ) {
wp_delete_file( $user_ini_path );
return !file_exists( $user_ini_path );
}
return file_put_contents( $user_ini_path, $content ) !== false;
}
/**
* Clean up file content by removing excessive newlines
*/
private function cleanup_file_content( $content ) {
// Remove excessive newlines but keep some structure
$content = preg_replace( '/\n{3,}/', "\n\n", $content );
// Remove leading/trailing whitespace
$content = trim( $content );
// Ensure single newline at end if content exists
if( !empty( $content ) ) {
$content .= "\n";
}
return $content;
}
/**
* Check if a value is considered empty for PHP configuration
*/
private function is_empty_value( $value ) {
// Consider null, empty string, or whitespace-only as empty
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';
// Check if PHP supports .user.ini
if( !ini_get( 'user_ini.filename' ) ) {
return false;
}
// Check if we can write to the directory
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";
// Read existing content
$content = file_exists( $user_ini_path ) ? file_get_contents( $user_ini_path ) : '';
// Remove existing block
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
// Only add new block if value is not empty
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;
}
// Clean up any extra newlines
$content = $this->cleanup_file_content( $content );
// If content is empty, remove the file
if( trim( $content ) === '' ) {
wp_delete_file( $user_ini_path );
return !file_exists( $user_ini_path );
}
return file_put_contents( $user_ini_path, $content ) !== false;
}
/**
* Check if directive can be set via ini_set()
*/
private function can_use_ini_set( $directive ) {
// Check if ini_set is disabled
if( !function_exists( 'ini_set' ) ) {
return false;
}
// Check if directive is changeable at runtime
$changeable_directives = [
'max_execution_time' => true,
'memory_limit' => true,
'max_input_vars' => false, // PHP_INI_PERDIR only
'post_max_size' => false, // PHP_INI_PERDIR only
'upload_max_filesize' => false, // PHP_INI_PERDIR only
];
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 value is empty, remove the rule
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() {
// Check if running on Apache with mod_php
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;
}
// For string values, no quotes needed in .user.ini
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;
// Clear any previous errors
$this->clear_errors();
// Create backups if requested
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;
}
}
}
// Execute wp-config changes
if( $this->has_wp_config_changes() ) {
if( !$this->execute_wp_config_stack() ) {
$success = false;
}
}
// Execute htaccess changes
if( $this->has_htaccess_changes() ) {
if( !$this->execute_htaccess_stack() ) {
$success = false;
}
}
// Clear stacks on success
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() {
// Read current content
$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;
}
// Process all stacked changes
$new_content = $this->process_wp_config_stack( $current_content );
// Atomic test and write
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() {
// Read current content (create empty if doesn't exist)
$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;
}
}
// Process all stacked changes
$new_content = $this->process_htaccess_stack( $current_content );
// Atomic test and write
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 ) {
// Sort stack by timestamp to ensure proper order
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";
// Always remove existing block first
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
// Handle different types of changes
if( isset( $change['type'] ) && $change['type'] === 'ini_directive' ) {
$directive_name = $change['directive_name'];
// Clean up legacy ini_set() calls
$content = $this->remove_legacy_ini_set( $content, $directive_name );
// Only add new block if mode is not remove and value is not empty
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 {
// Handle regular constant
$constant = $stack_key;
// Clean up legacy definitions
$content = $this->remove_legacy_constant_definitions( $content, $constant );
// Only add new block if mode is not remove and value is not empty
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 );
}
}
}
return $content;
}
/**
* Process htaccess stack and generate new content
*
* @param string $content Current file content
*
* @return string Updated content
*/
private function process_htaccess_stack( $content ) {
// Sort stack by timestamp to ensure proper order
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";
// Always remove existing block first
$content = $this->remove_marker_block( $content, $marker_start, $marker_end );
// Only add new block if mode is not remove and content is not empty
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;
}
}
// Prepend all new blocks at the top of the file
if( !empty( $new_blocks ) ) {
$blocks_content = implode( "\n\n", $new_blocks );
// Clean up any leading whitespace from existing content
$content = ltrim( $content );
// Add new blocks at the top with proper spacing
$content = $blocks_content . "\n\n" . $content;
}
// Clean up excessive newlines but maintain structure
$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 ) {
// Remove excessive newlines but keep some structure
$content = preg_replace( '/\n{4,}/', "\n\n\n", $content );
// Remove leading/trailing whitespace
$content = trim( $content );
// Ensure single newline at end if content exists
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();
// Validate wp-config stack
if( $this->has_wp_config_changes() ) {
foreach( $this->wp_config_stack as $stack_key => $change ) {
if( isset( $change['type'] ) && $change['type'] === 'ini_directive' ) {
// Validate ini directive
if( !$this->validate_ini_directive_name( $change['directive_name'] ) ) {
return false;
}
} else {
// Validate constant
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;
}
}
}
// Validate htaccess stack (existing logic)
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 ) {
// Remove define() statements
$pattern = '/\n?define\s*\(\s*[\'"]' . preg_quote( $constant, '/' ) . '[\'"]\s*,.*?\)\s*;?\n?/i';
$content = preg_replace( $pattern, '', $content );
// Remove ini_set() for relevant constants
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
*
* @param string $content Current content
* @param string $block Block to insert
*
* @return string Updated content
*/
private function insert_wp_config_block( $content, $block ) {
// Find the position to insert (before the last occurrence of "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 '';
}
// Remove potential PHP code injection
$content = preg_replace( '/<\?php.*?\?>/si', '', $content );
$content = preg_replace( '/<\?.*?\?>/si', '', $content );
// Remove HTML tags that are NOT Apache directives
// This regex matches HTML tags but excludes Apache directive syntax
$content = preg_replace( '/<(?!\/?(?:Files|Directory|Location|VirtualHost|IfModule|IfDefine|Limit|LimitExcept|RequireAll|RequireAny|RequireNone)(?:\s|>))[^>]*>/i', '', $content );
// Remove any remaining script tags or dangerous content
$content = preg_replace( '/